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