LLVM 17.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"
23#include <cassert>
24
25namespace llvm {
26class BranchInst;
27class LandingPadInst;
28class Loop;
29class PHINode;
30template <typename PtrType> class SmallPtrSetImpl;
31class BlockFrequencyInfo;
32class BranchProbabilityInfo;
33class DomTreeUpdater;
34class Function;
35class IRBuilderBase;
36class LoopInfo;
37class MDNode;
38class MemoryDependenceResults;
39class MemorySSAUpdater;
40class PostDominatorTree;
41class ReturnInst;
42class TargetLibraryInfo;
43class Value;
44
45/// Replace contents of every block in \p BBs with single unreachable
46/// instruction. If \p Updates is specified, collect all necessary DT updates
47/// into this vector. If \p KeepOneInputPHIs is true, one-input Phis in
48/// successors of blocks being deleted will be preserved.
49void detachDeadBlocks(ArrayRef <BasicBlock *> BBs,
50 SmallVectorImpl<DominatorTree::UpdateType> *Updates,
51 bool KeepOneInputPHIs = false);
52
53/// Delete the specified block, which must have no predecessors.
54void DeleteDeadBlock(BasicBlock *BB, DomTreeUpdater *DTU = nullptr,
55 bool KeepOneInputPHIs = false);
56
57/// Delete the specified blocks from \p BB. The set of deleted blocks must have
58/// no predecessors that are not being deleted themselves. \p BBs must have no
59/// duplicating blocks. If there are loops among this set of blocks, all
60/// relevant loop info updates should be done before this function is called.
61/// If \p KeepOneInputPHIs is true, one-input Phis in successors of blocks
62/// being deleted will be preserved.
63void DeleteDeadBlocks(ArrayRef <BasicBlock *> BBs,
64 DomTreeUpdater *DTU = nullptr,
65 bool KeepOneInputPHIs = false);
66
67/// Delete all basic blocks from \p F that are not reachable from its entry
68/// node. If \p KeepOneInputPHIs is true, one-input Phis in successors of
69/// blocks being deleted will be preserved.
70bool EliminateUnreachableBlocks(Function &F, DomTreeUpdater *DTU = nullptr,
71 bool KeepOneInputPHIs = false);
72
73/// We know that BB has one predecessor. If there are any single-entry PHI nodes
74/// in it, fold them away. This handles the case when all entries to the PHI
75/// nodes in a block are guaranteed equal, such as when the block has exactly
76/// one predecessor.
77bool FoldSingleEntryPHINodes(BasicBlock *BB,
78 MemoryDependenceResults *MemDep = nullptr);
79
80/// Examine each PHI in the given block and delete it if it is dead. Also
81/// recursively delete any operands that become dead as a result. This includes
82/// tracing the def-use list from the PHI to see if it is ultimately unused or
83/// if it reaches an unused cycle. Return true if any PHIs were deleted.
84bool DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI = nullptr,
85 MemorySSAUpdater *MSSAU = nullptr);
86
87/// Attempts to merge a block into its predecessor, if possible. The return
88/// value indicates success or failure.
89/// By default do not merge blocks if BB's predecessor has multiple successors.
90/// If PredecessorWithTwoSuccessors = true, the blocks can only be merged
91/// if BB's Pred has a branch to BB and to AnotherBB, and BB has a single
92/// successor Sing. In this case the branch will be updated with Sing instead of
93/// BB, and BB will still be merged into its predecessor and removed.
94/// If \p DT is not nullptr, update it directly; in that case, DTU must be
95/// nullptr.
96bool MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU = nullptr,
97 LoopInfo *LI = nullptr,
98 MemorySSAUpdater *MSSAU = nullptr,
99 MemoryDependenceResults *MemDep = nullptr,
100 bool PredecessorWithTwoSuccessors = false,
101 DominatorTree *DT = nullptr);
102
103/// Merge block(s) sucessors, if possible. Return true if at least two
104/// of the blocks were merged together.
105/// In order to merge, each block must be terminated by an unconditional
106/// branch. If L is provided, then the blocks merged into their predecessors
107/// must be in L. In addition, This utility calls on another utility:
108/// MergeBlockIntoPredecessor. Blocks are successfully merged when the call to
109/// MergeBlockIntoPredecessor returns true.
111 SmallPtrSetImpl<BasicBlock *> &MergeBlocks, Loop *L = nullptr,
112 DomTreeUpdater *DTU = nullptr, LoopInfo *LI = nullptr);
113
114/// Try to remove redundant dbg.value instructions from given basic block.
115/// Returns true if at least one instruction was removed. Remove redundant
116/// pseudo ops when RemovePseudoOp is true.
117bool RemoveRedundantDbgInstrs(BasicBlock *BB);
118
119/// Replace all uses of an instruction (specified by BI) with a value, then
120/// remove and delete the original instruction.
122
123/// Replace the instruction specified by BI with the instruction specified by I.
124/// Copies DebugLoc from BI to I, if I doesn't already have a DebugLoc. The
125/// original instruction is deleted and BI is updated to point to the new
126/// instruction.
127void ReplaceInstWithInst(BasicBlock *BB, BasicBlock::iterator &BI,
128 Instruction *I);
129
130/// Replace the instruction specified by From with the instruction specified by
131/// To. Copies DebugLoc from BI to I, if I doesn't already have a DebugLoc.
132void ReplaceInstWithInst(Instruction *From, Instruction *To);
133
134/// Check if we can prove that all paths starting from this block converge
135/// to a block that either has a @llvm.experimental.deoptimize call
136/// prior to its terminating return instruction or is terminated by unreachable.
137/// All blocks in the traversed sequence must have an unique successor, maybe
138/// except for the last one.
139bool IsBlockFollowedByDeoptOrUnreachable(const BasicBlock *BB);
140
141/// Option class for critical edge splitting.
142///
143/// This provides a builder interface for overriding the default options used
144/// during critical edge splitting.
151 bool KeepOneInputPHIs = false;
152 bool PreserveLCSSA = false;
154 /// SplitCriticalEdge is guaranteed to preserve loop-simplify form if LI is
155 /// provided. If it cannot be preserved, no splitting will take place. If it
156 /// is not set, preserve loop-simplify form if possible.
158
160 LoopInfo *LI = nullptr,
161 MemorySSAUpdater *MSSAU = nullptr,
162 PostDominatorTree *PDT = nullptr)
163 : DT(DT), PDT(PDT), LI(LI), MSSAU(MSSAU) {}
164
166 MergeIdenticalEdges = true;
167 return *this;
168 }
169
171 KeepOneInputPHIs = true;
172 return *this;
173 }
174
176 PreserveLCSSA = true;
177 return *this;
178 }
179
182 return *this;
183 }
184
186 PreserveLoopSimplify = false;
187 return *this;
188 }
189};
190
191/// When a loop exit edge is split, LCSSA form may require new PHIs in the new
192/// exit block. This function inserts the new PHIs, as needed. Preds is a list
193/// of preds inside the loop, SplitBB is the new loop exit block, and DestBB is
194/// the old loop exit, now the successor of SplitBB.
195void createPHIsForSplitLoopExit(ArrayRef<BasicBlock *> Preds,
196 BasicBlock *SplitBB, BasicBlock *DestBB);
197
198/// If this edge is a critical edge, insert a new node to split the critical
199/// edge. This will update the analyses passed in through the option struct.
200/// This returns the new block if the edge was split, null otherwise.
201///
202/// If MergeIdenticalEdges in the options struct is true (not the default),
203/// *all* edges from TI to the specified successor will be merged into the same
204/// critical edge block. This is most commonly interesting with switch
205/// instructions, which may have many edges to any one destination. This
206/// ensures that all edges to that dest go to one block instead of each going
207/// to a different block, but isn't the standard definition of a "critical
208/// edge".
209///
210/// It is invalid to call this function on a critical edge that starts at an
211/// IndirectBrInst. Splitting these edges will almost always create an invalid
212/// program because the address of the new block won't be the one that is jumped
213/// to.
214BasicBlock *SplitCriticalEdge(Instruction *TI, unsigned SuccNum,
215 const CriticalEdgeSplittingOptions &Options =
216 CriticalEdgeSplittingOptions(),
217 const Twine &BBName = "");
218
219/// If it is known that an edge is critical, SplitKnownCriticalEdge can be
220/// called directly, rather than calling SplitCriticalEdge first.
221BasicBlock *SplitKnownCriticalEdge(Instruction *TI, unsigned SuccNum,
222 const CriticalEdgeSplittingOptions &Options =
223 CriticalEdgeSplittingOptions(),
224 const Twine &BBName = "");
225
226/// If an edge from Src to Dst is critical, split the edge and return true,
227/// otherwise return false. This method requires that there be an edge between
228/// the two blocks. It updates the analyses passed in the options struct
229inline BasicBlock *
233 Instruction *TI = Src->getTerminator();
234 unsigned i = 0;
235 while (true) {
236 assert(i != TI->getNumSuccessors() && "Edge doesn't exist!");
237 if (TI->getSuccessor(i) == Dst)
238 return SplitCriticalEdge(TI, i, Options);
239 ++i;
240 }
241}
242
243/// Loop over all of the edges in the CFG, breaking critical edges as they are
244/// found. Returns the number of broken edges.
245unsigned SplitAllCriticalEdges(Function &F,
246 const CriticalEdgeSplittingOptions &Options =
247 CriticalEdgeSplittingOptions());
248
249/// Split the edge connecting the specified blocks, and return the newly created
250/// basic block between \p From and \p To.
251BasicBlock *SplitEdge(BasicBlock *From, BasicBlock *To,
252 DominatorTree *DT = nullptr, LoopInfo *LI = nullptr,
253 MemorySSAUpdater *MSSAU = nullptr,
254 const Twine &BBName = "");
255
256/// Sets the unwind edge of an instruction to a particular successor.
257void setUnwindEdgeTo(Instruction *TI, BasicBlock *Succ);
258
259/// Replaces all uses of OldPred with the NewPred block in all PHINodes in a
260/// block.
261void updatePhiNodes(BasicBlock *DestBB, BasicBlock *OldPred,
262 BasicBlock *NewPred, PHINode *Until = nullptr);
263
264/// Split the edge connect the specficed blocks in the case that \p Succ is an
265/// Exception Handling Block
266BasicBlock *ehAwareSplitEdge(BasicBlock *BB, BasicBlock *Succ,
267 LandingPadInst *OriginalPad = nullptr,
268 PHINode *LandingPadReplacement = nullptr,
269 const CriticalEdgeSplittingOptions &Options =
270 CriticalEdgeSplittingOptions(),
271 const Twine &BBName = "");
272
273/// Split the specified block at the specified instruction.
274///
275/// If \p Before is true, splitBlockBefore handles the block
276/// splitting. Otherwise, execution proceeds as described below.
277///
278/// Everything before \p SplitPt stays in \p Old and everything starting with \p
279/// SplitPt moves to a new block. The two blocks are joined by an unconditional
280/// branch. The new block with name \p BBName is returned.
281///
282/// FIXME: deprecated, switch to the DomTreeUpdater-based one.
283BasicBlock *SplitBlock(BasicBlock *Old, Instruction *SplitPt, DominatorTree *DT,
284 LoopInfo *LI = nullptr,
285 MemorySSAUpdater *MSSAU = nullptr,
286 const Twine &BBName = "", bool Before = false);
287
288/// Split the specified block at the specified instruction.
289///
290/// If \p Before is true, splitBlockBefore handles the block
291/// splitting. Otherwise, execution proceeds as described below.
292///
293/// Everything before \p SplitPt stays in \p Old and everything starting with \p
294/// SplitPt moves to a new block. The two blocks are joined by an unconditional
295/// branch. The new block with name \p BBName is returned.
296BasicBlock *SplitBlock(BasicBlock *Old, Instruction *SplitPt,
297 DomTreeUpdater *DTU = nullptr, LoopInfo *LI = nullptr,
298 MemorySSAUpdater *MSSAU = nullptr,
299 const Twine &BBName = "", bool Before = false);
300
301/// Split the specified block at the specified instruction \p SplitPt.
302/// All instructions before \p SplitPt are moved to a new block and all
303/// instructions after \p SplitPt stay in the old block. The new block and the
304/// old block are joined by inserting an unconditional branch to the end of the
305/// new block. The new block with name \p BBName is returned.
306BasicBlock *splitBlockBefore(BasicBlock *Old, Instruction *SplitPt,
307 DomTreeUpdater *DTU, LoopInfo *LI,
308 MemorySSAUpdater *MSSAU, const Twine &BBName = "");
309
310/// This method introduces at least one new basic block into the function and
311/// moves some of the predecessors of BB to be predecessors of the new block.
312/// The new predecessors are indicated by the Preds array. The new block is
313/// given a suffix of 'Suffix'. Returns new basic block to which predecessors
314/// from Preds are now pointing.
315///
316/// If BB is a landingpad block then additional basicblock might be introduced.
317/// It will have Suffix+".split_lp". See SplitLandingPadPredecessors for more
318/// details on this case.
319///
320/// This currently updates the LLVM IR, DominatorTree, LoopInfo, and LCCSA but
321/// no other analyses. In particular, it does not preserve LoopSimplify
322/// (because it's complicated to handle the case where one of the edges being
323/// split is an exit of a loop with other exits).
324///
325/// FIXME: deprecated, switch to the DomTreeUpdater-based one.
326BasicBlock *SplitBlockPredecessors(BasicBlock *BB, ArrayRef<BasicBlock *> Preds,
327 const char *Suffix, DominatorTree *DT,
328 LoopInfo *LI = nullptr,
329 MemorySSAUpdater *MSSAU = nullptr,
330 bool PreserveLCSSA = false);
331
332/// This method introduces at least one new basic block into the function and
333/// moves some of the predecessors of BB to be predecessors of the new block.
334/// The new predecessors are indicated by the Preds array. The new block is
335/// given a suffix of 'Suffix'. Returns new basic block to which predecessors
336/// from Preds are now pointing.
337///
338/// If BB is a landingpad block then additional basicblock might be introduced.
339/// It will have Suffix+".split_lp". See SplitLandingPadPredecessors for more
340/// details on this case.
341///
342/// This currently updates the LLVM IR, DominatorTree, LoopInfo, and LCCSA but
343/// no other analyses. In particular, it does not preserve LoopSimplify
344/// (because it's complicated to handle the case where one of the edges being
345/// split is an exit of a loop with other exits).
346BasicBlock *SplitBlockPredecessors(BasicBlock *BB, ArrayRef<BasicBlock *> Preds,
347 const char *Suffix,
348 DomTreeUpdater *DTU = nullptr,
349 LoopInfo *LI = nullptr,
350 MemorySSAUpdater *MSSAU = nullptr,
351 bool PreserveLCSSA = false);
352
353/// This method transforms the landing pad, OrigBB, by introducing two new basic
354/// blocks into the function. One of those new basic blocks gets the
355/// predecessors listed in Preds. The other basic block gets the remaining
356/// predecessors of OrigBB. The landingpad instruction OrigBB is clone into both
357/// of the new basic blocks. The new blocks are given the suffixes 'Suffix1' and
358/// 'Suffix2', and are returned in the NewBBs vector.
359///
360/// This currently updates the LLVM IR, DominatorTree, LoopInfo, and LCCSA but
361/// no other analyses. In particular, it does not preserve LoopSimplify
362/// (because it's complicated to handle the case where one of the edges being
363/// split is an exit of a loop with other exits).
364///
365/// FIXME: deprecated, switch to the DomTreeUpdater-based one.
366void SplitLandingPadPredecessors(BasicBlock *OrigBB,
367 ArrayRef<BasicBlock *> Preds,
368 const char *Suffix, const char *Suffix2,
369 SmallVectorImpl<BasicBlock *> &NewBBs,
370 DominatorTree *DT, LoopInfo *LI = nullptr,
371 MemorySSAUpdater *MSSAU = nullptr,
372 bool PreserveLCSSA = false);
373
374/// This method transforms the landing pad, OrigBB, by introducing two new basic
375/// blocks into the function. One of those new basic blocks gets the
376/// predecessors listed in Preds. The other basic block gets the remaining
377/// predecessors of OrigBB. The landingpad instruction OrigBB is clone into both
378/// of the new basic blocks. The new blocks are given the suffixes 'Suffix1' and
379/// 'Suffix2', and are returned in the NewBBs vector.
380///
381/// This currently updates the LLVM IR, DominatorTree, LoopInfo, and LCCSA but
382/// no other analyses. In particular, it does not preserve LoopSimplify
383/// (because it's complicated to handle the case where one of the edges being
384/// split is an exit of a loop with other exits).
386 BasicBlock *OrigBB, ArrayRef<BasicBlock *> Preds, const char *Suffix,
387 const char *Suffix2, SmallVectorImpl<BasicBlock *> &NewBBs,
388 DomTreeUpdater *DTU = nullptr, LoopInfo *LI = nullptr,
389 MemorySSAUpdater *MSSAU = nullptr, bool PreserveLCSSA = false);
390
391/// This method duplicates the specified return instruction into a predecessor
392/// which ends in an unconditional branch. If the return instruction returns a
393/// value defined by a PHI, propagate the right value into the return. It
394/// returns the new return instruction in the predecessor.
395ReturnInst *FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB,
396 BasicBlock *Pred,
397 DomTreeUpdater *DTU = nullptr);
398
399/// Split the containing block at the specified instruction - everything before
400/// SplitBefore stays in the old basic block, and the rest of the instructions
401/// in the BB are moved to a new block. The two blocks are connected by a
402/// conditional branch (with value of Cmp being the condition).
403/// Before:
404/// Head
405/// SplitBefore
406/// Tail
407/// After:
408/// Head
409/// if (Cond)
410/// ThenBlock
411/// SplitBefore
412/// Tail
413///
414/// If \p ThenBlock is not specified, a new block will be created for it.
415/// If \p Unreachable is true, the newly created block will end with
416/// UnreachableInst, otherwise it branches to Tail.
417/// Returns the NewBasicBlock's terminator.
418///
419/// Updates DT and LI if given.
420///
421/// FIXME: deprecated, switch to the DomTreeUpdater-based one.
422Instruction *SplitBlockAndInsertIfThen(Value *Cond, Instruction *SplitBefore,
423 bool Unreachable, MDNode *BranchWeights,
424 DominatorTree *DT,
425 LoopInfo *LI = nullptr,
426 BasicBlock *ThenBlock = nullptr);
427
428/// Split the containing block at the specified instruction - everything before
429/// SplitBefore stays in the old basic block, and the rest of the instructions
430/// in the BB are moved to a new block. The two blocks are connected by a
431/// conditional branch (with value of Cmp being the condition).
432/// Before:
433/// Head
434/// SplitBefore
435/// Tail
436/// After:
437/// Head
438/// if (Cond)
439/// ThenBlock
440/// SplitBefore
441/// Tail
442///
443/// If \p ThenBlock is not specified, a new block will be created for it.
444/// If \p Unreachable is true, the newly created block will end with
445/// UnreachableInst, otherwise it branches to Tail.
446/// Returns the NewBasicBlock's terminator.
447///
448/// Updates DT and LI if given.
449Instruction *SplitBlockAndInsertIfThen(Value *Cond, Instruction *SplitBefore,
450 bool Unreachable,
451 MDNode *BranchWeights = nullptr,
452 DomTreeUpdater *DTU = nullptr,
453 LoopInfo *LI = nullptr,
454 BasicBlock *ThenBlock = nullptr);
455
456/// SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen,
457/// but also creates the ElseBlock.
458/// Before:
459/// Head
460/// SplitBefore
461/// Tail
462/// After:
463/// Head
464/// if (Cond)
465/// ThenBlock
466/// else
467/// ElseBlock
468/// SplitBefore
469/// Tail
470///
471/// Updates DT if given.
472void SplitBlockAndInsertIfThenElse(Value *Cond, Instruction *SplitBefore,
473 Instruction **ThenTerm,
474 Instruction **ElseTerm,
475 MDNode *BranchWeights = nullptr,
476 DomTreeUpdater *DTU = nullptr);
477
478/// Insert a for (int i = 0; i < End; i++) loop structure (with the exception
479/// that \p End is assumed > 0, and thus not checked on entry) at \p
480/// SplitBefore. Returns the first insert point in the loop body, and the
481/// PHINode for the induction variable (i.e. "i" above).
482std::pair<Instruction*, Value*>
483SplitBlockAndInsertSimpleForLoop(Value *End, Instruction *SplitBefore);
484
485/// Utility function for performing a given action on each lane of a vector
486/// with \p EC elements. To simplify porting legacy code, this defaults to
487/// unrolling the implied loop for non-scalable element counts, but this is
488/// not considered to be part of the contract of this routine, and is
489/// expected to change in the future. The callback takes as arguments an
490/// IRBuilder whose insert point is correctly set for instantiating the
491/// given index, and a value which is (at runtime) the index to access.
492/// This index *may* be a constant.
493void SplitBlockAndInsertForEachLane(ElementCount EC, Type *IndexTy,
494 Instruction *InsertBefore,
495 std::function<void(IRBuilderBase&, Value*)> Func);
496
497/// Check whether BB is the merge point of a if-region.
498/// If so, return the branch instruction that determines which entry into
499/// BB will be taken. Also, return by references the block that will be
500/// entered from if the condition is true, and the block that will be
501/// entered if the condition is false.
502///
503/// This does no checking to see if the true/false blocks have large or unsavory
504/// instructions in them.
505BranchInst *GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
506 BasicBlock *&IfFalse);
507
508// Split critical edges where the source of the edge is an indirectbr
509// instruction. This isn't always possible, but we can handle some easy cases.
510// This is useful because MI is unable to split such critical edges,
511// which means it will not be able to sink instructions along those edges.
512// This is especially painful for indirect branches with many successors, where
513// we end up having to prepare all outgoing values in the origin block.
514//
515// Our normal algorithm for splitting critical edges requires us to update
516// the outgoing edges of the edge origin block, but for an indirectbr this
517// is hard, since it would require finding and updating the block addresses
518// the indirect branch uses. But if a block only has a single indirectbr
519// predecessor, with the others being regular branches, we can do it in a
520// different way.
521// Say we have A -> D, B -> D, I -> D where only I -> D is an indirectbr.
522// We can split D into D0 and D1, where D0 contains only the PHIs from D,
523// and D1 is the D block body. We can then duplicate D0 as D0A and D0B, and
524// create the following structure:
525// A -> D0A, B -> D0A, I -> D0B, D0A -> D1, D0B -> D1
526// If BPI and BFI aren't non-null, BPI/BFI will be updated accordingly.
527// When `IgnoreBlocksWithoutPHI` is set to `true` critical edges leading to a
528// block without phi-instructions will not be split.
529bool SplitIndirectBrCriticalEdges(Function &F, bool IgnoreBlocksWithoutPHI,
530 BranchProbabilityInfo *BPI = nullptr,
531 BlockFrequencyInfo *BFI = nullptr);
532
533/// Given a set of incoming and outgoing blocks, create a "hub" such that every
534/// edge from an incoming block InBB to an outgoing block OutBB is now split
535/// into two edges, one from InBB to the hub and another from the hub to
536/// OutBB. The hub consists of a series of guard blocks, one for each outgoing
537/// block. Each guard block conditionally branches to the corresponding outgoing
538/// block, or the next guard block in the chain. These guard blocks are returned
539/// in the argument vector.
540///
541/// Since the control flow edges from InBB to OutBB have now been replaced, the
542/// function also updates any PHINodes in OutBB. For each such PHINode, the
543/// operands corresponding to incoming blocks are moved to a new PHINode in the
544/// hub, and the hub is made an operand of the original PHINode.
545///
546/// Input CFG:
547/// ----------
548///
549/// Def
550/// |
551/// v
552/// In1 In2
553/// | |
554/// | |
555/// v v
556/// Foo ---> Out1 Out2
557/// |
558/// v
559/// Use
560///
561///
562/// Create hub: Incoming = {In1, In2}, Outgoing = {Out1, Out2}
563/// ----------------------------------------------------------
564///
565/// Def
566/// |
567/// v
568/// In1 In2 Foo
569/// | Hub | |
570/// | + - - | - - + |
571/// | ' v ' V
572/// +------> Guard1 -----> Out1
573/// ' | '
574/// ' v '
575/// ' Guard2 -----> Out2
576/// ' ' |
577/// + - - - - - + |
578/// v
579/// Use
580///
581/// Limitations:
582/// -----------
583/// 1. This assumes that all terminators in the CFG are direct branches (the
584/// "br" instruction). The presence of any other control flow such as
585/// indirectbr, switch or callbr will cause an assert.
586///
587/// 2. The updates to the PHINodes are not sufficient to restore SSA
588/// form. Consider a definition Def, its use Use, incoming block In2 and
589/// outgoing block Out2, such that:
590/// a. In2 is reachable from D or contains D.
591/// b. U is reachable from Out2 or is contained in Out2.
592/// c. U is not a PHINode if U is contained in Out2.
593///
594/// Clearly, Def dominates Out2 since the program is valid SSA. But when the
595/// hub is introduced, there is a new path through the hub along which Use is
596/// reachable from entry without passing through Def, and SSA is no longer
597/// valid. To fix this, we need to look at all the blocks post-dominated by
598/// the hub on the one hand, and dominated by Out2 on the other. This is left
599/// for the caller to accomplish, since each specific use of this function
600/// may have additional information which simplifies this fixup. For example,
601/// see restoreSSA() in the UnifyLoopExits pass.
604 const SetVector<BasicBlock *> &Predecessors,
605 const SetVector<BasicBlock *> &Successors, const StringRef Prefix,
606 std::optional<unsigned> MaxControlFlowBooleans = std::nullopt);
607
608} // end namespace llvm
609
610#endif // LLVM_TRANSFORMS_UTILS_BASICBLOCKUTILS_H
SmallVector< MachineOperand, 4 > Cond
BlockVerifier::State From
static LVOptions Options
Definition: LVOptions.cpp:25
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
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"))
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file implements a set that has insertion order iteration characteristics.
LLVM Basic Block Representation.
Definition: BasicBlock.h:56
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:87
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:166
unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
BasicBlock * getSuccessor(unsigned Idx) const LLVM_READONLY
Return the specified successor. This instruction must be a terminator.
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
A vector that has set insertion semantics.
Definition: SetVector.h:51
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:577
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
void ReplaceInstWithInst(BasicBlock *BB, BasicBlock::iterator &BI, Instruction *I)
Replace the instruction specified by BI with the instruction specified by I.
bool RemoveRedundantDbgInstrs(BasicBlock *BB)
Try to remove redundant dbg.value instructions from given basic block.
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 @...
BranchInst * GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue, BasicBlock *&IfFalse)
Check whether BB is the merge point of a if-region.
void detachDeadBlocks(ArrayRef< BasicBlock * > BBs, SmallVectorImpl< DominatorTree::UpdateType > *Updates, bool KeepOneInputPHIs=false)
Replace contents of every block in BBs with single unreachable instruction.
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...
void SplitLandingPadPredecessors(BasicBlock *OrigBB, ArrayRef< BasicBlock * > Preds, const char *Suffix, const char *Suffix2, SmallVectorImpl< BasicBlock * > &NewBBs, DominatorTree *DT, 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...
BasicBlock * splitBlockBefore(BasicBlock *Old, Instruction *SplitPt, DomTreeUpdater *DTU, LoopInfo *LI, MemorySSAUpdater *MSSAU, const Twine &BBName="")
Split the specified block at the specified instruction SplitPt.
void DeleteDeadBlock(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete the specified block, which must have no predecessors.
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...
void SplitBlockAndInsertIfThenElse(Value *Cond, Instruction *SplitBefore, Instruction **ThenTerm, Instruction **ElseTerm, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr)
SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen, but also creates the ElseBlock...
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,...
bool SplitIndirectBrCriticalEdges(Function &F, bool IgnoreBlocksWithoutPHI, BranchProbabilityInfo *BPI=nullptr, BlockFrequencyInfo *BFI=nullptr)
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.
bool EliminateUnreachableBlocks(Function &F, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete all basic blocks from F that are not reachable from its entry node.
bool MergeBlockSuccessorsIntoGivenBlocks(SmallPtrSetImpl< BasicBlock * > &MergeBlocks, Loop *L=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr)
Merge block(s) sucessors, if possible.
void SplitBlockAndInsertForEachLane(ElementCount EC, Type *IndexTy, Instruction *InsertBefore, std::function< void(IRBuilderBase &, Value *)> Func)
Utility function for performing a given action on each lane of a vector with EC elements.
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.
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...
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.
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.
BasicBlock * CreateControlFlowHub(DomTreeUpdater *DTU, SmallVectorImpl< BasicBlock * > &GuardBlocks, const SetVector< BasicBlock * > &Predecessors, const SetVector< BasicBlock * > &Successors, const StringRef Prefix, std::optional< unsigned > MaxControlFlowBooleans=std::nullopt)
Given a set of incoming and outgoing blocks, create a "hub" such that every edge from an incoming blo...
std::pair< Instruction *, Value * > SplitBlockAndInsertSimpleForLoop(Value *End, Instruction *SplitBefore)
Insert a for (int i = 0; i < End; i++) loop structure (with the exception that End is assumed > 0,...
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.
bool FoldSingleEntryPHINodes(BasicBlock *BB, MemoryDependenceResults *MemDep=nullptr)
We know that BB has one predecessor.
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.
BasicBlock * SplitBlock(BasicBlock *Old, Instruction *SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="", bool Before=false)
Split the specified block at the specified instruction.
void DeleteDeadBlocks(ArrayRef< BasicBlock * > BBs, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete the specified blocks from BB.
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...
Instruction * SplitBlockAndInsertIfThen(Value *Cond, Instruction *SplitBefore, bool Unreachable, MDNode *BranchWeights, DominatorTree *DT, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
void setUnwindEdgeTo(Instruction *TI, BasicBlock *Succ)
Sets the unwind edge of an instruction to a particular successor.
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()