LLVM 18.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, BasicBlock::iterator SplitPt, DominatorTree *DT,
284 LoopInfo *LI = nullptr,
285 MemorySSAUpdater *MSSAU = nullptr,
286 const Twine &BBName = "", bool Before = false);
288 LoopInfo *LI = nullptr,
289 MemorySSAUpdater *MSSAU = nullptr,
290 const Twine &BBName = "", bool Before = false) {
291 return SplitBlock(Old, SplitPt->getIterator(), DT, LI, MSSAU, BBName, Before);
292}
293
294/// Split the specified block at the specified instruction.
295///
296/// If \p Before is true, splitBlockBefore handles the block
297/// splitting. Otherwise, execution proceeds as described below.
298///
299/// Everything before \p SplitPt stays in \p Old and everything starting with \p
300/// SplitPt moves to a new block. The two blocks are joined by an unconditional
301/// branch. The new block with name \p BBName is returned.
302BasicBlock *SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt,
303 DomTreeUpdater *DTU = nullptr, LoopInfo *LI = nullptr,
304 MemorySSAUpdater *MSSAU = nullptr,
305 const Twine &BBName = "", bool Before = false);
307 DomTreeUpdater *DTU = nullptr, LoopInfo *LI = nullptr,
308 MemorySSAUpdater *MSSAU = nullptr,
309 const Twine &BBName = "", bool Before = false) {
310 return SplitBlock(Old, SplitPt->getIterator(), DTU, LI, MSSAU, BBName, Before);
311}
312
313/// Split the specified block at the specified instruction \p SplitPt.
314/// All instructions before \p SplitPt are moved to a new block and all
315/// instructions after \p SplitPt stay in the old block. The new block and the
316/// old block are joined by inserting an unconditional branch to the end of the
317/// new block. The new block with name \p BBName is returned.
318BasicBlock *splitBlockBefore(BasicBlock *Old, BasicBlock::iterator SplitPt,
319 DomTreeUpdater *DTU, LoopInfo *LI,
320 MemorySSAUpdater *MSSAU, const Twine &BBName = "");
322 DomTreeUpdater *DTU, LoopInfo *LI,
323 MemorySSAUpdater *MSSAU, const Twine &BBName = "") {
324 return splitBlockBefore(Old, SplitPt->getIterator(), DTU, LI, MSSAU, BBName);
325}
326
327/// This method introduces at least one new basic block into the function and
328/// moves some of the predecessors of BB to be predecessors of the new block.
329/// The new predecessors are indicated by the Preds array. The new block is
330/// given a suffix of 'Suffix'. Returns new basic block to which predecessors
331/// from Preds are now pointing.
332///
333/// If BB is a landingpad block then additional basicblock might be introduced.
334/// It will have Suffix+".split_lp". See SplitLandingPadPredecessors for more
335/// details on this case.
336///
337/// This currently updates the LLVM IR, DominatorTree, LoopInfo, and LCCSA but
338/// no other analyses. In particular, it does not preserve LoopSimplify
339/// (because it's complicated to handle the case where one of the edges being
340/// split is an exit of a loop with other exits).
341///
342/// FIXME: deprecated, switch to the DomTreeUpdater-based one.
343BasicBlock *SplitBlockPredecessors(BasicBlock *BB, ArrayRef<BasicBlock *> Preds,
344 const char *Suffix, DominatorTree *DT,
345 LoopInfo *LI = nullptr,
346 MemorySSAUpdater *MSSAU = nullptr,
347 bool PreserveLCSSA = false);
348
349/// This method introduces at least one new basic block into the function and
350/// moves some of the predecessors of BB to be predecessors of the new block.
351/// The new predecessors are indicated by the Preds array. The new block is
352/// given a suffix of 'Suffix'. Returns new basic block to which predecessors
353/// from Preds are now pointing.
354///
355/// If BB is a landingpad block then additional basicblock might be introduced.
356/// It will have Suffix+".split_lp". See SplitLandingPadPredecessors for more
357/// details on this case.
358///
359/// This currently updates the LLVM IR, DominatorTree, LoopInfo, and LCCSA but
360/// no other analyses. In particular, it does not preserve LoopSimplify
361/// (because it's complicated to handle the case where one of the edges being
362/// split is an exit of a loop with other exits).
363BasicBlock *SplitBlockPredecessors(BasicBlock *BB, ArrayRef<BasicBlock *> Preds,
364 const char *Suffix,
365 DomTreeUpdater *DTU = nullptr,
366 LoopInfo *LI = nullptr,
367 MemorySSAUpdater *MSSAU = nullptr,
368 bool PreserveLCSSA = false);
369
370/// This method transforms the landing pad, OrigBB, by introducing two new basic
371/// blocks into the function. One of those new basic blocks gets the
372/// predecessors listed in Preds. The other basic block gets the remaining
373/// predecessors of OrigBB. The landingpad instruction OrigBB is clone into both
374/// of the new basic blocks. The new blocks are given the suffixes 'Suffix1' and
375/// 'Suffix2', and are returned in the NewBBs vector.
376///
377/// This currently updates the LLVM IR, DominatorTree, LoopInfo, and LCCSA but
378/// no other analyses. In particular, it does not preserve LoopSimplify
379/// (because it's complicated to handle the case where one of the edges being
380/// split is an exit of a loop with other exits).
381///
382/// FIXME: deprecated, switch to the DomTreeUpdater-based one.
383void SplitLandingPadPredecessors(BasicBlock *OrigBB,
384 ArrayRef<BasicBlock *> Preds,
385 const char *Suffix, const char *Suffix2,
386 SmallVectorImpl<BasicBlock *> &NewBBs,
387 DominatorTree *DT, LoopInfo *LI = nullptr,
388 MemorySSAUpdater *MSSAU = nullptr,
389 bool PreserveLCSSA = false);
390
391/// This method transforms the landing pad, OrigBB, by introducing two new basic
392/// blocks into the function. One of those new basic blocks gets the
393/// predecessors listed in Preds. The other basic block gets the remaining
394/// predecessors of OrigBB. The landingpad instruction OrigBB is clone into both
395/// of the new basic blocks. The new blocks are given the suffixes 'Suffix1' and
396/// 'Suffix2', and are returned in the NewBBs vector.
397///
398/// This currently updates the LLVM IR, DominatorTree, LoopInfo, and LCCSA but
399/// no other analyses. In particular, it does not preserve LoopSimplify
400/// (because it's complicated to handle the case where one of the edges being
401/// split is an exit of a loop with other exits).
403 BasicBlock *OrigBB, ArrayRef<BasicBlock *> Preds, const char *Suffix,
404 const char *Suffix2, SmallVectorImpl<BasicBlock *> &NewBBs,
405 DomTreeUpdater *DTU = nullptr, LoopInfo *LI = nullptr,
406 MemorySSAUpdater *MSSAU = nullptr, bool PreserveLCSSA = false);
407
408/// This method duplicates the specified return instruction into a predecessor
409/// which ends in an unconditional branch. If the return instruction returns a
410/// value defined by a PHI, propagate the right value into the return. It
411/// returns the new return instruction in the predecessor.
412ReturnInst *FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB,
413 BasicBlock *Pred,
414 DomTreeUpdater *DTU = nullptr);
415
416/// Split the containing block at the specified instruction - everything before
417/// SplitBefore stays in the old basic block, and the rest of the instructions
418/// in the BB are moved to a new block. The two blocks are connected by a
419/// conditional branch (with value of Cmp being the condition).
420/// Before:
421/// Head
422/// SplitBefore
423/// Tail
424/// After:
425/// Head
426/// if (Cond)
427/// ThenBlock
428/// SplitBefore
429/// Tail
430///
431/// If \p ThenBlock is not specified, a new block will be created for it.
432/// If \p Unreachable is true, the newly created block will end with
433/// UnreachableInst, otherwise it branches to Tail.
434/// Returns the NewBasicBlock's terminator.
435///
436/// Updates DTU and LI if given.
437Instruction *SplitBlockAndInsertIfThen(Value *Cond, BasicBlock::iterator SplitBefore,
438 bool Unreachable,
439 MDNode *BranchWeights = nullptr,
440 DomTreeUpdater *DTU = nullptr,
441 LoopInfo *LI = nullptr,
442 BasicBlock *ThenBlock = nullptr);
443
445 bool Unreachable,
446 MDNode *BranchWeights = nullptr,
447 DomTreeUpdater *DTU = nullptr,
448 LoopInfo *LI = nullptr,
449 BasicBlock *ThenBlock = nullptr) {
450 return SplitBlockAndInsertIfThen(Cond, SplitBefore->getIterator(),
451 Unreachable, BranchWeights, DTU, LI,
452 ThenBlock);
453}
454
455/// Similar to SplitBlockAndInsertIfThen, but the inserted block is on the false
456/// path of the branch.
457Instruction *SplitBlockAndInsertIfElse(Value *Cond, BasicBlock::iterator SplitBefore,
458 bool Unreachable,
459 MDNode *BranchWeights = nullptr,
460 DomTreeUpdater *DTU = nullptr,
461 LoopInfo *LI = nullptr,
462 BasicBlock *ElseBlock = nullptr);
463
465 bool Unreachable,
466 MDNode *BranchWeights = nullptr,
467 DomTreeUpdater *DTU = nullptr,
468 LoopInfo *LI = nullptr,
469 BasicBlock *ElseBlock = nullptr) {
470 return SplitBlockAndInsertIfElse(Cond, SplitBefore->getIterator(),
471 Unreachable, BranchWeights, DTU, LI,
472 ElseBlock);
473}
474
475/// SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen,
476/// but also creates the ElseBlock.
477/// Before:
478/// Head
479/// SplitBefore
480/// Tail
481/// After:
482/// Head
483/// if (Cond)
484/// ThenBlock
485/// else
486/// ElseBlock
487/// SplitBefore
488/// Tail
489///
490/// Updates DT if given.
492 BasicBlock::iterator SplitBefore,
493 Instruction **ThenTerm,
494 Instruction **ElseTerm,
495 MDNode *BranchWeights = nullptr,
496 DomTreeUpdater *DTU = nullptr,
497 LoopInfo *LI = nullptr);
498
500 Instruction **ThenTerm,
501 Instruction **ElseTerm,
502 MDNode *BranchWeights = nullptr,
503 DomTreeUpdater *DTU = nullptr,
504 LoopInfo *LI = nullptr)
505{
506 SplitBlockAndInsertIfThenElse(Cond, SplitBefore->getIterator(), ThenTerm,
507 ElseTerm, BranchWeights, DTU, LI);
508}
509
510/// Split the containing block at the specified instruction - everything before
511/// SplitBefore stays in the old basic block, and the rest of the instructions
512/// in the BB are moved to a new block. The two blocks are connected by a
513/// conditional branch (with value of Cmp being the condition).
514/// Before:
515/// Head
516/// SplitBefore
517/// Tail
518/// After:
519/// Head
520/// if (Cond)
521/// TrueBlock
522/// else
523//// FalseBlock
524/// SplitBefore
525/// Tail
526///
527/// If \p ThenBlock is null, the resulting CFG won't contain the TrueBlock. If
528/// \p ThenBlock is non-null and points to non-null BasicBlock pointer, that
529/// block will be inserted as the TrueBlock. Otherwise a new block will be
530/// created. Likewise for the \p ElseBlock parameter.
531/// If \p UnreachableThen or \p UnreachableElse is true, the corresponding newly
532/// created blocks will end with UnreachableInst, otherwise with branches to
533/// Tail. The function will not modify existing basic blocks passed to it. The
534/// caller must ensure that Tail is reachable from Head.
535/// Returns the newly created blocks in \p ThenBlock and \p ElseBlock.
536/// Updates DTU and LI if given.
538 BasicBlock::iterator SplitBefore,
539 BasicBlock **ThenBlock,
540 BasicBlock **ElseBlock,
541 bool UnreachableThen = false,
542 bool UnreachableElse = false,
543 MDNode *BranchWeights = nullptr,
544 DomTreeUpdater *DTU = nullptr,
545 LoopInfo *LI = nullptr);
546
548 BasicBlock **ThenBlock,
549 BasicBlock **ElseBlock,
550 bool UnreachableThen = false,
551 bool UnreachableElse = false,
552 MDNode *BranchWeights = nullptr,
553 DomTreeUpdater *DTU = nullptr,
554 LoopInfo *LI = nullptr) {
555 SplitBlockAndInsertIfThenElse(Cond, SplitBefore->getIterator(), ThenBlock,
556 ElseBlock, UnreachableThen, UnreachableElse, BranchWeights, DTU, LI);
557}
558
559/// Insert a for (int i = 0; i < End; i++) loop structure (with the exception
560/// that \p End is assumed > 0, and thus not checked on entry) at \p
561/// SplitBefore. Returns the first insert point in the loop body, and the
562/// PHINode for the induction variable (i.e. "i" above).
563std::pair<Instruction*, Value*>
564SplitBlockAndInsertSimpleForLoop(Value *End, Instruction *SplitBefore);
565
566/// Utility function for performing a given action on each lane of a vector
567/// with \p EC elements. To simplify porting legacy code, this defaults to
568/// unrolling the implied loop for non-scalable element counts, but this is
569/// not considered to be part of the contract of this routine, and is
570/// expected to change in the future. The callback takes as arguments an
571/// IRBuilder whose insert point is correctly set for instantiating the
572/// given index, and a value which is (at runtime) the index to access.
573/// This index *may* be a constant.
574void SplitBlockAndInsertForEachLane(ElementCount EC, Type *IndexTy,
575 Instruction *InsertBefore,
576 std::function<void(IRBuilderBase&, Value*)> Func);
577
578/// Utility function for performing a given action on each lane of a vector
579/// with \p EVL effective length. EVL is assumed > 0. To simplify porting legacy
580/// code, this defaults to unrolling the implied loop for non-scalable element
581/// counts, but this is not considered to be part of the contract of this
582/// routine, and is expected to change in the future. The callback takes as
583/// arguments an IRBuilder whose insert point is correctly set for instantiating
584/// the given index, and a value which is (at runtime) the index to access. This
585/// index *may* be a constant.
587 Value *End, Instruction *InsertBefore,
588 std::function<void(IRBuilderBase &, Value *)> Func);
589
590/// Check whether BB is the merge point of a if-region.
591/// If so, return the branch instruction that determines which entry into
592/// BB will be taken. Also, return by references the block that will be
593/// entered from if the condition is true, and the block that will be
594/// entered if the condition is false.
595///
596/// This does no checking to see if the true/false blocks have large or unsavory
597/// instructions in them.
598BranchInst *GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
599 BasicBlock *&IfFalse);
600
601// Split critical edges where the source of the edge is an indirectbr
602// instruction. This isn't always possible, but we can handle some easy cases.
603// This is useful because MI is unable to split such critical edges,
604// which means it will not be able to sink instructions along those edges.
605// This is especially painful for indirect branches with many successors, where
606// we end up having to prepare all outgoing values in the origin block.
607//
608// Our normal algorithm for splitting critical edges requires us to update
609// the outgoing edges of the edge origin block, but for an indirectbr this
610// is hard, since it would require finding and updating the block addresses
611// the indirect branch uses. But if a block only has a single indirectbr
612// predecessor, with the others being regular branches, we can do it in a
613// different way.
614// Say we have A -> D, B -> D, I -> D where only I -> D is an indirectbr.
615// We can split D into D0 and D1, where D0 contains only the PHIs from D,
616// and D1 is the D block body. We can then duplicate D0 as D0A and D0B, and
617// create the following structure:
618// A -> D0A, B -> D0A, I -> D0B, D0A -> D1, D0B -> D1
619// If BPI and BFI aren't non-null, BPI/BFI will be updated accordingly.
620// When `IgnoreBlocksWithoutPHI` is set to `true` critical edges leading to a
621// block without phi-instructions will not be split.
622bool SplitIndirectBrCriticalEdges(Function &F, bool IgnoreBlocksWithoutPHI,
623 BranchProbabilityInfo *BPI = nullptr,
624 BlockFrequencyInfo *BFI = nullptr);
625
626/// Given a set of incoming and outgoing blocks, create a "hub" such that every
627/// edge from an incoming block InBB to an outgoing block OutBB is now split
628/// into two edges, one from InBB to the hub and another from the hub to
629/// OutBB. The hub consists of a series of guard blocks, one for each outgoing
630/// block. Each guard block conditionally branches to the corresponding outgoing
631/// block, or the next guard block in the chain. These guard blocks are returned
632/// in the argument vector.
633///
634/// Since the control flow edges from InBB to OutBB have now been replaced, the
635/// function also updates any PHINodes in OutBB. For each such PHINode, the
636/// operands corresponding to incoming blocks are moved to a new PHINode in the
637/// hub, and the hub is made an operand of the original PHINode.
638///
639/// Input CFG:
640/// ----------
641///
642/// Def
643/// |
644/// v
645/// In1 In2
646/// | |
647/// | |
648/// v v
649/// Foo ---> Out1 Out2
650/// |
651/// v
652/// Use
653///
654///
655/// Create hub: Incoming = {In1, In2}, Outgoing = {Out1, Out2}
656/// ----------------------------------------------------------
657///
658/// Def
659/// |
660/// v
661/// In1 In2 Foo
662/// | Hub | |
663/// | + - - | - - + |
664/// | ' v ' V
665/// +------> Guard1 -----> Out1
666/// ' | '
667/// ' v '
668/// ' Guard2 -----> Out2
669/// ' ' |
670/// + - - - - - + |
671/// v
672/// Use
673///
674/// Limitations:
675/// -----------
676/// 1. This assumes that all terminators in the CFG are direct branches (the
677/// "br" instruction). The presence of any other control flow such as
678/// indirectbr, switch or callbr will cause an assert.
679///
680/// 2. The updates to the PHINodes are not sufficient to restore SSA
681/// form. Consider a definition Def, its use Use, incoming block In2 and
682/// outgoing block Out2, such that:
683/// a. In2 is reachable from D or contains D.
684/// b. U is reachable from Out2 or is contained in Out2.
685/// c. U is not a PHINode if U is contained in Out2.
686///
687/// Clearly, Def dominates Out2 since the program is valid SSA. But when the
688/// hub is introduced, there is a new path through the hub along which Use is
689/// reachable from entry without passing through Def, and SSA is no longer
690/// valid. To fix this, we need to look at all the blocks post-dominated by
691/// the hub on the one hand, and dominated by Out2 on the other. This is left
692/// for the caller to accomplish, since each specific use of this function
693/// may have additional information which simplifies this fixup. For example,
694/// see restoreSSA() in the UnifyLoopExits pass.
697 const SetVector<BasicBlock *> &Predecessors,
698 const SetVector<BasicBlock *> &Successors, const StringRef Prefix,
699 std::optional<unsigned> MaxControlFlowBooleans = std::nullopt);
700
701// Utility function for inverting branch condition and for swapping its
702// successors
703void InvertBranch(BranchInst *PBI, IRBuilderBase &Builder);
704
705// Check whether the function only has simple terminator:
706// br/brcond/unreachable/ret
708} // end namespace llvm
709
710#endif // LLVM_TRANSFORMS_UTILS_BASICBLOCKUTILS_H
BlockVerifier::State From
bool End
Definition: ELF_riscv.cpp:478
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"))
const SmallVectorImpl< MachineOperand > & Cond
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:60
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:165
Conditional or Unconditional Branch instruction.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:165
Common base class shared among various IRBuilders.
Definition: IRBuilder.h:94
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.
Metadata node.
Definition: Metadata.h:1037
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
A vector that has set insertion semantics.
Definition: SetVector.h:57
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
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
LLVM Value Representation.
Definition: Value.h:74
self_iterator getIterator()
Definition: ilist_node.h:109
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.
bool hasOnlySimpleTerminator(const Function &F)
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...
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.
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.
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...
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...
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.
void InvertBranch(BranchInst *PBI, IRBuilderBase &Builder)
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 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...
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, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="", bool Before=false)
Split the specified block at the specified instruction.
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 ...
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...
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()