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