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