1 //===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Peephole optimize the CFG.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Transforms/Utils/Local.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SetVector.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Analysis/ConstantFolding.h"
22 #include "llvm/Analysis/InstructionSimplify.h"
23 #include "llvm/Analysis/TargetTransformInfo.h"
24 #include "llvm/Analysis/ValueTracking.h"
25 #include "llvm/IR/CFG.h"
26 #include "llvm/IR/ConstantRange.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/GlobalVariable.h"
31 #include "llvm/IR/IRBuilder.h"
32 #include "llvm/IR/Instructions.h"
33 #include "llvm/IR/IntrinsicInst.h"
34 #include "llvm/IR/LLVMContext.h"
35 #include "llvm/IR/MDBuilder.h"
36 #include "llvm/IR/Metadata.h"
37 #include "llvm/IR/Module.h"
38 #include "llvm/IR/NoFolder.h"
39 #include "llvm/IR/Operator.h"
40 #include "llvm/IR/PatternMatch.h"
41 #include "llvm/IR/Type.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
46 #include "llvm/Transforms/Utils/Local.h"
47 #include "llvm/Transforms/Utils/ValueMapper.h"
52 using namespace PatternMatch;
54 #define DEBUG_TYPE "simplifycfg"
56 static cl::opt<unsigned>
57 PHINodeFoldingThreshold("phi-node-folding-threshold", cl::Hidden, cl::init(1),
58 cl::desc("Control the amount of phi node folding to perform (default = 1)"));
61 DupRet("simplifycfg-dup-ret", cl::Hidden, cl::init(false),
62 cl::desc("Duplicate return instructions into unconditional branches"));
65 SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
66 cl::desc("Sink common instructions down to the end block"));
68 static cl::opt<bool> HoistCondStores(
69 "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true),
70 cl::desc("Hoist conditional stores if an unconditional store precedes"));
72 STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
73 STATISTIC(NumLinearMaps, "Number of switch instructions turned into linear mapping");
74 STATISTIC(NumLookupTables, "Number of switch instructions turned into lookup tables");
75 STATISTIC(NumLookupTablesHoles, "Number of switch instructions turned into lookup tables (holes checked)");
76 STATISTIC(NumTableCmpReuses, "Number of reused switch table lookup compares");
77 STATISTIC(NumSinkCommons, "Number of common instructions sunk down to the end block");
78 STATISTIC(NumSpeculations, "Number of speculative executed instructions");
81 // The first field contains the value that the switch produces when a certain
82 // case group is selected, and the second field is a vector containing the cases
83 // composing the case group.
84 typedef SmallVector<std::pair<Constant *, SmallVector<ConstantInt *, 4>>, 2>
85 SwitchCaseResultVectorTy;
86 // The first field contains the phi node that generates a result of the switch
87 // and the second field contains the value generated for a certain case in the switch
89 typedef SmallVector<std::pair<PHINode *, Constant *>, 4> SwitchCaseResultsTy;
91 /// ValueEqualityComparisonCase - Represents a case of a switch.
92 struct ValueEqualityComparisonCase {
96 ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
97 : Value(Value), Dest(Dest) {}
99 bool operator<(ValueEqualityComparisonCase RHS) const {
100 // Comparing pointers is ok as we only rely on the order for uniquing.
101 return Value < RHS.Value;
104 bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
107 class SimplifyCFGOpt {
108 const TargetTransformInfo &TTI;
109 unsigned BonusInstThreshold;
110 const DataLayout *const DL;
111 AssumptionTracker *AT;
112 Value *isValueEqualityComparison(TerminatorInst *TI);
113 BasicBlock *GetValueEqualityComparisonCases(TerminatorInst *TI,
114 std::vector<ValueEqualityComparisonCase> &Cases);
115 bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
117 IRBuilder<> &Builder);
118 bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
119 IRBuilder<> &Builder);
121 bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder);
122 bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
123 bool SimplifyUnreachable(UnreachableInst *UI);
124 bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
125 bool SimplifyIndirectBr(IndirectBrInst *IBI);
126 bool SimplifyUncondBranch(BranchInst *BI, IRBuilder <> &Builder);
127 bool SimplifyCondBranch(BranchInst *BI, IRBuilder <>&Builder);
130 SimplifyCFGOpt(const TargetTransformInfo &TTI, unsigned BonusInstThreshold,
131 const DataLayout *DL, AssumptionTracker *AT)
132 : TTI(TTI), BonusInstThreshold(BonusInstThreshold), DL(DL), AT(AT) {}
133 bool run(BasicBlock *BB);
137 /// SafeToMergeTerminators - Return true if it is safe to merge these two
138 /// terminator instructions together.
140 static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
141 if (SI1 == SI2) return false; // Can't merge with self!
143 // It is not safe to merge these two switch instructions if they have a common
144 // successor, and if that successor has a PHI node, and if *that* PHI node has
145 // conflicting incoming values from the two switch blocks.
146 BasicBlock *SI1BB = SI1->getParent();
147 BasicBlock *SI2BB = SI2->getParent();
148 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
150 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
151 if (SI1Succs.count(*I))
152 for (BasicBlock::iterator BBI = (*I)->begin();
153 isa<PHINode>(BBI); ++BBI) {
154 PHINode *PN = cast<PHINode>(BBI);
155 if (PN->getIncomingValueForBlock(SI1BB) !=
156 PN->getIncomingValueForBlock(SI2BB))
163 /// isProfitableToFoldUnconditional - Return true if it is safe and profitable
164 /// to merge these two terminator instructions together, where SI1 is an
165 /// unconditional branch. PhiNodes will store all PHI nodes in common
168 static bool isProfitableToFoldUnconditional(BranchInst *SI1,
171 SmallVectorImpl<PHINode*> &PhiNodes) {
172 if (SI1 == SI2) return false; // Can't merge with self!
173 assert(SI1->isUnconditional() && SI2->isConditional());
175 // We fold the unconditional branch if we can easily update all PHI nodes in
176 // common successors:
177 // 1> We have a constant incoming value for the conditional branch;
178 // 2> We have "Cond" as the incoming value for the unconditional branch;
179 // 3> SI2->getCondition() and Cond have same operands.
180 CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition());
181 if (!Ci2) return false;
182 if (!(Cond->getOperand(0) == Ci2->getOperand(0) &&
183 Cond->getOperand(1) == Ci2->getOperand(1)) &&
184 !(Cond->getOperand(0) == Ci2->getOperand(1) &&
185 Cond->getOperand(1) == Ci2->getOperand(0)))
188 BasicBlock *SI1BB = SI1->getParent();
189 BasicBlock *SI2BB = SI2->getParent();
190 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
191 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
192 if (SI1Succs.count(*I))
193 for (BasicBlock::iterator BBI = (*I)->begin();
194 isa<PHINode>(BBI); ++BBI) {
195 PHINode *PN = cast<PHINode>(BBI);
196 if (PN->getIncomingValueForBlock(SI1BB) != Cond ||
197 !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB)))
199 PhiNodes.push_back(PN);
204 /// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will
205 /// now be entries in it from the 'NewPred' block. The values that will be
206 /// flowing into the PHI nodes will be the same as those coming in from
207 /// ExistPred, an existing predecessor of Succ.
208 static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
209 BasicBlock *ExistPred) {
210 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
213 for (BasicBlock::iterator I = Succ->begin();
214 (PN = dyn_cast<PHINode>(I)); ++I)
215 PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
218 /// ComputeSpeculationCost - Compute an abstract "cost" of speculating the
219 /// given instruction, which is assumed to be safe to speculate. 1 means
220 /// cheap, 2 means less cheap, and UINT_MAX means prohibitively expensive.
221 static unsigned ComputeSpeculationCost(const User *I, const DataLayout *DL) {
222 assert(isSafeToSpeculativelyExecute(I, DL) &&
223 "Instruction is not safe to speculatively execute!");
224 switch (Operator::getOpcode(I)) {
226 // In doubt, be conservative.
228 case Instruction::GetElementPtr:
229 // GEPs are cheap if all indices are constant.
230 if (!cast<GEPOperator>(I)->hasAllConstantIndices())
233 case Instruction::ExtractValue:
234 case Instruction::Load:
235 case Instruction::Add:
236 case Instruction::Sub:
237 case Instruction::And:
238 case Instruction::Or:
239 case Instruction::Xor:
240 case Instruction::Shl:
241 case Instruction::LShr:
242 case Instruction::AShr:
243 case Instruction::ICmp:
244 case Instruction::Trunc:
245 case Instruction::ZExt:
246 case Instruction::SExt:
247 case Instruction::BitCast:
248 case Instruction::ExtractElement:
249 case Instruction::InsertElement:
250 return 1; // These are all cheap.
252 case Instruction::Call:
253 case Instruction::Select:
258 /// DominatesMergePoint - If we have a merge point of an "if condition" as
259 /// accepted above, return true if the specified value dominates the block. We
260 /// don't handle the true generality of domination here, just a special case
261 /// which works well enough for us.
263 /// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
264 /// see if V (which must be an instruction) and its recursive operands
265 /// that do not dominate BB have a combined cost lower than CostRemaining and
266 /// are non-trapping. If both are true, the instruction is inserted into the
267 /// set and true is returned.
269 /// The cost for most non-trapping instructions is defined as 1 except for
270 /// Select whose cost is 2.
272 /// After this function returns, CostRemaining is decreased by the cost of
273 /// V plus its non-dominating operands. If that cost is greater than
274 /// CostRemaining, false is returned and CostRemaining is undefined.
275 static bool DominatesMergePoint(Value *V, BasicBlock *BB,
276 SmallPtrSetImpl<Instruction*> *AggressiveInsts,
277 unsigned &CostRemaining,
278 const DataLayout *DL) {
279 Instruction *I = dyn_cast<Instruction>(V);
281 // Non-instructions all dominate instructions, but not all constantexprs
282 // can be executed unconditionally.
283 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
288 BasicBlock *PBB = I->getParent();
290 // We don't want to allow weird loops that might have the "if condition" in
291 // the bottom of this block.
292 if (PBB == BB) return false;
294 // If this instruction is defined in a block that contains an unconditional
295 // branch to BB, then it must be in the 'conditional' part of the "if
296 // statement". If not, it definitely dominates the region.
297 BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
298 if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB)
301 // If we aren't allowing aggressive promotion anymore, then don't consider
302 // instructions in the 'if region'.
303 if (!AggressiveInsts) return false;
305 // If we have seen this instruction before, don't count it again.
306 if (AggressiveInsts->count(I)) return true;
308 // Okay, it looks like the instruction IS in the "condition". Check to
309 // see if it's a cheap instruction to unconditionally compute, and if it
310 // only uses stuff defined outside of the condition. If so, hoist it out.
311 if (!isSafeToSpeculativelyExecute(I, DL))
314 unsigned Cost = ComputeSpeculationCost(I, DL);
316 if (Cost > CostRemaining)
319 CostRemaining -= Cost;
321 // Okay, we can only really hoist these out if their operands do
322 // not take us over the cost threshold.
323 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
324 if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining, DL))
326 // Okay, it's safe to do this! Remember this instruction.
327 AggressiveInsts->insert(I);
331 /// GetConstantInt - Extract ConstantInt from value, looking through IntToPtr
332 /// and PointerNullValue. Return NULL if value is not a constant int.
333 static ConstantInt *GetConstantInt(Value *V, const DataLayout *DL) {
334 // Normal constant int.
335 ConstantInt *CI = dyn_cast<ConstantInt>(V);
336 if (CI || !DL || !isa<Constant>(V) || !V->getType()->isPointerTy())
339 // This is some kind of pointer constant. Turn it into a pointer-sized
340 // ConstantInt if possible.
341 IntegerType *PtrTy = cast<IntegerType>(DL->getIntPtrType(V->getType()));
343 // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
344 if (isa<ConstantPointerNull>(V))
345 return ConstantInt::get(PtrTy, 0);
347 // IntToPtr const int.
348 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
349 if (CE->getOpcode() == Instruction::IntToPtr)
350 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
351 // The constant is very likely to have the right type already.
352 if (CI->getType() == PtrTy)
355 return cast<ConstantInt>
356 (ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
363 /// Given a chain of or (||) or and (&&) comparison of a value against a
364 /// constant, this will try to recover the information required for a switch
366 /// It will depth-first traverse the chain of comparison, seeking for patterns
367 /// like %a == 12 or %a < 4 and combine them to produce a set of integer
368 /// representing the different cases for the switch.
369 /// Note that if the chain is composed of '||' it will build the set of elements
370 /// that matches the comparisons (i.e. any of this value validate the chain)
371 /// while for a chain of '&&' it will build the set elements that make the test
373 struct ConstantComparesGatherer {
375 Value *CompValue; /// Value found for the switch comparison
376 Value *Extra; /// Extra clause to be checked before the switch
377 SmallVector<ConstantInt *, 8> Vals; /// Set of integers to match in switch
378 unsigned UsedICmps; /// Number of comparisons matched in the and/or chain
380 /// Construct and compute the result for the comparison instruction Cond
381 ConstantComparesGatherer(Instruction *Cond, const DataLayout *DL)
382 : CompValue(nullptr), Extra(nullptr), UsedICmps(0) {
387 ConstantComparesGatherer(const ConstantComparesGatherer &)
388 LLVM_DELETED_FUNCTION;
389 ConstantComparesGatherer &
390 operator=(const ConstantComparesGatherer &) LLVM_DELETED_FUNCTION;
394 /// Try to set the current value used for the comparison, it succeeds only if
395 /// it wasn't set before or if the new value is the same as the old one
396 bool setValueOnce(Value *NewVal) {
397 if(CompValue && CompValue != NewVal) return false;
399 return (CompValue != nullptr);
402 /// Try to match Instruction "I" as a comparison against a constant and
403 /// populates the array Vals with the set of values that match (or do not
404 /// match depending on isEQ).
405 /// Return false on failure. On success, the Value the comparison matched
406 /// against is placed in CompValue.
407 /// If CompValue is already set, the function is expected to fail if a match
408 /// is found but the value compared to is different.
409 bool matchInstruction(Instruction *I, const DataLayout *DL, bool isEQ) {
410 // If this is an icmp against a constant, handle this as one of the cases.
413 if (!((ICI = dyn_cast<ICmpInst>(I)) &&
414 (C = GetConstantInt(I->getOperand(1), DL)))) {
421 // Pattern match a special case
422 // (x & ~2^x) == y --> x == y || x == y|2^x
423 // This undoes a transformation done by instcombine to fuse 2 compares.
424 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ:ICmpInst::ICMP_NE)) {
425 if (match(ICI->getOperand(0),
426 m_And(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
427 APInt Not = ~RHSC->getValue();
428 if (Not.isPowerOf2()) {
429 // If we already have a value for the switch, it has to match!
430 if(!setValueOnce(RHSVal))
434 Vals.push_back(ConstantInt::get(C->getContext(),
435 C->getValue() | Not));
441 // If we already have a value for the switch, it has to match!
442 if(!setValueOnce(ICI->getOperand(0)))
447 return ICI->getOperand(0);
450 // If we have "x ult 3", for example, then we can add 0,1,2 to the set.
451 ConstantRange Span = ConstantRange::makeICmpRegion(ICI->getPredicate(),
454 // Shift the range if the compare is fed by an add. This is the range
455 // compare idiom as emitted by instcombine.
456 Value *CandidateVal = I->getOperand(0);
457 if(match(I->getOperand(0), m_Add(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
458 Span = Span.subtract(RHSC->getValue());
459 CandidateVal = RHSVal;
462 // If this is an and/!= check, then we are looking to build the set of
463 // value that *don't* pass the and chain. I.e. to turn "x ugt 2" into
466 Span = Span.inverse();
468 // If there are a ton of values, we don't want to make a ginormous switch.
469 if (Span.getSetSize().ugt(8) || Span.isEmptySet()) {
473 // If we already have a value for the switch, it has to match!
474 if(!setValueOnce(CandidateVal))
477 // Add all values from the range to the set
478 for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
479 Vals.push_back(ConstantInt::get(I->getContext(), Tmp));
486 /// gather - Given a potentially 'or'd or 'and'd together collection of icmp
487 /// eq/ne/lt/gt instructions that compare a value against a constant, extract
488 /// the value being compared, and stick the list constants into the Vals
490 /// One "Extra" case is allowed to differ from the other.
491 void gather(Value *V, const DataLayout *DL) {
492 Instruction *I = dyn_cast<Instruction>(V);
493 bool isEQ = (I->getOpcode() == Instruction::Or);
495 // Keep a stack (SmallVector for efficiency) for depth-first traversal
496 SmallVector<Value *, 8> DFT;
501 while(!DFT.empty()) {
502 V = DFT.pop_back_val();
504 if (Instruction *I = dyn_cast<Instruction>(V)) {
505 // If it is a || (or && depending on isEQ), process the operands.
506 if (I->getOpcode() == (isEQ ? Instruction::Or : Instruction::And)) {
507 DFT.push_back(I->getOperand(1));
508 DFT.push_back(I->getOperand(0));
512 // Try to match the current instruction
513 if (matchInstruction(I, DL, isEQ))
514 // Match succeed, continue the loop
518 // One element of the sequence of || (or &&) could not be match as a
519 // comparison against the same value as the others.
520 // We allow only one "Extra" case to be checked before the switch
525 // Failed to parse a proper sequence, abort now
534 static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
535 Instruction *Cond = nullptr;
536 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
537 Cond = dyn_cast<Instruction>(SI->getCondition());
538 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
539 if (BI->isConditional())
540 Cond = dyn_cast<Instruction>(BI->getCondition());
541 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
542 Cond = dyn_cast<Instruction>(IBI->getAddress());
545 TI->eraseFromParent();
546 if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond);
549 /// isValueEqualityComparison - Return true if the specified terminator checks
550 /// to see if a value is equal to constant integer value.
551 Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) {
553 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
554 // Do not permit merging of large switch instructions into their
555 // predecessors unless there is only one predecessor.
556 if (SI->getNumSuccessors()*std::distance(pred_begin(SI->getParent()),
557 pred_end(SI->getParent())) <= 128)
558 CV = SI->getCondition();
559 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
560 if (BI->isConditional() && BI->getCondition()->hasOneUse())
561 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
562 if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL))
563 CV = ICI->getOperand(0);
565 // Unwrap any lossless ptrtoint cast.
567 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
568 Value *Ptr = PTII->getPointerOperand();
569 if (PTII->getType() == DL->getIntPtrType(Ptr->getType()))
576 /// GetValueEqualityComparisonCases - Given a value comparison instruction,
577 /// decode all of the 'cases' that it represents and return the 'default' block.
578 BasicBlock *SimplifyCFGOpt::
579 GetValueEqualityComparisonCases(TerminatorInst *TI,
580 std::vector<ValueEqualityComparisonCase>
582 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
583 Cases.reserve(SI->getNumCases());
584 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i)
585 Cases.push_back(ValueEqualityComparisonCase(i.getCaseValue(),
586 i.getCaseSuccessor()));
587 return SI->getDefaultDest();
590 BranchInst *BI = cast<BranchInst>(TI);
591 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
592 BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE);
593 Cases.push_back(ValueEqualityComparisonCase(GetConstantInt(ICI->getOperand(1),
596 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
600 /// EliminateBlockCases - Given a vector of bb/value pairs, remove any entries
601 /// in the list that match the specified block.
602 static void EliminateBlockCases(BasicBlock *BB,
603 std::vector<ValueEqualityComparisonCase> &Cases) {
604 Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end());
607 /// ValuesOverlap - Return true if there are any keys in C1 that exist in C2 as
610 ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
611 std::vector<ValueEqualityComparisonCase > &C2) {
612 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
614 // Make V1 be smaller than V2.
615 if (V1->size() > V2->size())
618 if (V1->size() == 0) return false;
619 if (V1->size() == 1) {
621 ConstantInt *TheVal = (*V1)[0].Value;
622 for (unsigned i = 0, e = V2->size(); i != e; ++i)
623 if (TheVal == (*V2)[i].Value)
627 // Otherwise, just sort both lists and compare element by element.
628 array_pod_sort(V1->begin(), V1->end());
629 array_pod_sort(V2->begin(), V2->end());
630 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
631 while (i1 != e1 && i2 != e2) {
632 if ((*V1)[i1].Value == (*V2)[i2].Value)
634 if ((*V1)[i1].Value < (*V2)[i2].Value)
642 /// SimplifyEqualityComparisonWithOnlyPredecessor - If TI is known to be a
643 /// terminator instruction and its block is known to only have a single
644 /// predecessor block, check to see if that predecessor is also a value
645 /// comparison with the same value, and if that comparison determines the
646 /// outcome of this comparison. If so, simplify TI. This does a very limited
647 /// form of jump threading.
648 bool SimplifyCFGOpt::
649 SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
651 IRBuilder<> &Builder) {
652 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
653 if (!PredVal) return false; // Not a value comparison in predecessor.
655 Value *ThisVal = isValueEqualityComparison(TI);
656 assert(ThisVal && "This isn't a value comparison!!");
657 if (ThisVal != PredVal) return false; // Different predicates.
659 // TODO: Preserve branch weight metadata, similarly to how
660 // FoldValueComparisonIntoPredecessors preserves it.
662 // Find out information about when control will move from Pred to TI's block.
663 std::vector<ValueEqualityComparisonCase> PredCases;
664 BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
666 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
668 // Find information about how control leaves this block.
669 std::vector<ValueEqualityComparisonCase> ThisCases;
670 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
671 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
673 // If TI's block is the default block from Pred's comparison, potentially
674 // simplify TI based on this knowledge.
675 if (PredDef == TI->getParent()) {
676 // If we are here, we know that the value is none of those cases listed in
677 // PredCases. If there are any cases in ThisCases that are in PredCases, we
679 if (!ValuesOverlap(PredCases, ThisCases))
682 if (isa<BranchInst>(TI)) {
683 // Okay, one of the successors of this condbr is dead. Convert it to a
685 assert(ThisCases.size() == 1 && "Branch can only have one case!");
686 // Insert the new branch.
687 Instruction *NI = Builder.CreateBr(ThisDef);
690 // Remove PHI node entries for the dead edge.
691 ThisCases[0].Dest->removePredecessor(TI->getParent());
693 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
694 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
696 EraseTerminatorInstAndDCECond(TI);
700 SwitchInst *SI = cast<SwitchInst>(TI);
701 // Okay, TI has cases that are statically dead, prune them away.
702 SmallPtrSet<Constant*, 16> DeadCases;
703 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
704 DeadCases.insert(PredCases[i].Value);
706 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
707 << "Through successor TI: " << *TI);
709 // Collect branch weights into a vector.
710 SmallVector<uint32_t, 8> Weights;
711 MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
712 bool HasWeight = MD && (MD->getNumOperands() == 2 + SI->getNumCases());
714 for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
716 ConstantInt* CI = dyn_cast<ConstantInt>(MD->getOperand(MD_i));
718 Weights.push_back(CI->getValue().getZExtValue());
720 for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
722 if (DeadCases.count(i.getCaseValue())) {
724 std::swap(Weights[i.getCaseIndex()+1], Weights.back());
727 i.getCaseSuccessor()->removePredecessor(TI->getParent());
731 if (HasWeight && Weights.size() >= 2)
732 SI->setMetadata(LLVMContext::MD_prof,
733 MDBuilder(SI->getParent()->getContext()).
734 createBranchWeights(Weights));
736 DEBUG(dbgs() << "Leaving: " << *TI << "\n");
740 // Otherwise, TI's block must correspond to some matched value. Find out
741 // which value (or set of values) this is.
742 ConstantInt *TIV = nullptr;
743 BasicBlock *TIBB = TI->getParent();
744 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
745 if (PredCases[i].Dest == TIBB) {
747 return false; // Cannot handle multiple values coming to this block.
748 TIV = PredCases[i].Value;
750 assert(TIV && "No edge from pred to succ?");
752 // Okay, we found the one constant that our value can be if we get into TI's
753 // BB. Find out which successor will unconditionally be branched to.
754 BasicBlock *TheRealDest = nullptr;
755 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
756 if (ThisCases[i].Value == TIV) {
757 TheRealDest = ThisCases[i].Dest;
761 // If not handled by any explicit cases, it is handled by the default case.
762 if (!TheRealDest) TheRealDest = ThisDef;
764 // Remove PHI node entries for dead edges.
765 BasicBlock *CheckEdge = TheRealDest;
766 for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
767 if (*SI != CheckEdge)
768 (*SI)->removePredecessor(TIBB);
772 // Insert the new branch.
773 Instruction *NI = Builder.CreateBr(TheRealDest);
776 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
777 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
779 EraseTerminatorInstAndDCECond(TI);
784 /// ConstantIntOrdering - This class implements a stable ordering of constant
785 /// integers that does not depend on their address. This is important for
786 /// applications that sort ConstantInt's to ensure uniqueness.
787 struct ConstantIntOrdering {
788 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
789 return LHS->getValue().ult(RHS->getValue());
794 static int ConstantIntSortPredicate(ConstantInt *const *P1,
795 ConstantInt *const *P2) {
796 const ConstantInt *LHS = *P1;
797 const ConstantInt *RHS = *P2;
798 if (LHS->getValue().ult(RHS->getValue()))
800 if (LHS->getValue() == RHS->getValue())
805 static inline bool HasBranchWeights(const Instruction* I) {
806 MDNode *ProfMD = I->getMetadata(LLVMContext::MD_prof);
807 if (ProfMD && ProfMD->getOperand(0))
808 if (MDString* MDS = dyn_cast<MDString>(ProfMD->getOperand(0)))
809 return MDS->getString().equals("branch_weights");
814 /// Get Weights of a given TerminatorInst, the default weight is at the front
815 /// of the vector. If TI is a conditional eq, we need to swap the branch-weight
817 static void GetBranchWeights(TerminatorInst *TI,
818 SmallVectorImpl<uint64_t> &Weights) {
819 MDNode *MD = TI->getMetadata(LLVMContext::MD_prof);
821 for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) {
822 ConstantInt *CI = cast<ConstantInt>(MD->getOperand(i));
823 Weights.push_back(CI->getValue().getZExtValue());
826 // If TI is a conditional eq, the default case is the false case,
827 // and the corresponding branch-weight data is at index 2. We swap the
828 // default weight to be the first entry.
829 if (BranchInst* BI = dyn_cast<BranchInst>(TI)) {
830 assert(Weights.size() == 2);
831 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
832 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
833 std::swap(Weights.front(), Weights.back());
837 /// Keep halving the weights until all can fit in uint32_t.
838 static void FitWeights(MutableArrayRef<uint64_t> Weights) {
839 uint64_t Max = *std::max_element(Weights.begin(), Weights.end());
840 if (Max > UINT_MAX) {
841 unsigned Offset = 32 - countLeadingZeros(Max);
842 for (uint64_t &I : Weights)
847 /// FoldValueComparisonIntoPredecessors - The specified terminator is a value
848 /// equality comparison instruction (either a switch or a branch on "X == c").
849 /// See if any of the predecessors of the terminator block are value comparisons
850 /// on the same value. If so, and if safe to do so, fold them together.
851 bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
852 IRBuilder<> &Builder) {
853 BasicBlock *BB = TI->getParent();
854 Value *CV = isValueEqualityComparison(TI); // CondVal
855 assert(CV && "Not a comparison?");
856 bool Changed = false;
858 SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
859 while (!Preds.empty()) {
860 BasicBlock *Pred = Preds.pop_back_val();
862 // See if the predecessor is a comparison with the same value.
863 TerminatorInst *PTI = Pred->getTerminator();
864 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
866 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
867 // Figure out which 'cases' to copy from SI to PSI.
868 std::vector<ValueEqualityComparisonCase> BBCases;
869 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
871 std::vector<ValueEqualityComparisonCase> PredCases;
872 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
874 // Based on whether the default edge from PTI goes to BB or not, fill in
875 // PredCases and PredDefault with the new switch cases we would like to
877 SmallVector<BasicBlock*, 8> NewSuccessors;
879 // Update the branch weight metadata along the way
880 SmallVector<uint64_t, 8> Weights;
881 bool PredHasWeights = HasBranchWeights(PTI);
882 bool SuccHasWeights = HasBranchWeights(TI);
884 if (PredHasWeights) {
885 GetBranchWeights(PTI, Weights);
886 // branch-weight metadata is inconsistent here.
887 if (Weights.size() != 1 + PredCases.size())
888 PredHasWeights = SuccHasWeights = false;
889 } else if (SuccHasWeights)
890 // If there are no predecessor weights but there are successor weights,
891 // populate Weights with 1, which will later be scaled to the sum of
892 // successor's weights
893 Weights.assign(1 + PredCases.size(), 1);
895 SmallVector<uint64_t, 8> SuccWeights;
896 if (SuccHasWeights) {
897 GetBranchWeights(TI, SuccWeights);
898 // branch-weight metadata is inconsistent here.
899 if (SuccWeights.size() != 1 + BBCases.size())
900 PredHasWeights = SuccHasWeights = false;
901 } else if (PredHasWeights)
902 SuccWeights.assign(1 + BBCases.size(), 1);
904 if (PredDefault == BB) {
905 // If this is the default destination from PTI, only the edges in TI
906 // that don't occur in PTI, or that branch to BB will be activated.
907 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
908 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
909 if (PredCases[i].Dest != BB)
910 PTIHandled.insert(PredCases[i].Value);
912 // The default destination is BB, we don't need explicit targets.
913 std::swap(PredCases[i], PredCases.back());
915 if (PredHasWeights || SuccHasWeights) {
916 // Increase weight for the default case.
917 Weights[0] += Weights[i+1];
918 std::swap(Weights[i+1], Weights.back());
922 PredCases.pop_back();
926 // Reconstruct the new switch statement we will be building.
927 if (PredDefault != BBDefault) {
928 PredDefault->removePredecessor(Pred);
929 PredDefault = BBDefault;
930 NewSuccessors.push_back(BBDefault);
933 unsigned CasesFromPred = Weights.size();
934 uint64_t ValidTotalSuccWeight = 0;
935 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
936 if (!PTIHandled.count(BBCases[i].Value) &&
937 BBCases[i].Dest != BBDefault) {
938 PredCases.push_back(BBCases[i]);
939 NewSuccessors.push_back(BBCases[i].Dest);
940 if (SuccHasWeights || PredHasWeights) {
941 // The default weight is at index 0, so weight for the ith case
942 // should be at index i+1. Scale the cases from successor by
943 // PredDefaultWeight (Weights[0]).
944 Weights.push_back(Weights[0] * SuccWeights[i+1]);
945 ValidTotalSuccWeight += SuccWeights[i+1];
949 if (SuccHasWeights || PredHasWeights) {
950 ValidTotalSuccWeight += SuccWeights[0];
951 // Scale the cases from predecessor by ValidTotalSuccWeight.
952 for (unsigned i = 1; i < CasesFromPred; ++i)
953 Weights[i] *= ValidTotalSuccWeight;
954 // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
955 Weights[0] *= SuccWeights[0];
958 // If this is not the default destination from PSI, only the edges
959 // in SI that occur in PSI with a destination of BB will be
961 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
962 std::map<ConstantInt*, uint64_t> WeightsForHandled;
963 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
964 if (PredCases[i].Dest == BB) {
965 PTIHandled.insert(PredCases[i].Value);
967 if (PredHasWeights || SuccHasWeights) {
968 WeightsForHandled[PredCases[i].Value] = Weights[i+1];
969 std::swap(Weights[i+1], Weights.back());
973 std::swap(PredCases[i], PredCases.back());
974 PredCases.pop_back();
978 // Okay, now we know which constants were sent to BB from the
979 // predecessor. Figure out where they will all go now.
980 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
981 if (PTIHandled.count(BBCases[i].Value)) {
982 // If this is one we are capable of getting...
983 if (PredHasWeights || SuccHasWeights)
984 Weights.push_back(WeightsForHandled[BBCases[i].Value]);
985 PredCases.push_back(BBCases[i]);
986 NewSuccessors.push_back(BBCases[i].Dest);
987 PTIHandled.erase(BBCases[i].Value);// This constant is taken care of
990 // If there are any constants vectored to BB that TI doesn't handle,
991 // they must go to the default destination of TI.
992 for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I =
994 E = PTIHandled.end(); I != E; ++I) {
995 if (PredHasWeights || SuccHasWeights)
996 Weights.push_back(WeightsForHandled[*I]);
997 PredCases.push_back(ValueEqualityComparisonCase(*I, BBDefault));
998 NewSuccessors.push_back(BBDefault);
1002 // Okay, at this point, we know which new successor Pred will get. Make
1003 // sure we update the number of entries in the PHI nodes for these
1005 for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
1006 AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
1008 Builder.SetInsertPoint(PTI);
1009 // Convert pointer to int before we switch.
1010 if (CV->getType()->isPointerTy()) {
1011 assert(DL && "Cannot switch on pointer without DataLayout");
1012 CV = Builder.CreatePtrToInt(CV, DL->getIntPtrType(CV->getType()),
1016 // Now that the successors are updated, create the new Switch instruction.
1017 SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault,
1019 NewSI->setDebugLoc(PTI->getDebugLoc());
1020 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
1021 NewSI->addCase(PredCases[i].Value, PredCases[i].Dest);
1023 if (PredHasWeights || SuccHasWeights) {
1024 // Halve the weights if any of them cannot fit in an uint32_t
1025 FitWeights(Weights);
1027 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
1029 NewSI->setMetadata(LLVMContext::MD_prof,
1030 MDBuilder(BB->getContext()).
1031 createBranchWeights(MDWeights));
1034 EraseTerminatorInstAndDCECond(PTI);
1036 // Okay, last check. If BB is still a successor of PSI, then we must
1037 // have an infinite loop case. If so, add an infinitely looping block
1038 // to handle the case to preserve the behavior of the code.
1039 BasicBlock *InfLoopBlock = nullptr;
1040 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
1041 if (NewSI->getSuccessor(i) == BB) {
1042 if (!InfLoopBlock) {
1043 // Insert it at the end of the function, because it's either code,
1044 // or it won't matter if it's hot. :)
1045 InfLoopBlock = BasicBlock::Create(BB->getContext(),
1046 "infloop", BB->getParent());
1047 BranchInst::Create(InfLoopBlock, InfLoopBlock);
1049 NewSI->setSuccessor(i, InfLoopBlock);
1058 // isSafeToHoistInvoke - If we would need to insert a select that uses the
1059 // value of this invoke (comments in HoistThenElseCodeToIf explain why we
1060 // would need to do this), we can't hoist the invoke, as there is nowhere
1061 // to put the select in this case.
1062 static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
1063 Instruction *I1, Instruction *I2) {
1064 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
1066 for (BasicBlock::iterator BBI = SI->begin();
1067 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1068 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1069 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1070 if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) {
1078 static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I);
1080 /// HoistThenElseCodeToIf - Given a conditional branch that goes to BB1 and
1081 /// BB2, hoist any common code in the two blocks up into the branch block. The
1082 /// caller of this function guarantees that BI's block dominates BB1 and BB2.
1083 static bool HoistThenElseCodeToIf(BranchInst *BI, const DataLayout *DL) {
1084 // This does very trivial matching, with limited scanning, to find identical
1085 // instructions in the two blocks. In particular, we don't want to get into
1086 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
1087 // such, we currently just scan for obviously identical instructions in an
1089 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
1090 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
1092 BasicBlock::iterator BB1_Itr = BB1->begin();
1093 BasicBlock::iterator BB2_Itr = BB2->begin();
1095 Instruction *I1 = BB1_Itr++, *I2 = BB2_Itr++;
1096 // Skip debug info if it is not identical.
1097 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1098 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1099 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1100 while (isa<DbgInfoIntrinsic>(I1))
1102 while (isa<DbgInfoIntrinsic>(I2))
1105 if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
1106 (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
1109 BasicBlock *BIParent = BI->getParent();
1111 bool Changed = false;
1113 // If we are hoisting the terminator instruction, don't move one (making a
1114 // broken BB), instead clone it, and remove BI.
1115 if (isa<TerminatorInst>(I1))
1116 goto HoistTerminator;
1118 // For a normal instruction, we just move one to right before the branch,
1119 // then replace all uses of the other with the first. Finally, we remove
1120 // the now redundant second instruction.
1121 BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
1122 if (!I2->use_empty())
1123 I2->replaceAllUsesWith(I1);
1124 I1->intersectOptionalDataWith(I2);
1125 unsigned KnownIDs[] = {
1126 LLVMContext::MD_tbaa,
1127 LLVMContext::MD_range,
1128 LLVMContext::MD_fpmath,
1129 LLVMContext::MD_invariant_load,
1130 LLVMContext::MD_nonnull
1132 combineMetadata(I1, I2, KnownIDs);
1133 I2->eraseFromParent();
1138 // Skip debug info if it is not identical.
1139 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1140 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1141 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1142 while (isa<DbgInfoIntrinsic>(I1))
1144 while (isa<DbgInfoIntrinsic>(I2))
1147 } while (I1->isIdenticalToWhenDefined(I2));
1152 // It may not be possible to hoist an invoke.
1153 if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
1156 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
1158 for (BasicBlock::iterator BBI = SI->begin();
1159 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1160 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1161 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1165 // Check for passingValueIsAlwaysUndefined here because we would rather
1166 // eliminate undefined control flow then converting it to a select.
1167 if (passingValueIsAlwaysUndefined(BB1V, PN) ||
1168 passingValueIsAlwaysUndefined(BB2V, PN))
1171 if (isa<ConstantExpr>(BB1V) && !isSafeToSpeculativelyExecute(BB1V, DL))
1173 if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V, DL))
1178 // Okay, it is safe to hoist the terminator.
1179 Instruction *NT = I1->clone();
1180 BIParent->getInstList().insert(BI, NT);
1181 if (!NT->getType()->isVoidTy()) {
1182 I1->replaceAllUsesWith(NT);
1183 I2->replaceAllUsesWith(NT);
1187 IRBuilder<true, NoFolder> Builder(NT);
1188 // Hoisting one of the terminators from our successor is a great thing.
1189 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
1190 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
1191 // nodes, so we insert select instruction to compute the final result.
1192 std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
1193 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
1195 for (BasicBlock::iterator BBI = SI->begin();
1196 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1197 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1198 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1199 if (BB1V == BB2V) continue;
1201 // These values do not agree. Insert a select instruction before NT
1202 // that determines the right value.
1203 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
1205 SI = cast<SelectInst>
1206 (Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
1207 BB1V->getName()+"."+BB2V->getName()));
1209 // Make the PHI node use the select for all incoming values for BB1/BB2
1210 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1211 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
1212 PN->setIncomingValue(i, SI);
1216 // Update any PHI nodes in our new successors.
1217 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
1218 AddPredecessorToBlock(*SI, BIParent, BB1);
1220 EraseTerminatorInstAndDCECond(BI);
1224 /// SinkThenElseCodeToEnd - Given an unconditional branch that goes to BBEnd,
1225 /// check whether BBEnd has only two predecessors and the other predecessor
1226 /// ends with an unconditional branch. If it is true, sink any common code
1227 /// in the two predecessors to BBEnd.
1228 static bool SinkThenElseCodeToEnd(BranchInst *BI1) {
1229 assert(BI1->isUnconditional());
1230 BasicBlock *BB1 = BI1->getParent();
1231 BasicBlock *BBEnd = BI1->getSuccessor(0);
1233 // Check that BBEnd has two predecessors and the other predecessor ends with
1234 // an unconditional branch.
1235 pred_iterator PI = pred_begin(BBEnd), PE = pred_end(BBEnd);
1236 BasicBlock *Pred0 = *PI++;
1237 if (PI == PE) // Only one predecessor.
1239 BasicBlock *Pred1 = *PI++;
1240 if (PI != PE) // More than two predecessors.
1242 BasicBlock *BB2 = (Pred0 == BB1) ? Pred1 : Pred0;
1243 BranchInst *BI2 = dyn_cast<BranchInst>(BB2->getTerminator());
1244 if (!BI2 || !BI2->isUnconditional())
1247 // Gather the PHI nodes in BBEnd.
1248 std::map<Value*, std::pair<Value*, PHINode*> > MapValueFromBB1ToBB2;
1249 Instruction *FirstNonPhiInBBEnd = nullptr;
1250 for (BasicBlock::iterator I = BBEnd->begin(), E = BBEnd->end();
1252 if (PHINode *PN = dyn_cast<PHINode>(I)) {
1253 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1254 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1255 MapValueFromBB1ToBB2[BB1V] = std::make_pair(BB2V, PN);
1257 FirstNonPhiInBBEnd = &*I;
1261 if (!FirstNonPhiInBBEnd)
1265 // This does very trivial matching, with limited scanning, to find identical
1266 // instructions in the two blocks. We scan backward for obviously identical
1267 // instructions in an identical order.
1268 BasicBlock::InstListType::reverse_iterator RI1 = BB1->getInstList().rbegin(),
1269 RE1 = BB1->getInstList().rend(), RI2 = BB2->getInstList().rbegin(),
1270 RE2 = BB2->getInstList().rend();
1272 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1275 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1278 // Skip the unconditional branches.
1282 bool Changed = false;
1283 while (RI1 != RE1 && RI2 != RE2) {
1285 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1288 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1292 Instruction *I1 = &*RI1, *I2 = &*RI2;
1293 // I1 and I2 should have a single use in the same PHI node, and they
1294 // perform the same operation.
1295 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
1296 if (isa<PHINode>(I1) || isa<PHINode>(I2) ||
1297 isa<TerminatorInst>(I1) || isa<TerminatorInst>(I2) ||
1298 isa<LandingPadInst>(I1) || isa<LandingPadInst>(I2) ||
1299 isa<AllocaInst>(I1) || isa<AllocaInst>(I2) ||
1300 I1->mayHaveSideEffects() || I2->mayHaveSideEffects() ||
1301 I1->mayReadOrWriteMemory() || I2->mayReadOrWriteMemory() ||
1302 !I1->hasOneUse() || !I2->hasOneUse() ||
1303 MapValueFromBB1ToBB2.find(I1) == MapValueFromBB1ToBB2.end() ||
1304 MapValueFromBB1ToBB2[I1].first != I2)
1307 // Check whether we should swap the operands of ICmpInst.
1308 ICmpInst *ICmp1 = dyn_cast<ICmpInst>(I1), *ICmp2 = dyn_cast<ICmpInst>(I2);
1309 bool SwapOpnds = false;
1310 if (ICmp1 && ICmp2 &&
1311 ICmp1->getOperand(0) != ICmp2->getOperand(0) &&
1312 ICmp1->getOperand(1) != ICmp2->getOperand(1) &&
1313 (ICmp1->getOperand(0) == ICmp2->getOperand(1) ||
1314 ICmp1->getOperand(1) == ICmp2->getOperand(0))) {
1315 ICmp2->swapOperands();
1318 if (!I1->isSameOperationAs(I2)) {
1320 ICmp2->swapOperands();
1324 // The operands should be either the same or they need to be generated
1325 // with a PHI node after sinking. We only handle the case where there is
1326 // a single pair of different operands.
1327 Value *DifferentOp1 = nullptr, *DifferentOp2 = nullptr;
1328 unsigned Op1Idx = 0;
1329 for (unsigned I = 0, E = I1->getNumOperands(); I != E; ++I) {
1330 if (I1->getOperand(I) == I2->getOperand(I))
1332 // Early exit if we have more-than one pair of different operands or
1333 // the different operand is already in MapValueFromBB1ToBB2.
1334 // Early exit if we need a PHI node to replace a constant.
1336 MapValueFromBB1ToBB2.find(I1->getOperand(I)) !=
1337 MapValueFromBB1ToBB2.end() ||
1338 isa<Constant>(I1->getOperand(I)) ||
1339 isa<Constant>(I2->getOperand(I))) {
1340 // If we can't sink the instructions, undo the swapping.
1342 ICmp2->swapOperands();
1345 DifferentOp1 = I1->getOperand(I);
1347 DifferentOp2 = I2->getOperand(I);
1350 // We insert the pair of different operands to MapValueFromBB1ToBB2 and
1351 // remove (I1, I2) from MapValueFromBB1ToBB2.
1353 PHINode *NewPN = PHINode::Create(DifferentOp1->getType(), 2,
1354 DifferentOp1->getName() + ".sink",
1356 MapValueFromBB1ToBB2[DifferentOp1] = std::make_pair(DifferentOp2, NewPN);
1357 // I1 should use NewPN instead of DifferentOp1.
1358 I1->setOperand(Op1Idx, NewPN);
1359 NewPN->addIncoming(DifferentOp1, BB1);
1360 NewPN->addIncoming(DifferentOp2, BB2);
1361 DEBUG(dbgs() << "Create PHI node " << *NewPN << "\n";);
1363 PHINode *OldPN = MapValueFromBB1ToBB2[I1].second;
1364 MapValueFromBB1ToBB2.erase(I1);
1366 DEBUG(dbgs() << "SINK common instructions " << *I1 << "\n";);
1367 DEBUG(dbgs() << " " << *I2 << "\n";);
1368 // We need to update RE1 and RE2 if we are going to sink the first
1369 // instruction in the basic block down.
1370 bool UpdateRE1 = (I1 == BB1->begin()), UpdateRE2 = (I2 == BB2->begin());
1371 // Sink the instruction.
1372 BBEnd->getInstList().splice(FirstNonPhiInBBEnd, BB1->getInstList(), I1);
1373 if (!OldPN->use_empty())
1374 OldPN->replaceAllUsesWith(I1);
1375 OldPN->eraseFromParent();
1377 if (!I2->use_empty())
1378 I2->replaceAllUsesWith(I1);
1379 I1->intersectOptionalDataWith(I2);
1380 // TODO: Use combineMetadata here to preserve what metadata we can
1381 // (analogous to the hoisting case above).
1382 I2->eraseFromParent();
1385 RE1 = BB1->getInstList().rend();
1387 RE2 = BB2->getInstList().rend();
1388 FirstNonPhiInBBEnd = I1;
1395 /// \brief Determine if we can hoist sink a sole store instruction out of a
1396 /// conditional block.
1398 /// We are looking for code like the following:
1400 /// store i32 %add, i32* %arrayidx2
1401 /// ... // No other stores or function calls (we could be calling a memory
1402 /// ... // function).
1403 /// %cmp = icmp ult %x, %y
1404 /// br i1 %cmp, label %EndBB, label %ThenBB
1406 /// store i32 %add5, i32* %arrayidx2
1410 /// We are going to transform this into:
1412 /// store i32 %add, i32* %arrayidx2
1414 /// %cmp = icmp ult %x, %y
1415 /// %add.add5 = select i1 %cmp, i32 %add, %add5
1416 /// store i32 %add.add5, i32* %arrayidx2
1419 /// \return The pointer to the value of the previous store if the store can be
1420 /// hoisted into the predecessor block. 0 otherwise.
1421 static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB,
1422 BasicBlock *StoreBB, BasicBlock *EndBB) {
1423 StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
1427 // Volatile or atomic.
1428 if (!StoreToHoist->isSimple())
1431 Value *StorePtr = StoreToHoist->getPointerOperand();
1433 // Look for a store to the same pointer in BrBB.
1434 unsigned MaxNumInstToLookAt = 10;
1435 for (BasicBlock::reverse_iterator RI = BrBB->rbegin(),
1436 RE = BrBB->rend(); RI != RE && (--MaxNumInstToLookAt); ++RI) {
1437 Instruction *CurI = &*RI;
1439 // Could be calling an instruction that effects memory like free().
1440 if (CurI->mayHaveSideEffects() && !isa<StoreInst>(CurI))
1443 StoreInst *SI = dyn_cast<StoreInst>(CurI);
1444 // Found the previous store make sure it stores to the same location.
1445 if (SI && SI->getPointerOperand() == StorePtr)
1446 // Found the previous store, return its value operand.
1447 return SI->getValueOperand();
1449 return nullptr; // Unknown store.
1455 /// \brief Speculate a conditional basic block flattening the CFG.
1457 /// Note that this is a very risky transform currently. Speculating
1458 /// instructions like this is most often not desirable. Instead, there is an MI
1459 /// pass which can do it with full awareness of the resource constraints.
1460 /// However, some cases are "obvious" and we should do directly. An example of
1461 /// this is speculating a single, reasonably cheap instruction.
1463 /// There is only one distinct advantage to flattening the CFG at the IR level:
1464 /// it makes very common but simplistic optimizations such as are common in
1465 /// instcombine and the DAG combiner more powerful by removing CFG edges and
1466 /// modeling their effects with easier to reason about SSA value graphs.
1469 /// An illustration of this transform is turning this IR:
1472 /// %cmp = icmp ult %x, %y
1473 /// br i1 %cmp, label %EndBB, label %ThenBB
1475 /// %sub = sub %x, %y
1478 /// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ]
1485 /// %cmp = icmp ult %x, %y
1486 /// %sub = sub %x, %y
1487 /// %cond = select i1 %cmp, 0, %sub
1491 /// \returns true if the conditional block is removed.
1492 static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB,
1493 const DataLayout *DL) {
1494 // Be conservative for now. FP select instruction can often be expensive.
1495 Value *BrCond = BI->getCondition();
1496 if (isa<FCmpInst>(BrCond))
1499 BasicBlock *BB = BI->getParent();
1500 BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
1502 // If ThenBB is actually on the false edge of the conditional branch, remember
1503 // to swap the select operands later.
1504 bool Invert = false;
1505 if (ThenBB != BI->getSuccessor(0)) {
1506 assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
1509 assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
1511 // Keep a count of how many times instructions are used within CondBB when
1512 // they are candidates for sinking into CondBB. Specifically:
1513 // - They are defined in BB, and
1514 // - They have no side effects, and
1515 // - All of their uses are in CondBB.
1516 SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
1518 unsigned SpeculationCost = 0;
1519 Value *SpeculatedStoreValue = nullptr;
1520 StoreInst *SpeculatedStore = nullptr;
1521 for (BasicBlock::iterator BBI = ThenBB->begin(),
1522 BBE = std::prev(ThenBB->end());
1523 BBI != BBE; ++BBI) {
1524 Instruction *I = BBI;
1526 if (isa<DbgInfoIntrinsic>(I))
1529 // Only speculatively execution a single instruction (not counting the
1530 // terminator) for now.
1532 if (SpeculationCost > 1)
1535 // Don't hoist the instruction if it's unsafe or expensive.
1536 if (!isSafeToSpeculativelyExecute(I, DL) &&
1537 !(HoistCondStores &&
1538 (SpeculatedStoreValue = isSafeToSpeculateStore(I, BB, ThenBB,
1541 if (!SpeculatedStoreValue &&
1542 ComputeSpeculationCost(I, DL) > PHINodeFoldingThreshold)
1545 // Store the store speculation candidate.
1546 if (SpeculatedStoreValue)
1547 SpeculatedStore = cast<StoreInst>(I);
1549 // Do not hoist the instruction if any of its operands are defined but not
1550 // used in BB. The transformation will prevent the operand from
1551 // being sunk into the use block.
1552 for (User::op_iterator i = I->op_begin(), e = I->op_end();
1554 Instruction *OpI = dyn_cast<Instruction>(*i);
1555 if (!OpI || OpI->getParent() != BB ||
1556 OpI->mayHaveSideEffects())
1557 continue; // Not a candidate for sinking.
1559 ++SinkCandidateUseCounts[OpI];
1563 // Consider any sink candidates which are only used in CondBB as costs for
1564 // speculation. Note, while we iterate over a DenseMap here, we are summing
1565 // and so iteration order isn't significant.
1566 for (SmallDenseMap<Instruction *, unsigned, 4>::iterator I =
1567 SinkCandidateUseCounts.begin(), E = SinkCandidateUseCounts.end();
1569 if (I->first->getNumUses() == I->second) {
1571 if (SpeculationCost > 1)
1575 // Check that the PHI nodes can be converted to selects.
1576 bool HaveRewritablePHIs = false;
1577 for (BasicBlock::iterator I = EndBB->begin();
1578 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1579 Value *OrigV = PN->getIncomingValueForBlock(BB);
1580 Value *ThenV = PN->getIncomingValueForBlock(ThenBB);
1582 // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf.
1583 // Skip PHIs which are trivial.
1587 // Don't convert to selects if we could remove undefined behavior instead.
1588 if (passingValueIsAlwaysUndefined(OrigV, PN) ||
1589 passingValueIsAlwaysUndefined(ThenV, PN))
1592 HaveRewritablePHIs = true;
1593 ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
1594 ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
1595 if (!OrigCE && !ThenCE)
1596 continue; // Known safe and cheap.
1598 if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE, DL)) ||
1599 (OrigCE && !isSafeToSpeculativelyExecute(OrigCE, DL)))
1601 unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE, DL) : 0;
1602 unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE, DL) : 0;
1603 if (OrigCost + ThenCost > 2 * PHINodeFoldingThreshold)
1606 // Account for the cost of an unfolded ConstantExpr which could end up
1607 // getting expanded into Instructions.
1608 // FIXME: This doesn't account for how many operations are combined in the
1609 // constant expression.
1611 if (SpeculationCost > 1)
1615 // If there are no PHIs to process, bail early. This helps ensure idempotence
1617 if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue))
1620 // If we get here, we can hoist the instruction and if-convert.
1621 DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
1623 // Insert a select of the value of the speculated store.
1624 if (SpeculatedStoreValue) {
1625 IRBuilder<true, NoFolder> Builder(BI);
1626 Value *TrueV = SpeculatedStore->getValueOperand();
1627 Value *FalseV = SpeculatedStoreValue;
1629 std::swap(TrueV, FalseV);
1630 Value *S = Builder.CreateSelect(BrCond, TrueV, FalseV, TrueV->getName() +
1631 "." + FalseV->getName());
1632 SpeculatedStore->setOperand(0, S);
1635 // Hoist the instructions.
1636 BB->getInstList().splice(BI, ThenBB->getInstList(), ThenBB->begin(),
1637 std::prev(ThenBB->end()));
1639 // Insert selects and rewrite the PHI operands.
1640 IRBuilder<true, NoFolder> Builder(BI);
1641 for (BasicBlock::iterator I = EndBB->begin();
1642 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1643 unsigned OrigI = PN->getBasicBlockIndex(BB);
1644 unsigned ThenI = PN->getBasicBlockIndex(ThenBB);
1645 Value *OrigV = PN->getIncomingValue(OrigI);
1646 Value *ThenV = PN->getIncomingValue(ThenI);
1648 // Skip PHIs which are trivial.
1652 // Create a select whose true value is the speculatively executed value and
1653 // false value is the preexisting value. Swap them if the branch
1654 // destinations were inverted.
1655 Value *TrueV = ThenV, *FalseV = OrigV;
1657 std::swap(TrueV, FalseV);
1658 Value *V = Builder.CreateSelect(BrCond, TrueV, FalseV,
1659 TrueV->getName() + "." + FalseV->getName());
1660 PN->setIncomingValue(OrigI, V);
1661 PN->setIncomingValue(ThenI, V);
1668 /// \returns True if this block contains a CallInst with the NoDuplicate
1670 static bool HasNoDuplicateCall(const BasicBlock *BB) {
1671 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1672 const CallInst *CI = dyn_cast<CallInst>(I);
1675 if (CI->cannotDuplicate())
1681 /// BlockIsSimpleEnoughToThreadThrough - Return true if we can thread a branch
1682 /// across this block.
1683 static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
1684 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
1687 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1688 if (isa<DbgInfoIntrinsic>(BBI))
1690 if (Size > 10) return false; // Don't clone large BB's.
1693 // We can only support instructions that do not define values that are
1694 // live outside of the current basic block.
1695 for (User *U : BBI->users()) {
1696 Instruction *UI = cast<Instruction>(U);
1697 if (UI->getParent() != BB || isa<PHINode>(UI)) return false;
1700 // Looks ok, continue checking.
1706 /// FoldCondBranchOnPHI - If we have a conditional branch on a PHI node value
1707 /// that is defined in the same block as the branch and if any PHI entries are
1708 /// constants, thread edges corresponding to that entry to be branches to their
1709 /// ultimate destination.
1710 static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout *DL) {
1711 BasicBlock *BB = BI->getParent();
1712 PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
1713 // NOTE: we currently cannot transform this case if the PHI node is used
1714 // outside of the block.
1715 if (!PN || PN->getParent() != BB || !PN->hasOneUse())
1718 // Degenerate case of a single entry PHI.
1719 if (PN->getNumIncomingValues() == 1) {
1720 FoldSingleEntryPHINodes(PN->getParent());
1724 // Now we know that this block has multiple preds and two succs.
1725 if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
1727 if (HasNoDuplicateCall(BB)) return false;
1729 // Okay, this is a simple enough basic block. See if any phi values are
1731 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1732 ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
1733 if (!CB || !CB->getType()->isIntegerTy(1)) continue;
1735 // Okay, we now know that all edges from PredBB should be revectored to
1736 // branch to RealDest.
1737 BasicBlock *PredBB = PN->getIncomingBlock(i);
1738 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
1740 if (RealDest == BB) continue; // Skip self loops.
1741 // Skip if the predecessor's terminator is an indirect branch.
1742 if (isa<IndirectBrInst>(PredBB->getTerminator())) continue;
1744 // The dest block might have PHI nodes, other predecessors and other
1745 // difficult cases. Instead of being smart about this, just insert a new
1746 // block that jumps to the destination block, effectively splitting
1747 // the edge we are about to create.
1748 BasicBlock *EdgeBB = BasicBlock::Create(BB->getContext(),
1749 RealDest->getName()+".critedge",
1750 RealDest->getParent(), RealDest);
1751 BranchInst::Create(RealDest, EdgeBB);
1753 // Update PHI nodes.
1754 AddPredecessorToBlock(RealDest, EdgeBB, BB);
1756 // BB may have instructions that are being threaded over. Clone these
1757 // instructions into EdgeBB. We know that there will be no uses of the
1758 // cloned instructions outside of EdgeBB.
1759 BasicBlock::iterator InsertPt = EdgeBB->begin();
1760 DenseMap<Value*, Value*> TranslateMap; // Track translated values.
1761 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1762 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
1763 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
1766 // Clone the instruction.
1767 Instruction *N = BBI->clone();
1768 if (BBI->hasName()) N->setName(BBI->getName()+".c");
1770 // Update operands due to translation.
1771 for (User::op_iterator i = N->op_begin(), e = N->op_end();
1773 DenseMap<Value*, Value*>::iterator PI = TranslateMap.find(*i);
1774 if (PI != TranslateMap.end())
1778 // Check for trivial simplification.
1779 if (Value *V = SimplifyInstruction(N, DL)) {
1780 TranslateMap[BBI] = V;
1781 delete N; // Instruction folded away, don't need actual inst
1783 // Insert the new instruction into its new home.
1784 EdgeBB->getInstList().insert(InsertPt, N);
1785 if (!BBI->use_empty())
1786 TranslateMap[BBI] = N;
1790 // Loop over all of the edges from PredBB to BB, changing them to branch
1791 // to EdgeBB instead.
1792 TerminatorInst *PredBBTI = PredBB->getTerminator();
1793 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
1794 if (PredBBTI->getSuccessor(i) == BB) {
1795 BB->removePredecessor(PredBB);
1796 PredBBTI->setSuccessor(i, EdgeBB);
1799 // Recurse, simplifying any other constants.
1800 return FoldCondBranchOnPHI(BI, DL) | true;
1806 /// FoldTwoEntryPHINode - Given a BB that starts with the specified two-entry
1807 /// PHI node, see if we can eliminate it.
1808 static bool FoldTwoEntryPHINode(PHINode *PN, const DataLayout *DL) {
1809 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
1810 // statement", which has a very simple dominance structure. Basically, we
1811 // are trying to find the condition that is being branched on, which
1812 // subsequently causes this merge to happen. We really want control
1813 // dependence information for this check, but simplifycfg can't keep it up
1814 // to date, and this catches most of the cases we care about anyway.
1815 BasicBlock *BB = PN->getParent();
1816 BasicBlock *IfTrue, *IfFalse;
1817 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
1819 // Don't bother if the branch will be constant folded trivially.
1820 isa<ConstantInt>(IfCond))
1823 // Okay, we found that we can merge this two-entry phi node into a select.
1824 // Doing so would require us to fold *all* two entry phi nodes in this block.
1825 // At some point this becomes non-profitable (particularly if the target
1826 // doesn't support cmov's). Only do this transformation if there are two or
1827 // fewer PHI nodes in this block.
1828 unsigned NumPhis = 0;
1829 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
1833 // Loop over the PHI's seeing if we can promote them all to select
1834 // instructions. While we are at it, keep track of the instructions
1835 // that need to be moved to the dominating block.
1836 SmallPtrSet<Instruction*, 4> AggressiveInsts;
1837 unsigned MaxCostVal0 = PHINodeFoldingThreshold,
1838 MaxCostVal1 = PHINodeFoldingThreshold;
1840 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
1841 PHINode *PN = cast<PHINode>(II++);
1842 if (Value *V = SimplifyInstruction(PN, DL)) {
1843 PN->replaceAllUsesWith(V);
1844 PN->eraseFromParent();
1848 if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts,
1850 !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts,
1855 // If we folded the first phi, PN dangles at this point. Refresh it. If
1856 // we ran out of PHIs then we simplified them all.
1857 PN = dyn_cast<PHINode>(BB->begin());
1858 if (!PN) return true;
1860 // Don't fold i1 branches on PHIs which contain binary operators. These can
1861 // often be turned into switches and other things.
1862 if (PN->getType()->isIntegerTy(1) &&
1863 (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
1864 isa<BinaryOperator>(PN->getIncomingValue(1)) ||
1865 isa<BinaryOperator>(IfCond)))
1868 // If we all PHI nodes are promotable, check to make sure that all
1869 // instructions in the predecessor blocks can be promoted as well. If
1870 // not, we won't be able to get rid of the control flow, so it's not
1871 // worth promoting to select instructions.
1872 BasicBlock *DomBlock = nullptr;
1873 BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
1874 BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
1875 if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
1878 DomBlock = *pred_begin(IfBlock1);
1879 for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I)
1880 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
1881 // This is not an aggressive instruction that we can promote.
1882 // Because of this, we won't be able to get rid of the control
1883 // flow, so the xform is not worth it.
1888 if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
1891 DomBlock = *pred_begin(IfBlock2);
1892 for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I)
1893 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
1894 // This is not an aggressive instruction that we can promote.
1895 // Because of this, we won't be able to get rid of the control
1896 // flow, so the xform is not worth it.
1901 DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: "
1902 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
1904 // If we can still promote the PHI nodes after this gauntlet of tests,
1905 // do all of the PHI's now.
1906 Instruction *InsertPt = DomBlock->getTerminator();
1907 IRBuilder<true, NoFolder> Builder(InsertPt);
1909 // Move all 'aggressive' instructions, which are defined in the
1910 // conditional parts of the if's up to the dominating block.
1912 DomBlock->getInstList().splice(InsertPt,
1913 IfBlock1->getInstList(), IfBlock1->begin(),
1914 IfBlock1->getTerminator());
1916 DomBlock->getInstList().splice(InsertPt,
1917 IfBlock2->getInstList(), IfBlock2->begin(),
1918 IfBlock2->getTerminator());
1920 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1921 // Change the PHI node into a select instruction.
1922 Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1923 Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
1926 cast<SelectInst>(Builder.CreateSelect(IfCond, TrueVal, FalseVal, ""));
1927 PN->replaceAllUsesWith(NV);
1929 PN->eraseFromParent();
1932 // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
1933 // has been flattened. Change DomBlock to jump directly to our new block to
1934 // avoid other simplifycfg's kicking in on the diamond.
1935 TerminatorInst *OldTI = DomBlock->getTerminator();
1936 Builder.SetInsertPoint(OldTI);
1937 Builder.CreateBr(BB);
1938 OldTI->eraseFromParent();
1942 /// SimplifyCondBranchToTwoReturns - If we found a conditional branch that goes
1943 /// to two returning blocks, try to merge them together into one return,
1944 /// introducing a select if the return values disagree.
1945 static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
1946 IRBuilder<> &Builder) {
1947 assert(BI->isConditional() && "Must be a conditional branch");
1948 BasicBlock *TrueSucc = BI->getSuccessor(0);
1949 BasicBlock *FalseSucc = BI->getSuccessor(1);
1950 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
1951 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
1953 // Check to ensure both blocks are empty (just a return) or optionally empty
1954 // with PHI nodes. If there are other instructions, merging would cause extra
1955 // computation on one path or the other.
1956 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
1958 if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
1961 Builder.SetInsertPoint(BI);
1962 // Okay, we found a branch that is going to two return nodes. If
1963 // there is no return value for this function, just change the
1964 // branch into a return.
1965 if (FalseRet->getNumOperands() == 0) {
1966 TrueSucc->removePredecessor(BI->getParent());
1967 FalseSucc->removePredecessor(BI->getParent());
1968 Builder.CreateRetVoid();
1969 EraseTerminatorInstAndDCECond(BI);
1973 // Otherwise, figure out what the true and false return values are
1974 // so we can insert a new select instruction.
1975 Value *TrueValue = TrueRet->getReturnValue();
1976 Value *FalseValue = FalseRet->getReturnValue();
1978 // Unwrap any PHI nodes in the return blocks.
1979 if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
1980 if (TVPN->getParent() == TrueSucc)
1981 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
1982 if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
1983 if (FVPN->getParent() == FalseSucc)
1984 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
1986 // In order for this transformation to be safe, we must be able to
1987 // unconditionally execute both operands to the return. This is
1988 // normally the case, but we could have a potentially-trapping
1989 // constant expression that prevents this transformation from being
1991 if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
1994 if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
1998 // Okay, we collected all the mapped values and checked them for sanity, and
1999 // defined to really do this transformation. First, update the CFG.
2000 TrueSucc->removePredecessor(BI->getParent());
2001 FalseSucc->removePredecessor(BI->getParent());
2003 // Insert select instructions where needed.
2004 Value *BrCond = BI->getCondition();
2006 // Insert a select if the results differ.
2007 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
2008 } else if (isa<UndefValue>(TrueValue)) {
2009 TrueValue = FalseValue;
2011 TrueValue = Builder.CreateSelect(BrCond, TrueValue,
2012 FalseValue, "retval");
2016 Value *RI = !TrueValue ?
2017 Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
2021 DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
2022 << "\n " << *BI << "NewRet = " << *RI
2023 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc);
2025 EraseTerminatorInstAndDCECond(BI);
2030 /// ExtractBranchMetadata - Given a conditional BranchInstruction, retrieve the
2031 /// probabilities of the branch taking each edge. Fills in the two APInt
2032 /// parameters and return true, or returns false if no or invalid metadata was
2034 static bool ExtractBranchMetadata(BranchInst *BI,
2035 uint64_t &ProbTrue, uint64_t &ProbFalse) {
2036 assert(BI->isConditional() &&
2037 "Looking for probabilities on unconditional branch?");
2038 MDNode *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
2039 if (!ProfileData || ProfileData->getNumOperands() != 3) return false;
2040 ConstantInt *CITrue = dyn_cast<ConstantInt>(ProfileData->getOperand(1));
2041 ConstantInt *CIFalse = dyn_cast<ConstantInt>(ProfileData->getOperand(2));
2042 if (!CITrue || !CIFalse) return false;
2043 ProbTrue = CITrue->getValue().getZExtValue();
2044 ProbFalse = CIFalse->getValue().getZExtValue();
2048 /// checkCSEInPredecessor - Return true if the given instruction is available
2049 /// in its predecessor block. If yes, the instruction will be removed.
2051 static bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB) {
2052 if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
2054 for (BasicBlock::iterator I = PB->begin(), E = PB->end(); I != E; I++) {
2055 Instruction *PBI = &*I;
2056 // Check whether Inst and PBI generate the same value.
2057 if (Inst->isIdenticalTo(PBI)) {
2058 Inst->replaceAllUsesWith(PBI);
2059 Inst->eraseFromParent();
2066 /// FoldBranchToCommonDest - If this basic block is simple enough, and if a
2067 /// predecessor branches to us and one of our successors, fold the block into
2068 /// the predecessor and use logical operations to pick the right destination.
2069 bool llvm::FoldBranchToCommonDest(BranchInst *BI, const DataLayout *DL,
2070 unsigned BonusInstThreshold) {
2071 BasicBlock *BB = BI->getParent();
2073 Instruction *Cond = nullptr;
2074 if (BI->isConditional())
2075 Cond = dyn_cast<Instruction>(BI->getCondition());
2077 // For unconditional branch, check for a simple CFG pattern, where
2078 // BB has a single predecessor and BB's successor is also its predecessor's
2079 // successor. If such pattern exisits, check for CSE between BB and its
2081 if (BasicBlock *PB = BB->getSinglePredecessor())
2082 if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
2083 if (PBI->isConditional() &&
2084 (BI->getSuccessor(0) == PBI->getSuccessor(0) ||
2085 BI->getSuccessor(0) == PBI->getSuccessor(1))) {
2086 for (BasicBlock::iterator I = BB->begin(), E = BB->end();
2088 Instruction *Curr = I++;
2089 if (isa<CmpInst>(Curr)) {
2093 // Quit if we can't remove this instruction.
2094 if (!checkCSEInPredecessor(Curr, PB))
2103 if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
2104 Cond->getParent() != BB || !Cond->hasOneUse())
2107 // Make sure the instruction after the condition is the cond branch.
2108 BasicBlock::iterator CondIt = Cond; ++CondIt;
2110 // Ignore dbg intrinsics.
2111 while (isa<DbgInfoIntrinsic>(CondIt)) ++CondIt;
2116 // Only allow this transformation if computing the condition doesn't involve
2117 // too many instructions and these involved instructions can be executed
2118 // unconditionally. We denote all involved instructions except the condition
2119 // as "bonus instructions", and only allow this transformation when the
2120 // number of the bonus instructions does not exceed a certain threshold.
2121 unsigned NumBonusInsts = 0;
2122 for (auto I = BB->begin(); Cond != I; ++I) {
2123 // Ignore dbg intrinsics.
2124 if (isa<DbgInfoIntrinsic>(I))
2126 if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(I, DL))
2128 // I has only one use and can be executed unconditionally.
2129 Instruction *User = dyn_cast<Instruction>(I->user_back());
2130 if (User == nullptr || User->getParent() != BB)
2132 // I is used in the same BB. Since BI uses Cond and doesn't have more slots
2133 // to use any other instruction, User must be an instruction between next(I)
2136 // Early exits once we reach the limit.
2137 if (NumBonusInsts > BonusInstThreshold)
2141 // Cond is known to be a compare or binary operator. Check to make sure that
2142 // neither operand is a potentially-trapping constant expression.
2143 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
2146 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
2150 // Finally, don't infinitely unroll conditional loops.
2151 BasicBlock *TrueDest = BI->getSuccessor(0);
2152 BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr;
2153 if (TrueDest == BB || FalseDest == BB)
2156 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2157 BasicBlock *PredBlock = *PI;
2158 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
2160 // Check that we have two conditional branches. If there is a PHI node in
2161 // the common successor, verify that the same value flows in from both
2163 SmallVector<PHINode*, 4> PHIs;
2164 if (!PBI || PBI->isUnconditional() ||
2165 (BI->isConditional() &&
2166 !SafeToMergeTerminators(BI, PBI)) ||
2167 (!BI->isConditional() &&
2168 !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs)))
2171 // Determine if the two branches share a common destination.
2172 Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd;
2173 bool InvertPredCond = false;
2175 if (BI->isConditional()) {
2176 if (PBI->getSuccessor(0) == TrueDest)
2177 Opc = Instruction::Or;
2178 else if (PBI->getSuccessor(1) == FalseDest)
2179 Opc = Instruction::And;
2180 else if (PBI->getSuccessor(0) == FalseDest)
2181 Opc = Instruction::And, InvertPredCond = true;
2182 else if (PBI->getSuccessor(1) == TrueDest)
2183 Opc = Instruction::Or, InvertPredCond = true;
2187 if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest)
2191 DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
2192 IRBuilder<> Builder(PBI);
2194 // If we need to invert the condition in the pred block to match, do so now.
2195 if (InvertPredCond) {
2196 Value *NewCond = PBI->getCondition();
2198 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
2199 CmpInst *CI = cast<CmpInst>(NewCond);
2200 CI->setPredicate(CI->getInversePredicate());
2202 NewCond = Builder.CreateNot(NewCond,
2203 PBI->getCondition()->getName()+".not");
2206 PBI->setCondition(NewCond);
2207 PBI->swapSuccessors();
2210 // If we have bonus instructions, clone them into the predecessor block.
2211 // Note that there may be mutliple predecessor blocks, so we cannot move
2212 // bonus instructions to a predecessor block.
2213 ValueToValueMapTy VMap; // maps original values to cloned values
2214 // We already make sure Cond is the last instruction before BI. Therefore,
2215 // every instructions before Cond other than DbgInfoIntrinsic are bonus
2217 for (auto BonusInst = BB->begin(); Cond != BonusInst; ++BonusInst) {
2218 if (isa<DbgInfoIntrinsic>(BonusInst))
2220 Instruction *NewBonusInst = BonusInst->clone();
2221 RemapInstruction(NewBonusInst, VMap,
2222 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
2223 VMap[BonusInst] = NewBonusInst;
2225 // If we moved a load, we cannot any longer claim any knowledge about
2226 // its potential value. The previous information might have been valid
2227 // only given the branch precondition.
2228 // For an analogous reason, we must also drop all the metadata whose
2229 // semantics we don't understand.
2230 NewBonusInst->dropUnknownMetadata(LLVMContext::MD_dbg);
2232 PredBlock->getInstList().insert(PBI, NewBonusInst);
2233 NewBonusInst->takeName(BonusInst);
2234 BonusInst->setName(BonusInst->getName() + ".old");
2237 // Clone Cond into the predecessor basic block, and or/and the
2238 // two conditions together.
2239 Instruction *New = Cond->clone();
2240 RemapInstruction(New, VMap,
2241 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
2242 PredBlock->getInstList().insert(PBI, New);
2243 New->takeName(Cond);
2244 Cond->setName(New->getName() + ".old");
2246 if (BI->isConditional()) {
2247 Instruction *NewCond =
2248 cast<Instruction>(Builder.CreateBinOp(Opc, PBI->getCondition(),
2250 PBI->setCondition(NewCond);
2252 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2253 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2255 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2257 SmallVector<uint64_t, 8> NewWeights;
2259 if (PBI->getSuccessor(0) == BB) {
2260 if (PredHasWeights && SuccHasWeights) {
2261 // PBI: br i1 %x, BB, FalseDest
2262 // BI: br i1 %y, TrueDest, FalseDest
2263 //TrueWeight is TrueWeight for PBI * TrueWeight for BI.
2264 NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
2265 //FalseWeight is FalseWeight for PBI * TotalWeight for BI +
2266 // TrueWeight for PBI * FalseWeight for BI.
2267 // We assume that total weights of a BranchInst can fit into 32 bits.
2268 // Therefore, we will not have overflow using 64-bit arithmetic.
2269 NewWeights.push_back(PredFalseWeight * (SuccFalseWeight +
2270 SuccTrueWeight) + PredTrueWeight * SuccFalseWeight);
2272 AddPredecessorToBlock(TrueDest, PredBlock, BB);
2273 PBI->setSuccessor(0, TrueDest);
2275 if (PBI->getSuccessor(1) == BB) {
2276 if (PredHasWeights && SuccHasWeights) {
2277 // PBI: br i1 %x, TrueDest, BB
2278 // BI: br i1 %y, TrueDest, FalseDest
2279 //TrueWeight is TrueWeight for PBI * TotalWeight for BI +
2280 // FalseWeight for PBI * TrueWeight for BI.
2281 NewWeights.push_back(PredTrueWeight * (SuccFalseWeight +
2282 SuccTrueWeight) + PredFalseWeight * SuccTrueWeight);
2283 //FalseWeight is FalseWeight for PBI * FalseWeight for BI.
2284 NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
2286 AddPredecessorToBlock(FalseDest, PredBlock, BB);
2287 PBI->setSuccessor(1, FalseDest);
2289 if (NewWeights.size() == 2) {
2290 // Halve the weights if any of them cannot fit in an uint32_t
2291 FitWeights(NewWeights);
2293 SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),NewWeights.end());
2294 PBI->setMetadata(LLVMContext::MD_prof,
2295 MDBuilder(BI->getContext()).
2296 createBranchWeights(MDWeights));
2298 PBI->setMetadata(LLVMContext::MD_prof, nullptr);
2300 // Update PHI nodes in the common successors.
2301 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
2302 ConstantInt *PBI_C = cast<ConstantInt>(
2303 PHIs[i]->getIncomingValueForBlock(PBI->getParent()));
2304 assert(PBI_C->getType()->isIntegerTy(1));
2305 Instruction *MergedCond = nullptr;
2306 if (PBI->getSuccessor(0) == TrueDest) {
2307 // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value)
2308 // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value)
2309 // is false: !PBI_Cond and BI_Value
2310 Instruction *NotCond =
2311 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2314 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2319 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2320 PBI->getCondition(), MergedCond,
2323 // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C)
2324 // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond)
2325 // is false: PBI_Cond and BI_Value
2327 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2328 PBI->getCondition(), New,
2330 if (PBI_C->isOne()) {
2331 Instruction *NotCond =
2332 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2335 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2336 NotCond, MergedCond,
2341 PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()),
2344 // Change PBI from Conditional to Unconditional.
2345 BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI);
2346 EraseTerminatorInstAndDCECond(PBI);
2350 // TODO: If BB is reachable from all paths through PredBlock, then we
2351 // could replace PBI's branch probabilities with BI's.
2353 // Copy any debug value intrinsics into the end of PredBlock.
2354 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
2355 if (isa<DbgInfoIntrinsic>(*I))
2356 I->clone()->insertBefore(PBI);
2363 /// SimplifyCondBranchToCondBranch - If we have a conditional branch as a
2364 /// predecessor of another block, this function tries to simplify it. We know
2365 /// that PBI and BI are both conditional branches, and BI is in one of the
2366 /// successor blocks of PBI - PBI branches to BI.
2367 static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI) {
2368 assert(PBI->isConditional() && BI->isConditional());
2369 BasicBlock *BB = BI->getParent();
2371 // If this block ends with a branch instruction, and if there is a
2372 // predecessor that ends on a branch of the same condition, make
2373 // this conditional branch redundant.
2374 if (PBI->getCondition() == BI->getCondition() &&
2375 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2376 // Okay, the outcome of this conditional branch is statically
2377 // knowable. If this block had a single pred, handle specially.
2378 if (BB->getSinglePredecessor()) {
2379 // Turn this into a branch on constant.
2380 bool CondIsTrue = PBI->getSuccessor(0) == BB;
2381 BI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
2383 return true; // Nuke the branch on constant.
2386 // Otherwise, if there are multiple predecessors, insert a PHI that merges
2387 // in the constant and simplify the block result. Subsequent passes of
2388 // simplifycfg will thread the block.
2389 if (BlockIsSimpleEnoughToThreadThrough(BB)) {
2390 pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
2391 PHINode *NewPN = PHINode::Create(Type::getInt1Ty(BB->getContext()),
2392 std::distance(PB, PE),
2393 BI->getCondition()->getName() + ".pr",
2395 // Okay, we're going to insert the PHI node. Since PBI is not the only
2396 // predecessor, compute the PHI'd conditional value for all of the preds.
2397 // Any predecessor where the condition is not computable we keep symbolic.
2398 for (pred_iterator PI = PB; PI != PE; ++PI) {
2399 BasicBlock *P = *PI;
2400 if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) &&
2401 PBI != BI && PBI->isConditional() &&
2402 PBI->getCondition() == BI->getCondition() &&
2403 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2404 bool CondIsTrue = PBI->getSuccessor(0) == BB;
2405 NewPN->addIncoming(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
2408 NewPN->addIncoming(BI->getCondition(), P);
2412 BI->setCondition(NewPN);
2417 // If this is a conditional branch in an empty block, and if any
2418 // predecessors are a conditional branch to one of our destinations,
2419 // fold the conditions into logical ops and one cond br.
2420 BasicBlock::iterator BBI = BB->begin();
2421 // Ignore dbg intrinsics.
2422 while (isa<DbgInfoIntrinsic>(BBI))
2428 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
2433 if (PBI->getSuccessor(0) == BI->getSuccessor(0))
2435 else if (PBI->getSuccessor(0) == BI->getSuccessor(1))
2436 PBIOp = 0, BIOp = 1;
2437 else if (PBI->getSuccessor(1) == BI->getSuccessor(0))
2438 PBIOp = 1, BIOp = 0;
2439 else if (PBI->getSuccessor(1) == BI->getSuccessor(1))
2444 // Check to make sure that the other destination of this branch
2445 // isn't BB itself. If so, this is an infinite loop that will
2446 // keep getting unwound.
2447 if (PBI->getSuccessor(PBIOp) == BB)
2450 // Do not perform this transformation if it would require
2451 // insertion of a large number of select instructions. For targets
2452 // without predication/cmovs, this is a big pessimization.
2454 // Also do not perform this transformation if any phi node in the common
2455 // destination block can trap when reached by BB or PBB (PR17073). In that
2456 // case, it would be unsafe to hoist the operation into a select instruction.
2458 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
2459 unsigned NumPhis = 0;
2460 for (BasicBlock::iterator II = CommonDest->begin();
2461 isa<PHINode>(II); ++II, ++NumPhis) {
2462 if (NumPhis > 2) // Disable this xform.
2465 PHINode *PN = cast<PHINode>(II);
2466 Value *BIV = PN->getIncomingValueForBlock(BB);
2467 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV))
2471 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2472 Value *PBIV = PN->getIncomingValue(PBBIdx);
2473 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV))
2478 // Finally, if everything is ok, fold the branches to logical ops.
2479 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
2481 DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
2482 << "AND: " << *BI->getParent());
2485 // If OtherDest *is* BB, then BB is a basic block with a single conditional
2486 // branch in it, where one edge (OtherDest) goes back to itself but the other
2487 // exits. We don't *know* that the program avoids the infinite loop
2488 // (even though that seems likely). If we do this xform naively, we'll end up
2489 // recursively unpeeling the loop. Since we know that (after the xform is
2490 // done) that the block *is* infinite if reached, we just make it an obviously
2491 // infinite loop with no cond branch.
2492 if (OtherDest == BB) {
2493 // Insert it at the end of the function, because it's either code,
2494 // or it won't matter if it's hot. :)
2495 BasicBlock *InfLoopBlock = BasicBlock::Create(BB->getContext(),
2496 "infloop", BB->getParent());
2497 BranchInst::Create(InfLoopBlock, InfLoopBlock);
2498 OtherDest = InfLoopBlock;
2501 DEBUG(dbgs() << *PBI->getParent()->getParent());
2503 // BI may have other predecessors. Because of this, we leave
2504 // it alone, but modify PBI.
2506 // Make sure we get to CommonDest on True&True directions.
2507 Value *PBICond = PBI->getCondition();
2508 IRBuilder<true, NoFolder> Builder(PBI);
2510 PBICond = Builder.CreateNot(PBICond, PBICond->getName()+".not");
2512 Value *BICond = BI->getCondition();
2514 BICond = Builder.CreateNot(BICond, BICond->getName()+".not");
2516 // Merge the conditions.
2517 Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
2519 // Modify PBI to branch on the new condition to the new dests.
2520 PBI->setCondition(Cond);
2521 PBI->setSuccessor(0, CommonDest);
2522 PBI->setSuccessor(1, OtherDest);
2524 // Update branch weight for PBI.
2525 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2526 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2528 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2530 if (PredHasWeights && SuccHasWeights) {
2531 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
2532 uint64_t PredOther = PBIOp ?PredTrueWeight : PredFalseWeight;
2533 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
2534 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
2535 // The weight to CommonDest should be PredCommon * SuccTotal +
2536 // PredOther * SuccCommon.
2537 // The weight to OtherDest should be PredOther * SuccOther.
2538 SmallVector<uint64_t, 2> NewWeights;
2539 NewWeights.push_back(PredCommon * (SuccCommon + SuccOther) +
2540 PredOther * SuccCommon);
2541 NewWeights.push_back(PredOther * SuccOther);
2542 // Halve the weights if any of them cannot fit in an uint32_t
2543 FitWeights(NewWeights);
2545 SmallVector<uint32_t, 2> MDWeights(NewWeights.begin(),NewWeights.end());
2546 PBI->setMetadata(LLVMContext::MD_prof,
2547 MDBuilder(BI->getContext()).
2548 createBranchWeights(MDWeights));
2551 // OtherDest may have phi nodes. If so, add an entry from PBI's
2552 // block that are identical to the entries for BI's block.
2553 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
2555 // We know that the CommonDest already had an edge from PBI to
2556 // it. If it has PHIs though, the PHIs may have different
2557 // entries for BB and PBI's BB. If so, insert a select to make
2560 for (BasicBlock::iterator II = CommonDest->begin();
2561 (PN = dyn_cast<PHINode>(II)); ++II) {
2562 Value *BIV = PN->getIncomingValueForBlock(BB);
2563 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2564 Value *PBIV = PN->getIncomingValue(PBBIdx);
2566 // Insert a select in PBI to pick the right value.
2567 Value *NV = cast<SelectInst>
2568 (Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName()+".mux"));
2569 PN->setIncomingValue(PBBIdx, NV);
2573 DEBUG(dbgs() << "INTO: " << *PBI->getParent());
2574 DEBUG(dbgs() << *PBI->getParent()->getParent());
2576 // This basic block is probably dead. We know it has at least
2577 // one fewer predecessor.
2581 // SimplifyTerminatorOnSelect - Simplifies a terminator by replacing it with a
2582 // branch to TrueBB if Cond is true or to FalseBB if Cond is false.
2583 // Takes care of updating the successors and removing the old terminator.
2584 // Also makes sure not to introduce new successors by assuming that edges to
2585 // non-successor TrueBBs and FalseBBs aren't reachable.
2586 static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond,
2587 BasicBlock *TrueBB, BasicBlock *FalseBB,
2588 uint32_t TrueWeight,
2589 uint32_t FalseWeight){
2590 // Remove any superfluous successor edges from the CFG.
2591 // First, figure out which successors to preserve.
2592 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
2594 BasicBlock *KeepEdge1 = TrueBB;
2595 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
2597 // Then remove the rest.
2598 for (unsigned I = 0, E = OldTerm->getNumSuccessors(); I != E; ++I) {
2599 BasicBlock *Succ = OldTerm->getSuccessor(I);
2600 // Make sure only to keep exactly one copy of each edge.
2601 if (Succ == KeepEdge1)
2602 KeepEdge1 = nullptr;
2603 else if (Succ == KeepEdge2)
2604 KeepEdge2 = nullptr;
2606 Succ->removePredecessor(OldTerm->getParent());
2609 IRBuilder<> Builder(OldTerm);
2610 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
2612 // Insert an appropriate new terminator.
2613 if (!KeepEdge1 && !KeepEdge2) {
2614 if (TrueBB == FalseBB)
2615 // We were only looking for one successor, and it was present.
2616 // Create an unconditional branch to it.
2617 Builder.CreateBr(TrueBB);
2619 // We found both of the successors we were looking for.
2620 // Create a conditional branch sharing the condition of the select.
2621 BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
2622 if (TrueWeight != FalseWeight)
2623 NewBI->setMetadata(LLVMContext::MD_prof,
2624 MDBuilder(OldTerm->getContext()).
2625 createBranchWeights(TrueWeight, FalseWeight));
2627 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
2628 // Neither of the selected blocks were successors, so this
2629 // terminator must be unreachable.
2630 new UnreachableInst(OldTerm->getContext(), OldTerm);
2632 // One of the selected values was a successor, but the other wasn't.
2633 // Insert an unconditional branch to the one that was found;
2634 // the edge to the one that wasn't must be unreachable.
2636 // Only TrueBB was found.
2637 Builder.CreateBr(TrueBB);
2639 // Only FalseBB was found.
2640 Builder.CreateBr(FalseBB);
2643 EraseTerminatorInstAndDCECond(OldTerm);
2647 // SimplifySwitchOnSelect - Replaces
2648 // (switch (select cond, X, Y)) on constant X, Y
2649 // with a branch - conditional if X and Y lead to distinct BBs,
2650 // unconditional otherwise.
2651 static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
2652 // Check for constant integer values in the select.
2653 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
2654 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
2655 if (!TrueVal || !FalseVal)
2658 // Find the relevant condition and destinations.
2659 Value *Condition = Select->getCondition();
2660 BasicBlock *TrueBB = SI->findCaseValue(TrueVal).getCaseSuccessor();
2661 BasicBlock *FalseBB = SI->findCaseValue(FalseVal).getCaseSuccessor();
2663 // Get weight for TrueBB and FalseBB.
2664 uint32_t TrueWeight = 0, FalseWeight = 0;
2665 SmallVector<uint64_t, 8> Weights;
2666 bool HasWeights = HasBranchWeights(SI);
2668 GetBranchWeights(SI, Weights);
2669 if (Weights.size() == 1 + SI->getNumCases()) {
2670 TrueWeight = (uint32_t)Weights[SI->findCaseValue(TrueVal).
2671 getSuccessorIndex()];
2672 FalseWeight = (uint32_t)Weights[SI->findCaseValue(FalseVal).
2673 getSuccessorIndex()];
2677 // Perform the actual simplification.
2678 return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB,
2679 TrueWeight, FalseWeight);
2682 // SimplifyIndirectBrOnSelect - Replaces
2683 // (indirectbr (select cond, blockaddress(@fn, BlockA),
2684 // blockaddress(@fn, BlockB)))
2686 // (br cond, BlockA, BlockB).
2687 static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
2688 // Check that both operands of the select are block addresses.
2689 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
2690 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
2694 // Extract the actual blocks.
2695 BasicBlock *TrueBB = TBA->getBasicBlock();
2696 BasicBlock *FalseBB = FBA->getBasicBlock();
2698 // Perform the actual simplification.
2699 return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB,
2703 /// TryToSimplifyUncondBranchWithICmpInIt - This is called when we find an icmp
2704 /// instruction (a seteq/setne with a constant) as the only instruction in a
2705 /// block that ends with an uncond branch. We are looking for a very specific
2706 /// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
2707 /// this case, we merge the first two "or's of icmp" into a switch, but then the
2708 /// default value goes to an uncond block with a seteq in it, we get something
2711 /// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
2713 /// %tmp = icmp eq i8 %A, 92
2716 /// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
2718 /// We prefer to split the edge to 'end' so that there is a true/false entry to
2719 /// the PHI, merging the third icmp into the switch.
2720 static bool TryToSimplifyUncondBranchWithICmpInIt(
2721 ICmpInst *ICI, IRBuilder<> &Builder, const TargetTransformInfo &TTI,
2722 unsigned BonusInstThreshold, const DataLayout *DL, AssumptionTracker *AT) {
2723 BasicBlock *BB = ICI->getParent();
2725 // If the block has any PHIs in it or the icmp has multiple uses, it is too
2727 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) return false;
2729 Value *V = ICI->getOperand(0);
2730 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
2732 // The pattern we're looking for is where our only predecessor is a switch on
2733 // 'V' and this block is the default case for the switch. In this case we can
2734 // fold the compared value into the switch to simplify things.
2735 BasicBlock *Pred = BB->getSinglePredecessor();
2736 if (!Pred || !isa<SwitchInst>(Pred->getTerminator())) return false;
2738 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
2739 if (SI->getCondition() != V)
2742 // If BB is reachable on a non-default case, then we simply know the value of
2743 // V in this block. Substitute it and constant fold the icmp instruction
2745 if (SI->getDefaultDest() != BB) {
2746 ConstantInt *VVal = SI->findCaseDest(BB);
2747 assert(VVal && "Should have a unique destination value");
2748 ICI->setOperand(0, VVal);
2750 if (Value *V = SimplifyInstruction(ICI, DL)) {
2751 ICI->replaceAllUsesWith(V);
2752 ICI->eraseFromParent();
2754 // BB is now empty, so it is likely to simplify away.
2755 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
2758 // Ok, the block is reachable from the default dest. If the constant we're
2759 // comparing exists in one of the other edges, then we can constant fold ICI
2761 if (SI->findCaseValue(Cst) != SI->case_default()) {
2763 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
2764 V = ConstantInt::getFalse(BB->getContext());
2766 V = ConstantInt::getTrue(BB->getContext());
2768 ICI->replaceAllUsesWith(V);
2769 ICI->eraseFromParent();
2770 // BB is now empty, so it is likely to simplify away.
2771 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
2774 // The use of the icmp has to be in the 'end' block, by the only PHI node in
2776 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
2777 PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
2778 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
2779 isa<PHINode>(++BasicBlock::iterator(PHIUse)))
2782 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
2784 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
2785 Constant *NewCst = ConstantInt::getFalse(BB->getContext());
2787 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
2788 std::swap(DefaultCst, NewCst);
2790 // Replace ICI (which is used by the PHI for the default value) with true or
2791 // false depending on if it is EQ or NE.
2792 ICI->replaceAllUsesWith(DefaultCst);
2793 ICI->eraseFromParent();
2795 // Okay, the switch goes to this block on a default value. Add an edge from
2796 // the switch to the merge point on the compared value.
2797 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "switch.edge",
2798 BB->getParent(), BB);
2799 SmallVector<uint64_t, 8> Weights;
2800 bool HasWeights = HasBranchWeights(SI);
2802 GetBranchWeights(SI, Weights);
2803 if (Weights.size() == 1 + SI->getNumCases()) {
2804 // Split weight for default case to case for "Cst".
2805 Weights[0] = (Weights[0]+1) >> 1;
2806 Weights.push_back(Weights[0]);
2808 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
2809 SI->setMetadata(LLVMContext::MD_prof,
2810 MDBuilder(SI->getContext()).
2811 createBranchWeights(MDWeights));
2814 SI->addCase(Cst, NewBB);
2816 // NewBB branches to the phi block, add the uncond branch and the phi entry.
2817 Builder.SetInsertPoint(NewBB);
2818 Builder.SetCurrentDebugLocation(SI->getDebugLoc());
2819 Builder.CreateBr(SuccBlock);
2820 PHIUse->addIncoming(NewCst, NewBB);
2824 /// SimplifyBranchOnICmpChain - The specified branch is a conditional branch.
2825 /// Check to see if it is branching on an or/and chain of icmp instructions, and
2826 /// fold it into a switch instruction if so.
2827 static bool SimplifyBranchOnICmpChain(BranchInst *BI, const DataLayout *DL,
2828 IRBuilder<> &Builder) {
2829 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
2830 if (!Cond) return false;
2832 // Change br (X == 0 | X == 1), T, F into a switch instruction.
2833 // If this is a bunch of seteq's or'd together, or if it's a bunch of
2834 // 'setne's and'ed together, collect them.
2836 // Try to gather values from a chain of and/or to be turned into a switch
2837 ConstantComparesGatherer ConstantCompare(Cond, DL);
2838 // Unpack the result
2839 SmallVectorImpl<ConstantInt*> &Values = ConstantCompare.Vals;
2840 Value *CompVal = ConstantCompare.CompValue;
2841 unsigned UsedICmps = ConstantCompare.UsedICmps;
2842 Value *ExtraCase = ConstantCompare.Extra;
2844 // If we didn't have a multiply compared value, fail.
2845 if (!CompVal) return false;
2847 // Avoid turning single icmps into a switch.
2851 bool TrueWhenEqual = (Cond->getOpcode() == Instruction::Or);
2853 // There might be duplicate constants in the list, which the switch
2854 // instruction can't handle, remove them now.
2855 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
2856 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
2858 // If Extra was used, we require at least two switch values to do the
2859 // transformation. A switch with one value is just an cond branch.
2860 if (ExtraCase && Values.size() < 2) return false;
2862 // TODO: Preserve branch weight metadata, similarly to how
2863 // FoldValueComparisonIntoPredecessors preserves it.
2865 // Figure out which block is which destination.
2866 BasicBlock *DefaultBB = BI->getSuccessor(1);
2867 BasicBlock *EdgeBB = BI->getSuccessor(0);
2868 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
2870 BasicBlock *BB = BI->getParent();
2872 DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
2873 << " cases into SWITCH. BB is:\n" << *BB);
2875 // If there are any extra values that couldn't be folded into the switch
2876 // then we evaluate them with an explicit branch first. Split the block
2877 // right before the condbr to handle it.
2879 BasicBlock *NewBB = BB->splitBasicBlock(BI, "switch.early.test");
2880 // Remove the uncond branch added to the old block.
2881 TerminatorInst *OldTI = BB->getTerminator();
2882 Builder.SetInsertPoint(OldTI);
2885 Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
2887 Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
2889 OldTI->eraseFromParent();
2891 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
2892 // for the edge we just added.
2893 AddPredecessorToBlock(EdgeBB, BB, NewBB);
2895 DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
2896 << "\nEXTRABB = " << *BB);
2900 Builder.SetInsertPoint(BI);
2901 // Convert pointer to int before we switch.
2902 if (CompVal->getType()->isPointerTy()) {
2903 assert(DL && "Cannot switch on pointer without DataLayout");
2904 CompVal = Builder.CreatePtrToInt(CompVal,
2905 DL->getIntPtrType(CompVal->getType()),
2909 // Create the new switch instruction now.
2910 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
2912 // Add all of the 'cases' to the switch instruction.
2913 for (unsigned i = 0, e = Values.size(); i != e; ++i)
2914 New->addCase(Values[i], EdgeBB);
2916 // We added edges from PI to the EdgeBB. As such, if there were any
2917 // PHI nodes in EdgeBB, they need entries to be added corresponding to
2918 // the number of edges added.
2919 for (BasicBlock::iterator BBI = EdgeBB->begin();
2920 isa<PHINode>(BBI); ++BBI) {
2921 PHINode *PN = cast<PHINode>(BBI);
2922 Value *InVal = PN->getIncomingValueForBlock(BB);
2923 for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
2924 PN->addIncoming(InVal, BB);
2927 // Erase the old branch instruction.
2928 EraseTerminatorInstAndDCECond(BI);
2930 DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
2934 bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
2935 // If this is a trivial landing pad that just continues unwinding the caught
2936 // exception then zap the landing pad, turning its invokes into calls.
2937 BasicBlock *BB = RI->getParent();
2938 LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI());
2939 if (RI->getValue() != LPInst)
2940 // Not a landing pad, or the resume is not unwinding the exception that
2941 // caused control to branch here.
2944 // Check that there are no other instructions except for debug intrinsics.
2945 BasicBlock::iterator I = LPInst, E = RI;
2947 if (!isa<DbgInfoIntrinsic>(I))
2950 // Turn all invokes that unwind here into calls and delete the basic block.
2951 bool InvokeRequiresTableEntry = false;
2952 bool Changed = false;
2953 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
2954 InvokeInst *II = cast<InvokeInst>((*PI++)->getTerminator());
2956 if (II->hasFnAttr(Attribute::UWTable)) {
2957 // Don't remove an `invoke' instruction if the ABI requires an entry into
2959 InvokeRequiresTableEntry = true;
2963 SmallVector<Value*, 8> Args(II->op_begin(), II->op_end() - 3);
2965 // Insert a call instruction before the invoke.
2966 CallInst *Call = CallInst::Create(II->getCalledValue(), Args, "", II);
2968 Call->setCallingConv(II->getCallingConv());
2969 Call->setAttributes(II->getAttributes());
2970 Call->setDebugLoc(II->getDebugLoc());
2972 // Anything that used the value produced by the invoke instruction now uses
2973 // the value produced by the call instruction. Note that we do this even
2974 // for void functions and calls with no uses so that the callgraph edge is
2976 II->replaceAllUsesWith(Call);
2977 BB->removePredecessor(II->getParent());
2979 // Insert a branch to the normal destination right before the invoke.
2980 BranchInst::Create(II->getNormalDest(), II);
2982 // Finally, delete the invoke instruction!
2983 II->eraseFromParent();
2987 if (!InvokeRequiresTableEntry)
2988 // The landingpad is now unreachable. Zap it.
2989 BB->eraseFromParent();
2994 bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
2995 BasicBlock *BB = RI->getParent();
2996 if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
2998 // Find predecessors that end with branches.
2999 SmallVector<BasicBlock*, 8> UncondBranchPreds;
3000 SmallVector<BranchInst*, 8> CondBranchPreds;
3001 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
3002 BasicBlock *P = *PI;
3003 TerminatorInst *PTI = P->getTerminator();
3004 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
3005 if (BI->isUnconditional())
3006 UncondBranchPreds.push_back(P);
3008 CondBranchPreds.push_back(BI);
3012 // If we found some, do the transformation!
3013 if (!UncondBranchPreds.empty() && DupRet) {
3014 while (!UncondBranchPreds.empty()) {
3015 BasicBlock *Pred = UncondBranchPreds.pop_back_val();
3016 DEBUG(dbgs() << "FOLDING: " << *BB
3017 << "INTO UNCOND BRANCH PRED: " << *Pred);
3018 (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
3021 // If we eliminated all predecessors of the block, delete the block now.
3022 if (pred_begin(BB) == pred_end(BB))
3023 // We know there are no successors, so just nuke the block.
3024 BB->eraseFromParent();
3029 // Check out all of the conditional branches going to this return
3030 // instruction. If any of them just select between returns, change the
3031 // branch itself into a select/return pair.
3032 while (!CondBranchPreds.empty()) {
3033 BranchInst *BI = CondBranchPreds.pop_back_val();
3035 // Check to see if the non-BB successor is also a return block.
3036 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
3037 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
3038 SimplifyCondBranchToTwoReturns(BI, Builder))
3044 bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
3045 BasicBlock *BB = UI->getParent();
3047 bool Changed = false;
3049 // If there are any instructions immediately before the unreachable that can
3050 // be removed, do so.
3051 while (UI != BB->begin()) {
3052 BasicBlock::iterator BBI = UI;
3054 // Do not delete instructions that can have side effects which might cause
3055 // the unreachable to not be reachable; specifically, calls and volatile
3056 // operations may have this effect.
3057 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break;
3059 if (BBI->mayHaveSideEffects()) {
3060 if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
3061 if (SI->isVolatile())
3063 } else if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
3064 if (LI->isVolatile())
3066 } else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
3067 if (RMWI->isVolatile())
3069 } else if (AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
3070 if (CXI->isVolatile())
3072 } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
3073 !isa<LandingPadInst>(BBI)) {
3076 // Note that deleting LandingPad's here is in fact okay, although it
3077 // involves a bit of subtle reasoning. If this inst is a LandingPad,
3078 // all the predecessors of this block will be the unwind edges of Invokes,
3079 // and we can therefore guarantee this block will be erased.
3082 // Delete this instruction (any uses are guaranteed to be dead)
3083 if (!BBI->use_empty())
3084 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
3085 BBI->eraseFromParent();
3089 // If the unreachable instruction is the first in the block, take a gander
3090 // at all of the predecessors of this instruction, and simplify them.
3091 if (&BB->front() != UI) return Changed;
3093 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
3094 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
3095 TerminatorInst *TI = Preds[i]->getTerminator();
3096 IRBuilder<> Builder(TI);
3097 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
3098 if (BI->isUnconditional()) {
3099 if (BI->getSuccessor(0) == BB) {
3100 new UnreachableInst(TI->getContext(), TI);
3101 TI->eraseFromParent();
3105 if (BI->getSuccessor(0) == BB) {
3106 Builder.CreateBr(BI->getSuccessor(1));
3107 EraseTerminatorInstAndDCECond(BI);
3108 } else if (BI->getSuccessor(1) == BB) {
3109 Builder.CreateBr(BI->getSuccessor(0));
3110 EraseTerminatorInstAndDCECond(BI);
3114 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
3115 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
3117 if (i.getCaseSuccessor() == BB) {
3118 BB->removePredecessor(SI->getParent());
3123 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
3124 if (II->getUnwindDest() == BB) {
3125 // Convert the invoke to a call instruction. This would be a good
3126 // place to note that the call does not throw though.
3127 BranchInst *BI = Builder.CreateBr(II->getNormalDest());
3128 II->removeFromParent(); // Take out of symbol table
3130 // Insert the call now...
3131 SmallVector<Value*, 8> Args(II->op_begin(), II->op_end()-3);
3132 Builder.SetInsertPoint(BI);
3133 CallInst *CI = Builder.CreateCall(II->getCalledValue(),
3134 Args, II->getName());
3135 CI->setCallingConv(II->getCallingConv());
3136 CI->setAttributes(II->getAttributes());
3137 // If the invoke produced a value, the call does now instead.
3138 II->replaceAllUsesWith(CI);
3145 // If this block is now dead, remove it.
3146 if (pred_begin(BB) == pred_end(BB) &&
3147 BB != &BB->getParent()->getEntryBlock()) {
3148 // We know there are no successors, so just nuke the block.
3149 BB->eraseFromParent();
3156 /// TurnSwitchRangeIntoICmp - Turns a switch with that contains only a
3157 /// integer range comparison into a sub, an icmp and a branch.
3158 static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
3159 assert(SI->getNumCases() > 1 && "Degenerate switch?");
3161 // Make sure all cases point to the same destination and gather the values.
3162 SmallVector<ConstantInt *, 16> Cases;
3163 SwitchInst::CaseIt I = SI->case_begin();
3164 Cases.push_back(I.getCaseValue());
3165 SwitchInst::CaseIt PrevI = I++;
3166 for (SwitchInst::CaseIt E = SI->case_end(); I != E; PrevI = I++) {
3167 if (PrevI.getCaseSuccessor() != I.getCaseSuccessor())
3169 Cases.push_back(I.getCaseValue());
3171 assert(Cases.size() == SI->getNumCases() && "Not all cases gathered");
3173 // Sort the case values, then check if they form a range we can transform.
3174 array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
3175 for (unsigned I = 1, E = Cases.size(); I != E; ++I) {
3176 if (Cases[I-1]->getValue() != Cases[I]->getValue()+1)
3180 Constant *Offset = ConstantExpr::getNeg(Cases.back());
3181 Constant *NumCases = ConstantInt::get(Offset->getType(), SI->getNumCases());
3183 Value *Sub = SI->getCondition();
3184 if (!Offset->isNullValue())
3185 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName()+".off");
3187 // If NumCases overflowed, then all possible values jump to the successor.
3188 if (NumCases->isNullValue() && SI->getNumCases() != 0)
3189 Cmp = ConstantInt::getTrue(SI->getContext());
3191 Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
3192 BranchInst *NewBI = Builder.CreateCondBr(
3193 Cmp, SI->case_begin().getCaseSuccessor(), SI->getDefaultDest());
3195 // Update weight for the newly-created conditional branch.
3196 SmallVector<uint64_t, 8> Weights;
3197 bool HasWeights = HasBranchWeights(SI);
3199 GetBranchWeights(SI, Weights);
3200 if (Weights.size() == 1 + SI->getNumCases()) {
3201 // Combine all weights for the cases to be the true weight of NewBI.
3202 // We assume that the sum of all weights for a Terminator can fit into 32
3204 uint32_t NewTrueWeight = 0;
3205 for (unsigned I = 1, E = Weights.size(); I != E; ++I)
3206 NewTrueWeight += (uint32_t)Weights[I];
3207 NewBI->setMetadata(LLVMContext::MD_prof,
3208 MDBuilder(SI->getContext()).
3209 createBranchWeights(NewTrueWeight,
3210 (uint32_t)Weights[0]));
3214 // Prune obsolete incoming values off the successor's PHI nodes.
3215 for (BasicBlock::iterator BBI = SI->case_begin().getCaseSuccessor()->begin();
3216 isa<PHINode>(BBI); ++BBI) {
3217 for (unsigned I = 0, E = SI->getNumCases()-1; I != E; ++I)
3218 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
3220 SI->eraseFromParent();
3225 /// EliminateDeadSwitchCases - Compute masked bits for the condition of a switch
3226 /// and use it to remove dead cases.
3227 static bool EliminateDeadSwitchCases(SwitchInst *SI, const DataLayout *DL,
3228 AssumptionTracker *AT) {
3229 Value *Cond = SI->getCondition();
3230 unsigned Bits = Cond->getType()->getIntegerBitWidth();
3231 APInt KnownZero(Bits, 0), KnownOne(Bits, 0);
3232 computeKnownBits(Cond, KnownZero, KnownOne, DL, 0, AT, SI);
3234 // Gather dead cases.
3235 SmallVector<ConstantInt*, 8> DeadCases;
3236 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
3237 if ((I.getCaseValue()->getValue() & KnownZero) != 0 ||
3238 (I.getCaseValue()->getValue() & KnownOne) != KnownOne) {
3239 DeadCases.push_back(I.getCaseValue());
3240 DEBUG(dbgs() << "SimplifyCFG: switch case '"
3241 << I.getCaseValue() << "' is dead.\n");
3245 SmallVector<uint64_t, 8> Weights;
3246 bool HasWeight = HasBranchWeights(SI);
3248 GetBranchWeights(SI, Weights);
3249 HasWeight = (Weights.size() == 1 + SI->getNumCases());
3252 // Remove dead cases from the switch.
3253 for (unsigned I = 0, E = DeadCases.size(); I != E; ++I) {
3254 SwitchInst::CaseIt Case = SI->findCaseValue(DeadCases[I]);
3255 assert(Case != SI->case_default() &&
3256 "Case was not found. Probably mistake in DeadCases forming.");
3258 std::swap(Weights[Case.getCaseIndex()+1], Weights.back());
3262 // Prune unused values from PHI nodes.
3263 Case.getCaseSuccessor()->removePredecessor(SI->getParent());
3264 SI->removeCase(Case);
3266 if (HasWeight && Weights.size() >= 2) {
3267 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
3268 SI->setMetadata(LLVMContext::MD_prof,
3269 MDBuilder(SI->getParent()->getContext()).
3270 createBranchWeights(MDWeights));
3273 return !DeadCases.empty();
3276 /// FindPHIForConditionForwarding - If BB would be eligible for simplification
3277 /// by TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
3278 /// by an unconditional branch), look at the phi node for BB in the successor
3279 /// block and see if the incoming value is equal to CaseValue. If so, return
3280 /// the phi node, and set PhiIndex to BB's index in the phi node.
3281 static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
3284 if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
3285 return nullptr; // BB must be empty to be a candidate for simplification.
3286 if (!BB->getSinglePredecessor())
3287 return nullptr; // BB must be dominated by the switch.
3289 BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
3290 if (!Branch || !Branch->isUnconditional())
3291 return nullptr; // Terminator must be unconditional branch.
3293 BasicBlock *Succ = Branch->getSuccessor(0);
3295 BasicBlock::iterator I = Succ->begin();
3296 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3297 int Idx = PHI->getBasicBlockIndex(BB);
3298 assert(Idx >= 0 && "PHI has no entry for predecessor?");
3300 Value *InValue = PHI->getIncomingValue(Idx);
3301 if (InValue != CaseValue) continue;
3310 /// ForwardSwitchConditionToPHI - Try to forward the condition of a switch
3311 /// instruction to a phi node dominated by the switch, if that would mean that
3312 /// some of the destination blocks of the switch can be folded away.
3313 /// Returns true if a change is made.
3314 static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
3315 typedef DenseMap<PHINode*, SmallVector<int,4> > ForwardingNodesMap;
3316 ForwardingNodesMap ForwardingNodes;
3318 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
3319 ConstantInt *CaseValue = I.getCaseValue();
3320 BasicBlock *CaseDest = I.getCaseSuccessor();
3323 PHINode *PHI = FindPHIForConditionForwarding(CaseValue, CaseDest,
3327 ForwardingNodes[PHI].push_back(PhiIndex);
3330 bool Changed = false;
3332 for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(),
3333 E = ForwardingNodes.end(); I != E; ++I) {
3334 PHINode *Phi = I->first;
3335 SmallVectorImpl<int> &Indexes = I->second;
3337 if (Indexes.size() < 2) continue;
3339 for (size_t I = 0, E = Indexes.size(); I != E; ++I)
3340 Phi->setIncomingValue(Indexes[I], SI->getCondition());
3347 /// ValidLookupTableConstant - Return true if the backend will be able to handle
3348 /// initializing an array of constants like C.
3349 static bool ValidLookupTableConstant(Constant *C) {
3350 if (C->isThreadDependent())
3352 if (C->isDLLImportDependent())
3355 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
3356 return CE->isGEPWithNoNotionalOverIndexing();
3358 return isa<ConstantFP>(C) ||
3359 isa<ConstantInt>(C) ||
3360 isa<ConstantPointerNull>(C) ||
3361 isa<GlobalValue>(C) ||
3365 /// LookupConstant - If V is a Constant, return it. Otherwise, try to look up
3366 /// its constant value in ConstantPool, returning 0 if it's not there.
3367 static Constant *LookupConstant(Value *V,
3368 const SmallDenseMap<Value*, Constant*>& ConstantPool) {
3369 if (Constant *C = dyn_cast<Constant>(V))
3371 return ConstantPool.lookup(V);
3374 /// ConstantFold - Try to fold instruction I into a constant. This works for
3375 /// simple instructions such as binary operations where both operands are
3376 /// constant or can be replaced by constants from the ConstantPool. Returns the
3377 /// resulting constant on success, 0 otherwise.
3379 ConstantFold(Instruction *I,
3380 const SmallDenseMap<Value *, Constant *> &ConstantPool,
3381 const DataLayout *DL) {
3382 if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
3383 Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
3386 if (A->isAllOnesValue())
3387 return LookupConstant(Select->getTrueValue(), ConstantPool);
3388 if (A->isNullValue())
3389 return LookupConstant(Select->getFalseValue(), ConstantPool);
3393 SmallVector<Constant *, 4> COps;
3394 for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
3395 if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
3401 if (CmpInst *Cmp = dyn_cast<CmpInst>(I))
3402 return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0],
3405 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), COps, DL);
3408 /// GetCaseResults - Try to determine the resulting constant values in phi nodes
3409 /// at the common destination basic block, *CommonDest, for one of the case
3410 /// destionations CaseDest corresponding to value CaseVal (0 for the default
3411 /// case), of a switch instruction SI.
3413 GetCaseResults(SwitchInst *SI,
3414 ConstantInt *CaseVal,
3415 BasicBlock *CaseDest,
3416 BasicBlock **CommonDest,
3417 SmallVectorImpl<std::pair<PHINode *, Constant *> > &Res,
3418 const DataLayout *DL) {
3419 // The block from which we enter the common destination.
3420 BasicBlock *Pred = SI->getParent();
3422 // If CaseDest is empty except for some side-effect free instructions through
3423 // which we can constant-propagate the CaseVal, continue to its successor.
3424 SmallDenseMap<Value*, Constant*> ConstantPool;
3425 ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
3426 for (BasicBlock::iterator I = CaseDest->begin(), E = CaseDest->end(); I != E;
3428 if (TerminatorInst *T = dyn_cast<TerminatorInst>(I)) {
3429 // If the terminator is a simple branch, continue to the next block.
3430 if (T->getNumSuccessors() != 1)
3433 CaseDest = T->getSuccessor(0);
3434 } else if (isa<DbgInfoIntrinsic>(I)) {
3435 // Skip debug intrinsic.
3437 } else if (Constant *C = ConstantFold(I, ConstantPool, DL)) {
3438 // Instruction is side-effect free and constant.
3439 ConstantPool.insert(std::make_pair(I, C));
3445 // If we did not have a CommonDest before, use the current one.
3447 *CommonDest = CaseDest;
3448 // If the destination isn't the common one, abort.
3449 if (CaseDest != *CommonDest)
3452 // Get the values for this case from phi nodes in the destination block.
3453 BasicBlock::iterator I = (*CommonDest)->begin();
3454 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3455 int Idx = PHI->getBasicBlockIndex(Pred);
3459 Constant *ConstVal = LookupConstant(PHI->getIncomingValue(Idx),
3464 // Note: If the constant comes from constant-propagating the case value
3465 // through the CaseDest basic block, it will be safe to remove the
3466 // instructions in that block. They cannot be used (except in the phi nodes
3467 // we visit) outside CaseDest, because that block does not dominate its
3468 // successor. If it did, we would not be in this phi node.
3470 // Be conservative about which kinds of constants we support.
3471 if (!ValidLookupTableConstant(ConstVal))
3474 Res.push_back(std::make_pair(PHI, ConstVal));
3477 return Res.size() > 0;
3480 // MapCaseToResult - Helper function used to
3481 // add CaseVal to the list of cases that generate Result.
3482 static void MapCaseToResult(ConstantInt *CaseVal,
3483 SwitchCaseResultVectorTy &UniqueResults,
3485 for (auto &I : UniqueResults) {
3486 if (I.first == Result) {
3487 I.second.push_back(CaseVal);
3491 UniqueResults.push_back(std::make_pair(Result,
3492 SmallVector<ConstantInt*, 4>(1, CaseVal)));
3495 // InitializeUniqueCases - Helper function that initializes a map containing
3496 // results for the PHI node of the common destination block for a switch
3497 // instruction. Returns false if multiple PHI nodes have been found or if
3498 // there is not a common destination block for the switch.
3499 static bool InitializeUniqueCases(
3500 SwitchInst *SI, const DataLayout *DL, PHINode *&PHI,
3501 BasicBlock *&CommonDest,
3502 SwitchCaseResultVectorTy &UniqueResults,
3503 Constant *&DefaultResult) {
3504 for (auto &I : SI->cases()) {
3505 ConstantInt *CaseVal = I.getCaseValue();
3507 // Resulting value at phi nodes for this case value.
3508 SwitchCaseResultsTy Results;
3509 if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results,
3513 // Only one value per case is permitted
3514 if (Results.size() > 1)
3516 MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second);
3518 // Check the PHI consistency.
3520 PHI = Results[0].first;
3521 else if (PHI != Results[0].first)
3524 // Find the default result value.
3525 SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults;
3526 BasicBlock *DefaultDest = SI->getDefaultDest();
3527 GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults,
3529 // If the default value is not found abort unless the default destination
3532 DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr;
3533 if ((!DefaultResult &&
3534 !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg())))
3540 // ConvertTwoCaseSwitch - Helper function that checks if it is possible to
3541 // transform a switch with only two cases (or two cases + default)
3542 // that produces a result into a value select.
3545 // case 10: %0 = icmp eq i32 %a, 10
3546 // return 10; %1 = select i1 %0, i32 10, i32 4
3547 // case 20: ----> %2 = icmp eq i32 %a, 20
3548 // return 2; %3 = select i1 %2, i32 2, i32 %1
3553 ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector,
3554 Constant *DefaultResult, Value *Condition,
3555 IRBuilder<> &Builder) {
3556 assert(ResultVector.size() == 2 &&
3557 "We should have exactly two unique results at this point");
3558 // If we are selecting between only two cases transform into a simple
3559 // select or a two-way select if default is possible.
3560 if (ResultVector[0].second.size() == 1 &&
3561 ResultVector[1].second.size() == 1) {
3562 ConstantInt *const FirstCase = ResultVector[0].second[0];
3563 ConstantInt *const SecondCase = ResultVector[1].second[0];
3565 bool DefaultCanTrigger = DefaultResult;
3566 Value *SelectValue = ResultVector[1].first;
3567 if (DefaultCanTrigger) {
3568 Value *const ValueCompare =
3569 Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp");
3570 SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first,
3571 DefaultResult, "switch.select");
3573 Value *const ValueCompare =
3574 Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp");
3575 return Builder.CreateSelect(ValueCompare, ResultVector[0].first, SelectValue,
3582 // RemoveSwitchAfterSelectConversion - Helper function to cleanup a switch
3583 // instruction that has been converted into a select, fixing up PHI nodes and
3585 static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI,
3587 IRBuilder<> &Builder) {
3588 BasicBlock *SelectBB = SI->getParent();
3589 while (PHI->getBasicBlockIndex(SelectBB) >= 0)
3590 PHI->removeIncomingValue(SelectBB);
3591 PHI->addIncoming(SelectValue, SelectBB);
3593 Builder.CreateBr(PHI->getParent());
3595 // Remove the switch.
3596 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
3597 BasicBlock *Succ = SI->getSuccessor(i);
3599 if (Succ == PHI->getParent())
3601 Succ->removePredecessor(SelectBB);
3603 SI->eraseFromParent();
3606 /// SwitchToSelect - If the switch is only used to initialize one or more
3607 /// phi nodes in a common successor block with only two different
3608 /// constant values, replace the switch with select.
3609 static bool SwitchToSelect(SwitchInst *SI, IRBuilder<> &Builder,
3610 const DataLayout *DL, AssumptionTracker *AT) {
3611 Value *const Cond = SI->getCondition();
3612 PHINode *PHI = nullptr;
3613 BasicBlock *CommonDest = nullptr;
3614 Constant *DefaultResult;
3615 SwitchCaseResultVectorTy UniqueResults;
3616 // Collect all the cases that will deliver the same value from the switch.
3617 if (!InitializeUniqueCases(SI, DL, PHI, CommonDest, UniqueResults,
3620 // Selects choose between maximum two values.
3621 if (UniqueResults.size() != 2)
3623 assert(PHI != nullptr && "PHI for value select not found");
3625 Builder.SetInsertPoint(SI);
3626 Value *SelectValue = ConvertTwoCaseSwitch(
3628 DefaultResult, Cond, Builder);
3630 RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder);
3633 // The switch couldn't be converted into a select.
3638 /// SwitchLookupTable - This class represents a lookup table that can be used
3639 /// to replace a switch.
3640 class SwitchLookupTable {
3642 /// SwitchLookupTable - Create a lookup table to use as a switch replacement
3643 /// with the contents of Values, using DefaultValue to fill any holes in the
3645 SwitchLookupTable(Module &M,
3647 ConstantInt *Offset,
3648 const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values,
3649 Constant *DefaultValue,
3650 const DataLayout *DL);
3652 /// BuildLookup - Build instructions with Builder to retrieve the value at
3653 /// the position given by Index in the lookup table.
3654 Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
3656 /// WouldFitInRegister - Return true if a table with TableSize elements of
3657 /// type ElementType would fit in a target-legal register.
3658 static bool WouldFitInRegister(const DataLayout *DL,
3660 const Type *ElementType);
3663 // Depending on the contents of the table, it can be represented in
3666 // For tables where each element contains the same value, we just have to
3667 // store that single value and return it for each lookup.
3670 // For tables where there is a linear relationship between table index
3671 // and values. We calculate the result with a simple multiplication
3672 // and addition instead of a table lookup.
3675 // For small tables with integer elements, we can pack them into a bitmap
3676 // that fits into a target-legal register. Values are retrieved by
3677 // shift and mask operations.
3680 // The table is stored as an array of values. Values are retrieved by load
3681 // instructions from the table.
3685 // For SingleValueKind, this is the single value.
3686 Constant *SingleValue;
3688 // For BitMapKind, this is the bitmap.
3689 ConstantInt *BitMap;
3690 IntegerType *BitMapElementTy;
3692 // For LinearMapKind, these are the constants used to derive the value.
3693 ConstantInt *LinearOffset;
3694 ConstantInt *LinearMultiplier;
3696 // For ArrayKind, this is the array.
3697 GlobalVariable *Array;
3701 SwitchLookupTable::SwitchLookupTable(Module &M,
3703 ConstantInt *Offset,
3704 const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values,
3705 Constant *DefaultValue,
3706 const DataLayout *DL)
3707 : SingleValue(nullptr), BitMap(nullptr), BitMapElementTy(nullptr),
3708 LinearOffset(nullptr), LinearMultiplier(nullptr), Array(nullptr) {
3709 assert(Values.size() && "Can't build lookup table without values!");
3710 assert(TableSize >= Values.size() && "Can't fit values in table!");
3712 // If all values in the table are equal, this is that value.
3713 SingleValue = Values.begin()->second;
3715 Type *ValueType = Values.begin()->second->getType();
3717 // Build up the table contents.
3718 SmallVector<Constant*, 64> TableContents(TableSize);
3719 for (size_t I = 0, E = Values.size(); I != E; ++I) {
3720 ConstantInt *CaseVal = Values[I].first;
3721 Constant *CaseRes = Values[I].second;
3722 assert(CaseRes->getType() == ValueType);
3724 uint64_t Idx = (CaseVal->getValue() - Offset->getValue())
3726 TableContents[Idx] = CaseRes;
3728 if (CaseRes != SingleValue)
3729 SingleValue = nullptr;
3732 // Fill in any holes in the table with the default result.
3733 if (Values.size() < TableSize) {
3734 assert(DefaultValue &&
3735 "Need a default value to fill the lookup table holes.");
3736 assert(DefaultValue->getType() == ValueType);
3737 for (uint64_t I = 0; I < TableSize; ++I) {
3738 if (!TableContents[I])
3739 TableContents[I] = DefaultValue;
3742 if (DefaultValue != SingleValue)
3743 SingleValue = nullptr;
3746 // If each element in the table contains the same value, we only need to store
3747 // that single value.
3749 Kind = SingleValueKind;
3753 // Check if we can derive the value with a linear transformation from the
3755 if (isa<IntegerType>(ValueType)) {
3756 bool LinearMappingPossible = true;
3759 assert(TableSize >= 2 && "Should be a SingleValue table.");
3760 // Check if there is the same distance between two consecutive values.
3761 for (uint64_t I = 0; I < TableSize; ++I) {
3762 ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]);
3764 // This is an undef. We could deal with it, but undefs in lookup tables
3765 // are very seldom. It's probably not worth the additional complexity.
3766 LinearMappingPossible = false;
3769 APInt Val = ConstVal->getValue();
3771 APInt Dist = Val - PrevVal;
3774 } else if (Dist != DistToPrev) {
3775 LinearMappingPossible = false;
3781 if (LinearMappingPossible) {
3782 LinearOffset = cast<ConstantInt>(TableContents[0]);
3783 LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev);
3784 Kind = LinearMapKind;
3790 // If the type is integer and the table fits in a register, build a bitmap.
3791 if (WouldFitInRegister(DL, TableSize, ValueType)) {
3792 IntegerType *IT = cast<IntegerType>(ValueType);
3793 APInt TableInt(TableSize * IT->getBitWidth(), 0);
3794 for (uint64_t I = TableSize; I > 0; --I) {
3795 TableInt <<= IT->getBitWidth();
3796 // Insert values into the bitmap. Undef values are set to zero.
3797 if (!isa<UndefValue>(TableContents[I - 1])) {
3798 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
3799 TableInt |= Val->getValue().zext(TableInt.getBitWidth());
3802 BitMap = ConstantInt::get(M.getContext(), TableInt);
3803 BitMapElementTy = IT;
3809 // Store the table in an array.
3810 ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
3811 Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
3813 Array = new GlobalVariable(M, ArrayTy, /*constant=*/ true,
3814 GlobalVariable::PrivateLinkage,
3817 Array->setUnnamedAddr(true);
3821 Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
3823 case SingleValueKind:
3825 case LinearMapKind: {
3826 // Derive the result value from the input value.
3827 Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(),
3828 false, "switch.idx.cast");
3829 if (!LinearMultiplier->isOne())
3830 Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult");
3831 if (!LinearOffset->isZero())
3832 Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset");
3836 // Type of the bitmap (e.g. i59).
3837 IntegerType *MapTy = BitMap->getType();
3839 // Cast Index to the same type as the bitmap.
3840 // Note: The Index is <= the number of elements in the table, so
3841 // truncating it to the width of the bitmask is safe.
3842 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
3844 // Multiply the shift amount by the element width.
3845 ShiftAmt = Builder.CreateMul(ShiftAmt,
3846 ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
3850 Value *DownShifted = Builder.CreateLShr(BitMap, ShiftAmt,
3851 "switch.downshift");
3853 return Builder.CreateTrunc(DownShifted, BitMapElementTy,
3857 // Make sure the table index will not overflow when treated as signed.
3858 IntegerType *IT = cast<IntegerType>(Index->getType());
3859 uint64_t TableSize = Array->getInitializer()->getType()
3860 ->getArrayNumElements();
3861 if (TableSize > (1ULL << (IT->getBitWidth() - 1)))
3862 Index = Builder.CreateZExt(Index,
3863 IntegerType::get(IT->getContext(),
3864 IT->getBitWidth() + 1),
3865 "switch.tableidx.zext");
3867 Value *GEPIndices[] = { Builder.getInt32(0), Index };
3868 Value *GEP = Builder.CreateInBoundsGEP(Array, GEPIndices,
3870 return Builder.CreateLoad(GEP, "switch.load");
3873 llvm_unreachable("Unknown lookup table kind!");
3876 bool SwitchLookupTable::WouldFitInRegister(const DataLayout *DL,
3878 const Type *ElementType) {
3881 const IntegerType *IT = dyn_cast<IntegerType>(ElementType);
3884 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
3885 // are <= 15, we could try to narrow the type.
3887 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
3888 if (TableSize >= UINT_MAX/IT->getBitWidth())
3890 return DL->fitsInLegalInteger(TableSize * IT->getBitWidth());
3893 /// ShouldBuildLookupTable - Determine whether a lookup table should be built
3894 /// for this switch, based on the number of cases, size of the table and the
3895 /// types of the results.
3896 static bool ShouldBuildLookupTable(SwitchInst *SI,
3898 const TargetTransformInfo &TTI,
3899 const DataLayout *DL,
3900 const SmallDenseMap<PHINode*, Type*>& ResultTypes) {
3901 if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
3902 return false; // TableSize overflowed, or mul below might overflow.
3904 bool AllTablesFitInRegister = true;
3905 bool HasIllegalType = false;
3906 for (const auto &I : ResultTypes) {
3907 Type *Ty = I.second;
3909 // Saturate this flag to true.
3910 HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty);
3912 // Saturate this flag to false.
3913 AllTablesFitInRegister = AllTablesFitInRegister &&
3914 SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
3916 // If both flags saturate, we're done. NOTE: This *only* works with
3917 // saturating flags, and all flags have to saturate first due to the
3918 // non-deterministic behavior of iterating over a dense map.
3919 if (HasIllegalType && !AllTablesFitInRegister)
3923 // If each table would fit in a register, we should build it anyway.
3924 if (AllTablesFitInRegister)
3927 // Don't build a table that doesn't fit in-register if it has illegal types.
3931 // The table density should be at least 40%. This is the same criterion as for
3932 // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
3933 // FIXME: Find the best cut-off.
3934 return SI->getNumCases() * 10 >= TableSize * 4;
3937 /// Try to reuse the switch table index compare. Following pattern:
3939 /// if (idx < tablesize)
3940 /// r = table[idx]; // table does not contain default_value
3942 /// r = default_value;
3943 /// if (r != default_value)
3946 /// Is optimized to:
3948 /// cond = idx < tablesize;
3952 /// r = default_value;
3956 /// Jump threading will then eliminate the second if(cond).
3957 static void reuseTableCompare(User *PhiUser, BasicBlock *PhiBlock,
3958 BranchInst *RangeCheckBranch, Constant *DefaultValue,
3959 const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values) {
3961 ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser);
3965 // We require that the compare is in the same block as the phi so that jump
3966 // threading can do its work afterwards.
3967 if (CmpInst->getParent() != PhiBlock)
3970 Constant *CmpOp1 = dyn_cast<Constant>(CmpInst->getOperand(1));
3974 Value *RangeCmp = RangeCheckBranch->getCondition();
3975 Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType());
3976 Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType());
3978 // Check if the compare with the default value is constant true or false.
3979 Constant *DefaultConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
3980 DefaultValue, CmpOp1, true);
3981 if (DefaultConst != TrueConst && DefaultConst != FalseConst)
3984 // Check if the compare with the case values is distinct from the default
3986 for (auto ValuePair : Values) {
3987 Constant *CaseConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
3988 ValuePair.second, CmpOp1, true);
3989 if (!CaseConst || CaseConst == DefaultConst)
3991 assert((CaseConst == TrueConst || CaseConst == FalseConst) &&
3992 "Expect true or false as compare result.");
3995 // Check if the branch instruction dominates the phi node. It's a simple
3996 // dominance check, but sufficient for our needs.
3997 // Although this check is invariant in the calling loops, it's better to do it
3998 // at this late stage. Practically we do it at most once for a switch.
3999 BasicBlock *BranchBlock = RangeCheckBranch->getParent();
4000 for (auto PI = pred_begin(PhiBlock), E = pred_end(PhiBlock); PI != E; ++PI) {
4001 BasicBlock *Pred = *PI;
4002 if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock)
4006 if (DefaultConst == FalseConst) {
4007 // The compare yields the same result. We can replace it.
4008 CmpInst->replaceAllUsesWith(RangeCmp);
4009 ++NumTableCmpReuses;
4011 // The compare yields the same result, just inverted. We can replace it.
4012 Value *InvertedTableCmp = BinaryOperator::CreateXor(RangeCmp,
4013 ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp",
4015 CmpInst->replaceAllUsesWith(InvertedTableCmp);
4016 ++NumTableCmpReuses;
4020 /// SwitchToLookupTable - If the switch is only used to initialize one or more
4021 /// phi nodes in a common successor block with different constant values,
4022 /// replace the switch with lookup tables.
4023 static bool SwitchToLookupTable(SwitchInst *SI,
4024 IRBuilder<> &Builder,
4025 const TargetTransformInfo &TTI,
4026 const DataLayout* DL) {
4027 assert(SI->getNumCases() > 1 && "Degenerate switch?");
4029 // Only build lookup table when we have a target that supports it.
4030 if (!TTI.shouldBuildLookupTables())
4033 // FIXME: If the switch is too sparse for a lookup table, perhaps we could
4034 // split off a dense part and build a lookup table for that.
4036 // FIXME: This creates arrays of GEPs to constant strings, which means each
4037 // GEP needs a runtime relocation in PIC code. We should just build one big
4038 // string and lookup indices into that.
4040 // Ignore switches with less than three cases. Lookup tables will not make them
4041 // faster, so we don't analyze them.
4042 if (SI->getNumCases() < 3)
4045 // Figure out the corresponding result for each case value and phi node in the
4046 // common destination, as well as the the min and max case values.
4047 assert(SI->case_begin() != SI->case_end());
4048 SwitchInst::CaseIt CI = SI->case_begin();
4049 ConstantInt *MinCaseVal = CI.getCaseValue();
4050 ConstantInt *MaxCaseVal = CI.getCaseValue();
4052 BasicBlock *CommonDest = nullptr;
4053 typedef SmallVector<std::pair<ConstantInt*, Constant*>, 4> ResultListTy;
4054 SmallDenseMap<PHINode*, ResultListTy> ResultLists;
4055 SmallDenseMap<PHINode*, Constant*> DefaultResults;
4056 SmallDenseMap<PHINode*, Type*> ResultTypes;
4057 SmallVector<PHINode*, 4> PHIs;
4059 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
4060 ConstantInt *CaseVal = CI.getCaseValue();
4061 if (CaseVal->getValue().slt(MinCaseVal->getValue()))
4062 MinCaseVal = CaseVal;
4063 if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
4064 MaxCaseVal = CaseVal;
4066 // Resulting value at phi nodes for this case value.
4067 typedef SmallVector<std::pair<PHINode*, Constant*>, 4> ResultsTy;
4069 if (!GetCaseResults(SI, CaseVal, CI.getCaseSuccessor(), &CommonDest,
4073 // Append the result from this case to the list for each phi.
4074 for (const auto &I : Results) {
4075 PHINode *PHI = I.first;
4076 Constant *Value = I.second;
4077 if (!ResultLists.count(PHI))
4078 PHIs.push_back(PHI);
4079 ResultLists[PHI].push_back(std::make_pair(CaseVal, Value));
4083 // Keep track of the result types.
4084 for (PHINode *PHI : PHIs) {
4085 ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
4088 uint64_t NumResults = ResultLists[PHIs[0]].size();
4089 APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
4090 uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
4091 bool TableHasHoles = (NumResults < TableSize);
4093 // If the table has holes, we need a constant result for the default case
4094 // or a bitmask that fits in a register.
4095 SmallVector<std::pair<PHINode*, Constant*>, 4> DefaultResultsList;
4096 bool HasDefaultResults = GetCaseResults(SI, nullptr, SI->getDefaultDest(),
4097 &CommonDest, DefaultResultsList, DL);
4099 bool NeedMask = (TableHasHoles && !HasDefaultResults);
4101 // As an extra penalty for the validity test we require more cases.
4102 if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
4104 if (!(DL && DL->fitsInLegalInteger(TableSize)))
4108 for (const auto &I : DefaultResultsList) {
4109 PHINode *PHI = I.first;
4110 Constant *Result = I.second;
4111 DefaultResults[PHI] = Result;
4114 if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
4117 // Create the BB that does the lookups.
4118 Module &Mod = *CommonDest->getParent()->getParent();
4119 BasicBlock *LookupBB = BasicBlock::Create(Mod.getContext(),
4121 CommonDest->getParent(),
4124 // Compute the table index value.
4125 Builder.SetInsertPoint(SI);
4126 Value *TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal,
4129 // Compute the maximum table size representable by the integer type we are
4131 unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
4132 uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
4133 assert(MaxTableSize >= TableSize &&
4134 "It is impossible for a switch to have more entries than the max "
4135 "representable value of its input integer type's size.");
4137 // If we have a fully covered lookup table, unconditionally branch to the
4138 // lookup table BB. Otherwise, check if the condition value is within the case
4139 // range. If it is so, branch to the new BB. Otherwise branch to SI's default
4141 BranchInst *RangeCheckBranch = nullptr;
4143 const bool GeneratingCoveredLookupTable = MaxTableSize == TableSize;
4144 if (GeneratingCoveredLookupTable) {
4145 Builder.CreateBr(LookupBB);
4146 // We cached PHINodes in PHIs, to avoid accessing deleted PHINodes later,
4147 // do not delete PHINodes here.
4148 SI->getDefaultDest()->removePredecessor(SI->getParent(),
4149 true/*DontDeleteUselessPHIs*/);
4151 Value *Cmp = Builder.CreateICmpULT(TableIndex, ConstantInt::get(
4152 MinCaseVal->getType(), TableSize));
4153 RangeCheckBranch = Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
4156 // Populate the BB that does the lookups.
4157 Builder.SetInsertPoint(LookupBB);
4160 // Before doing the lookup we do the hole check.
4161 // The LookupBB is therefore re-purposed to do the hole check
4162 // and we create a new LookupBB.
4163 BasicBlock *MaskBB = LookupBB;
4164 MaskBB->setName("switch.hole_check");
4165 LookupBB = BasicBlock::Create(Mod.getContext(),
4167 CommonDest->getParent(),
4170 // Make the mask's bitwidth at least 8bit and a power-of-2 to avoid
4171 // unnecessary illegal types.
4172 uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL));
4173 APInt MaskInt(TableSizePowOf2, 0);
4174 APInt One(TableSizePowOf2, 1);
4175 // Build bitmask; fill in a 1 bit for every case.
4176 const ResultListTy &ResultList = ResultLists[PHIs[0]];
4177 for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
4178 uint64_t Idx = (ResultList[I].first->getValue() -
4179 MinCaseVal->getValue()).getLimitedValue();
4180 MaskInt |= One << Idx;
4182 ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
4184 // Get the TableIndex'th bit of the bitmask.
4185 // If this bit is 0 (meaning hole) jump to the default destination,
4186 // else continue with table lookup.
4187 IntegerType *MapTy = TableMask->getType();
4188 Value *MaskIndex = Builder.CreateZExtOrTrunc(TableIndex, MapTy,
4189 "switch.maskindex");
4190 Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex,
4192 Value *LoBit = Builder.CreateTrunc(Shifted,
4193 Type::getInt1Ty(Mod.getContext()),
4195 Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
4197 Builder.SetInsertPoint(LookupBB);
4198 AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent());
4201 bool ReturnedEarly = false;
4202 for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
4203 PHINode *PHI = PHIs[I];
4204 const ResultListTy &ResultList = ResultLists[PHI];
4206 // If using a bitmask, use any value to fill the lookup table holes.
4207 Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
4208 SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL);
4210 Value *Result = Table.BuildLookup(TableIndex, Builder);
4212 // If the result is used to return immediately from the function, we want to
4213 // do that right here.
4214 if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
4215 PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) {
4216 Builder.CreateRet(Result);
4217 ReturnedEarly = true;
4221 // Do a small peephole optimization: re-use the switch table compare if
4223 if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) {
4224 BasicBlock *PhiBlock = PHI->getParent();
4225 // Search for compare instructions which use the phi.
4226 for (auto *User : PHI->users()) {
4227 reuseTableCompare(User, PhiBlock, RangeCheckBranch, DV, ResultList);
4231 PHI->addIncoming(Result, LookupBB);
4235 Builder.CreateBr(CommonDest);
4237 // Remove the switch.
4238 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
4239 BasicBlock *Succ = SI->getSuccessor(i);
4241 if (Succ == SI->getDefaultDest())
4243 Succ->removePredecessor(SI->getParent());
4245 SI->eraseFromParent();
4249 ++NumLookupTablesHoles;
4253 bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
4254 BasicBlock *BB = SI->getParent();
4256 if (isValueEqualityComparison(SI)) {
4257 // If we only have one predecessor, and if it is a branch on this value,
4258 // see if that predecessor totally determines the outcome of this switch.
4259 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
4260 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
4261 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4263 Value *Cond = SI->getCondition();
4264 if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
4265 if (SimplifySwitchOnSelect(SI, Select))
4266 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4268 // If the block only contains the switch, see if we can fold the block
4269 // away into any preds.
4270 BasicBlock::iterator BBI = BB->begin();
4271 // Ignore dbg intrinsics.
4272 while (isa<DbgInfoIntrinsic>(BBI))
4275 if (FoldValueComparisonIntoPredecessors(SI, Builder))
4276 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4279 // Try to transform the switch into an icmp and a branch.
4280 if (TurnSwitchRangeIntoICmp(SI, Builder))
4281 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4283 // Remove unreachable cases.
4284 if (EliminateDeadSwitchCases(SI, DL, AT))
4285 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4287 if (SwitchToSelect(SI, Builder, DL, AT))
4288 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4290 if (ForwardSwitchConditionToPHI(SI))
4291 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4293 if (SwitchToLookupTable(SI, Builder, TTI, DL))
4294 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4299 bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
4300 BasicBlock *BB = IBI->getParent();
4301 bool Changed = false;
4303 // Eliminate redundant destinations.
4304 SmallPtrSet<Value *, 8> Succs;
4305 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
4306 BasicBlock *Dest = IBI->getDestination(i);
4307 if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) {
4308 Dest->removePredecessor(BB);
4309 IBI->removeDestination(i);
4315 if (IBI->getNumDestinations() == 0) {
4316 // If the indirectbr has no successors, change it to unreachable.
4317 new UnreachableInst(IBI->getContext(), IBI);
4318 EraseTerminatorInstAndDCECond(IBI);
4322 if (IBI->getNumDestinations() == 1) {
4323 // If the indirectbr has one successor, change it to a direct branch.
4324 BranchInst::Create(IBI->getDestination(0), IBI);
4325 EraseTerminatorInstAndDCECond(IBI);
4329 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
4330 if (SimplifyIndirectBrOnSelect(IBI, SI))
4331 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4336 bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder){
4337 BasicBlock *BB = BI->getParent();
4339 if (SinkCommon && SinkThenElseCodeToEnd(BI))
4342 // If the Terminator is the only non-phi instruction, simplify the block.
4343 BasicBlock::iterator I = BB->getFirstNonPHIOrDbg();
4344 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
4345 TryToSimplifyUncondBranchFromEmptyBlock(BB))
4348 // If the only instruction in the block is a seteq/setne comparison
4349 // against a constant, try to simplify the block.
4350 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
4351 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
4352 for (++I; isa<DbgInfoIntrinsic>(I); ++I)
4354 if (I->isTerminator() &&
4355 TryToSimplifyUncondBranchWithICmpInIt(ICI, Builder, TTI,
4356 BonusInstThreshold, DL, AT))
4360 // If this basic block is ONLY a compare and a branch, and if a predecessor
4361 // branches to us and our successor, fold the comparison into the
4362 // predecessor and use logical operations to update the incoming value
4363 // for PHI nodes in common successor.
4364 if (FoldBranchToCommonDest(BI, DL, BonusInstThreshold))
4365 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4370 bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
4371 BasicBlock *BB = BI->getParent();
4373 // Conditional branch
4374 if (isValueEqualityComparison(BI)) {
4375 // If we only have one predecessor, and if it is a branch on this value,
4376 // see if that predecessor totally determines the outcome of this
4378 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
4379 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
4380 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4382 // This block must be empty, except for the setcond inst, if it exists.
4383 // Ignore dbg intrinsics.
4384 BasicBlock::iterator I = BB->begin();
4385 // Ignore dbg intrinsics.
4386 while (isa<DbgInfoIntrinsic>(I))
4389 if (FoldValueComparisonIntoPredecessors(BI, Builder))
4390 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4391 } else if (&*I == cast<Instruction>(BI->getCondition())){
4393 // Ignore dbg intrinsics.
4394 while (isa<DbgInfoIntrinsic>(I))
4396 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
4397 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4401 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
4402 if (SimplifyBranchOnICmpChain(BI, DL, Builder))
4405 // If this basic block is ONLY a compare and a branch, and if a predecessor
4406 // branches to us and one of our successors, fold the comparison into the
4407 // predecessor and use logical operations to pick the right destination.
4408 if (FoldBranchToCommonDest(BI, DL, BonusInstThreshold))
4409 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4411 // We have a conditional branch to two blocks that are only reachable
4412 // from BI. We know that the condbr dominates the two blocks, so see if
4413 // there is any identical code in the "then" and "else" blocks. If so, we
4414 // can hoist it up to the branching block.
4415 if (BI->getSuccessor(0)->getSinglePredecessor()) {
4416 if (BI->getSuccessor(1)->getSinglePredecessor()) {
4417 if (HoistThenElseCodeToIf(BI, DL))
4418 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4420 // If Successor #1 has multiple preds, we may be able to conditionally
4421 // execute Successor #0 if it branches to Successor #1.
4422 TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
4423 if (Succ0TI->getNumSuccessors() == 1 &&
4424 Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
4425 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), DL))
4426 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4428 } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
4429 // If Successor #0 has multiple preds, we may be able to conditionally
4430 // execute Successor #1 if it branches to Successor #0.
4431 TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
4432 if (Succ1TI->getNumSuccessors() == 1 &&
4433 Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
4434 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), DL))
4435 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4438 // If this is a branch on a phi node in the current block, thread control
4439 // through this block if any PHI node entries are constants.
4440 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
4441 if (PN->getParent() == BI->getParent())
4442 if (FoldCondBranchOnPHI(BI, DL))
4443 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4445 // Scan predecessor blocks for conditional branches.
4446 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
4447 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
4448 if (PBI != BI && PBI->isConditional())
4449 if (SimplifyCondBranchToCondBranch(PBI, BI))
4450 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4455 /// Check if passing a value to an instruction will cause undefined behavior.
4456 static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
4457 Constant *C = dyn_cast<Constant>(V);
4464 if (C->isNullValue()) {
4465 // Only look at the first use, avoid hurting compile time with long uselists
4466 User *Use = *I->user_begin();
4468 // Now make sure that there are no instructions in between that can alter
4469 // control flow (eg. calls)
4470 for (BasicBlock::iterator i = ++BasicBlock::iterator(I); &*i != Use; ++i)
4471 if (i == I->getParent()->end() || i->mayHaveSideEffects())
4474 // Look through GEPs. A load from a GEP derived from NULL is still undefined
4475 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
4476 if (GEP->getPointerOperand() == I)
4477 return passingValueIsAlwaysUndefined(V, GEP);
4479 // Look through bitcasts.
4480 if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
4481 return passingValueIsAlwaysUndefined(V, BC);
4483 // Load from null is undefined.
4484 if (LoadInst *LI = dyn_cast<LoadInst>(Use))
4485 if (!LI->isVolatile())
4486 return LI->getPointerAddressSpace() == 0;
4488 // Store to null is undefined.
4489 if (StoreInst *SI = dyn_cast<StoreInst>(Use))
4490 if (!SI->isVolatile())
4491 return SI->getPointerAddressSpace() == 0 && SI->getPointerOperand() == I;
4496 /// If BB has an incoming value that will always trigger undefined behavior
4497 /// (eg. null pointer dereference), remove the branch leading here.
4498 static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
4499 for (BasicBlock::iterator i = BB->begin();
4500 PHINode *PHI = dyn_cast<PHINode>(i); ++i)
4501 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
4502 if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) {
4503 TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator();
4504 IRBuilder<> Builder(T);
4505 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
4506 BB->removePredecessor(PHI->getIncomingBlock(i));
4507 // Turn uncoditional branches into unreachables and remove the dead
4508 // destination from conditional branches.
4509 if (BI->isUnconditional())
4510 Builder.CreateUnreachable();
4512 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) :
4513 BI->getSuccessor(0));
4514 BI->eraseFromParent();
4517 // TODO: SwitchInst.
4523 bool SimplifyCFGOpt::run(BasicBlock *BB) {
4524 bool Changed = false;
4526 assert(BB && BB->getParent() && "Block not embedded in function!");
4527 assert(BB->getTerminator() && "Degenerate basic block encountered!");
4529 // Remove basic blocks that have no predecessors (except the entry block)...
4530 // or that just have themself as a predecessor. These are unreachable.
4531 if ((pred_begin(BB) == pred_end(BB) &&
4532 BB != &BB->getParent()->getEntryBlock()) ||
4533 BB->getSinglePredecessor() == BB) {
4534 DEBUG(dbgs() << "Removing BB: \n" << *BB);
4535 DeleteDeadBlock(BB);
4539 // Check to see if we can constant propagate this terminator instruction
4541 Changed |= ConstantFoldTerminator(BB, true);
4543 // Check for and eliminate duplicate PHI nodes in this block.
4544 Changed |= EliminateDuplicatePHINodes(BB);
4546 // Check for and remove branches that will always cause undefined behavior.
4547 Changed |= removeUndefIntroducingPredecessor(BB);
4549 // Merge basic blocks into their predecessor if there is only one distinct
4550 // pred, and if there is only one distinct successor of the predecessor, and
4551 // if there are no PHI nodes.
4553 if (MergeBlockIntoPredecessor(BB))
4556 IRBuilder<> Builder(BB);
4558 // If there is a trivial two-entry PHI node in this basic block, and we can
4559 // eliminate it, do so now.
4560 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
4561 if (PN->getNumIncomingValues() == 2)
4562 Changed |= FoldTwoEntryPHINode(PN, DL);
4564 Builder.SetInsertPoint(BB->getTerminator());
4565 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
4566 if (BI->isUnconditional()) {
4567 if (SimplifyUncondBranch(BI, Builder)) return true;
4569 if (SimplifyCondBranch(BI, Builder)) return true;
4571 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
4572 if (SimplifyReturn(RI, Builder)) return true;
4573 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
4574 if (SimplifyResume(RI, Builder)) return true;
4575 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
4576 if (SimplifySwitch(SI, Builder)) return true;
4577 } else if (UnreachableInst *UI =
4578 dyn_cast<UnreachableInst>(BB->getTerminator())) {
4579 if (SimplifyUnreachable(UI)) return true;
4580 } else if (IndirectBrInst *IBI =
4581 dyn_cast<IndirectBrInst>(BB->getTerminator())) {
4582 if (SimplifyIndirectBr(IBI)) return true;
4588 /// SimplifyCFG - This function is used to do simplification of a CFG. For
4589 /// example, it adjusts branches to branches to eliminate the extra hop, it
4590 /// eliminates unreachable basic blocks, and does other "peephole" optimization
4591 /// of the CFG. It returns true if a modification was made.
4593 bool llvm::SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
4594 unsigned BonusInstThreshold,
4595 const DataLayout *DL, AssumptionTracker *AT) {
4596 return SimplifyCFGOpt(TTI, BonusInstThreshold, DL, AT).run(BB);