[llvm] [Transforms/Utils][NFC] Drop uses of BranchInst (PR #186586)
Alexis Engelke via llvm-commits
llvm-commits at lists.llvm.org
Sat Mar 14 04:09:57 PDT 2026
https://github.com/aengelke created https://github.com/llvm/llvm-project/pull/186586
None
>From 39ce7e7ee1b5f38c39885590f15fb8a2cb7c5c36 Mon Sep 17 00:00:00 2001
From: Alexis Engelke <engelke at in.tum.de>
Date: Sat, 14 Mar 2026 10:46:13 +0000
Subject: [PATCH] [Transforms/Utils][NFC] Drop uses of BranchInst
---
.../lib/Transforms/Utils/AMDGPUEmitPrintf.cpp | 8 +-
llvm/lib/Transforms/Utils/BasicBlockUtils.cpp | 27 ++-
.../Transforms/Utils/BreakCriticalEdges.cpp | 2 +-
llvm/lib/Transforms/Utils/CloneFunction.cpp | 42 ++--
llvm/lib/Transforms/Utils/CodeExtractor.cpp | 10 +-
.../lib/Transforms/Utils/ControlFlowUtils.cpp | 36 ++-
llvm/lib/Transforms/Utils/Evaluator.cpp | 17 +-
llvm/lib/Transforms/Utils/FixIrreducible.cpp | 22 +-
llvm/lib/Transforms/Utils/FlattenCFG.cpp | 40 ++--
llvm/lib/Transforms/Utils/InlineFunction.cpp | 21 +-
llvm/lib/Transforms/Utils/Local.cpp | 19 +-
llvm/lib/Transforms/Utils/LoopPeel.cpp | 12 +-
.../Transforms/Utils/LoopRotationUtils.cpp | 21 +-
llvm/lib/Transforms/Utils/LoopSimplify.cpp | 21 +-
llvm/lib/Transforms/Utils/LoopUnroll.cpp | 18 +-
.../lib/Transforms/Utils/LoopUnrollAndJam.cpp | 37 ++-
.../lib/Transforms/Utils/LowerGlobalDtors.cpp | 2 +-
llvm/lib/Transforms/Utils/LowerInvoke.cpp | 2 +-
.../Transforms/Utils/LowerMemIntrinsics.cpp | 18 +-
llvm/lib/Transforms/Utils/LowerSwitch.cpp | 10 +-
llvm/lib/Transforms/Utils/MatrixUtils.cpp | 10 +-
llvm/lib/Transforms/Utils/MisExpect.cpp | 2 +-
llvm/lib/Transforms/Utils/PredicateInfo.cpp | 8 +-
llvm/lib/Transforms/Utils/ProfileVerify.cpp | 2 +-
llvm/lib/Transforms/Utils/SCCPSolver.cpp | 15 +-
llvm/lib/Transforms/Utils/SimplifyCFG.cpp | 220 +++++++++---------
llvm/lib/Transforms/Utils/SimplifyIndVar.cpp | 4 +-
.../Utils/UnifyFunctionExitNodes.cpp | 4 +-
llvm/lib/Transforms/Utils/UnifyLoopExits.cpp | 12 +-
llvm/unittests/Transforms/Utils/LocalTest.cpp | 11 +-
.../Transforms/Utils/LoopUtilsTest.cpp | 3 +-
.../Transforms/Utils/ProfDataUtilTest.cpp | 4 +-
.../Utils/ScalarEvolutionExpanderTest.cpp | 6 +-
33 files changed, 333 insertions(+), 353 deletions(-)
diff --git a/llvm/lib/Transforms/Utils/AMDGPUEmitPrintf.cpp b/llvm/lib/Transforms/Utils/AMDGPUEmitPrintf.cpp
index 0d85b16ef1c31..c52d62985677b 100644
--- a/llvm/lib/Transforms/Utils/AMDGPUEmitPrintf.cpp
+++ b/llvm/lib/Transforms/Utils/AMDGPUEmitPrintf.cpp
@@ -119,7 +119,7 @@ static Value *getStrlenWithNull(IRBuilder<> &Builder, Value *Str) {
Builder.SetInsertPoint(Prev);
auto CmpNull =
Builder.CreateICmpEQ(Str, Constant::getNullValue(Str->getType()));
- BranchInst::Create(Join, While, CmpNull, Prev);
+ Builder.CreateCondBr(CmpNull, Join, While);
// Entry to the while loop.
Builder.SetInsertPoint(While);
@@ -141,7 +141,7 @@ static Value *getStrlenWithNull(IRBuilder<> &Builder, Value *Str) {
Len = Builder.CreateAdd(Len, One);
// Final join.
- BranchInst::Create(Join, WhileDone);
+ UncondBrInst::Create(Join, WhileDone);
Builder.SetInsertPoint(Join, Join->begin());
auto LenPhi = Builder.CreatePHI(Len->getType(), 2);
LenPhi->addIncoming(Len, WhileDone);
@@ -459,7 +459,7 @@ Value *llvm::emitAMDGPUPrintfCall(IRBuilder<> &Builder, ArrayRef<Value *> Args,
BasicBlock *ArgPush = BasicBlock::Create(
Ctx, "argpush.block", Builder.GetInsertBlock()->getParent());
- BranchInst::Create(ArgPush, End, Cmp, Builder.GetInsertBlock());
+ CondBrInst::Create(Cmp, ArgPush, End, Builder.GetInsertBlock());
Builder.SetInsertPoint(ArgPush);
// Create controlDWord and store as the first entry, format as follows
@@ -512,7 +512,7 @@ Value *llvm::emitAMDGPUPrintfCall(IRBuilder<> &Builder, ArrayRef<Value *> Args,
IsConstFmtStr);
// End block, returns -1 on failure
- BranchInst::Create(End, ArgPush);
+ UncondBrInst::Create(End, ArgPush);
Builder.SetInsertPoint(End);
return Builder.CreateSExt(Builder.CreateNot(Cmp), Int32Ty, "printf_result");
}
diff --git a/llvm/lib/Transforms/Utils/BasicBlockUtils.cpp b/llvm/lib/Transforms/Utils/BasicBlockUtils.cpp
index c33ceed7ebc20..f8e0ad2b7b661 100644
--- a/llvm/lib/Transforms/Utils/BasicBlockUtils.cpp
+++ b/llvm/lib/Transforms/Utils/BasicBlockUtils.cpp
@@ -250,16 +250,16 @@ bool llvm::MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU,
// Currently only allow PredBB to have two predecessors, one being BB.
// Update BI to branch to BB's only successor instead of BB.
- BranchInst *PredBB_BI;
+ CondBrInst *PredBB_BI;
BasicBlock *NewSucc = nullptr;
unsigned FallThruPath;
if (PredecessorWithTwoSuccessors) {
- if (!(PredBB_BI = dyn_cast<BranchInst>(PTI)))
+ if (!(PredBB_BI = dyn_cast<CondBrInst>(PTI)))
return false;
- BranchInst *BB_JmpI = dyn_cast<BranchInst>(BB->getTerminator());
- if (!BB_JmpI || !BB_JmpI->isUnconditional())
+ UncondBrInst *BB_JmpI = dyn_cast<UncondBrInst>(BB->getTerminator());
+ if (!BB_JmpI)
return false;
- NewSucc = BB_JmpI->getSuccessor(0);
+ NewSucc = BB_JmpI->getSuccessor();
FallThruPath = PredBB_BI->getSuccessor(0) == BB ? 0 : 1;
}
@@ -746,7 +746,7 @@ BasicBlock *llvm::SplitCallBrEdge(BasicBlock *CallBrBlock, BasicBlock *Succ,
// Rewire control flow from callbr to the new target block.
CallBr->setSuccessor(SuccIdx, CallBrTarget);
// Jump from the new target block to the original successor.
- BranchInst::Create(Succ, CallBrTarget);
+ UncondBrInst::Create(Succ, CallBrTarget);
bool Updated =
updateCycleLoopInfo<LoopInfo, Loop>(LI, CallBrBlock, CallBrTarget, Succ);
@@ -853,7 +853,7 @@ BasicBlock *llvm::ehAwareSplitEdge(BasicBlock *BB, BasicBlock *Succ,
if (LandingPadReplacement) {
auto *NewLP = OriginalPad->clone();
- auto *Terminator = BranchInst::Create(Succ, NewBB);
+ auto *Terminator = UncondBrInst::Create(Succ, NewBB);
NewLP->insertBefore(Terminator->getIterator());
LandingPadReplacement->addIncoming(NewLP, NewBB);
} else {
@@ -1190,7 +1190,7 @@ BasicBlock *llvm::splitBlockBefore(BasicBlock *Old,
/// Update the PHI nodes in OrigBB to include the values coming from NewBB.
/// This also updates AliasAnalysis, if available.
static void UpdatePHINodes(BasicBlock *OrigBB, BasicBlock *NewBB,
- ArrayRef<BasicBlock *> Preds, BranchInst *BI,
+ ArrayRef<BasicBlock *> Preds, Instruction *BI,
bool HasLoopExit) {
// Otherwise, create a new PHI node in NewBB for each PHI node in OrigBB.
SmallPtrSet<BasicBlock *, 16> PredSet(llvm::from_range, Preds);
@@ -1283,7 +1283,7 @@ SplitBlockPredecessorsImpl(BasicBlock *BB, ArrayRef<BasicBlock *> Preds,
BB->getContext(), BB->getName() + Suffix, BB->getParent(), BB);
// The new block unconditionally branches to the old block.
- BranchInst *BI = BranchInst::Create(BB, NewBB);
+ UncondBrInst *BI = UncondBrInst::Create(BB, NewBB);
Loop *L = nullptr;
BasicBlock *OldLatch = nullptr;
@@ -1381,7 +1381,7 @@ static void SplitLandingPadPredecessorsImpl(
NewBBs.push_back(NewBB1);
// The new block unconditionally branches to the old block.
- BranchInst *BI1 = BranchInst::Create(OrigBB, NewBB1);
+ UncondBrInst *BI1 = UncondBrInst::Create(OrigBB, NewBB1);
BI1->setDebugLoc(OrigBB->getFirstNonPHIIt()->getDebugLoc());
// Move the edges from Preds to point to NewBB1 instead of OrigBB.
@@ -1422,7 +1422,7 @@ static void SplitLandingPadPredecessorsImpl(
NewBBs.push_back(NewBB2);
// The new block unconditionally branches to the old block.
- BranchInst *BI2 = BranchInst::Create(OrigBB, NewBB2);
+ UncondBrInst *BI2 = UncondBrInst::Create(OrigBB, NewBB2);
BI2->setDebugLoc(OrigBB->getFirstNonPHIIt()->getDebugLoc());
// Move the remaining edges from OrigBB to point to NewBB2.
@@ -1617,7 +1617,7 @@ void llvm::SplitBlockAndInsertIfThenElse(
if (Unreachable)
(void)new UnreachableInst(C, BB);
else {
- (void)BranchInst::Create(Tail, BB);
+ (void)UncondBrInst::Create(Tail, BB);
ToTailEdge = true;
}
BB->getTerminator()->setDebugLoc(SplitBefore->getDebugLoc());
@@ -1630,8 +1630,7 @@ void llvm::SplitBlockAndInsertIfThenElse(
handleBlock(ElseBlock, UnreachableElse, FalseBlock, ElseToTailEdge);
Instruction *HeadOldTerm = Head->getTerminator();
- BranchInst *HeadNewTerm =
- BranchInst::Create(/*ifTrue*/ TrueBlock, /*ifFalse*/ FalseBlock, Cond);
+ CondBrInst *HeadNewTerm = CondBrInst::Create(Cond, TrueBlock, FalseBlock);
HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
diff --git a/llvm/lib/Transforms/Utils/BreakCriticalEdges.cpp b/llvm/lib/Transforms/Utils/BreakCriticalEdges.cpp
index 78f2ab5dffa98..32d3886284a6c 100644
--- a/llvm/lib/Transforms/Utils/BreakCriticalEdges.cpp
+++ b/llvm/lib/Transforms/Utils/BreakCriticalEdges.cpp
@@ -173,7 +173,7 @@ llvm::SplitKnownCriticalEdge(Instruction *TI, unsigned SuccNum,
DestBB->getName() +
"_crit_edge");
// Create our unconditional branch.
- BranchInst *NewBI = BranchInst::Create(DestBB, NewBB);
+ UncondBrInst *NewBI = UncondBrInst::Create(DestBB, NewBB);
NewBI->setDebugLoc(TI->getDebugLoc());
if (auto *LoopMD = TI->getMetadata(LLVMContext::MD_loop))
NewBI->setMetadata(LLVMContext::MD_loop, LoopMD);
diff --git a/llvm/lib/Transforms/Utils/CloneFunction.cpp b/llvm/lib/Transforms/Utils/CloneFunction.cpp
index 192d313b23798..031ce978d21ce 100644
--- a/llvm/lib/Transforms/Utils/CloneFunction.cpp
+++ b/llvm/lib/Transforms/Utils/CloneFunction.cpp
@@ -644,25 +644,23 @@ void PruningFunctionCloner::CloneBlock(
// Finally, clone over the terminator.
const Instruction *OldTI = BB->getTerminator();
bool TerminatorDone = false;
- if (const BranchInst *BI = dyn_cast<BranchInst>(OldTI)) {
- if (BI->isConditional()) {
- // If the condition was a known constant in the callee...
- ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
- // Or is a known constant in the caller...
- if (!Cond) {
- Value *V = VMap.lookup(BI->getCondition());
- Cond = dyn_cast_or_null<ConstantInt>(V);
- }
+ if (const CondBrInst *BI = dyn_cast<CondBrInst>(OldTI)) {
+ // If the condition was a known constant in the callee...
+ ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
+ // Or is a known constant in the caller...
+ if (!Cond) {
+ Value *V = VMap.lookup(BI->getCondition());
+ Cond = dyn_cast_or_null<ConstantInt>(V);
+ }
- // Constant fold to uncond branch!
- if (Cond) {
- BasicBlock *Dest = BI->getSuccessor(!Cond->getZExtValue());
- auto *NewBI = BranchInst::Create(Dest, NewBB);
- NewBI->setDebugLoc(BI->getDebugLoc());
- VMap[OldTI] = NewBI;
- ToClone.push_back(Dest);
- TerminatorDone = true;
- }
+ // Constant fold to uncond branch!
+ if (Cond) {
+ BasicBlock *Dest = BI->getSuccessor(!Cond->getZExtValue());
+ auto *NewBI = UncondBrInst::Create(Dest, NewBB);
+ NewBI->setDebugLoc(BI->getDebugLoc());
+ VMap[OldTI] = NewBI;
+ ToClone.push_back(Dest);
+ TerminatorDone = true;
}
} else if (const SwitchInst *SI = dyn_cast<SwitchInst>(OldTI)) {
// If switching on a value known constant in the caller.
@@ -674,7 +672,7 @@ void PruningFunctionCloner::CloneBlock(
if (Cond) { // Constant fold to uncond branch!
SwitchInst::ConstCaseHandle Case = *SI->findCaseValue(Cond);
BasicBlock *Dest = const_cast<BasicBlock *>(Case.getCaseSuccessor());
- auto *NewBI = BranchInst::Create(Dest, NewBB);
+ auto *NewBI = UncondBrInst::Create(Dest, NewBB);
NewBI->setDebugLoc(SI->getDebugLoc());
VMap[OldTI] = NewBI;
ToClone.push_back(Dest);
@@ -959,13 +957,13 @@ void llvm::CloneAndPruneIntoFromInst(Function *NewFunc, const Function *OldFunc,
// uncond branches, and this code folds them.
Function::iterator I = Begin;
while (I != NewFunc->end()) {
- BranchInst *BI = dyn_cast<BranchInst>(I->getTerminator());
- if (!BI || BI->isConditional()) {
+ UncondBrInst *BI = dyn_cast<UncondBrInst>(I->getTerminator());
+ if (!BI) {
++I;
continue;
}
- BasicBlock *Dest = BI->getSuccessor(0);
+ BasicBlock *Dest = BI->getSuccessor();
if (!Dest->getSinglePredecessor() || Dest->hasAddressTaken()) {
++I;
continue;
diff --git a/llvm/lib/Transforms/Utils/CodeExtractor.cpp b/llvm/lib/Transforms/Utils/CodeExtractor.cpp
index b298a8ae144d8..db4d2011687af 100644
--- a/llvm/lib/Transforms/Utils/CodeExtractor.cpp
+++ b/llvm/lib/Transforms/Utils/CodeExtractor.cpp
@@ -791,7 +791,7 @@ void CodeExtractor::severSplitPHINodesOfExits() {
for (BasicBlock *PredBB : Preds)
if (Blocks.count(PredBB))
PredBB->getTerminator()->replaceUsesOfWith(ExitBB, NewBB);
- BranchInst::Create(ExitBB, NewBB);
+ UncondBrInst::Create(ExitBB, NewBB);
Blocks.insert(NewBB);
}
@@ -1742,7 +1742,7 @@ void CodeExtractor::emitFunctionBody(
}
// Connect newFunction entry block to new header.
- BranchInst *BranchI = BranchInst::Create(header, newFuncRoot);
+ UncondBrInst *BranchI = UncondBrInst::Create(header, newFuncRoot);
applyFirstDebugLoc(oldFunction, Blocks.getArrayRef(), BranchI);
// Store the arguments right after the definition of output value.
@@ -1982,15 +1982,15 @@ CallInst *CodeExtractor::emitReplacerCall(
case 1:
// Only a single destination, change the switch into an unconditional
// branch.
- BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch->getIterator());
+ UncondBrInst::Create(TheSwitch->getSuccessor(1), TheSwitch->getIterator());
TheSwitch->eraseFromParent();
break;
case 2:
// Only two destinations, convert to a condition branch.
// Remark: This also swaps the target branches:
// 0 -> false -> getSuccessor(2); 1 -> true -> getSuccessor(1)
- BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch->getSuccessor(2),
- call, TheSwitch->getIterator());
+ CondBrInst::Create(call, TheSwitch->getSuccessor(1),
+ TheSwitch->getSuccessor(2), TheSwitch->getIterator());
TheSwitch->eraseFromParent();
break;
default:
diff --git a/llvm/lib/Transforms/Utils/ControlFlowUtils.cpp b/llvm/lib/Transforms/Utils/ControlFlowUtils.cpp
index 8de83cc3700cc..cf3bacc08f5a5 100644
--- a/llvm/lib/Transforms/Utils/ControlFlowUtils.cpp
+++ b/llvm/lib/Transforms/Utils/ControlFlowUtils.cpp
@@ -34,27 +34,25 @@ using EdgeDescriptor = ControlFlowHub::BranchDescriptor;
// branch to the FirstGuardBlock.
static Value *redirectToHub(BasicBlock *BB, BasicBlock *Succ0,
BasicBlock *Succ1, BasicBlock *FirstGuardBlock) {
- assert(isa<BranchInst>(BB->getTerminator()) &&
- "Only support branch terminator.");
- auto *Branch = cast<BranchInst>(BB->getTerminator());
- auto *Condition = Branch->isConditional() ? Branch->getCondition() : nullptr;
-
- assert(Succ0 || Succ1);
-
- if (Branch->isUnconditional()) {
+ if (auto *Branch = dyn_cast<UncondBrInst>(BB->getTerminator())) {
assert(Succ0 == Branch->getSuccessor(0));
assert(!Succ1);
+ Branch->setSuccessor(FirstGuardBlock);
+ return nullptr;
+ }
+
+ auto *Branch = cast<CondBrInst>(BB->getTerminator());
+ auto *Condition = Branch->getCondition();
+
+ assert(Succ0 || Succ1);
+ assert(!Succ1 || Succ1 == Branch->getSuccessor(1));
+ if (Succ0 && !Succ1) {
Branch->setSuccessor(0, FirstGuardBlock);
+ } else if (Succ1 && !Succ0) {
+ Branch->setSuccessor(1, FirstGuardBlock);
} else {
- assert(!Succ1 || Succ1 == Branch->getSuccessor(1));
- if (Succ0 && !Succ1) {
- Branch->setSuccessor(0, FirstGuardBlock);
- } else if (Succ1 && !Succ0) {
- Branch->setSuccessor(1, FirstGuardBlock);
- } else {
- Branch->eraseFromParent();
- BranchInst::Create(FirstGuardBlock, BB);
- }
+ Branch->eraseFromParent();
+ UncondBrInst::Create(FirstGuardBlock, BB);
}
return Condition;
@@ -73,11 +71,11 @@ static void setupBranchForGuard(ArrayRef<BasicBlock *> GuardBlocks,
int I = 0;
for (int E = GuardBlocks.size() - 1; I != E; ++I) {
BasicBlock *Out = Outgoing[I];
- BranchInst::Create(Out, GuardBlocks[I + 1], GuardPredicates[Out],
+ CondBrInst::Create(GuardPredicates[Out], Out, GuardBlocks[I + 1],
GuardBlocks[I]);
}
BasicBlock *Out = Outgoing[I];
- BranchInst::Create(Out, Outgoing[I + 1], GuardPredicates[Out],
+ CondBrInst::Create(GuardPredicates[Out], Out, Outgoing[I + 1],
GuardBlocks[I]);
}
diff --git a/llvm/lib/Transforms/Utils/Evaluator.cpp b/llvm/lib/Transforms/Utils/Evaluator.cpp
index b2ee1da143ba7..2b3dfdc4f01f5 100644
--- a/llvm/lib/Transforms/Utils/Evaluator.cpp
+++ b/llvm/lib/Transforms/Utils/Evaluator.cpp
@@ -526,16 +526,13 @@ bool Evaluator::EvaluateBlock(BasicBlock::iterator CurInst, BasicBlock *&NextBB,
} else if (CurInst->isTerminator()) {
LLVM_DEBUG(dbgs() << "Found a terminator instruction.\n");
- if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
- if (BI->isUnconditional()) {
- NextBB = BI->getSuccessor(0);
- } else {
- ConstantInt *Cond =
- dyn_cast<ConstantInt>(getVal(BI->getCondition()));
- if (!Cond) return false; // Cannot determine.
-
- NextBB = BI->getSuccessor(!Cond->getZExtValue());
- }
+ if (UncondBrInst *BI = dyn_cast<UncondBrInst>(CurInst)) {
+ NextBB = BI->getSuccessor(0);
+ } else if (CondBrInst *BI = dyn_cast<CondBrInst>(CurInst)) {
+ ConstantInt *Cond = dyn_cast<ConstantInt>(getVal(BI->getCondition()));
+ if (!Cond)
+ return false; // Cannot determine.
+ NextBB = BI->getSuccessor(!Cond->getZExtValue());
} else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
ConstantInt *Val =
dyn_cast<ConstantInt>(getVal(SI->getCondition()));
diff --git a/llvm/lib/Transforms/Utils/FixIrreducible.cpp b/llvm/lib/Transforms/Utils/FixIrreducible.cpp
index 804af22daa5af..8e6425adc2855 100644
--- a/llvm/lib/Transforms/Utils/FixIrreducible.cpp
+++ b/llvm/lib/Transforms/Utils/FixIrreducible.cpp
@@ -290,7 +290,13 @@ static bool fixIrreducible(Cycle &C, CycleInfo &CI, DominatorTree &DT,
}
for (BasicBlock *P : Predecessors) {
- if (BranchInst *Branch = dyn_cast<BranchInst>(P->getTerminator())) {
+ if (isa<UncondBrInst>(P->getTerminator())) {
+ assert(P->getTerminator()->getSuccessor(0) == Header);
+ CHub.addBranch(P, Header);
+
+ LLVM_DEBUG(dbgs() << "Added internal branch: " << printBasicBlock(P)
+ << " -> " << printBasicBlock(Header) << '\n');
+ } else if (CondBrInst *Branch = dyn_cast<CondBrInst>(P->getTerminator())) {
// Exactly one of the two successors is the header.
BasicBlock *Succ0 = Branch->getSuccessor(0) == Header ? Header : nullptr;
BasicBlock *Succ1 = Succ0 ? nullptr : Header;
@@ -328,12 +334,18 @@ static bool fixIrreducible(Cycle &C, CycleInfo &CI, DominatorTree &DT,
}
for (BasicBlock *P : Predecessors) {
- if (BranchInst *Branch = dyn_cast<BranchInst>(P->getTerminator()); Branch) {
+ if (UncondBrInst *Branch = dyn_cast<UncondBrInst>(P->getTerminator())) {
+ BasicBlock *Succ0 = Branch->getSuccessor();
+ Succ0 = C.contains(Succ0) ? Succ0 : nullptr;
+ CHub.addBranch(P, Succ0);
+
+ LLVM_DEBUG(dbgs() << "Added external branch: " << printBasicBlock(P)
+ << " -> " << printBasicBlock(Succ0) << '\n');
+ } else if (CondBrInst *Branch = dyn_cast<CondBrInst>(P->getTerminator())) {
BasicBlock *Succ0 = Branch->getSuccessor(0);
Succ0 = C.contains(Succ0) ? Succ0 : nullptr;
- BasicBlock *Succ1 =
- Branch->isUnconditional() ? nullptr : Branch->getSuccessor(1);
- Succ1 = Succ1 && C.contains(Succ1) ? Succ1 : nullptr;
+ BasicBlock *Succ1 = Branch->getSuccessor(1);
+ Succ1 = C.contains(Succ1) ? Succ1 : nullptr;
CHub.addBranch(P, Succ0, Succ1);
LLVM_DEBUG(dbgs() << "Added external branch: " << printBasicBlock(P)
diff --git a/llvm/lib/Transforms/Utils/FlattenCFG.cpp b/llvm/lib/Transforms/Utils/FlattenCFG.cpp
index 1208fe182b880..2837fb57b44ac 100644
--- a/llvm/lib/Transforms/Utils/FlattenCFG.cpp
+++ b/llvm/lib/Transforms/Utils/FlattenCFG.cpp
@@ -146,15 +146,9 @@ bool FlattenCFGOpt::FlattenParallelAndOr(BasicBlock *BB, IRBuilder<> &Builder) {
// Check predecessors of \param BB.
SmallPtrSet<BasicBlock *, 16> Preds(llvm::from_range, predecessors(BB));
for (BasicBlock *Pred : Preds) {
- BranchInst *PBI = dyn_cast<BranchInst>(Pred->getTerminator());
-
- // All predecessors should terminate with a branch.
- if (!PBI)
- return false;
-
BasicBlock *PP = Pred->getSinglePredecessor();
- if (PBI->isUnconditional()) {
+ if (isa<UncondBrInst>(Pred->getTerminator())) {
// Case 1: Pred (BB3) is an unconditional block, it should
// have a single predecessor (BB2) that is also a predecessor
// of \param BB (BB4) and should not have address-taken.
@@ -169,7 +163,9 @@ bool FlattenCFGOpt::FlattenParallelAndOr(BasicBlock *BB, IRBuilder<> &Builder) {
}
// Only conditional branches are allowed beyond this point.
- assert(PBI->isConditional());
+ CondBrInst *PBI = dyn_cast<CondBrInst>(Pred->getTerminator());
+ if (!PBI)
+ return false;
// Condition's unique use should be the branch instruction.
Value *PC = PBI->getCondition();
@@ -216,13 +212,9 @@ bool FlattenCFGOpt::FlattenParallelAndOr(BasicBlock *BB, IRBuilder<> &Builder) {
if (!Preds.contains(PS)) {
// Case 2.
LastCondBlock = Pred;
- } else {
- // Case 1
- BranchInst *BPS = dyn_cast<BranchInst>(PS->getTerminator());
- if (BPS && BPS->isUnconditional()) {
- // Case 1: PS(BB3) should be an unconditional branch.
- LastCondBlock = Pred;
- }
+ } else if (isa<UncondBrInst>(PS->getTerminator())) {
+ // Case 1: PS(BB3) should be an unconditional branch.
+ LastCondBlock = Pred;
}
}
@@ -232,16 +224,14 @@ bool FlattenCFGOpt::FlattenParallelAndOr(BasicBlock *BB, IRBuilder<> &Builder) {
Instruction *TBB = LastCondBlock->getTerminator();
BasicBlock *PS1 = TBB->getSuccessor(0);
BasicBlock *PS2 = TBB->getSuccessor(1);
- BranchInst *PBI1 = dyn_cast<BranchInst>(PS1->getTerminator());
- BranchInst *PBI2 = dyn_cast<BranchInst>(PS2->getTerminator());
+ UncondBrInst *PBI1 = dyn_cast<UncondBrInst>(PS1->getTerminator());
+ UncondBrInst *PBI2 = dyn_cast<UncondBrInst>(PS2->getTerminator());
// If PS1 does not jump into PS2, but PS2 jumps into PS1,
// attempt branch inversion.
- if (!PBI1 || !PBI1->isUnconditional() ||
- (PS1->getTerminator()->getSuccessor(0) != PS2)) {
+ if (!PBI1 || (PS1->getTerminator()->getSuccessor(0) != PS2)) {
// Check whether PS2 jumps into PS1.
- if (!PBI2 || !PBI2->isUnconditional() ||
- (PS2->getTerminator()->getSuccessor(0) != PS1))
+ if (!PBI2 || (PS2->getTerminator()->getSuccessor(0) != PS1))
return false;
// Do branch inversion.
@@ -249,7 +239,7 @@ bool FlattenCFGOpt::FlattenParallelAndOr(BasicBlock *BB, IRBuilder<> &Builder) {
bool EverChanged = false;
for (; CurrBlock != FirstCondBlock;
CurrBlock = CurrBlock->getSinglePredecessor()) {
- auto *BI = cast<BranchInst>(CurrBlock->getTerminator());
+ auto *BI = cast<CondBrInst>(CurrBlock->getTerminator());
auto *CI = dyn_cast<CmpInst>(BI->getCondition());
if (!CI)
continue;
@@ -266,7 +256,7 @@ bool FlattenCFGOpt::FlattenParallelAndOr(BasicBlock *BB, IRBuilder<> &Builder) {
}
// PS1 must have a conditional branch.
- if (!PBI1 || !PBI1->isUnconditional())
+ if (!PBI1)
return false;
// PS2 should not contain PHI node.
@@ -276,7 +266,7 @@ bool FlattenCFGOpt::FlattenParallelAndOr(BasicBlock *BB, IRBuilder<> &Builder) {
// Do the transformation.
BasicBlock *CB;
- BranchInst *PBI = cast<BranchInst>(FirstCondBlock->getTerminator());
+ CondBrInst *PBI = cast<CondBrInst>(FirstCondBlock->getTerminator());
bool Iteration = true;
IRBuilder<>::InsertPointGuard Guard(Builder);
Value *PC = PBI->getCondition();
@@ -286,7 +276,7 @@ bool FlattenCFGOpt::FlattenParallelAndOr(BasicBlock *BB, IRBuilder<> &Builder) {
// Delete the conditional branch.
FirstCondBlock->back().eraseFromParent();
FirstCondBlock->splice(FirstCondBlock->end(), CB);
- PBI = cast<BranchInst>(FirstCondBlock->getTerminator());
+ PBI = cast<CondBrInst>(FirstCondBlock->getTerminator());
Value *CC = PBI->getCondition();
// Merge conditions.
Builder.SetInsertPoint(PBI);
diff --git a/llvm/lib/Transforms/Utils/InlineFunction.cpp b/llvm/lib/Transforms/Utils/InlineFunction.cpp
index a779a25f7378e..6dfdeb096023e 100644
--- a/llvm/lib/Transforms/Utils/InlineFunction.cpp
+++ b/llvm/lib/Transforms/Utils/InlineFunction.cpp
@@ -240,7 +240,7 @@ void LandingPadInliningInfo::forwardResume(
BasicBlock *Dest = getInnerResumeDest();
BasicBlock *Src = RI->getParent();
- auto *BI = BranchInst::Create(Dest, Src);
+ auto *BI = UncondBrInst::Create(Dest, Src);
BI->setDebugLoc(RI->getDebugLoc());
// Update the PHIs in the destination. They were inserted in an order which
@@ -3236,7 +3236,8 @@ void llvm::InlineFunctionImpl(CallBase &CB, InlineFunctionInfo &IFI,
// If the call site was an invoke instruction, add a branch to the normal
// destination.
if (InvokeInst *II = dyn_cast<InvokeInst>(&CB)) {
- BranchInst *NewBr = BranchInst::Create(II->getNormalDest(), CB.getIterator());
+ UncondBrInst *NewBr =
+ UncondBrInst::Create(II->getNormalDest(), CB.getIterator());
NewBr->setDebugLoc(Returns[0]->getDebugLoc());
}
@@ -3269,11 +3270,12 @@ void llvm::InlineFunctionImpl(CallBase &CB, InlineFunctionInfo &IFI,
// "starter" and "ender" blocks. How we accomplish this depends on whether
// this is an invoke instruction or a call instruction.
BasicBlock *AfterCallBB;
- BranchInst *CreatedBranchToNormalDest = nullptr;
+ UncondBrInst *CreatedBranchToNormalDest = nullptr;
if (InvokeInst *II = dyn_cast<InvokeInst>(&CB)) {
// Add an unconditional branch to make this look like the CallInst case...
- CreatedBranchToNormalDest = BranchInst::Create(II->getNormalDest(), CB.getIterator());
+ CreatedBranchToNormalDest =
+ UncondBrInst::Create(II->getNormalDest(), CB.getIterator());
// We intend to replace this DebugLoc with another later.
CreatedBranchToNormalDest->setDebugLoc(DebugLoc::getTemporary());
@@ -3301,10 +3303,8 @@ void llvm::InlineFunctionImpl(CallBase &CB, InlineFunctionInfo &IFI,
// Change the branch that used to go to AfterCallBB to branch to the first
// basic block of the inlined function.
//
- Instruction *Br = OrigBB->getTerminator();
- assert(Br && Br->getOpcode() == Instruction::UncondBr &&
- "splitBasicBlock broken!");
- Br->setOperand(0, &*FirstNewBlock);
+ UncondBrInst *Br = cast<UncondBrInst>(OrigBB->getTerminator());
+ Br->setSuccessor(&*FirstNewBlock);
// Now that the function is correct, make it a little bit nicer. In
// particular, move the basic blocks inserted from the end of the function
@@ -3341,7 +3341,7 @@ void llvm::InlineFunctionImpl(CallBase &CB, InlineFunctionInfo &IFI,
// Add a branch to the merge points and remove return instructions.
DebugLoc Loc;
for (ReturnInst *RI : Returns) {
- BranchInst *BI = BranchInst::Create(AfterCallBB, RI->getIterator());
+ UncondBrInst *BI = UncondBrInst::Create(AfterCallBB, RI->getIterator());
Loc = RI->getDebugLoc();
BI->setDebugLoc(Loc);
RI->eraseFromParent();
@@ -3398,8 +3398,7 @@ void llvm::InlineFunctionImpl(CallBase &CB, InlineFunctionInfo &IFI,
// We should always be able to fold the entry block of the function into the
// single predecessor of the block...
- assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
- BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
+ BasicBlock *CalleeEntry = Br->getSuccessor();
// Splice the code entry block into calling block, right before the
// unconditional branch.
diff --git a/llvm/lib/Transforms/Utils/Local.cpp b/llvm/lib/Transforms/Utils/Local.cpp
index bd617cd003a76..416bbb69c4dbe 100644
--- a/llvm/lib/Transforms/Utils/Local.cpp
+++ b/llvm/lib/Transforms/Utils/Local.cpp
@@ -138,9 +138,7 @@ bool llvm::ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions,
IRBuilder<> Builder(T);
// Branch - See if we are conditional jumping on constant
- if (auto *BI = dyn_cast<BranchInst>(T)) {
- if (BI->isUnconditional()) return false; // Can't optimize uncond branch
-
+ if (auto *BI = dyn_cast<CondBrInst>(T)) {
BasicBlock *Dest1 = BI->getSuccessor(0);
BasicBlock *Dest2 = BI->getSuccessor(1);
@@ -154,7 +152,7 @@ bool llvm::ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions,
Dest1->removePredecessor(BI->getParent());
// Replace the conditional branch with an unconditional one.
- BranchInst *NewBI = Builder.CreateBr(Dest1);
+ UncondBrInst *NewBI = Builder.CreateBr(Dest1);
// Transfer the metadata to the new branch instruction.
NewBI->copyMetadata(*BI, {LLVMContext::MD_loop, LLVMContext::MD_dbg,
@@ -178,7 +176,7 @@ bool llvm::ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions,
OldDest->removePredecessor(BB);
// Replace the conditional branch with an unconditional one.
- BranchInst *NewBI = Builder.CreateBr(Destination);
+ UncondBrInst *NewBI = Builder.CreateBr(Destination);
// Transfer the metadata to the new branch instruction.
NewBI->copyMetadata(*BI, {LLVMContext::MD_loop, LLVMContext::MD_dbg,
@@ -317,9 +315,8 @@ bool llvm::ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions,
FirstCase.getCaseValue(), "cond");
// Insert the new branch.
- BranchInst *NewBr = Builder.CreateCondBr(Cond,
- FirstCase.getCaseSuccessor(),
- SI->getDefaultDest());
+ CondBrInst *NewBr = Builder.CreateCondBr(
+ Cond, FirstCase.getCaseSuccessor(), SI->getDefaultDest());
SmallVector<uint32_t> Weights;
if (extractBranchWeights(*SI, Weights) && Weights.size() == 2) {
uint32_t DefWeight = Weights[0];
@@ -1161,7 +1158,7 @@ bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB,
"TryToSimplifyUncondBranchFromEmptyBlock called on entry block!");
// We can't simplify infinite loops.
- BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0);
+ BasicBlock *Succ = cast<UncondBrInst>(BB->getTerminator())->getSuccessor(0);
if (BB == Succ)
return false;
@@ -2602,7 +2599,7 @@ CallInst *llvm::changeToCall(InvokeInst *II, DomTreeUpdater *DTU) {
// Follow the call by a branch to the normal destination.
BasicBlock *NormalDestBB = II->getNormalDest();
- auto *BI = BranchInst::Create(NormalDestBB, II->getIterator());
+ auto *BI = UncondBrInst::Create(NormalDestBB, II->getIterator());
// Although it takes place after the call itself, the new branch is still
// performing part of the control-flow functionality of the invoke, so we use
// II's DebugLoc.
@@ -2787,7 +2784,7 @@ static bool markAliveBlocks(Function &F,
// jump to the normal destination branch.
BasicBlock *NormalDestBB = II->getNormalDest();
BasicBlock *UnwindDestBB = II->getUnwindDest();
- BranchInst::Create(NormalDestBB, II->getIterator());
+ UncondBrInst::Create(NormalDestBB, II->getIterator());
UnwindDestBB->removePredecessor(II->getParent());
II->eraseFromParent();
if (DTU)
diff --git a/llvm/lib/Transforms/Utils/LoopPeel.cpp b/llvm/lib/Transforms/Utils/LoopPeel.cpp
index fa089f8292654..91737b5c30533 100644
--- a/llvm/lib/Transforms/Utils/LoopPeel.cpp
+++ b/llvm/lib/Transforms/Utils/LoopPeel.cpp
@@ -708,8 +708,8 @@ countToEliminateCompares(Loop &L, unsigned MaxPeelCount, ScalarEvolution &SE,
ComputePeelCountMinMax(MinMax);
}
- auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
- if (!BI || BI->isUnconditional())
+ auto *BI = dyn_cast<CondBrInst>(BB->getTerminator());
+ if (!BI)
continue;
// Ignore loop exit condition.
@@ -731,8 +731,8 @@ static bool violatesLegacyMultiExitLoopCheck(Loop *L) {
if (!Latch)
return true;
- BranchInst *LatchBR = dyn_cast<BranchInst>(Latch->getTerminator());
- if (!LatchBR || LatchBR->getNumSuccessors() != 2 || !L->isLoopExiting(Latch))
+ CondBrInst *LatchBR = dyn_cast<CondBrInst>(Latch->getTerminator());
+ if (!LatchBR || !L->isLoopExiting(Latch))
return true;
assert((LatchBR->getSuccessor(0) == L->getHeader() ||
@@ -972,7 +972,7 @@ static void cloneLoopBlocks(
// This is the last iteration and we definitely will go to the exit. Just
// set both successors to InsertBot and let the branch be simplified later.
assert(IterNumber == 0 && "Only peeling a single iteration implemented.");
- auto *LatchTerm = cast<BranchInst>(NewLatch->getTerminator());
+ auto *LatchTerm = cast<CondBrInst>(NewLatch->getTerminator());
LatchTerm->setSuccessor(0, InsertBot);
LatchTerm->setSuccessor(1, InsertBot);
} else {
@@ -1217,7 +1217,7 @@ void llvm::peelLoop(Loop *L, unsigned PeelCount, bool PeelLast, LoopInfo *LI,
NewPreHeader = SplitEdge(PreHeader, Header, &DT, LI);
SCEVExpander Expander(*SE, "loop-peel");
- BranchInst *PreHeaderBR = cast<BranchInst>(PreHeader->getTerminator());
+ Instruction *PreHeaderBR = PreHeader->getTerminator();
Value *BTCValue =
Expander.expandCodeFor(BTC, BTC->getType(), PreHeaderBR);
IRBuilder<> B(PreHeaderBR);
diff --git a/llvm/lib/Transforms/Utils/LoopRotationUtils.cpp b/llvm/lib/Transforms/Utils/LoopRotationUtils.cpp
index 3e11db7dd6e6b..bf236d48f58f9 100644
--- a/llvm/lib/Transforms/Utils/LoopRotationUtils.cpp
+++ b/llvm/lib/Transforms/Utils/LoopRotationUtils.cpp
@@ -183,8 +183,7 @@ static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
// This means that rotating the loop can remove the phi.
static bool profitableToRotateLoopExitingLatch(Loop *L) {
BasicBlock *Header = L->getHeader();
- BranchInst *BI = dyn_cast<BranchInst>(Header->getTerminator());
- assert(BI && BI->isConditional() && "need header with conditional exit");
+ CondBrInst *BI = dyn_cast<CondBrInst>(Header->getTerminator());
BasicBlock *HeaderExit = BI->getSuccessor(0);
if (L->contains(HeaderExit))
HeaderExit = BI->getSuccessor(1);
@@ -200,7 +199,7 @@ static bool profitableToRotateLoopExitingLatch(Loop *L) {
return false;
}
-static void updateBranchWeights(BranchInst &PreHeaderBI, BranchInst &LoopBI,
+static void updateBranchWeights(CondBrInst &PreHeaderBI, CondBrInst &LoopBI,
bool HasConditionalPreHeader,
bool SuccsSwapped) {
MDNode *WeightMD = getBranchWeightMDNode(PreHeaderBI);
@@ -346,8 +345,8 @@ bool LoopRotate::rotateLoop(Loop *L, bool SimplifiedLatch) {
BasicBlock *OrigHeader = L->getHeader();
BasicBlock *OrigLatch = L->getLoopLatch();
- BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
- if (!BI || BI->isUnconditional())
+ CondBrInst *BI = dyn_cast<CondBrInst>(OrigHeader->getTerminator());
+ if (!BI)
return Rotated;
// If the loop header is not one of the loop exiting blocks then
@@ -741,8 +740,7 @@ bool LoopRotate::rotateLoop(Loop *L, bool SimplifiedLatch) {
// then we fold away the cond branch to an uncond branch. This simplifies the
// loop in cases important for nested loops, and it also means we don't have
// to split as many edges.
- BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
- assert(PHBI->isConditional() && "Should be clone of BI condbr!");
+ CondBrInst *PHBI = cast<CondBrInst>(OrigPreheader->getTerminator());
const Value *Cond = PHBI->getCondition();
const bool HasConditionalPreHeader =
!isa<ConstantInt>(Cond) ||
@@ -787,7 +785,7 @@ bool LoopRotate::rotateLoop(Loop *L, bool SimplifiedLatch) {
// We can fold the conditional branch in the preheader, this makes things
// simpler. The first step is to remove the extra edge to the Exit block.
Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
- BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI->getIterator());
+ UncondBrInst *NewBI = UncondBrInst::Create(NewHeader, PHBI->getIterator());
NewBI->setDebugLoc(PHBI->getDebugLoc());
PHBI->eraseFromParent();
@@ -903,16 +901,15 @@ bool LoopRotate::simplifyLoopLatch(Loop *L) {
if (!Latch || Latch->hasAddressTaken())
return false;
- BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
- if (!Jmp || !Jmp->isUnconditional())
+ UncondBrInst *Jmp = dyn_cast<UncondBrInst>(Latch->getTerminator());
+ if (!Jmp)
return false;
BasicBlock *LastExit = Latch->getSinglePredecessor();
if (!LastExit || !L->isLoopExiting(LastExit))
return false;
- BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
- if (!BI)
+ if (!isa<UncondBrInst, CondBrInst>(LastExit->getTerminator()))
return false;
if (!shouldSpeculateInstrs(Latch->begin(), Jmp->getIterator(), L))
diff --git a/llvm/lib/Transforms/Utils/LoopSimplify.cpp b/llvm/lib/Transforms/Utils/LoopSimplify.cpp
index 3b11fa39d01a6..efd43c250af9a 100644
--- a/llvm/lib/Transforms/Utils/LoopSimplify.cpp
+++ b/llvm/lib/Transforms/Utils/LoopSimplify.cpp
@@ -381,7 +381,7 @@ static BasicBlock *insertUniqueBackedgeBlock(Loop *L, BasicBlock *Preheader,
// Create and insert the new backedge block.
BasicBlock *BEBlock = BasicBlock::Create(Header->getContext(),
Header->getName() + ".backedge", F);
- BranchInst *BETerminator = BranchInst::Create(Header, BEBlock);
+ UncondBrInst *BETerminator = UncondBrInst::Create(Header, BEBlock);
BETerminator->setDebugLoc(Header->getFirstNonPHIIt()->getDebugLoc());
LLVM_DEBUG(dbgs() << "LoopSimplify: Inserting unique backedge block "
@@ -518,20 +518,19 @@ static bool simplifyOneLoop(Loop *L, SmallVectorImpl<Loop *> &Worklist,
SmallVector<BasicBlock*, 8> ExitingBlocks;
L->getExitingBlocks(ExitingBlocks);
for (BasicBlock *ExitingBlock : ExitingBlocks)
- if (BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator()))
- if (BI->isConditional()) {
- if (UndefValue *Cond = dyn_cast<UndefValue>(BI->getCondition())) {
+ if (CondBrInst *BI = dyn_cast<CondBrInst>(ExitingBlock->getTerminator())) {
+ if (UndefValue *Cond = dyn_cast<UndefValue>(BI->getCondition())) {
- LLVM_DEBUG(dbgs()
- << "LoopSimplify: Resolving \"br i1 undef\" to exit in "
- << ExitingBlock->getName() << "\n");
+ LLVM_DEBUG(
+ dbgs() << "LoopSimplify: Resolving \"br i1 undef\" to exit in "
+ << ExitingBlock->getName() << "\n");
- BI->setCondition(ConstantInt::get(Cond->getType(),
- !L->contains(BI->getSuccessor(0))));
+ BI->setCondition(ConstantInt::get(Cond->getType(),
+ !L->contains(BI->getSuccessor(0))));
- Changed = true;
- }
+ Changed = true;
}
+ }
// Does the loop already have a preheader? If so, don't insert one.
BasicBlock *Preheader = L->getLoopPreheader();
diff --git a/llvm/lib/Transforms/Utils/LoopUnroll.cpp b/llvm/lib/Transforms/Utils/LoopUnroll.cpp
index c2821f36fb4d2..6a2ccbea996bf 100644
--- a/llvm/lib/Transforms/Utils/LoopUnroll.cpp
+++ b/llvm/lib/Transforms/Utils/LoopUnroll.cpp
@@ -521,7 +521,7 @@ llvm::UnrollLoop(Loop *L, UnrollLoopOptions ULO, LoopInfo *LI,
for (auto *ExitingBlock : ExitingBlocks) {
// The folding code is not prepared to deal with non-branch instructions
// right now.
- auto *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
+ auto *BI = dyn_cast<CondBrInst>(ExitingBlock->getTerminator());
if (!BI)
continue;
@@ -572,12 +572,13 @@ llvm::UnrollLoop(Loop *L, UnrollLoopOptions ULO, LoopInfo *LI,
// (2b) latch is conditional and is an exiting block
// FIXME: The implementation can be extended to work with more complicated
// cases, e.g. loops with multiple latches.
- BranchInst *LatchBI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
+ Instruction *LatchTerm = LatchBlock->getTerminator();
// A conditional branch which exits the loop, which can be optimized to an
// unconditional branch in the unrolled loop in some cases.
bool LatchIsExiting = L->isLoopExiting(LatchBlock);
- if (!LatchBI || (LatchBI->isConditional() && !LatchIsExiting)) {
+ if (!isa<UncondBrInst>(LatchTerm) &&
+ !(isa<CondBrInst>(LatchTerm) && LatchIsExiting)) {
LLVM_DEBUG(
dbgs() << "Can't unroll; a conditional latch must exit the loop");
return LoopUnrollResult::Unmodified;
@@ -952,7 +953,7 @@ llvm::UnrollLoop(Loop *L, UnrollLoopOptions ULO, LoopInfo *LI,
SmallVector<DominatorTree::UpdateType> DTUpdates;
auto SetDest = [&](BasicBlock *Src, bool WillExit, bool ExitOnTrue) {
- auto *Term = cast<BranchInst>(Src->getTerminator());
+ auto *Term = cast<CondBrInst>(Src->getTerminator());
const unsigned Idx = ExitOnTrue ^ WillExit;
BasicBlock *Dest = Term->getSuccessor(Idx);
BasicBlock *DeadSucc = Term->getSuccessor(1-Idx);
@@ -961,7 +962,7 @@ llvm::UnrollLoop(Loop *L, UnrollLoopOptions ULO, LoopInfo *LI,
DeadSucc->removePredecessor(Src, /* KeepOneInputPHIs */ true);
// Replace the conditional branch with an unconditional one.
- auto *BI = BranchInst::Create(Dest, Term->getIterator());
+ auto *BI = UncondBrInst::Create(Dest, Term->getIterator());
BI->setDebugLoc(Term->getDebugLoc());
Term->eraseFromParent();
@@ -1064,13 +1065,12 @@ llvm::UnrollLoop(Loop *L, UnrollLoopOptions ULO, LoopInfo *LI,
// Merge adjacent basic blocks, if possible.
for (BasicBlock *Latch : Latches) {
- BranchInst *Term = dyn_cast<BranchInst>(Latch->getTerminator());
- assert((Term ||
+ assert((isa<UncondBrInst, CondBrInst>(Latch->getTerminator()) ||
(CompletelyUnroll && !LatchIsExiting && Latch == Latches.back())) &&
"Need a branch as terminator, except when fully unrolling with "
"unconditional latch");
- if (Term && Term->isUnconditional()) {
- BasicBlock *Dest = Term->getSuccessor(0);
+ if (auto *Term = dyn_cast<UncondBrInst>(Latch->getTerminator())) {
+ BasicBlock *Dest = Term->getSuccessor();
BasicBlock *Fold = Dest->getUniquePredecessor();
if (MergeBlockIntoPredecessor(Dest, /*DTU=*/DTUToUse, LI,
/*MSSAU=*/nullptr, /*MemDep=*/nullptr,
diff --git a/llvm/lib/Transforms/Utils/LoopUnrollAndJam.cpp b/llvm/lib/Transforms/Utils/LoopUnrollAndJam.cpp
index 1e614bd29ee6e..1a08a3d115d9e 100644
--- a/llvm/lib/Transforms/Utils/LoopUnrollAndJam.cpp
+++ b/llvm/lib/Transforms/Utils/LoopUnrollAndJam.cpp
@@ -293,8 +293,7 @@ llvm::UnrollAndJamLoop(Loop *L, unsigned Count, unsigned TripCount,
BasicBlock *LatchBlock = L->getLoopLatch();
assert(Preheader && "No preheader");
assert(LatchBlock && "No latch block");
- BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
- assert(BI && !BI->isUnconditional());
+ CondBrInst *BI = cast<CondBrInst>(LatchBlock->getTerminator());
bool ContinueOnTrue = L->contains(BI->getSuccessor(0));
BasicBlock *LoopExit = BI->getSuccessor(ContinueOnTrue);
bool SubLoopContinueOnTrue = SubLoop->contains(
@@ -485,10 +484,9 @@ llvm::UnrollAndJamLoop(Loop *L, unsigned Count, unsigned TripCount,
LastValueMap);
// Update ForeBlocks successors and phi nodes
- BranchInst *ForeTerm =
- cast<BranchInst>(ForeBlocksLast.back()->getTerminator());
- assert(ForeTerm->getNumSuccessors() == 1 && "Expecting one successor");
- ForeTerm->setSuccessor(0, SubLoopBlocksFirst[0]);
+ UncondBrInst *ForeTerm =
+ cast<UncondBrInst>(ForeBlocksLast.back()->getTerminator());
+ ForeTerm->setSuccessor(SubLoopBlocksFirst[0]);
if (CompletelyUnroll) {
while (PHINode *Phi = dyn_cast<PHINode>(ForeBlocksFirst[0]->begin())) {
@@ -503,15 +501,14 @@ llvm::UnrollAndJamLoop(Loop *L, unsigned Count, unsigned TripCount,
for (unsigned It = 1; It != Count; It++) {
// Remap ForeBlock successors from previous iteration to this
- BranchInst *ForeTerm =
- cast<BranchInst>(ForeBlocksLast[It - 1]->getTerminator());
- assert(ForeTerm->getNumSuccessors() == 1 && "Expecting one successor");
- ForeTerm->setSuccessor(0, ForeBlocksFirst[It]);
+ UncondBrInst *ForeTerm =
+ cast<UncondBrInst>(ForeBlocksLast[It - 1]->getTerminator());
+ ForeTerm->setSuccessor(ForeBlocksFirst[It]);
}
// Subloop successors and phis
- BranchInst *SubTerm =
- cast<BranchInst>(SubLoopBlocksLast.back()->getTerminator());
+ CondBrInst *SubTerm =
+ cast<CondBrInst>(SubLoopBlocksLast.back()->getTerminator());
SubTerm->setSuccessor(!SubLoopContinueOnTrue, SubLoopBlocksFirst[0]);
SubTerm->setSuccessor(SubLoopContinueOnTrue, AftBlocksFirst[0]);
SubLoopBlocksFirst[0]->replacePhiUsesWith(ForeBlocksLast[0],
@@ -522,9 +519,9 @@ llvm::UnrollAndJamLoop(Loop *L, unsigned Count, unsigned TripCount,
for (unsigned It = 1; It != Count; It++) {
// Replace the conditional branch of the previous iteration subloop with an
// unconditional one to this one
- BranchInst *SubTerm =
- cast<BranchInst>(SubLoopBlocksLast[It - 1]->getTerminator());
- BranchInst::Create(SubLoopBlocksFirst[It], SubTerm->getIterator());
+ CondBrInst *SubTerm =
+ cast<CondBrInst>(SubLoopBlocksLast[It - 1]->getTerminator());
+ UncondBrInst::Create(SubLoopBlocksFirst[It], SubTerm->getIterator());
SubTerm->eraseFromParent();
SubLoopBlocksFirst[It]->replacePhiUsesWith(ForeBlocksLast[It],
@@ -535,9 +532,9 @@ llvm::UnrollAndJamLoop(Loop *L, unsigned Count, unsigned TripCount,
}
// Aft blocks successors and phis
- BranchInst *AftTerm = cast<BranchInst>(AftBlocksLast.back()->getTerminator());
+ CondBrInst *AftTerm = cast<CondBrInst>(AftBlocksLast.back()->getTerminator());
if (CompletelyUnroll) {
- BranchInst::Create(LoopExit, AftTerm->getIterator());
+ UncondBrInst::Create(LoopExit, AftTerm->getIterator());
AftTerm->eraseFromParent();
} else {
AftTerm->setSuccessor(!ContinueOnTrue, ForeBlocksFirst[0]);
@@ -550,9 +547,9 @@ llvm::UnrollAndJamLoop(Loop *L, unsigned Count, unsigned TripCount,
for (unsigned It = 1; It != Count; It++) {
// Replace the conditional branch of the previous iteration subloop with an
// unconditional one to this one
- BranchInst *AftTerm =
- cast<BranchInst>(AftBlocksLast[It - 1]->getTerminator());
- BranchInst::Create(AftBlocksFirst[It], AftTerm->getIterator());
+ CondBrInst *AftTerm =
+ cast<CondBrInst>(AftBlocksLast[It - 1]->getTerminator());
+ UncondBrInst::Create(AftBlocksFirst[It], AftTerm->getIterator());
AftTerm->eraseFromParent();
AftBlocksFirst[It]->replacePhiUsesWith(SubLoopBlocksLast[It],
diff --git a/llvm/lib/Transforms/Utils/LowerGlobalDtors.cpp b/llvm/lib/Transforms/Utils/LowerGlobalDtors.cpp
index df3a2a94b7ddb..d33025adb520c 100644
--- a/llvm/lib/Transforms/Utils/LowerGlobalDtors.cpp
+++ b/llvm/lib/Transforms/Utils/LowerGlobalDtors.cpp
@@ -210,7 +210,7 @@ static bool runImpl(Module &M) {
Value *Res = CallInst::Create(AtExit, Args, "call", EntryBB);
Value *Cmp = new ICmpInst(EntryBB, ICmpInst::ICMP_NE, Res,
Constant::getNullValue(Res->getType()));
- BranchInst::Create(FailBB, RetBB, Cmp, EntryBB);
+ CondBrInst::Create(Cmp, FailBB, RetBB, EntryBB);
// If `__cxa_atexit` hits out-of-memory, trap, so that we don't misbehave.
// This should be very rare, because if the process is running out of
diff --git a/llvm/lib/Transforms/Utils/LowerInvoke.cpp b/llvm/lib/Transforms/Utils/LowerInvoke.cpp
index cecb6629773f1..488745886ec37 100644
--- a/llvm/lib/Transforms/Utils/LowerInvoke.cpp
+++ b/llvm/lib/Transforms/Utils/LowerInvoke.cpp
@@ -60,7 +60,7 @@ static bool runImpl(Function &F) {
II->replaceAllUsesWith(NewCall);
// Insert an unconditional branch to the normal destination.
- BranchInst::Create(II->getNormalDest(), II->getIterator());
+ UncondBrInst::Create(II->getNormalDest(), II->getIterator());
// Remove any PHI node entries from the exception destination.
II->getUnwindDest()->removePredecessor(&BB);
diff --git a/llvm/lib/Transforms/Utils/LowerMemIntrinsics.cpp b/llvm/lib/Transforms/Utils/LowerMemIntrinsics.cpp
index 452de63ca76b8..c934940264c36 100644
--- a/llvm/lib/Transforms/Utils/LowerMemIntrinsics.cpp
+++ b/llvm/lib/Transforms/Utils/LowerMemIntrinsics.cpp
@@ -204,7 +204,7 @@ insertLoopExpansion(Instruction *InsertBefore, Value *Len,
"At least one of the loops must be generated");
BasicBlock *MainLoopBB = nullptr;
- BranchInst *MainLoopBr = nullptr;
+ CondBrInst *MainLoopBr = nullptr;
// Construct the main loop unless we statically known that it is not taken.
if (MayTakeMainLoop) {
@@ -313,7 +313,7 @@ insertLoopExpansion(Instruction *InsertBefore, Value *Len,
LEI.ResidualLoopIP = cast<Instruction>(ResNewIndex);
// Stay in the residual loop until all ResidualUnits are handled.
- BranchInst *BR = ResBuilder.CreateCondBr(
+ CondBrInst *BR = ResBuilder.CreateCondBr(
ResBuilder.CreateICmpULT(ResNewIndex, ResidualUnits), ResidualLoopBB,
PostLoopBB);
@@ -822,9 +822,9 @@ static void createMemMoveLoopUnknownSize(Instruction *InsertBefore,
ResidualLoopPhi->addIncoming(CopyLen, CopyBackwardsBB);
// How to get to the residual:
- BranchInst *BrInst =
- BranchInst::Create(IntermediateBB, ResidualLoopBB,
- SkipResidualCondition, ThenTerm->getIterator());
+ CondBrInst *BrInst =
+ CondBrInst::Create(SkipResidualCondition, IntermediateBB,
+ ResidualLoopBB, ThenTerm->getIterator());
BrInst->setDebugLoc(DbgLoc);
ThenTerm->eraseFromParent();
@@ -852,8 +852,8 @@ static void createMemMoveLoopUnknownSize(Instruction *InsertBefore,
// How to get to the main loop:
Instruction *PredBBTerm = PredBB->getTerminator();
- BranchInst *BrInst = BranchInst::Create(
- ExitBB, MainLoopBB, SkipMainCondition, PredBBTerm->getIterator());
+ CondBrInst *BrInst = CondBrInst::Create(
+ SkipMainCondition, ExitBB, MainLoopBB, PredBBTerm->getIterator());
BrInst->setDebugLoc(DbgLoc);
PredBBTerm->eraseFromParent();
}
@@ -891,8 +891,8 @@ static void createMemMoveLoopUnknownSize(Instruction *InsertBefore,
MainLoopBB);
// getting in or skipping the main loop
- BranchInst *BrInst =
- BranchInst::Create(SuccessorBB, MainLoopBB, SkipMainCondition,
+ CondBrInst *BrInst =
+ CondBrInst::Create(SkipMainCondition, SuccessorBB, MainLoopBB,
CopyFwdBBTerm->getIterator());
BrInst->setDebugLoc(DbgLoc);
CopyFwdBBTerm->eraseFromParent();
diff --git a/llvm/lib/Transforms/Utils/LowerSwitch.cpp b/llvm/lib/Transforms/Utils/LowerSwitch.cpp
index 6acbce884fcc0..9313f313cb02d 100644
--- a/llvm/lib/Transforms/Utils/LowerSwitch.cpp
+++ b/llvm/lib/Transforms/Utils/LowerSwitch.cpp
@@ -191,7 +191,7 @@ BasicBlock *NewLeafBlock(CaseRange &Leaf, Value *Val, ConstantInt *LowerBound,
// Make the conditional branch...
BasicBlock *Succ = Leaf.BB;
- BranchInst::Create(Succ, Default, Comp, NewLeaf);
+ CondBrInst::Create(Comp, Succ, Default, NewLeaf);
// Update the PHI incoming value/block for the default.
for (auto &I : Default->phis()) {
@@ -297,7 +297,7 @@ BasicBlock *SwitchConvert(CaseItr Begin, CaseItr End, ConstantInt *LowerBound,
F->insert(++OrigBlock->getIterator(), NewNode);
Comp->insertInto(NewNode, NewNode->end());
- BranchInst::Create(LBranch, RBranch, Comp, NewNode);
+ CondBrInst::Create(Comp, LBranch, RBranch, NewNode);
return NewNode;
}
@@ -377,7 +377,7 @@ void ProcessSwitchInst(SwitchInst *SI,
// If there is only the default destination, just branch.
if (Cases.empty()) {
- BranchInst::Create(Default, OrigBlock);
+ UncondBrInst::Create(Default, OrigBlock);
// Remove all the references from Default's PHIs to OrigBlock, but one.
FixPhis(Default, OrigBlock, OrigBlock, UnsignedMax);
SI->eraseFromParent();
@@ -492,7 +492,7 @@ void ProcessSwitchInst(SwitchInst *SI,
// If there are no cases left, just branch.
if (Cases.empty()) {
- BranchInst::Create(Default, OrigBlock);
+ UncondBrInst::Create(Default, OrigBlock);
SI->eraseFromParent();
// As all the cases have been replaced with a single branch, only keep
// one entry in the PHI nodes.
@@ -521,7 +521,7 @@ void ProcessSwitchInst(SwitchInst *SI,
FixPhis(Default, OrigBlock, nullptr, UnsignedMax);
// Branch to our shiny new if-then stuff...
- BranchInst::Create(SwitchBlock, OrigBlock);
+ UncondBrInst::Create(SwitchBlock, OrigBlock);
// We are now done with the switch instruction, delete it.
BasicBlock *OldDefault = SI->getDefaultDest();
diff --git a/llvm/lib/Transforms/Utils/MatrixUtils.cpp b/llvm/lib/Transforms/Utils/MatrixUtils.cpp
index cc4326dd1a071..b04003b5090fa 100644
--- a/llvm/lib/Transforms/Utils/MatrixUtils.cpp
+++ b/llvm/lib/Transforms/Utils/MatrixUtils.cpp
@@ -40,8 +40,8 @@ BasicBlock *TileInfo::CreateLoop(BasicBlock *Preheader, BasicBlock *Exit,
Header->getParent(), Exit);
Type *I32Ty = Type::getInt64Ty(Ctx);
- BranchInst::Create(Body, Header);
- BranchInst::Create(Latch, Body);
+ UncondBrInst::Create(Body, Header);
+ UncondBrInst::Create(Latch, Body);
PHINode *IV =
PHINode::Create(I32Ty, 2, Name + ".iv", Header->getTerminator()->getIterator());
IV->addIncoming(ConstantInt::get(I32Ty, 0), Preheader);
@@ -49,7 +49,7 @@ BasicBlock *TileInfo::CreateLoop(BasicBlock *Preheader, BasicBlock *Exit,
B.SetInsertPoint(Latch);
Value *Inc = B.CreateAdd(IV, Step, Name + ".step");
Value *Cond = B.CreateICmpNE(Inc, Bound, Name + ".cond");
- auto *BR = BranchInst::Create(Header, Exit, Cond, Latch);
+ auto *BR = B.CreateCondBr(Cond, Header, Exit);
if (!ProfcheckDisableMetadataFixes) {
assert(Step->getZExtValue() != 0 &&
"Expected a non-zero step size. This is chosen by the pass and "
@@ -60,8 +60,8 @@ BasicBlock *TileInfo::CreateLoop(BasicBlock *Preheader, BasicBlock *Exit,
}
IV->addIncoming(Inc, Latch);
- BranchInst *PreheaderBr = cast<BranchInst>(Preheader->getTerminator());
- BasicBlock *Tmp = PreheaderBr->getSuccessor(0);
+ UncondBrInst *PreheaderBr = cast<UncondBrInst>(Preheader->getTerminator());
+ BasicBlock *Tmp = PreheaderBr->getSuccessor();
PreheaderBr->setSuccessor(0, Header);
DTU.applyUpdatesPermissive({
{DominatorTree::Delete, Preheader, Tmp},
diff --git a/llvm/lib/Transforms/Utils/MisExpect.cpp b/llvm/lib/Transforms/Utils/MisExpect.cpp
index 1585e9e509f89..3adecdcaef0ab 100644
--- a/llvm/lib/Transforms/Utils/MisExpect.cpp
+++ b/llvm/lib/Transforms/Utils/MisExpect.cpp
@@ -73,7 +73,7 @@ static uint32_t getMisExpectTolerance(const LLVMContext &Ctx) {
static const Instruction *getInstCondition(const Instruction *I) {
assert(I != nullptr && "MisExpect target Instruction cannot be nullptr");
const Instruction *Ret = nullptr;
- if (auto *B = dyn_cast<BranchInst>(I)) {
+ if (auto *B = dyn_cast<CondBrInst>(I)) {
Ret = dyn_cast<Instruction>(B->getCondition());
}
// TODO: Find a way to resolve condition location for switches
diff --git a/llvm/lib/Transforms/Utils/PredicateInfo.cpp b/llvm/lib/Transforms/Utils/PredicateInfo.cpp
index a5fff94b60d18..3d3c70522fb55 100644
--- a/llvm/lib/Transforms/Utils/PredicateInfo.cpp
+++ b/llvm/lib/Transforms/Utils/PredicateInfo.cpp
@@ -220,7 +220,7 @@ class PredicateInfoBuilder {
void processAssume(AssumeInst *, BasicBlock *,
SmallVectorImpl<Value *> &OpsToRename);
- void processBranch(BranchInst *, BasicBlock *,
+ void processBranch(CondBrInst *, BasicBlock *,
SmallVectorImpl<Value *> &OpsToRename);
void processSwitch(SwitchInst *, BasicBlock *,
SmallVectorImpl<Value *> &OpsToRename);
@@ -409,7 +409,7 @@ void PredicateInfoBuilder::processAssume(
// Process a block terminating branch, and place relevant operations to be
// renamed into OpsToRename.
void PredicateInfoBuilder::processBranch(
- BranchInst *BI, BasicBlock *BranchBB,
+ CondBrInst *BI, BasicBlock *BranchBB,
SmallVectorImpl<Value *> &OpsToRename) {
BasicBlock *FirstBB = BI->getSuccessor(0);
BasicBlock *SecondBB = BI->getSuccessor(1);
@@ -490,9 +490,7 @@ void PredicateInfoBuilder::buildPredicateInfo() {
if (!DT.isReachableFromEntry(&BB))
continue;
- if (auto *BI = dyn_cast<BranchInst>(BB.getTerminator())) {
- if (!BI->isConditional())
- continue;
+ if (auto *BI = dyn_cast<CondBrInst>(BB.getTerminator())) {
// Can't insert conditional information if they all go to the same place.
if (BI->getSuccessor(0) == BI->getSuccessor(1))
continue;
diff --git a/llvm/lib/Transforms/Utils/ProfileVerify.cpp b/llvm/lib/Transforms/Utils/ProfileVerify.cpp
index ce7bcff9c4e0b..89d2656e60d91 100644
--- a/llvm/lib/Transforms/Utils/ProfileVerify.cpp
+++ b/llvm/lib/Transforms/Utils/ProfileVerify.cpp
@@ -58,7 +58,7 @@ class ProfileInjector {
if (succ_size(&BB) < 2)
return nullptr;
auto *Term = BB.getTerminator();
- return (isa<BranchInst>(Term) || isa<SwitchInst>(Term) ||
+ return (isa<CondBrInst>(Term) || isa<SwitchInst>(Term) ||
isa<IndirectBrInst>(Term) || isa<CallBrInst>(Term))
? Term
: nullptr;
diff --git a/llvm/lib/Transforms/Utils/SCCPSolver.cpp b/llvm/lib/Transforms/Utils/SCCPSolver.cpp
index fd315c14df866..9ba1002533997 100644
--- a/llvm/lib/Transforms/Utils/SCCPSolver.cpp
+++ b/llvm/lib/Transforms/Utils/SCCPSolver.cpp
@@ -393,8 +393,7 @@ bool SCCPSolver::removeNonFeasibleEdges(BasicBlock *BB, DomTreeUpdater &DTU,
// SCCP can only determine non-feasible edges for br, switch and indirectbr.
Instruction *TI = BB->getTerminator();
- assert((isa<BranchInst>(TI) || isa<SwitchInst>(TI) ||
- isa<IndirectBrInst>(TI)) &&
+ assert((isa<UncondBrInst, CondBrInst, SwitchInst, IndirectBrInst>(TI)) &&
"Terminator must be a br, switch or indirectbr");
if (FeasibleSuccessors.size() == 0) {
@@ -426,7 +425,7 @@ bool SCCPSolver::removeNonFeasibleEdges(BasicBlock *BB, DomTreeUpdater &DTU,
Updates.push_back({DominatorTree::Delete, BB, Succ});
}
- Instruction *BI = BranchInst::Create(OnlyFeasibleSuccessor, BB);
+ Instruction *BI = UncondBrInst::Create(OnlyFeasibleSuccessor, BB);
BI->setDebugLoc(TI->getDebugLoc());
TI->eraseFromParent();
DTU.applyUpdatesPermissive(Updates);
@@ -1251,12 +1250,12 @@ bool SCCPInstVisitor::markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
void SCCPInstVisitor::getFeasibleSuccessors(Instruction &TI,
SmallVectorImpl<bool> &Succs) {
Succs.resize(TI.getNumSuccessors());
- if (auto *BI = dyn_cast<BranchInst>(&TI)) {
- if (BI->isUnconditional()) {
- Succs[0] = true;
- return;
- }
+ if (isa<UncondBrInst>(TI)) {
+ Succs[0] = true;
+ return;
+ }
+ if (auto *BI = dyn_cast<CondBrInst>(&TI)) {
const ValueLatticeElement &BCValue = getValueState(BI->getCondition());
ConstantInt *CI = getConstantInt(BCValue, BI->getCondition()->getType());
if (!CI) {
diff --git a/llvm/lib/Transforms/Utils/SimplifyCFG.cpp b/llvm/lib/Transforms/Utils/SimplifyCFG.cpp
index 105ba9151d8f3..326176abb40a6 100644
--- a/llvm/lib/Transforms/Utils/SimplifyCFG.cpp
+++ b/llvm/lib/Transforms/Utils/SimplifyCFG.cpp
@@ -297,7 +297,7 @@ class SimplifyCFGOpt {
bool simplifyIndirectBr(IndirectBrInst *IBI);
bool simplifyUncondBranch(UncondBrInst *BI, IRBuilder<> &Builder);
bool simplifyCondBranch(CondBrInst *BI, IRBuilder<> &Builder);
- bool foldCondBranchOnValueKnownInPredecessor(BranchInst *BI);
+ bool foldCondBranchOnValueKnownInPredecessor(CondBrInst *BI);
bool tryToSimplifyUncondBranchWithICmpInIt(ICmpInst *ICI,
IRBuilder<> &Builder);
@@ -309,11 +309,11 @@ class SimplifyCFGOpt {
Instruction *TI, Instruction *I1,
SmallVectorImpl<Instruction *> &OtherSuccTIs,
ArrayRef<BasicBlock *> UniqueSuccessors);
- bool speculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB);
+ bool speculativelyExecuteBB(CondBrInst *BI, BasicBlock *ThenBB);
bool simplifyTerminatorOnSelect(Instruction *OldTerm, Value *Cond,
BasicBlock *TrueBB, BasicBlock *FalseBB,
uint32_t TrueWeight, uint32_t FalseWeight);
- bool simplifyBranchOnICmpChain(BranchInst *BI, IRBuilder<> &Builder,
+ bool simplifyBranchOnICmpChain(CondBrInst *BI, IRBuilder<> &Builder,
const DataLayout &DL);
bool simplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select);
bool simplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI);
@@ -480,8 +480,8 @@ static bool dominatesMergePoint(
// If this instruction is defined in a block that contains an unconditional
// branch to BB, then it must be in the 'conditional' part of the "if
// statement". If not, it definitely dominates the region.
- BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
- if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB)
+ UncondBrInst *BI = dyn_cast<UncondBrInst>(PBB->getTerminator());
+ if (!BI || BI->getSuccessor() != BB)
return true;
// If we have seen this instruction before, don't count it again.
@@ -849,9 +849,8 @@ static void eraseTerminatorAndDCECond(Instruction *TI,
Instruction *Cond = nullptr;
if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Cond = dyn_cast<Instruction>(SI->getCondition());
- } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
- if (BI->isConditional())
- Cond = dyn_cast<Instruction>(BI->getCondition());
+ } else if (CondBrInst *BI = dyn_cast<CondBrInst>(TI)) {
+ Cond = dyn_cast<Instruction>(BI->getCondition());
} else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
Cond = dyn_cast<Instruction>(IBI->getAddress());
}
@@ -870,8 +869,8 @@ Value *SimplifyCFGOpt::isValueEqualityComparison(Instruction *TI) {
// predecessors unless there is only one predecessor.
if (!SI->getParent()->hasNPredecessorsOrMore(128 / SI->getNumSuccessors()))
CV = SI->getCondition();
- } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
- if (BI->isConditional() && BI->getCondition()->hasOneUse()) {
+ } else if (CondBrInst *BI = dyn_cast<CondBrInst>(TI))
+ if (BI->getCondition()->hasOneUse()) {
if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
if (ICI->isEquality() && getConstantInt(ICI->getOperand(1), DL))
CV = ICI->getOperand(0);
@@ -906,7 +905,7 @@ BasicBlock *SimplifyCFGOpt::getValueEqualityComparisonCases(
return SI->getDefaultDest();
}
- BranchInst *BI = cast<BranchInst>(TI);
+ CondBrInst *BI = cast<CondBrInst>(TI);
Value *Cond = BI->getCondition();
ICmpInst::Predicate Pred;
ConstantInt *C;
@@ -1004,7 +1003,7 @@ bool SimplifyCFGOpt::simplifyEqualityComparisonWithOnlyPredecessor(
if (!valuesOverlap(PredCases, ThisCases))
return false;
- if (isa<BranchInst>(TI)) {
+ if (isa<CondBrInst>(TI)) {
// Okay, one of the successors of this condbr is dead. Convert it to a
// uncond br.
assert(ThisCases.size() == 1 && "Branch can only have one case!");
@@ -1153,7 +1152,7 @@ static void getBranchWeights(Instruction *TI,
// If TI is a conditional eq, the default case is the false case,
// and the corresponding branch-weight data is at index 2. We swap the
// default weight to be the first entry.
- if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
+ if (CondBrInst *BI = dyn_cast<CondBrInst>(TI)) {
assert(Weights.size() == 2);
auto *ICI = dyn_cast<ICmpInst>(BI->getCondition());
if (!ICI)
@@ -1436,7 +1435,7 @@ bool SimplifyCFGOpt::performValueComparisonIntoPredecessorFolding(
// or it won't matter if it's hot. :)
InfLoopBlock =
BasicBlock::Create(BB->getContext(), "infloop", BB->getParent());
- BranchInst::Create(InfLoopBlock, InfLoopBlock);
+ UncondBrInst::Create(InfLoopBlock, InfLoopBlock);
if (DTU)
Updates.push_back(
{DominatorTree::Insert, InfLoopBlock, InfLoopBlock});
@@ -1738,12 +1737,12 @@ static bool areIdenticalUpToCommutativity(const Instruction *I1,
/// will be speculated.
/// \param Invert indicates if speculates FalseBB. Only used in triangle CFG.
static void hoistConditionalLoadsStores(
- BranchInst *BI,
+ CondBrInst *BI,
SmallVectorImpl<Instruction *> &SpeculatedConditionalLoadsStores,
std::optional<bool> Invert, Instruction *Sel) {
auto &Context = BI->getParent()->getContext();
auto *VCondTy = FixedVectorType::get(Type::getInt1Ty(Context), 1);
- auto *Cond = BI->getOperand(0);
+ auto *Cond = BI->getCondition();
// Construct the condition if needed.
BasicBlock *BB = BI->getParent();
Value *Mask = nullptr;
@@ -2053,7 +2052,7 @@ bool SimplifyCFGOpt::hoistSuccIdenticalTerminatorToSwitchOrIf(
SmallVectorImpl<Instruction *> &OtherSuccTIs,
ArrayRef<BasicBlock *> UniqueSuccessors) {
- auto *BI = dyn_cast<BranchInst>(TI);
+ auto *BI = dyn_cast<CondBrInst>(TI);
bool Changed = false;
BasicBlock *TIParent = TI->getParent();
@@ -2437,8 +2436,8 @@ static bool sinkCommonCodeFromPredecessors(BasicBlock *BB,
SmallVector<BasicBlock*,4> UnconditionalPreds;
bool HaveNonUnconditionalPredecessors = false;
for (auto *PredBB : predecessors(BB)) {
- auto *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator());
- if (PredBr && PredBr->isUnconditional())
+ auto *PredBr = dyn_cast<UncondBrInst>(PredBB->getTerminator());
+ if (PredBr)
UnconditionalPreds.push_back(PredBB);
else
HaveNonUnconditionalPredecessors = true;
@@ -2906,7 +2905,7 @@ static void mergeCompatibleInvokesImpl(ArrayRef<InvokeInst *> Invokes,
// to the block with the merged `invoke`.
for (BasicBlock *OrigSuccBB : successors(II->getParent()))
OrigSuccBB->removePredecessor(II->getParent());
- auto *BI = BranchInst::Create(MergedInvoke->getParent(), II->getParent());
+ auto *BI = UncondBrInst::Create(MergedInvoke->getParent(), II->getParent());
// The unconditional branch is part of the replacement for the original
// invoke, so should use its DebugLoc.
BI->setDebugLoc(II->getDebugLoc());
@@ -3145,7 +3144,7 @@ static bool validateAndCostRequiredSelects(BasicBlock *BB, BasicBlock *ThenBB,
return HaveRewritablePHIs;
}
-static bool isProfitableToSpeculate(const BranchInst *BI,
+static bool isProfitableToSpeculate(const CondBrInst *BI,
std::optional<bool> Invert,
const TargetTransformInfo &TTI) {
// If the branch is non-unpredictable, and is predicted to *not* branch to
@@ -3204,7 +3203,7 @@ static bool isProfitableToSpeculate(const BranchInst *BI,
/// \endcode
///
/// \returns true if the conditional block is removed.
-bool SimplifyCFGOpt::speculativelyExecuteBB(BranchInst *BI,
+bool SimplifyCFGOpt::speculativelyExecuteBB(CondBrInst *BI,
BasicBlock *ThenBB) {
if (!Options.SpeculateBlocks)
return false;
@@ -3509,8 +3508,8 @@ static ConstantInt *getKnownValueOnEdge(Value *V, BasicBlock *From,
return nullptr;
// We know the value if the From block branches on it.
- auto *BI = dyn_cast<BranchInst>(From->getTerminator());
- if (BI && BI->isConditional() && BI->getCondition() == V &&
+ auto *BI = dyn_cast<CondBrInst>(From->getTerminator());
+ if (BI && BI->getCondition() == V &&
BI->getSuccessor(0) != BI->getSuccessor(1))
return BI->getSuccessor(0) == To ? ConstantInt::getTrue(BI->getContext())
: ConstantInt::getFalse(BI->getContext());
@@ -3522,7 +3521,7 @@ static ConstantInt *getKnownValueOnEdge(Value *V, BasicBlock *From,
/// value in predecessors (e.g. a phi node in the current block), thread edges
/// from the predecessor to their ultimate destination.
static std::optional<bool>
-foldCondBranchOnValueKnownInPredecessorImpl(BranchInst *BI, DomTreeUpdater *DTU,
+foldCondBranchOnValueKnownInPredecessorImpl(CondBrInst *BI, DomTreeUpdater *DTU,
const DataLayout &DL,
AssumptionCache *AC) {
SmallMapVector<ConstantInt *, SmallSetVector<BasicBlock *, 2>, 2> KnownValues;
@@ -3680,7 +3679,7 @@ foldCondBranchOnValueKnownInPredecessorImpl(BranchInst *BI, DomTreeUpdater *DTU,
InsertPt->cloneDebugInfoFrom(BI);
BB->removePredecessor(EdgeBB);
- BranchInst *EdgeBI = cast<BranchInst>(EdgeBB->getTerminator());
+ UncondBrInst *EdgeBI = cast<UncondBrInst>(EdgeBB->getTerminator());
EdgeBI->setSuccessor(0, RealDest);
EdgeBI->setDebugLoc(BI->getDebugLoc());
@@ -3704,7 +3703,7 @@ foldCondBranchOnValueKnownInPredecessorImpl(BranchInst *BI, DomTreeUpdater *DTU,
return false;
}
-bool SimplifyCFGOpt::foldCondBranchOnValueKnownInPredecessor(BranchInst *BI) {
+bool SimplifyCFGOpt::foldCondBranchOnValueKnownInPredecessor(CondBrInst *BI) {
// Note: If BB is a loop header then there is a risk that threading introduces
// a non-canonical loop by moving a back edge. So we avoid this optimization
// for loop headers if NeedCanonicalLoop is set.
@@ -3747,10 +3746,10 @@ static bool foldTwoEntryPHINode(PHINode *PN, const TargetTransformInfo &TTI,
BasicBlock *DomBlock = DomBI->getParent();
SmallVector<BasicBlock *, 2> IfBlocks;
- llvm::copy_if(
- PN->blocks(), std::back_inserter(IfBlocks), [](BasicBlock *IfBlock) {
- return cast<BranchInst>(IfBlock->getTerminator())->isUnconditional();
- });
+ llvm::copy_if(PN->blocks(), std::back_inserter(IfBlocks),
+ [](BasicBlock *IfBlock) {
+ return isa<UncondBrInst>(IfBlock->getTerminator());
+ });
assert((IfBlocks.size() == 1 || IfBlocks.size() == 2) &&
"Will have either one or two blocks to speculate.");
@@ -3937,7 +3936,7 @@ static Value *createLogicalOp(IRBuilderBase &Builder,
/// Return true if either PBI or BI has branch weight available, and store
/// the weights in {Pred|Succ}{True|False}Weight. If one of PBI and BI does
/// not have branch weight, use 1:1 as its weight.
-static bool extractPredSuccWeights(BranchInst *PBI, BranchInst *BI,
+static bool extractPredSuccWeights(CondBrInst *PBI, CondBrInst *BI,
uint64_t &PredTrueWeight,
uint64_t &PredFalseWeight,
uint64_t &SuccTrueWeight,
@@ -3961,10 +3960,9 @@ static bool extractPredSuccWeights(BranchInst *PBI, BranchInst *BI,
/// that joins the branches' conditions to arrive at the common destination if
/// that would be profitable.
static std::optional<std::tuple<BasicBlock *, Instruction::BinaryOps, bool>>
-shouldFoldCondBranchesToCommonDestination(BranchInst *BI, BranchInst *PBI,
+shouldFoldCondBranchesToCommonDestination(CondBrInst *BI, CondBrInst *PBI,
const TargetTransformInfo *TTI) {
- assert(BI && PBI && BI->isConditional() && PBI->isConditional() &&
- "Both blocks must end with a conditional branches.");
+ assert(BI && PBI && "Both blocks must end with a conditional branches.");
assert(is_contained(predecessors(BI->getParent()), PBI->getParent()) &&
"PredBB must be a predecessor of BB.");
@@ -4146,12 +4144,12 @@ bool llvm::foldBranchToCommonDest(CondBrInst *BI, DomTreeUpdater *DTU,
// With which predecessors will we want to deal with?
SmallVector<BasicBlock *, 8> Preds;
for (BasicBlock *PredBlock : predecessors(BB)) {
- BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
+ CondBrInst *PBI = dyn_cast<CondBrInst>(PredBlock->getTerminator());
// Check that we have two conditional branches. If there is a PHI node in
// the common successor, verify that the same value flows in from both
// blocks.
- if (!PBI || PBI->isUnconditional() || !safeToMergeTerminators(BI, PBI))
+ if (!PBI || !safeToMergeTerminators(BI, PBI))
continue;
// Determine if the two branches share a common destination.
@@ -4199,7 +4197,7 @@ bool llvm::foldBranchToCommonDest(CondBrInst *BI, DomTreeUpdater *DTU,
if (&I == Cond)
continue;
// Ignore the terminator.
- if (isa<BranchInst>(I))
+ if (isa<UncondBrInst, CondBrInst>(I))
continue;
// I must be safe to execute unconditionally.
if (!isSafeToSpeculativelyExecute(&I))
@@ -4416,10 +4414,10 @@ static bool mergeConditionalStoreToAddress(
// OK, we're going to sink the stores to PostBB. The store has to be
// conditional though, so first create the predicate.
- BranchInst *PBranch =
- cast<BranchInst>(PFB->getSinglePredecessor()->getTerminator());
- BranchInst *QBranch =
- cast<BranchInst>(QFB->getSinglePredecessor()->getTerminator());
+ CondBrInst *PBranch =
+ cast<CondBrInst>(PFB->getSinglePredecessor()->getTerminator());
+ CondBrInst *QBranch =
+ cast<CondBrInst>(QFB->getSinglePredecessor()->getTerminator());
Value *PCond = PBranch->getCondition();
Value *QCond = QBranch->getCondition();
@@ -4473,7 +4471,7 @@ static bool mergeConditionalStoreToAddress(
return true;
}
-static bool mergeConditionalStores(BranchInst *PBI, BranchInst *QBI,
+static bool mergeConditionalStores(CondBrInst *PBI, CondBrInst *QBI,
DomTreeUpdater *DTU, const DataLayout &DL,
const TargetTransformInfo &TTI) {
// The intention here is to find diamonds or triangles (see below) where each
@@ -4585,7 +4583,7 @@ static bool mergeConditionalStores(BranchInst *PBI, BranchInst *QBI,
/// If the previous block ended with a widenable branch, determine if reusing
/// the target block is profitable and legal. This will have the effect of
/// "widening" PBI, but doesn't require us to reason about hosting safety.
-static bool tryWidenCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI,
+static bool tryWidenCondBranchToCondBranch(CondBrInst *PBI, CondBrInst *BI,
DomTreeUpdater *DTU) {
// TODO: This can be generalized in two important ways:
// 1) We can allow phi nodes in IfFalseBB and simply reuse all the input
@@ -4642,11 +4640,10 @@ static bool tryWidenCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI,
/// this function tries to simplify it. We know
/// that PBI and BI are both conditional branches, and BI is in one of the
/// successor blocks of PBI - PBI branches to BI.
-static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI,
+static bool SimplifyCondBranchToCondBranch(CondBrInst *PBI, CondBrInst *BI,
DomTreeUpdater *DTU,
const DataLayout &DL,
const TargetTransformInfo &TTI) {
- assert(PBI->isConditional() && BI->isConditional());
BasicBlock *BB = BI->getParent();
// If this block ends with a branch instruction, and if there is a
@@ -4757,7 +4754,7 @@ static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI,
// or it won't matter if it's hot. :)
BasicBlock *InfLoopBlock =
BasicBlock::Create(BB->getContext(), "infloop", BB->getParent());
- BranchInst::Create(InfLoopBlock, InfLoopBlock);
+ UncondBrInst::Create(InfLoopBlock, InfLoopBlock);
if (DTU)
Updates.push_back({DominatorTree::Insert, InfLoopBlock, InfLoopBlock});
OtherDest = InfLoopBlock;
@@ -4912,7 +4909,7 @@ bool SimplifyCFGOpt::simplifyTerminatorOnSelect(Instruction *OldTerm,
} else {
// We found both of the successors we were looking for.
// Create a conditional branch sharing the condition of the select.
- BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
+ CondBrInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
setBranchWeights(*NewBI, {TrueWeight, FalseWeight},
/*IsExpected=*/false, /*ElideAllZero=*/true);
}
@@ -5216,10 +5213,9 @@ bool SimplifyCFGOpt::tryToSimplifyUncondBranchWithICmpSelectInIt(
return true;
}
-/// The specified branch is a conditional branch.
/// Check to see if it is branching on an or/and chain of icmp instructions, and
/// fold it into a switch instruction if so.
-bool SimplifyCFGOpt::simplifyBranchOnICmpChain(BranchInst *BI,
+bool SimplifyCFGOpt::simplifyBranchOnICmpChain(CondBrInst *BI,
IRBuilder<> &Builder,
const DataLayout &DL) {
Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
@@ -5341,7 +5337,7 @@ bool SimplifyCFGOpt::simplifyBranchOnICmpChain(BranchInst *BI,
X = Builder.CreateAdd(X, ConstantInt::get(CompVal->getType(), Offset));
Value *Cond =
Builder.CreateICmp(Pred, X, ConstantInt::get(CompVal->getType(), RHS));
- BranchInst *NewBI = Builder.CreateCondBr(Cond, EdgeBB, DefaultBB);
+ CondBrInst *NewBI = Builder.CreateCondBr(Cond, EdgeBB, DefaultBB);
if (HasProfile)
setBranchWeights(*NewBI, BranchWeights, /*IsExpected=*/false);
// We don't need to update PHI nodes since we don't add any new edges.
@@ -5652,7 +5648,7 @@ static bool mergeCleanupPad(CleanupReturnInst *RI) {
SuccessorCleanupPad->eraseFromParent();
// Now, we simply replace the cleanupret with a branch to the unwind
// destination.
- BranchInst::Create(UnwindDest, RI->getParent());
+ UncondBrInst::Create(UnwindDest, RI->getParent());
RI->eraseFromParent();
return true;
@@ -5726,16 +5722,20 @@ bool SimplifyCFGOpt::simplifyUnreachable(UnreachableInst *UI) {
for (BasicBlock *Predecessor : Preds) {
Instruction *TI = Predecessor->getTerminator();
IRBuilder<> Builder(TI);
- if (auto *BI = dyn_cast<BranchInst>(TI)) {
+ if (isa<UncondBrInst>(TI)) {
+ new UnreachableInst(TI->getContext(), TI->getIterator());
+ TI->eraseFromParent();
+ Changed = true;
+ if (DTU)
+ Updates.push_back({DominatorTree::Delete, Predecessor, BB});
+ } else if (auto *BI = dyn_cast<CondBrInst>(TI)) {
// We could either have a proper unconditional branch,
// or a degenerate conditional branch with matching destinations.
- if (all_of(BI->successors(),
- [BB](auto *Successor) { return Successor == BB; })) {
+ if (BI->getSuccessor(0) == BI->getSuccessor(1)) {
new UnreachableInst(TI->getContext(), TI->getIterator());
TI->eraseFromParent();
Changed = true;
} else {
- assert(BI->isConditional() && "Can't get here with an uncond branch.");
Value* Cond = BI->getCondition();
assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
"The destinations are guaranteed to be different here.");
@@ -6027,7 +6027,7 @@ bool SimplifyCFGOpt::turnSwitchRangeIntoICmp(SwitchInst *SI,
Constant *Offset = ConstantExpr::getNeg(Min);
Constant *NumCases = ConstantInt::get(Offset->getType(),
Max->getValue() - Min->getValue() + 1);
- BranchInst *NewBI;
+ Instruction *NewBI;
if (NumCases->isOneValue()) {
assert(Max->getValue() == Min->getValue());
Value *Cmp = Builder.CreateICmpEQ(SI->getCondition(), Min);
@@ -6045,7 +6045,7 @@ bool SimplifyCFGOpt::turnSwitchRangeIntoICmp(SwitchInst *SI,
}
// Update weight for the newly-created conditional branch.
- if (hasBranchWeightMD(*SI) && NewBI->isConditional()) {
+ if (hasBranchWeightMD(*SI) && isa<CondBrInst>(NewBI)) {
SmallVector<uint64_t, 8> Weights;
getBranchWeights(SI, Weights);
if (Weights.size() == 1 + SI->getNumCases()) {
@@ -6080,7 +6080,7 @@ bool SimplifyCFGOpt::turnSwitchRangeIntoICmp(SwitchInst *SI,
++PreviousEdges;
unsigned E = PreviousEdges - 1;
// Remove all incoming values from OtherDest if OtherDest is unreachable.
- if (NewBI->isUnconditional())
+ if (isa<UncondBrInst>(NewBI))
++E;
for (unsigned I = 0; I != E; ++I)
PHI.removeIncomingValue(SI->getParent());
@@ -6226,11 +6226,11 @@ static PHINode *findPHIForConditionForwarding(ConstantInt *CaseValue,
if (!BB->getSinglePredecessor())
return nullptr; // BB must be dominated by the switch.
- BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
- if (!Branch || !Branch->isUnconditional())
+ UncondBrInst *Branch = dyn_cast<UncondBrInst>(BB->getTerminator());
+ if (!Branch)
return nullptr; // Terminator must be unconditional branch.
- BasicBlock *Succ = Branch->getSuccessor(0);
+ BasicBlock *Succ = Branch->getSuccessor();
for (PHINode &PHI : Succ->phis()) {
int Idx = PHI.getBasicBlockIndex(BB);
@@ -7175,7 +7175,7 @@ static bool shouldUseSwitchConditionAsTableIndex(
/// \endcode
/// Jump threading will then eliminate the second if(cond).
static void reuseTableCompare(
- User *PhiUser, BasicBlock *PhiBlock, BranchInst *RangeCheckBranch,
+ User *PhiUser, BasicBlock *PhiBlock, CondBrInst *RangeCheckBranch,
Constant *DefaultValue,
const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values) {
ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser);
@@ -7459,8 +7459,8 @@ static bool simplifySwitchLookup(SwitchInst *SI, IRBuilder<> &Builder,
BasicBlock *LookupBB = BasicBlock::Create(
Mod.getContext(), "switch.lookup", CommonDest->getParent(), CommonDest);
- BranchInst *RangeCheckBranch = nullptr;
- BranchInst *CondBranch = nullptr;
+ CondBrInst *RangeCheckBranch = nullptr;
+ CondBrInst *CondBranch = nullptr;
Builder.SetInsertPoint(SI);
const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize);
@@ -7816,7 +7816,7 @@ static bool simplifySwitchOfPowersOfTwo(SwitchInst *SI, IRBuilder<> &Builder,
SmallVector<uint32_t> Weights;
auto HasWeights =
!ProfcheckDisableMetadataFixes && extractBranchWeights(*SI, Weights);
- auto *BI = BranchInst::Create(SplitBB, DefaultCaseBB, IsPow2, It);
+ auto *BI = CondBrInst::Create(IsPow2, SplitBB, DefaultCaseBB, It);
if (HasWeights && any_of(Weights, not_equal_to(0))) {
// IsPow2 covers a subset of the cases in which we'd go to the default
// label. The other is those powers of 2 that don't appear in the case
@@ -8012,8 +8012,8 @@ struct EqualBBWrapper {
// FIXME: Relax that the terminator is a BranchInst by checking for equality
// on other kinds of terminators. We decide to only support unconditional
// branches for now for compile time reasons.
- auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
- if (!BI || !BI->isUnconditional())
+ auto *BI = dyn_cast<UncondBrInst>(BB->getTerminator());
+ if (!BI)
return false;
// Avoid blocks that are "address-taken" (blockaddress) or have unusual
@@ -8044,21 +8044,17 @@ template <> struct llvm::DenseMapInfo<const EqualBBWrapper *> {
}
static unsigned getHashValue(const EqualBBWrapper *EBW) {
BasicBlock *BB = EBW->BB;
- BranchInst *BI = cast<BranchInst>(BB->getTerminator());
- assert(BI->isUnconditional() &&
- "Only supporting unconditional branches for now");
- assert(BI->getNumSuccessors() == 1 &&
- "Expected unconditional branches to have one successor");
+ UncondBrInst *BI = cast<UncondBrInst>(BB->getTerminator());
assert(BB->size() == 1 && "Expected just a single branch in the BB");
- // Since we assume the BB is just a single BranchInst with a single
+ // Since we assume the BB is just a single UncondBrInst with a single
// successor, we hash as the BB and the incoming Values of its successor
// PHIs. Initially, we tried to just use the successor BB as the hash, but
// including the incoming PHI values leads to better performance.
// We also tried to build a map from BB -> Succs.IncomingValues ahead of
// time and passing it in EqualBBWrapper, but this slowed down the average
// compile time without having any impact on the worst case compile time.
- BasicBlock *Succ = BI->getSuccessor(0);
+ BasicBlock *Succ = BI->getSuccessor();
auto PhiValsForBB = map_range(Succ->phis(), [&](PHINode &Phi) {
return (*EBW->PhiPredIVs)[&Phi][BB];
});
@@ -8080,15 +8076,13 @@ template <> struct llvm::DenseMapInfo<const EqualBBWrapper *> {
// B.size() here, and we need to check more than just the BranchInsts
// for equality.
- BranchInst *ABI = cast<BranchInst>(A->getTerminator());
- BranchInst *BBI = cast<BranchInst>(B->getTerminator());
- assert(ABI->isUnconditional() && BBI->isUnconditional() &&
- "Only supporting unconditional branches for now");
- if (ABI->getSuccessor(0) != BBI->getSuccessor(0))
+ UncondBrInst *ABI = cast<UncondBrInst>(A->getTerminator());
+ UncondBrInst *BBI = cast<UncondBrInst>(B->getTerminator());
+ if (ABI->getSuccessor() != BBI->getSuccessor())
return false;
// Need to check that PHIs in successor have matching values.
- BasicBlock *Succ = ABI->getSuccessor(0);
+ BasicBlock *Succ = ABI->getSuccessor();
auto IfPhiIVMatch = [&](PHINode &Phi) {
// Replace O(|Pred|) Phi.getIncomingValueForBlock with this O(1) hashmap
// query.
@@ -8354,7 +8348,7 @@ bool SimplifyCFGOpt::simplifyIndirectBr(IndirectBrInst *IBI) {
if (IBI->getNumDestinations() == 1) {
// If the indirectbr has one successor, change it to a direct branch.
- BranchInst::Create(IBI->getDestination(0), IBI->getIterator());
+ UncondBrInst::Create(IBI->getDestination(0), IBI->getIterator());
eraseTerminatorAndDCECond(IBI);
return true;
}
@@ -8392,7 +8386,7 @@ bool SimplifyCFGOpt::simplifyIndirectBr(IndirectBrInst *IBI) {
/// TODO - This transformation could remove entries from a phi in the target
/// block when the inputs in the phi are the same for the two blocks being
/// merged. In some cases, this could result in removal of the PHI entirely.
-static bool tryToMergeLandingPad(LandingPadInst *LPad, BranchInst *BI,
+static bool tryToMergeLandingPad(LandingPadInst *LPad, UncondBrInst *BI,
BasicBlock *BB, DomTreeUpdater *DTU) {
auto Succ = BB->getUniqueSuccessor();
assert(Succ);
@@ -8409,7 +8403,7 @@ static bool tryToMergeLandingPad(LandingPadInst *LPad, BranchInst *BI,
if (!LPad2 || !LPad2->isIdenticalTo(LPad))
continue;
++I;
- BranchInst *BI2 = dyn_cast<BranchInst>(I);
+ UncondBrInst *BI2 = dyn_cast<UncondBrInst>(I);
if (!BI2 || !BI2->isIdenticalTo(BI))
continue;
@@ -8524,24 +8518,24 @@ static BasicBlock *allPredecessorsComeFromSameSource(BasicBlock *BB) {
/// bb4:
/// ...
/// NOTE: %cond2 always dominates the terminator of bb0.
-static bool mergeNestedCondBranch(BranchInst *BI, DomTreeUpdater *DTU) {
+static bool mergeNestedCondBranch(CondBrInst *BI, DomTreeUpdater *DTU) {
BasicBlock *BB = BI->getParent();
BasicBlock *BB1 = BI->getSuccessor(0);
BasicBlock *BB2 = BI->getSuccessor(1);
- auto IsSimpleSuccessor = [BB](BasicBlock *Succ, BranchInst *&SuccBI) {
+ auto IsSimpleSuccessor = [BB](BasicBlock *Succ, CondBrInst *&SuccBI) {
if (Succ == BB)
return false;
if (&Succ->front() != Succ->getTerminator())
return false;
- SuccBI = dyn_cast<BranchInst>(Succ->getTerminator());
- if (!SuccBI || !SuccBI->isConditional())
+ SuccBI = dyn_cast<CondBrInst>(Succ->getTerminator());
+ if (!SuccBI)
return false;
BasicBlock *Succ1 = SuccBI->getSuccessor(0);
BasicBlock *Succ2 = SuccBI->getSuccessor(1);
return Succ1 != Succ && Succ2 != Succ && Succ1 != BB && Succ2 != BB &&
!isa<PHINode>(Succ1->front()) && !isa<PHINode>(Succ2->front());
};
- BranchInst *BB1BI, *BB2BI;
+ CondBrInst *BB1BI, *BB2BI;
if (!IsSimpleSuccessor(BB1, BB1BI) || !IsSimpleSuccessor(BB2, BB2BI))
return false;
@@ -8715,16 +8709,16 @@ bool SimplifyCFGOpt::simplifyCondBranch(CondBrInst *BI, IRBuilder<> &Builder) {
// Scan predecessor blocks for conditional branches.
for (BasicBlock *Pred : predecessors(BB))
- if (BranchInst *PBI = dyn_cast<BranchInst>(Pred->getTerminator()))
- if (PBI != BI && PBI->isConditional())
+ if (CondBrInst *PBI = dyn_cast<CondBrInst>(Pred->getTerminator()))
+ if (PBI != BI)
if (SimplifyCondBranchToCondBranch(PBI, BI, DTU, DL, TTI))
return requestResimplify();
// Look for diamond patterns.
if (MergeCondStores)
if (BasicBlock *PrevBB = allPredecessorsComeFromSameSource(BB))
- if (BranchInst *PBI = dyn_cast<BranchInst>(PrevBB->getTerminator()))
- if (PBI != BI && PBI->isConditional())
+ if (CondBrInst *PBI = dyn_cast<CondBrInst>(PrevBB->getTerminator()))
+ if (PBI != BI)
if (mergeConditionalStores(PBI, BI, DTU, DL, TTI))
return requestResimplify();
@@ -8883,26 +8877,28 @@ static bool removeUndefIntroducingPredecessor(BasicBlock *BB,
BasicBlock *Predecessor = PHI.getIncomingBlock(i);
Instruction *T = Predecessor->getTerminator();
IRBuilder<> Builder(T);
- if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
+ if (isa<UncondBrInst>(T)) {
BB->removePredecessor(Predecessor);
- // Turn unconditional branches into unreachables and remove the dead
- // destination from conditional branches.
- if (BI->isUnconditional())
- Builder.CreateUnreachable();
- else {
- // Preserve guarding condition in assume, because it might not be
- // inferrable from any dominating condition.
- Value *Cond = BI->getCondition();
- CallInst *Assumption;
- if (BI->getSuccessor(0) == BB)
- Assumption = Builder.CreateAssumption(Builder.CreateNot(Cond));
- else
- Assumption = Builder.CreateAssumption(Cond);
- if (AC)
- AC->registerAssumption(cast<AssumeInst>(Assumption));
- Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1)
- : BI->getSuccessor(0));
- }
+ // Turn unconditional branches into unreachables.
+ Builder.CreateUnreachable();
+ T->eraseFromParent();
+ if (DTU)
+ DTU->applyUpdates({{DominatorTree::Delete, Predecessor, BB}});
+ return true;
+ } else if (CondBrInst *BI = dyn_cast<CondBrInst>(T)) {
+ BB->removePredecessor(Predecessor);
+ // Preserve guarding condition in assume, because it might not be
+ // inferrable from any dominating condition.
+ Value *Cond = BI->getCondition();
+ CallInst *Assumption;
+ if (BI->getSuccessor(0) == BB)
+ Assumption = Builder.CreateAssumption(Builder.CreateNot(Cond));
+ else
+ Assumption = Builder.CreateAssumption(Cond);
+ if (AC)
+ AC->registerAssumption(cast<AssumeInst>(Assumption));
+ Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1)
+ : BI->getSuccessor(0));
BI->eraseFromParent();
if (DTU)
DTU->applyUpdates({{DominatorTree::Delete, Predecessor, BB}});
diff --git a/llvm/lib/Transforms/Utils/SimplifyIndVar.cpp b/llvm/lib/Transforms/Utils/SimplifyIndVar.cpp
index 792c1ac31c2ba..5154b7b290ba0 100644
--- a/llvm/lib/Transforms/Utils/SimplifyIndVar.cpp
+++ b/llvm/lib/Transforms/Utils/SimplifyIndVar.cpp
@@ -2231,8 +2231,8 @@ void WidenIV::calculatePostIncRange(Instruction *NarrowDef,
auto *TI = BB->getTerminator();
UpdateRangeFromGuards(TI);
- auto *BI = dyn_cast<BranchInst>(TI);
- if (!BI || !BI->isConditional())
+ auto *BI = dyn_cast<CondBrInst>(TI);
+ if (!BI)
continue;
auto *TrueSuccessor = BI->getSuccessor(0);
diff --git a/llvm/lib/Transforms/Utils/UnifyFunctionExitNodes.cpp b/llvm/lib/Transforms/Utils/UnifyFunctionExitNodes.cpp
index 68d0684a64d68..17fa30e436c2f 100644
--- a/llvm/lib/Transforms/Utils/UnifyFunctionExitNodes.cpp
+++ b/llvm/lib/Transforms/Utils/UnifyFunctionExitNodes.cpp
@@ -36,7 +36,7 @@ bool unifyUnreachableBlocks(Function &F) {
for (BasicBlock *BB : UnreachableBlocks) {
BB->back().eraseFromParent(); // Remove the unreachable inst.
- BranchInst::Create(UnreachableBlock, BB);
+ UncondBrInst::Create(UnreachableBlock, BB);
}
return true;
@@ -78,7 +78,7 @@ bool unifyReturnBlocks(Function &F) {
PN->addIncoming(BB->getTerminator()->getOperand(0), BB);
BB->back().eraseFromParent(); // Remove the return insn
- BranchInst::Create(NewRetBlock, BB);
+ UncondBrInst::Create(NewRetBlock, BB);
}
return true;
diff --git a/llvm/lib/Transforms/Utils/UnifyLoopExits.cpp b/llvm/lib/Transforms/Utils/UnifyLoopExits.cpp
index 21baf4ec1d032..6947cb4f92723 100644
--- a/llvm/lib/Transforms/Utils/UnifyLoopExits.cpp
+++ b/llvm/lib/Transforms/Utils/UnifyLoopExits.cpp
@@ -167,12 +167,18 @@ static bool unifyLoopExits(DominatorTree &DT, LoopInfo &LI, Loop *L) {
for (unsigned I = 0; I < ExitingBlocks.size(); ++I) {
BasicBlock *BB = ExitingBlocks[I];
- if (BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator())) {
+ if (UncondBrInst *Branch = dyn_cast<UncondBrInst>(BB->getTerminator())) {
BasicBlock *Succ0 = Branch->getSuccessor(0);
Succ0 = L->contains(Succ0) ? nullptr : Succ0;
+ CHub.addBranch(BB, Succ0);
- BasicBlock *Succ1 =
- Branch->isUnconditional() ? nullptr : Branch->getSuccessor(1);
+ LLVM_DEBUG(dbgs() << "Added extiting branch: " << printBasicBlock(BB)
+ << " -> " << printBasicBlock(Succ0) << '\n');
+ } else if (CondBrInst *Branch = dyn_cast<CondBrInst>(BB->getTerminator())) {
+ BasicBlock *Succ0 = Branch->getSuccessor(0);
+ Succ0 = L->contains(Succ0) ? nullptr : Succ0;
+
+ BasicBlock *Succ1 = Branch->getSuccessor(1);
Succ1 = L->contains(Succ1) ? nullptr : Succ1;
CHub.addBranch(BB, Succ0, Succ1);
diff --git a/llvm/unittests/Transforms/Utils/LocalTest.cpp b/llvm/unittests/Transforms/Utils/LocalTest.cpp
index 896e1de8b32f3..8ceeacf132da1 100644
--- a/llvm/unittests/Transforms/Utils/LocalTest.cpp
+++ b/llvm/unittests/Transforms/Utils/LocalTest.cpp
@@ -39,10 +39,10 @@ TEST(Local, RecursivelyDeleteDeadPHINodes) {
builder.SetInsertPoint(bb0);
PHINode *phi = builder.CreatePHI(Type::getInt32Ty(C), 2);
- BranchInst *br0 = builder.CreateCondBr(builder.getTrue(), bb0, bb1);
+ CondBrInst *br0 = builder.CreateCondBr(builder.getTrue(), bb0, bb1);
builder.SetInsertPoint(bb1);
- BranchInst *br1 = builder.CreateBr(bb0);
+ UncondBrInst *br1 = builder.CreateBr(bb0);
phi->addIncoming(phi, bb0);
phi->addIncoming(phi, bb1);
@@ -80,7 +80,7 @@ TEST(Local, RemoveDuplicatePHINodes) {
GlobalValue::ExternalLinkage, "F"));
BasicBlock *Entry(BasicBlock::Create(C, "", F.get()));
BasicBlock *BB(BasicBlock::Create(C, "", F.get()));
- BranchInst::Create(BB, Entry);
+ UncondBrInst::Create(BB, Entry);
B.SetInsertPoint(BB);
@@ -100,7 +100,7 @@ TEST(Local, RemoveDuplicatePHINodes) {
P1->addIncoming(P3, BB);
P2->addIncoming(P4, BB);
- BranchInst::Create(BB, BB);
+ UncondBrInst::Create(BB, BB);
// Verify that we can eliminate PHIs that become duplicates after chaning PHIs
// downstream.
@@ -219,8 +219,7 @@ TEST(Local, MergeBasicBlockIntoOnlyPred) {
BasicBlock *SinglePred = BB->getSinglePredecessor();
if (!SinglePred || SinglePred == BB || BB->hasAddressTaken())
continue;
- BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
- if (Term && !Term->isConditional())
+ if (isa<UncondBrInst>(SinglePred->getTerminator()))
MergeBasicBlockIntoOnlyPred(BB, &DTU);
}
if (DTU.hasDomTree()) {
diff --git a/llvm/unittests/Transforms/Utils/LoopUtilsTest.cpp b/llvm/unittests/Transforms/Utils/LoopUtilsTest.cpp
index a839d75cd6235..4e51061f1cdec 100644
--- a/llvm/unittests/Transforms/Utils/LoopUtilsTest.cpp
+++ b/llvm/unittests/Transforms/Utils/LoopUtilsTest.cpp
@@ -89,9 +89,8 @@ TEST(LoopUtils, DeleteDeadLoopNest) {
Function::iterator FI = F.begin();
BasicBlock *Entry = &*(FI++);
assert(Entry->getName() == "entry" && "Expecting BasicBlock entry");
- const BranchInst *BI = dyn_cast<BranchInst>(Entry->getTerminator());
+ const UncondBrInst *BI = dyn_cast<UncondBrInst>(Entry->getTerminator());
assert(BI && "Expecting valid branch instruction");
- EXPECT_EQ(BI->getNumSuccessors(), (unsigned)1);
EXPECT_EQ(BI->getSuccessor(0)->getName(), "for.end");
});
}
diff --git a/llvm/unittests/Transforms/Utils/ProfDataUtilTest.cpp b/llvm/unittests/Transforms/Utils/ProfDataUtilTest.cpp
index 46a3ecd5d3aa3..e345c07a8c3d2 100644
--- a/llvm/unittests/Transforms/Utils/ProfDataUtilTest.cpp
+++ b/llvm/unittests/Transforms/Utils/ProfDataUtilTest.cpp
@@ -44,7 +44,7 @@ define void @foo(i1 %cond0) {
Function *F = M->getFunction("foo");
auto &Entry = F->getEntryBlock();
auto &I = Entry.front();
- auto *Branch = dyn_cast<BranchInst>(&I);
+ auto *Branch = dyn_cast<CondBrInst>(&I);
EXPECT_NE(nullptr, Branch);
auto *ProfileData = Branch->getMetadata(LLVMContext::MD_prof);
EXPECT_NE(ProfileData, nullptr);
@@ -72,7 +72,7 @@ define void @foo(i1 %cond0) {
Function *F = M->getFunction("foo");
auto &Entry = F->getEntryBlock();
auto &I = Entry.front();
- auto *Branch = dyn_cast<BranchInst>(&I);
+ auto *Branch = dyn_cast<CondBrInst>(&I);
EXPECT_NE(nullptr, Branch);
auto *ProfileData = Branch->getMetadata(LLVMContext::MD_prof);
EXPECT_EQ(ProfileData, nullptr);
diff --git a/llvm/unittests/Transforms/Utils/ScalarEvolutionExpanderTest.cpp b/llvm/unittests/Transforms/Utils/ScalarEvolutionExpanderTest.cpp
index e97d00dda7f8c..268b9313da882 100644
--- a/llvm/unittests/Transforms/Utils/ScalarEvolutionExpanderTest.cpp
+++ b/llvm/unittests/Transforms/Utils/ScalarEvolutionExpanderTest.cpp
@@ -82,7 +82,7 @@ TEST_F(ScalarEvolutionExpanderTest, ExpandPtrTypeSCEV) {
BasicBlock *EntryBB = BasicBlock::Create(Context, "entry", F);
BasicBlock *LoopBB = BasicBlock::Create(Context, "loop", F);
BasicBlock *ExitBB = BasicBlock::Create(Context, "exit", F);
- BranchInst::Create(LoopBB, EntryBB);
+ UncondBrInst::Create(LoopBB, EntryBB);
ReturnInst::Create(Context, nullptr, ExitBB);
// loop: ; preds = %loop, %entry
@@ -95,8 +95,8 @@ TEST_F(ScalarEvolutionExpanderTest, ExpandPtrTypeSCEV) {
// br i1 undef, label %loop, label %exit
const DataLayout &DL = F->getDataLayout();
- BranchInst *Br = BranchInst::Create(
- LoopBB, ExitBB, PoisonValue::get(Type::getInt1Ty(Context)), LoopBB);
+ CondBrInst *Br = CondBrInst::Create(
+ PoisonValue::get(Type::getInt1Ty(Context)), LoopBB, ExitBB, LoopBB);
AllocaInst *Alloca = new AllocaInst(I32Ty, DL.getAllocaAddrSpace(), "alloca",
Br->getIterator());
ConstantInt *Ci32 = ConstantInt::get(Context, APInt(32, 1));
More information about the llvm-commits
mailing list