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"
46 #include "llvm/Transforms/Utils/Local.h"
47 #include "llvm/Transforms/Utils/ValueMapper.h"
52 using namespace PatternMatch;
54 #define DEBUG_TYPE "simplifycfg"
56 static cl::opt<unsigned>
57 PHINodeFoldingThreshold("phi-node-folding-threshold", cl::Hidden, cl::init(1),
58 cl::desc("Control the amount of phi node folding to perform (default = 1)"));
61 DupRet("simplifycfg-dup-ret", cl::Hidden, cl::init(false),
62 cl::desc("Duplicate return instructions into unconditional branches"));
65 SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
66 cl::desc("Sink common instructions down to the end block"));
68 static cl::opt<bool> HoistCondStores(
69 "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true),
70 cl::desc("Hoist conditional stores if an unconditional store precedes"));
72 STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
73 STATISTIC(NumLinearMaps, "Number of switch instructions turned into linear mapping");
74 STATISTIC(NumLookupTables, "Number of switch instructions turned into lookup tables");
75 STATISTIC(NumLookupTablesHoles, "Number of switch instructions turned into lookup tables (holes checked)");
76 STATISTIC(NumTableCmpReuses, "Number of reused switch table lookup compares");
77 STATISTIC(NumSinkCommons, "Number of common instructions sunk down to the end block");
78 STATISTIC(NumSpeculations, "Number of speculative executed instructions");
81 // The first field contains the value that the switch produces when a certain
82 // case group is selected, and the second field is a vector containing the cases
83 // composing the case group.
84 typedef SmallVector<std::pair<Constant *, SmallVector<ConstantInt *, 4>>, 2>
85 SwitchCaseResultVectorTy;
86 // The first field contains the phi node that generates a result of the switch
87 // and the second field contains the value generated for a certain case in the switch
89 typedef SmallVector<std::pair<PHINode *, Constant *>, 4> SwitchCaseResultsTy;
91 /// ValueEqualityComparisonCase - Represents a case of a switch.
92 struct ValueEqualityComparisonCase {
96 ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
97 : Value(Value), Dest(Dest) {}
99 bool operator<(ValueEqualityComparisonCase RHS) const {
100 // Comparing pointers is ok as we only rely on the order for uniquing.
101 return Value < RHS.Value;
104 bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
107 class SimplifyCFGOpt {
108 const TargetTransformInfo &TTI;
109 unsigned BonusInstThreshold;
110 const DataLayout *const DL;
112 Value *isValueEqualityComparison(TerminatorInst *TI);
113 BasicBlock *GetValueEqualityComparisonCases(TerminatorInst *TI,
114 std::vector<ValueEqualityComparisonCase> &Cases);
115 bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
117 IRBuilder<> &Builder);
118 bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
119 IRBuilder<> &Builder);
121 bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder);
122 bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
123 bool SimplifyUnreachable(UnreachableInst *UI);
124 bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
125 bool SimplifyIndirectBr(IndirectBrInst *IBI);
126 bool SimplifyUncondBranch(BranchInst *BI, IRBuilder <> &Builder);
127 bool SimplifyCondBranch(BranchInst *BI, IRBuilder <>&Builder);
130 SimplifyCFGOpt(const TargetTransformInfo &TTI, unsigned BonusInstThreshold,
131 const DataLayout *DL, AssumptionCache *AC)
132 : TTI(TTI), BonusInstThreshold(BonusInstThreshold), DL(DL), AC(AC) {}
133 bool run(BasicBlock *BB);
137 /// SafeToMergeTerminators - Return true if it is safe to merge these two
138 /// terminator instructions together.
140 static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
141 if (SI1 == SI2) return false; // Can't merge with self!
143 // It is not safe to merge these two switch instructions if they have a common
144 // successor, and if that successor has a PHI node, and if *that* PHI node has
145 // conflicting incoming values from the two switch blocks.
146 BasicBlock *SI1BB = SI1->getParent();
147 BasicBlock *SI2BB = SI2->getParent();
148 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
150 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
151 if (SI1Succs.count(*I))
152 for (BasicBlock::iterator BBI = (*I)->begin();
153 isa<PHINode>(BBI); ++BBI) {
154 PHINode *PN = cast<PHINode>(BBI);
155 if (PN->getIncomingValueForBlock(SI1BB) !=
156 PN->getIncomingValueForBlock(SI2BB))
163 /// isProfitableToFoldUnconditional - Return true if it is safe and profitable
164 /// to merge these two terminator instructions together, where SI1 is an
165 /// unconditional branch. PhiNodes will store all PHI nodes in common
168 static bool isProfitableToFoldUnconditional(BranchInst *SI1,
171 SmallVectorImpl<PHINode*> &PhiNodes) {
172 if (SI1 == SI2) return false; // Can't merge with self!
173 assert(SI1->isUnconditional() && SI2->isConditional());
175 // We fold the unconditional branch if we can easily update all PHI nodes in
176 // common successors:
177 // 1> We have a constant incoming value for the conditional branch;
178 // 2> We have "Cond" as the incoming value for the unconditional branch;
179 // 3> SI2->getCondition() and Cond have same operands.
180 CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition());
181 if (!Ci2) return false;
182 if (!(Cond->getOperand(0) == Ci2->getOperand(0) &&
183 Cond->getOperand(1) == Ci2->getOperand(1)) &&
184 !(Cond->getOperand(0) == Ci2->getOperand(1) &&
185 Cond->getOperand(1) == Ci2->getOperand(0)))
188 BasicBlock *SI1BB = SI1->getParent();
189 BasicBlock *SI2BB = SI2->getParent();
190 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
191 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
192 if (SI1Succs.count(*I))
193 for (BasicBlock::iterator BBI = (*I)->begin();
194 isa<PHINode>(BBI); ++BBI) {
195 PHINode *PN = cast<PHINode>(BBI);
196 if (PN->getIncomingValueForBlock(SI1BB) != Cond ||
197 !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB)))
199 PhiNodes.push_back(PN);
204 /// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will
205 /// now be entries in it from the 'NewPred' block. The values that will be
206 /// flowing into the PHI nodes will be the same as those coming in from
207 /// ExistPred, an existing predecessor of Succ.
208 static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
209 BasicBlock *ExistPred) {
210 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
213 for (BasicBlock::iterator I = Succ->begin();
214 (PN = dyn_cast<PHINode>(I)); ++I)
215 PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
218 /// ComputeSpeculationCost - Compute an abstract "cost" of speculating the
219 /// given instruction, which is assumed to be safe to speculate. TCC_Free means
220 /// cheap, TCC_Basic means less cheap, and TCC_Expensive means prohibitively
222 static unsigned ComputeSpeculationCost(const User *I, const DataLayout *DL,
223 const TargetTransformInfo &TTI) {
224 assert(isSafeToSpeculativelyExecute(I, DL) &&
225 "Instruction is not safe to speculatively execute!");
226 return TTI.getUserCost(I);
228 /// DominatesMergePoint - If we have a merge point of an "if condition" as
229 /// accepted above, return true if the specified value dominates the block. We
230 /// don't handle the true generality of domination here, just a special case
231 /// which works well enough for us.
233 /// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
234 /// see if V (which must be an instruction) and its recursive operands
235 /// that do not dominate BB have a combined cost lower than CostRemaining and
236 /// are non-trapping. If both are true, the instruction is inserted into the
237 /// set and true is returned.
239 /// The cost for most non-trapping instructions is defined as 1 except for
240 /// Select whose cost is 2.
242 /// After this function returns, CostRemaining is decreased by the cost of
243 /// V plus its non-dominating operands. If that cost is greater than
244 /// CostRemaining, false is returned and CostRemaining is undefined.
245 static bool DominatesMergePoint(Value *V, BasicBlock *BB,
246 SmallPtrSetImpl<Instruction*> *AggressiveInsts,
247 unsigned &CostRemaining,
248 const DataLayout *DL,
249 const TargetTransformInfo &TTI) {
250 Instruction *I = dyn_cast<Instruction>(V);
252 // Non-instructions all dominate instructions, but not all constantexprs
253 // can be executed unconditionally.
254 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
259 BasicBlock *PBB = I->getParent();
261 // We don't want to allow weird loops that might have the "if condition" in
262 // the bottom of this block.
263 if (PBB == BB) return false;
265 // If this instruction is defined in a block that contains an unconditional
266 // branch to BB, then it must be in the 'conditional' part of the "if
267 // statement". If not, it definitely dominates the region.
268 BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
269 if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB)
272 // If we aren't allowing aggressive promotion anymore, then don't consider
273 // instructions in the 'if region'.
274 if (!AggressiveInsts) return false;
276 // If we have seen this instruction before, don't count it again.
277 if (AggressiveInsts->count(I)) return true;
279 // Okay, it looks like the instruction IS in the "condition". Check to
280 // see if it's a cheap instruction to unconditionally compute, and if it
281 // only uses stuff defined outside of the condition. If so, hoist it out.
282 if (!isSafeToSpeculativelyExecute(I, DL))
285 unsigned Cost = ComputeSpeculationCost(I, DL, TTI);
287 if (Cost > CostRemaining)
290 CostRemaining -= Cost;
292 // Okay, we can only really hoist these out if their operands do
293 // not take us over the cost threshold.
294 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
295 if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining, DL, TTI))
297 // Okay, it's safe to do this! Remember this instruction.
298 AggressiveInsts->insert(I);
302 /// GetConstantInt - Extract ConstantInt from value, looking through IntToPtr
303 /// and PointerNullValue. Return NULL if value is not a constant int.
304 static ConstantInt *GetConstantInt(Value *V, const DataLayout *DL) {
305 // Normal constant int.
306 ConstantInt *CI = dyn_cast<ConstantInt>(V);
307 if (CI || !DL || !isa<Constant>(V) || !V->getType()->isPointerTy())
310 // This is some kind of pointer constant. Turn it into a pointer-sized
311 // ConstantInt if possible.
312 IntegerType *PtrTy = cast<IntegerType>(DL->getIntPtrType(V->getType()));
314 // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
315 if (isa<ConstantPointerNull>(V))
316 return ConstantInt::get(PtrTy, 0);
318 // IntToPtr const int.
319 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
320 if (CE->getOpcode() == Instruction::IntToPtr)
321 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
322 // The constant is very likely to have the right type already.
323 if (CI->getType() == PtrTy)
326 return cast<ConstantInt>
327 (ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
334 /// Given a chain of or (||) or and (&&) comparison of a value against a
335 /// constant, this will try to recover the information required for a switch
337 /// It will depth-first traverse the chain of comparison, seeking for patterns
338 /// like %a == 12 or %a < 4 and combine them to produce a set of integer
339 /// representing the different cases for the switch.
340 /// Note that if the chain is composed of '||' it will build the set of elements
341 /// that matches the comparisons (i.e. any of this value validate the chain)
342 /// while for a chain of '&&' it will build the set elements that make the test
344 struct ConstantComparesGatherer {
346 Value *CompValue; /// Value found for the switch comparison
347 Value *Extra; /// Extra clause to be checked before the switch
348 SmallVector<ConstantInt *, 8> Vals; /// Set of integers to match in switch
349 unsigned UsedICmps; /// Number of comparisons matched in the and/or chain
351 /// Construct and compute the result for the comparison instruction Cond
352 ConstantComparesGatherer(Instruction *Cond, const DataLayout *DL)
353 : CompValue(nullptr), Extra(nullptr), UsedICmps(0) {
358 ConstantComparesGatherer(const ConstantComparesGatherer &)
359 LLVM_DELETED_FUNCTION;
360 ConstantComparesGatherer &
361 operator=(const ConstantComparesGatherer &) LLVM_DELETED_FUNCTION;
365 /// Try to set the current value used for the comparison, it succeeds only if
366 /// it wasn't set before or if the new value is the same as the old one
367 bool setValueOnce(Value *NewVal) {
368 if(CompValue && CompValue != NewVal) return false;
370 return (CompValue != nullptr);
373 /// Try to match Instruction "I" as a comparison against a constant and
374 /// populates the array Vals with the set of values that match (or do not
375 /// match depending on isEQ).
376 /// Return false on failure. On success, the Value the comparison matched
377 /// against is placed in CompValue.
378 /// If CompValue is already set, the function is expected to fail if a match
379 /// is found but the value compared to is different.
380 bool matchInstruction(Instruction *I, const DataLayout *DL, bool isEQ) {
381 // If this is an icmp against a constant, handle this as one of the cases.
384 if (!((ICI = dyn_cast<ICmpInst>(I)) &&
385 (C = GetConstantInt(I->getOperand(1), DL)))) {
392 // Pattern match a special case
393 // (x & ~2^x) == y --> x == y || x == y|2^x
394 // This undoes a transformation done by instcombine to fuse 2 compares.
395 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ:ICmpInst::ICMP_NE)) {
396 if (match(ICI->getOperand(0),
397 m_And(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
398 APInt Not = ~RHSC->getValue();
399 if (Not.isPowerOf2()) {
400 // If we already have a value for the switch, it has to match!
401 if(!setValueOnce(RHSVal))
405 Vals.push_back(ConstantInt::get(C->getContext(),
406 C->getValue() | Not));
412 // If we already have a value for the switch, it has to match!
413 if(!setValueOnce(ICI->getOperand(0)))
418 return ICI->getOperand(0);
421 // If we have "x ult 3", for example, then we can add 0,1,2 to the set.
422 ConstantRange Span = ConstantRange::makeICmpRegion(ICI->getPredicate(),
425 // Shift the range if the compare is fed by an add. This is the range
426 // compare idiom as emitted by instcombine.
427 Value *CandidateVal = I->getOperand(0);
428 if(match(I->getOperand(0), m_Add(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
429 Span = Span.subtract(RHSC->getValue());
430 CandidateVal = RHSVal;
433 // If this is an and/!= check, then we are looking to build the set of
434 // value that *don't* pass the and chain. I.e. to turn "x ugt 2" into
437 Span = Span.inverse();
439 // If there are a ton of values, we don't want to make a ginormous switch.
440 if (Span.getSetSize().ugt(8) || Span.isEmptySet()) {
444 // If we already have a value for the switch, it has to match!
445 if(!setValueOnce(CandidateVal))
448 // Add all values from the range to the set
449 for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
450 Vals.push_back(ConstantInt::get(I->getContext(), Tmp));
457 /// gather - Given a potentially 'or'd or 'and'd together collection of icmp
458 /// eq/ne/lt/gt instructions that compare a value against a constant, extract
459 /// the value being compared, and stick the list constants into the Vals
461 /// One "Extra" case is allowed to differ from the other.
462 void gather(Value *V, const DataLayout *DL) {
463 Instruction *I = dyn_cast<Instruction>(V);
464 bool isEQ = (I->getOpcode() == Instruction::Or);
466 // Keep a stack (SmallVector for efficiency) for depth-first traversal
467 SmallVector<Value *, 8> DFT;
472 while(!DFT.empty()) {
473 V = DFT.pop_back_val();
475 if (Instruction *I = dyn_cast<Instruction>(V)) {
476 // If it is a || (or && depending on isEQ), process the operands.
477 if (I->getOpcode() == (isEQ ? Instruction::Or : Instruction::And)) {
478 DFT.push_back(I->getOperand(1));
479 DFT.push_back(I->getOperand(0));
483 // Try to match the current instruction
484 if (matchInstruction(I, DL, isEQ))
485 // Match succeed, continue the loop
489 // One element of the sequence of || (or &&) could not be match as a
490 // comparison against the same value as the others.
491 // We allow only one "Extra" case to be checked before the switch
496 // Failed to parse a proper sequence, abort now
505 static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
506 Instruction *Cond = nullptr;
507 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
508 Cond = dyn_cast<Instruction>(SI->getCondition());
509 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
510 if (BI->isConditional())
511 Cond = dyn_cast<Instruction>(BI->getCondition());
512 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
513 Cond = dyn_cast<Instruction>(IBI->getAddress());
516 TI->eraseFromParent();
517 if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond);
520 /// isValueEqualityComparison - Return true if the specified terminator checks
521 /// to see if a value is equal to constant integer value.
522 Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) {
524 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
525 // Do not permit merging of large switch instructions into their
526 // predecessors unless there is only one predecessor.
527 if (SI->getNumSuccessors()*std::distance(pred_begin(SI->getParent()),
528 pred_end(SI->getParent())) <= 128)
529 CV = SI->getCondition();
530 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
531 if (BI->isConditional() && BI->getCondition()->hasOneUse())
532 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
533 if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL))
534 CV = ICI->getOperand(0);
536 // Unwrap any lossless ptrtoint cast.
538 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
539 Value *Ptr = PTII->getPointerOperand();
540 if (PTII->getType() == DL->getIntPtrType(Ptr->getType()))
547 /// GetValueEqualityComparisonCases - Given a value comparison instruction,
548 /// decode all of the 'cases' that it represents and return the 'default' block.
549 BasicBlock *SimplifyCFGOpt::
550 GetValueEqualityComparisonCases(TerminatorInst *TI,
551 std::vector<ValueEqualityComparisonCase>
553 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
554 Cases.reserve(SI->getNumCases());
555 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i)
556 Cases.push_back(ValueEqualityComparisonCase(i.getCaseValue(),
557 i.getCaseSuccessor()));
558 return SI->getDefaultDest();
561 BranchInst *BI = cast<BranchInst>(TI);
562 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
563 BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE);
564 Cases.push_back(ValueEqualityComparisonCase(GetConstantInt(ICI->getOperand(1),
567 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
571 /// EliminateBlockCases - Given a vector of bb/value pairs, remove any entries
572 /// in the list that match the specified block.
573 static void EliminateBlockCases(BasicBlock *BB,
574 std::vector<ValueEqualityComparisonCase> &Cases) {
575 Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end());
578 /// ValuesOverlap - Return true if there are any keys in C1 that exist in C2 as
581 ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
582 std::vector<ValueEqualityComparisonCase > &C2) {
583 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
585 // Make V1 be smaller than V2.
586 if (V1->size() > V2->size())
589 if (V1->size() == 0) return false;
590 if (V1->size() == 1) {
592 ConstantInt *TheVal = (*V1)[0].Value;
593 for (unsigned i = 0, e = V2->size(); i != e; ++i)
594 if (TheVal == (*V2)[i].Value)
598 // Otherwise, just sort both lists and compare element by element.
599 array_pod_sort(V1->begin(), V1->end());
600 array_pod_sort(V2->begin(), V2->end());
601 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
602 while (i1 != e1 && i2 != e2) {
603 if ((*V1)[i1].Value == (*V2)[i2].Value)
605 if ((*V1)[i1].Value < (*V2)[i2].Value)
613 /// SimplifyEqualityComparisonWithOnlyPredecessor - If TI is known to be a
614 /// terminator instruction and its block is known to only have a single
615 /// predecessor block, check to see if that predecessor is also a value
616 /// comparison with the same value, and if that comparison determines the
617 /// outcome of this comparison. If so, simplify TI. This does a very limited
618 /// form of jump threading.
619 bool SimplifyCFGOpt::
620 SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
622 IRBuilder<> &Builder) {
623 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
624 if (!PredVal) return false; // Not a value comparison in predecessor.
626 Value *ThisVal = isValueEqualityComparison(TI);
627 assert(ThisVal && "This isn't a value comparison!!");
628 if (ThisVal != PredVal) return false; // Different predicates.
630 // TODO: Preserve branch weight metadata, similarly to how
631 // FoldValueComparisonIntoPredecessors preserves it.
633 // Find out information about when control will move from Pred to TI's block.
634 std::vector<ValueEqualityComparisonCase> PredCases;
635 BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
637 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
639 // Find information about how control leaves this block.
640 std::vector<ValueEqualityComparisonCase> ThisCases;
641 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
642 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
644 // If TI's block is the default block from Pred's comparison, potentially
645 // simplify TI based on this knowledge.
646 if (PredDef == TI->getParent()) {
647 // If we are here, we know that the value is none of those cases listed in
648 // PredCases. If there are any cases in ThisCases that are in PredCases, we
650 if (!ValuesOverlap(PredCases, ThisCases))
653 if (isa<BranchInst>(TI)) {
654 // Okay, one of the successors of this condbr is dead. Convert it to a
656 assert(ThisCases.size() == 1 && "Branch can only have one case!");
657 // Insert the new branch.
658 Instruction *NI = Builder.CreateBr(ThisDef);
661 // Remove PHI node entries for the dead edge.
662 ThisCases[0].Dest->removePredecessor(TI->getParent());
664 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
665 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
667 EraseTerminatorInstAndDCECond(TI);
671 SwitchInst *SI = cast<SwitchInst>(TI);
672 // Okay, TI has cases that are statically dead, prune them away.
673 SmallPtrSet<Constant*, 16> DeadCases;
674 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
675 DeadCases.insert(PredCases[i].Value);
677 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
678 << "Through successor TI: " << *TI);
680 // Collect branch weights into a vector.
681 SmallVector<uint32_t, 8> Weights;
682 MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
683 bool HasWeight = MD && (MD->getNumOperands() == 2 + SI->getNumCases());
685 for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
687 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(MD_i));
688 Weights.push_back(CI->getValue().getZExtValue());
690 for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
692 if (DeadCases.count(i.getCaseValue())) {
694 std::swap(Weights[i.getCaseIndex()+1], Weights.back());
697 i.getCaseSuccessor()->removePredecessor(TI->getParent());
701 if (HasWeight && Weights.size() >= 2)
702 SI->setMetadata(LLVMContext::MD_prof,
703 MDBuilder(SI->getParent()->getContext()).
704 createBranchWeights(Weights));
706 DEBUG(dbgs() << "Leaving: " << *TI << "\n");
710 // Otherwise, TI's block must correspond to some matched value. Find out
711 // which value (or set of values) this is.
712 ConstantInt *TIV = nullptr;
713 BasicBlock *TIBB = TI->getParent();
714 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
715 if (PredCases[i].Dest == TIBB) {
717 return false; // Cannot handle multiple values coming to this block.
718 TIV = PredCases[i].Value;
720 assert(TIV && "No edge from pred to succ?");
722 // Okay, we found the one constant that our value can be if we get into TI's
723 // BB. Find out which successor will unconditionally be branched to.
724 BasicBlock *TheRealDest = nullptr;
725 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
726 if (ThisCases[i].Value == TIV) {
727 TheRealDest = ThisCases[i].Dest;
731 // If not handled by any explicit cases, it is handled by the default case.
732 if (!TheRealDest) TheRealDest = ThisDef;
734 // Remove PHI node entries for dead edges.
735 BasicBlock *CheckEdge = TheRealDest;
736 for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
737 if (*SI != CheckEdge)
738 (*SI)->removePredecessor(TIBB);
742 // Insert the new branch.
743 Instruction *NI = Builder.CreateBr(TheRealDest);
746 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
747 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
749 EraseTerminatorInstAndDCECond(TI);
754 /// ConstantIntOrdering - This class implements a stable ordering of constant
755 /// integers that does not depend on their address. This is important for
756 /// applications that sort ConstantInt's to ensure uniqueness.
757 struct ConstantIntOrdering {
758 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
759 return LHS->getValue().ult(RHS->getValue());
764 static int ConstantIntSortPredicate(ConstantInt *const *P1,
765 ConstantInt *const *P2) {
766 const ConstantInt *LHS = *P1;
767 const ConstantInt *RHS = *P2;
768 if (LHS->getValue().ult(RHS->getValue()))
770 if (LHS->getValue() == RHS->getValue())
775 static inline bool HasBranchWeights(const Instruction* I) {
776 MDNode *ProfMD = I->getMetadata(LLVMContext::MD_prof);
777 if (ProfMD && ProfMD->getOperand(0))
778 if (MDString* MDS = dyn_cast<MDString>(ProfMD->getOperand(0)))
779 return MDS->getString().equals("branch_weights");
784 /// Get Weights of a given TerminatorInst, the default weight is at the front
785 /// of the vector. If TI is a conditional eq, we need to swap the branch-weight
787 static void GetBranchWeights(TerminatorInst *TI,
788 SmallVectorImpl<uint64_t> &Weights) {
789 MDNode *MD = TI->getMetadata(LLVMContext::MD_prof);
791 for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) {
792 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(i));
793 Weights.push_back(CI->getValue().getZExtValue());
796 // If TI is a conditional eq, the default case is the false case,
797 // and the corresponding branch-weight data is at index 2. We swap the
798 // default weight to be the first entry.
799 if (BranchInst* BI = dyn_cast<BranchInst>(TI)) {
800 assert(Weights.size() == 2);
801 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
802 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
803 std::swap(Weights.front(), Weights.back());
807 /// Keep halving the weights until all can fit in uint32_t.
808 static void FitWeights(MutableArrayRef<uint64_t> Weights) {
809 uint64_t Max = *std::max_element(Weights.begin(), Weights.end());
810 if (Max > UINT_MAX) {
811 unsigned Offset = 32 - countLeadingZeros(Max);
812 for (uint64_t &I : Weights)
817 /// FoldValueComparisonIntoPredecessors - The specified terminator is a value
818 /// equality comparison instruction (either a switch or a branch on "X == c").
819 /// See if any of the predecessors of the terminator block are value comparisons
820 /// on the same value. If so, and if safe to do so, fold them together.
821 bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
822 IRBuilder<> &Builder) {
823 BasicBlock *BB = TI->getParent();
824 Value *CV = isValueEqualityComparison(TI); // CondVal
825 assert(CV && "Not a comparison?");
826 bool Changed = false;
828 SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
829 while (!Preds.empty()) {
830 BasicBlock *Pred = Preds.pop_back_val();
832 // See if the predecessor is a comparison with the same value.
833 TerminatorInst *PTI = Pred->getTerminator();
834 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
836 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
837 // Figure out which 'cases' to copy from SI to PSI.
838 std::vector<ValueEqualityComparisonCase> BBCases;
839 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
841 std::vector<ValueEqualityComparisonCase> PredCases;
842 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
844 // Based on whether the default edge from PTI goes to BB or not, fill in
845 // PredCases and PredDefault with the new switch cases we would like to
847 SmallVector<BasicBlock*, 8> NewSuccessors;
849 // Update the branch weight metadata along the way
850 SmallVector<uint64_t, 8> Weights;
851 bool PredHasWeights = HasBranchWeights(PTI);
852 bool SuccHasWeights = HasBranchWeights(TI);
854 if (PredHasWeights) {
855 GetBranchWeights(PTI, Weights);
856 // branch-weight metadata is inconsistent here.
857 if (Weights.size() != 1 + PredCases.size())
858 PredHasWeights = SuccHasWeights = false;
859 } else if (SuccHasWeights)
860 // If there are no predecessor weights but there are successor weights,
861 // populate Weights with 1, which will later be scaled to the sum of
862 // successor's weights
863 Weights.assign(1 + PredCases.size(), 1);
865 SmallVector<uint64_t, 8> SuccWeights;
866 if (SuccHasWeights) {
867 GetBranchWeights(TI, SuccWeights);
868 // branch-weight metadata is inconsistent here.
869 if (SuccWeights.size() != 1 + BBCases.size())
870 PredHasWeights = SuccHasWeights = false;
871 } else if (PredHasWeights)
872 SuccWeights.assign(1 + BBCases.size(), 1);
874 if (PredDefault == BB) {
875 // If this is the default destination from PTI, only the edges in TI
876 // that don't occur in PTI, or that branch to BB will be activated.
877 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
878 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
879 if (PredCases[i].Dest != BB)
880 PTIHandled.insert(PredCases[i].Value);
882 // The default destination is BB, we don't need explicit targets.
883 std::swap(PredCases[i], PredCases.back());
885 if (PredHasWeights || SuccHasWeights) {
886 // Increase weight for the default case.
887 Weights[0] += Weights[i+1];
888 std::swap(Weights[i+1], Weights.back());
892 PredCases.pop_back();
896 // Reconstruct the new switch statement we will be building.
897 if (PredDefault != BBDefault) {
898 PredDefault->removePredecessor(Pred);
899 PredDefault = BBDefault;
900 NewSuccessors.push_back(BBDefault);
903 unsigned CasesFromPred = Weights.size();
904 uint64_t ValidTotalSuccWeight = 0;
905 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
906 if (!PTIHandled.count(BBCases[i].Value) &&
907 BBCases[i].Dest != BBDefault) {
908 PredCases.push_back(BBCases[i]);
909 NewSuccessors.push_back(BBCases[i].Dest);
910 if (SuccHasWeights || PredHasWeights) {
911 // The default weight is at index 0, so weight for the ith case
912 // should be at index i+1. Scale the cases from successor by
913 // PredDefaultWeight (Weights[0]).
914 Weights.push_back(Weights[0] * SuccWeights[i+1]);
915 ValidTotalSuccWeight += SuccWeights[i+1];
919 if (SuccHasWeights || PredHasWeights) {
920 ValidTotalSuccWeight += SuccWeights[0];
921 // Scale the cases from predecessor by ValidTotalSuccWeight.
922 for (unsigned i = 1; i < CasesFromPred; ++i)
923 Weights[i] *= ValidTotalSuccWeight;
924 // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
925 Weights[0] *= SuccWeights[0];
928 // If this is not the default destination from PSI, only the edges
929 // in SI that occur in PSI with a destination of BB will be
931 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
932 std::map<ConstantInt*, uint64_t> WeightsForHandled;
933 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
934 if (PredCases[i].Dest == BB) {
935 PTIHandled.insert(PredCases[i].Value);
937 if (PredHasWeights || SuccHasWeights) {
938 WeightsForHandled[PredCases[i].Value] = Weights[i+1];
939 std::swap(Weights[i+1], Weights.back());
943 std::swap(PredCases[i], PredCases.back());
944 PredCases.pop_back();
948 // Okay, now we know which constants were sent to BB from the
949 // predecessor. Figure out where they will all go now.
950 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
951 if (PTIHandled.count(BBCases[i].Value)) {
952 // If this is one we are capable of getting...
953 if (PredHasWeights || SuccHasWeights)
954 Weights.push_back(WeightsForHandled[BBCases[i].Value]);
955 PredCases.push_back(BBCases[i]);
956 NewSuccessors.push_back(BBCases[i].Dest);
957 PTIHandled.erase(BBCases[i].Value);// This constant is taken care of
960 // If there are any constants vectored to BB that TI doesn't handle,
961 // they must go to the default destination of TI.
962 for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I =
964 E = PTIHandled.end(); I != E; ++I) {
965 if (PredHasWeights || SuccHasWeights)
966 Weights.push_back(WeightsForHandled[*I]);
967 PredCases.push_back(ValueEqualityComparisonCase(*I, BBDefault));
968 NewSuccessors.push_back(BBDefault);
972 // Okay, at this point, we know which new successor Pred will get. Make
973 // sure we update the number of entries in the PHI nodes for these
975 for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
976 AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
978 Builder.SetInsertPoint(PTI);
979 // Convert pointer to int before we switch.
980 if (CV->getType()->isPointerTy()) {
981 assert(DL && "Cannot switch on pointer without DataLayout");
982 CV = Builder.CreatePtrToInt(CV, DL->getIntPtrType(CV->getType()),
986 // Now that the successors are updated, create the new Switch instruction.
987 SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault,
989 NewSI->setDebugLoc(PTI->getDebugLoc());
990 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
991 NewSI->addCase(PredCases[i].Value, PredCases[i].Dest);
993 if (PredHasWeights || SuccHasWeights) {
994 // Halve the weights if any of them cannot fit in an uint32_t
997 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
999 NewSI->setMetadata(LLVMContext::MD_prof,
1000 MDBuilder(BB->getContext()).
1001 createBranchWeights(MDWeights));
1004 EraseTerminatorInstAndDCECond(PTI);
1006 // Okay, last check. If BB is still a successor of PSI, then we must
1007 // have an infinite loop case. If so, add an infinitely looping block
1008 // to handle the case to preserve the behavior of the code.
1009 BasicBlock *InfLoopBlock = nullptr;
1010 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
1011 if (NewSI->getSuccessor(i) == BB) {
1012 if (!InfLoopBlock) {
1013 // Insert it at the end of the function, because it's either code,
1014 // or it won't matter if it's hot. :)
1015 InfLoopBlock = BasicBlock::Create(BB->getContext(),
1016 "infloop", BB->getParent());
1017 BranchInst::Create(InfLoopBlock, InfLoopBlock);
1019 NewSI->setSuccessor(i, InfLoopBlock);
1028 // isSafeToHoistInvoke - If we would need to insert a select that uses the
1029 // value of this invoke (comments in HoistThenElseCodeToIf explain why we
1030 // would need to do this), we can't hoist the invoke, as there is nowhere
1031 // to put the select in this case.
1032 static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
1033 Instruction *I1, Instruction *I2) {
1034 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
1036 for (BasicBlock::iterator BBI = SI->begin();
1037 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1038 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1039 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1040 if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) {
1048 static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I);
1050 /// HoistThenElseCodeToIf - Given a conditional branch that goes to BB1 and
1051 /// BB2, hoist any common code in the two blocks up into the branch block. The
1052 /// caller of this function guarantees that BI's block dominates BB1 and BB2.
1053 static bool HoistThenElseCodeToIf(BranchInst *BI, const DataLayout *DL) {
1054 // This does very trivial matching, with limited scanning, to find identical
1055 // instructions in the two blocks. In particular, we don't want to get into
1056 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
1057 // such, we currently just scan for obviously identical instructions in an
1059 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
1060 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
1062 BasicBlock::iterator BB1_Itr = BB1->begin();
1063 BasicBlock::iterator BB2_Itr = BB2->begin();
1065 Instruction *I1 = BB1_Itr++, *I2 = BB2_Itr++;
1066 // Skip debug info if it is not identical.
1067 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1068 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1069 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1070 while (isa<DbgInfoIntrinsic>(I1))
1072 while (isa<DbgInfoIntrinsic>(I2))
1075 if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
1076 (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
1079 BasicBlock *BIParent = BI->getParent();
1081 bool Changed = false;
1083 // If we are hoisting the terminator instruction, don't move one (making a
1084 // broken BB), instead clone it, and remove BI.
1085 if (isa<TerminatorInst>(I1))
1086 goto HoistTerminator;
1088 // For a normal instruction, we just move one to right before the branch,
1089 // then replace all uses of the other with the first. Finally, we remove
1090 // the now redundant second instruction.
1091 BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
1092 if (!I2->use_empty())
1093 I2->replaceAllUsesWith(I1);
1094 I1->intersectOptionalDataWith(I2);
1095 unsigned KnownIDs[] = {
1096 LLVMContext::MD_tbaa,
1097 LLVMContext::MD_range,
1098 LLVMContext::MD_fpmath,
1099 LLVMContext::MD_invariant_load,
1100 LLVMContext::MD_nonnull
1102 combineMetadata(I1, I2, KnownIDs);
1103 I2->eraseFromParent();
1108 // Skip debug info if it is not identical.
1109 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1110 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1111 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1112 while (isa<DbgInfoIntrinsic>(I1))
1114 while (isa<DbgInfoIntrinsic>(I2))
1117 } while (I1->isIdenticalToWhenDefined(I2));
1122 // It may not be possible to hoist an invoke.
1123 if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
1126 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
1128 for (BasicBlock::iterator BBI = SI->begin();
1129 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1130 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1131 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1135 // Check for passingValueIsAlwaysUndefined here because we would rather
1136 // eliminate undefined control flow then converting it to a select.
1137 if (passingValueIsAlwaysUndefined(BB1V, PN) ||
1138 passingValueIsAlwaysUndefined(BB2V, PN))
1141 if (isa<ConstantExpr>(BB1V) && !isSafeToSpeculativelyExecute(BB1V, DL))
1143 if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V, DL))
1148 // Okay, it is safe to hoist the terminator.
1149 Instruction *NT = I1->clone();
1150 BIParent->getInstList().insert(BI, NT);
1151 if (!NT->getType()->isVoidTy()) {
1152 I1->replaceAllUsesWith(NT);
1153 I2->replaceAllUsesWith(NT);
1157 IRBuilder<true, NoFolder> Builder(NT);
1158 // Hoisting one of the terminators from our successor is a great thing.
1159 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
1160 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
1161 // nodes, so we insert select instruction to compute the final result.
1162 std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
1163 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
1165 for (BasicBlock::iterator BBI = SI->begin();
1166 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1167 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1168 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1169 if (BB1V == BB2V) continue;
1171 // These values do not agree. Insert a select instruction before NT
1172 // that determines the right value.
1173 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
1175 SI = cast<SelectInst>
1176 (Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
1177 BB1V->getName()+"."+BB2V->getName()));
1179 // Make the PHI node use the select for all incoming values for BB1/BB2
1180 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1181 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
1182 PN->setIncomingValue(i, SI);
1186 // Update any PHI nodes in our new successors.
1187 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
1188 AddPredecessorToBlock(*SI, BIParent, BB1);
1190 EraseTerminatorInstAndDCECond(BI);
1194 /// SinkThenElseCodeToEnd - Given an unconditional branch that goes to BBEnd,
1195 /// check whether BBEnd has only two predecessors and the other predecessor
1196 /// ends with an unconditional branch. If it is true, sink any common code
1197 /// in the two predecessors to BBEnd.
1198 static bool SinkThenElseCodeToEnd(BranchInst *BI1) {
1199 assert(BI1->isUnconditional());
1200 BasicBlock *BB1 = BI1->getParent();
1201 BasicBlock *BBEnd = BI1->getSuccessor(0);
1203 // Check that BBEnd has two predecessors and the other predecessor ends with
1204 // an unconditional branch.
1205 pred_iterator PI = pred_begin(BBEnd), PE = pred_end(BBEnd);
1206 BasicBlock *Pred0 = *PI++;
1207 if (PI == PE) // Only one predecessor.
1209 BasicBlock *Pred1 = *PI++;
1210 if (PI != PE) // More than two predecessors.
1212 BasicBlock *BB2 = (Pred0 == BB1) ? Pred1 : Pred0;
1213 BranchInst *BI2 = dyn_cast<BranchInst>(BB2->getTerminator());
1214 if (!BI2 || !BI2->isUnconditional())
1217 // Gather the PHI nodes in BBEnd.
1218 SmallDenseMap<std::pair<Value *, Value *>, PHINode *> JointValueMap;
1219 Instruction *FirstNonPhiInBBEnd = nullptr;
1220 for (BasicBlock::iterator I = BBEnd->begin(), E = BBEnd->end(); I != E; ++I) {
1221 if (PHINode *PN = dyn_cast<PHINode>(I)) {
1222 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1223 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1224 JointValueMap[std::make_pair(BB1V, BB2V)] = PN;
1226 FirstNonPhiInBBEnd = &*I;
1230 if (!FirstNonPhiInBBEnd)
1233 // This does very trivial matching, with limited scanning, to find identical
1234 // instructions in the two blocks. We scan backward for obviously identical
1235 // instructions in an identical order.
1236 BasicBlock::InstListType::reverse_iterator RI1 = BB1->getInstList().rbegin(),
1237 RE1 = BB1->getInstList().rend(),
1238 RI2 = BB2->getInstList().rbegin(),
1239 RE2 = BB2->getInstList().rend();
1241 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1244 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1247 // Skip the unconditional branches.
1251 bool Changed = false;
1252 while (RI1 != RE1 && RI2 != RE2) {
1254 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1257 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1261 Instruction *I1 = &*RI1, *I2 = &*RI2;
1262 auto InstPair = std::make_pair(I1, I2);
1263 // I1 and I2 should have a single use in the same PHI node, and they
1264 // perform the same operation.
1265 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
1266 if (isa<PHINode>(I1) || isa<PHINode>(I2) ||
1267 isa<TerminatorInst>(I1) || isa<TerminatorInst>(I2) ||
1268 isa<LandingPadInst>(I1) || isa<LandingPadInst>(I2) ||
1269 isa<AllocaInst>(I1) || isa<AllocaInst>(I2) ||
1270 I1->mayHaveSideEffects() || I2->mayHaveSideEffects() ||
1271 I1->mayReadOrWriteMemory() || I2->mayReadOrWriteMemory() ||
1272 !I1->hasOneUse() || !I2->hasOneUse() ||
1273 !JointValueMap.count(InstPair))
1276 // Check whether we should swap the operands of ICmpInst.
1277 // TODO: Add support of communativity.
1278 ICmpInst *ICmp1 = dyn_cast<ICmpInst>(I1), *ICmp2 = dyn_cast<ICmpInst>(I2);
1279 bool SwapOpnds = false;
1280 if (ICmp1 && ICmp2 &&
1281 ICmp1->getOperand(0) != ICmp2->getOperand(0) &&
1282 ICmp1->getOperand(1) != ICmp2->getOperand(1) &&
1283 (ICmp1->getOperand(0) == ICmp2->getOperand(1) ||
1284 ICmp1->getOperand(1) == ICmp2->getOperand(0))) {
1285 ICmp2->swapOperands();
1288 if (!I1->isSameOperationAs(I2)) {
1290 ICmp2->swapOperands();
1294 // The operands should be either the same or they need to be generated
1295 // with a PHI node after sinking. We only handle the case where there is
1296 // a single pair of different operands.
1297 Value *DifferentOp1 = nullptr, *DifferentOp2 = nullptr;
1298 unsigned Op1Idx = ~0U;
1299 for (unsigned I = 0, E = I1->getNumOperands(); I != E; ++I) {
1300 if (I1->getOperand(I) == I2->getOperand(I))
1302 // Early exit if we have more-than one pair of different operands or if
1303 // we need a PHI node to replace a constant.
1304 if (Op1Idx != ~0U ||
1305 isa<Constant>(I1->getOperand(I)) ||
1306 isa<Constant>(I2->getOperand(I))) {
1307 // If we can't sink the instructions, undo the swapping.
1309 ICmp2->swapOperands();
1312 DifferentOp1 = I1->getOperand(I);
1314 DifferentOp2 = I2->getOperand(I);
1317 DEBUG(dbgs() << "SINK common instructions " << *I1 << "\n");
1318 DEBUG(dbgs() << " " << *I2 << "\n");
1320 // We insert the pair of different operands to JointValueMap and
1321 // remove (I1, I2) from JointValueMap.
1322 if (Op1Idx != ~0U) {
1323 auto &NewPN = JointValueMap[std::make_pair(DifferentOp1, DifferentOp2)];
1326 PHINode::Create(DifferentOp1->getType(), 2,
1327 DifferentOp1->getName() + ".sink", BBEnd->begin());
1328 NewPN->addIncoming(DifferentOp1, BB1);
1329 NewPN->addIncoming(DifferentOp2, BB2);
1330 DEBUG(dbgs() << "Create PHI node " << *NewPN << "\n";);
1332 // I1 should use NewPN instead of DifferentOp1.
1333 I1->setOperand(Op1Idx, NewPN);
1335 PHINode *OldPN = JointValueMap[InstPair];
1336 JointValueMap.erase(InstPair);
1338 // We need to update RE1 and RE2 if we are going to sink the first
1339 // instruction in the basic block down.
1340 bool UpdateRE1 = (I1 == BB1->begin()), UpdateRE2 = (I2 == BB2->begin());
1341 // Sink the instruction.
1342 BBEnd->getInstList().splice(FirstNonPhiInBBEnd, BB1->getInstList(), I1);
1343 if (!OldPN->use_empty())
1344 OldPN->replaceAllUsesWith(I1);
1345 OldPN->eraseFromParent();
1347 if (!I2->use_empty())
1348 I2->replaceAllUsesWith(I1);
1349 I1->intersectOptionalDataWith(I2);
1350 // TODO: Use combineMetadata here to preserve what metadata we can
1351 // (analogous to the hoisting case above).
1352 I2->eraseFromParent();
1355 RE1 = BB1->getInstList().rend();
1357 RE2 = BB2->getInstList().rend();
1358 FirstNonPhiInBBEnd = I1;
1365 /// \brief Determine if we can hoist sink a sole store instruction out of a
1366 /// conditional block.
1368 /// We are looking for code like the following:
1370 /// store i32 %add, i32* %arrayidx2
1371 /// ... // No other stores or function calls (we could be calling a memory
1372 /// ... // function).
1373 /// %cmp = icmp ult %x, %y
1374 /// br i1 %cmp, label %EndBB, label %ThenBB
1376 /// store i32 %add5, i32* %arrayidx2
1380 /// We are going to transform this into:
1382 /// store i32 %add, i32* %arrayidx2
1384 /// %cmp = icmp ult %x, %y
1385 /// %add.add5 = select i1 %cmp, i32 %add, %add5
1386 /// store i32 %add.add5, i32* %arrayidx2
1389 /// \return The pointer to the value of the previous store if the store can be
1390 /// hoisted into the predecessor block. 0 otherwise.
1391 static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB,
1392 BasicBlock *StoreBB, BasicBlock *EndBB) {
1393 StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
1397 // Volatile or atomic.
1398 if (!StoreToHoist->isSimple())
1401 Value *StorePtr = StoreToHoist->getPointerOperand();
1403 // Look for a store to the same pointer in BrBB.
1404 unsigned MaxNumInstToLookAt = 10;
1405 for (BasicBlock::reverse_iterator RI = BrBB->rbegin(),
1406 RE = BrBB->rend(); RI != RE && (--MaxNumInstToLookAt); ++RI) {
1407 Instruction *CurI = &*RI;
1409 // Could be calling an instruction that effects memory like free().
1410 if (CurI->mayHaveSideEffects() && !isa<StoreInst>(CurI))
1413 StoreInst *SI = dyn_cast<StoreInst>(CurI);
1414 // Found the previous store make sure it stores to the same location.
1415 if (SI && SI->getPointerOperand() == StorePtr)
1416 // Found the previous store, return its value operand.
1417 return SI->getValueOperand();
1419 return nullptr; // Unknown store.
1425 /// \brief Speculate a conditional basic block flattening the CFG.
1427 /// Note that this is a very risky transform currently. Speculating
1428 /// instructions like this is most often not desirable. Instead, there is an MI
1429 /// pass which can do it with full awareness of the resource constraints.
1430 /// However, some cases are "obvious" and we should do directly. An example of
1431 /// this is speculating a single, reasonably cheap instruction.
1433 /// There is only one distinct advantage to flattening the CFG at the IR level:
1434 /// it makes very common but simplistic optimizations such as are common in
1435 /// instcombine and the DAG combiner more powerful by removing CFG edges and
1436 /// modeling their effects with easier to reason about SSA value graphs.
1439 /// An illustration of this transform is turning this IR:
1442 /// %cmp = icmp ult %x, %y
1443 /// br i1 %cmp, label %EndBB, label %ThenBB
1445 /// %sub = sub %x, %y
1448 /// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ]
1455 /// %cmp = icmp ult %x, %y
1456 /// %sub = sub %x, %y
1457 /// %cond = select i1 %cmp, 0, %sub
1461 /// \returns true if the conditional block is removed.
1462 static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB,
1463 const DataLayout *DL,
1464 const TargetTransformInfo &TTI) {
1465 // Be conservative for now. FP select instruction can often be expensive.
1466 Value *BrCond = BI->getCondition();
1467 if (isa<FCmpInst>(BrCond))
1470 BasicBlock *BB = BI->getParent();
1471 BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
1473 // If ThenBB is actually on the false edge of the conditional branch, remember
1474 // to swap the select operands later.
1475 bool Invert = false;
1476 if (ThenBB != BI->getSuccessor(0)) {
1477 assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
1480 assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
1482 // Keep a count of how many times instructions are used within CondBB when
1483 // they are candidates for sinking into CondBB. Specifically:
1484 // - They are defined in BB, and
1485 // - They have no side effects, and
1486 // - All of their uses are in CondBB.
1487 SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
1489 unsigned SpeculationCost = 0;
1490 Value *SpeculatedStoreValue = nullptr;
1491 StoreInst *SpeculatedStore = nullptr;
1492 for (BasicBlock::iterator BBI = ThenBB->begin(),
1493 BBE = std::prev(ThenBB->end());
1494 BBI != BBE; ++BBI) {
1495 Instruction *I = BBI;
1497 if (isa<DbgInfoIntrinsic>(I))
1500 // Only speculatively execution a single instruction (not counting the
1501 // terminator) for now.
1503 if (SpeculationCost > 1)
1506 // Don't hoist the instruction if it's unsafe or expensive.
1507 if (!isSafeToSpeculativelyExecute(I, DL) &&
1508 !(HoistCondStores &&
1509 (SpeculatedStoreValue = isSafeToSpeculateStore(I, BB, ThenBB,
1512 if (!SpeculatedStoreValue &&
1513 ComputeSpeculationCost(I, DL, TTI) > PHINodeFoldingThreshold *
1514 TargetTransformInfo::TCC_Basic)
1517 // Store the store speculation candidate.
1518 if (SpeculatedStoreValue)
1519 SpeculatedStore = cast<StoreInst>(I);
1521 // Do not hoist the instruction if any of its operands are defined but not
1522 // used in BB. The transformation will prevent the operand from
1523 // being sunk into the use block.
1524 for (User::op_iterator i = I->op_begin(), e = I->op_end();
1526 Instruction *OpI = dyn_cast<Instruction>(*i);
1527 if (!OpI || OpI->getParent() != BB ||
1528 OpI->mayHaveSideEffects())
1529 continue; // Not a candidate for sinking.
1531 ++SinkCandidateUseCounts[OpI];
1535 // Consider any sink candidates which are only used in CondBB as costs for
1536 // speculation. Note, while we iterate over a DenseMap here, we are summing
1537 // and so iteration order isn't significant.
1538 for (SmallDenseMap<Instruction *, unsigned, 4>::iterator I =
1539 SinkCandidateUseCounts.begin(), E = SinkCandidateUseCounts.end();
1541 if (I->first->getNumUses() == I->second) {
1543 if (SpeculationCost > 1)
1547 // Check that the PHI nodes can be converted to selects.
1548 bool HaveRewritablePHIs = false;
1549 for (BasicBlock::iterator I = EndBB->begin();
1550 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1551 Value *OrigV = PN->getIncomingValueForBlock(BB);
1552 Value *ThenV = PN->getIncomingValueForBlock(ThenBB);
1554 // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf.
1555 // Skip PHIs which are trivial.
1559 // Don't convert to selects if we could remove undefined behavior instead.
1560 if (passingValueIsAlwaysUndefined(OrigV, PN) ||
1561 passingValueIsAlwaysUndefined(ThenV, PN))
1564 HaveRewritablePHIs = true;
1565 ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
1566 ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
1567 if (!OrigCE && !ThenCE)
1568 continue; // Known safe and cheap.
1570 if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE, DL)) ||
1571 (OrigCE && !isSafeToSpeculativelyExecute(OrigCE, DL)))
1573 unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE, DL, TTI) : 0;
1574 unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE, DL, TTI) : 0;
1575 unsigned MaxCost = 2 * PHINodeFoldingThreshold *
1576 TargetTransformInfo::TCC_Basic;
1577 if (OrigCost + ThenCost > MaxCost)
1580 // Account for the cost of an unfolded ConstantExpr which could end up
1581 // getting expanded into Instructions.
1582 // FIXME: This doesn't account for how many operations are combined in the
1583 // constant expression.
1585 if (SpeculationCost > 1)
1589 // If there are no PHIs to process, bail early. This helps ensure idempotence
1591 if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue))
1594 // If we get here, we can hoist the instruction and if-convert.
1595 DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
1597 // Insert a select of the value of the speculated store.
1598 if (SpeculatedStoreValue) {
1599 IRBuilder<true, NoFolder> Builder(BI);
1600 Value *TrueV = SpeculatedStore->getValueOperand();
1601 Value *FalseV = SpeculatedStoreValue;
1603 std::swap(TrueV, FalseV);
1604 Value *S = Builder.CreateSelect(BrCond, TrueV, FalseV, TrueV->getName() +
1605 "." + FalseV->getName());
1606 SpeculatedStore->setOperand(0, S);
1609 // Hoist the instructions.
1610 BB->getInstList().splice(BI, ThenBB->getInstList(), ThenBB->begin(),
1611 std::prev(ThenBB->end()));
1613 // Insert selects and rewrite the PHI operands.
1614 IRBuilder<true, NoFolder> Builder(BI);
1615 for (BasicBlock::iterator I = EndBB->begin();
1616 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1617 unsigned OrigI = PN->getBasicBlockIndex(BB);
1618 unsigned ThenI = PN->getBasicBlockIndex(ThenBB);
1619 Value *OrigV = PN->getIncomingValue(OrigI);
1620 Value *ThenV = PN->getIncomingValue(ThenI);
1622 // Skip PHIs which are trivial.
1626 // Create a select whose true value is the speculatively executed value and
1627 // false value is the preexisting value. Swap them if the branch
1628 // destinations were inverted.
1629 Value *TrueV = ThenV, *FalseV = OrigV;
1631 std::swap(TrueV, FalseV);
1632 Value *V = Builder.CreateSelect(BrCond, TrueV, FalseV,
1633 TrueV->getName() + "." + FalseV->getName());
1634 PN->setIncomingValue(OrigI, V);
1635 PN->setIncomingValue(ThenI, V);
1642 /// \returns True if this block contains a CallInst with the NoDuplicate
1644 static bool HasNoDuplicateCall(const BasicBlock *BB) {
1645 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1646 const CallInst *CI = dyn_cast<CallInst>(I);
1649 if (CI->cannotDuplicate())
1655 /// BlockIsSimpleEnoughToThreadThrough - Return true if we can thread a branch
1656 /// across this block.
1657 static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
1658 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
1661 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1662 if (isa<DbgInfoIntrinsic>(BBI))
1664 if (Size > 10) return false; // Don't clone large BB's.
1667 // We can only support instructions that do not define values that are
1668 // live outside of the current basic block.
1669 for (User *U : BBI->users()) {
1670 Instruction *UI = cast<Instruction>(U);
1671 if (UI->getParent() != BB || isa<PHINode>(UI)) return false;
1674 // Looks ok, continue checking.
1680 /// FoldCondBranchOnPHI - If we have a conditional branch on a PHI node value
1681 /// that is defined in the same block as the branch and if any PHI entries are
1682 /// constants, thread edges corresponding to that entry to be branches to their
1683 /// ultimate destination.
1684 static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout *DL) {
1685 BasicBlock *BB = BI->getParent();
1686 PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
1687 // NOTE: we currently cannot transform this case if the PHI node is used
1688 // outside of the block.
1689 if (!PN || PN->getParent() != BB || !PN->hasOneUse())
1692 // Degenerate case of a single entry PHI.
1693 if (PN->getNumIncomingValues() == 1) {
1694 FoldSingleEntryPHINodes(PN->getParent());
1698 // Now we know that this block has multiple preds and two succs.
1699 if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
1701 if (HasNoDuplicateCall(BB)) return false;
1703 // Okay, this is a simple enough basic block. See if any phi values are
1705 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1706 ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
1707 if (!CB || !CB->getType()->isIntegerTy(1)) continue;
1709 // Okay, we now know that all edges from PredBB should be revectored to
1710 // branch to RealDest.
1711 BasicBlock *PredBB = PN->getIncomingBlock(i);
1712 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
1714 if (RealDest == BB) continue; // Skip self loops.
1715 // Skip if the predecessor's terminator is an indirect branch.
1716 if (isa<IndirectBrInst>(PredBB->getTerminator())) continue;
1718 // The dest block might have PHI nodes, other predecessors and other
1719 // difficult cases. Instead of being smart about this, just insert a new
1720 // block that jumps to the destination block, effectively splitting
1721 // the edge we are about to create.
1722 BasicBlock *EdgeBB = BasicBlock::Create(BB->getContext(),
1723 RealDest->getName()+".critedge",
1724 RealDest->getParent(), RealDest);
1725 BranchInst::Create(RealDest, EdgeBB);
1727 // Update PHI nodes.
1728 AddPredecessorToBlock(RealDest, EdgeBB, BB);
1730 // BB may have instructions that are being threaded over. Clone these
1731 // instructions into EdgeBB. We know that there will be no uses of the
1732 // cloned instructions outside of EdgeBB.
1733 BasicBlock::iterator InsertPt = EdgeBB->begin();
1734 DenseMap<Value*, Value*> TranslateMap; // Track translated values.
1735 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1736 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
1737 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
1740 // Clone the instruction.
1741 Instruction *N = BBI->clone();
1742 if (BBI->hasName()) N->setName(BBI->getName()+".c");
1744 // Update operands due to translation.
1745 for (User::op_iterator i = N->op_begin(), e = N->op_end();
1747 DenseMap<Value*, Value*>::iterator PI = TranslateMap.find(*i);
1748 if (PI != TranslateMap.end())
1752 // Check for trivial simplification.
1753 if (Value *V = SimplifyInstruction(N, DL)) {
1754 TranslateMap[BBI] = V;
1755 delete N; // Instruction folded away, don't need actual inst
1757 // Insert the new instruction into its new home.
1758 EdgeBB->getInstList().insert(InsertPt, N);
1759 if (!BBI->use_empty())
1760 TranslateMap[BBI] = N;
1764 // Loop over all of the edges from PredBB to BB, changing them to branch
1765 // to EdgeBB instead.
1766 TerminatorInst *PredBBTI = PredBB->getTerminator();
1767 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
1768 if (PredBBTI->getSuccessor(i) == BB) {
1769 BB->removePredecessor(PredBB);
1770 PredBBTI->setSuccessor(i, EdgeBB);
1773 // Recurse, simplifying any other constants.
1774 return FoldCondBranchOnPHI(BI, DL) | true;
1780 /// FoldTwoEntryPHINode - Given a BB that starts with the specified two-entry
1781 /// PHI node, see if we can eliminate it.
1782 static bool FoldTwoEntryPHINode(PHINode *PN, const DataLayout *DL,
1783 const TargetTransformInfo &TTI) {
1784 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
1785 // statement", which has a very simple dominance structure. Basically, we
1786 // are trying to find the condition that is being branched on, which
1787 // subsequently causes this merge to happen. We really want control
1788 // dependence information for this check, but simplifycfg can't keep it up
1789 // to date, and this catches most of the cases we care about anyway.
1790 BasicBlock *BB = PN->getParent();
1791 BasicBlock *IfTrue, *IfFalse;
1792 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
1794 // Don't bother if the branch will be constant folded trivially.
1795 isa<ConstantInt>(IfCond))
1798 // Okay, we found that we can merge this two-entry phi node into a select.
1799 // Doing so would require us to fold *all* two entry phi nodes in this block.
1800 // At some point this becomes non-profitable (particularly if the target
1801 // doesn't support cmov's). Only do this transformation if there are two or
1802 // fewer PHI nodes in this block.
1803 unsigned NumPhis = 0;
1804 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
1808 // Loop over the PHI's seeing if we can promote them all to select
1809 // instructions. While we are at it, keep track of the instructions
1810 // that need to be moved to the dominating block.
1811 SmallPtrSet<Instruction*, 4> AggressiveInsts;
1812 unsigned MaxCostVal0 = PHINodeFoldingThreshold,
1813 MaxCostVal1 = PHINodeFoldingThreshold;
1814 MaxCostVal0 *= TargetTransformInfo::TCC_Basic;
1815 MaxCostVal1 *= TargetTransformInfo::TCC_Basic;
1817 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
1818 PHINode *PN = cast<PHINode>(II++);
1819 if (Value *V = SimplifyInstruction(PN, DL)) {
1820 PN->replaceAllUsesWith(V);
1821 PN->eraseFromParent();
1825 if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts,
1826 MaxCostVal0, DL, TTI) ||
1827 !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts,
1828 MaxCostVal1, DL, TTI))
1832 // If we folded the first phi, PN dangles at this point. Refresh it. If
1833 // we ran out of PHIs then we simplified them all.
1834 PN = dyn_cast<PHINode>(BB->begin());
1835 if (!PN) return true;
1837 // Don't fold i1 branches on PHIs which contain binary operators. These can
1838 // often be turned into switches and other things.
1839 if (PN->getType()->isIntegerTy(1) &&
1840 (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
1841 isa<BinaryOperator>(PN->getIncomingValue(1)) ||
1842 isa<BinaryOperator>(IfCond)))
1845 // If we all PHI nodes are promotable, check to make sure that all
1846 // instructions in the predecessor blocks can be promoted as well. If
1847 // not, we won't be able to get rid of the control flow, so it's not
1848 // worth promoting to select instructions.
1849 BasicBlock *DomBlock = nullptr;
1850 BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
1851 BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
1852 if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
1855 DomBlock = *pred_begin(IfBlock1);
1856 for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I)
1857 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
1858 // This is not an aggressive instruction that we can promote.
1859 // Because of this, we won't be able to get rid of the control
1860 // flow, so the xform is not worth it.
1865 if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
1868 DomBlock = *pred_begin(IfBlock2);
1869 for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I)
1870 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
1871 // This is not an aggressive instruction that we can promote.
1872 // Because of this, we won't be able to get rid of the control
1873 // flow, so the xform is not worth it.
1878 DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: "
1879 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
1881 // If we can still promote the PHI nodes after this gauntlet of tests,
1882 // do all of the PHI's now.
1883 Instruction *InsertPt = DomBlock->getTerminator();
1884 IRBuilder<true, NoFolder> Builder(InsertPt);
1886 // Move all 'aggressive' instructions, which are defined in the
1887 // conditional parts of the if's up to the dominating block.
1889 DomBlock->getInstList().splice(InsertPt,
1890 IfBlock1->getInstList(), IfBlock1->begin(),
1891 IfBlock1->getTerminator());
1893 DomBlock->getInstList().splice(InsertPt,
1894 IfBlock2->getInstList(), IfBlock2->begin(),
1895 IfBlock2->getTerminator());
1897 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1898 // Change the PHI node into a select instruction.
1899 Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1900 Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
1903 cast<SelectInst>(Builder.CreateSelect(IfCond, TrueVal, FalseVal, ""));
1904 PN->replaceAllUsesWith(NV);
1906 PN->eraseFromParent();
1909 // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
1910 // has been flattened. Change DomBlock to jump directly to our new block to
1911 // avoid other simplifycfg's kicking in on the diamond.
1912 TerminatorInst *OldTI = DomBlock->getTerminator();
1913 Builder.SetInsertPoint(OldTI);
1914 Builder.CreateBr(BB);
1915 OldTI->eraseFromParent();
1919 /// SimplifyCondBranchToTwoReturns - If we found a conditional branch that goes
1920 /// to two returning blocks, try to merge them together into one return,
1921 /// introducing a select if the return values disagree.
1922 static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
1923 IRBuilder<> &Builder) {
1924 assert(BI->isConditional() && "Must be a conditional branch");
1925 BasicBlock *TrueSucc = BI->getSuccessor(0);
1926 BasicBlock *FalseSucc = BI->getSuccessor(1);
1927 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
1928 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
1930 // Check to ensure both blocks are empty (just a return) or optionally empty
1931 // with PHI nodes. If there are other instructions, merging would cause extra
1932 // computation on one path or the other.
1933 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
1935 if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
1938 Builder.SetInsertPoint(BI);
1939 // Okay, we found a branch that is going to two return nodes. If
1940 // there is no return value for this function, just change the
1941 // branch into a return.
1942 if (FalseRet->getNumOperands() == 0) {
1943 TrueSucc->removePredecessor(BI->getParent());
1944 FalseSucc->removePredecessor(BI->getParent());
1945 Builder.CreateRetVoid();
1946 EraseTerminatorInstAndDCECond(BI);
1950 // Otherwise, figure out what the true and false return values are
1951 // so we can insert a new select instruction.
1952 Value *TrueValue = TrueRet->getReturnValue();
1953 Value *FalseValue = FalseRet->getReturnValue();
1955 // Unwrap any PHI nodes in the return blocks.
1956 if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
1957 if (TVPN->getParent() == TrueSucc)
1958 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
1959 if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
1960 if (FVPN->getParent() == FalseSucc)
1961 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
1963 // In order for this transformation to be safe, we must be able to
1964 // unconditionally execute both operands to the return. This is
1965 // normally the case, but we could have a potentially-trapping
1966 // constant expression that prevents this transformation from being
1968 if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
1971 if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
1975 // Okay, we collected all the mapped values and checked them for sanity, and
1976 // defined to really do this transformation. First, update the CFG.
1977 TrueSucc->removePredecessor(BI->getParent());
1978 FalseSucc->removePredecessor(BI->getParent());
1980 // Insert select instructions where needed.
1981 Value *BrCond = BI->getCondition();
1983 // Insert a select if the results differ.
1984 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
1985 } else if (isa<UndefValue>(TrueValue)) {
1986 TrueValue = FalseValue;
1988 TrueValue = Builder.CreateSelect(BrCond, TrueValue,
1989 FalseValue, "retval");
1993 Value *RI = !TrueValue ?
1994 Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
1998 DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
1999 << "\n " << *BI << "NewRet = " << *RI
2000 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc);
2002 EraseTerminatorInstAndDCECond(BI);
2007 /// ExtractBranchMetadata - Given a conditional BranchInstruction, retrieve the
2008 /// probabilities of the branch taking each edge. Fills in the two APInt
2009 /// parameters and return true, or returns false if no or invalid metadata was
2011 static bool ExtractBranchMetadata(BranchInst *BI,
2012 uint64_t &ProbTrue, uint64_t &ProbFalse) {
2013 assert(BI->isConditional() &&
2014 "Looking for probabilities on unconditional branch?");
2015 MDNode *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
2016 if (!ProfileData || ProfileData->getNumOperands() != 3) return false;
2017 ConstantInt *CITrue =
2018 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
2019 ConstantInt *CIFalse =
2020 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
2021 if (!CITrue || !CIFalse) return false;
2022 ProbTrue = CITrue->getValue().getZExtValue();
2023 ProbFalse = CIFalse->getValue().getZExtValue();
2027 /// checkCSEInPredecessor - Return true if the given instruction is available
2028 /// in its predecessor block. If yes, the instruction will be removed.
2030 static bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB) {
2031 if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
2033 for (BasicBlock::iterator I = PB->begin(), E = PB->end(); I != E; I++) {
2034 Instruction *PBI = &*I;
2035 // Check whether Inst and PBI generate the same value.
2036 if (Inst->isIdenticalTo(PBI)) {
2037 Inst->replaceAllUsesWith(PBI);
2038 Inst->eraseFromParent();
2045 /// FoldBranchToCommonDest - If this basic block is simple enough, and if a
2046 /// predecessor branches to us and one of our successors, fold the block into
2047 /// the predecessor and use logical operations to pick the right destination.
2048 bool llvm::FoldBranchToCommonDest(BranchInst *BI, const DataLayout *DL,
2049 unsigned BonusInstThreshold) {
2050 BasicBlock *BB = BI->getParent();
2052 Instruction *Cond = nullptr;
2053 if (BI->isConditional())
2054 Cond = dyn_cast<Instruction>(BI->getCondition());
2056 // For unconditional branch, check for a simple CFG pattern, where
2057 // BB has a single predecessor and BB's successor is also its predecessor's
2058 // successor. If such pattern exisits, check for CSE between BB and its
2060 if (BasicBlock *PB = BB->getSinglePredecessor())
2061 if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
2062 if (PBI->isConditional() &&
2063 (BI->getSuccessor(0) == PBI->getSuccessor(0) ||
2064 BI->getSuccessor(0) == PBI->getSuccessor(1))) {
2065 for (BasicBlock::iterator I = BB->begin(), E = BB->end();
2067 Instruction *Curr = I++;
2068 if (isa<CmpInst>(Curr)) {
2072 // Quit if we can't remove this instruction.
2073 if (!checkCSEInPredecessor(Curr, PB))
2082 if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
2083 Cond->getParent() != BB || !Cond->hasOneUse())
2086 // Make sure the instruction after the condition is the cond branch.
2087 BasicBlock::iterator CondIt = Cond; ++CondIt;
2089 // Ignore dbg intrinsics.
2090 while (isa<DbgInfoIntrinsic>(CondIt)) ++CondIt;
2095 // Only allow this transformation if computing the condition doesn't involve
2096 // too many instructions and these involved instructions can be executed
2097 // unconditionally. We denote all involved instructions except the condition
2098 // as "bonus instructions", and only allow this transformation when the
2099 // number of the bonus instructions does not exceed a certain threshold.
2100 unsigned NumBonusInsts = 0;
2101 for (auto I = BB->begin(); Cond != I; ++I) {
2102 // Ignore dbg intrinsics.
2103 if (isa<DbgInfoIntrinsic>(I))
2105 if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(I, DL))
2107 // I has only one use and can be executed unconditionally.
2108 Instruction *User = dyn_cast<Instruction>(I->user_back());
2109 if (User == nullptr || User->getParent() != BB)
2111 // I is used in the same BB. Since BI uses Cond and doesn't have more slots
2112 // to use any other instruction, User must be an instruction between next(I)
2115 // Early exits once we reach the limit.
2116 if (NumBonusInsts > BonusInstThreshold)
2120 // Cond is known to be a compare or binary operator. Check to make sure that
2121 // neither operand is a potentially-trapping constant expression.
2122 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
2125 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
2129 // Finally, don't infinitely unroll conditional loops.
2130 BasicBlock *TrueDest = BI->getSuccessor(0);
2131 BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr;
2132 if (TrueDest == BB || FalseDest == BB)
2135 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2136 BasicBlock *PredBlock = *PI;
2137 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
2139 // Check that we have two conditional branches. If there is a PHI node in
2140 // the common successor, verify that the same value flows in from both
2142 SmallVector<PHINode*, 4> PHIs;
2143 if (!PBI || PBI->isUnconditional() ||
2144 (BI->isConditional() &&
2145 !SafeToMergeTerminators(BI, PBI)) ||
2146 (!BI->isConditional() &&
2147 !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs)))
2150 // Determine if the two branches share a common destination.
2151 Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd;
2152 bool InvertPredCond = false;
2154 if (BI->isConditional()) {
2155 if (PBI->getSuccessor(0) == TrueDest)
2156 Opc = Instruction::Or;
2157 else if (PBI->getSuccessor(1) == FalseDest)
2158 Opc = Instruction::And;
2159 else if (PBI->getSuccessor(0) == FalseDest)
2160 Opc = Instruction::And, InvertPredCond = true;
2161 else if (PBI->getSuccessor(1) == TrueDest)
2162 Opc = Instruction::Or, InvertPredCond = true;
2166 if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest)
2170 DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
2171 IRBuilder<> Builder(PBI);
2173 // If we need to invert the condition in the pred block to match, do so now.
2174 if (InvertPredCond) {
2175 Value *NewCond = PBI->getCondition();
2177 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
2178 CmpInst *CI = cast<CmpInst>(NewCond);
2179 CI->setPredicate(CI->getInversePredicate());
2181 NewCond = Builder.CreateNot(NewCond,
2182 PBI->getCondition()->getName()+".not");
2185 PBI->setCondition(NewCond);
2186 PBI->swapSuccessors();
2189 // If we have bonus instructions, clone them into the predecessor block.
2190 // Note that there may be mutliple predecessor blocks, so we cannot move
2191 // bonus instructions to a predecessor block.
2192 ValueToValueMapTy VMap; // maps original values to cloned values
2193 // We already make sure Cond is the last instruction before BI. Therefore,
2194 // every instructions before Cond other than DbgInfoIntrinsic are bonus
2196 for (auto BonusInst = BB->begin(); Cond != BonusInst; ++BonusInst) {
2197 if (isa<DbgInfoIntrinsic>(BonusInst))
2199 Instruction *NewBonusInst = BonusInst->clone();
2200 RemapInstruction(NewBonusInst, VMap,
2201 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
2202 VMap[BonusInst] = NewBonusInst;
2204 // If we moved a load, we cannot any longer claim any knowledge about
2205 // its potential value. The previous information might have been valid
2206 // only given the branch precondition.
2207 // For an analogous reason, we must also drop all the metadata whose
2208 // semantics we don't understand.
2209 NewBonusInst->dropUnknownMetadata(LLVMContext::MD_dbg);
2211 PredBlock->getInstList().insert(PBI, NewBonusInst);
2212 NewBonusInst->takeName(BonusInst);
2213 BonusInst->setName(BonusInst->getName() + ".old");
2216 // Clone Cond into the predecessor basic block, and or/and the
2217 // two conditions together.
2218 Instruction *New = Cond->clone();
2219 RemapInstruction(New, VMap,
2220 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
2221 PredBlock->getInstList().insert(PBI, New);
2222 New->takeName(Cond);
2223 Cond->setName(New->getName() + ".old");
2225 if (BI->isConditional()) {
2226 Instruction *NewCond =
2227 cast<Instruction>(Builder.CreateBinOp(Opc, PBI->getCondition(),
2229 PBI->setCondition(NewCond);
2231 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2232 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2234 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2236 SmallVector<uint64_t, 8> NewWeights;
2238 if (PBI->getSuccessor(0) == BB) {
2239 if (PredHasWeights && SuccHasWeights) {
2240 // PBI: br i1 %x, BB, FalseDest
2241 // BI: br i1 %y, TrueDest, FalseDest
2242 //TrueWeight is TrueWeight for PBI * TrueWeight for BI.
2243 NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
2244 //FalseWeight is FalseWeight for PBI * TotalWeight for BI +
2245 // TrueWeight for PBI * FalseWeight for BI.
2246 // We assume that total weights of a BranchInst can fit into 32 bits.
2247 // Therefore, we will not have overflow using 64-bit arithmetic.
2248 NewWeights.push_back(PredFalseWeight * (SuccFalseWeight +
2249 SuccTrueWeight) + PredTrueWeight * SuccFalseWeight);
2251 AddPredecessorToBlock(TrueDest, PredBlock, BB);
2252 PBI->setSuccessor(0, TrueDest);
2254 if (PBI->getSuccessor(1) == BB) {
2255 if (PredHasWeights && SuccHasWeights) {
2256 // PBI: br i1 %x, TrueDest, BB
2257 // BI: br i1 %y, TrueDest, FalseDest
2258 //TrueWeight is TrueWeight for PBI * TotalWeight for BI +
2259 // FalseWeight for PBI * TrueWeight for BI.
2260 NewWeights.push_back(PredTrueWeight * (SuccFalseWeight +
2261 SuccTrueWeight) + PredFalseWeight * SuccTrueWeight);
2262 //FalseWeight is FalseWeight for PBI * FalseWeight for BI.
2263 NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
2265 AddPredecessorToBlock(FalseDest, PredBlock, BB);
2266 PBI->setSuccessor(1, FalseDest);
2268 if (NewWeights.size() == 2) {
2269 // Halve the weights if any of them cannot fit in an uint32_t
2270 FitWeights(NewWeights);
2272 SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),NewWeights.end());
2273 PBI->setMetadata(LLVMContext::MD_prof,
2274 MDBuilder(BI->getContext()).
2275 createBranchWeights(MDWeights));
2277 PBI->setMetadata(LLVMContext::MD_prof, nullptr);
2279 // Update PHI nodes in the common successors.
2280 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
2281 ConstantInt *PBI_C = cast<ConstantInt>(
2282 PHIs[i]->getIncomingValueForBlock(PBI->getParent()));
2283 assert(PBI_C->getType()->isIntegerTy(1));
2284 Instruction *MergedCond = nullptr;
2285 if (PBI->getSuccessor(0) == TrueDest) {
2286 // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value)
2287 // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value)
2288 // is false: !PBI_Cond and BI_Value
2289 Instruction *NotCond =
2290 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2293 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2298 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2299 PBI->getCondition(), MergedCond,
2302 // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C)
2303 // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond)
2304 // is false: PBI_Cond and BI_Value
2306 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2307 PBI->getCondition(), New,
2309 if (PBI_C->isOne()) {
2310 Instruction *NotCond =
2311 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2314 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2315 NotCond, MergedCond,
2320 PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()),
2323 // Change PBI from Conditional to Unconditional.
2324 BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI);
2325 EraseTerminatorInstAndDCECond(PBI);
2329 // TODO: If BB is reachable from all paths through PredBlock, then we
2330 // could replace PBI's branch probabilities with BI's.
2332 // Copy any debug value intrinsics into the end of PredBlock.
2333 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
2334 if (isa<DbgInfoIntrinsic>(*I))
2335 I->clone()->insertBefore(PBI);
2342 /// SimplifyCondBranchToCondBranch - If we have a conditional branch as a
2343 /// predecessor of another block, this function tries to simplify it. We know
2344 /// that PBI and BI are both conditional branches, and BI is in one of the
2345 /// successor blocks of PBI - PBI branches to BI.
2346 static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI) {
2347 assert(PBI->isConditional() && BI->isConditional());
2348 BasicBlock *BB = BI->getParent();
2350 // If this block ends with a branch instruction, and if there is a
2351 // predecessor that ends on a branch of the same condition, make
2352 // this conditional branch redundant.
2353 if (PBI->getCondition() == BI->getCondition() &&
2354 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2355 // Okay, the outcome of this conditional branch is statically
2356 // knowable. If this block had a single pred, handle specially.
2357 if (BB->getSinglePredecessor()) {
2358 // Turn this into a branch on constant.
2359 bool CondIsTrue = PBI->getSuccessor(0) == BB;
2360 BI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
2362 return true; // Nuke the branch on constant.
2365 // Otherwise, if there are multiple predecessors, insert a PHI that merges
2366 // in the constant and simplify the block result. Subsequent passes of
2367 // simplifycfg will thread the block.
2368 if (BlockIsSimpleEnoughToThreadThrough(BB)) {
2369 pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
2370 PHINode *NewPN = PHINode::Create(Type::getInt1Ty(BB->getContext()),
2371 std::distance(PB, PE),
2372 BI->getCondition()->getName() + ".pr",
2374 // Okay, we're going to insert the PHI node. Since PBI is not the only
2375 // predecessor, compute the PHI'd conditional value for all of the preds.
2376 // Any predecessor where the condition is not computable we keep symbolic.
2377 for (pred_iterator PI = PB; PI != PE; ++PI) {
2378 BasicBlock *P = *PI;
2379 if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) &&
2380 PBI != BI && PBI->isConditional() &&
2381 PBI->getCondition() == BI->getCondition() &&
2382 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2383 bool CondIsTrue = PBI->getSuccessor(0) == BB;
2384 NewPN->addIncoming(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
2387 NewPN->addIncoming(BI->getCondition(), P);
2391 BI->setCondition(NewPN);
2396 // If this is a conditional branch in an empty block, and if any
2397 // predecessors are a conditional branch to one of our destinations,
2398 // fold the conditions into logical ops and one cond br.
2399 BasicBlock::iterator BBI = BB->begin();
2400 // Ignore dbg intrinsics.
2401 while (isa<DbgInfoIntrinsic>(BBI))
2407 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
2412 if (PBI->getSuccessor(0) == BI->getSuccessor(0))
2414 else if (PBI->getSuccessor(0) == BI->getSuccessor(1))
2415 PBIOp = 0, BIOp = 1;
2416 else if (PBI->getSuccessor(1) == BI->getSuccessor(0))
2417 PBIOp = 1, BIOp = 0;
2418 else if (PBI->getSuccessor(1) == BI->getSuccessor(1))
2423 // Check to make sure that the other destination of this branch
2424 // isn't BB itself. If so, this is an infinite loop that will
2425 // keep getting unwound.
2426 if (PBI->getSuccessor(PBIOp) == BB)
2429 // Do not perform this transformation if it would require
2430 // insertion of a large number of select instructions. For targets
2431 // without predication/cmovs, this is a big pessimization.
2433 // Also do not perform this transformation if any phi node in the common
2434 // destination block can trap when reached by BB or PBB (PR17073). In that
2435 // case, it would be unsafe to hoist the operation into a select instruction.
2437 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
2438 unsigned NumPhis = 0;
2439 for (BasicBlock::iterator II = CommonDest->begin();
2440 isa<PHINode>(II); ++II, ++NumPhis) {
2441 if (NumPhis > 2) // Disable this xform.
2444 PHINode *PN = cast<PHINode>(II);
2445 Value *BIV = PN->getIncomingValueForBlock(BB);
2446 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV))
2450 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2451 Value *PBIV = PN->getIncomingValue(PBBIdx);
2452 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV))
2457 // Finally, if everything is ok, fold the branches to logical ops.
2458 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
2460 DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
2461 << "AND: " << *BI->getParent());
2464 // If OtherDest *is* BB, then BB is a basic block with a single conditional
2465 // branch in it, where one edge (OtherDest) goes back to itself but the other
2466 // exits. We don't *know* that the program avoids the infinite loop
2467 // (even though that seems likely). If we do this xform naively, we'll end up
2468 // recursively unpeeling the loop. Since we know that (after the xform is
2469 // done) that the block *is* infinite if reached, we just make it an obviously
2470 // infinite loop with no cond branch.
2471 if (OtherDest == BB) {
2472 // Insert it at the end of the function, because it's either code,
2473 // or it won't matter if it's hot. :)
2474 BasicBlock *InfLoopBlock = BasicBlock::Create(BB->getContext(),
2475 "infloop", BB->getParent());
2476 BranchInst::Create(InfLoopBlock, InfLoopBlock);
2477 OtherDest = InfLoopBlock;
2480 DEBUG(dbgs() << *PBI->getParent()->getParent());
2482 // BI may have other predecessors. Because of this, we leave
2483 // it alone, but modify PBI.
2485 // Make sure we get to CommonDest on True&True directions.
2486 Value *PBICond = PBI->getCondition();
2487 IRBuilder<true, NoFolder> Builder(PBI);
2489 PBICond = Builder.CreateNot(PBICond, PBICond->getName()+".not");
2491 Value *BICond = BI->getCondition();
2493 BICond = Builder.CreateNot(BICond, BICond->getName()+".not");
2495 // Merge the conditions.
2496 Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
2498 // Modify PBI to branch on the new condition to the new dests.
2499 PBI->setCondition(Cond);
2500 PBI->setSuccessor(0, CommonDest);
2501 PBI->setSuccessor(1, OtherDest);
2503 // Update branch weight for PBI.
2504 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2505 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2507 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2509 if (PredHasWeights && SuccHasWeights) {
2510 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
2511 uint64_t PredOther = PBIOp ?PredTrueWeight : PredFalseWeight;
2512 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
2513 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
2514 // The weight to CommonDest should be PredCommon * SuccTotal +
2515 // PredOther * SuccCommon.
2516 // The weight to OtherDest should be PredOther * SuccOther.
2517 SmallVector<uint64_t, 2> NewWeights;
2518 NewWeights.push_back(PredCommon * (SuccCommon + SuccOther) +
2519 PredOther * SuccCommon);
2520 NewWeights.push_back(PredOther * SuccOther);
2521 // Halve the weights if any of them cannot fit in an uint32_t
2522 FitWeights(NewWeights);
2524 SmallVector<uint32_t, 2> MDWeights(NewWeights.begin(),NewWeights.end());
2525 PBI->setMetadata(LLVMContext::MD_prof,
2526 MDBuilder(BI->getContext()).
2527 createBranchWeights(MDWeights));
2530 // OtherDest may have phi nodes. If so, add an entry from PBI's
2531 // block that are identical to the entries for BI's block.
2532 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
2534 // We know that the CommonDest already had an edge from PBI to
2535 // it. If it has PHIs though, the PHIs may have different
2536 // entries for BB and PBI's BB. If so, insert a select to make
2539 for (BasicBlock::iterator II = CommonDest->begin();
2540 (PN = dyn_cast<PHINode>(II)); ++II) {
2541 Value *BIV = PN->getIncomingValueForBlock(BB);
2542 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2543 Value *PBIV = PN->getIncomingValue(PBBIdx);
2545 // Insert a select in PBI to pick the right value.
2546 Value *NV = cast<SelectInst>
2547 (Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName()+".mux"));
2548 PN->setIncomingValue(PBBIdx, NV);
2552 DEBUG(dbgs() << "INTO: " << *PBI->getParent());
2553 DEBUG(dbgs() << *PBI->getParent()->getParent());
2555 // This basic block is probably dead. We know it has at least
2556 // one fewer predecessor.
2560 // SimplifyTerminatorOnSelect - Simplifies a terminator by replacing it with a
2561 // branch to TrueBB if Cond is true or to FalseBB if Cond is false.
2562 // Takes care of updating the successors and removing the old terminator.
2563 // Also makes sure not to introduce new successors by assuming that edges to
2564 // non-successor TrueBBs and FalseBBs aren't reachable.
2565 static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond,
2566 BasicBlock *TrueBB, BasicBlock *FalseBB,
2567 uint32_t TrueWeight,
2568 uint32_t FalseWeight){
2569 // Remove any superfluous successor edges from the CFG.
2570 // First, figure out which successors to preserve.
2571 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
2573 BasicBlock *KeepEdge1 = TrueBB;
2574 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
2576 // Then remove the rest.
2577 for (unsigned I = 0, E = OldTerm->getNumSuccessors(); I != E; ++I) {
2578 BasicBlock *Succ = OldTerm->getSuccessor(I);
2579 // Make sure only to keep exactly one copy of each edge.
2580 if (Succ == KeepEdge1)
2581 KeepEdge1 = nullptr;
2582 else if (Succ == KeepEdge2)
2583 KeepEdge2 = nullptr;
2585 Succ->removePredecessor(OldTerm->getParent());
2588 IRBuilder<> Builder(OldTerm);
2589 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
2591 // Insert an appropriate new terminator.
2592 if (!KeepEdge1 && !KeepEdge2) {
2593 if (TrueBB == FalseBB)
2594 // We were only looking for one successor, and it was present.
2595 // Create an unconditional branch to it.
2596 Builder.CreateBr(TrueBB);
2598 // We found both of the successors we were looking for.
2599 // Create a conditional branch sharing the condition of the select.
2600 BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
2601 if (TrueWeight != FalseWeight)
2602 NewBI->setMetadata(LLVMContext::MD_prof,
2603 MDBuilder(OldTerm->getContext()).
2604 createBranchWeights(TrueWeight, FalseWeight));
2606 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
2607 // Neither of the selected blocks were successors, so this
2608 // terminator must be unreachable.
2609 new UnreachableInst(OldTerm->getContext(), OldTerm);
2611 // One of the selected values was a successor, but the other wasn't.
2612 // Insert an unconditional branch to the one that was found;
2613 // the edge to the one that wasn't must be unreachable.
2615 // Only TrueBB was found.
2616 Builder.CreateBr(TrueBB);
2618 // Only FalseBB was found.
2619 Builder.CreateBr(FalseBB);
2622 EraseTerminatorInstAndDCECond(OldTerm);
2626 // SimplifySwitchOnSelect - Replaces
2627 // (switch (select cond, X, Y)) on constant X, Y
2628 // with a branch - conditional if X and Y lead to distinct BBs,
2629 // unconditional otherwise.
2630 static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
2631 // Check for constant integer values in the select.
2632 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
2633 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
2634 if (!TrueVal || !FalseVal)
2637 // Find the relevant condition and destinations.
2638 Value *Condition = Select->getCondition();
2639 BasicBlock *TrueBB = SI->findCaseValue(TrueVal).getCaseSuccessor();
2640 BasicBlock *FalseBB = SI->findCaseValue(FalseVal).getCaseSuccessor();
2642 // Get weight for TrueBB and FalseBB.
2643 uint32_t TrueWeight = 0, FalseWeight = 0;
2644 SmallVector<uint64_t, 8> Weights;
2645 bool HasWeights = HasBranchWeights(SI);
2647 GetBranchWeights(SI, Weights);
2648 if (Weights.size() == 1 + SI->getNumCases()) {
2649 TrueWeight = (uint32_t)Weights[SI->findCaseValue(TrueVal).
2650 getSuccessorIndex()];
2651 FalseWeight = (uint32_t)Weights[SI->findCaseValue(FalseVal).
2652 getSuccessorIndex()];
2656 // Perform the actual simplification.
2657 return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB,
2658 TrueWeight, FalseWeight);
2661 // SimplifyIndirectBrOnSelect - Replaces
2662 // (indirectbr (select cond, blockaddress(@fn, BlockA),
2663 // blockaddress(@fn, BlockB)))
2665 // (br cond, BlockA, BlockB).
2666 static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
2667 // Check that both operands of the select are block addresses.
2668 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
2669 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
2673 // Extract the actual blocks.
2674 BasicBlock *TrueBB = TBA->getBasicBlock();
2675 BasicBlock *FalseBB = FBA->getBasicBlock();
2677 // Perform the actual simplification.
2678 return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB,
2682 /// TryToSimplifyUncondBranchWithICmpInIt - This is called when we find an icmp
2683 /// instruction (a seteq/setne with a constant) as the only instruction in a
2684 /// block that ends with an uncond branch. We are looking for a very specific
2685 /// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
2686 /// this case, we merge the first two "or's of icmp" into a switch, but then the
2687 /// default value goes to an uncond block with a seteq in it, we get something
2690 /// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
2692 /// %tmp = icmp eq i8 %A, 92
2695 /// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
2697 /// We prefer to split the edge to 'end' so that there is a true/false entry to
2698 /// the PHI, merging the third icmp into the switch.
2699 static bool TryToSimplifyUncondBranchWithICmpInIt(
2700 ICmpInst *ICI, IRBuilder<> &Builder, const TargetTransformInfo &TTI,
2701 unsigned BonusInstThreshold, const DataLayout *DL, AssumptionCache *AC) {
2702 BasicBlock *BB = ICI->getParent();
2704 // If the block has any PHIs in it or the icmp has multiple uses, it is too
2706 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) return false;
2708 Value *V = ICI->getOperand(0);
2709 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
2711 // The pattern we're looking for is where our only predecessor is a switch on
2712 // 'V' and this block is the default case for the switch. In this case we can
2713 // fold the compared value into the switch to simplify things.
2714 BasicBlock *Pred = BB->getSinglePredecessor();
2715 if (!Pred || !isa<SwitchInst>(Pred->getTerminator())) return false;
2717 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
2718 if (SI->getCondition() != V)
2721 // If BB is reachable on a non-default case, then we simply know the value of
2722 // V in this block. Substitute it and constant fold the icmp instruction
2724 if (SI->getDefaultDest() != BB) {
2725 ConstantInt *VVal = SI->findCaseDest(BB);
2726 assert(VVal && "Should have a unique destination value");
2727 ICI->setOperand(0, VVal);
2729 if (Value *V = SimplifyInstruction(ICI, DL)) {
2730 ICI->replaceAllUsesWith(V);
2731 ICI->eraseFromParent();
2733 // BB is now empty, so it is likely to simplify away.
2734 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
2737 // Ok, the block is reachable from the default dest. If the constant we're
2738 // comparing exists in one of the other edges, then we can constant fold ICI
2740 if (SI->findCaseValue(Cst) != SI->case_default()) {
2742 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
2743 V = ConstantInt::getFalse(BB->getContext());
2745 V = ConstantInt::getTrue(BB->getContext());
2747 ICI->replaceAllUsesWith(V);
2748 ICI->eraseFromParent();
2749 // BB is now empty, so it is likely to simplify away.
2750 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
2753 // The use of the icmp has to be in the 'end' block, by the only PHI node in
2755 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
2756 PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
2757 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
2758 isa<PHINode>(++BasicBlock::iterator(PHIUse)))
2761 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
2763 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
2764 Constant *NewCst = ConstantInt::getFalse(BB->getContext());
2766 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
2767 std::swap(DefaultCst, NewCst);
2769 // Replace ICI (which is used by the PHI for the default value) with true or
2770 // false depending on if it is EQ or NE.
2771 ICI->replaceAllUsesWith(DefaultCst);
2772 ICI->eraseFromParent();
2774 // Okay, the switch goes to this block on a default value. Add an edge from
2775 // the switch to the merge point on the compared value.
2776 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "switch.edge",
2777 BB->getParent(), BB);
2778 SmallVector<uint64_t, 8> Weights;
2779 bool HasWeights = HasBranchWeights(SI);
2781 GetBranchWeights(SI, Weights);
2782 if (Weights.size() == 1 + SI->getNumCases()) {
2783 // Split weight for default case to case for "Cst".
2784 Weights[0] = (Weights[0]+1) >> 1;
2785 Weights.push_back(Weights[0]);
2787 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
2788 SI->setMetadata(LLVMContext::MD_prof,
2789 MDBuilder(SI->getContext()).
2790 createBranchWeights(MDWeights));
2793 SI->addCase(Cst, NewBB);
2795 // NewBB branches to the phi block, add the uncond branch and the phi entry.
2796 Builder.SetInsertPoint(NewBB);
2797 Builder.SetCurrentDebugLocation(SI->getDebugLoc());
2798 Builder.CreateBr(SuccBlock);
2799 PHIUse->addIncoming(NewCst, NewBB);
2803 /// SimplifyBranchOnICmpChain - The specified branch is a conditional branch.
2804 /// Check to see if it is branching on an or/and chain of icmp instructions, and
2805 /// fold it into a switch instruction if so.
2806 static bool SimplifyBranchOnICmpChain(BranchInst *BI, const DataLayout *DL,
2807 IRBuilder<> &Builder) {
2808 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
2809 if (!Cond) return false;
2811 // Change br (X == 0 | X == 1), T, F into a switch instruction.
2812 // If this is a bunch of seteq's or'd together, or if it's a bunch of
2813 // 'setne's and'ed together, collect them.
2815 // Try to gather values from a chain of and/or to be turned into a switch
2816 ConstantComparesGatherer ConstantCompare(Cond, DL);
2817 // Unpack the result
2818 SmallVectorImpl<ConstantInt*> &Values = ConstantCompare.Vals;
2819 Value *CompVal = ConstantCompare.CompValue;
2820 unsigned UsedICmps = ConstantCompare.UsedICmps;
2821 Value *ExtraCase = ConstantCompare.Extra;
2823 // If we didn't have a multiply compared value, fail.
2824 if (!CompVal) return false;
2826 // Avoid turning single icmps into a switch.
2830 bool TrueWhenEqual = (Cond->getOpcode() == Instruction::Or);
2832 // There might be duplicate constants in the list, which the switch
2833 // instruction can't handle, remove them now.
2834 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
2835 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
2837 // If Extra was used, we require at least two switch values to do the
2838 // transformation. A switch with one value is just an cond branch.
2839 if (ExtraCase && Values.size() < 2) return false;
2841 // TODO: Preserve branch weight metadata, similarly to how
2842 // FoldValueComparisonIntoPredecessors preserves it.
2844 // Figure out which block is which destination.
2845 BasicBlock *DefaultBB = BI->getSuccessor(1);
2846 BasicBlock *EdgeBB = BI->getSuccessor(0);
2847 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
2849 BasicBlock *BB = BI->getParent();
2851 DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
2852 << " cases into SWITCH. BB is:\n" << *BB);
2854 // If there are any extra values that couldn't be folded into the switch
2855 // then we evaluate them with an explicit branch first. Split the block
2856 // right before the condbr to handle it.
2858 BasicBlock *NewBB = BB->splitBasicBlock(BI, "switch.early.test");
2859 // Remove the uncond branch added to the old block.
2860 TerminatorInst *OldTI = BB->getTerminator();
2861 Builder.SetInsertPoint(OldTI);
2864 Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
2866 Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
2868 OldTI->eraseFromParent();
2870 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
2871 // for the edge we just added.
2872 AddPredecessorToBlock(EdgeBB, BB, NewBB);
2874 DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
2875 << "\nEXTRABB = " << *BB);
2879 Builder.SetInsertPoint(BI);
2880 // Convert pointer to int before we switch.
2881 if (CompVal->getType()->isPointerTy()) {
2882 assert(DL && "Cannot switch on pointer without DataLayout");
2883 CompVal = Builder.CreatePtrToInt(CompVal,
2884 DL->getIntPtrType(CompVal->getType()),
2888 // Create the new switch instruction now.
2889 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
2891 // Add all of the 'cases' to the switch instruction.
2892 for (unsigned i = 0, e = Values.size(); i != e; ++i)
2893 New->addCase(Values[i], EdgeBB);
2895 // We added edges from PI to the EdgeBB. As such, if there were any
2896 // PHI nodes in EdgeBB, they need entries to be added corresponding to
2897 // the number of edges added.
2898 for (BasicBlock::iterator BBI = EdgeBB->begin();
2899 isa<PHINode>(BBI); ++BBI) {
2900 PHINode *PN = cast<PHINode>(BBI);
2901 Value *InVal = PN->getIncomingValueForBlock(BB);
2902 for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
2903 PN->addIncoming(InVal, BB);
2906 // Erase the old branch instruction.
2907 EraseTerminatorInstAndDCECond(BI);
2909 DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
2913 bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
2914 // If this is a trivial landing pad that just continues unwinding the caught
2915 // exception then zap the landing pad, turning its invokes into calls.
2916 BasicBlock *BB = RI->getParent();
2917 LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI());
2918 if (RI->getValue() != LPInst)
2919 // Not a landing pad, or the resume is not unwinding the exception that
2920 // caused control to branch here.
2923 // Check that there are no other instructions except for debug intrinsics.
2924 BasicBlock::iterator I = LPInst, E = RI;
2926 if (!isa<DbgInfoIntrinsic>(I))
2929 // Turn all invokes that unwind here into calls and delete the basic block.
2930 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
2931 InvokeInst *II = cast<InvokeInst>((*PI++)->getTerminator());
2932 SmallVector<Value*, 8> Args(II->op_begin(), II->op_end() - 3);
2933 // Insert a call instruction before the invoke.
2934 CallInst *Call = CallInst::Create(II->getCalledValue(), Args, "", II);
2936 Call->setCallingConv(II->getCallingConv());
2937 Call->setAttributes(II->getAttributes());
2938 Call->setDebugLoc(II->getDebugLoc());
2940 // Anything that used the value produced by the invoke instruction now uses
2941 // the value produced by the call instruction. Note that we do this even
2942 // for void functions and calls with no uses so that the callgraph edge is
2944 II->replaceAllUsesWith(Call);
2945 BB->removePredecessor(II->getParent());
2947 // Insert a branch to the normal destination right before the invoke.
2948 BranchInst::Create(II->getNormalDest(), II);
2950 // Finally, delete the invoke instruction!
2951 II->eraseFromParent();
2954 // The landingpad is now unreachable. Zap it.
2955 BB->eraseFromParent();
2959 bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
2960 BasicBlock *BB = RI->getParent();
2961 if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
2963 // Find predecessors that end with branches.
2964 SmallVector<BasicBlock*, 8> UncondBranchPreds;
2965 SmallVector<BranchInst*, 8> CondBranchPreds;
2966 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2967 BasicBlock *P = *PI;
2968 TerminatorInst *PTI = P->getTerminator();
2969 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
2970 if (BI->isUnconditional())
2971 UncondBranchPreds.push_back(P);
2973 CondBranchPreds.push_back(BI);
2977 // If we found some, do the transformation!
2978 if (!UncondBranchPreds.empty() && DupRet) {
2979 while (!UncondBranchPreds.empty()) {
2980 BasicBlock *Pred = UncondBranchPreds.pop_back_val();
2981 DEBUG(dbgs() << "FOLDING: " << *BB
2982 << "INTO UNCOND BRANCH PRED: " << *Pred);
2983 (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
2986 // If we eliminated all predecessors of the block, delete the block now.
2988 // We know there are no successors, so just nuke the block.
2989 BB->eraseFromParent();
2994 // Check out all of the conditional branches going to this return
2995 // instruction. If any of them just select between returns, change the
2996 // branch itself into a select/return pair.
2997 while (!CondBranchPreds.empty()) {
2998 BranchInst *BI = CondBranchPreds.pop_back_val();
3000 // Check to see if the non-BB successor is also a return block.
3001 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
3002 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
3003 SimplifyCondBranchToTwoReturns(BI, Builder))
3009 bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
3010 BasicBlock *BB = UI->getParent();
3012 bool Changed = false;
3014 // If there are any instructions immediately before the unreachable that can
3015 // be removed, do so.
3016 while (UI != BB->begin()) {
3017 BasicBlock::iterator BBI = UI;
3019 // Do not delete instructions that can have side effects which might cause
3020 // the unreachable to not be reachable; specifically, calls and volatile
3021 // operations may have this effect.
3022 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break;
3024 if (BBI->mayHaveSideEffects()) {
3025 if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
3026 if (SI->isVolatile())
3028 } else if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
3029 if (LI->isVolatile())
3031 } else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
3032 if (RMWI->isVolatile())
3034 } else if (AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
3035 if (CXI->isVolatile())
3037 } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
3038 !isa<LandingPadInst>(BBI)) {
3041 // Note that deleting LandingPad's here is in fact okay, although it
3042 // involves a bit of subtle reasoning. If this inst is a LandingPad,
3043 // all the predecessors of this block will be the unwind edges of Invokes,
3044 // and we can therefore guarantee this block will be erased.
3047 // Delete this instruction (any uses are guaranteed to be dead)
3048 if (!BBI->use_empty())
3049 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
3050 BBI->eraseFromParent();
3054 // If the unreachable instruction is the first in the block, take a gander
3055 // at all of the predecessors of this instruction, and simplify them.
3056 if (&BB->front() != UI) return Changed;
3058 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
3059 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
3060 TerminatorInst *TI = Preds[i]->getTerminator();
3061 IRBuilder<> Builder(TI);
3062 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
3063 if (BI->isUnconditional()) {
3064 if (BI->getSuccessor(0) == BB) {
3065 new UnreachableInst(TI->getContext(), TI);
3066 TI->eraseFromParent();
3070 if (BI->getSuccessor(0) == BB) {
3071 Builder.CreateBr(BI->getSuccessor(1));
3072 EraseTerminatorInstAndDCECond(BI);
3073 } else if (BI->getSuccessor(1) == BB) {
3074 Builder.CreateBr(BI->getSuccessor(0));
3075 EraseTerminatorInstAndDCECond(BI);
3079 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
3080 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
3082 if (i.getCaseSuccessor() == BB) {
3083 BB->removePredecessor(SI->getParent());
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_empty(BB) &&
3112 BB != &BB->getParent()->getEntryBlock()) {
3113 // We know there are no successors, so just nuke the block.
3114 BB->eraseFromParent();
3121 static bool CasesAreContiguous(SmallVectorImpl<ConstantInt *> &Cases) {
3122 assert(Cases.size() >= 1);
3124 array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
3125 for (size_t I = 1, E = Cases.size(); I != E; ++I) {
3126 if (Cases[I - 1]->getValue() != Cases[I]->getValue() + 1)
3132 /// Turn a switch with two reachable destinations into an integer range
3133 /// comparison and branch.
3134 static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
3135 assert(SI->getNumCases() > 1 && "Degenerate switch?");
3138 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
3140 // Partition the cases into two sets with different destinations.
3141 BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr;
3142 BasicBlock *DestB = nullptr;
3143 SmallVector <ConstantInt *, 16> CasesA;
3144 SmallVector <ConstantInt *, 16> CasesB;
3146 for (SwitchInst::CaseIt I : SI->cases()) {
3147 BasicBlock *Dest = I.getCaseSuccessor();
3148 if (!DestA) DestA = Dest;
3149 if (Dest == DestA) {
3150 CasesA.push_back(I.getCaseValue());
3153 if (!DestB) DestB = Dest;
3154 if (Dest == DestB) {
3155 CasesB.push_back(I.getCaseValue());
3158 return false; // More than two destinations.
3161 assert(DestA && DestB && "Single-destination switch should have been folded.");
3162 assert(DestA != DestB);
3163 assert(DestB != SI->getDefaultDest());
3164 assert(!CasesB.empty() && "There must be non-default cases.");
3165 assert(!CasesA.empty() || HasDefault);
3167 // Figure out if one of the sets of cases form a contiguous range.
3168 SmallVectorImpl<ConstantInt *> *ContiguousCases = nullptr;
3169 BasicBlock *ContiguousDest = nullptr;
3170 BasicBlock *OtherDest = nullptr;
3171 if (!CasesA.empty() && CasesAreContiguous(CasesA)) {
3172 ContiguousCases = &CasesA;
3173 ContiguousDest = DestA;
3175 } else if (CasesAreContiguous(CasesB)) {
3176 ContiguousCases = &CasesB;
3177 ContiguousDest = DestB;
3182 // Start building the compare and branch.
3184 Constant *Offset = ConstantExpr::getNeg(ContiguousCases->back());
3185 Constant *NumCases = ConstantInt::get(Offset->getType(), ContiguousCases->size());
3187 Value *Sub = SI->getCondition();
3188 if (!Offset->isNullValue())
3189 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off");
3192 // If NumCases overflowed, then all possible values jump to the successor.
3193 if (NumCases->isNullValue() && !ContiguousCases->empty())
3194 Cmp = ConstantInt::getTrue(SI->getContext());
3196 Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
3197 BranchInst *NewBI = Builder.CreateCondBr(Cmp, ContiguousDest, OtherDest);
3199 // Update weight for the newly-created conditional branch.
3200 if (HasBranchWeights(SI)) {
3201 SmallVector<uint64_t, 8> Weights;
3202 GetBranchWeights(SI, Weights);
3203 if (Weights.size() == 1 + SI->getNumCases()) {
3204 uint64_t TrueWeight = 0;
3205 uint64_t FalseWeight = 0;
3206 for (size_t I = 0, E = Weights.size(); I != E; ++I) {
3207 if (SI->getSuccessor(I) == ContiguousDest)
3208 TrueWeight += Weights[I];
3210 FalseWeight += Weights[I];
3212 while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) {
3216 NewBI->setMetadata(LLVMContext::MD_prof,
3217 MDBuilder(SI->getContext()).createBranchWeights(
3218 (uint32_t)TrueWeight, (uint32_t)FalseWeight));
3222 // Prune obsolete incoming values off the successors' PHI nodes.
3223 for (auto BBI = ContiguousDest->begin(); isa<PHINode>(BBI); ++BBI) {
3224 unsigned PreviousEdges = ContiguousCases->size();
3225 if (ContiguousDest == SI->getDefaultDest()) ++PreviousEdges;
3226 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
3227 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
3229 for (auto BBI = OtherDest->begin(); isa<PHINode>(BBI); ++BBI) {
3230 unsigned PreviousEdges = SI->getNumCases() - ContiguousCases->size();
3231 if (OtherDest == SI->getDefaultDest()) ++PreviousEdges;
3232 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
3233 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
3237 SI->eraseFromParent();
3242 /// EliminateDeadSwitchCases - Compute masked bits for the condition of a switch
3243 /// and use it to remove dead cases.
3244 static bool EliminateDeadSwitchCases(SwitchInst *SI, const DataLayout *DL,
3245 AssumptionCache *AC) {
3246 Value *Cond = SI->getCondition();
3247 unsigned Bits = Cond->getType()->getIntegerBitWidth();
3248 APInt KnownZero(Bits, 0), KnownOne(Bits, 0);
3249 computeKnownBits(Cond, KnownZero, KnownOne, DL, 0, AC, SI);
3251 // Gather dead cases.
3252 SmallVector<ConstantInt*, 8> DeadCases;
3253 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
3254 if ((I.getCaseValue()->getValue() & KnownZero) != 0 ||
3255 (I.getCaseValue()->getValue() & KnownOne) != KnownOne) {
3256 DeadCases.push_back(I.getCaseValue());
3257 DEBUG(dbgs() << "SimplifyCFG: switch case '"
3258 << I.getCaseValue() << "' is dead.\n");
3262 SmallVector<uint64_t, 8> Weights;
3263 bool HasWeight = HasBranchWeights(SI);
3265 GetBranchWeights(SI, Weights);
3266 HasWeight = (Weights.size() == 1 + SI->getNumCases());
3269 // Remove dead cases from the switch.
3270 for (unsigned I = 0, E = DeadCases.size(); I != E; ++I) {
3271 SwitchInst::CaseIt Case = SI->findCaseValue(DeadCases[I]);
3272 assert(Case != SI->case_default() &&
3273 "Case was not found. Probably mistake in DeadCases forming.");
3275 std::swap(Weights[Case.getCaseIndex()+1], Weights.back());
3279 // Prune unused values from PHI nodes.
3280 Case.getCaseSuccessor()->removePredecessor(SI->getParent());
3281 SI->removeCase(Case);
3283 if (HasWeight && Weights.size() >= 2) {
3284 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
3285 SI->setMetadata(LLVMContext::MD_prof,
3286 MDBuilder(SI->getParent()->getContext()).
3287 createBranchWeights(MDWeights));
3290 return !DeadCases.empty();
3293 /// FindPHIForConditionForwarding - If BB would be eligible for simplification
3294 /// by TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
3295 /// by an unconditional branch), look at the phi node for BB in the successor
3296 /// block and see if the incoming value is equal to CaseValue. If so, return
3297 /// the phi node, and set PhiIndex to BB's index in the phi node.
3298 static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
3301 if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
3302 return nullptr; // BB must be empty to be a candidate for simplification.
3303 if (!BB->getSinglePredecessor())
3304 return nullptr; // BB must be dominated by the switch.
3306 BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
3307 if (!Branch || !Branch->isUnconditional())
3308 return nullptr; // Terminator must be unconditional branch.
3310 BasicBlock *Succ = Branch->getSuccessor(0);
3312 BasicBlock::iterator I = Succ->begin();
3313 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3314 int Idx = PHI->getBasicBlockIndex(BB);
3315 assert(Idx >= 0 && "PHI has no entry for predecessor?");
3317 Value *InValue = PHI->getIncomingValue(Idx);
3318 if (InValue != CaseValue) continue;
3327 /// ForwardSwitchConditionToPHI - Try to forward the condition of a switch
3328 /// instruction to a phi node dominated by the switch, if that would mean that
3329 /// some of the destination blocks of the switch can be folded away.
3330 /// Returns true if a change is made.
3331 static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
3332 typedef DenseMap<PHINode*, SmallVector<int,4> > ForwardingNodesMap;
3333 ForwardingNodesMap ForwardingNodes;
3335 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
3336 ConstantInt *CaseValue = I.getCaseValue();
3337 BasicBlock *CaseDest = I.getCaseSuccessor();
3340 PHINode *PHI = FindPHIForConditionForwarding(CaseValue, CaseDest,
3344 ForwardingNodes[PHI].push_back(PhiIndex);
3347 bool Changed = false;
3349 for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(),
3350 E = ForwardingNodes.end(); I != E; ++I) {
3351 PHINode *Phi = I->first;
3352 SmallVectorImpl<int> &Indexes = I->second;
3354 if (Indexes.size() < 2) continue;
3356 for (size_t I = 0, E = Indexes.size(); I != E; ++I)
3357 Phi->setIncomingValue(Indexes[I], SI->getCondition());
3364 /// ValidLookupTableConstant - Return true if the backend will be able to handle
3365 /// initializing an array of constants like C.
3366 static bool ValidLookupTableConstant(Constant *C) {
3367 if (C->isThreadDependent())
3369 if (C->isDLLImportDependent())
3372 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
3373 return CE->isGEPWithNoNotionalOverIndexing();
3375 return isa<ConstantFP>(C) ||
3376 isa<ConstantInt>(C) ||
3377 isa<ConstantPointerNull>(C) ||
3378 isa<GlobalValue>(C) ||
3382 /// LookupConstant - If V is a Constant, return it. Otherwise, try to look up
3383 /// its constant value in ConstantPool, returning 0 if it's not there.
3384 static Constant *LookupConstant(Value *V,
3385 const SmallDenseMap<Value*, Constant*>& ConstantPool) {
3386 if (Constant *C = dyn_cast<Constant>(V))
3388 return ConstantPool.lookup(V);
3391 /// ConstantFold - Try to fold instruction I into a constant. This works for
3392 /// simple instructions such as binary operations where both operands are
3393 /// constant or can be replaced by constants from the ConstantPool. Returns the
3394 /// resulting constant on success, 0 otherwise.
3396 ConstantFold(Instruction *I,
3397 const SmallDenseMap<Value *, Constant *> &ConstantPool,
3398 const DataLayout *DL) {
3399 if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
3400 Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
3403 if (A->isAllOnesValue())
3404 return LookupConstant(Select->getTrueValue(), ConstantPool);
3405 if (A->isNullValue())
3406 return LookupConstant(Select->getFalseValue(), ConstantPool);
3410 SmallVector<Constant *, 4> COps;
3411 for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
3412 if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
3418 if (CmpInst *Cmp = dyn_cast<CmpInst>(I))
3419 return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0],
3422 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), COps, DL);
3425 /// GetCaseResults - Try to determine the resulting constant values in phi nodes
3426 /// at the common destination basic block, *CommonDest, for one of the case
3427 /// destionations CaseDest corresponding to value CaseVal (0 for the default
3428 /// case), of a switch instruction SI.
3430 GetCaseResults(SwitchInst *SI,
3431 ConstantInt *CaseVal,
3432 BasicBlock *CaseDest,
3433 BasicBlock **CommonDest,
3434 SmallVectorImpl<std::pair<PHINode *, Constant *> > &Res,
3435 const DataLayout *DL) {
3436 // The block from which we enter the common destination.
3437 BasicBlock *Pred = SI->getParent();
3439 // If CaseDest is empty except for some side-effect free instructions through
3440 // which we can constant-propagate the CaseVal, continue to its successor.
3441 SmallDenseMap<Value*, Constant*> ConstantPool;
3442 ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
3443 for (BasicBlock::iterator I = CaseDest->begin(), E = CaseDest->end(); I != E;
3445 if (TerminatorInst *T = dyn_cast<TerminatorInst>(I)) {
3446 // If the terminator is a simple branch, continue to the next block.
3447 if (T->getNumSuccessors() != 1)
3450 CaseDest = T->getSuccessor(0);
3451 } else if (isa<DbgInfoIntrinsic>(I)) {
3452 // Skip debug intrinsic.
3454 } else if (Constant *C = ConstantFold(I, ConstantPool, DL)) {
3455 // Instruction is side-effect free and constant.
3457 // If the instruction has uses outside this block or a phi node slot for
3458 // the block, it is not safe to bypass the instruction since it would then
3459 // no longer dominate all its uses.
3460 for (auto &Use : I->uses()) {
3461 User *User = Use.getUser();
3462 if (Instruction *I = dyn_cast<Instruction>(User))
3463 if (I->getParent() == CaseDest)
3465 if (PHINode *Phi = dyn_cast<PHINode>(User))
3466 if (Phi->getIncomingBlock(Use) == CaseDest)
3471 ConstantPool.insert(std::make_pair(I, C));
3477 // If we did not have a CommonDest before, use the current one.
3479 *CommonDest = CaseDest;
3480 // If the destination isn't the common one, abort.
3481 if (CaseDest != *CommonDest)
3484 // Get the values for this case from phi nodes in the destination block.
3485 BasicBlock::iterator I = (*CommonDest)->begin();
3486 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3487 int Idx = PHI->getBasicBlockIndex(Pred);
3491 Constant *ConstVal = LookupConstant(PHI->getIncomingValue(Idx),
3496 // Be conservative about which kinds of constants we support.
3497 if (!ValidLookupTableConstant(ConstVal))
3500 Res.push_back(std::make_pair(PHI, ConstVal));
3503 return Res.size() > 0;
3506 // MapCaseToResult - Helper function used to
3507 // add CaseVal to the list of cases that generate Result.
3508 static void MapCaseToResult(ConstantInt *CaseVal,
3509 SwitchCaseResultVectorTy &UniqueResults,
3511 for (auto &I : UniqueResults) {
3512 if (I.first == Result) {
3513 I.second.push_back(CaseVal);
3517 UniqueResults.push_back(std::make_pair(Result,
3518 SmallVector<ConstantInt*, 4>(1, CaseVal)));
3521 // InitializeUniqueCases - Helper function that initializes a map containing
3522 // results for the PHI node of the common destination block for a switch
3523 // instruction. Returns false if multiple PHI nodes have been found or if
3524 // there is not a common destination block for the switch.
3525 static bool InitializeUniqueCases(
3526 SwitchInst *SI, const DataLayout *DL, PHINode *&PHI,
3527 BasicBlock *&CommonDest,
3528 SwitchCaseResultVectorTy &UniqueResults,
3529 Constant *&DefaultResult) {
3530 for (auto &I : SI->cases()) {
3531 ConstantInt *CaseVal = I.getCaseValue();
3533 // Resulting value at phi nodes for this case value.
3534 SwitchCaseResultsTy Results;
3535 if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results,
3539 // Only one value per case is permitted
3540 if (Results.size() > 1)
3542 MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second);
3544 // Check the PHI consistency.
3546 PHI = Results[0].first;
3547 else if (PHI != Results[0].first)
3550 // Find the default result value.
3551 SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults;
3552 BasicBlock *DefaultDest = SI->getDefaultDest();
3553 GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults,
3555 // If the default value is not found abort unless the default destination
3558 DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr;
3559 if ((!DefaultResult &&
3560 !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg())))
3566 // ConvertTwoCaseSwitch - Helper function that checks if it is possible to
3567 // transform a switch with only two cases (or two cases + default)
3568 // that produces a result into a value select.
3571 // case 10: %0 = icmp eq i32 %a, 10
3572 // return 10; %1 = select i1 %0, i32 10, i32 4
3573 // case 20: ----> %2 = icmp eq i32 %a, 20
3574 // return 2; %3 = select i1 %2, i32 2, i32 %1
3579 ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector,
3580 Constant *DefaultResult, Value *Condition,
3581 IRBuilder<> &Builder) {
3582 assert(ResultVector.size() == 2 &&
3583 "We should have exactly two unique results at this point");
3584 // If we are selecting between only two cases transform into a simple
3585 // select or a two-way select if default is possible.
3586 if (ResultVector[0].second.size() == 1 &&
3587 ResultVector[1].second.size() == 1) {
3588 ConstantInt *const FirstCase = ResultVector[0].second[0];
3589 ConstantInt *const SecondCase = ResultVector[1].second[0];
3591 bool DefaultCanTrigger = DefaultResult;
3592 Value *SelectValue = ResultVector[1].first;
3593 if (DefaultCanTrigger) {
3594 Value *const ValueCompare =
3595 Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp");
3596 SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first,
3597 DefaultResult, "switch.select");
3599 Value *const ValueCompare =
3600 Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp");
3601 return Builder.CreateSelect(ValueCompare, ResultVector[0].first, SelectValue,
3608 // RemoveSwitchAfterSelectConversion - Helper function to cleanup a switch
3609 // instruction that has been converted into a select, fixing up PHI nodes and
3611 static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI,
3613 IRBuilder<> &Builder) {
3614 BasicBlock *SelectBB = SI->getParent();
3615 while (PHI->getBasicBlockIndex(SelectBB) >= 0)
3616 PHI->removeIncomingValue(SelectBB);
3617 PHI->addIncoming(SelectValue, SelectBB);
3619 Builder.CreateBr(PHI->getParent());
3621 // Remove the switch.
3622 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
3623 BasicBlock *Succ = SI->getSuccessor(i);
3625 if (Succ == PHI->getParent())
3627 Succ->removePredecessor(SelectBB);
3629 SI->eraseFromParent();
3632 /// SwitchToSelect - If the switch is only used to initialize one or more
3633 /// phi nodes in a common successor block with only two different
3634 /// constant values, replace the switch with select.
3635 static bool SwitchToSelect(SwitchInst *SI, IRBuilder<> &Builder,
3636 const DataLayout *DL, AssumptionCache *AC) {
3637 Value *const Cond = SI->getCondition();
3638 PHINode *PHI = nullptr;
3639 BasicBlock *CommonDest = nullptr;
3640 Constant *DefaultResult;
3641 SwitchCaseResultVectorTy UniqueResults;
3642 // Collect all the cases that will deliver the same value from the switch.
3643 if (!InitializeUniqueCases(SI, DL, PHI, CommonDest, UniqueResults,
3646 // Selects choose between maximum two values.
3647 if (UniqueResults.size() != 2)
3649 assert(PHI != nullptr && "PHI for value select not found");
3651 Builder.SetInsertPoint(SI);
3652 Value *SelectValue = ConvertTwoCaseSwitch(
3654 DefaultResult, Cond, Builder);
3656 RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder);
3659 // The switch couldn't be converted into a select.
3664 /// SwitchLookupTable - This class represents a lookup table that can be used
3665 /// to replace a switch.
3666 class SwitchLookupTable {
3668 /// SwitchLookupTable - Create a lookup table to use as a switch replacement
3669 /// with the contents of Values, using DefaultValue to fill any holes in the
3671 SwitchLookupTable(Module &M,
3673 ConstantInt *Offset,
3674 const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values,
3675 Constant *DefaultValue,
3676 const DataLayout *DL);
3678 /// BuildLookup - Build instructions with Builder to retrieve the value at
3679 /// the position given by Index in the lookup table.
3680 Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
3682 /// WouldFitInRegister - Return true if a table with TableSize elements of
3683 /// type ElementType would fit in a target-legal register.
3684 static bool WouldFitInRegister(const DataLayout *DL,
3686 const Type *ElementType);
3689 // Depending on the contents of the table, it can be represented in
3692 // For tables where each element contains the same value, we just have to
3693 // store that single value and return it for each lookup.
3696 // For tables where there is a linear relationship between table index
3697 // and values. We calculate the result with a simple multiplication
3698 // and addition instead of a table lookup.
3701 // For small tables with integer elements, we can pack them into a bitmap
3702 // that fits into a target-legal register. Values are retrieved by
3703 // shift and mask operations.
3706 // The table is stored as an array of values. Values are retrieved by load
3707 // instructions from the table.
3711 // For SingleValueKind, this is the single value.
3712 Constant *SingleValue;
3714 // For BitMapKind, this is the bitmap.
3715 ConstantInt *BitMap;
3716 IntegerType *BitMapElementTy;
3718 // For LinearMapKind, these are the constants used to derive the value.
3719 ConstantInt *LinearOffset;
3720 ConstantInt *LinearMultiplier;
3722 // For ArrayKind, this is the array.
3723 GlobalVariable *Array;
3727 SwitchLookupTable::SwitchLookupTable(Module &M,
3729 ConstantInt *Offset,
3730 const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values,
3731 Constant *DefaultValue,
3732 const DataLayout *DL)
3733 : SingleValue(nullptr), BitMap(nullptr), BitMapElementTy(nullptr),
3734 LinearOffset(nullptr), LinearMultiplier(nullptr), Array(nullptr) {
3735 assert(Values.size() && "Can't build lookup table without values!");
3736 assert(TableSize >= Values.size() && "Can't fit values in table!");
3738 // If all values in the table are equal, this is that value.
3739 SingleValue = Values.begin()->second;
3741 Type *ValueType = Values.begin()->second->getType();
3743 // Build up the table contents.
3744 SmallVector<Constant*, 64> TableContents(TableSize);
3745 for (size_t I = 0, E = Values.size(); I != E; ++I) {
3746 ConstantInt *CaseVal = Values[I].first;
3747 Constant *CaseRes = Values[I].second;
3748 assert(CaseRes->getType() == ValueType);
3750 uint64_t Idx = (CaseVal->getValue() - Offset->getValue())
3752 TableContents[Idx] = CaseRes;
3754 if (CaseRes != SingleValue)
3755 SingleValue = nullptr;
3758 // Fill in any holes in the table with the default result.
3759 if (Values.size() < TableSize) {
3760 assert(DefaultValue &&
3761 "Need a default value to fill the lookup table holes.");
3762 assert(DefaultValue->getType() == ValueType);
3763 for (uint64_t I = 0; I < TableSize; ++I) {
3764 if (!TableContents[I])
3765 TableContents[I] = DefaultValue;
3768 if (DefaultValue != SingleValue)
3769 SingleValue = nullptr;
3772 // If each element in the table contains the same value, we only need to store
3773 // that single value.
3775 Kind = SingleValueKind;
3779 // Check if we can derive the value with a linear transformation from the
3781 if (isa<IntegerType>(ValueType)) {
3782 bool LinearMappingPossible = true;
3785 assert(TableSize >= 2 && "Should be a SingleValue table.");
3786 // Check if there is the same distance between two consecutive values.
3787 for (uint64_t I = 0; I < TableSize; ++I) {
3788 ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]);
3790 // This is an undef. We could deal with it, but undefs in lookup tables
3791 // are very seldom. It's probably not worth the additional complexity.
3792 LinearMappingPossible = false;
3795 APInt Val = ConstVal->getValue();
3797 APInt Dist = Val - PrevVal;
3800 } else if (Dist != DistToPrev) {
3801 LinearMappingPossible = false;
3807 if (LinearMappingPossible) {
3808 LinearOffset = cast<ConstantInt>(TableContents[0]);
3809 LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev);
3810 Kind = LinearMapKind;
3816 // If the type is integer and the table fits in a register, build a bitmap.
3817 if (WouldFitInRegister(DL, TableSize, ValueType)) {
3818 IntegerType *IT = cast<IntegerType>(ValueType);
3819 APInt TableInt(TableSize * IT->getBitWidth(), 0);
3820 for (uint64_t I = TableSize; I > 0; --I) {
3821 TableInt <<= IT->getBitWidth();
3822 // Insert values into the bitmap. Undef values are set to zero.
3823 if (!isa<UndefValue>(TableContents[I - 1])) {
3824 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
3825 TableInt |= Val->getValue().zext(TableInt.getBitWidth());
3828 BitMap = ConstantInt::get(M.getContext(), TableInt);
3829 BitMapElementTy = IT;
3835 // Store the table in an array.
3836 ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
3837 Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
3839 Array = new GlobalVariable(M, ArrayTy, /*constant=*/ true,
3840 GlobalVariable::PrivateLinkage,
3843 Array->setUnnamedAddr(true);
3847 Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
3849 case SingleValueKind:
3851 case LinearMapKind: {
3852 // Derive the result value from the input value.
3853 Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(),
3854 false, "switch.idx.cast");
3855 if (!LinearMultiplier->isOne())
3856 Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult");
3857 if (!LinearOffset->isZero())
3858 Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset");
3862 // Type of the bitmap (e.g. i59).
3863 IntegerType *MapTy = BitMap->getType();
3865 // Cast Index to the same type as the bitmap.
3866 // Note: The Index is <= the number of elements in the table, so
3867 // truncating it to the width of the bitmask is safe.
3868 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
3870 // Multiply the shift amount by the element width.
3871 ShiftAmt = Builder.CreateMul(ShiftAmt,
3872 ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
3876 Value *DownShifted = Builder.CreateLShr(BitMap, ShiftAmt,
3877 "switch.downshift");
3879 return Builder.CreateTrunc(DownShifted, BitMapElementTy,
3883 // Make sure the table index will not overflow when treated as signed.
3884 IntegerType *IT = cast<IntegerType>(Index->getType());
3885 uint64_t TableSize = Array->getInitializer()->getType()
3886 ->getArrayNumElements();
3887 if (TableSize > (1ULL << (IT->getBitWidth() - 1)))
3888 Index = Builder.CreateZExt(Index,
3889 IntegerType::get(IT->getContext(),
3890 IT->getBitWidth() + 1),
3891 "switch.tableidx.zext");
3893 Value *GEPIndices[] = { Builder.getInt32(0), Index };
3894 Value *GEP = Builder.CreateInBoundsGEP(Array, GEPIndices,
3896 return Builder.CreateLoad(GEP, "switch.load");
3899 llvm_unreachable("Unknown lookup table kind!");
3902 bool SwitchLookupTable::WouldFitInRegister(const DataLayout *DL,
3904 const Type *ElementType) {
3907 const IntegerType *IT = dyn_cast<IntegerType>(ElementType);
3910 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
3911 // are <= 15, we could try to narrow the type.
3913 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
3914 if (TableSize >= UINT_MAX/IT->getBitWidth())
3916 return DL->fitsInLegalInteger(TableSize * IT->getBitWidth());
3919 /// ShouldBuildLookupTable - Determine whether a lookup table should be built
3920 /// for this switch, based on the number of cases, size of the table and the
3921 /// types of the results.
3922 static bool ShouldBuildLookupTable(SwitchInst *SI,
3924 const TargetTransformInfo &TTI,
3925 const DataLayout *DL,
3926 const SmallDenseMap<PHINode*, Type*>& ResultTypes) {
3927 if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
3928 return false; // TableSize overflowed, or mul below might overflow.
3930 bool AllTablesFitInRegister = true;
3931 bool HasIllegalType = false;
3932 for (const auto &I : ResultTypes) {
3933 Type *Ty = I.second;
3935 // Saturate this flag to true.
3936 HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty);
3938 // Saturate this flag to false.
3939 AllTablesFitInRegister = AllTablesFitInRegister &&
3940 SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
3942 // If both flags saturate, we're done. NOTE: This *only* works with
3943 // saturating flags, and all flags have to saturate first due to the
3944 // non-deterministic behavior of iterating over a dense map.
3945 if (HasIllegalType && !AllTablesFitInRegister)
3949 // If each table would fit in a register, we should build it anyway.
3950 if (AllTablesFitInRegister)
3953 // Don't build a table that doesn't fit in-register if it has illegal types.
3957 // The table density should be at least 40%. This is the same criterion as for
3958 // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
3959 // FIXME: Find the best cut-off.
3960 return SI->getNumCases() * 10 >= TableSize * 4;
3963 /// Try to reuse the switch table index compare. Following pattern:
3965 /// if (idx < tablesize)
3966 /// r = table[idx]; // table does not contain default_value
3968 /// r = default_value;
3969 /// if (r != default_value)
3972 /// Is optimized to:
3974 /// cond = idx < tablesize;
3978 /// r = default_value;
3982 /// Jump threading will then eliminate the second if(cond).
3983 static void reuseTableCompare(User *PhiUser, BasicBlock *PhiBlock,
3984 BranchInst *RangeCheckBranch, Constant *DefaultValue,
3985 const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values) {
3987 ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser);
3991 // We require that the compare is in the same block as the phi so that jump
3992 // threading can do its work afterwards.
3993 if (CmpInst->getParent() != PhiBlock)
3996 Constant *CmpOp1 = dyn_cast<Constant>(CmpInst->getOperand(1));
4000 Value *RangeCmp = RangeCheckBranch->getCondition();
4001 Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType());
4002 Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType());
4004 // Check if the compare with the default value is constant true or false.
4005 Constant *DefaultConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
4006 DefaultValue, CmpOp1, true);
4007 if (DefaultConst != TrueConst && DefaultConst != FalseConst)
4010 // Check if the compare with the case values is distinct from the default
4012 for (auto ValuePair : Values) {
4013 Constant *CaseConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
4014 ValuePair.second, CmpOp1, true);
4015 if (!CaseConst || CaseConst == DefaultConst)
4017 assert((CaseConst == TrueConst || CaseConst == FalseConst) &&
4018 "Expect true or false as compare result.");
4021 // Check if the branch instruction dominates the phi node. It's a simple
4022 // dominance check, but sufficient for our needs.
4023 // Although this check is invariant in the calling loops, it's better to do it
4024 // at this late stage. Practically we do it at most once for a switch.
4025 BasicBlock *BranchBlock = RangeCheckBranch->getParent();
4026 for (auto PI = pred_begin(PhiBlock), E = pred_end(PhiBlock); PI != E; ++PI) {
4027 BasicBlock *Pred = *PI;
4028 if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock)
4032 if (DefaultConst == FalseConst) {
4033 // The compare yields the same result. We can replace it.
4034 CmpInst->replaceAllUsesWith(RangeCmp);
4035 ++NumTableCmpReuses;
4037 // The compare yields the same result, just inverted. We can replace it.
4038 Value *InvertedTableCmp = BinaryOperator::CreateXor(RangeCmp,
4039 ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp",
4041 CmpInst->replaceAllUsesWith(InvertedTableCmp);
4042 ++NumTableCmpReuses;
4046 /// SwitchToLookupTable - If the switch is only used to initialize one or more
4047 /// phi nodes in a common successor block with different constant values,
4048 /// replace the switch with lookup tables.
4049 static bool SwitchToLookupTable(SwitchInst *SI,
4050 IRBuilder<> &Builder,
4051 const TargetTransformInfo &TTI,
4052 const DataLayout* DL) {
4053 assert(SI->getNumCases() > 1 && "Degenerate switch?");
4055 // Only build lookup table when we have a target that supports it.
4056 if (!TTI.shouldBuildLookupTables())
4059 // FIXME: If the switch is too sparse for a lookup table, perhaps we could
4060 // split off a dense part and build a lookup table for that.
4062 // FIXME: This creates arrays of GEPs to constant strings, which means each
4063 // GEP needs a runtime relocation in PIC code. We should just build one big
4064 // string and lookup indices into that.
4066 // Ignore switches with less than three cases. Lookup tables will not make them
4067 // faster, so we don't analyze them.
4068 if (SI->getNumCases() < 3)
4071 // Figure out the corresponding result for each case value and phi node in the
4072 // common destination, as well as the the min and max case values.
4073 assert(SI->case_begin() != SI->case_end());
4074 SwitchInst::CaseIt CI = SI->case_begin();
4075 ConstantInt *MinCaseVal = CI.getCaseValue();
4076 ConstantInt *MaxCaseVal = CI.getCaseValue();
4078 BasicBlock *CommonDest = nullptr;
4079 typedef SmallVector<std::pair<ConstantInt*, Constant*>, 4> ResultListTy;
4080 SmallDenseMap<PHINode*, ResultListTy> ResultLists;
4081 SmallDenseMap<PHINode*, Constant*> DefaultResults;
4082 SmallDenseMap<PHINode*, Type*> ResultTypes;
4083 SmallVector<PHINode*, 4> PHIs;
4085 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
4086 ConstantInt *CaseVal = CI.getCaseValue();
4087 if (CaseVal->getValue().slt(MinCaseVal->getValue()))
4088 MinCaseVal = CaseVal;
4089 if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
4090 MaxCaseVal = CaseVal;
4092 // Resulting value at phi nodes for this case value.
4093 typedef SmallVector<std::pair<PHINode*, Constant*>, 4> ResultsTy;
4095 if (!GetCaseResults(SI, CaseVal, CI.getCaseSuccessor(), &CommonDest,
4099 // Append the result from this case to the list for each phi.
4100 for (const auto &I : Results) {
4101 PHINode *PHI = I.first;
4102 Constant *Value = I.second;
4103 if (!ResultLists.count(PHI))
4104 PHIs.push_back(PHI);
4105 ResultLists[PHI].push_back(std::make_pair(CaseVal, Value));
4109 // Keep track of the result types.
4110 for (PHINode *PHI : PHIs) {
4111 ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
4114 uint64_t NumResults = ResultLists[PHIs[0]].size();
4115 APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
4116 uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
4117 bool TableHasHoles = (NumResults < TableSize);
4119 // If the table has holes, we need a constant result for the default case
4120 // or a bitmask that fits in a register.
4121 SmallVector<std::pair<PHINode*, Constant*>, 4> DefaultResultsList;
4122 bool HasDefaultResults = GetCaseResults(SI, nullptr, SI->getDefaultDest(),
4123 &CommonDest, DefaultResultsList, DL);
4125 bool NeedMask = (TableHasHoles && !HasDefaultResults);
4127 // As an extra penalty for the validity test we require more cases.
4128 if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
4130 if (!(DL && DL->fitsInLegalInteger(TableSize)))
4134 for (const auto &I : DefaultResultsList) {
4135 PHINode *PHI = I.first;
4136 Constant *Result = I.second;
4137 DefaultResults[PHI] = Result;
4140 if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
4143 // Create the BB that does the lookups.
4144 Module &Mod = *CommonDest->getParent()->getParent();
4145 BasicBlock *LookupBB = BasicBlock::Create(Mod.getContext(),
4147 CommonDest->getParent(),
4150 // Compute the table index value.
4151 Builder.SetInsertPoint(SI);
4152 Value *TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal,
4155 // Compute the maximum table size representable by the integer type we are
4157 unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
4158 uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
4159 assert(MaxTableSize >= TableSize &&
4160 "It is impossible for a switch to have more entries than the max "
4161 "representable value of its input integer type's size.");
4163 // If the default destination is unreachable, or if the lookup table covers
4164 // all values of the conditional variable, branch directly to the lookup table
4165 // BB. Otherwise, check that the condition is within the case range.
4166 const bool DefaultIsReachable =
4167 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
4168 const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize);
4169 BranchInst *RangeCheckBranch = nullptr;
4171 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
4172 Builder.CreateBr(LookupBB);
4173 // We cached PHINodes in PHIs, to avoid accessing deleted PHINodes later,
4174 // do not delete PHINodes here.
4175 SI->getDefaultDest()->removePredecessor(SI->getParent(),
4176 /*DontDeleteUselessPHIs=*/true);
4178 Value *Cmp = Builder.CreateICmpULT(TableIndex, ConstantInt::get(
4179 MinCaseVal->getType(), TableSize));
4180 RangeCheckBranch = Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
4183 // Populate the BB that does the lookups.
4184 Builder.SetInsertPoint(LookupBB);
4187 // Before doing the lookup we do the hole check.
4188 // The LookupBB is therefore re-purposed to do the hole check
4189 // and we create a new LookupBB.
4190 BasicBlock *MaskBB = LookupBB;
4191 MaskBB->setName("switch.hole_check");
4192 LookupBB = BasicBlock::Create(Mod.getContext(),
4194 CommonDest->getParent(),
4197 // Make the mask's bitwidth at least 8bit and a power-of-2 to avoid
4198 // unnecessary illegal types.
4199 uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL));
4200 APInt MaskInt(TableSizePowOf2, 0);
4201 APInt One(TableSizePowOf2, 1);
4202 // Build bitmask; fill in a 1 bit for every case.
4203 const ResultListTy &ResultList = ResultLists[PHIs[0]];
4204 for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
4205 uint64_t Idx = (ResultList[I].first->getValue() -
4206 MinCaseVal->getValue()).getLimitedValue();
4207 MaskInt |= One << Idx;
4209 ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
4211 // Get the TableIndex'th bit of the bitmask.
4212 // If this bit is 0 (meaning hole) jump to the default destination,
4213 // else continue with table lookup.
4214 IntegerType *MapTy = TableMask->getType();
4215 Value *MaskIndex = Builder.CreateZExtOrTrunc(TableIndex, MapTy,
4216 "switch.maskindex");
4217 Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex,
4219 Value *LoBit = Builder.CreateTrunc(Shifted,
4220 Type::getInt1Ty(Mod.getContext()),
4222 Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
4224 Builder.SetInsertPoint(LookupBB);
4225 AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent());
4228 bool ReturnedEarly = false;
4229 for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
4230 PHINode *PHI = PHIs[I];
4231 const ResultListTy &ResultList = ResultLists[PHI];
4233 // If using a bitmask, use any value to fill the lookup table holes.
4234 Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
4235 SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL);
4237 Value *Result = Table.BuildLookup(TableIndex, Builder);
4239 // If the result is used to return immediately from the function, we want to
4240 // do that right here.
4241 if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
4242 PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) {
4243 Builder.CreateRet(Result);
4244 ReturnedEarly = true;
4248 // Do a small peephole optimization: re-use the switch table compare if
4250 if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) {
4251 BasicBlock *PhiBlock = PHI->getParent();
4252 // Search for compare instructions which use the phi.
4253 for (auto *User : PHI->users()) {
4254 reuseTableCompare(User, PhiBlock, RangeCheckBranch, DV, ResultList);
4258 PHI->addIncoming(Result, LookupBB);
4262 Builder.CreateBr(CommonDest);
4264 // Remove the switch.
4265 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
4266 BasicBlock *Succ = SI->getSuccessor(i);
4268 if (Succ == SI->getDefaultDest())
4270 Succ->removePredecessor(SI->getParent());
4272 SI->eraseFromParent();
4276 ++NumLookupTablesHoles;
4280 bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
4281 BasicBlock *BB = SI->getParent();
4283 if (isValueEqualityComparison(SI)) {
4284 // If we only have one predecessor, and if it is a branch on this value,
4285 // see if that predecessor totally determines the outcome of this switch.
4286 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
4287 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
4288 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
4290 Value *Cond = SI->getCondition();
4291 if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
4292 if (SimplifySwitchOnSelect(SI, Select))
4293 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
4295 // If the block only contains the switch, see if we can fold the block
4296 // away into any preds.
4297 BasicBlock::iterator BBI = BB->begin();
4298 // Ignore dbg intrinsics.
4299 while (isa<DbgInfoIntrinsic>(BBI))
4302 if (FoldValueComparisonIntoPredecessors(SI, Builder))
4303 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
4306 // Try to transform the switch into an icmp and a branch.
4307 if (TurnSwitchRangeIntoICmp(SI, Builder))
4308 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
4310 // Remove unreachable cases.
4311 if (EliminateDeadSwitchCases(SI, DL, AC))
4312 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
4314 if (SwitchToSelect(SI, Builder, DL, AC))
4315 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
4317 if (ForwardSwitchConditionToPHI(SI))
4318 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
4320 if (SwitchToLookupTable(SI, Builder, TTI, DL))
4321 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
4326 bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
4327 BasicBlock *BB = IBI->getParent();
4328 bool Changed = false;
4330 // Eliminate redundant destinations.
4331 SmallPtrSet<Value *, 8> Succs;
4332 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
4333 BasicBlock *Dest = IBI->getDestination(i);
4334 if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) {
4335 Dest->removePredecessor(BB);
4336 IBI->removeDestination(i);
4342 if (IBI->getNumDestinations() == 0) {
4343 // If the indirectbr has no successors, change it to unreachable.
4344 new UnreachableInst(IBI->getContext(), IBI);
4345 EraseTerminatorInstAndDCECond(IBI);
4349 if (IBI->getNumDestinations() == 1) {
4350 // If the indirectbr has one successor, change it to a direct branch.
4351 BranchInst::Create(IBI->getDestination(0), IBI);
4352 EraseTerminatorInstAndDCECond(IBI);
4356 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
4357 if (SimplifyIndirectBrOnSelect(IBI, SI))
4358 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
4363 bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder){
4364 BasicBlock *BB = BI->getParent();
4366 if (SinkCommon && SinkThenElseCodeToEnd(BI))
4369 // If the Terminator is the only non-phi instruction, simplify the block.
4370 BasicBlock::iterator I = BB->getFirstNonPHIOrDbg();
4371 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
4372 TryToSimplifyUncondBranchFromEmptyBlock(BB))
4375 // If the only instruction in the block is a seteq/setne comparison
4376 // against a constant, try to simplify the block.
4377 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
4378 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
4379 for (++I; isa<DbgInfoIntrinsic>(I); ++I)
4381 if (I->isTerminator() &&
4382 TryToSimplifyUncondBranchWithICmpInIt(ICI, Builder, TTI,
4383 BonusInstThreshold, DL, AC))
4387 // If this basic block is ONLY a compare and a branch, and if a predecessor
4388 // branches to us and our successor, fold the comparison into the
4389 // predecessor and use logical operations to update the incoming value
4390 // for PHI nodes in common successor.
4391 if (FoldBranchToCommonDest(BI, DL, BonusInstThreshold))
4392 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
4397 bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
4398 BasicBlock *BB = BI->getParent();
4400 // Conditional branch
4401 if (isValueEqualityComparison(BI)) {
4402 // If we only have one predecessor, and if it is a branch on this value,
4403 // see if that predecessor totally determines the outcome of this
4405 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
4406 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
4407 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
4409 // This block must be empty, except for the setcond inst, if it exists.
4410 // Ignore dbg intrinsics.
4411 BasicBlock::iterator I = BB->begin();
4412 // Ignore dbg intrinsics.
4413 while (isa<DbgInfoIntrinsic>(I))
4416 if (FoldValueComparisonIntoPredecessors(BI, Builder))
4417 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
4418 } else if (&*I == cast<Instruction>(BI->getCondition())){
4420 // Ignore dbg intrinsics.
4421 while (isa<DbgInfoIntrinsic>(I))
4423 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
4424 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
4428 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
4429 if (SimplifyBranchOnICmpChain(BI, DL, Builder))
4432 // If this basic block is ONLY a compare and a branch, and if a predecessor
4433 // branches to us and one of our successors, fold the comparison into the
4434 // predecessor and use logical operations to pick the right destination.
4435 if (FoldBranchToCommonDest(BI, DL, BonusInstThreshold))
4436 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
4438 // We have a conditional branch to two blocks that are only reachable
4439 // from BI. We know that the condbr dominates the two blocks, so see if
4440 // there is any identical code in the "then" and "else" blocks. If so, we
4441 // can hoist it up to the branching block.
4442 if (BI->getSuccessor(0)->getSinglePredecessor()) {
4443 if (BI->getSuccessor(1)->getSinglePredecessor()) {
4444 if (HoistThenElseCodeToIf(BI, DL))
4445 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
4447 // If Successor #1 has multiple preds, we may be able to conditionally
4448 // execute Successor #0 if it branches to Successor #1.
4449 TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
4450 if (Succ0TI->getNumSuccessors() == 1 &&
4451 Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
4452 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), DL, TTI))
4453 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
4455 } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
4456 // If Successor #0 has multiple preds, we may be able to conditionally
4457 // execute Successor #1 if it branches to Successor #0.
4458 TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
4459 if (Succ1TI->getNumSuccessors() == 1 &&
4460 Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
4461 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), DL, TTI))
4462 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
4465 // If this is a branch on a phi node in the current block, thread control
4466 // through this block if any PHI node entries are constants.
4467 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
4468 if (PN->getParent() == BI->getParent())
4469 if (FoldCondBranchOnPHI(BI, DL))
4470 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
4472 // Scan predecessor blocks for conditional branches.
4473 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
4474 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
4475 if (PBI != BI && PBI->isConditional())
4476 if (SimplifyCondBranchToCondBranch(PBI, BI))
4477 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
4482 /// Check if passing a value to an instruction will cause undefined behavior.
4483 static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
4484 Constant *C = dyn_cast<Constant>(V);
4491 if (C->isNullValue()) {
4492 // Only look at the first use, avoid hurting compile time with long uselists
4493 User *Use = *I->user_begin();
4495 // Now make sure that there are no instructions in between that can alter
4496 // control flow (eg. calls)
4497 for (BasicBlock::iterator i = ++BasicBlock::iterator(I); &*i != Use; ++i)
4498 if (i == I->getParent()->end() || i->mayHaveSideEffects())
4501 // Look through GEPs. A load from a GEP derived from NULL is still undefined
4502 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
4503 if (GEP->getPointerOperand() == I)
4504 return passingValueIsAlwaysUndefined(V, GEP);
4506 // Look through bitcasts.
4507 if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
4508 return passingValueIsAlwaysUndefined(V, BC);
4510 // Load from null is undefined.
4511 if (LoadInst *LI = dyn_cast<LoadInst>(Use))
4512 if (!LI->isVolatile())
4513 return LI->getPointerAddressSpace() == 0;
4515 // Store to null is undefined.
4516 if (StoreInst *SI = dyn_cast<StoreInst>(Use))
4517 if (!SI->isVolatile())
4518 return SI->getPointerAddressSpace() == 0 && SI->getPointerOperand() == I;
4523 /// If BB has an incoming value that will always trigger undefined behavior
4524 /// (eg. null pointer dereference), remove the branch leading here.
4525 static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
4526 for (BasicBlock::iterator i = BB->begin();
4527 PHINode *PHI = dyn_cast<PHINode>(i); ++i)
4528 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
4529 if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) {
4530 TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator();
4531 IRBuilder<> Builder(T);
4532 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
4533 BB->removePredecessor(PHI->getIncomingBlock(i));
4534 // Turn uncoditional branches into unreachables and remove the dead
4535 // destination from conditional branches.
4536 if (BI->isUnconditional())
4537 Builder.CreateUnreachable();
4539 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) :
4540 BI->getSuccessor(0));
4541 BI->eraseFromParent();
4544 // TODO: SwitchInst.
4550 bool SimplifyCFGOpt::run(BasicBlock *BB) {
4551 bool Changed = false;
4553 assert(BB && BB->getParent() && "Block not embedded in function!");
4554 assert(BB->getTerminator() && "Degenerate basic block encountered!");
4556 // Remove basic blocks that have no predecessors (except the entry block)...
4557 // or that just have themself as a predecessor. These are unreachable.
4558 if ((pred_empty(BB) &&
4559 BB != &BB->getParent()->getEntryBlock()) ||
4560 BB->getSinglePredecessor() == BB) {
4561 DEBUG(dbgs() << "Removing BB: \n" << *BB);
4562 DeleteDeadBlock(BB);
4566 // Check to see if we can constant propagate this terminator instruction
4568 Changed |= ConstantFoldTerminator(BB, true);
4570 // Check for and eliminate duplicate PHI nodes in this block.
4571 Changed |= EliminateDuplicatePHINodes(BB);
4573 // Check for and remove branches that will always cause undefined behavior.
4574 Changed |= removeUndefIntroducingPredecessor(BB);
4576 // Merge basic blocks into their predecessor if there is only one distinct
4577 // pred, and if there is only one distinct successor of the predecessor, and
4578 // if there are no PHI nodes.
4580 if (MergeBlockIntoPredecessor(BB))
4583 IRBuilder<> Builder(BB);
4585 // If there is a trivial two-entry PHI node in this basic block, and we can
4586 // eliminate it, do so now.
4587 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
4588 if (PN->getNumIncomingValues() == 2)
4589 Changed |= FoldTwoEntryPHINode(PN, DL, TTI);
4591 Builder.SetInsertPoint(BB->getTerminator());
4592 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
4593 if (BI->isUnconditional()) {
4594 if (SimplifyUncondBranch(BI, Builder)) return true;
4596 if (SimplifyCondBranch(BI, Builder)) return true;
4598 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
4599 if (SimplifyReturn(RI, Builder)) return true;
4600 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
4601 if (SimplifyResume(RI, Builder)) return true;
4602 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
4603 if (SimplifySwitch(SI, Builder)) return true;
4604 } else if (UnreachableInst *UI =
4605 dyn_cast<UnreachableInst>(BB->getTerminator())) {
4606 if (SimplifyUnreachable(UI)) return true;
4607 } else if (IndirectBrInst *IBI =
4608 dyn_cast<IndirectBrInst>(BB->getTerminator())) {
4609 if (SimplifyIndirectBr(IBI)) return true;
4615 /// SimplifyCFG - This function is used to do simplification of a CFG. For
4616 /// example, it adjusts branches to branches to eliminate the extra hop, it
4617 /// eliminates unreachable basic blocks, and does other "peephole" optimization
4618 /// of the CFG. It returns true if a modification was made.
4620 bool llvm::SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
4621 unsigned BonusInstThreshold, const DataLayout *DL,
4622 AssumptionCache *AC) {
4623 return SimplifyCFGOpt(TTI, BonusInstThreshold, DL, AC).run(BB);