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();