LLVM 23.0.0git
BasicBlockUtils.h
Go to the documentation of this file.
1//===- Transform/Utils/BasicBlockUtils.h - BasicBlock Utils -----*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This family of functions perform manipulations on basic blocks, and
10// instructions contained within basic blocks.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_TRANSFORMS_UTILS_BASICBLOCKUTILS_H
15#define LLVM_TRANSFORMS_UTILS_BASICBLOCKUTILS_H
16
17// FIXME: Move to this file: BasicBlock::removePredecessor, BB::splitBasicBlock
18
19#include "llvm/ADT/ArrayRef.h"
20#include "llvm/ADT/SetVector.h"
21#include "llvm/IR/BasicBlock.h"
22#include "llvm/IR/CycleInfo.h"
23#include "llvm/IR/Dominators.h"
26#include <cassert>
27
28namespace llvm {
29class BranchInst;
30class LandingPadInst;
31class Loop;
32class PHINode;
33template <typename PtrType> class SmallPtrSetImpl;
36class DomTreeUpdater;
37class Function;
38class IRBuilderBase;
39class LoopInfo;
40class MDNode;
44class ReturnInst;
46class Value;
47
48/// Check if the given basic block contains any loop or entry convergent
49/// intrinsic instructions.
51
52/// Replace contents of every block in \p BBs with single unreachable
53/// instruction. If \p Updates is specified, collect all necessary DT updates
54/// into this vector. If \p KeepOneInputPHIs is true, one-input Phis in
55/// successors of blocks being deleted will be preserved.
56LLVM_ABI void
59 bool KeepOneInputPHIs = false);
60
61/// Delete the specified block, which must have no predecessors.
62LLVM_ABI void DeleteDeadBlock(BasicBlock *BB, DomTreeUpdater *DTU = nullptr,
63 bool KeepOneInputPHIs = false);
64
65/// Delete the specified blocks from \p BB. The set of deleted blocks must have
66/// no predecessors that are not being deleted themselves. \p BBs must have no
67/// duplicating blocks. If there are loops among this set of blocks, all
68/// relevant loop info updates should be done before this function is called.
69/// If \p KeepOneInputPHIs is true, one-input Phis in successors of blocks
70/// being deleted will be preserved.
72 DomTreeUpdater *DTU = nullptr,
73 bool KeepOneInputPHIs = false);
74
75/// Delete all basic blocks from \p F that are not reachable from its entry
76/// node. If \p KeepOneInputPHIs is true, one-input Phis in successors of
77/// blocks being deleted will be preserved.
79 DomTreeUpdater *DTU = nullptr,
80 bool KeepOneInputPHIs = false);
81
82/// We know that BB has one predecessor. If there are any single-entry PHI nodes
83/// in it, fold them away. This handles the case when all entries to the PHI
84/// nodes in a block are guaranteed equal, such as when the block has exactly
85/// one predecessor.
86LLVM_ABI bool
88 MemoryDependenceResults *MemDep = nullptr);
89
90/// Examine each PHI in the given block and delete it if it is dead. Also
91/// recursively delete any operands that become dead as a result. This includes
92/// tracing the def-use list from the PHI to see if it is ultimately unused or
93/// if it reaches an unused cycle. Return true if any PHIs were deleted.
95 const TargetLibraryInfo *TLI = nullptr,
96 MemorySSAUpdater *MSSAU = nullptr);
97
98/// Attempts to merge a block into its predecessor, if possible. The return
99/// value indicates success or failure.
100/// By default do not merge blocks if BB's predecessor has multiple successors.
101/// If PredecessorWithTwoSuccessors = true, the blocks can only be merged
102/// if BB's Pred has a branch to BB and to AnotherBB, and BB has a single
103/// successor Sing. In this case the branch will be updated with Sing instead of
104/// BB, and BB will still be merged into its predecessor and removed.
105/// If \p DT is not nullptr, update it directly; in that case, DTU must be
106/// nullptr.
108 BasicBlock *BB, DomTreeUpdater *DTU = nullptr, LoopInfo *LI = nullptr,
109 MemorySSAUpdater *MSSAU = nullptr,
110 MemoryDependenceResults *MemDep = nullptr,
111 bool PredecessorWithTwoSuccessors = false, DominatorTree *DT = nullptr);
112
113/// Merge block(s) sucessors, if possible. Return true if at least two
114/// of the blocks were merged together.
115/// In order to merge, each block must be terminated by an unconditional
116/// branch. If L is provided, then the blocks merged into their predecessors
117/// must be in L. In addition, This utility calls on another utility:
118/// MergeBlockIntoPredecessor. Blocks are successfully merged when the call to
119/// MergeBlockIntoPredecessor returns true.
121 SmallPtrSetImpl<BasicBlock *> &MergeBlocks, Loop *L = nullptr,
122 DomTreeUpdater *DTU = nullptr, LoopInfo *LI = nullptr);
123
124/// Try to remove redundant dbg.value instructions from given basic block.
125/// Returns true if at least one instruction was removed. Remove redundant
126/// pseudo ops when RemovePseudoOp is true.
128
129/// Replace all uses of an instruction (specified by BI) with a value, then
130/// remove and delete the original instruction.
132
133/// Replace the instruction specified by BI with the instruction specified by I.
134/// Copies DebugLoc from BI to I, if I doesn't already have a DebugLoc. The
135/// original instruction is deleted and BI is updated to point to the new
136/// instruction.
138 Instruction *I);
139
140/// Replace the instruction specified by From with the instruction specified by
141/// To. Copies DebugLoc from BI to I, if I doesn't already have a DebugLoc.
143
144/// Check if we can prove that all paths starting from this block converge
145/// to a block that either has a @llvm.experimental.deoptimize call
146/// prior to its terminating return instruction or is terminated by unreachable.
147/// All blocks in the traversed sequence must have an unique successor, maybe
148/// except for the last one.
150
151/// Option class for critical edge splitting.
152///
153/// This provides a builder interface for overriding the default options used
154/// during critical edge splitting.
161 bool KeepOneInputPHIs = false;
162 bool PreserveLCSSA = false;
164 /// SplitCriticalEdge is guaranteed to preserve loop-simplify form if LI is
165 /// provided. If it cannot be preserved, no splitting will take place. If it
166 /// is not set, preserve loop-simplify form if possible.
168
170 LoopInfo *LI = nullptr,
171 MemorySSAUpdater *MSSAU = nullptr,
172 PostDominatorTree *PDT = nullptr)
173 : DT(DT), PDT(PDT), LI(LI), MSSAU(MSSAU) {}
174
179
181 KeepOneInputPHIs = true;
182 return *this;
183 }
184
186 PreserveLCSSA = true;
187 return *this;
188 }
189
194
199};
200
201/// When a loop exit edge is split, LCSSA form may require new PHIs in the new
202/// exit block. This function inserts the new PHIs, as needed. Preds is a list
203/// of preds inside the loop, SplitBB is the new loop exit block, and DestBB is
204/// the old loop exit, now the successor of SplitBB.
206 BasicBlock *SplitBB,
207 BasicBlock *DestBB);
208
209/// If this edge is a critical edge, insert a new node to split the critical
210/// edge. This will update the analyses passed in through the option struct.
211/// This returns the new block if the edge was split, null otherwise.
212///
213/// If MergeIdenticalEdges in the options struct is true (not the default),
214/// *all* edges from TI to the specified successor will be merged into the same
215/// critical edge block. This is most commonly interesting with switch
216/// instructions, which may have many edges to any one destination. This
217/// ensures that all edges to that dest go to one block instead of each going
218/// to a different block, but isn't the standard definition of a "critical
219/// edge".
220///
221/// It is invalid to call this function on a critical edge that starts at an
222/// IndirectBrInst. Splitting these edges will almost always create an invalid
223/// program because the address of the new block won't be the one that is jumped
224/// to.
225LLVM_ABI BasicBlock *
226SplitCriticalEdge(Instruction *TI, unsigned SuccNum,
227 const CriticalEdgeSplittingOptions &Options =
228 CriticalEdgeSplittingOptions(),
229 const Twine &BBName = "");
230
231/// If it is known that an edge is critical, SplitKnownCriticalEdge can be
232/// called directly, rather than calling SplitCriticalEdge first.
233LLVM_ABI BasicBlock *
234SplitKnownCriticalEdge(Instruction *TI, unsigned SuccNum,
235 const CriticalEdgeSplittingOptions &Options =
236 CriticalEdgeSplittingOptions(),
237 const Twine &BBName = "");
238
239/// If an edge from Src to Dst is critical, split the edge and return true,
240/// otherwise return false. This method requires that there be an edge between
241/// the two blocks. It updates the analyses passed in the options struct
242inline BasicBlock *
246 Instruction *TI = Src->getTerminator();
247 unsigned i = 0;
248 while (true) {
249 assert(i != TI->getNumSuccessors() && "Edge doesn't exist!");
250 if (TI->getSuccessor(i) == Dst)
251 return SplitCriticalEdge(TI, i, Options);
252 ++i;
253 }
254}
255
256/// Loop over all of the edges in the CFG, breaking critical edges as they are
257/// found. Returns the number of broken edges.
258LLVM_ABI unsigned
259SplitAllCriticalEdges(Function &F, const CriticalEdgeSplittingOptions &Options =
260 CriticalEdgeSplittingOptions());
261
262/// Split the edge connecting the specified blocks, and return the newly created
263/// basic block between \p From and \p To.
264LLVM_ABI BasicBlock *SplitEdge(BasicBlock *From, BasicBlock *To,
265 DominatorTree *DT = nullptr,
266 LoopInfo *LI = nullptr,
267 MemorySSAUpdater *MSSAU = nullptr,
268 const Twine &BBName = "");
269
270/// \brief Create a new intermediate target block for a callbr edge.
271///
272/// Create a new basic block between a callbr instruction and one of its
273/// successors. The new block replaces the original successor in the callbr
274/// instruction and unconditionally branches to the original successor. This
275/// is useful for normalizing control flow, e.g., when transforming
276/// irreducible loops.
277///
278/// \param CallBrBlock block containing the callbr instruction
279/// \param Succ original successor block
280/// \param SuccIdx index of the original successor in the callbr
281/// instruction
282/// \param DTU optional \p DomTreeUpdater for updating the
283/// dominator tree
284/// \param CI optional \p CycleInfo for updating cycle membership
285/// \param LI optional \p LoopInfo for updating loop membership
286/// \param UpdatedLI optional output flag indicating if \p LoopInfo has
287/// been updated
288///
289/// \returns newly created intermediate target block
290///
291/// \note This function updates PHI nodes, dominator tree, loop info, and
292/// cycle info as needed.
293LLVM_ABI BasicBlock *
294SplitCallBrEdge(BasicBlock *CallBrBlock, BasicBlock *Succ, unsigned SuccIdx,
295 DomTreeUpdater *DTU = nullptr, CycleInfo *CI = nullptr,
296 LoopInfo *LI = nullptr, bool *UpdatedLI = nullptr);
297
298/// Sets the unwind edge of an instruction to a particular successor.
299LLVM_ABI void setUnwindEdgeTo(Instruction *TI, BasicBlock *Succ);
300
301/// Replaces all uses of OldPred with the NewPred block in all PHINodes in a
302/// block.
303LLVM_ABI void updatePhiNodes(BasicBlock *DestBB, BasicBlock *OldPred,
304 BasicBlock *NewPred, PHINode *Until = nullptr);
305
306/// Split the edge connect the specficed blocks in the case that \p Succ is an
307/// Exception Handling Block
308LLVM_ABI BasicBlock *
309ehAwareSplitEdge(BasicBlock *BB, BasicBlock *Succ,
310 LandingPadInst *OriginalPad = nullptr,
311 PHINode *LandingPadReplacement = nullptr,
312 const CriticalEdgeSplittingOptions &Options =
313 CriticalEdgeSplittingOptions(),
314 const Twine &BBName = "");
315
316/// Split the specified block at the specified instruction.
317///
318/// Everything before \p SplitPt stays in \p Old and everything starting with \p
319/// SplitPt moves to a new block. The two blocks are joined by an unconditional
320/// branch. The new block with name \p BBName is returned.
321///
322/// FIXME: deprecated, switch to the DomTreeUpdater-based one.
323LLVM_ABI BasicBlock *SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt,
324 DominatorTree *DT, LoopInfo *LI = nullptr,
325 MemorySSAUpdater *MSSAU = nullptr,
326 const Twine &BBName = "");
328 DominatorTree *DT, LoopInfo *LI = nullptr,
329 MemorySSAUpdater *MSSAU = nullptr,
330 const Twine &BBName = "") {
331 return SplitBlock(Old, SplitPt->getIterator(), DT, LI, MSSAU, BBName);
332}
333
334/// Split the specified block at the specified instruction.
335///
336/// Everything before \p SplitPt stays in \p Old and everything starting with \p
337/// SplitPt moves to a new block. The two blocks are joined by an unconditional
338/// branch. The new block with name \p BBName is returned.
339LLVM_ABI BasicBlock *SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt,
340 DomTreeUpdater *DTU = nullptr,
341 LoopInfo *LI = nullptr,
342 MemorySSAUpdater *MSSAU = nullptr,
343 const Twine &BBName = "");
345 DomTreeUpdater *DTU = nullptr,
346 LoopInfo *LI = nullptr,
347 MemorySSAUpdater *MSSAU = nullptr,
348 const Twine &BBName = "") {
349 return SplitBlock(Old, SplitPt->getIterator(), DTU, LI, MSSAU, BBName);
350}
351
352/// Split the specified block at the specified instruction \p SplitPt.
353/// All instructions before \p SplitPt are moved to a new block and all
354/// instructions after \p SplitPt stay in the old block. The new block and the
355/// old block are joined by inserting an unconditional branch to the end of the
356/// new block. The new block with name \p BBName is returned.
357LLVM_ABI BasicBlock *splitBlockBefore(BasicBlock *Old,
358 BasicBlock::iterator SplitPt,
359 DomTreeUpdater *DTU, LoopInfo *LI,
360 MemorySSAUpdater *MSSAU,
361 const Twine &BBName = "");
363 DomTreeUpdater *DTU, LoopInfo *LI,
364 MemorySSAUpdater *MSSAU, const Twine &BBName = "") {
365 return splitBlockBefore(Old, SplitPt->getIterator(), DTU, LI, MSSAU, BBName);
366}
367
368/// This method introduces at least one new basic block into the function and
369/// moves some of the predecessors of BB to be predecessors of the new block.
370/// The new predecessors are indicated by the Preds array. The new block is
371/// given a suffix of 'Suffix'. Returns new basic block to which predecessors
372/// from Preds are now pointing.
373///
374/// If BB is a landingpad block then additional basicblock might be introduced.
375/// It will have Suffix+".split_lp". See SplitLandingPadPredecessors for more
376/// details on this case.
377///
378/// This currently updates the LLVM IR, DominatorTree, LoopInfo, and LCCSA but
379/// no other analyses. In particular, it does not preserve LoopSimplify
380/// (because it's complicated to handle the case where one of the edges being
381/// split is an exit of a loop with other exits).
382///
383/// FIXME: deprecated, switch to the DomTreeUpdater-based one.
385 BasicBlock *BB, ArrayRef<BasicBlock *> Preds, const char *Suffix,
386 DominatorTree *DT, LoopInfo *LI = nullptr,
387 MemorySSAUpdater *MSSAU = nullptr, bool PreserveLCSSA = false);
388
389/// This method introduces at least one new basic block into the function and
390/// moves some of the predecessors of BB to be predecessors of the new block.
391/// The new predecessors are indicated by the Preds array. The new block is
392/// given a suffix of 'Suffix'. Returns new basic block to which predecessors
393/// from Preds are now pointing.
394///
395/// If BB is a landingpad block then additional basicblock might be introduced.
396/// It will have Suffix+".split_lp". See SplitLandingPadPredecessors for more
397/// details on this case.
398///
399/// This currently updates the LLVM IR, DominatorTree, LoopInfo, and LCCSA but
400/// no other analyses. In particular, it does not preserve LoopSimplify
401/// (because it's complicated to handle the case where one of the edges being
402/// split is an exit of a loop with other exits).
404 BasicBlock *BB, ArrayRef<BasicBlock *> Preds, const char *Suffix,
405 DomTreeUpdater *DTU = nullptr, LoopInfo *LI = nullptr,
406 MemorySSAUpdater *MSSAU = nullptr, bool PreserveLCSSA = false);
407
408/// This method transforms the landing pad, OrigBB, by introducing two new basic
409/// blocks into the function. One of those new basic blocks gets the
410/// predecessors listed in Preds. The other basic block gets the remaining
411/// predecessors of OrigBB. The landingpad instruction OrigBB is clone into both
412/// of the new basic blocks. The new blocks are given the suffixes 'Suffix1' and
413/// 'Suffix2', and are returned in the NewBBs vector.
414///
415/// This currently updates the LLVM IR, DominatorTree, LoopInfo, and LCCSA but
416/// no other analyses. In particular, it does not preserve LoopSimplify
417/// (because it's complicated to handle the case where one of the edges being
418/// split is an exit of a loop with other exits).
420 BasicBlock *OrigBB, ArrayRef<BasicBlock *> Preds, const char *Suffix,
421 const char *Suffix2, SmallVectorImpl<BasicBlock *> &NewBBs,
422 DomTreeUpdater *DTU = nullptr, LoopInfo *LI = nullptr,
423 MemorySSAUpdater *MSSAU = nullptr, bool PreserveLCSSA = false);
424
425/// This method duplicates the specified return instruction into a predecessor
426/// which ends in an unconditional branch. If the return instruction returns a
427/// value defined by a PHI, propagate the right value into the return. It
428/// returns the new return instruction in the predecessor.
429LLVM_ABI ReturnInst *FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB,
430 BasicBlock *Pred,
431 DomTreeUpdater *DTU = nullptr);
432
433/// Split the containing block at the specified instruction - everything before
434/// SplitBefore stays in the old basic block, and the rest of the instructions
435/// in the BB are moved to a new block. The two blocks are connected by a
436/// conditional branch (with value of Cmp being the condition).
437/// Before:
438/// Head
439/// SplitBefore
440/// Tail
441/// After:
442/// Head
443/// if (Cond)
444/// ThenBlock
445/// SplitBefore
446/// Tail
447///
448/// If \p ThenBlock is not specified, a new block will be created for it.
449/// If \p Unreachable is true, the newly created block will end with
450/// UnreachableInst, otherwise it branches to Tail.
451/// Returns the NewBasicBlock's terminator.
452///
453/// Updates DTU and LI if given.
454LLVM_ABI Instruction *
456 bool Unreachable, MDNode *BranchWeights = nullptr,
457 DomTreeUpdater *DTU = nullptr, LoopInfo *LI = nullptr,
458 BasicBlock *ThenBlock = nullptr);
459
461 bool Unreachable,
462 MDNode *BranchWeights = nullptr,
463 DomTreeUpdater *DTU = nullptr,
464 LoopInfo *LI = nullptr,
465 BasicBlock *ThenBlock = nullptr) {
466 return SplitBlockAndInsertIfThen(Cond, SplitBefore->getIterator(),
467 Unreachable, BranchWeights, DTU, LI,
468 ThenBlock);
469}
470
471/// Similar to SplitBlockAndInsertIfThen, but the inserted block is on the false
472/// path of the branch.
473LLVM_ABI Instruction *
475 bool Unreachable, MDNode *BranchWeights = nullptr,
476 DomTreeUpdater *DTU = nullptr, LoopInfo *LI = nullptr,
477 BasicBlock *ElseBlock = nullptr);
478
480 bool Unreachable,
481 MDNode *BranchWeights = nullptr,
482 DomTreeUpdater *DTU = nullptr,
483 LoopInfo *LI = nullptr,
484 BasicBlock *ElseBlock = nullptr) {
485 return SplitBlockAndInsertIfElse(Cond, SplitBefore->getIterator(),
486 Unreachable, BranchWeights, DTU, LI,
487 ElseBlock);
488}
489
490/// SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen,
491/// but also creates the ElseBlock.
492/// Before:
493/// Head
494/// SplitBefore
495/// Tail
496/// After:
497/// Head
498/// if (Cond)
499/// ThenBlock
500/// else
501/// ElseBlock
502/// SplitBefore
503/// Tail
504///
505/// Updates DT if given.
507 Value *Cond, BasicBlock::iterator SplitBefore, Instruction **ThenTerm,
508 Instruction **ElseTerm, MDNode *BranchWeights = nullptr,
509 DomTreeUpdater *DTU = nullptr, LoopInfo *LI = nullptr);
510
512 Instruction **ThenTerm,
513 Instruction **ElseTerm,
514 MDNode *BranchWeights = nullptr,
515 DomTreeUpdater *DTU = nullptr,
516 LoopInfo *LI = nullptr)
517{
518 SplitBlockAndInsertIfThenElse(Cond, SplitBefore->getIterator(), ThenTerm,
519 ElseTerm, BranchWeights, DTU, LI);
520}
521
522/// Split the containing block at the specified instruction - everything before
523/// SplitBefore stays in the old basic block, and the rest of the instructions
524/// in the BB are moved to a new block. The two blocks are connected by a
525/// conditional branch (with value of Cmp being the condition).
526/// Before:
527/// Head
528/// SplitBefore
529/// Tail
530/// After:
531/// Head
532/// if (Cond)
533/// TrueBlock
534/// else
535//// FalseBlock
536/// SplitBefore
537/// Tail
538///
539/// If \p ThenBlock is null, the resulting CFG won't contain the TrueBlock. If
540/// \p ThenBlock is non-null and points to non-null BasicBlock pointer, that
541/// block will be inserted as the TrueBlock. Otherwise a new block will be
542/// created. Likewise for the \p ElseBlock parameter.
543/// If \p UnreachableThen or \p UnreachableElse is true, the corresponding newly
544/// created blocks will end with UnreachableInst, otherwise with branches to
545/// Tail. The function will not modify existing basic blocks passed to it. The
546/// caller must ensure that Tail is reachable from Head.
547/// Returns the newly created blocks in \p ThenBlock and \p ElseBlock.
548/// Updates DTU and LI if given.
550 Value *Cond, BasicBlock::iterator SplitBefore, BasicBlock **ThenBlock,
551 BasicBlock **ElseBlock, bool UnreachableThen = false,
552 bool UnreachableElse = false, MDNode *BranchWeights = nullptr,
553 DomTreeUpdater *DTU = nullptr, LoopInfo *LI = nullptr);
554
556 BasicBlock **ThenBlock,
557 BasicBlock **ElseBlock,
558 bool UnreachableThen = false,
559 bool UnreachableElse = false,
560 MDNode *BranchWeights = nullptr,
561 DomTreeUpdater *DTU = nullptr,
562 LoopInfo *LI = nullptr) {
563 SplitBlockAndInsertIfThenElse(Cond, SplitBefore->getIterator(), ThenBlock,
564 ElseBlock, UnreachableThen, UnreachableElse, BranchWeights, DTU, LI);
565}
566
567/// Insert a for (int i = 0; i < End; i++) loop structure (with the exception
568/// that \p End is assumed > 0, and thus not checked on entry) at \p
569/// SplitBefore. Returns the first insert point in the loop body, and the
570/// PHINode for the induction variable (i.e. "i" above).
571LLVM_ABI std::pair<Instruction *, Value *>
573
574/// Utility function for performing a given action on each lane of a vector
575/// with \p EC elements. To simplify porting legacy code, this defaults to
576/// unrolling the implied loop for non-scalable element counts, but this is
577/// not considered to be part of the contract of this routine, and is
578/// expected to change in the future. The callback takes as arguments an
579/// IRBuilder whose insert point is correctly set for instantiating the
580/// given index, and a value which is (at runtime) the index to access.
581/// This index *may* be a constant.
583 ElementCount EC, Type *IndexTy, BasicBlock::iterator InsertBefore,
584 std::function<void(IRBuilderBase &, Value *)> Func);
585
586/// Utility function for performing a given action on each lane of a vector
587/// with \p EVL effective length. EVL is assumed > 0. To simplify porting legacy
588/// code, this defaults to unrolling the implied loop for non-scalable element
589/// counts, but this is not considered to be part of the contract of this
590/// routine, and is expected to change in the future. The callback takes as
591/// arguments an IRBuilder whose insert point is correctly set for instantiating
592/// the given index, and a value which is (at runtime) the index to access. This
593/// index *may* be a constant.
595 Value *End, BasicBlock::iterator InsertBefore,
596 std::function<void(IRBuilderBase &, Value *)> Func);
597
598/// Check whether BB is the merge point of a if-region.
599/// If so, return the branch instruction that determines which entry into
600/// BB will be taken. Also, return by references the block that will be
601/// entered from if the condition is true, and the block that will be
602/// entered if the condition is false.
603///
604/// This does no checking to see if the true/false blocks have large or unsavory
605/// instructions in them.
606LLVM_ABI BranchInst *GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
607 BasicBlock *&IfFalse);
608
609// Split critical edges where the source of the edge is an indirectbr
610// instruction. This isn't always possible, but we can handle some easy cases.
611// This is useful because MI is unable to split such critical edges,
612// which means it will not be able to sink instructions along those edges.
613// This is especially painful for indirect branches with many successors, where
614// we end up having to prepare all outgoing values in the origin block.
615//
616// Our normal algorithm for splitting critical edges requires us to update
617// the outgoing edges of the edge origin block, but for an indirectbr this
618// is hard, since it would require finding and updating the block addresses
619// the indirect branch uses. But if a block only has a single indirectbr
620// predecessor, with the others being regular branches, we can do it in a
621// different way.
622// Say we have A -> D, B -> D, I -> D where only I -> D is an indirectbr.
623// We can split D into D0 and D1, where D0 contains only the PHIs from D,
624// and D1 is the D block body. We can then duplicate D0 as D0A and D0B, and
625// create the following structure:
626// A -> D0A, B -> D0A, I -> D0B, D0A -> D1, D0B -> D1
627// If BPI and BFI aren't non-null, BPI/BFI will be updated accordingly.
628// When `IgnoreBlocksWithoutPHI` is set to `true` critical edges leading to a
629// block without phi-instructions will not be split.
631 bool IgnoreBlocksWithoutPHI,
632 BranchProbabilityInfo *BPI = nullptr,
633 BlockFrequencyInfo *BFI = nullptr);
634
635// Utility function for inverting branch condition and for swapping its
636// successors
637LLVM_ABI void InvertBranch(BranchInst *PBI, IRBuilderBase &Builder);
638
639// Check whether the function only has simple terminator:
640// br/brcond/unreachable/ret
641LLVM_ABI bool hasOnlySimpleTerminator(const Function &F);
642
643/// Print BasicBlock \p BB as an operand or print "<nullptr>" if \p BB is a
644/// nullptr.
645LLVM_ABI Printable printBasicBlock(const BasicBlock *BB);
646
647} // end namespace llvm
648
649#endif // LLVM_TRANSFORMS_UTILS_BASICBLOCKUTILS_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define LLVM_ABI
Definition Compiler.h:213
This file declares the LLVM IR specialization of the GenericCycle templates.
static LVOptions Options
Definition LVOptions.cpp:25
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static cl::opt< bool > SplitAllCriticalEdges("phi-elim-split-all-critical-edges", cl::init(false), cl::Hidden, cl::desc("Split all critical edges during " "PHI elimination"))
const SmallVectorImpl< MachineOperand > & Cond
This file implements a set that has insertion order iteration characteristics.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
LLVM Basic Block Representation.
Definition BasicBlock.h:62
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
Conditional or Unconditional Branch instruction.
Analysis providing branch probability information.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:164
Common base class shared among various IRBuilders.
Definition IRBuilder.h:114
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
LLVM_ABI BasicBlock * getSuccessor(unsigned Idx) const LLVM_READONLY
Return the specified successor. This instruction must be a terminator.
The landingpad instruction holds all of the information necessary to generate correct exception handl...
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Metadata node.
Definition Metadata.h:1080
Provides a lazy, caching interface for making common memory aliasing information queries,...
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
Return a value (possibly void), from a function.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Provides information about what library functions are available for the current target.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
LLVM Value Representation.
Definition Value.h:75
self_iterator getIterator()
Definition ilist_node.h:123
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
LLVM_ABI void ReplaceInstWithInst(BasicBlock *BB, BasicBlock::iterator &BI, Instruction *I)
Replace the instruction specified by BI with the instruction specified by I.
LLVM_ABI bool RemoveRedundantDbgInstrs(BasicBlock *BB)
Try to remove redundant dbg.value instructions from given basic block.
LLVM_ABI bool IsBlockFollowedByDeoptOrUnreachable(const BasicBlock *BB)
Check if we can prove that all paths starting from this block converge to a block that either has a @...
LLVM_ABI BranchInst * GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue, BasicBlock *&IfFalse)
Check whether BB is the merge point of a if-region.
LLVM_ABI void detachDeadBlocks(ArrayRef< BasicBlock * > BBs, SmallVectorImpl< DominatorTree::UpdateType > *Updates, bool KeepOneInputPHIs=false)
Replace contents of every block in BBs with single unreachable instruction.
LLVM_ABI bool hasOnlySimpleTerminator(const Function &F)
LLVM_ABI ReturnInst * FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB, BasicBlock *Pred, DomTreeUpdater *DTU=nullptr)
This method duplicates the specified return instruction into a predecessor which ends in an unconditi...
LLVM_ABI std::pair< Instruction *, Value * > SplitBlockAndInsertSimpleForLoop(Value *End, BasicBlock::iterator SplitBefore)
Insert a for (int i = 0; i < End; i++) loop structure (with the exception that End is assumed > 0,...
LLVM_ABI BasicBlock * splitBlockBefore(BasicBlock *Old, BasicBlock::iterator SplitPt, DomTreeUpdater *DTU, LoopInfo *LI, MemorySSAUpdater *MSSAU, const Twine &BBName="")
Split the specified block at the specified instruction SplitPt.
LLVM_ABI Instruction * SplitBlockAndInsertIfElse(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ElseBlock=nullptr)
Similar to SplitBlockAndInsertIfThen, but the inserted block is on the false path of the branch.
LLVM_ABI BasicBlock * SplitCallBrEdge(BasicBlock *CallBrBlock, BasicBlock *Succ, unsigned SuccIdx, DomTreeUpdater *DTU=nullptr, CycleInfo *CI=nullptr, LoopInfo *LI=nullptr, bool *UpdatedLI=nullptr)
Create a new intermediate target block for a callbr edge.
LLVM_ABI void DeleteDeadBlock(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete the specified block, which must have no predecessors.
LLVM_ABI void ReplaceInstWithValue(BasicBlock::iterator &BI, Value *V)
Replace all uses of an instruction (specified by BI) with a value, then remove and delete the origina...
LLVM_ABI BasicBlock * SplitKnownCriticalEdge(Instruction *TI, unsigned SuccNum, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions(), const Twine &BBName="")
If it is known that an edge is critical, SplitKnownCriticalEdge can be called directly,...
LLVM_ABI bool SplitIndirectBrCriticalEdges(Function &F, bool IgnoreBlocksWithoutPHI, BranchProbabilityInfo *BPI=nullptr, BlockFrequencyInfo *BFI=nullptr)
LLVM_ABI bool DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr)
Examine each PHI in the given block and delete it if it is dead.
LLVM_ABI bool HasLoopOrEntryConvergenceToken(const BasicBlock *BB)
Check if the given basic block contains any loop or entry convergent intrinsic instructions.
LLVM_ABI void InvertBranch(BranchInst *PBI, IRBuilderBase &Builder)
LLVM_ABI bool EliminateUnreachableBlocks(Function &F, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete all basic blocks from F that are not reachable from its entry node.
LLVM_ABI bool MergeBlockSuccessorsIntoGivenBlocks(SmallPtrSetImpl< BasicBlock * > &MergeBlocks, Loop *L=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr)
Merge block(s) sucessors, if possible.
LLVM_ABI void SplitBlockAndInsertIfThenElse(Value *Cond, BasicBlock::iterator SplitBefore, Instruction **ThenTerm, Instruction **ElseTerm, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr)
SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen, but also creates the ElseBlock...
LLVM_ABI BasicBlock * ehAwareSplitEdge(BasicBlock *BB, BasicBlock *Succ, LandingPadInst *OriginalPad=nullptr, PHINode *LandingPadReplacement=nullptr, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions(), const Twine &BBName="")
Split the edge connect the specficed blocks in the case that Succ is an Exception Handling Block.
LLVM_ABI void SplitLandingPadPredecessors(BasicBlock *OrigBB, ArrayRef< BasicBlock * > Preds, const char *Suffix, const char *Suffix2, SmallVectorImpl< BasicBlock * > &NewBBs, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, bool PreserveLCSSA=false)
This method transforms the landing pad, OrigBB, by introducing two new basic blocks into the function...
LLVM_ABI BasicBlock * SplitBlockPredecessors(BasicBlock *BB, ArrayRef< BasicBlock * > Preds, const char *Suffix, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, bool PreserveLCSSA=false)
This method introduces at least one new basic block into the function and moves some of the predecess...
LLVM_ABI void createPHIsForSplitLoopExit(ArrayRef< BasicBlock * > Preds, BasicBlock *SplitBB, BasicBlock *DestBB)
When a loop exit edge is split, LCSSA form may require new PHIs in the new exit block.
LLVM_ABI bool MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, MemoryDependenceResults *MemDep=nullptr, bool PredecessorWithTwoSuccessors=false, DominatorTree *DT=nullptr)
Attempts to merge a block into its predecessor, if possible.
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction.
LLVM_ABI BasicBlock * SplitCriticalEdge(Instruction *TI, unsigned SuccNum, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions(), const Twine &BBName="")
If this edge is a critical edge, insert a new node to split the critical edge.
LLVM_ABI bool FoldSingleEntryPHINodes(BasicBlock *BB, MemoryDependenceResults *MemDep=nullptr)
We know that BB has one predecessor.
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI void updatePhiNodes(BasicBlock *DestBB, BasicBlock *OldPred, BasicBlock *NewPred, PHINode *Until=nullptr)
Replaces all uses of OldPred with the NewPred block in all PHINodes in a block.
LLVM_ABI Printable printBasicBlock(const BasicBlock *BB)
Print BasicBlock BB as an operand or print "<nullptr>" if BB is a nullptr.
LLVM_ABI Instruction * SplitBlockAndInsertIfThen(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
LLVM_ABI void DeleteDeadBlocks(ArrayRef< BasicBlock * > BBs, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete the specified blocks from BB.
LLVM_ABI BasicBlock * SplitEdge(BasicBlock *From, BasicBlock *To, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the edge connecting the specified blocks, and return the newly created basic block between From...
LLVM_ABI void setUnwindEdgeTo(Instruction *TI, BasicBlock *Succ)
Sets the unwind edge of an instruction to a particular successor.
LLVM_ABI void SplitBlockAndInsertForEachLane(ElementCount EC, Type *IndexTy, BasicBlock::iterator InsertBefore, std::function< void(IRBuilderBase &, Value *)> Func)
Utility function for performing a given action on each lane of a vector with EC elements.
GenericCycleInfo< SSAContext > CycleInfo
Definition CycleInfo.h:23
Option class for critical edge splitting.
CriticalEdgeSplittingOptions(DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, PostDominatorTree *PDT=nullptr)
CriticalEdgeSplittingOptions & setMergeIdenticalEdges()
CriticalEdgeSplittingOptions & setKeepOneInputPHIs()
bool PreserveLoopSimplify
SplitCriticalEdge is guaranteed to preserve loop-simplify form if LI is provided.
CriticalEdgeSplittingOptions & unsetPreserveLoopSimplify()
CriticalEdgeSplittingOptions & setPreserveLCSSA()
CriticalEdgeSplittingOptions & setIgnoreUnreachableDests()