1 //===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Peephole optimize the CFG.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Transforms/Utils/Local.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SetVector.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Analysis/ConstantFolding.h"
22 #include "llvm/Analysis/InstructionSimplify.h"
23 #include "llvm/Analysis/TargetTransformInfo.h"
24 #include "llvm/Analysis/ValueTracking.h"
25 #include "llvm/IR/CFG.h"
26 #include "llvm/IR/ConstantRange.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/GlobalVariable.h"
31 #include "llvm/IR/IRBuilder.h"
32 #include "llvm/IR/Instructions.h"
33 #include "llvm/IR/IntrinsicInst.h"
34 #include "llvm/IR/LLVMContext.h"
35 #include "llvm/IR/MDBuilder.h"
36 #include "llvm/IR/Metadata.h"
37 #include "llvm/IR/Module.h"
38 #include "llvm/IR/NoFolder.h"
39 #include "llvm/IR/Operator.h"
40 #include "llvm/IR/PatternMatch.h"
41 #include "llvm/IR/Type.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
50 using namespace PatternMatch;
52 #define DEBUG_TYPE "simplifycfg"
54 static cl::opt<unsigned>
55 PHINodeFoldingThreshold("phi-node-folding-threshold", cl::Hidden, cl::init(1),
56 cl::desc("Control the amount of phi node folding to perform (default = 1)"));
59 DupRet("simplifycfg-dup-ret", cl::Hidden, cl::init(false),
60 cl::desc("Duplicate return instructions into unconditional branches"));
63 SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
64 cl::desc("Sink common instructions down to the end block"));
66 static cl::opt<bool> HoistCondStores(
67 "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true),
68 cl::desc("Hoist conditional stores if an unconditional store precedes"));
70 STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
71 STATISTIC(NumLookupTables, "Number of switch instructions turned into lookup tables");
72 STATISTIC(NumLookupTablesHoles, "Number of switch instructions turned into lookup tables (holes checked)");
73 STATISTIC(NumSinkCommons, "Number of common instructions sunk down to the end block");
74 STATISTIC(NumSpeculations, "Number of speculative executed instructions");
77 /// ValueEqualityComparisonCase - Represents a case of a switch.
78 struct ValueEqualityComparisonCase {
82 ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
83 : Value(Value), Dest(Dest) {}
85 bool operator<(ValueEqualityComparisonCase RHS) const {
86 // Comparing pointers is ok as we only rely on the order for uniquing.
87 return Value < RHS.Value;
90 bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
93 class SimplifyCFGOpt {
94 const TargetTransformInfo &TTI;
95 const DataLayout *const DL;
96 Value *isValueEqualityComparison(TerminatorInst *TI);
97 BasicBlock *GetValueEqualityComparisonCases(TerminatorInst *TI,
98 std::vector<ValueEqualityComparisonCase> &Cases);
99 bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
101 IRBuilder<> &Builder);
102 bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
103 IRBuilder<> &Builder);
105 bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder);
106 bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
107 bool SimplifyUnreachable(UnreachableInst *UI);
108 bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
109 bool SimplifyIndirectBr(IndirectBrInst *IBI);
110 bool SimplifyUncondBranch(BranchInst *BI, IRBuilder <> &Builder);
111 bool SimplifyCondBranch(BranchInst *BI, IRBuilder <>&Builder);
114 SimplifyCFGOpt(const TargetTransformInfo &TTI, const DataLayout *DL)
115 : TTI(TTI), DL(DL) {}
116 bool run(BasicBlock *BB);
120 /// SafeToMergeTerminators - Return true if it is safe to merge these two
121 /// terminator instructions together.
123 static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
124 if (SI1 == SI2) return false; // Can't merge with self!
126 // It is not safe to merge these two switch instructions if they have a common
127 // successor, and if that successor has a PHI node, and if *that* PHI node has
128 // conflicting incoming values from the two switch blocks.
129 BasicBlock *SI1BB = SI1->getParent();
130 BasicBlock *SI2BB = SI2->getParent();
131 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
133 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
134 if (SI1Succs.count(*I))
135 for (BasicBlock::iterator BBI = (*I)->begin();
136 isa<PHINode>(BBI); ++BBI) {
137 PHINode *PN = cast<PHINode>(BBI);
138 if (PN->getIncomingValueForBlock(SI1BB) !=
139 PN->getIncomingValueForBlock(SI2BB))
146 /// isProfitableToFoldUnconditional - Return true if it is safe and profitable
147 /// to merge these two terminator instructions together, where SI1 is an
148 /// unconditional branch. PhiNodes will store all PHI nodes in common
151 static bool isProfitableToFoldUnconditional(BranchInst *SI1,
154 SmallVectorImpl<PHINode*> &PhiNodes) {
155 if (SI1 == SI2) return false; // Can't merge with self!
156 assert(SI1->isUnconditional() && SI2->isConditional());
158 // We fold the unconditional branch if we can easily update all PHI nodes in
159 // common successors:
160 // 1> We have a constant incoming value for the conditional branch;
161 // 2> We have "Cond" as the incoming value for the unconditional branch;
162 // 3> SI2->getCondition() and Cond have same operands.
163 CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition());
164 if (!Ci2) return false;
165 if (!(Cond->getOperand(0) == Ci2->getOperand(0) &&
166 Cond->getOperand(1) == Ci2->getOperand(1)) &&
167 !(Cond->getOperand(0) == Ci2->getOperand(1) &&
168 Cond->getOperand(1) == Ci2->getOperand(0)))
171 BasicBlock *SI1BB = SI1->getParent();
172 BasicBlock *SI2BB = SI2->getParent();
173 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
174 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
175 if (SI1Succs.count(*I))
176 for (BasicBlock::iterator BBI = (*I)->begin();
177 isa<PHINode>(BBI); ++BBI) {
178 PHINode *PN = cast<PHINode>(BBI);
179 if (PN->getIncomingValueForBlock(SI1BB) != Cond ||
180 !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB)))
182 PhiNodes.push_back(PN);
187 /// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will
188 /// now be entries in it from the 'NewPred' block. The values that will be
189 /// flowing into the PHI nodes will be the same as those coming in from
190 /// ExistPred, an existing predecessor of Succ.
191 static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
192 BasicBlock *ExistPred) {
193 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
196 for (BasicBlock::iterator I = Succ->begin();
197 (PN = dyn_cast<PHINode>(I)); ++I)
198 PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
201 /// ComputeSpeculationCost - Compute an abstract "cost" of speculating the
202 /// given instruction, which is assumed to be safe to speculate. 1 means
203 /// cheap, 2 means less cheap, and UINT_MAX means prohibitively expensive.
204 static unsigned ComputeSpeculationCost(const User *I) {
205 assert(isSafeToSpeculativelyExecute(I) &&
206 "Instruction is not safe to speculatively execute!");
207 switch (Operator::getOpcode(I)) {
209 // In doubt, be conservative.
211 case Instruction::GetElementPtr:
212 // GEPs are cheap if all indices are constant.
213 if (!cast<GEPOperator>(I)->hasAllConstantIndices())
216 case Instruction::ExtractValue:
217 case Instruction::Load:
218 case Instruction::Add:
219 case Instruction::Sub:
220 case Instruction::And:
221 case Instruction::Or:
222 case Instruction::Xor:
223 case Instruction::Shl:
224 case Instruction::LShr:
225 case Instruction::AShr:
226 case Instruction::ICmp:
227 case Instruction::Trunc:
228 case Instruction::ZExt:
229 case Instruction::SExt:
230 case Instruction::BitCast:
231 case Instruction::ExtractElement:
232 case Instruction::InsertElement:
233 return 1; // These are all cheap.
235 case Instruction::Call:
236 case Instruction::Select:
241 /// DominatesMergePoint - If we have a merge point of an "if condition" as
242 /// accepted above, return true if the specified value dominates the block. We
243 /// don't handle the true generality of domination here, just a special case
244 /// which works well enough for us.
246 /// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
247 /// see if V (which must be an instruction) and its recursive operands
248 /// that do not dominate BB have a combined cost lower than CostRemaining and
249 /// are non-trapping. If both are true, the instruction is inserted into the
250 /// set and true is returned.
252 /// The cost for most non-trapping instructions is defined as 1 except for
253 /// Select whose cost is 2.
255 /// After this function returns, CostRemaining is decreased by the cost of
256 /// V plus its non-dominating operands. If that cost is greater than
257 /// CostRemaining, false is returned and CostRemaining is undefined.
258 static bool DominatesMergePoint(Value *V, BasicBlock *BB,
259 SmallPtrSet<Instruction*, 4> *AggressiveInsts,
260 unsigned &CostRemaining) {
261 Instruction *I = dyn_cast<Instruction>(V);
263 // Non-instructions all dominate instructions, but not all constantexprs
264 // can be executed unconditionally.
265 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
270 BasicBlock *PBB = I->getParent();
272 // We don't want to allow weird loops that might have the "if condition" in
273 // the bottom of this block.
274 if (PBB == BB) return false;
276 // If this instruction is defined in a block that contains an unconditional
277 // branch to BB, then it must be in the 'conditional' part of the "if
278 // statement". If not, it definitely dominates the region.
279 BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
280 if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB)
283 // If we aren't allowing aggressive promotion anymore, then don't consider
284 // instructions in the 'if region'.
285 if (!AggressiveInsts) return false;
287 // If we have seen this instruction before, don't count it again.
288 if (AggressiveInsts->count(I)) return true;
290 // Okay, it looks like the instruction IS in the "condition". Check to
291 // see if it's a cheap instruction to unconditionally compute, and if it
292 // only uses stuff defined outside of the condition. If so, hoist it out.
293 if (!isSafeToSpeculativelyExecute(I))
296 unsigned Cost = ComputeSpeculationCost(I);
298 if (Cost > CostRemaining)
301 CostRemaining -= Cost;
303 // Okay, we can only really hoist these out if their operands do
304 // not take us over the cost threshold.
305 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
306 if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining))
308 // Okay, it's safe to do this! Remember this instruction.
309 AggressiveInsts->insert(I);
313 /// GetConstantInt - Extract ConstantInt from value, looking through IntToPtr
314 /// and PointerNullValue. Return NULL if value is not a constant int.
315 static ConstantInt *GetConstantInt(Value *V, const DataLayout *DL) {
316 // Normal constant int.
317 ConstantInt *CI = dyn_cast<ConstantInt>(V);
318 if (CI || !DL || !isa<Constant>(V) || !V->getType()->isPointerTy())
321 // This is some kind of pointer constant. Turn it into a pointer-sized
322 // ConstantInt if possible.
323 IntegerType *PtrTy = cast<IntegerType>(DL->getIntPtrType(V->getType()));
325 // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
326 if (isa<ConstantPointerNull>(V))
327 return ConstantInt::get(PtrTy, 0);
329 // IntToPtr const int.
330 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
331 if (CE->getOpcode() == Instruction::IntToPtr)
332 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
333 // The constant is very likely to have the right type already.
334 if (CI->getType() == PtrTy)
337 return cast<ConstantInt>
338 (ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
343 /// GatherConstantCompares - Given a potentially 'or'd or 'and'd together
344 /// collection of icmp eq/ne instructions that compare a value against a
345 /// constant, return the value being compared, and stick the constant into the
348 GatherConstantCompares(Value *V, std::vector<ConstantInt*> &Vals, Value *&Extra,
349 const DataLayout *DL, bool isEQ, unsigned &UsedICmps) {
350 Instruction *I = dyn_cast<Instruction>(V);
351 if (!I) return nullptr;
353 // If this is an icmp against a constant, handle this as one of the cases.
354 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) {
355 if (ConstantInt *C = GetConstantInt(I->getOperand(1), DL)) {
359 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ:ICmpInst::ICMP_NE)) {
360 // (x & ~2^x) == y --> x == y || x == y|2^x
361 // This undoes a transformation done by instcombine to fuse 2 compares.
362 if (match(ICI->getOperand(0),
363 m_And(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
364 APInt Not = ~RHSC->getValue();
365 if (Not.isPowerOf2()) {
368 ConstantInt::get(C->getContext(), C->getValue() | Not));
376 return I->getOperand(0);
379 // If we have "x ult 3" comparison, for example, then we can add 0,1,2 to
382 ConstantRange::makeICmpRegion(ICI->getPredicate(), C->getValue());
384 // Shift the range if the compare is fed by an add. This is the range
385 // compare idiom as emitted by instcombine.
387 match(I->getOperand(0), m_Add(m_Value(RHSVal), m_ConstantInt(RHSC)));
389 Span = Span.subtract(RHSC->getValue());
391 // If this is an and/!= check then we want to optimize "x ugt 2" into
394 Span = Span.inverse();
396 // If there are a ton of values, we don't want to make a ginormous switch.
397 if (Span.getSetSize().ugt(8) || Span.isEmptySet())
400 for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
401 Vals.push_back(ConstantInt::get(V->getContext(), Tmp));
403 return hasAdd ? RHSVal : I->getOperand(0);
408 // Otherwise, we can only handle an | or &, depending on isEQ.
409 if (I->getOpcode() != (isEQ ? Instruction::Or : Instruction::And))
412 unsigned NumValsBeforeLHS = Vals.size();
413 unsigned UsedICmpsBeforeLHS = UsedICmps;
414 if (Value *LHS = GatherConstantCompares(I->getOperand(0), Vals, Extra, DL,
416 unsigned NumVals = Vals.size();
417 unsigned UsedICmpsBeforeRHS = UsedICmps;
418 if (Value *RHS = GatherConstantCompares(I->getOperand(1), Vals, Extra, DL,
422 Vals.resize(NumVals);
423 UsedICmps = UsedICmpsBeforeRHS;
426 // The RHS of the or/and can't be folded in and we haven't used "Extra" yet,
427 // set it and return success.
428 if (Extra == nullptr || Extra == I->getOperand(1)) {
429 Extra = I->getOperand(1);
433 Vals.resize(NumValsBeforeLHS);
434 UsedICmps = UsedICmpsBeforeLHS;
438 // If the LHS can't be folded in, but Extra is available and RHS can, try to
440 if (Extra == nullptr || Extra == I->getOperand(0)) {
441 Value *OldExtra = Extra;
442 Extra = I->getOperand(0);
443 if (Value *RHS = GatherConstantCompares(I->getOperand(1), Vals, Extra, DL,
446 assert(Vals.size() == NumValsBeforeLHS);
453 static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
454 Instruction *Cond = nullptr;
455 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
456 Cond = dyn_cast<Instruction>(SI->getCondition());
457 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
458 if (BI->isConditional())
459 Cond = dyn_cast<Instruction>(BI->getCondition());
460 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
461 Cond = dyn_cast<Instruction>(IBI->getAddress());
464 TI->eraseFromParent();
465 if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond);
468 /// isValueEqualityComparison - Return true if the specified terminator checks
469 /// to see if a value is equal to constant integer value.
470 Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) {
472 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
473 // Do not permit merging of large switch instructions into their
474 // predecessors unless there is only one predecessor.
475 if (SI->getNumSuccessors()*std::distance(pred_begin(SI->getParent()),
476 pred_end(SI->getParent())) <= 128)
477 CV = SI->getCondition();
478 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
479 if (BI->isConditional() && BI->getCondition()->hasOneUse())
480 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
481 if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL))
482 CV = ICI->getOperand(0);
484 // Unwrap any lossless ptrtoint cast.
486 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
487 Value *Ptr = PTII->getPointerOperand();
488 if (PTII->getType() == DL->getIntPtrType(Ptr->getType()))
495 /// GetValueEqualityComparisonCases - Given a value comparison instruction,
496 /// decode all of the 'cases' that it represents and return the 'default' block.
497 BasicBlock *SimplifyCFGOpt::
498 GetValueEqualityComparisonCases(TerminatorInst *TI,
499 std::vector<ValueEqualityComparisonCase>
501 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
502 Cases.reserve(SI->getNumCases());
503 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i)
504 Cases.push_back(ValueEqualityComparisonCase(i.getCaseValue(),
505 i.getCaseSuccessor()));
506 return SI->getDefaultDest();
509 BranchInst *BI = cast<BranchInst>(TI);
510 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
511 BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE);
512 Cases.push_back(ValueEqualityComparisonCase(GetConstantInt(ICI->getOperand(1),
515 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
519 /// EliminateBlockCases - Given a vector of bb/value pairs, remove any entries
520 /// in the list that match the specified block.
521 static void EliminateBlockCases(BasicBlock *BB,
522 std::vector<ValueEqualityComparisonCase> &Cases) {
523 Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end());
526 /// ValuesOverlap - Return true if there are any keys in C1 that exist in C2 as
529 ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
530 std::vector<ValueEqualityComparisonCase > &C2) {
531 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
533 // Make V1 be smaller than V2.
534 if (V1->size() > V2->size())
537 if (V1->size() == 0) return false;
538 if (V1->size() == 1) {
540 ConstantInt *TheVal = (*V1)[0].Value;
541 for (unsigned i = 0, e = V2->size(); i != e; ++i)
542 if (TheVal == (*V2)[i].Value)
546 // Otherwise, just sort both lists and compare element by element.
547 array_pod_sort(V1->begin(), V1->end());
548 array_pod_sort(V2->begin(), V2->end());
549 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
550 while (i1 != e1 && i2 != e2) {
551 if ((*V1)[i1].Value == (*V2)[i2].Value)
553 if ((*V1)[i1].Value < (*V2)[i2].Value)
561 /// SimplifyEqualityComparisonWithOnlyPredecessor - If TI is known to be a
562 /// terminator instruction and its block is known to only have a single
563 /// predecessor block, check to see if that predecessor is also a value
564 /// comparison with the same value, and if that comparison determines the
565 /// outcome of this comparison. If so, simplify TI. This does a very limited
566 /// form of jump threading.
567 bool SimplifyCFGOpt::
568 SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
570 IRBuilder<> &Builder) {
571 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
572 if (!PredVal) return false; // Not a value comparison in predecessor.
574 Value *ThisVal = isValueEqualityComparison(TI);
575 assert(ThisVal && "This isn't a value comparison!!");
576 if (ThisVal != PredVal) return false; // Different predicates.
578 // TODO: Preserve branch weight metadata, similarly to how
579 // FoldValueComparisonIntoPredecessors preserves it.
581 // Find out information about when control will move from Pred to TI's block.
582 std::vector<ValueEqualityComparisonCase> PredCases;
583 BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
585 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
587 // Find information about how control leaves this block.
588 std::vector<ValueEqualityComparisonCase> ThisCases;
589 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
590 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
592 // If TI's block is the default block from Pred's comparison, potentially
593 // simplify TI based on this knowledge.
594 if (PredDef == TI->getParent()) {
595 // If we are here, we know that the value is none of those cases listed in
596 // PredCases. If there are any cases in ThisCases that are in PredCases, we
598 if (!ValuesOverlap(PredCases, ThisCases))
601 if (isa<BranchInst>(TI)) {
602 // Okay, one of the successors of this condbr is dead. Convert it to a
604 assert(ThisCases.size() == 1 && "Branch can only have one case!");
605 // Insert the new branch.
606 Instruction *NI = Builder.CreateBr(ThisDef);
609 // Remove PHI node entries for the dead edge.
610 ThisCases[0].Dest->removePredecessor(TI->getParent());
612 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
613 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
615 EraseTerminatorInstAndDCECond(TI);
619 SwitchInst *SI = cast<SwitchInst>(TI);
620 // Okay, TI has cases that are statically dead, prune them away.
621 SmallPtrSet<Constant*, 16> DeadCases;
622 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
623 DeadCases.insert(PredCases[i].Value);
625 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
626 << "Through successor TI: " << *TI);
628 // Collect branch weights into a vector.
629 SmallVector<uint32_t, 8> Weights;
630 MDNode* MD = SI->getMetadata(LLVMContext::MD_prof);
631 bool HasWeight = MD && (MD->getNumOperands() == 2 + SI->getNumCases());
633 for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
635 ConstantInt* CI = dyn_cast<ConstantInt>(MD->getOperand(MD_i));
637 Weights.push_back(CI->getValue().getZExtValue());
639 for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
641 if (DeadCases.count(i.getCaseValue())) {
643 std::swap(Weights[i.getCaseIndex()+1], Weights.back());
646 i.getCaseSuccessor()->removePredecessor(TI->getParent());
650 if (HasWeight && Weights.size() >= 2)
651 SI->setMetadata(LLVMContext::MD_prof,
652 MDBuilder(SI->getParent()->getContext()).
653 createBranchWeights(Weights));
655 DEBUG(dbgs() << "Leaving: " << *TI << "\n");
659 // Otherwise, TI's block must correspond to some matched value. Find out
660 // which value (or set of values) this is.
661 ConstantInt *TIV = nullptr;
662 BasicBlock *TIBB = TI->getParent();
663 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
664 if (PredCases[i].Dest == TIBB) {
666 return false; // Cannot handle multiple values coming to this block.
667 TIV = PredCases[i].Value;
669 assert(TIV && "No edge from pred to succ?");
671 // Okay, we found the one constant that our value can be if we get into TI's
672 // BB. Find out which successor will unconditionally be branched to.
673 BasicBlock *TheRealDest = nullptr;
674 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
675 if (ThisCases[i].Value == TIV) {
676 TheRealDest = ThisCases[i].Dest;
680 // If not handled by any explicit cases, it is handled by the default case.
681 if (!TheRealDest) TheRealDest = ThisDef;
683 // Remove PHI node entries for dead edges.
684 BasicBlock *CheckEdge = TheRealDest;
685 for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
686 if (*SI != CheckEdge)
687 (*SI)->removePredecessor(TIBB);
691 // Insert the new branch.
692 Instruction *NI = Builder.CreateBr(TheRealDest);
695 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
696 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
698 EraseTerminatorInstAndDCECond(TI);
703 /// ConstantIntOrdering - This class implements a stable ordering of constant
704 /// integers that does not depend on their address. This is important for
705 /// applications that sort ConstantInt's to ensure uniqueness.
706 struct ConstantIntOrdering {
707 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
708 return LHS->getValue().ult(RHS->getValue());
713 static int ConstantIntSortPredicate(ConstantInt *const *P1,
714 ConstantInt *const *P2) {
715 const ConstantInt *LHS = *P1;
716 const ConstantInt *RHS = *P2;
717 if (LHS->getValue().ult(RHS->getValue()))
719 if (LHS->getValue() == RHS->getValue())
724 static inline bool HasBranchWeights(const Instruction* I) {
725 MDNode* ProfMD = I->getMetadata(LLVMContext::MD_prof);
726 if (ProfMD && ProfMD->getOperand(0))
727 if (MDString* MDS = dyn_cast<MDString>(ProfMD->getOperand(0)))
728 return MDS->getString().equals("branch_weights");
733 /// Get Weights of a given TerminatorInst, the default weight is at the front
734 /// of the vector. If TI is a conditional eq, we need to swap the branch-weight
736 static void GetBranchWeights(TerminatorInst *TI,
737 SmallVectorImpl<uint64_t> &Weights) {
738 MDNode* MD = TI->getMetadata(LLVMContext::MD_prof);
740 for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) {
741 ConstantInt *CI = cast<ConstantInt>(MD->getOperand(i));
742 Weights.push_back(CI->getValue().getZExtValue());
745 // If TI is a conditional eq, the default case is the false case,
746 // and the corresponding branch-weight data is at index 2. We swap the
747 // default weight to be the first entry.
748 if (BranchInst* BI = dyn_cast<BranchInst>(TI)) {
749 assert(Weights.size() == 2);
750 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
751 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
752 std::swap(Weights.front(), Weights.back());
756 /// Keep halving the weights until all can fit in uint32_t.
757 static void FitWeights(MutableArrayRef<uint64_t> Weights) {
758 uint64_t Max = *std::max_element(Weights.begin(), Weights.end());
759 if (Max > UINT_MAX) {
760 unsigned Offset = 32 - countLeadingZeros(Max);
761 for (uint64_t &I : Weights)
766 /// FoldValueComparisonIntoPredecessors - The specified terminator is a value
767 /// equality comparison instruction (either a switch or a branch on "X == c").
768 /// See if any of the predecessors of the terminator block are value comparisons
769 /// on the same value. If so, and if safe to do so, fold them together.
770 bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
771 IRBuilder<> &Builder) {
772 BasicBlock *BB = TI->getParent();
773 Value *CV = isValueEqualityComparison(TI); // CondVal
774 assert(CV && "Not a comparison?");
775 bool Changed = false;
777 SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
778 while (!Preds.empty()) {
779 BasicBlock *Pred = Preds.pop_back_val();
781 // See if the predecessor is a comparison with the same value.
782 TerminatorInst *PTI = Pred->getTerminator();
783 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
785 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
786 // Figure out which 'cases' to copy from SI to PSI.
787 std::vector<ValueEqualityComparisonCase> BBCases;
788 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
790 std::vector<ValueEqualityComparisonCase> PredCases;
791 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
793 // Based on whether the default edge from PTI goes to BB or not, fill in
794 // PredCases and PredDefault with the new switch cases we would like to
796 SmallVector<BasicBlock*, 8> NewSuccessors;
798 // Update the branch weight metadata along the way
799 SmallVector<uint64_t, 8> Weights;
800 bool PredHasWeights = HasBranchWeights(PTI);
801 bool SuccHasWeights = HasBranchWeights(TI);
803 if (PredHasWeights) {
804 GetBranchWeights(PTI, Weights);
805 // branch-weight metadata is inconsistent here.
806 if (Weights.size() != 1 + PredCases.size())
807 PredHasWeights = SuccHasWeights = false;
808 } else if (SuccHasWeights)
809 // If there are no predecessor weights but there are successor weights,
810 // populate Weights with 1, which will later be scaled to the sum of
811 // successor's weights
812 Weights.assign(1 + PredCases.size(), 1);
814 SmallVector<uint64_t, 8> SuccWeights;
815 if (SuccHasWeights) {
816 GetBranchWeights(TI, SuccWeights);
817 // branch-weight metadata is inconsistent here.
818 if (SuccWeights.size() != 1 + BBCases.size())
819 PredHasWeights = SuccHasWeights = false;
820 } else if (PredHasWeights)
821 SuccWeights.assign(1 + BBCases.size(), 1);
823 if (PredDefault == BB) {
824 // If this is the default destination from PTI, only the edges in TI
825 // that don't occur in PTI, or that branch to BB will be activated.
826 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
827 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
828 if (PredCases[i].Dest != BB)
829 PTIHandled.insert(PredCases[i].Value);
831 // The default destination is BB, we don't need explicit targets.
832 std::swap(PredCases[i], PredCases.back());
834 if (PredHasWeights || SuccHasWeights) {
835 // Increase weight for the default case.
836 Weights[0] += Weights[i+1];
837 std::swap(Weights[i+1], Weights.back());
841 PredCases.pop_back();
845 // Reconstruct the new switch statement we will be building.
846 if (PredDefault != BBDefault) {
847 PredDefault->removePredecessor(Pred);
848 PredDefault = BBDefault;
849 NewSuccessors.push_back(BBDefault);
852 unsigned CasesFromPred = Weights.size();
853 uint64_t ValidTotalSuccWeight = 0;
854 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
855 if (!PTIHandled.count(BBCases[i].Value) &&
856 BBCases[i].Dest != BBDefault) {
857 PredCases.push_back(BBCases[i]);
858 NewSuccessors.push_back(BBCases[i].Dest);
859 if (SuccHasWeights || PredHasWeights) {
860 // The default weight is at index 0, so weight for the ith case
861 // should be at index i+1. Scale the cases from successor by
862 // PredDefaultWeight (Weights[0]).
863 Weights.push_back(Weights[0] * SuccWeights[i+1]);
864 ValidTotalSuccWeight += SuccWeights[i+1];
868 if (SuccHasWeights || PredHasWeights) {
869 ValidTotalSuccWeight += SuccWeights[0];
870 // Scale the cases from predecessor by ValidTotalSuccWeight.
871 for (unsigned i = 1; i < CasesFromPred; ++i)
872 Weights[i] *= ValidTotalSuccWeight;
873 // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
874 Weights[0] *= SuccWeights[0];
877 // If this is not the default destination from PSI, only the edges
878 // in SI that occur in PSI with a destination of BB will be
880 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
881 std::map<ConstantInt*, uint64_t> WeightsForHandled;
882 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
883 if (PredCases[i].Dest == BB) {
884 PTIHandled.insert(PredCases[i].Value);
886 if (PredHasWeights || SuccHasWeights) {
887 WeightsForHandled[PredCases[i].Value] = Weights[i+1];
888 std::swap(Weights[i+1], Weights.back());
892 std::swap(PredCases[i], PredCases.back());
893 PredCases.pop_back();
897 // Okay, now we know which constants were sent to BB from the
898 // predecessor. Figure out where they will all go now.
899 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
900 if (PTIHandled.count(BBCases[i].Value)) {
901 // If this is one we are capable of getting...
902 if (PredHasWeights || SuccHasWeights)
903 Weights.push_back(WeightsForHandled[BBCases[i].Value]);
904 PredCases.push_back(BBCases[i]);
905 NewSuccessors.push_back(BBCases[i].Dest);
906 PTIHandled.erase(BBCases[i].Value);// This constant is taken care of
909 // If there are any constants vectored to BB that TI doesn't handle,
910 // they must go to the default destination of TI.
911 for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I =
913 E = PTIHandled.end(); I != E; ++I) {
914 if (PredHasWeights || SuccHasWeights)
915 Weights.push_back(WeightsForHandled[*I]);
916 PredCases.push_back(ValueEqualityComparisonCase(*I, BBDefault));
917 NewSuccessors.push_back(BBDefault);
921 // Okay, at this point, we know which new successor Pred will get. Make
922 // sure we update the number of entries in the PHI nodes for these
924 for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
925 AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
927 Builder.SetInsertPoint(PTI);
928 // Convert pointer to int before we switch.
929 if (CV->getType()->isPointerTy()) {
930 assert(DL && "Cannot switch on pointer without DataLayout");
931 CV = Builder.CreatePtrToInt(CV, DL->getIntPtrType(CV->getType()),
935 // Now that the successors are updated, create the new Switch instruction.
936 SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault,
938 NewSI->setDebugLoc(PTI->getDebugLoc());
939 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
940 NewSI->addCase(PredCases[i].Value, PredCases[i].Dest);
942 if (PredHasWeights || SuccHasWeights) {
943 // Halve the weights if any of them cannot fit in an uint32_t
946 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
948 NewSI->setMetadata(LLVMContext::MD_prof,
949 MDBuilder(BB->getContext()).
950 createBranchWeights(MDWeights));
953 EraseTerminatorInstAndDCECond(PTI);
955 // Okay, last check. If BB is still a successor of PSI, then we must
956 // have an infinite loop case. If so, add an infinitely looping block
957 // to handle the case to preserve the behavior of the code.
958 BasicBlock *InfLoopBlock = nullptr;
959 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
960 if (NewSI->getSuccessor(i) == BB) {
962 // Insert it at the end of the function, because it's either code,
963 // or it won't matter if it's hot. :)
964 InfLoopBlock = BasicBlock::Create(BB->getContext(),
965 "infloop", BB->getParent());
966 BranchInst::Create(InfLoopBlock, InfLoopBlock);
968 NewSI->setSuccessor(i, InfLoopBlock);
977 // isSafeToHoistInvoke - If we would need to insert a select that uses the
978 // value of this invoke (comments in HoistThenElseCodeToIf explain why we
979 // would need to do this), we can't hoist the invoke, as there is nowhere
980 // to put the select in this case.
981 static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
982 Instruction *I1, Instruction *I2) {
983 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
985 for (BasicBlock::iterator BBI = SI->begin();
986 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
987 Value *BB1V = PN->getIncomingValueForBlock(BB1);
988 Value *BB2V = PN->getIncomingValueForBlock(BB2);
989 if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) {
997 /// HoistThenElseCodeToIf - Given a conditional branch that goes to BB1 and
998 /// BB2, hoist any common code in the two blocks up into the branch block. The
999 /// caller of this function guarantees that BI's block dominates BB1 and BB2.
1000 static bool HoistThenElseCodeToIf(BranchInst *BI) {
1001 // This does very trivial matching, with limited scanning, to find identical
1002 // instructions in the two blocks. In particular, we don't want to get into
1003 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
1004 // such, we currently just scan for obviously identical instructions in an
1006 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
1007 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
1009 BasicBlock::iterator BB1_Itr = BB1->begin();
1010 BasicBlock::iterator BB2_Itr = BB2->begin();
1012 Instruction *I1 = BB1_Itr++, *I2 = BB2_Itr++;
1013 // Skip debug info if it is not identical.
1014 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1015 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1016 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1017 while (isa<DbgInfoIntrinsic>(I1))
1019 while (isa<DbgInfoIntrinsic>(I2))
1022 if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
1023 (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
1026 BasicBlock *BIParent = BI->getParent();
1028 bool Changed = false;
1030 // If we are hoisting the terminator instruction, don't move one (making a
1031 // broken BB), instead clone it, and remove BI.
1032 if (isa<TerminatorInst>(I1))
1033 goto HoistTerminator;
1035 // For a normal instruction, we just move one to right before the branch,
1036 // then replace all uses of the other with the first. Finally, we remove
1037 // the now redundant second instruction.
1038 BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
1039 if (!I2->use_empty())
1040 I2->replaceAllUsesWith(I1);
1041 I1->intersectOptionalDataWith(I2);
1042 I2->eraseFromParent();
1047 // Skip debug info if it is not identical.
1048 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1049 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1050 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1051 while (isa<DbgInfoIntrinsic>(I1))
1053 while (isa<DbgInfoIntrinsic>(I2))
1056 } while (I1->isIdenticalToWhenDefined(I2));
1061 // It may not be possible to hoist an invoke.
1062 if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
1065 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
1067 for (BasicBlock::iterator BBI = SI->begin();
1068 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1069 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1070 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1074 if (isa<ConstantExpr>(BB1V) && !isSafeToSpeculativelyExecute(BB1V))
1076 if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V))
1081 // Okay, it is safe to hoist the terminator.
1082 Instruction *NT = I1->clone();
1083 BIParent->getInstList().insert(BI, NT);
1084 if (!NT->getType()->isVoidTy()) {
1085 I1->replaceAllUsesWith(NT);
1086 I2->replaceAllUsesWith(NT);
1090 IRBuilder<true, NoFolder> Builder(NT);
1091 // Hoisting one of the terminators from our successor is a great thing.
1092 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
1093 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
1094 // nodes, so we insert select instruction to compute the final result.
1095 std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
1096 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
1098 for (BasicBlock::iterator BBI = SI->begin();
1099 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1100 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1101 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1102 if (BB1V == BB2V) continue;
1104 // These values do not agree. Insert a select instruction before NT
1105 // that determines the right value.
1106 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
1108 SI = cast<SelectInst>
1109 (Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
1110 BB1V->getName()+"."+BB2V->getName()));
1112 // Make the PHI node use the select for all incoming values for BB1/BB2
1113 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1114 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
1115 PN->setIncomingValue(i, SI);
1119 // Update any PHI nodes in our new successors.
1120 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
1121 AddPredecessorToBlock(*SI, BIParent, BB1);
1123 EraseTerminatorInstAndDCECond(BI);
1127 /// SinkThenElseCodeToEnd - Given an unconditional branch that goes to BBEnd,
1128 /// check whether BBEnd has only two predecessors and the other predecessor
1129 /// ends with an unconditional branch. If it is true, sink any common code
1130 /// in the two predecessors to BBEnd.
1131 static bool SinkThenElseCodeToEnd(BranchInst *BI1) {
1132 assert(BI1->isUnconditional());
1133 BasicBlock *BB1 = BI1->getParent();
1134 BasicBlock *BBEnd = BI1->getSuccessor(0);
1136 // Check that BBEnd has two predecessors and the other predecessor ends with
1137 // an unconditional branch.
1138 pred_iterator PI = pred_begin(BBEnd), PE = pred_end(BBEnd);
1139 BasicBlock *Pred0 = *PI++;
1140 if (PI == PE) // Only one predecessor.
1142 BasicBlock *Pred1 = *PI++;
1143 if (PI != PE) // More than two predecessors.
1145 BasicBlock *BB2 = (Pred0 == BB1) ? Pred1 : Pred0;
1146 BranchInst *BI2 = dyn_cast<BranchInst>(BB2->getTerminator());
1147 if (!BI2 || !BI2->isUnconditional())
1150 // Gather the PHI nodes in BBEnd.
1151 std::map<Value*, std::pair<Value*, PHINode*> > MapValueFromBB1ToBB2;
1152 Instruction *FirstNonPhiInBBEnd = nullptr;
1153 for (BasicBlock::iterator I = BBEnd->begin(), E = BBEnd->end();
1155 if (PHINode *PN = dyn_cast<PHINode>(I)) {
1156 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1157 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1158 MapValueFromBB1ToBB2[BB1V] = std::make_pair(BB2V, PN);
1160 FirstNonPhiInBBEnd = &*I;
1164 if (!FirstNonPhiInBBEnd)
1168 // This does very trivial matching, with limited scanning, to find identical
1169 // instructions in the two blocks. We scan backward for obviously identical
1170 // instructions in an identical order.
1171 BasicBlock::InstListType::reverse_iterator RI1 = BB1->getInstList().rbegin(),
1172 RE1 = BB1->getInstList().rend(), RI2 = BB2->getInstList().rbegin(),
1173 RE2 = BB2->getInstList().rend();
1175 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1178 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1181 // Skip the unconditional branches.
1185 bool Changed = false;
1186 while (RI1 != RE1 && RI2 != RE2) {
1188 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1191 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1195 Instruction *I1 = &*RI1, *I2 = &*RI2;
1196 // I1 and I2 should have a single use in the same PHI node, and they
1197 // perform the same operation.
1198 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
1199 if (isa<PHINode>(I1) || isa<PHINode>(I2) ||
1200 isa<TerminatorInst>(I1) || isa<TerminatorInst>(I2) ||
1201 isa<LandingPadInst>(I1) || isa<LandingPadInst>(I2) ||
1202 isa<AllocaInst>(I1) || isa<AllocaInst>(I2) ||
1203 I1->mayHaveSideEffects() || I2->mayHaveSideEffects() ||
1204 I1->mayReadOrWriteMemory() || I2->mayReadOrWriteMemory() ||
1205 !I1->hasOneUse() || !I2->hasOneUse() ||
1206 MapValueFromBB1ToBB2.find(I1) == MapValueFromBB1ToBB2.end() ||
1207 MapValueFromBB1ToBB2[I1].first != I2)
1210 // Check whether we should swap the operands of ICmpInst.
1211 ICmpInst *ICmp1 = dyn_cast<ICmpInst>(I1), *ICmp2 = dyn_cast<ICmpInst>(I2);
1212 bool SwapOpnds = false;
1213 if (ICmp1 && ICmp2 &&
1214 ICmp1->getOperand(0) != ICmp2->getOperand(0) &&
1215 ICmp1->getOperand(1) != ICmp2->getOperand(1) &&
1216 (ICmp1->getOperand(0) == ICmp2->getOperand(1) ||
1217 ICmp1->getOperand(1) == ICmp2->getOperand(0))) {
1218 ICmp2->swapOperands();
1221 if (!I1->isSameOperationAs(I2)) {
1223 ICmp2->swapOperands();
1227 // The operands should be either the same or they need to be generated
1228 // with a PHI node after sinking. We only handle the case where there is
1229 // a single pair of different operands.
1230 Value *DifferentOp1 = nullptr, *DifferentOp2 = nullptr;
1231 unsigned Op1Idx = 0;
1232 for (unsigned I = 0, E = I1->getNumOperands(); I != E; ++I) {
1233 if (I1->getOperand(I) == I2->getOperand(I))
1235 // Early exit if we have more-than one pair of different operands or
1236 // the different operand is already in MapValueFromBB1ToBB2.
1237 // Early exit if we need a PHI node to replace a constant.
1239 MapValueFromBB1ToBB2.find(I1->getOperand(I)) !=
1240 MapValueFromBB1ToBB2.end() ||
1241 isa<Constant>(I1->getOperand(I)) ||
1242 isa<Constant>(I2->getOperand(I))) {
1243 // If we can't sink the instructions, undo the swapping.
1245 ICmp2->swapOperands();
1248 DifferentOp1 = I1->getOperand(I);
1250 DifferentOp2 = I2->getOperand(I);
1253 // We insert the pair of different operands to MapValueFromBB1ToBB2 and
1254 // remove (I1, I2) from MapValueFromBB1ToBB2.
1256 PHINode *NewPN = PHINode::Create(DifferentOp1->getType(), 2,
1257 DifferentOp1->getName() + ".sink",
1259 MapValueFromBB1ToBB2[DifferentOp1] = std::make_pair(DifferentOp2, NewPN);
1260 // I1 should use NewPN instead of DifferentOp1.
1261 I1->setOperand(Op1Idx, NewPN);
1262 NewPN->addIncoming(DifferentOp1, BB1);
1263 NewPN->addIncoming(DifferentOp2, BB2);
1264 DEBUG(dbgs() << "Create PHI node " << *NewPN << "\n";);
1266 PHINode *OldPN = MapValueFromBB1ToBB2[I1].second;
1267 MapValueFromBB1ToBB2.erase(I1);
1269 DEBUG(dbgs() << "SINK common instructions " << *I1 << "\n";);
1270 DEBUG(dbgs() << " " << *I2 << "\n";);
1271 // We need to update RE1 and RE2 if we are going to sink the first
1272 // instruction in the basic block down.
1273 bool UpdateRE1 = (I1 == BB1->begin()), UpdateRE2 = (I2 == BB2->begin());
1274 // Sink the instruction.
1275 BBEnd->getInstList().splice(FirstNonPhiInBBEnd, BB1->getInstList(), I1);
1276 if (!OldPN->use_empty())
1277 OldPN->replaceAllUsesWith(I1);
1278 OldPN->eraseFromParent();
1280 if (!I2->use_empty())
1281 I2->replaceAllUsesWith(I1);
1282 I1->intersectOptionalDataWith(I2);
1283 I2->eraseFromParent();
1286 RE1 = BB1->getInstList().rend();
1288 RE2 = BB2->getInstList().rend();
1289 FirstNonPhiInBBEnd = I1;
1296 /// \brief Determine if we can hoist sink a sole store instruction out of a
1297 /// conditional block.
1299 /// We are looking for code like the following:
1301 /// store i32 %add, i32* %arrayidx2
1302 /// ... // No other stores or function calls (we could be calling a memory
1303 /// ... // function).
1304 /// %cmp = icmp ult %x, %y
1305 /// br i1 %cmp, label %EndBB, label %ThenBB
1307 /// store i32 %add5, i32* %arrayidx2
1311 /// We are going to transform this into:
1313 /// store i32 %add, i32* %arrayidx2
1315 /// %cmp = icmp ult %x, %y
1316 /// %add.add5 = select i1 %cmp, i32 %add, %add5
1317 /// store i32 %add.add5, i32* %arrayidx2
1320 /// \return The pointer to the value of the previous store if the store can be
1321 /// hoisted into the predecessor block. 0 otherwise.
1322 static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB,
1323 BasicBlock *StoreBB, BasicBlock *EndBB) {
1324 StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
1328 // Volatile or atomic.
1329 if (!StoreToHoist->isSimple())
1332 Value *StorePtr = StoreToHoist->getPointerOperand();
1334 // Look for a store to the same pointer in BrBB.
1335 unsigned MaxNumInstToLookAt = 10;
1336 for (BasicBlock::reverse_iterator RI = BrBB->rbegin(),
1337 RE = BrBB->rend(); RI != RE && (--MaxNumInstToLookAt); ++RI) {
1338 Instruction *CurI = &*RI;
1340 // Could be calling an instruction that effects memory like free().
1341 if (CurI->mayHaveSideEffects() && !isa<StoreInst>(CurI))
1344 StoreInst *SI = dyn_cast<StoreInst>(CurI);
1345 // Found the previous store make sure it stores to the same location.
1346 if (SI && SI->getPointerOperand() == StorePtr)
1347 // Found the previous store, return its value operand.
1348 return SI->getValueOperand();
1350 return nullptr; // Unknown store.
1356 /// \brief Speculate a conditional basic block flattening the CFG.
1358 /// Note that this is a very risky transform currently. Speculating
1359 /// instructions like this is most often not desirable. Instead, there is an MI
1360 /// pass which can do it with full awareness of the resource constraints.
1361 /// However, some cases are "obvious" and we should do directly. An example of
1362 /// this is speculating a single, reasonably cheap instruction.
1364 /// There is only one distinct advantage to flattening the CFG at the IR level:
1365 /// it makes very common but simplistic optimizations such as are common in
1366 /// instcombine and the DAG combiner more powerful by removing CFG edges and
1367 /// modeling their effects with easier to reason about SSA value graphs.
1370 /// An illustration of this transform is turning this IR:
1373 /// %cmp = icmp ult %x, %y
1374 /// br i1 %cmp, label %EndBB, label %ThenBB
1376 /// %sub = sub %x, %y
1379 /// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ]
1386 /// %cmp = icmp ult %x, %y
1387 /// %sub = sub %x, %y
1388 /// %cond = select i1 %cmp, 0, %sub
1392 /// \returns true if the conditional block is removed.
1393 static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB) {
1394 // Be conservative for now. FP select instruction can often be expensive.
1395 Value *BrCond = BI->getCondition();
1396 if (isa<FCmpInst>(BrCond))
1399 BasicBlock *BB = BI->getParent();
1400 BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
1402 // If ThenBB is actually on the false edge of the conditional branch, remember
1403 // to swap the select operands later.
1404 bool Invert = false;
1405 if (ThenBB != BI->getSuccessor(0)) {
1406 assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
1409 assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
1411 // Keep a count of how many times instructions are used within CondBB when
1412 // they are candidates for sinking into CondBB. Specifically:
1413 // - They are defined in BB, and
1414 // - They have no side effects, and
1415 // - All of their uses are in CondBB.
1416 SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
1418 unsigned SpeculationCost = 0;
1419 Value *SpeculatedStoreValue = nullptr;
1420 StoreInst *SpeculatedStore = nullptr;
1421 for (BasicBlock::iterator BBI = ThenBB->begin(),
1422 BBE = std::prev(ThenBB->end());
1423 BBI != BBE; ++BBI) {
1424 Instruction *I = BBI;
1426 if (isa<DbgInfoIntrinsic>(I))
1429 // Only speculatively execution a single instruction (not counting the
1430 // terminator) for now.
1432 if (SpeculationCost > 1)
1435 // Don't hoist the instruction if it's unsafe or expensive.
1436 if (!isSafeToSpeculativelyExecute(I) &&
1437 !(HoistCondStores &&
1438 (SpeculatedStoreValue = isSafeToSpeculateStore(I, BB, ThenBB,
1441 if (!SpeculatedStoreValue &&
1442 ComputeSpeculationCost(I) > PHINodeFoldingThreshold)
1445 // Store the store speculation candidate.
1446 if (SpeculatedStoreValue)
1447 SpeculatedStore = cast<StoreInst>(I);
1449 // Do not hoist the instruction if any of its operands are defined but not
1450 // used in BB. The transformation will prevent the operand from
1451 // being sunk into the use block.
1452 for (User::op_iterator i = I->op_begin(), e = I->op_end();
1454 Instruction *OpI = dyn_cast<Instruction>(*i);
1455 if (!OpI || OpI->getParent() != BB ||
1456 OpI->mayHaveSideEffects())
1457 continue; // Not a candidate for sinking.
1459 ++SinkCandidateUseCounts[OpI];
1463 // Consider any sink candidates which are only used in CondBB as costs for
1464 // speculation. Note, while we iterate over a DenseMap here, we are summing
1465 // and so iteration order isn't significant.
1466 for (SmallDenseMap<Instruction *, unsigned, 4>::iterator I =
1467 SinkCandidateUseCounts.begin(), E = SinkCandidateUseCounts.end();
1469 if (I->first->getNumUses() == I->second) {
1471 if (SpeculationCost > 1)
1475 // Check that the PHI nodes can be converted to selects.
1476 bool HaveRewritablePHIs = false;
1477 for (BasicBlock::iterator I = EndBB->begin();
1478 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1479 Value *OrigV = PN->getIncomingValueForBlock(BB);
1480 Value *ThenV = PN->getIncomingValueForBlock(ThenBB);
1482 // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf.
1483 // Skip PHIs which are trivial.
1487 HaveRewritablePHIs = true;
1488 ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
1489 ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
1490 if (!OrigCE && !ThenCE)
1491 continue; // Known safe and cheap.
1493 if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE)) ||
1494 (OrigCE && !isSafeToSpeculativelyExecute(OrigCE)))
1496 unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE) : 0;
1497 unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE) : 0;
1498 if (OrigCost + ThenCost > 2 * PHINodeFoldingThreshold)
1501 // Account for the cost of an unfolded ConstantExpr which could end up
1502 // getting expanded into Instructions.
1503 // FIXME: This doesn't account for how many operations are combined in the
1504 // constant expression.
1506 if (SpeculationCost > 1)
1510 // If there are no PHIs to process, bail early. This helps ensure idempotence
1512 if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue))
1515 // If we get here, we can hoist the instruction and if-convert.
1516 DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
1518 // Insert a select of the value of the speculated store.
1519 if (SpeculatedStoreValue) {
1520 IRBuilder<true, NoFolder> Builder(BI);
1521 Value *TrueV = SpeculatedStore->getValueOperand();
1522 Value *FalseV = SpeculatedStoreValue;
1524 std::swap(TrueV, FalseV);
1525 Value *S = Builder.CreateSelect(BrCond, TrueV, FalseV, TrueV->getName() +
1526 "." + FalseV->getName());
1527 SpeculatedStore->setOperand(0, S);
1530 // Hoist the instructions.
1531 BB->getInstList().splice(BI, ThenBB->getInstList(), ThenBB->begin(),
1532 std::prev(ThenBB->end()));
1534 // Insert selects and rewrite the PHI operands.
1535 IRBuilder<true, NoFolder> Builder(BI);
1536 for (BasicBlock::iterator I = EndBB->begin();
1537 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1538 unsigned OrigI = PN->getBasicBlockIndex(BB);
1539 unsigned ThenI = PN->getBasicBlockIndex(ThenBB);
1540 Value *OrigV = PN->getIncomingValue(OrigI);
1541 Value *ThenV = PN->getIncomingValue(ThenI);
1543 // Skip PHIs which are trivial.
1547 // Create a select whose true value is the speculatively executed value and
1548 // false value is the preexisting value. Swap them if the branch
1549 // destinations were inverted.
1550 Value *TrueV = ThenV, *FalseV = OrigV;
1552 std::swap(TrueV, FalseV);
1553 Value *V = Builder.CreateSelect(BrCond, TrueV, FalseV,
1554 TrueV->getName() + "." + FalseV->getName());
1555 PN->setIncomingValue(OrigI, V);
1556 PN->setIncomingValue(ThenI, V);
1563 /// \returns True if this block contains a CallInst with the NoDuplicate
1565 static bool HasNoDuplicateCall(const BasicBlock *BB) {
1566 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1567 const CallInst *CI = dyn_cast<CallInst>(I);
1570 if (CI->cannotDuplicate())
1576 /// BlockIsSimpleEnoughToThreadThrough - Return true if we can thread a branch
1577 /// across this block.
1578 static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
1579 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
1582 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1583 if (isa<DbgInfoIntrinsic>(BBI))
1585 if (Size > 10) return false; // Don't clone large BB's.
1588 // We can only support instructions that do not define values that are
1589 // live outside of the current basic block.
1590 for (User *U : BBI->users()) {
1591 Instruction *UI = cast<Instruction>(U);
1592 if (UI->getParent() != BB || isa<PHINode>(UI)) return false;
1595 // Looks ok, continue checking.
1601 /// FoldCondBranchOnPHI - If we have a conditional branch on a PHI node value
1602 /// that is defined in the same block as the branch and if any PHI entries are
1603 /// constants, thread edges corresponding to that entry to be branches to their
1604 /// ultimate destination.
1605 static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout *DL) {
1606 BasicBlock *BB = BI->getParent();
1607 PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
1608 // NOTE: we currently cannot transform this case if the PHI node is used
1609 // outside of the block.
1610 if (!PN || PN->getParent() != BB || !PN->hasOneUse())
1613 // Degenerate case of a single entry PHI.
1614 if (PN->getNumIncomingValues() == 1) {
1615 FoldSingleEntryPHINodes(PN->getParent());
1619 // Now we know that this block has multiple preds and two succs.
1620 if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
1622 if (HasNoDuplicateCall(BB)) return false;
1624 // Okay, this is a simple enough basic block. See if any phi values are
1626 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1627 ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
1628 if (!CB || !CB->getType()->isIntegerTy(1)) continue;
1630 // Okay, we now know that all edges from PredBB should be revectored to
1631 // branch to RealDest.
1632 BasicBlock *PredBB = PN->getIncomingBlock(i);
1633 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
1635 if (RealDest == BB) continue; // Skip self loops.
1636 // Skip if the predecessor's terminator is an indirect branch.
1637 if (isa<IndirectBrInst>(PredBB->getTerminator())) continue;
1639 // The dest block might have PHI nodes, other predecessors and other
1640 // difficult cases. Instead of being smart about this, just insert a new
1641 // block that jumps to the destination block, effectively splitting
1642 // the edge we are about to create.
1643 BasicBlock *EdgeBB = BasicBlock::Create(BB->getContext(),
1644 RealDest->getName()+".critedge",
1645 RealDest->getParent(), RealDest);
1646 BranchInst::Create(RealDest, EdgeBB);
1648 // Update PHI nodes.
1649 AddPredecessorToBlock(RealDest, EdgeBB, BB);
1651 // BB may have instructions that are being threaded over. Clone these
1652 // instructions into EdgeBB. We know that there will be no uses of the
1653 // cloned instructions outside of EdgeBB.
1654 BasicBlock::iterator InsertPt = EdgeBB->begin();
1655 DenseMap<Value*, Value*> TranslateMap; // Track translated values.
1656 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1657 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
1658 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
1661 // Clone the instruction.
1662 Instruction *N = BBI->clone();
1663 if (BBI->hasName()) N->setName(BBI->getName()+".c");
1665 // Update operands due to translation.
1666 for (User::op_iterator i = N->op_begin(), e = N->op_end();
1668 DenseMap<Value*, Value*>::iterator PI = TranslateMap.find(*i);
1669 if (PI != TranslateMap.end())
1673 // Check for trivial simplification.
1674 if (Value *V = SimplifyInstruction(N, DL)) {
1675 TranslateMap[BBI] = V;
1676 delete N; // Instruction folded away, don't need actual inst
1678 // Insert the new instruction into its new home.
1679 EdgeBB->getInstList().insert(InsertPt, N);
1680 if (!BBI->use_empty())
1681 TranslateMap[BBI] = N;
1685 // Loop over all of the edges from PredBB to BB, changing them to branch
1686 // to EdgeBB instead.
1687 TerminatorInst *PredBBTI = PredBB->getTerminator();
1688 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
1689 if (PredBBTI->getSuccessor(i) == BB) {
1690 BB->removePredecessor(PredBB);
1691 PredBBTI->setSuccessor(i, EdgeBB);
1694 // Recurse, simplifying any other constants.
1695 return FoldCondBranchOnPHI(BI, DL) | true;
1701 /// FoldTwoEntryPHINode - Given a BB that starts with the specified two-entry
1702 /// PHI node, see if we can eliminate it.
1703 static bool FoldTwoEntryPHINode(PHINode *PN, const DataLayout *DL) {
1704 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
1705 // statement", which has a very simple dominance structure. Basically, we
1706 // are trying to find the condition that is being branched on, which
1707 // subsequently causes this merge to happen. We really want control
1708 // dependence information for this check, but simplifycfg can't keep it up
1709 // to date, and this catches most of the cases we care about anyway.
1710 BasicBlock *BB = PN->getParent();
1711 BasicBlock *IfTrue, *IfFalse;
1712 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
1714 // Don't bother if the branch will be constant folded trivially.
1715 isa<ConstantInt>(IfCond))
1718 // Okay, we found that we can merge this two-entry phi node into a select.
1719 // Doing so would require us to fold *all* two entry phi nodes in this block.
1720 // At some point this becomes non-profitable (particularly if the target
1721 // doesn't support cmov's). Only do this transformation if there are two or
1722 // fewer PHI nodes in this block.
1723 unsigned NumPhis = 0;
1724 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
1728 // Loop over the PHI's seeing if we can promote them all to select
1729 // instructions. While we are at it, keep track of the instructions
1730 // that need to be moved to the dominating block.
1731 SmallPtrSet<Instruction*, 4> AggressiveInsts;
1732 unsigned MaxCostVal0 = PHINodeFoldingThreshold,
1733 MaxCostVal1 = PHINodeFoldingThreshold;
1735 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
1736 PHINode *PN = cast<PHINode>(II++);
1737 if (Value *V = SimplifyInstruction(PN, DL)) {
1738 PN->replaceAllUsesWith(V);
1739 PN->eraseFromParent();
1743 if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts,
1745 !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts,
1750 // If we folded the first phi, PN dangles at this point. Refresh it. If
1751 // we ran out of PHIs then we simplified them all.
1752 PN = dyn_cast<PHINode>(BB->begin());
1753 if (!PN) return true;
1755 // Don't fold i1 branches on PHIs which contain binary operators. These can
1756 // often be turned into switches and other things.
1757 if (PN->getType()->isIntegerTy(1) &&
1758 (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
1759 isa<BinaryOperator>(PN->getIncomingValue(1)) ||
1760 isa<BinaryOperator>(IfCond)))
1763 // If we all PHI nodes are promotable, check to make sure that all
1764 // instructions in the predecessor blocks can be promoted as well. If
1765 // not, we won't be able to get rid of the control flow, so it's not
1766 // worth promoting to select instructions.
1767 BasicBlock *DomBlock = nullptr;
1768 BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
1769 BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
1770 if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
1773 DomBlock = *pred_begin(IfBlock1);
1774 for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I)
1775 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
1776 // This is not an aggressive instruction that we can promote.
1777 // Because of this, we won't be able to get rid of the control
1778 // flow, so the xform is not worth it.
1783 if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
1786 DomBlock = *pred_begin(IfBlock2);
1787 for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I)
1788 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
1789 // This is not an aggressive instruction that we can promote.
1790 // Because of this, we won't be able to get rid of the control
1791 // flow, so the xform is not worth it.
1796 DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: "
1797 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
1799 // If we can still promote the PHI nodes after this gauntlet of tests,
1800 // do all of the PHI's now.
1801 Instruction *InsertPt = DomBlock->getTerminator();
1802 IRBuilder<true, NoFolder> Builder(InsertPt);
1804 // Move all 'aggressive' instructions, which are defined in the
1805 // conditional parts of the if's up to the dominating block.
1807 DomBlock->getInstList().splice(InsertPt,
1808 IfBlock1->getInstList(), IfBlock1->begin(),
1809 IfBlock1->getTerminator());
1811 DomBlock->getInstList().splice(InsertPt,
1812 IfBlock2->getInstList(), IfBlock2->begin(),
1813 IfBlock2->getTerminator());
1815 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1816 // Change the PHI node into a select instruction.
1817 Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1818 Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
1821 cast<SelectInst>(Builder.CreateSelect(IfCond, TrueVal, FalseVal, ""));
1822 PN->replaceAllUsesWith(NV);
1824 PN->eraseFromParent();
1827 // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
1828 // has been flattened. Change DomBlock to jump directly to our new block to
1829 // avoid other simplifycfg's kicking in on the diamond.
1830 TerminatorInst *OldTI = DomBlock->getTerminator();
1831 Builder.SetInsertPoint(OldTI);
1832 Builder.CreateBr(BB);
1833 OldTI->eraseFromParent();
1837 /// SimplifyCondBranchToTwoReturns - If we found a conditional branch that goes
1838 /// to two returning blocks, try to merge them together into one return,
1839 /// introducing a select if the return values disagree.
1840 static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
1841 IRBuilder<> &Builder) {
1842 assert(BI->isConditional() && "Must be a conditional branch");
1843 BasicBlock *TrueSucc = BI->getSuccessor(0);
1844 BasicBlock *FalseSucc = BI->getSuccessor(1);
1845 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
1846 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
1848 // Check to ensure both blocks are empty (just a return) or optionally empty
1849 // with PHI nodes. If there are other instructions, merging would cause extra
1850 // computation on one path or the other.
1851 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
1853 if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
1856 Builder.SetInsertPoint(BI);
1857 // Okay, we found a branch that is going to two return nodes. If
1858 // there is no return value for this function, just change the
1859 // branch into a return.
1860 if (FalseRet->getNumOperands() == 0) {
1861 TrueSucc->removePredecessor(BI->getParent());
1862 FalseSucc->removePredecessor(BI->getParent());
1863 Builder.CreateRetVoid();
1864 EraseTerminatorInstAndDCECond(BI);
1868 // Otherwise, figure out what the true and false return values are
1869 // so we can insert a new select instruction.
1870 Value *TrueValue = TrueRet->getReturnValue();
1871 Value *FalseValue = FalseRet->getReturnValue();
1873 // Unwrap any PHI nodes in the return blocks.
1874 if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
1875 if (TVPN->getParent() == TrueSucc)
1876 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
1877 if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
1878 if (FVPN->getParent() == FalseSucc)
1879 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
1881 // In order for this transformation to be safe, we must be able to
1882 // unconditionally execute both operands to the return. This is
1883 // normally the case, but we could have a potentially-trapping
1884 // constant expression that prevents this transformation from being
1886 if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
1889 if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
1893 // Okay, we collected all the mapped values and checked them for sanity, and
1894 // defined to really do this transformation. First, update the CFG.
1895 TrueSucc->removePredecessor(BI->getParent());
1896 FalseSucc->removePredecessor(BI->getParent());
1898 // Insert select instructions where needed.
1899 Value *BrCond = BI->getCondition();
1901 // Insert a select if the results differ.
1902 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
1903 } else if (isa<UndefValue>(TrueValue)) {
1904 TrueValue = FalseValue;
1906 TrueValue = Builder.CreateSelect(BrCond, TrueValue,
1907 FalseValue, "retval");
1911 Value *RI = !TrueValue ?
1912 Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
1916 DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
1917 << "\n " << *BI << "NewRet = " << *RI
1918 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc);
1920 EraseTerminatorInstAndDCECond(BI);
1925 /// ExtractBranchMetadata - Given a conditional BranchInstruction, retrieve the
1926 /// probabilities of the branch taking each edge. Fills in the two APInt
1927 /// parameters and return true, or returns false if no or invalid metadata was
1929 static bool ExtractBranchMetadata(BranchInst *BI,
1930 uint64_t &ProbTrue, uint64_t &ProbFalse) {
1931 assert(BI->isConditional() &&
1932 "Looking for probabilities on unconditional branch?");
1933 MDNode *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
1934 if (!ProfileData || ProfileData->getNumOperands() != 3) return false;
1935 ConstantInt *CITrue = dyn_cast<ConstantInt>(ProfileData->getOperand(1));
1936 ConstantInt *CIFalse = dyn_cast<ConstantInt>(ProfileData->getOperand(2));
1937 if (!CITrue || !CIFalse) return false;
1938 ProbTrue = CITrue->getValue().getZExtValue();
1939 ProbFalse = CIFalse->getValue().getZExtValue();
1943 /// checkCSEInPredecessor - Return true if the given instruction is available
1944 /// in its predecessor block. If yes, the instruction will be removed.
1946 static bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB) {
1947 if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
1949 for (BasicBlock::iterator I = PB->begin(), E = PB->end(); I != E; I++) {
1950 Instruction *PBI = &*I;
1951 // Check whether Inst and PBI generate the same value.
1952 if (Inst->isIdenticalTo(PBI)) {
1953 Inst->replaceAllUsesWith(PBI);
1954 Inst->eraseFromParent();
1961 /// FoldBranchToCommonDest - If this basic block is simple enough, and if a
1962 /// predecessor branches to us and one of our successors, fold the block into
1963 /// the predecessor and use logical operations to pick the right destination.
1964 bool llvm::FoldBranchToCommonDest(BranchInst *BI) {
1965 BasicBlock *BB = BI->getParent();
1967 Instruction *Cond = nullptr;
1968 if (BI->isConditional())
1969 Cond = dyn_cast<Instruction>(BI->getCondition());
1971 // For unconditional branch, check for a simple CFG pattern, where
1972 // BB has a single predecessor and BB's successor is also its predecessor's
1973 // successor. If such pattern exisits, check for CSE between BB and its
1975 if (BasicBlock *PB = BB->getSinglePredecessor())
1976 if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
1977 if (PBI->isConditional() &&
1978 (BI->getSuccessor(0) == PBI->getSuccessor(0) ||
1979 BI->getSuccessor(0) == PBI->getSuccessor(1))) {
1980 for (BasicBlock::iterator I = BB->begin(), E = BB->end();
1982 Instruction *Curr = I++;
1983 if (isa<CmpInst>(Curr)) {
1987 // Quit if we can't remove this instruction.
1988 if (!checkCSEInPredecessor(Curr, PB))
1997 if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
1998 Cond->getParent() != BB || !Cond->hasOneUse())
2001 // Only allow this if the condition is a simple instruction that can be
2002 // executed unconditionally. It must be in the same block as the branch, and
2003 // must be at the front of the block.
2004 BasicBlock::iterator FrontIt = BB->front();
2006 // Ignore dbg intrinsics.
2007 while (isa<DbgInfoIntrinsic>(FrontIt)) ++FrontIt;
2009 // Allow a single instruction to be hoisted in addition to the compare
2010 // that feeds the branch. We later ensure that any values that _it_ uses
2011 // were also live in the predecessor, so that we don't unnecessarily create
2012 // register pressure or inhibit out-of-order execution.
2013 Instruction *BonusInst = nullptr;
2014 if (&*FrontIt != Cond &&
2015 FrontIt->hasOneUse() && FrontIt->user_back() == Cond &&
2016 isSafeToSpeculativelyExecute(FrontIt)) {
2017 BonusInst = &*FrontIt;
2020 // Ignore dbg intrinsics.
2021 while (isa<DbgInfoIntrinsic>(FrontIt)) ++FrontIt;
2024 // Only a single bonus inst is allowed.
2025 if (&*FrontIt != Cond)
2028 // Make sure the instruction after the condition is the cond branch.
2029 BasicBlock::iterator CondIt = Cond; ++CondIt;
2031 // Ingore dbg intrinsics.
2032 while (isa<DbgInfoIntrinsic>(CondIt)) ++CondIt;
2037 // Cond is known to be a compare or binary operator. Check to make sure that
2038 // neither operand is a potentially-trapping constant expression.
2039 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
2042 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
2046 // Finally, don't infinitely unroll conditional loops.
2047 BasicBlock *TrueDest = BI->getSuccessor(0);
2048 BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr;
2049 if (TrueDest == BB || FalseDest == BB)
2052 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2053 BasicBlock *PredBlock = *PI;
2054 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
2056 // Check that we have two conditional branches. If there is a PHI node in
2057 // the common successor, verify that the same value flows in from both
2059 SmallVector<PHINode*, 4> PHIs;
2060 if (!PBI || PBI->isUnconditional() ||
2061 (BI->isConditional() &&
2062 !SafeToMergeTerminators(BI, PBI)) ||
2063 (!BI->isConditional() &&
2064 !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs)))
2067 // Determine if the two branches share a common destination.
2068 Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd;
2069 bool InvertPredCond = false;
2071 if (BI->isConditional()) {
2072 if (PBI->getSuccessor(0) == TrueDest)
2073 Opc = Instruction::Or;
2074 else if (PBI->getSuccessor(1) == FalseDest)
2075 Opc = Instruction::And;
2076 else if (PBI->getSuccessor(0) == FalseDest)
2077 Opc = Instruction::And, InvertPredCond = true;
2078 else if (PBI->getSuccessor(1) == TrueDest)
2079 Opc = Instruction::Or, InvertPredCond = true;
2083 if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest)
2087 // Ensure that any values used in the bonus instruction are also used
2088 // by the terminator of the predecessor. This means that those values
2089 // must already have been resolved, so we won't be inhibiting the
2090 // out-of-order core by speculating them earlier. We also allow
2091 // instructions that are used by the terminator's condition because it
2092 // exposes more merging opportunities.
2093 bool UsedByBranch = (BonusInst && BonusInst->hasOneUse() &&
2094 BonusInst->user_back() == Cond);
2096 if (BonusInst && !UsedByBranch) {
2097 // Collect the values used by the bonus inst
2098 SmallPtrSet<Value*, 4> UsedValues;
2099 for (Instruction::op_iterator OI = BonusInst->op_begin(),
2100 OE = BonusInst->op_end(); OI != OE; ++OI) {
2102 if (!isa<Constant>(V) && !isa<Argument>(V))
2103 UsedValues.insert(V);
2106 SmallVector<std::pair<Value*, unsigned>, 4> Worklist;
2107 Worklist.push_back(std::make_pair(PBI->getOperand(0), 0));
2109 // Walk up to four levels back up the use-def chain of the predecessor's
2110 // terminator to see if all those values were used. The choice of four
2111 // levels is arbitrary, to provide a compile-time-cost bound.
2112 while (!Worklist.empty()) {
2113 std::pair<Value*, unsigned> Pair = Worklist.back();
2114 Worklist.pop_back();
2116 if (Pair.second >= 4) continue;
2117 UsedValues.erase(Pair.first);
2118 if (UsedValues.empty()) break;
2120 if (Instruction *I = dyn_cast<Instruction>(Pair.first)) {
2121 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
2123 Worklist.push_back(std::make_pair(OI->get(), Pair.second+1));
2127 if (!UsedValues.empty()) return false;
2130 DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
2131 IRBuilder<> Builder(PBI);
2133 // If we need to invert the condition in the pred block to match, do so now.
2134 if (InvertPredCond) {
2135 Value *NewCond = PBI->getCondition();
2137 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
2138 CmpInst *CI = cast<CmpInst>(NewCond);
2139 CI->setPredicate(CI->getInversePredicate());
2141 NewCond = Builder.CreateNot(NewCond,
2142 PBI->getCondition()->getName()+".not");
2145 PBI->setCondition(NewCond);
2146 PBI->swapSuccessors();
2149 // If we have a bonus inst, clone it into the predecessor block.
2150 Instruction *NewBonus = nullptr;
2152 NewBonus = BonusInst->clone();
2154 // If we moved a load, we cannot any longer claim any knowledge about
2155 // its potential value. The previous information might have been valid
2156 // only given the branch precondition.
2157 // For an analogous reason, we must also drop all the metadata whose
2158 // semantics we don't understand.
2159 NewBonus->dropUnknownMetadata(LLVMContext::MD_dbg);
2161 PredBlock->getInstList().insert(PBI, NewBonus);
2162 NewBonus->takeName(BonusInst);
2163 BonusInst->setName(BonusInst->getName()+".old");
2166 // Clone Cond into the predecessor basic block, and or/and the
2167 // two conditions together.
2168 Instruction *New = Cond->clone();
2169 if (BonusInst) New->replaceUsesOfWith(BonusInst, NewBonus);
2170 PredBlock->getInstList().insert(PBI, New);
2171 New->takeName(Cond);
2172 Cond->setName(New->getName()+".old");
2174 if (BI->isConditional()) {
2175 Instruction *NewCond =
2176 cast<Instruction>(Builder.CreateBinOp(Opc, PBI->getCondition(),
2178 PBI->setCondition(NewCond);
2180 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2181 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2183 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2185 SmallVector<uint64_t, 8> NewWeights;
2187 if (PBI->getSuccessor(0) == BB) {
2188 if (PredHasWeights && SuccHasWeights) {
2189 // PBI: br i1 %x, BB, FalseDest
2190 // BI: br i1 %y, TrueDest, FalseDest
2191 //TrueWeight is TrueWeight for PBI * TrueWeight for BI.
2192 NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
2193 //FalseWeight is FalseWeight for PBI * TotalWeight for BI +
2194 // TrueWeight for PBI * FalseWeight for BI.
2195 // We assume that total weights of a BranchInst can fit into 32 bits.
2196 // Therefore, we will not have overflow using 64-bit arithmetic.
2197 NewWeights.push_back(PredFalseWeight * (SuccFalseWeight +
2198 SuccTrueWeight) + PredTrueWeight * SuccFalseWeight);
2200 AddPredecessorToBlock(TrueDest, PredBlock, BB);
2201 PBI->setSuccessor(0, TrueDest);
2203 if (PBI->getSuccessor(1) == BB) {
2204 if (PredHasWeights && SuccHasWeights) {
2205 // PBI: br i1 %x, TrueDest, BB
2206 // BI: br i1 %y, TrueDest, FalseDest
2207 //TrueWeight is TrueWeight for PBI * TotalWeight for BI +
2208 // FalseWeight for PBI * TrueWeight for BI.
2209 NewWeights.push_back(PredTrueWeight * (SuccFalseWeight +
2210 SuccTrueWeight) + PredFalseWeight * SuccTrueWeight);
2211 //FalseWeight is FalseWeight for PBI * FalseWeight for BI.
2212 NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
2214 AddPredecessorToBlock(FalseDest, PredBlock, BB);
2215 PBI->setSuccessor(1, FalseDest);
2217 if (NewWeights.size() == 2) {
2218 // Halve the weights if any of them cannot fit in an uint32_t
2219 FitWeights(NewWeights);
2221 SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),NewWeights.end());
2222 PBI->setMetadata(LLVMContext::MD_prof,
2223 MDBuilder(BI->getContext()).
2224 createBranchWeights(MDWeights));
2226 PBI->setMetadata(LLVMContext::MD_prof, nullptr);
2228 // Update PHI nodes in the common successors.
2229 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
2230 ConstantInt *PBI_C = cast<ConstantInt>(
2231 PHIs[i]->getIncomingValueForBlock(PBI->getParent()));
2232 assert(PBI_C->getType()->isIntegerTy(1));
2233 Instruction *MergedCond = nullptr;
2234 if (PBI->getSuccessor(0) == TrueDest) {
2235 // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value)
2236 // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value)
2237 // is false: !PBI_Cond and BI_Value
2238 Instruction *NotCond =
2239 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2242 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2247 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2248 PBI->getCondition(), MergedCond,
2251 // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C)
2252 // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond)
2253 // is false: PBI_Cond and BI_Value
2255 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2256 PBI->getCondition(), New,
2258 if (PBI_C->isOne()) {
2259 Instruction *NotCond =
2260 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2263 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2264 NotCond, MergedCond,
2269 PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()),
2272 // Change PBI from Conditional to Unconditional.
2273 BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI);
2274 EraseTerminatorInstAndDCECond(PBI);
2278 // TODO: If BB is reachable from all paths through PredBlock, then we
2279 // could replace PBI's branch probabilities with BI's.
2281 // Copy any debug value intrinsics into the end of PredBlock.
2282 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
2283 if (isa<DbgInfoIntrinsic>(*I))
2284 I->clone()->insertBefore(PBI);
2291 /// SimplifyCondBranchToCondBranch - If we have a conditional branch as a
2292 /// predecessor of another block, this function tries to simplify it. We know
2293 /// that PBI and BI are both conditional branches, and BI is in one of the
2294 /// successor blocks of PBI - PBI branches to BI.
2295 static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI) {
2296 assert(PBI->isConditional() && BI->isConditional());
2297 BasicBlock *BB = BI->getParent();
2299 // If this block ends with a branch instruction, and if there is a
2300 // predecessor that ends on a branch of the same condition, make
2301 // this conditional branch redundant.
2302 if (PBI->getCondition() == BI->getCondition() &&
2303 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2304 // Okay, the outcome of this conditional branch is statically
2305 // knowable. If this block had a single pred, handle specially.
2306 if (BB->getSinglePredecessor()) {
2307 // Turn this into a branch on constant.
2308 bool CondIsTrue = PBI->getSuccessor(0) == BB;
2309 BI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
2311 return true; // Nuke the branch on constant.
2314 // Otherwise, if there are multiple predecessors, insert a PHI that merges
2315 // in the constant and simplify the block result. Subsequent passes of
2316 // simplifycfg will thread the block.
2317 if (BlockIsSimpleEnoughToThreadThrough(BB)) {
2318 pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
2319 PHINode *NewPN = PHINode::Create(Type::getInt1Ty(BB->getContext()),
2320 std::distance(PB, PE),
2321 BI->getCondition()->getName() + ".pr",
2323 // Okay, we're going to insert the PHI node. Since PBI is not the only
2324 // predecessor, compute the PHI'd conditional value for all of the preds.
2325 // Any predecessor where the condition is not computable we keep symbolic.
2326 for (pred_iterator PI = PB; PI != PE; ++PI) {
2327 BasicBlock *P = *PI;
2328 if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) &&
2329 PBI != BI && PBI->isConditional() &&
2330 PBI->getCondition() == BI->getCondition() &&
2331 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2332 bool CondIsTrue = PBI->getSuccessor(0) == BB;
2333 NewPN->addIncoming(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
2336 NewPN->addIncoming(BI->getCondition(), P);
2340 BI->setCondition(NewPN);
2345 // If this is a conditional branch in an empty block, and if any
2346 // predecessors is a conditional branch to one of our destinations,
2347 // fold the conditions into logical ops and one cond br.
2348 BasicBlock::iterator BBI = BB->begin();
2349 // Ignore dbg intrinsics.
2350 while (isa<DbgInfoIntrinsic>(BBI))
2356 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
2361 if (PBI->getSuccessor(0) == BI->getSuccessor(0))
2363 else if (PBI->getSuccessor(0) == BI->getSuccessor(1))
2364 PBIOp = 0, BIOp = 1;
2365 else if (PBI->getSuccessor(1) == BI->getSuccessor(0))
2366 PBIOp = 1, BIOp = 0;
2367 else if (PBI->getSuccessor(1) == BI->getSuccessor(1))
2372 // Check to make sure that the other destination of this branch
2373 // isn't BB itself. If so, this is an infinite loop that will
2374 // keep getting unwound.
2375 if (PBI->getSuccessor(PBIOp) == BB)
2378 // Do not perform this transformation if it would require
2379 // insertion of a large number of select instructions. For targets
2380 // without predication/cmovs, this is a big pessimization.
2381 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
2383 unsigned NumPhis = 0;
2384 for (BasicBlock::iterator II = CommonDest->begin();
2385 isa<PHINode>(II); ++II, ++NumPhis)
2386 if (NumPhis > 2) // Disable this xform.
2389 // Finally, if everything is ok, fold the branches to logical ops.
2390 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
2392 DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
2393 << "AND: " << *BI->getParent());
2396 // If OtherDest *is* BB, then BB is a basic block with a single conditional
2397 // branch in it, where one edge (OtherDest) goes back to itself but the other
2398 // exits. We don't *know* that the program avoids the infinite loop
2399 // (even though that seems likely). If we do this xform naively, we'll end up
2400 // recursively unpeeling the loop. Since we know that (after the xform is
2401 // done) that the block *is* infinite if reached, we just make it an obviously
2402 // infinite loop with no cond branch.
2403 if (OtherDest == BB) {
2404 // Insert it at the end of the function, because it's either code,
2405 // or it won't matter if it's hot. :)
2406 BasicBlock *InfLoopBlock = BasicBlock::Create(BB->getContext(),
2407 "infloop", BB->getParent());
2408 BranchInst::Create(InfLoopBlock, InfLoopBlock);
2409 OtherDest = InfLoopBlock;
2412 DEBUG(dbgs() << *PBI->getParent()->getParent());
2414 // BI may have other predecessors. Because of this, we leave
2415 // it alone, but modify PBI.
2417 // Make sure we get to CommonDest on True&True directions.
2418 Value *PBICond = PBI->getCondition();
2419 IRBuilder<true, NoFolder> Builder(PBI);
2421 PBICond = Builder.CreateNot(PBICond, PBICond->getName()+".not");
2423 Value *BICond = BI->getCondition();
2425 BICond = Builder.CreateNot(BICond, BICond->getName()+".not");
2427 // Merge the conditions.
2428 Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
2430 // Modify PBI to branch on the new condition to the new dests.
2431 PBI->setCondition(Cond);
2432 PBI->setSuccessor(0, CommonDest);
2433 PBI->setSuccessor(1, OtherDest);
2435 // Update branch weight for PBI.
2436 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2437 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2439 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2441 if (PredHasWeights && SuccHasWeights) {
2442 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
2443 uint64_t PredOther = PBIOp ?PredTrueWeight : PredFalseWeight;
2444 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
2445 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
2446 // The weight to CommonDest should be PredCommon * SuccTotal +
2447 // PredOther * SuccCommon.
2448 // The weight to OtherDest should be PredOther * SuccOther.
2449 SmallVector<uint64_t, 2> NewWeights;
2450 NewWeights.push_back(PredCommon * (SuccCommon + SuccOther) +
2451 PredOther * SuccCommon);
2452 NewWeights.push_back(PredOther * SuccOther);
2453 // Halve the weights if any of them cannot fit in an uint32_t
2454 FitWeights(NewWeights);
2456 SmallVector<uint32_t, 2> MDWeights(NewWeights.begin(),NewWeights.end());
2457 PBI->setMetadata(LLVMContext::MD_prof,
2458 MDBuilder(BI->getContext()).
2459 createBranchWeights(MDWeights));
2462 // OtherDest may have phi nodes. If so, add an entry from PBI's
2463 // block that are identical to the entries for BI's block.
2464 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
2466 // We know that the CommonDest already had an edge from PBI to
2467 // it. If it has PHIs though, the PHIs may have different
2468 // entries for BB and PBI's BB. If so, insert a select to make
2471 for (BasicBlock::iterator II = CommonDest->begin();
2472 (PN = dyn_cast<PHINode>(II)); ++II) {
2473 Value *BIV = PN->getIncomingValueForBlock(BB);
2474 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2475 Value *PBIV = PN->getIncomingValue(PBBIdx);
2477 // Insert a select in PBI to pick the right value.
2478 Value *NV = cast<SelectInst>
2479 (Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName()+".mux"));
2480 PN->setIncomingValue(PBBIdx, NV);
2484 DEBUG(dbgs() << "INTO: " << *PBI->getParent());
2485 DEBUG(dbgs() << *PBI->getParent()->getParent());
2487 // This basic block is probably dead. We know it has at least
2488 // one fewer predecessor.
2492 // SimplifyTerminatorOnSelect - Simplifies a terminator by replacing it with a
2493 // branch to TrueBB if Cond is true or to FalseBB if Cond is false.
2494 // Takes care of updating the successors and removing the old terminator.
2495 // Also makes sure not to introduce new successors by assuming that edges to
2496 // non-successor TrueBBs and FalseBBs aren't reachable.
2497 static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond,
2498 BasicBlock *TrueBB, BasicBlock *FalseBB,
2499 uint32_t TrueWeight,
2500 uint32_t FalseWeight){
2501 // Remove any superfluous successor edges from the CFG.
2502 // First, figure out which successors to preserve.
2503 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
2505 BasicBlock *KeepEdge1 = TrueBB;
2506 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
2508 // Then remove the rest.
2509 for (unsigned I = 0, E = OldTerm->getNumSuccessors(); I != E; ++I) {
2510 BasicBlock *Succ = OldTerm->getSuccessor(I);
2511 // Make sure only to keep exactly one copy of each edge.
2512 if (Succ == KeepEdge1)
2513 KeepEdge1 = nullptr;
2514 else if (Succ == KeepEdge2)
2515 KeepEdge2 = nullptr;
2517 Succ->removePredecessor(OldTerm->getParent());
2520 IRBuilder<> Builder(OldTerm);
2521 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
2523 // Insert an appropriate new terminator.
2524 if (!KeepEdge1 && !KeepEdge2) {
2525 if (TrueBB == FalseBB)
2526 // We were only looking for one successor, and it was present.
2527 // Create an unconditional branch to it.
2528 Builder.CreateBr(TrueBB);
2530 // We found both of the successors we were looking for.
2531 // Create a conditional branch sharing the condition of the select.
2532 BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
2533 if (TrueWeight != FalseWeight)
2534 NewBI->setMetadata(LLVMContext::MD_prof,
2535 MDBuilder(OldTerm->getContext()).
2536 createBranchWeights(TrueWeight, FalseWeight));
2538 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
2539 // Neither of the selected blocks were successors, so this
2540 // terminator must be unreachable.
2541 new UnreachableInst(OldTerm->getContext(), OldTerm);
2543 // One of the selected values was a successor, but the other wasn't.
2544 // Insert an unconditional branch to the one that was found;
2545 // the edge to the one that wasn't must be unreachable.
2547 // Only TrueBB was found.
2548 Builder.CreateBr(TrueBB);
2550 // Only FalseBB was found.
2551 Builder.CreateBr(FalseBB);
2554 EraseTerminatorInstAndDCECond(OldTerm);
2558 // SimplifySwitchOnSelect - Replaces
2559 // (switch (select cond, X, Y)) on constant X, Y
2560 // with a branch - conditional if X and Y lead to distinct BBs,
2561 // unconditional otherwise.
2562 static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
2563 // Check for constant integer values in the select.
2564 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
2565 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
2566 if (!TrueVal || !FalseVal)
2569 // Find the relevant condition and destinations.
2570 Value *Condition = Select->getCondition();
2571 BasicBlock *TrueBB = SI->findCaseValue(TrueVal).getCaseSuccessor();
2572 BasicBlock *FalseBB = SI->findCaseValue(FalseVal).getCaseSuccessor();
2574 // Get weight for TrueBB and FalseBB.
2575 uint32_t TrueWeight = 0, FalseWeight = 0;
2576 SmallVector<uint64_t, 8> Weights;
2577 bool HasWeights = HasBranchWeights(SI);
2579 GetBranchWeights(SI, Weights);
2580 if (Weights.size() == 1 + SI->getNumCases()) {
2581 TrueWeight = (uint32_t)Weights[SI->findCaseValue(TrueVal).
2582 getSuccessorIndex()];
2583 FalseWeight = (uint32_t)Weights[SI->findCaseValue(FalseVal).
2584 getSuccessorIndex()];
2588 // Perform the actual simplification.
2589 return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB,
2590 TrueWeight, FalseWeight);
2593 // SimplifyIndirectBrOnSelect - Replaces
2594 // (indirectbr (select cond, blockaddress(@fn, BlockA),
2595 // blockaddress(@fn, BlockB)))
2597 // (br cond, BlockA, BlockB).
2598 static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
2599 // Check that both operands of the select are block addresses.
2600 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
2601 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
2605 // Extract the actual blocks.
2606 BasicBlock *TrueBB = TBA->getBasicBlock();
2607 BasicBlock *FalseBB = FBA->getBasicBlock();
2609 // Perform the actual simplification.
2610 return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB,
2614 /// TryToSimplifyUncondBranchWithICmpInIt - This is called when we find an icmp
2615 /// instruction (a seteq/setne with a constant) as the only instruction in a
2616 /// block that ends with an uncond branch. We are looking for a very specific
2617 /// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
2618 /// this case, we merge the first two "or's of icmp" into a switch, but then the
2619 /// default value goes to an uncond block with a seteq in it, we get something
2622 /// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
2624 /// %tmp = icmp eq i8 %A, 92
2627 /// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
2629 /// We prefer to split the edge to 'end' so that there is a true/false entry to
2630 /// the PHI, merging the third icmp into the switch.
2631 static bool TryToSimplifyUncondBranchWithICmpInIt(
2632 ICmpInst *ICI, IRBuilder<> &Builder, const TargetTransformInfo &TTI,
2633 const DataLayout *DL) {
2634 BasicBlock *BB = ICI->getParent();
2636 // If the block has any PHIs in it or the icmp has multiple uses, it is too
2638 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) return false;
2640 Value *V = ICI->getOperand(0);
2641 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
2643 // The pattern we're looking for is where our only predecessor is a switch on
2644 // 'V' and this block is the default case for the switch. In this case we can
2645 // fold the compared value into the switch to simplify things.
2646 BasicBlock *Pred = BB->getSinglePredecessor();
2647 if (!Pred || !isa<SwitchInst>(Pred->getTerminator())) return false;
2649 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
2650 if (SI->getCondition() != V)
2653 // If BB is reachable on a non-default case, then we simply know the value of
2654 // V in this block. Substitute it and constant fold the icmp instruction
2656 if (SI->getDefaultDest() != BB) {
2657 ConstantInt *VVal = SI->findCaseDest(BB);
2658 assert(VVal && "Should have a unique destination value");
2659 ICI->setOperand(0, VVal);
2661 if (Value *V = SimplifyInstruction(ICI, DL)) {
2662 ICI->replaceAllUsesWith(V);
2663 ICI->eraseFromParent();
2665 // BB is now empty, so it is likely to simplify away.
2666 return SimplifyCFG(BB, TTI, DL) | true;
2669 // Ok, the block is reachable from the default dest. If the constant we're
2670 // comparing exists in one of the other edges, then we can constant fold ICI
2672 if (SI->findCaseValue(Cst) != SI->case_default()) {
2674 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
2675 V = ConstantInt::getFalse(BB->getContext());
2677 V = ConstantInt::getTrue(BB->getContext());
2679 ICI->replaceAllUsesWith(V);
2680 ICI->eraseFromParent();
2681 // BB is now empty, so it is likely to simplify away.
2682 return SimplifyCFG(BB, TTI, DL) | true;
2685 // The use of the icmp has to be in the 'end' block, by the only PHI node in
2687 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
2688 PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
2689 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
2690 isa<PHINode>(++BasicBlock::iterator(PHIUse)))
2693 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
2695 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
2696 Constant *NewCst = ConstantInt::getFalse(BB->getContext());
2698 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
2699 std::swap(DefaultCst, NewCst);
2701 // Replace ICI (which is used by the PHI for the default value) with true or
2702 // false depending on if it is EQ or NE.
2703 ICI->replaceAllUsesWith(DefaultCst);
2704 ICI->eraseFromParent();
2706 // Okay, the switch goes to this block on a default value. Add an edge from
2707 // the switch to the merge point on the compared value.
2708 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "switch.edge",
2709 BB->getParent(), BB);
2710 SmallVector<uint64_t, 8> Weights;
2711 bool HasWeights = HasBranchWeights(SI);
2713 GetBranchWeights(SI, Weights);
2714 if (Weights.size() == 1 + SI->getNumCases()) {
2715 // Split weight for default case to case for "Cst".
2716 Weights[0] = (Weights[0]+1) >> 1;
2717 Weights.push_back(Weights[0]);
2719 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
2720 SI->setMetadata(LLVMContext::MD_prof,
2721 MDBuilder(SI->getContext()).
2722 createBranchWeights(MDWeights));
2725 SI->addCase(Cst, NewBB);
2727 // NewBB branches to the phi block, add the uncond branch and the phi entry.
2728 Builder.SetInsertPoint(NewBB);
2729 Builder.SetCurrentDebugLocation(SI->getDebugLoc());
2730 Builder.CreateBr(SuccBlock);
2731 PHIUse->addIncoming(NewCst, NewBB);
2735 /// SimplifyBranchOnICmpChain - The specified branch is a conditional branch.
2736 /// Check to see if it is branching on an or/and chain of icmp instructions, and
2737 /// fold it into a switch instruction if so.
2738 static bool SimplifyBranchOnICmpChain(BranchInst *BI, const DataLayout *DL,
2739 IRBuilder<> &Builder) {
2740 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
2741 if (!Cond) return false;
2744 // Change br (X == 0 | X == 1), T, F into a switch instruction.
2745 // If this is a bunch of seteq's or'd together, or if it's a bunch of
2746 // 'setne's and'ed together, collect them.
2747 Value *CompVal = nullptr;
2748 std::vector<ConstantInt*> Values;
2749 bool TrueWhenEqual = true;
2750 Value *ExtraCase = nullptr;
2751 unsigned UsedICmps = 0;
2753 if (Cond->getOpcode() == Instruction::Or) {
2754 CompVal = GatherConstantCompares(Cond, Values, ExtraCase, DL, true,
2756 } else if (Cond->getOpcode() == Instruction::And) {
2757 CompVal = GatherConstantCompares(Cond, Values, ExtraCase, DL, false,
2759 TrueWhenEqual = false;
2762 // If we didn't have a multiply compared value, fail.
2763 if (!CompVal) return false;
2765 // Avoid turning single icmps into a switch.
2769 // There might be duplicate constants in the list, which the switch
2770 // instruction can't handle, remove them now.
2771 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
2772 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
2774 // If Extra was used, we require at least two switch values to do the
2775 // transformation. A switch with one value is just an cond branch.
2776 if (ExtraCase && Values.size() < 2) return false;
2778 // TODO: Preserve branch weight metadata, similarly to how
2779 // FoldValueComparisonIntoPredecessors preserves it.
2781 // Figure out which block is which destination.
2782 BasicBlock *DefaultBB = BI->getSuccessor(1);
2783 BasicBlock *EdgeBB = BI->getSuccessor(0);
2784 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
2786 BasicBlock *BB = BI->getParent();
2788 DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
2789 << " cases into SWITCH. BB is:\n" << *BB);
2791 // If there are any extra values that couldn't be folded into the switch
2792 // then we evaluate them with an explicit branch first. Split the block
2793 // right before the condbr to handle it.
2795 BasicBlock *NewBB = BB->splitBasicBlock(BI, "switch.early.test");
2796 // Remove the uncond branch added to the old block.
2797 TerminatorInst *OldTI = BB->getTerminator();
2798 Builder.SetInsertPoint(OldTI);
2801 Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
2803 Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
2805 OldTI->eraseFromParent();
2807 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
2808 // for the edge we just added.
2809 AddPredecessorToBlock(EdgeBB, BB, NewBB);
2811 DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
2812 << "\nEXTRABB = " << *BB);
2816 Builder.SetInsertPoint(BI);
2817 // Convert pointer to int before we switch.
2818 if (CompVal->getType()->isPointerTy()) {
2819 assert(DL && "Cannot switch on pointer without DataLayout");
2820 CompVal = Builder.CreatePtrToInt(CompVal,
2821 DL->getIntPtrType(CompVal->getType()),
2825 // Create the new switch instruction now.
2826 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
2828 // Add all of the 'cases' to the switch instruction.
2829 for (unsigned i = 0, e = Values.size(); i != e; ++i)
2830 New->addCase(Values[i], EdgeBB);
2832 // We added edges from PI to the EdgeBB. As such, if there were any
2833 // PHI nodes in EdgeBB, they need entries to be added corresponding to
2834 // the number of edges added.
2835 for (BasicBlock::iterator BBI = EdgeBB->begin();
2836 isa<PHINode>(BBI); ++BBI) {
2837 PHINode *PN = cast<PHINode>(BBI);
2838 Value *InVal = PN->getIncomingValueForBlock(BB);
2839 for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
2840 PN->addIncoming(InVal, BB);
2843 // Erase the old branch instruction.
2844 EraseTerminatorInstAndDCECond(BI);
2846 DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
2850 bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
2851 // If this is a trivial landing pad that just continues unwinding the caught
2852 // exception then zap the landing pad, turning its invokes into calls.
2853 BasicBlock *BB = RI->getParent();
2854 LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI());
2855 if (RI->getValue() != LPInst)
2856 // Not a landing pad, or the resume is not unwinding the exception that
2857 // caused control to branch here.
2860 // Check that there are no other instructions except for debug intrinsics.
2861 BasicBlock::iterator I = LPInst, E = RI;
2863 if (!isa<DbgInfoIntrinsic>(I))
2866 // Turn all invokes that unwind here into calls and delete the basic block.
2867 bool InvokeRequiresTableEntry = false;
2868 bool Changed = false;
2869 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
2870 InvokeInst *II = cast<InvokeInst>((*PI++)->getTerminator());
2872 if (II->hasFnAttr(Attribute::UWTable)) {
2873 // Don't remove an `invoke' instruction if the ABI requires an entry into
2875 InvokeRequiresTableEntry = true;
2879 SmallVector<Value*, 8> Args(II->op_begin(), II->op_end() - 3);
2881 // Insert a call instruction before the invoke.
2882 CallInst *Call = CallInst::Create(II->getCalledValue(), Args, "", II);
2884 Call->setCallingConv(II->getCallingConv());
2885 Call->setAttributes(II->getAttributes());
2886 Call->setDebugLoc(II->getDebugLoc());
2888 // Anything that used the value produced by the invoke instruction now uses
2889 // the value produced by the call instruction. Note that we do this even
2890 // for void functions and calls with no uses so that the callgraph edge is
2892 II->replaceAllUsesWith(Call);
2893 BB->removePredecessor(II->getParent());
2895 // Insert a branch to the normal destination right before the invoke.
2896 BranchInst::Create(II->getNormalDest(), II);
2898 // Finally, delete the invoke instruction!
2899 II->eraseFromParent();
2903 if (!InvokeRequiresTableEntry)
2904 // The landingpad is now unreachable. Zap it.
2905 BB->eraseFromParent();
2910 bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
2911 BasicBlock *BB = RI->getParent();
2912 if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
2914 // Find predecessors that end with branches.
2915 SmallVector<BasicBlock*, 8> UncondBranchPreds;
2916 SmallVector<BranchInst*, 8> CondBranchPreds;
2917 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2918 BasicBlock *P = *PI;
2919 TerminatorInst *PTI = P->getTerminator();
2920 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
2921 if (BI->isUnconditional())
2922 UncondBranchPreds.push_back(P);
2924 CondBranchPreds.push_back(BI);
2928 // If we found some, do the transformation!
2929 if (!UncondBranchPreds.empty() && DupRet) {
2930 while (!UncondBranchPreds.empty()) {
2931 BasicBlock *Pred = UncondBranchPreds.pop_back_val();
2932 DEBUG(dbgs() << "FOLDING: " << *BB
2933 << "INTO UNCOND BRANCH PRED: " << *Pred);
2934 (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
2937 // If we eliminated all predecessors of the block, delete the block now.
2938 if (pred_begin(BB) == pred_end(BB))
2939 // We know there are no successors, so just nuke the block.
2940 BB->eraseFromParent();
2945 // Check out all of the conditional branches going to this return
2946 // instruction. If any of them just select between returns, change the
2947 // branch itself into a select/return pair.
2948 while (!CondBranchPreds.empty()) {
2949 BranchInst *BI = CondBranchPreds.pop_back_val();
2951 // Check to see if the non-BB successor is also a return block.
2952 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
2953 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
2954 SimplifyCondBranchToTwoReturns(BI, Builder))
2960 bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
2961 BasicBlock *BB = UI->getParent();
2963 bool Changed = false;
2965 // If there are any instructions immediately before the unreachable that can
2966 // be removed, do so.
2967 while (UI != BB->begin()) {
2968 BasicBlock::iterator BBI = UI;
2970 // Do not delete instructions that can have side effects which might cause
2971 // the unreachable to not be reachable; specifically, calls and volatile
2972 // operations may have this effect.
2973 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break;
2975 if (BBI->mayHaveSideEffects()) {
2976 if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
2977 if (SI->isVolatile())
2979 } else if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
2980 if (LI->isVolatile())
2982 } else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
2983 if (RMWI->isVolatile())
2985 } else if (AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
2986 if (CXI->isVolatile())
2988 } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
2989 !isa<LandingPadInst>(BBI)) {
2992 // Note that deleting LandingPad's here is in fact okay, although it
2993 // involves a bit of subtle reasoning. If this inst is a LandingPad,
2994 // all the predecessors of this block will be the unwind edges of Invokes,
2995 // and we can therefore guarantee this block will be erased.
2998 // Delete this instruction (any uses are guaranteed to be dead)
2999 if (!BBI->use_empty())
3000 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
3001 BBI->eraseFromParent();
3005 // If the unreachable instruction is the first in the block, take a gander
3006 // at all of the predecessors of this instruction, and simplify them.
3007 if (&BB->front() != UI) return Changed;
3009 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
3010 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
3011 TerminatorInst *TI = Preds[i]->getTerminator();
3012 IRBuilder<> Builder(TI);
3013 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
3014 if (BI->isUnconditional()) {
3015 if (BI->getSuccessor(0) == BB) {
3016 new UnreachableInst(TI->getContext(), TI);
3017 TI->eraseFromParent();
3021 if (BI->getSuccessor(0) == BB) {
3022 Builder.CreateBr(BI->getSuccessor(1));
3023 EraseTerminatorInstAndDCECond(BI);
3024 } else if (BI->getSuccessor(1) == BB) {
3025 Builder.CreateBr(BI->getSuccessor(0));
3026 EraseTerminatorInstAndDCECond(BI);
3030 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
3031 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
3033 if (i.getCaseSuccessor() == BB) {
3034 BB->removePredecessor(SI->getParent());
3039 // If the default value is unreachable, figure out the most popular
3040 // destination and make it the default.
3041 if (SI->getDefaultDest() == BB) {
3042 std::map<BasicBlock*, std::pair<unsigned, unsigned> > Popularity;
3043 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
3045 std::pair<unsigned, unsigned> &entry =
3046 Popularity[i.getCaseSuccessor()];
3047 if (entry.first == 0) {
3049 entry.second = i.getCaseIndex();
3055 // Find the most popular block.
3056 unsigned MaxPop = 0;
3057 unsigned MaxIndex = 0;
3058 BasicBlock *MaxBlock = nullptr;
3059 for (std::map<BasicBlock*, std::pair<unsigned, unsigned> >::iterator
3060 I = Popularity.begin(), E = Popularity.end(); I != E; ++I) {
3061 if (I->second.first > MaxPop ||
3062 (I->second.first == MaxPop && MaxIndex > I->second.second)) {
3063 MaxPop = I->second.first;
3064 MaxIndex = I->second.second;
3065 MaxBlock = I->first;
3069 // Make this the new default, allowing us to delete any explicit
3071 SI->setDefaultDest(MaxBlock);
3074 // If MaxBlock has phinodes in it, remove MaxPop-1 entries from
3076 if (isa<PHINode>(MaxBlock->begin()))
3077 for (unsigned i = 0; i != MaxPop-1; ++i)
3078 MaxBlock->removePredecessor(SI->getParent());
3080 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
3082 if (i.getCaseSuccessor() == MaxBlock) {
3088 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
3089 if (II->getUnwindDest() == BB) {
3090 // Convert the invoke to a call instruction. This would be a good
3091 // place to note that the call does not throw though.
3092 BranchInst *BI = Builder.CreateBr(II->getNormalDest());
3093 II->removeFromParent(); // Take out of symbol table
3095 // Insert the call now...
3096 SmallVector<Value*, 8> Args(II->op_begin(), II->op_end()-3);
3097 Builder.SetInsertPoint(BI);
3098 CallInst *CI = Builder.CreateCall(II->getCalledValue(),
3099 Args, II->getName());
3100 CI->setCallingConv(II->getCallingConv());
3101 CI->setAttributes(II->getAttributes());
3102 // If the invoke produced a value, the call does now instead.
3103 II->replaceAllUsesWith(CI);
3110 // If this block is now dead, remove it.
3111 if (pred_begin(BB) == pred_end(BB) &&
3112 BB != &BB->getParent()->getEntryBlock()) {
3113 // We know there are no successors, so just nuke the block.
3114 BB->eraseFromParent();
3121 /// TurnSwitchRangeIntoICmp - Turns a switch with that contains only a
3122 /// integer range comparison into a sub, an icmp and a branch.
3123 static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
3124 assert(SI->getNumCases() > 1 && "Degenerate switch?");
3126 // Make sure all cases point to the same destination and gather the values.
3127 SmallVector<ConstantInt *, 16> Cases;
3128 SwitchInst::CaseIt I = SI->case_begin();
3129 Cases.push_back(I.getCaseValue());
3130 SwitchInst::CaseIt PrevI = I++;
3131 for (SwitchInst::CaseIt E = SI->case_end(); I != E; PrevI = I++) {
3132 if (PrevI.getCaseSuccessor() != I.getCaseSuccessor())
3134 Cases.push_back(I.getCaseValue());
3136 assert(Cases.size() == SI->getNumCases() && "Not all cases gathered");
3138 // Sort the case values, then check if they form a range we can transform.
3139 array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
3140 for (unsigned I = 1, E = Cases.size(); I != E; ++I) {
3141 if (Cases[I-1]->getValue() != Cases[I]->getValue()+1)
3145 Constant *Offset = ConstantExpr::getNeg(Cases.back());
3146 Constant *NumCases = ConstantInt::get(Offset->getType(), SI->getNumCases());
3148 Value *Sub = SI->getCondition();
3149 if (!Offset->isNullValue())
3150 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName()+".off");
3152 // If NumCases overflowed, then all possible values jump to the successor.
3153 if (NumCases->isNullValue() && SI->getNumCases() != 0)
3154 Cmp = ConstantInt::getTrue(SI->getContext());
3156 Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
3157 BranchInst *NewBI = Builder.CreateCondBr(
3158 Cmp, SI->case_begin().getCaseSuccessor(), SI->getDefaultDest());
3160 // Update weight for the newly-created conditional branch.
3161 SmallVector<uint64_t, 8> Weights;
3162 bool HasWeights = HasBranchWeights(SI);
3164 GetBranchWeights(SI, Weights);
3165 if (Weights.size() == 1 + SI->getNumCases()) {
3166 // Combine all weights for the cases to be the true weight of NewBI.
3167 // We assume that the sum of all weights for a Terminator can fit into 32
3169 uint32_t NewTrueWeight = 0;
3170 for (unsigned I = 1, E = Weights.size(); I != E; ++I)
3171 NewTrueWeight += (uint32_t)Weights[I];
3172 NewBI->setMetadata(LLVMContext::MD_prof,
3173 MDBuilder(SI->getContext()).
3174 createBranchWeights(NewTrueWeight,
3175 (uint32_t)Weights[0]));
3179 // Prune obsolete incoming values off the successor's PHI nodes.
3180 for (BasicBlock::iterator BBI = SI->case_begin().getCaseSuccessor()->begin();
3181 isa<PHINode>(BBI); ++BBI) {
3182 for (unsigned I = 0, E = SI->getNumCases()-1; I != E; ++I)
3183 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
3185 SI->eraseFromParent();
3190 /// EliminateDeadSwitchCases - Compute masked bits for the condition of a switch
3191 /// and use it to remove dead cases.
3192 static bool EliminateDeadSwitchCases(SwitchInst *SI) {
3193 Value *Cond = SI->getCondition();
3194 unsigned Bits = Cond->getType()->getIntegerBitWidth();
3195 APInt KnownZero(Bits, 0), KnownOne(Bits, 0);
3196 computeKnownBits(Cond, KnownZero, KnownOne);
3198 // Gather dead cases.
3199 SmallVector<ConstantInt*, 8> DeadCases;
3200 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
3201 if ((I.getCaseValue()->getValue() & KnownZero) != 0 ||
3202 (I.getCaseValue()->getValue() & KnownOne) != KnownOne) {
3203 DeadCases.push_back(I.getCaseValue());
3204 DEBUG(dbgs() << "SimplifyCFG: switch case '"
3205 << I.getCaseValue() << "' is dead.\n");
3209 SmallVector<uint64_t, 8> Weights;
3210 bool HasWeight = HasBranchWeights(SI);
3212 GetBranchWeights(SI, Weights);
3213 HasWeight = (Weights.size() == 1 + SI->getNumCases());
3216 // Remove dead cases from the switch.
3217 for (unsigned I = 0, E = DeadCases.size(); I != E; ++I) {
3218 SwitchInst::CaseIt Case = SI->findCaseValue(DeadCases[I]);
3219 assert(Case != SI->case_default() &&
3220 "Case was not found. Probably mistake in DeadCases forming.");
3222 std::swap(Weights[Case.getCaseIndex()+1], Weights.back());
3226 // Prune unused values from PHI nodes.
3227 Case.getCaseSuccessor()->removePredecessor(SI->getParent());
3228 SI->removeCase(Case);
3230 if (HasWeight && Weights.size() >= 2) {
3231 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
3232 SI->setMetadata(LLVMContext::MD_prof,
3233 MDBuilder(SI->getParent()->getContext()).
3234 createBranchWeights(MDWeights));
3237 return !DeadCases.empty();
3240 /// FindPHIForConditionForwarding - If BB would be eligible for simplification
3241 /// by TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
3242 /// by an unconditional branch), look at the phi node for BB in the successor
3243 /// block and see if the incoming value is equal to CaseValue. If so, return
3244 /// the phi node, and set PhiIndex to BB's index in the phi node.
3245 static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
3248 if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
3249 return nullptr; // BB must be empty to be a candidate for simplification.
3250 if (!BB->getSinglePredecessor())
3251 return nullptr; // BB must be dominated by the switch.
3253 BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
3254 if (!Branch || !Branch->isUnconditional())
3255 return nullptr; // Terminator must be unconditional branch.
3257 BasicBlock *Succ = Branch->getSuccessor(0);
3259 BasicBlock::iterator I = Succ->begin();
3260 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3261 int Idx = PHI->getBasicBlockIndex(BB);
3262 assert(Idx >= 0 && "PHI has no entry for predecessor?");
3264 Value *InValue = PHI->getIncomingValue(Idx);
3265 if (InValue != CaseValue) continue;
3274 /// ForwardSwitchConditionToPHI - Try to forward the condition of a switch
3275 /// instruction to a phi node dominated by the switch, if that would mean that
3276 /// some of the destination blocks of the switch can be folded away.
3277 /// Returns true if a change is made.
3278 static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
3279 typedef DenseMap<PHINode*, SmallVector<int,4> > ForwardingNodesMap;
3280 ForwardingNodesMap ForwardingNodes;
3282 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
3283 ConstantInt *CaseValue = I.getCaseValue();
3284 BasicBlock *CaseDest = I.getCaseSuccessor();
3287 PHINode *PHI = FindPHIForConditionForwarding(CaseValue, CaseDest,
3291 ForwardingNodes[PHI].push_back(PhiIndex);
3294 bool Changed = false;
3296 for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(),
3297 E = ForwardingNodes.end(); I != E; ++I) {
3298 PHINode *Phi = I->first;
3299 SmallVectorImpl<int> &Indexes = I->second;
3301 if (Indexes.size() < 2) continue;
3303 for (size_t I = 0, E = Indexes.size(); I != E; ++I)
3304 Phi->setIncomingValue(Indexes[I], SI->getCondition());
3311 /// ValidLookupTableConstant - Return true if the backend will be able to handle
3312 /// initializing an array of constants like C.
3313 static bool ValidLookupTableConstant(Constant *C) {
3314 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
3315 return CE->isGEPWithNoNotionalOverIndexing();
3317 return isa<ConstantFP>(C) ||
3318 isa<ConstantInt>(C) ||
3319 isa<ConstantPointerNull>(C) ||
3320 isa<GlobalValue>(C) ||
3324 /// LookupConstant - If V is a Constant, return it. Otherwise, try to look up
3325 /// its constant value in ConstantPool, returning 0 if it's not there.
3326 static Constant *LookupConstant(Value *V,
3327 const SmallDenseMap<Value*, Constant*>& ConstantPool) {
3328 if (Constant *C = dyn_cast<Constant>(V))
3330 return ConstantPool.lookup(V);
3333 /// ConstantFold - Try to fold instruction I into a constant. This works for
3334 /// simple instructions such as binary operations where both operands are
3335 /// constant or can be replaced by constants from the ConstantPool. Returns the
3336 /// resulting constant on success, 0 otherwise.
3338 ConstantFold(Instruction *I,
3339 const SmallDenseMap<Value *, Constant *> &ConstantPool,
3340 const DataLayout *DL) {
3341 if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
3342 Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
3345 if (A->isAllOnesValue())
3346 return LookupConstant(Select->getTrueValue(), ConstantPool);
3347 if (A->isNullValue())
3348 return LookupConstant(Select->getFalseValue(), ConstantPool);
3352 SmallVector<Constant *, 4> COps;
3353 for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
3354 if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
3360 if (CmpInst *Cmp = dyn_cast<CmpInst>(I))
3361 return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0],
3364 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), COps, DL);
3367 /// GetCaseResults - Try to determine the resulting constant values in phi nodes
3368 /// at the common destination basic block, *CommonDest, for one of the case
3369 /// destionations CaseDest corresponding to value CaseVal (0 for the default
3370 /// case), of a switch instruction SI.
3372 GetCaseResults(SwitchInst *SI,
3373 ConstantInt *CaseVal,
3374 BasicBlock *CaseDest,
3375 BasicBlock **CommonDest,
3376 SmallVectorImpl<std::pair<PHINode *, Constant *> > &Res,
3377 const DataLayout *DL) {
3378 // The block from which we enter the common destination.
3379 BasicBlock *Pred = SI->getParent();
3381 // If CaseDest is empty except for some side-effect free instructions through
3382 // which we can constant-propagate the CaseVal, continue to its successor.
3383 SmallDenseMap<Value*, Constant*> ConstantPool;
3384 ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
3385 for (BasicBlock::iterator I = CaseDest->begin(), E = CaseDest->end(); I != E;
3387 if (TerminatorInst *T = dyn_cast<TerminatorInst>(I)) {
3388 // If the terminator is a simple branch, continue to the next block.
3389 if (T->getNumSuccessors() != 1)
3392 CaseDest = T->getSuccessor(0);
3393 } else if (isa<DbgInfoIntrinsic>(I)) {
3394 // Skip debug intrinsic.
3396 } else if (Constant *C = ConstantFold(I, ConstantPool, DL)) {
3397 // Instruction is side-effect free and constant.
3398 ConstantPool.insert(std::make_pair(I, C));
3404 // If we did not have a CommonDest before, use the current one.
3406 *CommonDest = CaseDest;
3407 // If the destination isn't the common one, abort.
3408 if (CaseDest != *CommonDest)
3411 // Get the values for this case from phi nodes in the destination block.
3412 BasicBlock::iterator I = (*CommonDest)->begin();
3413 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3414 int Idx = PHI->getBasicBlockIndex(Pred);
3418 Constant *ConstVal = LookupConstant(PHI->getIncomingValue(Idx),
3423 // Note: If the constant comes from constant-propagating the case value
3424 // through the CaseDest basic block, it will be safe to remove the
3425 // instructions in that block. They cannot be used (except in the phi nodes
3426 // we visit) outside CaseDest, because that block does not dominate its
3427 // successor. If it did, we would not be in this phi node.
3429 // Be conservative about which kinds of constants we support.
3430 if (!ValidLookupTableConstant(ConstVal))
3433 Res.push_back(std::make_pair(PHI, ConstVal));
3436 return Res.size() > 0;
3440 /// SwitchLookupTable - This class represents a lookup table that can be used
3441 /// to replace a switch.
3442 class SwitchLookupTable {
3444 /// SwitchLookupTable - Create a lookup table to use as a switch replacement
3445 /// with the contents of Values, using DefaultValue to fill any holes in the
3447 SwitchLookupTable(Module &M,
3449 ConstantInt *Offset,
3450 const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values,
3451 Constant *DefaultValue,
3452 const DataLayout *DL);
3454 /// BuildLookup - Build instructions with Builder to retrieve the value at
3455 /// the position given by Index in the lookup table.
3456 Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
3458 /// WouldFitInRegister - Return true if a table with TableSize elements of
3459 /// type ElementType would fit in a target-legal register.
3460 static bool WouldFitInRegister(const DataLayout *DL,
3462 const Type *ElementType);
3465 // Depending on the contents of the table, it can be represented in
3468 // For tables where each element contains the same value, we just have to
3469 // store that single value and return it for each lookup.
3472 // For small tables with integer elements, we can pack them into a bitmap
3473 // that fits into a target-legal register. Values are retrieved by
3474 // shift and mask operations.
3477 // The table is stored as an array of values. Values are retrieved by load
3478 // instructions from the table.
3482 // For SingleValueKind, this is the single value.
3483 Constant *SingleValue;
3485 // For BitMapKind, this is the bitmap.
3486 ConstantInt *BitMap;
3487 IntegerType *BitMapElementTy;
3489 // For ArrayKind, this is the array.
3490 GlobalVariable *Array;
3494 SwitchLookupTable::SwitchLookupTable(Module &M,
3496 ConstantInt *Offset,
3497 const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values,
3498 Constant *DefaultValue,
3499 const DataLayout *DL)
3500 : SingleValue(nullptr), BitMap(nullptr), BitMapElementTy(nullptr),
3502 assert(Values.size() && "Can't build lookup table without values!");
3503 assert(TableSize >= Values.size() && "Can't fit values in table!");
3505 // If all values in the table are equal, this is that value.
3506 SingleValue = Values.begin()->second;
3508 Type *ValueType = Values.begin()->second->getType();
3510 // Build up the table contents.
3511 SmallVector<Constant*, 64> TableContents(TableSize);
3512 for (size_t I = 0, E = Values.size(); I != E; ++I) {
3513 ConstantInt *CaseVal = Values[I].first;
3514 Constant *CaseRes = Values[I].second;
3515 assert(CaseRes->getType() == ValueType);
3517 uint64_t Idx = (CaseVal->getValue() - Offset->getValue())
3519 TableContents[Idx] = CaseRes;
3521 if (CaseRes != SingleValue)
3522 SingleValue = nullptr;
3525 // Fill in any holes in the table with the default result.
3526 if (Values.size() < TableSize) {
3527 assert(DefaultValue && "Need a default value to fill the lookup table holes.");
3528 assert(DefaultValue->getType() == ValueType);
3529 for (uint64_t I = 0; I < TableSize; ++I) {
3530 if (!TableContents[I])
3531 TableContents[I] = DefaultValue;
3534 if (DefaultValue != SingleValue)
3535 SingleValue = nullptr;
3538 // If each element in the table contains the same value, we only need to store
3539 // that single value.
3541 Kind = SingleValueKind;
3545 // If the type is integer and the table fits in a register, build a bitmap.
3546 if (WouldFitInRegister(DL, TableSize, ValueType)) {
3547 IntegerType *IT = cast<IntegerType>(ValueType);
3548 APInt TableInt(TableSize * IT->getBitWidth(), 0);
3549 for (uint64_t I = TableSize; I > 0; --I) {
3550 TableInt <<= IT->getBitWidth();
3551 // Insert values into the bitmap. Undef values are set to zero.
3552 if (!isa<UndefValue>(TableContents[I - 1])) {
3553 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
3554 TableInt |= Val->getValue().zext(TableInt.getBitWidth());
3557 BitMap = ConstantInt::get(M.getContext(), TableInt);
3558 BitMapElementTy = IT;
3564 // Store the table in an array.
3565 ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
3566 Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
3568 Array = new GlobalVariable(M, ArrayTy, /*constant=*/ true,
3569 GlobalVariable::PrivateLinkage,
3572 Array->setUnnamedAddr(true);
3576 Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
3578 case SingleValueKind:
3581 // Type of the bitmap (e.g. i59).
3582 IntegerType *MapTy = BitMap->getType();
3584 // Cast Index to the same type as the bitmap.
3585 // Note: The Index is <= the number of elements in the table, so
3586 // truncating it to the width of the bitmask is safe.
3587 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
3589 // Multiply the shift amount by the element width.
3590 ShiftAmt = Builder.CreateMul(ShiftAmt,
3591 ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
3595 Value *DownShifted = Builder.CreateLShr(BitMap, ShiftAmt,
3596 "switch.downshift");
3598 return Builder.CreateTrunc(DownShifted, BitMapElementTy,
3602 Value *GEPIndices[] = { Builder.getInt32(0), Index };
3603 Value *GEP = Builder.CreateInBoundsGEP(Array, GEPIndices,
3605 return Builder.CreateLoad(GEP, "switch.load");
3608 llvm_unreachable("Unknown lookup table kind!");
3611 bool SwitchLookupTable::WouldFitInRegister(const DataLayout *DL,
3613 const Type *ElementType) {
3616 const IntegerType *IT = dyn_cast<IntegerType>(ElementType);
3619 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
3620 // are <= 15, we could try to narrow the type.
3622 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
3623 if (TableSize >= UINT_MAX/IT->getBitWidth())
3625 return DL->fitsInLegalInteger(TableSize * IT->getBitWidth());
3628 /// ShouldBuildLookupTable - Determine whether a lookup table should be built
3629 /// for this switch, based on the number of cases, size of the table and the
3630 /// types of the results.
3631 static bool ShouldBuildLookupTable(SwitchInst *SI,
3633 const TargetTransformInfo &TTI,
3634 const DataLayout *DL,
3635 const SmallDenseMap<PHINode*, Type*>& ResultTypes) {
3636 if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
3637 return false; // TableSize overflowed, or mul below might overflow.
3639 bool AllTablesFitInRegister = true;
3640 bool HasIllegalType = false;
3641 for (SmallDenseMap<PHINode*, Type*>::const_iterator I = ResultTypes.begin(),
3642 E = ResultTypes.end(); I != E; ++I) {
3643 Type *Ty = I->second;
3645 // Saturate this flag to true.
3646 HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty);
3648 // Saturate this flag to false.
3649 AllTablesFitInRegister = AllTablesFitInRegister &&
3650 SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
3652 // If both flags saturate, we're done. NOTE: This *only* works with
3653 // saturating flags, and all flags have to saturate first due to the
3654 // non-deterministic behavior of iterating over a dense map.
3655 if (HasIllegalType && !AllTablesFitInRegister)
3659 // If each table would fit in a register, we should build it anyway.
3660 if (AllTablesFitInRegister)
3663 // Don't build a table that doesn't fit in-register if it has illegal types.
3667 // The table density should be at least 40%. This is the same criterion as for
3668 // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
3669 // FIXME: Find the best cut-off.
3670 return SI->getNumCases() * 10 >= TableSize * 4;
3673 /// SwitchToLookupTable - If the switch is only used to initialize one or more
3674 /// phi nodes in a common successor block with different constant values,
3675 /// replace the switch with lookup tables.
3676 static bool SwitchToLookupTable(SwitchInst *SI,
3677 IRBuilder<> &Builder,
3678 const TargetTransformInfo &TTI,
3679 const DataLayout* DL) {
3680 assert(SI->getNumCases() > 1 && "Degenerate switch?");
3682 // Only build lookup table when we have a target that supports it.
3683 if (!TTI.shouldBuildLookupTables())
3686 // FIXME: If the switch is too sparse for a lookup table, perhaps we could
3687 // split off a dense part and build a lookup table for that.
3689 // FIXME: This creates arrays of GEPs to constant strings, which means each
3690 // GEP needs a runtime relocation in PIC code. We should just build one big
3691 // string and lookup indices into that.
3693 // Ignore switches with less than three cases. Lookup tables will not make them
3694 // faster, so we don't analyze them.
3695 if (SI->getNumCases() < 3)
3698 // Figure out the corresponding result for each case value and phi node in the
3699 // common destination, as well as the the min and max case values.
3700 assert(SI->case_begin() != SI->case_end());
3701 SwitchInst::CaseIt CI = SI->case_begin();
3702 ConstantInt *MinCaseVal = CI.getCaseValue();
3703 ConstantInt *MaxCaseVal = CI.getCaseValue();
3705 BasicBlock *CommonDest = nullptr;
3706 typedef SmallVector<std::pair<ConstantInt*, Constant*>, 4> ResultListTy;
3707 SmallDenseMap<PHINode*, ResultListTy> ResultLists;
3708 SmallDenseMap<PHINode*, Constant*> DefaultResults;
3709 SmallDenseMap<PHINode*, Type*> ResultTypes;
3710 SmallVector<PHINode*, 4> PHIs;
3712 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
3713 ConstantInt *CaseVal = CI.getCaseValue();
3714 if (CaseVal->getValue().slt(MinCaseVal->getValue()))
3715 MinCaseVal = CaseVal;
3716 if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
3717 MaxCaseVal = CaseVal;
3719 // Resulting value at phi nodes for this case value.
3720 typedef SmallVector<std::pair<PHINode*, Constant*>, 4> ResultsTy;
3722 if (!GetCaseResults(SI, CaseVal, CI.getCaseSuccessor(), &CommonDest,
3726 // Append the result from this case to the list for each phi.
3727 for (ResultsTy::iterator I = Results.begin(), E = Results.end(); I!=E; ++I) {
3728 if (!ResultLists.count(I->first))
3729 PHIs.push_back(I->first);
3730 ResultLists[I->first].push_back(std::make_pair(CaseVal, I->second));
3734 // Keep track of the result types.
3735 for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
3736 PHINode *PHI = PHIs[I];
3737 ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
3740 uint64_t NumResults = ResultLists[PHIs[0]].size();
3741 APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
3742 uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
3743 bool TableHasHoles = (NumResults < TableSize);
3745 // If the table has holes, we need a constant result for the default case
3746 // or a bitmask that fits in a register.
3747 SmallVector<std::pair<PHINode*, Constant*>, 4> DefaultResultsList;
3748 bool HasDefaultResults = false;
3749 if (TableHasHoles) {
3750 HasDefaultResults = GetCaseResults(SI, nullptr, SI->getDefaultDest(),
3751 &CommonDest, DefaultResultsList, DL);
3753 bool NeedMask = (TableHasHoles && !HasDefaultResults);
3755 // As an extra penalty for the validity test we require more cases.
3756 if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
3758 if (!(DL && DL->fitsInLegalInteger(TableSize)))
3762 for (size_t I = 0, E = DefaultResultsList.size(); I != E; ++I) {
3763 PHINode *PHI = DefaultResultsList[I].first;
3764 Constant *Result = DefaultResultsList[I].second;
3765 DefaultResults[PHI] = Result;
3768 if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
3771 // Create the BB that does the lookups.
3772 Module &Mod = *CommonDest->getParent()->getParent();
3773 BasicBlock *LookupBB = BasicBlock::Create(Mod.getContext(),
3775 CommonDest->getParent(),
3778 // Compute the table index value.
3779 Builder.SetInsertPoint(SI);
3780 Value *TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal,
3783 // Compute the maximum table size representable by the integer type we are
3785 unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
3786 uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
3787 assert(MaxTableSize >= TableSize &&
3788 "It is impossible for a switch to have more entries than the max "
3789 "representable value of its input integer type's size.");
3791 // If we have a fully covered lookup table, unconditionally branch to the
3792 // lookup table BB. Otherwise, check if the condition value is within the case
3793 // range. If it is so, branch to the new BB. Otherwise branch to SI's default
3795 const bool GeneratingCoveredLookupTable = MaxTableSize == TableSize;
3796 if (GeneratingCoveredLookupTable) {
3797 Builder.CreateBr(LookupBB);
3798 SI->getDefaultDest()->removePredecessor(SI->getParent());
3800 Value *Cmp = Builder.CreateICmpULT(TableIndex, ConstantInt::get(
3801 MinCaseVal->getType(), TableSize));
3802 Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
3805 // Populate the BB that does the lookups.
3806 Builder.SetInsertPoint(LookupBB);
3809 // Before doing the lookup we do the hole check.
3810 // The LookupBB is therefore re-purposed to do the hole check
3811 // and we create a new LookupBB.
3812 BasicBlock *MaskBB = LookupBB;
3813 MaskBB->setName("switch.hole_check");
3814 LookupBB = BasicBlock::Create(Mod.getContext(),
3816 CommonDest->getParent(),
3819 // Build bitmask; fill in a 1 bit for every case.
3820 APInt MaskInt(TableSize, 0);
3821 APInt One(TableSize, 1);
3822 const ResultListTy &ResultList = ResultLists[PHIs[0]];
3823 for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
3824 uint64_t Idx = (ResultList[I].first->getValue() -
3825 MinCaseVal->getValue()).getLimitedValue();
3826 MaskInt |= One << Idx;
3828 ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
3830 // Get the TableIndex'th bit of the bitmask.
3831 // If this bit is 0 (meaning hole) jump to the default destination,
3832 // else continue with table lookup.
3833 IntegerType *MapTy = TableMask->getType();
3834 Value *MaskIndex = Builder.CreateZExtOrTrunc(TableIndex, MapTy,
3835 "switch.maskindex");
3836 Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex,
3838 Value *LoBit = Builder.CreateTrunc(Shifted,
3839 Type::getInt1Ty(Mod.getContext()),
3841 Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
3843 Builder.SetInsertPoint(LookupBB);
3844 AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent());
3847 bool ReturnedEarly = false;
3848 for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
3849 PHINode *PHI = PHIs[I];
3851 // If using a bitmask, use any value to fill the lookup table holes.
3852 Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
3853 SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultLists[PHI],
3856 Value *Result = Table.BuildLookup(TableIndex, Builder);
3858 // If the result is used to return immediately from the function, we want to
3859 // do that right here.
3860 if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
3861 PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) {
3862 Builder.CreateRet(Result);
3863 ReturnedEarly = true;
3867 PHI->addIncoming(Result, LookupBB);
3871 Builder.CreateBr(CommonDest);
3873 // Remove the switch.
3874 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
3875 BasicBlock *Succ = SI->getSuccessor(i);
3877 if (Succ == SI->getDefaultDest())
3879 Succ->removePredecessor(SI->getParent());
3881 SI->eraseFromParent();
3885 ++NumLookupTablesHoles;
3889 bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
3890 BasicBlock *BB = SI->getParent();
3892 if (isValueEqualityComparison(SI)) {
3893 // If we only have one predecessor, and if it is a branch on this value,
3894 // see if that predecessor totally determines the outcome of this switch.
3895 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
3896 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
3897 return SimplifyCFG(BB, TTI, DL) | true;
3899 Value *Cond = SI->getCondition();
3900 if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
3901 if (SimplifySwitchOnSelect(SI, Select))
3902 return SimplifyCFG(BB, TTI, DL) | true;
3904 // If the block only contains the switch, see if we can fold the block
3905 // away into any preds.
3906 BasicBlock::iterator BBI = BB->begin();
3907 // Ignore dbg intrinsics.
3908 while (isa<DbgInfoIntrinsic>(BBI))
3911 if (FoldValueComparisonIntoPredecessors(SI, Builder))
3912 return SimplifyCFG(BB, TTI, DL) | true;
3915 // Try to transform the switch into an icmp and a branch.
3916 if (TurnSwitchRangeIntoICmp(SI, Builder))
3917 return SimplifyCFG(BB, TTI, DL) | true;
3919 // Remove unreachable cases.
3920 if (EliminateDeadSwitchCases(SI))
3921 return SimplifyCFG(BB, TTI, DL) | true;
3923 if (ForwardSwitchConditionToPHI(SI))
3924 return SimplifyCFG(BB, TTI, DL) | true;
3926 if (SwitchToLookupTable(SI, Builder, TTI, DL))
3927 return SimplifyCFG(BB, TTI, DL) | true;
3932 bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
3933 BasicBlock *BB = IBI->getParent();
3934 bool Changed = false;
3936 // Eliminate redundant destinations.
3937 SmallPtrSet<Value *, 8> Succs;
3938 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
3939 BasicBlock *Dest = IBI->getDestination(i);
3940 if (!Dest->hasAddressTaken() || !Succs.insert(Dest)) {
3941 Dest->removePredecessor(BB);
3942 IBI->removeDestination(i);
3948 if (IBI->getNumDestinations() == 0) {
3949 // If the indirectbr has no successors, change it to unreachable.
3950 new UnreachableInst(IBI->getContext(), IBI);
3951 EraseTerminatorInstAndDCECond(IBI);
3955 if (IBI->getNumDestinations() == 1) {
3956 // If the indirectbr has one successor, change it to a direct branch.
3957 BranchInst::Create(IBI->getDestination(0), IBI);
3958 EraseTerminatorInstAndDCECond(IBI);
3962 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
3963 if (SimplifyIndirectBrOnSelect(IBI, SI))
3964 return SimplifyCFG(BB, TTI, DL) | true;
3969 bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder){
3970 BasicBlock *BB = BI->getParent();
3972 if (SinkCommon && SinkThenElseCodeToEnd(BI))
3975 // If the Terminator is the only non-phi instruction, simplify the block.
3976 BasicBlock::iterator I = BB->getFirstNonPHIOrDbgOrLifetime();
3977 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
3978 TryToSimplifyUncondBranchFromEmptyBlock(BB))
3981 // If the only instruction in the block is a seteq/setne comparison
3982 // against a constant, try to simplify the block.
3983 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
3984 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
3985 for (++I; isa<DbgInfoIntrinsic>(I); ++I)
3987 if (I->isTerminator() &&
3988 TryToSimplifyUncondBranchWithICmpInIt(ICI, Builder, TTI, DL))
3992 // If this basic block is ONLY a compare and a branch, and if a predecessor
3993 // branches to us and our successor, fold the comparison into the
3994 // predecessor and use logical operations to update the incoming value
3995 // for PHI nodes in common successor.
3996 if (FoldBranchToCommonDest(BI))
3997 return SimplifyCFG(BB, TTI, DL) | true;
4002 bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
4003 BasicBlock *BB = BI->getParent();
4005 // Conditional branch
4006 if (isValueEqualityComparison(BI)) {
4007 // If we only have one predecessor, and if it is a branch on this value,
4008 // see if that predecessor totally determines the outcome of this
4010 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
4011 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
4012 return SimplifyCFG(BB, TTI, DL) | true;
4014 // This block must be empty, except for the setcond inst, if it exists.
4015 // Ignore dbg intrinsics.
4016 BasicBlock::iterator I = BB->begin();
4017 // Ignore dbg intrinsics.
4018 while (isa<DbgInfoIntrinsic>(I))
4021 if (FoldValueComparisonIntoPredecessors(BI, Builder))
4022 return SimplifyCFG(BB, TTI, DL) | true;
4023 } else if (&*I == cast<Instruction>(BI->getCondition())){
4025 // Ignore dbg intrinsics.
4026 while (isa<DbgInfoIntrinsic>(I))
4028 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
4029 return SimplifyCFG(BB, TTI, DL) | true;
4033 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
4034 if (SimplifyBranchOnICmpChain(BI, DL, Builder))
4037 // If this basic block is ONLY a compare and a branch, and if a predecessor
4038 // branches to us and one of our successors, fold the comparison into the
4039 // predecessor and use logical operations to pick the right destination.
4040 if (FoldBranchToCommonDest(BI))
4041 return SimplifyCFG(BB, TTI, DL) | true;
4043 // We have a conditional branch to two blocks that are only reachable
4044 // from BI. We know that the condbr dominates the two blocks, so see if
4045 // there is any identical code in the "then" and "else" blocks. If so, we
4046 // can hoist it up to the branching block.
4047 if (BI->getSuccessor(0)->getSinglePredecessor()) {
4048 if (BI->getSuccessor(1)->getSinglePredecessor()) {
4049 if (HoistThenElseCodeToIf(BI))
4050 return SimplifyCFG(BB, TTI, DL) | true;
4052 // If Successor #1 has multiple preds, we may be able to conditionally
4053 // execute Successor #0 if it branches to successor #1.
4054 TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
4055 if (Succ0TI->getNumSuccessors() == 1 &&
4056 Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
4057 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0)))
4058 return SimplifyCFG(BB, TTI, DL) | true;
4060 } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
4061 // If Successor #0 has multiple preds, we may be able to conditionally
4062 // execute Successor #1 if it branches to successor #0.
4063 TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
4064 if (Succ1TI->getNumSuccessors() == 1 &&
4065 Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
4066 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1)))
4067 return SimplifyCFG(BB, TTI, DL) | true;
4070 // If this is a branch on a phi node in the current block, thread control
4071 // through this block if any PHI node entries are constants.
4072 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
4073 if (PN->getParent() == BI->getParent())
4074 if (FoldCondBranchOnPHI(BI, DL))
4075 return SimplifyCFG(BB, TTI, DL) | true;
4077 // Scan predecessor blocks for conditional branches.
4078 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
4079 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
4080 if (PBI != BI && PBI->isConditional())
4081 if (SimplifyCondBranchToCondBranch(PBI, BI))
4082 return SimplifyCFG(BB, TTI, DL) | true;
4087 /// Check if passing a value to an instruction will cause undefined behavior.
4088 static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
4089 Constant *C = dyn_cast<Constant>(V);
4096 if (C->isNullValue()) {
4097 // Only look at the first use, avoid hurting compile time with long uselists
4098 User *Use = *I->user_begin();
4100 // Now make sure that there are no instructions in between that can alter
4101 // control flow (eg. calls)
4102 for (BasicBlock::iterator i = ++BasicBlock::iterator(I); &*i != Use; ++i)
4103 if (i == I->getParent()->end() || i->mayHaveSideEffects())
4106 // Look through GEPs. A load from a GEP derived from NULL is still undefined
4107 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
4108 if (GEP->getPointerOperand() == I)
4109 return passingValueIsAlwaysUndefined(V, GEP);
4111 // Look through bitcasts.
4112 if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
4113 return passingValueIsAlwaysUndefined(V, BC);
4115 // Load from null is undefined.
4116 if (LoadInst *LI = dyn_cast<LoadInst>(Use))
4117 if (!LI->isVolatile())
4118 return LI->getPointerAddressSpace() == 0;
4120 // Store to null is undefined.
4121 if (StoreInst *SI = dyn_cast<StoreInst>(Use))
4122 if (!SI->isVolatile())
4123 return SI->getPointerAddressSpace() == 0 && SI->getPointerOperand() == I;
4128 /// If BB has an incoming value that will always trigger undefined behavior
4129 /// (eg. null pointer dereference), remove the branch leading here.
4130 static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
4131 for (BasicBlock::iterator i = BB->begin();
4132 PHINode *PHI = dyn_cast<PHINode>(i); ++i)
4133 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
4134 if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) {
4135 TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator();
4136 IRBuilder<> Builder(T);
4137 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
4138 BB->removePredecessor(PHI->getIncomingBlock(i));
4139 // Turn uncoditional branches into unreachables and remove the dead
4140 // destination from conditional branches.
4141 if (BI->isUnconditional())
4142 Builder.CreateUnreachable();
4144 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) :
4145 BI->getSuccessor(0));
4146 BI->eraseFromParent();
4149 // TODO: SwitchInst.
4155 bool SimplifyCFGOpt::run(BasicBlock *BB) {
4156 bool Changed = false;
4158 assert(BB && BB->getParent() && "Block not embedded in function!");
4159 assert(BB->getTerminator() && "Degenerate basic block encountered!");
4161 // Remove basic blocks that have no predecessors (except the entry block)...
4162 // or that just have themself as a predecessor. These are unreachable.
4163 if ((pred_begin(BB) == pred_end(BB) &&
4164 BB != &BB->getParent()->getEntryBlock()) ||
4165 BB->getSinglePredecessor() == BB) {
4166 DEBUG(dbgs() << "Removing BB: \n" << *BB);
4167 DeleteDeadBlock(BB);
4171 // Check to see if we can constant propagate this terminator instruction
4173 Changed |= ConstantFoldTerminator(BB, true);
4175 // Check for and eliminate duplicate PHI nodes in this block.
4176 Changed |= EliminateDuplicatePHINodes(BB);
4178 // Check for and remove branches that will always cause undefined behavior.
4179 Changed |= removeUndefIntroducingPredecessor(BB);
4181 // Merge basic blocks into their predecessor if there is only one distinct
4182 // pred, and if there is only one distinct successor of the predecessor, and
4183 // if there are no PHI nodes.
4185 if (MergeBlockIntoPredecessor(BB))
4188 IRBuilder<> Builder(BB);
4190 // If there is a trivial two-entry PHI node in this basic block, and we can
4191 // eliminate it, do so now.
4192 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
4193 if (PN->getNumIncomingValues() == 2)
4194 Changed |= FoldTwoEntryPHINode(PN, DL);
4196 Builder.SetInsertPoint(BB->getTerminator());
4197 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
4198 if (BI->isUnconditional()) {
4199 if (SimplifyUncondBranch(BI, Builder)) return true;
4201 if (SimplifyCondBranch(BI, Builder)) return true;
4203 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
4204 if (SimplifyReturn(RI, Builder)) return true;
4205 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
4206 if (SimplifyResume(RI, Builder)) return true;
4207 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
4208 if (SimplifySwitch(SI, Builder)) return true;
4209 } else if (UnreachableInst *UI =
4210 dyn_cast<UnreachableInst>(BB->getTerminator())) {
4211 if (SimplifyUnreachable(UI)) return true;
4212 } else if (IndirectBrInst *IBI =
4213 dyn_cast<IndirectBrInst>(BB->getTerminator())) {
4214 if (SimplifyIndirectBr(IBI)) return true;
4220 /// SimplifyCFG - This function is used to do simplification of a CFG. For
4221 /// example, it adjusts branches to branches to eliminate the extra hop, it
4222 /// eliminates unreachable basic blocks, and does other "peephole" optimization
4223 /// of the CFG. It returns true if a modification was made.
4225 bool llvm::SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
4226 const DataLayout *DL) {
4227 return SimplifyCFGOpt(TTI, DL).run(BB);