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/Dominators.h"
25#include <cassert>
26
27namespace llvm {
28class CondBrInst;
29class CycleInfo;
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.
94LLVM_ABI bool
95DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI = nullptr,
96 MemorySSAUpdater *MSSAU = nullptr,
97 SmallPtrSetImpl<PHINode *> *KnownNonDeadPHIs = nullptr);
98
99/// Attempts to merge a block into its predecessor, if possible. The return
100/// value indicates success or failure.
101/// By default do not merge blocks if BB's predecessor has multiple successors.
102/// If PredecessorWithTwoSuccessors = true, the blocks can only be merged
103/// if BB's Pred has a branch to BB and to AnotherBB, and BB has a single
104/// successor Sing. In this case the branch will be updated with Sing instead of
105/// BB, and BB will still be merged into its predecessor and removed.
106/// If \p DT is not nullptr, update it directly; in that case, DTU must be
107/// nullptr.
109 BasicBlock *BB, DomTreeUpdater *DTU = nullptr, LoopInfo *LI = nullptr,
110 MemorySSAUpdater *MSSAU = nullptr,
111 MemoryDependenceResults *MemDep = nullptr,
112 bool PredecessorWithTwoSuccessors = false, DominatorTree *DT = nullptr);
113
114/// Merge block(s) sucessors, if possible. Return true if at least two
115/// of the blocks were merged together.
116/// In order to merge, each block must be terminated by an unconditional
117/// branch. If L is provided, then the blocks merged into their predecessors
118/// must be in L. In addition, This utility calls on another utility:
119/// MergeBlockIntoPredecessor. Blocks are successfully merged when the call to
120/// MergeBlockIntoPredecessor returns true.
122 SmallPtrSetImpl<BasicBlock *> &MergeBlocks, Loop *L = nullptr,
123 DomTreeUpdater *DTU = nullptr, LoopInfo *LI = nullptr);
124
125/// Try to remove redundant dbg.value instructions from given basic block.
126/// Returns true if at least one instruction was removed. Remove redundant
127/// pseudo ops when RemovePseudoOp is true.
129
130/// Replace all uses of an instruction (specified by BI) with a value, then
131/// remove and delete the original instruction.
133
134/// Replace the instruction specified by BI with the instruction specified by I.
135/// Copies DebugLoc from BI to I, if I doesn't already have a DebugLoc. The
136/// original instruction is deleted and BI is updated to point to the new
137/// instruction.
139 Instruction *I);
140
141/// Replace the instruction specified by From with the instruction specified by
142/// To. Copies DebugLoc from BI to I, if I doesn't already have a DebugLoc.
144
145/// Check if we can prove that all paths starting from this block converge
146/// to a block that either has a @llvm.experimental.deoptimize call
147/// prior to its terminating return instruction or is terminated by unreachable.
148/// All blocks in the traversed sequence must have an unique successor, maybe
149/// except for the last one.
151
152/// Option class for critical edge splitting.
153///
154/// This provides a builder interface for overriding the default options used
155/// during critical edge splitting.
162 bool KeepOneInputPHIs = false;
163 bool PreserveLCSSA = false;
165 /// SplitCriticalEdge is guaranteed to preserve loop-simplify form if LI is
166 /// provided. If it cannot be preserved, no splitting will take place. If it
167 /// is not set, preserve loop-simplify form if possible.
169
171 LoopInfo *LI = nullptr,
172 MemorySSAUpdater *MSSAU = nullptr,
173 PostDominatorTree *PDT = nullptr)
174 : DT(DT), PDT(PDT), LI(LI), MSSAU(MSSAU) {}
175
180
182 KeepOneInputPHIs = true;
183 return *this;
184 }
185
187 PreserveLCSSA = true;
188 return *this;
189 }
190
195
200};
201
202/// When a loop exit edge is split, LCSSA form may require new PHIs in the new
203/// exit block. This function inserts the new PHIs, as needed. Preds is a list
204/// of preds inside the loop, SplitBB is the new loop exit block, and DestBB is
205/// the old loop exit, now the successor of SplitBB.
207 BasicBlock *SplitBB,
208 BasicBlock *DestBB);
209
210/// If this edge is a critical edge, insert a new node to split the critical
211/// edge. This will update the analyses passed in through the option struct.
212/// This returns the new block if the edge was split, null otherwise.
213///
214/// If MergeIdenticalEdges in the options struct is true (not the default),
215/// *all* edges from TI to the specified successor will be merged into the same
216/// critical edge block. This is most commonly interesting with switch
217/// instructions, which may have many edges to any one destination. This
218/// ensures that all edges to that dest go to one block instead of each going
219/// to a different block, but isn't the standard definition of a "critical
220/// edge".
221///
222/// It is invalid to call this function on a critical edge that starts at an
223/// IndirectBrInst. Splitting these edges will almost always create an invalid
224/// program because the address of the new block won't be the one that is jumped
225/// to.
226LLVM_ABI BasicBlock *
227SplitCriticalEdge(Instruction *TI, unsigned SuccNum,
228 const CriticalEdgeSplittingOptions &Options =
229 CriticalEdgeSplittingOptions(),
230 const Twine &BBName = "");
231
232/// If it is known that an edge is critical, SplitKnownCriticalEdge can be
233/// called directly, rather than calling SplitCriticalEdge first.
234LLVM_ABI BasicBlock *
235SplitKnownCriticalEdge(Instruction *TI, unsigned SuccNum,
236 const CriticalEdgeSplittingOptions &Options =
237 CriticalEdgeSplittingOptions(),
238 const Twine &BBName = "");
239
240/// If an edge from Src to Dst is critical, split the edge and return true,
241/// otherwise return false. This method requires that there be an edge between
242/// the two blocks. It updates the analyses passed in the options struct
243inline BasicBlock *
247 Instruction *TI = Src->getTerminator();
248 unsigned i = 0;
249 while (true) {
250 assert(i != TI->getNumSuccessors() && "Edge doesn't exist!");
251 if (TI->getSuccessor(i) == Dst)
252 return SplitCriticalEdge(TI, i, Options);
253 ++i;
254 }
255}
256
257/// Loop over all of the edges in the CFG, breaking critical edges as they are
258/// found. Returns the number of broken edges.
259LLVM_ABI unsigned
260SplitAllCriticalEdges(Function &F, const CriticalEdgeSplittingOptions &Options =
261 CriticalEdgeSplittingOptions());
262
263/// Split the edge connecting the specified blocks, and return the newly created
264/// basic block between \p From and \p To.
265LLVM_ABI BasicBlock *SplitEdge(BasicBlock *From, BasicBlock *To,
266 DominatorTree *DT = nullptr,
267 LoopInfo *LI = nullptr,
268 MemorySSAUpdater *MSSAU = nullptr,
269 const Twine &BBName = "");
270
271/// \brief Create a new intermediate target block for a callbr edge.
272///
273/// Create a new basic block between a callbr instruction and one of its
274/// successors. The new block replaces the original successor in the callbr
275/// instruction and unconditionally branches to the original successor. This
276/// is useful for normalizing control flow, e.g., when transforming
277/// irreducible loops.
278///
279/// \param CallBrBlock block containing the callbr instruction
280/// \param Succ original successor block
281/// \param SuccIdx index of the original successor in the callbr
282/// instruction
283/// \param CallBrTarget optional \p BasicBlock generated by \c SplitCallBrEdge
284/// to reuse for the split
285/// \param DTU optional \p DomTreeUpdater for updating the
286/// dominator tree
287/// \param CI optional \p CycleInfo for updating cycle membership
288/// \param LI optional \p LoopInfo for updating loop membership
289/// \param UpdatedLI optional output flag indicating if \p LoopInfo has
290/// been updated
291///
292/// \returns newly created intermediate target block
293///
294/// \note This function updates PHI nodes, dominator tree, loop info, and
295/// cycle info as needed.
296LLVM_ABI BasicBlock *
297SplitCallBrEdge(BasicBlock *CallBrBlock, BasicBlock *Succ, unsigned SuccIdx,
298 BasicBlock *CallBrTarget = nullptr,
299 DomTreeUpdater *DTU = nullptr, CycleInfo *CI = nullptr,
300 LoopInfo *LI = nullptr, bool *UpdatedLI = nullptr);
301
302/// Sets the unwind edge of an instruction to a particular successor.
303LLVM_ABI void setUnwindEdgeTo(Instruction *TI, BasicBlock *Succ);
304
305/// Replaces all uses of OldPred with the NewPred block in all PHINodes in a
306/// block.
307LLVM_ABI void updatePhiNodes(BasicBlock *DestBB, BasicBlock *OldPred,
308 BasicBlock *NewPred, PHINode *Until = nullptr);
309
310/// Split the edge connect the specficed blocks in the case that \p Succ is an
311/// Exception Handling Block
312LLVM_ABI BasicBlock *
313ehAwareSplitEdge(BasicBlock *BB, BasicBlock *Succ,
314 LandingPadInst *OriginalPad = nullptr,
315 PHINode *LandingPadReplacement = nullptr,
316 const CriticalEdgeSplittingOptions &Options =
317 CriticalEdgeSplittingOptions(),
318 const Twine &BBName = "");
319
320/// Split the specified block at the specified instruction.
321///
322/// Everything before \p SplitPt stays in \p Old and everything starting with \p
323/// SplitPt moves to a new block. The two blocks are joined by an unconditional
324/// branch. The new block with name \p BBName is returned.
325///
326/// FIXME: deprecated, switch to the DomTreeUpdater-based one.
327LLVM_ABI BasicBlock *SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt,
328 DominatorTree *DT, LoopInfo *LI = nullptr,
329 MemorySSAUpdater *MSSAU = nullptr,
330 const Twine &BBName = "");
332 DominatorTree *DT, LoopInfo *LI = nullptr,
333 MemorySSAUpdater *MSSAU = nullptr,
334 const Twine &BBName = "") {
335 return SplitBlock(Old, SplitPt->getIterator(), DT, LI, MSSAU, BBName);
336}
337
338/// Split the specified block at the specified instruction.
339///
340/// Everything before \p SplitPt stays in \p Old and everything starting with \p
341/// SplitPt moves to a new block. The two blocks are joined by an unconditional
342/// branch. The new block with name \p BBName is returned.
343LLVM_ABI BasicBlock *SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt,
344 DomTreeUpdater *DTU = nullptr,
345 LoopInfo *LI = nullptr,
346 MemorySSAUpdater *MSSAU = nullptr,
347 const Twine &BBName = "");
349 DomTreeUpdater *DTU = nullptr,
350 LoopInfo *LI = nullptr,
351 MemorySSAUpdater *MSSAU = nullptr,
352 const Twine &BBName = "") {
353 return SplitBlock(Old, SplitPt->getIterator(), DTU, LI, MSSAU, BBName);
354}
355
356/// Split the specified block at the specified instruction \p SplitPt.
357/// All instructions before \p SplitPt are moved to a new block and all
358/// instructions after \p SplitPt stay in the old block. The new block and the
359/// old block are joined by inserting an unconditional branch to the end of the
360/// new block. The new block with name \p BBName is returned.
361LLVM_ABI BasicBlock *splitBlockBefore(BasicBlock *Old,
362 BasicBlock::iterator SplitPt,
363 DomTreeUpdater *DTU, LoopInfo *LI,
364 MemorySSAUpdater *MSSAU,
365 const Twine &BBName = "");
367 DomTreeUpdater *DTU, LoopInfo *LI,
368 MemorySSAUpdater *MSSAU, const Twine &BBName = "") {
369 return splitBlockBefore(Old, SplitPt->getIterator(), DTU, LI, MSSAU, BBName);
370}
371
372/// This method introduces at least one new basic block into the function and
373/// moves some of the predecessors of BB to be predecessors of the new block.
374/// The new predecessors are indicated by the Preds array. The new block is
375/// given a suffix of 'Suffix'. Returns new basic block to which predecessors
376/// from Preds are now pointing.
377///
378/// If BB is a landingpad block then additional basicblock might be introduced.
379/// It will have Suffix+".split_lp". See SplitLandingPadPredecessors for more
380/// details on this case.
381///
382/// This currently updates the LLVM IR, DominatorTree, LoopInfo, and LCCSA but
383/// no other analyses. In particular, it does not preserve LoopSimplify
384/// (because it's complicated to handle the case where one of the edges being
385/// split is an exit of a loop with other exits).
386///
387/// FIXME: deprecated, switch to the DomTreeUpdater-based one.
389 BasicBlock *BB, ArrayRef<BasicBlock *> Preds, const char *Suffix,
390 DominatorTree *DT, LoopInfo *LI = nullptr,
391 MemorySSAUpdater *MSSAU = nullptr, bool PreserveLCSSA = false);
392
393/// This method introduces at least one new basic block into the function and
394/// moves some of the predecessors of BB to be predecessors of the new block.
395/// The new predecessors are indicated by the Preds array. The new block is
396/// given a suffix of 'Suffix'. Returns new basic block to which predecessors
397/// from Preds are now pointing.
398///
399/// If BB is a landingpad block then additional basicblock might be introduced.
400/// It will have Suffix+".split_lp". See SplitLandingPadPredecessors for more
401/// details on this case.
402///
403/// This currently updates the LLVM IR, DominatorTree, LoopInfo, and LCCSA but
404/// no other analyses. In particular, it does not preserve LoopSimplify
405/// (because it's complicated to handle the case where one of the edges being
406/// split is an exit of a loop with other exits).
408 BasicBlock *BB, ArrayRef<BasicBlock *> Preds, const char *Suffix,
409 DomTreeUpdater *DTU = nullptr, LoopInfo *LI = nullptr,
410 MemorySSAUpdater *MSSAU = nullptr, bool PreserveLCSSA = false);
411
412/// This method transforms the landing pad, OrigBB, by introducing two new basic
413/// blocks into the function. One of those new basic blocks gets the
414/// predecessors listed in Preds. The other basic block gets the remaining
415/// predecessors of OrigBB. The landingpad instruction OrigBB is clone into both
416/// of the new basic blocks. The new blocks are given the suffixes 'Suffix1' and
417/// 'Suffix2', and are returned in the NewBBs vector.
418///
419/// This currently updates the LLVM IR, DominatorTree, LoopInfo, and LCCSA but
420/// no other analyses. In particular, it does not preserve LoopSimplify
421/// (because it's complicated to handle the case where one of the edges being
422/// split is an exit of a loop with other exits).
424 BasicBlock *OrigBB, ArrayRef<BasicBlock *> Preds, const char *Suffix,
425 const char *Suffix2, SmallVectorImpl<BasicBlock *> &NewBBs,
426 DomTreeUpdater *DTU = nullptr, LoopInfo *LI = nullptr,
427 MemorySSAUpdater *MSSAU = nullptr, bool PreserveLCSSA = false);
428
429/// This method duplicates the specified return instruction into a predecessor
430/// which ends in an unconditional branch. If the return instruction returns a
431/// value defined by a PHI, propagate the right value into the return. It
432/// returns the new return instruction in the predecessor.
433LLVM_ABI ReturnInst *FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB,
434 BasicBlock *Pred,
435 DomTreeUpdater *DTU = nullptr);
436
437/// Split the containing block at the specified instruction - everything before
438/// SplitBefore stays in the old basic block, and the rest of the instructions
439/// in the BB are moved to a new block. The two blocks are connected by a
440/// conditional branch (with value of Cmp being the condition).
441/// Before:
442/// Head
443/// SplitBefore
444/// Tail
445/// After:
446/// Head
447/// if (Cond)
448/// ThenBlock
449/// SplitBefore
450/// Tail
451///
452/// If \p ThenBlock is not specified, a new block will be created for it.
453/// If \p Unreachable is true, the newly created block will end with
454/// UnreachableInst, otherwise it branches to Tail.
455/// Returns the NewBasicBlock's terminator.
456///
457/// Updates DTU and LI if given.
458LLVM_ABI Instruction *
460 bool Unreachable, MDNode *BranchWeights = nullptr,
461 DomTreeUpdater *DTU = nullptr, LoopInfo *LI = nullptr,
462 BasicBlock *ThenBlock = nullptr);
463
465 bool Unreachable,
466 MDNode *BranchWeights = nullptr,
467 DomTreeUpdater *DTU = nullptr,
468 LoopInfo *LI = nullptr,
469 BasicBlock *ThenBlock = nullptr) {
470 return SplitBlockAndInsertIfThen(Cond, SplitBefore->getIterator(),
471 Unreachable, BranchWeights, DTU, LI,
472 ThenBlock);
473}
474
475/// Similar to SplitBlockAndInsertIfThen, but the inserted block is on the false
476/// path of the branch.
477LLVM_ABI Instruction *
479 bool Unreachable, MDNode *BranchWeights = nullptr,
480 DomTreeUpdater *DTU = nullptr, LoopInfo *LI = nullptr,
481 BasicBlock *ElseBlock = nullptr);
482
484 bool Unreachable,
485 MDNode *BranchWeights = nullptr,
486 DomTreeUpdater *DTU = nullptr,
487 LoopInfo *LI = nullptr,
488 BasicBlock *ElseBlock = nullptr) {
489 return SplitBlockAndInsertIfElse(Cond, SplitBefore->getIterator(),
490 Unreachable, BranchWeights, DTU, LI,
491 ElseBlock);
492}
493
494/// SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen,
495/// but also creates the ElseBlock.
496/// Before:
497/// Head
498/// SplitBefore
499/// Tail
500/// After:
501/// Head
502/// if (Cond)
503/// ThenBlock
504/// else
505/// ElseBlock
506/// SplitBefore
507/// Tail
508///
509/// Updates DT if given.
511 Value *Cond, BasicBlock::iterator SplitBefore, Instruction **ThenTerm,
512 Instruction **ElseTerm, MDNode *BranchWeights = nullptr,
513 DomTreeUpdater *DTU = nullptr, LoopInfo *LI = nullptr);
514
516 Instruction **ThenTerm,
517 Instruction **ElseTerm,
518 MDNode *BranchWeights = nullptr,
519 DomTreeUpdater *DTU = nullptr,
520 LoopInfo *LI = nullptr)
521{
522 SplitBlockAndInsertIfThenElse(Cond, SplitBefore->getIterator(), ThenTerm,
523 ElseTerm, BranchWeights, DTU, LI);
524}
525
526/// Split the containing block at the specified instruction - everything before
527/// SplitBefore stays in the old basic block, and the rest of the instructions
528/// in the BB are moved to a new block. The two blocks are connected by a
529/// conditional branch (with value of Cmp being the condition).
530/// Before:
531/// Head
532/// SplitBefore
533/// Tail
534/// After:
535/// Head
536/// if (Cond)
537/// TrueBlock
538/// else
539//// FalseBlock
540/// SplitBefore
541/// Tail
542///
543/// If \p ThenBlock is null, the resulting CFG won't contain the TrueBlock. If
544/// \p ThenBlock is non-null and points to non-null BasicBlock pointer, that
545/// block will be inserted as the TrueBlock. Otherwise a new block will be
546/// created. Likewise for the \p ElseBlock parameter.
547/// If \p UnreachableThen or \p UnreachableElse is true, the corresponding newly
548/// created blocks will end with UnreachableInst, otherwise with branches to
549/// Tail. The function will not modify existing basic blocks passed to it. The
550/// caller must ensure that Tail is reachable from Head.
551/// Returns the newly created blocks in \p ThenBlock and \p ElseBlock.
552/// Updates DTU and LI if given.
554 Value *Cond, BasicBlock::iterator SplitBefore, BasicBlock **ThenBlock,
555 BasicBlock **ElseBlock, bool UnreachableThen = false,
556 bool UnreachableElse = false, MDNode *BranchWeights = nullptr,
557 DomTreeUpdater *DTU = nullptr, LoopInfo *LI = nullptr);
558
560 BasicBlock **ThenBlock,
561 BasicBlock **ElseBlock,
562 bool UnreachableThen = false,
563 bool UnreachableElse = false,
564 MDNode *BranchWeights = nullptr,
565 DomTreeUpdater *DTU = nullptr,
566 LoopInfo *LI = nullptr) {
567 SplitBlockAndInsertIfThenElse(Cond, SplitBefore->getIterator(), ThenBlock,
568 ElseBlock, UnreachableThen, UnreachableElse, BranchWeights, DTU, LI);
569}
570
571/// Insert a for (int i = 0; i < End; i++) loop structure (with the exception
572/// that \p End is assumed > 0, and thus not checked on entry) at \p
573/// SplitBefore. Returns the first insert point in the loop body, and the
574/// PHINode for the induction variable (i.e. "i" above).
575LLVM_ABI std::pair<Instruction *, Value *>
577
578/// Utility function for performing a given action on each lane of a vector
579/// with \p EC elements. To simplify porting legacy code, this defaults to
580/// unrolling the implied loop for non-scalable element counts, but this is
581/// not considered to be part of the contract of this routine, and is
582/// expected to change in the future. The callback takes as arguments an
583/// IRBuilder whose insert point is correctly set for instantiating the
584/// given index, and a value which is (at runtime) the index to access.
585/// This index *may* be a constant.
587 ElementCount EC, Type *IndexTy, BasicBlock::iterator InsertBefore,
588 std::function<void(IRBuilderBase &, Value *)> Func);
589
590/// Utility function for performing a given action on each lane of a vector
591/// with \p EVL effective length. EVL is assumed > 0. To simplify porting legacy
592/// code, this defaults to unrolling the implied loop for non-scalable element
593/// counts, but this is not considered to be part of the contract of this
594/// routine, and is expected to change in the future. The callback takes as
595/// arguments an IRBuilder whose insert point is correctly set for instantiating
596/// the given index, and a value which is (at runtime) the index to access. This
597/// index *may* be a constant.
599 Value *End, BasicBlock::iterator InsertBefore,
600 std::function<void(IRBuilderBase &, Value *)> Func);
601
602/// Check whether BB is the merge point of a if-region.
603/// If so, return the branch instruction that determines which entry into
604/// BB will be taken. Also, return by references the block that will be
605/// entered from if the condition is true, and the block that will be
606/// entered if the condition is false.
607///
608/// This does no checking to see if the true/false blocks have large or unsavory
609/// instructions in them.
610LLVM_ABI CondBrInst *GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
611 BasicBlock *&IfFalse);
612
613// Split critical edges where the source of the edge is an indirectbr
614// instruction. This isn't always possible, but we can handle some easy cases.
615// This is useful because MI is unable to split such critical edges,
616// which means it will not be able to sink instructions along those edges.
617// This is especially painful for indirect branches with many successors, where
618// we end up having to prepare all outgoing values in the origin block.
619//
620// Our normal algorithm for splitting critical edges requires us to update
621// the outgoing edges of the edge origin block, but for an indirectbr this
622// is hard, since it would require finding and updating the block addresses
623// the indirect branch uses. But if a block only has a single indirectbr
624// predecessor, with the others being regular branches, we can do it in a
625// different way.
626// Say we have A -> D, B -> D, I -> D where only I -> D is an indirectbr.
627// We can split D into D0 and D1, where D0 contains only the PHIs from D,
628// and D1 is the D block body. We can then duplicate D0 as D0A and D0B, and
629// create the following structure:
630// A -> D0A, B -> D0A, I -> D0B, D0A -> D1, D0B -> D1
631// If BPI and BFI aren't non-null, BPI/BFI will be updated accordingly.
632// When `IgnoreBlocksWithoutPHI` is set to `true` critical edges leading to a
633// block without phi-instructions will not be split.
635 bool IgnoreBlocksWithoutPHI,
636 BranchProbabilityInfo *BPI = nullptr,
637 BlockFrequencyInfo *BFI = nullptr,
638 DomTreeUpdater *DTU = nullptr);
639
640// Utility function for inverting branch condition and for swapping its
641// successors
642LLVM_ABI void InvertBranch(CondBrInst *PBI, IRBuilderBase &Builder);
643
644// Check whether the function only has simple terminator:
645// br/brcond/unreachable/ret
646LLVM_ABI bool hasOnlySimpleTerminator(const Function &F);
647
648/// Print BasicBlock \p BB as an operand or print "<nullptr>" if \p BB is a
649/// nullptr.
650LLVM_ABI Printable printBasicBlock(const BasicBlock *BB);
651
652} // end namespace llvm
653
654#endif // LLVM_TRANSFORMS_UTILS_BASICBLOCKUTILS_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define LLVM_ABI
Definition Compiler.h:215
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.
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...
Analysis providing branch probability information.
Conditional Branch instruction.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:151
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:1069
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.
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 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 bool SplitIndirectBrCriticalEdges(Function &F, bool IgnoreBlocksWithoutPHI, BranchProbabilityInfo *BPI=nullptr, BlockFrequencyInfo *BFI=nullptr, DomTreeUpdater *DTU=nullptr)
LLVM_ABI bool DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, SmallPtrSetImpl< PHINode * > *KnownNonDeadPHIs=nullptr)
Examine each PHI in the given block and delete it if it is dead.
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 CondBrInst * GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue, BasicBlock *&IfFalse)
Check whether BB is the merge point of a if-region.
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(CondBrInst *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.
LLVM_ABI BasicBlock * SplitCallBrEdge(BasicBlock *CallBrBlock, BasicBlock *Succ, unsigned SuccIdx, BasicBlock *CallBrTarget=nullptr, DomTreeUpdater *DTU=nullptr, CycleInfo *CI=nullptr, LoopInfo *LI=nullptr, bool *UpdatedLI=nullptr)
Create a new intermediate target block for a callbr edge.
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()