1 //===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // Peephole optimize the CFG. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/ADT/APInt.h" 15 #include "llvm/ADT/ArrayRef.h" 16 #include "llvm/ADT/DenseMap.h" 17 #include "llvm/ADT/Optional.h" 18 #include "llvm/ADT/SetOperations.h" 19 #include "llvm/ADT/SetVector.h" 20 #include "llvm/ADT/SmallPtrSet.h" 21 #include "llvm/ADT/SmallSet.h" 22 #include "llvm/ADT/SmallVector.h" 23 #include "llvm/ADT/Statistic.h" 24 #include "llvm/ADT/STLExtras.h" 25 #include "llvm/Analysis/AssumptionCache.h" 26 #include "llvm/Analysis/ConstantFolding.h" 27 #include "llvm/Analysis/EHPersonalities.h" 28 #include "llvm/Analysis/InstructionSimplify.h" 29 #include "llvm/Analysis/TargetTransformInfo.h" 30 #include "llvm/Analysis/ValueTracking.h" 31 #include "llvm/IR/BasicBlock.h" 32 #include "llvm/IR/CallSite.h" 33 #include "llvm/IR/CFG.h" 34 #include "llvm/IR/Constant.h" 35 #include "llvm/IR/ConstantRange.h" 36 #include "llvm/IR/Constants.h" 37 #include "llvm/IR/DataLayout.h" 38 #include "llvm/IR/DebugInfo.h" 39 #include "llvm/IR/DerivedTypes.h" 40 #include "llvm/IR/GlobalValue.h" 41 #include "llvm/IR/GlobalVariable.h" 42 #include "llvm/IR/IRBuilder.h" 43 #include "llvm/IR/InstrTypes.h" 44 #include "llvm/IR/Instruction.h" 45 #include "llvm/IR/Instructions.h" 46 #include "llvm/IR/IntrinsicInst.h" 47 #include "llvm/IR/Intrinsics.h" 48 #include "llvm/IR/LLVMContext.h" 49 #include "llvm/IR/MDBuilder.h" 50 #include "llvm/IR/Metadata.h" 51 #include "llvm/IR/Module.h" 52 #include "llvm/IR/NoFolder.h" 53 #include "llvm/IR/Operator.h" 54 #include "llvm/IR/PatternMatch.h" 55 #include "llvm/IR/Type.h" 56 #include "llvm/IR/User.h" 57 #include "llvm/IR/Value.h" 58 #include "llvm/IR/DebugInfo.h" 59 #include "llvm/Support/Casting.h" 60 #include "llvm/Support/CommandLine.h" 61 #include "llvm/Support/Debug.h" 62 #include "llvm/Support/ErrorHandling.h" 63 #include "llvm/Support/MathExtras.h" 64 #include "llvm/Support/raw_ostream.h" 65 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 66 #include "llvm/Transforms/Utils/Local.h" 67 #include "llvm/Transforms/Utils/ValueMapper.h" 68 #include <algorithm> 69 #include <cassert> 70 #include <climits> 71 #include <cstddef> 72 #include <cstdint> 73 #include <iterator> 74 #include <map> 75 #include <set> 76 #include <utility> 77 #include <vector> 78 79 using namespace llvm; 80 using namespace PatternMatch; 81 82 #define DEBUG_TYPE "simplifycfg" 83 84 // Chosen as 2 so as to be cheap, but still to have enough power to fold 85 // a select, so the "clamp" idiom (of a min followed by a max) will be caught. 86 // To catch this, we need to fold a compare and a select, hence '2' being the 87 // minimum reasonable default. 88 static cl::opt<unsigned> PHINodeFoldingThreshold( 89 "phi-node-folding-threshold", cl::Hidden, cl::init(2), 90 cl::desc( 91 "Control the amount of phi node folding to perform (default = 2)")); 92 93 static cl::opt<bool> DupRet( 94 "simplifycfg-dup-ret", cl::Hidden, cl::init(false), 95 cl::desc("Duplicate return instructions into unconditional branches")); 96 97 static cl::opt<bool> 98 SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true), 99 cl::desc("Sink common instructions down to the end block")); 100 101 static cl::opt<bool> HoistCondStores( 102 "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true), 103 cl::desc("Hoist conditional stores if an unconditional store precedes")); 104 105 static cl::opt<bool> MergeCondStores( 106 "simplifycfg-merge-cond-stores", cl::Hidden, cl::init(true), 107 cl::desc("Hoist conditional stores even if an unconditional store does not " 108 "precede - hoist multiple conditional stores into a single " 109 "predicated store")); 110 111 static cl::opt<bool> MergeCondStoresAggressively( 112 "simplifycfg-merge-cond-stores-aggressively", cl::Hidden, cl::init(false), 113 cl::desc("When merging conditional stores, do so even if the resultant " 114 "basic blocks are unlikely to be if-converted as a result")); 115 116 static cl::opt<bool> SpeculateOneExpensiveInst( 117 "speculate-one-expensive-inst", cl::Hidden, cl::init(true), 118 cl::desc("Allow exactly one expensive instruction to be speculatively " 119 "executed")); 120 121 static cl::opt<unsigned> MaxSpeculationDepth( 122 "max-speculation-depth", cl::Hidden, cl::init(10), 123 cl::desc("Limit maximum recursion depth when calculating costs of " 124 "speculatively executed instructions")); 125 126 STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps"); 127 STATISTIC(NumLinearMaps, 128 "Number of switch instructions turned into linear mapping"); 129 STATISTIC(NumLookupTables, 130 "Number of switch instructions turned into lookup tables"); 131 STATISTIC( 132 NumLookupTablesHoles, 133 "Number of switch instructions turned into lookup tables (holes checked)"); 134 STATISTIC(NumTableCmpReuses, "Number of reused switch table lookup compares"); 135 STATISTIC(NumSinkCommons, 136 "Number of common instructions sunk down to the end block"); 137 STATISTIC(NumSpeculations, "Number of speculative executed instructions"); 138 139 namespace { 140 141 // The first field contains the value that the switch produces when a certain 142 // case group is selected, and the second field is a vector containing the 143 // cases composing the case group. 144 typedef SmallVector<std::pair<Constant *, SmallVector<ConstantInt *, 4>>, 2> 145 SwitchCaseResultVectorTy; 146 // The first field contains the phi node that generates a result of the switch 147 // and the second field contains the value generated for a certain case in the 148 // switch for that PHI. 149 typedef SmallVector<std::pair<PHINode *, Constant *>, 4> SwitchCaseResultsTy; 150 151 /// ValueEqualityComparisonCase - Represents a case of a switch. 152 struct ValueEqualityComparisonCase { 153 ConstantInt *Value; 154 BasicBlock *Dest; 155 156 ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest) 157 : Value(Value), Dest(Dest) {} 158 159 bool operator<(ValueEqualityComparisonCase RHS) const { 160 // Comparing pointers is ok as we only rely on the order for uniquing. 161 return Value < RHS.Value; 162 } 163 164 bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; } 165 }; 166 167 class SimplifyCFGOpt { 168 const TargetTransformInfo &TTI; 169 const DataLayout &DL; 170 unsigned BonusInstThreshold; 171 AssumptionCache *AC; 172 SmallPtrSetImpl<BasicBlock *> *LoopHeaders; 173 // See comments in SimplifyCFGOpt::SimplifySwitch. 174 bool LateSimplifyCFG; 175 Value *isValueEqualityComparison(TerminatorInst *TI); 176 BasicBlock *GetValueEqualityComparisonCases( 177 TerminatorInst *TI, std::vector<ValueEqualityComparisonCase> &Cases); 178 bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI, 179 BasicBlock *Pred, 180 IRBuilder<> &Builder); 181 bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI, 182 IRBuilder<> &Builder); 183 184 bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder); 185 bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder); 186 bool SimplifySingleResume(ResumeInst *RI); 187 bool SimplifyCommonResume(ResumeInst *RI); 188 bool SimplifyCleanupReturn(CleanupReturnInst *RI); 189 bool SimplifyUnreachable(UnreachableInst *UI); 190 bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder); 191 bool SimplifyIndirectBr(IndirectBrInst *IBI); 192 bool SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder); 193 bool SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder); 194 195 public: 196 SimplifyCFGOpt(const TargetTransformInfo &TTI, const DataLayout &DL, 197 unsigned BonusInstThreshold, AssumptionCache *AC, 198 SmallPtrSetImpl<BasicBlock *> *LoopHeaders, 199 bool LateSimplifyCFG) 200 : TTI(TTI), DL(DL), BonusInstThreshold(BonusInstThreshold), AC(AC), 201 LoopHeaders(LoopHeaders), LateSimplifyCFG(LateSimplifyCFG) {} 202 203 bool run(BasicBlock *BB); 204 }; 205 206 } // end anonymous namespace 207 208 /// Return true if it is safe to merge these two 209 /// terminator instructions together. 210 static bool 211 SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2, 212 SmallSetVector<BasicBlock *, 4> *FailBlocks = nullptr) { 213 if (SI1 == SI2) 214 return false; // Can't merge with self! 215 216 // It is not safe to merge these two switch instructions if they have a common 217 // successor, and if that successor has a PHI node, and if *that* PHI node has 218 // conflicting incoming values from the two switch blocks. 219 BasicBlock *SI1BB = SI1->getParent(); 220 BasicBlock *SI2BB = SI2->getParent(); 221 222 SmallPtrSet<BasicBlock *, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB)); 223 bool Fail = false; 224 for (BasicBlock *Succ : successors(SI2BB)) 225 if (SI1Succs.count(Succ)) 226 for (BasicBlock::iterator BBI = Succ->begin(); isa<PHINode>(BBI); ++BBI) { 227 PHINode *PN = cast<PHINode>(BBI); 228 if (PN->getIncomingValueForBlock(SI1BB) != 229 PN->getIncomingValueForBlock(SI2BB)) { 230 if (FailBlocks) 231 FailBlocks->insert(Succ); 232 Fail = true; 233 } 234 } 235 236 return !Fail; 237 } 238 239 /// Return true if it is safe and profitable to merge these two terminator 240 /// instructions together, where SI1 is an unconditional branch. PhiNodes will 241 /// store all PHI nodes in common successors. 242 static bool 243 isProfitableToFoldUnconditional(BranchInst *SI1, BranchInst *SI2, 244 Instruction *Cond, 245 SmallVectorImpl<PHINode *> &PhiNodes) { 246 if (SI1 == SI2) 247 return false; // Can't merge with self! 248 assert(SI1->isUnconditional() && SI2->isConditional()); 249 250 // We fold the unconditional branch if we can easily update all PHI nodes in 251 // common successors: 252 // 1> We have a constant incoming value for the conditional branch; 253 // 2> We have "Cond" as the incoming value for the unconditional branch; 254 // 3> SI2->getCondition() and Cond have same operands. 255 CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition()); 256 if (!Ci2) 257 return false; 258 if (!(Cond->getOperand(0) == Ci2->getOperand(0) && 259 Cond->getOperand(1) == Ci2->getOperand(1)) && 260 !(Cond->getOperand(0) == Ci2->getOperand(1) && 261 Cond->getOperand(1) == Ci2->getOperand(0))) 262 return false; 263 264 BasicBlock *SI1BB = SI1->getParent(); 265 BasicBlock *SI2BB = SI2->getParent(); 266 SmallPtrSet<BasicBlock *, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB)); 267 for (BasicBlock *Succ : successors(SI2BB)) 268 if (SI1Succs.count(Succ)) 269 for (BasicBlock::iterator BBI = Succ->begin(); isa<PHINode>(BBI); ++BBI) { 270 PHINode *PN = cast<PHINode>(BBI); 271 if (PN->getIncomingValueForBlock(SI1BB) != Cond || 272 !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB))) 273 return false; 274 PhiNodes.push_back(PN); 275 } 276 return true; 277 } 278 279 /// Update PHI nodes in Succ to indicate that there will now be entries in it 280 /// from the 'NewPred' block. The values that will be flowing into the PHI nodes 281 /// will be the same as those coming in from ExistPred, an existing predecessor 282 /// of Succ. 283 static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred, 284 BasicBlock *ExistPred) { 285 if (!isa<PHINode>(Succ->begin())) 286 return; // Quick exit if nothing to do 287 288 PHINode *PN; 289 for (BasicBlock::iterator I = Succ->begin(); (PN = dyn_cast<PHINode>(I)); ++I) 290 PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred); 291 } 292 293 /// Compute an abstract "cost" of speculating the given instruction, 294 /// which is assumed to be safe to speculate. TCC_Free means cheap, 295 /// TCC_Basic means less cheap, and TCC_Expensive means prohibitively 296 /// expensive. 297 static unsigned ComputeSpeculationCost(const User *I, 298 const TargetTransformInfo &TTI) { 299 assert(isSafeToSpeculativelyExecute(I) && 300 "Instruction is not safe to speculatively execute!"); 301 return TTI.getUserCost(I); 302 } 303 304 /// If we have a merge point of an "if condition" as accepted above, 305 /// return true if the specified value dominates the block. We 306 /// don't handle the true generality of domination here, just a special case 307 /// which works well enough for us. 308 /// 309 /// If AggressiveInsts is non-null, and if V does not dominate BB, we check to 310 /// see if V (which must be an instruction) and its recursive operands 311 /// that do not dominate BB have a combined cost lower than CostRemaining and 312 /// are non-trapping. If both are true, the instruction is inserted into the 313 /// set and true is returned. 314 /// 315 /// The cost for most non-trapping instructions is defined as 1 except for 316 /// Select whose cost is 2. 317 /// 318 /// After this function returns, CostRemaining is decreased by the cost of 319 /// V plus its non-dominating operands. If that cost is greater than 320 /// CostRemaining, false is returned and CostRemaining is undefined. 321 static bool DominatesMergePoint(Value *V, BasicBlock *BB, 322 SmallPtrSetImpl<Instruction *> *AggressiveInsts, 323 unsigned &CostRemaining, 324 const TargetTransformInfo &TTI, 325 unsigned Depth = 0) { 326 // It is possible to hit a zero-cost cycle (phi/gep instructions for example), 327 // so limit the recursion depth. 328 // TODO: While this recursion limit does prevent pathological behavior, it 329 // would be better to track visited instructions to avoid cycles. 330 if (Depth == MaxSpeculationDepth) 331 return false; 332 333 Instruction *I = dyn_cast<Instruction>(V); 334 if (!I) { 335 // Non-instructions all dominate instructions, but not all constantexprs 336 // can be executed unconditionally. 337 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V)) 338 if (C->canTrap()) 339 return false; 340 return true; 341 } 342 BasicBlock *PBB = I->getParent(); 343 344 // We don't want to allow weird loops that might have the "if condition" in 345 // the bottom of this block. 346 if (PBB == BB) 347 return false; 348 349 // If this instruction is defined in a block that contains an unconditional 350 // branch to BB, then it must be in the 'conditional' part of the "if 351 // statement". If not, it definitely dominates the region. 352 BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator()); 353 if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB) 354 return true; 355 356 // If we aren't allowing aggressive promotion anymore, then don't consider 357 // instructions in the 'if region'. 358 if (!AggressiveInsts) 359 return false; 360 361 // If we have seen this instruction before, don't count it again. 362 if (AggressiveInsts->count(I)) 363 return true; 364 365 // Okay, it looks like the instruction IS in the "condition". Check to 366 // see if it's a cheap instruction to unconditionally compute, and if it 367 // only uses stuff defined outside of the condition. If so, hoist it out. 368 if (!isSafeToSpeculativelyExecute(I)) 369 return false; 370 371 unsigned Cost = ComputeSpeculationCost(I, TTI); 372 373 // Allow exactly one instruction to be speculated regardless of its cost 374 // (as long as it is safe to do so). 375 // This is intended to flatten the CFG even if the instruction is a division 376 // or other expensive operation. The speculation of an expensive instruction 377 // is expected to be undone in CodeGenPrepare if the speculation has not 378 // enabled further IR optimizations. 379 if (Cost > CostRemaining && 380 (!SpeculateOneExpensiveInst || !AggressiveInsts->empty() || Depth > 0)) 381 return false; 382 383 // Avoid unsigned wrap. 384 CostRemaining = (Cost > CostRemaining) ? 0 : CostRemaining - Cost; 385 386 // Okay, we can only really hoist these out if their operands do 387 // not take us over the cost threshold. 388 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) 389 if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining, TTI, 390 Depth + 1)) 391 return false; 392 // Okay, it's safe to do this! Remember this instruction. 393 AggressiveInsts->insert(I); 394 return true; 395 } 396 397 /// Extract ConstantInt from value, looking through IntToPtr 398 /// and PointerNullValue. Return NULL if value is not a constant int. 399 static ConstantInt *GetConstantInt(Value *V, const DataLayout &DL) { 400 // Normal constant int. 401 ConstantInt *CI = dyn_cast<ConstantInt>(V); 402 if (CI || !isa<Constant>(V) || !V->getType()->isPointerTy()) 403 return CI; 404 405 // This is some kind of pointer constant. Turn it into a pointer-sized 406 // ConstantInt if possible. 407 IntegerType *PtrTy = cast<IntegerType>(DL.getIntPtrType(V->getType())); 408 409 // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*). 410 if (isa<ConstantPointerNull>(V)) 411 return ConstantInt::get(PtrTy, 0); 412 413 // IntToPtr const int. 414 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) 415 if (CE->getOpcode() == Instruction::IntToPtr) 416 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) { 417 // The constant is very likely to have the right type already. 418 if (CI->getType() == PtrTy) 419 return CI; 420 else 421 return cast<ConstantInt>( 422 ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false)); 423 } 424 return nullptr; 425 } 426 427 namespace { 428 429 /// Given a chain of or (||) or and (&&) comparison of a value against a 430 /// constant, this will try to recover the information required for a switch 431 /// structure. 432 /// It will depth-first traverse the chain of comparison, seeking for patterns 433 /// like %a == 12 or %a < 4 and combine them to produce a set of integer 434 /// representing the different cases for the switch. 435 /// Note that if the chain is composed of '||' it will build the set of elements 436 /// that matches the comparisons (i.e. any of this value validate the chain) 437 /// while for a chain of '&&' it will build the set elements that make the test 438 /// fail. 439 struct ConstantComparesGatherer { 440 const DataLayout &DL; 441 Value *CompValue; /// Value found for the switch comparison 442 Value *Extra; /// Extra clause to be checked before the switch 443 SmallVector<ConstantInt *, 8> Vals; /// Set of integers to match in switch 444 unsigned UsedICmps; /// Number of comparisons matched in the and/or chain 445 446 /// Construct and compute the result for the comparison instruction Cond 447 ConstantComparesGatherer(Instruction *Cond, const DataLayout &DL) 448 : DL(DL), CompValue(nullptr), Extra(nullptr), UsedICmps(0) { 449 gather(Cond); 450 } 451 452 /// Prevent copy 453 ConstantComparesGatherer(const ConstantComparesGatherer &) = delete; 454 ConstantComparesGatherer & 455 operator=(const ConstantComparesGatherer &) = delete; 456 457 private: 458 /// Try to set the current value used for the comparison, it succeeds only if 459 /// it wasn't set before or if the new value is the same as the old one 460 bool setValueOnce(Value *NewVal) { 461 if (CompValue && CompValue != NewVal) 462 return false; 463 CompValue = NewVal; 464 return (CompValue != nullptr); 465 } 466 467 /// Try to match Instruction "I" as a comparison against a constant and 468 /// populates the array Vals with the set of values that match (or do not 469 /// match depending on isEQ). 470 /// Return false on failure. On success, the Value the comparison matched 471 /// against is placed in CompValue. 472 /// If CompValue is already set, the function is expected to fail if a match 473 /// is found but the value compared to is different. 474 bool matchInstruction(Instruction *I, bool isEQ) { 475 // If this is an icmp against a constant, handle this as one of the cases. 476 ICmpInst *ICI; 477 ConstantInt *C; 478 if (!((ICI = dyn_cast<ICmpInst>(I)) && 479 (C = GetConstantInt(I->getOperand(1), DL)))) { 480 return false; 481 } 482 483 Value *RHSVal; 484 const APInt *RHSC; 485 486 // Pattern match a special case 487 // (x & ~2^z) == y --> x == y || x == y|2^z 488 // This undoes a transformation done by instcombine to fuse 2 compares. 489 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE)) { 490 491 // It's a little bit hard to see why the following transformations are 492 // correct. Here is a CVC3 program to verify them for 64-bit values: 493 494 /* 495 ONE : BITVECTOR(64) = BVZEROEXTEND(0bin1, 63); 496 x : BITVECTOR(64); 497 y : BITVECTOR(64); 498 z : BITVECTOR(64); 499 mask : BITVECTOR(64) = BVSHL(ONE, z); 500 QUERY( (y & ~mask = y) => 501 ((x & ~mask = y) <=> (x = y OR x = (y | mask))) 502 ); 503 QUERY( (y | mask = y) => 504 ((x | mask = y) <=> (x = y OR x = (y & ~mask))) 505 ); 506 */ 507 508 // Please note that each pattern must be a dual implication (<--> or 509 // iff). One directional implication can create spurious matches. If the 510 // implication is only one-way, an unsatisfiable condition on the left 511 // side can imply a satisfiable condition on the right side. Dual 512 // implication ensures that satisfiable conditions are transformed to 513 // other satisfiable conditions and unsatisfiable conditions are 514 // transformed to other unsatisfiable conditions. 515 516 // Here is a concrete example of a unsatisfiable condition on the left 517 // implying a satisfiable condition on the right: 518 // 519 // mask = (1 << z) 520 // (x & ~mask) == y --> (x == y || x == (y | mask)) 521 // 522 // Substituting y = 3, z = 0 yields: 523 // (x & -2) == 3 --> (x == 3 || x == 2) 524 525 // Pattern match a special case: 526 /* 527 QUERY( (y & ~mask = y) => 528 ((x & ~mask = y) <=> (x = y OR x = (y | mask))) 529 ); 530 */ 531 if (match(ICI->getOperand(0), 532 m_And(m_Value(RHSVal), m_APInt(RHSC)))) { 533 APInt Mask = ~*RHSC; 534 if (Mask.isPowerOf2() && (C->getValue() & ~Mask) == C->getValue()) { 535 // If we already have a value for the switch, it has to match! 536 if (!setValueOnce(RHSVal)) 537 return false; 538 539 Vals.push_back(C); 540 Vals.push_back( 541 ConstantInt::get(C->getContext(), 542 C->getValue() | Mask)); 543 UsedICmps++; 544 return true; 545 } 546 } 547 548 // Pattern match a special case: 549 /* 550 QUERY( (y | mask = y) => 551 ((x | mask = y) <=> (x = y OR x = (y & ~mask))) 552 ); 553 */ 554 if (match(ICI->getOperand(0), 555 m_Or(m_Value(RHSVal), m_APInt(RHSC)))) { 556 APInt Mask = *RHSC; 557 if (Mask.isPowerOf2() && (C->getValue() | Mask) == C->getValue()) { 558 // If we already have a value for the switch, it has to match! 559 if (!setValueOnce(RHSVal)) 560 return false; 561 562 Vals.push_back(C); 563 Vals.push_back(ConstantInt::get(C->getContext(), 564 C->getValue() & ~Mask)); 565 UsedICmps++; 566 return true; 567 } 568 } 569 570 // If we already have a value for the switch, it has to match! 571 if (!setValueOnce(ICI->getOperand(0))) 572 return false; 573 574 UsedICmps++; 575 Vals.push_back(C); 576 return ICI->getOperand(0); 577 } 578 579 // If we have "x ult 3", for example, then we can add 0,1,2 to the set. 580 ConstantRange Span = ConstantRange::makeAllowedICmpRegion( 581 ICI->getPredicate(), C->getValue()); 582 583 // Shift the range if the compare is fed by an add. This is the range 584 // compare idiom as emitted by instcombine. 585 Value *CandidateVal = I->getOperand(0); 586 if (match(I->getOperand(0), m_Add(m_Value(RHSVal), m_APInt(RHSC)))) { 587 Span = Span.subtract(*RHSC); 588 CandidateVal = RHSVal; 589 } 590 591 // If this is an and/!= check, then we are looking to build the set of 592 // value that *don't* pass the and chain. I.e. to turn "x ugt 2" into 593 // x != 0 && x != 1. 594 if (!isEQ) 595 Span = Span.inverse(); 596 597 // If there are a ton of values, we don't want to make a ginormous switch. 598 if (Span.getSetSize().ugt(8) || Span.isEmptySet()) { 599 return false; 600 } 601 602 // If we already have a value for the switch, it has to match! 603 if (!setValueOnce(CandidateVal)) 604 return false; 605 606 // Add all values from the range to the set 607 for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp) 608 Vals.push_back(ConstantInt::get(I->getContext(), Tmp)); 609 610 UsedICmps++; 611 return true; 612 } 613 614 /// Given a potentially 'or'd or 'and'd together collection of icmp 615 /// eq/ne/lt/gt instructions that compare a value against a constant, extract 616 /// the value being compared, and stick the list constants into the Vals 617 /// vector. 618 /// One "Extra" case is allowed to differ from the other. 619 void gather(Value *V) { 620 Instruction *I = dyn_cast<Instruction>(V); 621 bool isEQ = (I->getOpcode() == Instruction::Or); 622 623 // Keep a stack (SmallVector for efficiency) for depth-first traversal 624 SmallVector<Value *, 8> DFT; 625 SmallPtrSet<Value *, 8> Visited; 626 627 // Initialize 628 Visited.insert(V); 629 DFT.push_back(V); 630 631 while (!DFT.empty()) { 632 V = DFT.pop_back_val(); 633 634 if (Instruction *I = dyn_cast<Instruction>(V)) { 635 // If it is a || (or && depending on isEQ), process the operands. 636 if (I->getOpcode() == (isEQ ? Instruction::Or : Instruction::And)) { 637 if (Visited.insert(I->getOperand(1)).second) 638 DFT.push_back(I->getOperand(1)); 639 if (Visited.insert(I->getOperand(0)).second) 640 DFT.push_back(I->getOperand(0)); 641 continue; 642 } 643 644 // Try to match the current instruction 645 if (matchInstruction(I, isEQ)) 646 // Match succeed, continue the loop 647 continue; 648 } 649 650 // One element of the sequence of || (or &&) could not be match as a 651 // comparison against the same value as the others. 652 // We allow only one "Extra" case to be checked before the switch 653 if (!Extra) { 654 Extra = V; 655 continue; 656 } 657 // Failed to parse a proper sequence, abort now 658 CompValue = nullptr; 659 break; 660 } 661 } 662 }; 663 664 } // end anonymous namespace 665 666 static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) { 667 Instruction *Cond = nullptr; 668 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { 669 Cond = dyn_cast<Instruction>(SI->getCondition()); 670 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { 671 if (BI->isConditional()) 672 Cond = dyn_cast<Instruction>(BI->getCondition()); 673 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) { 674 Cond = dyn_cast<Instruction>(IBI->getAddress()); 675 } 676 677 TI->eraseFromParent(); 678 if (Cond) 679 RecursivelyDeleteTriviallyDeadInstructions(Cond); 680 } 681 682 /// Return true if the specified terminator checks 683 /// to see if a value is equal to constant integer value. 684 Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) { 685 Value *CV = nullptr; 686 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { 687 // Do not permit merging of large switch instructions into their 688 // predecessors unless there is only one predecessor. 689 if (SI->getNumSuccessors() * std::distance(pred_begin(SI->getParent()), 690 pred_end(SI->getParent())) <= 691 128) 692 CV = SI->getCondition(); 693 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) 694 if (BI->isConditional() && BI->getCondition()->hasOneUse()) 695 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) { 696 if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL)) 697 CV = ICI->getOperand(0); 698 } 699 700 // Unwrap any lossless ptrtoint cast. 701 if (CV) { 702 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) { 703 Value *Ptr = PTII->getPointerOperand(); 704 if (PTII->getType() == DL.getIntPtrType(Ptr->getType())) 705 CV = Ptr; 706 } 707 } 708 return CV; 709 } 710 711 /// Given a value comparison instruction, 712 /// decode all of the 'cases' that it represents and return the 'default' block. 713 BasicBlock *SimplifyCFGOpt::GetValueEqualityComparisonCases( 714 TerminatorInst *TI, std::vector<ValueEqualityComparisonCase> &Cases) { 715 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { 716 Cases.reserve(SI->getNumCases()); 717 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; 718 ++i) 719 Cases.push_back( 720 ValueEqualityComparisonCase(i.getCaseValue(), i.getCaseSuccessor())); 721 return SI->getDefaultDest(); 722 } 723 724 BranchInst *BI = cast<BranchInst>(TI); 725 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition()); 726 BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE); 727 Cases.push_back(ValueEqualityComparisonCase( 728 GetConstantInt(ICI->getOperand(1), DL), Succ)); 729 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ); 730 } 731 732 /// Given a vector of bb/value pairs, remove any entries 733 /// in the list that match the specified block. 734 static void 735 EliminateBlockCases(BasicBlock *BB, 736 std::vector<ValueEqualityComparisonCase> &Cases) { 737 Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end()); 738 } 739 740 /// Return true if there are any keys in C1 that exist in C2 as well. 741 static bool ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1, 742 std::vector<ValueEqualityComparisonCase> &C2) { 743 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2; 744 745 // Make V1 be smaller than V2. 746 if (V1->size() > V2->size()) 747 std::swap(V1, V2); 748 749 if (V1->empty()) 750 return false; 751 if (V1->size() == 1) { 752 // Just scan V2. 753 ConstantInt *TheVal = (*V1)[0].Value; 754 for (unsigned i = 0, e = V2->size(); i != e; ++i) 755 if (TheVal == (*V2)[i].Value) 756 return true; 757 } 758 759 // Otherwise, just sort both lists and compare element by element. 760 array_pod_sort(V1->begin(), V1->end()); 761 array_pod_sort(V2->begin(), V2->end()); 762 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size(); 763 while (i1 != e1 && i2 != e2) { 764 if ((*V1)[i1].Value == (*V2)[i2].Value) 765 return true; 766 if ((*V1)[i1].Value < (*V2)[i2].Value) 767 ++i1; 768 else 769 ++i2; 770 } 771 return false; 772 } 773 774 /// If TI is known to be a terminator instruction and its block is known to 775 /// only have a single predecessor block, check to see if that predecessor is 776 /// also a value comparison with the same value, and if that comparison 777 /// determines the outcome of this comparison. If so, simplify TI. This does a 778 /// very limited form of jump threading. 779 bool SimplifyCFGOpt::SimplifyEqualityComparisonWithOnlyPredecessor( 780 TerminatorInst *TI, BasicBlock *Pred, IRBuilder<> &Builder) { 781 Value *PredVal = isValueEqualityComparison(Pred->getTerminator()); 782 if (!PredVal) 783 return false; // Not a value comparison in predecessor. 784 785 Value *ThisVal = isValueEqualityComparison(TI); 786 assert(ThisVal && "This isn't a value comparison!!"); 787 if (ThisVal != PredVal) 788 return false; // Different predicates. 789 790 // TODO: Preserve branch weight metadata, similarly to how 791 // FoldValueComparisonIntoPredecessors preserves it. 792 793 // Find out information about when control will move from Pred to TI's block. 794 std::vector<ValueEqualityComparisonCase> PredCases; 795 BasicBlock *PredDef = 796 GetValueEqualityComparisonCases(Pred->getTerminator(), PredCases); 797 EliminateBlockCases(PredDef, PredCases); // Remove default from cases. 798 799 // Find information about how control leaves this block. 800 std::vector<ValueEqualityComparisonCase> ThisCases; 801 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases); 802 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases. 803 804 // If TI's block is the default block from Pred's comparison, potentially 805 // simplify TI based on this knowledge. 806 if (PredDef == TI->getParent()) { 807 // If we are here, we know that the value is none of those cases listed in 808 // PredCases. If there are any cases in ThisCases that are in PredCases, we 809 // can simplify TI. 810 if (!ValuesOverlap(PredCases, ThisCases)) 811 return false; 812 813 if (isa<BranchInst>(TI)) { 814 // Okay, one of the successors of this condbr is dead. Convert it to a 815 // uncond br. 816 assert(ThisCases.size() == 1 && "Branch can only have one case!"); 817 // Insert the new branch. 818 Instruction *NI = Builder.CreateBr(ThisDef); 819 (void)NI; 820 821 // Remove PHI node entries for the dead edge. 822 ThisCases[0].Dest->removePredecessor(TI->getParent()); 823 824 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator() 825 << "Through successor TI: " << *TI << "Leaving: " << *NI 826 << "\n"); 827 828 EraseTerminatorInstAndDCECond(TI); 829 return true; 830 } 831 832 SwitchInst *SI = cast<SwitchInst>(TI); 833 // Okay, TI has cases that are statically dead, prune them away. 834 SmallPtrSet<Constant *, 16> DeadCases; 835 for (unsigned i = 0, e = PredCases.size(); i != e; ++i) 836 DeadCases.insert(PredCases[i].Value); 837 838 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator() 839 << "Through successor TI: " << *TI); 840 841 // Collect branch weights into a vector. 842 SmallVector<uint32_t, 8> Weights; 843 MDNode *MD = SI->getMetadata(LLVMContext::MD_prof); 844 bool HasWeight = MD && (MD->getNumOperands() == 2 + SI->getNumCases()); 845 if (HasWeight) 846 for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e; 847 ++MD_i) { 848 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(MD_i)); 849 Weights.push_back(CI->getValue().getZExtValue()); 850 } 851 for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) { 852 --i; 853 if (DeadCases.count(i.getCaseValue())) { 854 if (HasWeight) { 855 std::swap(Weights[i.getCaseIndex() + 1], Weights.back()); 856 Weights.pop_back(); 857 } 858 i.getCaseSuccessor()->removePredecessor(TI->getParent()); 859 SI->removeCase(i); 860 } 861 } 862 if (HasWeight && Weights.size() >= 2) 863 SI->setMetadata(LLVMContext::MD_prof, 864 MDBuilder(SI->getParent()->getContext()) 865 .createBranchWeights(Weights)); 866 867 DEBUG(dbgs() << "Leaving: " << *TI << "\n"); 868 return true; 869 } 870 871 // Otherwise, TI's block must correspond to some matched value. Find out 872 // which value (or set of values) this is. 873 ConstantInt *TIV = nullptr; 874 BasicBlock *TIBB = TI->getParent(); 875 for (unsigned i = 0, e = PredCases.size(); i != e; ++i) 876 if (PredCases[i].Dest == TIBB) { 877 if (TIV) 878 return false; // Cannot handle multiple values coming to this block. 879 TIV = PredCases[i].Value; 880 } 881 assert(TIV && "No edge from pred to succ?"); 882 883 // Okay, we found the one constant that our value can be if we get into TI's 884 // BB. Find out which successor will unconditionally be branched to. 885 BasicBlock *TheRealDest = nullptr; 886 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i) 887 if (ThisCases[i].Value == TIV) { 888 TheRealDest = ThisCases[i].Dest; 889 break; 890 } 891 892 // If not handled by any explicit cases, it is handled by the default case. 893 if (!TheRealDest) 894 TheRealDest = ThisDef; 895 896 // Remove PHI node entries for dead edges. 897 BasicBlock *CheckEdge = TheRealDest; 898 for (BasicBlock *Succ : successors(TIBB)) 899 if (Succ != CheckEdge) 900 Succ->removePredecessor(TIBB); 901 else 902 CheckEdge = nullptr; 903 904 // Insert the new branch. 905 Instruction *NI = Builder.CreateBr(TheRealDest); 906 (void)NI; 907 908 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator() 909 << "Through successor TI: " << *TI << "Leaving: " << *NI 910 << "\n"); 911 912 EraseTerminatorInstAndDCECond(TI); 913 return true; 914 } 915 916 namespace { 917 918 /// This class implements a stable ordering of constant 919 /// integers that does not depend on their address. This is important for 920 /// applications that sort ConstantInt's to ensure uniqueness. 921 struct ConstantIntOrdering { 922 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const { 923 return LHS->getValue().ult(RHS->getValue()); 924 } 925 }; 926 927 } // end anonymous namespace 928 929 static int ConstantIntSortPredicate(ConstantInt *const *P1, 930 ConstantInt *const *P2) { 931 const ConstantInt *LHS = *P1; 932 const ConstantInt *RHS = *P2; 933 if (LHS == RHS) 934 return 0; 935 return LHS->getValue().ult(RHS->getValue()) ? 1 : -1; 936 } 937 938 static inline bool HasBranchWeights(const Instruction *I) { 939 MDNode *ProfMD = I->getMetadata(LLVMContext::MD_prof); 940 if (ProfMD && ProfMD->getOperand(0)) 941 if (MDString *MDS = dyn_cast<MDString>(ProfMD->getOperand(0))) 942 return MDS->getString().equals("branch_weights"); 943 944 return false; 945 } 946 947 /// Get Weights of a given TerminatorInst, the default weight is at the front 948 /// of the vector. If TI is a conditional eq, we need to swap the branch-weight 949 /// metadata. 950 static void GetBranchWeights(TerminatorInst *TI, 951 SmallVectorImpl<uint64_t> &Weights) { 952 MDNode *MD = TI->getMetadata(LLVMContext::MD_prof); 953 assert(MD); 954 for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) { 955 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(i)); 956 Weights.push_back(CI->getValue().getZExtValue()); 957 } 958 959 // If TI is a conditional eq, the default case is the false case, 960 // and the corresponding branch-weight data is at index 2. We swap the 961 // default weight to be the first entry. 962 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { 963 assert(Weights.size() == 2); 964 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition()); 965 if (ICI->getPredicate() == ICmpInst::ICMP_EQ) 966 std::swap(Weights.front(), Weights.back()); 967 } 968 } 969 970 /// Keep halving the weights until all can fit in uint32_t. 971 static void FitWeights(MutableArrayRef<uint64_t> Weights) { 972 uint64_t Max = *std::max_element(Weights.begin(), Weights.end()); 973 if (Max > UINT_MAX) { 974 unsigned Offset = 32 - countLeadingZeros(Max); 975 for (uint64_t &I : Weights) 976 I >>= Offset; 977 } 978 } 979 980 /// The specified terminator is a value equality comparison instruction 981 /// (either a switch or a branch on "X == c"). 982 /// See if any of the predecessors of the terminator block are value comparisons 983 /// on the same value. If so, and if safe to do so, fold them together. 984 bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI, 985 IRBuilder<> &Builder) { 986 BasicBlock *BB = TI->getParent(); 987 Value *CV = isValueEqualityComparison(TI); // CondVal 988 assert(CV && "Not a comparison?"); 989 bool Changed = false; 990 991 SmallVector<BasicBlock *, 16> Preds(pred_begin(BB), pred_end(BB)); 992 while (!Preds.empty()) { 993 BasicBlock *Pred = Preds.pop_back_val(); 994 995 // See if the predecessor is a comparison with the same value. 996 TerminatorInst *PTI = Pred->getTerminator(); 997 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal 998 999 if (PCV == CV && TI != PTI) { 1000 SmallSetVector<BasicBlock*, 4> FailBlocks; 1001 if (!SafeToMergeTerminators(TI, PTI, &FailBlocks)) { 1002 for (auto *Succ : FailBlocks) { 1003 if (!SplitBlockPredecessors(Succ, TI->getParent(), ".fold.split")) 1004 return false; 1005 } 1006 } 1007 1008 // Figure out which 'cases' to copy from SI to PSI. 1009 std::vector<ValueEqualityComparisonCase> BBCases; 1010 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases); 1011 1012 std::vector<ValueEqualityComparisonCase> PredCases; 1013 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases); 1014 1015 // Based on whether the default edge from PTI goes to BB or not, fill in 1016 // PredCases and PredDefault with the new switch cases we would like to 1017 // build. 1018 SmallVector<BasicBlock *, 8> NewSuccessors; 1019 1020 // Update the branch weight metadata along the way 1021 SmallVector<uint64_t, 8> Weights; 1022 bool PredHasWeights = HasBranchWeights(PTI); 1023 bool SuccHasWeights = HasBranchWeights(TI); 1024 1025 if (PredHasWeights) { 1026 GetBranchWeights(PTI, Weights); 1027 // branch-weight metadata is inconsistent here. 1028 if (Weights.size() != 1 + PredCases.size()) 1029 PredHasWeights = SuccHasWeights = false; 1030 } else if (SuccHasWeights) 1031 // If there are no predecessor weights but there are successor weights, 1032 // populate Weights with 1, which will later be scaled to the sum of 1033 // successor's weights 1034 Weights.assign(1 + PredCases.size(), 1); 1035 1036 SmallVector<uint64_t, 8> SuccWeights; 1037 if (SuccHasWeights) { 1038 GetBranchWeights(TI, SuccWeights); 1039 // branch-weight metadata is inconsistent here. 1040 if (SuccWeights.size() != 1 + BBCases.size()) 1041 PredHasWeights = SuccHasWeights = false; 1042 } else if (PredHasWeights) 1043 SuccWeights.assign(1 + BBCases.size(), 1); 1044 1045 if (PredDefault == BB) { 1046 // If this is the default destination from PTI, only the edges in TI 1047 // that don't occur in PTI, or that branch to BB will be activated. 1048 std::set<ConstantInt *, ConstantIntOrdering> PTIHandled; 1049 for (unsigned i = 0, e = PredCases.size(); i != e; ++i) 1050 if (PredCases[i].Dest != BB) 1051 PTIHandled.insert(PredCases[i].Value); 1052 else { 1053 // The default destination is BB, we don't need explicit targets. 1054 std::swap(PredCases[i], PredCases.back()); 1055 1056 if (PredHasWeights || SuccHasWeights) { 1057 // Increase weight for the default case. 1058 Weights[0] += Weights[i + 1]; 1059 std::swap(Weights[i + 1], Weights.back()); 1060 Weights.pop_back(); 1061 } 1062 1063 PredCases.pop_back(); 1064 --i; 1065 --e; 1066 } 1067 1068 // Reconstruct the new switch statement we will be building. 1069 if (PredDefault != BBDefault) { 1070 PredDefault->removePredecessor(Pred); 1071 PredDefault = BBDefault; 1072 NewSuccessors.push_back(BBDefault); 1073 } 1074 1075 unsigned CasesFromPred = Weights.size(); 1076 uint64_t ValidTotalSuccWeight = 0; 1077 for (unsigned i = 0, e = BBCases.size(); i != e; ++i) 1078 if (!PTIHandled.count(BBCases[i].Value) && 1079 BBCases[i].Dest != BBDefault) { 1080 PredCases.push_back(BBCases[i]); 1081 NewSuccessors.push_back(BBCases[i].Dest); 1082 if (SuccHasWeights || PredHasWeights) { 1083 // The default weight is at index 0, so weight for the ith case 1084 // should be at index i+1. Scale the cases from successor by 1085 // PredDefaultWeight (Weights[0]). 1086 Weights.push_back(Weights[0] * SuccWeights[i + 1]); 1087 ValidTotalSuccWeight += SuccWeights[i + 1]; 1088 } 1089 } 1090 1091 if (SuccHasWeights || PredHasWeights) { 1092 ValidTotalSuccWeight += SuccWeights[0]; 1093 // Scale the cases from predecessor by ValidTotalSuccWeight. 1094 for (unsigned i = 1; i < CasesFromPred; ++i) 1095 Weights[i] *= ValidTotalSuccWeight; 1096 // Scale the default weight by SuccDefaultWeight (SuccWeights[0]). 1097 Weights[0] *= SuccWeights[0]; 1098 } 1099 } else { 1100 // If this is not the default destination from PSI, only the edges 1101 // in SI that occur in PSI with a destination of BB will be 1102 // activated. 1103 std::set<ConstantInt *, ConstantIntOrdering> PTIHandled; 1104 std::map<ConstantInt *, uint64_t> WeightsForHandled; 1105 for (unsigned i = 0, e = PredCases.size(); i != e; ++i) 1106 if (PredCases[i].Dest == BB) { 1107 PTIHandled.insert(PredCases[i].Value); 1108 1109 if (PredHasWeights || SuccHasWeights) { 1110 WeightsForHandled[PredCases[i].Value] = Weights[i + 1]; 1111 std::swap(Weights[i + 1], Weights.back()); 1112 Weights.pop_back(); 1113 } 1114 1115 std::swap(PredCases[i], PredCases.back()); 1116 PredCases.pop_back(); 1117 --i; 1118 --e; 1119 } 1120 1121 // Okay, now we know which constants were sent to BB from the 1122 // predecessor. Figure out where they will all go now. 1123 for (unsigned i = 0, e = BBCases.size(); i != e; ++i) 1124 if (PTIHandled.count(BBCases[i].Value)) { 1125 // If this is one we are capable of getting... 1126 if (PredHasWeights || SuccHasWeights) 1127 Weights.push_back(WeightsForHandled[BBCases[i].Value]); 1128 PredCases.push_back(BBCases[i]); 1129 NewSuccessors.push_back(BBCases[i].Dest); 1130 PTIHandled.erase( 1131 BBCases[i].Value); // This constant is taken care of 1132 } 1133 1134 // If there are any constants vectored to BB that TI doesn't handle, 1135 // they must go to the default destination of TI. 1136 for (ConstantInt *I : PTIHandled) { 1137 if (PredHasWeights || SuccHasWeights) 1138 Weights.push_back(WeightsForHandled[I]); 1139 PredCases.push_back(ValueEqualityComparisonCase(I, BBDefault)); 1140 NewSuccessors.push_back(BBDefault); 1141 } 1142 } 1143 1144 // Okay, at this point, we know which new successor Pred will get. Make 1145 // sure we update the number of entries in the PHI nodes for these 1146 // successors. 1147 for (BasicBlock *NewSuccessor : NewSuccessors) 1148 AddPredecessorToBlock(NewSuccessor, Pred, BB); 1149 1150 Builder.SetInsertPoint(PTI); 1151 // Convert pointer to int before we switch. 1152 if (CV->getType()->isPointerTy()) { 1153 CV = Builder.CreatePtrToInt(CV, DL.getIntPtrType(CV->getType()), 1154 "magicptr"); 1155 } 1156 1157 // Now that the successors are updated, create the new Switch instruction. 1158 SwitchInst *NewSI = 1159 Builder.CreateSwitch(CV, PredDefault, PredCases.size()); 1160 NewSI->setDebugLoc(PTI->getDebugLoc()); 1161 for (ValueEqualityComparisonCase &V : PredCases) 1162 NewSI->addCase(V.Value, V.Dest); 1163 1164 if (PredHasWeights || SuccHasWeights) { 1165 // Halve the weights if any of them cannot fit in an uint32_t 1166 FitWeights(Weights); 1167 1168 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end()); 1169 1170 NewSI->setMetadata( 1171 LLVMContext::MD_prof, 1172 MDBuilder(BB->getContext()).createBranchWeights(MDWeights)); 1173 } 1174 1175 EraseTerminatorInstAndDCECond(PTI); 1176 1177 // Okay, last check. If BB is still a successor of PSI, then we must 1178 // have an infinite loop case. If so, add an infinitely looping block 1179 // to handle the case to preserve the behavior of the code. 1180 BasicBlock *InfLoopBlock = nullptr; 1181 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i) 1182 if (NewSI->getSuccessor(i) == BB) { 1183 if (!InfLoopBlock) { 1184 // Insert it at the end of the function, because it's either code, 1185 // or it won't matter if it's hot. :) 1186 InfLoopBlock = BasicBlock::Create(BB->getContext(), "infloop", 1187 BB->getParent()); 1188 BranchInst::Create(InfLoopBlock, InfLoopBlock); 1189 } 1190 NewSI->setSuccessor(i, InfLoopBlock); 1191 } 1192 1193 Changed = true; 1194 } 1195 } 1196 return Changed; 1197 } 1198 1199 // If we would need to insert a select that uses the value of this invoke 1200 // (comments in HoistThenElseCodeToIf explain why we would need to do this), we 1201 // can't hoist the invoke, as there is nowhere to put the select in this case. 1202 static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2, 1203 Instruction *I1, Instruction *I2) { 1204 for (BasicBlock *Succ : successors(BB1)) { 1205 PHINode *PN; 1206 for (BasicBlock::iterator BBI = Succ->begin(); 1207 (PN = dyn_cast<PHINode>(BBI)); ++BBI) { 1208 Value *BB1V = PN->getIncomingValueForBlock(BB1); 1209 Value *BB2V = PN->getIncomingValueForBlock(BB2); 1210 if (BB1V != BB2V && (BB1V == I1 || BB2V == I2)) { 1211 return false; 1212 } 1213 } 1214 } 1215 return true; 1216 } 1217 1218 static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I); 1219 1220 /// Given a conditional branch that goes to BB1 and BB2, hoist any common code 1221 /// in the two blocks up into the branch block. The caller of this function 1222 /// guarantees that BI's block dominates BB1 and BB2. 1223 static bool HoistThenElseCodeToIf(BranchInst *BI, 1224 const TargetTransformInfo &TTI) { 1225 // This does very trivial matching, with limited scanning, to find identical 1226 // instructions in the two blocks. In particular, we don't want to get into 1227 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As 1228 // such, we currently just scan for obviously identical instructions in an 1229 // identical order. 1230 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination. 1231 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination 1232 1233 BasicBlock::iterator BB1_Itr = BB1->begin(); 1234 BasicBlock::iterator BB2_Itr = BB2->begin(); 1235 1236 Instruction *I1 = &*BB1_Itr++, *I2 = &*BB2_Itr++; 1237 // Skip debug info if it is not identical. 1238 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1); 1239 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2); 1240 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) { 1241 while (isa<DbgInfoIntrinsic>(I1)) 1242 I1 = &*BB1_Itr++; 1243 while (isa<DbgInfoIntrinsic>(I2)) 1244 I2 = &*BB2_Itr++; 1245 } 1246 if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) || 1247 (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))) 1248 return false; 1249 1250 BasicBlock *BIParent = BI->getParent(); 1251 1252 bool Changed = false; 1253 do { 1254 // If we are hoisting the terminator instruction, don't move one (making a 1255 // broken BB), instead clone it, and remove BI. 1256 if (isa<TerminatorInst>(I1)) 1257 goto HoistTerminator; 1258 1259 if (!TTI.isProfitableToHoist(I1) || !TTI.isProfitableToHoist(I2)) 1260 return Changed; 1261 1262 // For a normal instruction, we just move one to right before the branch, 1263 // then replace all uses of the other with the first. Finally, we remove 1264 // the now redundant second instruction. 1265 BIParent->getInstList().splice(BI->getIterator(), BB1->getInstList(), I1); 1266 if (!I2->use_empty()) 1267 I2->replaceAllUsesWith(I1); 1268 I1->andIRFlags(I2); 1269 unsigned KnownIDs[] = {LLVMContext::MD_tbaa, 1270 LLVMContext::MD_range, 1271 LLVMContext::MD_fpmath, 1272 LLVMContext::MD_invariant_load, 1273 LLVMContext::MD_nonnull, 1274 LLVMContext::MD_invariant_group, 1275 LLVMContext::MD_align, 1276 LLVMContext::MD_dereferenceable, 1277 LLVMContext::MD_dereferenceable_or_null, 1278 LLVMContext::MD_mem_parallel_loop_access}; 1279 combineMetadata(I1, I2, KnownIDs); 1280 1281 // I1 and I2 are being combined into a single instruction. Its debug 1282 // location is the merged locations of the original instructions. 1283 if (!isa<CallInst>(I1)) 1284 I1->setDebugLoc( 1285 DILocation::getMergedLocation(I1->getDebugLoc(), I2->getDebugLoc())); 1286 1287 I2->eraseFromParent(); 1288 Changed = true; 1289 1290 I1 = &*BB1_Itr++; 1291 I2 = &*BB2_Itr++; 1292 // Skip debug info if it is not identical. 1293 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1); 1294 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2); 1295 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) { 1296 while (isa<DbgInfoIntrinsic>(I1)) 1297 I1 = &*BB1_Itr++; 1298 while (isa<DbgInfoIntrinsic>(I2)) 1299 I2 = &*BB2_Itr++; 1300 } 1301 } while (I1->isIdenticalToWhenDefined(I2)); 1302 1303 return true; 1304 1305 HoistTerminator: 1306 // It may not be possible to hoist an invoke. 1307 if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)) 1308 return Changed; 1309 1310 for (BasicBlock *Succ : successors(BB1)) { 1311 PHINode *PN; 1312 for (BasicBlock::iterator BBI = Succ->begin(); 1313 (PN = dyn_cast<PHINode>(BBI)); ++BBI) { 1314 Value *BB1V = PN->getIncomingValueForBlock(BB1); 1315 Value *BB2V = PN->getIncomingValueForBlock(BB2); 1316 if (BB1V == BB2V) 1317 continue; 1318 1319 // Check for passingValueIsAlwaysUndefined here because we would rather 1320 // eliminate undefined control flow then converting it to a select. 1321 if (passingValueIsAlwaysUndefined(BB1V, PN) || 1322 passingValueIsAlwaysUndefined(BB2V, PN)) 1323 return Changed; 1324 1325 if (isa<ConstantExpr>(BB1V) && !isSafeToSpeculativelyExecute(BB1V)) 1326 return Changed; 1327 if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V)) 1328 return Changed; 1329 } 1330 } 1331 1332 // Okay, it is safe to hoist the terminator. 1333 Instruction *NT = I1->clone(); 1334 BIParent->getInstList().insert(BI->getIterator(), NT); 1335 if (!NT->getType()->isVoidTy()) { 1336 I1->replaceAllUsesWith(NT); 1337 I2->replaceAllUsesWith(NT); 1338 NT->takeName(I1); 1339 } 1340 1341 IRBuilder<NoFolder> Builder(NT); 1342 // Hoisting one of the terminators from our successor is a great thing. 1343 // Unfortunately, the successors of the if/else blocks may have PHI nodes in 1344 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI 1345 // nodes, so we insert select instruction to compute the final result. 1346 std::map<std::pair<Value *, Value *>, SelectInst *> InsertedSelects; 1347 for (BasicBlock *Succ : successors(BB1)) { 1348 PHINode *PN; 1349 for (BasicBlock::iterator BBI = Succ->begin(); 1350 (PN = dyn_cast<PHINode>(BBI)); ++BBI) { 1351 Value *BB1V = PN->getIncomingValueForBlock(BB1); 1352 Value *BB2V = PN->getIncomingValueForBlock(BB2); 1353 if (BB1V == BB2V) 1354 continue; 1355 1356 // These values do not agree. Insert a select instruction before NT 1357 // that determines the right value. 1358 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)]; 1359 if (!SI) 1360 SI = cast<SelectInst>( 1361 Builder.CreateSelect(BI->getCondition(), BB1V, BB2V, 1362 BB1V->getName() + "." + BB2V->getName(), BI)); 1363 1364 // Make the PHI node use the select for all incoming values for BB1/BB2 1365 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 1366 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2) 1367 PN->setIncomingValue(i, SI); 1368 } 1369 } 1370 1371 // Update any PHI nodes in our new successors. 1372 for (BasicBlock *Succ : successors(BB1)) 1373 AddPredecessorToBlock(Succ, BIParent, BB1); 1374 1375 EraseTerminatorInstAndDCECond(BI); 1376 return true; 1377 } 1378 1379 // Is it legal to place a variable in operand \c OpIdx of \c I? 1380 // FIXME: This should be promoted to Instruction. 1381 static bool canReplaceOperandWithVariable(const Instruction *I, 1382 unsigned OpIdx) { 1383 // We can't have a PHI with a metadata type. 1384 if (I->getOperand(OpIdx)->getType()->isMetadataTy()) 1385 return false; 1386 1387 // Early exit. 1388 if (!isa<Constant>(I->getOperand(OpIdx))) 1389 return true; 1390 1391 switch (I->getOpcode()) { 1392 default: 1393 return true; 1394 case Instruction::Call: 1395 case Instruction::Invoke: 1396 // FIXME: many arithmetic intrinsics have no issue taking a 1397 // variable, however it's hard to distingish these from 1398 // specials such as @llvm.frameaddress that require a constant. 1399 if (isa<IntrinsicInst>(I)) 1400 return false; 1401 1402 // Constant bundle operands may need to retain their constant-ness for 1403 // correctness. 1404 if (ImmutableCallSite(I).isBundleOperand(OpIdx)) 1405 return false; 1406 1407 return true; 1408 1409 case Instruction::ShuffleVector: 1410 // Shufflevector masks are constant. 1411 return OpIdx != 2; 1412 case Instruction::ExtractValue: 1413 case Instruction::InsertValue: 1414 // All operands apart from the first are constant. 1415 return OpIdx == 0; 1416 case Instruction::Alloca: 1417 return false; 1418 case Instruction::GetElementPtr: 1419 if (OpIdx == 0) 1420 return true; 1421 gep_type_iterator It = std::next(gep_type_begin(I), OpIdx - 1); 1422 return It.isSequential(); 1423 } 1424 } 1425 1426 // All instructions in Insts belong to different blocks that all unconditionally 1427 // branch to a common successor. Analyze each instruction and return true if it 1428 // would be possible to sink them into their successor, creating one common 1429 // instruction instead. For every value that would be required to be provided by 1430 // PHI node (because an operand varies in each input block), add to PHIOperands. 1431 static bool canSinkInstructions( 1432 ArrayRef<Instruction *> Insts, 1433 DenseMap<Instruction *, SmallVector<Value *, 4>> &PHIOperands) { 1434 // Prune out obviously bad instructions to move. Any non-store instruction 1435 // must have exactly one use, and we check later that use is by a single, 1436 // common PHI instruction in the successor. 1437 for (auto *I : Insts) { 1438 // These instructions may change or break semantics if moved. 1439 if (isa<PHINode>(I) || I->isEHPad() || isa<AllocaInst>(I) || 1440 I->getType()->isTokenTy()) 1441 return false; 1442 1443 // Conservatively return false if I is an inline-asm instruction. Sinking 1444 // and merging inline-asm instructions can potentially create arguments 1445 // that cannot satisfy the inline-asm constraints. 1446 if (const auto *C = dyn_cast<CallInst>(I)) 1447 if (C->isInlineAsm()) 1448 return false; 1449 1450 // Everything must have only one use too, apart from stores which 1451 // have no uses. 1452 if (!isa<StoreInst>(I) && !I->hasOneUse()) 1453 return false; 1454 } 1455 1456 const Instruction *I0 = Insts.front(); 1457 for (auto *I : Insts) 1458 if (!I->isSameOperationAs(I0)) 1459 return false; 1460 1461 // All instructions in Insts are known to be the same opcode. If they aren't 1462 // stores, check the only user of each is a PHI or in the same block as the 1463 // instruction, because if a user is in the same block as an instruction 1464 // we're contemplating sinking, it must already be determined to be sinkable. 1465 if (!isa<StoreInst>(I0)) { 1466 auto *PNUse = dyn_cast<PHINode>(*I0->user_begin()); 1467 auto *Succ = I0->getParent()->getTerminator()->getSuccessor(0); 1468 if (!all_of(Insts, [&PNUse,&Succ](const Instruction *I) -> bool { 1469 auto *U = cast<Instruction>(*I->user_begin()); 1470 return (PNUse && 1471 PNUse->getParent() == Succ && 1472 PNUse->getIncomingValueForBlock(I->getParent()) == I) || 1473 U->getParent() == I->getParent(); 1474 })) 1475 return false; 1476 } 1477 1478 // Because SROA can't handle speculating stores of selects, try not 1479 // to sink loads or stores of allocas when we'd have to create a PHI for 1480 // the address operand. Also, because it is likely that loads or stores 1481 // of allocas will disappear when Mem2Reg/SROA is run, don't sink them. 1482 // This can cause code churn which can have unintended consequences down 1483 // the line - see https://llvm.org/bugs/show_bug.cgi?id=30244. 1484 // FIXME: This is a workaround for a deficiency in SROA - see 1485 // https://llvm.org/bugs/show_bug.cgi?id=30188 1486 if (isa<StoreInst>(I0) && any_of(Insts, [](const Instruction *I) { 1487 return isa<AllocaInst>(I->getOperand(1)); 1488 })) 1489 return false; 1490 if (isa<LoadInst>(I0) && any_of(Insts, [](const Instruction *I) { 1491 return isa<AllocaInst>(I->getOperand(0)); 1492 })) 1493 return false; 1494 1495 for (unsigned OI = 0, OE = I0->getNumOperands(); OI != OE; ++OI) { 1496 if (I0->getOperand(OI)->getType()->isTokenTy()) 1497 // Don't touch any operand of token type. 1498 return false; 1499 1500 auto SameAsI0 = [&I0, OI](const Instruction *I) { 1501 assert(I->getNumOperands() == I0->getNumOperands()); 1502 return I->getOperand(OI) == I0->getOperand(OI); 1503 }; 1504 if (!all_of(Insts, SameAsI0)) { 1505 if (!canReplaceOperandWithVariable(I0, OI)) 1506 // We can't create a PHI from this GEP. 1507 return false; 1508 // Don't create indirect calls! The called value is the final operand. 1509 if ((isa<CallInst>(I0) || isa<InvokeInst>(I0)) && OI == OE - 1) { 1510 // FIXME: if the call was *already* indirect, we should do this. 1511 return false; 1512 } 1513 for (auto *I : Insts) 1514 PHIOperands[I].push_back(I->getOperand(OI)); 1515 } 1516 } 1517 return true; 1518 } 1519 1520 // Assuming canSinkLastInstruction(Blocks) has returned true, sink the last 1521 // instruction of every block in Blocks to their common successor, commoning 1522 // into one instruction. 1523 static bool sinkLastInstruction(ArrayRef<BasicBlock*> Blocks) { 1524 auto *BBEnd = Blocks[0]->getTerminator()->getSuccessor(0); 1525 1526 // canSinkLastInstruction returning true guarantees that every block has at 1527 // least one non-terminator instruction. 1528 SmallVector<Instruction*,4> Insts; 1529 for (auto *BB : Blocks) { 1530 Instruction *I = BB->getTerminator(); 1531 do { 1532 I = I->getPrevNode(); 1533 } while (isa<DbgInfoIntrinsic>(I) && I != &BB->front()); 1534 if (!isa<DbgInfoIntrinsic>(I)) 1535 Insts.push_back(I); 1536 } 1537 1538 // The only checking we need to do now is that all users of all instructions 1539 // are the same PHI node. canSinkLastInstruction should have checked this but 1540 // it is slightly over-aggressive - it gets confused by commutative instructions 1541 // so double-check it here. 1542 Instruction *I0 = Insts.front(); 1543 if (!isa<StoreInst>(I0)) { 1544 auto *PNUse = dyn_cast<PHINode>(*I0->user_begin()); 1545 if (!all_of(Insts, [&PNUse](const Instruction *I) -> bool { 1546 auto *U = cast<Instruction>(*I->user_begin()); 1547 return U == PNUse; 1548 })) 1549 return false; 1550 } 1551 1552 // We don't need to do any more checking here; canSinkLastInstruction should 1553 // have done it all for us. 1554 SmallVector<Value*, 4> NewOperands; 1555 for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O) { 1556 // This check is different to that in canSinkLastInstruction. There, we 1557 // cared about the global view once simplifycfg (and instcombine) have 1558 // completed - it takes into account PHIs that become trivially 1559 // simplifiable. However here we need a more local view; if an operand 1560 // differs we create a PHI and rely on instcombine to clean up the very 1561 // small mess we may make. 1562 bool NeedPHI = any_of(Insts, [&I0, O](const Instruction *I) { 1563 return I->getOperand(O) != I0->getOperand(O); 1564 }); 1565 if (!NeedPHI) { 1566 NewOperands.push_back(I0->getOperand(O)); 1567 continue; 1568 } 1569 1570 // Create a new PHI in the successor block and populate it. 1571 auto *Op = I0->getOperand(O); 1572 assert(!Op->getType()->isTokenTy() && "Can't PHI tokens!"); 1573 auto *PN = PHINode::Create(Op->getType(), Insts.size(), 1574 Op->getName() + ".sink", &BBEnd->front()); 1575 for (auto *I : Insts) 1576 PN->addIncoming(I->getOperand(O), I->getParent()); 1577 NewOperands.push_back(PN); 1578 } 1579 1580 // Arbitrarily use I0 as the new "common" instruction; remap its operands 1581 // and move it to the start of the successor block. 1582 for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O) 1583 I0->getOperandUse(O).set(NewOperands[O]); 1584 I0->moveBefore(&*BBEnd->getFirstInsertionPt()); 1585 1586 // The debug location for the "common" instruction is the merged locations of 1587 // all the commoned instructions. We start with the original location of the 1588 // "common" instruction and iteratively merge each location in the loop below. 1589 const DILocation *Loc = I0->getDebugLoc(); 1590 1591 // Update metadata and IR flags, and merge debug locations. 1592 for (auto *I : Insts) 1593 if (I != I0) { 1594 Loc = DILocation::getMergedLocation(Loc, I->getDebugLoc()); 1595 combineMetadataForCSE(I0, I); 1596 I0->andIRFlags(I); 1597 } 1598 if (!isa<CallInst>(I0)) 1599 I0->setDebugLoc(Loc); 1600 1601 if (!isa<StoreInst>(I0)) { 1602 // canSinkLastInstruction checked that all instructions were used by 1603 // one and only one PHI node. Find that now, RAUW it to our common 1604 // instruction and nuke it. 1605 assert(I0->hasOneUse()); 1606 auto *PN = cast<PHINode>(*I0->user_begin()); 1607 PN->replaceAllUsesWith(I0); 1608 PN->eraseFromParent(); 1609 } 1610 1611 // Finally nuke all instructions apart from the common instruction. 1612 for (auto *I : Insts) 1613 if (I != I0) 1614 I->eraseFromParent(); 1615 1616 return true; 1617 } 1618 1619 namespace { 1620 1621 // LockstepReverseIterator - Iterates through instructions 1622 // in a set of blocks in reverse order from the first non-terminator. 1623 // For example (assume all blocks have size n): 1624 // LockstepReverseIterator I([B1, B2, B3]); 1625 // *I-- = [B1[n], B2[n], B3[n]]; 1626 // *I-- = [B1[n-1], B2[n-1], B3[n-1]]; 1627 // *I-- = [B1[n-2], B2[n-2], B3[n-2]]; 1628 // ... 1629 class LockstepReverseIterator { 1630 ArrayRef<BasicBlock*> Blocks; 1631 SmallVector<Instruction*,4> Insts; 1632 bool Fail; 1633 public: 1634 LockstepReverseIterator(ArrayRef<BasicBlock*> Blocks) : 1635 Blocks(Blocks) { 1636 reset(); 1637 } 1638 1639 void reset() { 1640 Fail = false; 1641 Insts.clear(); 1642 for (auto *BB : Blocks) { 1643 Instruction *Inst = BB->getTerminator(); 1644 for (Inst = Inst->getPrevNode(); Inst && isa<DbgInfoIntrinsic>(Inst);) 1645 Inst = Inst->getPrevNode(); 1646 if (!Inst) { 1647 // Block wasn't big enough. 1648 Fail = true; 1649 return; 1650 } 1651 Insts.push_back(Inst); 1652 } 1653 } 1654 1655 bool isValid() const { 1656 return !Fail; 1657 } 1658 1659 void operator -- () { 1660 if (Fail) 1661 return; 1662 for (auto *&Inst : Insts) { 1663 for (Inst = Inst->getPrevNode(); Inst && isa<DbgInfoIntrinsic>(Inst);) 1664 Inst = Inst->getPrevNode(); 1665 // Already at beginning of block. 1666 if (!Inst) { 1667 Fail = true; 1668 return; 1669 } 1670 } 1671 } 1672 1673 ArrayRef<Instruction*> operator * () const { 1674 return Insts; 1675 } 1676 }; 1677 1678 } // end anonymous namespace 1679 1680 /// Given an unconditional branch that goes to BBEnd, 1681 /// check whether BBEnd has only two predecessors and the other predecessor 1682 /// ends with an unconditional branch. If it is true, sink any common code 1683 /// in the two predecessors to BBEnd. 1684 static bool SinkThenElseCodeToEnd(BranchInst *BI1) { 1685 assert(BI1->isUnconditional()); 1686 BasicBlock *BBEnd = BI1->getSuccessor(0); 1687 1688 // We support two situations: 1689 // (1) all incoming arcs are unconditional 1690 // (2) one incoming arc is conditional 1691 // 1692 // (2) is very common in switch defaults and 1693 // else-if patterns; 1694 // 1695 // if (a) f(1); 1696 // else if (b) f(2); 1697 // 1698 // produces: 1699 // 1700 // [if] 1701 // / \ 1702 // [f(1)] [if] 1703 // | | \ 1704 // | | | 1705 // | [f(2)]| 1706 // \ | / 1707 // [ end ] 1708 // 1709 // [end] has two unconditional predecessor arcs and one conditional. The 1710 // conditional refers to the implicit empty 'else' arc. This conditional 1711 // arc can also be caused by an empty default block in a switch. 1712 // 1713 // In this case, we attempt to sink code from all *unconditional* arcs. 1714 // If we can sink instructions from these arcs (determined during the scan 1715 // phase below) we insert a common successor for all unconditional arcs and 1716 // connect that to [end], to enable sinking: 1717 // 1718 // [if] 1719 // / \ 1720 // [x(1)] [if] 1721 // | | \ 1722 // | | \ 1723 // | [x(2)] | 1724 // \ / | 1725 // [sink.split] | 1726 // \ / 1727 // [ end ] 1728 // 1729 SmallVector<BasicBlock*,4> UnconditionalPreds; 1730 Instruction *Cond = nullptr; 1731 for (auto *B : predecessors(BBEnd)) { 1732 auto *T = B->getTerminator(); 1733 if (isa<BranchInst>(T) && cast<BranchInst>(T)->isUnconditional()) 1734 UnconditionalPreds.push_back(B); 1735 else if ((isa<BranchInst>(T) || isa<SwitchInst>(T)) && !Cond) 1736 Cond = T; 1737 else 1738 return false; 1739 } 1740 if (UnconditionalPreds.size() < 2) 1741 return false; 1742 1743 bool Changed = false; 1744 // We take a two-step approach to tail sinking. First we scan from the end of 1745 // each block upwards in lockstep. If the n'th instruction from the end of each 1746 // block can be sunk, those instructions are added to ValuesToSink and we 1747 // carry on. If we can sink an instruction but need to PHI-merge some operands 1748 // (because they're not identical in each instruction) we add these to 1749 // PHIOperands. 1750 unsigned ScanIdx = 0; 1751 SmallPtrSet<Value*,4> InstructionsToSink; 1752 DenseMap<Instruction*, SmallVector<Value*,4>> PHIOperands; 1753 LockstepReverseIterator LRI(UnconditionalPreds); 1754 while (LRI.isValid() && 1755 canSinkInstructions(*LRI, PHIOperands)) { 1756 DEBUG(dbgs() << "SINK: instruction can be sunk: " << *(*LRI)[0] << "\n"); 1757 InstructionsToSink.insert((*LRI).begin(), (*LRI).end()); 1758 ++ScanIdx; 1759 --LRI; 1760 } 1761 1762 auto ProfitableToSinkInstruction = [&](LockstepReverseIterator &LRI) { 1763 unsigned NumPHIdValues = 0; 1764 for (auto *I : *LRI) 1765 for (auto *V : PHIOperands[I]) 1766 if (InstructionsToSink.count(V) == 0) 1767 ++NumPHIdValues; 1768 DEBUG(dbgs() << "SINK: #phid values: " << NumPHIdValues << "\n"); 1769 unsigned NumPHIInsts = NumPHIdValues / UnconditionalPreds.size(); 1770 if ((NumPHIdValues % UnconditionalPreds.size()) != 0) 1771 NumPHIInsts++; 1772 1773 return NumPHIInsts <= 1; 1774 }; 1775 1776 if (ScanIdx > 0 && Cond) { 1777 // Check if we would actually sink anything first! This mutates the CFG and 1778 // adds an extra block. The goal in doing this is to allow instructions that 1779 // couldn't be sunk before to be sunk - obviously, speculatable instructions 1780 // (such as trunc, add) can be sunk and predicated already. So we check that 1781 // we're going to sink at least one non-speculatable instruction. 1782 LRI.reset(); 1783 unsigned Idx = 0; 1784 bool Profitable = false; 1785 while (ProfitableToSinkInstruction(LRI) && Idx < ScanIdx) { 1786 if (!isSafeToSpeculativelyExecute((*LRI)[0])) { 1787 Profitable = true; 1788 break; 1789 } 1790 --LRI; 1791 ++Idx; 1792 } 1793 if (!Profitable) 1794 return false; 1795 1796 DEBUG(dbgs() << "SINK: Splitting edge\n"); 1797 // We have a conditional edge and we're going to sink some instructions. 1798 // Insert a new block postdominating all blocks we're going to sink from. 1799 if (!SplitBlockPredecessors(BI1->getSuccessor(0), UnconditionalPreds, 1800 ".sink.split")) 1801 // Edges couldn't be split. 1802 return false; 1803 Changed = true; 1804 } 1805 1806 // Now that we've analyzed all potential sinking candidates, perform the 1807 // actual sink. We iteratively sink the last non-terminator of the source 1808 // blocks into their common successor unless doing so would require too 1809 // many PHI instructions to be generated (currently only one PHI is allowed 1810 // per sunk instruction). 1811 // 1812 // We can use InstructionsToSink to discount values needing PHI-merging that will 1813 // actually be sunk in a later iteration. This allows us to be more 1814 // aggressive in what we sink. This does allow a false positive where we 1815 // sink presuming a later value will also be sunk, but stop half way through 1816 // and never actually sink it which means we produce more PHIs than intended. 1817 // This is unlikely in practice though. 1818 for (unsigned SinkIdx = 0; SinkIdx != ScanIdx; ++SinkIdx) { 1819 DEBUG(dbgs() << "SINK: Sink: " 1820 << *UnconditionalPreds[0]->getTerminator()->getPrevNode() 1821 << "\n"); 1822 1823 // Because we've sunk every instruction in turn, the current instruction to 1824 // sink is always at index 0. 1825 LRI.reset(); 1826 if (!ProfitableToSinkInstruction(LRI)) { 1827 // Too many PHIs would be created. 1828 DEBUG(dbgs() << "SINK: stopping here, too many PHIs would be created!\n"); 1829 break; 1830 } 1831 1832 if (!sinkLastInstruction(UnconditionalPreds)) 1833 return Changed; 1834 NumSinkCommons++; 1835 Changed = true; 1836 } 1837 return Changed; 1838 } 1839 1840 /// \brief Determine if we can hoist sink a sole store instruction out of a 1841 /// conditional block. 1842 /// 1843 /// We are looking for code like the following: 1844 /// BrBB: 1845 /// store i32 %add, i32* %arrayidx2 1846 /// ... // No other stores or function calls (we could be calling a memory 1847 /// ... // function). 1848 /// %cmp = icmp ult %x, %y 1849 /// br i1 %cmp, label %EndBB, label %ThenBB 1850 /// ThenBB: 1851 /// store i32 %add5, i32* %arrayidx2 1852 /// br label EndBB 1853 /// EndBB: 1854 /// ... 1855 /// We are going to transform this into: 1856 /// BrBB: 1857 /// store i32 %add, i32* %arrayidx2 1858 /// ... // 1859 /// %cmp = icmp ult %x, %y 1860 /// %add.add5 = select i1 %cmp, i32 %add, %add5 1861 /// store i32 %add.add5, i32* %arrayidx2 1862 /// ... 1863 /// 1864 /// \return The pointer to the value of the previous store if the store can be 1865 /// hoisted into the predecessor block. 0 otherwise. 1866 static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB, 1867 BasicBlock *StoreBB, BasicBlock *EndBB) { 1868 StoreInst *StoreToHoist = dyn_cast<StoreInst>(I); 1869 if (!StoreToHoist) 1870 return nullptr; 1871 1872 // Volatile or atomic. 1873 if (!StoreToHoist->isSimple()) 1874 return nullptr; 1875 1876 Value *StorePtr = StoreToHoist->getPointerOperand(); 1877 1878 // Look for a store to the same pointer in BrBB. 1879 unsigned MaxNumInstToLookAt = 9; 1880 for (Instruction &CurI : reverse(*BrBB)) { 1881 if (!MaxNumInstToLookAt) 1882 break; 1883 // Skip debug info. 1884 if (isa<DbgInfoIntrinsic>(CurI)) 1885 continue; 1886 --MaxNumInstToLookAt; 1887 1888 // Could be calling an instruction that affects memory like free(). 1889 if (CurI.mayHaveSideEffects() && !isa<StoreInst>(CurI)) 1890 return nullptr; 1891 1892 if (auto *SI = dyn_cast<StoreInst>(&CurI)) { 1893 // Found the previous store make sure it stores to the same location. 1894 if (SI->getPointerOperand() == StorePtr) 1895 // Found the previous store, return its value operand. 1896 return SI->getValueOperand(); 1897 return nullptr; // Unknown store. 1898 } 1899 } 1900 1901 return nullptr; 1902 } 1903 1904 /// \brief Speculate a conditional basic block flattening the CFG. 1905 /// 1906 /// Note that this is a very risky transform currently. Speculating 1907 /// instructions like this is most often not desirable. Instead, there is an MI 1908 /// pass which can do it with full awareness of the resource constraints. 1909 /// However, some cases are "obvious" and we should do directly. An example of 1910 /// this is speculating a single, reasonably cheap instruction. 1911 /// 1912 /// There is only one distinct advantage to flattening the CFG at the IR level: 1913 /// it makes very common but simplistic optimizations such as are common in 1914 /// instcombine and the DAG combiner more powerful by removing CFG edges and 1915 /// modeling their effects with easier to reason about SSA value graphs. 1916 /// 1917 /// 1918 /// An illustration of this transform is turning this IR: 1919 /// \code 1920 /// BB: 1921 /// %cmp = icmp ult %x, %y 1922 /// br i1 %cmp, label %EndBB, label %ThenBB 1923 /// ThenBB: 1924 /// %sub = sub %x, %y 1925 /// br label BB2 1926 /// EndBB: 1927 /// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ] 1928 /// ... 1929 /// \endcode 1930 /// 1931 /// Into this IR: 1932 /// \code 1933 /// BB: 1934 /// %cmp = icmp ult %x, %y 1935 /// %sub = sub %x, %y 1936 /// %cond = select i1 %cmp, 0, %sub 1937 /// ... 1938 /// \endcode 1939 /// 1940 /// \returns true if the conditional block is removed. 1941 static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB, 1942 const TargetTransformInfo &TTI) { 1943 // Be conservative for now. FP select instruction can often be expensive. 1944 Value *BrCond = BI->getCondition(); 1945 if (isa<FCmpInst>(BrCond)) 1946 return false; 1947 1948 BasicBlock *BB = BI->getParent(); 1949 BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0); 1950 1951 // If ThenBB is actually on the false edge of the conditional branch, remember 1952 // to swap the select operands later. 1953 bool Invert = false; 1954 if (ThenBB != BI->getSuccessor(0)) { 1955 assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?"); 1956 Invert = true; 1957 } 1958 assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block"); 1959 1960 // Keep a count of how many times instructions are used within CondBB when 1961 // they are candidates for sinking into CondBB. Specifically: 1962 // - They are defined in BB, and 1963 // - They have no side effects, and 1964 // - All of their uses are in CondBB. 1965 SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts; 1966 1967 unsigned SpeculationCost = 0; 1968 Value *SpeculatedStoreValue = nullptr; 1969 StoreInst *SpeculatedStore = nullptr; 1970 for (BasicBlock::iterator BBI = ThenBB->begin(), 1971 BBE = std::prev(ThenBB->end()); 1972 BBI != BBE; ++BBI) { 1973 Instruction *I = &*BBI; 1974 // Skip debug info. 1975 if (isa<DbgInfoIntrinsic>(I)) 1976 continue; 1977 1978 // Only speculatively execute a single instruction (not counting the 1979 // terminator) for now. 1980 ++SpeculationCost; 1981 if (SpeculationCost > 1) 1982 return false; 1983 1984 // Don't hoist the instruction if it's unsafe or expensive. 1985 if (!isSafeToSpeculativelyExecute(I) && 1986 !(HoistCondStores && (SpeculatedStoreValue = isSafeToSpeculateStore( 1987 I, BB, ThenBB, EndBB)))) 1988 return false; 1989 if (!SpeculatedStoreValue && 1990 ComputeSpeculationCost(I, TTI) > 1991 PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic) 1992 return false; 1993 1994 // Store the store speculation candidate. 1995 if (SpeculatedStoreValue) 1996 SpeculatedStore = cast<StoreInst>(I); 1997 1998 // Do not hoist the instruction if any of its operands are defined but not 1999 // used in BB. The transformation will prevent the operand from 2000 // being sunk into the use block. 2001 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) { 2002 Instruction *OpI = dyn_cast<Instruction>(*i); 2003 if (!OpI || OpI->getParent() != BB || OpI->mayHaveSideEffects()) 2004 continue; // Not a candidate for sinking. 2005 2006 ++SinkCandidateUseCounts[OpI]; 2007 } 2008 } 2009 2010 // Consider any sink candidates which are only used in CondBB as costs for 2011 // speculation. Note, while we iterate over a DenseMap here, we are summing 2012 // and so iteration order isn't significant. 2013 for (SmallDenseMap<Instruction *, unsigned, 4>::iterator 2014 I = SinkCandidateUseCounts.begin(), 2015 E = SinkCandidateUseCounts.end(); 2016 I != E; ++I) 2017 if (I->first->getNumUses() == I->second) { 2018 ++SpeculationCost; 2019 if (SpeculationCost > 1) 2020 return false; 2021 } 2022 2023 // Check that the PHI nodes can be converted to selects. 2024 bool HaveRewritablePHIs = false; 2025 for (BasicBlock::iterator I = EndBB->begin(); 2026 PHINode *PN = dyn_cast<PHINode>(I); ++I) { 2027 Value *OrigV = PN->getIncomingValueForBlock(BB); 2028 Value *ThenV = PN->getIncomingValueForBlock(ThenBB); 2029 2030 // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf. 2031 // Skip PHIs which are trivial. 2032 if (ThenV == OrigV) 2033 continue; 2034 2035 // Don't convert to selects if we could remove undefined behavior instead. 2036 if (passingValueIsAlwaysUndefined(OrigV, PN) || 2037 passingValueIsAlwaysUndefined(ThenV, PN)) 2038 return false; 2039 2040 HaveRewritablePHIs = true; 2041 ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV); 2042 ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV); 2043 if (!OrigCE && !ThenCE) 2044 continue; // Known safe and cheap. 2045 2046 if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE)) || 2047 (OrigCE && !isSafeToSpeculativelyExecute(OrigCE))) 2048 return false; 2049 unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE, TTI) : 0; 2050 unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE, TTI) : 0; 2051 unsigned MaxCost = 2052 2 * PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic; 2053 if (OrigCost + ThenCost > MaxCost) 2054 return false; 2055 2056 // Account for the cost of an unfolded ConstantExpr which could end up 2057 // getting expanded into Instructions. 2058 // FIXME: This doesn't account for how many operations are combined in the 2059 // constant expression. 2060 ++SpeculationCost; 2061 if (SpeculationCost > 1) 2062 return false; 2063 } 2064 2065 // If there are no PHIs to process, bail early. This helps ensure idempotence 2066 // as well. 2067 if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue)) 2068 return false; 2069 2070 // If we get here, we can hoist the instruction and if-convert. 2071 DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";); 2072 2073 // Insert a select of the value of the speculated store. 2074 if (SpeculatedStoreValue) { 2075 IRBuilder<NoFolder> Builder(BI); 2076 Value *TrueV = SpeculatedStore->getValueOperand(); 2077 Value *FalseV = SpeculatedStoreValue; 2078 if (Invert) 2079 std::swap(TrueV, FalseV); 2080 Value *S = Builder.CreateSelect( 2081 BrCond, TrueV, FalseV, TrueV->getName() + "." + FalseV->getName(), BI); 2082 SpeculatedStore->setOperand(0, S); 2083 SpeculatedStore->setDebugLoc( 2084 DILocation::getMergedLocation( 2085 BI->getDebugLoc(), SpeculatedStore->getDebugLoc())); 2086 } 2087 2088 // Metadata can be dependent on the condition we are hoisting above. 2089 // Conservatively strip all metadata on the instruction. 2090 for (auto &I : *ThenBB) 2091 I.dropUnknownNonDebugMetadata(); 2092 2093 // Hoist the instructions. 2094 BB->getInstList().splice(BI->getIterator(), ThenBB->getInstList(), 2095 ThenBB->begin(), std::prev(ThenBB->end())); 2096 2097 // Insert selects and rewrite the PHI operands. 2098 IRBuilder<NoFolder> Builder(BI); 2099 for (BasicBlock::iterator I = EndBB->begin(); 2100 PHINode *PN = dyn_cast<PHINode>(I); ++I) { 2101 unsigned OrigI = PN->getBasicBlockIndex(BB); 2102 unsigned ThenI = PN->getBasicBlockIndex(ThenBB); 2103 Value *OrigV = PN->getIncomingValue(OrigI); 2104 Value *ThenV = PN->getIncomingValue(ThenI); 2105 2106 // Skip PHIs which are trivial. 2107 if (OrigV == ThenV) 2108 continue; 2109 2110 // Create a select whose true value is the speculatively executed value and 2111 // false value is the preexisting value. Swap them if the branch 2112 // destinations were inverted. 2113 Value *TrueV = ThenV, *FalseV = OrigV; 2114 if (Invert) 2115 std::swap(TrueV, FalseV); 2116 Value *V = Builder.CreateSelect( 2117 BrCond, TrueV, FalseV, TrueV->getName() + "." + FalseV->getName(), BI); 2118 PN->setIncomingValue(OrigI, V); 2119 PN->setIncomingValue(ThenI, V); 2120 } 2121 2122 ++NumSpeculations; 2123 return true; 2124 } 2125 2126 /// Return true if we can thread a branch across this block. 2127 static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) { 2128 BranchInst *BI = cast<BranchInst>(BB->getTerminator()); 2129 unsigned Size = 0; 2130 2131 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) { 2132 if (isa<DbgInfoIntrinsic>(BBI)) 2133 continue; 2134 if (Size > 10) 2135 return false; // Don't clone large BB's. 2136 ++Size; 2137 2138 // We can only support instructions that do not define values that are 2139 // live outside of the current basic block. 2140 for (User *U : BBI->users()) { 2141 Instruction *UI = cast<Instruction>(U); 2142 if (UI->getParent() != BB || isa<PHINode>(UI)) 2143 return false; 2144 } 2145 2146 // Looks ok, continue checking. 2147 } 2148 2149 return true; 2150 } 2151 2152 /// If we have a conditional branch on a PHI node value that is defined in the 2153 /// same block as the branch and if any PHI entries are constants, thread edges 2154 /// corresponding to that entry to be branches to their ultimate destination. 2155 static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout &DL, 2156 AssumptionCache *AC) { 2157 BasicBlock *BB = BI->getParent(); 2158 PHINode *PN = dyn_cast<PHINode>(BI->getCondition()); 2159 // NOTE: we currently cannot transform this case if the PHI node is used 2160 // outside of the block. 2161 if (!PN || PN->getParent() != BB || !PN->hasOneUse()) 2162 return false; 2163 2164 // Degenerate case of a single entry PHI. 2165 if (PN->getNumIncomingValues() == 1) { 2166 FoldSingleEntryPHINodes(PN->getParent()); 2167 return true; 2168 } 2169 2170 // Now we know that this block has multiple preds and two succs. 2171 if (!BlockIsSimpleEnoughToThreadThrough(BB)) 2172 return false; 2173 2174 // Can't fold blocks that contain noduplicate or convergent calls. 2175 if (any_of(*BB, [](const Instruction &I) { 2176 const CallInst *CI = dyn_cast<CallInst>(&I); 2177 return CI && (CI->cannotDuplicate() || CI->isConvergent()); 2178 })) 2179 return false; 2180 2181 // Okay, this is a simple enough basic block. See if any phi values are 2182 // constants. 2183 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 2184 ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i)); 2185 if (!CB || !CB->getType()->isIntegerTy(1)) 2186 continue; 2187 2188 // Okay, we now know that all edges from PredBB should be revectored to 2189 // branch to RealDest. 2190 BasicBlock *PredBB = PN->getIncomingBlock(i); 2191 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue()); 2192 2193 if (RealDest == BB) 2194 continue; // Skip self loops. 2195 // Skip if the predecessor's terminator is an indirect branch. 2196 if (isa<IndirectBrInst>(PredBB->getTerminator())) 2197 continue; 2198 2199 // The dest block might have PHI nodes, other predecessors and other 2200 // difficult cases. Instead of being smart about this, just insert a new 2201 // block that jumps to the destination block, effectively splitting 2202 // the edge we are about to create. 2203 BasicBlock *EdgeBB = 2204 BasicBlock::Create(BB->getContext(), RealDest->getName() + ".critedge", 2205 RealDest->getParent(), RealDest); 2206 BranchInst::Create(RealDest, EdgeBB); 2207 2208 // Update PHI nodes. 2209 AddPredecessorToBlock(RealDest, EdgeBB, BB); 2210 2211 // BB may have instructions that are being threaded over. Clone these 2212 // instructions into EdgeBB. We know that there will be no uses of the 2213 // cloned instructions outside of EdgeBB. 2214 BasicBlock::iterator InsertPt = EdgeBB->begin(); 2215 DenseMap<Value *, Value *> TranslateMap; // Track translated values. 2216 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) { 2217 if (PHINode *PN = dyn_cast<PHINode>(BBI)) { 2218 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB); 2219 continue; 2220 } 2221 // Clone the instruction. 2222 Instruction *N = BBI->clone(); 2223 if (BBI->hasName()) 2224 N->setName(BBI->getName() + ".c"); 2225 2226 // Update operands due to translation. 2227 for (User::op_iterator i = N->op_begin(), e = N->op_end(); i != e; ++i) { 2228 DenseMap<Value *, Value *>::iterator PI = TranslateMap.find(*i); 2229 if (PI != TranslateMap.end()) 2230 *i = PI->second; 2231 } 2232 2233 // Check for trivial simplification. 2234 if (Value *V = SimplifyInstruction(N, DL)) { 2235 if (!BBI->use_empty()) 2236 TranslateMap[&*BBI] = V; 2237 if (!N->mayHaveSideEffects()) { 2238 delete N; // Instruction folded away, don't need actual inst 2239 N = nullptr; 2240 } 2241 } else { 2242 if (!BBI->use_empty()) 2243 TranslateMap[&*BBI] = N; 2244 } 2245 // Insert the new instruction into its new home. 2246 if (N) 2247 EdgeBB->getInstList().insert(InsertPt, N); 2248 2249 // Register the new instruction with the assumption cache if necessary. 2250 if (auto *II = dyn_cast_or_null<IntrinsicInst>(N)) 2251 if (II->getIntrinsicID() == Intrinsic::assume) 2252 AC->registerAssumption(II); 2253 } 2254 2255 // Loop over all of the edges from PredBB to BB, changing them to branch 2256 // to EdgeBB instead. 2257 TerminatorInst *PredBBTI = PredBB->getTerminator(); 2258 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i) 2259 if (PredBBTI->getSuccessor(i) == BB) { 2260 BB->removePredecessor(PredBB); 2261 PredBBTI->setSuccessor(i, EdgeBB); 2262 } 2263 2264 // Recurse, simplifying any other constants. 2265 return FoldCondBranchOnPHI(BI, DL, AC) | true; 2266 } 2267 2268 return false; 2269 } 2270 2271 /// Given a BB that starts with the specified two-entry PHI node, 2272 /// see if we can eliminate it. 2273 static bool FoldTwoEntryPHINode(PHINode *PN, const TargetTransformInfo &TTI, 2274 const DataLayout &DL) { 2275 // Ok, this is a two entry PHI node. Check to see if this is a simple "if 2276 // statement", which has a very simple dominance structure. Basically, we 2277 // are trying to find the condition that is being branched on, which 2278 // subsequently causes this merge to happen. We really want control 2279 // dependence information for this check, but simplifycfg can't keep it up 2280 // to date, and this catches most of the cases we care about anyway. 2281 BasicBlock *BB = PN->getParent(); 2282 BasicBlock *IfTrue, *IfFalse; 2283 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse); 2284 if (!IfCond || 2285 // Don't bother if the branch will be constant folded trivially. 2286 isa<ConstantInt>(IfCond)) 2287 return false; 2288 2289 // Okay, we found that we can merge this two-entry phi node into a select. 2290 // Doing so would require us to fold *all* two entry phi nodes in this block. 2291 // At some point this becomes non-profitable (particularly if the target 2292 // doesn't support cmov's). Only do this transformation if there are two or 2293 // fewer PHI nodes in this block. 2294 unsigned NumPhis = 0; 2295 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I) 2296 if (NumPhis > 2) 2297 return false; 2298 2299 // Loop over the PHI's seeing if we can promote them all to select 2300 // instructions. While we are at it, keep track of the instructions 2301 // that need to be moved to the dominating block. 2302 SmallPtrSet<Instruction *, 4> AggressiveInsts; 2303 unsigned MaxCostVal0 = PHINodeFoldingThreshold, 2304 MaxCostVal1 = PHINodeFoldingThreshold; 2305 MaxCostVal0 *= TargetTransformInfo::TCC_Basic; 2306 MaxCostVal1 *= TargetTransformInfo::TCC_Basic; 2307 2308 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) { 2309 PHINode *PN = cast<PHINode>(II++); 2310 if (Value *V = SimplifyInstruction(PN, DL)) { 2311 PN->replaceAllUsesWith(V); 2312 PN->eraseFromParent(); 2313 continue; 2314 } 2315 2316 if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts, 2317 MaxCostVal0, TTI) || 2318 !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts, 2319 MaxCostVal1, TTI)) 2320 return false; 2321 } 2322 2323 // If we folded the first phi, PN dangles at this point. Refresh it. If 2324 // we ran out of PHIs then we simplified them all. 2325 PN = dyn_cast<PHINode>(BB->begin()); 2326 if (!PN) 2327 return true; 2328 2329 // Don't fold i1 branches on PHIs which contain binary operators. These can 2330 // often be turned into switches and other things. 2331 if (PN->getType()->isIntegerTy(1) && 2332 (isa<BinaryOperator>(PN->getIncomingValue(0)) || 2333 isa<BinaryOperator>(PN->getIncomingValue(1)) || 2334 isa<BinaryOperator>(IfCond))) 2335 return false; 2336 2337 // If all PHI nodes are promotable, check to make sure that all instructions 2338 // in the predecessor blocks can be promoted as well. If not, we won't be able 2339 // to get rid of the control flow, so it's not worth promoting to select 2340 // instructions. 2341 BasicBlock *DomBlock = nullptr; 2342 BasicBlock *IfBlock1 = PN->getIncomingBlock(0); 2343 BasicBlock *IfBlock2 = PN->getIncomingBlock(1); 2344 if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) { 2345 IfBlock1 = nullptr; 2346 } else { 2347 DomBlock = *pred_begin(IfBlock1); 2348 for (BasicBlock::iterator I = IfBlock1->begin(); !isa<TerminatorInst>(I); 2349 ++I) 2350 if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) { 2351 // This is not an aggressive instruction that we can promote. 2352 // Because of this, we won't be able to get rid of the control flow, so 2353 // the xform is not worth it. 2354 return false; 2355 } 2356 } 2357 2358 if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) { 2359 IfBlock2 = nullptr; 2360 } else { 2361 DomBlock = *pred_begin(IfBlock2); 2362 for (BasicBlock::iterator I = IfBlock2->begin(); !isa<TerminatorInst>(I); 2363 ++I) 2364 if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) { 2365 // This is not an aggressive instruction that we can promote. 2366 // Because of this, we won't be able to get rid of the control flow, so 2367 // the xform is not worth it. 2368 return false; 2369 } 2370 } 2371 2372 DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: " 2373 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n"); 2374 2375 // If we can still promote the PHI nodes after this gauntlet of tests, 2376 // do all of the PHI's now. 2377 Instruction *InsertPt = DomBlock->getTerminator(); 2378 IRBuilder<NoFolder> Builder(InsertPt); 2379 2380 // Move all 'aggressive' instructions, which are defined in the 2381 // conditional parts of the if's up to the dominating block. 2382 if (IfBlock1) { 2383 for (auto &I : *IfBlock1) 2384 I.dropUnknownNonDebugMetadata(); 2385 DomBlock->getInstList().splice(InsertPt->getIterator(), 2386 IfBlock1->getInstList(), IfBlock1->begin(), 2387 IfBlock1->getTerminator()->getIterator()); 2388 } 2389 if (IfBlock2) { 2390 for (auto &I : *IfBlock2) 2391 I.dropUnknownNonDebugMetadata(); 2392 DomBlock->getInstList().splice(InsertPt->getIterator(), 2393 IfBlock2->getInstList(), IfBlock2->begin(), 2394 IfBlock2->getTerminator()->getIterator()); 2395 } 2396 2397 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) { 2398 // Change the PHI node into a select instruction. 2399 Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse); 2400 Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue); 2401 2402 Value *Sel = Builder.CreateSelect(IfCond, TrueVal, FalseVal, "", InsertPt); 2403 PN->replaceAllUsesWith(Sel); 2404 Sel->takeName(PN); 2405 PN->eraseFromParent(); 2406 } 2407 2408 // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement 2409 // has been flattened. Change DomBlock to jump directly to our new block to 2410 // avoid other simplifycfg's kicking in on the diamond. 2411 TerminatorInst *OldTI = DomBlock->getTerminator(); 2412 Builder.SetInsertPoint(OldTI); 2413 Builder.CreateBr(BB); 2414 OldTI->eraseFromParent(); 2415 return true; 2416 } 2417 2418 /// If we found a conditional branch that goes to two returning blocks, 2419 /// try to merge them together into one return, 2420 /// introducing a select if the return values disagree. 2421 static bool SimplifyCondBranchToTwoReturns(BranchInst *BI, 2422 IRBuilder<> &Builder) { 2423 assert(BI->isConditional() && "Must be a conditional branch"); 2424 BasicBlock *TrueSucc = BI->getSuccessor(0); 2425 BasicBlock *FalseSucc = BI->getSuccessor(1); 2426 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator()); 2427 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator()); 2428 2429 // Check to ensure both blocks are empty (just a return) or optionally empty 2430 // with PHI nodes. If there are other instructions, merging would cause extra 2431 // computation on one path or the other. 2432 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator()) 2433 return false; 2434 if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator()) 2435 return false; 2436 2437 Builder.SetInsertPoint(BI); 2438 // Okay, we found a branch that is going to two return nodes. If 2439 // there is no return value for this function, just change the 2440 // branch into a return. 2441 if (FalseRet->getNumOperands() == 0) { 2442 TrueSucc->removePredecessor(BI->getParent()); 2443 FalseSucc->removePredecessor(BI->getParent()); 2444 Builder.CreateRetVoid(); 2445 EraseTerminatorInstAndDCECond(BI); 2446 return true; 2447 } 2448 2449 // Otherwise, figure out what the true and false return values are 2450 // so we can insert a new select instruction. 2451 Value *TrueValue = TrueRet->getReturnValue(); 2452 Value *FalseValue = FalseRet->getReturnValue(); 2453 2454 // Unwrap any PHI nodes in the return blocks. 2455 if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue)) 2456 if (TVPN->getParent() == TrueSucc) 2457 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent()); 2458 if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue)) 2459 if (FVPN->getParent() == FalseSucc) 2460 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent()); 2461 2462 // In order for this transformation to be safe, we must be able to 2463 // unconditionally execute both operands to the return. This is 2464 // normally the case, but we could have a potentially-trapping 2465 // constant expression that prevents this transformation from being 2466 // safe. 2467 if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue)) 2468 if (TCV->canTrap()) 2469 return false; 2470 if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue)) 2471 if (FCV->canTrap()) 2472 return false; 2473 2474 // Okay, we collected all the mapped values and checked them for sanity, and 2475 // defined to really do this transformation. First, update the CFG. 2476 TrueSucc->removePredecessor(BI->getParent()); 2477 FalseSucc->removePredecessor(BI->getParent()); 2478 2479 // Insert select instructions where needed. 2480 Value *BrCond = BI->getCondition(); 2481 if (TrueValue) { 2482 // Insert a select if the results differ. 2483 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) { 2484 } else if (isa<UndefValue>(TrueValue)) { 2485 TrueValue = FalseValue; 2486 } else { 2487 TrueValue = 2488 Builder.CreateSelect(BrCond, TrueValue, FalseValue, "retval", BI); 2489 } 2490 } 2491 2492 Value *RI = 2493 !TrueValue ? Builder.CreateRetVoid() : Builder.CreateRet(TrueValue); 2494 2495 (void)RI; 2496 2497 DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:" 2498 << "\n " << *BI << "NewRet = " << *RI 2499 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: " << *FalseSucc); 2500 2501 EraseTerminatorInstAndDCECond(BI); 2502 2503 return true; 2504 } 2505 2506 /// Return true if the given instruction is available 2507 /// in its predecessor block. If yes, the instruction will be removed. 2508 static bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB) { 2509 if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst)) 2510 return false; 2511 for (Instruction &I : *PB) { 2512 Instruction *PBI = &I; 2513 // Check whether Inst and PBI generate the same value. 2514 if (Inst->isIdenticalTo(PBI)) { 2515 Inst->replaceAllUsesWith(PBI); 2516 Inst->eraseFromParent(); 2517 return true; 2518 } 2519 } 2520 return false; 2521 } 2522 2523 /// Return true if either PBI or BI has branch weight available, and store 2524 /// the weights in {Pred|Succ}{True|False}Weight. If one of PBI and BI does 2525 /// not have branch weight, use 1:1 as its weight. 2526 static bool extractPredSuccWeights(BranchInst *PBI, BranchInst *BI, 2527 uint64_t &PredTrueWeight, 2528 uint64_t &PredFalseWeight, 2529 uint64_t &SuccTrueWeight, 2530 uint64_t &SuccFalseWeight) { 2531 bool PredHasWeights = 2532 PBI->extractProfMetadata(PredTrueWeight, PredFalseWeight); 2533 bool SuccHasWeights = 2534 BI->extractProfMetadata(SuccTrueWeight, SuccFalseWeight); 2535 if (PredHasWeights || SuccHasWeights) { 2536 if (!PredHasWeights) 2537 PredTrueWeight = PredFalseWeight = 1; 2538 if (!SuccHasWeights) 2539 SuccTrueWeight = SuccFalseWeight = 1; 2540 return true; 2541 } else { 2542 return false; 2543 } 2544 } 2545 2546 /// If this basic block is simple enough, and if a predecessor branches to us 2547 /// and one of our successors, fold the block into the predecessor and use 2548 /// logical operations to pick the right destination. 2549 bool llvm::FoldBranchToCommonDest(BranchInst *BI, unsigned BonusInstThreshold) { 2550 BasicBlock *BB = BI->getParent(); 2551 2552 Instruction *Cond = nullptr; 2553 if (BI->isConditional()) 2554 Cond = dyn_cast<Instruction>(BI->getCondition()); 2555 else { 2556 // For unconditional branch, check for a simple CFG pattern, where 2557 // BB has a single predecessor and BB's successor is also its predecessor's 2558 // successor. If such pattern exisits, check for CSE between BB and its 2559 // predecessor. 2560 if (BasicBlock *PB = BB->getSinglePredecessor()) 2561 if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator())) 2562 if (PBI->isConditional() && 2563 (BI->getSuccessor(0) == PBI->getSuccessor(0) || 2564 BI->getSuccessor(0) == PBI->getSuccessor(1))) { 2565 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) { 2566 Instruction *Curr = &*I++; 2567 if (isa<CmpInst>(Curr)) { 2568 Cond = Curr; 2569 break; 2570 } 2571 // Quit if we can't remove this instruction. 2572 if (!checkCSEInPredecessor(Curr, PB)) 2573 return false; 2574 } 2575 } 2576 2577 if (!Cond) 2578 return false; 2579 } 2580 2581 if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) || 2582 Cond->getParent() != BB || !Cond->hasOneUse()) 2583 return false; 2584 2585 // Make sure the instruction after the condition is the cond branch. 2586 BasicBlock::iterator CondIt = ++Cond->getIterator(); 2587 2588 // Ignore dbg intrinsics. 2589 while (isa<DbgInfoIntrinsic>(CondIt)) 2590 ++CondIt; 2591 2592 if (&*CondIt != BI) 2593 return false; 2594 2595 // Only allow this transformation if computing the condition doesn't involve 2596 // too many instructions and these involved instructions can be executed 2597 // unconditionally. We denote all involved instructions except the condition 2598 // as "bonus instructions", and only allow this transformation when the 2599 // number of the bonus instructions does not exceed a certain threshold. 2600 unsigned NumBonusInsts = 0; 2601 for (auto I = BB->begin(); Cond != &*I; ++I) { 2602 // Ignore dbg intrinsics. 2603 if (isa<DbgInfoIntrinsic>(I)) 2604 continue; 2605 if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(&*I)) 2606 return false; 2607 // I has only one use and can be executed unconditionally. 2608 Instruction *User = dyn_cast<Instruction>(I->user_back()); 2609 if (User == nullptr || User->getParent() != BB) 2610 return false; 2611 // I is used in the same BB. Since BI uses Cond and doesn't have more slots 2612 // to use any other instruction, User must be an instruction between next(I) 2613 // and Cond. 2614 ++NumBonusInsts; 2615 // Early exits once we reach the limit. 2616 if (NumBonusInsts > BonusInstThreshold) 2617 return false; 2618 } 2619 2620 // Cond is known to be a compare or binary operator. Check to make sure that 2621 // neither operand is a potentially-trapping constant expression. 2622 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0))) 2623 if (CE->canTrap()) 2624 return false; 2625 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1))) 2626 if (CE->canTrap()) 2627 return false; 2628 2629 // Finally, don't infinitely unroll conditional loops. 2630 BasicBlock *TrueDest = BI->getSuccessor(0); 2631 BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr; 2632 if (TrueDest == BB || FalseDest == BB) 2633 return false; 2634 2635 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) { 2636 BasicBlock *PredBlock = *PI; 2637 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator()); 2638 2639 // Check that we have two conditional branches. If there is a PHI node in 2640 // the common successor, verify that the same value flows in from both 2641 // blocks. 2642 SmallVector<PHINode *, 4> PHIs; 2643 if (!PBI || PBI->isUnconditional() || 2644 (BI->isConditional() && !SafeToMergeTerminators(BI, PBI)) || 2645 (!BI->isConditional() && 2646 !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs))) 2647 continue; 2648 2649 // Determine if the two branches share a common destination. 2650 Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd; 2651 bool InvertPredCond = false; 2652 2653 if (BI->isConditional()) { 2654 if (PBI->getSuccessor(0) == TrueDest) { 2655 Opc = Instruction::Or; 2656 } else if (PBI->getSuccessor(1) == FalseDest) { 2657 Opc = Instruction::And; 2658 } else if (PBI->getSuccessor(0) == FalseDest) { 2659 Opc = Instruction::And; 2660 InvertPredCond = true; 2661 } else if (PBI->getSuccessor(1) == TrueDest) { 2662 Opc = Instruction::Or; 2663 InvertPredCond = true; 2664 } else { 2665 continue; 2666 } 2667 } else { 2668 if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest) 2669 continue; 2670 } 2671 2672 DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB); 2673 IRBuilder<> Builder(PBI); 2674 2675 // If we need to invert the condition in the pred block to match, do so now. 2676 if (InvertPredCond) { 2677 Value *NewCond = PBI->getCondition(); 2678 2679 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) { 2680 CmpInst *CI = cast<CmpInst>(NewCond); 2681 CI->setPredicate(CI->getInversePredicate()); 2682 } else { 2683 NewCond = 2684 Builder.CreateNot(NewCond, PBI->getCondition()->getName() + ".not"); 2685 } 2686 2687 PBI->setCondition(NewCond); 2688 PBI->swapSuccessors(); 2689 } 2690 2691 // If we have bonus instructions, clone them into the predecessor block. 2692 // Note that there may be multiple predecessor blocks, so we cannot move 2693 // bonus instructions to a predecessor block. 2694 ValueToValueMapTy VMap; // maps original values to cloned values 2695 // We already make sure Cond is the last instruction before BI. Therefore, 2696 // all instructions before Cond other than DbgInfoIntrinsic are bonus 2697 // instructions. 2698 for (auto BonusInst = BB->begin(); Cond != &*BonusInst; ++BonusInst) { 2699 if (isa<DbgInfoIntrinsic>(BonusInst)) 2700 continue; 2701 Instruction *NewBonusInst = BonusInst->clone(); 2702 RemapInstruction(NewBonusInst, VMap, 2703 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals); 2704 VMap[&*BonusInst] = NewBonusInst; 2705 2706 // If we moved a load, we cannot any longer claim any knowledge about 2707 // its potential value. The previous information might have been valid 2708 // only given the branch precondition. 2709 // For an analogous reason, we must also drop all the metadata whose 2710 // semantics we don't understand. 2711 NewBonusInst->dropUnknownNonDebugMetadata(); 2712 2713 PredBlock->getInstList().insert(PBI->getIterator(), NewBonusInst); 2714 NewBonusInst->takeName(&*BonusInst); 2715 BonusInst->setName(BonusInst->getName() + ".old"); 2716 } 2717 2718 // Clone Cond into the predecessor basic block, and or/and the 2719 // two conditions together. 2720 Instruction *New = Cond->clone(); 2721 RemapInstruction(New, VMap, 2722 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals); 2723 PredBlock->getInstList().insert(PBI->getIterator(), New); 2724 New->takeName(Cond); 2725 Cond->setName(New->getName() + ".old"); 2726 2727 if (BI->isConditional()) { 2728 Instruction *NewCond = cast<Instruction>( 2729 Builder.CreateBinOp(Opc, PBI->getCondition(), New, "or.cond")); 2730 PBI->setCondition(NewCond); 2731 2732 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight; 2733 bool HasWeights = 2734 extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight, 2735 SuccTrueWeight, SuccFalseWeight); 2736 SmallVector<uint64_t, 8> NewWeights; 2737 2738 if (PBI->getSuccessor(0) == BB) { 2739 if (HasWeights) { 2740 // PBI: br i1 %x, BB, FalseDest 2741 // BI: br i1 %y, TrueDest, FalseDest 2742 // TrueWeight is TrueWeight for PBI * TrueWeight for BI. 2743 NewWeights.push_back(PredTrueWeight * SuccTrueWeight); 2744 // FalseWeight is FalseWeight for PBI * TotalWeight for BI + 2745 // TrueWeight for PBI * FalseWeight for BI. 2746 // We assume that total weights of a BranchInst can fit into 32 bits. 2747 // Therefore, we will not have overflow using 64-bit arithmetic. 2748 NewWeights.push_back(PredFalseWeight * 2749 (SuccFalseWeight + SuccTrueWeight) + 2750 PredTrueWeight * SuccFalseWeight); 2751 } 2752 AddPredecessorToBlock(TrueDest, PredBlock, BB); 2753 PBI->setSuccessor(0, TrueDest); 2754 } 2755 if (PBI->getSuccessor(1) == BB) { 2756 if (HasWeights) { 2757 // PBI: br i1 %x, TrueDest, BB 2758 // BI: br i1 %y, TrueDest, FalseDest 2759 // TrueWeight is TrueWeight for PBI * TotalWeight for BI + 2760 // FalseWeight for PBI * TrueWeight for BI. 2761 NewWeights.push_back(PredTrueWeight * 2762 (SuccFalseWeight + SuccTrueWeight) + 2763 PredFalseWeight * SuccTrueWeight); 2764 // FalseWeight is FalseWeight for PBI * FalseWeight for BI. 2765 NewWeights.push_back(PredFalseWeight * SuccFalseWeight); 2766 } 2767 AddPredecessorToBlock(FalseDest, PredBlock, BB); 2768 PBI->setSuccessor(1, FalseDest); 2769 } 2770 if (NewWeights.size() == 2) { 2771 // Halve the weights if any of them cannot fit in an uint32_t 2772 FitWeights(NewWeights); 2773 2774 SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(), 2775 NewWeights.end()); 2776 PBI->setMetadata( 2777 LLVMContext::MD_prof, 2778 MDBuilder(BI->getContext()).createBranchWeights(MDWeights)); 2779 } else 2780 PBI->setMetadata(LLVMContext::MD_prof, nullptr); 2781 } else { 2782 // Update PHI nodes in the common successors. 2783 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) { 2784 ConstantInt *PBI_C = cast<ConstantInt>( 2785 PHIs[i]->getIncomingValueForBlock(PBI->getParent())); 2786 assert(PBI_C->getType()->isIntegerTy(1)); 2787 Instruction *MergedCond = nullptr; 2788 if (PBI->getSuccessor(0) == TrueDest) { 2789 // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value) 2790 // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value) 2791 // is false: !PBI_Cond and BI_Value 2792 Instruction *NotCond = cast<Instruction>( 2793 Builder.CreateNot(PBI->getCondition(), "not.cond")); 2794 MergedCond = cast<Instruction>( 2795 Builder.CreateBinOp(Instruction::And, NotCond, New, "and.cond")); 2796 if (PBI_C->isOne()) 2797 MergedCond = cast<Instruction>(Builder.CreateBinOp( 2798 Instruction::Or, PBI->getCondition(), MergedCond, "or.cond")); 2799 } else { 2800 // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C) 2801 // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond) 2802 // is false: PBI_Cond and BI_Value 2803 MergedCond = cast<Instruction>(Builder.CreateBinOp( 2804 Instruction::And, PBI->getCondition(), New, "and.cond")); 2805 if (PBI_C->isOne()) { 2806 Instruction *NotCond = cast<Instruction>( 2807 Builder.CreateNot(PBI->getCondition(), "not.cond")); 2808 MergedCond = cast<Instruction>(Builder.CreateBinOp( 2809 Instruction::Or, NotCond, MergedCond, "or.cond")); 2810 } 2811 } 2812 // Update PHI Node. 2813 PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()), 2814 MergedCond); 2815 } 2816 // Change PBI from Conditional to Unconditional. 2817 BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI); 2818 EraseTerminatorInstAndDCECond(PBI); 2819 PBI = New_PBI; 2820 } 2821 2822 // If BI was a loop latch, it may have had associated loop metadata. 2823 // We need to copy it to the new latch, that is, PBI. 2824 if (MDNode *LoopMD = BI->getMetadata(LLVMContext::MD_loop)) 2825 PBI->setMetadata(LLVMContext::MD_loop, LoopMD); 2826 2827 // TODO: If BB is reachable from all paths through PredBlock, then we 2828 // could replace PBI's branch probabilities with BI's. 2829 2830 // Copy any debug value intrinsics into the end of PredBlock. 2831 for (Instruction &I : *BB) 2832 if (isa<DbgInfoIntrinsic>(I)) 2833 I.clone()->insertBefore(PBI); 2834 2835 return true; 2836 } 2837 return false; 2838 } 2839 2840 // If there is only one store in BB1 and BB2, return it, otherwise return 2841 // nullptr. 2842 static StoreInst *findUniqueStoreInBlocks(BasicBlock *BB1, BasicBlock *BB2) { 2843 StoreInst *S = nullptr; 2844 for (auto *BB : {BB1, BB2}) { 2845 if (!BB) 2846 continue; 2847 for (auto &I : *BB) 2848 if (auto *SI = dyn_cast<StoreInst>(&I)) { 2849 if (S) 2850 // Multiple stores seen. 2851 return nullptr; 2852 else 2853 S = SI; 2854 } 2855 } 2856 return S; 2857 } 2858 2859 static Value *ensureValueAvailableInSuccessor(Value *V, BasicBlock *BB, 2860 Value *AlternativeV = nullptr) { 2861 // PHI is going to be a PHI node that allows the value V that is defined in 2862 // BB to be referenced in BB's only successor. 2863 // 2864 // If AlternativeV is nullptr, the only value we care about in PHI is V. It 2865 // doesn't matter to us what the other operand is (it'll never get used). We 2866 // could just create a new PHI with an undef incoming value, but that could 2867 // increase register pressure if EarlyCSE/InstCombine can't fold it with some 2868 // other PHI. So here we directly look for some PHI in BB's successor with V 2869 // as an incoming operand. If we find one, we use it, else we create a new 2870 // one. 2871 // 2872 // If AlternativeV is not nullptr, we care about both incoming values in PHI. 2873 // PHI must be exactly: phi <ty> [ %BB, %V ], [ %OtherBB, %AlternativeV] 2874 // where OtherBB is the single other predecessor of BB's only successor. 2875 PHINode *PHI = nullptr; 2876 BasicBlock *Succ = BB->getSingleSuccessor(); 2877 2878 for (auto I = Succ->begin(); isa<PHINode>(I); ++I) 2879 if (cast<PHINode>(I)->getIncomingValueForBlock(BB) == V) { 2880 PHI = cast<PHINode>(I); 2881 if (!AlternativeV) 2882 break; 2883 2884 assert(std::distance(pred_begin(Succ), pred_end(Succ)) == 2); 2885 auto PredI = pred_begin(Succ); 2886 BasicBlock *OtherPredBB = *PredI == BB ? *++PredI : *PredI; 2887 if (PHI->getIncomingValueForBlock(OtherPredBB) == AlternativeV) 2888 break; 2889 PHI = nullptr; 2890 } 2891 if (PHI) 2892 return PHI; 2893 2894 // If V is not an instruction defined in BB, just return it. 2895 if (!AlternativeV && 2896 (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB)) 2897 return V; 2898 2899 PHI = PHINode::Create(V->getType(), 2, "simplifycfg.merge", &Succ->front()); 2900 PHI->addIncoming(V, BB); 2901 for (BasicBlock *PredBB : predecessors(Succ)) 2902 if (PredBB != BB) 2903 PHI->addIncoming( 2904 AlternativeV ? AlternativeV : UndefValue::get(V->getType()), PredBB); 2905 return PHI; 2906 } 2907 2908 static bool mergeConditionalStoreToAddress(BasicBlock *PTB, BasicBlock *PFB, 2909 BasicBlock *QTB, BasicBlock *QFB, 2910 BasicBlock *PostBB, Value *Address, 2911 bool InvertPCond, bool InvertQCond) { 2912 auto IsaBitcastOfPointerType = [](const Instruction &I) { 2913 return Operator::getOpcode(&I) == Instruction::BitCast && 2914 I.getType()->isPointerTy(); 2915 }; 2916 2917 // If we're not in aggressive mode, we only optimize if we have some 2918 // confidence that by optimizing we'll allow P and/or Q to be if-converted. 2919 auto IsWorthwhile = [&](BasicBlock *BB) { 2920 if (!BB) 2921 return true; 2922 // Heuristic: if the block can be if-converted/phi-folded and the 2923 // instructions inside are all cheap (arithmetic/GEPs), it's worthwhile to 2924 // thread this store. 2925 unsigned N = 0; 2926 for (auto &I : *BB) { 2927 // Cheap instructions viable for folding. 2928 if (isa<BinaryOperator>(I) || isa<GetElementPtrInst>(I) || 2929 isa<StoreInst>(I)) 2930 ++N; 2931 // Free instructions. 2932 else if (isa<TerminatorInst>(I) || isa<DbgInfoIntrinsic>(I) || 2933 IsaBitcastOfPointerType(I)) 2934 continue; 2935 else 2936 return false; 2937 } 2938 return N <= PHINodeFoldingThreshold; 2939 }; 2940 2941 if (!MergeCondStoresAggressively && 2942 (!IsWorthwhile(PTB) || !IsWorthwhile(PFB) || !IsWorthwhile(QTB) || 2943 !IsWorthwhile(QFB))) 2944 return false; 2945 2946 // For every pointer, there must be exactly two stores, one coming from 2947 // PTB or PFB, and the other from QTB or QFB. We don't support more than one 2948 // store (to any address) in PTB,PFB or QTB,QFB. 2949 // FIXME: We could relax this restriction with a bit more work and performance 2950 // testing. 2951 StoreInst *PStore = findUniqueStoreInBlocks(PTB, PFB); 2952 StoreInst *QStore = findUniqueStoreInBlocks(QTB, QFB); 2953 if (!PStore || !QStore) 2954 return false; 2955 2956 // Now check the stores are compatible. 2957 if (!QStore->isUnordered() || !PStore->isUnordered()) 2958 return false; 2959 2960 // Check that sinking the store won't cause program behavior changes. Sinking 2961 // the store out of the Q blocks won't change any behavior as we're sinking 2962 // from a block to its unconditional successor. But we're moving a store from 2963 // the P blocks down through the middle block (QBI) and past both QFB and QTB. 2964 // So we need to check that there are no aliasing loads or stores in 2965 // QBI, QTB and QFB. We also need to check there are no conflicting memory 2966 // operations between PStore and the end of its parent block. 2967 // 2968 // The ideal way to do this is to query AliasAnalysis, but we don't 2969 // preserve AA currently so that is dangerous. Be super safe and just 2970 // check there are no other memory operations at all. 2971 for (auto &I : *QFB->getSinglePredecessor()) 2972 if (I.mayReadOrWriteMemory()) 2973 return false; 2974 for (auto &I : *QFB) 2975 if (&I != QStore && I.mayReadOrWriteMemory()) 2976 return false; 2977 if (QTB) 2978 for (auto &I : *QTB) 2979 if (&I != QStore && I.mayReadOrWriteMemory()) 2980 return false; 2981 for (auto I = BasicBlock::iterator(PStore), E = PStore->getParent()->end(); 2982 I != E; ++I) 2983 if (&*I != PStore && I->mayReadOrWriteMemory()) 2984 return false; 2985 2986 // OK, we're going to sink the stores to PostBB. The store has to be 2987 // conditional though, so first create the predicate. 2988 Value *PCond = cast<BranchInst>(PFB->getSinglePredecessor()->getTerminator()) 2989 ->getCondition(); 2990 Value *QCond = cast<BranchInst>(QFB->getSinglePredecessor()->getTerminator()) 2991 ->getCondition(); 2992 2993 Value *PPHI = ensureValueAvailableInSuccessor(PStore->getValueOperand(), 2994 PStore->getParent()); 2995 Value *QPHI = ensureValueAvailableInSuccessor(QStore->getValueOperand(), 2996 QStore->getParent(), PPHI); 2997 2998 IRBuilder<> QB(&*PostBB->getFirstInsertionPt()); 2999 3000 Value *PPred = PStore->getParent() == PTB ? PCond : QB.CreateNot(PCond); 3001 Value *QPred = QStore->getParent() == QTB ? QCond : QB.CreateNot(QCond); 3002 3003 if (InvertPCond) 3004 PPred = QB.CreateNot(PPred); 3005 if (InvertQCond) 3006 QPred = QB.CreateNot(QPred); 3007 Value *CombinedPred = QB.CreateOr(PPred, QPred); 3008 3009 auto *T = 3010 SplitBlockAndInsertIfThen(CombinedPred, &*QB.GetInsertPoint(), false); 3011 QB.SetInsertPoint(T); 3012 StoreInst *SI = cast<StoreInst>(QB.CreateStore(QPHI, Address)); 3013 AAMDNodes AAMD; 3014 PStore->getAAMetadata(AAMD, /*Merge=*/false); 3015 PStore->getAAMetadata(AAMD, /*Merge=*/true); 3016 SI->setAAMetadata(AAMD); 3017 3018 QStore->eraseFromParent(); 3019 PStore->eraseFromParent(); 3020 3021 return true; 3022 } 3023 3024 static bool mergeConditionalStores(BranchInst *PBI, BranchInst *QBI) { 3025 // The intention here is to find diamonds or triangles (see below) where each 3026 // conditional block contains a store to the same address. Both of these 3027 // stores are conditional, so they can't be unconditionally sunk. But it may 3028 // be profitable to speculatively sink the stores into one merged store at the 3029 // end, and predicate the merged store on the union of the two conditions of 3030 // PBI and QBI. 3031 // 3032 // This can reduce the number of stores executed if both of the conditions are 3033 // true, and can allow the blocks to become small enough to be if-converted. 3034 // This optimization will also chain, so that ladders of test-and-set 3035 // sequences can be if-converted away. 3036 // 3037 // We only deal with simple diamonds or triangles: 3038 // 3039 // PBI or PBI or a combination of the two 3040 // / \ | \ 3041 // PTB PFB | PFB 3042 // \ / | / 3043 // QBI QBI 3044 // / \ | \ 3045 // QTB QFB | QFB 3046 // \ / | / 3047 // PostBB PostBB 3048 // 3049 // We model triangles as a type of diamond with a nullptr "true" block. 3050 // Triangles are canonicalized so that the fallthrough edge is represented by 3051 // a true condition, as in the diagram above. 3052 // 3053 BasicBlock *PTB = PBI->getSuccessor(0); 3054 BasicBlock *PFB = PBI->getSuccessor(1); 3055 BasicBlock *QTB = QBI->getSuccessor(0); 3056 BasicBlock *QFB = QBI->getSuccessor(1); 3057 BasicBlock *PostBB = QFB->getSingleSuccessor(); 3058 3059 bool InvertPCond = false, InvertQCond = false; 3060 // Canonicalize fallthroughs to the true branches. 3061 if (PFB == QBI->getParent()) { 3062 std::swap(PFB, PTB); 3063 InvertPCond = true; 3064 } 3065 if (QFB == PostBB) { 3066 std::swap(QFB, QTB); 3067 InvertQCond = true; 3068 } 3069 3070 // From this point on we can assume PTB or QTB may be fallthroughs but PFB 3071 // and QFB may not. Model fallthroughs as a nullptr block. 3072 if (PTB == QBI->getParent()) 3073 PTB = nullptr; 3074 if (QTB == PostBB) 3075 QTB = nullptr; 3076 3077 // Legality bailouts. We must have at least the non-fallthrough blocks and 3078 // the post-dominating block, and the non-fallthroughs must only have one 3079 // predecessor. 3080 auto HasOnePredAndOneSucc = [](BasicBlock *BB, BasicBlock *P, BasicBlock *S) { 3081 return BB->getSinglePredecessor() == P && BB->getSingleSuccessor() == S; 3082 }; 3083 if (!PostBB || 3084 !HasOnePredAndOneSucc(PFB, PBI->getParent(), QBI->getParent()) || 3085 !HasOnePredAndOneSucc(QFB, QBI->getParent(), PostBB)) 3086 return false; 3087 if ((PTB && !HasOnePredAndOneSucc(PTB, PBI->getParent(), QBI->getParent())) || 3088 (QTB && !HasOnePredAndOneSucc(QTB, QBI->getParent(), PostBB))) 3089 return false; 3090 if (PostBB->getNumUses() != 2 || QBI->getParent()->getNumUses() != 2) 3091 return false; 3092 3093 // OK, this is a sequence of two diamonds or triangles. 3094 // Check if there are stores in PTB or PFB that are repeated in QTB or QFB. 3095 SmallPtrSet<Value *, 4> PStoreAddresses, QStoreAddresses; 3096 for (auto *BB : {PTB, PFB}) { 3097 if (!BB) 3098 continue; 3099 for (auto &I : *BB) 3100 if (StoreInst *SI = dyn_cast<StoreInst>(&I)) 3101 PStoreAddresses.insert(SI->getPointerOperand()); 3102 } 3103 for (auto *BB : {QTB, QFB}) { 3104 if (!BB) 3105 continue; 3106 for (auto &I : *BB) 3107 if (StoreInst *SI = dyn_cast<StoreInst>(&I)) 3108 QStoreAddresses.insert(SI->getPointerOperand()); 3109 } 3110 3111 set_intersect(PStoreAddresses, QStoreAddresses); 3112 // set_intersect mutates PStoreAddresses in place. Rename it here to make it 3113 // clear what it contains. 3114 auto &CommonAddresses = PStoreAddresses; 3115 3116 bool Changed = false; 3117 for (auto *Address : CommonAddresses) 3118 Changed |= mergeConditionalStoreToAddress( 3119 PTB, PFB, QTB, QFB, PostBB, Address, InvertPCond, InvertQCond); 3120 return Changed; 3121 } 3122 3123 /// If we have a conditional branch as a predecessor of another block, 3124 /// this function tries to simplify it. We know 3125 /// that PBI and BI are both conditional branches, and BI is in one of the 3126 /// successor blocks of PBI - PBI branches to BI. 3127 static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI, 3128 const DataLayout &DL) { 3129 assert(PBI->isConditional() && BI->isConditional()); 3130 BasicBlock *BB = BI->getParent(); 3131 3132 // If this block ends with a branch instruction, and if there is a 3133 // predecessor that ends on a branch of the same condition, make 3134 // this conditional branch redundant. 3135 if (PBI->getCondition() == BI->getCondition() && 3136 PBI->getSuccessor(0) != PBI->getSuccessor(1)) { 3137 // Okay, the outcome of this conditional branch is statically 3138 // knowable. If this block had a single pred, handle specially. 3139 if (BB->getSinglePredecessor()) { 3140 // Turn this into a branch on constant. 3141 bool CondIsTrue = PBI->getSuccessor(0) == BB; 3142 BI->setCondition( 3143 ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue)); 3144 return true; // Nuke the branch on constant. 3145 } 3146 3147 // Otherwise, if there are multiple predecessors, insert a PHI that merges 3148 // in the constant and simplify the block result. Subsequent passes of 3149 // simplifycfg will thread the block. 3150 if (BlockIsSimpleEnoughToThreadThrough(BB)) { 3151 pred_iterator PB = pred_begin(BB), PE = pred_end(BB); 3152 PHINode *NewPN = PHINode::Create( 3153 Type::getInt1Ty(BB->getContext()), std::distance(PB, PE), 3154 BI->getCondition()->getName() + ".pr", &BB->front()); 3155 // Okay, we're going to insert the PHI node. Since PBI is not the only 3156 // predecessor, compute the PHI'd conditional value for all of the preds. 3157 // Any predecessor where the condition is not computable we keep symbolic. 3158 for (pred_iterator PI = PB; PI != PE; ++PI) { 3159 BasicBlock *P = *PI; 3160 if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) && PBI != BI && 3161 PBI->isConditional() && PBI->getCondition() == BI->getCondition() && 3162 PBI->getSuccessor(0) != PBI->getSuccessor(1)) { 3163 bool CondIsTrue = PBI->getSuccessor(0) == BB; 3164 NewPN->addIncoming( 3165 ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue), 3166 P); 3167 } else { 3168 NewPN->addIncoming(BI->getCondition(), P); 3169 } 3170 } 3171 3172 BI->setCondition(NewPN); 3173 return true; 3174 } 3175 } 3176 3177 if (auto *CE = dyn_cast<ConstantExpr>(BI->getCondition())) 3178 if (CE->canTrap()) 3179 return false; 3180 3181 // If both branches are conditional and both contain stores to the same 3182 // address, remove the stores from the conditionals and create a conditional 3183 // merged store at the end. 3184 if (MergeCondStores && mergeConditionalStores(PBI, BI)) 3185 return true; 3186 3187 // If this is a conditional branch in an empty block, and if any 3188 // predecessors are a conditional branch to one of our destinations, 3189 // fold the conditions into logical ops and one cond br. 3190 BasicBlock::iterator BBI = BB->begin(); 3191 // Ignore dbg intrinsics. 3192 while (isa<DbgInfoIntrinsic>(BBI)) 3193 ++BBI; 3194 if (&*BBI != BI) 3195 return false; 3196 3197 int PBIOp, BIOp; 3198 if (PBI->getSuccessor(0) == BI->getSuccessor(0)) { 3199 PBIOp = 0; 3200 BIOp = 0; 3201 } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) { 3202 PBIOp = 0; 3203 BIOp = 1; 3204 } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) { 3205 PBIOp = 1; 3206 BIOp = 0; 3207 } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) { 3208 PBIOp = 1; 3209 BIOp = 1; 3210 } else { 3211 return false; 3212 } 3213 3214 // Check to make sure that the other destination of this branch 3215 // isn't BB itself. If so, this is an infinite loop that will 3216 // keep getting unwound. 3217 if (PBI->getSuccessor(PBIOp) == BB) 3218 return false; 3219 3220 // Do not perform this transformation if it would require 3221 // insertion of a large number of select instructions. For targets 3222 // without predication/cmovs, this is a big pessimization. 3223 3224 // Also do not perform this transformation if any phi node in the common 3225 // destination block can trap when reached by BB or PBB (PR17073). In that 3226 // case, it would be unsafe to hoist the operation into a select instruction. 3227 3228 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp); 3229 unsigned NumPhis = 0; 3230 for (BasicBlock::iterator II = CommonDest->begin(); isa<PHINode>(II); 3231 ++II, ++NumPhis) { 3232 if (NumPhis > 2) // Disable this xform. 3233 return false; 3234 3235 PHINode *PN = cast<PHINode>(II); 3236 Value *BIV = PN->getIncomingValueForBlock(BB); 3237 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV)) 3238 if (CE->canTrap()) 3239 return false; 3240 3241 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent()); 3242 Value *PBIV = PN->getIncomingValue(PBBIdx); 3243 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV)) 3244 if (CE->canTrap()) 3245 return false; 3246 } 3247 3248 // Finally, if everything is ok, fold the branches to logical ops. 3249 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1); 3250 3251 DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent() 3252 << "AND: " << *BI->getParent()); 3253 3254 // If OtherDest *is* BB, then BB is a basic block with a single conditional 3255 // branch in it, where one edge (OtherDest) goes back to itself but the other 3256 // exits. We don't *know* that the program avoids the infinite loop 3257 // (even though that seems likely). If we do this xform naively, we'll end up 3258 // recursively unpeeling the loop. Since we know that (after the xform is 3259 // done) that the block *is* infinite if reached, we just make it an obviously 3260 // infinite loop with no cond branch. 3261 if (OtherDest == BB) { 3262 // Insert it at the end of the function, because it's either code, 3263 // or it won't matter if it's hot. :) 3264 BasicBlock *InfLoopBlock = 3265 BasicBlock::Create(BB->getContext(), "infloop", BB->getParent()); 3266 BranchInst::Create(InfLoopBlock, InfLoopBlock); 3267 OtherDest = InfLoopBlock; 3268 } 3269 3270 DEBUG(dbgs() << *PBI->getParent()->getParent()); 3271 3272 // BI may have other predecessors. Because of this, we leave 3273 // it alone, but modify PBI. 3274 3275 // Make sure we get to CommonDest on True&True directions. 3276 Value *PBICond = PBI->getCondition(); 3277 IRBuilder<NoFolder> Builder(PBI); 3278 if (PBIOp) 3279 PBICond = Builder.CreateNot(PBICond, PBICond->getName() + ".not"); 3280 3281 Value *BICond = BI->getCondition(); 3282 if (BIOp) 3283 BICond = Builder.CreateNot(BICond, BICond->getName() + ".not"); 3284 3285 // Merge the conditions. 3286 Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge"); 3287 3288 // Modify PBI to branch on the new condition to the new dests. 3289 PBI->setCondition(Cond); 3290 PBI->setSuccessor(0, CommonDest); 3291 PBI->setSuccessor(1, OtherDest); 3292 3293 // Update branch weight for PBI. 3294 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight; 3295 uint64_t PredCommon, PredOther, SuccCommon, SuccOther; 3296 bool HasWeights = 3297 extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight, 3298 SuccTrueWeight, SuccFalseWeight); 3299 if (HasWeights) { 3300 PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight; 3301 PredOther = PBIOp ? PredTrueWeight : PredFalseWeight; 3302 SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight; 3303 SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight; 3304 // The weight to CommonDest should be PredCommon * SuccTotal + 3305 // PredOther * SuccCommon. 3306 // The weight to OtherDest should be PredOther * SuccOther. 3307 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) + 3308 PredOther * SuccCommon, 3309 PredOther * SuccOther}; 3310 // Halve the weights if any of them cannot fit in an uint32_t 3311 FitWeights(NewWeights); 3312 3313 PBI->setMetadata(LLVMContext::MD_prof, 3314 MDBuilder(BI->getContext()) 3315 .createBranchWeights(NewWeights[0], NewWeights[1])); 3316 } 3317 3318 // OtherDest may have phi nodes. If so, add an entry from PBI's 3319 // block that are identical to the entries for BI's block. 3320 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB); 3321 3322 // We know that the CommonDest already had an edge from PBI to 3323 // it. If it has PHIs though, the PHIs may have different 3324 // entries for BB and PBI's BB. If so, insert a select to make 3325 // them agree. 3326 PHINode *PN; 3327 for (BasicBlock::iterator II = CommonDest->begin(); 3328 (PN = dyn_cast<PHINode>(II)); ++II) { 3329 Value *BIV = PN->getIncomingValueForBlock(BB); 3330 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent()); 3331 Value *PBIV = PN->getIncomingValue(PBBIdx); 3332 if (BIV != PBIV) { 3333 // Insert a select in PBI to pick the right value. 3334 SelectInst *NV = cast<SelectInst>( 3335 Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName() + ".mux")); 3336 PN->setIncomingValue(PBBIdx, NV); 3337 // Although the select has the same condition as PBI, the original branch 3338 // weights for PBI do not apply to the new select because the select's 3339 // 'logical' edges are incoming edges of the phi that is eliminated, not 3340 // the outgoing edges of PBI. 3341 if (HasWeights) { 3342 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight; 3343 uint64_t PredOther = PBIOp ? PredTrueWeight : PredFalseWeight; 3344 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight; 3345 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight; 3346 // The weight to PredCommonDest should be PredCommon * SuccTotal. 3347 // The weight to PredOtherDest should be PredOther * SuccCommon. 3348 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther), 3349 PredOther * SuccCommon}; 3350 3351 FitWeights(NewWeights); 3352 3353 NV->setMetadata(LLVMContext::MD_prof, 3354 MDBuilder(BI->getContext()) 3355 .createBranchWeights(NewWeights[0], NewWeights[1])); 3356 } 3357 } 3358 } 3359 3360 DEBUG(dbgs() << "INTO: " << *PBI->getParent()); 3361 DEBUG(dbgs() << *PBI->getParent()->getParent()); 3362 3363 // This basic block is probably dead. We know it has at least 3364 // one fewer predecessor. 3365 return true; 3366 } 3367 3368 // Simplifies a terminator by replacing it with a branch to TrueBB if Cond is 3369 // true or to FalseBB if Cond is false. 3370 // Takes care of updating the successors and removing the old terminator. 3371 // Also makes sure not to introduce new successors by assuming that edges to 3372 // non-successor TrueBBs and FalseBBs aren't reachable. 3373 static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond, 3374 BasicBlock *TrueBB, BasicBlock *FalseBB, 3375 uint32_t TrueWeight, 3376 uint32_t FalseWeight) { 3377 // Remove any superfluous successor edges from the CFG. 3378 // First, figure out which successors to preserve. 3379 // If TrueBB and FalseBB are equal, only try to preserve one copy of that 3380 // successor. 3381 BasicBlock *KeepEdge1 = TrueBB; 3382 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr; 3383 3384 // Then remove the rest. 3385 for (BasicBlock *Succ : OldTerm->successors()) { 3386 // Make sure only to keep exactly one copy of each edge. 3387 if (Succ == KeepEdge1) 3388 KeepEdge1 = nullptr; 3389 else if (Succ == KeepEdge2) 3390 KeepEdge2 = nullptr; 3391 else 3392 Succ->removePredecessor(OldTerm->getParent(), 3393 /*DontDeleteUselessPHIs=*/true); 3394 } 3395 3396 IRBuilder<> Builder(OldTerm); 3397 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc()); 3398 3399 // Insert an appropriate new terminator. 3400 if (!KeepEdge1 && !KeepEdge2) { 3401 if (TrueBB == FalseBB) 3402 // We were only looking for one successor, and it was present. 3403 // Create an unconditional branch to it. 3404 Builder.CreateBr(TrueBB); 3405 else { 3406 // We found both of the successors we were looking for. 3407 // Create a conditional branch sharing the condition of the select. 3408 BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB); 3409 if (TrueWeight != FalseWeight) 3410 NewBI->setMetadata(LLVMContext::MD_prof, 3411 MDBuilder(OldTerm->getContext()) 3412 .createBranchWeights(TrueWeight, FalseWeight)); 3413 } 3414 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) { 3415 // Neither of the selected blocks were successors, so this 3416 // terminator must be unreachable. 3417 new UnreachableInst(OldTerm->getContext(), OldTerm); 3418 } else { 3419 // One of the selected values was a successor, but the other wasn't. 3420 // Insert an unconditional branch to the one that was found; 3421 // the edge to the one that wasn't must be unreachable. 3422 if (!KeepEdge1) 3423 // Only TrueBB was found. 3424 Builder.CreateBr(TrueBB); 3425 else 3426 // Only FalseBB was found. 3427 Builder.CreateBr(FalseBB); 3428 } 3429 3430 EraseTerminatorInstAndDCECond(OldTerm); 3431 return true; 3432 } 3433 3434 // Replaces 3435 // (switch (select cond, X, Y)) on constant X, Y 3436 // with a branch - conditional if X and Y lead to distinct BBs, 3437 // unconditional otherwise. 3438 static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) { 3439 // Check for constant integer values in the select. 3440 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue()); 3441 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue()); 3442 if (!TrueVal || !FalseVal) 3443 return false; 3444 3445 // Find the relevant condition and destinations. 3446 Value *Condition = Select->getCondition(); 3447 BasicBlock *TrueBB = SI->findCaseValue(TrueVal).getCaseSuccessor(); 3448 BasicBlock *FalseBB = SI->findCaseValue(FalseVal).getCaseSuccessor(); 3449 3450 // Get weight for TrueBB and FalseBB. 3451 uint32_t TrueWeight = 0, FalseWeight = 0; 3452 SmallVector<uint64_t, 8> Weights; 3453 bool HasWeights = HasBranchWeights(SI); 3454 if (HasWeights) { 3455 GetBranchWeights(SI, Weights); 3456 if (Weights.size() == 1 + SI->getNumCases()) { 3457 TrueWeight = 3458 (uint32_t)Weights[SI->findCaseValue(TrueVal).getSuccessorIndex()]; 3459 FalseWeight = 3460 (uint32_t)Weights[SI->findCaseValue(FalseVal).getSuccessorIndex()]; 3461 } 3462 } 3463 3464 // Perform the actual simplification. 3465 return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB, TrueWeight, 3466 FalseWeight); 3467 } 3468 3469 // Replaces 3470 // (indirectbr (select cond, blockaddress(@fn, BlockA), 3471 // blockaddress(@fn, BlockB))) 3472 // with 3473 // (br cond, BlockA, BlockB). 3474 static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) { 3475 // Check that both operands of the select are block addresses. 3476 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue()); 3477 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue()); 3478 if (!TBA || !FBA) 3479 return false; 3480 3481 // Extract the actual blocks. 3482 BasicBlock *TrueBB = TBA->getBasicBlock(); 3483 BasicBlock *FalseBB = FBA->getBasicBlock(); 3484 3485 // Perform the actual simplification. 3486 return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB, 0, 3487 0); 3488 } 3489 3490 /// This is called when we find an icmp instruction 3491 /// (a seteq/setne with a constant) as the only instruction in a 3492 /// block that ends with an uncond branch. We are looking for a very specific 3493 /// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In 3494 /// this case, we merge the first two "or's of icmp" into a switch, but then the 3495 /// default value goes to an uncond block with a seteq in it, we get something 3496 /// like: 3497 /// 3498 /// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ] 3499 /// DEFAULT: 3500 /// %tmp = icmp eq i8 %A, 92 3501 /// br label %end 3502 /// end: 3503 /// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ] 3504 /// 3505 /// We prefer to split the edge to 'end' so that there is a true/false entry to 3506 /// the PHI, merging the third icmp into the switch. 3507 static bool TryToSimplifyUncondBranchWithICmpInIt( 3508 ICmpInst *ICI, IRBuilder<> &Builder, const DataLayout &DL, 3509 const TargetTransformInfo &TTI, unsigned BonusInstThreshold, 3510 AssumptionCache *AC) { 3511 BasicBlock *BB = ICI->getParent(); 3512 3513 // If the block has any PHIs in it or the icmp has multiple uses, it is too 3514 // complex. 3515 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) 3516 return false; 3517 3518 Value *V = ICI->getOperand(0); 3519 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1)); 3520 3521 // The pattern we're looking for is where our only predecessor is a switch on 3522 // 'V' and this block is the default case for the switch. In this case we can 3523 // fold the compared value into the switch to simplify things. 3524 BasicBlock *Pred = BB->getSinglePredecessor(); 3525 if (!Pred || !isa<SwitchInst>(Pred->getTerminator())) 3526 return false; 3527 3528 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator()); 3529 if (SI->getCondition() != V) 3530 return false; 3531 3532 // If BB is reachable on a non-default case, then we simply know the value of 3533 // V in this block. Substitute it and constant fold the icmp instruction 3534 // away. 3535 if (SI->getDefaultDest() != BB) { 3536 ConstantInt *VVal = SI->findCaseDest(BB); 3537 assert(VVal && "Should have a unique destination value"); 3538 ICI->setOperand(0, VVal); 3539 3540 if (Value *V = SimplifyInstruction(ICI, DL)) { 3541 ICI->replaceAllUsesWith(V); 3542 ICI->eraseFromParent(); 3543 } 3544 // BB is now empty, so it is likely to simplify away. 3545 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; 3546 } 3547 3548 // Ok, the block is reachable from the default dest. If the constant we're 3549 // comparing exists in one of the other edges, then we can constant fold ICI 3550 // and zap it. 3551 if (SI->findCaseValue(Cst) != SI->case_default()) { 3552 Value *V; 3553 if (ICI->getPredicate() == ICmpInst::ICMP_EQ) 3554 V = ConstantInt::getFalse(BB->getContext()); 3555 else 3556 V = ConstantInt::getTrue(BB->getContext()); 3557 3558 ICI->replaceAllUsesWith(V); 3559 ICI->eraseFromParent(); 3560 // BB is now empty, so it is likely to simplify away. 3561 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; 3562 } 3563 3564 // The use of the icmp has to be in the 'end' block, by the only PHI node in 3565 // the block. 3566 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0); 3567 PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back()); 3568 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() || 3569 isa<PHINode>(++BasicBlock::iterator(PHIUse))) 3570 return false; 3571 3572 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets 3573 // true in the PHI. 3574 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext()); 3575 Constant *NewCst = ConstantInt::getFalse(BB->getContext()); 3576 3577 if (ICI->getPredicate() == ICmpInst::ICMP_EQ) 3578 std::swap(DefaultCst, NewCst); 3579 3580 // Replace ICI (which is used by the PHI for the default value) with true or 3581 // false depending on if it is EQ or NE. 3582 ICI->replaceAllUsesWith(DefaultCst); 3583 ICI->eraseFromParent(); 3584 3585 // Okay, the switch goes to this block on a default value. Add an edge from 3586 // the switch to the merge point on the compared value. 3587 BasicBlock *NewBB = 3588 BasicBlock::Create(BB->getContext(), "switch.edge", BB->getParent(), BB); 3589 SmallVector<uint64_t, 8> Weights; 3590 bool HasWeights = HasBranchWeights(SI); 3591 if (HasWeights) { 3592 GetBranchWeights(SI, Weights); 3593 if (Weights.size() == 1 + SI->getNumCases()) { 3594 // Split weight for default case to case for "Cst". 3595 Weights[0] = (Weights[0] + 1) >> 1; 3596 Weights.push_back(Weights[0]); 3597 3598 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end()); 3599 SI->setMetadata( 3600 LLVMContext::MD_prof, 3601 MDBuilder(SI->getContext()).createBranchWeights(MDWeights)); 3602 } 3603 } 3604 SI->addCase(Cst, NewBB); 3605 3606 // NewBB branches to the phi block, add the uncond branch and the phi entry. 3607 Builder.SetInsertPoint(NewBB); 3608 Builder.SetCurrentDebugLocation(SI->getDebugLoc()); 3609 Builder.CreateBr(SuccBlock); 3610 PHIUse->addIncoming(NewCst, NewBB); 3611 return true; 3612 } 3613 3614 /// The specified branch is a conditional branch. 3615 /// Check to see if it is branching on an or/and chain of icmp instructions, and 3616 /// fold it into a switch instruction if so. 3617 static bool SimplifyBranchOnICmpChain(BranchInst *BI, IRBuilder<> &Builder, 3618 const DataLayout &DL) { 3619 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition()); 3620 if (!Cond) 3621 return false; 3622 3623 // Change br (X == 0 | X == 1), T, F into a switch instruction. 3624 // If this is a bunch of seteq's or'd together, or if it's a bunch of 3625 // 'setne's and'ed together, collect them. 3626 3627 // Try to gather values from a chain of and/or to be turned into a switch 3628 ConstantComparesGatherer ConstantCompare(Cond, DL); 3629 // Unpack the result 3630 SmallVectorImpl<ConstantInt *> &Values = ConstantCompare.Vals; 3631 Value *CompVal = ConstantCompare.CompValue; 3632 unsigned UsedICmps = ConstantCompare.UsedICmps; 3633 Value *ExtraCase = ConstantCompare.Extra; 3634 3635 // If we didn't have a multiply compared value, fail. 3636 if (!CompVal) 3637 return false; 3638 3639 // Avoid turning single icmps into a switch. 3640 if (UsedICmps <= 1) 3641 return false; 3642 3643 bool TrueWhenEqual = (Cond->getOpcode() == Instruction::Or); 3644 3645 // There might be duplicate constants in the list, which the switch 3646 // instruction can't handle, remove them now. 3647 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate); 3648 Values.erase(std::unique(Values.begin(), Values.end()), Values.end()); 3649 3650 // If Extra was used, we require at least two switch values to do the 3651 // transformation. A switch with one value is just a conditional branch. 3652 if (ExtraCase && Values.size() < 2) 3653 return false; 3654 3655 // TODO: Preserve branch weight metadata, similarly to how 3656 // FoldValueComparisonIntoPredecessors preserves it. 3657 3658 // Figure out which block is which destination. 3659 BasicBlock *DefaultBB = BI->getSuccessor(1); 3660 BasicBlock *EdgeBB = BI->getSuccessor(0); 3661 if (!TrueWhenEqual) 3662 std::swap(DefaultBB, EdgeBB); 3663 3664 BasicBlock *BB = BI->getParent(); 3665 3666 DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size() 3667 << " cases into SWITCH. BB is:\n" 3668 << *BB); 3669 3670 // If there are any extra values that couldn't be folded into the switch 3671 // then we evaluate them with an explicit branch first. Split the block 3672 // right before the condbr to handle it. 3673 if (ExtraCase) { 3674 BasicBlock *NewBB = 3675 BB->splitBasicBlock(BI->getIterator(), "switch.early.test"); 3676 // Remove the uncond branch added to the old block. 3677 TerminatorInst *OldTI = BB->getTerminator(); 3678 Builder.SetInsertPoint(OldTI); 3679 3680 if (TrueWhenEqual) 3681 Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB); 3682 else 3683 Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB); 3684 3685 OldTI->eraseFromParent(); 3686 3687 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them 3688 // for the edge we just added. 3689 AddPredecessorToBlock(EdgeBB, BB, NewBB); 3690 3691 DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase 3692 << "\nEXTRABB = " << *BB); 3693 BB = NewBB; 3694 } 3695 3696 Builder.SetInsertPoint(BI); 3697 // Convert pointer to int before we switch. 3698 if (CompVal->getType()->isPointerTy()) { 3699 CompVal = Builder.CreatePtrToInt( 3700 CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr"); 3701 } 3702 3703 // Create the new switch instruction now. 3704 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size()); 3705 3706 // Add all of the 'cases' to the switch instruction. 3707 for (unsigned i = 0, e = Values.size(); i != e; ++i) 3708 New->addCase(Values[i], EdgeBB); 3709 3710 // We added edges from PI to the EdgeBB. As such, if there were any 3711 // PHI nodes in EdgeBB, they need entries to be added corresponding to 3712 // the number of edges added. 3713 for (BasicBlock::iterator BBI = EdgeBB->begin(); isa<PHINode>(BBI); ++BBI) { 3714 PHINode *PN = cast<PHINode>(BBI); 3715 Value *InVal = PN->getIncomingValueForBlock(BB); 3716 for (unsigned i = 0, e = Values.size() - 1; i != e; ++i) 3717 PN->addIncoming(InVal, BB); 3718 } 3719 3720 // Erase the old branch instruction. 3721 EraseTerminatorInstAndDCECond(BI); 3722 3723 DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n'); 3724 return true; 3725 } 3726 3727 bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) { 3728 if (isa<PHINode>(RI->getValue())) 3729 return SimplifyCommonResume(RI); 3730 else if (isa<LandingPadInst>(RI->getParent()->getFirstNonPHI()) && 3731 RI->getValue() == RI->getParent()->getFirstNonPHI()) 3732 // The resume must unwind the exception that caused control to branch here. 3733 return SimplifySingleResume(RI); 3734 3735 return false; 3736 } 3737 3738 // Simplify resume that is shared by several landing pads (phi of landing pad). 3739 bool SimplifyCFGOpt::SimplifyCommonResume(ResumeInst *RI) { 3740 BasicBlock *BB = RI->getParent(); 3741 3742 // Check that there are no other instructions except for debug intrinsics 3743 // between the phi of landing pads (RI->getValue()) and resume instruction. 3744 BasicBlock::iterator I = cast<Instruction>(RI->getValue())->getIterator(), 3745 E = RI->getIterator(); 3746 while (++I != E) 3747 if (!isa<DbgInfoIntrinsic>(I)) 3748 return false; 3749 3750 SmallSet<BasicBlock *, 4> TrivialUnwindBlocks; 3751 auto *PhiLPInst = cast<PHINode>(RI->getValue()); 3752 3753 // Check incoming blocks to see if any of them are trivial. 3754 for (unsigned Idx = 0, End = PhiLPInst->getNumIncomingValues(); Idx != End; 3755 Idx++) { 3756 auto *IncomingBB = PhiLPInst->getIncomingBlock(Idx); 3757 auto *IncomingValue = PhiLPInst->getIncomingValue(Idx); 3758 3759 // If the block has other successors, we can not delete it because 3760 // it has other dependents. 3761 if (IncomingBB->getUniqueSuccessor() != BB) 3762 continue; 3763 3764 auto *LandingPad = dyn_cast<LandingPadInst>(IncomingBB->getFirstNonPHI()); 3765 // Not the landing pad that caused the control to branch here. 3766 if (IncomingValue != LandingPad) 3767 continue; 3768 3769 bool isTrivial = true; 3770 3771 I = IncomingBB->getFirstNonPHI()->getIterator(); 3772 E = IncomingBB->getTerminator()->getIterator(); 3773 while (++I != E) 3774 if (!isa<DbgInfoIntrinsic>(I)) { 3775 isTrivial = false; 3776 break; 3777 } 3778 3779 if (isTrivial) 3780 TrivialUnwindBlocks.insert(IncomingBB); 3781 } 3782 3783 // If no trivial unwind blocks, don't do any simplifications. 3784 if (TrivialUnwindBlocks.empty()) 3785 return false; 3786 3787 // Turn all invokes that unwind here into calls. 3788 for (auto *TrivialBB : TrivialUnwindBlocks) { 3789 // Blocks that will be simplified should be removed from the phi node. 3790 // Note there could be multiple edges to the resume block, and we need 3791 // to remove them all. 3792 while (PhiLPInst->getBasicBlockIndex(TrivialBB) != -1) 3793 BB->removePredecessor(TrivialBB, true); 3794 3795 for (pred_iterator PI = pred_begin(TrivialBB), PE = pred_end(TrivialBB); 3796 PI != PE;) { 3797 BasicBlock *Pred = *PI++; 3798 removeUnwindEdge(Pred); 3799 } 3800 3801 // In each SimplifyCFG run, only the current processed block can be erased. 3802 // Otherwise, it will break the iteration of SimplifyCFG pass. So instead 3803 // of erasing TrivialBB, we only remove the branch to the common resume 3804 // block so that we can later erase the resume block since it has no 3805 // predecessors. 3806 TrivialBB->getTerminator()->eraseFromParent(); 3807 new UnreachableInst(RI->getContext(), TrivialBB); 3808 } 3809 3810 // Delete the resume block if all its predecessors have been removed. 3811 if (pred_empty(BB)) 3812 BB->eraseFromParent(); 3813 3814 return !TrivialUnwindBlocks.empty(); 3815 } 3816 3817 // Simplify resume that is only used by a single (non-phi) landing pad. 3818 bool SimplifyCFGOpt::SimplifySingleResume(ResumeInst *RI) { 3819 BasicBlock *BB = RI->getParent(); 3820 LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI()); 3821 assert(RI->getValue() == LPInst && 3822 "Resume must unwind the exception that caused control to here"); 3823 3824 // Check that there are no other instructions except for debug intrinsics. 3825 BasicBlock::iterator I = LPInst->getIterator(), E = RI->getIterator(); 3826 while (++I != E) 3827 if (!isa<DbgInfoIntrinsic>(I)) 3828 return false; 3829 3830 // Turn all invokes that unwind here into calls and delete the basic block. 3831 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) { 3832 BasicBlock *Pred = *PI++; 3833 removeUnwindEdge(Pred); 3834 } 3835 3836 // The landingpad is now unreachable. Zap it. 3837 BB->eraseFromParent(); 3838 if (LoopHeaders) 3839 LoopHeaders->erase(BB); 3840 return true; 3841 } 3842 3843 static bool removeEmptyCleanup(CleanupReturnInst *RI) { 3844 // If this is a trivial cleanup pad that executes no instructions, it can be 3845 // eliminated. If the cleanup pad continues to the caller, any predecessor 3846 // that is an EH pad will be updated to continue to the caller and any 3847 // predecessor that terminates with an invoke instruction will have its invoke 3848 // instruction converted to a call instruction. If the cleanup pad being 3849 // simplified does not continue to the caller, each predecessor will be 3850 // updated to continue to the unwind destination of the cleanup pad being 3851 // simplified. 3852 BasicBlock *BB = RI->getParent(); 3853 CleanupPadInst *CPInst = RI->getCleanupPad(); 3854 if (CPInst->getParent() != BB) 3855 // This isn't an empty cleanup. 3856 return false; 3857 3858 // We cannot kill the pad if it has multiple uses. This typically arises 3859 // from unreachable basic blocks. 3860 if (!CPInst->hasOneUse()) 3861 return false; 3862 3863 // Check that there are no other instructions except for benign intrinsics. 3864 BasicBlock::iterator I = CPInst->getIterator(), E = RI->getIterator(); 3865 while (++I != E) { 3866 auto *II = dyn_cast<IntrinsicInst>(I); 3867 if (!II) 3868 return false; 3869 3870 Intrinsic::ID IntrinsicID = II->getIntrinsicID(); 3871 switch (IntrinsicID) { 3872 case Intrinsic::dbg_declare: 3873 case Intrinsic::dbg_value: 3874 case Intrinsic::lifetime_end: 3875 break; 3876 default: 3877 return false; 3878 } 3879 } 3880 3881 // If the cleanup return we are simplifying unwinds to the caller, this will 3882 // set UnwindDest to nullptr. 3883 BasicBlock *UnwindDest = RI->getUnwindDest(); 3884 Instruction *DestEHPad = UnwindDest ? UnwindDest->getFirstNonPHI() : nullptr; 3885 3886 // We're about to remove BB from the control flow. Before we do, sink any 3887 // PHINodes into the unwind destination. Doing this before changing the 3888 // control flow avoids some potentially slow checks, since we can currently 3889 // be certain that UnwindDest and BB have no common predecessors (since they 3890 // are both EH pads). 3891 if (UnwindDest) { 3892 // First, go through the PHI nodes in UnwindDest and update any nodes that 3893 // reference the block we are removing 3894 for (BasicBlock::iterator I = UnwindDest->begin(), 3895 IE = DestEHPad->getIterator(); 3896 I != IE; ++I) { 3897 PHINode *DestPN = cast<PHINode>(I); 3898 3899 int Idx = DestPN->getBasicBlockIndex(BB); 3900 // Since BB unwinds to UnwindDest, it has to be in the PHI node. 3901 assert(Idx != -1); 3902 // This PHI node has an incoming value that corresponds to a control 3903 // path through the cleanup pad we are removing. If the incoming 3904 // value is in the cleanup pad, it must be a PHINode (because we 3905 // verified above that the block is otherwise empty). Otherwise, the 3906 // value is either a constant or a value that dominates the cleanup 3907 // pad being removed. 3908 // 3909 // Because BB and UnwindDest are both EH pads, all of their 3910 // predecessors must unwind to these blocks, and since no instruction 3911 // can have multiple unwind destinations, there will be no overlap in 3912 // incoming blocks between SrcPN and DestPN. 3913 Value *SrcVal = DestPN->getIncomingValue(Idx); 3914 PHINode *SrcPN = dyn_cast<PHINode>(SrcVal); 3915 3916 // Remove the entry for the block we are deleting. 3917 DestPN->removeIncomingValue(Idx, false); 3918 3919 if (SrcPN && SrcPN->getParent() == BB) { 3920 // If the incoming value was a PHI node in the cleanup pad we are 3921 // removing, we need to merge that PHI node's incoming values into 3922 // DestPN. 3923 for (unsigned SrcIdx = 0, SrcE = SrcPN->getNumIncomingValues(); 3924 SrcIdx != SrcE; ++SrcIdx) { 3925 DestPN->addIncoming(SrcPN->getIncomingValue(SrcIdx), 3926 SrcPN->getIncomingBlock(SrcIdx)); 3927 } 3928 } else { 3929 // Otherwise, the incoming value came from above BB and 3930 // so we can just reuse it. We must associate all of BB's 3931 // predecessors with this value. 3932 for (auto *pred : predecessors(BB)) { 3933 DestPN->addIncoming(SrcVal, pred); 3934 } 3935 } 3936 } 3937 3938 // Sink any remaining PHI nodes directly into UnwindDest. 3939 Instruction *InsertPt = DestEHPad; 3940 for (BasicBlock::iterator I = BB->begin(), 3941 IE = BB->getFirstNonPHI()->getIterator(); 3942 I != IE;) { 3943 // The iterator must be incremented here because the instructions are 3944 // being moved to another block. 3945 PHINode *PN = cast<PHINode>(I++); 3946 if (PN->use_empty()) 3947 // If the PHI node has no uses, just leave it. It will be erased 3948 // when we erase BB below. 3949 continue; 3950 3951 // Otherwise, sink this PHI node into UnwindDest. 3952 // Any predecessors to UnwindDest which are not already represented 3953 // must be back edges which inherit the value from the path through 3954 // BB. In this case, the PHI value must reference itself. 3955 for (auto *pred : predecessors(UnwindDest)) 3956 if (pred != BB) 3957 PN->addIncoming(PN, pred); 3958 PN->moveBefore(InsertPt); 3959 } 3960 } 3961 3962 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) { 3963 // The iterator must be updated here because we are removing this pred. 3964 BasicBlock *PredBB = *PI++; 3965 if (UnwindDest == nullptr) { 3966 removeUnwindEdge(PredBB); 3967 } else { 3968 TerminatorInst *TI = PredBB->getTerminator(); 3969 TI->replaceUsesOfWith(BB, UnwindDest); 3970 } 3971 } 3972 3973 // The cleanup pad is now unreachable. Zap it. 3974 BB->eraseFromParent(); 3975 return true; 3976 } 3977 3978 // Try to merge two cleanuppads together. 3979 static bool mergeCleanupPad(CleanupReturnInst *RI) { 3980 // Skip any cleanuprets which unwind to caller, there is nothing to merge 3981 // with. 3982 BasicBlock *UnwindDest = RI->getUnwindDest(); 3983 if (!UnwindDest) 3984 return false; 3985 3986 // This cleanupret isn't the only predecessor of this cleanuppad, it wouldn't 3987 // be safe to merge without code duplication. 3988 if (UnwindDest->getSinglePredecessor() != RI->getParent()) 3989 return false; 3990 3991 // Verify that our cleanuppad's unwind destination is another cleanuppad. 3992 auto *SuccessorCleanupPad = dyn_cast<CleanupPadInst>(&UnwindDest->front()); 3993 if (!SuccessorCleanupPad) 3994 return false; 3995 3996 CleanupPadInst *PredecessorCleanupPad = RI->getCleanupPad(); 3997 // Replace any uses of the successor cleanupad with the predecessor pad 3998 // The only cleanuppad uses should be this cleanupret, it's cleanupret and 3999 // funclet bundle operands. 4000 SuccessorCleanupPad->replaceAllUsesWith(PredecessorCleanupPad); 4001 // Remove the old cleanuppad. 4002 SuccessorCleanupPad->eraseFromParent(); 4003 // Now, we simply replace the cleanupret with a branch to the unwind 4004 // destination. 4005 BranchInst::Create(UnwindDest, RI->getParent()); 4006 RI->eraseFromParent(); 4007 4008 return true; 4009 } 4010 4011 bool SimplifyCFGOpt::SimplifyCleanupReturn(CleanupReturnInst *RI) { 4012 // It is possible to transiantly have an undef cleanuppad operand because we 4013 // have deleted some, but not all, dead blocks. 4014 // Eventually, this block will be deleted. 4015 if (isa<UndefValue>(RI->getOperand(0))) 4016 return false; 4017 4018 if (mergeCleanupPad(RI)) 4019 return true; 4020 4021 if (removeEmptyCleanup(RI)) 4022 return true; 4023 4024 return false; 4025 } 4026 4027 bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) { 4028 BasicBlock *BB = RI->getParent(); 4029 if (!BB->getFirstNonPHIOrDbg()->isTerminator()) 4030 return false; 4031 4032 // Find predecessors that end with branches. 4033 SmallVector<BasicBlock *, 8> UncondBranchPreds; 4034 SmallVector<BranchInst *, 8> CondBranchPreds; 4035 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) { 4036 BasicBlock *P = *PI; 4037 TerminatorInst *PTI = P->getTerminator(); 4038 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) { 4039 if (BI->isUnconditional()) 4040 UncondBranchPreds.push_back(P); 4041 else 4042 CondBranchPreds.push_back(BI); 4043 } 4044 } 4045 4046 // If we found some, do the transformation! 4047 if (!UncondBranchPreds.empty() && DupRet) { 4048 while (!UncondBranchPreds.empty()) { 4049 BasicBlock *Pred = UncondBranchPreds.pop_back_val(); 4050 DEBUG(dbgs() << "FOLDING: " << *BB 4051 << "INTO UNCOND BRANCH PRED: " << *Pred); 4052 (void)FoldReturnIntoUncondBranch(RI, BB, Pred); 4053 } 4054 4055 // If we eliminated all predecessors of the block, delete the block now. 4056 if (pred_empty(BB)) { 4057 // We know there are no successors, so just nuke the block. 4058 BB->eraseFromParent(); 4059 if (LoopHeaders) 4060 LoopHeaders->erase(BB); 4061 } 4062 4063 return true; 4064 } 4065 4066 // Check out all of the conditional branches going to this return 4067 // instruction. If any of them just select between returns, change the 4068 // branch itself into a select/return pair. 4069 while (!CondBranchPreds.empty()) { 4070 BranchInst *BI = CondBranchPreds.pop_back_val(); 4071 4072 // Check to see if the non-BB successor is also a return block. 4073 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) && 4074 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) && 4075 SimplifyCondBranchToTwoReturns(BI, Builder)) 4076 return true; 4077 } 4078 return false; 4079 } 4080 4081 bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) { 4082 BasicBlock *BB = UI->getParent(); 4083 4084 bool Changed = false; 4085 4086 // If there are any instructions immediately before the unreachable that can 4087 // be removed, do so. 4088 while (UI->getIterator() != BB->begin()) { 4089 BasicBlock::iterator BBI = UI->getIterator(); 4090 --BBI; 4091 // Do not delete instructions that can have side effects which might cause 4092 // the unreachable to not be reachable; specifically, calls and volatile 4093 // operations may have this effect. 4094 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) 4095 break; 4096 4097 if (BBI->mayHaveSideEffects()) { 4098 if (auto *SI = dyn_cast<StoreInst>(BBI)) { 4099 if (SI->isVolatile()) 4100 break; 4101 } else if (auto *LI = dyn_cast<LoadInst>(BBI)) { 4102 if (LI->isVolatile()) 4103 break; 4104 } else if (auto *RMWI = dyn_cast<AtomicRMWInst>(BBI)) { 4105 if (RMWI->isVolatile()) 4106 break; 4107 } else if (auto *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) { 4108 if (CXI->isVolatile()) 4109 break; 4110 } else if (isa<CatchPadInst>(BBI)) { 4111 // A catchpad may invoke exception object constructors and such, which 4112 // in some languages can be arbitrary code, so be conservative by 4113 // default. 4114 // For CoreCLR, it just involves a type test, so can be removed. 4115 if (classifyEHPersonality(BB->getParent()->getPersonalityFn()) != 4116 EHPersonality::CoreCLR) 4117 break; 4118 } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) && 4119 !isa<LandingPadInst>(BBI)) { 4120 break; 4121 } 4122 // Note that deleting LandingPad's here is in fact okay, although it 4123 // involves a bit of subtle reasoning. If this inst is a LandingPad, 4124 // all the predecessors of this block will be the unwind edges of Invokes, 4125 // and we can therefore guarantee this block will be erased. 4126 } 4127 4128 // Delete this instruction (any uses are guaranteed to be dead) 4129 if (!BBI->use_empty()) 4130 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType())); 4131 BBI->eraseFromParent(); 4132 Changed = true; 4133 } 4134 4135 // If the unreachable instruction is the first in the block, take a gander 4136 // at all of the predecessors of this instruction, and simplify them. 4137 if (&BB->front() != UI) 4138 return Changed; 4139 4140 SmallVector<BasicBlock *, 8> Preds(pred_begin(BB), pred_end(BB)); 4141 for (unsigned i = 0, e = Preds.size(); i != e; ++i) { 4142 TerminatorInst *TI = Preds[i]->getTerminator(); 4143 IRBuilder<> Builder(TI); 4144 if (auto *BI = dyn_cast<BranchInst>(TI)) { 4145 if (BI->isUnconditional()) { 4146 if (BI->getSuccessor(0) == BB) { 4147 new UnreachableInst(TI->getContext(), TI); 4148 TI->eraseFromParent(); 4149 Changed = true; 4150 } 4151 } else { 4152 if (BI->getSuccessor(0) == BB) { 4153 Builder.CreateBr(BI->getSuccessor(1)); 4154 EraseTerminatorInstAndDCECond(BI); 4155 } else if (BI->getSuccessor(1) == BB) { 4156 Builder.CreateBr(BI->getSuccessor(0)); 4157 EraseTerminatorInstAndDCECond(BI); 4158 Changed = true; 4159 } 4160 } 4161 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) { 4162 for (auto i = SI->case_begin(), e = SI->case_end(); i != e;) { 4163 if (i.getCaseSuccessor() != BB) { 4164 ++i; 4165 continue; 4166 } 4167 BB->removePredecessor(SI->getParent()); 4168 i = SI->removeCase(i); 4169 e = SI->case_end(); 4170 Changed = true; 4171 } 4172 } else if (auto *II = dyn_cast<InvokeInst>(TI)) { 4173 if (II->getUnwindDest() == BB) { 4174 removeUnwindEdge(TI->getParent()); 4175 Changed = true; 4176 } 4177 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) { 4178 if (CSI->getUnwindDest() == BB) { 4179 removeUnwindEdge(TI->getParent()); 4180 Changed = true; 4181 continue; 4182 } 4183 4184 for (CatchSwitchInst::handler_iterator I = CSI->handler_begin(), 4185 E = CSI->handler_end(); 4186 I != E; ++I) { 4187 if (*I == BB) { 4188 CSI->removeHandler(I); 4189 --I; 4190 --E; 4191 Changed = true; 4192 } 4193 } 4194 if (CSI->getNumHandlers() == 0) { 4195 BasicBlock *CatchSwitchBB = CSI->getParent(); 4196 if (CSI->hasUnwindDest()) { 4197 // Redirect preds to the unwind dest 4198 CatchSwitchBB->replaceAllUsesWith(CSI->getUnwindDest()); 4199 } else { 4200 // Rewrite all preds to unwind to caller (or from invoke to call). 4201 SmallVector<BasicBlock *, 8> EHPreds(predecessors(CatchSwitchBB)); 4202 for (BasicBlock *EHPred : EHPreds) 4203 removeUnwindEdge(EHPred); 4204 } 4205 // The catchswitch is no longer reachable. 4206 new UnreachableInst(CSI->getContext(), CSI); 4207 CSI->eraseFromParent(); 4208 Changed = true; 4209 } 4210 } else if (isa<CleanupReturnInst>(TI)) { 4211 new UnreachableInst(TI->getContext(), TI); 4212 TI->eraseFromParent(); 4213 Changed = true; 4214 } 4215 } 4216 4217 // If this block is now dead, remove it. 4218 if (pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) { 4219 // We know there are no successors, so just nuke the block. 4220 BB->eraseFromParent(); 4221 if (LoopHeaders) 4222 LoopHeaders->erase(BB); 4223 return true; 4224 } 4225 4226 return Changed; 4227 } 4228 4229 static bool CasesAreContiguous(SmallVectorImpl<ConstantInt *> &Cases) { 4230 assert(Cases.size() >= 1); 4231 4232 array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate); 4233 for (size_t I = 1, E = Cases.size(); I != E; ++I) { 4234 if (Cases[I - 1]->getValue() != Cases[I]->getValue() + 1) 4235 return false; 4236 } 4237 return true; 4238 } 4239 4240 /// Turn a switch with two reachable destinations into an integer range 4241 /// comparison and branch. 4242 static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) { 4243 assert(SI->getNumCases() > 1 && "Degenerate switch?"); 4244 4245 bool HasDefault = 4246 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg()); 4247 4248 // Partition the cases into two sets with different destinations. 4249 BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr; 4250 BasicBlock *DestB = nullptr; 4251 SmallVector<ConstantInt *, 16> CasesA; 4252 SmallVector<ConstantInt *, 16> CasesB; 4253 4254 for (SwitchInst::CaseIt I : SI->cases()) { 4255 BasicBlock *Dest = I.getCaseSuccessor(); 4256 if (!DestA) 4257 DestA = Dest; 4258 if (Dest == DestA) { 4259 CasesA.push_back(I.getCaseValue()); 4260 continue; 4261 } 4262 if (!DestB) 4263 DestB = Dest; 4264 if (Dest == DestB) { 4265 CasesB.push_back(I.getCaseValue()); 4266 continue; 4267 } 4268 return false; // More than two destinations. 4269 } 4270 4271 assert(DestA && DestB && 4272 "Single-destination switch should have been folded."); 4273 assert(DestA != DestB); 4274 assert(DestB != SI->getDefaultDest()); 4275 assert(!CasesB.empty() && "There must be non-default cases."); 4276 assert(!CasesA.empty() || HasDefault); 4277 4278 // Figure out if one of the sets of cases form a contiguous range. 4279 SmallVectorImpl<ConstantInt *> *ContiguousCases = nullptr; 4280 BasicBlock *ContiguousDest = nullptr; 4281 BasicBlock *OtherDest = nullptr; 4282 if (!CasesA.empty() && CasesAreContiguous(CasesA)) { 4283 ContiguousCases = &CasesA; 4284 ContiguousDest = DestA; 4285 OtherDest = DestB; 4286 } else if (CasesAreContiguous(CasesB)) { 4287 ContiguousCases = &CasesB; 4288 ContiguousDest = DestB; 4289 OtherDest = DestA; 4290 } else 4291 return false; 4292 4293 // Start building the compare and branch. 4294 4295 Constant *Offset = ConstantExpr::getNeg(ContiguousCases->back()); 4296 Constant *NumCases = 4297 ConstantInt::get(Offset->getType(), ContiguousCases->size()); 4298 4299 Value *Sub = SI->getCondition(); 4300 if (!Offset->isNullValue()) 4301 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off"); 4302 4303 Value *Cmp; 4304 // If NumCases overflowed, then all possible values jump to the successor. 4305 if (NumCases->isNullValue() && !ContiguousCases->empty()) 4306 Cmp = ConstantInt::getTrue(SI->getContext()); 4307 else 4308 Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch"); 4309 BranchInst *NewBI = Builder.CreateCondBr(Cmp, ContiguousDest, OtherDest); 4310 4311 // Update weight for the newly-created conditional branch. 4312 if (HasBranchWeights(SI)) { 4313 SmallVector<uint64_t, 8> Weights; 4314 GetBranchWeights(SI, Weights); 4315 if (Weights.size() == 1 + SI->getNumCases()) { 4316 uint64_t TrueWeight = 0; 4317 uint64_t FalseWeight = 0; 4318 for (size_t I = 0, E = Weights.size(); I != E; ++I) { 4319 if (SI->getSuccessor(I) == ContiguousDest) 4320 TrueWeight += Weights[I]; 4321 else 4322 FalseWeight += Weights[I]; 4323 } 4324 while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) { 4325 TrueWeight /= 2; 4326 FalseWeight /= 2; 4327 } 4328 NewBI->setMetadata(LLVMContext::MD_prof, 4329 MDBuilder(SI->getContext()) 4330 .createBranchWeights((uint32_t)TrueWeight, 4331 (uint32_t)FalseWeight)); 4332 } 4333 } 4334 4335 // Prune obsolete incoming values off the successors' PHI nodes. 4336 for (auto BBI = ContiguousDest->begin(); isa<PHINode>(BBI); ++BBI) { 4337 unsigned PreviousEdges = ContiguousCases->size(); 4338 if (ContiguousDest == SI->getDefaultDest()) 4339 ++PreviousEdges; 4340 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I) 4341 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent()); 4342 } 4343 for (auto BBI = OtherDest->begin(); isa<PHINode>(BBI); ++BBI) { 4344 unsigned PreviousEdges = SI->getNumCases() - ContiguousCases->size(); 4345 if (OtherDest == SI->getDefaultDest()) 4346 ++PreviousEdges; 4347 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I) 4348 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent()); 4349 } 4350 4351 // Drop the switch. 4352 SI->eraseFromParent(); 4353 4354 return true; 4355 } 4356 4357 /// Compute masked bits for the condition of a switch 4358 /// and use it to remove dead cases. 4359 static bool EliminateDeadSwitchCases(SwitchInst *SI, AssumptionCache *AC, 4360 const DataLayout &DL) { 4361 Value *Cond = SI->getCondition(); 4362 unsigned Bits = Cond->getType()->getIntegerBitWidth(); 4363 APInt KnownZero(Bits, 0), KnownOne(Bits, 0); 4364 computeKnownBits(Cond, KnownZero, KnownOne, DL, 0, AC, SI); 4365 4366 // We can also eliminate cases by determining that their values are outside of 4367 // the limited range of the condition based on how many significant (non-sign) 4368 // bits are in the condition value. 4369 unsigned ExtraSignBits = ComputeNumSignBits(Cond, DL, 0, AC, SI) - 1; 4370 unsigned MaxSignificantBitsInCond = Bits - ExtraSignBits; 4371 4372 // Gather dead cases. 4373 SmallVector<ConstantInt *, 8> DeadCases; 4374 for (auto &Case : SI->cases()) { 4375 APInt CaseVal = Case.getCaseValue()->getValue(); 4376 if ((CaseVal & KnownZero) != 0 || (CaseVal & KnownOne) != KnownOne || 4377 (CaseVal.getMinSignedBits() > MaxSignificantBitsInCond)) { 4378 DeadCases.push_back(Case.getCaseValue()); 4379 DEBUG(dbgs() << "SimplifyCFG: switch case " << CaseVal << " is dead.\n"); 4380 } 4381 } 4382 4383 // If we can prove that the cases must cover all possible values, the 4384 // default destination becomes dead and we can remove it. If we know some 4385 // of the bits in the value, we can use that to more precisely compute the 4386 // number of possible unique case values. 4387 bool HasDefault = 4388 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg()); 4389 const unsigned NumUnknownBits = 4390 Bits - (KnownZero | KnownOne).countPopulation(); 4391 assert(NumUnknownBits <= Bits); 4392 if (HasDefault && DeadCases.empty() && 4393 NumUnknownBits < 64 /* avoid overflow */ && 4394 SI->getNumCases() == (1ULL << NumUnknownBits)) { 4395 DEBUG(dbgs() << "SimplifyCFG: switch default is dead.\n"); 4396 BasicBlock *NewDefault = 4397 SplitBlockPredecessors(SI->getDefaultDest(), SI->getParent(), ""); 4398 SI->setDefaultDest(&*NewDefault); 4399 SplitBlock(&*NewDefault, &NewDefault->front()); 4400 auto *OldTI = NewDefault->getTerminator(); 4401 new UnreachableInst(SI->getContext(), OldTI); 4402 EraseTerminatorInstAndDCECond(OldTI); 4403 return true; 4404 } 4405 4406 SmallVector<uint64_t, 8> Weights; 4407 bool HasWeight = HasBranchWeights(SI); 4408 if (HasWeight) { 4409 GetBranchWeights(SI, Weights); 4410 HasWeight = (Weights.size() == 1 + SI->getNumCases()); 4411 } 4412 4413 // Remove dead cases from the switch. 4414 for (ConstantInt *DeadCase : DeadCases) { 4415 SwitchInst::CaseIt Case = SI->findCaseValue(DeadCase); 4416 assert(Case != SI->case_default() && 4417 "Case was not found. Probably mistake in DeadCases forming."); 4418 if (HasWeight) { 4419 std::swap(Weights[Case.getCaseIndex() + 1], Weights.back()); 4420 Weights.pop_back(); 4421 } 4422 4423 // Prune unused values from PHI nodes. 4424 Case.getCaseSuccessor()->removePredecessor(SI->getParent()); 4425 SI->removeCase(Case); 4426 } 4427 if (HasWeight && Weights.size() >= 2) { 4428 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end()); 4429 SI->setMetadata(LLVMContext::MD_prof, 4430 MDBuilder(SI->getParent()->getContext()) 4431 .createBranchWeights(MDWeights)); 4432 } 4433 4434 return !DeadCases.empty(); 4435 } 4436 4437 /// If BB would be eligible for simplification by 4438 /// TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated 4439 /// by an unconditional branch), look at the phi node for BB in the successor 4440 /// block and see if the incoming value is equal to CaseValue. If so, return 4441 /// the phi node, and set PhiIndex to BB's index in the phi node. 4442 static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue, 4443 BasicBlock *BB, int *PhiIndex) { 4444 if (BB->getFirstNonPHIOrDbg() != BB->getTerminator()) 4445 return nullptr; // BB must be empty to be a candidate for simplification. 4446 if (!BB->getSinglePredecessor()) 4447 return nullptr; // BB must be dominated by the switch. 4448 4449 BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator()); 4450 if (!Branch || !Branch->isUnconditional()) 4451 return nullptr; // Terminator must be unconditional branch. 4452 4453 BasicBlock *Succ = Branch->getSuccessor(0); 4454 4455 BasicBlock::iterator I = Succ->begin(); 4456 while (PHINode *PHI = dyn_cast<PHINode>(I++)) { 4457 int Idx = PHI->getBasicBlockIndex(BB); 4458 assert(Idx >= 0 && "PHI has no entry for predecessor?"); 4459 4460 Value *InValue = PHI->getIncomingValue(Idx); 4461 if (InValue != CaseValue) 4462 continue; 4463 4464 *PhiIndex = Idx; 4465 return PHI; 4466 } 4467 4468 return nullptr; 4469 } 4470 4471 /// Try to forward the condition of a switch instruction to a phi node 4472 /// dominated by the switch, if that would mean that some of the destination 4473 /// blocks of the switch can be folded away. 4474 /// Returns true if a change is made. 4475 static bool ForwardSwitchConditionToPHI(SwitchInst *SI) { 4476 typedef DenseMap<PHINode *, SmallVector<int, 4>> ForwardingNodesMap; 4477 ForwardingNodesMap ForwardingNodes; 4478 4479 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; 4480 ++I) { 4481 ConstantInt *CaseValue = I.getCaseValue(); 4482 BasicBlock *CaseDest = I.getCaseSuccessor(); 4483 4484 int PhiIndex; 4485 PHINode *PHI = 4486 FindPHIForConditionForwarding(CaseValue, CaseDest, &PhiIndex); 4487 if (!PHI) 4488 continue; 4489 4490 ForwardingNodes[PHI].push_back(PhiIndex); 4491 } 4492 4493 bool Changed = false; 4494 4495 for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(), 4496 E = ForwardingNodes.end(); 4497 I != E; ++I) { 4498 PHINode *Phi = I->first; 4499 SmallVectorImpl<int> &Indexes = I->second; 4500 4501 if (Indexes.size() < 2) 4502 continue; 4503 4504 for (size_t I = 0, E = Indexes.size(); I != E; ++I) 4505 Phi->setIncomingValue(Indexes[I], SI->getCondition()); 4506 Changed = true; 4507 } 4508 4509 return Changed; 4510 } 4511 4512 /// Return true if the backend will be able to handle 4513 /// initializing an array of constants like C. 4514 static bool ValidLookupTableConstant(Constant *C, const TargetTransformInfo &TTI) { 4515 if (C->isThreadDependent()) 4516 return false; 4517 if (C->isDLLImportDependent()) 4518 return false; 4519 4520 if (!isa<ConstantFP>(C) && !isa<ConstantInt>(C) && 4521 !isa<ConstantPointerNull>(C) && !isa<GlobalValue>(C) && 4522 !isa<UndefValue>(C) && !isa<ConstantExpr>(C)) 4523 return false; 4524 4525 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 4526 if (!CE->isGEPWithNoNotionalOverIndexing()) 4527 return false; 4528 if (!ValidLookupTableConstant(CE->getOperand(0), TTI)) 4529 return false; 4530 } 4531 4532 if (!TTI.shouldBuildLookupTablesForConstant(C)) 4533 return false; 4534 4535 return true; 4536 } 4537 4538 /// If V is a Constant, return it. Otherwise, try to look up 4539 /// its constant value in ConstantPool, returning 0 if it's not there. 4540 static Constant * 4541 LookupConstant(Value *V, 4542 const SmallDenseMap<Value *, Constant *> &ConstantPool) { 4543 if (Constant *C = dyn_cast<Constant>(V)) 4544 return C; 4545 return ConstantPool.lookup(V); 4546 } 4547 4548 /// Try to fold instruction I into a constant. This works for 4549 /// simple instructions such as binary operations where both operands are 4550 /// constant or can be replaced by constants from the ConstantPool. Returns the 4551 /// resulting constant on success, 0 otherwise. 4552 static Constant * 4553 ConstantFold(Instruction *I, const DataLayout &DL, 4554 const SmallDenseMap<Value *, Constant *> &ConstantPool) { 4555 if (SelectInst *Select = dyn_cast<SelectInst>(I)) { 4556 Constant *A = LookupConstant(Select->getCondition(), ConstantPool); 4557 if (!A) 4558 return nullptr; 4559 if (A->isAllOnesValue()) 4560 return LookupConstant(Select->getTrueValue(), ConstantPool); 4561 if (A->isNullValue()) 4562 return LookupConstant(Select->getFalseValue(), ConstantPool); 4563 return nullptr; 4564 } 4565 4566 SmallVector<Constant *, 4> COps; 4567 for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) { 4568 if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool)) 4569 COps.push_back(A); 4570 else 4571 return nullptr; 4572 } 4573 4574 if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) { 4575 return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0], 4576 COps[1], DL); 4577 } 4578 4579 return ConstantFoldInstOperands(I, COps, DL); 4580 } 4581 4582 /// Try to determine the resulting constant values in phi nodes 4583 /// at the common destination basic block, *CommonDest, for one of the case 4584 /// destionations CaseDest corresponding to value CaseVal (0 for the default 4585 /// case), of a switch instruction SI. 4586 static bool 4587 GetCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest, 4588 BasicBlock **CommonDest, 4589 SmallVectorImpl<std::pair<PHINode *, Constant *>> &Res, 4590 const DataLayout &DL, const TargetTransformInfo &TTI) { 4591 // The block from which we enter the common destination. 4592 BasicBlock *Pred = SI->getParent(); 4593 4594 // If CaseDest is empty except for some side-effect free instructions through 4595 // which we can constant-propagate the CaseVal, continue to its successor. 4596 SmallDenseMap<Value *, Constant *> ConstantPool; 4597 ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal)); 4598 for (BasicBlock::iterator I = CaseDest->begin(), E = CaseDest->end(); I != E; 4599 ++I) { 4600 if (TerminatorInst *T = dyn_cast<TerminatorInst>(I)) { 4601 // If the terminator is a simple branch, continue to the next block. 4602 if (T->getNumSuccessors() != 1 || T->isExceptional()) 4603 return false; 4604 Pred = CaseDest; 4605 CaseDest = T->getSuccessor(0); 4606 } else if (isa<DbgInfoIntrinsic>(I)) { 4607 // Skip debug intrinsic. 4608 continue; 4609 } else if (Constant *C = ConstantFold(&*I, DL, ConstantPool)) { 4610 // Instruction is side-effect free and constant. 4611 4612 // If the instruction has uses outside this block or a phi node slot for 4613 // the block, it is not safe to bypass the instruction since it would then 4614 // no longer dominate all its uses. 4615 for (auto &Use : I->uses()) { 4616 User *User = Use.getUser(); 4617 if (Instruction *I = dyn_cast<Instruction>(User)) 4618 if (I->getParent() == CaseDest) 4619 continue; 4620 if (PHINode *Phi = dyn_cast<PHINode>(User)) 4621 if (Phi->getIncomingBlock(Use) == CaseDest) 4622 continue; 4623 return false; 4624 } 4625 4626 ConstantPool.insert(std::make_pair(&*I, C)); 4627 } else { 4628 break; 4629 } 4630 } 4631 4632 // If we did not have a CommonDest before, use the current one. 4633 if (!*CommonDest) 4634 *CommonDest = CaseDest; 4635 // If the destination isn't the common one, abort. 4636 if (CaseDest != *CommonDest) 4637 return false; 4638 4639 // Get the values for this case from phi nodes in the destination block. 4640 BasicBlock::iterator I = (*CommonDest)->begin(); 4641 while (PHINode *PHI = dyn_cast<PHINode>(I++)) { 4642 int Idx = PHI->getBasicBlockIndex(Pred); 4643 if (Idx == -1) 4644 continue; 4645 4646 Constant *ConstVal = 4647 LookupConstant(PHI->getIncomingValue(Idx), ConstantPool); 4648 if (!ConstVal) 4649 return false; 4650 4651 // Be conservative about which kinds of constants we support. 4652 if (!ValidLookupTableConstant(ConstVal, TTI)) 4653 return false; 4654 4655 Res.push_back(std::make_pair(PHI, ConstVal)); 4656 } 4657 4658 return Res.size() > 0; 4659 } 4660 4661 // Helper function used to add CaseVal to the list of cases that generate 4662 // Result. 4663 static void MapCaseToResult(ConstantInt *CaseVal, 4664 SwitchCaseResultVectorTy &UniqueResults, 4665 Constant *Result) { 4666 for (auto &I : UniqueResults) { 4667 if (I.first == Result) { 4668 I.second.push_back(CaseVal); 4669 return; 4670 } 4671 } 4672 UniqueResults.push_back( 4673 std::make_pair(Result, SmallVector<ConstantInt *, 4>(1, CaseVal))); 4674 } 4675 4676 // Helper function that initializes a map containing 4677 // results for the PHI node of the common destination block for a switch 4678 // instruction. Returns false if multiple PHI nodes have been found or if 4679 // there is not a common destination block for the switch. 4680 static bool InitializeUniqueCases(SwitchInst *SI, PHINode *&PHI, 4681 BasicBlock *&CommonDest, 4682 SwitchCaseResultVectorTy &UniqueResults, 4683 Constant *&DefaultResult, 4684 const DataLayout &DL, 4685 const TargetTransformInfo &TTI) { 4686 for (auto &I : SI->cases()) { 4687 ConstantInt *CaseVal = I.getCaseValue(); 4688 4689 // Resulting value at phi nodes for this case value. 4690 SwitchCaseResultsTy Results; 4691 if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results, 4692 DL, TTI)) 4693 return false; 4694 4695 // Only one value per case is permitted 4696 if (Results.size() > 1) 4697 return false; 4698 MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second); 4699 4700 // Check the PHI consistency. 4701 if (!PHI) 4702 PHI = Results[0].first; 4703 else if (PHI != Results[0].first) 4704 return false; 4705 } 4706 // Find the default result value. 4707 SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults; 4708 BasicBlock *DefaultDest = SI->getDefaultDest(); 4709 GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults, 4710 DL, TTI); 4711 // If the default value is not found abort unless the default destination 4712 // is unreachable. 4713 DefaultResult = 4714 DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr; 4715 if ((!DefaultResult && 4716 !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg()))) 4717 return false; 4718 4719 return true; 4720 } 4721 4722 // Helper function that checks if it is possible to transform a switch with only 4723 // two cases (or two cases + default) that produces a result into a select. 4724 // Example: 4725 // switch (a) { 4726 // case 10: %0 = icmp eq i32 %a, 10 4727 // return 10; %1 = select i1 %0, i32 10, i32 4 4728 // case 20: ----> %2 = icmp eq i32 %a, 20 4729 // return 2; %3 = select i1 %2, i32 2, i32 %1 4730 // default: 4731 // return 4; 4732 // } 4733 static Value *ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector, 4734 Constant *DefaultResult, Value *Condition, 4735 IRBuilder<> &Builder) { 4736 assert(ResultVector.size() == 2 && 4737 "We should have exactly two unique results at this point"); 4738 // If we are selecting between only two cases transform into a simple 4739 // select or a two-way select if default is possible. 4740 if (ResultVector[0].second.size() == 1 && 4741 ResultVector[1].second.size() == 1) { 4742 ConstantInt *const FirstCase = ResultVector[0].second[0]; 4743 ConstantInt *const SecondCase = ResultVector[1].second[0]; 4744 4745 bool DefaultCanTrigger = DefaultResult; 4746 Value *SelectValue = ResultVector[1].first; 4747 if (DefaultCanTrigger) { 4748 Value *const ValueCompare = 4749 Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp"); 4750 SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first, 4751 DefaultResult, "switch.select"); 4752 } 4753 Value *const ValueCompare = 4754 Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp"); 4755 return Builder.CreateSelect(ValueCompare, ResultVector[0].first, 4756 SelectValue, "switch.select"); 4757 } 4758 4759 return nullptr; 4760 } 4761 4762 // Helper function to cleanup a switch instruction that has been converted into 4763 // a select, fixing up PHI nodes and basic blocks. 4764 static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI, 4765 Value *SelectValue, 4766 IRBuilder<> &Builder) { 4767 BasicBlock *SelectBB = SI->getParent(); 4768 while (PHI->getBasicBlockIndex(SelectBB) >= 0) 4769 PHI->removeIncomingValue(SelectBB); 4770 PHI->addIncoming(SelectValue, SelectBB); 4771 4772 Builder.CreateBr(PHI->getParent()); 4773 4774 // Remove the switch. 4775 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) { 4776 BasicBlock *Succ = SI->getSuccessor(i); 4777 4778 if (Succ == PHI->getParent()) 4779 continue; 4780 Succ->removePredecessor(SelectBB); 4781 } 4782 SI->eraseFromParent(); 4783 } 4784 4785 /// If the switch is only used to initialize one or more 4786 /// phi nodes in a common successor block with only two different 4787 /// constant values, replace the switch with select. 4788 static bool SwitchToSelect(SwitchInst *SI, IRBuilder<> &Builder, 4789 AssumptionCache *AC, const DataLayout &DL, 4790 const TargetTransformInfo &TTI) { 4791 Value *const Cond = SI->getCondition(); 4792 PHINode *PHI = nullptr; 4793 BasicBlock *CommonDest = nullptr; 4794 Constant *DefaultResult; 4795 SwitchCaseResultVectorTy UniqueResults; 4796 // Collect all the cases that will deliver the same value from the switch. 4797 if (!InitializeUniqueCases(SI, PHI, CommonDest, UniqueResults, DefaultResult, 4798 DL, TTI)) 4799 return false; 4800 // Selects choose between maximum two values. 4801 if (UniqueResults.size() != 2) 4802 return false; 4803 assert(PHI != nullptr && "PHI for value select not found"); 4804 4805 Builder.SetInsertPoint(SI); 4806 Value *SelectValue = 4807 ConvertTwoCaseSwitch(UniqueResults, DefaultResult, Cond, Builder); 4808 if (SelectValue) { 4809 RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder); 4810 return true; 4811 } 4812 // The switch couldn't be converted into a select. 4813 return false; 4814 } 4815 4816 namespace { 4817 4818 /// This class represents a lookup table that can be used to replace a switch. 4819 class SwitchLookupTable { 4820 public: 4821 /// Create a lookup table to use as a switch replacement with the contents 4822 /// of Values, using DefaultValue to fill any holes in the table. 4823 SwitchLookupTable( 4824 Module &M, uint64_t TableSize, ConstantInt *Offset, 4825 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values, 4826 Constant *DefaultValue, const DataLayout &DL); 4827 4828 /// Build instructions with Builder to retrieve the value at 4829 /// the position given by Index in the lookup table. 4830 Value *BuildLookup(Value *Index, IRBuilder<> &Builder); 4831 4832 /// Return true if a table with TableSize elements of 4833 /// type ElementType would fit in a target-legal register. 4834 static bool WouldFitInRegister(const DataLayout &DL, uint64_t TableSize, 4835 Type *ElementType); 4836 4837 private: 4838 // Depending on the contents of the table, it can be represented in 4839 // different ways. 4840 enum { 4841 // For tables where each element contains the same value, we just have to 4842 // store that single value and return it for each lookup. 4843 SingleValueKind, 4844 4845 // For tables where there is a linear relationship between table index 4846 // and values. We calculate the result with a simple multiplication 4847 // and addition instead of a table lookup. 4848 LinearMapKind, 4849 4850 // For small tables with integer elements, we can pack them into a bitmap 4851 // that fits into a target-legal register. Values are retrieved by 4852 // shift and mask operations. 4853 BitMapKind, 4854 4855 // The table is stored as an array of values. Values are retrieved by load 4856 // instructions from the table. 4857 ArrayKind 4858 } Kind; 4859 4860 // For SingleValueKind, this is the single value. 4861 Constant *SingleValue; 4862 4863 // For BitMapKind, this is the bitmap. 4864 ConstantInt *BitMap; 4865 IntegerType *BitMapElementTy; 4866 4867 // For LinearMapKind, these are the constants used to derive the value. 4868 ConstantInt *LinearOffset; 4869 ConstantInt *LinearMultiplier; 4870 4871 // For ArrayKind, this is the array. 4872 GlobalVariable *Array; 4873 }; 4874 4875 } // end anonymous namespace 4876 4877 SwitchLookupTable::SwitchLookupTable( 4878 Module &M, uint64_t TableSize, ConstantInt *Offset, 4879 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values, 4880 Constant *DefaultValue, const DataLayout &DL) 4881 : SingleValue(nullptr), BitMap(nullptr), BitMapElementTy(nullptr), 4882 LinearOffset(nullptr), LinearMultiplier(nullptr), Array(nullptr) { 4883 assert(Values.size() && "Can't build lookup table without values!"); 4884 assert(TableSize >= Values.size() && "Can't fit values in table!"); 4885 4886 // If all values in the table are equal, this is that value. 4887 SingleValue = Values.begin()->second; 4888 4889 Type *ValueType = Values.begin()->second->getType(); 4890 4891 // Build up the table contents. 4892 SmallVector<Constant *, 64> TableContents(TableSize); 4893 for (size_t I = 0, E = Values.size(); I != E; ++I) { 4894 ConstantInt *CaseVal = Values[I].first; 4895 Constant *CaseRes = Values[I].second; 4896 assert(CaseRes->getType() == ValueType); 4897 4898 uint64_t Idx = (CaseVal->getValue() - Offset->getValue()).getLimitedValue(); 4899 TableContents[Idx] = CaseRes; 4900 4901 if (CaseRes != SingleValue) 4902 SingleValue = nullptr; 4903 } 4904 4905 // Fill in any holes in the table with the default result. 4906 if (Values.size() < TableSize) { 4907 assert(DefaultValue && 4908 "Need a default value to fill the lookup table holes."); 4909 assert(DefaultValue->getType() == ValueType); 4910 for (uint64_t I = 0; I < TableSize; ++I) { 4911 if (!TableContents[I]) 4912 TableContents[I] = DefaultValue; 4913 } 4914 4915 if (DefaultValue != SingleValue) 4916 SingleValue = nullptr; 4917 } 4918 4919 // If each element in the table contains the same value, we only need to store 4920 // that single value. 4921 if (SingleValue) { 4922 Kind = SingleValueKind; 4923 return; 4924 } 4925 4926 // Check if we can derive the value with a linear transformation from the 4927 // table index. 4928 if (isa<IntegerType>(ValueType)) { 4929 bool LinearMappingPossible = true; 4930 APInt PrevVal; 4931 APInt DistToPrev; 4932 assert(TableSize >= 2 && "Should be a SingleValue table."); 4933 // Check if there is the same distance between two consecutive values. 4934 for (uint64_t I = 0; I < TableSize; ++I) { 4935 ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]); 4936 if (!ConstVal) { 4937 // This is an undef. We could deal with it, but undefs in lookup tables 4938 // are very seldom. It's probably not worth the additional complexity. 4939 LinearMappingPossible = false; 4940 break; 4941 } 4942 APInt Val = ConstVal->getValue(); 4943 if (I != 0) { 4944 APInt Dist = Val - PrevVal; 4945 if (I == 1) { 4946 DistToPrev = Dist; 4947 } else if (Dist != DistToPrev) { 4948 LinearMappingPossible = false; 4949 break; 4950 } 4951 } 4952 PrevVal = Val; 4953 } 4954 if (LinearMappingPossible) { 4955 LinearOffset = cast<ConstantInt>(TableContents[0]); 4956 LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev); 4957 Kind = LinearMapKind; 4958 ++NumLinearMaps; 4959 return; 4960 } 4961 } 4962 4963 // If the type is integer and the table fits in a register, build a bitmap. 4964 if (WouldFitInRegister(DL, TableSize, ValueType)) { 4965 IntegerType *IT = cast<IntegerType>(ValueType); 4966 APInt TableInt(TableSize * IT->getBitWidth(), 0); 4967 for (uint64_t I = TableSize; I > 0; --I) { 4968 TableInt <<= IT->getBitWidth(); 4969 // Insert values into the bitmap. Undef values are set to zero. 4970 if (!isa<UndefValue>(TableContents[I - 1])) { 4971 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]); 4972 TableInt |= Val->getValue().zext(TableInt.getBitWidth()); 4973 } 4974 } 4975 BitMap = ConstantInt::get(M.getContext(), TableInt); 4976 BitMapElementTy = IT; 4977 Kind = BitMapKind; 4978 ++NumBitMaps; 4979 return; 4980 } 4981 4982 // Store the table in an array. 4983 ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize); 4984 Constant *Initializer = ConstantArray::get(ArrayTy, TableContents); 4985 4986 Array = new GlobalVariable(M, ArrayTy, /*constant=*/true, 4987 GlobalVariable::PrivateLinkage, Initializer, 4988 "switch.table"); 4989 Array->setUnnamedAddr(GlobalValue::UnnamedAddr::Global); 4990 Kind = ArrayKind; 4991 } 4992 4993 Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) { 4994 switch (Kind) { 4995 case SingleValueKind: 4996 return SingleValue; 4997 case LinearMapKind: { 4998 // Derive the result value from the input value. 4999 Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(), 5000 false, "switch.idx.cast"); 5001 if (!LinearMultiplier->isOne()) 5002 Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult"); 5003 if (!LinearOffset->isZero()) 5004 Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset"); 5005 return Result; 5006 } 5007 case BitMapKind: { 5008 // Type of the bitmap (e.g. i59). 5009 IntegerType *MapTy = BitMap->getType(); 5010 5011 // Cast Index to the same type as the bitmap. 5012 // Note: The Index is <= the number of elements in the table, so 5013 // truncating it to the width of the bitmask is safe. 5014 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast"); 5015 5016 // Multiply the shift amount by the element width. 5017 ShiftAmt = Builder.CreateMul( 5018 ShiftAmt, ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()), 5019 "switch.shiftamt"); 5020 5021 // Shift down. 5022 Value *DownShifted = 5023 Builder.CreateLShr(BitMap, ShiftAmt, "switch.downshift"); 5024 // Mask off. 5025 return Builder.CreateTrunc(DownShifted, BitMapElementTy, "switch.masked"); 5026 } 5027 case ArrayKind: { 5028 // Make sure the table index will not overflow when treated as signed. 5029 IntegerType *IT = cast<IntegerType>(Index->getType()); 5030 uint64_t TableSize = 5031 Array->getInitializer()->getType()->getArrayNumElements(); 5032 if (TableSize > (1ULL << (IT->getBitWidth() - 1))) 5033 Index = Builder.CreateZExt( 5034 Index, IntegerType::get(IT->getContext(), IT->getBitWidth() + 1), 5035 "switch.tableidx.zext"); 5036 5037 Value *GEPIndices[] = {Builder.getInt32(0), Index}; 5038 Value *GEP = Builder.CreateInBoundsGEP(Array->getValueType(), Array, 5039 GEPIndices, "switch.gep"); 5040 return Builder.CreateLoad(GEP, "switch.load"); 5041 } 5042 } 5043 llvm_unreachable("Unknown lookup table kind!"); 5044 } 5045 5046 bool SwitchLookupTable::WouldFitInRegister(const DataLayout &DL, 5047 uint64_t TableSize, 5048 Type *ElementType) { 5049 auto *IT = dyn_cast<IntegerType>(ElementType); 5050 if (!IT) 5051 return false; 5052 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values 5053 // are <= 15, we could try to narrow the type. 5054 5055 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width. 5056 if (TableSize >= UINT_MAX / IT->getBitWidth()) 5057 return false; 5058 return DL.fitsInLegalInteger(TableSize * IT->getBitWidth()); 5059 } 5060 5061 /// Determine whether a lookup table should be built for this switch, based on 5062 /// the number of cases, size of the table, and the types of the results. 5063 static bool 5064 ShouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize, 5065 const TargetTransformInfo &TTI, const DataLayout &DL, 5066 const SmallDenseMap<PHINode *, Type *> &ResultTypes) { 5067 if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10) 5068 return false; // TableSize overflowed, or mul below might overflow. 5069 5070 bool AllTablesFitInRegister = true; 5071 bool HasIllegalType = false; 5072 for (const auto &I : ResultTypes) { 5073 Type *Ty = I.second; 5074 5075 // Saturate this flag to true. 5076 HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty); 5077 5078 // Saturate this flag to false. 5079 AllTablesFitInRegister = 5080 AllTablesFitInRegister && 5081 SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty); 5082 5083 // If both flags saturate, we're done. NOTE: This *only* works with 5084 // saturating flags, and all flags have to saturate first due to the 5085 // non-deterministic behavior of iterating over a dense map. 5086 if (HasIllegalType && !AllTablesFitInRegister) 5087 break; 5088 } 5089 5090 // If each table would fit in a register, we should build it anyway. 5091 if (AllTablesFitInRegister) 5092 return true; 5093 5094 // Don't build a table that doesn't fit in-register if it has illegal types. 5095 if (HasIllegalType) 5096 return false; 5097 5098 // The table density should be at least 40%. This is the same criterion as for 5099 // jump tables, see SelectionDAGBuilder::handleJTSwitchCase. 5100 // FIXME: Find the best cut-off. 5101 return SI->getNumCases() * 10 >= TableSize * 4; 5102 } 5103 5104 /// Try to reuse the switch table index compare. Following pattern: 5105 /// \code 5106 /// if (idx < tablesize) 5107 /// r = table[idx]; // table does not contain default_value 5108 /// else 5109 /// r = default_value; 5110 /// if (r != default_value) 5111 /// ... 5112 /// \endcode 5113 /// Is optimized to: 5114 /// \code 5115 /// cond = idx < tablesize; 5116 /// if (cond) 5117 /// r = table[idx]; 5118 /// else 5119 /// r = default_value; 5120 /// if (cond) 5121 /// ... 5122 /// \endcode 5123 /// Jump threading will then eliminate the second if(cond). 5124 static void reuseTableCompare( 5125 User *PhiUser, BasicBlock *PhiBlock, BranchInst *RangeCheckBranch, 5126 Constant *DefaultValue, 5127 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values) { 5128 5129 ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser); 5130 if (!CmpInst) 5131 return; 5132 5133 // We require that the compare is in the same block as the phi so that jump 5134 // threading can do its work afterwards. 5135 if (CmpInst->getParent() != PhiBlock) 5136 return; 5137 5138 Constant *CmpOp1 = dyn_cast<Constant>(CmpInst->getOperand(1)); 5139 if (!CmpOp1) 5140 return; 5141 5142 Value *RangeCmp = RangeCheckBranch->getCondition(); 5143 Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType()); 5144 Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType()); 5145 5146 // Check if the compare with the default value is constant true or false. 5147 Constant *DefaultConst = ConstantExpr::getICmp(CmpInst->getPredicate(), 5148 DefaultValue, CmpOp1, true); 5149 if (DefaultConst != TrueConst && DefaultConst != FalseConst) 5150 return; 5151 5152 // Check if the compare with the case values is distinct from the default 5153 // compare result. 5154 for (auto ValuePair : Values) { 5155 Constant *CaseConst = ConstantExpr::getICmp(CmpInst->getPredicate(), 5156 ValuePair.second, CmpOp1, true); 5157 if (!CaseConst || CaseConst == DefaultConst) 5158 return; 5159 assert((CaseConst == TrueConst || CaseConst == FalseConst) && 5160 "Expect true or false as compare result."); 5161 } 5162 5163 // Check if the branch instruction dominates the phi node. It's a simple 5164 // dominance check, but sufficient for our needs. 5165 // Although this check is invariant in the calling loops, it's better to do it 5166 // at this late stage. Practically we do it at most once for a switch. 5167 BasicBlock *BranchBlock = RangeCheckBranch->getParent(); 5168 for (auto PI = pred_begin(PhiBlock), E = pred_end(PhiBlock); PI != E; ++PI) { 5169 BasicBlock *Pred = *PI; 5170 if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock) 5171 return; 5172 } 5173 5174 if (DefaultConst == FalseConst) { 5175 // The compare yields the same result. We can replace it. 5176 CmpInst->replaceAllUsesWith(RangeCmp); 5177 ++NumTableCmpReuses; 5178 } else { 5179 // The compare yields the same result, just inverted. We can replace it. 5180 Value *InvertedTableCmp = BinaryOperator::CreateXor( 5181 RangeCmp, ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp", 5182 RangeCheckBranch); 5183 CmpInst->replaceAllUsesWith(InvertedTableCmp); 5184 ++NumTableCmpReuses; 5185 } 5186 } 5187 5188 /// If the switch is only used to initialize one or more phi nodes in a common 5189 /// successor block with different constant values, replace the switch with 5190 /// lookup tables. 5191 static bool SwitchToLookupTable(SwitchInst *SI, IRBuilder<> &Builder, 5192 const DataLayout &DL, 5193 const TargetTransformInfo &TTI) { 5194 assert(SI->getNumCases() > 1 && "Degenerate switch?"); 5195 5196 // Only build lookup table when we have a target that supports it. 5197 if (!TTI.shouldBuildLookupTables()) 5198 return false; 5199 5200 // FIXME: If the switch is too sparse for a lookup table, perhaps we could 5201 // split off a dense part and build a lookup table for that. 5202 5203 // FIXME: This creates arrays of GEPs to constant strings, which means each 5204 // GEP needs a runtime relocation in PIC code. We should just build one big 5205 // string and lookup indices into that. 5206 5207 // Ignore switches with less than three cases. Lookup tables will not make 5208 // them 5209 // faster, so we don't analyze them. 5210 if (SI->getNumCases() < 3) 5211 return false; 5212 5213 // Figure out the corresponding result for each case value and phi node in the 5214 // common destination, as well as the min and max case values. 5215 assert(SI->case_begin() != SI->case_end()); 5216 SwitchInst::CaseIt CI = SI->case_begin(); 5217 ConstantInt *MinCaseVal = CI.getCaseValue(); 5218 ConstantInt *MaxCaseVal = CI.getCaseValue(); 5219 5220 BasicBlock *CommonDest = nullptr; 5221 typedef SmallVector<std::pair<ConstantInt *, Constant *>, 4> ResultListTy; 5222 SmallDenseMap<PHINode *, ResultListTy> ResultLists; 5223 SmallDenseMap<PHINode *, Constant *> DefaultResults; 5224 SmallDenseMap<PHINode *, Type *> ResultTypes; 5225 SmallVector<PHINode *, 4> PHIs; 5226 5227 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) { 5228 ConstantInt *CaseVal = CI.getCaseValue(); 5229 if (CaseVal->getValue().slt(MinCaseVal->getValue())) 5230 MinCaseVal = CaseVal; 5231 if (CaseVal->getValue().sgt(MaxCaseVal->getValue())) 5232 MaxCaseVal = CaseVal; 5233 5234 // Resulting value at phi nodes for this case value. 5235 typedef SmallVector<std::pair<PHINode *, Constant *>, 4> ResultsTy; 5236 ResultsTy Results; 5237 if (!GetCaseResults(SI, CaseVal, CI.getCaseSuccessor(), &CommonDest, 5238 Results, DL, TTI)) 5239 return false; 5240 5241 // Append the result from this case to the list for each phi. 5242 for (const auto &I : Results) { 5243 PHINode *PHI = I.first; 5244 Constant *Value = I.second; 5245 if (!ResultLists.count(PHI)) 5246 PHIs.push_back(PHI); 5247 ResultLists[PHI].push_back(std::make_pair(CaseVal, Value)); 5248 } 5249 } 5250 5251 // Keep track of the result types. 5252 for (PHINode *PHI : PHIs) { 5253 ResultTypes[PHI] = ResultLists[PHI][0].second->getType(); 5254 } 5255 5256 uint64_t NumResults = ResultLists[PHIs[0]].size(); 5257 APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue(); 5258 uint64_t TableSize = RangeSpread.getLimitedValue() + 1; 5259 bool TableHasHoles = (NumResults < TableSize); 5260 5261 // If the table has holes, we need a constant result for the default case 5262 // or a bitmask that fits in a register. 5263 SmallVector<std::pair<PHINode *, Constant *>, 4> DefaultResultsList; 5264 bool HasDefaultResults = 5265 GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, 5266 DefaultResultsList, DL, TTI); 5267 5268 bool NeedMask = (TableHasHoles && !HasDefaultResults); 5269 if (NeedMask) { 5270 // As an extra penalty for the validity test we require more cases. 5271 if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark). 5272 return false; 5273 if (!DL.fitsInLegalInteger(TableSize)) 5274 return false; 5275 } 5276 5277 for (const auto &I : DefaultResultsList) { 5278 PHINode *PHI = I.first; 5279 Constant *Result = I.second; 5280 DefaultResults[PHI] = Result; 5281 } 5282 5283 if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes)) 5284 return false; 5285 5286 // Create the BB that does the lookups. 5287 Module &Mod = *CommonDest->getParent()->getParent(); 5288 BasicBlock *LookupBB = BasicBlock::Create( 5289 Mod.getContext(), "switch.lookup", CommonDest->getParent(), CommonDest); 5290 5291 // Compute the table index value. 5292 Builder.SetInsertPoint(SI); 5293 Value *TableIndex = 5294 Builder.CreateSub(SI->getCondition(), MinCaseVal, "switch.tableidx"); 5295 5296 // Compute the maximum table size representable by the integer type we are 5297 // switching upon. 5298 unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits(); 5299 uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize; 5300 assert(MaxTableSize >= TableSize && 5301 "It is impossible for a switch to have more entries than the max " 5302 "representable value of its input integer type's size."); 5303 5304 // If the default destination is unreachable, or if the lookup table covers 5305 // all values of the conditional variable, branch directly to the lookup table 5306 // BB. Otherwise, check that the condition is within the case range. 5307 const bool DefaultIsReachable = 5308 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg()); 5309 const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize); 5310 BranchInst *RangeCheckBranch = nullptr; 5311 5312 if (!DefaultIsReachable || GeneratingCoveredLookupTable) { 5313 Builder.CreateBr(LookupBB); 5314 // Note: We call removeProdecessor later since we need to be able to get the 5315 // PHI value for the default case in case we're using a bit mask. 5316 } else { 5317 Value *Cmp = Builder.CreateICmpULT( 5318 TableIndex, ConstantInt::get(MinCaseVal->getType(), TableSize)); 5319 RangeCheckBranch = 5320 Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest()); 5321 } 5322 5323 // Populate the BB that does the lookups. 5324 Builder.SetInsertPoint(LookupBB); 5325 5326 if (NeedMask) { 5327 // Before doing the lookup we do the hole check. 5328 // The LookupBB is therefore re-purposed to do the hole check 5329 // and we create a new LookupBB. 5330 BasicBlock *MaskBB = LookupBB; 5331 MaskBB->setName("switch.hole_check"); 5332 LookupBB = BasicBlock::Create(Mod.getContext(), "switch.lookup", 5333 CommonDest->getParent(), CommonDest); 5334 5335 // Make the mask's bitwidth at least 8bit and a power-of-2 to avoid 5336 // unnecessary illegal types. 5337 uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL)); 5338 APInt MaskInt(TableSizePowOf2, 0); 5339 APInt One(TableSizePowOf2, 1); 5340 // Build bitmask; fill in a 1 bit for every case. 5341 const ResultListTy &ResultList = ResultLists[PHIs[0]]; 5342 for (size_t I = 0, E = ResultList.size(); I != E; ++I) { 5343 uint64_t Idx = (ResultList[I].first->getValue() - MinCaseVal->getValue()) 5344 .getLimitedValue(); 5345 MaskInt |= One << Idx; 5346 } 5347 ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt); 5348 5349 // Get the TableIndex'th bit of the bitmask. 5350 // If this bit is 0 (meaning hole) jump to the default destination, 5351 // else continue with table lookup. 5352 IntegerType *MapTy = TableMask->getType(); 5353 Value *MaskIndex = 5354 Builder.CreateZExtOrTrunc(TableIndex, MapTy, "switch.maskindex"); 5355 Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex, "switch.shifted"); 5356 Value *LoBit = Builder.CreateTrunc( 5357 Shifted, Type::getInt1Ty(Mod.getContext()), "switch.lobit"); 5358 Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest()); 5359 5360 Builder.SetInsertPoint(LookupBB); 5361 AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent()); 5362 } 5363 5364 if (!DefaultIsReachable || GeneratingCoveredLookupTable) { 5365 // We cached PHINodes in PHIs, to avoid accessing deleted PHINodes later, 5366 // do not delete PHINodes here. 5367 SI->getDefaultDest()->removePredecessor(SI->getParent(), 5368 /*DontDeleteUselessPHIs=*/true); 5369 } 5370 5371 bool ReturnedEarly = false; 5372 for (size_t I = 0, E = PHIs.size(); I != E; ++I) { 5373 PHINode *PHI = PHIs[I]; 5374 const ResultListTy &ResultList = ResultLists[PHI]; 5375 5376 // If using a bitmask, use any value to fill the lookup table holes. 5377 Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI]; 5378 SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL); 5379 5380 Value *Result = Table.BuildLookup(TableIndex, Builder); 5381 5382 // If the result is used to return immediately from the function, we want to 5383 // do that right here. 5384 if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) && 5385 PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) { 5386 Builder.CreateRet(Result); 5387 ReturnedEarly = true; 5388 break; 5389 } 5390 5391 // Do a small peephole optimization: re-use the switch table compare if 5392 // possible. 5393 if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) { 5394 BasicBlock *PhiBlock = PHI->getParent(); 5395 // Search for compare instructions which use the phi. 5396 for (auto *User : PHI->users()) { 5397 reuseTableCompare(User, PhiBlock, RangeCheckBranch, DV, ResultList); 5398 } 5399 } 5400 5401 PHI->addIncoming(Result, LookupBB); 5402 } 5403 5404 if (!ReturnedEarly) 5405 Builder.CreateBr(CommonDest); 5406 5407 // Remove the switch. 5408 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) { 5409 BasicBlock *Succ = SI->getSuccessor(i); 5410 5411 if (Succ == SI->getDefaultDest()) 5412 continue; 5413 Succ->removePredecessor(SI->getParent()); 5414 } 5415 SI->eraseFromParent(); 5416 5417 ++NumLookupTables; 5418 if (NeedMask) 5419 ++NumLookupTablesHoles; 5420 return true; 5421 } 5422 5423 static bool isSwitchDense(ArrayRef<int64_t> Values) { 5424 // See also SelectionDAGBuilder::isDense(), which this function was based on. 5425 uint64_t Diff = (uint64_t)Values.back() - (uint64_t)Values.front(); 5426 uint64_t Range = Diff + 1; 5427 uint64_t NumCases = Values.size(); 5428 // 40% is the default density for building a jump table in optsize/minsize mode. 5429 uint64_t MinDensity = 40; 5430 5431 return NumCases * 100 >= Range * MinDensity; 5432 } 5433 5434 // Try and transform a switch that has "holes" in it to a contiguous sequence 5435 // of cases. 5436 // 5437 // A switch such as: switch(i) {case 5: case 9: case 13: case 17:} can be 5438 // range-reduced to: switch ((i-5) / 4) {case 0: case 1: case 2: case 3:}. 5439 // 5440 // This converts a sparse switch into a dense switch which allows better 5441 // lowering and could also allow transforming into a lookup table. 5442 static bool ReduceSwitchRange(SwitchInst *SI, IRBuilder<> &Builder, 5443 const DataLayout &DL, 5444 const TargetTransformInfo &TTI) { 5445 auto *CondTy = cast<IntegerType>(SI->getCondition()->getType()); 5446 if (CondTy->getIntegerBitWidth() > 64 || 5447 !DL.fitsInLegalInteger(CondTy->getIntegerBitWidth())) 5448 return false; 5449 // Only bother with this optimization if there are more than 3 switch cases; 5450 // SDAG will only bother creating jump tables for 4 or more cases. 5451 if (SI->getNumCases() < 4) 5452 return false; 5453 5454 // This transform is agnostic to the signedness of the input or case values. We 5455 // can treat the case values as signed or unsigned. We can optimize more common 5456 // cases such as a sequence crossing zero {-4,0,4,8} if we interpret case values 5457 // as signed. 5458 SmallVector<int64_t,4> Values; 5459 for (auto &C : SI->cases()) 5460 Values.push_back(C.getCaseValue()->getValue().getSExtValue()); 5461 std::sort(Values.begin(), Values.end()); 5462 5463 // If the switch is already dense, there's nothing useful to do here. 5464 if (isSwitchDense(Values)) 5465 return false; 5466 5467 // First, transform the values such that they start at zero and ascend. 5468 int64_t Base = Values[0]; 5469 for (auto &V : Values) 5470 V -= Base; 5471 5472 // Now we have signed numbers that have been shifted so that, given enough 5473 // precision, there are no negative values. Since the rest of the transform 5474 // is bitwise only, we switch now to an unsigned representation. 5475 uint64_t GCD = 0; 5476 for (auto &V : Values) 5477 GCD = GreatestCommonDivisor64(GCD, (uint64_t)V); 5478 5479 // This transform can be done speculatively because it is so cheap - it results 5480 // in a single rotate operation being inserted. This can only happen if the 5481 // factor extracted is a power of 2. 5482 // FIXME: If the GCD is an odd number we can multiply by the multiplicative 5483 // inverse of GCD and then perform this transform. 5484 // FIXME: It's possible that optimizing a switch on powers of two might also 5485 // be beneficial - flag values are often powers of two and we could use a CLZ 5486 // as the key function. 5487 if (GCD <= 1 || !isPowerOf2_64(GCD)) 5488 // No common divisor found or too expensive to compute key function. 5489 return false; 5490 5491 unsigned Shift = Log2_64(GCD); 5492 for (auto &V : Values) 5493 V = (int64_t)((uint64_t)V >> Shift); 5494 5495 if (!isSwitchDense(Values)) 5496 // Transform didn't create a dense switch. 5497 return false; 5498 5499 // The obvious transform is to shift the switch condition right and emit a 5500 // check that the condition actually cleanly divided by GCD, i.e. 5501 // C & (1 << Shift - 1) == 0 5502 // inserting a new CFG edge to handle the case where it didn't divide cleanly. 5503 // 5504 // A cheaper way of doing this is a simple ROTR(C, Shift). This performs the 5505 // shift and puts the shifted-off bits in the uppermost bits. If any of these 5506 // are nonzero then the switch condition will be very large and will hit the 5507 // default case. 5508 5509 auto *Ty = cast<IntegerType>(SI->getCondition()->getType()); 5510 Builder.SetInsertPoint(SI); 5511 auto *ShiftC = ConstantInt::get(Ty, Shift); 5512 auto *Sub = Builder.CreateSub(SI->getCondition(), ConstantInt::get(Ty, Base)); 5513 auto *LShr = Builder.CreateLShr(Sub, ShiftC); 5514 auto *Shl = Builder.CreateShl(Sub, Ty->getBitWidth() - Shift); 5515 auto *Rot = Builder.CreateOr(LShr, Shl); 5516 SI->replaceUsesOfWith(SI->getCondition(), Rot); 5517 5518 for (SwitchInst::CaseIt C = SI->case_begin(), E = SI->case_end(); C != E; 5519 ++C) { 5520 auto *Orig = C.getCaseValue(); 5521 auto Sub = Orig->getValue() - APInt(Ty->getBitWidth(), Base); 5522 C.setValue( 5523 cast<ConstantInt>(ConstantInt::get(Ty, Sub.lshr(ShiftC->getValue())))); 5524 } 5525 return true; 5526 } 5527 5528 bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) { 5529 BasicBlock *BB = SI->getParent(); 5530 5531 if (isValueEqualityComparison(SI)) { 5532 // If we only have one predecessor, and if it is a branch on this value, 5533 // see if that predecessor totally determines the outcome of this switch. 5534 if (BasicBlock *OnlyPred = BB->getSinglePredecessor()) 5535 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder)) 5536 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; 5537 5538 Value *Cond = SI->getCondition(); 5539 if (SelectInst *Select = dyn_cast<SelectInst>(Cond)) 5540 if (SimplifySwitchOnSelect(SI, Select)) 5541 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; 5542 5543 // If the block only contains the switch, see if we can fold the block 5544 // away into any preds. 5545 BasicBlock::iterator BBI = BB->begin(); 5546 // Ignore dbg intrinsics. 5547 while (isa<DbgInfoIntrinsic>(BBI)) 5548 ++BBI; 5549 if (SI == &*BBI) 5550 if (FoldValueComparisonIntoPredecessors(SI, Builder)) 5551 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; 5552 } 5553 5554 // Try to transform the switch into an icmp and a branch. 5555 if (TurnSwitchRangeIntoICmp(SI, Builder)) 5556 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; 5557 5558 // Remove unreachable cases. 5559 if (EliminateDeadSwitchCases(SI, AC, DL)) 5560 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; 5561 5562 if (SwitchToSelect(SI, Builder, AC, DL, TTI)) 5563 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; 5564 5565 if (ForwardSwitchConditionToPHI(SI)) 5566 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; 5567 5568 // The conversion from switch to lookup tables results in difficult 5569 // to analyze code and makes pruning branches much harder. 5570 // This is a problem of the switch expression itself can still be 5571 // restricted as a result of inlining or CVP. There only apply this 5572 // transformation during late steps of the optimisation chain. 5573 if (LateSimplifyCFG && SwitchToLookupTable(SI, Builder, DL, TTI)) 5574 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; 5575 5576 if (ReduceSwitchRange(SI, Builder, DL, TTI)) 5577 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; 5578 5579 return false; 5580 } 5581 5582 bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) { 5583 BasicBlock *BB = IBI->getParent(); 5584 bool Changed = false; 5585 5586 // Eliminate redundant destinations. 5587 SmallPtrSet<Value *, 8> Succs; 5588 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) { 5589 BasicBlock *Dest = IBI->getDestination(i); 5590 if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) { 5591 Dest->removePredecessor(BB); 5592 IBI->removeDestination(i); 5593 --i; 5594 --e; 5595 Changed = true; 5596 } 5597 } 5598 5599 if (IBI->getNumDestinations() == 0) { 5600 // If the indirectbr has no successors, change it to unreachable. 5601 new UnreachableInst(IBI->getContext(), IBI); 5602 EraseTerminatorInstAndDCECond(IBI); 5603 return true; 5604 } 5605 5606 if (IBI->getNumDestinations() == 1) { 5607 // If the indirectbr has one successor, change it to a direct branch. 5608 BranchInst::Create(IBI->getDestination(0), IBI); 5609 EraseTerminatorInstAndDCECond(IBI); 5610 return true; 5611 } 5612 5613 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) { 5614 if (SimplifyIndirectBrOnSelect(IBI, SI)) 5615 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; 5616 } 5617 return Changed; 5618 } 5619 5620 /// Given an block with only a single landing pad and a unconditional branch 5621 /// try to find another basic block which this one can be merged with. This 5622 /// handles cases where we have multiple invokes with unique landing pads, but 5623 /// a shared handler. 5624 /// 5625 /// We specifically choose to not worry about merging non-empty blocks 5626 /// here. That is a PRE/scheduling problem and is best solved elsewhere. In 5627 /// practice, the optimizer produces empty landing pad blocks quite frequently 5628 /// when dealing with exception dense code. (see: instcombine, gvn, if-else 5629 /// sinking in this file) 5630 /// 5631 /// This is primarily a code size optimization. We need to avoid performing 5632 /// any transform which might inhibit optimization (such as our ability to 5633 /// specialize a particular handler via tail commoning). We do this by not 5634 /// merging any blocks which require us to introduce a phi. Since the same 5635 /// values are flowing through both blocks, we don't loose any ability to 5636 /// specialize. If anything, we make such specialization more likely. 5637 /// 5638 /// TODO - This transformation could remove entries from a phi in the target 5639 /// block when the inputs in the phi are the same for the two blocks being 5640 /// merged. In some cases, this could result in removal of the PHI entirely. 5641 static bool TryToMergeLandingPad(LandingPadInst *LPad, BranchInst *BI, 5642 BasicBlock *BB) { 5643 auto Succ = BB->getUniqueSuccessor(); 5644 assert(Succ); 5645 // If there's a phi in the successor block, we'd likely have to introduce 5646 // a phi into the merged landing pad block. 5647 if (isa<PHINode>(*Succ->begin())) 5648 return false; 5649 5650 for (BasicBlock *OtherPred : predecessors(Succ)) { 5651 if (BB == OtherPred) 5652 continue; 5653 BasicBlock::iterator I = OtherPred->begin(); 5654 LandingPadInst *LPad2 = dyn_cast<LandingPadInst>(I); 5655 if (!LPad2 || !LPad2->isIdenticalTo(LPad)) 5656 continue; 5657 for (++I; isa<DbgInfoIntrinsic>(I); ++I) { 5658 } 5659 BranchInst *BI2 = dyn_cast<BranchInst>(I); 5660 if (!BI2 || !BI2->isIdenticalTo(BI)) 5661 continue; 5662 5663 // We've found an identical block. Update our predecessors to take that 5664 // path instead and make ourselves dead. 5665 SmallSet<BasicBlock *, 16> Preds; 5666 Preds.insert(pred_begin(BB), pred_end(BB)); 5667 for (BasicBlock *Pred : Preds) { 5668 InvokeInst *II = cast<InvokeInst>(Pred->getTerminator()); 5669 assert(II->getNormalDest() != BB && II->getUnwindDest() == BB && 5670 "unexpected successor"); 5671 II->setUnwindDest(OtherPred); 5672 } 5673 5674 // The debug info in OtherPred doesn't cover the merged control flow that 5675 // used to go through BB. We need to delete it or update it. 5676 for (auto I = OtherPred->begin(), E = OtherPred->end(); I != E;) { 5677 Instruction &Inst = *I; 5678 I++; 5679 if (isa<DbgInfoIntrinsic>(Inst)) 5680 Inst.eraseFromParent(); 5681 } 5682 5683 SmallSet<BasicBlock *, 16> Succs; 5684 Succs.insert(succ_begin(BB), succ_end(BB)); 5685 for (BasicBlock *Succ : Succs) { 5686 Succ->removePredecessor(BB); 5687 } 5688 5689 IRBuilder<> Builder(BI); 5690 Builder.CreateUnreachable(); 5691 BI->eraseFromParent(); 5692 return true; 5693 } 5694 return false; 5695 } 5696 5697 bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI, 5698 IRBuilder<> &Builder) { 5699 BasicBlock *BB = BI->getParent(); 5700 5701 if (SinkCommon && SinkThenElseCodeToEnd(BI)) 5702 return true; 5703 5704 // If the Terminator is the only non-phi instruction, simplify the block. 5705 // if LoopHeader is provided, check if the block is a loop header 5706 // (This is for early invocations before loop simplify and vectorization 5707 // to keep canonical loop forms for nested loops. 5708 // These blocks can be eliminated when the pass is invoked later 5709 // in the back-end.) 5710 BasicBlock::iterator I = BB->getFirstNonPHIOrDbg()->getIterator(); 5711 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() && 5712 (!LoopHeaders || !LoopHeaders->count(BB)) && 5713 TryToSimplifyUncondBranchFromEmptyBlock(BB)) 5714 return true; 5715 5716 // If the only instruction in the block is a seteq/setne comparison 5717 // against a constant, try to simplify the block. 5718 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) 5719 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) { 5720 for (++I; isa<DbgInfoIntrinsic>(I); ++I) 5721 ; 5722 if (I->isTerminator() && 5723 TryToSimplifyUncondBranchWithICmpInIt(ICI, Builder, DL, TTI, 5724 BonusInstThreshold, AC)) 5725 return true; 5726 } 5727 5728 // See if we can merge an empty landing pad block with another which is 5729 // equivalent. 5730 if (LandingPadInst *LPad = dyn_cast<LandingPadInst>(I)) { 5731 for (++I; isa<DbgInfoIntrinsic>(I); ++I) { 5732 } 5733 if (I->isTerminator() && TryToMergeLandingPad(LPad, BI, BB)) 5734 return true; 5735 } 5736 5737 // If this basic block is ONLY a compare and a branch, and if a predecessor 5738 // branches to us and our successor, fold the comparison into the 5739 // predecessor and use logical operations to update the incoming value 5740 // for PHI nodes in common successor. 5741 if (FoldBranchToCommonDest(BI, BonusInstThreshold)) 5742 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; 5743 return false; 5744 } 5745 5746 static BasicBlock *allPredecessorsComeFromSameSource(BasicBlock *BB) { 5747 BasicBlock *PredPred = nullptr; 5748 for (auto *P : predecessors(BB)) { 5749 BasicBlock *PPred = P->getSinglePredecessor(); 5750 if (!PPred || (PredPred && PredPred != PPred)) 5751 return nullptr; 5752 PredPred = PPred; 5753 } 5754 return PredPred; 5755 } 5756 5757 bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) { 5758 BasicBlock *BB = BI->getParent(); 5759 5760 // Conditional branch 5761 if (isValueEqualityComparison(BI)) { 5762 // If we only have one predecessor, and if it is a branch on this value, 5763 // see if that predecessor totally determines the outcome of this 5764 // switch. 5765 if (BasicBlock *OnlyPred = BB->getSinglePredecessor()) 5766 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder)) 5767 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; 5768 5769 // This block must be empty, except for the setcond inst, if it exists. 5770 // Ignore dbg intrinsics. 5771 BasicBlock::iterator I = BB->begin(); 5772 // Ignore dbg intrinsics. 5773 while (isa<DbgInfoIntrinsic>(I)) 5774 ++I; 5775 if (&*I == BI) { 5776 if (FoldValueComparisonIntoPredecessors(BI, Builder)) 5777 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; 5778 } else if (&*I == cast<Instruction>(BI->getCondition())) { 5779 ++I; 5780 // Ignore dbg intrinsics. 5781 while (isa<DbgInfoIntrinsic>(I)) 5782 ++I; 5783 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder)) 5784 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; 5785 } 5786 } 5787 5788 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction. 5789 if (SimplifyBranchOnICmpChain(BI, Builder, DL)) 5790 return true; 5791 5792 // If this basic block has a single dominating predecessor block and the 5793 // dominating block's condition implies BI's condition, we know the direction 5794 // of the BI branch. 5795 if (BasicBlock *Dom = BB->getSinglePredecessor()) { 5796 auto *PBI = dyn_cast_or_null<BranchInst>(Dom->getTerminator()); 5797 if (PBI && PBI->isConditional() && 5798 PBI->getSuccessor(0) != PBI->getSuccessor(1) && 5799 (PBI->getSuccessor(0) == BB || PBI->getSuccessor(1) == BB)) { 5800 bool CondIsFalse = PBI->getSuccessor(1) == BB; 5801 Optional<bool> Implication = isImpliedCondition( 5802 PBI->getCondition(), BI->getCondition(), DL, CondIsFalse); 5803 if (Implication) { 5804 // Turn this into a branch on constant. 5805 auto *OldCond = BI->getCondition(); 5806 ConstantInt *CI = *Implication 5807 ? ConstantInt::getTrue(BB->getContext()) 5808 : ConstantInt::getFalse(BB->getContext()); 5809 BI->setCondition(CI); 5810 RecursivelyDeleteTriviallyDeadInstructions(OldCond); 5811 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; 5812 } 5813 } 5814 } 5815 5816 // If this basic block is ONLY a compare and a branch, and if a predecessor 5817 // branches to us and one of our successors, fold the comparison into the 5818 // predecessor and use logical operations to pick the right destination. 5819 if (FoldBranchToCommonDest(BI, BonusInstThreshold)) 5820 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; 5821 5822 // We have a conditional branch to two blocks that are only reachable 5823 // from BI. We know that the condbr dominates the two blocks, so see if 5824 // there is any identical code in the "then" and "else" blocks. If so, we 5825 // can hoist it up to the branching block. 5826 if (BI->getSuccessor(0)->getSinglePredecessor()) { 5827 if (BI->getSuccessor(1)->getSinglePredecessor()) { 5828 if (HoistThenElseCodeToIf(BI, TTI)) 5829 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; 5830 } else { 5831 // If Successor #1 has multiple preds, we may be able to conditionally 5832 // execute Successor #0 if it branches to Successor #1. 5833 TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator(); 5834 if (Succ0TI->getNumSuccessors() == 1 && 5835 Succ0TI->getSuccessor(0) == BI->getSuccessor(1)) 5836 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), TTI)) 5837 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; 5838 } 5839 } else if (BI->getSuccessor(1)->getSinglePredecessor()) { 5840 // If Successor #0 has multiple preds, we may be able to conditionally 5841 // execute Successor #1 if it branches to Successor #0. 5842 TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator(); 5843 if (Succ1TI->getNumSuccessors() == 1 && 5844 Succ1TI->getSuccessor(0) == BI->getSuccessor(0)) 5845 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), TTI)) 5846 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; 5847 } 5848 5849 // If this is a branch on a phi node in the current block, thread control 5850 // through this block if any PHI node entries are constants. 5851 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition())) 5852 if (PN->getParent() == BI->getParent()) 5853 if (FoldCondBranchOnPHI(BI, DL, AC)) 5854 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; 5855 5856 // Scan predecessor blocks for conditional branches. 5857 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) 5858 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator())) 5859 if (PBI != BI && PBI->isConditional()) 5860 if (SimplifyCondBranchToCondBranch(PBI, BI, DL)) 5861 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; 5862 5863 // Look for diamond patterns. 5864 if (MergeCondStores) 5865 if (BasicBlock *PrevBB = allPredecessorsComeFromSameSource(BB)) 5866 if (BranchInst *PBI = dyn_cast<BranchInst>(PrevBB->getTerminator())) 5867 if (PBI != BI && PBI->isConditional()) 5868 if (mergeConditionalStores(PBI, BI)) 5869 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true; 5870 5871 return false; 5872 } 5873 5874 /// Check if passing a value to an instruction will cause undefined behavior. 5875 static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) { 5876 Constant *C = dyn_cast<Constant>(V); 5877 if (!C) 5878 return false; 5879 5880 if (I->use_empty()) 5881 return false; 5882 5883 if (C->isNullValue() || isa<UndefValue>(C)) { 5884 // Only look at the first use, avoid hurting compile time with long uselists 5885 User *Use = *I->user_begin(); 5886 5887 // Now make sure that there are no instructions in between that can alter 5888 // control flow (eg. calls) 5889 for (BasicBlock::iterator 5890 i = ++BasicBlock::iterator(I), 5891 UI = BasicBlock::iterator(dyn_cast<Instruction>(Use)); 5892 i != UI; ++i) 5893 if (i == I->getParent()->end() || i->mayHaveSideEffects()) 5894 return false; 5895 5896 // Look through GEPs. A load from a GEP derived from NULL is still undefined 5897 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use)) 5898 if (GEP->getPointerOperand() == I) 5899 return passingValueIsAlwaysUndefined(V, GEP); 5900 5901 // Look through bitcasts. 5902 if (BitCastInst *BC = dyn_cast<BitCastInst>(Use)) 5903 return passingValueIsAlwaysUndefined(V, BC); 5904 5905 // Load from null is undefined. 5906 if (LoadInst *LI = dyn_cast<LoadInst>(Use)) 5907 if (!LI->isVolatile()) 5908 return LI->getPointerAddressSpace() == 0; 5909 5910 // Store to null is undefined. 5911 if (StoreInst *SI = dyn_cast<StoreInst>(Use)) 5912 if (!SI->isVolatile()) 5913 return SI->getPointerAddressSpace() == 0 && 5914 SI->getPointerOperand() == I; 5915 5916 // A call to null is undefined. 5917 if (auto CS = CallSite(Use)) 5918 return CS.getCalledValue() == I; 5919 } 5920 return false; 5921 } 5922 5923 /// If BB has an incoming value that will always trigger undefined behavior 5924 /// (eg. null pointer dereference), remove the branch leading here. 5925 static bool removeUndefIntroducingPredecessor(BasicBlock *BB) { 5926 for (BasicBlock::iterator i = BB->begin(); 5927 PHINode *PHI = dyn_cast<PHINode>(i); ++i) 5928 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i) 5929 if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) { 5930 TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator(); 5931 IRBuilder<> Builder(T); 5932 if (BranchInst *BI = dyn_cast<BranchInst>(T)) { 5933 BB->removePredecessor(PHI->getIncomingBlock(i)); 5934 // Turn uncoditional branches into unreachables and remove the dead 5935 // destination from conditional branches. 5936 if (BI->isUnconditional()) 5937 Builder.CreateUnreachable(); 5938 else 5939 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) 5940 : BI->getSuccessor(0)); 5941 BI->eraseFromParent(); 5942 return true; 5943 } 5944 // TODO: SwitchInst. 5945 } 5946 5947 return false; 5948 } 5949 5950 bool SimplifyCFGOpt::run(BasicBlock *BB) { 5951 bool Changed = false; 5952 5953 assert(BB && BB->getParent() && "Block not embedded in function!"); 5954 assert(BB->getTerminator() && "Degenerate basic block encountered!"); 5955 5956 // Remove basic blocks that have no predecessors (except the entry block)... 5957 // or that just have themself as a predecessor. These are unreachable. 5958 if ((pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) || 5959 BB->getSinglePredecessor() == BB) { 5960 DEBUG(dbgs() << "Removing BB: \n" << *BB); 5961 DeleteDeadBlock(BB); 5962 return true; 5963 } 5964 5965 // Check to see if we can constant propagate this terminator instruction 5966 // away... 5967 Changed |= ConstantFoldTerminator(BB, true); 5968 5969 // Check for and eliminate duplicate PHI nodes in this block. 5970 Changed |= EliminateDuplicatePHINodes(BB); 5971 5972 // Check for and remove branches that will always cause undefined behavior. 5973 Changed |= removeUndefIntroducingPredecessor(BB); 5974 5975 // Merge basic blocks into their predecessor if there is only one distinct 5976 // pred, and if there is only one distinct successor of the predecessor, and 5977 // if there are no PHI nodes. 5978 // 5979 if (MergeBlockIntoPredecessor(BB)) 5980 return true; 5981 5982 IRBuilder<> Builder(BB); 5983 5984 // If there is a trivial two-entry PHI node in this basic block, and we can 5985 // eliminate it, do so now. 5986 if (PHINode *PN = dyn_cast<PHINode>(BB->begin())) 5987 if (PN->getNumIncomingValues() == 2) 5988 Changed |= FoldTwoEntryPHINode(PN, TTI, DL); 5989 5990 Builder.SetInsertPoint(BB->getTerminator()); 5991 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) { 5992 if (BI->isUnconditional()) { 5993 if (SimplifyUncondBranch(BI, Builder)) 5994 return true; 5995 } else { 5996 if (SimplifyCondBranch(BI, Builder)) 5997 return true; 5998 } 5999 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) { 6000 if (SimplifyReturn(RI, Builder)) 6001 return true; 6002 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) { 6003 if (SimplifyResume(RI, Builder)) 6004 return true; 6005 } else if (CleanupReturnInst *RI = 6006 dyn_cast<CleanupReturnInst>(BB->getTerminator())) { 6007 if (SimplifyCleanupReturn(RI)) 6008 return true; 6009 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) { 6010 if (SimplifySwitch(SI, Builder)) 6011 return true; 6012 } else if (UnreachableInst *UI = 6013 dyn_cast<UnreachableInst>(BB->getTerminator())) { 6014 if (SimplifyUnreachable(UI)) 6015 return true; 6016 } else if (IndirectBrInst *IBI = 6017 dyn_cast<IndirectBrInst>(BB->getTerminator())) { 6018 if (SimplifyIndirectBr(IBI)) 6019 return true; 6020 } 6021 6022 return Changed; 6023 } 6024 6025 /// This function is used to do simplification of a CFG. 6026 /// For example, it adjusts branches to branches to eliminate the extra hop, 6027 /// eliminates unreachable basic blocks, and does other "peephole" optimization 6028 /// of the CFG. It returns true if a modification was made. 6029 /// 6030 bool llvm::SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI, 6031 unsigned BonusInstThreshold, AssumptionCache *AC, 6032 SmallPtrSetImpl<BasicBlock *> *LoopHeaders, 6033 bool LateSimplifyCFG) { 6034 return SimplifyCFGOpt(TTI, BB->getModule()->getDataLayout(), 6035 BonusInstThreshold, AC, LoopHeaders, LateSimplifyCFG) 6036 .run(BB); 6037 } 6038