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/SetOperations.h"
18 #include "llvm/ADT/SetVector.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/ConstantFolding.h"
23 #include "llvm/Analysis/EHPersonalities.h"
24 #include "llvm/Analysis/InstructionSimplify.h"
25 #include "llvm/Analysis/TargetTransformInfo.h"
26 #include "llvm/Analysis/ValueTracking.h"
27 #include "llvm/IR/CFG.h"
28 #include "llvm/IR/ConstantRange.h"
29 #include "llvm/IR/Constants.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/DerivedTypes.h"
32 #include "llvm/IR/GlobalVariable.h"
33 #include "llvm/IR/IRBuilder.h"
34 #include "llvm/IR/Instructions.h"
35 #include "llvm/IR/IntrinsicInst.h"
36 #include "llvm/IR/LLVMContext.h"
37 #include "llvm/IR/MDBuilder.h"
38 #include "llvm/IR/Metadata.h"
39 #include "llvm/IR/Module.h"
40 #include "llvm/IR/NoFolder.h"
41 #include "llvm/IR/Operator.h"
42 #include "llvm/IR/PatternMatch.h"
43 #include "llvm/IR/Type.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/Debug.h"
46 #include "llvm/Support/raw_ostream.h"
47 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
48 #include "llvm/Transforms/Utils/ValueMapper.h"
53 using namespace PatternMatch;
55 #define DEBUG_TYPE "simplifycfg"
57 // Chosen as 2 so as to be cheap, but still to have enough power to fold
58 // a select, so the "clamp" idiom (of a min followed by a max) will be caught.
59 // To catch this, we need to fold a compare and a select, hence '2' being the
60 // minimum reasonable default.
61 static cl::opt<unsigned>
62 PHINodeFoldingThreshold("phi-node-folding-threshold", cl::Hidden, cl::init(2),
63 cl::desc("Control the amount of phi node folding to perform (default = 2)"));
66 DupRet("simplifycfg-dup-ret", cl::Hidden, cl::init(false),
67 cl::desc("Duplicate return instructions into unconditional branches"));
70 SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
71 cl::desc("Sink common instructions down to the end block"));
73 static cl::opt<bool> HoistCondStores(
74 "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true),
75 cl::desc("Hoist conditional stores if an unconditional store precedes"));
77 static cl::opt<bool> MergeCondStores(
78 "simplifycfg-merge-cond-stores", cl::Hidden, cl::init(true),
79 cl::desc("Hoist conditional stores even if an unconditional store does not "
80 "precede - hoist multiple conditional stores into a single "
83 static cl::opt<bool> MergeCondStoresAggressively(
84 "simplifycfg-merge-cond-stores-aggressively", cl::Hidden, cl::init(false),
85 cl::desc("When merging conditional stores, do so even if the resultant "
86 "basic blocks are unlikely to be if-converted as a result"));
88 static cl::opt<bool> SpeculateOneExpensiveInst(
89 "speculate-one-expensive-inst", cl::Hidden, cl::init(true),
90 cl::desc("Allow exactly one expensive instruction to be speculatively "
93 STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
94 STATISTIC(NumLinearMaps, "Number of switch instructions turned into linear mapping");
95 STATISTIC(NumLookupTables, "Number of switch instructions turned into lookup tables");
96 STATISTIC(NumLookupTablesHoles, "Number of switch instructions turned into lookup tables (holes checked)");
97 STATISTIC(NumTableCmpReuses, "Number of reused switch table lookup compares");
98 STATISTIC(NumSinkCommons, "Number of common instructions sunk down to the end block");
99 STATISTIC(NumSpeculations, "Number of speculative executed instructions");
102 // The first field contains the value that the switch produces when a certain
103 // case group is selected, and the second field is a vector containing the
104 // cases composing the case group.
105 typedef SmallVector<std::pair<Constant *, SmallVector<ConstantInt *, 4>>, 2>
106 SwitchCaseResultVectorTy;
107 // The first field contains the phi node that generates a result of the switch
108 // and the second field contains the value generated for a certain case in the
109 // switch for that PHI.
110 typedef SmallVector<std::pair<PHINode *, Constant *>, 4> SwitchCaseResultsTy;
112 /// ValueEqualityComparisonCase - Represents a case of a switch.
113 struct ValueEqualityComparisonCase {
117 ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
118 : Value(Value), Dest(Dest) {}
120 bool operator<(ValueEqualityComparisonCase RHS) const {
121 // Comparing pointers is ok as we only rely on the order for uniquing.
122 return Value < RHS.Value;
125 bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
128 class SimplifyCFGOpt {
129 const TargetTransformInfo &TTI;
130 const DataLayout &DL;
131 unsigned BonusInstThreshold;
133 Value *isValueEqualityComparison(TerminatorInst *TI);
134 BasicBlock *GetValueEqualityComparisonCases(TerminatorInst *TI,
135 std::vector<ValueEqualityComparisonCase> &Cases);
136 bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
138 IRBuilder<> &Builder);
139 bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
140 IRBuilder<> &Builder);
142 bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder);
143 bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
144 bool SimplifySingleResume(ResumeInst *RI);
145 bool SimplifyCommonResume(ResumeInst *RI);
146 bool SimplifyCleanupReturn(CleanupReturnInst *RI);
147 bool SimplifyUnreachable(UnreachableInst *UI);
148 bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
149 bool SimplifyIndirectBr(IndirectBrInst *IBI);
150 bool SimplifyUncondBranch(BranchInst *BI, IRBuilder <> &Builder);
151 bool SimplifyCondBranch(BranchInst *BI, IRBuilder <>&Builder);
154 SimplifyCFGOpt(const TargetTransformInfo &TTI, const DataLayout &DL,
155 unsigned BonusInstThreshold, AssumptionCache *AC)
156 : TTI(TTI), DL(DL), BonusInstThreshold(BonusInstThreshold), AC(AC) {}
157 bool run(BasicBlock *BB);
161 /// Return true if it is safe to merge these two
162 /// terminator instructions together.
163 static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
164 if (SI1 == SI2) return false; // Can't merge with self!
166 // It is not safe to merge these two switch instructions if they have a common
167 // successor, and if that successor has a PHI node, and if *that* PHI node has
168 // conflicting incoming values from the two switch blocks.
169 BasicBlock *SI1BB = SI1->getParent();
170 BasicBlock *SI2BB = SI2->getParent();
171 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
173 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
174 if (SI1Succs.count(*I))
175 for (BasicBlock::iterator BBI = (*I)->begin();
176 isa<PHINode>(BBI); ++BBI) {
177 PHINode *PN = cast<PHINode>(BBI);
178 if (PN->getIncomingValueForBlock(SI1BB) !=
179 PN->getIncomingValueForBlock(SI2BB))
186 /// Return true if it is safe and profitable to merge these two terminator
187 /// instructions together, where SI1 is an unconditional branch. PhiNodes will
188 /// store all PHI nodes in common successors.
189 static bool isProfitableToFoldUnconditional(BranchInst *SI1,
192 SmallVectorImpl<PHINode*> &PhiNodes) {
193 if (SI1 == SI2) return false; // Can't merge with self!
194 assert(SI1->isUnconditional() && SI2->isConditional());
196 // We fold the unconditional branch if we can easily update all PHI nodes in
197 // common successors:
198 // 1> We have a constant incoming value for the conditional branch;
199 // 2> We have "Cond" as the incoming value for the unconditional branch;
200 // 3> SI2->getCondition() and Cond have same operands.
201 CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition());
202 if (!Ci2) return false;
203 if (!(Cond->getOperand(0) == Ci2->getOperand(0) &&
204 Cond->getOperand(1) == Ci2->getOperand(1)) &&
205 !(Cond->getOperand(0) == Ci2->getOperand(1) &&
206 Cond->getOperand(1) == Ci2->getOperand(0)))
209 BasicBlock *SI1BB = SI1->getParent();
210 BasicBlock *SI2BB = SI2->getParent();
211 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
212 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
213 if (SI1Succs.count(*I))
214 for (BasicBlock::iterator BBI = (*I)->begin();
215 isa<PHINode>(BBI); ++BBI) {
216 PHINode *PN = cast<PHINode>(BBI);
217 if (PN->getIncomingValueForBlock(SI1BB) != Cond ||
218 !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB)))
220 PhiNodes.push_back(PN);
225 /// Update PHI nodes in Succ to indicate that there will now be entries in it
226 /// from the 'NewPred' block. The values that will be flowing into the PHI nodes
227 /// will be the same as those coming in from ExistPred, an existing predecessor
229 static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
230 BasicBlock *ExistPred) {
231 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
234 for (BasicBlock::iterator I = Succ->begin();
235 (PN = dyn_cast<PHINode>(I)); ++I)
236 PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
239 /// Compute an abstract "cost" of speculating the given instruction,
240 /// which is assumed to be safe to speculate. TCC_Free means cheap,
241 /// TCC_Basic means less cheap, and TCC_Expensive means prohibitively
243 static unsigned ComputeSpeculationCost(const User *I,
244 const TargetTransformInfo &TTI) {
245 assert(isSafeToSpeculativelyExecute(I) &&
246 "Instruction is not safe to speculatively execute!");
247 return TTI.getUserCost(I);
250 /// If we have a merge point of an "if condition" as accepted above,
251 /// return true if the specified value dominates the block. We
252 /// don't handle the true generality of domination here, just a special case
253 /// which works well enough for us.
255 /// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
256 /// see if V (which must be an instruction) and its recursive operands
257 /// that do not dominate BB have a combined cost lower than CostRemaining and
258 /// are non-trapping. If both are true, the instruction is inserted into the
259 /// set and true is returned.
261 /// The cost for most non-trapping instructions is defined as 1 except for
262 /// Select whose cost is 2.
264 /// After this function returns, CostRemaining is decreased by the cost of
265 /// V plus its non-dominating operands. If that cost is greater than
266 /// CostRemaining, false is returned and CostRemaining is undefined.
267 static bool DominatesMergePoint(Value *V, BasicBlock *BB,
268 SmallPtrSetImpl<Instruction*> *AggressiveInsts,
269 unsigned &CostRemaining,
270 const TargetTransformInfo &TTI,
271 unsigned Depth = 0) {
272 Instruction *I = dyn_cast<Instruction>(V);
274 // Non-instructions all dominate instructions, but not all constantexprs
275 // can be executed unconditionally.
276 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
281 BasicBlock *PBB = I->getParent();
283 // We don't want to allow weird loops that might have the "if condition" in
284 // the bottom of this block.
285 if (PBB == BB) return false;
287 // If this instruction is defined in a block that contains an unconditional
288 // branch to BB, then it must be in the 'conditional' part of the "if
289 // statement". If not, it definitely dominates the region.
290 BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
291 if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB)
294 // If we aren't allowing aggressive promotion anymore, then don't consider
295 // instructions in the 'if region'.
296 if (!AggressiveInsts) return false;
298 // If we have seen this instruction before, don't count it again.
299 if (AggressiveInsts->count(I)) return true;
301 // Okay, it looks like the instruction IS in the "condition". Check to
302 // see if it's a cheap instruction to unconditionally compute, and if it
303 // only uses stuff defined outside of the condition. If so, hoist it out.
304 if (!isSafeToSpeculativelyExecute(I))
307 unsigned Cost = ComputeSpeculationCost(I, TTI);
309 // Allow exactly one instruction to be speculated regardless of its cost
310 // (as long as it is safe to do so).
311 // This is intended to flatten the CFG even if the instruction is a division
312 // or other expensive operation. The speculation of an expensive instruction
313 // is expected to be undone in CodeGenPrepare if the speculation has not
314 // enabled further IR optimizations.
315 if (Cost > CostRemaining &&
316 (!SpeculateOneExpensiveInst || !AggressiveInsts->empty() || Depth > 0))
319 // Avoid unsigned wrap.
320 CostRemaining = (Cost > CostRemaining) ? 0 : CostRemaining - Cost;
322 // Okay, we can only really hoist these out if their operands do
323 // not take us over the cost threshold.
324 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
325 if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining, TTI,
328 // Okay, it's safe to do this! Remember this instruction.
329 AggressiveInsts->insert(I);
333 /// Extract ConstantInt from value, looking through IntToPtr
334 /// and PointerNullValue. Return NULL if value is not a constant int.
335 static ConstantInt *GetConstantInt(Value *V, const DataLayout &DL) {
336 // Normal constant int.
337 ConstantInt *CI = dyn_cast<ConstantInt>(V);
338 if (CI || !isa<Constant>(V) || !V->getType()->isPointerTy())
341 // This is some kind of pointer constant. Turn it into a pointer-sized
342 // ConstantInt if possible.
343 IntegerType *PtrTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
345 // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
346 if (isa<ConstantPointerNull>(V))
347 return ConstantInt::get(PtrTy, 0);
349 // IntToPtr const int.
350 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
351 if (CE->getOpcode() == Instruction::IntToPtr)
352 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
353 // The constant is very likely to have the right type already.
354 if (CI->getType() == PtrTy)
357 return cast<ConstantInt>
358 (ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
365 /// Given a chain of or (||) or and (&&) comparison of a value against a
366 /// constant, this will try to recover the information required for a switch
368 /// It will depth-first traverse the chain of comparison, seeking for patterns
369 /// like %a == 12 or %a < 4 and combine them to produce a set of integer
370 /// representing the different cases for the switch.
371 /// Note that if the chain is composed of '||' it will build the set of elements
372 /// that matches the comparisons (i.e. any of this value validate the chain)
373 /// while for a chain of '&&' it will build the set elements that make the test
375 struct ConstantComparesGatherer {
376 const DataLayout &DL;
377 Value *CompValue; /// Value found for the switch comparison
378 Value *Extra; /// Extra clause to be checked before the switch
379 SmallVector<ConstantInt *, 8> Vals; /// Set of integers to match in switch
380 unsigned UsedICmps; /// Number of comparisons matched in the and/or chain
382 /// Construct and compute the result for the comparison instruction Cond
383 ConstantComparesGatherer(Instruction *Cond, const DataLayout &DL)
384 : DL(DL), CompValue(nullptr), Extra(nullptr), UsedICmps(0) {
389 ConstantComparesGatherer(const ConstantComparesGatherer &) = delete;
390 ConstantComparesGatherer &
391 operator=(const ConstantComparesGatherer &) = delete;
395 /// Try to set the current value used for the comparison, it succeeds only if
396 /// it wasn't set before or if the new value is the same as the old one
397 bool setValueOnce(Value *NewVal) {
398 if(CompValue && CompValue != NewVal) return false;
400 return (CompValue != nullptr);
403 /// Try to match Instruction "I" as a comparison against a constant and
404 /// populates the array Vals with the set of values that match (or do not
405 /// match depending on isEQ).
406 /// Return false on failure. On success, the Value the comparison matched
407 /// against is placed in CompValue.
408 /// If CompValue is already set, the function is expected to fail if a match
409 /// is found but the value compared to is different.
410 bool matchInstruction(Instruction *I, bool isEQ) {
411 // If this is an icmp against a constant, handle this as one of the cases.
414 if (!((ICI = dyn_cast<ICmpInst>(I)) &&
415 (C = GetConstantInt(I->getOperand(1), DL)))) {
422 // Pattern match a special case
423 // (x & ~2^x) == y --> x == y || x == y|2^x
424 // This undoes a transformation done by instcombine to fuse 2 compares.
425 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ:ICmpInst::ICMP_NE)) {
426 if (match(ICI->getOperand(0),
427 m_And(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
428 APInt Not = ~RHSC->getValue();
429 if (Not.isPowerOf2()) {
430 // If we already have a value for the switch, it has to match!
431 if(!setValueOnce(RHSVal))
435 Vals.push_back(ConstantInt::get(C->getContext(),
436 C->getValue() | Not));
442 // If we already have a value for the switch, it has to match!
443 if(!setValueOnce(ICI->getOperand(0)))
448 return ICI->getOperand(0);
451 // If we have "x ult 3", for example, then we can add 0,1,2 to the set.
452 ConstantRange Span = ConstantRange::makeAllowedICmpRegion(
453 ICI->getPredicate(), C->getValue());
455 // Shift the range if the compare is fed by an add. This is the range
456 // compare idiom as emitted by instcombine.
457 Value *CandidateVal = I->getOperand(0);
458 if(match(I->getOperand(0), m_Add(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
459 Span = Span.subtract(RHSC->getValue());
460 CandidateVal = RHSVal;
463 // If this is an and/!= check, then we are looking to build the set of
464 // value that *don't* pass the and chain. I.e. to turn "x ugt 2" into
467 Span = Span.inverse();
469 // If there are a ton of values, we don't want to make a ginormous switch.
470 if (Span.getSetSize().ugt(8) || Span.isEmptySet()) {
474 // If we already have a value for the switch, it has to match!
475 if(!setValueOnce(CandidateVal))
478 // Add all values from the range to the set
479 for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
480 Vals.push_back(ConstantInt::get(I->getContext(), Tmp));
487 /// Given a potentially 'or'd or 'and'd together collection of icmp
488 /// eq/ne/lt/gt instructions that compare a value against a constant, extract
489 /// the value being compared, and stick the list constants into the Vals
491 /// One "Extra" case is allowed to differ from the other.
492 void gather(Value *V) {
493 Instruction *I = dyn_cast<Instruction>(V);
494 bool isEQ = (I->getOpcode() == Instruction::Or);
496 // Keep a stack (SmallVector for efficiency) for depth-first traversal
497 SmallVector<Value *, 8> DFT;
502 while(!DFT.empty()) {
503 V = DFT.pop_back_val();
505 if (Instruction *I = dyn_cast<Instruction>(V)) {
506 // If it is a || (or && depending on isEQ), process the operands.
507 if (I->getOpcode() == (isEQ ? Instruction::Or : Instruction::And)) {
508 DFT.push_back(I->getOperand(1));
509 DFT.push_back(I->getOperand(0));
513 // Try to match the current instruction
514 if (matchInstruction(I, isEQ))
515 // Match succeed, continue the loop
519 // One element of the sequence of || (or &&) could not be match as a
520 // comparison against the same value as the others.
521 // We allow only one "Extra" case to be checked before the switch
526 // Failed to parse a proper sequence, abort now
535 static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
536 Instruction *Cond = nullptr;
537 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
538 Cond = dyn_cast<Instruction>(SI->getCondition());
539 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
540 if (BI->isConditional())
541 Cond = dyn_cast<Instruction>(BI->getCondition());
542 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
543 Cond = dyn_cast<Instruction>(IBI->getAddress());
546 TI->eraseFromParent();
547 if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond);
550 /// Return true if the specified terminator checks
551 /// to see if a value is equal to constant integer value.
552 Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) {
554 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
555 // Do not permit merging of large switch instructions into their
556 // predecessors unless there is only one predecessor.
557 if (SI->getNumSuccessors()*std::distance(pred_begin(SI->getParent()),
558 pred_end(SI->getParent())) <= 128)
559 CV = SI->getCondition();
560 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
561 if (BI->isConditional() && BI->getCondition()->hasOneUse())
562 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
563 if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL))
564 CV = ICI->getOperand(0);
567 // Unwrap any lossless ptrtoint cast.
569 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
570 Value *Ptr = PTII->getPointerOperand();
571 if (PTII->getType() == DL.getIntPtrType(Ptr->getType()))
578 /// Given a value comparison instruction,
579 /// decode all of the 'cases' that it represents and return the 'default' block.
580 BasicBlock *SimplifyCFGOpt::
581 GetValueEqualityComparisonCases(TerminatorInst *TI,
582 std::vector<ValueEqualityComparisonCase>
584 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
585 Cases.reserve(SI->getNumCases());
586 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i)
587 Cases.push_back(ValueEqualityComparisonCase(i.getCaseValue(),
588 i.getCaseSuccessor()));
589 return SI->getDefaultDest();
592 BranchInst *BI = cast<BranchInst>(TI);
593 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
594 BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE);
595 Cases.push_back(ValueEqualityComparisonCase(GetConstantInt(ICI->getOperand(1),
598 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
602 /// Given a vector of bb/value pairs, remove any entries
603 /// in the list that match the specified block.
604 static void EliminateBlockCases(BasicBlock *BB,
605 std::vector<ValueEqualityComparisonCase> &Cases) {
606 Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end());
609 /// Return true if there are any keys in C1 that exist in C2 as well.
611 ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
612 std::vector<ValueEqualityComparisonCase > &C2) {
613 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
615 // Make V1 be smaller than V2.
616 if (V1->size() > V2->size())
619 if (V1->size() == 0) return false;
620 if (V1->size() == 1) {
622 ConstantInt *TheVal = (*V1)[0].Value;
623 for (unsigned i = 0, e = V2->size(); i != e; ++i)
624 if (TheVal == (*V2)[i].Value)
628 // Otherwise, just sort both lists and compare element by element.
629 array_pod_sort(V1->begin(), V1->end());
630 array_pod_sort(V2->begin(), V2->end());
631 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
632 while (i1 != e1 && i2 != e2) {
633 if ((*V1)[i1].Value == (*V2)[i2].Value)
635 if ((*V1)[i1].Value < (*V2)[i2].Value)
643 /// If TI is known to be a terminator instruction and its block is known to
644 /// only have a single predecessor block, check to see if that predecessor is
645 /// also a value comparison with the same value, and if that comparison
646 /// determines the outcome of this comparison. If so, simplify TI. This does a
647 /// very limited 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 = mdconst::extract<ConstantInt>(MD->getOperand(MD_i));
717 Weights.push_back(CI->getValue().getZExtValue());
719 for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
721 if (DeadCases.count(i.getCaseValue())) {
723 std::swap(Weights[i.getCaseIndex()+1], Weights.back());
726 i.getCaseSuccessor()->removePredecessor(TI->getParent());
730 if (HasWeight && Weights.size() >= 2)
731 SI->setMetadata(LLVMContext::MD_prof,
732 MDBuilder(SI->getParent()->getContext()).
733 createBranchWeights(Weights));
735 DEBUG(dbgs() << "Leaving: " << *TI << "\n");
739 // Otherwise, TI's block must correspond to some matched value. Find out
740 // which value (or set of values) this is.
741 ConstantInt *TIV = nullptr;
742 BasicBlock *TIBB = TI->getParent();
743 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
744 if (PredCases[i].Dest == TIBB) {
746 return false; // Cannot handle multiple values coming to this block.
747 TIV = PredCases[i].Value;
749 assert(TIV && "No edge from pred to succ?");
751 // Okay, we found the one constant that our value can be if we get into TI's
752 // BB. Find out which successor will unconditionally be branched to.
753 BasicBlock *TheRealDest = nullptr;
754 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
755 if (ThisCases[i].Value == TIV) {
756 TheRealDest = ThisCases[i].Dest;
760 // If not handled by any explicit cases, it is handled by the default case.
761 if (!TheRealDest) TheRealDest = ThisDef;
763 // Remove PHI node entries for dead edges.
764 BasicBlock *CheckEdge = TheRealDest;
765 for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
766 if (*SI != CheckEdge)
767 (*SI)->removePredecessor(TIBB);
771 // Insert the new branch.
772 Instruction *NI = Builder.CreateBr(TheRealDest);
775 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
776 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
778 EraseTerminatorInstAndDCECond(TI);
783 /// This class implements a stable ordering of constant
784 /// integers that does not depend on their address. This is important for
785 /// applications that sort ConstantInt's to ensure uniqueness.
786 struct ConstantIntOrdering {
787 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
788 return LHS->getValue().ult(RHS->getValue());
793 static int ConstantIntSortPredicate(ConstantInt *const *P1,
794 ConstantInt *const *P2) {
795 const ConstantInt *LHS = *P1;
796 const ConstantInt *RHS = *P2;
797 if (LHS->getValue().ult(RHS->getValue()))
799 if (LHS->getValue() == RHS->getValue())
804 static inline bool HasBranchWeights(const Instruction* I) {
805 MDNode *ProfMD = I->getMetadata(LLVMContext::MD_prof);
806 if (ProfMD && ProfMD->getOperand(0))
807 if (MDString* MDS = dyn_cast<MDString>(ProfMD->getOperand(0)))
808 return MDS->getString().equals("branch_weights");
813 /// Get Weights of a given TerminatorInst, the default weight is at the front
814 /// of the vector. If TI is a conditional eq, we need to swap the branch-weight
816 static void GetBranchWeights(TerminatorInst *TI,
817 SmallVectorImpl<uint64_t> &Weights) {
818 MDNode *MD = TI->getMetadata(LLVMContext::MD_prof);
820 for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) {
821 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(i));
822 Weights.push_back(CI->getValue().getZExtValue());
825 // If TI is a conditional eq, the default case is the false case,
826 // and the corresponding branch-weight data is at index 2. We swap the
827 // default weight to be the first entry.
828 if (BranchInst* BI = dyn_cast<BranchInst>(TI)) {
829 assert(Weights.size() == 2);
830 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
831 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
832 std::swap(Weights.front(), Weights.back());
836 /// Keep halving the weights until all can fit in uint32_t.
837 static void FitWeights(MutableArrayRef<uint64_t> Weights) {
838 uint64_t Max = *std::max_element(Weights.begin(), Weights.end());
839 if (Max > UINT_MAX) {
840 unsigned Offset = 32 - countLeadingZeros(Max);
841 for (uint64_t &I : Weights)
846 /// The specified terminator is a value equality comparison instruction
847 /// (either a switch or a branch on "X == c").
848 /// See if any of the predecessors of the terminator block are value comparisons
849 /// on the same value. If so, and if safe to do so, fold them together.
850 bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
851 IRBuilder<> &Builder) {
852 BasicBlock *BB = TI->getParent();
853 Value *CV = isValueEqualityComparison(TI); // CondVal
854 assert(CV && "Not a comparison?");
855 bool Changed = false;
857 SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
858 while (!Preds.empty()) {
859 BasicBlock *Pred = Preds.pop_back_val();
861 // See if the predecessor is a comparison with the same value.
862 TerminatorInst *PTI = Pred->getTerminator();
863 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
865 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
866 // Figure out which 'cases' to copy from SI to PSI.
867 std::vector<ValueEqualityComparisonCase> BBCases;
868 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
870 std::vector<ValueEqualityComparisonCase> PredCases;
871 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
873 // Based on whether the default edge from PTI goes to BB or not, fill in
874 // PredCases and PredDefault with the new switch cases we would like to
876 SmallVector<BasicBlock*, 8> NewSuccessors;
878 // Update the branch weight metadata along the way
879 SmallVector<uint64_t, 8> Weights;
880 bool PredHasWeights = HasBranchWeights(PTI);
881 bool SuccHasWeights = HasBranchWeights(TI);
883 if (PredHasWeights) {
884 GetBranchWeights(PTI, Weights);
885 // branch-weight metadata is inconsistent here.
886 if (Weights.size() != 1 + PredCases.size())
887 PredHasWeights = SuccHasWeights = false;
888 } else if (SuccHasWeights)
889 // If there are no predecessor weights but there are successor weights,
890 // populate Weights with 1, which will later be scaled to the sum of
891 // successor's weights
892 Weights.assign(1 + PredCases.size(), 1);
894 SmallVector<uint64_t, 8> SuccWeights;
895 if (SuccHasWeights) {
896 GetBranchWeights(TI, SuccWeights);
897 // branch-weight metadata is inconsistent here.
898 if (SuccWeights.size() != 1 + BBCases.size())
899 PredHasWeights = SuccHasWeights = false;
900 } else if (PredHasWeights)
901 SuccWeights.assign(1 + BBCases.size(), 1);
903 if (PredDefault == BB) {
904 // If this is the default destination from PTI, only the edges in TI
905 // that don't occur in PTI, or that branch to BB will be activated.
906 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
907 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
908 if (PredCases[i].Dest != BB)
909 PTIHandled.insert(PredCases[i].Value);
911 // The default destination is BB, we don't need explicit targets.
912 std::swap(PredCases[i], PredCases.back());
914 if (PredHasWeights || SuccHasWeights) {
915 // Increase weight for the default case.
916 Weights[0] += Weights[i+1];
917 std::swap(Weights[i+1], Weights.back());
921 PredCases.pop_back();
925 // Reconstruct the new switch statement we will be building.
926 if (PredDefault != BBDefault) {
927 PredDefault->removePredecessor(Pred);
928 PredDefault = BBDefault;
929 NewSuccessors.push_back(BBDefault);
932 unsigned CasesFromPred = Weights.size();
933 uint64_t ValidTotalSuccWeight = 0;
934 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
935 if (!PTIHandled.count(BBCases[i].Value) &&
936 BBCases[i].Dest != BBDefault) {
937 PredCases.push_back(BBCases[i]);
938 NewSuccessors.push_back(BBCases[i].Dest);
939 if (SuccHasWeights || PredHasWeights) {
940 // The default weight is at index 0, so weight for the ith case
941 // should be at index i+1. Scale the cases from successor by
942 // PredDefaultWeight (Weights[0]).
943 Weights.push_back(Weights[0] * SuccWeights[i+1]);
944 ValidTotalSuccWeight += SuccWeights[i+1];
948 if (SuccHasWeights || PredHasWeights) {
949 ValidTotalSuccWeight += SuccWeights[0];
950 // Scale the cases from predecessor by ValidTotalSuccWeight.
951 for (unsigned i = 1; i < CasesFromPred; ++i)
952 Weights[i] *= ValidTotalSuccWeight;
953 // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
954 Weights[0] *= SuccWeights[0];
957 // If this is not the default destination from PSI, only the edges
958 // in SI that occur in PSI with a destination of BB will be
960 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
961 std::map<ConstantInt*, uint64_t> WeightsForHandled;
962 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
963 if (PredCases[i].Dest == BB) {
964 PTIHandled.insert(PredCases[i].Value);
966 if (PredHasWeights || SuccHasWeights) {
967 WeightsForHandled[PredCases[i].Value] = Weights[i+1];
968 std::swap(Weights[i+1], Weights.back());
972 std::swap(PredCases[i], PredCases.back());
973 PredCases.pop_back();
977 // Okay, now we know which constants were sent to BB from the
978 // predecessor. Figure out where they will all go now.
979 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
980 if (PTIHandled.count(BBCases[i].Value)) {
981 // If this is one we are capable of getting...
982 if (PredHasWeights || SuccHasWeights)
983 Weights.push_back(WeightsForHandled[BBCases[i].Value]);
984 PredCases.push_back(BBCases[i]);
985 NewSuccessors.push_back(BBCases[i].Dest);
986 PTIHandled.erase(BBCases[i].Value);// This constant is taken care of
989 // If there are any constants vectored to BB that TI doesn't handle,
990 // they must go to the default destination of TI.
991 for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I =
993 E = PTIHandled.end(); I != E; ++I) {
994 if (PredHasWeights || SuccHasWeights)
995 Weights.push_back(WeightsForHandled[*I]);
996 PredCases.push_back(ValueEqualityComparisonCase(*I, BBDefault));
997 NewSuccessors.push_back(BBDefault);
1001 // Okay, at this point, we know which new successor Pred will get. Make
1002 // sure we update the number of entries in the PHI nodes for these
1004 for (BasicBlock *NewSuccessor : NewSuccessors)
1005 AddPredecessorToBlock(NewSuccessor, Pred, BB);
1007 Builder.SetInsertPoint(PTI);
1008 // Convert pointer to int before we switch.
1009 if (CV->getType()->isPointerTy()) {
1010 CV = Builder.CreatePtrToInt(CV, DL.getIntPtrType(CV->getType()),
1014 // Now that the successors are updated, create the new Switch instruction.
1015 SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault,
1017 NewSI->setDebugLoc(PTI->getDebugLoc());
1018 for (ValueEqualityComparisonCase &V : PredCases)
1019 NewSI->addCase(V.Value, V.Dest);
1021 if (PredHasWeights || SuccHasWeights) {
1022 // Halve the weights if any of them cannot fit in an uint32_t
1023 FitWeights(Weights);
1025 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
1027 NewSI->setMetadata(LLVMContext::MD_prof,
1028 MDBuilder(BB->getContext()).
1029 createBranchWeights(MDWeights));
1032 EraseTerminatorInstAndDCECond(PTI);
1034 // Okay, last check. If BB is still a successor of PSI, then we must
1035 // have an infinite loop case. If so, add an infinitely looping block
1036 // to handle the case to preserve the behavior of the code.
1037 BasicBlock *InfLoopBlock = nullptr;
1038 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
1039 if (NewSI->getSuccessor(i) == BB) {
1040 if (!InfLoopBlock) {
1041 // Insert it at the end of the function, because it's either code,
1042 // or it won't matter if it's hot. :)
1043 InfLoopBlock = BasicBlock::Create(BB->getContext(),
1044 "infloop", BB->getParent());
1045 BranchInst::Create(InfLoopBlock, InfLoopBlock);
1047 NewSI->setSuccessor(i, InfLoopBlock);
1056 // If we would need to insert a select that uses the value of this invoke
1057 // (comments in HoistThenElseCodeToIf explain why we would need to do this), we
1058 // can't hoist the invoke, as there is nowhere to put the select in this case.
1059 static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
1060 Instruction *I1, Instruction *I2) {
1061 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
1063 for (BasicBlock::iterator BBI = SI->begin();
1064 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1065 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1066 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1067 if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) {
1075 static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I);
1077 /// Given a conditional branch that goes to BB1 and BB2, hoist any common code
1078 /// in the two blocks up into the branch block. The caller of this function
1079 /// guarantees that BI's block dominates BB1 and BB2.
1080 static bool HoistThenElseCodeToIf(BranchInst *BI,
1081 const TargetTransformInfo &TTI) {
1082 // This does very trivial matching, with limited scanning, to find identical
1083 // instructions in the two blocks. In particular, we don't want to get into
1084 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
1085 // such, we currently just scan for obviously identical instructions in an
1087 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
1088 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
1090 BasicBlock::iterator BB1_Itr = BB1->begin();
1091 BasicBlock::iterator BB2_Itr = BB2->begin();
1093 Instruction *I1 = &*BB1_Itr++, *I2 = &*BB2_Itr++;
1094 // Skip debug info if it is not identical.
1095 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1096 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1097 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1098 while (isa<DbgInfoIntrinsic>(I1))
1100 while (isa<DbgInfoIntrinsic>(I2))
1103 if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
1104 (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
1107 BasicBlock *BIParent = BI->getParent();
1109 bool Changed = false;
1111 // If we are hoisting the terminator instruction, don't move one (making a
1112 // broken BB), instead clone it, and remove BI.
1113 if (isa<TerminatorInst>(I1))
1114 goto HoistTerminator;
1116 if (!TTI.isProfitableToHoist(I1) || !TTI.isProfitableToHoist(I2))
1119 // For a normal instruction, we just move one to right before the branch,
1120 // then replace all uses of the other with the first. Finally, we remove
1121 // the now redundant second instruction.
1122 BIParent->getInstList().splice(BI->getIterator(), BB1->getInstList(), I1);
1123 if (!I2->use_empty())
1124 I2->replaceAllUsesWith(I1);
1125 I1->intersectOptionalDataWith(I2);
1126 unsigned KnownIDs[] = {
1127 LLVMContext::MD_tbaa, LLVMContext::MD_range,
1128 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
1129 LLVMContext::MD_nonnull, LLVMContext::MD_invariant_group,
1130 LLVMContext::MD_align, LLVMContext::MD_dereferenceable,
1131 LLVMContext::MD_dereferenceable_or_null};
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))
1173 if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V))
1178 // Okay, it is safe to hoist the terminator.
1179 Instruction *NT = I1->clone();
1180 BIParent->getInstList().insert(BI->getIterator(), 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 /// 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 SmallDenseMap<std::pair<Value *, Value *>, PHINode *> JointValueMap;
1249 Instruction *FirstNonPhiInBBEnd = nullptr;
1250 for (BasicBlock::iterator I = BBEnd->begin(), E = BBEnd->end(); I != E; ++I) {
1251 if (PHINode *PN = dyn_cast<PHINode>(I)) {
1252 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1253 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1254 JointValueMap[std::make_pair(BB1V, BB2V)] = PN;
1256 FirstNonPhiInBBEnd = &*I;
1260 if (!FirstNonPhiInBBEnd)
1263 // This does very trivial matching, with limited scanning, to find identical
1264 // instructions in the two blocks. We scan backward for obviously identical
1265 // instructions in an identical order.
1266 BasicBlock::InstListType::reverse_iterator RI1 = BB1->getInstList().rbegin(),
1267 RE1 = BB1->getInstList().rend(),
1268 RI2 = BB2->getInstList().rbegin(),
1269 RE2 = BB2->getInstList().rend();
1271 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1274 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1277 // Skip the unconditional branches.
1281 bool Changed = false;
1282 while (RI1 != RE1 && RI2 != RE2) {
1284 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1287 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1291 Instruction *I1 = &*RI1, *I2 = &*RI2;
1292 auto InstPair = std::make_pair(I1, I2);
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 I1->isEHPad() || I2->isEHPad() ||
1299 isa<AllocaInst>(I1) || isa<AllocaInst>(I2) ||
1300 I1->mayHaveSideEffects() || I2->mayHaveSideEffects() ||
1301 I1->mayReadOrWriteMemory() || I2->mayReadOrWriteMemory() ||
1302 !I1->hasOneUse() || !I2->hasOneUse() ||
1303 !JointValueMap.count(InstPair))
1306 // Check whether we should swap the operands of ICmpInst.
1307 // TODO: Add support of communativity.
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 = ~0U;
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 if
1333 // we need a PHI node to replace a constant.
1334 if (Op1Idx != ~0U ||
1335 isa<Constant>(I1->getOperand(I)) ||
1336 isa<Constant>(I2->getOperand(I))) {
1337 // If we can't sink the instructions, undo the swapping.
1339 ICmp2->swapOperands();
1342 DifferentOp1 = I1->getOperand(I);
1344 DifferentOp2 = I2->getOperand(I);
1347 DEBUG(dbgs() << "SINK common instructions " << *I1 << "\n");
1348 DEBUG(dbgs() << " " << *I2 << "\n");
1350 // We insert the pair of different operands to JointValueMap and
1351 // remove (I1, I2) from JointValueMap.
1352 if (Op1Idx != ~0U) {
1353 auto &NewPN = JointValueMap[std::make_pair(DifferentOp1, DifferentOp2)];
1356 PHINode::Create(DifferentOp1->getType(), 2,
1357 DifferentOp1->getName() + ".sink", &BBEnd->front());
1358 NewPN->addIncoming(DifferentOp1, BB1);
1359 NewPN->addIncoming(DifferentOp2, BB2);
1360 DEBUG(dbgs() << "Create PHI node " << *NewPN << "\n";);
1362 // I1 should use NewPN instead of DifferentOp1.
1363 I1->setOperand(Op1Idx, NewPN);
1365 PHINode *OldPN = JointValueMap[InstPair];
1366 JointValueMap.erase(InstPair);
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->getIterator(),
1373 BB1->getInstList(), I1);
1374 if (!OldPN->use_empty())
1375 OldPN->replaceAllUsesWith(I1);
1376 OldPN->eraseFromParent();
1378 if (!I2->use_empty())
1379 I2->replaceAllUsesWith(I1);
1380 I1->intersectOptionalDataWith(I2);
1381 // TODO: Use combineMetadata here to preserve what metadata we can
1382 // (analogous to the hoisting case above).
1383 I2->eraseFromParent();
1386 RE1 = BB1->getInstList().rend();
1388 RE2 = BB2->getInstList().rend();
1389 FirstNonPhiInBBEnd = &*I1;
1396 /// \brief Determine if we can hoist sink a sole store instruction out of a
1397 /// conditional block.
1399 /// We are looking for code like the following:
1401 /// store i32 %add, i32* %arrayidx2
1402 /// ... // No other stores or function calls (we could be calling a memory
1403 /// ... // function).
1404 /// %cmp = icmp ult %x, %y
1405 /// br i1 %cmp, label %EndBB, label %ThenBB
1407 /// store i32 %add5, i32* %arrayidx2
1411 /// We are going to transform this into:
1413 /// store i32 %add, i32* %arrayidx2
1415 /// %cmp = icmp ult %x, %y
1416 /// %add.add5 = select i1 %cmp, i32 %add, %add5
1417 /// store i32 %add.add5, i32* %arrayidx2
1420 /// \return The pointer to the value of the previous store if the store can be
1421 /// hoisted into the predecessor block. 0 otherwise.
1422 static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB,
1423 BasicBlock *StoreBB, BasicBlock *EndBB) {
1424 StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
1428 // Volatile or atomic.
1429 if (!StoreToHoist->isSimple())
1432 Value *StorePtr = StoreToHoist->getPointerOperand();
1434 // Look for a store to the same pointer in BrBB.
1435 unsigned MaxNumInstToLookAt = 10;
1436 for (BasicBlock::reverse_iterator RI = BrBB->rbegin(),
1437 RE = BrBB->rend(); RI != RE && (--MaxNumInstToLookAt); ++RI) {
1438 Instruction *CurI = &*RI;
1440 // Could be calling an instruction that effects memory like free().
1441 if (CurI->mayHaveSideEffects() && !isa<StoreInst>(CurI))
1444 StoreInst *SI = dyn_cast<StoreInst>(CurI);
1445 // Found the previous store make sure it stores to the same location.
1446 if (SI && SI->getPointerOperand() == StorePtr)
1447 // Found the previous store, return its value operand.
1448 return SI->getValueOperand();
1450 return nullptr; // Unknown store.
1456 /// \brief Speculate a conditional basic block flattening the CFG.
1458 /// Note that this is a very risky transform currently. Speculating
1459 /// instructions like this is most often not desirable. Instead, there is an MI
1460 /// pass which can do it with full awareness of the resource constraints.
1461 /// However, some cases are "obvious" and we should do directly. An example of
1462 /// this is speculating a single, reasonably cheap instruction.
1464 /// There is only one distinct advantage to flattening the CFG at the IR level:
1465 /// it makes very common but simplistic optimizations such as are common in
1466 /// instcombine and the DAG combiner more powerful by removing CFG edges and
1467 /// modeling their effects with easier to reason about SSA value graphs.
1470 /// An illustration of this transform is turning this IR:
1473 /// %cmp = icmp ult %x, %y
1474 /// br i1 %cmp, label %EndBB, label %ThenBB
1476 /// %sub = sub %x, %y
1479 /// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ]
1486 /// %cmp = icmp ult %x, %y
1487 /// %sub = sub %x, %y
1488 /// %cond = select i1 %cmp, 0, %sub
1492 /// \returns true if the conditional block is removed.
1493 static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB,
1494 const TargetTransformInfo &TTI) {
1495 // Be conservative for now. FP select instruction can often be expensive.
1496 Value *BrCond = BI->getCondition();
1497 if (isa<FCmpInst>(BrCond))
1500 BasicBlock *BB = BI->getParent();
1501 BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
1503 // If ThenBB is actually on the false edge of the conditional branch, remember
1504 // to swap the select operands later.
1505 bool Invert = false;
1506 if (ThenBB != BI->getSuccessor(0)) {
1507 assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
1510 assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
1512 // Keep a count of how many times instructions are used within CondBB when
1513 // they are candidates for sinking into CondBB. Specifically:
1514 // - They are defined in BB, and
1515 // - They have no side effects, and
1516 // - All of their uses are in CondBB.
1517 SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
1519 unsigned SpeculationCost = 0;
1520 Value *SpeculatedStoreValue = nullptr;
1521 StoreInst *SpeculatedStore = nullptr;
1522 for (BasicBlock::iterator BBI = ThenBB->begin(),
1523 BBE = std::prev(ThenBB->end());
1524 BBI != BBE; ++BBI) {
1525 Instruction *I = &*BBI;
1527 if (isa<DbgInfoIntrinsic>(I))
1530 // Only speculatively execute a single instruction (not counting the
1531 // terminator) for now.
1533 if (SpeculationCost > 1)
1536 // Don't hoist the instruction if it's unsafe or expensive.
1537 if (!isSafeToSpeculativelyExecute(I) &&
1538 !(HoistCondStores && (SpeculatedStoreValue = isSafeToSpeculateStore(
1539 I, BB, ThenBB, EndBB))))
1541 if (!SpeculatedStoreValue &&
1542 ComputeSpeculationCost(I, TTI) >
1543 PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic)
1546 // Store the store speculation candidate.
1547 if (SpeculatedStoreValue)
1548 SpeculatedStore = cast<StoreInst>(I);
1550 // Do not hoist the instruction if any of its operands are defined but not
1551 // used in BB. The transformation will prevent the operand from
1552 // being sunk into the use block.
1553 for (User::op_iterator i = I->op_begin(), e = I->op_end();
1555 Instruction *OpI = dyn_cast<Instruction>(*i);
1556 if (!OpI || OpI->getParent() != BB ||
1557 OpI->mayHaveSideEffects())
1558 continue; // Not a candidate for sinking.
1560 ++SinkCandidateUseCounts[OpI];
1564 // Consider any sink candidates which are only used in CondBB as costs for
1565 // speculation. Note, while we iterate over a DenseMap here, we are summing
1566 // and so iteration order isn't significant.
1567 for (SmallDenseMap<Instruction *, unsigned, 4>::iterator I =
1568 SinkCandidateUseCounts.begin(), E = SinkCandidateUseCounts.end();
1570 if (I->first->getNumUses() == I->second) {
1572 if (SpeculationCost > 1)
1576 // Check that the PHI nodes can be converted to selects.
1577 bool HaveRewritablePHIs = false;
1578 for (BasicBlock::iterator I = EndBB->begin();
1579 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1580 Value *OrigV = PN->getIncomingValueForBlock(BB);
1581 Value *ThenV = PN->getIncomingValueForBlock(ThenBB);
1583 // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf.
1584 // Skip PHIs which are trivial.
1588 // Don't convert to selects if we could remove undefined behavior instead.
1589 if (passingValueIsAlwaysUndefined(OrigV, PN) ||
1590 passingValueIsAlwaysUndefined(ThenV, PN))
1593 HaveRewritablePHIs = true;
1594 ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
1595 ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
1596 if (!OrigCE && !ThenCE)
1597 continue; // Known safe and cheap.
1599 if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE)) ||
1600 (OrigCE && !isSafeToSpeculativelyExecute(OrigCE)))
1602 unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE, TTI) : 0;
1603 unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE, TTI) : 0;
1604 unsigned MaxCost = 2 * PHINodeFoldingThreshold *
1605 TargetTransformInfo::TCC_Basic;
1606 if (OrigCost + ThenCost > MaxCost)
1609 // Account for the cost of an unfolded ConstantExpr which could end up
1610 // getting expanded into Instructions.
1611 // FIXME: This doesn't account for how many operations are combined in the
1612 // constant expression.
1614 if (SpeculationCost > 1)
1618 // If there are no PHIs to process, bail early. This helps ensure idempotence
1620 if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue))
1623 // If we get here, we can hoist the instruction and if-convert.
1624 DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
1626 // Insert a select of the value of the speculated store.
1627 if (SpeculatedStoreValue) {
1628 IRBuilder<true, NoFolder> Builder(BI);
1629 Value *TrueV = SpeculatedStore->getValueOperand();
1630 Value *FalseV = SpeculatedStoreValue;
1632 std::swap(TrueV, FalseV);
1633 Value *S = Builder.CreateSelect(BrCond, TrueV, FalseV, TrueV->getName() +
1634 "." + FalseV->getName());
1635 SpeculatedStore->setOperand(0, S);
1638 // Metadata can be dependent on the condition we are hoisting above.
1639 // Conservatively strip all metadata on the instruction.
1640 for (auto &I: *ThenBB)
1641 I.dropUnknownNonDebugMetadata();
1643 // Hoist the instructions.
1644 BB->getInstList().splice(BI->getIterator(), ThenBB->getInstList(),
1645 ThenBB->begin(), std::prev(ThenBB->end()));
1647 // Insert selects and rewrite the PHI operands.
1648 IRBuilder<true, NoFolder> Builder(BI);
1649 for (BasicBlock::iterator I = EndBB->begin();
1650 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1651 unsigned OrigI = PN->getBasicBlockIndex(BB);
1652 unsigned ThenI = PN->getBasicBlockIndex(ThenBB);
1653 Value *OrigV = PN->getIncomingValue(OrigI);
1654 Value *ThenV = PN->getIncomingValue(ThenI);
1656 // Skip PHIs which are trivial.
1660 // Create a select whose true value is the speculatively executed value and
1661 // false value is the preexisting value. Swap them if the branch
1662 // destinations were inverted.
1663 Value *TrueV = ThenV, *FalseV = OrigV;
1665 std::swap(TrueV, FalseV);
1666 Value *V = Builder.CreateSelect(BrCond, TrueV, FalseV,
1667 TrueV->getName() + "." + FalseV->getName());
1668 PN->setIncomingValue(OrigI, V);
1669 PN->setIncomingValue(ThenI, V);
1676 /// \returns True if this block contains a CallInst with the NoDuplicate
1678 static bool HasNoDuplicateCall(const BasicBlock *BB) {
1679 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1680 const CallInst *CI = dyn_cast<CallInst>(I);
1683 if (CI->cannotDuplicate())
1689 /// Return true if we can thread a branch across this block.
1690 static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
1691 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
1694 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1695 if (isa<DbgInfoIntrinsic>(BBI))
1697 if (Size > 10) return false; // Don't clone large BB's.
1700 // We can only support instructions that do not define values that are
1701 // live outside of the current basic block.
1702 for (User *U : BBI->users()) {
1703 Instruction *UI = cast<Instruction>(U);
1704 if (UI->getParent() != BB || isa<PHINode>(UI)) return false;
1707 // Looks ok, continue checking.
1713 /// If we have a conditional branch on a PHI node value that is defined in the
1714 /// same block as the branch and if any PHI entries are constants, thread edges
1715 /// corresponding to that entry to be branches to their ultimate destination.
1716 static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout &DL) {
1717 BasicBlock *BB = BI->getParent();
1718 PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
1719 // NOTE: we currently cannot transform this case if the PHI node is used
1720 // outside of the block.
1721 if (!PN || PN->getParent() != BB || !PN->hasOneUse())
1724 // Degenerate case of a single entry PHI.
1725 if (PN->getNumIncomingValues() == 1) {
1726 FoldSingleEntryPHINodes(PN->getParent());
1730 // Now we know that this block has multiple preds and two succs.
1731 if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
1733 if (HasNoDuplicateCall(BB)) return false;
1735 // Okay, this is a simple enough basic block. See if any phi values are
1737 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1738 ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
1739 if (!CB || !CB->getType()->isIntegerTy(1)) continue;
1741 // Okay, we now know that all edges from PredBB should be revectored to
1742 // branch to RealDest.
1743 BasicBlock *PredBB = PN->getIncomingBlock(i);
1744 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
1746 if (RealDest == BB) continue; // Skip self loops.
1747 // Skip if the predecessor's terminator is an indirect branch.
1748 if (isa<IndirectBrInst>(PredBB->getTerminator())) continue;
1750 // The dest block might have PHI nodes, other predecessors and other
1751 // difficult cases. Instead of being smart about this, just insert a new
1752 // block that jumps to the destination block, effectively splitting
1753 // the edge we are about to create.
1754 BasicBlock *EdgeBB = BasicBlock::Create(BB->getContext(),
1755 RealDest->getName()+".critedge",
1756 RealDest->getParent(), RealDest);
1757 BranchInst::Create(RealDest, EdgeBB);
1759 // Update PHI nodes.
1760 AddPredecessorToBlock(RealDest, EdgeBB, BB);
1762 // BB may have instructions that are being threaded over. Clone these
1763 // instructions into EdgeBB. We know that there will be no uses of the
1764 // cloned instructions outside of EdgeBB.
1765 BasicBlock::iterator InsertPt = EdgeBB->begin();
1766 DenseMap<Value*, Value*> TranslateMap; // Track translated values.
1767 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1768 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
1769 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
1772 // Clone the instruction.
1773 Instruction *N = BBI->clone();
1774 if (BBI->hasName()) N->setName(BBI->getName()+".c");
1776 // Update operands due to translation.
1777 for (User::op_iterator i = N->op_begin(), e = N->op_end();
1779 DenseMap<Value*, Value*>::iterator PI = TranslateMap.find(*i);
1780 if (PI != TranslateMap.end())
1784 // Check for trivial simplification.
1785 if (Value *V = SimplifyInstruction(N, DL)) {
1786 TranslateMap[&*BBI] = V;
1787 delete N; // Instruction folded away, don't need actual inst
1789 // Insert the new instruction into its new home.
1790 EdgeBB->getInstList().insert(InsertPt, N);
1791 if (!BBI->use_empty())
1792 TranslateMap[&*BBI] = N;
1796 // Loop over all of the edges from PredBB to BB, changing them to branch
1797 // to EdgeBB instead.
1798 TerminatorInst *PredBBTI = PredBB->getTerminator();
1799 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
1800 if (PredBBTI->getSuccessor(i) == BB) {
1801 BB->removePredecessor(PredBB);
1802 PredBBTI->setSuccessor(i, EdgeBB);
1805 // Recurse, simplifying any other constants.
1806 return FoldCondBranchOnPHI(BI, DL) | true;
1812 /// Given a BB that starts with the specified two-entry PHI node,
1813 /// see if we can eliminate it.
1814 static bool FoldTwoEntryPHINode(PHINode *PN, const TargetTransformInfo &TTI,
1815 const DataLayout &DL) {
1816 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
1817 // statement", which has a very simple dominance structure. Basically, we
1818 // are trying to find the condition that is being branched on, which
1819 // subsequently causes this merge to happen. We really want control
1820 // dependence information for this check, but simplifycfg can't keep it up
1821 // to date, and this catches most of the cases we care about anyway.
1822 BasicBlock *BB = PN->getParent();
1823 BasicBlock *IfTrue, *IfFalse;
1824 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
1826 // Don't bother if the branch will be constant folded trivially.
1827 isa<ConstantInt>(IfCond))
1830 // Okay, we found that we can merge this two-entry phi node into a select.
1831 // Doing so would require us to fold *all* two entry phi nodes in this block.
1832 // At some point this becomes non-profitable (particularly if the target
1833 // doesn't support cmov's). Only do this transformation if there are two or
1834 // fewer PHI nodes in this block.
1835 unsigned NumPhis = 0;
1836 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
1840 // Loop over the PHI's seeing if we can promote them all to select
1841 // instructions. While we are at it, keep track of the instructions
1842 // that need to be moved to the dominating block.
1843 SmallPtrSet<Instruction*, 4> AggressiveInsts;
1844 unsigned MaxCostVal0 = PHINodeFoldingThreshold,
1845 MaxCostVal1 = PHINodeFoldingThreshold;
1846 MaxCostVal0 *= TargetTransformInfo::TCC_Basic;
1847 MaxCostVal1 *= TargetTransformInfo::TCC_Basic;
1849 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
1850 PHINode *PN = cast<PHINode>(II++);
1851 if (Value *V = SimplifyInstruction(PN, DL)) {
1852 PN->replaceAllUsesWith(V);
1853 PN->eraseFromParent();
1857 if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts,
1858 MaxCostVal0, TTI) ||
1859 !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts,
1864 // If we folded the first phi, PN dangles at this point. Refresh it. If
1865 // we ran out of PHIs then we simplified them all.
1866 PN = dyn_cast<PHINode>(BB->begin());
1867 if (!PN) return true;
1869 // Don't fold i1 branches on PHIs which contain binary operators. These can
1870 // often be turned into switches and other things.
1871 if (PN->getType()->isIntegerTy(1) &&
1872 (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
1873 isa<BinaryOperator>(PN->getIncomingValue(1)) ||
1874 isa<BinaryOperator>(IfCond)))
1877 // If we all PHI nodes are promotable, check to make sure that all
1878 // instructions in the predecessor blocks can be promoted as well. If
1879 // not, we won't be able to get rid of the control flow, so it's not
1880 // worth promoting to select instructions.
1881 BasicBlock *DomBlock = nullptr;
1882 BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
1883 BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
1884 if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
1887 DomBlock = *pred_begin(IfBlock1);
1888 for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I)
1889 if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) {
1890 // This is not an aggressive instruction that we can promote.
1891 // Because of this, we won't be able to get rid of the control
1892 // flow, so the xform is not worth it.
1897 if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
1900 DomBlock = *pred_begin(IfBlock2);
1901 for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I)
1902 if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) {
1903 // This is not an aggressive instruction that we can promote.
1904 // Because of this, we won't be able to get rid of the control
1905 // flow, so the xform is not worth it.
1910 DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: "
1911 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
1913 // If we can still promote the PHI nodes after this gauntlet of tests,
1914 // do all of the PHI's now.
1915 Instruction *InsertPt = DomBlock->getTerminator();
1916 IRBuilder<true, NoFolder> Builder(InsertPt);
1918 // Move all 'aggressive' instructions, which are defined in the
1919 // conditional parts of the if's up to the dominating block.
1921 DomBlock->getInstList().splice(InsertPt->getIterator(),
1922 IfBlock1->getInstList(), IfBlock1->begin(),
1923 IfBlock1->getTerminator()->getIterator());
1925 DomBlock->getInstList().splice(InsertPt->getIterator(),
1926 IfBlock2->getInstList(), IfBlock2->begin(),
1927 IfBlock2->getTerminator()->getIterator());
1929 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1930 // Change the PHI node into a select instruction.
1931 Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1932 Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
1935 cast<SelectInst>(Builder.CreateSelect(IfCond, TrueVal, FalseVal, ""));
1936 PN->replaceAllUsesWith(NV);
1938 PN->eraseFromParent();
1941 // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
1942 // has been flattened. Change DomBlock to jump directly to our new block to
1943 // avoid other simplifycfg's kicking in on the diamond.
1944 TerminatorInst *OldTI = DomBlock->getTerminator();
1945 Builder.SetInsertPoint(OldTI);
1946 Builder.CreateBr(BB);
1947 OldTI->eraseFromParent();
1951 /// If we found a conditional branch that goes to two returning blocks,
1952 /// try to merge them together into one return,
1953 /// introducing a select if the return values disagree.
1954 static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
1955 IRBuilder<> &Builder) {
1956 assert(BI->isConditional() && "Must be a conditional branch");
1957 BasicBlock *TrueSucc = BI->getSuccessor(0);
1958 BasicBlock *FalseSucc = BI->getSuccessor(1);
1959 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
1960 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
1962 // Check to ensure both blocks are empty (just a return) or optionally empty
1963 // with PHI nodes. If there are other instructions, merging would cause extra
1964 // computation on one path or the other.
1965 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
1967 if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
1970 Builder.SetInsertPoint(BI);
1971 // Okay, we found a branch that is going to two return nodes. If
1972 // there is no return value for this function, just change the
1973 // branch into a return.
1974 if (FalseRet->getNumOperands() == 0) {
1975 TrueSucc->removePredecessor(BI->getParent());
1976 FalseSucc->removePredecessor(BI->getParent());
1977 Builder.CreateRetVoid();
1978 EraseTerminatorInstAndDCECond(BI);
1982 // Otherwise, figure out what the true and false return values are
1983 // so we can insert a new select instruction.
1984 Value *TrueValue = TrueRet->getReturnValue();
1985 Value *FalseValue = FalseRet->getReturnValue();
1987 // Unwrap any PHI nodes in the return blocks.
1988 if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
1989 if (TVPN->getParent() == TrueSucc)
1990 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
1991 if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
1992 if (FVPN->getParent() == FalseSucc)
1993 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
1995 // In order for this transformation to be safe, we must be able to
1996 // unconditionally execute both operands to the return. This is
1997 // normally the case, but we could have a potentially-trapping
1998 // constant expression that prevents this transformation from being
2000 if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
2003 if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
2007 // Okay, we collected all the mapped values and checked them for sanity, and
2008 // defined to really do this transformation. First, update the CFG.
2009 TrueSucc->removePredecessor(BI->getParent());
2010 FalseSucc->removePredecessor(BI->getParent());
2012 // Insert select instructions where needed.
2013 Value *BrCond = BI->getCondition();
2015 // Insert a select if the results differ.
2016 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
2017 } else if (isa<UndefValue>(TrueValue)) {
2018 TrueValue = FalseValue;
2020 TrueValue = Builder.CreateSelect(BrCond, TrueValue,
2021 FalseValue, "retval");
2025 Value *RI = !TrueValue ?
2026 Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
2030 DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
2031 << "\n " << *BI << "NewRet = " << *RI
2032 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc);
2034 EraseTerminatorInstAndDCECond(BI);
2039 /// Given a conditional BranchInstruction, retrieve the probabilities of the
2040 /// branch taking each edge. Fills in the two APInt parameters and returns true,
2041 /// or returns false if no or invalid metadata was found.
2042 static bool ExtractBranchMetadata(BranchInst *BI,
2043 uint64_t &ProbTrue, uint64_t &ProbFalse) {
2044 assert(BI->isConditional() &&
2045 "Looking for probabilities on unconditional branch?");
2046 MDNode *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
2047 if (!ProfileData || ProfileData->getNumOperands() != 3) return false;
2048 ConstantInt *CITrue =
2049 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
2050 ConstantInt *CIFalse =
2051 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
2052 if (!CITrue || !CIFalse) return false;
2053 ProbTrue = CITrue->getValue().getZExtValue();
2054 ProbFalse = CIFalse->getValue().getZExtValue();
2058 /// Return true if the given instruction is available
2059 /// in its predecessor block. If yes, the instruction will be removed.
2060 static bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB) {
2061 if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
2063 for (BasicBlock::iterator I = PB->begin(), E = PB->end(); I != E; I++) {
2064 Instruction *PBI = &*I;
2065 // Check whether Inst and PBI generate the same value.
2066 if (Inst->isIdenticalTo(PBI)) {
2067 Inst->replaceAllUsesWith(PBI);
2068 Inst->eraseFromParent();
2075 /// If this basic block is simple enough, and if a predecessor branches to us
2076 /// and one of our successors, fold the block into the predecessor and use
2077 /// logical operations to pick the right destination.
2078 bool llvm::FoldBranchToCommonDest(BranchInst *BI, unsigned BonusInstThreshold) {
2079 BasicBlock *BB = BI->getParent();
2081 Instruction *Cond = nullptr;
2082 if (BI->isConditional())
2083 Cond = dyn_cast<Instruction>(BI->getCondition());
2085 // For unconditional branch, check for a simple CFG pattern, where
2086 // BB has a single predecessor and BB's successor is also its predecessor's
2087 // successor. If such pattern exisits, check for CSE between BB and its
2089 if (BasicBlock *PB = BB->getSinglePredecessor())
2090 if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
2091 if (PBI->isConditional() &&
2092 (BI->getSuccessor(0) == PBI->getSuccessor(0) ||
2093 BI->getSuccessor(0) == PBI->getSuccessor(1))) {
2094 for (BasicBlock::iterator I = BB->begin(), E = BB->end();
2096 Instruction *Curr = &*I++;
2097 if (isa<CmpInst>(Curr)) {
2101 // Quit if we can't remove this instruction.
2102 if (!checkCSEInPredecessor(Curr, PB))
2111 if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
2112 Cond->getParent() != BB || !Cond->hasOneUse())
2115 // Make sure the instruction after the condition is the cond branch.
2116 BasicBlock::iterator CondIt = ++Cond->getIterator();
2118 // Ignore dbg intrinsics.
2119 while (isa<DbgInfoIntrinsic>(CondIt)) ++CondIt;
2124 // Only allow this transformation if computing the condition doesn't involve
2125 // too many instructions and these involved instructions can be executed
2126 // unconditionally. We denote all involved instructions except the condition
2127 // as "bonus instructions", and only allow this transformation when the
2128 // number of the bonus instructions does not exceed a certain threshold.
2129 unsigned NumBonusInsts = 0;
2130 for (auto I = BB->begin(); Cond != I; ++I) {
2131 // Ignore dbg intrinsics.
2132 if (isa<DbgInfoIntrinsic>(I))
2134 if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(&*I))
2136 // I has only one use and can be executed unconditionally.
2137 Instruction *User = dyn_cast<Instruction>(I->user_back());
2138 if (User == nullptr || User->getParent() != BB)
2140 // I is used in the same BB. Since BI uses Cond and doesn't have more slots
2141 // to use any other instruction, User must be an instruction between next(I)
2144 // Early exits once we reach the limit.
2145 if (NumBonusInsts > BonusInstThreshold)
2149 // Cond is known to be a compare or binary operator. Check to make sure that
2150 // neither operand is a potentially-trapping constant expression.
2151 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
2154 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
2158 // Finally, don't infinitely unroll conditional loops.
2159 BasicBlock *TrueDest = BI->getSuccessor(0);
2160 BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr;
2161 if (TrueDest == BB || FalseDest == BB)
2164 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2165 BasicBlock *PredBlock = *PI;
2166 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
2168 // Check that we have two conditional branches. If there is a PHI node in
2169 // the common successor, verify that the same value flows in from both
2171 SmallVector<PHINode*, 4> PHIs;
2172 if (!PBI || PBI->isUnconditional() ||
2173 (BI->isConditional() &&
2174 !SafeToMergeTerminators(BI, PBI)) ||
2175 (!BI->isConditional() &&
2176 !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs)))
2179 // Determine if the two branches share a common destination.
2180 Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd;
2181 bool InvertPredCond = false;
2183 if (BI->isConditional()) {
2184 if (PBI->getSuccessor(0) == TrueDest)
2185 Opc = Instruction::Or;
2186 else if (PBI->getSuccessor(1) == FalseDest)
2187 Opc = Instruction::And;
2188 else if (PBI->getSuccessor(0) == FalseDest)
2189 Opc = Instruction::And, InvertPredCond = true;
2190 else if (PBI->getSuccessor(1) == TrueDest)
2191 Opc = Instruction::Or, InvertPredCond = true;
2195 if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest)
2199 DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
2200 IRBuilder<> Builder(PBI);
2202 // If we need to invert the condition in the pred block to match, do so now.
2203 if (InvertPredCond) {
2204 Value *NewCond = PBI->getCondition();
2206 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
2207 CmpInst *CI = cast<CmpInst>(NewCond);
2208 CI->setPredicate(CI->getInversePredicate());
2210 NewCond = Builder.CreateNot(NewCond,
2211 PBI->getCondition()->getName()+".not");
2214 PBI->setCondition(NewCond);
2215 PBI->swapSuccessors();
2218 // If we have bonus instructions, clone them into the predecessor block.
2219 // Note that there may be multiple predecessor blocks, so we cannot move
2220 // bonus instructions to a predecessor block.
2221 ValueToValueMapTy VMap; // maps original values to cloned values
2222 // We already make sure Cond is the last instruction before BI. Therefore,
2223 // all instructions before Cond other than DbgInfoIntrinsic are bonus
2225 for (auto BonusInst = BB->begin(); Cond != BonusInst; ++BonusInst) {
2226 if (isa<DbgInfoIntrinsic>(BonusInst))
2228 Instruction *NewBonusInst = BonusInst->clone();
2229 RemapInstruction(NewBonusInst, VMap,
2230 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
2231 VMap[&*BonusInst] = NewBonusInst;
2233 // If we moved a load, we cannot any longer claim any knowledge about
2234 // its potential value. The previous information might have been valid
2235 // only given the branch precondition.
2236 // For an analogous reason, we must also drop all the metadata whose
2237 // semantics we don't understand.
2238 NewBonusInst->dropUnknownNonDebugMetadata();
2240 PredBlock->getInstList().insert(PBI->getIterator(), NewBonusInst);
2241 NewBonusInst->takeName(&*BonusInst);
2242 BonusInst->setName(BonusInst->getName() + ".old");
2245 // Clone Cond into the predecessor basic block, and or/and the
2246 // two conditions together.
2247 Instruction *New = Cond->clone();
2248 RemapInstruction(New, VMap,
2249 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
2250 PredBlock->getInstList().insert(PBI->getIterator(), New);
2251 New->takeName(Cond);
2252 Cond->setName(New->getName() + ".old");
2254 if (BI->isConditional()) {
2255 Instruction *NewCond =
2256 cast<Instruction>(Builder.CreateBinOp(Opc, PBI->getCondition(),
2258 PBI->setCondition(NewCond);
2260 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2261 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2263 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2265 SmallVector<uint64_t, 8> NewWeights;
2267 if (PBI->getSuccessor(0) == BB) {
2268 if (PredHasWeights && SuccHasWeights) {
2269 // PBI: br i1 %x, BB, FalseDest
2270 // BI: br i1 %y, TrueDest, FalseDest
2271 //TrueWeight is TrueWeight for PBI * TrueWeight for BI.
2272 NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
2273 //FalseWeight is FalseWeight for PBI * TotalWeight for BI +
2274 // TrueWeight for PBI * FalseWeight for BI.
2275 // We assume that total weights of a BranchInst can fit into 32 bits.
2276 // Therefore, we will not have overflow using 64-bit arithmetic.
2277 NewWeights.push_back(PredFalseWeight * (SuccFalseWeight +
2278 SuccTrueWeight) + PredTrueWeight * SuccFalseWeight);
2280 AddPredecessorToBlock(TrueDest, PredBlock, BB);
2281 PBI->setSuccessor(0, TrueDest);
2283 if (PBI->getSuccessor(1) == BB) {
2284 if (PredHasWeights && SuccHasWeights) {
2285 // PBI: br i1 %x, TrueDest, BB
2286 // BI: br i1 %y, TrueDest, FalseDest
2287 //TrueWeight is TrueWeight for PBI * TotalWeight for BI +
2288 // FalseWeight for PBI * TrueWeight for BI.
2289 NewWeights.push_back(PredTrueWeight * (SuccFalseWeight +
2290 SuccTrueWeight) + PredFalseWeight * SuccTrueWeight);
2291 //FalseWeight is FalseWeight for PBI * FalseWeight for BI.
2292 NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
2294 AddPredecessorToBlock(FalseDest, PredBlock, BB);
2295 PBI->setSuccessor(1, FalseDest);
2297 if (NewWeights.size() == 2) {
2298 // Halve the weights if any of them cannot fit in an uint32_t
2299 FitWeights(NewWeights);
2301 SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),NewWeights.end());
2302 PBI->setMetadata(LLVMContext::MD_prof,
2303 MDBuilder(BI->getContext()).
2304 createBranchWeights(MDWeights));
2306 PBI->setMetadata(LLVMContext::MD_prof, nullptr);
2308 // Update PHI nodes in the common successors.
2309 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
2310 ConstantInt *PBI_C = cast<ConstantInt>(
2311 PHIs[i]->getIncomingValueForBlock(PBI->getParent()));
2312 assert(PBI_C->getType()->isIntegerTy(1));
2313 Instruction *MergedCond = nullptr;
2314 if (PBI->getSuccessor(0) == TrueDest) {
2315 // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value)
2316 // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value)
2317 // is false: !PBI_Cond and BI_Value
2318 Instruction *NotCond =
2319 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2322 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2327 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2328 PBI->getCondition(), MergedCond,
2331 // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C)
2332 // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond)
2333 // is false: PBI_Cond and BI_Value
2335 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2336 PBI->getCondition(), New,
2338 if (PBI_C->isOne()) {
2339 Instruction *NotCond =
2340 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2343 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2344 NotCond, MergedCond,
2349 PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()),
2352 // Change PBI from Conditional to Unconditional.
2353 BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI);
2354 EraseTerminatorInstAndDCECond(PBI);
2358 // TODO: If BB is reachable from all paths through PredBlock, then we
2359 // could replace PBI's branch probabilities with BI's.
2361 // Copy any debug value intrinsics into the end of PredBlock.
2362 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
2363 if (isa<DbgInfoIntrinsic>(*I))
2364 I->clone()->insertBefore(PBI);
2371 // If there is only one store in BB1 and BB2, return it, otherwise return
2373 static StoreInst *findUniqueStoreInBlocks(BasicBlock *BB1, BasicBlock *BB2) {
2374 StoreInst *S = nullptr;
2375 for (auto *BB : {BB1, BB2}) {
2379 if (auto *SI = dyn_cast<StoreInst>(&I)) {
2381 // Multiple stores seen.
2390 static Value *ensureValueAvailableInSuccessor(Value *V, BasicBlock *BB,
2391 Value *AlternativeV = nullptr) {
2392 // PHI is going to be a PHI node that allows the value V that is defined in
2393 // BB to be referenced in BB's only successor.
2395 // If AlternativeV is nullptr, the only value we care about in PHI is V. It
2396 // doesn't matter to us what the other operand is (it'll never get used). We
2397 // could just create a new PHI with an undef incoming value, but that could
2398 // increase register pressure if EarlyCSE/InstCombine can't fold it with some
2399 // other PHI. So here we directly look for some PHI in BB's successor with V
2400 // as an incoming operand. If we find one, we use it, else we create a new
2403 // If AlternativeV is not nullptr, we care about both incoming values in PHI.
2404 // PHI must be exactly: phi <ty> [ %BB, %V ], [ %OtherBB, %AlternativeV]
2405 // where OtherBB is the single other predecessor of BB's only successor.
2406 PHINode *PHI = nullptr;
2407 BasicBlock *Succ = BB->getSingleSuccessor();
2409 for (auto I = Succ->begin(); isa<PHINode>(I); ++I)
2410 if (cast<PHINode>(I)->getIncomingValueForBlock(BB) == V) {
2411 PHI = cast<PHINode>(I);
2415 assert(std::distance(pred_begin(Succ), pred_end(Succ)) == 2);
2416 auto PredI = pred_begin(Succ);
2417 BasicBlock *OtherPredBB = *PredI == BB ? *++PredI : *PredI;
2418 if (PHI->getIncomingValueForBlock(OtherPredBB) == AlternativeV)
2425 // If V is not an instruction defined in BB, just return it.
2426 if (!AlternativeV &&
2427 (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB))
2430 PHI = PHINode::Create(V->getType(), 2, "simplifycfg.merge", &Succ->front());
2431 PHI->addIncoming(V, BB);
2432 for (BasicBlock *PredBB : predecessors(Succ))
2434 PHI->addIncoming(AlternativeV ? AlternativeV : UndefValue::get(V->getType()),
2439 static bool mergeConditionalStoreToAddress(BasicBlock *PTB, BasicBlock *PFB,
2440 BasicBlock *QTB, BasicBlock *QFB,
2441 BasicBlock *PostBB, Value *Address,
2442 bool InvertPCond, bool InvertQCond) {
2443 auto IsaBitcastOfPointerType = [](const Instruction &I) {
2444 return Operator::getOpcode(&I) == Instruction::BitCast &&
2445 I.getType()->isPointerTy();
2448 // If we're not in aggressive mode, we only optimize if we have some
2449 // confidence that by optimizing we'll allow P and/or Q to be if-converted.
2450 auto IsWorthwhile = [&](BasicBlock *BB) {
2453 // Heuristic: if the block can be if-converted/phi-folded and the
2454 // instructions inside are all cheap (arithmetic/GEPs), it's worthwhile to
2455 // thread this store.
2457 for (auto &I : *BB) {
2458 // Cheap instructions viable for folding.
2459 if (isa<BinaryOperator>(I) || isa<GetElementPtrInst>(I) ||
2462 // Free instructions.
2463 else if (isa<TerminatorInst>(I) || isa<DbgInfoIntrinsic>(I) ||
2464 IsaBitcastOfPointerType(I))
2469 return N <= PHINodeFoldingThreshold;
2472 if (!MergeCondStoresAggressively && (!IsWorthwhile(PTB) ||
2473 !IsWorthwhile(PFB) ||
2474 !IsWorthwhile(QTB) ||
2475 !IsWorthwhile(QFB)))
2478 // For every pointer, there must be exactly two stores, one coming from
2479 // PTB or PFB, and the other from QTB or QFB. We don't support more than one
2480 // store (to any address) in PTB,PFB or QTB,QFB.
2481 // FIXME: We could relax this restriction with a bit more work and performance
2483 StoreInst *PStore = findUniqueStoreInBlocks(PTB, PFB);
2484 StoreInst *QStore = findUniqueStoreInBlocks(QTB, QFB);
2485 if (!PStore || !QStore)
2488 // Now check the stores are compatible.
2489 if (!QStore->isUnordered() || !PStore->isUnordered())
2492 // Check that sinking the store won't cause program behavior changes. Sinking
2493 // the store out of the Q blocks won't change any behavior as we're sinking
2494 // from a block to its unconditional successor. But we're moving a store from
2495 // the P blocks down through the middle block (QBI) and past both QFB and QTB.
2496 // So we need to check that there are no aliasing loads or stores in
2497 // QBI, QTB and QFB. We also need to check there are no conflicting memory
2498 // operations between PStore and the end of its parent block.
2500 // The ideal way to do this is to query AliasAnalysis, but we don't
2501 // preserve AA currently so that is dangerous. Be super safe and just
2502 // check there are no other memory operations at all.
2503 for (auto &I : *QFB->getSinglePredecessor())
2504 if (I.mayReadOrWriteMemory())
2506 for (auto &I : *QFB)
2507 if (&I != QStore && I.mayReadOrWriteMemory())
2510 for (auto &I : *QTB)
2511 if (&I != QStore && I.mayReadOrWriteMemory())
2513 for (auto I = BasicBlock::iterator(PStore), E = PStore->getParent()->end();
2515 if (&*I != PStore && I->mayReadOrWriteMemory())
2518 // OK, we're going to sink the stores to PostBB. The store has to be
2519 // conditional though, so first create the predicate.
2520 Value *PCond = cast<BranchInst>(PFB->getSinglePredecessor()->getTerminator())
2522 Value *QCond = cast<BranchInst>(QFB->getSinglePredecessor()->getTerminator())
2525 Value *PPHI = ensureValueAvailableInSuccessor(PStore->getValueOperand(),
2526 PStore->getParent());
2527 Value *QPHI = ensureValueAvailableInSuccessor(QStore->getValueOperand(),
2528 QStore->getParent(), PPHI);
2530 IRBuilder<> QB(&*PostBB->getFirstInsertionPt());
2532 Value *PPred = PStore->getParent() == PTB ? PCond : QB.CreateNot(PCond);
2533 Value *QPred = QStore->getParent() == QTB ? QCond : QB.CreateNot(QCond);
2536 PPred = QB.CreateNot(PPred);
2538 QPred = QB.CreateNot(QPred);
2539 Value *CombinedPred = QB.CreateOr(PPred, QPred);
2542 SplitBlockAndInsertIfThen(CombinedPred, &*QB.GetInsertPoint(), false);
2543 QB.SetInsertPoint(T);
2544 StoreInst *SI = cast<StoreInst>(QB.CreateStore(QPHI, Address));
2546 PStore->getAAMetadata(AAMD, /*Merge=*/false);
2547 PStore->getAAMetadata(AAMD, /*Merge=*/true);
2548 SI->setAAMetadata(AAMD);
2550 QStore->eraseFromParent();
2551 PStore->eraseFromParent();
2556 static bool mergeConditionalStores(BranchInst *PBI, BranchInst *QBI) {
2557 // The intention here is to find diamonds or triangles (see below) where each
2558 // conditional block contains a store to the same address. Both of these
2559 // stores are conditional, so they can't be unconditionally sunk. But it may
2560 // be profitable to speculatively sink the stores into one merged store at the
2561 // end, and predicate the merged store on the union of the two conditions of
2564 // This can reduce the number of stores executed if both of the conditions are
2565 // true, and can allow the blocks to become small enough to be if-converted.
2566 // This optimization will also chain, so that ladders of test-and-set
2567 // sequences can be if-converted away.
2569 // We only deal with simple diamonds or triangles:
2571 // PBI or PBI or a combination of the two
2581 // We model triangles as a type of diamond with a nullptr "true" block.
2582 // Triangles are canonicalized so that the fallthrough edge is represented by
2583 // a true condition, as in the diagram above.
2585 BasicBlock *PTB = PBI->getSuccessor(0);
2586 BasicBlock *PFB = PBI->getSuccessor(1);
2587 BasicBlock *QTB = QBI->getSuccessor(0);
2588 BasicBlock *QFB = QBI->getSuccessor(1);
2589 BasicBlock *PostBB = QFB->getSingleSuccessor();
2591 bool InvertPCond = false, InvertQCond = false;
2592 // Canonicalize fallthroughs to the true branches.
2593 if (PFB == QBI->getParent()) {
2594 std::swap(PFB, PTB);
2597 if (QFB == PostBB) {
2598 std::swap(QFB, QTB);
2602 // From this point on we can assume PTB or QTB may be fallthroughs but PFB
2603 // and QFB may not. Model fallthroughs as a nullptr block.
2604 if (PTB == QBI->getParent())
2609 // Legality bailouts. We must have at least the non-fallthrough blocks and
2610 // the post-dominating block, and the non-fallthroughs must only have one
2612 auto HasOnePredAndOneSucc = [](BasicBlock *BB, BasicBlock *P, BasicBlock *S) {
2613 return BB->getSinglePredecessor() == P &&
2614 BB->getSingleSuccessor() == S;
2617 !HasOnePredAndOneSucc(PFB, PBI->getParent(), QBI->getParent()) ||
2618 !HasOnePredAndOneSucc(QFB, QBI->getParent(), PostBB))
2620 if ((PTB && !HasOnePredAndOneSucc(PTB, PBI->getParent(), QBI->getParent())) ||
2621 (QTB && !HasOnePredAndOneSucc(QTB, QBI->getParent(), PostBB)))
2623 if (PostBB->getNumUses() != 2 || QBI->getParent()->getNumUses() != 2)
2626 // OK, this is a sequence of two diamonds or triangles.
2627 // Check if there are stores in PTB or PFB that are repeated in QTB or QFB.
2628 SmallPtrSet<Value *,4> PStoreAddresses, QStoreAddresses;
2629 for (auto *BB : {PTB, PFB}) {
2633 if (StoreInst *SI = dyn_cast<StoreInst>(&I))
2634 PStoreAddresses.insert(SI->getPointerOperand());
2636 for (auto *BB : {QTB, QFB}) {
2640 if (StoreInst *SI = dyn_cast<StoreInst>(&I))
2641 QStoreAddresses.insert(SI->getPointerOperand());
2644 set_intersect(PStoreAddresses, QStoreAddresses);
2645 // set_intersect mutates PStoreAddresses in place. Rename it here to make it
2646 // clear what it contains.
2647 auto &CommonAddresses = PStoreAddresses;
2649 bool Changed = false;
2650 for (auto *Address : CommonAddresses)
2651 Changed |= mergeConditionalStoreToAddress(
2652 PTB, PFB, QTB, QFB, PostBB, Address, InvertPCond, InvertQCond);
2656 /// If we have a conditional branch as a predecessor of another block,
2657 /// this function tries to simplify it. We know
2658 /// that PBI and BI are both conditional branches, and BI is in one of the
2659 /// successor blocks of PBI - PBI branches to BI.
2660 static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI,
2661 const DataLayout &DL) {
2662 assert(PBI->isConditional() && BI->isConditional());
2663 BasicBlock *BB = BI->getParent();
2665 // If this block ends with a branch instruction, and if there is a
2666 // predecessor that ends on a branch of the same condition, make
2667 // this conditional branch redundant.
2668 if (PBI->getCondition() == BI->getCondition() &&
2669 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2670 // Okay, the outcome of this conditional branch is statically
2671 // knowable. If this block had a single pred, handle specially.
2672 if (BB->getSinglePredecessor()) {
2673 // Turn this into a branch on constant.
2674 bool CondIsTrue = PBI->getSuccessor(0) == BB;
2675 BI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
2677 return true; // Nuke the branch on constant.
2680 // Otherwise, if there are multiple predecessors, insert a PHI that merges
2681 // in the constant and simplify the block result. Subsequent passes of
2682 // simplifycfg will thread the block.
2683 if (BlockIsSimpleEnoughToThreadThrough(BB)) {
2684 pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
2685 PHINode *NewPN = PHINode::Create(
2686 Type::getInt1Ty(BB->getContext()), std::distance(PB, PE),
2687 BI->getCondition()->getName() + ".pr", &BB->front());
2688 // Okay, we're going to insert the PHI node. Since PBI is not the only
2689 // predecessor, compute the PHI'd conditional value for all of the preds.
2690 // Any predecessor where the condition is not computable we keep symbolic.
2691 for (pred_iterator PI = PB; PI != PE; ++PI) {
2692 BasicBlock *P = *PI;
2693 if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) &&
2694 PBI != BI && PBI->isConditional() &&
2695 PBI->getCondition() == BI->getCondition() &&
2696 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2697 bool CondIsTrue = PBI->getSuccessor(0) == BB;
2698 NewPN->addIncoming(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
2701 NewPN->addIncoming(BI->getCondition(), P);
2705 BI->setCondition(NewPN);
2710 if (auto *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
2714 // If BI is reached from the true path of PBI and PBI's condition implies
2715 // BI's condition, we know the direction of the BI branch.
2716 if (PBI->getSuccessor(0) == BI->getParent() &&
2717 isImpliedCondition(PBI->getCondition(), BI->getCondition(), DL) &&
2718 PBI->getSuccessor(0) != PBI->getSuccessor(1) &&
2719 BB->getSinglePredecessor()) {
2720 // Turn this into a branch on constant.
2721 auto *OldCond = BI->getCondition();
2722 BI->setCondition(ConstantInt::getTrue(BB->getContext()));
2723 RecursivelyDeleteTriviallyDeadInstructions(OldCond);
2724 return true; // Nuke the branch on constant.
2727 // If both branches are conditional and both contain stores to the same
2728 // address, remove the stores from the conditionals and create a conditional
2729 // merged store at the end.
2730 if (MergeCondStores && mergeConditionalStores(PBI, BI))
2733 // If this is a conditional branch in an empty block, and if any
2734 // predecessors are a conditional branch to one of our destinations,
2735 // fold the conditions into logical ops and one cond br.
2736 BasicBlock::iterator BBI = BB->begin();
2737 // Ignore dbg intrinsics.
2738 while (isa<DbgInfoIntrinsic>(BBI))
2744 if (PBI->getSuccessor(0) == BI->getSuccessor(0))
2746 else if (PBI->getSuccessor(0) == BI->getSuccessor(1))
2747 PBIOp = 0, BIOp = 1;
2748 else if (PBI->getSuccessor(1) == BI->getSuccessor(0))
2749 PBIOp = 1, BIOp = 0;
2750 else if (PBI->getSuccessor(1) == BI->getSuccessor(1))
2755 // Check to make sure that the other destination of this branch
2756 // isn't BB itself. If so, this is an infinite loop that will
2757 // keep getting unwound.
2758 if (PBI->getSuccessor(PBIOp) == BB)
2761 // Do not perform this transformation if it would require
2762 // insertion of a large number of select instructions. For targets
2763 // without predication/cmovs, this is a big pessimization.
2765 // Also do not perform this transformation if any phi node in the common
2766 // destination block can trap when reached by BB or PBB (PR17073). In that
2767 // case, it would be unsafe to hoist the operation into a select instruction.
2769 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
2770 unsigned NumPhis = 0;
2771 for (BasicBlock::iterator II = CommonDest->begin();
2772 isa<PHINode>(II); ++II, ++NumPhis) {
2773 if (NumPhis > 2) // Disable this xform.
2776 PHINode *PN = cast<PHINode>(II);
2777 Value *BIV = PN->getIncomingValueForBlock(BB);
2778 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV))
2782 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2783 Value *PBIV = PN->getIncomingValue(PBBIdx);
2784 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV))
2789 // Finally, if everything is ok, fold the branches to logical ops.
2790 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
2792 DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
2793 << "AND: " << *BI->getParent());
2796 // If OtherDest *is* BB, then BB is a basic block with a single conditional
2797 // branch in it, where one edge (OtherDest) goes back to itself but the other
2798 // exits. We don't *know* that the program avoids the infinite loop
2799 // (even though that seems likely). If we do this xform naively, we'll end up
2800 // recursively unpeeling the loop. Since we know that (after the xform is
2801 // done) that the block *is* infinite if reached, we just make it an obviously
2802 // infinite loop with no cond branch.
2803 if (OtherDest == BB) {
2804 // Insert it at the end of the function, because it's either code,
2805 // or it won't matter if it's hot. :)
2806 BasicBlock *InfLoopBlock = BasicBlock::Create(BB->getContext(),
2807 "infloop", BB->getParent());
2808 BranchInst::Create(InfLoopBlock, InfLoopBlock);
2809 OtherDest = InfLoopBlock;
2812 DEBUG(dbgs() << *PBI->getParent()->getParent());
2814 // BI may have other predecessors. Because of this, we leave
2815 // it alone, but modify PBI.
2817 // Make sure we get to CommonDest on True&True directions.
2818 Value *PBICond = PBI->getCondition();
2819 IRBuilder<true, NoFolder> Builder(PBI);
2821 PBICond = Builder.CreateNot(PBICond, PBICond->getName()+".not");
2823 Value *BICond = BI->getCondition();
2825 BICond = Builder.CreateNot(BICond, BICond->getName()+".not");
2827 // Merge the conditions.
2828 Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
2830 // Modify PBI to branch on the new condition to the new dests.
2831 PBI->setCondition(Cond);
2832 PBI->setSuccessor(0, CommonDest);
2833 PBI->setSuccessor(1, OtherDest);
2835 // Update branch weight for PBI.
2836 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2837 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2839 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2841 if (PredHasWeights && SuccHasWeights) {
2842 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
2843 uint64_t PredOther = PBIOp ?PredTrueWeight : PredFalseWeight;
2844 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
2845 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
2846 // The weight to CommonDest should be PredCommon * SuccTotal +
2847 // PredOther * SuccCommon.
2848 // The weight to OtherDest should be PredOther * SuccOther.
2849 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) +
2850 PredOther * SuccCommon,
2851 PredOther * SuccOther};
2852 // Halve the weights if any of them cannot fit in an uint32_t
2853 FitWeights(NewWeights);
2855 PBI->setMetadata(LLVMContext::MD_prof,
2856 MDBuilder(BI->getContext())
2857 .createBranchWeights(NewWeights[0], NewWeights[1]));
2860 // OtherDest may have phi nodes. If so, add an entry from PBI's
2861 // block that are identical to the entries for BI's block.
2862 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
2864 // We know that the CommonDest already had an edge from PBI to
2865 // it. If it has PHIs though, the PHIs may have different
2866 // entries for BB and PBI's BB. If so, insert a select to make
2869 for (BasicBlock::iterator II = CommonDest->begin();
2870 (PN = dyn_cast<PHINode>(II)); ++II) {
2871 Value *BIV = PN->getIncomingValueForBlock(BB);
2872 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2873 Value *PBIV = PN->getIncomingValue(PBBIdx);
2875 // Insert a select in PBI to pick the right value.
2876 Value *NV = cast<SelectInst>
2877 (Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName()+".mux"));
2878 PN->setIncomingValue(PBBIdx, NV);
2882 DEBUG(dbgs() << "INTO: " << *PBI->getParent());
2883 DEBUG(dbgs() << *PBI->getParent()->getParent());
2885 // This basic block is probably dead. We know it has at least
2886 // one fewer predecessor.
2890 // Simplifies a terminator by replacing it with a branch to TrueBB if Cond is
2891 // true or to FalseBB if Cond is false.
2892 // Takes care of updating the successors and removing the old terminator.
2893 // Also makes sure not to introduce new successors by assuming that edges to
2894 // non-successor TrueBBs and FalseBBs aren't reachable.
2895 static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond,
2896 BasicBlock *TrueBB, BasicBlock *FalseBB,
2897 uint32_t TrueWeight,
2898 uint32_t FalseWeight){
2899 // Remove any superfluous successor edges from the CFG.
2900 // First, figure out which successors to preserve.
2901 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
2903 BasicBlock *KeepEdge1 = TrueBB;
2904 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
2906 // Then remove the rest.
2907 for (BasicBlock *Succ : OldTerm->successors()) {
2908 // Make sure only to keep exactly one copy of each edge.
2909 if (Succ == KeepEdge1)
2910 KeepEdge1 = nullptr;
2911 else if (Succ == KeepEdge2)
2912 KeepEdge2 = nullptr;
2914 Succ->removePredecessor(OldTerm->getParent(),
2915 /*DontDeleteUselessPHIs=*/true);
2918 IRBuilder<> Builder(OldTerm);
2919 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
2921 // Insert an appropriate new terminator.
2922 if (!KeepEdge1 && !KeepEdge2) {
2923 if (TrueBB == FalseBB)
2924 // We were only looking for one successor, and it was present.
2925 // Create an unconditional branch to it.
2926 Builder.CreateBr(TrueBB);
2928 // We found both of the successors we were looking for.
2929 // Create a conditional branch sharing the condition of the select.
2930 BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
2931 if (TrueWeight != FalseWeight)
2932 NewBI->setMetadata(LLVMContext::MD_prof,
2933 MDBuilder(OldTerm->getContext()).
2934 createBranchWeights(TrueWeight, FalseWeight));
2936 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
2937 // Neither of the selected blocks were successors, so this
2938 // terminator must be unreachable.
2939 new UnreachableInst(OldTerm->getContext(), OldTerm);
2941 // One of the selected values was a successor, but the other wasn't.
2942 // Insert an unconditional branch to the one that was found;
2943 // the edge to the one that wasn't must be unreachable.
2945 // Only TrueBB was found.
2946 Builder.CreateBr(TrueBB);
2948 // Only FalseBB was found.
2949 Builder.CreateBr(FalseBB);
2952 EraseTerminatorInstAndDCECond(OldTerm);
2957 // (switch (select cond, X, Y)) on constant X, Y
2958 // with a branch - conditional if X and Y lead to distinct BBs,
2959 // unconditional otherwise.
2960 static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
2961 // Check for constant integer values in the select.
2962 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
2963 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
2964 if (!TrueVal || !FalseVal)
2967 // Find the relevant condition and destinations.
2968 Value *Condition = Select->getCondition();
2969 BasicBlock *TrueBB = SI->findCaseValue(TrueVal).getCaseSuccessor();
2970 BasicBlock *FalseBB = SI->findCaseValue(FalseVal).getCaseSuccessor();
2972 // Get weight for TrueBB and FalseBB.
2973 uint32_t TrueWeight = 0, FalseWeight = 0;
2974 SmallVector<uint64_t, 8> Weights;
2975 bool HasWeights = HasBranchWeights(SI);
2977 GetBranchWeights(SI, Weights);
2978 if (Weights.size() == 1 + SI->getNumCases()) {
2979 TrueWeight = (uint32_t)Weights[SI->findCaseValue(TrueVal).
2980 getSuccessorIndex()];
2981 FalseWeight = (uint32_t)Weights[SI->findCaseValue(FalseVal).
2982 getSuccessorIndex()];
2986 // Perform the actual simplification.
2987 return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB,
2988 TrueWeight, FalseWeight);
2992 // (indirectbr (select cond, blockaddress(@fn, BlockA),
2993 // blockaddress(@fn, BlockB)))
2995 // (br cond, BlockA, BlockB).
2996 static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
2997 // Check that both operands of the select are block addresses.
2998 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
2999 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
3003 // Extract the actual blocks.
3004 BasicBlock *TrueBB = TBA->getBasicBlock();
3005 BasicBlock *FalseBB = FBA->getBasicBlock();
3007 // Perform the actual simplification.
3008 return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB,
3012 /// This is called when we find an icmp instruction
3013 /// (a seteq/setne with a constant) as the only instruction in a
3014 /// block that ends with an uncond branch. We are looking for a very specific
3015 /// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
3016 /// this case, we merge the first two "or's of icmp" into a switch, but then the
3017 /// default value goes to an uncond block with a seteq in it, we get something
3020 /// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
3022 /// %tmp = icmp eq i8 %A, 92
3025 /// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
3027 /// We prefer to split the edge to 'end' so that there is a true/false entry to
3028 /// the PHI, merging the third icmp into the switch.
3029 static bool TryToSimplifyUncondBranchWithICmpInIt(
3030 ICmpInst *ICI, IRBuilder<> &Builder, const DataLayout &DL,
3031 const TargetTransformInfo &TTI, unsigned BonusInstThreshold,
3032 AssumptionCache *AC) {
3033 BasicBlock *BB = ICI->getParent();
3035 // If the block has any PHIs in it or the icmp has multiple uses, it is too
3037 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) return false;
3039 Value *V = ICI->getOperand(0);
3040 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
3042 // The pattern we're looking for is where our only predecessor is a switch on
3043 // 'V' and this block is the default case for the switch. In this case we can
3044 // fold the compared value into the switch to simplify things.
3045 BasicBlock *Pred = BB->getSinglePredecessor();
3046 if (!Pred || !isa<SwitchInst>(Pred->getTerminator())) return false;
3048 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
3049 if (SI->getCondition() != V)
3052 // If BB is reachable on a non-default case, then we simply know the value of
3053 // V in this block. Substitute it and constant fold the icmp instruction
3055 if (SI->getDefaultDest() != BB) {
3056 ConstantInt *VVal = SI->findCaseDest(BB);
3057 assert(VVal && "Should have a unique destination value");
3058 ICI->setOperand(0, VVal);
3060 if (Value *V = SimplifyInstruction(ICI, DL)) {
3061 ICI->replaceAllUsesWith(V);
3062 ICI->eraseFromParent();
3064 // BB is now empty, so it is likely to simplify away.
3065 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
3068 // Ok, the block is reachable from the default dest. If the constant we're
3069 // comparing exists in one of the other edges, then we can constant fold ICI
3071 if (SI->findCaseValue(Cst) != SI->case_default()) {
3073 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
3074 V = ConstantInt::getFalse(BB->getContext());
3076 V = ConstantInt::getTrue(BB->getContext());
3078 ICI->replaceAllUsesWith(V);
3079 ICI->eraseFromParent();
3080 // BB is now empty, so it is likely to simplify away.
3081 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
3084 // The use of the icmp has to be in the 'end' block, by the only PHI node in
3086 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
3087 PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
3088 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
3089 isa<PHINode>(++BasicBlock::iterator(PHIUse)))
3092 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
3094 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
3095 Constant *NewCst = ConstantInt::getFalse(BB->getContext());
3097 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
3098 std::swap(DefaultCst, NewCst);
3100 // Replace ICI (which is used by the PHI for the default value) with true or
3101 // false depending on if it is EQ or NE.
3102 ICI->replaceAllUsesWith(DefaultCst);
3103 ICI->eraseFromParent();
3105 // Okay, the switch goes to this block on a default value. Add an edge from
3106 // the switch to the merge point on the compared value.
3107 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "switch.edge",
3108 BB->getParent(), BB);
3109 SmallVector<uint64_t, 8> Weights;
3110 bool HasWeights = HasBranchWeights(SI);
3112 GetBranchWeights(SI, Weights);
3113 if (Weights.size() == 1 + SI->getNumCases()) {
3114 // Split weight for default case to case for "Cst".
3115 Weights[0] = (Weights[0]+1) >> 1;
3116 Weights.push_back(Weights[0]);
3118 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
3119 SI->setMetadata(LLVMContext::MD_prof,
3120 MDBuilder(SI->getContext()).
3121 createBranchWeights(MDWeights));
3124 SI->addCase(Cst, NewBB);
3126 // NewBB branches to the phi block, add the uncond branch and the phi entry.
3127 Builder.SetInsertPoint(NewBB);
3128 Builder.SetCurrentDebugLocation(SI->getDebugLoc());
3129 Builder.CreateBr(SuccBlock);
3130 PHIUse->addIncoming(NewCst, NewBB);
3134 /// The specified branch is a conditional branch.
3135 /// Check to see if it is branching on an or/and chain of icmp instructions, and
3136 /// fold it into a switch instruction if so.
3137 static bool SimplifyBranchOnICmpChain(BranchInst *BI, IRBuilder<> &Builder,
3138 const DataLayout &DL) {
3139 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
3140 if (!Cond) return false;
3142 // Change br (X == 0 | X == 1), T, F into a switch instruction.
3143 // If this is a bunch of seteq's or'd together, or if it's a bunch of
3144 // 'setne's and'ed together, collect them.
3146 // Try to gather values from a chain of and/or to be turned into a switch
3147 ConstantComparesGatherer ConstantCompare(Cond, DL);
3148 // Unpack the result
3149 SmallVectorImpl<ConstantInt*> &Values = ConstantCompare.Vals;
3150 Value *CompVal = ConstantCompare.CompValue;
3151 unsigned UsedICmps = ConstantCompare.UsedICmps;
3152 Value *ExtraCase = ConstantCompare.Extra;
3154 // If we didn't have a multiply compared value, fail.
3155 if (!CompVal) return false;
3157 // Avoid turning single icmps into a switch.
3161 bool TrueWhenEqual = (Cond->getOpcode() == Instruction::Or);
3163 // There might be duplicate constants in the list, which the switch
3164 // instruction can't handle, remove them now.
3165 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
3166 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
3168 // If Extra was used, we require at least two switch values to do the
3169 // transformation. A switch with one value is just a conditional branch.
3170 if (ExtraCase && Values.size() < 2) return false;
3172 // TODO: Preserve branch weight metadata, similarly to how
3173 // FoldValueComparisonIntoPredecessors preserves it.
3175 // Figure out which block is which destination.
3176 BasicBlock *DefaultBB = BI->getSuccessor(1);
3177 BasicBlock *EdgeBB = BI->getSuccessor(0);
3178 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
3180 BasicBlock *BB = BI->getParent();
3182 DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
3183 << " cases into SWITCH. BB is:\n" << *BB);
3185 // If there are any extra values that couldn't be folded into the switch
3186 // then we evaluate them with an explicit branch first. Split the block
3187 // right before the condbr to handle it.
3190 BB->splitBasicBlock(BI->getIterator(), "switch.early.test");
3191 // Remove the uncond branch added to the old block.
3192 TerminatorInst *OldTI = BB->getTerminator();
3193 Builder.SetInsertPoint(OldTI);
3196 Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
3198 Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
3200 OldTI->eraseFromParent();
3202 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
3203 // for the edge we just added.
3204 AddPredecessorToBlock(EdgeBB, BB, NewBB);
3206 DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
3207 << "\nEXTRABB = " << *BB);
3211 Builder.SetInsertPoint(BI);
3212 // Convert pointer to int before we switch.
3213 if (CompVal->getType()->isPointerTy()) {
3214 CompVal = Builder.CreatePtrToInt(
3215 CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr");
3218 // Create the new switch instruction now.
3219 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
3221 // Add all of the 'cases' to the switch instruction.
3222 for (unsigned i = 0, e = Values.size(); i != e; ++i)
3223 New->addCase(Values[i], EdgeBB);
3225 // We added edges from PI to the EdgeBB. As such, if there were any
3226 // PHI nodes in EdgeBB, they need entries to be added corresponding to
3227 // the number of edges added.
3228 for (BasicBlock::iterator BBI = EdgeBB->begin();
3229 isa<PHINode>(BBI); ++BBI) {
3230 PHINode *PN = cast<PHINode>(BBI);
3231 Value *InVal = PN->getIncomingValueForBlock(BB);
3232 for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
3233 PN->addIncoming(InVal, BB);
3236 // Erase the old branch instruction.
3237 EraseTerminatorInstAndDCECond(BI);
3239 DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
3243 bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
3244 if (isa<PHINode>(RI->getValue()))
3245 return SimplifyCommonResume(RI);
3246 else if (isa<LandingPadInst>(RI->getParent()->getFirstNonPHI()) &&
3247 RI->getValue() == RI->getParent()->getFirstNonPHI())
3248 // The resume must unwind the exception that caused control to branch here.
3249 return SimplifySingleResume(RI);
3254 // Simplify resume that is shared by several landing pads (phi of landing pad).
3255 bool SimplifyCFGOpt::SimplifyCommonResume(ResumeInst *RI) {
3256 BasicBlock *BB = RI->getParent();
3258 // Check that there are no other instructions except for debug intrinsics
3259 // between the phi of landing pads (RI->getValue()) and resume instruction.
3260 BasicBlock::iterator I = cast<Instruction>(RI->getValue())->getIterator(),
3261 E = RI->getIterator();
3263 if (!isa<DbgInfoIntrinsic>(I))
3266 SmallSet<BasicBlock *, 4> TrivialUnwindBlocks;
3267 auto *PhiLPInst = cast<PHINode>(RI->getValue());
3269 // Check incoming blocks to see if any of them are trivial.
3270 for (unsigned Idx = 0, End = PhiLPInst->getNumIncomingValues();
3271 Idx != End; Idx++) {
3272 auto *IncomingBB = PhiLPInst->getIncomingBlock(Idx);
3273 auto *IncomingValue = PhiLPInst->getIncomingValue(Idx);
3275 // If the block has other successors, we can not delete it because
3276 // it has other dependents.
3277 if (IncomingBB->getUniqueSuccessor() != BB)
3281 dyn_cast<LandingPadInst>(IncomingBB->getFirstNonPHI());
3282 // Not the landing pad that caused the control to branch here.
3283 if (IncomingValue != LandingPad)
3286 bool isTrivial = true;
3288 I = IncomingBB->getFirstNonPHI()->getIterator();
3289 E = IncomingBB->getTerminator()->getIterator();
3291 if (!isa<DbgInfoIntrinsic>(I)) {
3297 TrivialUnwindBlocks.insert(IncomingBB);
3300 // If no trivial unwind blocks, don't do any simplifications.
3301 if (TrivialUnwindBlocks.empty()) return false;
3303 // Turn all invokes that unwind here into calls.
3304 for (auto *TrivialBB : TrivialUnwindBlocks) {
3305 // Blocks that will be simplified should be removed from the phi node.
3306 // Note there could be multiple edges to the resume block, and we need
3307 // to remove them all.
3308 while (PhiLPInst->getBasicBlockIndex(TrivialBB) != -1)
3309 BB->removePredecessor(TrivialBB, true);
3311 for (pred_iterator PI = pred_begin(TrivialBB), PE = pred_end(TrivialBB);
3313 BasicBlock *Pred = *PI++;
3314 removeUnwindEdge(Pred);
3317 // In each SimplifyCFG run, only the current processed block can be erased.
3318 // Otherwise, it will break the iteration of SimplifyCFG pass. So instead
3319 // of erasing TrivialBB, we only remove the branch to the common resume
3320 // block so that we can later erase the resume block since it has no
3322 TrivialBB->getTerminator()->eraseFromParent();
3323 new UnreachableInst(RI->getContext(), TrivialBB);
3326 // Delete the resume block if all its predecessors have been removed.
3328 BB->eraseFromParent();
3330 return !TrivialUnwindBlocks.empty();
3333 // Simplify resume that is only used by a single (non-phi) landing pad.
3334 bool SimplifyCFGOpt::SimplifySingleResume(ResumeInst *RI) {
3335 BasicBlock *BB = RI->getParent();
3336 LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI());
3337 assert (RI->getValue() == LPInst &&
3338 "Resume must unwind the exception that caused control to here");
3340 // Check that there are no other instructions except for debug intrinsics.
3341 BasicBlock::iterator I = LPInst->getIterator(), E = RI->getIterator();
3343 if (!isa<DbgInfoIntrinsic>(I))
3346 // Turn all invokes that unwind here into calls and delete the basic block.
3347 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
3348 BasicBlock *Pred = *PI++;
3349 removeUnwindEdge(Pred);
3352 // The landingpad is now unreachable. Zap it.
3353 BB->eraseFromParent();
3357 bool SimplifyCFGOpt::SimplifyCleanupReturn(CleanupReturnInst *RI) {
3358 // If this is a trivial cleanup pad that executes no instructions, it can be
3359 // eliminated. If the cleanup pad continues to the caller, any predecessor
3360 // that is an EH pad will be updated to continue to the caller and any
3361 // predecessor that terminates with an invoke instruction will have its invoke
3362 // instruction converted to a call instruction. If the cleanup pad being
3363 // simplified does not continue to the caller, each predecessor will be
3364 // updated to continue to the unwind destination of the cleanup pad being
3366 BasicBlock *BB = RI->getParent();
3367 CleanupPadInst *CPInst = RI->getCleanupPad();
3368 if (CPInst->getParent() != BB)
3369 // This isn't an empty cleanup.
3372 // Check that there are no other instructions except for debug intrinsics.
3373 BasicBlock::iterator I = CPInst->getIterator(), E = RI->getIterator();
3375 if (!isa<DbgInfoIntrinsic>(I))
3378 // If the cleanup return we are simplifying unwinds to the caller, this will
3379 // set UnwindDest to nullptr.
3380 BasicBlock *UnwindDest = RI->getUnwindDest();
3381 Instruction *DestEHPad = UnwindDest ? UnwindDest->getFirstNonPHI() : nullptr;
3383 // We're about to remove BB from the control flow. Before we do, sink any
3384 // PHINodes into the unwind destination. Doing this before changing the
3385 // control flow avoids some potentially slow checks, since we can currently
3386 // be certain that UnwindDest and BB have no common predecessors (since they
3387 // are both EH pads).
3389 // First, go through the PHI nodes in UnwindDest and update any nodes that
3390 // reference the block we are removing
3391 for (BasicBlock::iterator I = UnwindDest->begin(),
3392 IE = DestEHPad->getIterator();
3394 PHINode *DestPN = cast<PHINode>(I);
3396 int Idx = DestPN->getBasicBlockIndex(BB);
3397 // Since BB unwinds to UnwindDest, it has to be in the PHI node.
3399 // This PHI node has an incoming value that corresponds to a control
3400 // path through the cleanup pad we are removing. If the incoming
3401 // value is in the cleanup pad, it must be a PHINode (because we
3402 // verified above that the block is otherwise empty). Otherwise, the
3403 // value is either a constant or a value that dominates the cleanup
3404 // pad being removed.
3406 // Because BB and UnwindDest are both EH pads, all of their
3407 // predecessors must unwind to these blocks, and since no instruction
3408 // can have multiple unwind destinations, there will be no overlap in
3409 // incoming blocks between SrcPN and DestPN.
3410 Value *SrcVal = DestPN->getIncomingValue(Idx);
3411 PHINode *SrcPN = dyn_cast<PHINode>(SrcVal);
3413 // Remove the entry for the block we are deleting.
3414 DestPN->removeIncomingValue(Idx, false);
3416 if (SrcPN && SrcPN->getParent() == BB) {
3417 // If the incoming value was a PHI node in the cleanup pad we are
3418 // removing, we need to merge that PHI node's incoming values into
3420 for (unsigned SrcIdx = 0, SrcE = SrcPN->getNumIncomingValues();
3421 SrcIdx != SrcE; ++SrcIdx) {
3422 DestPN->addIncoming(SrcPN->getIncomingValue(SrcIdx),
3423 SrcPN->getIncomingBlock(SrcIdx));
3426 // Otherwise, the incoming value came from above BB and
3427 // so we can just reuse it. We must associate all of BB's
3428 // predecessors with this value.
3429 for (auto *pred : predecessors(BB)) {
3430 DestPN->addIncoming(SrcVal, pred);
3435 // Sink any remaining PHI nodes directly into UnwindDest.
3436 Instruction *InsertPt = DestEHPad;
3437 for (BasicBlock::iterator I = BB->begin(),
3438 IE = BB->getFirstNonPHI()->getIterator();
3440 // The iterator must be incremented here because the instructions are
3441 // being moved to another block.
3442 PHINode *PN = cast<PHINode>(I++);
3443 if (PN->use_empty())
3444 // If the PHI node has no uses, just leave it. It will be erased
3445 // when we erase BB below.
3448 // Otherwise, sink this PHI node into UnwindDest.
3449 // Any predecessors to UnwindDest which are not already represented
3450 // must be back edges which inherit the value from the path through
3451 // BB. In this case, the PHI value must reference itself.
3452 for (auto *pred : predecessors(UnwindDest))
3454 PN->addIncoming(PN, pred);
3455 PN->moveBefore(InsertPt);
3459 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
3460 // The iterator must be updated here because we are removing this pred.
3461 BasicBlock *PredBB = *PI++;
3462 if (UnwindDest == nullptr) {
3463 removeUnwindEdge(PredBB);
3465 TerminatorInst *TI = PredBB->getTerminator();
3466 TI->replaceUsesOfWith(BB, UnwindDest);
3470 // The cleanup pad is now unreachable. Zap it.
3471 BB->eraseFromParent();
3475 bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
3476 BasicBlock *BB = RI->getParent();
3477 if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
3479 // Find predecessors that end with branches.
3480 SmallVector<BasicBlock*, 8> UncondBranchPreds;
3481 SmallVector<BranchInst*, 8> CondBranchPreds;
3482 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
3483 BasicBlock *P = *PI;
3484 TerminatorInst *PTI = P->getTerminator();
3485 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
3486 if (BI->isUnconditional())
3487 UncondBranchPreds.push_back(P);
3489 CondBranchPreds.push_back(BI);
3493 // If we found some, do the transformation!
3494 if (!UncondBranchPreds.empty() && DupRet) {
3495 while (!UncondBranchPreds.empty()) {
3496 BasicBlock *Pred = UncondBranchPreds.pop_back_val();
3497 DEBUG(dbgs() << "FOLDING: " << *BB
3498 << "INTO UNCOND BRANCH PRED: " << *Pred);
3499 (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
3502 // If we eliminated all predecessors of the block, delete the block now.
3504 // We know there are no successors, so just nuke the block.
3505 BB->eraseFromParent();
3510 // Check out all of the conditional branches going to this return
3511 // instruction. If any of them just select between returns, change the
3512 // branch itself into a select/return pair.
3513 while (!CondBranchPreds.empty()) {
3514 BranchInst *BI = CondBranchPreds.pop_back_val();
3516 // Check to see if the non-BB successor is also a return block.
3517 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
3518 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
3519 SimplifyCondBranchToTwoReturns(BI, Builder))
3525 bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
3526 BasicBlock *BB = UI->getParent();
3528 bool Changed = false;
3530 // If there are any instructions immediately before the unreachable that can
3531 // be removed, do so.
3532 while (UI->getIterator() != BB->begin()) {
3533 BasicBlock::iterator BBI = UI->getIterator();
3535 // Do not delete instructions that can have side effects which might cause
3536 // the unreachable to not be reachable; specifically, calls and volatile
3537 // operations may have this effect.
3538 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break;
3540 if (BBI->mayHaveSideEffects()) {
3541 if (auto *SI = dyn_cast<StoreInst>(BBI)) {
3542 if (SI->isVolatile())
3544 } else if (auto *LI = dyn_cast<LoadInst>(BBI)) {
3545 if (LI->isVolatile())
3547 } else if (auto *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
3548 if (RMWI->isVolatile())
3550 } else if (auto *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
3551 if (CXI->isVolatile())
3553 } else if (isa<CatchPadInst>(BBI)) {
3554 // A catchpad may invoke exception object constructors and such, which
3555 // in some languages can be arbitrary code, so be conservative by
3557 // For CoreCLR, it just involves a type test, so can be removed.
3558 if (classifyEHPersonality(BB->getParent()->getPersonalityFn()) !=
3559 EHPersonality::CoreCLR)
3561 } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
3562 !isa<LandingPadInst>(BBI)) {
3565 // Note that deleting LandingPad's here is in fact okay, although it
3566 // involves a bit of subtle reasoning. If this inst is a LandingPad,
3567 // all the predecessors of this block will be the unwind edges of Invokes,
3568 // and we can therefore guarantee this block will be erased.
3571 // Delete this instruction (any uses are guaranteed to be dead)
3572 if (!BBI->use_empty())
3573 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
3574 BBI->eraseFromParent();
3578 // If the unreachable instruction is the first in the block, take a gander
3579 // at all of the predecessors of this instruction, and simplify them.
3580 if (&BB->front() != UI) return Changed;
3582 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
3583 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
3584 TerminatorInst *TI = Preds[i]->getTerminator();
3585 IRBuilder<> Builder(TI);
3586 if (auto *BI = dyn_cast<BranchInst>(TI)) {
3587 if (BI->isUnconditional()) {
3588 if (BI->getSuccessor(0) == BB) {
3589 new UnreachableInst(TI->getContext(), TI);
3590 TI->eraseFromParent();
3594 if (BI->getSuccessor(0) == BB) {
3595 Builder.CreateBr(BI->getSuccessor(1));
3596 EraseTerminatorInstAndDCECond(BI);
3597 } else if (BI->getSuccessor(1) == BB) {
3598 Builder.CreateBr(BI->getSuccessor(0));
3599 EraseTerminatorInstAndDCECond(BI);
3603 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
3604 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
3606 if (i.getCaseSuccessor() == BB) {
3607 BB->removePredecessor(SI->getParent());
3612 } else if (auto *II = dyn_cast<InvokeInst>(TI)) {
3613 if (II->getUnwindDest() == BB) {
3614 removeUnwindEdge(TI->getParent());
3617 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
3618 if (CSI->getUnwindDest() == BB) {
3619 removeUnwindEdge(TI->getParent());
3624 for (CatchSwitchInst::handler_iterator I = CSI->handler_begin(),
3625 E = CSI->handler_end();
3628 CSI->removeHandler(I);
3634 if (CSI->getNumHandlers() == 0) {
3635 BasicBlock *CatchSwitchBB = CSI->getParent();
3636 if (CSI->hasUnwindDest()) {
3637 // Redirect preds to the unwind dest
3638 CatchSwitchBB->replaceAllUsesWith(CSI->getUnwindDest());
3640 // Rewrite all preds to unwind to caller (or from invoke to call).
3641 SmallVector<BasicBlock *, 8> EHPreds(predecessors(CatchSwitchBB));
3642 for (BasicBlock *EHPred : EHPreds)
3643 removeUnwindEdge(EHPred);
3645 // The catchswitch is no longer reachable.
3646 new UnreachableInst(CSI->getContext(), CSI);
3647 CSI->eraseFromParent();
3650 } else if (isa<CleanupReturnInst>(TI)) {
3651 new UnreachableInst(TI->getContext(), TI);
3652 TI->eraseFromParent();
3657 // If this block is now dead, remove it.
3658 if (pred_empty(BB) &&
3659 BB != &BB->getParent()->getEntryBlock()) {
3660 // We know there are no successors, so just nuke the block.
3661 BB->eraseFromParent();
3668 static bool CasesAreContiguous(SmallVectorImpl<ConstantInt *> &Cases) {
3669 assert(Cases.size() >= 1);
3671 array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
3672 for (size_t I = 1, E = Cases.size(); I != E; ++I) {
3673 if (Cases[I - 1]->getValue() != Cases[I]->getValue() + 1)
3679 /// Turn a switch with two reachable destinations into an integer range
3680 /// comparison and branch.
3681 static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
3682 assert(SI->getNumCases() > 1 && "Degenerate switch?");
3685 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
3687 // Partition the cases into two sets with different destinations.
3688 BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr;
3689 BasicBlock *DestB = nullptr;
3690 SmallVector <ConstantInt *, 16> CasesA;
3691 SmallVector <ConstantInt *, 16> CasesB;
3693 for (SwitchInst::CaseIt I : SI->cases()) {
3694 BasicBlock *Dest = I.getCaseSuccessor();
3695 if (!DestA) DestA = Dest;
3696 if (Dest == DestA) {
3697 CasesA.push_back(I.getCaseValue());
3700 if (!DestB) DestB = Dest;
3701 if (Dest == DestB) {
3702 CasesB.push_back(I.getCaseValue());
3705 return false; // More than two destinations.
3708 assert(DestA && DestB && "Single-destination switch should have been folded.");
3709 assert(DestA != DestB);
3710 assert(DestB != SI->getDefaultDest());
3711 assert(!CasesB.empty() && "There must be non-default cases.");
3712 assert(!CasesA.empty() || HasDefault);
3714 // Figure out if one of the sets of cases form a contiguous range.
3715 SmallVectorImpl<ConstantInt *> *ContiguousCases = nullptr;
3716 BasicBlock *ContiguousDest = nullptr;
3717 BasicBlock *OtherDest = nullptr;
3718 if (!CasesA.empty() && CasesAreContiguous(CasesA)) {
3719 ContiguousCases = &CasesA;
3720 ContiguousDest = DestA;
3722 } else if (CasesAreContiguous(CasesB)) {
3723 ContiguousCases = &CasesB;
3724 ContiguousDest = DestB;
3729 // Start building the compare and branch.
3731 Constant *Offset = ConstantExpr::getNeg(ContiguousCases->back());
3732 Constant *NumCases = ConstantInt::get(Offset->getType(), ContiguousCases->size());
3734 Value *Sub = SI->getCondition();
3735 if (!Offset->isNullValue())
3736 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off");
3739 // If NumCases overflowed, then all possible values jump to the successor.
3740 if (NumCases->isNullValue() && !ContiguousCases->empty())
3741 Cmp = ConstantInt::getTrue(SI->getContext());
3743 Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
3744 BranchInst *NewBI = Builder.CreateCondBr(Cmp, ContiguousDest, OtherDest);
3746 // Update weight for the newly-created conditional branch.
3747 if (HasBranchWeights(SI)) {
3748 SmallVector<uint64_t, 8> Weights;
3749 GetBranchWeights(SI, Weights);
3750 if (Weights.size() == 1 + SI->getNumCases()) {
3751 uint64_t TrueWeight = 0;
3752 uint64_t FalseWeight = 0;
3753 for (size_t I = 0, E = Weights.size(); I != E; ++I) {
3754 if (SI->getSuccessor(I) == ContiguousDest)
3755 TrueWeight += Weights[I];
3757 FalseWeight += Weights[I];
3759 while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) {
3763 NewBI->setMetadata(LLVMContext::MD_prof,
3764 MDBuilder(SI->getContext()).createBranchWeights(
3765 (uint32_t)TrueWeight, (uint32_t)FalseWeight));
3769 // Prune obsolete incoming values off the successors' PHI nodes.
3770 for (auto BBI = ContiguousDest->begin(); isa<PHINode>(BBI); ++BBI) {
3771 unsigned PreviousEdges = ContiguousCases->size();
3772 if (ContiguousDest == SI->getDefaultDest()) ++PreviousEdges;
3773 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
3774 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
3776 for (auto BBI = OtherDest->begin(); isa<PHINode>(BBI); ++BBI) {
3777 unsigned PreviousEdges = SI->getNumCases() - ContiguousCases->size();
3778 if (OtherDest == SI->getDefaultDest()) ++PreviousEdges;
3779 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
3780 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
3784 SI->eraseFromParent();
3789 /// Compute masked bits for the condition of a switch
3790 /// and use it to remove dead cases.
3791 static bool EliminateDeadSwitchCases(SwitchInst *SI, AssumptionCache *AC,
3792 const DataLayout &DL) {
3793 Value *Cond = SI->getCondition();
3794 unsigned Bits = Cond->getType()->getIntegerBitWidth();
3795 APInt KnownZero(Bits, 0), KnownOne(Bits, 0);
3796 computeKnownBits(Cond, KnownZero, KnownOne, DL, 0, AC, SI);
3798 // Gather dead cases.
3799 SmallVector<ConstantInt*, 8> DeadCases;
3800 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
3801 if ((I.getCaseValue()->getValue() & KnownZero) != 0 ||
3802 (I.getCaseValue()->getValue() & KnownOne) != KnownOne) {
3803 DeadCases.push_back(I.getCaseValue());
3804 DEBUG(dbgs() << "SimplifyCFG: switch case '"
3805 << I.getCaseValue() << "' is dead.\n");
3809 // If we can prove that the cases must cover all possible values, the
3810 // default destination becomes dead and we can remove it. If we know some
3811 // of the bits in the value, we can use that to more precisely compute the
3812 // number of possible unique case values.
3814 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
3815 const unsigned NumUnknownBits = Bits -
3816 (KnownZero.Or(KnownOne)).countPopulation();
3817 assert(NumUnknownBits <= Bits);
3818 if (HasDefault && DeadCases.empty() &&
3819 NumUnknownBits < 64 /* avoid overflow */ &&
3820 SI->getNumCases() == (1ULL << NumUnknownBits)) {
3821 DEBUG(dbgs() << "SimplifyCFG: switch default is dead.\n");
3822 BasicBlock *NewDefault = SplitBlockPredecessors(SI->getDefaultDest(),
3823 SI->getParent(), "");
3824 SI->setDefaultDest(&*NewDefault);
3825 SplitBlock(&*NewDefault, &NewDefault->front());
3826 auto *OldTI = NewDefault->getTerminator();
3827 new UnreachableInst(SI->getContext(), OldTI);
3828 EraseTerminatorInstAndDCECond(OldTI);
3832 SmallVector<uint64_t, 8> Weights;
3833 bool HasWeight = HasBranchWeights(SI);
3835 GetBranchWeights(SI, Weights);
3836 HasWeight = (Weights.size() == 1 + SI->getNumCases());
3839 // Remove dead cases from the switch.
3840 for (unsigned I = 0, E = DeadCases.size(); I != E; ++I) {
3841 SwitchInst::CaseIt Case = SI->findCaseValue(DeadCases[I]);
3842 assert(Case != SI->case_default() &&
3843 "Case was not found. Probably mistake in DeadCases forming.");
3845 std::swap(Weights[Case.getCaseIndex()+1], Weights.back());
3849 // Prune unused values from PHI nodes.
3850 Case.getCaseSuccessor()->removePredecessor(SI->getParent());
3851 SI->removeCase(Case);
3853 if (HasWeight && Weights.size() >= 2) {
3854 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
3855 SI->setMetadata(LLVMContext::MD_prof,
3856 MDBuilder(SI->getParent()->getContext()).
3857 createBranchWeights(MDWeights));
3860 return !DeadCases.empty();
3863 /// If BB would be eligible for simplification by
3864 /// TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
3865 /// by an unconditional branch), look at the phi node for BB in the successor
3866 /// block and see if the incoming value is equal to CaseValue. If so, return
3867 /// the phi node, and set PhiIndex to BB's index in the phi node.
3868 static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
3871 if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
3872 return nullptr; // BB must be empty to be a candidate for simplification.
3873 if (!BB->getSinglePredecessor())
3874 return nullptr; // BB must be dominated by the switch.
3876 BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
3877 if (!Branch || !Branch->isUnconditional())
3878 return nullptr; // Terminator must be unconditional branch.
3880 BasicBlock *Succ = Branch->getSuccessor(0);
3882 BasicBlock::iterator I = Succ->begin();
3883 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3884 int Idx = PHI->getBasicBlockIndex(BB);
3885 assert(Idx >= 0 && "PHI has no entry for predecessor?");
3887 Value *InValue = PHI->getIncomingValue(Idx);
3888 if (InValue != CaseValue) continue;
3897 /// Try to forward the condition of a switch instruction to a phi node
3898 /// dominated by the switch, if that would mean that some of the destination
3899 /// blocks of the switch can be folded away.
3900 /// Returns true if a change is made.
3901 static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
3902 typedef DenseMap<PHINode*, SmallVector<int,4> > ForwardingNodesMap;
3903 ForwardingNodesMap ForwardingNodes;
3905 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
3906 ConstantInt *CaseValue = I.getCaseValue();
3907 BasicBlock *CaseDest = I.getCaseSuccessor();
3910 PHINode *PHI = FindPHIForConditionForwarding(CaseValue, CaseDest,
3914 ForwardingNodes[PHI].push_back(PhiIndex);
3917 bool Changed = false;
3919 for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(),
3920 E = ForwardingNodes.end(); I != E; ++I) {
3921 PHINode *Phi = I->first;
3922 SmallVectorImpl<int> &Indexes = I->second;
3924 if (Indexes.size() < 2) continue;
3926 for (size_t I = 0, E = Indexes.size(); I != E; ++I)
3927 Phi->setIncomingValue(Indexes[I], SI->getCondition());
3934 /// Return true if the backend will be able to handle
3935 /// initializing an array of constants like C.
3936 static bool ValidLookupTableConstant(Constant *C) {
3937 if (C->isThreadDependent())
3939 if (C->isDLLImportDependent())
3942 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
3943 return CE->isGEPWithNoNotionalOverIndexing();
3945 return isa<ConstantFP>(C) ||
3946 isa<ConstantInt>(C) ||
3947 isa<ConstantPointerNull>(C) ||
3948 isa<GlobalValue>(C) ||
3952 /// If V is a Constant, return it. Otherwise, try to look up
3953 /// its constant value in ConstantPool, returning 0 if it's not there.
3954 static Constant *LookupConstant(Value *V,
3955 const SmallDenseMap<Value*, Constant*>& ConstantPool) {
3956 if (Constant *C = dyn_cast<Constant>(V))
3958 return ConstantPool.lookup(V);
3961 /// Try to fold instruction I into a constant. This works for
3962 /// simple instructions such as binary operations where both operands are
3963 /// constant or can be replaced by constants from the ConstantPool. Returns the
3964 /// resulting constant on success, 0 otherwise.
3966 ConstantFold(Instruction *I, const DataLayout &DL,
3967 const SmallDenseMap<Value *, Constant *> &ConstantPool) {
3968 if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
3969 Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
3972 if (A->isAllOnesValue())
3973 return LookupConstant(Select->getTrueValue(), ConstantPool);
3974 if (A->isNullValue())
3975 return LookupConstant(Select->getFalseValue(), ConstantPool);
3979 SmallVector<Constant *, 4> COps;
3980 for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
3981 if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
3987 if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
3988 return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0],
3992 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), COps, DL);
3995 /// Try to determine the resulting constant values in phi nodes
3996 /// at the common destination basic block, *CommonDest, for one of the case
3997 /// destionations CaseDest corresponding to value CaseVal (0 for the default
3998 /// case), of a switch instruction SI.
4000 GetCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest,
4001 BasicBlock **CommonDest,
4002 SmallVectorImpl<std::pair<PHINode *, Constant *>> &Res,
4003 const DataLayout &DL) {
4004 // The block from which we enter the common destination.
4005 BasicBlock *Pred = SI->getParent();
4007 // If CaseDest is empty except for some side-effect free instructions through
4008 // which we can constant-propagate the CaseVal, continue to its successor.
4009 SmallDenseMap<Value*, Constant*> ConstantPool;
4010 ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
4011 for (BasicBlock::iterator I = CaseDest->begin(), E = CaseDest->end(); I != E;
4013 if (TerminatorInst *T = dyn_cast<TerminatorInst>(I)) {
4014 // If the terminator is a simple branch, continue to the next block.
4015 if (T->getNumSuccessors() != 1)
4018 CaseDest = T->getSuccessor(0);
4019 } else if (isa<DbgInfoIntrinsic>(I)) {
4020 // Skip debug intrinsic.
4022 } else if (Constant *C = ConstantFold(&*I, DL, ConstantPool)) {
4023 // Instruction is side-effect free and constant.
4025 // If the instruction has uses outside this block or a phi node slot for
4026 // the block, it is not safe to bypass the instruction since it would then
4027 // no longer dominate all its uses.
4028 for (auto &Use : I->uses()) {
4029 User *User = Use.getUser();
4030 if (Instruction *I = dyn_cast<Instruction>(User))
4031 if (I->getParent() == CaseDest)
4033 if (PHINode *Phi = dyn_cast<PHINode>(User))
4034 if (Phi->getIncomingBlock(Use) == CaseDest)
4039 ConstantPool.insert(std::make_pair(&*I, C));
4045 // If we did not have a CommonDest before, use the current one.
4047 *CommonDest = CaseDest;
4048 // If the destination isn't the common one, abort.
4049 if (CaseDest != *CommonDest)
4052 // Get the values for this case from phi nodes in the destination block.
4053 BasicBlock::iterator I = (*CommonDest)->begin();
4054 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
4055 int Idx = PHI->getBasicBlockIndex(Pred);
4059 Constant *ConstVal = LookupConstant(PHI->getIncomingValue(Idx),
4064 // Be conservative about which kinds of constants we support.
4065 if (!ValidLookupTableConstant(ConstVal))
4068 Res.push_back(std::make_pair(PHI, ConstVal));
4071 return Res.size() > 0;
4074 // Helper function used to add CaseVal to the list of cases that generate
4076 static void MapCaseToResult(ConstantInt *CaseVal,
4077 SwitchCaseResultVectorTy &UniqueResults,
4079 for (auto &I : UniqueResults) {
4080 if (I.first == Result) {
4081 I.second.push_back(CaseVal);
4085 UniqueResults.push_back(std::make_pair(Result,
4086 SmallVector<ConstantInt*, 4>(1, CaseVal)));
4089 // Helper function that initializes a map containing
4090 // results for the PHI node of the common destination block for a switch
4091 // instruction. Returns false if multiple PHI nodes have been found or if
4092 // there is not a common destination block for the switch.
4093 static bool InitializeUniqueCases(SwitchInst *SI, PHINode *&PHI,
4094 BasicBlock *&CommonDest,
4095 SwitchCaseResultVectorTy &UniqueResults,
4096 Constant *&DefaultResult,
4097 const DataLayout &DL) {
4098 for (auto &I : SI->cases()) {
4099 ConstantInt *CaseVal = I.getCaseValue();
4101 // Resulting value at phi nodes for this case value.
4102 SwitchCaseResultsTy Results;
4103 if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results,
4107 // Only one value per case is permitted
4108 if (Results.size() > 1)
4110 MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second);
4112 // Check the PHI consistency.
4114 PHI = Results[0].first;
4115 else if (PHI != Results[0].first)
4118 // Find the default result value.
4119 SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults;
4120 BasicBlock *DefaultDest = SI->getDefaultDest();
4121 GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults,
4123 // If the default value is not found abort unless the default destination
4126 DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr;
4127 if ((!DefaultResult &&
4128 !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg())))
4134 // Helper function that checks if it is possible to transform a switch with only
4135 // two cases (or two cases + default) that produces a result into a select.
4138 // case 10: %0 = icmp eq i32 %a, 10
4139 // return 10; %1 = select i1 %0, i32 10, i32 4
4140 // case 20: ----> %2 = icmp eq i32 %a, 20
4141 // return 2; %3 = select i1 %2, i32 2, i32 %1
4146 ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector,
4147 Constant *DefaultResult, Value *Condition,
4148 IRBuilder<> &Builder) {
4149 assert(ResultVector.size() == 2 &&
4150 "We should have exactly two unique results at this point");
4151 // If we are selecting between only two cases transform into a simple
4152 // select or a two-way select if default is possible.
4153 if (ResultVector[0].second.size() == 1 &&
4154 ResultVector[1].second.size() == 1) {
4155 ConstantInt *const FirstCase = ResultVector[0].second[0];
4156 ConstantInt *const SecondCase = ResultVector[1].second[0];
4158 bool DefaultCanTrigger = DefaultResult;
4159 Value *SelectValue = ResultVector[1].first;
4160 if (DefaultCanTrigger) {
4161 Value *const ValueCompare =
4162 Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp");
4163 SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first,
4164 DefaultResult, "switch.select");
4166 Value *const ValueCompare =
4167 Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp");
4168 return Builder.CreateSelect(ValueCompare, ResultVector[0].first, SelectValue,
4175 // Helper function to cleanup a switch instruction that has been converted into
4176 // a select, fixing up PHI nodes and basic blocks.
4177 static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI,
4179 IRBuilder<> &Builder) {
4180 BasicBlock *SelectBB = SI->getParent();
4181 while (PHI->getBasicBlockIndex(SelectBB) >= 0)
4182 PHI->removeIncomingValue(SelectBB);
4183 PHI->addIncoming(SelectValue, SelectBB);
4185 Builder.CreateBr(PHI->getParent());
4187 // Remove the switch.
4188 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
4189 BasicBlock *Succ = SI->getSuccessor(i);
4191 if (Succ == PHI->getParent())
4193 Succ->removePredecessor(SelectBB);
4195 SI->eraseFromParent();
4198 /// If the switch is only used to initialize one or more
4199 /// phi nodes in a common successor block with only two different
4200 /// constant values, replace the switch with select.
4201 static bool SwitchToSelect(SwitchInst *SI, IRBuilder<> &Builder,
4202 AssumptionCache *AC, const DataLayout &DL) {
4203 Value *const Cond = SI->getCondition();
4204 PHINode *PHI = nullptr;
4205 BasicBlock *CommonDest = nullptr;
4206 Constant *DefaultResult;
4207 SwitchCaseResultVectorTy UniqueResults;
4208 // Collect all the cases that will deliver the same value from the switch.
4209 if (!InitializeUniqueCases(SI, PHI, CommonDest, UniqueResults, DefaultResult,
4212 // Selects choose between maximum two values.
4213 if (UniqueResults.size() != 2)
4215 assert(PHI != nullptr && "PHI for value select not found");
4217 Builder.SetInsertPoint(SI);
4218 Value *SelectValue = ConvertTwoCaseSwitch(
4220 DefaultResult, Cond, Builder);
4222 RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder);
4225 // The switch couldn't be converted into a select.
4230 /// This class represents a lookup table that can be used to replace a switch.
4231 class SwitchLookupTable {
4233 /// Create a lookup table to use as a switch replacement with the contents
4234 /// of Values, using DefaultValue to fill any holes in the table.
4236 Module &M, uint64_t TableSize, ConstantInt *Offset,
4237 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
4238 Constant *DefaultValue, const DataLayout &DL);
4240 /// Build instructions with Builder to retrieve the value at
4241 /// the position given by Index in the lookup table.
4242 Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
4244 /// Return true if a table with TableSize elements of
4245 /// type ElementType would fit in a target-legal register.
4246 static bool WouldFitInRegister(const DataLayout &DL, uint64_t TableSize,
4250 // Depending on the contents of the table, it can be represented in
4253 // For tables where each element contains the same value, we just have to
4254 // store that single value and return it for each lookup.
4257 // For tables where there is a linear relationship between table index
4258 // and values. We calculate the result with a simple multiplication
4259 // and addition instead of a table lookup.
4262 // For small tables with integer elements, we can pack them into a bitmap
4263 // that fits into a target-legal register. Values are retrieved by
4264 // shift and mask operations.
4267 // The table is stored as an array of values. Values are retrieved by load
4268 // instructions from the table.
4272 // For SingleValueKind, this is the single value.
4273 Constant *SingleValue;
4275 // For BitMapKind, this is the bitmap.
4276 ConstantInt *BitMap;
4277 IntegerType *BitMapElementTy;
4279 // For LinearMapKind, these are the constants used to derive the value.
4280 ConstantInt *LinearOffset;
4281 ConstantInt *LinearMultiplier;
4283 // For ArrayKind, this is the array.
4284 GlobalVariable *Array;
4288 SwitchLookupTable::SwitchLookupTable(
4289 Module &M, uint64_t TableSize, ConstantInt *Offset,
4290 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
4291 Constant *DefaultValue, const DataLayout &DL)
4292 : SingleValue(nullptr), BitMap(nullptr), BitMapElementTy(nullptr),
4293 LinearOffset(nullptr), LinearMultiplier(nullptr), Array(nullptr) {
4294 assert(Values.size() && "Can't build lookup table without values!");
4295 assert(TableSize >= Values.size() && "Can't fit values in table!");
4297 // If all values in the table are equal, this is that value.
4298 SingleValue = Values.begin()->second;
4300 Type *ValueType = Values.begin()->second->getType();
4302 // Build up the table contents.
4303 SmallVector<Constant*, 64> TableContents(TableSize);
4304 for (size_t I = 0, E = Values.size(); I != E; ++I) {
4305 ConstantInt *CaseVal = Values[I].first;
4306 Constant *CaseRes = Values[I].second;
4307 assert(CaseRes->getType() == ValueType);
4309 uint64_t Idx = (CaseVal->getValue() - Offset->getValue())
4311 TableContents[Idx] = CaseRes;
4313 if (CaseRes != SingleValue)
4314 SingleValue = nullptr;
4317 // Fill in any holes in the table with the default result.
4318 if (Values.size() < TableSize) {
4319 assert(DefaultValue &&
4320 "Need a default value to fill the lookup table holes.");
4321 assert(DefaultValue->getType() == ValueType);
4322 for (uint64_t I = 0; I < TableSize; ++I) {
4323 if (!TableContents[I])
4324 TableContents[I] = DefaultValue;
4327 if (DefaultValue != SingleValue)
4328 SingleValue = nullptr;
4331 // If each element in the table contains the same value, we only need to store
4332 // that single value.
4334 Kind = SingleValueKind;
4338 // Check if we can derive the value with a linear transformation from the
4340 if (isa<IntegerType>(ValueType)) {
4341 bool LinearMappingPossible = true;
4344 assert(TableSize >= 2 && "Should be a SingleValue table.");
4345 // Check if there is the same distance between two consecutive values.
4346 for (uint64_t I = 0; I < TableSize; ++I) {
4347 ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]);
4349 // This is an undef. We could deal with it, but undefs in lookup tables
4350 // are very seldom. It's probably not worth the additional complexity.
4351 LinearMappingPossible = false;
4354 APInt Val = ConstVal->getValue();
4356 APInt Dist = Val - PrevVal;
4359 } else if (Dist != DistToPrev) {
4360 LinearMappingPossible = false;
4366 if (LinearMappingPossible) {
4367 LinearOffset = cast<ConstantInt>(TableContents[0]);
4368 LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev);
4369 Kind = LinearMapKind;
4375 // If the type is integer and the table fits in a register, build a bitmap.
4376 if (WouldFitInRegister(DL, TableSize, ValueType)) {
4377 IntegerType *IT = cast<IntegerType>(ValueType);
4378 APInt TableInt(TableSize * IT->getBitWidth(), 0);
4379 for (uint64_t I = TableSize; I > 0; --I) {
4380 TableInt <<= IT->getBitWidth();
4381 // Insert values into the bitmap. Undef values are set to zero.
4382 if (!isa<UndefValue>(TableContents[I - 1])) {
4383 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
4384 TableInt |= Val->getValue().zext(TableInt.getBitWidth());
4387 BitMap = ConstantInt::get(M.getContext(), TableInt);
4388 BitMapElementTy = IT;
4394 // Store the table in an array.
4395 ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
4396 Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
4398 Array = new GlobalVariable(M, ArrayTy, /*constant=*/ true,
4399 GlobalVariable::PrivateLinkage,
4402 Array->setUnnamedAddr(true);
4406 Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
4408 case SingleValueKind:
4410 case LinearMapKind: {
4411 // Derive the result value from the input value.
4412 Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(),
4413 false, "switch.idx.cast");
4414 if (!LinearMultiplier->isOne())
4415 Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult");
4416 if (!LinearOffset->isZero())
4417 Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset");
4421 // Type of the bitmap (e.g. i59).
4422 IntegerType *MapTy = BitMap->getType();
4424 // Cast Index to the same type as the bitmap.
4425 // Note: The Index is <= the number of elements in the table, so
4426 // truncating it to the width of the bitmask is safe.
4427 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
4429 // Multiply the shift amount by the element width.
4430 ShiftAmt = Builder.CreateMul(ShiftAmt,
4431 ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
4435 Value *DownShifted = Builder.CreateLShr(BitMap, ShiftAmt,
4436 "switch.downshift");
4438 return Builder.CreateTrunc(DownShifted, BitMapElementTy,
4442 // Make sure the table index will not overflow when treated as signed.
4443 IntegerType *IT = cast<IntegerType>(Index->getType());
4444 uint64_t TableSize = Array->getInitializer()->getType()
4445 ->getArrayNumElements();
4446 if (TableSize > (1ULL << (IT->getBitWidth() - 1)))
4447 Index = Builder.CreateZExt(Index,
4448 IntegerType::get(IT->getContext(),
4449 IT->getBitWidth() + 1),
4450 "switch.tableidx.zext");
4452 Value *GEPIndices[] = { Builder.getInt32(0), Index };
4453 Value *GEP = Builder.CreateInBoundsGEP(Array->getValueType(), Array,
4454 GEPIndices, "switch.gep");
4455 return Builder.CreateLoad(GEP, "switch.load");
4458 llvm_unreachable("Unknown lookup table kind!");
4461 bool SwitchLookupTable::WouldFitInRegister(const DataLayout &DL,
4463 Type *ElementType) {
4464 auto *IT = dyn_cast<IntegerType>(ElementType);
4467 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
4468 // are <= 15, we could try to narrow the type.
4470 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
4471 if (TableSize >= UINT_MAX/IT->getBitWidth())
4473 return DL.fitsInLegalInteger(TableSize * IT->getBitWidth());
4476 /// Determine whether a lookup table should be built for this switch, based on
4477 /// the number of cases, size of the table, and the types of the results.
4479 ShouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize,
4480 const TargetTransformInfo &TTI, const DataLayout &DL,
4481 const SmallDenseMap<PHINode *, Type *> &ResultTypes) {
4482 if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
4483 return false; // TableSize overflowed, or mul below might overflow.
4485 bool AllTablesFitInRegister = true;
4486 bool HasIllegalType = false;
4487 for (const auto &I : ResultTypes) {
4488 Type *Ty = I.second;
4490 // Saturate this flag to true.
4491 HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty);
4493 // Saturate this flag to false.
4494 AllTablesFitInRegister = AllTablesFitInRegister &&
4495 SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
4497 // If both flags saturate, we're done. NOTE: This *only* works with
4498 // saturating flags, and all flags have to saturate first due to the
4499 // non-deterministic behavior of iterating over a dense map.
4500 if (HasIllegalType && !AllTablesFitInRegister)
4504 // If each table would fit in a register, we should build it anyway.
4505 if (AllTablesFitInRegister)
4508 // Don't build a table that doesn't fit in-register if it has illegal types.
4512 // The table density should be at least 40%. This is the same criterion as for
4513 // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
4514 // FIXME: Find the best cut-off.
4515 return SI->getNumCases() * 10 >= TableSize * 4;
4518 /// Try to reuse the switch table index compare. Following pattern:
4520 /// if (idx < tablesize)
4521 /// r = table[idx]; // table does not contain default_value
4523 /// r = default_value;
4524 /// if (r != default_value)
4527 /// Is optimized to:
4529 /// cond = idx < tablesize;
4533 /// r = default_value;
4537 /// Jump threading will then eliminate the second if(cond).
4538 static void reuseTableCompare(User *PhiUser, BasicBlock *PhiBlock,
4539 BranchInst *RangeCheckBranch, Constant *DefaultValue,
4540 const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values) {
4542 ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser);
4546 // We require that the compare is in the same block as the phi so that jump
4547 // threading can do its work afterwards.
4548 if (CmpInst->getParent() != PhiBlock)
4551 Constant *CmpOp1 = dyn_cast<Constant>(CmpInst->getOperand(1));
4555 Value *RangeCmp = RangeCheckBranch->getCondition();
4556 Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType());
4557 Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType());
4559 // Check if the compare with the default value is constant true or false.
4560 Constant *DefaultConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
4561 DefaultValue, CmpOp1, true);
4562 if (DefaultConst != TrueConst && DefaultConst != FalseConst)
4565 // Check if the compare with the case values is distinct from the default
4567 for (auto ValuePair : Values) {
4568 Constant *CaseConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
4569 ValuePair.second, CmpOp1, true);
4570 if (!CaseConst || CaseConst == DefaultConst)
4572 assert((CaseConst == TrueConst || CaseConst == FalseConst) &&
4573 "Expect true or false as compare result.");
4576 // Check if the branch instruction dominates the phi node. It's a simple
4577 // dominance check, but sufficient for our needs.
4578 // Although this check is invariant in the calling loops, it's better to do it
4579 // at this late stage. Practically we do it at most once for a switch.
4580 BasicBlock *BranchBlock = RangeCheckBranch->getParent();
4581 for (auto PI = pred_begin(PhiBlock), E = pred_end(PhiBlock); PI != E; ++PI) {
4582 BasicBlock *Pred = *PI;
4583 if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock)
4587 if (DefaultConst == FalseConst) {
4588 // The compare yields the same result. We can replace it.
4589 CmpInst->replaceAllUsesWith(RangeCmp);
4590 ++NumTableCmpReuses;
4592 // The compare yields the same result, just inverted. We can replace it.
4593 Value *InvertedTableCmp = BinaryOperator::CreateXor(RangeCmp,
4594 ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp",
4596 CmpInst->replaceAllUsesWith(InvertedTableCmp);
4597 ++NumTableCmpReuses;
4601 /// If the switch is only used to initialize one or more phi nodes in a common
4602 /// successor block with different constant values, replace the switch with
4604 static bool SwitchToLookupTable(SwitchInst *SI, IRBuilder<> &Builder,
4605 const DataLayout &DL,
4606 const TargetTransformInfo &TTI) {
4607 assert(SI->getNumCases() > 1 && "Degenerate switch?");
4609 // Only build lookup table when we have a target that supports it.
4610 if (!TTI.shouldBuildLookupTables())
4613 // FIXME: If the switch is too sparse for a lookup table, perhaps we could
4614 // split off a dense part and build a lookup table for that.
4616 // FIXME: This creates arrays of GEPs to constant strings, which means each
4617 // GEP needs a runtime relocation in PIC code. We should just build one big
4618 // string and lookup indices into that.
4620 // Ignore switches with less than three cases. Lookup tables will not make them
4621 // faster, so we don't analyze them.
4622 if (SI->getNumCases() < 3)
4625 // Figure out the corresponding result for each case value and phi node in the
4626 // common destination, as well as the min and max case values.
4627 assert(SI->case_begin() != SI->case_end());
4628 SwitchInst::CaseIt CI = SI->case_begin();
4629 ConstantInt *MinCaseVal = CI.getCaseValue();
4630 ConstantInt *MaxCaseVal = CI.getCaseValue();
4632 BasicBlock *CommonDest = nullptr;
4633 typedef SmallVector<std::pair<ConstantInt*, Constant*>, 4> ResultListTy;
4634 SmallDenseMap<PHINode*, ResultListTy> ResultLists;
4635 SmallDenseMap<PHINode*, Constant*> DefaultResults;
4636 SmallDenseMap<PHINode*, Type*> ResultTypes;
4637 SmallVector<PHINode*, 4> PHIs;
4639 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
4640 ConstantInt *CaseVal = CI.getCaseValue();
4641 if (CaseVal->getValue().slt(MinCaseVal->getValue()))
4642 MinCaseVal = CaseVal;
4643 if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
4644 MaxCaseVal = CaseVal;
4646 // Resulting value at phi nodes for this case value.
4647 typedef SmallVector<std::pair<PHINode*, Constant*>, 4> ResultsTy;
4649 if (!GetCaseResults(SI, CaseVal, CI.getCaseSuccessor(), &CommonDest,
4653 // Append the result from this case to the list for each phi.
4654 for (const auto &I : Results) {
4655 PHINode *PHI = I.first;
4656 Constant *Value = I.second;
4657 if (!ResultLists.count(PHI))
4658 PHIs.push_back(PHI);
4659 ResultLists[PHI].push_back(std::make_pair(CaseVal, Value));
4663 // Keep track of the result types.
4664 for (PHINode *PHI : PHIs) {
4665 ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
4668 uint64_t NumResults = ResultLists[PHIs[0]].size();
4669 APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
4670 uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
4671 bool TableHasHoles = (NumResults < TableSize);
4673 // If the table has holes, we need a constant result for the default case
4674 // or a bitmask that fits in a register.
4675 SmallVector<std::pair<PHINode*, Constant*>, 4> DefaultResultsList;
4676 bool HasDefaultResults = GetCaseResults(SI, nullptr, SI->getDefaultDest(),
4677 &CommonDest, DefaultResultsList, DL);
4679 bool NeedMask = (TableHasHoles && !HasDefaultResults);
4681 // As an extra penalty for the validity test we require more cases.
4682 if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
4684 if (!DL.fitsInLegalInteger(TableSize))
4688 for (const auto &I : DefaultResultsList) {
4689 PHINode *PHI = I.first;
4690 Constant *Result = I.second;
4691 DefaultResults[PHI] = Result;
4694 if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
4697 // Create the BB that does the lookups.
4698 Module &Mod = *CommonDest->getParent()->getParent();
4699 BasicBlock *LookupBB = BasicBlock::Create(Mod.getContext(),
4701 CommonDest->getParent(),
4704 // Compute the table index value.
4705 Builder.SetInsertPoint(SI);
4706 Value *TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal,
4709 // Compute the maximum table size representable by the integer type we are
4711 unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
4712 uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
4713 assert(MaxTableSize >= TableSize &&
4714 "It is impossible for a switch to have more entries than the max "
4715 "representable value of its input integer type's size.");
4717 // If the default destination is unreachable, or if the lookup table covers
4718 // all values of the conditional variable, branch directly to the lookup table
4719 // BB. Otherwise, check that the condition is within the case range.
4720 const bool DefaultIsReachable =
4721 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
4722 const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize);
4723 BranchInst *RangeCheckBranch = nullptr;
4725 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
4726 Builder.CreateBr(LookupBB);
4727 // Note: We call removeProdecessor later since we need to be able to get the
4728 // PHI value for the default case in case we're using a bit mask.
4730 Value *Cmp = Builder.CreateICmpULT(TableIndex, ConstantInt::get(
4731 MinCaseVal->getType(), TableSize));
4732 RangeCheckBranch = Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
4735 // Populate the BB that does the lookups.
4736 Builder.SetInsertPoint(LookupBB);
4739 // Before doing the lookup we do the hole check.
4740 // The LookupBB is therefore re-purposed to do the hole check
4741 // and we create a new LookupBB.
4742 BasicBlock *MaskBB = LookupBB;
4743 MaskBB->setName("switch.hole_check");
4744 LookupBB = BasicBlock::Create(Mod.getContext(),
4746 CommonDest->getParent(),
4749 // Make the mask's bitwidth at least 8bit and a power-of-2 to avoid
4750 // unnecessary illegal types.
4751 uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL));
4752 APInt MaskInt(TableSizePowOf2, 0);
4753 APInt One(TableSizePowOf2, 1);
4754 // Build bitmask; fill in a 1 bit for every case.
4755 const ResultListTy &ResultList = ResultLists[PHIs[0]];
4756 for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
4757 uint64_t Idx = (ResultList[I].first->getValue() -
4758 MinCaseVal->getValue()).getLimitedValue();
4759 MaskInt |= One << Idx;
4761 ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
4763 // Get the TableIndex'th bit of the bitmask.
4764 // If this bit is 0 (meaning hole) jump to the default destination,
4765 // else continue with table lookup.
4766 IntegerType *MapTy = TableMask->getType();
4767 Value *MaskIndex = Builder.CreateZExtOrTrunc(TableIndex, MapTy,
4768 "switch.maskindex");
4769 Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex,
4771 Value *LoBit = Builder.CreateTrunc(Shifted,
4772 Type::getInt1Ty(Mod.getContext()),
4774 Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
4776 Builder.SetInsertPoint(LookupBB);
4777 AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent());
4780 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
4781 // We cached PHINodes in PHIs, to avoid accessing deleted PHINodes later,
4782 // do not delete PHINodes here.
4783 SI->getDefaultDest()->removePredecessor(SI->getParent(),
4784 /*DontDeleteUselessPHIs=*/true);
4787 bool ReturnedEarly = false;
4788 for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
4789 PHINode *PHI = PHIs[I];
4790 const ResultListTy &ResultList = ResultLists[PHI];
4792 // If using a bitmask, use any value to fill the lookup table holes.
4793 Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
4794 SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL);
4796 Value *Result = Table.BuildLookup(TableIndex, Builder);
4798 // If the result is used to return immediately from the function, we want to
4799 // do that right here.
4800 if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
4801 PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) {
4802 Builder.CreateRet(Result);
4803 ReturnedEarly = true;
4807 // Do a small peephole optimization: re-use the switch table compare if
4809 if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) {
4810 BasicBlock *PhiBlock = PHI->getParent();
4811 // Search for compare instructions which use the phi.
4812 for (auto *User : PHI->users()) {
4813 reuseTableCompare(User, PhiBlock, RangeCheckBranch, DV, ResultList);
4817 PHI->addIncoming(Result, LookupBB);
4821 Builder.CreateBr(CommonDest);
4823 // Remove the switch.
4824 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
4825 BasicBlock *Succ = SI->getSuccessor(i);
4827 if (Succ == SI->getDefaultDest())
4829 Succ->removePredecessor(SI->getParent());
4831 SI->eraseFromParent();
4835 ++NumLookupTablesHoles;
4839 bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
4840 BasicBlock *BB = SI->getParent();
4842 if (isValueEqualityComparison(SI)) {
4843 // If we only have one predecessor, and if it is a branch on this value,
4844 // see if that predecessor totally determines the outcome of this switch.
4845 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
4846 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
4847 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
4849 Value *Cond = SI->getCondition();
4850 if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
4851 if (SimplifySwitchOnSelect(SI, Select))
4852 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
4854 // If the block only contains the switch, see if we can fold the block
4855 // away into any preds.
4856 BasicBlock::iterator BBI = BB->begin();
4857 // Ignore dbg intrinsics.
4858 while (isa<DbgInfoIntrinsic>(BBI))
4861 if (FoldValueComparisonIntoPredecessors(SI, Builder))
4862 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
4865 // Try to transform the switch into an icmp and a branch.
4866 if (TurnSwitchRangeIntoICmp(SI, Builder))
4867 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
4869 // Remove unreachable cases.
4870 if (EliminateDeadSwitchCases(SI, AC, DL))
4871 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
4873 if (SwitchToSelect(SI, Builder, AC, DL))
4874 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
4876 if (ForwardSwitchConditionToPHI(SI))
4877 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
4879 if (SwitchToLookupTable(SI, Builder, DL, TTI))
4880 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
4885 bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
4886 BasicBlock *BB = IBI->getParent();
4887 bool Changed = false;
4889 // Eliminate redundant destinations.
4890 SmallPtrSet<Value *, 8> Succs;
4891 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
4892 BasicBlock *Dest = IBI->getDestination(i);
4893 if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) {
4894 Dest->removePredecessor(BB);
4895 IBI->removeDestination(i);
4901 if (IBI->getNumDestinations() == 0) {
4902 // If the indirectbr has no successors, change it to unreachable.
4903 new UnreachableInst(IBI->getContext(), IBI);
4904 EraseTerminatorInstAndDCECond(IBI);
4908 if (IBI->getNumDestinations() == 1) {
4909 // If the indirectbr has one successor, change it to a direct branch.
4910 BranchInst::Create(IBI->getDestination(0), IBI);
4911 EraseTerminatorInstAndDCECond(IBI);
4915 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
4916 if (SimplifyIndirectBrOnSelect(IBI, SI))
4917 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
4922 /// Given an block with only a single landing pad and a unconditional branch
4923 /// try to find another basic block which this one can be merged with. This
4924 /// handles cases where we have multiple invokes with unique landing pads, but
4925 /// a shared handler.
4927 /// We specifically choose to not worry about merging non-empty blocks
4928 /// here. That is a PRE/scheduling problem and is best solved elsewhere. In
4929 /// practice, the optimizer produces empty landing pad blocks quite frequently
4930 /// when dealing with exception dense code. (see: instcombine, gvn, if-else
4931 /// sinking in this file)
4933 /// This is primarily a code size optimization. We need to avoid performing
4934 /// any transform which might inhibit optimization (such as our ability to
4935 /// specialize a particular handler via tail commoning). We do this by not
4936 /// merging any blocks which require us to introduce a phi. Since the same
4937 /// values are flowing through both blocks, we don't loose any ability to
4938 /// specialize. If anything, we make such specialization more likely.
4940 /// TODO - This transformation could remove entries from a phi in the target
4941 /// block when the inputs in the phi are the same for the two blocks being
4942 /// merged. In some cases, this could result in removal of the PHI entirely.
4943 static bool TryToMergeLandingPad(LandingPadInst *LPad, BranchInst *BI,
4945 auto Succ = BB->getUniqueSuccessor();
4947 // If there's a phi in the successor block, we'd likely have to introduce
4948 // a phi into the merged landing pad block.
4949 if (isa<PHINode>(*Succ->begin()))
4952 for (BasicBlock *OtherPred : predecessors(Succ)) {
4953 if (BB == OtherPred)
4955 BasicBlock::iterator I = OtherPred->begin();
4956 LandingPadInst *LPad2 = dyn_cast<LandingPadInst>(I);
4957 if (!LPad2 || !LPad2->isIdenticalTo(LPad))
4959 for (++I; isa<DbgInfoIntrinsic>(I); ++I) {}
4960 BranchInst *BI2 = dyn_cast<BranchInst>(I);
4961 if (!BI2 || !BI2->isIdenticalTo(BI))
4964 // We've found an identical block. Update our predeccessors to take that
4965 // path instead and make ourselves dead.
4966 SmallSet<BasicBlock *, 16> Preds;
4967 Preds.insert(pred_begin(BB), pred_end(BB));
4968 for (BasicBlock *Pred : Preds) {
4969 InvokeInst *II = cast<InvokeInst>(Pred->getTerminator());
4970 assert(II->getNormalDest() != BB &&
4971 II->getUnwindDest() == BB && "unexpected successor");
4972 II->setUnwindDest(OtherPred);
4975 // The debug info in OtherPred doesn't cover the merged control flow that
4976 // used to go through BB. We need to delete it or update it.
4977 for (auto I = OtherPred->begin(), E = OtherPred->end();
4979 Instruction &Inst = *I; I++;
4980 if (isa<DbgInfoIntrinsic>(Inst))
4981 Inst.eraseFromParent();
4984 SmallSet<BasicBlock *, 16> Succs;
4985 Succs.insert(succ_begin(BB), succ_end(BB));
4986 for (BasicBlock *Succ : Succs) {
4987 Succ->removePredecessor(BB);
4990 IRBuilder<> Builder(BI);
4991 Builder.CreateUnreachable();
4992 BI->eraseFromParent();
4998 bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder){
4999 BasicBlock *BB = BI->getParent();
5001 if (SinkCommon && SinkThenElseCodeToEnd(BI))
5004 // If the Terminator is the only non-phi instruction, simplify the block.
5005 BasicBlock::iterator I = BB->getFirstNonPHIOrDbg()->getIterator();
5006 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
5007 TryToSimplifyUncondBranchFromEmptyBlock(BB))
5010 // If the only instruction in the block is a seteq/setne comparison
5011 // against a constant, try to simplify the block.
5012 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
5013 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
5014 for (++I; isa<DbgInfoIntrinsic>(I); ++I)
5016 if (I->isTerminator() &&
5017 TryToSimplifyUncondBranchWithICmpInIt(ICI, Builder, DL, TTI,
5018 BonusInstThreshold, AC))
5022 // See if we can merge an empty landing pad block with another which is
5024 if (LandingPadInst *LPad = dyn_cast<LandingPadInst>(I)) {
5025 for (++I; isa<DbgInfoIntrinsic>(I); ++I) {}
5026 if (I->isTerminator() &&
5027 TryToMergeLandingPad(LPad, BI, BB))
5031 // If this basic block is ONLY a compare and a branch, and if a predecessor
5032 // branches to us and our successor, fold the comparison into the
5033 // predecessor and use logical operations to update the incoming value
5034 // for PHI nodes in common successor.
5035 if (FoldBranchToCommonDest(BI, BonusInstThreshold))
5036 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5040 static BasicBlock *allPredecessorsComeFromSameSource(BasicBlock *BB) {
5041 BasicBlock *PredPred = nullptr;
5042 for (auto *P : predecessors(BB)) {
5043 BasicBlock *PPred = P->getSinglePredecessor();
5044 if (!PPred || (PredPred && PredPred != PPred))
5051 bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
5052 BasicBlock *BB = BI->getParent();
5054 // Conditional branch
5055 if (isValueEqualityComparison(BI)) {
5056 // If we only have one predecessor, and if it is a branch on this value,
5057 // see if that predecessor totally determines the outcome of this
5059 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
5060 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
5061 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5063 // This block must be empty, except for the setcond inst, if it exists.
5064 // Ignore dbg intrinsics.
5065 BasicBlock::iterator I = BB->begin();
5066 // Ignore dbg intrinsics.
5067 while (isa<DbgInfoIntrinsic>(I))
5070 if (FoldValueComparisonIntoPredecessors(BI, Builder))
5071 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5072 } else if (&*I == cast<Instruction>(BI->getCondition())){
5074 // Ignore dbg intrinsics.
5075 while (isa<DbgInfoIntrinsic>(I))
5077 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
5078 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5082 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
5083 if (SimplifyBranchOnICmpChain(BI, Builder, DL))
5086 // If this basic block is ONLY a compare and a branch, and if a predecessor
5087 // branches to us and one of our successors, fold the comparison into the
5088 // predecessor and use logical operations to pick the right destination.
5089 if (FoldBranchToCommonDest(BI, BonusInstThreshold))
5090 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5092 // We have a conditional branch to two blocks that are only reachable
5093 // from BI. We know that the condbr dominates the two blocks, so see if
5094 // there is any identical code in the "then" and "else" blocks. If so, we
5095 // can hoist it up to the branching block.
5096 if (BI->getSuccessor(0)->getSinglePredecessor()) {
5097 if (BI->getSuccessor(1)->getSinglePredecessor()) {
5098 if (HoistThenElseCodeToIf(BI, TTI))
5099 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5101 // If Successor #1 has multiple preds, we may be able to conditionally
5102 // execute Successor #0 if it branches to Successor #1.
5103 TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
5104 if (Succ0TI->getNumSuccessors() == 1 &&
5105 Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
5106 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), TTI))
5107 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5109 } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
5110 // If Successor #0 has multiple preds, we may be able to conditionally
5111 // execute Successor #1 if it branches to Successor #0.
5112 TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
5113 if (Succ1TI->getNumSuccessors() == 1 &&
5114 Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
5115 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), TTI))
5116 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5119 // If this is a branch on a phi node in the current block, thread control
5120 // through this block if any PHI node entries are constants.
5121 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
5122 if (PN->getParent() == BI->getParent())
5123 if (FoldCondBranchOnPHI(BI, DL))
5124 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5126 // Scan predecessor blocks for conditional branches.
5127 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
5128 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
5129 if (PBI != BI && PBI->isConditional())
5130 if (SimplifyCondBranchToCondBranch(PBI, BI, DL))
5131 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5133 // Look for diamond patterns.
5134 if (MergeCondStores)
5135 if (BasicBlock *PrevBB = allPredecessorsComeFromSameSource(BB))
5136 if (BranchInst *PBI = dyn_cast<BranchInst>(PrevBB->getTerminator()))
5137 if (PBI != BI && PBI->isConditional())
5138 if (mergeConditionalStores(PBI, BI))
5139 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5144 /// Check if passing a value to an instruction will cause undefined behavior.
5145 static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
5146 Constant *C = dyn_cast<Constant>(V);
5153 if (C->isNullValue()) {
5154 // Only look at the first use, avoid hurting compile time with long uselists
5155 User *Use = *I->user_begin();
5157 // Now make sure that there are no instructions in between that can alter
5158 // control flow (eg. calls)
5159 for (BasicBlock::iterator i = ++BasicBlock::iterator(I); &*i != Use; ++i)
5160 if (i == I->getParent()->end() || i->mayHaveSideEffects())
5163 // Look through GEPs. A load from a GEP derived from NULL is still undefined
5164 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
5165 if (GEP->getPointerOperand() == I)
5166 return passingValueIsAlwaysUndefined(V, GEP);
5168 // Look through bitcasts.
5169 if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
5170 return passingValueIsAlwaysUndefined(V, BC);
5172 // Load from null is undefined.
5173 if (LoadInst *LI = dyn_cast<LoadInst>(Use))
5174 if (!LI->isVolatile())
5175 return LI->getPointerAddressSpace() == 0;
5177 // Store to null is undefined.
5178 if (StoreInst *SI = dyn_cast<StoreInst>(Use))
5179 if (!SI->isVolatile())
5180 return SI->getPointerAddressSpace() == 0 && SI->getPointerOperand() == I;
5185 /// If BB has an incoming value that will always trigger undefined behavior
5186 /// (eg. null pointer dereference), remove the branch leading here.
5187 static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
5188 for (BasicBlock::iterator i = BB->begin();
5189 PHINode *PHI = dyn_cast<PHINode>(i); ++i)
5190 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
5191 if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) {
5192 TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator();
5193 IRBuilder<> Builder(T);
5194 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
5195 BB->removePredecessor(PHI->getIncomingBlock(i));
5196 // Turn uncoditional branches into unreachables and remove the dead
5197 // destination from conditional branches.
5198 if (BI->isUnconditional())
5199 Builder.CreateUnreachable();
5201 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) :
5202 BI->getSuccessor(0));
5203 BI->eraseFromParent();
5206 // TODO: SwitchInst.
5212 bool SimplifyCFGOpt::run(BasicBlock *BB) {
5213 bool Changed = false;
5215 assert(BB && BB->getParent() && "Block not embedded in function!");
5216 assert(BB->getTerminator() && "Degenerate basic block encountered!");
5218 // Remove basic blocks that have no predecessors (except the entry block)...
5219 // or that just have themself as a predecessor. These are unreachable.
5220 if ((pred_empty(BB) &&
5221 BB != &BB->getParent()->getEntryBlock()) ||
5222 BB->getSinglePredecessor() == BB) {
5223 DEBUG(dbgs() << "Removing BB: \n" << *BB);
5224 DeleteDeadBlock(BB);
5228 // Check to see if we can constant propagate this terminator instruction
5230 Changed |= ConstantFoldTerminator(BB, true);
5232 // Check for and eliminate duplicate PHI nodes in this block.
5233 Changed |= EliminateDuplicatePHINodes(BB);
5235 // Check for and remove branches that will always cause undefined behavior.
5236 Changed |= removeUndefIntroducingPredecessor(BB);
5238 // Merge basic blocks into their predecessor if there is only one distinct
5239 // pred, and if there is only one distinct successor of the predecessor, and
5240 // if there are no PHI nodes.
5242 if (MergeBlockIntoPredecessor(BB))
5245 IRBuilder<> Builder(BB);
5247 // If there is a trivial two-entry PHI node in this basic block, and we can
5248 // eliminate it, do so now.
5249 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
5250 if (PN->getNumIncomingValues() == 2)
5251 Changed |= FoldTwoEntryPHINode(PN, TTI, DL);
5253 Builder.SetInsertPoint(BB->getTerminator());
5254 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
5255 if (BI->isUnconditional()) {
5256 if (SimplifyUncondBranch(BI, Builder)) return true;
5258 if (SimplifyCondBranch(BI, Builder)) return true;
5260 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
5261 if (SimplifyReturn(RI, Builder)) return true;
5262 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
5263 if (SimplifyResume(RI, Builder)) return true;
5264 } else if (CleanupReturnInst *RI =
5265 dyn_cast<CleanupReturnInst>(BB->getTerminator())) {
5266 if (SimplifyCleanupReturn(RI)) return true;
5267 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
5268 if (SimplifySwitch(SI, Builder)) return true;
5269 } else if (UnreachableInst *UI =
5270 dyn_cast<UnreachableInst>(BB->getTerminator())) {
5271 if (SimplifyUnreachable(UI)) return true;
5272 } else if (IndirectBrInst *IBI =
5273 dyn_cast<IndirectBrInst>(BB->getTerminator())) {
5274 if (SimplifyIndirectBr(IBI)) return true;
5280 /// This function is used to do simplification of a CFG.
5281 /// For example, it adjusts branches to branches to eliminate the extra hop,
5282 /// eliminates unreachable basic blocks, and does other "peephole" optimization
5283 /// of the CFG. It returns true if a modification was made.
5285 bool llvm::SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
5286 unsigned BonusInstThreshold, AssumptionCache *AC) {
5287 return SimplifyCFGOpt(TTI, BB->getModule()->getDataLayout(),
5288 BonusInstThreshold, AC).run(BB);