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 // Chosen as 2 so as to be cheap, but still to have enough power to fold
57 // a select, so the "clamp" idiom (of a min followed by a max) will be caught.
58 // To catch this, we need to fold a compare and a select, hence '2' being the
59 // minimum reasonable default.
60 static cl::opt<unsigned>
61 PHINodeFoldingThreshold("phi-node-folding-threshold", cl::Hidden, cl::init(2),
62 cl::desc("Control the amount of phi node folding to perform (default = 2)"));
65 DupRet("simplifycfg-dup-ret", cl::Hidden, cl::init(false),
66 cl::desc("Duplicate return instructions into unconditional branches"));
69 SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
70 cl::desc("Sink common instructions down to the end block"));
72 static cl::opt<bool> HoistCondStores(
73 "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true),
74 cl::desc("Hoist conditional stores if an unconditional store precedes"));
76 STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
77 STATISTIC(NumLinearMaps, "Number of switch instructions turned into linear mapping");
78 STATISTIC(NumLookupTables, "Number of switch instructions turned into lookup tables");
79 STATISTIC(NumLookupTablesHoles, "Number of switch instructions turned into lookup tables (holes checked)");
80 STATISTIC(NumTableCmpReuses, "Number of reused switch table lookup compares");
81 STATISTIC(NumSinkCommons, "Number of common instructions sunk down to the end block");
82 STATISTIC(NumSpeculations, "Number of speculative executed instructions");
85 // The first field contains the value that the switch produces when a certain
86 // case group is selected, and the second field is a vector containing the cases
87 // composing the case group.
88 typedef SmallVector<std::pair<Constant *, SmallVector<ConstantInt *, 4>>, 2>
89 SwitchCaseResultVectorTy;
90 // The first field contains the phi node that generates a result of the switch
91 // and the second field contains the value generated for a certain case in the switch
93 typedef SmallVector<std::pair<PHINode *, Constant *>, 4> SwitchCaseResultsTy;
95 /// ValueEqualityComparisonCase - Represents a case of a switch.
96 struct ValueEqualityComparisonCase {
100 ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
101 : Value(Value), Dest(Dest) {}
103 bool operator<(ValueEqualityComparisonCase RHS) const {
104 // Comparing pointers is ok as we only rely on the order for uniquing.
105 return Value < RHS.Value;
108 bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
111 class SimplifyCFGOpt {
112 const TargetTransformInfo &TTI;
113 unsigned BonusInstThreshold;
114 const DataLayout *const DL;
116 Value *isValueEqualityComparison(TerminatorInst *TI);
117 BasicBlock *GetValueEqualityComparisonCases(TerminatorInst *TI,
118 std::vector<ValueEqualityComparisonCase> &Cases);
119 bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
121 IRBuilder<> &Builder);
122 bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
123 IRBuilder<> &Builder);
125 bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder);
126 bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
127 bool SimplifyUnreachable(UnreachableInst *UI);
128 bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
129 bool SimplifyIndirectBr(IndirectBrInst *IBI);
130 bool SimplifyUncondBranch(BranchInst *BI, IRBuilder <> &Builder);
131 bool SimplifyCondBranch(BranchInst *BI, IRBuilder <>&Builder);
134 SimplifyCFGOpt(const TargetTransformInfo &TTI, unsigned BonusInstThreshold,
135 const DataLayout *DL, AssumptionCache *AC)
136 : TTI(TTI), BonusInstThreshold(BonusInstThreshold), DL(DL), AC(AC) {}
137 bool run(BasicBlock *BB);
141 /// SafeToMergeTerminators - Return true if it is safe to merge these two
142 /// terminator instructions together.
144 static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
145 if (SI1 == SI2) return false; // Can't merge with self!
147 // It is not safe to merge these two switch instructions if they have a common
148 // successor, and if that successor has a PHI node, and if *that* PHI node has
149 // conflicting incoming values from the two switch blocks.
150 BasicBlock *SI1BB = SI1->getParent();
151 BasicBlock *SI2BB = SI2->getParent();
152 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
154 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
155 if (SI1Succs.count(*I))
156 for (BasicBlock::iterator BBI = (*I)->begin();
157 isa<PHINode>(BBI); ++BBI) {
158 PHINode *PN = cast<PHINode>(BBI);
159 if (PN->getIncomingValueForBlock(SI1BB) !=
160 PN->getIncomingValueForBlock(SI2BB))
167 /// isProfitableToFoldUnconditional - Return true if it is safe and profitable
168 /// to merge these two terminator instructions together, where SI1 is an
169 /// unconditional branch. PhiNodes will store all PHI nodes in common
172 static bool isProfitableToFoldUnconditional(BranchInst *SI1,
175 SmallVectorImpl<PHINode*> &PhiNodes) {
176 if (SI1 == SI2) return false; // Can't merge with self!
177 assert(SI1->isUnconditional() && SI2->isConditional());
179 // We fold the unconditional branch if we can easily update all PHI nodes in
180 // common successors:
181 // 1> We have a constant incoming value for the conditional branch;
182 // 2> We have "Cond" as the incoming value for the unconditional branch;
183 // 3> SI2->getCondition() and Cond have same operands.
184 CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition());
185 if (!Ci2) return false;
186 if (!(Cond->getOperand(0) == Ci2->getOperand(0) &&
187 Cond->getOperand(1) == Ci2->getOperand(1)) &&
188 !(Cond->getOperand(0) == Ci2->getOperand(1) &&
189 Cond->getOperand(1) == Ci2->getOperand(0)))
192 BasicBlock *SI1BB = SI1->getParent();
193 BasicBlock *SI2BB = SI2->getParent();
194 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
195 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
196 if (SI1Succs.count(*I))
197 for (BasicBlock::iterator BBI = (*I)->begin();
198 isa<PHINode>(BBI); ++BBI) {
199 PHINode *PN = cast<PHINode>(BBI);
200 if (PN->getIncomingValueForBlock(SI1BB) != Cond ||
201 !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB)))
203 PhiNodes.push_back(PN);
208 /// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will
209 /// now be entries in it from the 'NewPred' block. The values that will be
210 /// flowing into the PHI nodes will be the same as those coming in from
211 /// ExistPred, an existing predecessor of Succ.
212 static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
213 BasicBlock *ExistPred) {
214 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
217 for (BasicBlock::iterator I = Succ->begin();
218 (PN = dyn_cast<PHINode>(I)); ++I)
219 PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
222 /// ComputeSpeculationCost - Compute an abstract "cost" of speculating the
223 /// given instruction, which is assumed to be safe to speculate. TCC_Free means
224 /// cheap, TCC_Basic means less cheap, and TCC_Expensive means prohibitively
226 static unsigned ComputeSpeculationCost(const User *I, const DataLayout *DL,
227 const TargetTransformInfo &TTI) {
228 assert(isSafeToSpeculativelyExecute(I, DL) &&
229 "Instruction is not safe to speculatively execute!");
230 return TTI.getUserCost(I);
232 /// DominatesMergePoint - If we have a merge point of an "if condition" as
233 /// accepted above, return true if the specified value dominates the block. We
234 /// don't handle the true generality of domination here, just a special case
235 /// which works well enough for us.
237 /// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
238 /// see if V (which must be an instruction) and its recursive operands
239 /// that do not dominate BB have a combined cost lower than CostRemaining and
240 /// are non-trapping. If both are true, the instruction is inserted into the
241 /// set and true is returned.
243 /// The cost for most non-trapping instructions is defined as 1 except for
244 /// Select whose cost is 2.
246 /// After this function returns, CostRemaining is decreased by the cost of
247 /// V plus its non-dominating operands. If that cost is greater than
248 /// CostRemaining, false is returned and CostRemaining is undefined.
249 static bool DominatesMergePoint(Value *V, BasicBlock *BB,
250 SmallPtrSetImpl<Instruction*> *AggressiveInsts,
251 unsigned &CostRemaining,
252 const DataLayout *DL,
253 const TargetTransformInfo &TTI) {
254 Instruction *I = dyn_cast<Instruction>(V);
256 // Non-instructions all dominate instructions, but not all constantexprs
257 // can be executed unconditionally.
258 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
263 BasicBlock *PBB = I->getParent();
265 // We don't want to allow weird loops that might have the "if condition" in
266 // the bottom of this block.
267 if (PBB == BB) return false;
269 // If this instruction is defined in a block that contains an unconditional
270 // branch to BB, then it must be in the 'conditional' part of the "if
271 // statement". If not, it definitely dominates the region.
272 BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
273 if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB)
276 // If we aren't allowing aggressive promotion anymore, then don't consider
277 // instructions in the 'if region'.
278 if (!AggressiveInsts) return false;
280 // If we have seen this instruction before, don't count it again.
281 if (AggressiveInsts->count(I)) return true;
283 // Okay, it looks like the instruction IS in the "condition". Check to
284 // see if it's a cheap instruction to unconditionally compute, and if it
285 // only uses stuff defined outside of the condition. If so, hoist it out.
286 if (!isSafeToSpeculativelyExecute(I, DL))
289 unsigned Cost = ComputeSpeculationCost(I, DL, TTI);
291 if (Cost > CostRemaining)
294 CostRemaining -= Cost;
296 // Okay, we can only really hoist these out if their operands do
297 // not take us over the cost threshold.
298 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
299 if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining, DL, TTI))
301 // Okay, it's safe to do this! Remember this instruction.
302 AggressiveInsts->insert(I);
306 /// GetConstantInt - Extract ConstantInt from value, looking through IntToPtr
307 /// and PointerNullValue. Return NULL if value is not a constant int.
308 static ConstantInt *GetConstantInt(Value *V, const DataLayout *DL) {
309 // Normal constant int.
310 ConstantInt *CI = dyn_cast<ConstantInt>(V);
311 if (CI || !DL || !isa<Constant>(V) || !V->getType()->isPointerTy())
314 // This is some kind of pointer constant. Turn it into a pointer-sized
315 // ConstantInt if possible.
316 IntegerType *PtrTy = cast<IntegerType>(DL->getIntPtrType(V->getType()));
318 // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
319 if (isa<ConstantPointerNull>(V))
320 return ConstantInt::get(PtrTy, 0);
322 // IntToPtr const int.
323 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
324 if (CE->getOpcode() == Instruction::IntToPtr)
325 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
326 // The constant is very likely to have the right type already.
327 if (CI->getType() == PtrTy)
330 return cast<ConstantInt>
331 (ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
338 /// Given a chain of or (||) or and (&&) comparison of a value against a
339 /// constant, this will try to recover the information required for a switch
341 /// It will depth-first traverse the chain of comparison, seeking for patterns
342 /// like %a == 12 or %a < 4 and combine them to produce a set of integer
343 /// representing the different cases for the switch.
344 /// Note that if the chain is composed of '||' it will build the set of elements
345 /// that matches the comparisons (i.e. any of this value validate the chain)
346 /// while for a chain of '&&' it will build the set elements that make the test
348 struct ConstantComparesGatherer {
350 Value *CompValue; /// Value found for the switch comparison
351 Value *Extra; /// Extra clause to be checked before the switch
352 SmallVector<ConstantInt *, 8> Vals; /// Set of integers to match in switch
353 unsigned UsedICmps; /// Number of comparisons matched in the and/or chain
355 /// Construct and compute the result for the comparison instruction Cond
356 ConstantComparesGatherer(Instruction *Cond, const DataLayout *DL)
357 : CompValue(nullptr), Extra(nullptr), UsedICmps(0) {
362 ConstantComparesGatherer(const ConstantComparesGatherer &) = delete;
363 ConstantComparesGatherer &
364 operator=(const ConstantComparesGatherer &) = delete;
368 /// Try to set the current value used for the comparison, it succeeds only if
369 /// it wasn't set before or if the new value is the same as the old one
370 bool setValueOnce(Value *NewVal) {
371 if(CompValue && CompValue != NewVal) return false;
373 return (CompValue != nullptr);
376 /// Try to match Instruction "I" as a comparison against a constant and
377 /// populates the array Vals with the set of values that match (or do not
378 /// match depending on isEQ).
379 /// Return false on failure. On success, the Value the comparison matched
380 /// against is placed in CompValue.
381 /// If CompValue is already set, the function is expected to fail if a match
382 /// is found but the value compared to is different.
383 bool matchInstruction(Instruction *I, const DataLayout *DL, bool isEQ) {
384 // If this is an icmp against a constant, handle this as one of the cases.
387 if (!((ICI = dyn_cast<ICmpInst>(I)) &&
388 (C = GetConstantInt(I->getOperand(1), DL)))) {
395 // Pattern match a special case
396 // (x & ~2^x) == y --> x == y || x == y|2^x
397 // This undoes a transformation done by instcombine to fuse 2 compares.
398 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ:ICmpInst::ICMP_NE)) {
399 if (match(ICI->getOperand(0),
400 m_And(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
401 APInt Not = ~RHSC->getValue();
402 if (Not.isPowerOf2()) {
403 // If we already have a value for the switch, it has to match!
404 if(!setValueOnce(RHSVal))
408 Vals.push_back(ConstantInt::get(C->getContext(),
409 C->getValue() | Not));
415 // If we already have a value for the switch, it has to match!
416 if(!setValueOnce(ICI->getOperand(0)))
421 return ICI->getOperand(0);
424 // If we have "x ult 3", for example, then we can add 0,1,2 to the set.
425 ConstantRange Span = ConstantRange::makeICmpRegion(ICI->getPredicate(),
428 // Shift the range if the compare is fed by an add. This is the range
429 // compare idiom as emitted by instcombine.
430 Value *CandidateVal = I->getOperand(0);
431 if(match(I->getOperand(0), m_Add(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
432 Span = Span.subtract(RHSC->getValue());
433 CandidateVal = RHSVal;
436 // If this is an and/!= check, then we are looking to build the set of
437 // value that *don't* pass the and chain. I.e. to turn "x ugt 2" into
440 Span = Span.inverse();
442 // If there are a ton of values, we don't want to make a ginormous switch.
443 if (Span.getSetSize().ugt(8) || Span.isEmptySet()) {
447 // If we already have a value for the switch, it has to match!
448 if(!setValueOnce(CandidateVal))
451 // Add all values from the range to the set
452 for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
453 Vals.push_back(ConstantInt::get(I->getContext(), Tmp));
460 /// gather - Given a potentially 'or'd or 'and'd together collection of icmp
461 /// eq/ne/lt/gt instructions that compare a value against a constant, extract
462 /// the value being compared, and stick the list constants into the Vals
464 /// One "Extra" case is allowed to differ from the other.
465 void gather(Value *V, const DataLayout *DL) {
466 Instruction *I = dyn_cast<Instruction>(V);
467 bool isEQ = (I->getOpcode() == Instruction::Or);
469 // Keep a stack (SmallVector for efficiency) for depth-first traversal
470 SmallVector<Value *, 8> DFT;
475 while(!DFT.empty()) {
476 V = DFT.pop_back_val();
478 if (Instruction *I = dyn_cast<Instruction>(V)) {
479 // If it is a || (or && depending on isEQ), process the operands.
480 if (I->getOpcode() == (isEQ ? Instruction::Or : Instruction::And)) {
481 DFT.push_back(I->getOperand(1));
482 DFT.push_back(I->getOperand(0));
486 // Try to match the current instruction
487 if (matchInstruction(I, DL, isEQ))
488 // Match succeed, continue the loop
492 // One element of the sequence of || (or &&) could not be match as a
493 // comparison against the same value as the others.
494 // We allow only one "Extra" case to be checked before the switch
499 // Failed to parse a proper sequence, abort now
508 static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
509 Instruction *Cond = nullptr;
510 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
511 Cond = dyn_cast<Instruction>(SI->getCondition());
512 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
513 if (BI->isConditional())
514 Cond = dyn_cast<Instruction>(BI->getCondition());
515 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
516 Cond = dyn_cast<Instruction>(IBI->getAddress());
519 TI->eraseFromParent();
520 if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond);
523 /// isValueEqualityComparison - Return true if the specified terminator checks
524 /// to see if a value is equal to constant integer value.
525 Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) {
527 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
528 // Do not permit merging of large switch instructions into their
529 // predecessors unless there is only one predecessor.
530 if (SI->getNumSuccessors()*std::distance(pred_begin(SI->getParent()),
531 pred_end(SI->getParent())) <= 128)
532 CV = SI->getCondition();
533 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
534 if (BI->isConditional() && BI->getCondition()->hasOneUse())
535 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
536 if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL))
537 CV = ICI->getOperand(0);
539 // Unwrap any lossless ptrtoint cast.
541 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
542 Value *Ptr = PTII->getPointerOperand();
543 if (PTII->getType() == DL->getIntPtrType(Ptr->getType()))
550 /// GetValueEqualityComparisonCases - Given a value comparison instruction,
551 /// decode all of the 'cases' that it represents and return the 'default' block.
552 BasicBlock *SimplifyCFGOpt::
553 GetValueEqualityComparisonCases(TerminatorInst *TI,
554 std::vector<ValueEqualityComparisonCase>
556 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
557 Cases.reserve(SI->getNumCases());
558 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i)
559 Cases.push_back(ValueEqualityComparisonCase(i.getCaseValue(),
560 i.getCaseSuccessor()));
561 return SI->getDefaultDest();
564 BranchInst *BI = cast<BranchInst>(TI);
565 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
566 BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE);
567 Cases.push_back(ValueEqualityComparisonCase(GetConstantInt(ICI->getOperand(1),
570 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
574 /// EliminateBlockCases - Given a vector of bb/value pairs, remove any entries
575 /// in the list that match the specified block.
576 static void EliminateBlockCases(BasicBlock *BB,
577 std::vector<ValueEqualityComparisonCase> &Cases) {
578 Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end());
581 /// ValuesOverlap - Return true if there are any keys in C1 that exist in C2 as
584 ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
585 std::vector<ValueEqualityComparisonCase > &C2) {
586 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
588 // Make V1 be smaller than V2.
589 if (V1->size() > V2->size())
592 if (V1->size() == 0) return false;
593 if (V1->size() == 1) {
595 ConstantInt *TheVal = (*V1)[0].Value;
596 for (unsigned i = 0, e = V2->size(); i != e; ++i)
597 if (TheVal == (*V2)[i].Value)
601 // Otherwise, just sort both lists and compare element by element.
602 array_pod_sort(V1->begin(), V1->end());
603 array_pod_sort(V2->begin(), V2->end());
604 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
605 while (i1 != e1 && i2 != e2) {
606 if ((*V1)[i1].Value == (*V2)[i2].Value)
608 if ((*V1)[i1].Value < (*V2)[i2].Value)
616 /// SimplifyEqualityComparisonWithOnlyPredecessor - If TI is known to be a
617 /// terminator instruction and its block is known to only have a single
618 /// predecessor block, check to see if that predecessor is also a value
619 /// comparison with the same value, and if that comparison determines the
620 /// outcome of this comparison. If so, simplify TI. This does a very limited
621 /// form of jump threading.
622 bool SimplifyCFGOpt::
623 SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
625 IRBuilder<> &Builder) {
626 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
627 if (!PredVal) return false; // Not a value comparison in predecessor.
629 Value *ThisVal = isValueEqualityComparison(TI);
630 assert(ThisVal && "This isn't a value comparison!!");
631 if (ThisVal != PredVal) return false; // Different predicates.
633 // TODO: Preserve branch weight metadata, similarly to how
634 // FoldValueComparisonIntoPredecessors preserves it.
636 // Find out information about when control will move from Pred to TI's block.
637 std::vector<ValueEqualityComparisonCase> PredCases;
638 BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
640 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
642 // Find information about how control leaves this block.
643 std::vector<ValueEqualityComparisonCase> ThisCases;
644 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
645 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
647 // If TI's block is the default block from Pred's comparison, potentially
648 // simplify TI based on this knowledge.
649 if (PredDef == TI->getParent()) {
650 // If we are here, we know that the value is none of those cases listed in
651 // PredCases. If there are any cases in ThisCases that are in PredCases, we
653 if (!ValuesOverlap(PredCases, ThisCases))
656 if (isa<BranchInst>(TI)) {
657 // Okay, one of the successors of this condbr is dead. Convert it to a
659 assert(ThisCases.size() == 1 && "Branch can only have one case!");
660 // Insert the new branch.
661 Instruction *NI = Builder.CreateBr(ThisDef);
664 // Remove PHI node entries for the dead edge.
665 ThisCases[0].Dest->removePredecessor(TI->getParent());
667 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
668 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
670 EraseTerminatorInstAndDCECond(TI);
674 SwitchInst *SI = cast<SwitchInst>(TI);
675 // Okay, TI has cases that are statically dead, prune them away.
676 SmallPtrSet<Constant*, 16> DeadCases;
677 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
678 DeadCases.insert(PredCases[i].Value);
680 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
681 << "Through successor TI: " << *TI);
683 // Collect branch weights into a vector.
684 SmallVector<uint32_t, 8> Weights;
685 MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
686 bool HasWeight = MD && (MD->getNumOperands() == 2 + SI->getNumCases());
688 for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
690 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(MD_i));
691 Weights.push_back(CI->getValue().getZExtValue());
693 for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
695 if (DeadCases.count(i.getCaseValue())) {
697 std::swap(Weights[i.getCaseIndex()+1], Weights.back());
700 i.getCaseSuccessor()->removePredecessor(TI->getParent());
704 if (HasWeight && Weights.size() >= 2)
705 SI->setMetadata(LLVMContext::MD_prof,
706 MDBuilder(SI->getParent()->getContext()).
707 createBranchWeights(Weights));
709 DEBUG(dbgs() << "Leaving: " << *TI << "\n");
713 // Otherwise, TI's block must correspond to some matched value. Find out
714 // which value (or set of values) this is.
715 ConstantInt *TIV = nullptr;
716 BasicBlock *TIBB = TI->getParent();
717 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
718 if (PredCases[i].Dest == TIBB) {
720 return false; // Cannot handle multiple values coming to this block.
721 TIV = PredCases[i].Value;
723 assert(TIV && "No edge from pred to succ?");
725 // Okay, we found the one constant that our value can be if we get into TI's
726 // BB. Find out which successor will unconditionally be branched to.
727 BasicBlock *TheRealDest = nullptr;
728 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
729 if (ThisCases[i].Value == TIV) {
730 TheRealDest = ThisCases[i].Dest;
734 // If not handled by any explicit cases, it is handled by the default case.
735 if (!TheRealDest) TheRealDest = ThisDef;
737 // Remove PHI node entries for dead edges.
738 BasicBlock *CheckEdge = TheRealDest;
739 for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
740 if (*SI != CheckEdge)
741 (*SI)->removePredecessor(TIBB);
745 // Insert the new branch.
746 Instruction *NI = Builder.CreateBr(TheRealDest);
749 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
750 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
752 EraseTerminatorInstAndDCECond(TI);
757 /// ConstantIntOrdering - This class implements a stable ordering of constant
758 /// integers that does not depend on their address. This is important for
759 /// applications that sort ConstantInt's to ensure uniqueness.
760 struct ConstantIntOrdering {
761 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
762 return LHS->getValue().ult(RHS->getValue());
767 static int ConstantIntSortPredicate(ConstantInt *const *P1,
768 ConstantInt *const *P2) {
769 const ConstantInt *LHS = *P1;
770 const ConstantInt *RHS = *P2;
771 if (LHS->getValue().ult(RHS->getValue()))
773 if (LHS->getValue() == RHS->getValue())
778 static inline bool HasBranchWeights(const Instruction* I) {
779 MDNode *ProfMD = I->getMetadata(LLVMContext::MD_prof);
780 if (ProfMD && ProfMD->getOperand(0))
781 if (MDString* MDS = dyn_cast<MDString>(ProfMD->getOperand(0)))
782 return MDS->getString().equals("branch_weights");
787 /// Get Weights of a given TerminatorInst, the default weight is at the front
788 /// of the vector. If TI is a conditional eq, we need to swap the branch-weight
790 static void GetBranchWeights(TerminatorInst *TI,
791 SmallVectorImpl<uint64_t> &Weights) {
792 MDNode *MD = TI->getMetadata(LLVMContext::MD_prof);
794 for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) {
795 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(i));
796 Weights.push_back(CI->getValue().getZExtValue());
799 // If TI is a conditional eq, the default case is the false case,
800 // and the corresponding branch-weight data is at index 2. We swap the
801 // default weight to be the first entry.
802 if (BranchInst* BI = dyn_cast<BranchInst>(TI)) {
803 assert(Weights.size() == 2);
804 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
805 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
806 std::swap(Weights.front(), Weights.back());
810 /// Keep halving the weights until all can fit in uint32_t.
811 static void FitWeights(MutableArrayRef<uint64_t> Weights) {
812 uint64_t Max = *std::max_element(Weights.begin(), Weights.end());
813 if (Max > UINT_MAX) {
814 unsigned Offset = 32 - countLeadingZeros(Max);
815 for (uint64_t &I : Weights)
820 /// FoldValueComparisonIntoPredecessors - The specified terminator is a value
821 /// equality comparison instruction (either a switch or a branch on "X == c").
822 /// See if any of the predecessors of the terminator block are value comparisons
823 /// on the same value. If so, and if safe to do so, fold them together.
824 bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
825 IRBuilder<> &Builder) {
826 BasicBlock *BB = TI->getParent();
827 Value *CV = isValueEqualityComparison(TI); // CondVal
828 assert(CV && "Not a comparison?");
829 bool Changed = false;
831 SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
832 while (!Preds.empty()) {
833 BasicBlock *Pred = Preds.pop_back_val();
835 // See if the predecessor is a comparison with the same value.
836 TerminatorInst *PTI = Pred->getTerminator();
837 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
839 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
840 // Figure out which 'cases' to copy from SI to PSI.
841 std::vector<ValueEqualityComparisonCase> BBCases;
842 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
844 std::vector<ValueEqualityComparisonCase> PredCases;
845 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
847 // Based on whether the default edge from PTI goes to BB or not, fill in
848 // PredCases and PredDefault with the new switch cases we would like to
850 SmallVector<BasicBlock*, 8> NewSuccessors;
852 // Update the branch weight metadata along the way
853 SmallVector<uint64_t, 8> Weights;
854 bool PredHasWeights = HasBranchWeights(PTI);
855 bool SuccHasWeights = HasBranchWeights(TI);
857 if (PredHasWeights) {
858 GetBranchWeights(PTI, Weights);
859 // branch-weight metadata is inconsistent here.
860 if (Weights.size() != 1 + PredCases.size())
861 PredHasWeights = SuccHasWeights = false;
862 } else if (SuccHasWeights)
863 // If there are no predecessor weights but there are successor weights,
864 // populate Weights with 1, which will later be scaled to the sum of
865 // successor's weights
866 Weights.assign(1 + PredCases.size(), 1);
868 SmallVector<uint64_t, 8> SuccWeights;
869 if (SuccHasWeights) {
870 GetBranchWeights(TI, SuccWeights);
871 // branch-weight metadata is inconsistent here.
872 if (SuccWeights.size() != 1 + BBCases.size())
873 PredHasWeights = SuccHasWeights = false;
874 } else if (PredHasWeights)
875 SuccWeights.assign(1 + BBCases.size(), 1);
877 if (PredDefault == BB) {
878 // If this is the default destination from PTI, only the edges in TI
879 // that don't occur in PTI, or that branch to BB will be activated.
880 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
881 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
882 if (PredCases[i].Dest != BB)
883 PTIHandled.insert(PredCases[i].Value);
885 // The default destination is BB, we don't need explicit targets.
886 std::swap(PredCases[i], PredCases.back());
888 if (PredHasWeights || SuccHasWeights) {
889 // Increase weight for the default case.
890 Weights[0] += Weights[i+1];
891 std::swap(Weights[i+1], Weights.back());
895 PredCases.pop_back();
899 // Reconstruct the new switch statement we will be building.
900 if (PredDefault != BBDefault) {
901 PredDefault->removePredecessor(Pred);
902 PredDefault = BBDefault;
903 NewSuccessors.push_back(BBDefault);
906 unsigned CasesFromPred = Weights.size();
907 uint64_t ValidTotalSuccWeight = 0;
908 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
909 if (!PTIHandled.count(BBCases[i].Value) &&
910 BBCases[i].Dest != BBDefault) {
911 PredCases.push_back(BBCases[i]);
912 NewSuccessors.push_back(BBCases[i].Dest);
913 if (SuccHasWeights || PredHasWeights) {
914 // The default weight is at index 0, so weight for the ith case
915 // should be at index i+1. Scale the cases from successor by
916 // PredDefaultWeight (Weights[0]).
917 Weights.push_back(Weights[0] * SuccWeights[i+1]);
918 ValidTotalSuccWeight += SuccWeights[i+1];
922 if (SuccHasWeights || PredHasWeights) {
923 ValidTotalSuccWeight += SuccWeights[0];
924 // Scale the cases from predecessor by ValidTotalSuccWeight.
925 for (unsigned i = 1; i < CasesFromPred; ++i)
926 Weights[i] *= ValidTotalSuccWeight;
927 // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
928 Weights[0] *= SuccWeights[0];
931 // If this is not the default destination from PSI, only the edges
932 // in SI that occur in PSI with a destination of BB will be
934 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
935 std::map<ConstantInt*, uint64_t> WeightsForHandled;
936 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
937 if (PredCases[i].Dest == BB) {
938 PTIHandled.insert(PredCases[i].Value);
940 if (PredHasWeights || SuccHasWeights) {
941 WeightsForHandled[PredCases[i].Value] = Weights[i+1];
942 std::swap(Weights[i+1], Weights.back());
946 std::swap(PredCases[i], PredCases.back());
947 PredCases.pop_back();
951 // Okay, now we know which constants were sent to BB from the
952 // predecessor. Figure out where they will all go now.
953 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
954 if (PTIHandled.count(BBCases[i].Value)) {
955 // If this is one we are capable of getting...
956 if (PredHasWeights || SuccHasWeights)
957 Weights.push_back(WeightsForHandled[BBCases[i].Value]);
958 PredCases.push_back(BBCases[i]);
959 NewSuccessors.push_back(BBCases[i].Dest);
960 PTIHandled.erase(BBCases[i].Value);// This constant is taken care of
963 // If there are any constants vectored to BB that TI doesn't handle,
964 // they must go to the default destination of TI.
965 for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I =
967 E = PTIHandled.end(); I != E; ++I) {
968 if (PredHasWeights || SuccHasWeights)
969 Weights.push_back(WeightsForHandled[*I]);
970 PredCases.push_back(ValueEqualityComparisonCase(*I, BBDefault));
971 NewSuccessors.push_back(BBDefault);
975 // Okay, at this point, we know which new successor Pred will get. Make
976 // sure we update the number of entries in the PHI nodes for these
978 for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
979 AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
981 Builder.SetInsertPoint(PTI);
982 // Convert pointer to int before we switch.
983 if (CV->getType()->isPointerTy()) {
984 assert(DL && "Cannot switch on pointer without DataLayout");
985 CV = Builder.CreatePtrToInt(CV, DL->getIntPtrType(CV->getType()),
989 // Now that the successors are updated, create the new Switch instruction.
990 SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault,
992 NewSI->setDebugLoc(PTI->getDebugLoc());
993 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
994 NewSI->addCase(PredCases[i].Value, PredCases[i].Dest);
996 if (PredHasWeights || SuccHasWeights) {
997 // Halve the weights if any of them cannot fit in an uint32_t
1000 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
1002 NewSI->setMetadata(LLVMContext::MD_prof,
1003 MDBuilder(BB->getContext()).
1004 createBranchWeights(MDWeights));
1007 EraseTerminatorInstAndDCECond(PTI);
1009 // Okay, last check. If BB is still a successor of PSI, then we must
1010 // have an infinite loop case. If so, add an infinitely looping block
1011 // to handle the case to preserve the behavior of the code.
1012 BasicBlock *InfLoopBlock = nullptr;
1013 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
1014 if (NewSI->getSuccessor(i) == BB) {
1015 if (!InfLoopBlock) {
1016 // Insert it at the end of the function, because it's either code,
1017 // or it won't matter if it's hot. :)
1018 InfLoopBlock = BasicBlock::Create(BB->getContext(),
1019 "infloop", BB->getParent());
1020 BranchInst::Create(InfLoopBlock, InfLoopBlock);
1022 NewSI->setSuccessor(i, InfLoopBlock);
1031 // isSafeToHoistInvoke - If we would need to insert a select that uses the
1032 // value of this invoke (comments in HoistThenElseCodeToIf explain why we
1033 // would need to do this), we can't hoist the invoke, as there is nowhere
1034 // to put the select in this case.
1035 static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
1036 Instruction *I1, Instruction *I2) {
1037 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
1039 for (BasicBlock::iterator BBI = SI->begin();
1040 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1041 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1042 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1043 if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) {
1051 static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I);
1053 /// HoistThenElseCodeToIf - Given a conditional branch that goes to BB1 and
1054 /// BB2, hoist any common code in the two blocks up into the branch block. The
1055 /// caller of this function guarantees that BI's block dominates BB1 and BB2.
1056 static bool HoistThenElseCodeToIf(BranchInst *BI, const DataLayout *DL) {
1057 // This does very trivial matching, with limited scanning, to find identical
1058 // instructions in the two blocks. In particular, we don't want to get into
1059 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
1060 // such, we currently just scan for obviously identical instructions in an
1062 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
1063 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
1065 BasicBlock::iterator BB1_Itr = BB1->begin();
1066 BasicBlock::iterator BB2_Itr = BB2->begin();
1068 Instruction *I1 = BB1_Itr++, *I2 = BB2_Itr++;
1069 // Skip debug info if it is not identical.
1070 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1071 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1072 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1073 while (isa<DbgInfoIntrinsic>(I1))
1075 while (isa<DbgInfoIntrinsic>(I2))
1078 if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
1079 (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
1082 BasicBlock *BIParent = BI->getParent();
1084 bool Changed = false;
1086 // If we are hoisting the terminator instruction, don't move one (making a
1087 // broken BB), instead clone it, and remove BI.
1088 if (isa<TerminatorInst>(I1))
1089 goto HoistTerminator;
1091 // For a normal instruction, we just move one to right before the branch,
1092 // then replace all uses of the other with the first. Finally, we remove
1093 // the now redundant second instruction.
1094 BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
1095 if (!I2->use_empty())
1096 I2->replaceAllUsesWith(I1);
1097 I1->intersectOptionalDataWith(I2);
1098 unsigned KnownIDs[] = {
1099 LLVMContext::MD_tbaa,
1100 LLVMContext::MD_range,
1101 LLVMContext::MD_fpmath,
1102 LLVMContext::MD_invariant_load,
1103 LLVMContext::MD_nonnull
1105 combineMetadata(I1, I2, KnownIDs);
1106 I2->eraseFromParent();
1111 // Skip debug info if it is not identical.
1112 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1113 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1114 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1115 while (isa<DbgInfoIntrinsic>(I1))
1117 while (isa<DbgInfoIntrinsic>(I2))
1120 } while (I1->isIdenticalToWhenDefined(I2));
1125 // It may not be possible to hoist an invoke.
1126 if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
1129 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
1131 for (BasicBlock::iterator BBI = SI->begin();
1132 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1133 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1134 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1138 // Check for passingValueIsAlwaysUndefined here because we would rather
1139 // eliminate undefined control flow then converting it to a select.
1140 if (passingValueIsAlwaysUndefined(BB1V, PN) ||
1141 passingValueIsAlwaysUndefined(BB2V, PN))
1144 if (isa<ConstantExpr>(BB1V) && !isSafeToSpeculativelyExecute(BB1V, DL))
1146 if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V, DL))
1151 // Okay, it is safe to hoist the terminator.
1152 Instruction *NT = I1->clone();
1153 BIParent->getInstList().insert(BI, NT);
1154 if (!NT->getType()->isVoidTy()) {
1155 I1->replaceAllUsesWith(NT);
1156 I2->replaceAllUsesWith(NT);
1160 IRBuilder<true, NoFolder> Builder(NT);
1161 // Hoisting one of the terminators from our successor is a great thing.
1162 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
1163 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
1164 // nodes, so we insert select instruction to compute the final result.
1165 std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
1166 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
1168 for (BasicBlock::iterator BBI = SI->begin();
1169 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1170 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1171 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1172 if (BB1V == BB2V) continue;
1174 // These values do not agree. Insert a select instruction before NT
1175 // that determines the right value.
1176 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
1178 SI = cast<SelectInst>
1179 (Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
1180 BB1V->getName()+"."+BB2V->getName()));
1182 // Make the PHI node use the select for all incoming values for BB1/BB2
1183 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1184 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
1185 PN->setIncomingValue(i, SI);
1189 // Update any PHI nodes in our new successors.
1190 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
1191 AddPredecessorToBlock(*SI, BIParent, BB1);
1193 EraseTerminatorInstAndDCECond(BI);
1197 /// SinkThenElseCodeToEnd - Given an unconditional branch that goes to BBEnd,
1198 /// check whether BBEnd has only two predecessors and the other predecessor
1199 /// ends with an unconditional branch. If it is true, sink any common code
1200 /// in the two predecessors to BBEnd.
1201 static bool SinkThenElseCodeToEnd(BranchInst *BI1) {
1202 assert(BI1->isUnconditional());
1203 BasicBlock *BB1 = BI1->getParent();
1204 BasicBlock *BBEnd = BI1->getSuccessor(0);
1206 // Check that BBEnd has two predecessors and the other predecessor ends with
1207 // an unconditional branch.
1208 pred_iterator PI = pred_begin(BBEnd), PE = pred_end(BBEnd);
1209 BasicBlock *Pred0 = *PI++;
1210 if (PI == PE) // Only one predecessor.
1212 BasicBlock *Pred1 = *PI++;
1213 if (PI != PE) // More than two predecessors.
1215 BasicBlock *BB2 = (Pred0 == BB1) ? Pred1 : Pred0;
1216 BranchInst *BI2 = dyn_cast<BranchInst>(BB2->getTerminator());
1217 if (!BI2 || !BI2->isUnconditional())
1220 // Gather the PHI nodes in BBEnd.
1221 SmallDenseMap<std::pair<Value *, Value *>, PHINode *> JointValueMap;
1222 Instruction *FirstNonPhiInBBEnd = nullptr;
1223 for (BasicBlock::iterator I = BBEnd->begin(), E = BBEnd->end(); I != E; ++I) {
1224 if (PHINode *PN = dyn_cast<PHINode>(I)) {
1225 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1226 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1227 JointValueMap[std::make_pair(BB1V, BB2V)] = PN;
1229 FirstNonPhiInBBEnd = &*I;
1233 if (!FirstNonPhiInBBEnd)
1236 // This does very trivial matching, with limited scanning, to find identical
1237 // instructions in the two blocks. We scan backward for obviously identical
1238 // instructions in an identical order.
1239 BasicBlock::InstListType::reverse_iterator RI1 = BB1->getInstList().rbegin(),
1240 RE1 = BB1->getInstList().rend(),
1241 RI2 = BB2->getInstList().rbegin(),
1242 RE2 = BB2->getInstList().rend();
1244 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1247 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1250 // Skip the unconditional branches.
1254 bool Changed = false;
1255 while (RI1 != RE1 && RI2 != RE2) {
1257 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1260 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1264 Instruction *I1 = &*RI1, *I2 = &*RI2;
1265 auto InstPair = std::make_pair(I1, I2);
1266 // I1 and I2 should have a single use in the same PHI node, and they
1267 // perform the same operation.
1268 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
1269 if (isa<PHINode>(I1) || isa<PHINode>(I2) ||
1270 isa<TerminatorInst>(I1) || isa<TerminatorInst>(I2) ||
1271 isa<LandingPadInst>(I1) || isa<LandingPadInst>(I2) ||
1272 isa<AllocaInst>(I1) || isa<AllocaInst>(I2) ||
1273 I1->mayHaveSideEffects() || I2->mayHaveSideEffects() ||
1274 I1->mayReadOrWriteMemory() || I2->mayReadOrWriteMemory() ||
1275 !I1->hasOneUse() || !I2->hasOneUse() ||
1276 !JointValueMap.count(InstPair))
1279 // Check whether we should swap the operands of ICmpInst.
1280 // TODO: Add support of communativity.
1281 ICmpInst *ICmp1 = dyn_cast<ICmpInst>(I1), *ICmp2 = dyn_cast<ICmpInst>(I2);
1282 bool SwapOpnds = false;
1283 if (ICmp1 && ICmp2 &&
1284 ICmp1->getOperand(0) != ICmp2->getOperand(0) &&
1285 ICmp1->getOperand(1) != ICmp2->getOperand(1) &&
1286 (ICmp1->getOperand(0) == ICmp2->getOperand(1) ||
1287 ICmp1->getOperand(1) == ICmp2->getOperand(0))) {
1288 ICmp2->swapOperands();
1291 if (!I1->isSameOperationAs(I2)) {
1293 ICmp2->swapOperands();
1297 // The operands should be either the same or they need to be generated
1298 // with a PHI node after sinking. We only handle the case where there is
1299 // a single pair of different operands.
1300 Value *DifferentOp1 = nullptr, *DifferentOp2 = nullptr;
1301 unsigned Op1Idx = ~0U;
1302 for (unsigned I = 0, E = I1->getNumOperands(); I != E; ++I) {
1303 if (I1->getOperand(I) == I2->getOperand(I))
1305 // Early exit if we have more-than one pair of different operands or if
1306 // we need a PHI node to replace a constant.
1307 if (Op1Idx != ~0U ||
1308 isa<Constant>(I1->getOperand(I)) ||
1309 isa<Constant>(I2->getOperand(I))) {
1310 // If we can't sink the instructions, undo the swapping.
1312 ICmp2->swapOperands();
1315 DifferentOp1 = I1->getOperand(I);
1317 DifferentOp2 = I2->getOperand(I);
1320 DEBUG(dbgs() << "SINK common instructions " << *I1 << "\n");
1321 DEBUG(dbgs() << " " << *I2 << "\n");
1323 // We insert the pair of different operands to JointValueMap and
1324 // remove (I1, I2) from JointValueMap.
1325 if (Op1Idx != ~0U) {
1326 auto &NewPN = JointValueMap[std::make_pair(DifferentOp1, DifferentOp2)];
1329 PHINode::Create(DifferentOp1->getType(), 2,
1330 DifferentOp1->getName() + ".sink", BBEnd->begin());
1331 NewPN->addIncoming(DifferentOp1, BB1);
1332 NewPN->addIncoming(DifferentOp2, BB2);
1333 DEBUG(dbgs() << "Create PHI node " << *NewPN << "\n";);
1335 // I1 should use NewPN instead of DifferentOp1.
1336 I1->setOperand(Op1Idx, NewPN);
1338 PHINode *OldPN = JointValueMap[InstPair];
1339 JointValueMap.erase(InstPair);
1341 // We need to update RE1 and RE2 if we are going to sink the first
1342 // instruction in the basic block down.
1343 bool UpdateRE1 = (I1 == BB1->begin()), UpdateRE2 = (I2 == BB2->begin());
1344 // Sink the instruction.
1345 BBEnd->getInstList().splice(FirstNonPhiInBBEnd, BB1->getInstList(), I1);
1346 if (!OldPN->use_empty())
1347 OldPN->replaceAllUsesWith(I1);
1348 OldPN->eraseFromParent();
1350 if (!I2->use_empty())
1351 I2->replaceAllUsesWith(I1);
1352 I1->intersectOptionalDataWith(I2);
1353 // TODO: Use combineMetadata here to preserve what metadata we can
1354 // (analogous to the hoisting case above).
1355 I2->eraseFromParent();
1358 RE1 = BB1->getInstList().rend();
1360 RE2 = BB2->getInstList().rend();
1361 FirstNonPhiInBBEnd = I1;
1368 /// \brief Determine if we can hoist sink a sole store instruction out of a
1369 /// conditional block.
1371 /// We are looking for code like the following:
1373 /// store i32 %add, i32* %arrayidx2
1374 /// ... // No other stores or function calls (we could be calling a memory
1375 /// ... // function).
1376 /// %cmp = icmp ult %x, %y
1377 /// br i1 %cmp, label %EndBB, label %ThenBB
1379 /// store i32 %add5, i32* %arrayidx2
1383 /// We are going to transform this into:
1385 /// store i32 %add, i32* %arrayidx2
1387 /// %cmp = icmp ult %x, %y
1388 /// %add.add5 = select i1 %cmp, i32 %add, %add5
1389 /// store i32 %add.add5, i32* %arrayidx2
1392 /// \return The pointer to the value of the previous store if the store can be
1393 /// hoisted into the predecessor block. 0 otherwise.
1394 static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB,
1395 BasicBlock *StoreBB, BasicBlock *EndBB) {
1396 StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
1400 // Volatile or atomic.
1401 if (!StoreToHoist->isSimple())
1404 Value *StorePtr = StoreToHoist->getPointerOperand();
1406 // Look for a store to the same pointer in BrBB.
1407 unsigned MaxNumInstToLookAt = 10;
1408 for (BasicBlock::reverse_iterator RI = BrBB->rbegin(),
1409 RE = BrBB->rend(); RI != RE && (--MaxNumInstToLookAt); ++RI) {
1410 Instruction *CurI = &*RI;
1412 // Could be calling an instruction that effects memory like free().
1413 if (CurI->mayHaveSideEffects() && !isa<StoreInst>(CurI))
1416 StoreInst *SI = dyn_cast<StoreInst>(CurI);
1417 // Found the previous store make sure it stores to the same location.
1418 if (SI && SI->getPointerOperand() == StorePtr)
1419 // Found the previous store, return its value operand.
1420 return SI->getValueOperand();
1422 return nullptr; // Unknown store.
1428 /// \brief Speculate a conditional basic block flattening the CFG.
1430 /// Note that this is a very risky transform currently. Speculating
1431 /// instructions like this is most often not desirable. Instead, there is an MI
1432 /// pass which can do it with full awareness of the resource constraints.
1433 /// However, some cases are "obvious" and we should do directly. An example of
1434 /// this is speculating a single, reasonably cheap instruction.
1436 /// There is only one distinct advantage to flattening the CFG at the IR level:
1437 /// it makes very common but simplistic optimizations such as are common in
1438 /// instcombine and the DAG combiner more powerful by removing CFG edges and
1439 /// modeling their effects with easier to reason about SSA value graphs.
1442 /// An illustration of this transform is turning this IR:
1445 /// %cmp = icmp ult %x, %y
1446 /// br i1 %cmp, label %EndBB, label %ThenBB
1448 /// %sub = sub %x, %y
1451 /// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ]
1458 /// %cmp = icmp ult %x, %y
1459 /// %sub = sub %x, %y
1460 /// %cond = select i1 %cmp, 0, %sub
1464 /// \returns true if the conditional block is removed.
1465 static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB,
1466 const DataLayout *DL,
1467 const TargetTransformInfo &TTI) {
1468 // Be conservative for now. FP select instruction can often be expensive.
1469 Value *BrCond = BI->getCondition();
1470 if (isa<FCmpInst>(BrCond))
1473 BasicBlock *BB = BI->getParent();
1474 BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
1476 // If ThenBB is actually on the false edge of the conditional branch, remember
1477 // to swap the select operands later.
1478 bool Invert = false;
1479 if (ThenBB != BI->getSuccessor(0)) {
1480 assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
1483 assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
1485 // Keep a count of how many times instructions are used within CondBB when
1486 // they are candidates for sinking into CondBB. Specifically:
1487 // - They are defined in BB, and
1488 // - They have no side effects, and
1489 // - All of their uses are in CondBB.
1490 SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
1492 unsigned SpeculationCost = 0;
1493 Value *SpeculatedStoreValue = nullptr;
1494 StoreInst *SpeculatedStore = nullptr;
1495 for (BasicBlock::iterator BBI = ThenBB->begin(),
1496 BBE = std::prev(ThenBB->end());
1497 BBI != BBE; ++BBI) {
1498 Instruction *I = BBI;
1500 if (isa<DbgInfoIntrinsic>(I))
1503 // Only speculatively execution a single instruction (not counting the
1504 // terminator) for now.
1506 if (SpeculationCost > 1)
1509 // Don't hoist the instruction if it's unsafe or expensive.
1510 if (!isSafeToSpeculativelyExecute(I, DL) &&
1511 !(HoistCondStores &&
1512 (SpeculatedStoreValue = isSafeToSpeculateStore(I, BB, ThenBB,
1515 if (!SpeculatedStoreValue &&
1516 ComputeSpeculationCost(I, DL, TTI) > PHINodeFoldingThreshold *
1517 TargetTransformInfo::TCC_Basic)
1520 // Store the store speculation candidate.
1521 if (SpeculatedStoreValue)
1522 SpeculatedStore = cast<StoreInst>(I);
1524 // Do not hoist the instruction if any of its operands are defined but not
1525 // used in BB. The transformation will prevent the operand from
1526 // being sunk into the use block.
1527 for (User::op_iterator i = I->op_begin(), e = I->op_end();
1529 Instruction *OpI = dyn_cast<Instruction>(*i);
1530 if (!OpI || OpI->getParent() != BB ||
1531 OpI->mayHaveSideEffects())
1532 continue; // Not a candidate for sinking.
1534 ++SinkCandidateUseCounts[OpI];
1538 // Consider any sink candidates which are only used in CondBB as costs for
1539 // speculation. Note, while we iterate over a DenseMap here, we are summing
1540 // and so iteration order isn't significant.
1541 for (SmallDenseMap<Instruction *, unsigned, 4>::iterator I =
1542 SinkCandidateUseCounts.begin(), E = SinkCandidateUseCounts.end();
1544 if (I->first->getNumUses() == I->second) {
1546 if (SpeculationCost > 1)
1550 // Check that the PHI nodes can be converted to selects.
1551 bool HaveRewritablePHIs = false;
1552 for (BasicBlock::iterator I = EndBB->begin();
1553 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1554 Value *OrigV = PN->getIncomingValueForBlock(BB);
1555 Value *ThenV = PN->getIncomingValueForBlock(ThenBB);
1557 // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf.
1558 // Skip PHIs which are trivial.
1562 // Don't convert to selects if we could remove undefined behavior instead.
1563 if (passingValueIsAlwaysUndefined(OrigV, PN) ||
1564 passingValueIsAlwaysUndefined(ThenV, PN))
1567 HaveRewritablePHIs = true;
1568 ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
1569 ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
1570 if (!OrigCE && !ThenCE)
1571 continue; // Known safe and cheap.
1573 if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE, DL)) ||
1574 (OrigCE && !isSafeToSpeculativelyExecute(OrigCE, DL)))
1576 unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE, DL, TTI) : 0;
1577 unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE, DL, TTI) : 0;
1578 unsigned MaxCost = 2 * PHINodeFoldingThreshold *
1579 TargetTransformInfo::TCC_Basic;
1580 if (OrigCost + ThenCost > MaxCost)
1583 // Account for the cost of an unfolded ConstantExpr which could end up
1584 // getting expanded into Instructions.
1585 // FIXME: This doesn't account for how many operations are combined in the
1586 // constant expression.
1588 if (SpeculationCost > 1)
1592 // If there are no PHIs to process, bail early. This helps ensure idempotence
1594 if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue))
1597 // If we get here, we can hoist the instruction and if-convert.
1598 DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
1600 // Insert a select of the value of the speculated store.
1601 if (SpeculatedStoreValue) {
1602 IRBuilder<true, NoFolder> Builder(BI);
1603 Value *TrueV = SpeculatedStore->getValueOperand();
1604 Value *FalseV = SpeculatedStoreValue;
1606 std::swap(TrueV, FalseV);
1607 Value *S = Builder.CreateSelect(BrCond, TrueV, FalseV, TrueV->getName() +
1608 "." + FalseV->getName());
1609 SpeculatedStore->setOperand(0, S);
1612 // Hoist the instructions.
1613 BB->getInstList().splice(BI, ThenBB->getInstList(), ThenBB->begin(),
1614 std::prev(ThenBB->end()));
1616 // Insert selects and rewrite the PHI operands.
1617 IRBuilder<true, NoFolder> Builder(BI);
1618 for (BasicBlock::iterator I = EndBB->begin();
1619 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1620 unsigned OrigI = PN->getBasicBlockIndex(BB);
1621 unsigned ThenI = PN->getBasicBlockIndex(ThenBB);
1622 Value *OrigV = PN->getIncomingValue(OrigI);
1623 Value *ThenV = PN->getIncomingValue(ThenI);
1625 // Skip PHIs which are trivial.
1629 // Create a select whose true value is the speculatively executed value and
1630 // false value is the preexisting value. Swap them if the branch
1631 // destinations were inverted.
1632 Value *TrueV = ThenV, *FalseV = OrigV;
1634 std::swap(TrueV, FalseV);
1635 Value *V = Builder.CreateSelect(BrCond, TrueV, FalseV,
1636 TrueV->getName() + "." + FalseV->getName());
1637 PN->setIncomingValue(OrigI, V);
1638 PN->setIncomingValue(ThenI, V);
1645 /// \returns True if this block contains a CallInst with the NoDuplicate
1647 static bool HasNoDuplicateCall(const BasicBlock *BB) {
1648 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1649 const CallInst *CI = dyn_cast<CallInst>(I);
1652 if (CI->cannotDuplicate())
1658 /// BlockIsSimpleEnoughToThreadThrough - Return true if we can thread a branch
1659 /// across this block.
1660 static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
1661 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
1664 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1665 if (isa<DbgInfoIntrinsic>(BBI))
1667 if (Size > 10) return false; // Don't clone large BB's.
1670 // We can only support instructions that do not define values that are
1671 // live outside of the current basic block.
1672 for (User *U : BBI->users()) {
1673 Instruction *UI = cast<Instruction>(U);
1674 if (UI->getParent() != BB || isa<PHINode>(UI)) return false;
1677 // Looks ok, continue checking.
1683 /// FoldCondBranchOnPHI - If we have a conditional branch on a PHI node value
1684 /// that is defined in the same block as the branch and if any PHI entries are
1685 /// constants, thread edges corresponding to that entry to be branches to their
1686 /// ultimate destination.
1687 static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout *DL) {
1688 BasicBlock *BB = BI->getParent();
1689 PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
1690 // NOTE: we currently cannot transform this case if the PHI node is used
1691 // outside of the block.
1692 if (!PN || PN->getParent() != BB || !PN->hasOneUse())
1695 // Degenerate case of a single entry PHI.
1696 if (PN->getNumIncomingValues() == 1) {
1697 FoldSingleEntryPHINodes(PN->getParent());
1701 // Now we know that this block has multiple preds and two succs.
1702 if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
1704 if (HasNoDuplicateCall(BB)) return false;
1706 // Okay, this is a simple enough basic block. See if any phi values are
1708 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1709 ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
1710 if (!CB || !CB->getType()->isIntegerTy(1)) continue;
1712 // Okay, we now know that all edges from PredBB should be revectored to
1713 // branch to RealDest.
1714 BasicBlock *PredBB = PN->getIncomingBlock(i);
1715 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
1717 if (RealDest == BB) continue; // Skip self loops.
1718 // Skip if the predecessor's terminator is an indirect branch.
1719 if (isa<IndirectBrInst>(PredBB->getTerminator())) continue;
1721 // The dest block might have PHI nodes, other predecessors and other
1722 // difficult cases. Instead of being smart about this, just insert a new
1723 // block that jumps to the destination block, effectively splitting
1724 // the edge we are about to create.
1725 BasicBlock *EdgeBB = BasicBlock::Create(BB->getContext(),
1726 RealDest->getName()+".critedge",
1727 RealDest->getParent(), RealDest);
1728 BranchInst::Create(RealDest, EdgeBB);
1730 // Update PHI nodes.
1731 AddPredecessorToBlock(RealDest, EdgeBB, BB);
1733 // BB may have instructions that are being threaded over. Clone these
1734 // instructions into EdgeBB. We know that there will be no uses of the
1735 // cloned instructions outside of EdgeBB.
1736 BasicBlock::iterator InsertPt = EdgeBB->begin();
1737 DenseMap<Value*, Value*> TranslateMap; // Track translated values.
1738 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1739 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
1740 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
1743 // Clone the instruction.
1744 Instruction *N = BBI->clone();
1745 if (BBI->hasName()) N->setName(BBI->getName()+".c");
1747 // Update operands due to translation.
1748 for (User::op_iterator i = N->op_begin(), e = N->op_end();
1750 DenseMap<Value*, Value*>::iterator PI = TranslateMap.find(*i);
1751 if (PI != TranslateMap.end())
1755 // Check for trivial simplification.
1756 if (Value *V = SimplifyInstruction(N, DL)) {
1757 TranslateMap[BBI] = V;
1758 delete N; // Instruction folded away, don't need actual inst
1760 // Insert the new instruction into its new home.
1761 EdgeBB->getInstList().insert(InsertPt, N);
1762 if (!BBI->use_empty())
1763 TranslateMap[BBI] = N;
1767 // Loop over all of the edges from PredBB to BB, changing them to branch
1768 // to EdgeBB instead.
1769 TerminatorInst *PredBBTI = PredBB->getTerminator();
1770 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
1771 if (PredBBTI->getSuccessor(i) == BB) {
1772 BB->removePredecessor(PredBB);
1773 PredBBTI->setSuccessor(i, EdgeBB);
1776 // Recurse, simplifying any other constants.
1777 return FoldCondBranchOnPHI(BI, DL) | true;
1783 /// FoldTwoEntryPHINode - Given a BB that starts with the specified two-entry
1784 /// PHI node, see if we can eliminate it.
1785 static bool FoldTwoEntryPHINode(PHINode *PN, const DataLayout *DL,
1786 const TargetTransformInfo &TTI) {
1787 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
1788 // statement", which has a very simple dominance structure. Basically, we
1789 // are trying to find the condition that is being branched on, which
1790 // subsequently causes this merge to happen. We really want control
1791 // dependence information for this check, but simplifycfg can't keep it up
1792 // to date, and this catches most of the cases we care about anyway.
1793 BasicBlock *BB = PN->getParent();
1794 BasicBlock *IfTrue, *IfFalse;
1795 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
1797 // Don't bother if the branch will be constant folded trivially.
1798 isa<ConstantInt>(IfCond))
1801 // Okay, we found that we can merge this two-entry phi node into a select.
1802 // Doing so would require us to fold *all* two entry phi nodes in this block.
1803 // At some point this becomes non-profitable (particularly if the target
1804 // doesn't support cmov's). Only do this transformation if there are two or
1805 // fewer PHI nodes in this block.
1806 unsigned NumPhis = 0;
1807 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
1811 // Loop over the PHI's seeing if we can promote them all to select
1812 // instructions. While we are at it, keep track of the instructions
1813 // that need to be moved to the dominating block.
1814 SmallPtrSet<Instruction*, 4> AggressiveInsts;
1815 unsigned MaxCostVal0 = PHINodeFoldingThreshold,
1816 MaxCostVal1 = PHINodeFoldingThreshold;
1817 MaxCostVal0 *= TargetTransformInfo::TCC_Basic;
1818 MaxCostVal1 *= TargetTransformInfo::TCC_Basic;
1820 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
1821 PHINode *PN = cast<PHINode>(II++);
1822 if (Value *V = SimplifyInstruction(PN, DL)) {
1823 PN->replaceAllUsesWith(V);
1824 PN->eraseFromParent();
1828 if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts,
1829 MaxCostVal0, DL, TTI) ||
1830 !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts,
1831 MaxCostVal1, DL, TTI))
1835 // If we folded the first phi, PN dangles at this point. Refresh it. If
1836 // we ran out of PHIs then we simplified them all.
1837 PN = dyn_cast<PHINode>(BB->begin());
1838 if (!PN) return true;
1840 // Don't fold i1 branches on PHIs which contain binary operators. These can
1841 // often be turned into switches and other things.
1842 if (PN->getType()->isIntegerTy(1) &&
1843 (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
1844 isa<BinaryOperator>(PN->getIncomingValue(1)) ||
1845 isa<BinaryOperator>(IfCond)))
1848 // If we all PHI nodes are promotable, check to make sure that all
1849 // instructions in the predecessor blocks can be promoted as well. If
1850 // not, we won't be able to get rid of the control flow, so it's not
1851 // worth promoting to select instructions.
1852 BasicBlock *DomBlock = nullptr;
1853 BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
1854 BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
1855 if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
1858 DomBlock = *pred_begin(IfBlock1);
1859 for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I)
1860 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
1861 // This is not an aggressive instruction that we can promote.
1862 // Because of this, we won't be able to get rid of the control
1863 // flow, so the xform is not worth it.
1868 if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
1871 DomBlock = *pred_begin(IfBlock2);
1872 for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I)
1873 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
1874 // This is not an aggressive instruction that we can promote.
1875 // Because of this, we won't be able to get rid of the control
1876 // flow, so the xform is not worth it.
1881 DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: "
1882 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
1884 // If we can still promote the PHI nodes after this gauntlet of tests,
1885 // do all of the PHI's now.
1886 Instruction *InsertPt = DomBlock->getTerminator();
1887 IRBuilder<true, NoFolder> Builder(InsertPt);
1889 // Move all 'aggressive' instructions, which are defined in the
1890 // conditional parts of the if's up to the dominating block.
1892 DomBlock->getInstList().splice(InsertPt,
1893 IfBlock1->getInstList(), IfBlock1->begin(),
1894 IfBlock1->getTerminator());
1896 DomBlock->getInstList().splice(InsertPt,
1897 IfBlock2->getInstList(), IfBlock2->begin(),
1898 IfBlock2->getTerminator());
1900 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1901 // Change the PHI node into a select instruction.
1902 Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1903 Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
1906 cast<SelectInst>(Builder.CreateSelect(IfCond, TrueVal, FalseVal, ""));
1907 PN->replaceAllUsesWith(NV);
1909 PN->eraseFromParent();
1912 // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
1913 // has been flattened. Change DomBlock to jump directly to our new block to
1914 // avoid other simplifycfg's kicking in on the diamond.
1915 TerminatorInst *OldTI = DomBlock->getTerminator();
1916 Builder.SetInsertPoint(OldTI);
1917 Builder.CreateBr(BB);
1918 OldTI->eraseFromParent();
1922 /// SimplifyCondBranchToTwoReturns - If we found a conditional branch that goes
1923 /// to two returning blocks, try to merge them together into one return,
1924 /// introducing a select if the return values disagree.
1925 static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
1926 IRBuilder<> &Builder) {
1927 assert(BI->isConditional() && "Must be a conditional branch");
1928 BasicBlock *TrueSucc = BI->getSuccessor(0);
1929 BasicBlock *FalseSucc = BI->getSuccessor(1);
1930 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
1931 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
1933 // Check to ensure both blocks are empty (just a return) or optionally empty
1934 // with PHI nodes. If there are other instructions, merging would cause extra
1935 // computation on one path or the other.
1936 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
1938 if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
1941 Builder.SetInsertPoint(BI);
1942 // Okay, we found a branch that is going to two return nodes. If
1943 // there is no return value for this function, just change the
1944 // branch into a return.
1945 if (FalseRet->getNumOperands() == 0) {
1946 TrueSucc->removePredecessor(BI->getParent());
1947 FalseSucc->removePredecessor(BI->getParent());
1948 Builder.CreateRetVoid();
1949 EraseTerminatorInstAndDCECond(BI);
1953 // Otherwise, figure out what the true and false return values are
1954 // so we can insert a new select instruction.
1955 Value *TrueValue = TrueRet->getReturnValue();
1956 Value *FalseValue = FalseRet->getReturnValue();
1958 // Unwrap any PHI nodes in the return blocks.
1959 if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
1960 if (TVPN->getParent() == TrueSucc)
1961 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
1962 if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
1963 if (FVPN->getParent() == FalseSucc)
1964 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
1966 // In order for this transformation to be safe, we must be able to
1967 // unconditionally execute both operands to the return. This is
1968 // normally the case, but we could have a potentially-trapping
1969 // constant expression that prevents this transformation from being
1971 if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
1974 if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
1978 // Okay, we collected all the mapped values and checked them for sanity, and
1979 // defined to really do this transformation. First, update the CFG.
1980 TrueSucc->removePredecessor(BI->getParent());
1981 FalseSucc->removePredecessor(BI->getParent());
1983 // Insert select instructions where needed.
1984 Value *BrCond = BI->getCondition();
1986 // Insert a select if the results differ.
1987 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
1988 } else if (isa<UndefValue>(TrueValue)) {
1989 TrueValue = FalseValue;
1991 TrueValue = Builder.CreateSelect(BrCond, TrueValue,
1992 FalseValue, "retval");
1996 Value *RI = !TrueValue ?
1997 Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
2001 DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
2002 << "\n " << *BI << "NewRet = " << *RI
2003 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc);
2005 EraseTerminatorInstAndDCECond(BI);
2010 /// ExtractBranchMetadata - Given a conditional BranchInstruction, retrieve the
2011 /// probabilities of the branch taking each edge. Fills in the two APInt
2012 /// parameters and return true, or returns false if no or invalid metadata was
2014 static bool ExtractBranchMetadata(BranchInst *BI,
2015 uint64_t &ProbTrue, uint64_t &ProbFalse) {
2016 assert(BI->isConditional() &&
2017 "Looking for probabilities on unconditional branch?");
2018 MDNode *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
2019 if (!ProfileData || ProfileData->getNumOperands() != 3) return false;
2020 ConstantInt *CITrue =
2021 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
2022 ConstantInt *CIFalse =
2023 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
2024 if (!CITrue || !CIFalse) return false;
2025 ProbTrue = CITrue->getValue().getZExtValue();
2026 ProbFalse = CIFalse->getValue().getZExtValue();
2030 /// checkCSEInPredecessor - Return true if the given instruction is available
2031 /// in its predecessor block. If yes, the instruction will be removed.
2033 static bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB) {
2034 if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
2036 for (BasicBlock::iterator I = PB->begin(), E = PB->end(); I != E; I++) {
2037 Instruction *PBI = &*I;
2038 // Check whether Inst and PBI generate the same value.
2039 if (Inst->isIdenticalTo(PBI)) {
2040 Inst->replaceAllUsesWith(PBI);
2041 Inst->eraseFromParent();
2048 /// FoldBranchToCommonDest - If this basic block is simple enough, and if a
2049 /// predecessor branches to us and one of our successors, fold the block into
2050 /// the predecessor and use logical operations to pick the right destination.
2051 bool llvm::FoldBranchToCommonDest(BranchInst *BI, const DataLayout *DL,
2052 unsigned BonusInstThreshold) {
2053 BasicBlock *BB = BI->getParent();
2055 Instruction *Cond = nullptr;
2056 if (BI->isConditional())
2057 Cond = dyn_cast<Instruction>(BI->getCondition());
2059 // For unconditional branch, check for a simple CFG pattern, where
2060 // BB has a single predecessor and BB's successor is also its predecessor's
2061 // successor. If such pattern exisits, check for CSE between BB and its
2063 if (BasicBlock *PB = BB->getSinglePredecessor())
2064 if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
2065 if (PBI->isConditional() &&
2066 (BI->getSuccessor(0) == PBI->getSuccessor(0) ||
2067 BI->getSuccessor(0) == PBI->getSuccessor(1))) {
2068 for (BasicBlock::iterator I = BB->begin(), E = BB->end();
2070 Instruction *Curr = I++;
2071 if (isa<CmpInst>(Curr)) {
2075 // Quit if we can't remove this instruction.
2076 if (!checkCSEInPredecessor(Curr, PB))
2085 if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
2086 Cond->getParent() != BB || !Cond->hasOneUse())
2089 // Make sure the instruction after the condition is the cond branch.
2090 BasicBlock::iterator CondIt = Cond; ++CondIt;
2092 // Ignore dbg intrinsics.
2093 while (isa<DbgInfoIntrinsic>(CondIt)) ++CondIt;
2098 // Only allow this transformation if computing the condition doesn't involve
2099 // too many instructions and these involved instructions can be executed
2100 // unconditionally. We denote all involved instructions except the condition
2101 // as "bonus instructions", and only allow this transformation when the
2102 // number of the bonus instructions does not exceed a certain threshold.
2103 unsigned NumBonusInsts = 0;
2104 for (auto I = BB->begin(); Cond != I; ++I) {
2105 // Ignore dbg intrinsics.
2106 if (isa<DbgInfoIntrinsic>(I))
2108 if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(I, DL))
2110 // I has only one use and can be executed unconditionally.
2111 Instruction *User = dyn_cast<Instruction>(I->user_back());
2112 if (User == nullptr || User->getParent() != BB)
2114 // I is used in the same BB. Since BI uses Cond and doesn't have more slots
2115 // to use any other instruction, User must be an instruction between next(I)
2118 // Early exits once we reach the limit.
2119 if (NumBonusInsts > BonusInstThreshold)
2123 // Cond is known to be a compare or binary operator. Check to make sure that
2124 // neither operand is a potentially-trapping constant expression.
2125 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
2128 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
2132 // Finally, don't infinitely unroll conditional loops.
2133 BasicBlock *TrueDest = BI->getSuccessor(0);
2134 BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr;
2135 if (TrueDest == BB || FalseDest == BB)
2138 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2139 BasicBlock *PredBlock = *PI;
2140 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
2142 // Check that we have two conditional branches. If there is a PHI node in
2143 // the common successor, verify that the same value flows in from both
2145 SmallVector<PHINode*, 4> PHIs;
2146 if (!PBI || PBI->isUnconditional() ||
2147 (BI->isConditional() &&
2148 !SafeToMergeTerminators(BI, PBI)) ||
2149 (!BI->isConditional() &&
2150 !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs)))
2153 // Determine if the two branches share a common destination.
2154 Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd;
2155 bool InvertPredCond = false;
2157 if (BI->isConditional()) {
2158 if (PBI->getSuccessor(0) == TrueDest)
2159 Opc = Instruction::Or;
2160 else if (PBI->getSuccessor(1) == FalseDest)
2161 Opc = Instruction::And;
2162 else if (PBI->getSuccessor(0) == FalseDest)
2163 Opc = Instruction::And, InvertPredCond = true;
2164 else if (PBI->getSuccessor(1) == TrueDest)
2165 Opc = Instruction::Or, InvertPredCond = true;
2169 if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest)
2173 DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
2174 IRBuilder<> Builder(PBI);
2176 // If we need to invert the condition in the pred block to match, do so now.
2177 if (InvertPredCond) {
2178 Value *NewCond = PBI->getCondition();
2180 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
2181 CmpInst *CI = cast<CmpInst>(NewCond);
2182 CI->setPredicate(CI->getInversePredicate());
2184 NewCond = Builder.CreateNot(NewCond,
2185 PBI->getCondition()->getName()+".not");
2188 PBI->setCondition(NewCond);
2189 PBI->swapSuccessors();
2192 // If we have bonus instructions, clone them into the predecessor block.
2193 // Note that there may be mutliple predecessor blocks, so we cannot move
2194 // bonus instructions to a predecessor block.
2195 ValueToValueMapTy VMap; // maps original values to cloned values
2196 // We already make sure Cond is the last instruction before BI. Therefore,
2197 // every instructions before Cond other than DbgInfoIntrinsic are bonus
2199 for (auto BonusInst = BB->begin(); Cond != BonusInst; ++BonusInst) {
2200 if (isa<DbgInfoIntrinsic>(BonusInst))
2202 Instruction *NewBonusInst = BonusInst->clone();
2203 RemapInstruction(NewBonusInst, VMap,
2204 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
2205 VMap[BonusInst] = NewBonusInst;
2207 // If we moved a load, we cannot any longer claim any knowledge about
2208 // its potential value. The previous information might have been valid
2209 // only given the branch precondition.
2210 // For an analogous reason, we must also drop all the metadata whose
2211 // semantics we don't understand.
2212 NewBonusInst->dropUnknownMetadata(LLVMContext::MD_dbg);
2214 PredBlock->getInstList().insert(PBI, NewBonusInst);
2215 NewBonusInst->takeName(BonusInst);
2216 BonusInst->setName(BonusInst->getName() + ".old");
2219 // Clone Cond into the predecessor basic block, and or/and the
2220 // two conditions together.
2221 Instruction *New = Cond->clone();
2222 RemapInstruction(New, VMap,
2223 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
2224 PredBlock->getInstList().insert(PBI, New);
2225 New->takeName(Cond);
2226 Cond->setName(New->getName() + ".old");
2228 if (BI->isConditional()) {
2229 Instruction *NewCond =
2230 cast<Instruction>(Builder.CreateBinOp(Opc, PBI->getCondition(),
2232 PBI->setCondition(NewCond);
2234 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2235 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2237 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2239 SmallVector<uint64_t, 8> NewWeights;
2241 if (PBI->getSuccessor(0) == BB) {
2242 if (PredHasWeights && SuccHasWeights) {
2243 // PBI: br i1 %x, BB, FalseDest
2244 // BI: br i1 %y, TrueDest, FalseDest
2245 //TrueWeight is TrueWeight for PBI * TrueWeight for BI.
2246 NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
2247 //FalseWeight is FalseWeight for PBI * TotalWeight for BI +
2248 // TrueWeight for PBI * FalseWeight for BI.
2249 // We assume that total weights of a BranchInst can fit into 32 bits.
2250 // Therefore, we will not have overflow using 64-bit arithmetic.
2251 NewWeights.push_back(PredFalseWeight * (SuccFalseWeight +
2252 SuccTrueWeight) + PredTrueWeight * SuccFalseWeight);
2254 AddPredecessorToBlock(TrueDest, PredBlock, BB);
2255 PBI->setSuccessor(0, TrueDest);
2257 if (PBI->getSuccessor(1) == BB) {
2258 if (PredHasWeights && SuccHasWeights) {
2259 // PBI: br i1 %x, TrueDest, BB
2260 // BI: br i1 %y, TrueDest, FalseDest
2261 //TrueWeight is TrueWeight for PBI * TotalWeight for BI +
2262 // FalseWeight for PBI * TrueWeight for BI.
2263 NewWeights.push_back(PredTrueWeight * (SuccFalseWeight +
2264 SuccTrueWeight) + PredFalseWeight * SuccTrueWeight);
2265 //FalseWeight is FalseWeight for PBI * FalseWeight for BI.
2266 NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
2268 AddPredecessorToBlock(FalseDest, PredBlock, BB);
2269 PBI->setSuccessor(1, FalseDest);
2271 if (NewWeights.size() == 2) {
2272 // Halve the weights if any of them cannot fit in an uint32_t
2273 FitWeights(NewWeights);
2275 SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),NewWeights.end());
2276 PBI->setMetadata(LLVMContext::MD_prof,
2277 MDBuilder(BI->getContext()).
2278 createBranchWeights(MDWeights));
2280 PBI->setMetadata(LLVMContext::MD_prof, nullptr);
2282 // Update PHI nodes in the common successors.
2283 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
2284 ConstantInt *PBI_C = cast<ConstantInt>(
2285 PHIs[i]->getIncomingValueForBlock(PBI->getParent()));
2286 assert(PBI_C->getType()->isIntegerTy(1));
2287 Instruction *MergedCond = nullptr;
2288 if (PBI->getSuccessor(0) == TrueDest) {
2289 // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value)
2290 // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value)
2291 // is false: !PBI_Cond and BI_Value
2292 Instruction *NotCond =
2293 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2296 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2301 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2302 PBI->getCondition(), MergedCond,
2305 // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C)
2306 // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond)
2307 // is false: PBI_Cond and BI_Value
2309 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2310 PBI->getCondition(), New,
2312 if (PBI_C->isOne()) {
2313 Instruction *NotCond =
2314 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2317 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2318 NotCond, MergedCond,
2323 PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()),
2326 // Change PBI from Conditional to Unconditional.
2327 BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI);
2328 EraseTerminatorInstAndDCECond(PBI);
2332 // TODO: If BB is reachable from all paths through PredBlock, then we
2333 // could replace PBI's branch probabilities with BI's.
2335 // Copy any debug value intrinsics into the end of PredBlock.
2336 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
2337 if (isa<DbgInfoIntrinsic>(*I))
2338 I->clone()->insertBefore(PBI);
2345 /// SimplifyCondBranchToCondBranch - If we have a conditional branch as a
2346 /// predecessor of another block, this function tries to simplify it. We know
2347 /// that PBI and BI are both conditional branches, and BI is in one of the
2348 /// successor blocks of PBI - PBI branches to BI.
2349 static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI) {
2350 assert(PBI->isConditional() && BI->isConditional());
2351 BasicBlock *BB = BI->getParent();
2353 // If this block ends with a branch instruction, and if there is a
2354 // predecessor that ends on a branch of the same condition, make
2355 // this conditional branch redundant.
2356 if (PBI->getCondition() == BI->getCondition() &&
2357 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2358 // Okay, the outcome of this conditional branch is statically
2359 // knowable. If this block had a single pred, handle specially.
2360 if (BB->getSinglePredecessor()) {
2361 // Turn this into a branch on constant.
2362 bool CondIsTrue = PBI->getSuccessor(0) == BB;
2363 BI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
2365 return true; // Nuke the branch on constant.
2368 // Otherwise, if there are multiple predecessors, insert a PHI that merges
2369 // in the constant and simplify the block result. Subsequent passes of
2370 // simplifycfg will thread the block.
2371 if (BlockIsSimpleEnoughToThreadThrough(BB)) {
2372 pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
2373 PHINode *NewPN = PHINode::Create(Type::getInt1Ty(BB->getContext()),
2374 std::distance(PB, PE),
2375 BI->getCondition()->getName() + ".pr",
2377 // Okay, we're going to insert the PHI node. Since PBI is not the only
2378 // predecessor, compute the PHI'd conditional value for all of the preds.
2379 // Any predecessor where the condition is not computable we keep symbolic.
2380 for (pred_iterator PI = PB; PI != PE; ++PI) {
2381 BasicBlock *P = *PI;
2382 if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) &&
2383 PBI != BI && PBI->isConditional() &&
2384 PBI->getCondition() == BI->getCondition() &&
2385 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2386 bool CondIsTrue = PBI->getSuccessor(0) == BB;
2387 NewPN->addIncoming(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
2390 NewPN->addIncoming(BI->getCondition(), P);
2394 BI->setCondition(NewPN);
2399 // If this is a conditional branch in an empty block, and if any
2400 // predecessors are a conditional branch to one of our destinations,
2401 // fold the conditions into logical ops and one cond br.
2402 BasicBlock::iterator BBI = BB->begin();
2403 // Ignore dbg intrinsics.
2404 while (isa<DbgInfoIntrinsic>(BBI))
2410 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
2415 if (PBI->getSuccessor(0) == BI->getSuccessor(0))
2417 else if (PBI->getSuccessor(0) == BI->getSuccessor(1))
2418 PBIOp = 0, BIOp = 1;
2419 else if (PBI->getSuccessor(1) == BI->getSuccessor(0))
2420 PBIOp = 1, BIOp = 0;
2421 else if (PBI->getSuccessor(1) == BI->getSuccessor(1))
2426 // Check to make sure that the other destination of this branch
2427 // isn't BB itself. If so, this is an infinite loop that will
2428 // keep getting unwound.
2429 if (PBI->getSuccessor(PBIOp) == BB)
2432 // Do not perform this transformation if it would require
2433 // insertion of a large number of select instructions. For targets
2434 // without predication/cmovs, this is a big pessimization.
2436 // Also do not perform this transformation if any phi node in the common
2437 // destination block can trap when reached by BB or PBB (PR17073). In that
2438 // case, it would be unsafe to hoist the operation into a select instruction.
2440 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
2441 unsigned NumPhis = 0;
2442 for (BasicBlock::iterator II = CommonDest->begin();
2443 isa<PHINode>(II); ++II, ++NumPhis) {
2444 if (NumPhis > 2) // Disable this xform.
2447 PHINode *PN = cast<PHINode>(II);
2448 Value *BIV = PN->getIncomingValueForBlock(BB);
2449 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV))
2453 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2454 Value *PBIV = PN->getIncomingValue(PBBIdx);
2455 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV))
2460 // Finally, if everything is ok, fold the branches to logical ops.
2461 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
2463 DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
2464 << "AND: " << *BI->getParent());
2467 // If OtherDest *is* BB, then BB is a basic block with a single conditional
2468 // branch in it, where one edge (OtherDest) goes back to itself but the other
2469 // exits. We don't *know* that the program avoids the infinite loop
2470 // (even though that seems likely). If we do this xform naively, we'll end up
2471 // recursively unpeeling the loop. Since we know that (after the xform is
2472 // done) that the block *is* infinite if reached, we just make it an obviously
2473 // infinite loop with no cond branch.
2474 if (OtherDest == BB) {
2475 // Insert it at the end of the function, because it's either code,
2476 // or it won't matter if it's hot. :)
2477 BasicBlock *InfLoopBlock = BasicBlock::Create(BB->getContext(),
2478 "infloop", BB->getParent());
2479 BranchInst::Create(InfLoopBlock, InfLoopBlock);
2480 OtherDest = InfLoopBlock;
2483 DEBUG(dbgs() << *PBI->getParent()->getParent());
2485 // BI may have other predecessors. Because of this, we leave
2486 // it alone, but modify PBI.
2488 // Make sure we get to CommonDest on True&True directions.
2489 Value *PBICond = PBI->getCondition();
2490 IRBuilder<true, NoFolder> Builder(PBI);
2492 PBICond = Builder.CreateNot(PBICond, PBICond->getName()+".not");
2494 Value *BICond = BI->getCondition();
2496 BICond = Builder.CreateNot(BICond, BICond->getName()+".not");
2498 // Merge the conditions.
2499 Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
2501 // Modify PBI to branch on the new condition to the new dests.
2502 PBI->setCondition(Cond);
2503 PBI->setSuccessor(0, CommonDest);
2504 PBI->setSuccessor(1, OtherDest);
2506 // Update branch weight for PBI.
2507 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2508 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2510 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2512 if (PredHasWeights && SuccHasWeights) {
2513 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
2514 uint64_t PredOther = PBIOp ?PredTrueWeight : PredFalseWeight;
2515 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
2516 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
2517 // The weight to CommonDest should be PredCommon * SuccTotal +
2518 // PredOther * SuccCommon.
2519 // The weight to OtherDest should be PredOther * SuccOther.
2520 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) +
2521 PredOther * SuccCommon,
2522 PredOther * SuccOther};
2523 // Halve the weights if any of them cannot fit in an uint32_t
2524 FitWeights(NewWeights);
2526 PBI->setMetadata(LLVMContext::MD_prof,
2527 MDBuilder(BI->getContext())
2528 .createBranchWeights(NewWeights[0], NewWeights[1]));
2531 // OtherDest may have phi nodes. If so, add an entry from PBI's
2532 // block that are identical to the entries for BI's block.
2533 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
2535 // We know that the CommonDest already had an edge from PBI to
2536 // it. If it has PHIs though, the PHIs may have different
2537 // entries for BB and PBI's BB. If so, insert a select to make
2540 for (BasicBlock::iterator II = CommonDest->begin();
2541 (PN = dyn_cast<PHINode>(II)); ++II) {
2542 Value *BIV = PN->getIncomingValueForBlock(BB);
2543 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2544 Value *PBIV = PN->getIncomingValue(PBBIdx);
2546 // Insert a select in PBI to pick the right value.
2547 Value *NV = cast<SelectInst>
2548 (Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName()+".mux"));
2549 PN->setIncomingValue(PBBIdx, NV);
2553 DEBUG(dbgs() << "INTO: " << *PBI->getParent());
2554 DEBUG(dbgs() << *PBI->getParent()->getParent());
2556 // This basic block is probably dead. We know it has at least
2557 // one fewer predecessor.
2561 // SimplifyTerminatorOnSelect - Simplifies a terminator by replacing it with a
2562 // branch to TrueBB if Cond is true or to FalseBB if Cond is false.
2563 // Takes care of updating the successors and removing the old terminator.
2564 // Also makes sure not to introduce new successors by assuming that edges to
2565 // non-successor TrueBBs and FalseBBs aren't reachable.
2566 static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond,
2567 BasicBlock *TrueBB, BasicBlock *FalseBB,
2568 uint32_t TrueWeight,
2569 uint32_t FalseWeight){
2570 // Remove any superfluous successor edges from the CFG.
2571 // First, figure out which successors to preserve.
2572 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
2574 BasicBlock *KeepEdge1 = TrueBB;
2575 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
2577 // Then remove the rest.
2578 for (unsigned I = 0, E = OldTerm->getNumSuccessors(); I != E; ++I) {
2579 BasicBlock *Succ = OldTerm->getSuccessor(I);
2580 // Make sure only to keep exactly one copy of each edge.
2581 if (Succ == KeepEdge1)
2582 KeepEdge1 = nullptr;
2583 else if (Succ == KeepEdge2)
2584 KeepEdge2 = nullptr;
2586 Succ->removePredecessor(OldTerm->getParent());
2589 IRBuilder<> Builder(OldTerm);
2590 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
2592 // Insert an appropriate new terminator.
2593 if (!KeepEdge1 && !KeepEdge2) {
2594 if (TrueBB == FalseBB)
2595 // We were only looking for one successor, and it was present.
2596 // Create an unconditional branch to it.
2597 Builder.CreateBr(TrueBB);
2599 // We found both of the successors we were looking for.
2600 // Create a conditional branch sharing the condition of the select.
2601 BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
2602 if (TrueWeight != FalseWeight)
2603 NewBI->setMetadata(LLVMContext::MD_prof,
2604 MDBuilder(OldTerm->getContext()).
2605 createBranchWeights(TrueWeight, FalseWeight));
2607 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
2608 // Neither of the selected blocks were successors, so this
2609 // terminator must be unreachable.
2610 new UnreachableInst(OldTerm->getContext(), OldTerm);
2612 // One of the selected values was a successor, but the other wasn't.
2613 // Insert an unconditional branch to the one that was found;
2614 // the edge to the one that wasn't must be unreachable.
2616 // Only TrueBB was found.
2617 Builder.CreateBr(TrueBB);
2619 // Only FalseBB was found.
2620 Builder.CreateBr(FalseBB);
2623 EraseTerminatorInstAndDCECond(OldTerm);
2627 // SimplifySwitchOnSelect - Replaces
2628 // (switch (select cond, X, Y)) on constant X, Y
2629 // with a branch - conditional if X and Y lead to distinct BBs,
2630 // unconditional otherwise.
2631 static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
2632 // Check for constant integer values in the select.
2633 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
2634 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
2635 if (!TrueVal || !FalseVal)
2638 // Find the relevant condition and destinations.
2639 Value *Condition = Select->getCondition();
2640 BasicBlock *TrueBB = SI->findCaseValue(TrueVal).getCaseSuccessor();
2641 BasicBlock *FalseBB = SI->findCaseValue(FalseVal).getCaseSuccessor();
2643 // Get weight for TrueBB and FalseBB.
2644 uint32_t TrueWeight = 0, FalseWeight = 0;
2645 SmallVector<uint64_t, 8> Weights;
2646 bool HasWeights = HasBranchWeights(SI);
2648 GetBranchWeights(SI, Weights);
2649 if (Weights.size() == 1 + SI->getNumCases()) {
2650 TrueWeight = (uint32_t)Weights[SI->findCaseValue(TrueVal).
2651 getSuccessorIndex()];
2652 FalseWeight = (uint32_t)Weights[SI->findCaseValue(FalseVal).
2653 getSuccessorIndex()];
2657 // Perform the actual simplification.
2658 return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB,
2659 TrueWeight, FalseWeight);
2662 // SimplifyIndirectBrOnSelect - Replaces
2663 // (indirectbr (select cond, blockaddress(@fn, BlockA),
2664 // blockaddress(@fn, BlockB)))
2666 // (br cond, BlockA, BlockB).
2667 static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
2668 // Check that both operands of the select are block addresses.
2669 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
2670 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
2674 // Extract the actual blocks.
2675 BasicBlock *TrueBB = TBA->getBasicBlock();
2676 BasicBlock *FalseBB = FBA->getBasicBlock();
2678 // Perform the actual simplification.
2679 return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB,
2683 /// TryToSimplifyUncondBranchWithICmpInIt - This is called when we find an icmp
2684 /// instruction (a seteq/setne with a constant) as the only instruction in a
2685 /// block that ends with an uncond branch. We are looking for a very specific
2686 /// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
2687 /// this case, we merge the first two "or's of icmp" into a switch, but then the
2688 /// default value goes to an uncond block with a seteq in it, we get something
2691 /// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
2693 /// %tmp = icmp eq i8 %A, 92
2696 /// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
2698 /// We prefer to split the edge to 'end' so that there is a true/false entry to
2699 /// the PHI, merging the third icmp into the switch.
2700 static bool TryToSimplifyUncondBranchWithICmpInIt(
2701 ICmpInst *ICI, IRBuilder<> &Builder, const TargetTransformInfo &TTI,
2702 unsigned BonusInstThreshold, const DataLayout *DL, AssumptionCache *AC) {
2703 BasicBlock *BB = ICI->getParent();
2705 // If the block has any PHIs in it or the icmp has multiple uses, it is too
2707 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) return false;
2709 Value *V = ICI->getOperand(0);
2710 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
2712 // The pattern we're looking for is where our only predecessor is a switch on
2713 // 'V' and this block is the default case for the switch. In this case we can
2714 // fold the compared value into the switch to simplify things.
2715 BasicBlock *Pred = BB->getSinglePredecessor();
2716 if (!Pred || !isa<SwitchInst>(Pred->getTerminator())) return false;
2718 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
2719 if (SI->getCondition() != V)
2722 // If BB is reachable on a non-default case, then we simply know the value of
2723 // V in this block. Substitute it and constant fold the icmp instruction
2725 if (SI->getDefaultDest() != BB) {
2726 ConstantInt *VVal = SI->findCaseDest(BB);
2727 assert(VVal && "Should have a unique destination value");
2728 ICI->setOperand(0, VVal);
2730 if (Value *V = SimplifyInstruction(ICI, DL)) {
2731 ICI->replaceAllUsesWith(V);
2732 ICI->eraseFromParent();
2734 // BB is now empty, so it is likely to simplify away.
2735 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
2738 // Ok, the block is reachable from the default dest. If the constant we're
2739 // comparing exists in one of the other edges, then we can constant fold ICI
2741 if (SI->findCaseValue(Cst) != SI->case_default()) {
2743 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
2744 V = ConstantInt::getFalse(BB->getContext());
2746 V = ConstantInt::getTrue(BB->getContext());
2748 ICI->replaceAllUsesWith(V);
2749 ICI->eraseFromParent();
2750 // BB is now empty, so it is likely to simplify away.
2751 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
2754 // The use of the icmp has to be in the 'end' block, by the only PHI node in
2756 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
2757 PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
2758 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
2759 isa<PHINode>(++BasicBlock::iterator(PHIUse)))
2762 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
2764 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
2765 Constant *NewCst = ConstantInt::getFalse(BB->getContext());
2767 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
2768 std::swap(DefaultCst, NewCst);
2770 // Replace ICI (which is used by the PHI for the default value) with true or
2771 // false depending on if it is EQ or NE.
2772 ICI->replaceAllUsesWith(DefaultCst);
2773 ICI->eraseFromParent();
2775 // Okay, the switch goes to this block on a default value. Add an edge from
2776 // the switch to the merge point on the compared value.
2777 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "switch.edge",
2778 BB->getParent(), BB);
2779 SmallVector<uint64_t, 8> Weights;
2780 bool HasWeights = HasBranchWeights(SI);
2782 GetBranchWeights(SI, Weights);
2783 if (Weights.size() == 1 + SI->getNumCases()) {
2784 // Split weight for default case to case for "Cst".
2785 Weights[0] = (Weights[0]+1) >> 1;
2786 Weights.push_back(Weights[0]);
2788 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
2789 SI->setMetadata(LLVMContext::MD_prof,
2790 MDBuilder(SI->getContext()).
2791 createBranchWeights(MDWeights));
2794 SI->addCase(Cst, NewBB);
2796 // NewBB branches to the phi block, add the uncond branch and the phi entry.
2797 Builder.SetInsertPoint(NewBB);
2798 Builder.SetCurrentDebugLocation(SI->getDebugLoc());
2799 Builder.CreateBr(SuccBlock);
2800 PHIUse->addIncoming(NewCst, NewBB);
2804 /// SimplifyBranchOnICmpChain - The specified branch is a conditional branch.
2805 /// Check to see if it is branching on an or/and chain of icmp instructions, and
2806 /// fold it into a switch instruction if so.
2807 static bool SimplifyBranchOnICmpChain(BranchInst *BI, const DataLayout *DL,
2808 IRBuilder<> &Builder) {
2809 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
2810 if (!Cond) return false;
2812 // Change br (X == 0 | X == 1), T, F into a switch instruction.
2813 // If this is a bunch of seteq's or'd together, or if it's a bunch of
2814 // 'setne's and'ed together, collect them.
2816 // Try to gather values from a chain of and/or to be turned into a switch
2817 ConstantComparesGatherer ConstantCompare(Cond, DL);
2818 // Unpack the result
2819 SmallVectorImpl<ConstantInt*> &Values = ConstantCompare.Vals;
2820 Value *CompVal = ConstantCompare.CompValue;
2821 unsigned UsedICmps = ConstantCompare.UsedICmps;
2822 Value *ExtraCase = ConstantCompare.Extra;
2824 // If we didn't have a multiply compared value, fail.
2825 if (!CompVal) return false;
2827 // Avoid turning single icmps into a switch.
2831 bool TrueWhenEqual = (Cond->getOpcode() == Instruction::Or);
2833 // There might be duplicate constants in the list, which the switch
2834 // instruction can't handle, remove them now.
2835 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
2836 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
2838 // If Extra was used, we require at least two switch values to do the
2839 // transformation. A switch with one value is just an cond branch.
2840 if (ExtraCase && Values.size() < 2) return false;
2842 // TODO: Preserve branch weight metadata, similarly to how
2843 // FoldValueComparisonIntoPredecessors preserves it.
2845 // Figure out which block is which destination.
2846 BasicBlock *DefaultBB = BI->getSuccessor(1);
2847 BasicBlock *EdgeBB = BI->getSuccessor(0);
2848 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
2850 BasicBlock *BB = BI->getParent();
2852 DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
2853 << " cases into SWITCH. BB is:\n" << *BB);
2855 // If there are any extra values that couldn't be folded into the switch
2856 // then we evaluate them with an explicit branch first. Split the block
2857 // right before the condbr to handle it.
2859 BasicBlock *NewBB = BB->splitBasicBlock(BI, "switch.early.test");
2860 // Remove the uncond branch added to the old block.
2861 TerminatorInst *OldTI = BB->getTerminator();
2862 Builder.SetInsertPoint(OldTI);
2865 Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
2867 Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
2869 OldTI->eraseFromParent();
2871 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
2872 // for the edge we just added.
2873 AddPredecessorToBlock(EdgeBB, BB, NewBB);
2875 DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
2876 << "\nEXTRABB = " << *BB);
2880 Builder.SetInsertPoint(BI);
2881 // Convert pointer to int before we switch.
2882 if (CompVal->getType()->isPointerTy()) {
2883 assert(DL && "Cannot switch on pointer without DataLayout");
2884 CompVal = Builder.CreatePtrToInt(CompVal,
2885 DL->getIntPtrType(CompVal->getType()),
2889 // Create the new switch instruction now.
2890 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
2892 // Add all of the 'cases' to the switch instruction.
2893 for (unsigned i = 0, e = Values.size(); i != e; ++i)
2894 New->addCase(Values[i], EdgeBB);
2896 // We added edges from PI to the EdgeBB. As such, if there were any
2897 // PHI nodes in EdgeBB, they need entries to be added corresponding to
2898 // the number of edges added.
2899 for (BasicBlock::iterator BBI = EdgeBB->begin();
2900 isa<PHINode>(BBI); ++BBI) {
2901 PHINode *PN = cast<PHINode>(BBI);
2902 Value *InVal = PN->getIncomingValueForBlock(BB);
2903 for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
2904 PN->addIncoming(InVal, BB);
2907 // Erase the old branch instruction.
2908 EraseTerminatorInstAndDCECond(BI);
2910 DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
2914 bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
2915 // If this is a trivial landing pad that just continues unwinding the caught
2916 // exception then zap the landing pad, turning its invokes into calls.
2917 BasicBlock *BB = RI->getParent();
2918 LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI());
2919 if (RI->getValue() != LPInst)
2920 // Not a landing pad, or the resume is not unwinding the exception that
2921 // caused control to branch here.
2924 // Check that there are no other instructions except for debug intrinsics.
2925 BasicBlock::iterator I = LPInst, E = RI;
2927 if (!isa<DbgInfoIntrinsic>(I))
2930 // Turn all invokes that unwind here into calls and delete the basic block.
2931 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
2932 InvokeInst *II = cast<InvokeInst>((*PI++)->getTerminator());
2933 SmallVector<Value*, 8> Args(II->op_begin(), II->op_end() - 3);
2934 // Insert a call instruction before the invoke.
2935 CallInst *Call = CallInst::Create(II->getCalledValue(), Args, "", II);
2937 Call->setCallingConv(II->getCallingConv());
2938 Call->setAttributes(II->getAttributes());
2939 Call->setDebugLoc(II->getDebugLoc());
2941 // Anything that used the value produced by the invoke instruction now uses
2942 // the value produced by the call instruction. Note that we do this even
2943 // for void functions and calls with no uses so that the callgraph edge is
2945 II->replaceAllUsesWith(Call);
2946 BB->removePredecessor(II->getParent());
2948 // Insert a branch to the normal destination right before the invoke.
2949 BranchInst::Create(II->getNormalDest(), II);
2951 // Finally, delete the invoke instruction!
2952 II->eraseFromParent();
2955 // The landingpad is now unreachable. Zap it.
2956 BB->eraseFromParent();
2960 bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
2961 BasicBlock *BB = RI->getParent();
2962 if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
2964 // Find predecessors that end with branches.
2965 SmallVector<BasicBlock*, 8> UncondBranchPreds;
2966 SmallVector<BranchInst*, 8> CondBranchPreds;
2967 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2968 BasicBlock *P = *PI;
2969 TerminatorInst *PTI = P->getTerminator();
2970 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
2971 if (BI->isUnconditional())
2972 UncondBranchPreds.push_back(P);
2974 CondBranchPreds.push_back(BI);
2978 // If we found some, do the transformation!
2979 if (!UncondBranchPreds.empty() && DupRet) {
2980 while (!UncondBranchPreds.empty()) {
2981 BasicBlock *Pred = UncondBranchPreds.pop_back_val();
2982 DEBUG(dbgs() << "FOLDING: " << *BB
2983 << "INTO UNCOND BRANCH PRED: " << *Pred);
2984 (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
2987 // If we eliminated all predecessors of the block, delete the block now.
2989 // We know there are no successors, so just nuke the block.
2990 BB->eraseFromParent();
2995 // Check out all of the conditional branches going to this return
2996 // instruction. If any of them just select between returns, change the
2997 // branch itself into a select/return pair.
2998 while (!CondBranchPreds.empty()) {
2999 BranchInst *BI = CondBranchPreds.pop_back_val();
3001 // Check to see if the non-BB successor is also a return block.
3002 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
3003 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
3004 SimplifyCondBranchToTwoReturns(BI, Builder))
3010 bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
3011 BasicBlock *BB = UI->getParent();
3013 bool Changed = false;
3015 // If there are any instructions immediately before the unreachable that can
3016 // be removed, do so.
3017 while (UI != BB->begin()) {
3018 BasicBlock::iterator BBI = UI;
3020 // Do not delete instructions that can have side effects which might cause
3021 // the unreachable to not be reachable; specifically, calls and volatile
3022 // operations may have this effect.
3023 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break;
3025 if (BBI->mayHaveSideEffects()) {
3026 if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
3027 if (SI->isVolatile())
3029 } else if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
3030 if (LI->isVolatile())
3032 } else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
3033 if (RMWI->isVolatile())
3035 } else if (AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
3036 if (CXI->isVolatile())
3038 } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
3039 !isa<LandingPadInst>(BBI)) {
3042 // Note that deleting LandingPad's here is in fact okay, although it
3043 // involves a bit of subtle reasoning. If this inst is a LandingPad,
3044 // all the predecessors of this block will be the unwind edges of Invokes,
3045 // and we can therefore guarantee this block will be erased.
3048 // Delete this instruction (any uses are guaranteed to be dead)
3049 if (!BBI->use_empty())
3050 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
3051 BBI->eraseFromParent();
3055 // If the unreachable instruction is the first in the block, take a gander
3056 // at all of the predecessors of this instruction, and simplify them.
3057 if (&BB->front() != UI) return Changed;
3059 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
3060 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
3061 TerminatorInst *TI = Preds[i]->getTerminator();
3062 IRBuilder<> Builder(TI);
3063 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
3064 if (BI->isUnconditional()) {
3065 if (BI->getSuccessor(0) == BB) {
3066 new UnreachableInst(TI->getContext(), TI);
3067 TI->eraseFromParent();
3071 if (BI->getSuccessor(0) == BB) {
3072 Builder.CreateBr(BI->getSuccessor(1));
3073 EraseTerminatorInstAndDCECond(BI);
3074 } else if (BI->getSuccessor(1) == BB) {
3075 Builder.CreateBr(BI->getSuccessor(0));
3076 EraseTerminatorInstAndDCECond(BI);
3080 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
3081 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
3083 if (i.getCaseSuccessor() == BB) {
3084 BB->removePredecessor(SI->getParent());
3089 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
3090 if (II->getUnwindDest() == BB) {
3091 // Convert the invoke to a call instruction. This would be a good
3092 // place to note that the call does not throw though.
3093 BranchInst *BI = Builder.CreateBr(II->getNormalDest());
3094 II->removeFromParent(); // Take out of symbol table
3096 // Insert the call now...
3097 SmallVector<Value*, 8> Args(II->op_begin(), II->op_end()-3);
3098 Builder.SetInsertPoint(BI);
3099 CallInst *CI = Builder.CreateCall(II->getCalledValue(),
3100 Args, II->getName());
3101 CI->setCallingConv(II->getCallingConv());
3102 CI->setAttributes(II->getAttributes());
3103 // If the invoke produced a value, the call does now instead.
3104 II->replaceAllUsesWith(CI);
3111 // If this block is now dead, remove it.
3112 if (pred_empty(BB) &&
3113 BB != &BB->getParent()->getEntryBlock()) {
3114 // We know there are no successors, so just nuke the block.
3115 BB->eraseFromParent();
3122 static bool CasesAreContiguous(SmallVectorImpl<ConstantInt *> &Cases) {
3123 assert(Cases.size() >= 1);
3125 array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
3126 for (size_t I = 1, E = Cases.size(); I != E; ++I) {
3127 if (Cases[I - 1]->getValue() != Cases[I]->getValue() + 1)
3133 /// Turn a switch with two reachable destinations into an integer range
3134 /// comparison and branch.
3135 static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
3136 assert(SI->getNumCases() > 1 && "Degenerate switch?");
3139 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
3141 // Partition the cases into two sets with different destinations.
3142 BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr;
3143 BasicBlock *DestB = nullptr;
3144 SmallVector <ConstantInt *, 16> CasesA;
3145 SmallVector <ConstantInt *, 16> CasesB;
3147 for (SwitchInst::CaseIt I : SI->cases()) {
3148 BasicBlock *Dest = I.getCaseSuccessor();
3149 if (!DestA) DestA = Dest;
3150 if (Dest == DestA) {
3151 CasesA.push_back(I.getCaseValue());
3154 if (!DestB) DestB = Dest;
3155 if (Dest == DestB) {
3156 CasesB.push_back(I.getCaseValue());
3159 return false; // More than two destinations.
3162 assert(DestA && DestB && "Single-destination switch should have been folded.");
3163 assert(DestA != DestB);
3164 assert(DestB != SI->getDefaultDest());
3165 assert(!CasesB.empty() && "There must be non-default cases.");
3166 assert(!CasesA.empty() || HasDefault);
3168 // Figure out if one of the sets of cases form a contiguous range.
3169 SmallVectorImpl<ConstantInt *> *ContiguousCases = nullptr;
3170 BasicBlock *ContiguousDest = nullptr;
3171 BasicBlock *OtherDest = nullptr;
3172 if (!CasesA.empty() && CasesAreContiguous(CasesA)) {
3173 ContiguousCases = &CasesA;
3174 ContiguousDest = DestA;
3176 } else if (CasesAreContiguous(CasesB)) {
3177 ContiguousCases = &CasesB;
3178 ContiguousDest = DestB;
3183 // Start building the compare and branch.
3185 Constant *Offset = ConstantExpr::getNeg(ContiguousCases->back());
3186 Constant *NumCases = ConstantInt::get(Offset->getType(), ContiguousCases->size());
3188 Value *Sub = SI->getCondition();
3189 if (!Offset->isNullValue())
3190 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off");
3193 // If NumCases overflowed, then all possible values jump to the successor.
3194 if (NumCases->isNullValue() && !ContiguousCases->empty())
3195 Cmp = ConstantInt::getTrue(SI->getContext());
3197 Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
3198 BranchInst *NewBI = Builder.CreateCondBr(Cmp, ContiguousDest, OtherDest);
3200 // Update weight for the newly-created conditional branch.
3201 if (HasBranchWeights(SI)) {
3202 SmallVector<uint64_t, 8> Weights;
3203 GetBranchWeights(SI, Weights);
3204 if (Weights.size() == 1 + SI->getNumCases()) {
3205 uint64_t TrueWeight = 0;
3206 uint64_t FalseWeight = 0;
3207 for (size_t I = 0, E = Weights.size(); I != E; ++I) {
3208 if (SI->getSuccessor(I) == ContiguousDest)
3209 TrueWeight += Weights[I];
3211 FalseWeight += Weights[I];
3213 while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) {
3217 NewBI->setMetadata(LLVMContext::MD_prof,
3218 MDBuilder(SI->getContext()).createBranchWeights(
3219 (uint32_t)TrueWeight, (uint32_t)FalseWeight));
3223 // Prune obsolete incoming values off the successors' PHI nodes.
3224 for (auto BBI = ContiguousDest->begin(); isa<PHINode>(BBI); ++BBI) {
3225 unsigned PreviousEdges = ContiguousCases->size();
3226 if (ContiguousDest == SI->getDefaultDest()) ++PreviousEdges;
3227 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
3228 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
3230 for (auto BBI = OtherDest->begin(); isa<PHINode>(BBI); ++BBI) {
3231 unsigned PreviousEdges = SI->getNumCases() - ContiguousCases->size();
3232 if (OtherDest == SI->getDefaultDest()) ++PreviousEdges;
3233 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
3234 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
3238 SI->eraseFromParent();
3243 /// EliminateDeadSwitchCases - Compute masked bits for the condition of a switch
3244 /// and use it to remove dead cases.
3245 static bool EliminateDeadSwitchCases(SwitchInst *SI, const DataLayout *DL,
3246 AssumptionCache *AC) {
3247 Value *Cond = SI->getCondition();
3248 unsigned Bits = Cond->getType()->getIntegerBitWidth();
3249 APInt KnownZero(Bits, 0), KnownOne(Bits, 0);
3250 computeKnownBits(Cond, KnownZero, KnownOne, DL, 0, AC, SI);
3252 // Gather dead cases.
3253 SmallVector<ConstantInt*, 8> DeadCases;
3254 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
3255 if ((I.getCaseValue()->getValue() & KnownZero) != 0 ||
3256 (I.getCaseValue()->getValue() & KnownOne) != KnownOne) {
3257 DeadCases.push_back(I.getCaseValue());
3258 DEBUG(dbgs() << "SimplifyCFG: switch case '"
3259 << I.getCaseValue() << "' is dead.\n");
3263 SmallVector<uint64_t, 8> Weights;
3264 bool HasWeight = HasBranchWeights(SI);
3266 GetBranchWeights(SI, Weights);
3267 HasWeight = (Weights.size() == 1 + SI->getNumCases());
3270 // Remove dead cases from the switch.
3271 for (unsigned I = 0, E = DeadCases.size(); I != E; ++I) {
3272 SwitchInst::CaseIt Case = SI->findCaseValue(DeadCases[I]);
3273 assert(Case != SI->case_default() &&
3274 "Case was not found. Probably mistake in DeadCases forming.");
3276 std::swap(Weights[Case.getCaseIndex()+1], Weights.back());
3280 // Prune unused values from PHI nodes.
3281 Case.getCaseSuccessor()->removePredecessor(SI->getParent());
3282 SI->removeCase(Case);
3284 if (HasWeight && Weights.size() >= 2) {
3285 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
3286 SI->setMetadata(LLVMContext::MD_prof,
3287 MDBuilder(SI->getParent()->getContext()).
3288 createBranchWeights(MDWeights));
3291 return !DeadCases.empty();
3294 /// FindPHIForConditionForwarding - If BB would be eligible for simplification
3295 /// by TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
3296 /// by an unconditional branch), look at the phi node for BB in the successor
3297 /// block and see if the incoming value is equal to CaseValue. If so, return
3298 /// the phi node, and set PhiIndex to BB's index in the phi node.
3299 static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
3302 if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
3303 return nullptr; // BB must be empty to be a candidate for simplification.
3304 if (!BB->getSinglePredecessor())
3305 return nullptr; // BB must be dominated by the switch.
3307 BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
3308 if (!Branch || !Branch->isUnconditional())
3309 return nullptr; // Terminator must be unconditional branch.
3311 BasicBlock *Succ = Branch->getSuccessor(0);
3313 BasicBlock::iterator I = Succ->begin();
3314 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3315 int Idx = PHI->getBasicBlockIndex(BB);
3316 assert(Idx >= 0 && "PHI has no entry for predecessor?");
3318 Value *InValue = PHI->getIncomingValue(Idx);
3319 if (InValue != CaseValue) continue;
3328 /// ForwardSwitchConditionToPHI - Try to forward the condition of a switch
3329 /// instruction to a phi node dominated by the switch, if that would mean that
3330 /// some of the destination blocks of the switch can be folded away.
3331 /// Returns true if a change is made.
3332 static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
3333 typedef DenseMap<PHINode*, SmallVector<int,4> > ForwardingNodesMap;
3334 ForwardingNodesMap ForwardingNodes;
3336 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
3337 ConstantInt *CaseValue = I.getCaseValue();
3338 BasicBlock *CaseDest = I.getCaseSuccessor();
3341 PHINode *PHI = FindPHIForConditionForwarding(CaseValue, CaseDest,
3345 ForwardingNodes[PHI].push_back(PhiIndex);
3348 bool Changed = false;
3350 for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(),
3351 E = ForwardingNodes.end(); I != E; ++I) {
3352 PHINode *Phi = I->first;
3353 SmallVectorImpl<int> &Indexes = I->second;
3355 if (Indexes.size() < 2) continue;
3357 for (size_t I = 0, E = Indexes.size(); I != E; ++I)
3358 Phi->setIncomingValue(Indexes[I], SI->getCondition());
3365 /// ValidLookupTableConstant - Return true if the backend will be able to handle
3366 /// initializing an array of constants like C.
3367 static bool ValidLookupTableConstant(Constant *C) {
3368 if (C->isThreadDependent())
3370 if (C->isDLLImportDependent())
3373 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
3374 return CE->isGEPWithNoNotionalOverIndexing();
3376 return isa<ConstantFP>(C) ||
3377 isa<ConstantInt>(C) ||
3378 isa<ConstantPointerNull>(C) ||
3379 isa<GlobalValue>(C) ||
3383 /// LookupConstant - If V is a Constant, return it. Otherwise, try to look up
3384 /// its constant value in ConstantPool, returning 0 if it's not there.
3385 static Constant *LookupConstant(Value *V,
3386 const SmallDenseMap<Value*, Constant*>& ConstantPool) {
3387 if (Constant *C = dyn_cast<Constant>(V))
3389 return ConstantPool.lookup(V);
3392 /// ConstantFold - Try to fold instruction I into a constant. This works for
3393 /// simple instructions such as binary operations where both operands are
3394 /// constant or can be replaced by constants from the ConstantPool. Returns the
3395 /// resulting constant on success, 0 otherwise.
3397 ConstantFold(Instruction *I,
3398 const SmallDenseMap<Value *, Constant *> &ConstantPool,
3399 const DataLayout *DL) {
3400 if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
3401 Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
3404 if (A->isAllOnesValue())
3405 return LookupConstant(Select->getTrueValue(), ConstantPool);
3406 if (A->isNullValue())
3407 return LookupConstant(Select->getFalseValue(), ConstantPool);
3411 SmallVector<Constant *, 4> COps;
3412 for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
3413 if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
3419 if (CmpInst *Cmp = dyn_cast<CmpInst>(I))
3420 return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0],
3423 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), COps, DL);
3426 /// GetCaseResults - Try to determine the resulting constant values in phi nodes
3427 /// at the common destination basic block, *CommonDest, for one of the case
3428 /// destionations CaseDest corresponding to value CaseVal (0 for the default
3429 /// case), of a switch instruction SI.
3431 GetCaseResults(SwitchInst *SI,
3432 ConstantInt *CaseVal,
3433 BasicBlock *CaseDest,
3434 BasicBlock **CommonDest,
3435 SmallVectorImpl<std::pair<PHINode *, Constant *> > &Res,
3436 const DataLayout *DL) {
3437 // The block from which we enter the common destination.
3438 BasicBlock *Pred = SI->getParent();
3440 // If CaseDest is empty except for some side-effect free instructions through
3441 // which we can constant-propagate the CaseVal, continue to its successor.
3442 SmallDenseMap<Value*, Constant*> ConstantPool;
3443 ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
3444 for (BasicBlock::iterator I = CaseDest->begin(), E = CaseDest->end(); I != E;
3446 if (TerminatorInst *T = dyn_cast<TerminatorInst>(I)) {
3447 // If the terminator is a simple branch, continue to the next block.
3448 if (T->getNumSuccessors() != 1)
3451 CaseDest = T->getSuccessor(0);
3452 } else if (isa<DbgInfoIntrinsic>(I)) {
3453 // Skip debug intrinsic.
3455 } else if (Constant *C = ConstantFold(I, ConstantPool, DL)) {
3456 // Instruction is side-effect free and constant.
3458 // If the instruction has uses outside this block or a phi node slot for
3459 // the block, it is not safe to bypass the instruction since it would then
3460 // no longer dominate all its uses.
3461 for (auto &Use : I->uses()) {
3462 User *User = Use.getUser();
3463 if (Instruction *I = dyn_cast<Instruction>(User))
3464 if (I->getParent() == CaseDest)
3466 if (PHINode *Phi = dyn_cast<PHINode>(User))
3467 if (Phi->getIncomingBlock(Use) == CaseDest)
3472 ConstantPool.insert(std::make_pair(I, C));
3478 // If we did not have a CommonDest before, use the current one.
3480 *CommonDest = CaseDest;
3481 // If the destination isn't the common one, abort.
3482 if (CaseDest != *CommonDest)
3485 // Get the values for this case from phi nodes in the destination block.
3486 BasicBlock::iterator I = (*CommonDest)->begin();
3487 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3488 int Idx = PHI->getBasicBlockIndex(Pred);
3492 Constant *ConstVal = LookupConstant(PHI->getIncomingValue(Idx),
3497 // Be conservative about which kinds of constants we support.
3498 if (!ValidLookupTableConstant(ConstVal))
3501 Res.push_back(std::make_pair(PHI, ConstVal));
3504 return Res.size() > 0;
3507 // MapCaseToResult - Helper function used to
3508 // add CaseVal to the list of cases that generate Result.
3509 static void MapCaseToResult(ConstantInt *CaseVal,
3510 SwitchCaseResultVectorTy &UniqueResults,
3512 for (auto &I : UniqueResults) {
3513 if (I.first == Result) {
3514 I.second.push_back(CaseVal);
3518 UniqueResults.push_back(std::make_pair(Result,
3519 SmallVector<ConstantInt*, 4>(1, CaseVal)));
3522 // InitializeUniqueCases - Helper function that initializes a map containing
3523 // results for the PHI node of the common destination block for a switch
3524 // instruction. Returns false if multiple PHI nodes have been found or if
3525 // there is not a common destination block for the switch.
3526 static bool InitializeUniqueCases(
3527 SwitchInst *SI, const DataLayout *DL, PHINode *&PHI,
3528 BasicBlock *&CommonDest,
3529 SwitchCaseResultVectorTy &UniqueResults,
3530 Constant *&DefaultResult) {
3531 for (auto &I : SI->cases()) {
3532 ConstantInt *CaseVal = I.getCaseValue();
3534 // Resulting value at phi nodes for this case value.
3535 SwitchCaseResultsTy Results;
3536 if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results,
3540 // Only one value per case is permitted
3541 if (Results.size() > 1)
3543 MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second);
3545 // Check the PHI consistency.
3547 PHI = Results[0].first;
3548 else if (PHI != Results[0].first)
3551 // Find the default result value.
3552 SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults;
3553 BasicBlock *DefaultDest = SI->getDefaultDest();
3554 GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults,
3556 // If the default value is not found abort unless the default destination
3559 DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr;
3560 if ((!DefaultResult &&
3561 !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg())))
3567 // ConvertTwoCaseSwitch - Helper function that checks if it is possible to
3568 // transform a switch with only two cases (or two cases + default)
3569 // that produces a result into a value select.
3572 // case 10: %0 = icmp eq i32 %a, 10
3573 // return 10; %1 = select i1 %0, i32 10, i32 4
3574 // case 20: ----> %2 = icmp eq i32 %a, 20
3575 // return 2; %3 = select i1 %2, i32 2, i32 %1
3580 ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector,
3581 Constant *DefaultResult, Value *Condition,
3582 IRBuilder<> &Builder) {
3583 assert(ResultVector.size() == 2 &&
3584 "We should have exactly two unique results at this point");
3585 // If we are selecting between only two cases transform into a simple
3586 // select or a two-way select if default is possible.
3587 if (ResultVector[0].second.size() == 1 &&
3588 ResultVector[1].second.size() == 1) {
3589 ConstantInt *const FirstCase = ResultVector[0].second[0];
3590 ConstantInt *const SecondCase = ResultVector[1].second[0];
3592 bool DefaultCanTrigger = DefaultResult;
3593 Value *SelectValue = ResultVector[1].first;
3594 if (DefaultCanTrigger) {
3595 Value *const ValueCompare =
3596 Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp");
3597 SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first,
3598 DefaultResult, "switch.select");
3600 Value *const ValueCompare =
3601 Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp");
3602 return Builder.CreateSelect(ValueCompare, ResultVector[0].first, SelectValue,
3609 // RemoveSwitchAfterSelectConversion - Helper function to cleanup a switch
3610 // instruction that has been converted into a select, fixing up PHI nodes and
3612 static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI,
3614 IRBuilder<> &Builder) {
3615 BasicBlock *SelectBB = SI->getParent();
3616 while (PHI->getBasicBlockIndex(SelectBB) >= 0)
3617 PHI->removeIncomingValue(SelectBB);
3618 PHI->addIncoming(SelectValue, SelectBB);
3620 Builder.CreateBr(PHI->getParent());
3622 // Remove the switch.
3623 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
3624 BasicBlock *Succ = SI->getSuccessor(i);
3626 if (Succ == PHI->getParent())
3628 Succ->removePredecessor(SelectBB);
3630 SI->eraseFromParent();
3633 /// SwitchToSelect - If the switch is only used to initialize one or more
3634 /// phi nodes in a common successor block with only two different
3635 /// constant values, replace the switch with select.
3636 static bool SwitchToSelect(SwitchInst *SI, IRBuilder<> &Builder,
3637 const DataLayout *DL, AssumptionCache *AC) {
3638 Value *const Cond = SI->getCondition();
3639 PHINode *PHI = nullptr;
3640 BasicBlock *CommonDest = nullptr;
3641 Constant *DefaultResult;
3642 SwitchCaseResultVectorTy UniqueResults;
3643 // Collect all the cases that will deliver the same value from the switch.
3644 if (!InitializeUniqueCases(SI, DL, PHI, CommonDest, UniqueResults,
3647 // Selects choose between maximum two values.
3648 if (UniqueResults.size() != 2)
3650 assert(PHI != nullptr && "PHI for value select not found");
3652 Builder.SetInsertPoint(SI);
3653 Value *SelectValue = ConvertTwoCaseSwitch(
3655 DefaultResult, Cond, Builder);
3657 RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder);
3660 // The switch couldn't be converted into a select.
3665 /// SwitchLookupTable - This class represents a lookup table that can be used
3666 /// to replace a switch.
3667 class SwitchLookupTable {
3669 /// SwitchLookupTable - Create a lookup table to use as a switch replacement
3670 /// with the contents of Values, using DefaultValue to fill any holes in the
3672 SwitchLookupTable(Module &M,
3674 ConstantInt *Offset,
3675 const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values,
3676 Constant *DefaultValue,
3677 const DataLayout *DL);
3679 /// BuildLookup - Build instructions with Builder to retrieve the value at
3680 /// the position given by Index in the lookup table.
3681 Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
3683 /// WouldFitInRegister - Return true if a table with TableSize elements of
3684 /// type ElementType would fit in a target-legal register.
3685 static bool WouldFitInRegister(const DataLayout *DL,
3687 const Type *ElementType);
3690 // Depending on the contents of the table, it can be represented in
3693 // For tables where each element contains the same value, we just have to
3694 // store that single value and return it for each lookup.
3697 // For tables where there is a linear relationship between table index
3698 // and values. We calculate the result with a simple multiplication
3699 // and addition instead of a table lookup.
3702 // For small tables with integer elements, we can pack them into a bitmap
3703 // that fits into a target-legal register. Values are retrieved by
3704 // shift and mask operations.
3707 // The table is stored as an array of values. Values are retrieved by load
3708 // instructions from the table.
3712 // For SingleValueKind, this is the single value.
3713 Constant *SingleValue;
3715 // For BitMapKind, this is the bitmap.
3716 ConstantInt *BitMap;
3717 IntegerType *BitMapElementTy;
3719 // For LinearMapKind, these are the constants used to derive the value.
3720 ConstantInt *LinearOffset;
3721 ConstantInt *LinearMultiplier;
3723 // For ArrayKind, this is the array.
3724 GlobalVariable *Array;
3728 SwitchLookupTable::SwitchLookupTable(Module &M,
3730 ConstantInt *Offset,
3731 const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values,
3732 Constant *DefaultValue,
3733 const DataLayout *DL)
3734 : SingleValue(nullptr), BitMap(nullptr), BitMapElementTy(nullptr),
3735 LinearOffset(nullptr), LinearMultiplier(nullptr), Array(nullptr) {
3736 assert(Values.size() && "Can't build lookup table without values!");
3737 assert(TableSize >= Values.size() && "Can't fit values in table!");
3739 // If all values in the table are equal, this is that value.
3740 SingleValue = Values.begin()->second;
3742 Type *ValueType = Values.begin()->second->getType();
3744 // Build up the table contents.
3745 SmallVector<Constant*, 64> TableContents(TableSize);
3746 for (size_t I = 0, E = Values.size(); I != E; ++I) {
3747 ConstantInt *CaseVal = Values[I].first;
3748 Constant *CaseRes = Values[I].second;
3749 assert(CaseRes->getType() == ValueType);
3751 uint64_t Idx = (CaseVal->getValue() - Offset->getValue())
3753 TableContents[Idx] = CaseRes;
3755 if (CaseRes != SingleValue)
3756 SingleValue = nullptr;
3759 // Fill in any holes in the table with the default result.
3760 if (Values.size() < TableSize) {
3761 assert(DefaultValue &&
3762 "Need a default value to fill the lookup table holes.");
3763 assert(DefaultValue->getType() == ValueType);
3764 for (uint64_t I = 0; I < TableSize; ++I) {
3765 if (!TableContents[I])
3766 TableContents[I] = DefaultValue;
3769 if (DefaultValue != SingleValue)
3770 SingleValue = nullptr;
3773 // If each element in the table contains the same value, we only need to store
3774 // that single value.
3776 Kind = SingleValueKind;
3780 // Check if we can derive the value with a linear transformation from the
3782 if (isa<IntegerType>(ValueType)) {
3783 bool LinearMappingPossible = true;
3786 assert(TableSize >= 2 && "Should be a SingleValue table.");
3787 // Check if there is the same distance between two consecutive values.
3788 for (uint64_t I = 0; I < TableSize; ++I) {
3789 ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]);
3791 // This is an undef. We could deal with it, but undefs in lookup tables
3792 // are very seldom. It's probably not worth the additional complexity.
3793 LinearMappingPossible = false;
3796 APInt Val = ConstVal->getValue();
3798 APInt Dist = Val - PrevVal;
3801 } else if (Dist != DistToPrev) {
3802 LinearMappingPossible = false;
3808 if (LinearMappingPossible) {
3809 LinearOffset = cast<ConstantInt>(TableContents[0]);
3810 LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev);
3811 Kind = LinearMapKind;
3817 // If the type is integer and the table fits in a register, build a bitmap.
3818 if (WouldFitInRegister(DL, TableSize, ValueType)) {
3819 IntegerType *IT = cast<IntegerType>(ValueType);
3820 APInt TableInt(TableSize * IT->getBitWidth(), 0);
3821 for (uint64_t I = TableSize; I > 0; --I) {
3822 TableInt <<= IT->getBitWidth();
3823 // Insert values into the bitmap. Undef values are set to zero.
3824 if (!isa<UndefValue>(TableContents[I - 1])) {
3825 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
3826 TableInt |= Val->getValue().zext(TableInt.getBitWidth());
3829 BitMap = ConstantInt::get(M.getContext(), TableInt);
3830 BitMapElementTy = IT;
3836 // Store the table in an array.
3837 ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
3838 Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
3840 Array = new GlobalVariable(M, ArrayTy, /*constant=*/ true,
3841 GlobalVariable::PrivateLinkage,
3844 Array->setUnnamedAddr(true);
3848 Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
3850 case SingleValueKind:
3852 case LinearMapKind: {
3853 // Derive the result value from the input value.
3854 Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(),
3855 false, "switch.idx.cast");
3856 if (!LinearMultiplier->isOne())
3857 Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult");
3858 if (!LinearOffset->isZero())
3859 Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset");
3863 // Type of the bitmap (e.g. i59).
3864 IntegerType *MapTy = BitMap->getType();
3866 // Cast Index to the same type as the bitmap.
3867 // Note: The Index is <= the number of elements in the table, so
3868 // truncating it to the width of the bitmask is safe.
3869 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
3871 // Multiply the shift amount by the element width.
3872 ShiftAmt = Builder.CreateMul(ShiftAmt,
3873 ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
3877 Value *DownShifted = Builder.CreateLShr(BitMap, ShiftAmt,
3878 "switch.downshift");
3880 return Builder.CreateTrunc(DownShifted, BitMapElementTy,
3884 // Make sure the table index will not overflow when treated as signed.
3885 IntegerType *IT = cast<IntegerType>(Index->getType());
3886 uint64_t TableSize = Array->getInitializer()->getType()
3887 ->getArrayNumElements();
3888 if (TableSize > (1ULL << (IT->getBitWidth() - 1)))
3889 Index = Builder.CreateZExt(Index,
3890 IntegerType::get(IT->getContext(),
3891 IT->getBitWidth() + 1),
3892 "switch.tableidx.zext");
3894 Value *GEPIndices[] = { Builder.getInt32(0), Index };
3895 Value *GEP = Builder.CreateInBoundsGEP(Array, GEPIndices,
3897 return Builder.CreateLoad(GEP, "switch.load");
3900 llvm_unreachable("Unknown lookup table kind!");
3903 bool SwitchLookupTable::WouldFitInRegister(const DataLayout *DL,
3905 const Type *ElementType) {
3908 const IntegerType *IT = dyn_cast<IntegerType>(ElementType);
3911 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
3912 // are <= 15, we could try to narrow the type.
3914 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
3915 if (TableSize >= UINT_MAX/IT->getBitWidth())
3917 return DL->fitsInLegalInteger(TableSize * IT->getBitWidth());
3920 /// ShouldBuildLookupTable - Determine whether a lookup table should be built
3921 /// for this switch, based on the number of cases, size of the table and the
3922 /// types of the results.
3923 static bool ShouldBuildLookupTable(SwitchInst *SI,
3925 const TargetTransformInfo &TTI,
3926 const DataLayout *DL,
3927 const SmallDenseMap<PHINode*, Type*>& ResultTypes) {
3928 if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
3929 return false; // TableSize overflowed, or mul below might overflow.
3931 bool AllTablesFitInRegister = true;
3932 bool HasIllegalType = false;
3933 for (const auto &I : ResultTypes) {
3934 Type *Ty = I.second;
3936 // Saturate this flag to true.
3937 HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty);
3939 // Saturate this flag to false.
3940 AllTablesFitInRegister = AllTablesFitInRegister &&
3941 SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
3943 // If both flags saturate, we're done. NOTE: This *only* works with
3944 // saturating flags, and all flags have to saturate first due to the
3945 // non-deterministic behavior of iterating over a dense map.
3946 if (HasIllegalType && !AllTablesFitInRegister)
3950 // If each table would fit in a register, we should build it anyway.
3951 if (AllTablesFitInRegister)
3954 // Don't build a table that doesn't fit in-register if it has illegal types.
3958 // The table density should be at least 40%. This is the same criterion as for
3959 // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
3960 // FIXME: Find the best cut-off.
3961 return SI->getNumCases() * 10 >= TableSize * 4;
3964 /// Try to reuse the switch table index compare. Following pattern:
3966 /// if (idx < tablesize)
3967 /// r = table[idx]; // table does not contain default_value
3969 /// r = default_value;
3970 /// if (r != default_value)
3973 /// Is optimized to:
3975 /// cond = idx < tablesize;
3979 /// r = default_value;
3983 /// Jump threading will then eliminate the second if(cond).
3984 static void reuseTableCompare(User *PhiUser, BasicBlock *PhiBlock,
3985 BranchInst *RangeCheckBranch, Constant *DefaultValue,
3986 const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values) {
3988 ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser);
3992 // We require that the compare is in the same block as the phi so that jump
3993 // threading can do its work afterwards.
3994 if (CmpInst->getParent() != PhiBlock)
3997 Constant *CmpOp1 = dyn_cast<Constant>(CmpInst->getOperand(1));
4001 Value *RangeCmp = RangeCheckBranch->getCondition();
4002 Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType());
4003 Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType());
4005 // Check if the compare with the default value is constant true or false.
4006 Constant *DefaultConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
4007 DefaultValue, CmpOp1, true);
4008 if (DefaultConst != TrueConst && DefaultConst != FalseConst)
4011 // Check if the compare with the case values is distinct from the default
4013 for (auto ValuePair : Values) {
4014 Constant *CaseConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
4015 ValuePair.second, CmpOp1, true);
4016 if (!CaseConst || CaseConst == DefaultConst)
4018 assert((CaseConst == TrueConst || CaseConst == FalseConst) &&
4019 "Expect true or false as compare result.");
4022 // Check if the branch instruction dominates the phi node. It's a simple
4023 // dominance check, but sufficient for our needs.
4024 // Although this check is invariant in the calling loops, it's better to do it
4025 // at this late stage. Practically we do it at most once for a switch.
4026 BasicBlock *BranchBlock = RangeCheckBranch->getParent();
4027 for (auto PI = pred_begin(PhiBlock), E = pred_end(PhiBlock); PI != E; ++PI) {
4028 BasicBlock *Pred = *PI;
4029 if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock)
4033 if (DefaultConst == FalseConst) {
4034 // The compare yields the same result. We can replace it.
4035 CmpInst->replaceAllUsesWith(RangeCmp);
4036 ++NumTableCmpReuses;
4038 // The compare yields the same result, just inverted. We can replace it.
4039 Value *InvertedTableCmp = BinaryOperator::CreateXor(RangeCmp,
4040 ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp",
4042 CmpInst->replaceAllUsesWith(InvertedTableCmp);
4043 ++NumTableCmpReuses;
4047 /// SwitchToLookupTable - If the switch is only used to initialize one or more
4048 /// phi nodes in a common successor block with different constant values,
4049 /// replace the switch with lookup tables.
4050 static bool SwitchToLookupTable(SwitchInst *SI,
4051 IRBuilder<> &Builder,
4052 const TargetTransformInfo &TTI,
4053 const DataLayout* DL) {
4054 assert(SI->getNumCases() > 1 && "Degenerate switch?");
4056 // Only build lookup table when we have a target that supports it.
4057 if (!TTI.shouldBuildLookupTables())
4060 // FIXME: If the switch is too sparse for a lookup table, perhaps we could
4061 // split off a dense part and build a lookup table for that.
4063 // FIXME: This creates arrays of GEPs to constant strings, which means each
4064 // GEP needs a runtime relocation in PIC code. We should just build one big
4065 // string and lookup indices into that.
4067 // Ignore switches with less than three cases. Lookup tables will not make them
4068 // faster, so we don't analyze them.
4069 if (SI->getNumCases() < 3)
4072 // Figure out the corresponding result for each case value and phi node in the
4073 // common destination, as well as the the min and max case values.
4074 assert(SI->case_begin() != SI->case_end());
4075 SwitchInst::CaseIt CI = SI->case_begin();
4076 ConstantInt *MinCaseVal = CI.getCaseValue();
4077 ConstantInt *MaxCaseVal = CI.getCaseValue();
4079 BasicBlock *CommonDest = nullptr;
4080 typedef SmallVector<std::pair<ConstantInt*, Constant*>, 4> ResultListTy;
4081 SmallDenseMap<PHINode*, ResultListTy> ResultLists;
4082 SmallDenseMap<PHINode*, Constant*> DefaultResults;
4083 SmallDenseMap<PHINode*, Type*> ResultTypes;
4084 SmallVector<PHINode*, 4> PHIs;
4086 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
4087 ConstantInt *CaseVal = CI.getCaseValue();
4088 if (CaseVal->getValue().slt(MinCaseVal->getValue()))
4089 MinCaseVal = CaseVal;
4090 if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
4091 MaxCaseVal = CaseVal;
4093 // Resulting value at phi nodes for this case value.
4094 typedef SmallVector<std::pair<PHINode*, Constant*>, 4> ResultsTy;
4096 if (!GetCaseResults(SI, CaseVal, CI.getCaseSuccessor(), &CommonDest,
4100 // Append the result from this case to the list for each phi.
4101 for (const auto &I : Results) {
4102 PHINode *PHI = I.first;
4103 Constant *Value = I.second;
4104 if (!ResultLists.count(PHI))
4105 PHIs.push_back(PHI);
4106 ResultLists[PHI].push_back(std::make_pair(CaseVal, Value));
4110 // Keep track of the result types.
4111 for (PHINode *PHI : PHIs) {
4112 ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
4115 uint64_t NumResults = ResultLists[PHIs[0]].size();
4116 APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
4117 uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
4118 bool TableHasHoles = (NumResults < TableSize);
4120 // If the table has holes, we need a constant result for the default case
4121 // or a bitmask that fits in a register.
4122 SmallVector<std::pair<PHINode*, Constant*>, 4> DefaultResultsList;
4123 bool HasDefaultResults = GetCaseResults(SI, nullptr, SI->getDefaultDest(),
4124 &CommonDest, DefaultResultsList, DL);
4126 bool NeedMask = (TableHasHoles && !HasDefaultResults);
4128 // As an extra penalty for the validity test we require more cases.
4129 if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
4131 if (!(DL && DL->fitsInLegalInteger(TableSize)))
4135 for (const auto &I : DefaultResultsList) {
4136 PHINode *PHI = I.first;
4137 Constant *Result = I.second;
4138 DefaultResults[PHI] = Result;
4141 if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
4144 // Create the BB that does the lookups.
4145 Module &Mod = *CommonDest->getParent()->getParent();
4146 BasicBlock *LookupBB = BasicBlock::Create(Mod.getContext(),
4148 CommonDest->getParent(),
4151 // Compute the table index value.
4152 Builder.SetInsertPoint(SI);
4153 Value *TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal,
4156 // Compute the maximum table size representable by the integer type we are
4158 unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
4159 uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
4160 assert(MaxTableSize >= TableSize &&
4161 "It is impossible for a switch to have more entries than the max "
4162 "representable value of its input integer type's size.");
4164 // If the default destination is unreachable, or if the lookup table covers
4165 // all values of the conditional variable, branch directly to the lookup table
4166 // BB. Otherwise, check that the condition is within the case range.
4167 const bool DefaultIsReachable =
4168 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
4169 const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize);
4170 BranchInst *RangeCheckBranch = nullptr;
4172 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
4173 Builder.CreateBr(LookupBB);
4174 // We cached PHINodes in PHIs, to avoid accessing deleted PHINodes later,
4175 // do not delete PHINodes here.
4176 SI->getDefaultDest()->removePredecessor(SI->getParent(),
4177 /*DontDeleteUselessPHIs=*/true);
4179 Value *Cmp = Builder.CreateICmpULT(TableIndex, ConstantInt::get(
4180 MinCaseVal->getType(), TableSize));
4181 RangeCheckBranch = Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
4184 // Populate the BB that does the lookups.
4185 Builder.SetInsertPoint(LookupBB);
4188 // Before doing the lookup we do the hole check.
4189 // The LookupBB is therefore re-purposed to do the hole check
4190 // and we create a new LookupBB.
4191 BasicBlock *MaskBB = LookupBB;
4192 MaskBB->setName("switch.hole_check");
4193 LookupBB = BasicBlock::Create(Mod.getContext(),
4195 CommonDest->getParent(),
4198 // Make the mask's bitwidth at least 8bit and a power-of-2 to avoid
4199 // unnecessary illegal types.
4200 uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL));
4201 APInt MaskInt(TableSizePowOf2, 0);
4202 APInt One(TableSizePowOf2, 1);
4203 // Build bitmask; fill in a 1 bit for every case.
4204 const ResultListTy &ResultList = ResultLists[PHIs[0]];
4205 for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
4206 uint64_t Idx = (ResultList[I].first->getValue() -
4207 MinCaseVal->getValue()).getLimitedValue();
4208 MaskInt |= One << Idx;
4210 ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
4212 // Get the TableIndex'th bit of the bitmask.
4213 // If this bit is 0 (meaning hole) jump to the default destination,
4214 // else continue with table lookup.
4215 IntegerType *MapTy = TableMask->getType();
4216 Value *MaskIndex = Builder.CreateZExtOrTrunc(TableIndex, MapTy,
4217 "switch.maskindex");
4218 Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex,
4220 Value *LoBit = Builder.CreateTrunc(Shifted,
4221 Type::getInt1Ty(Mod.getContext()),
4223 Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
4225 Builder.SetInsertPoint(LookupBB);
4226 AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent());
4229 bool ReturnedEarly = false;
4230 for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
4231 PHINode *PHI = PHIs[I];
4232 const ResultListTy &ResultList = ResultLists[PHI];
4234 // If using a bitmask, use any value to fill the lookup table holes.
4235 Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
4236 SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL);
4238 Value *Result = Table.BuildLookup(TableIndex, Builder);
4240 // If the result is used to return immediately from the function, we want to
4241 // do that right here.
4242 if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
4243 PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) {
4244 Builder.CreateRet(Result);
4245 ReturnedEarly = true;
4249 // Do a small peephole optimization: re-use the switch table compare if
4251 if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) {
4252 BasicBlock *PhiBlock = PHI->getParent();
4253 // Search for compare instructions which use the phi.
4254 for (auto *User : PHI->users()) {
4255 reuseTableCompare(User, PhiBlock, RangeCheckBranch, DV, ResultList);
4259 PHI->addIncoming(Result, LookupBB);
4263 Builder.CreateBr(CommonDest);
4265 // Remove the switch.
4266 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
4267 BasicBlock *Succ = SI->getSuccessor(i);
4269 if (Succ == SI->getDefaultDest())
4271 Succ->removePredecessor(SI->getParent());
4273 SI->eraseFromParent();
4277 ++NumLookupTablesHoles;
4281 bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
4282 BasicBlock *BB = SI->getParent();
4284 if (isValueEqualityComparison(SI)) {
4285 // If we only have one predecessor, and if it is a branch on this value,
4286 // see if that predecessor totally determines the outcome of this switch.
4287 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
4288 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
4289 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
4291 Value *Cond = SI->getCondition();
4292 if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
4293 if (SimplifySwitchOnSelect(SI, Select))
4294 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
4296 // If the block only contains the switch, see if we can fold the block
4297 // away into any preds.
4298 BasicBlock::iterator BBI = BB->begin();
4299 // Ignore dbg intrinsics.
4300 while (isa<DbgInfoIntrinsic>(BBI))
4303 if (FoldValueComparisonIntoPredecessors(SI, Builder))
4304 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
4307 // Try to transform the switch into an icmp and a branch.
4308 if (TurnSwitchRangeIntoICmp(SI, Builder))
4309 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
4311 // Remove unreachable cases.
4312 if (EliminateDeadSwitchCases(SI, DL, AC))
4313 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
4315 if (SwitchToSelect(SI, Builder, DL, AC))
4316 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
4318 if (ForwardSwitchConditionToPHI(SI))
4319 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
4321 if (SwitchToLookupTable(SI, Builder, TTI, DL))
4322 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
4327 bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
4328 BasicBlock *BB = IBI->getParent();
4329 bool Changed = false;
4331 // Eliminate redundant destinations.
4332 SmallPtrSet<Value *, 8> Succs;
4333 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
4334 BasicBlock *Dest = IBI->getDestination(i);
4335 if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) {
4336 Dest->removePredecessor(BB);
4337 IBI->removeDestination(i);
4343 if (IBI->getNumDestinations() == 0) {
4344 // If the indirectbr has no successors, change it to unreachable.
4345 new UnreachableInst(IBI->getContext(), IBI);
4346 EraseTerminatorInstAndDCECond(IBI);
4350 if (IBI->getNumDestinations() == 1) {
4351 // If the indirectbr has one successor, change it to a direct branch.
4352 BranchInst::Create(IBI->getDestination(0), IBI);
4353 EraseTerminatorInstAndDCECond(IBI);
4357 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
4358 if (SimplifyIndirectBrOnSelect(IBI, SI))
4359 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
4364 bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder){
4365 BasicBlock *BB = BI->getParent();
4367 if (SinkCommon && SinkThenElseCodeToEnd(BI))
4370 // If the Terminator is the only non-phi instruction, simplify the block.
4371 BasicBlock::iterator I = BB->getFirstNonPHIOrDbg();
4372 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
4373 TryToSimplifyUncondBranchFromEmptyBlock(BB))
4376 // If the only instruction in the block is a seteq/setne comparison
4377 // against a constant, try to simplify the block.
4378 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
4379 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
4380 for (++I; isa<DbgInfoIntrinsic>(I); ++I)
4382 if (I->isTerminator() &&
4383 TryToSimplifyUncondBranchWithICmpInIt(ICI, Builder, TTI,
4384 BonusInstThreshold, DL, AC))
4388 // If this basic block is ONLY a compare and a branch, and if a predecessor
4389 // branches to us and our successor, fold the comparison into the
4390 // predecessor and use logical operations to update the incoming value
4391 // for PHI nodes in common successor.
4392 if (FoldBranchToCommonDest(BI, DL, BonusInstThreshold))
4393 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
4398 bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
4399 BasicBlock *BB = BI->getParent();
4401 // Conditional branch
4402 if (isValueEqualityComparison(BI)) {
4403 // If we only have one predecessor, and if it is a branch on this value,
4404 // see if that predecessor totally determines the outcome of this
4406 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
4407 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
4408 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
4410 // This block must be empty, except for the setcond inst, if it exists.
4411 // Ignore dbg intrinsics.
4412 BasicBlock::iterator I = BB->begin();
4413 // Ignore dbg intrinsics.
4414 while (isa<DbgInfoIntrinsic>(I))
4417 if (FoldValueComparisonIntoPredecessors(BI, Builder))
4418 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
4419 } else if (&*I == cast<Instruction>(BI->getCondition())){
4421 // Ignore dbg intrinsics.
4422 while (isa<DbgInfoIntrinsic>(I))
4424 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
4425 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
4429 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
4430 if (SimplifyBranchOnICmpChain(BI, DL, Builder))
4433 // If this basic block is ONLY a compare and a branch, and if a predecessor
4434 // branches to us and one of our successors, fold the comparison into the
4435 // predecessor and use logical operations to pick the right destination.
4436 if (FoldBranchToCommonDest(BI, DL, BonusInstThreshold))
4437 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
4439 // We have a conditional branch to two blocks that are only reachable
4440 // from BI. We know that the condbr dominates the two blocks, so see if
4441 // there is any identical code in the "then" and "else" blocks. If so, we
4442 // can hoist it up to the branching block.
4443 if (BI->getSuccessor(0)->getSinglePredecessor()) {
4444 if (BI->getSuccessor(1)->getSinglePredecessor()) {
4445 if (HoistThenElseCodeToIf(BI, DL))
4446 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
4448 // If Successor #1 has multiple preds, we may be able to conditionally
4449 // execute Successor #0 if it branches to Successor #1.
4450 TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
4451 if (Succ0TI->getNumSuccessors() == 1 &&
4452 Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
4453 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), DL, TTI))
4454 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
4456 } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
4457 // If Successor #0 has multiple preds, we may be able to conditionally
4458 // execute Successor #1 if it branches to Successor #0.
4459 TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
4460 if (Succ1TI->getNumSuccessors() == 1 &&
4461 Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
4462 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), DL, TTI))
4463 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
4466 // If this is a branch on a phi node in the current block, thread control
4467 // through this block if any PHI node entries are constants.
4468 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
4469 if (PN->getParent() == BI->getParent())
4470 if (FoldCondBranchOnPHI(BI, DL))
4471 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
4473 // Scan predecessor blocks for conditional branches.
4474 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
4475 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
4476 if (PBI != BI && PBI->isConditional())
4477 if (SimplifyCondBranchToCondBranch(PBI, BI))
4478 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AC) | true;
4483 /// Check if passing a value to an instruction will cause undefined behavior.
4484 static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
4485 Constant *C = dyn_cast<Constant>(V);
4492 if (C->isNullValue()) {
4493 // Only look at the first use, avoid hurting compile time with long uselists
4494 User *Use = *I->user_begin();
4496 // Now make sure that there are no instructions in between that can alter
4497 // control flow (eg. calls)
4498 for (BasicBlock::iterator i = ++BasicBlock::iterator(I); &*i != Use; ++i)
4499 if (i == I->getParent()->end() || i->mayHaveSideEffects())
4502 // Look through GEPs. A load from a GEP derived from NULL is still undefined
4503 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
4504 if (GEP->getPointerOperand() == I)
4505 return passingValueIsAlwaysUndefined(V, GEP);
4507 // Look through bitcasts.
4508 if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
4509 return passingValueIsAlwaysUndefined(V, BC);
4511 // Load from null is undefined.
4512 if (LoadInst *LI = dyn_cast<LoadInst>(Use))
4513 if (!LI->isVolatile())
4514 return LI->getPointerAddressSpace() == 0;
4516 // Store to null is undefined.
4517 if (StoreInst *SI = dyn_cast<StoreInst>(Use))
4518 if (!SI->isVolatile())
4519 return SI->getPointerAddressSpace() == 0 && SI->getPointerOperand() == I;
4524 /// If BB has an incoming value that will always trigger undefined behavior
4525 /// (eg. null pointer dereference), remove the branch leading here.
4526 static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
4527 for (BasicBlock::iterator i = BB->begin();
4528 PHINode *PHI = dyn_cast<PHINode>(i); ++i)
4529 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
4530 if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) {
4531 TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator();
4532 IRBuilder<> Builder(T);
4533 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
4534 BB->removePredecessor(PHI->getIncomingBlock(i));
4535 // Turn uncoditional branches into unreachables and remove the dead
4536 // destination from conditional branches.
4537 if (BI->isUnconditional())
4538 Builder.CreateUnreachable();
4540 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) :
4541 BI->getSuccessor(0));
4542 BI->eraseFromParent();
4545 // TODO: SwitchInst.
4551 bool SimplifyCFGOpt::run(BasicBlock *BB) {
4552 bool Changed = false;
4554 assert(BB && BB->getParent() && "Block not embedded in function!");
4555 assert(BB->getTerminator() && "Degenerate basic block encountered!");
4557 // Remove basic blocks that have no predecessors (except the entry block)...
4558 // or that just have themself as a predecessor. These are unreachable.
4559 if ((pred_empty(BB) &&
4560 BB != &BB->getParent()->getEntryBlock()) ||
4561 BB->getSinglePredecessor() == BB) {
4562 DEBUG(dbgs() << "Removing BB: \n" << *BB);
4563 DeleteDeadBlock(BB);
4567 // Check to see if we can constant propagate this terminator instruction
4569 Changed |= ConstantFoldTerminator(BB, true);
4571 // Check for and eliminate duplicate PHI nodes in this block.
4572 Changed |= EliminateDuplicatePHINodes(BB);
4574 // Check for and remove branches that will always cause undefined behavior.
4575 Changed |= removeUndefIntroducingPredecessor(BB);
4577 // Merge basic blocks into their predecessor if there is only one distinct
4578 // pred, and if there is only one distinct successor of the predecessor, and
4579 // if there are no PHI nodes.
4581 if (MergeBlockIntoPredecessor(BB))
4584 IRBuilder<> Builder(BB);
4586 // If there is a trivial two-entry PHI node in this basic block, and we can
4587 // eliminate it, do so now.
4588 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
4589 if (PN->getNumIncomingValues() == 2)
4590 Changed |= FoldTwoEntryPHINode(PN, DL, TTI);
4592 Builder.SetInsertPoint(BB->getTerminator());
4593 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
4594 if (BI->isUnconditional()) {
4595 if (SimplifyUncondBranch(BI, Builder)) return true;
4597 if (SimplifyCondBranch(BI, Builder)) return true;
4599 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
4600 if (SimplifyReturn(RI, Builder)) return true;
4601 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
4602 if (SimplifyResume(RI, Builder)) return true;
4603 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
4604 if (SimplifySwitch(SI, Builder)) return true;
4605 } else if (UnreachableInst *UI =
4606 dyn_cast<UnreachableInst>(BB->getTerminator())) {
4607 if (SimplifyUnreachable(UI)) return true;
4608 } else if (IndirectBrInst *IBI =
4609 dyn_cast<IndirectBrInst>(BB->getTerminator())) {
4610 if (SimplifyIndirectBr(IBI)) return true;
4616 /// SimplifyCFG - This function is used to do simplification of a CFG. For
4617 /// example, it adjusts branches to branches to eliminate the extra hop, it
4618 /// eliminates unreachable basic blocks, and does other "peephole" optimization
4619 /// of the CFG. It returns true if a modification was made.
4621 bool llvm::SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
4622 unsigned BonusInstThreshold, const DataLayout *DL,
4623 AssumptionCache *AC) {
4624 return SimplifyCFGOpt(TTI, BonusInstThreshold, DL, AC).run(BB);