54#define DEBUG_TYPE "basicblock-utils"
58 cl::desc(
"Set the maximum path length when checking whether a basic block "
59 "is followed by a block that either has a terminating "
60 "deoptimizing call or is terminated with an unreachable"));
68 bool KeepOneInputPHIs) {
73 Succ->removePredecessor(BB, KeepOneInputPHIs);
74 if (Updates && UniqueSuccessors.
insert(Succ).second)
79 while (!BB->
empty()) {
92 "The successor list of BB isn't empty before "
93 "applying corresponding DTU updates.");
107 bool KeepOneInputPHIs) {
109 for (
auto *BB : BBs) {
110 auto NonFirstPhiIt = BB->getFirstNonPHIIt();
111 if (NonFirstPhiIt != BB->end()) {
120 UniqueEHRetBlocksToDelete.
clear();
129 UniqueEHRetBlocksToDelete.
insert(ReturnInstrBB);
133 for (
BasicBlock *EHRetBB : UniqueEHRetBlocksToDelete)
138 UniqueEHRetBlocksToDelete.
clear();
146 bool KeepOneInputPHIs) {
151 bool KeepOneInputPHIs) {
156 for (
auto *BB :
Dead)
158 assert(
Dead.count(Pred) &&
"All predecessors must be dead!");
171 BB->eraseFromParent();
175 bool KeepOneInputPHIs) {
183 std::vector<BasicBlock*> DeadBlocks;
185 if (!Reachable.count(&BB))
186 DeadBlocks.push_back(&BB);
191 return !DeadBlocks.empty();
200 if (PN->getIncomingValue(0) != PN)
201 PN->replaceAllUsesWith(PN->getIncomingValue(0));
208 PN->eraseFromParent();
221 if (!KnownNonDeadPHIs)
222 KnownNonDeadPHIs = &LocalKnownNonDeadPHIs;
225 for (
const auto &
PHI : PHIs) {
229 if (PHIChanged && KnownNonDeadPHIs)
230 KnownNonDeadPHIs->
clear();
239 bool PredecessorWithTwoSuccessors,
246 if (!PredBB)
return false;
249 if (PredBB == BB)
return false;
264 unsigned FallThruPath;
265 if (PredecessorWithTwoSuccessors) {
272 FallThruPath = PredBB_BI->
getSuccessor(0) == BB ? 0 : 1;
295 assert(!DTU &&
"cannot use both DT and DTU for updates");
299 assert(BBNode &&
"PredNode unreachable but BBNode reachable?");
301 C->setIDom(PredNode);
306 std::vector<DominatorTree::UpdateType> Updates;
308 assert(!DT &&
"cannot use both DT and DTU for updates");
313 Updates.reserve(Updates.size() + 2 *
succ_size(BB) + 1);
322 if (!SuccsOfPredBB.
contains(SuccOfBB))
323 if (SeenSuccs.
insert(SuccOfBB).second)
327 if (SeenSuccs.
insert(SuccOfBB).second)
349 if (PredecessorWithTwoSuccessors) {
388 "successors should have been transferred to PredBB");
401 assert(!MergeBlocks.
empty() &&
"MergeBlocks should not be empty");
403 bool BlocksHaveBeenMerged =
false;
404 while (!MergeBlocks.
empty()) {
407 if (Dest && (!L || L->contains(Dest))) {
412 "Expecting BB to be unique predecessor of the Dest block");
413 MergeBlocks.
erase(Dest);
414 BlocksHaveBeenMerged =
true;
416 MergeBlocks.
erase(BB);
418 MergeBlocks.
erase(BB);
420 return BlocksHaveBeenMerged;
449 DVR.getDebugLoc()->getInlinedAt());
457 if (DVR.isDbgAssign()) {
472 for (
auto &DVR : ToBeRemoved)
473 DVR->eraseFromParent();
475 return !ToBeRemoved.
empty();
498 bool RemovedAny =
false;
502 for (
auto &
I : *BB) {
508 DVR.getDebugLoc()->getInlinedAt());
512 bool IsDbgValueKind =
518 if (Inserted || VMI->second.first !=
Values ||
519 VMI->second.second != DVR.getExpression()) {
521 VMI->second = {
Values, DVR.getExpression()};
523 VMI->second = {
Values,
nullptr};
530 DVR.eraseFromParent();
559 bool RemovedAny =
false;
564 for (
auto &
I : *BB) {
567 if (!DVR.isDbgValue() && !DVR.isDbgAssign())
569 bool IsDbgValueKind =
573 if (!SeenDefForAggregate.
contains(Aggregate)) {
574 bool IsKill = DVR.isKillLocation() && IsDbgValueKind;
576 SeenDefForAggregate.
insert(Aggregate);
577 }
else if (DVR.isDbgAssign()) {
578 DVR.eraseFromParent();
589 bool MadeChanges =
false;
616 I.replaceAllUsesWith(V);
619 if (
I.hasName() && !V->hasName())
623 BI = BI->eraseFromParent();
628 assert(
I->getParent() ==
nullptr &&
629 "ReplaceInstWithInst: Instruction already inserted into basic block!");
633 if (!
I->getDebugLoc())
634 I->setDebugLoc(BI->getDebugLoc());
667 const Twine &BBName) {
685 assert(SP == BB &&
"CFG broken");
694 "Should have a single succ!");
706template <
typename TI,
typename T>
709 static_assert(std::is_same_v<TI, CycleInfo> || std::is_same_v<TI, LoopInfo>,
710 "type must be CycleInfo or LoopInfo");
714 if constexpr (std::is_same_v<TI, CycleInfo>) {
715 T LC = LCI->getSmallestCommonCycle(MultiBrBlock, Succ);
718 LCI->addBlockToCycle(BrTarget, LC);
720 T *LC = LCI->getSmallestCommonLoop(MultiBrBlock, Succ);
723 LC->addBasicBlockToLoop(BrTarget, *LCI);
736 "expected callbr or switch terminator");
737 assert(SuccIdx < Term->getNumSuccessors() &&
738 Succ == Term->getSuccessor(SuccIdx) &&
"invalid successor index");
743 bool ReusesBrTarget = BrTarget;
751 if (!ReusesBrTarget) {
753 MultiBrBlock->
getName() +
".target." +
762 int BBIdx = PN.getBasicBlockIndex(MultiBrBlock);
763 assert(BBIdx != -1 &&
"expected incoming value from MultiBrBlock");
764 PN.setIncomingBlock(BBIdx, BrTarget);
770 *UpdatedLI = Updated;
774 PN.removeIncomingValue(MultiBrBlock,
false);
778 Term->setSuccessor(SuccIdx, BrTarget);
796 II->setUnwindDest(Succ);
798 CS->setUnwindDest(Succ);
800 CR->setUnwindDest(Succ);
819 if (PN.getIncomingBlock(BBIdx) != OldPred)
820 BBIdx = PN.getBasicBlockIndex(OldPred);
822 assert(BBIdx != -1 &&
"Invalid PHI Index!");
823 PN.setIncomingBlock(BBIdx, NewPred);
829 PHINode *LandingPadReplacement,
831 const Twine &BBName) {
834 if (!LandingPadReplacement && !PadInst->
isEHPad())
842 if (
Options.PreserveLoopSimplify && LI) {
843 if (
Loop *BBLoop = LI->getLoopFor(BB)) {
857 if (LI->getLoopFor(
P) != BBLoop) {
880 if (LandingPadReplacement) {
881 auto *NewLP = OriginalPad->
clone();
883 NewLP->insertBefore(Terminator->getIterator());
886 Value *ParentPad =
nullptr;
888 ParentPad = FuncletPad->getParentPad();
890 ParentPad = CatchSwitch->getParentPad();
892 ParentPad = CleanupPad->getParentPad();
894 ParentPad = LandingPad->getParent();
919 MSSAU->applyUpdates(Updates, *DT);
921 MSSAU->getMemorySSA()->verifyMemorySSA();
926 if (
Loop *BBLoop = LI->getLoopFor(BB)) {
929 if (
Loop *SuccLoop = LI->getLoopFor(Succ)) {
930 if (BBLoop == SuccLoop) {
932 SuccLoop->addBasicBlockToLoop(NewBB, *LI);
933 }
else if (BBLoop->contains(SuccLoop)) {
935 BBLoop->addBasicBlockToLoop(NewBB, *LI);
936 }
else if (SuccLoop->contains(BBLoop)) {
938 SuccLoop->addBasicBlockToLoop(NewBB, *LI);
944 assert(SuccLoop->getHeader() == Succ &&
945 "Should not create irreducible loops!");
946 if (
Loop *
P = SuccLoop->getParentLoop())
947 P->addBasicBlockToLoop(NewBB, *LI);
953 if (!BBLoop->contains(Succ)) {
954 assert(!BBLoop->contains(NewBB) &&
955 "Split point for loop exit is contained in loop!");
962 if (!LoopPreds.
empty()) {
964 Succ, LoopPreds,
"split", DT, LI, MSSAU,
Options.PreserveLCSSA);
980 "SplitBB has non-PHI nodes!");
984 int Idx = PN.getBasicBlockIndex(SplitBB);
985 assert(Idx >= 0 &&
"Invalid Block Index");
986 Value *V = PN.getIncomingValue(Idx);
991 if (VP->getParent() == SplitBB)
1004 PN.setIncomingValue(Idx, NewPN);
1011 unsigned NumBroken = 0;
1025 const Twine &BBName) {
1029 assert(SplitIt != SplitPt->getParent()->end());
1031 std::string Name = BBName.
str();
1033 SplitIt, Name.empty() ? Old->
getName() +
".split" : Name);
1039 L->addBasicBlockToLoop(New, *LI);
1048 if (UniqueSuccessorsOfOld.
insert(SuccessorOfOld).second) {
1057 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
1075 return SplitBlockImpl(Old, SplitPt,
nullptr, DT, LI, MSSAU, BBName);
1080 return SplitBlockImpl(Old, SplitPt, DTU,
nullptr, LI, MSSAU, BBName);
1098 bool PreserveLCSSA,
bool &HasLoopExit) {
1114 for (
auto *
Pred : Preds)
1141 assert(DT &&
"DT should be available to update LoopInfo!");
1146 bool IsLoopEntry = !!L;
1147 bool SplitMakesNewLoopHeader =
false;
1159 if (!PL->contains(OldBB))
1166 if (L->contains(
Pred))
1167 IsLoopEntry =
false;
1169 SplitMakesNewLoopHeader =
true;
1181 Loop *InnermostPredLoop =
nullptr;
1186 while (PredLoop && !PredLoop->contains(OldBB))
1187 PredLoop = PredLoop->getParentLoop();
1190 if (PredLoop && PredLoop->contains(OldBB) &&
1191 (!InnermostPredLoop ||
1192 InnermostPredLoop->
getLoopDepth() < PredLoop->getLoopDepth()))
1193 InnermostPredLoop = PredLoop;
1197 if (InnermostPredLoop)
1200 L->addBasicBlockToLoop(NewBB, *LI);
1201 if (SplitMakesNewLoopHeader) {
1208 L->moveToHeader(NewBB);
1217 const Twine &BBName) {
1225 bool HasLoopExit =
false;
1244 Value *InVal =
nullptr;
1287 if (
PredSet.count(IncomingBB)) {
1316 std::string NewName = std::string(Suffix) +
".split-lp";
1319 DTU, DT, LI, MSSAU, PreserveLCSSA);
1343 OldLatch = L->getLoopLatch();
1353 "Cannot split an edge from an IndirectBrInst");
1354 Pred->getTerminator()->replaceSuccessorWith(BB, NewBB);
1361 if (Preds.
empty()) {
1368 bool HasLoopExit =
false;
1372 if (!Preds.
empty()) {
1379 if (NewLatch != OldLatch) {
1397 bool PreserveLCSSA) {
1399 MSSAU, PreserveLCSSA);
1406 bool PreserveLCSSA) {
1408 nullptr, LI, MSSAU, PreserveLCSSA);
1435 "Cannot split an edge from an IndirectBrInst");
1436 Pred->getTerminator()->replaceUsesOfWith(OrigBB, NewBB1);
1439 bool HasLoopExit =
false;
1441 PreserveLCSSA, HasLoopExit);
1451 if (
Pred == NewBB1)
continue;
1453 "Cannot split an edge from an IndirectBrInst");
1459 if (!NewBB2Preds.
empty()) {
1472 NewBB2Pred->getTerminator()->replaceUsesOfWith(OrigBB, NewBB2);
1475 HasLoopExit =
false;
1477 PreserveLCSSA, HasLoopExit);
1497 "Split cannot be applied if LPad is token type. Otherwise an "
1498 "invalid PHINode of token type would be created.");
1515 const char *Suffix1,
const char *Suffix2,
1519 bool PreserveLCSSA) {
1521 NewBBs, DTU,
nullptr, LI, MSSAU,
1528 Instruction *UncondBranch = Pred->getTerminator();
1541 V = BCI->getOperand(0);
1542 NewBC = BCI->
clone();
1549 V = EVI->getOperand(0);
1550 NewEV = EVI->
clone();
1561 if (PN->getParent() == BB) {
1563 NewEV->
setOperand(0, PN->getIncomingValueForBlock(Pred));
1565 NewBC->
setOperand(0, PN->getIncomingValueForBlock(Pred));
1567 Op = PN->getIncomingValueForBlock(Pred);
1590 Cond, SplitBefore, &ThenBlock,
nullptr,
1592 false, BranchWeights, DTU, LI);
1603 Cond, SplitBefore,
nullptr, &ElseBlock,
1605 Unreachable, BranchWeights, DTU, LI);
1617 Cond, SplitBefore, &ThenBlock, &ElseBlock,
false,
1618 false, BranchWeights, DTU, LI);
1626 BasicBlock **ElseBlock,
bool UnreachableThen,
bool UnreachableElse,
1628 assert((ThenBlock || ElseBlock) &&
1629 "At least one branch block must be created");
1630 assert((!UnreachableThen || !UnreachableElse) &&
1631 "Split block tail must be reachable");
1638 Updates.
reserve(4 + 2 * UniqueOrigSuccessors.
size());
1645 bool ThenToTailEdge =
false;
1646 bool ElseToTailEdge =
false;
1665 BB->getTerminator()->
setDebugLoc(SplitBefore->getDebugLoc());
1671 handleBlock(ThenBlock, UnreachableThen, TrueBlock, ThenToTailEdge);
1672 handleBlock(ElseBlock, UnreachableElse, FalseBlock, ElseToTailEdge);
1676 HeadNewTerm->
setMetadata(LLVMContext::MD_prof, BranchWeights);
1686 for (
BasicBlock *UniqueOrigSuccessor : UniqueOrigSuccessors)
1688 for (
BasicBlock *UniqueOrigSuccessor : UniqueOrigSuccessors)
1696 L->addBasicBlockToLoop(TrueBlock, *LI);
1698 L->addBasicBlockToLoop(FalseBlock, *LI);
1699 L->addBasicBlockToLoop(Tail, *LI);
1704std::pair<Instruction *, Value *>
1711 auto *Ty =
End->getType();
1712 auto &
DL = SplitBefore->getDataLayout();
1713 const unsigned Bitwidth =
DL.getTypeSizeInBits(Ty);
1716 auto *
IV = Builder.CreatePHI(Ty, 2,
"iv");
1718 Builder.CreateAdd(
IV, ConstantInt::get(Ty, 1),
IV->getName() +
".next",
1719 true, Bitwidth != 2);
1720 auto *IVCheck = Builder.CreateICmpEQ(IVNext,
End,
1721 IV->getName() +
".check");
1722 Builder.CreateCondBr(IVCheck, LoopExit, LoopBody);
1726 IV->addIncoming(ConstantInt::get(Ty, 0), LoopPred);
1727 IV->addIncoming(IVNext, LoopBody);
1748 for (
unsigned Idx = 0; Idx < Num; ++Idx) {
1750 Func(IRB, ConstantInt::get(Ty, Idx));
1808 if (Pred1Br->getSuccessor(0) == BB &&
1809 Pred1Br->getSuccessor(1) == Pred2) {
1812 }
else if (Pred1Br->getSuccessor(0) == Pred2 &&
1813 Pred1Br->getSuccessor(1) == BB) {
1837 if (!BI)
return nullptr;
1857 NewCond = Builder.CreateNot(NewCond, NewCond->
getName() +
".not");
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static BasicBlock * SplitBlockPredecessorsImpl(BasicBlock *BB, ArrayRef< BasicBlock * > Preds, const char *Suffix, DomTreeUpdater *DTU, DominatorTree *DT, LoopInfo *LI, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
static bool removeRedundantDbgInstrsUsingBackwardScan(BasicBlock *BB)
Remove redundant instructions within sequences of consecutive dbg.value instructions.
static bool updateCycleLoopInfo(TI *LCI, BasicBlock *MultiBrBlock, BasicBlock *BrTarget, BasicBlock *Succ)
Helper function to update the cycle or loop information after inserting a new block between a callbr ...
static bool removeUndefDbgAssignsFromEntryBlock(BasicBlock *BB)
Remove redundant undef dbg.assign intrinsic from an entry block using a forward scan.
static void UpdateAnalysisInformation(BasicBlock *OldBB, BasicBlock *NewBB, ArrayRef< BasicBlock * > Preds, DomTreeUpdater *DTU, DominatorTree *DT, LoopInfo *LI, MemorySSAUpdater *MSSAU, bool PreserveLCSSA, bool &HasLoopExit)
Update DominatorTree, LoopInfo, and LCCSA analysis information.
static BasicBlock * SplitBlockImpl(BasicBlock *Old, BasicBlock::iterator SplitPt, DomTreeUpdater *DTU, DominatorTree *DT, LoopInfo *LI, MemorySSAUpdater *MSSAU, const Twine &BBName)
static bool removeRedundantDbgInstrsUsingForwardScan(BasicBlock *BB)
Remove redundant dbg.value instructions using a forward scan.
static void SplitLandingPadPredecessorsImpl(BasicBlock *OrigBB, ArrayRef< BasicBlock * > Preds, const char *Suffix1, const char *Suffix2, SmallVectorImpl< BasicBlock * > &NewBBs, DomTreeUpdater *DTU, DominatorTree *DT, LoopInfo *LI, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
static cl::opt< unsigned > MaxDeoptOrUnreachableSuccessorCheckDepth("max-deopt-or-unreachable-succ-check-depth", cl::init(8), cl::Hidden, cl::desc("Set the maximum path length when checking whether a basic block " "is followed by a block that either has a terminating " "deoptimizing call or is terminated with an unreachable"))
static void emptyAndDetachBlock(BasicBlock *BB, SmallVectorImpl< DominatorTree::UpdateType > *Updates, bool KeepOneInputPHIs)
Zap all the instructions in the block and replace them with an unreachable instruction and notify the...
static void UpdatePHINodes(BasicBlock *OrigBB, BasicBlock *NewBB, ArrayRef< BasicBlock * > Preds, Instruction *BI, bool HasLoopExit)
Update the PHI nodes in OrigBB to include the values coming from NewBB.
static bool hasReachableLoopEntryToHeader(const Loop &L, const DominatorTree &DT)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file declares the LLVM IR specialization of the GenericCycle templates.
SmallPtrSet< const BasicBlock *, 8 > VisitedBlocks
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
SmallVector< MachineOperand, 4 > Cond
uint64_t IntrinsicInst * II
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
static const uint32_t IV[8]
Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
Get the array size.
bool empty() const
Check if the array is empty.
LLVM Basic Block Representation.
iterator begin()
Instruction iterator methods.
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
LLVM_ABI const LandingPadInst * getLandingPadInst() const
Return the landingpad instruction associated with the landing pad.
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
LLVM_ABI BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
const Function * getParent() const
Return the enclosing method, or null if none.
const Instruction & back() const
LLVM_ABI BasicBlock * splitBasicBlockBefore(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction and insert the new basic blo...
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches,...
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
LLVM_ABI bool isEntryBlock() const
Return true if this is the entry block of the containing function.
LLVM_ABI const BasicBlock * getUniqueSuccessor() const
Return the successor of this block if it has a unique successor.
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
const Instruction & front() const
LLVM_ABI const CallInst * getTerminatingDeoptimizeCall() const
Returns the call instruction calling @llvm.experimental.deoptimize prior to the terminating return in...
LLVM_ABI const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
LLVM_ABI const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
LLVM_ABI InstListType::const_iterator getFirstNonPHIOrPseudoProbe() const
Returns an iterator to the first instruction in this block that is not a PHINode or a pseudo operatio...
InstListType::iterator iterator
Instruction iterators...
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
LLVM_ABI bool isLandingPad() const
Return true if this basic block is a landing pad.
LLVM_ABI bool canSplitPredecessors() const
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
void splice(BasicBlock::iterator ToIt, BasicBlock *FromBB)
Transfer all instructions from FromBB to this basic block at ToIt.
LLVM_ABI void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs=false)
Update PHI nodes in this BasicBlock before removal of predecessor Pred.
This class represents a no-op cast from one type to another.
static CleanupPadInst * Create(Value *ParentPad, ArrayRef< Value * > Args={}, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupReturnInst * Create(Value *CleanupPad, BasicBlock *UnwindBB=nullptr, InsertPosition InsertBefore=nullptr)
This class is the base class for the comparison instructions.
void setPredicate(Predicate P)
Set the predicate for this instruction to the specified value.
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Conditional Branch instruction.
LLVM_ABI void swapSuccessors()
Swap the successors of this branch instruction.
static CondBrInst * Create(Value *Cond, BasicBlock *IfTrue, BasicBlock *IfFalse, InsertPosition InsertBefore=nullptr)
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
void setCondition(Value *V)
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
Represents calls to the llvm.experimintal.convergence.* intrinsics.
Record of a variable value-assignment, aka a non instruction representation of the dbg....
Identifies a unique instance of a whole variable (discards/ignores fragment information).
Identifies a unique instance of a variable.
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Implements a dense probed hash-table based set.
iterator_range< iterator > children()
LLVM_ABI void deleteBB(BasicBlock *DelBB)
Delete DelBB.
DomTreeNodeBase< NodeT > * getRootNode()
getRootNode - This returns the entry node for the CFG of the function.
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
Add a new node to the dominator tree information.
void splitBlock(NodeT *NewBB)
splitBlock - BB is split and now it has one successor.
static constexpr UpdateKind Delete
DomTreeNodeBase< NodeT > * setNewRoot(NodeT *BB)
Add a new node to the forward dominator tree and make it a new root.
static constexpr UpdateKind Insert
void eraseNode(NodeT *BB)
eraseNode - Removes a node from the dominator tree.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
LLVM_ABI bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
DomTreeT & getDomTree()
Flush DomTree updates and return DomTree.
void applyUpdates(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
void flush()
Apply all pending updates to available trees and flush all BasicBlocks awaiting deletion.
bool hasDomTree() const
Returns true if it holds a DomTreeT.
void recalculate(FuncT &F)
Notify DTU that the entry block was replaced.
Module * getParent()
Get the module that this global value is contained inside of...
Common base class shared among various IRBuilders.
void disableGEPCanonicalization()
Disable canonicalization of getelementptr instructions to ptradd form.
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
LLVM_ABI Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
bool isEHPad() const
Return true if the instruction is a variety of EH-block.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
LLVM_ABI bool mayHaveSideEffects() const LLVM_READONLY
Return true if the instruction may have side effects.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
LLVM_ABI void moveBeforePreserving(InstListType::iterator MovePos)
Perform a moveBefore operation, while signalling that the caller intends to preserve the original ord...
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
bool isSpecialTerminator() const
LLVM_ABI InstListType::iterator insertInto(BasicBlock *ParentBB, InstListType::iterator It)
Inserts an unlinked instruction into ParentBB at position It and returns the iterator of the inserted...
This is an important class for using LLVM in a threaded context.
The landingpad instruction holds all of the information necessary to generate correct exception handl...
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
unsigned getLoopDepth() const
Return the nesting level of this loop.
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
void removeBlock(BlockT *BB)
This method completely removes BB from all data structures, including all of the Loop objects it is n...
bool isLoopHeader(const BlockT *BB) const
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
LLVM_ABI void erase(Loop *L)
Update LoopInfo after removing the last backedge from a loop.
Represents a single loop in the control flow graph.
Provides a lazy, caching interface for making common memory aliasing information queries,...
LLVM_ABI void invalidateCachedPredecessors()
Clears the PredIteratorCache info.
LLVM_ABI void removeInstruction(Instruction *InstToRemove)
Removes an instruction from the dependence analysis, updating the dependence of instructions that pre...
MemorySSA * getMemorySSA() const
Get handle on MemorySSA.
LLVM_ABI void moveAllAfterSpliceBlocks(BasicBlock *From, BasicBlock *To, Instruction *Start)
From block was spliced into From and To.
LLVM_ABI void moveAllAfterMergeBlocks(BasicBlock *From, BasicBlock *To, Instruction *Start)
From block was merged into To.
LLVM_ABI void moveToPlace(MemoryUseOrDef *What, BasicBlock *BB, MemorySSA::InsertionPlace Where)
LLVM_ABI void wireOldPredecessorsToNewImmediatePredecessor(BasicBlock *Old, BasicBlock *New, ArrayRef< BasicBlock * > Preds, bool IdenticalEdgesWereMerged=true)
A new empty BasicBlock (New) now branches directly to Old.
MemoryUseOrDef * getMemoryAccess(const Instruction *I) const
Given a memory Mod/Ref'ing instruction, get the MemorySSA access associated with it.
Class that has the common methods + fields of memory uses/defs.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
LLVM_ABI void removeIncomingValueIf(function_ref< bool(unsigned)> Predicate, bool DeletePHIIfEmpty=true)
Remove all incoming values for which the predicate returns true.
LLVM_ABI Value * removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty=true)
Remove an incoming value.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Simple wrapper around std::function<void(raw_ostream&)>.
Return a value (possibly void), from a function.
Implements a dense probed hash-table based set with some number of buckets stored inline.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
bool erase(PtrType Ptr)
Remove pointer from the set.
void insert_range(Range &&R)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
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...
LLVM_ABI std::string str() const
Return the twine contents as a std::string.
bool isTriviallyEmpty() const
Check if this twine is trivially empty; a false return value does not necessarily mean the twine is e...
The instances of the Type class are immutable: once they are created, they are never changed.
bool isTokenTy() const
Return true if this is 'token'.
Unconditional Branch instruction.
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
BasicBlock * getSuccessor(unsigned i=0) const
This function has undefined behavior.
A Use represents the edge between a Value definition and its users.
void setOperand(unsigned i, Value *Val)
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
bool hasOneUse() const
Return true if there is exactly one use of this value.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
LLVM_ABI void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
std::pair< iterator, bool > insert(const ValueT &V)
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
const ParentTy * getParent() const
self_iterator getIterator()
This class implements an extremely fast bulk output stream that can only output to a stream.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
AssignmentInstRange getAssignmentInsts(DIAssignID *ID)
Return a range of instructions (typically just one) that have ID as an attachment.
initializer< Ty > init(const Ty &Val)
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.
iterator_range< df_ext_iterator< T, SetTy > > depth_first_ext(const T &G, SetTy &S)
LLVM_ABI bool RemoveRedundantDbgInstrs(BasicBlock *BB)
Try to remove redundant dbg.value instructions from given basic block.
bool succ_empty(const Instruction *I)
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 @...
RelativeUniformCounterPtr Values
LLVM_ABI unsigned GetSuccessorNumber(const BasicBlock *BB, const BasicBlock *Succ)
Search for the specified successor of basic block BB and return its position in the terminator instru...
auto pred_end(const MachineBasicBlock *BB)
LLVM_ABI BasicBlock * SplitMultiBrEdge(BasicBlock *MultiBrBlock, BasicBlock *Succ, unsigned SuccIdx, BasicBlock *BrTarget=nullptr, DomTreeUpdater *DTU=nullptr, CycleInfo *CI=nullptr, LoopInfo *LI=nullptr, bool *UpdatedLI=nullptr)
Create a new intermediate target block for a callbr or switch edge.
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.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
auto successors(const MachineBasicBlock *BB)
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...
constexpr from_range_t from_range
LLVM_ABI std::pair< Instruction *, Value * > SplitBlockAndInsertSimpleForLoop(Value *End, BasicBlock::iterator SplitBefore)
Insert a for (int i = 0; i < End; i++) loop structure (with the exception that End is assumed > 0,...
LLVM_ABI BasicBlock * splitBlockBefore(BasicBlock *Old, BasicBlock::iterator SplitPt, DomTreeUpdater *DTU, LoopInfo *LI, MemorySSAUpdater *MSSAU, const Twine &BBName="")
Split the specified block at the specified instruction SplitPt.
LLVM_ABI Instruction * SplitBlockAndInsertIfElse(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ElseBlock=nullptr)
Similar to SplitBlockAndInsertIfThen, but the inserted block is on the false path of the branch.
LLVM_ABI bool DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, SmallPtrSetImpl< PHINode * > *KnownNonDeadPHIs=nullptr)
Examine each PHI in the given block and delete it if it is dead.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
auto cast_or_null(const Y &Val)
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,...
DomTreeNodeBase< BasicBlock > DomTreeNode
auto dyn_cast_or_null(const Y &Val)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI CondBrInst * GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue, BasicBlock *&IfFalse)
Check whether BB is the merge point of a if-region.
LLVM_ABI bool HasLoopOrEntryConvergenceToken(const BasicBlock *BB)
Check if the given basic block contains any loop or entry convergent intrinsic instructions.
LLVM_ABI void InvertBranch(CondBrInst *PBI, IRBuilderBase &Builder)
auto reverse(ContainerTy &&C)
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...
bool isa_and_present(const Y &Val)
isa_and_present<X> - Functionally identical to isa, except that a null value is accepted.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
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.
auto succ_size(const MachineBasicBlock *BB)
SmallVector< ValueTypeFromRangeType< R >, Size > to_vector(R &&Range)
Given a range of type R, iterate the entire range and return a SmallVector with elements of the vecto...
LLVM_ABI bool RecursivelyDeleteDeadPHINode(PHINode *PN, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, SmallPtrSetImpl< PHINode * > *KnownNonDeadPHIs=nullptr)
If the specified value is an effectively dead PHI node, due to being a def-use chain of single-use no...
LLVM_ABI bool VerifyMemorySSA
Enables verification of MemorySSA.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
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_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
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 bool isAssignmentTrackingEnabled(const Module &M)
Return true if assignment tracking is enabled for module M.
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction.
DWARFExpression::Operation Op
PredIterator< BasicBlock, Value::user_iterator > pred_iterator
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 bool isCriticalEdge(const Instruction *TI, unsigned SuccNum, bool AllowIdenticalEdges=false)
Return true if the specified edge is a critical edge.
LLVM_ABI unsigned SplitAllCriticalEdges(Function &F, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions())
Loop over all of the edges in the CFG, breaking critical edges as they are found.
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.
auto pred_begin(const MachineBasicBlock *BB)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
auto predecessors(const MachineBasicBlock *BB)
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
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...
@ End
Run the machine verifier once, at the end of the pipeline.
LLVM_ABI void setUnwindEdgeTo(Instruction *TI, BasicBlock *Succ)
Sets the unwind edge of an instruction to a particular successor.
LLVM_ABI void SplitBlockAndInsertForEachLane(Value *End, BasicBlock::iterator InsertBefore, std::function< void(IRBuilderBase &, Value *)> Func)
Utility function for performing a given action on each lane of a vector with EVL effective length.
static auto filterDbgVars(iterator_range< simple_ilist< DbgRecord >::iterator > R)
Filter the DbgRecord range to DbgVariableRecord types only and downcast.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Option class for critical edge splitting.
CriticalEdgeSplittingOptions & setPreserveLCSSA()