53#define DEBUG_TYPE "basicblock-utils"
57 cl::desc(
"Set the maximum path length when checking whether a basic block "
58 "is followed by a block that either has a terminating "
59 "deoptimizing call or is terminated with an unreachable"));
64 bool KeepOneInputPHIs) {
65 for (
auto *BB : BBs) {
70 Succ->removePredecessor(BB, KeepOneInputPHIs);
71 if (Updates && UniqueSuccessors.
insert(Succ).second)
72 Updates->
push_back({DominatorTree::Delete, BB, Succ});
76 while (!BB->empty()) {
85 BB->back().eraseFromParent();
89 isa<UnreachableInst>(BB->getTerminator()) &&
90 "The successor list of BB isn't empty before "
91 "applying corresponding DTU updates.");
96 bool KeepOneInputPHIs) {
101 bool KeepOneInputPHIs) {
105 assert(Dead.size() == BBs.
size() &&
"Duplicating blocks?");
106 for (
auto *BB : Dead)
108 assert(Dead.count(Pred) &&
"All predecessors must be dead!");
121 BB->eraseFromParent();
125 bool KeepOneInputPHIs) {
133 std::vector<BasicBlock*> DeadBlocks;
135 if (!Reachable.
count(&BB))
136 DeadBlocks.push_back(&BB);
141 return !DeadBlocks.empty();
146 if (!isa<PHINode>(BB->
begin()))
150 if (PN->getIncomingValue(0) != PN)
151 PN->replaceAllUsesWith(PN->getIncomingValue(0));
158 PN->eraseFromParent();
169 bool Changed =
false;
170 for (
const auto &
PHI : PHIs)
180 bool PredecessorWithTwoSuccessors,
187 if (!PredBB)
return false;
190 if (PredBB == BB)
return false;
205 unsigned FallThruPath;
206 if (PredecessorWithTwoSuccessors) {
207 if (!(PredBB_BI = dyn_cast<BranchInst>(PTI)))
213 FallThruPath = PredBB_BI->
getSuccessor(0) == BB ? 0 : 1;
226 if (isa<PHINode>(BB->
front())) {
228 if (!isa<PHINode>(PN.getIncomingValue(0)) ||
229 cast<PHINode>(PN.getIncomingValue(0))->getParent() != BB)
230 IncomingValues.
push_back(PN.getIncomingValue(0));
235 assert(!DTU &&
"cannot use both DT and DTU for updates");
239 assert(BBNode &&
"PredNode unreachable but BBNode reachable?");
241 C->setIDom(PredNode);
246 std::vector<DominatorTree::UpdateType> Updates;
248 assert(!DT &&
"cannot use both DT and DTU for updates");
253 Updates.reserve(Updates.size() + 2 *
succ_size(BB) + 1);
262 if (!SuccsOfPredBB.
contains(SuccOfBB))
263 if (SeenSuccs.
insert(SuccOfBB).second)
264 Updates.push_back({DominatorTree::Insert, PredBB, SuccOfBB});
267 if (SeenSuccs.
insert(SuccOfBB).second)
268 Updates.push_back({DominatorTree::Delete, BB, SuccOfBB});
269 Updates.push_back({DominatorTree::Delete, PredBB, BB});
289 if (PredecessorWithTwoSuccessors) {
326 "successors should have been transferred to PredBB");
339 assert(!MergeBlocks.
empty() &&
"MergeBlocks should not be empty");
341 bool BlocksHaveBeenMerged =
false;
342 while (!MergeBlocks.
empty()) {
345 if (Dest && (!L || L->contains(Dest))) {
350 "Expecting BB to be unique predecessor of the Dest block");
351 MergeBlocks.
erase(Dest);
352 BlocksHaveBeenMerged =
true;
354 MergeBlocks.
erase(BB);
356 MergeBlocks.
erase(BB);
358 return BlocksHaveBeenMerged;
387 DVR.getDebugLoc()->getInlinedAt());
388 auto R = VariableSet.
insert(Key);
395 if (DVR.isDbgAssign()) {
410 for (
auto &DVR : ToBeRemoved)
411 DVR->eraseFromParent();
413 return !ToBeRemoved.
empty();
436 bool RemovedAny =
false;
440 for (
auto &
I : *BB) {
443 if (DVR.getType() == DbgVariableRecord::LocationType::Declare)
446 DVR.getDebugLoc()->getInlinedAt());
447 auto [VMI, Inserted] = VariableMap.
try_emplace(Key);
450 bool IsDbgValueKind =
456 if (Inserted || VMI->second.first != Values ||
457 VMI->second.second != DVR.getExpression()) {
459 VMI->second = {Values, DVR.getExpression()};
461 VMI->second = {Values,
nullptr};
468 DVR.eraseFromParent();
497 bool RemovedAny =
false;
502 for (
auto &
I : *BB) {
505 if (!DVR.isDbgValue() && !DVR.isDbgAssign())
507 bool IsDbgValueKind =
511 if (!SeenDefForAggregate.
contains(Aggregate)) {
512 bool IsKill = DVR.isKillLocation() && IsDbgValueKind;
514 SeenDefForAggregate.
insert(Aggregate);
515 }
else if (DVR.isDbgAssign()) {
516 DVR.eraseFromParent();
527 bool MadeChanges =
false;
554 I.replaceAllUsesWith(V);
557 if (
I.hasName() && !V->hasName())
561 BI = BI->eraseFromParent();
566 assert(
I->getParent() ==
nullptr &&
567 "ReplaceInstWithInst: Instruction already inserted into basic block!");
571 if (!
I->getDebugLoc())
572 I->setDebugLoc(BI->getDebugLoc());
589 VisitedBlocks.
insert(BB).second) {
605 const Twine &BBName) {
623 assert(SP == BB &&
"CFG broken");
632 "Should have a single succ!");
637 if (
auto *
II = dyn_cast<InvokeInst>(TI))
638 II->setUnwindDest(Succ);
639 else if (
auto *CS = dyn_cast<CatchSwitchInst>(TI))
640 CS->setUnwindDest(Succ);
641 else if (
auto *CR = dyn_cast<CleanupReturnInst>(TI))
642 CR->setUnwindDest(Succ);
661 if (PN.getIncomingBlock(BBIdx) != OldPred)
662 BBIdx = PN.getBasicBlockIndex(OldPred);
664 assert(BBIdx != -1 &&
"Invalid PHI Index!");
665 PN.setIncomingBlock(BBIdx, NewPred);
671 PHINode *LandingPadReplacement,
673 const Twine &BBName) {
676 if (!LandingPadReplacement && !PadInst->
isEHPad())
684 if (
Options.PreserveLoopSimplify && LI) {
685 if (
Loop *BBLoop = LI->getLoopFor(BB)) {
699 if (LI->getLoopFor(
P) != BBLoop) {
722 if (LandingPadReplacement) {
723 auto *NewLP = OriginalPad->
clone();
725 NewLP->insertBefore(Terminator->getIterator());
728 Value *ParentPad =
nullptr;
729 if (
auto *FuncletPad = dyn_cast<FuncletPadInst>(PadInst))
730 ParentPad = FuncletPad->getParentPad();
731 else if (
auto *CatchSwitch = dyn_cast<CatchSwitchInst>(PadInst))
732 ParentPad = CatchSwitch->getParentPad();
733 else if (
auto *CleanupPad = dyn_cast<CleanupPadInst>(PadInst))
734 ParentPad = CleanupPad->getParentPad();
735 else if (
auto *LandingPad = dyn_cast<LandingPadInst>(PadInst))
736 ParentPad = LandingPad->getParent();
753 Updates.
push_back({DominatorTree::Insert, BB, NewBB});
754 Updates.
push_back({DominatorTree::Insert, NewBB, Succ});
755 Updates.
push_back({DominatorTree::Delete, BB, Succ});
761 MSSAU->applyUpdates(Updates, *DT);
763 MSSAU->getMemorySSA()->verifyMemorySSA();
768 if (
Loop *BBLoop = LI->getLoopFor(BB)) {
771 if (
Loop *SuccLoop = LI->getLoopFor(Succ)) {
772 if (BBLoop == SuccLoop) {
774 SuccLoop->addBasicBlockToLoop(NewBB, *LI);
775 }
else if (BBLoop->contains(SuccLoop)) {
777 BBLoop->addBasicBlockToLoop(NewBB, *LI);
778 }
else if (SuccLoop->contains(BBLoop)) {
780 SuccLoop->addBasicBlockToLoop(NewBB, *LI);
786 assert(SuccLoop->getHeader() == Succ &&
787 "Should not create irreducible loops!");
788 if (
Loop *
P = SuccLoop->getParentLoop())
789 P->addBasicBlockToLoop(NewBB, *LI);
795 if (!BBLoop->contains(Succ)) {
796 assert(!BBLoop->contains(NewBB) &&
797 "Split point for loop exit is contained in loop!");
804 if (!LoopPreds.
empty()) {
806 Succ, LoopPreds,
"split", DT, LI, MSSAU,
Options.PreserveLCSSA);
822 "SplitBB has non-PHI nodes!");
826 int Idx = PN.getBasicBlockIndex(SplitBB);
827 assert(
Idx >= 0 &&
"Invalid Block Index");
828 Value *V = PN.getIncomingValue(
Idx);
832 if (
const PHINode *VP = dyn_cast<PHINode>(V))
833 if (VP->getParent() == SplitBB)
846 PN.setIncomingValue(
Idx, NewPN);
853 unsigned NumBroken = 0;
867 const Twine &BBName,
bool Before) {
869 DomTreeUpdater LocalDTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
871 DTU ? DTU : (DT ? &LocalDTU :
nullptr), LI, MSSAU,
875 while (isa<PHINode>(SplitIt) || SplitIt->isEHPad()) {
877 assert(SplitIt != SplitPt->getParent()->end());
879 std::string
Name = BBName.
str();
887 L->addBasicBlockToLoop(New, *LI);
893 Updates.
push_back({DominatorTree::Insert, Old, New});
896 if (UniqueSuccessorsOfOld.
insert(SuccessorOfOld).second) {
897 Updates.
push_back({DominatorTree::Insert, New, SuccessorOfOld});
898 Updates.
push_back({DominatorTree::Delete, Old, SuccessorOfOld});
905 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
924 return SplitBlockImpl(Old, SplitPt,
nullptr, DT, LI, MSSAU, BBName,
931 return SplitBlockImpl(Old, SplitPt, DTU,
nullptr, LI, MSSAU, BBName,
938 const Twine &BBName) {
941 while (isa<PHINode>(SplitIt) || SplitIt->isEHPad())
943 std::string
Name = BBName.
str();
952 L->addBasicBlockToLoop(New, *LI);
959 DTUpdates.
push_back({DominatorTree::Insert, New, Old});
962 if (UniquePredecessorsOfOld.
insert(PredecessorOfOld).second) {
963 DTUpdates.
push_back({DominatorTree::Insert, PredecessorOfOld, New});
964 DTUpdates.
push_back({DominatorTree::Delete, PredecessorOfOld, Old});
986 bool PreserveLCSSA,
bool &HasLoopExit) {
1000 Updates.
push_back({DominatorTree::Insert, NewBB, OldBB});
1002 for (
auto *Pred : Preds)
1003 if (UniquePreds.
insert(Pred).second) {
1004 Updates.
push_back({DominatorTree::Insert, Pred, NewBB});
1005 Updates.
push_back({DominatorTree::Delete, Pred, OldBB});
1029 assert(DT &&
"DT should be available to update LoopInfo!");
1034 bool IsLoopEntry = !!L;
1035 bool SplitMakesNewLoopHeader =
false;
1047 if (!PL->contains(OldBB))
1054 if (L->contains(Pred))
1055 IsLoopEntry =
false;
1057 SplitMakesNewLoopHeader =
true;
1069 Loop *InnermostPredLoop =
nullptr;
1074 while (PredLoop && !PredLoop->contains(OldBB))
1078 if (PredLoop && PredLoop->contains(OldBB) &&
1079 (!InnermostPredLoop ||
1080 InnermostPredLoop->
getLoopDepth() < PredLoop->getLoopDepth()))
1081 InnermostPredLoop = PredLoop;
1085 if (InnermostPredLoop)
1088 L->addBasicBlockToLoop(NewBB, *LI);
1089 if (SplitMakesNewLoopHeader)
1090 L->moveToHeader(NewBB);
1106 Value *InVal =
nullptr;
1149 if (PredSet.
count(IncomingBB)) {
1178 std::string NewName = std::string(Suffix) +
".split-lp";
1181 DTU, DT, LI, MSSAU, PreserveLCSSA);
1205 OldLatch = L->getLoopLatch();
1214 assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
1215 "Cannot split an edge from an IndirectBrInst");
1216 Pred->getTerminator()->replaceSuccessorWith(BB, NewBB);
1223 if (Preds.
empty()) {
1230 bool HasLoopExit =
false;
1234 if (!Preds.
empty()) {
1241 if (NewLatch != OldLatch) {
1259 bool PreserveLCSSA) {
1261 MSSAU, PreserveLCSSA);
1268 bool PreserveLCSSA) {
1270 nullptr, LI, MSSAU, PreserveLCSSA);
1296 assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
1297 "Cannot split an edge from an IndirectBrInst");
1298 Pred->getTerminator()->replaceUsesOfWith(OrigBB, NewBB1);
1301 bool HasLoopExit =
false;
1303 PreserveLCSSA, HasLoopExit);
1313 if (Pred == NewBB1)
continue;
1315 "Cannot split an edge from an IndirectBrInst");
1321 if (!NewBB2Preds.
empty()) {
1334 NewBB2Pred->getTerminator()->replaceUsesOfWith(OrigBB, NewBB2);
1337 HasLoopExit =
false;
1339 PreserveLCSSA, HasLoopExit);
1359 "Split cannot be applied if LPad is token type. Otherwise an "
1360 "invalid PHINode of token type would be created.");
1377 const char *Suffix1,
const char *Suffix2,
1381 bool PreserveLCSSA) {
1383 NewBBs, DTU,
nullptr, LI, MSSAU,
1400 if (
BitCastInst *BCI = dyn_cast<BitCastInst>(V)) {
1403 V = BCI->getOperand(0);
1404 NewBC = BCI->
clone();
1411 V = EVI->getOperand(0);
1412 NewEV = EVI->
clone();
1422 if (
PHINode *PN = dyn_cast<PHINode>(V)) {
1423 if (PN->getParent() == BB) {
1425 NewEV->
setOperand(0, PN->getIncomingValueForBlock(Pred));
1427 NewBC->
setOperand(0, PN->getIncomingValueForBlock(Pred));
1429 Op = PN->getIncomingValueForBlock(Pred);
1440 DTU->
applyUpdates({{DominatorTree::Delete, Pred, BB}});
1442 return cast<ReturnInst>(NewRet);
1452 Cond, SplitBefore, &ThenBlock,
nullptr,
1454 false, BranchWeights, DTU, LI);
1465 Cond, SplitBefore,
nullptr, &ElseBlock,
1467 Unreachable, BranchWeights, DTU, LI);
1479 Cond, SplitBefore, &ThenBlock, &ElseBlock,
false,
1480 false, BranchWeights, DTU, LI);
1488 BasicBlock **ElseBlock,
bool UnreachableThen,
bool UnreachableElse,
1490 assert((ThenBlock || ElseBlock) &&
1491 "At least one branch block must be created");
1492 assert((!UnreachableThen || !UnreachableElse) &&
1493 "Split block tail must be reachable");
1500 Updates.
reserve(4 + 2 * UniqueOrigSuccessors.
size());
1507 bool ThenToTailEdge =
false;
1508 bool ElseToTailEdge =
false;
1527 BB->getTerminator()->
setDebugLoc(SplitBefore->getDebugLoc());
1533 handleBlock(ThenBlock, UnreachableThen, TrueBlock, ThenToTailEdge);
1534 handleBlock(ElseBlock, UnreachableElse, FalseBlock, ElseToTailEdge);
1539 HeadNewTerm->
setMetadata(LLVMContext::MD_prof, BranchWeights);
1543 Updates.
emplace_back(DominatorTree::Insert, Head, TrueBlock);
1544 Updates.
emplace_back(DominatorTree::Insert, Head, FalseBlock);
1549 for (
BasicBlock *UniqueOrigSuccessor : UniqueOrigSuccessors)
1551 for (
BasicBlock *UniqueOrigSuccessor : UniqueOrigSuccessors)
1552 Updates.
emplace_back(DominatorTree::Delete, Head, UniqueOrigSuccessor);
1559 L->addBasicBlockToLoop(TrueBlock, *LI);
1561 L->addBasicBlockToLoop(FalseBlock, *LI);
1562 L->addBasicBlockToLoop(
Tail, *LI);
1567std::pair<Instruction *, Value *>
1574 auto *Ty =
End->getType();
1575 auto &
DL = SplitBefore->getDataLayout();
1576 const unsigned Bitwidth =
DL.getTypeSizeInBits(Ty);
1581 Builder.
CreateAdd(
IV, ConstantInt::get(Ty, 1),
IV->getName() +
".next",
1582 true, Bitwidth != 2);
1584 IV->getName() +
".check");
1589 IV->addIncoming(ConstantInt::get(Ty, 0), LoopPred);
1590 IV->addIncoming(IVNext, LoopBody);
1599 IRBuilder<> IRB(InsertBefore->getParent(), InsertBefore);
1601 if (EC.isScalable()) {
1604 auto [BodyIP, Index] =
1612 unsigned Num = EC.getFixedValue();
1613 for (
unsigned Idx = 0;
Idx < Num; ++
Idx) {
1615 Func(IRB, ConstantInt::get(IndexTy,
Idx));
1623 IRBuilder<> IRB(InsertBefore->getParent(), InsertBefore);
1626 if (!isa<ConstantInt>(EVL)) {
1633 unsigned Num = cast<ConstantInt>(EVL)->getZExtValue();
1634 for (
unsigned Idx = 0;
Idx < Num; ++
Idx) {
1636 Func(IRB, ConstantInt::get(Ty,
Idx));
1667 if (!Pred1Br || !Pred2Br)
1719 if (!BI)
return nullptr;
1736 if (NewCond->
hasOneUse() && isa<CmpInst>(NewCond)) {
1737 CmpInst *CI = cast<CmpInst>(NewCond);
1747 for (
auto &BB :
F) {
1748 auto *Term = BB.getTerminator();
1749 if (!(isa<ReturnInst>(Term) || isa<UnreachableInst>(Term) ||
1750 isa<BranchInst>(Term)))
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 BasicBlock * SplitBlockImpl(BasicBlock *Old, BasicBlock::iterator SplitPt, DomTreeUpdater *DTU, DominatorTree *DT, LoopInfo *LI, MemorySSAUpdater *MSSAU, const Twine &BBName, bool Before)
static void UpdatePHINodes(BasicBlock *OrigBB, BasicBlock *NewBB, ArrayRef< BasicBlock * > Preds, BranchInst *BI, bool HasLoopExit)
Update the PHI nodes in OrigBB to include the values coming from NewBB.
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 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"))
BlockVerifier::State From
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
uint64_t IntrinsicInst * II
const SmallVectorImpl< MachineOperand > & Cond
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
static const uint32_t IV[8]
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
size - Get the array size.
bool empty() const
empty - 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...
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.
const Instruction & front() const
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 InstListType::const_iterator getFirstNonPHIOrDbg(bool SkipPseudoOp=true) const
Returns a pointer to the first instruction in this block that is not a PHINode or a debug intrinsic,...
LLVM_ABI BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="", bool Before=false)
Split the basic block into two basic blocks at the specified instruction.
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.
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.
const Function * getParent() const
Return the enclosing method, or null if none.
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.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
LLVM_ABI bool canSplitPredecessors() const
void splice(BasicBlock::iterator ToIt, BasicBlock *FromBB)
Transfer all instructions from FromBB to this basic block at ToIt.
const Instruction & back() const
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.
Conditional or Unconditional Branch instruction.
void setCondition(Value *V)
LLVM_ABI void swapSuccessors()
Swap the successors of this branch instruction.
bool isConditional() const
static BranchInst * Create(BasicBlock *IfTrue, InsertPosition InsertBefore=nullptr)
BasicBlock * getSuccessor(unsigned i) const
bool isUnconditional() const
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
Value * getCondition() const
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,...
This class represents an Operation in the Expression.
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.
DomTreeNodeBase< NodeT > * setNewRoot(NodeT *BB)
Add a new node to the forward dominator tree and make it a new root.
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.
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.
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
Value * CreateNot(Value *V, const Twine &Name="")
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
BranchInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a conditional 'br Cond, TrueDest, FalseDest' instruction.
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
LLVM_ABI Value * CreateElementCount(Type *Ty, ElementCount EC)
Create an expression which evaluates to the number of elements in EC at runtime.
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.
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
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.
Represents a single loop in the control flow graph.
Provides a lazy, caching interface for making common memory aliasing information queries,...
void invalidateCachedPredecessors()
Clears the PredIteratorCache info.
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 applyUpdates(ArrayRef< CFGUpdate > Updates, DominatorTree &DT, bool UpdateDTFirst=false)
Apply CFG updates, analogous with the DT edge updates.
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.
LLVM_ABI void verifyMemorySSA(VerificationLevel=VerificationLevel::Fast) const
Verify that MemorySSA is self consistent (IE definitions dominate all uses, uses appear in the right ...
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.
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.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
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.
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'.
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 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.
self_iterator getIterator()
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ Tail
Attemps to make calls as fast as possible while guaranteeing that tail call optimization can always b...
@ C
The default llvm calling convention, compatible with C.
LLVM_ABI 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 @...
LLVM_ABI BranchInst * GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue, BasicBlock *&IfFalse)
Check whether BB is the merge point of a if-region.
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 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)
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.
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 pred_size(const MachineBasicBlock *BB)
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,...
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 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.
auto reverse(ContainerTy &&C)
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 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 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 bool VerifyMemorySSA
Enables verification of MemorySSA.
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.
DWARFExpression::Operation Op
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.
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.
auto pred_begin(const MachineBasicBlock *BB)
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.
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 bool RecursivelyDeleteDeadPHINode(PHINode *PN, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr)
If the specified value is an effectively dead PHI node, due to being a def-use chain of single-use no...
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.
static auto filterDbgVars(iterator_range< simple_ilist< DbgRecord >::iterator > R)
Filter the DbgRecord range to DbgVariableRecord types only and downcast.
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.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Option class for critical edge splitting.
CriticalEdgeSplittingOptions & setPreserveLCSSA()