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