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