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 // Okay, we *could* sink last ScanIdx instructions. But how many can we 2056 // actually sink before encountering instruction that is unprofitable to sink? 2057 auto ProfitableToSinkInstruction = [&](LockstepReverseIterator &LRI) { 2058 unsigned NumPHIdValues = 0; 2059 for (auto *I : *LRI) 2060 for (auto *V : PHIOperands[I]) { 2061 if (!InstructionsToSink.contains(V)) 2062 ++NumPHIdValues; 2063 // FIXME: this check is overly optimistic. We may end up not sinking 2064 // said instruction, due to the very same profitability check. 2065 // See @creating_too_many_phis in sink-common-code.ll. 2066 } 2067 LLVM_DEBUG(dbgs() << "SINK: #phid values: " << NumPHIdValues << "\n"); 2068 unsigned NumPHIInsts = NumPHIdValues / UnconditionalPreds.size(); 2069 if ((NumPHIdValues % UnconditionalPreds.size()) != 0) 2070 NumPHIInsts++; 2071 2072 return NumPHIInsts <= 1; 2073 }; 2074 2075 // We've determined that we are going to sink last ScanIdx instructions, 2076 // and recorded them in InstructionsToSink. Now, some instructions may be 2077 // unprofitable to sink. But that determination depends on the instructions 2078 // that we are going to sink. 2079 2080 // First, forward scan: find the first instruction unprofitable to sink, 2081 // recording all the ones that are profitable to sink. 2082 // FIXME: would it be better, after we detect that not all are profitable. 2083 // to either record the profitable ones, or erase the unprofitable ones? 2084 // Maybe we need to choose (at runtime) the one that will touch least instrs? 2085 LRI.reset(); 2086 int Idx = 0; 2087 SmallPtrSet<Value *, 4> InstructionsProfitableToSink; 2088 while (Idx < ScanIdx) { 2089 if (!ProfitableToSinkInstruction(LRI)) { 2090 // Too many PHIs would be created. 2091 LLVM_DEBUG( 2092 dbgs() << "SINK: stopping here, too many PHIs would be created!\n"); 2093 break; 2094 } 2095 InstructionsProfitableToSink.insert((*LRI).begin(), (*LRI).end()); 2096 --LRI; 2097 ++Idx; 2098 } 2099 2100 // If no instructions can be sunk, early-return. 2101 if (Idx == 0) 2102 return false; 2103 2104 // Did we determine that (only) some instructions are unprofitable to sink? 2105 if (Idx < ScanIdx) { 2106 // Okay, some instructions are unprofitable. 2107 ScanIdx = Idx; 2108 InstructionsToSink = InstructionsProfitableToSink; 2109 2110 // But, that may make other instructions unprofitable, too. 2111 // So, do a backward scan, do any earlier instructions become unprofitable? 2112 assert(!ProfitableToSinkInstruction(LRI) && 2113 "We already know that the last instruction is unprofitable to sink"); 2114 ++LRI; 2115 --Idx; 2116 while (Idx >= 0) { 2117 // If we detect that an instruction becomes unprofitable to sink, 2118 // all earlier instructions won't be sunk either, 2119 // so preemptively keep InstructionsProfitableToSink in sync. 2120 // FIXME: is this the most performant approach? 2121 for (auto *I : *LRI) 2122 InstructionsProfitableToSink.erase(I); 2123 if (!ProfitableToSinkInstruction(LRI)) { 2124 // Everything starting with this instruction won't be sunk. 2125 ScanIdx = Idx; 2126 InstructionsToSink = InstructionsProfitableToSink; 2127 } 2128 ++LRI; 2129 --Idx; 2130 } 2131 } 2132 2133 // If no instructions can be sunk, early-return. 2134 if (ScanIdx == 0) 2135 return false; 2136 2137 bool Changed = false; 2138 2139 if (HaveNonUnconditionalPredecessors) { 2140 // It is always legal to sink common instructions from unconditional 2141 // predecessors. However, if not all predecessors are unconditional, 2142 // this transformation might be pessimizing. So as a rule of thumb, 2143 // don't do it unless we'd sink at least one non-speculatable instruction. 2144 // See https://bugs.llvm.org/show_bug.cgi?id=30244 2145 LRI.reset(); 2146 int Idx = 0; 2147 bool Profitable = false; 2148 while (Idx < ScanIdx) { 2149 if (!isSafeToSpeculativelyExecute((*LRI)[0])) { 2150 Profitable = true; 2151 break; 2152 } 2153 --LRI; 2154 ++Idx; 2155 } 2156 if (!Profitable) 2157 return false; 2158 2159 LLVM_DEBUG(dbgs() << "SINK: Splitting edge\n"); 2160 // We have a conditional edge and we're going to sink some instructions. 2161 // Insert a new block postdominating all blocks we're going to sink from. 2162 if (!SplitBlockPredecessors(BB, UnconditionalPreds, ".sink.split", DTU)) 2163 // Edges couldn't be split. 2164 return false; 2165 Changed = true; 2166 } 2167 2168 // Now that we've analyzed all potential sinking candidates, perform the 2169 // actual sink. We iteratively sink the last non-terminator of the source 2170 // blocks into their common successor unless doing so would require too 2171 // many PHI instructions to be generated (currently only one PHI is allowed 2172 // per sunk instruction). 2173 // 2174 // We can use InstructionsToSink to discount values needing PHI-merging that will 2175 // actually be sunk in a later iteration. This allows us to be more 2176 // aggressive in what we sink. This does allow a false positive where we 2177 // sink presuming a later value will also be sunk, but stop half way through 2178 // and never actually sink it which means we produce more PHIs than intended. 2179 // This is unlikely in practice though. 2180 int SinkIdx = 0; 2181 for (; SinkIdx != ScanIdx; ++SinkIdx) { 2182 LLVM_DEBUG(dbgs() << "SINK: Sink: " 2183 << *UnconditionalPreds[0]->getTerminator()->getPrevNode() 2184 << "\n"); 2185 2186 // Because we've sunk every instruction in turn, the current instruction to 2187 // sink is always at index 0. 2188 LRI.reset(); 2189 2190 if (!sinkLastInstruction(UnconditionalPreds)) { 2191 LLVM_DEBUG( 2192 dbgs() 2193 << "SINK: stopping here, failed to actually sink instruction!\n"); 2194 break; 2195 } 2196 2197 NumSinkCommonInstrs++; 2198 Changed = true; 2199 } 2200 if (SinkIdx != 0) 2201 ++NumSinkCommonCode; 2202 return Changed; 2203 } 2204 2205 /// Determine if we can hoist sink a sole store instruction out of a 2206 /// conditional block. 2207 /// 2208 /// We are looking for code like the following: 2209 /// BrBB: 2210 /// store i32 %add, i32* %arrayidx2 2211 /// ... // No other stores or function calls (we could be calling a memory 2212 /// ... // function). 2213 /// %cmp = icmp ult %x, %y 2214 /// br i1 %cmp, label %EndBB, label %ThenBB 2215 /// ThenBB: 2216 /// store i32 %add5, i32* %arrayidx2 2217 /// br label EndBB 2218 /// EndBB: 2219 /// ... 2220 /// We are going to transform this into: 2221 /// BrBB: 2222 /// store i32 %add, i32* %arrayidx2 2223 /// ... // 2224 /// %cmp = icmp ult %x, %y 2225 /// %add.add5 = select i1 %cmp, i32 %add, %add5 2226 /// store i32 %add.add5, i32* %arrayidx2 2227 /// ... 2228 /// 2229 /// \return The pointer to the value of the previous store if the store can be 2230 /// hoisted into the predecessor block. 0 otherwise. 2231 static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB, 2232 BasicBlock *StoreBB, BasicBlock *EndBB) { 2233 StoreInst *StoreToHoist = dyn_cast<StoreInst>(I); 2234 if (!StoreToHoist) 2235 return nullptr; 2236 2237 // Volatile or atomic. 2238 if (!StoreToHoist->isSimple()) 2239 return nullptr; 2240 2241 Value *StorePtr = StoreToHoist->getPointerOperand(); 2242 Type *StoreTy = StoreToHoist->getValueOperand()->getType(); 2243 2244 // Look for a store to the same pointer in BrBB. 2245 unsigned MaxNumInstToLookAt = 9; 2246 // Skip pseudo probe intrinsic calls which are not really killing any memory 2247 // accesses. 2248 for (Instruction &CurI : reverse(BrBB->instructionsWithoutDebug(true))) { 2249 if (!MaxNumInstToLookAt) 2250 break; 2251 --MaxNumInstToLookAt; 2252 2253 // Could be calling an instruction that affects memory like free(). 2254 if (CurI.mayWriteToMemory() && !isa<StoreInst>(CurI)) 2255 return nullptr; 2256 2257 if (auto *SI = dyn_cast<StoreInst>(&CurI)) { 2258 // Found the previous store to same location and type. Make sure it is 2259 // simple, to avoid introducing a spurious non-atomic write after an 2260 // atomic write. 2261 if (SI->getPointerOperand() == StorePtr && 2262 SI->getValueOperand()->getType() == StoreTy && SI->isSimple()) 2263 // Found the previous store, return its value operand. 2264 return SI->getValueOperand(); 2265 return nullptr; // Unknown store. 2266 } 2267 2268 if (auto *LI = dyn_cast<LoadInst>(&CurI)) { 2269 if (LI->getPointerOperand() == StorePtr && LI->getType() == StoreTy && 2270 LI->isSimple()) { 2271 // Local objects (created by an `alloca` instruction) are always 2272 // writable, so once we are past a read from a location it is valid to 2273 // also write to that same location. 2274 // If the address of the local object never escapes the function, that 2275 // means it's never concurrently read or written, hence moving the store 2276 // from under the condition will not introduce a data race. 2277 auto *AI = dyn_cast<AllocaInst>(getUnderlyingObject(StorePtr)); 2278 if (AI && !PointerMayBeCaptured(AI, false, true)) 2279 // Found a previous load, return it. 2280 return LI; 2281 } 2282 // The load didn't work out, but we may still find a store. 2283 } 2284 } 2285 2286 return nullptr; 2287 } 2288 2289 /// Estimate the cost of the insertion(s) and check that the PHI nodes can be 2290 /// converted to selects. 2291 static bool validateAndCostRequiredSelects(BasicBlock *BB, BasicBlock *ThenBB, 2292 BasicBlock *EndBB, 2293 unsigned &SpeculatedInstructions, 2294 InstructionCost &Cost, 2295 const TargetTransformInfo &TTI) { 2296 TargetTransformInfo::TargetCostKind CostKind = 2297 BB->getParent()->hasMinSize() 2298 ? TargetTransformInfo::TCK_CodeSize 2299 : TargetTransformInfo::TCK_SizeAndLatency; 2300 2301 bool HaveRewritablePHIs = false; 2302 for (PHINode &PN : EndBB->phis()) { 2303 Value *OrigV = PN.getIncomingValueForBlock(BB); 2304 Value *ThenV = PN.getIncomingValueForBlock(ThenBB); 2305 2306 // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf. 2307 // Skip PHIs which are trivial. 2308 if (ThenV == OrigV) 2309 continue; 2310 2311 Cost += TTI.getCmpSelInstrCost(Instruction::Select, PN.getType(), nullptr, 2312 CmpInst::BAD_ICMP_PREDICATE, CostKind); 2313 2314 // Don't convert to selects if we could remove undefined behavior instead. 2315 if (passingValueIsAlwaysUndefined(OrigV, &PN) || 2316 passingValueIsAlwaysUndefined(ThenV, &PN)) 2317 return false; 2318 2319 HaveRewritablePHIs = true; 2320 ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV); 2321 ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV); 2322 if (!OrigCE && !ThenCE) 2323 continue; // Known safe and cheap. 2324 2325 if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE)) || 2326 (OrigCE && !isSafeToSpeculativelyExecute(OrigCE))) 2327 return false; 2328 InstructionCost OrigCost = OrigCE ? computeSpeculationCost(OrigCE, TTI) : 0; 2329 InstructionCost ThenCost = ThenCE ? computeSpeculationCost(ThenCE, TTI) : 0; 2330 InstructionCost MaxCost = 2331 2 * PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic; 2332 if (OrigCost + ThenCost > MaxCost) 2333 return false; 2334 2335 // Account for the cost of an unfolded ConstantExpr which could end up 2336 // getting expanded into Instructions. 2337 // FIXME: This doesn't account for how many operations are combined in the 2338 // constant expression. 2339 ++SpeculatedInstructions; 2340 if (SpeculatedInstructions > 1) 2341 return false; 2342 } 2343 2344 return HaveRewritablePHIs; 2345 } 2346 2347 /// Speculate a conditional basic block flattening the CFG. 2348 /// 2349 /// Note that this is a very risky transform currently. Speculating 2350 /// instructions like this is most often not desirable. Instead, there is an MI 2351 /// pass which can do it with full awareness of the resource constraints. 2352 /// However, some cases are "obvious" and we should do directly. An example of 2353 /// this is speculating a single, reasonably cheap instruction. 2354 /// 2355 /// There is only one distinct advantage to flattening the CFG at the IR level: 2356 /// it makes very common but simplistic optimizations such as are common in 2357 /// instcombine and the DAG combiner more powerful by removing CFG edges and 2358 /// modeling their effects with easier to reason about SSA value graphs. 2359 /// 2360 /// 2361 /// An illustration of this transform is turning this IR: 2362 /// \code 2363 /// BB: 2364 /// %cmp = icmp ult %x, %y 2365 /// br i1 %cmp, label %EndBB, label %ThenBB 2366 /// ThenBB: 2367 /// %sub = sub %x, %y 2368 /// br label BB2 2369 /// EndBB: 2370 /// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ] 2371 /// ... 2372 /// \endcode 2373 /// 2374 /// Into this IR: 2375 /// \code 2376 /// BB: 2377 /// %cmp = icmp ult %x, %y 2378 /// %sub = sub %x, %y 2379 /// %cond = select i1 %cmp, 0, %sub 2380 /// ... 2381 /// \endcode 2382 /// 2383 /// \returns true if the conditional block is removed. 2384 bool SimplifyCFGOpt::SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB, 2385 const TargetTransformInfo &TTI) { 2386 // Be conservative for now. FP select instruction can often be expensive. 2387 Value *BrCond = BI->getCondition(); 2388 if (isa<FCmpInst>(BrCond)) 2389 return false; 2390 2391 BasicBlock *BB = BI->getParent(); 2392 BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0); 2393 InstructionCost Budget = 2394 PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic; 2395 2396 // If ThenBB is actually on the false edge of the conditional branch, remember 2397 // to swap the select operands later. 2398 bool Invert = false; 2399 if (ThenBB != BI->getSuccessor(0)) { 2400 assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?"); 2401 Invert = true; 2402 } 2403 assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block"); 2404 2405 // If the branch is non-unpredictable, and is predicted to *not* branch to 2406 // the `then` block, then avoid speculating it. 2407 if (!BI->getMetadata(LLVMContext::MD_unpredictable)) { 2408 uint64_t TWeight, FWeight; 2409 if (BI->extractProfMetadata(TWeight, FWeight) && (TWeight + FWeight) != 0) { 2410 uint64_t EndWeight = Invert ? TWeight : FWeight; 2411 BranchProbability BIEndProb = 2412 BranchProbability::getBranchProbability(EndWeight, TWeight + FWeight); 2413 BranchProbability Likely = TTI.getPredictableBranchThreshold(); 2414 if (BIEndProb >= Likely) 2415 return false; 2416 } 2417 } 2418 2419 // Keep a count of how many times instructions are used within ThenBB when 2420 // they are candidates for sinking into ThenBB. Specifically: 2421 // - They are defined in BB, and 2422 // - They have no side effects, and 2423 // - All of their uses are in ThenBB. 2424 SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts; 2425 2426 SmallVector<Instruction *, 4> SpeculatedDbgIntrinsics; 2427 2428 unsigned SpeculatedInstructions = 0; 2429 Value *SpeculatedStoreValue = nullptr; 2430 StoreInst *SpeculatedStore = nullptr; 2431 for (BasicBlock::iterator BBI = ThenBB->begin(), 2432 BBE = std::prev(ThenBB->end()); 2433 BBI != BBE; ++BBI) { 2434 Instruction *I = &*BBI; 2435 // Skip debug info. 2436 if (isa<DbgInfoIntrinsic>(I)) { 2437 SpeculatedDbgIntrinsics.push_back(I); 2438 continue; 2439 } 2440 2441 // Skip pseudo probes. The consequence is we lose track of the branch 2442 // probability for ThenBB, which is fine since the optimization here takes 2443 // place regardless of the branch probability. 2444 if (isa<PseudoProbeInst>(I)) { 2445 // The probe should be deleted so that it will not be over-counted when 2446 // the samples collected on the non-conditional path are counted towards 2447 // the conditional path. We leave it for the counts inference algorithm to 2448 // figure out a proper count for an unknown probe. 2449 SpeculatedDbgIntrinsics.push_back(I); 2450 continue; 2451 } 2452 2453 // Only speculatively execute a single instruction (not counting the 2454 // terminator) for now. 2455 ++SpeculatedInstructions; 2456 if (SpeculatedInstructions > 1) 2457 return false; 2458 2459 // Don't hoist the instruction if it's unsafe or expensive. 2460 if (!isSafeToSpeculativelyExecute(I) && 2461 !(HoistCondStores && (SpeculatedStoreValue = isSafeToSpeculateStore( 2462 I, BB, ThenBB, EndBB)))) 2463 return false; 2464 if (!SpeculatedStoreValue && 2465 computeSpeculationCost(I, TTI) > 2466 PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic) 2467 return false; 2468 2469 // Store the store speculation candidate. 2470 if (SpeculatedStoreValue) 2471 SpeculatedStore = cast<StoreInst>(I); 2472 2473 // Do not hoist the instruction if any of its operands are defined but not 2474 // used in BB. The transformation will prevent the operand from 2475 // being sunk into the use block. 2476 for (Use &Op : I->operands()) { 2477 Instruction *OpI = dyn_cast<Instruction>(Op); 2478 if (!OpI || OpI->getParent() != BB || OpI->mayHaveSideEffects()) 2479 continue; // Not a candidate for sinking. 2480 2481 ++SinkCandidateUseCounts[OpI]; 2482 } 2483 } 2484 2485 // Consider any sink candidates which are only used in ThenBB as costs for 2486 // speculation. Note, while we iterate over a DenseMap here, we are summing 2487 // and so iteration order isn't significant. 2488 for (SmallDenseMap<Instruction *, unsigned, 4>::iterator 2489 I = SinkCandidateUseCounts.begin(), 2490 E = SinkCandidateUseCounts.end(); 2491 I != E; ++I) 2492 if (I->first->hasNUses(I->second)) { 2493 ++SpeculatedInstructions; 2494 if (SpeculatedInstructions > 1) 2495 return false; 2496 } 2497 2498 // Check that we can insert the selects and that it's not too expensive to do 2499 // so. 2500 bool Convert = SpeculatedStore != nullptr; 2501 InstructionCost Cost = 0; 2502 Convert |= validateAndCostRequiredSelects(BB, ThenBB, EndBB, 2503 SpeculatedInstructions, 2504 Cost, TTI); 2505 if (!Convert || Cost > Budget) 2506 return false; 2507 2508 // If we get here, we can hoist the instruction and if-convert. 2509 LLVM_DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";); 2510 2511 // Insert a select of the value of the speculated store. 2512 if (SpeculatedStoreValue) { 2513 IRBuilder<NoFolder> Builder(BI); 2514 Value *TrueV = SpeculatedStore->getValueOperand(); 2515 Value *FalseV = SpeculatedStoreValue; 2516 if (Invert) 2517 std::swap(TrueV, FalseV); 2518 Value *S = Builder.CreateSelect( 2519 BrCond, TrueV, FalseV, "spec.store.select", BI); 2520 SpeculatedStore->setOperand(0, S); 2521 SpeculatedStore->applyMergedLocation(BI->getDebugLoc(), 2522 SpeculatedStore->getDebugLoc()); 2523 } 2524 2525 // Metadata can be dependent on the condition we are hoisting above. 2526 // Conservatively strip all metadata on the instruction. Drop the debug loc 2527 // to avoid making it appear as if the condition is a constant, which would 2528 // be misleading while debugging. 2529 // Similarly strip attributes that maybe dependent on condition we are 2530 // hoisting above. 2531 for (auto &I : *ThenBB) { 2532 if (!SpeculatedStoreValue || &I != SpeculatedStore) 2533 I.setDebugLoc(DebugLoc()); 2534 I.dropUndefImplyingAttrsAndUnknownMetadata(); 2535 } 2536 2537 // Hoist the instructions. 2538 BB->getInstList().splice(BI->getIterator(), ThenBB->getInstList(), 2539 ThenBB->begin(), std::prev(ThenBB->end())); 2540 2541 // Insert selects and rewrite the PHI operands. 2542 IRBuilder<NoFolder> Builder(BI); 2543 for (PHINode &PN : EndBB->phis()) { 2544 unsigned OrigI = PN.getBasicBlockIndex(BB); 2545 unsigned ThenI = PN.getBasicBlockIndex(ThenBB); 2546 Value *OrigV = PN.getIncomingValue(OrigI); 2547 Value *ThenV = PN.getIncomingValue(ThenI); 2548 2549 // Skip PHIs which are trivial. 2550 if (OrigV == ThenV) 2551 continue; 2552 2553 // Create a select whose true value is the speculatively executed value and 2554 // false value is the pre-existing value. Swap them if the branch 2555 // destinations were inverted. 2556 Value *TrueV = ThenV, *FalseV = OrigV; 2557 if (Invert) 2558 std::swap(TrueV, FalseV); 2559 Value *V = Builder.CreateSelect(BrCond, TrueV, FalseV, "spec.select", BI); 2560 PN.setIncomingValue(OrigI, V); 2561 PN.setIncomingValue(ThenI, V); 2562 } 2563 2564 // Remove speculated dbg intrinsics. 2565 // FIXME: Is it possible to do this in a more elegant way? Moving/merging the 2566 // dbg value for the different flows and inserting it after the select. 2567 for (Instruction *I : SpeculatedDbgIntrinsics) 2568 I->eraseFromParent(); 2569 2570 ++NumSpeculations; 2571 return true; 2572 } 2573 2574 /// Return true if we can thread a branch across this block. 2575 static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) { 2576 int Size = 0; 2577 2578 SmallPtrSet<const Value *, 32> EphValues; 2579 auto IsEphemeral = [&](const Instruction *I) { 2580 if (isa<AssumeInst>(I)) 2581 return true; 2582 return !I->mayHaveSideEffects() && !I->isTerminator() && 2583 all_of(I->users(), 2584 [&](const User *U) { return EphValues.count(U); }); 2585 }; 2586 2587 // Walk the loop in reverse so that we can identify ephemeral values properly 2588 // (values only feeding assumes). 2589 for (Instruction &I : reverse(BB->instructionsWithoutDebug(false))) { 2590 // Can't fold blocks that contain noduplicate or convergent calls. 2591 if (CallInst *CI = dyn_cast<CallInst>(&I)) 2592 if (CI->cannotDuplicate() || CI->isConvergent()) 2593 return false; 2594 2595 // Ignore ephemeral values which are deleted during codegen. 2596 if (IsEphemeral(&I)) 2597 EphValues.insert(&I); 2598 // We will delete Phis while threading, so Phis should not be accounted in 2599 // block's size. 2600 else if (!isa<PHINode>(I)) { 2601 if (Size++ > MaxSmallBlockSize) 2602 return false; // Don't clone large BB's. 2603 } 2604 2605 // We can only support instructions that do not define values that are 2606 // live outside of the current basic block. 2607 for (User *U : I.users()) { 2608 Instruction *UI = cast<Instruction>(U); 2609 if (UI->getParent() != BB || isa<PHINode>(UI)) 2610 return false; 2611 } 2612 2613 // Looks ok, continue checking. 2614 } 2615 2616 return true; 2617 } 2618 2619 /// If we have a conditional branch on a PHI node value that is defined in the 2620 /// same block as the branch and if any PHI entries are constants, thread edges 2621 /// corresponding to that entry to be branches to their ultimate destination. 2622 static Optional<bool> FoldCondBranchOnPHIImpl(BranchInst *BI, 2623 DomTreeUpdater *DTU, 2624 const DataLayout &DL, 2625 AssumptionCache *AC) { 2626 BasicBlock *BB = BI->getParent(); 2627 PHINode *PN = dyn_cast<PHINode>(BI->getCondition()); 2628 // NOTE: we currently cannot transform this case if the PHI node is used 2629 // outside of the block. 2630 if (!PN || PN->getParent() != BB || !PN->hasOneUse()) 2631 return false; 2632 2633 // Degenerate case of a single entry PHI. 2634 if (PN->getNumIncomingValues() == 1) { 2635 FoldSingleEntryPHINodes(PN->getParent()); 2636 return true; 2637 } 2638 2639 // Now we know that this block has multiple preds and two succs. 2640 if (!BlockIsSimpleEnoughToThreadThrough(BB)) 2641 return false; 2642 2643 // Okay, this is a simple enough basic block. See if any phi values are 2644 // constants. 2645 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 2646 ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i)); 2647 if (!CB || !CB->getType()->isIntegerTy(1)) 2648 continue; 2649 2650 // Okay, we now know that all edges from PredBB should be revectored to 2651 // branch to RealDest. 2652 BasicBlock *PredBB = PN->getIncomingBlock(i); 2653 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue()); 2654 2655 if (RealDest == BB) 2656 continue; // Skip self loops. 2657 // Skip if the predecessor's terminator is an indirect branch. 2658 if (isa<IndirectBrInst>(PredBB->getTerminator())) 2659 continue; 2660 2661 SmallVector<DominatorTree::UpdateType, 3> Updates; 2662 2663 // The dest block might have PHI nodes, other predecessors and other 2664 // difficult cases. Instead of being smart about this, just insert a new 2665 // block that jumps to the destination block, effectively splitting 2666 // the edge we are about to create. 2667 BasicBlock *EdgeBB = 2668 BasicBlock::Create(BB->getContext(), RealDest->getName() + ".critedge", 2669 RealDest->getParent(), RealDest); 2670 BranchInst *CritEdgeBranch = BranchInst::Create(RealDest, EdgeBB); 2671 if (DTU) 2672 Updates.push_back({DominatorTree::Insert, EdgeBB, RealDest}); 2673 CritEdgeBranch->setDebugLoc(BI->getDebugLoc()); 2674 2675 // Update PHI nodes. 2676 AddPredecessorToBlock(RealDest, EdgeBB, BB); 2677 2678 // BB may have instructions that are being threaded over. Clone these 2679 // instructions into EdgeBB. We know that there will be no uses of the 2680 // cloned instructions outside of EdgeBB. 2681 BasicBlock::iterator InsertPt = EdgeBB->begin(); 2682 DenseMap<Value *, Value *> TranslateMap; // Track translated values. 2683 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) { 2684 if (PHINode *PN = dyn_cast<PHINode>(BBI)) { 2685 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB); 2686 continue; 2687 } 2688 // Clone the instruction. 2689 Instruction *N = BBI->clone(); 2690 if (BBI->hasName()) 2691 N->setName(BBI->getName() + ".c"); 2692 2693 // Update operands due to translation. 2694 for (Use &Op : N->operands()) { 2695 DenseMap<Value *, Value *>::iterator PI = TranslateMap.find(Op); 2696 if (PI != TranslateMap.end()) 2697 Op = PI->second; 2698 } 2699 2700 // Check for trivial simplification. 2701 if (Value *V = SimplifyInstruction(N, {DL, nullptr, nullptr, AC})) { 2702 if (!BBI->use_empty()) 2703 TranslateMap[&*BBI] = V; 2704 if (!N->mayHaveSideEffects()) { 2705 N->deleteValue(); // Instruction folded away, don't need actual inst 2706 N = nullptr; 2707 } 2708 } else { 2709 if (!BBI->use_empty()) 2710 TranslateMap[&*BBI] = N; 2711 } 2712 if (N) { 2713 // Insert the new instruction into its new home. 2714 EdgeBB->getInstList().insert(InsertPt, N); 2715 2716 // Register the new instruction with the assumption cache if necessary. 2717 if (auto *Assume = dyn_cast<AssumeInst>(N)) 2718 if (AC) 2719 AC->registerAssumption(Assume); 2720 } 2721 } 2722 2723 // Loop over all of the edges from PredBB to BB, changing them to branch 2724 // to EdgeBB instead. 2725 Instruction *PredBBTI = PredBB->getTerminator(); 2726 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i) 2727 if (PredBBTI->getSuccessor(i) == BB) { 2728 BB->removePredecessor(PredBB); 2729 PredBBTI->setSuccessor(i, EdgeBB); 2730 } 2731 2732 if (DTU) { 2733 Updates.push_back({DominatorTree::Insert, PredBB, EdgeBB}); 2734 Updates.push_back({DominatorTree::Delete, PredBB, BB}); 2735 2736 DTU->applyUpdates(Updates); 2737 } 2738 2739 // Signal repeat, simplifying any other constants. 2740 return None; 2741 } 2742 2743 return false; 2744 } 2745 2746 static bool FoldCondBranchOnPHI(BranchInst *BI, DomTreeUpdater *DTU, 2747 const DataLayout &DL, AssumptionCache *AC) { 2748 Optional<bool> Result; 2749 bool EverChanged = false; 2750 do { 2751 // Note that None means "we changed things, but recurse further." 2752 Result = FoldCondBranchOnPHIImpl(BI, DTU, DL, AC); 2753 EverChanged |= Result == None || *Result; 2754 } while (Result == None); 2755 return EverChanged; 2756 } 2757 2758 /// Given a BB that starts with the specified two-entry PHI node, 2759 /// see if we can eliminate it. 2760 static bool FoldTwoEntryPHINode(PHINode *PN, const TargetTransformInfo &TTI, 2761 DomTreeUpdater *DTU, const DataLayout &DL) { 2762 // Ok, this is a two entry PHI node. Check to see if this is a simple "if 2763 // statement", which has a very simple dominance structure. Basically, we 2764 // are trying to find the condition that is being branched on, which 2765 // subsequently causes this merge to happen. We really want control 2766 // dependence information for this check, but simplifycfg can't keep it up 2767 // to date, and this catches most of the cases we care about anyway. 2768 BasicBlock *BB = PN->getParent(); 2769 2770 BasicBlock *IfTrue, *IfFalse; 2771 BranchInst *DomBI = GetIfCondition(BB, IfTrue, IfFalse); 2772 if (!DomBI) 2773 return false; 2774 Value *IfCond = DomBI->getCondition(); 2775 // Don't bother if the branch will be constant folded trivially. 2776 if (isa<ConstantInt>(IfCond)) 2777 return false; 2778 2779 BasicBlock *DomBlock = DomBI->getParent(); 2780 SmallVector<BasicBlock *, 2> IfBlocks; 2781 llvm::copy_if( 2782 PN->blocks(), std::back_inserter(IfBlocks), [](BasicBlock *IfBlock) { 2783 return cast<BranchInst>(IfBlock->getTerminator())->isUnconditional(); 2784 }); 2785 assert((IfBlocks.size() == 1 || IfBlocks.size() == 2) && 2786 "Will have either one or two blocks to speculate."); 2787 2788 // If the branch is non-unpredictable, see if we either predictably jump to 2789 // the merge bb (if we have only a single 'then' block), or if we predictably 2790 // jump to one specific 'then' block (if we have two of them). 2791 // It isn't beneficial to speculatively execute the code 2792 // from the block that we know is predictably not entered. 2793 if (!DomBI->getMetadata(LLVMContext::MD_unpredictable)) { 2794 uint64_t TWeight, FWeight; 2795 if (DomBI->extractProfMetadata(TWeight, FWeight) && 2796 (TWeight + FWeight) != 0) { 2797 BranchProbability BITrueProb = 2798 BranchProbability::getBranchProbability(TWeight, TWeight + FWeight); 2799 BranchProbability Likely = TTI.getPredictableBranchThreshold(); 2800 BranchProbability BIFalseProb = BITrueProb.getCompl(); 2801 if (IfBlocks.size() == 1) { 2802 BranchProbability BIBBProb = 2803 DomBI->getSuccessor(0) == BB ? BITrueProb : BIFalseProb; 2804 if (BIBBProb >= Likely) 2805 return false; 2806 } else { 2807 if (BITrueProb >= Likely || BIFalseProb >= Likely) 2808 return false; 2809 } 2810 } 2811 } 2812 2813 // Don't try to fold an unreachable block. For example, the phi node itself 2814 // can't be the candidate if-condition for a select that we want to form. 2815 if (auto *IfCondPhiInst = dyn_cast<PHINode>(IfCond)) 2816 if (IfCondPhiInst->getParent() == BB) 2817 return false; 2818 2819 // Okay, we found that we can merge this two-entry phi node into a select. 2820 // Doing so would require us to fold *all* two entry phi nodes in this block. 2821 // At some point this becomes non-profitable (particularly if the target 2822 // doesn't support cmov's). Only do this transformation if there are two or 2823 // fewer PHI nodes in this block. 2824 unsigned NumPhis = 0; 2825 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I) 2826 if (NumPhis > 2) 2827 return false; 2828 2829 // Loop over the PHI's seeing if we can promote them all to select 2830 // instructions. While we are at it, keep track of the instructions 2831 // that need to be moved to the dominating block. 2832 SmallPtrSet<Instruction *, 4> AggressiveInsts; 2833 InstructionCost Cost = 0; 2834 InstructionCost Budget = 2835 TwoEntryPHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic; 2836 2837 bool Changed = false; 2838 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) { 2839 PHINode *PN = cast<PHINode>(II++); 2840 if (Value *V = SimplifyInstruction(PN, {DL, PN})) { 2841 PN->replaceAllUsesWith(V); 2842 PN->eraseFromParent(); 2843 Changed = true; 2844 continue; 2845 } 2846 2847 if (!dominatesMergePoint(PN->getIncomingValue(0), BB, AggressiveInsts, 2848 Cost, Budget, TTI) || 2849 !dominatesMergePoint(PN->getIncomingValue(1), BB, AggressiveInsts, 2850 Cost, Budget, TTI)) 2851 return Changed; 2852 } 2853 2854 // If we folded the first phi, PN dangles at this point. Refresh it. If 2855 // we ran out of PHIs then we simplified them all. 2856 PN = dyn_cast<PHINode>(BB->begin()); 2857 if (!PN) 2858 return true; 2859 2860 // Return true if at least one of these is a 'not', and another is either 2861 // a 'not' too, or a constant. 2862 auto CanHoistNotFromBothValues = [](Value *V0, Value *V1) { 2863 if (!match(V0, m_Not(m_Value()))) 2864 std::swap(V0, V1); 2865 auto Invertible = m_CombineOr(m_Not(m_Value()), m_AnyIntegralConstant()); 2866 return match(V0, m_Not(m_Value())) && match(V1, Invertible); 2867 }; 2868 2869 // Don't fold i1 branches on PHIs which contain binary operators or 2870 // (possibly inverted) select form of or/ands, unless one of 2871 // the incoming values is an 'not' and another one is freely invertible. 2872 // These can often be turned into switches and other things. 2873 auto IsBinOpOrAnd = [](Value *V) { 2874 return match( 2875 V, m_CombineOr( 2876 m_BinOp(), 2877 m_CombineOr(m_Select(m_Value(), m_ImmConstant(), m_Value()), 2878 m_Select(m_Value(), m_Value(), m_ImmConstant())))); 2879 }; 2880 if (PN->getType()->isIntegerTy(1) && 2881 (IsBinOpOrAnd(PN->getIncomingValue(0)) || 2882 IsBinOpOrAnd(PN->getIncomingValue(1)) || IsBinOpOrAnd(IfCond)) && 2883 !CanHoistNotFromBothValues(PN->getIncomingValue(0), 2884 PN->getIncomingValue(1))) 2885 return Changed; 2886 2887 // If all PHI nodes are promotable, check to make sure that all instructions 2888 // in the predecessor blocks can be promoted as well. If not, we won't be able 2889 // to get rid of the control flow, so it's not worth promoting to select 2890 // instructions. 2891 for (BasicBlock *IfBlock : IfBlocks) 2892 for (BasicBlock::iterator I = IfBlock->begin(); !I->isTerminator(); ++I) 2893 if (!AggressiveInsts.count(&*I) && !I->isDebugOrPseudoInst()) { 2894 // This is not an aggressive instruction that we can promote. 2895 // Because of this, we won't be able to get rid of the control flow, so 2896 // the xform is not worth it. 2897 return Changed; 2898 } 2899 2900 // If either of the blocks has it's address taken, we can't do this fold. 2901 if (any_of(IfBlocks, 2902 [](BasicBlock *IfBlock) { return IfBlock->hasAddressTaken(); })) 2903 return Changed; 2904 2905 LLVM_DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond 2906 << " T: " << IfTrue->getName() 2907 << " F: " << IfFalse->getName() << "\n"); 2908 2909 // If we can still promote the PHI nodes after this gauntlet of tests, 2910 // do all of the PHI's now. 2911 2912 // Move all 'aggressive' instructions, which are defined in the 2913 // conditional parts of the if's up to the dominating block. 2914 for (BasicBlock *IfBlock : IfBlocks) 2915 hoistAllInstructionsInto(DomBlock, DomBI, IfBlock); 2916 2917 IRBuilder<NoFolder> Builder(DomBI); 2918 // Propagate fast-math-flags from phi nodes to replacement selects. 2919 IRBuilder<>::FastMathFlagGuard FMFGuard(Builder); 2920 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) { 2921 if (isa<FPMathOperator>(PN)) 2922 Builder.setFastMathFlags(PN->getFastMathFlags()); 2923 2924 // Change the PHI node into a select instruction. 2925 Value *TrueVal = PN->getIncomingValueForBlock(IfTrue); 2926 Value *FalseVal = PN->getIncomingValueForBlock(IfFalse); 2927 2928 Value *Sel = Builder.CreateSelect(IfCond, TrueVal, FalseVal, "", DomBI); 2929 PN->replaceAllUsesWith(Sel); 2930 Sel->takeName(PN); 2931 PN->eraseFromParent(); 2932 } 2933 2934 // At this point, all IfBlocks are empty, so our if statement 2935 // has been flattened. Change DomBlock to jump directly to our new block to 2936 // avoid other simplifycfg's kicking in on the diamond. 2937 Builder.CreateBr(BB); 2938 2939 SmallVector<DominatorTree::UpdateType, 3> Updates; 2940 if (DTU) { 2941 Updates.push_back({DominatorTree::Insert, DomBlock, BB}); 2942 for (auto *Successor : successors(DomBlock)) 2943 Updates.push_back({DominatorTree::Delete, DomBlock, Successor}); 2944 } 2945 2946 DomBI->eraseFromParent(); 2947 if (DTU) 2948 DTU->applyUpdates(Updates); 2949 2950 return true; 2951 } 2952 2953 static Value *createLogicalOp(IRBuilderBase &Builder, 2954 Instruction::BinaryOps Opc, Value *LHS, 2955 Value *RHS, const Twine &Name = "") { 2956 // Try to relax logical op to binary op. 2957 if (impliesPoison(RHS, LHS)) 2958 return Builder.CreateBinOp(Opc, LHS, RHS, Name); 2959 if (Opc == Instruction::And) 2960 return Builder.CreateLogicalAnd(LHS, RHS, Name); 2961 if (Opc == Instruction::Or) 2962 return Builder.CreateLogicalOr(LHS, RHS, Name); 2963 llvm_unreachable("Invalid logical opcode"); 2964 } 2965 2966 /// Return true if either PBI or BI has branch weight available, and store 2967 /// the weights in {Pred|Succ}{True|False}Weight. If one of PBI and BI does 2968 /// not have branch weight, use 1:1 as its weight. 2969 static bool extractPredSuccWeights(BranchInst *PBI, BranchInst *BI, 2970 uint64_t &PredTrueWeight, 2971 uint64_t &PredFalseWeight, 2972 uint64_t &SuccTrueWeight, 2973 uint64_t &SuccFalseWeight) { 2974 bool PredHasWeights = 2975 PBI->extractProfMetadata(PredTrueWeight, PredFalseWeight); 2976 bool SuccHasWeights = 2977 BI->extractProfMetadata(SuccTrueWeight, SuccFalseWeight); 2978 if (PredHasWeights || SuccHasWeights) { 2979 if (!PredHasWeights) 2980 PredTrueWeight = PredFalseWeight = 1; 2981 if (!SuccHasWeights) 2982 SuccTrueWeight = SuccFalseWeight = 1; 2983 return true; 2984 } else { 2985 return false; 2986 } 2987 } 2988 2989 /// Determine if the two branches share a common destination and deduce a glue 2990 /// that joins the branches' conditions to arrive at the common destination if 2991 /// that would be profitable. 2992 static Optional<std::pair<Instruction::BinaryOps, bool>> 2993 shouldFoldCondBranchesToCommonDestination(BranchInst *BI, BranchInst *PBI, 2994 const TargetTransformInfo *TTI) { 2995 assert(BI && PBI && BI->isConditional() && PBI->isConditional() && 2996 "Both blocks must end with a conditional branches."); 2997 assert(is_contained(predecessors(BI->getParent()), PBI->getParent()) && 2998 "PredBB must be a predecessor of BB."); 2999 3000 // We have the potential to fold the conditions together, but if the 3001 // predecessor branch is predictable, we may not want to merge them. 3002 uint64_t PTWeight, PFWeight; 3003 BranchProbability PBITrueProb, Likely; 3004 if (TTI && !PBI->getMetadata(LLVMContext::MD_unpredictable) && 3005 PBI->extractProfMetadata(PTWeight, PFWeight) && 3006 (PTWeight + PFWeight) != 0) { 3007 PBITrueProb = 3008 BranchProbability::getBranchProbability(PTWeight, PTWeight + PFWeight); 3009 Likely = TTI->getPredictableBranchThreshold(); 3010 } 3011 3012 if (PBI->getSuccessor(0) == BI->getSuccessor(0)) { 3013 // Speculate the 2nd condition unless the 1st is probably true. 3014 if (PBITrueProb.isUnknown() || PBITrueProb < Likely) 3015 return {{Instruction::Or, false}}; 3016 } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) { 3017 // Speculate the 2nd condition unless the 1st is probably false. 3018 if (PBITrueProb.isUnknown() || PBITrueProb.getCompl() < Likely) 3019 return {{Instruction::And, false}}; 3020 } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) { 3021 // Speculate the 2nd condition unless the 1st is probably true. 3022 if (PBITrueProb.isUnknown() || PBITrueProb < Likely) 3023 return {{Instruction::And, true}}; 3024 } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) { 3025 // Speculate the 2nd condition unless the 1st is probably false. 3026 if (PBITrueProb.isUnknown() || PBITrueProb.getCompl() < Likely) 3027 return {{Instruction::Or, true}}; 3028 } 3029 return None; 3030 } 3031 3032 static bool performBranchToCommonDestFolding(BranchInst *BI, BranchInst *PBI, 3033 DomTreeUpdater *DTU, 3034 MemorySSAUpdater *MSSAU, 3035 const TargetTransformInfo *TTI) { 3036 BasicBlock *BB = BI->getParent(); 3037 BasicBlock *PredBlock = PBI->getParent(); 3038 3039 // Determine if the two branches share a common destination. 3040 Instruction::BinaryOps Opc; 3041 bool InvertPredCond; 3042 std::tie(Opc, InvertPredCond) = 3043 *shouldFoldCondBranchesToCommonDestination(BI, PBI, TTI); 3044 3045 LLVM_DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB); 3046 3047 IRBuilder<> Builder(PBI); 3048 // The builder is used to create instructions to eliminate the branch in BB. 3049 // If BB's terminator has !annotation metadata, add it to the new 3050 // instructions. 3051 Builder.CollectMetadataToCopy(BB->getTerminator(), 3052 {LLVMContext::MD_annotation}); 3053 3054 // If we need to invert the condition in the pred block to match, do so now. 3055 if (InvertPredCond) { 3056 Value *NewCond = PBI->getCondition(); 3057 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) { 3058 CmpInst *CI = cast<CmpInst>(NewCond); 3059 CI->setPredicate(CI->getInversePredicate()); 3060 } else { 3061 NewCond = 3062 Builder.CreateNot(NewCond, PBI->getCondition()->getName() + ".not"); 3063 } 3064 3065 PBI->setCondition(NewCond); 3066 PBI->swapSuccessors(); 3067 } 3068 3069 BasicBlock *UniqueSucc = 3070 PBI->getSuccessor(0) == BB ? BI->getSuccessor(0) : BI->getSuccessor(1); 3071 3072 // Before cloning instructions, notify the successor basic block that it 3073 // is about to have a new predecessor. This will update PHI nodes, 3074 // which will allow us to update live-out uses of bonus instructions. 3075 AddPredecessorToBlock(UniqueSucc, PredBlock, BB, MSSAU); 3076 3077 // Try to update branch weights. 3078 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight; 3079 if (extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight, 3080 SuccTrueWeight, SuccFalseWeight)) { 3081 SmallVector<uint64_t, 8> NewWeights; 3082 3083 if (PBI->getSuccessor(0) == BB) { 3084 // PBI: br i1 %x, BB, FalseDest 3085 // BI: br i1 %y, UniqueSucc, FalseDest 3086 // TrueWeight is TrueWeight for PBI * TrueWeight for BI. 3087 NewWeights.push_back(PredTrueWeight * SuccTrueWeight); 3088 // FalseWeight is FalseWeight for PBI * TotalWeight for BI + 3089 // TrueWeight for PBI * FalseWeight for BI. 3090 // We assume that total weights of a BranchInst can fit into 32 bits. 3091 // Therefore, we will not have overflow using 64-bit arithmetic. 3092 NewWeights.push_back(PredFalseWeight * 3093 (SuccFalseWeight + SuccTrueWeight) + 3094 PredTrueWeight * SuccFalseWeight); 3095 } else { 3096 // PBI: br i1 %x, TrueDest, BB 3097 // BI: br i1 %y, TrueDest, UniqueSucc 3098 // TrueWeight is TrueWeight for PBI * TotalWeight for BI + 3099 // FalseWeight for PBI * TrueWeight for BI. 3100 NewWeights.push_back(PredTrueWeight * (SuccFalseWeight + SuccTrueWeight) + 3101 PredFalseWeight * SuccTrueWeight); 3102 // FalseWeight is FalseWeight for PBI * FalseWeight for BI. 3103 NewWeights.push_back(PredFalseWeight * SuccFalseWeight); 3104 } 3105 3106 // Halve the weights if any of them cannot fit in an uint32_t 3107 FitWeights(NewWeights); 3108 3109 SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(), NewWeights.end()); 3110 setBranchWeights(PBI, MDWeights[0], MDWeights[1]); 3111 3112 // TODO: If BB is reachable from all paths through PredBlock, then we 3113 // could replace PBI's branch probabilities with BI's. 3114 } else 3115 PBI->setMetadata(LLVMContext::MD_prof, nullptr); 3116 3117 // Now, update the CFG. 3118 PBI->setSuccessor(PBI->getSuccessor(0) != BB, UniqueSucc); 3119 3120 if (DTU) 3121 DTU->applyUpdates({{DominatorTree::Insert, PredBlock, UniqueSucc}, 3122 {DominatorTree::Delete, PredBlock, BB}}); 3123 3124 // If BI was a loop latch, it may have had associated loop metadata. 3125 // We need to copy it to the new latch, that is, PBI. 3126 if (MDNode *LoopMD = BI->getMetadata(LLVMContext::MD_loop)) 3127 PBI->setMetadata(LLVMContext::MD_loop, LoopMD); 3128 3129 ValueToValueMapTy VMap; // maps original values to cloned values 3130 CloneInstructionsIntoPredecessorBlockAndUpdateSSAUses(BB, PredBlock, VMap); 3131 3132 // Now that the Cond was cloned into the predecessor basic block, 3133 // or/and the two conditions together. 3134 Value *BICond = VMap[BI->getCondition()]; 3135 PBI->setCondition( 3136 createLogicalOp(Builder, Opc, PBI->getCondition(), BICond, "or.cond")); 3137 3138 // Copy any debug value intrinsics into the end of PredBlock. 3139 for (Instruction &I : *BB) { 3140 if (isa<DbgInfoIntrinsic>(I)) { 3141 Instruction *NewI = I.clone(); 3142 RemapInstruction(NewI, VMap, 3143 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals); 3144 NewI->insertBefore(PBI); 3145 } 3146 } 3147 3148 ++NumFoldBranchToCommonDest; 3149 return true; 3150 } 3151 3152 /// Return if an instruction's type or any of its operands' types are a vector 3153 /// type. 3154 static bool isVectorOp(Instruction &I) { 3155 return I.getType()->isVectorTy() || any_of(I.operands(), [](Use &U) { 3156 return U->getType()->isVectorTy(); 3157 }); 3158 } 3159 3160 /// If this basic block is simple enough, and if a predecessor branches to us 3161 /// and one of our successors, fold the block into the predecessor and use 3162 /// logical operations to pick the right destination. 3163 bool llvm::FoldBranchToCommonDest(BranchInst *BI, DomTreeUpdater *DTU, 3164 MemorySSAUpdater *MSSAU, 3165 const TargetTransformInfo *TTI, 3166 unsigned BonusInstThreshold) { 3167 // If this block ends with an unconditional branch, 3168 // let SpeculativelyExecuteBB() deal with it. 3169 if (!BI->isConditional()) 3170 return false; 3171 3172 BasicBlock *BB = BI->getParent(); 3173 TargetTransformInfo::TargetCostKind CostKind = 3174 BB->getParent()->hasMinSize() ? TargetTransformInfo::TCK_CodeSize 3175 : TargetTransformInfo::TCK_SizeAndLatency; 3176 3177 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition()); 3178 3179 if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) || 3180 Cond->getParent() != BB || !Cond->hasOneUse()) 3181 return false; 3182 3183 // Cond is known to be a compare or binary operator. Check to make sure that 3184 // neither operand is a potentially-trapping constant expression. 3185 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0))) 3186 if (CE->canTrap()) 3187 return false; 3188 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1))) 3189 if (CE->canTrap()) 3190 return false; 3191 3192 // Finally, don't infinitely unroll conditional loops. 3193 if (is_contained(successors(BB), BB)) 3194 return false; 3195 3196 // With which predecessors will we want to deal with? 3197 SmallVector<BasicBlock *, 8> Preds; 3198 for (BasicBlock *PredBlock : predecessors(BB)) { 3199 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator()); 3200 3201 // Check that we have two conditional branches. If there is a PHI node in 3202 // the common successor, verify that the same value flows in from both 3203 // blocks. 3204 if (!PBI || PBI->isUnconditional() || !SafeToMergeTerminators(BI, PBI)) 3205 continue; 3206 3207 // Determine if the two branches share a common destination. 3208 Instruction::BinaryOps Opc; 3209 bool InvertPredCond; 3210 if (auto Recipe = shouldFoldCondBranchesToCommonDestination(BI, PBI, TTI)) 3211 std::tie(Opc, InvertPredCond) = *Recipe; 3212 else 3213 continue; 3214 3215 // Check the cost of inserting the necessary logic before performing the 3216 // transformation. 3217 if (TTI) { 3218 Type *Ty = BI->getCondition()->getType(); 3219 InstructionCost Cost = TTI->getArithmeticInstrCost(Opc, Ty, CostKind); 3220 if (InvertPredCond && (!PBI->getCondition()->hasOneUse() || 3221 !isa<CmpInst>(PBI->getCondition()))) 3222 Cost += TTI->getArithmeticInstrCost(Instruction::Xor, Ty, CostKind); 3223 3224 if (Cost > BranchFoldThreshold) 3225 continue; 3226 } 3227 3228 // Ok, we do want to deal with this predecessor. Record it. 3229 Preds.emplace_back(PredBlock); 3230 } 3231 3232 // If there aren't any predecessors into which we can fold, 3233 // don't bother checking the cost. 3234 if (Preds.empty()) 3235 return false; 3236 3237 // Only allow this transformation if computing the condition doesn't involve 3238 // too many instructions and these involved instructions can be executed 3239 // unconditionally. We denote all involved instructions except the condition 3240 // as "bonus instructions", and only allow this transformation when the 3241 // number of the bonus instructions we'll need to create when cloning into 3242 // each predecessor does not exceed a certain threshold. 3243 unsigned NumBonusInsts = 0; 3244 bool SawVectorOp = false; 3245 const unsigned PredCount = Preds.size(); 3246 for (Instruction &I : *BB) { 3247 // Don't check the branch condition comparison itself. 3248 if (&I == Cond) 3249 continue; 3250 // Ignore dbg intrinsics, and the terminator. 3251 if (isa<DbgInfoIntrinsic>(I) || isa<BranchInst>(I)) 3252 continue; 3253 // I must be safe to execute unconditionally. 3254 if (!isSafeToSpeculativelyExecute(&I)) 3255 return false; 3256 SawVectorOp |= isVectorOp(I); 3257 3258 // Account for the cost of duplicating this instruction into each 3259 // predecessor. Ignore free instructions. 3260 if (!TTI || 3261 TTI->getUserCost(&I, CostKind) != TargetTransformInfo::TCC_Free) { 3262 NumBonusInsts += PredCount; 3263 3264 // Early exits once we reach the limit. 3265 if (NumBonusInsts > 3266 BonusInstThreshold * BranchFoldToCommonDestVectorMultiplier) 3267 return false; 3268 } 3269 3270 auto IsBCSSAUse = [BB, &I](Use &U) { 3271 auto *UI = cast<Instruction>(U.getUser()); 3272 if (auto *PN = dyn_cast<PHINode>(UI)) 3273 return PN->getIncomingBlock(U) == BB; 3274 return UI->getParent() == BB && I.comesBefore(UI); 3275 }; 3276 3277 // Does this instruction require rewriting of uses? 3278 if (!all_of(I.uses(), IsBCSSAUse)) 3279 return false; 3280 } 3281 if (NumBonusInsts > 3282 BonusInstThreshold * 3283 (SawVectorOp ? BranchFoldToCommonDestVectorMultiplier : 1)) 3284 return false; 3285 3286 // Ok, we have the budget. Perform the transformation. 3287 for (BasicBlock *PredBlock : Preds) { 3288 auto *PBI = cast<BranchInst>(PredBlock->getTerminator()); 3289 return performBranchToCommonDestFolding(BI, PBI, DTU, MSSAU, TTI); 3290 } 3291 return false; 3292 } 3293 3294 // If there is only one store in BB1 and BB2, return it, otherwise return 3295 // nullptr. 3296 static StoreInst *findUniqueStoreInBlocks(BasicBlock *BB1, BasicBlock *BB2) { 3297 StoreInst *S = nullptr; 3298 for (auto *BB : {BB1, BB2}) { 3299 if (!BB) 3300 continue; 3301 for (auto &I : *BB) 3302 if (auto *SI = dyn_cast<StoreInst>(&I)) { 3303 if (S) 3304 // Multiple stores seen. 3305 return nullptr; 3306 else 3307 S = SI; 3308 } 3309 } 3310 return S; 3311 } 3312 3313 static Value *ensureValueAvailableInSuccessor(Value *V, BasicBlock *BB, 3314 Value *AlternativeV = nullptr) { 3315 // PHI is going to be a PHI node that allows the value V that is defined in 3316 // BB to be referenced in BB's only successor. 3317 // 3318 // If AlternativeV is nullptr, the only value we care about in PHI is V. It 3319 // doesn't matter to us what the other operand is (it'll never get used). We 3320 // could just create a new PHI with an undef incoming value, but that could 3321 // increase register pressure if EarlyCSE/InstCombine can't fold it with some 3322 // other PHI. So here we directly look for some PHI in BB's successor with V 3323 // as an incoming operand. If we find one, we use it, else we create a new 3324 // one. 3325 // 3326 // If AlternativeV is not nullptr, we care about both incoming values in PHI. 3327 // PHI must be exactly: phi <ty> [ %BB, %V ], [ %OtherBB, %AlternativeV] 3328 // where OtherBB is the single other predecessor of BB's only successor. 3329 PHINode *PHI = nullptr; 3330 BasicBlock *Succ = BB->getSingleSuccessor(); 3331 3332 for (auto I = Succ->begin(); isa<PHINode>(I); ++I) 3333 if (cast<PHINode>(I)->getIncomingValueForBlock(BB) == V) { 3334 PHI = cast<PHINode>(I); 3335 if (!AlternativeV) 3336 break; 3337 3338 assert(Succ->hasNPredecessors(2)); 3339 auto PredI = pred_begin(Succ); 3340 BasicBlock *OtherPredBB = *PredI == BB ? *++PredI : *PredI; 3341 if (PHI->getIncomingValueForBlock(OtherPredBB) == AlternativeV) 3342 break; 3343 PHI = nullptr; 3344 } 3345 if (PHI) 3346 return PHI; 3347 3348 // If V is not an instruction defined in BB, just return it. 3349 if (!AlternativeV && 3350 (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB)) 3351 return V; 3352 3353 PHI = PHINode::Create(V->getType(), 2, "simplifycfg.merge", &Succ->front()); 3354 PHI->addIncoming(V, BB); 3355 for (BasicBlock *PredBB : predecessors(Succ)) 3356 if (PredBB != BB) 3357 PHI->addIncoming( 3358 AlternativeV ? AlternativeV : UndefValue::get(V->getType()), PredBB); 3359 return PHI; 3360 } 3361 3362 static bool mergeConditionalStoreToAddress( 3363 BasicBlock *PTB, BasicBlock *PFB, BasicBlock *QTB, BasicBlock *QFB, 3364 BasicBlock *PostBB, Value *Address, bool InvertPCond, bool InvertQCond, 3365 DomTreeUpdater *DTU, const DataLayout &DL, const TargetTransformInfo &TTI) { 3366 // For every pointer, there must be exactly two stores, one coming from 3367 // PTB or PFB, and the other from QTB or QFB. We don't support more than one 3368 // store (to any address) in PTB,PFB or QTB,QFB. 3369 // FIXME: We could relax this restriction with a bit more work and performance 3370 // testing. 3371 StoreInst *PStore = findUniqueStoreInBlocks(PTB, PFB); 3372 StoreInst *QStore = findUniqueStoreInBlocks(QTB, QFB); 3373 if (!PStore || !QStore) 3374 return false; 3375 3376 // Now check the stores are compatible. 3377 if (!QStore->isUnordered() || !PStore->isUnordered()) 3378 return false; 3379 3380 // Check that sinking the store won't cause program behavior changes. Sinking 3381 // the store out of the Q blocks won't change any behavior as we're sinking 3382 // from a block to its unconditional successor. But we're moving a store from 3383 // the P blocks down through the middle block (QBI) and past both QFB and QTB. 3384 // So we need to check that there are no aliasing loads or stores in 3385 // QBI, QTB and QFB. We also need to check there are no conflicting memory 3386 // operations between PStore and the end of its parent block. 3387 // 3388 // The ideal way to do this is to query AliasAnalysis, but we don't 3389 // preserve AA currently so that is dangerous. Be super safe and just 3390 // check there are no other memory operations at all. 3391 for (auto &I : *QFB->getSinglePredecessor()) 3392 if (I.mayReadOrWriteMemory()) 3393 return false; 3394 for (auto &I : *QFB) 3395 if (&I != QStore && I.mayReadOrWriteMemory()) 3396 return false; 3397 if (QTB) 3398 for (auto &I : *QTB) 3399 if (&I != QStore && I.mayReadOrWriteMemory()) 3400 return false; 3401 for (auto I = BasicBlock::iterator(PStore), E = PStore->getParent()->end(); 3402 I != E; ++I) 3403 if (&*I != PStore && I->mayReadOrWriteMemory()) 3404 return false; 3405 3406 // If we're not in aggressive mode, we only optimize if we have some 3407 // confidence that by optimizing we'll allow P and/or Q to be if-converted. 3408 auto IsWorthwhile = [&](BasicBlock *BB, ArrayRef<StoreInst *> FreeStores) { 3409 if (!BB) 3410 return true; 3411 // Heuristic: if the block can be if-converted/phi-folded and the 3412 // instructions inside are all cheap (arithmetic/GEPs), it's worthwhile to 3413 // thread this store. 3414 InstructionCost Cost = 0; 3415 InstructionCost Budget = 3416 PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic; 3417 for (auto &I : BB->instructionsWithoutDebug(false)) { 3418 // Consider terminator instruction to be free. 3419 if (I.isTerminator()) 3420 continue; 3421 // If this is one the stores that we want to speculate out of this BB, 3422 // then don't count it's cost, consider it to be free. 3423 if (auto *S = dyn_cast<StoreInst>(&I)) 3424 if (llvm::find(FreeStores, S)) 3425 continue; 3426 // Else, we have a white-list of instructions that we are ak speculating. 3427 if (!isa<BinaryOperator>(I) && !isa<GetElementPtrInst>(I)) 3428 return false; // Not in white-list - not worthwhile folding. 3429 // And finally, if this is a non-free instruction that we are okay 3430 // speculating, ensure that we consider the speculation budget. 3431 Cost += TTI.getUserCost(&I, TargetTransformInfo::TCK_SizeAndLatency); 3432 if (Cost > Budget) 3433 return false; // Eagerly refuse to fold as soon as we're out of budget. 3434 } 3435 assert(Cost <= Budget && 3436 "When we run out of budget we will eagerly return from within the " 3437 "per-instruction loop."); 3438 return true; 3439 }; 3440 3441 const std::array<StoreInst *, 2> FreeStores = {PStore, QStore}; 3442 if (!MergeCondStoresAggressively && 3443 (!IsWorthwhile(PTB, FreeStores) || !IsWorthwhile(PFB, FreeStores) || 3444 !IsWorthwhile(QTB, FreeStores) || !IsWorthwhile(QFB, FreeStores))) 3445 return false; 3446 3447 // If PostBB has more than two predecessors, we need to split it so we can 3448 // sink the store. 3449 if (std::next(pred_begin(PostBB), 2) != pred_end(PostBB)) { 3450 // We know that QFB's only successor is PostBB. And QFB has a single 3451 // predecessor. If QTB exists, then its only successor is also PostBB. 3452 // If QTB does not exist, then QFB's only predecessor has a conditional 3453 // branch to QFB and PostBB. 3454 BasicBlock *TruePred = QTB ? QTB : QFB->getSinglePredecessor(); 3455 BasicBlock *NewBB = 3456 SplitBlockPredecessors(PostBB, {QFB, TruePred}, "condstore.split", DTU); 3457 if (!NewBB) 3458 return false; 3459 PostBB = NewBB; 3460 } 3461 3462 // OK, we're going to sink the stores to PostBB. The store has to be 3463 // conditional though, so first create the predicate. 3464 Value *PCond = cast<BranchInst>(PFB->getSinglePredecessor()->getTerminator()) 3465 ->getCondition(); 3466 Value *QCond = cast<BranchInst>(QFB->getSinglePredecessor()->getTerminator()) 3467 ->getCondition(); 3468 3469 Value *PPHI = ensureValueAvailableInSuccessor(PStore->getValueOperand(), 3470 PStore->getParent()); 3471 Value *QPHI = ensureValueAvailableInSuccessor(QStore->getValueOperand(), 3472 QStore->getParent(), PPHI); 3473 3474 IRBuilder<> QB(&*PostBB->getFirstInsertionPt()); 3475 3476 Value *PPred = PStore->getParent() == PTB ? PCond : QB.CreateNot(PCond); 3477 Value *QPred = QStore->getParent() == QTB ? QCond : QB.CreateNot(QCond); 3478 3479 if (InvertPCond) 3480 PPred = QB.CreateNot(PPred); 3481 if (InvertQCond) 3482 QPred = QB.CreateNot(QPred); 3483 Value *CombinedPred = QB.CreateOr(PPred, QPred); 3484 3485 auto *T = SplitBlockAndInsertIfThen(CombinedPred, &*QB.GetInsertPoint(), 3486 /*Unreachable=*/false, 3487 /*BranchWeights=*/nullptr, DTU); 3488 QB.SetInsertPoint(T); 3489 StoreInst *SI = cast<StoreInst>(QB.CreateStore(QPHI, Address)); 3490 SI->setAAMetadata(PStore->getAAMetadata().merge(QStore->getAAMetadata())); 3491 // Choose the minimum alignment. If we could prove both stores execute, we 3492 // could use biggest one. In this case, though, we only know that one of the 3493 // stores executes. And we don't know it's safe to take the alignment from a 3494 // store that doesn't execute. 3495 SI->setAlignment(std::min(PStore->getAlign(), QStore->getAlign())); 3496 3497 QStore->eraseFromParent(); 3498 PStore->eraseFromParent(); 3499 3500 return true; 3501 } 3502 3503 static bool mergeConditionalStores(BranchInst *PBI, BranchInst *QBI, 3504 DomTreeUpdater *DTU, const DataLayout &DL, 3505 const TargetTransformInfo &TTI) { 3506 // The intention here is to find diamonds or triangles (see below) where each 3507 // conditional block contains a store to the same address. Both of these 3508 // stores are conditional, so they can't be unconditionally sunk. But it may 3509 // be profitable to speculatively sink the stores into one merged store at the 3510 // end, and predicate the merged store on the union of the two conditions of 3511 // PBI and QBI. 3512 // 3513 // This can reduce the number of stores executed if both of the conditions are 3514 // true, and can allow the blocks to become small enough to be if-converted. 3515 // This optimization will also chain, so that ladders of test-and-set 3516 // sequences can be if-converted away. 3517 // 3518 // We only deal with simple diamonds or triangles: 3519 // 3520 // PBI or PBI or a combination of the two 3521 // / \ | \ 3522 // PTB PFB | PFB 3523 // \ / | / 3524 // QBI QBI 3525 // / \ | \ 3526 // QTB QFB | QFB 3527 // \ / | / 3528 // PostBB PostBB 3529 // 3530 // We model triangles as a type of diamond with a nullptr "true" block. 3531 // Triangles are canonicalized so that the fallthrough edge is represented by 3532 // a true condition, as in the diagram above. 3533 BasicBlock *PTB = PBI->getSuccessor(0); 3534 BasicBlock *PFB = PBI->getSuccessor(1); 3535 BasicBlock *QTB = QBI->getSuccessor(0); 3536 BasicBlock *QFB = QBI->getSuccessor(1); 3537 BasicBlock *PostBB = QFB->getSingleSuccessor(); 3538 3539 // Make sure we have a good guess for PostBB. If QTB's only successor is 3540 // QFB, then QFB is a better PostBB. 3541 if (QTB->getSingleSuccessor() == QFB) 3542 PostBB = QFB; 3543 3544 // If we couldn't find a good PostBB, stop. 3545 if (!PostBB) 3546 return false; 3547 3548 bool InvertPCond = false, InvertQCond = false; 3549 // Canonicalize fallthroughs to the true branches. 3550 if (PFB == QBI->getParent()) { 3551 std::swap(PFB, PTB); 3552 InvertPCond = true; 3553 } 3554 if (QFB == PostBB) { 3555 std::swap(QFB, QTB); 3556 InvertQCond = true; 3557 } 3558 3559 // From this point on we can assume PTB or QTB may be fallthroughs but PFB 3560 // and QFB may not. Model fallthroughs as a nullptr block. 3561 if (PTB == QBI->getParent()) 3562 PTB = nullptr; 3563 if (QTB == PostBB) 3564 QTB = nullptr; 3565 3566 // Legality bailouts. We must have at least the non-fallthrough blocks and 3567 // the post-dominating block, and the non-fallthroughs must only have one 3568 // predecessor. 3569 auto HasOnePredAndOneSucc = [](BasicBlock *BB, BasicBlock *P, BasicBlock *S) { 3570 return BB->getSinglePredecessor() == P && BB->getSingleSuccessor() == S; 3571 }; 3572 if (!HasOnePredAndOneSucc(PFB, PBI->getParent(), QBI->getParent()) || 3573 !HasOnePredAndOneSucc(QFB, QBI->getParent(), PostBB)) 3574 return false; 3575 if ((PTB && !HasOnePredAndOneSucc(PTB, PBI->getParent(), QBI->getParent())) || 3576 (QTB && !HasOnePredAndOneSucc(QTB, QBI->getParent(), PostBB))) 3577 return false; 3578 if (!QBI->getParent()->hasNUses(2)) 3579 return false; 3580 3581 // OK, this is a sequence of two diamonds or triangles. 3582 // Check if there are stores in PTB or PFB that are repeated in QTB or QFB. 3583 SmallPtrSet<Value *, 4> PStoreAddresses, QStoreAddresses; 3584 for (auto *BB : {PTB, PFB}) { 3585 if (!BB) 3586 continue; 3587 for (auto &I : *BB) 3588 if (StoreInst *SI = dyn_cast<StoreInst>(&I)) 3589 PStoreAddresses.insert(SI->getPointerOperand()); 3590 } 3591 for (auto *BB : {QTB, QFB}) { 3592 if (!BB) 3593 continue; 3594 for (auto &I : *BB) 3595 if (StoreInst *SI = dyn_cast<StoreInst>(&I)) 3596 QStoreAddresses.insert(SI->getPointerOperand()); 3597 } 3598 3599 set_intersect(PStoreAddresses, QStoreAddresses); 3600 // set_intersect mutates PStoreAddresses in place. Rename it here to make it 3601 // clear what it contains. 3602 auto &CommonAddresses = PStoreAddresses; 3603 3604 bool Changed = false; 3605 for (auto *Address : CommonAddresses) 3606 Changed |= 3607 mergeConditionalStoreToAddress(PTB, PFB, QTB, QFB, PostBB, Address, 3608 InvertPCond, InvertQCond, DTU, DL, TTI); 3609 return Changed; 3610 } 3611 3612 /// If the previous block ended with a widenable branch, determine if reusing 3613 /// the target block is profitable and legal. This will have the effect of 3614 /// "widening" PBI, but doesn't require us to reason about hosting safety. 3615 static bool tryWidenCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI, 3616 DomTreeUpdater *DTU) { 3617 // TODO: This can be generalized in two important ways: 3618 // 1) We can allow phi nodes in IfFalseBB and simply reuse all the input 3619 // values from the PBI edge. 3620 // 2) We can sink side effecting instructions into BI's fallthrough 3621 // successor provided they doesn't contribute to computation of 3622 // BI's condition. 3623 Value *CondWB, *WC; 3624 BasicBlock *IfTrueBB, *IfFalseBB; 3625 if (!parseWidenableBranch(PBI, CondWB, WC, IfTrueBB, IfFalseBB) || 3626 IfTrueBB != BI->getParent() || !BI->getParent()->getSinglePredecessor()) 3627 return false; 3628 if (!IfFalseBB->phis().empty()) 3629 return false; // TODO 3630 // Use lambda to lazily compute expensive condition after cheap ones. 3631 auto NoSideEffects = [](BasicBlock &BB) { 3632 return !llvm::any_of(BB, [](const Instruction &I) { 3633 return I.mayWriteToMemory() || I.mayHaveSideEffects(); 3634 }); 3635 }; 3636 if (BI->getSuccessor(1) != IfFalseBB && // no inf looping 3637 BI->getSuccessor(1)->getTerminatingDeoptimizeCall() && // profitability 3638 NoSideEffects(*BI->getParent())) { 3639 auto *OldSuccessor = BI->getSuccessor(1); 3640 OldSuccessor->removePredecessor(BI->getParent()); 3641 BI->setSuccessor(1, IfFalseBB); 3642 if (DTU) 3643 DTU->applyUpdates( 3644 {{DominatorTree::Insert, BI->getParent(), IfFalseBB}, 3645 {DominatorTree::Delete, BI->getParent(), OldSuccessor}}); 3646 return true; 3647 } 3648 if (BI->getSuccessor(0) != IfFalseBB && // no inf looping 3649 BI->getSuccessor(0)->getTerminatingDeoptimizeCall() && // profitability 3650 NoSideEffects(*BI->getParent())) { 3651 auto *OldSuccessor = BI->getSuccessor(0); 3652 OldSuccessor->removePredecessor(BI->getParent()); 3653 BI->setSuccessor(0, IfFalseBB); 3654 if (DTU) 3655 DTU->applyUpdates( 3656 {{DominatorTree::Insert, BI->getParent(), IfFalseBB}, 3657 {DominatorTree::Delete, BI->getParent(), OldSuccessor}}); 3658 return true; 3659 } 3660 return false; 3661 } 3662 3663 /// If we have a conditional branch as a predecessor of another block, 3664 /// this function tries to simplify it. We know 3665 /// that PBI and BI are both conditional branches, and BI is in one of the 3666 /// successor blocks of PBI - PBI branches to BI. 3667 static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI, 3668 DomTreeUpdater *DTU, 3669 const DataLayout &DL, 3670 const TargetTransformInfo &TTI) { 3671 assert(PBI->isConditional() && BI->isConditional()); 3672 BasicBlock *BB = BI->getParent(); 3673 3674 // If this block ends with a branch instruction, and if there is a 3675 // predecessor that ends on a branch of the same condition, make 3676 // this conditional branch redundant. 3677 if (PBI->getCondition() == BI->getCondition() && 3678 PBI->getSuccessor(0) != PBI->getSuccessor(1)) { 3679 // Okay, the outcome of this conditional branch is statically 3680 // knowable. If this block had a single pred, handle specially. 3681 if (BB->getSinglePredecessor()) { 3682 // Turn this into a branch on constant. 3683 bool CondIsTrue = PBI->getSuccessor(0) == BB; 3684 BI->setCondition( 3685 ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue)); 3686 return true; // Nuke the branch on constant. 3687 } 3688 3689 // Otherwise, if there are multiple predecessors, insert a PHI that merges 3690 // in the constant and simplify the block result. Subsequent passes of 3691 // simplifycfg will thread the block. 3692 if (BlockIsSimpleEnoughToThreadThrough(BB)) { 3693 pred_iterator PB = pred_begin(BB), PE = pred_end(BB); 3694 PHINode *NewPN = PHINode::Create( 3695 Type::getInt1Ty(BB->getContext()), std::distance(PB, PE), 3696 BI->getCondition()->getName() + ".pr", &BB->front()); 3697 // Okay, we're going to insert the PHI node. Since PBI is not the only 3698 // predecessor, compute the PHI'd conditional value for all of the preds. 3699 // Any predecessor where the condition is not computable we keep symbolic. 3700 for (pred_iterator PI = PB; PI != PE; ++PI) { 3701 BasicBlock *P = *PI; 3702 if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) && PBI != BI && 3703 PBI->isConditional() && PBI->getCondition() == BI->getCondition() && 3704 PBI->getSuccessor(0) != PBI->getSuccessor(1)) { 3705 bool CondIsTrue = PBI->getSuccessor(0) == BB; 3706 NewPN->addIncoming( 3707 ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue), 3708 P); 3709 } else { 3710 NewPN->addIncoming(BI->getCondition(), P); 3711 } 3712 } 3713 3714 BI->setCondition(NewPN); 3715 return true; 3716 } 3717 } 3718 3719 // If the previous block ended with a widenable branch, determine if reusing 3720 // the target block is profitable and legal. This will have the effect of 3721 // "widening" PBI, but doesn't require us to reason about hosting safety. 3722 if (tryWidenCondBranchToCondBranch(PBI, BI, DTU)) 3723 return true; 3724 3725 if (auto *CE = dyn_cast<ConstantExpr>(BI->getCondition())) 3726 if (CE->canTrap()) 3727 return false; 3728 3729 // If both branches are conditional and both contain stores to the same 3730 // address, remove the stores from the conditionals and create a conditional 3731 // merged store at the end. 3732 if (MergeCondStores && mergeConditionalStores(PBI, BI, DTU, DL, TTI)) 3733 return true; 3734 3735 // If this is a conditional branch in an empty block, and if any 3736 // predecessors are a conditional branch to one of our destinations, 3737 // fold the conditions into logical ops and one cond br. 3738 3739 // Ignore dbg intrinsics. 3740 if (&*BB->instructionsWithoutDebug(false).begin() != BI) 3741 return false; 3742 3743 int PBIOp, BIOp; 3744 if (PBI->getSuccessor(0) == BI->getSuccessor(0)) { 3745 PBIOp = 0; 3746 BIOp = 0; 3747 } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) { 3748 PBIOp = 0; 3749 BIOp = 1; 3750 } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) { 3751 PBIOp = 1; 3752 BIOp = 0; 3753 } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) { 3754 PBIOp = 1; 3755 BIOp = 1; 3756 } else { 3757 return false; 3758 } 3759 3760 // Check to make sure that the other destination of this branch 3761 // isn't BB itself. If so, this is an infinite loop that will 3762 // keep getting unwound. 3763 if (PBI->getSuccessor(PBIOp) == BB) 3764 return false; 3765 3766 // Do not perform this transformation if it would require 3767 // insertion of a large number of select instructions. For targets 3768 // without predication/cmovs, this is a big pessimization. 3769 3770 // Also do not perform this transformation if any phi node in the common 3771 // destination block can trap when reached by BB or PBB (PR17073). In that 3772 // case, it would be unsafe to hoist the operation into a select instruction. 3773 3774 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp); 3775 BasicBlock *RemovedDest = PBI->getSuccessor(PBIOp ^ 1); 3776 unsigned NumPhis = 0; 3777 for (BasicBlock::iterator II = CommonDest->begin(); isa<PHINode>(II); 3778 ++II, ++NumPhis) { 3779 if (NumPhis > 2) // Disable this xform. 3780 return false; 3781 3782 PHINode *PN = cast<PHINode>(II); 3783 Value *BIV = PN->getIncomingValueForBlock(BB); 3784 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV)) 3785 if (CE->canTrap()) 3786 return false; 3787 3788 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent()); 3789 Value *PBIV = PN->getIncomingValue(PBBIdx); 3790 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV)) 3791 if (CE->canTrap()) 3792 return false; 3793 } 3794 3795 // Finally, if everything is ok, fold the branches to logical ops. 3796 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1); 3797 3798 LLVM_DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent() 3799 << "AND: " << *BI->getParent()); 3800 3801 SmallVector<DominatorTree::UpdateType, 5> Updates; 3802 3803 // If OtherDest *is* BB, then BB is a basic block with a single conditional 3804 // branch in it, where one edge (OtherDest) goes back to itself but the other 3805 // exits. We don't *know* that the program avoids the infinite loop 3806 // (even though that seems likely). If we do this xform naively, we'll end up 3807 // recursively unpeeling the loop. Since we know that (after the xform is 3808 // done) that the block *is* infinite if reached, we just make it an obviously 3809 // infinite loop with no cond branch. 3810 if (OtherDest == BB) { 3811 // Insert it at the end of the function, because it's either code, 3812 // or it won't matter if it's hot. :) 3813 BasicBlock *InfLoopBlock = 3814 BasicBlock::Create(BB->getContext(), "infloop", BB->getParent()); 3815 BranchInst::Create(InfLoopBlock, InfLoopBlock); 3816 if (DTU) 3817 Updates.push_back({DominatorTree::Insert, InfLoopBlock, InfLoopBlock}); 3818 OtherDest = InfLoopBlock; 3819 } 3820 3821 LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent()); 3822 3823 // BI may have other predecessors. Because of this, we leave 3824 // it alone, but modify PBI. 3825 3826 // Make sure we get to CommonDest on True&True directions. 3827 Value *PBICond = PBI->getCondition(); 3828 IRBuilder<NoFolder> Builder(PBI); 3829 if (PBIOp) 3830 PBICond = Builder.CreateNot(PBICond, PBICond->getName() + ".not"); 3831 3832 Value *BICond = BI->getCondition(); 3833 if (BIOp) 3834 BICond = Builder.CreateNot(BICond, BICond->getName() + ".not"); 3835 3836 // Merge the conditions. 3837 Value *Cond = 3838 createLogicalOp(Builder, Instruction::Or, PBICond, BICond, "brmerge"); 3839 3840 // Modify PBI to branch on the new condition to the new dests. 3841 PBI->setCondition(Cond); 3842 PBI->setSuccessor(0, CommonDest); 3843 PBI->setSuccessor(1, OtherDest); 3844 3845 if (DTU) { 3846 Updates.push_back({DominatorTree::Insert, PBI->getParent(), OtherDest}); 3847 Updates.push_back({DominatorTree::Delete, PBI->getParent(), RemovedDest}); 3848 3849 DTU->applyUpdates(Updates); 3850 } 3851 3852 // Update branch weight for PBI. 3853 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight; 3854 uint64_t PredCommon, PredOther, SuccCommon, SuccOther; 3855 bool HasWeights = 3856 extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight, 3857 SuccTrueWeight, SuccFalseWeight); 3858 if (HasWeights) { 3859 PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight; 3860 PredOther = PBIOp ? PredTrueWeight : PredFalseWeight; 3861 SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight; 3862 SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight; 3863 // The weight to CommonDest should be PredCommon * SuccTotal + 3864 // PredOther * SuccCommon. 3865 // The weight to OtherDest should be PredOther * SuccOther. 3866 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) + 3867 PredOther * SuccCommon, 3868 PredOther * SuccOther}; 3869 // Halve the weights if any of them cannot fit in an uint32_t 3870 FitWeights(NewWeights); 3871 3872 setBranchWeights(PBI, NewWeights[0], NewWeights[1]); 3873 } 3874 3875 // OtherDest may have phi nodes. If so, add an entry from PBI's 3876 // block that are identical to the entries for BI's block. 3877 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB); 3878 3879 // We know that the CommonDest already had an edge from PBI to 3880 // it. If it has PHIs though, the PHIs may have different 3881 // entries for BB and PBI's BB. If so, insert a select to make 3882 // them agree. 3883 for (PHINode &PN : CommonDest->phis()) { 3884 Value *BIV = PN.getIncomingValueForBlock(BB); 3885 unsigned PBBIdx = PN.getBasicBlockIndex(PBI->getParent()); 3886 Value *PBIV = PN.getIncomingValue(PBBIdx); 3887 if (BIV != PBIV) { 3888 // Insert a select in PBI to pick the right value. 3889 SelectInst *NV = cast<SelectInst>( 3890 Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName() + ".mux")); 3891 PN.setIncomingValue(PBBIdx, NV); 3892 // Although the select has the same condition as PBI, the original branch 3893 // weights for PBI do not apply to the new select because the select's 3894 // 'logical' edges are incoming edges of the phi that is eliminated, not 3895 // the outgoing edges of PBI. 3896 if (HasWeights) { 3897 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight; 3898 uint64_t PredOther = PBIOp ? PredTrueWeight : PredFalseWeight; 3899 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight; 3900 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight; 3901 // The weight to PredCommonDest should be PredCommon * SuccTotal. 3902 // The weight to PredOtherDest should be PredOther * SuccCommon. 3903 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther), 3904 PredOther * SuccCommon}; 3905 3906 FitWeights(NewWeights); 3907 3908 setBranchWeights(NV, NewWeights[0], NewWeights[1]); 3909 } 3910 } 3911 } 3912 3913 LLVM_DEBUG(dbgs() << "INTO: " << *PBI->getParent()); 3914 LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent()); 3915 3916 // This basic block is probably dead. We know it has at least 3917 // one fewer predecessor. 3918 return true; 3919 } 3920 3921 // Simplifies a terminator by replacing it with a branch to TrueBB if Cond is 3922 // true or to FalseBB if Cond is false. 3923 // Takes care of updating the successors and removing the old terminator. 3924 // Also makes sure not to introduce new successors by assuming that edges to 3925 // non-successor TrueBBs and FalseBBs aren't reachable. 3926 bool SimplifyCFGOpt::SimplifyTerminatorOnSelect(Instruction *OldTerm, 3927 Value *Cond, BasicBlock *TrueBB, 3928 BasicBlock *FalseBB, 3929 uint32_t TrueWeight, 3930 uint32_t FalseWeight) { 3931 auto *BB = OldTerm->getParent(); 3932 // Remove any superfluous successor edges from the CFG. 3933 // First, figure out which successors to preserve. 3934 // If TrueBB and FalseBB are equal, only try to preserve one copy of that 3935 // successor. 3936 BasicBlock *KeepEdge1 = TrueBB; 3937 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr; 3938 3939 SmallPtrSet<BasicBlock *, 2> RemovedSuccessors; 3940 3941 // Then remove the rest. 3942 for (BasicBlock *Succ : successors(OldTerm)) { 3943 // Make sure only to keep exactly one copy of each edge. 3944 if (Succ == KeepEdge1) 3945 KeepEdge1 = nullptr; 3946 else if (Succ == KeepEdge2) 3947 KeepEdge2 = nullptr; 3948 else { 3949 Succ->removePredecessor(BB, 3950 /*KeepOneInputPHIs=*/true); 3951 3952 if (Succ != TrueBB && Succ != FalseBB) 3953 RemovedSuccessors.insert(Succ); 3954 } 3955 } 3956 3957 IRBuilder<> Builder(OldTerm); 3958 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc()); 3959 3960 // Insert an appropriate new terminator. 3961 if (!KeepEdge1 && !KeepEdge2) { 3962 if (TrueBB == FalseBB) { 3963 // We were only looking for one successor, and it was present. 3964 // Create an unconditional branch to it. 3965 Builder.CreateBr(TrueBB); 3966 } else { 3967 // We found both of the successors we were looking for. 3968 // Create a conditional branch sharing the condition of the select. 3969 BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB); 3970 if (TrueWeight != FalseWeight) 3971 setBranchWeights(NewBI, TrueWeight, FalseWeight); 3972 } 3973 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) { 3974 // Neither of the selected blocks were successors, so this 3975 // terminator must be unreachable. 3976 new UnreachableInst(OldTerm->getContext(), OldTerm); 3977 } else { 3978 // One of the selected values was a successor, but the other wasn't. 3979 // Insert an unconditional branch to the one that was found; 3980 // the edge to the one that wasn't must be unreachable. 3981 if (!KeepEdge1) { 3982 // Only TrueBB was found. 3983 Builder.CreateBr(TrueBB); 3984 } else { 3985 // Only FalseBB was found. 3986 Builder.CreateBr(FalseBB); 3987 } 3988 } 3989 3990 EraseTerminatorAndDCECond(OldTerm); 3991 3992 if (DTU) { 3993 SmallVector<DominatorTree::UpdateType, 2> Updates; 3994 Updates.reserve(RemovedSuccessors.size()); 3995 for (auto *RemovedSuccessor : RemovedSuccessors) 3996 Updates.push_back({DominatorTree::Delete, BB, RemovedSuccessor}); 3997 DTU->applyUpdates(Updates); 3998 } 3999 4000 return true; 4001 } 4002 4003 // Replaces 4004 // (switch (select cond, X, Y)) on constant X, Y 4005 // with a branch - conditional if X and Y lead to distinct BBs, 4006 // unconditional otherwise. 4007 bool SimplifyCFGOpt::SimplifySwitchOnSelect(SwitchInst *SI, 4008 SelectInst *Select) { 4009 // Check for constant integer values in the select. 4010 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue()); 4011 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue()); 4012 if (!TrueVal || !FalseVal) 4013 return false; 4014 4015 // Find the relevant condition and destinations. 4016 Value *Condition = Select->getCondition(); 4017 BasicBlock *TrueBB = SI->findCaseValue(TrueVal)->getCaseSuccessor(); 4018 BasicBlock *FalseBB = SI->findCaseValue(FalseVal)->getCaseSuccessor(); 4019 4020 // Get weight for TrueBB and FalseBB. 4021 uint32_t TrueWeight = 0, FalseWeight = 0; 4022 SmallVector<uint64_t, 8> Weights; 4023 bool HasWeights = HasBranchWeights(SI); 4024 if (HasWeights) { 4025 GetBranchWeights(SI, Weights); 4026 if (Weights.size() == 1 + SI->getNumCases()) { 4027 TrueWeight = 4028 (uint32_t)Weights[SI->findCaseValue(TrueVal)->getSuccessorIndex()]; 4029 FalseWeight = 4030 (uint32_t)Weights[SI->findCaseValue(FalseVal)->getSuccessorIndex()]; 4031 } 4032 } 4033 4034 // Perform the actual simplification. 4035 return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB, TrueWeight, 4036 FalseWeight); 4037 } 4038 4039 // Replaces 4040 // (indirectbr (select cond, blockaddress(@fn, BlockA), 4041 // blockaddress(@fn, BlockB))) 4042 // with 4043 // (br cond, BlockA, BlockB). 4044 bool SimplifyCFGOpt::SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, 4045 SelectInst *SI) { 4046 // Check that both operands of the select are block addresses. 4047 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue()); 4048 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue()); 4049 if (!TBA || !FBA) 4050 return false; 4051 4052 // Extract the actual blocks. 4053 BasicBlock *TrueBB = TBA->getBasicBlock(); 4054 BasicBlock *FalseBB = FBA->getBasicBlock(); 4055 4056 // Perform the actual simplification. 4057 return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB, 0, 4058 0); 4059 } 4060 4061 /// This is called when we find an icmp instruction 4062 /// (a seteq/setne with a constant) as the only instruction in a 4063 /// block that ends with an uncond branch. We are looking for a very specific 4064 /// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In 4065 /// this case, we merge the first two "or's of icmp" into a switch, but then the 4066 /// default value goes to an uncond block with a seteq in it, we get something 4067 /// like: 4068 /// 4069 /// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ] 4070 /// DEFAULT: 4071 /// %tmp = icmp eq i8 %A, 92 4072 /// br label %end 4073 /// end: 4074 /// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ] 4075 /// 4076 /// We prefer to split the edge to 'end' so that there is a true/false entry to 4077 /// the PHI, merging the third icmp into the switch. 4078 bool SimplifyCFGOpt::tryToSimplifyUncondBranchWithICmpInIt( 4079 ICmpInst *ICI, IRBuilder<> &Builder) { 4080 BasicBlock *BB = ICI->getParent(); 4081 4082 // If the block has any PHIs in it or the icmp has multiple uses, it is too 4083 // complex. 4084 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) 4085 return false; 4086 4087 Value *V = ICI->getOperand(0); 4088 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1)); 4089 4090 // The pattern we're looking for is where our only predecessor is a switch on 4091 // 'V' and this block is the default case for the switch. In this case we can 4092 // fold the compared value into the switch to simplify things. 4093 BasicBlock *Pred = BB->getSinglePredecessor(); 4094 if (!Pred || !isa<SwitchInst>(Pred->getTerminator())) 4095 return false; 4096 4097 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator()); 4098 if (SI->getCondition() != V) 4099 return false; 4100 4101 // If BB is reachable on a non-default case, then we simply know the value of 4102 // V in this block. Substitute it and constant fold the icmp instruction 4103 // away. 4104 if (SI->getDefaultDest() != BB) { 4105 ConstantInt *VVal = SI->findCaseDest(BB); 4106 assert(VVal && "Should have a unique destination value"); 4107 ICI->setOperand(0, VVal); 4108 4109 if (Value *V = SimplifyInstruction(ICI, {DL, ICI})) { 4110 ICI->replaceAllUsesWith(V); 4111 ICI->eraseFromParent(); 4112 } 4113 // BB is now empty, so it is likely to simplify away. 4114 return requestResimplify(); 4115 } 4116 4117 // Ok, the block is reachable from the default dest. If the constant we're 4118 // comparing exists in one of the other edges, then we can constant fold ICI 4119 // and zap it. 4120 if (SI->findCaseValue(Cst) != SI->case_default()) { 4121 Value *V; 4122 if (ICI->getPredicate() == ICmpInst::ICMP_EQ) 4123 V = ConstantInt::getFalse(BB->getContext()); 4124 else 4125 V = ConstantInt::getTrue(BB->getContext()); 4126 4127 ICI->replaceAllUsesWith(V); 4128 ICI->eraseFromParent(); 4129 // BB is now empty, so it is likely to simplify away. 4130 return requestResimplify(); 4131 } 4132 4133 // The use of the icmp has to be in the 'end' block, by the only PHI node in 4134 // the block. 4135 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0); 4136 PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back()); 4137 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() || 4138 isa<PHINode>(++BasicBlock::iterator(PHIUse))) 4139 return false; 4140 4141 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets 4142 // true in the PHI. 4143 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext()); 4144 Constant *NewCst = ConstantInt::getFalse(BB->getContext()); 4145 4146 if (ICI->getPredicate() == ICmpInst::ICMP_EQ) 4147 std::swap(DefaultCst, NewCst); 4148 4149 // Replace ICI (which is used by the PHI for the default value) with true or 4150 // false depending on if it is EQ or NE. 4151 ICI->replaceAllUsesWith(DefaultCst); 4152 ICI->eraseFromParent(); 4153 4154 SmallVector<DominatorTree::UpdateType, 2> Updates; 4155 4156 // Okay, the switch goes to this block on a default value. Add an edge from 4157 // the switch to the merge point on the compared value. 4158 BasicBlock *NewBB = 4159 BasicBlock::Create(BB->getContext(), "switch.edge", BB->getParent(), BB); 4160 { 4161 SwitchInstProfUpdateWrapper SIW(*SI); 4162 auto W0 = SIW.getSuccessorWeight(0); 4163 SwitchInstProfUpdateWrapper::CaseWeightOpt NewW; 4164 if (W0) { 4165 NewW = ((uint64_t(*W0) + 1) >> 1); 4166 SIW.setSuccessorWeight(0, *NewW); 4167 } 4168 SIW.addCase(Cst, NewBB, NewW); 4169 if (DTU) 4170 Updates.push_back({DominatorTree::Insert, Pred, NewBB}); 4171 } 4172 4173 // NewBB branches to the phi block, add the uncond branch and the phi entry. 4174 Builder.SetInsertPoint(NewBB); 4175 Builder.SetCurrentDebugLocation(SI->getDebugLoc()); 4176 Builder.CreateBr(SuccBlock); 4177 PHIUse->addIncoming(NewCst, NewBB); 4178 if (DTU) { 4179 Updates.push_back({DominatorTree::Insert, NewBB, SuccBlock}); 4180 DTU->applyUpdates(Updates); 4181 } 4182 return true; 4183 } 4184 4185 /// The specified branch is a conditional branch. 4186 /// Check to see if it is branching on an or/and chain of icmp instructions, and 4187 /// fold it into a switch instruction if so. 4188 bool SimplifyCFGOpt::SimplifyBranchOnICmpChain(BranchInst *BI, 4189 IRBuilder<> &Builder, 4190 const DataLayout &DL) { 4191 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition()); 4192 if (!Cond) 4193 return false; 4194 4195 // Change br (X == 0 | X == 1), T, F into a switch instruction. 4196 // If this is a bunch of seteq's or'd together, or if it's a bunch of 4197 // 'setne's and'ed together, collect them. 4198 4199 // Try to gather values from a chain of and/or to be turned into a switch 4200 ConstantComparesGatherer ConstantCompare(Cond, DL); 4201 // Unpack the result 4202 SmallVectorImpl<ConstantInt *> &Values = ConstantCompare.Vals; 4203 Value *CompVal = ConstantCompare.CompValue; 4204 unsigned UsedICmps = ConstantCompare.UsedICmps; 4205 Value *ExtraCase = ConstantCompare.Extra; 4206 4207 // If we didn't have a multiply compared value, fail. 4208 if (!CompVal) 4209 return false; 4210 4211 // Avoid turning single icmps into a switch. 4212 if (UsedICmps <= 1) 4213 return false; 4214 4215 bool TrueWhenEqual = match(Cond, m_LogicalOr(m_Value(), m_Value())); 4216 4217 // There might be duplicate constants in the list, which the switch 4218 // instruction can't handle, remove them now. 4219 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate); 4220 Values.erase(std::unique(Values.begin(), Values.end()), Values.end()); 4221 4222 // If Extra was used, we require at least two switch values to do the 4223 // transformation. A switch with one value is just a conditional branch. 4224 if (ExtraCase && Values.size() < 2) 4225 return false; 4226 4227 // TODO: Preserve branch weight metadata, similarly to how 4228 // FoldValueComparisonIntoPredecessors preserves it. 4229 4230 // Figure out which block is which destination. 4231 BasicBlock *DefaultBB = BI->getSuccessor(1); 4232 BasicBlock *EdgeBB = BI->getSuccessor(0); 4233 if (!TrueWhenEqual) 4234 std::swap(DefaultBB, EdgeBB); 4235 4236 BasicBlock *BB = BI->getParent(); 4237 4238 LLVM_DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size() 4239 << " cases into SWITCH. BB is:\n" 4240 << *BB); 4241 4242 SmallVector<DominatorTree::UpdateType, 2> Updates; 4243 4244 // If there are any extra values that couldn't be folded into the switch 4245 // then we evaluate them with an explicit branch first. Split the block 4246 // right before the condbr to handle it. 4247 if (ExtraCase) { 4248 BasicBlock *NewBB = SplitBlock(BB, BI, DTU, /*LI=*/nullptr, 4249 /*MSSAU=*/nullptr, "switch.early.test"); 4250 4251 // Remove the uncond branch added to the old block. 4252 Instruction *OldTI = BB->getTerminator(); 4253 Builder.SetInsertPoint(OldTI); 4254 4255 // There can be an unintended UB if extra values are Poison. Before the 4256 // transformation, extra values may not be evaluated according to the 4257 // condition, and it will not raise UB. But after transformation, we are 4258 // evaluating extra values before checking the condition, and it will raise 4259 // UB. It can be solved by adding freeze instruction to extra values. 4260 AssumptionCache *AC = Options.AC; 4261 4262 if (!isGuaranteedNotToBeUndefOrPoison(ExtraCase, AC, BI, nullptr)) 4263 ExtraCase = Builder.CreateFreeze(ExtraCase); 4264 4265 if (TrueWhenEqual) 4266 Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB); 4267 else 4268 Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB); 4269 4270 OldTI->eraseFromParent(); 4271 4272 if (DTU) 4273 Updates.push_back({DominatorTree::Insert, BB, EdgeBB}); 4274 4275 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them 4276 // for the edge we just added. 4277 AddPredecessorToBlock(EdgeBB, BB, NewBB); 4278 4279 LLVM_DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase 4280 << "\nEXTRABB = " << *BB); 4281 BB = NewBB; 4282 } 4283 4284 Builder.SetInsertPoint(BI); 4285 // Convert pointer to int before we switch. 4286 if (CompVal->getType()->isPointerTy()) { 4287 CompVal = Builder.CreatePtrToInt( 4288 CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr"); 4289 } 4290 4291 // Create the new switch instruction now. 4292 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size()); 4293 4294 // Add all of the 'cases' to the switch instruction. 4295 for (unsigned i = 0, e = Values.size(); i != e; ++i) 4296 New->addCase(Values[i], EdgeBB); 4297 4298 // We added edges from PI to the EdgeBB. As such, if there were any 4299 // PHI nodes in EdgeBB, they need entries to be added corresponding to 4300 // the number of edges added. 4301 for (BasicBlock::iterator BBI = EdgeBB->begin(); isa<PHINode>(BBI); ++BBI) { 4302 PHINode *PN = cast<PHINode>(BBI); 4303 Value *InVal = PN->getIncomingValueForBlock(BB); 4304 for (unsigned i = 0, e = Values.size() - 1; i != e; ++i) 4305 PN->addIncoming(InVal, BB); 4306 } 4307 4308 // Erase the old branch instruction. 4309 EraseTerminatorAndDCECond(BI); 4310 if (DTU) 4311 DTU->applyUpdates(Updates); 4312 4313 LLVM_DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n'); 4314 return true; 4315 } 4316 4317 bool SimplifyCFGOpt::simplifyResume(ResumeInst *RI, IRBuilder<> &Builder) { 4318 if (isa<PHINode>(RI->getValue())) 4319 return simplifyCommonResume(RI); 4320 else if (isa<LandingPadInst>(RI->getParent()->getFirstNonPHI()) && 4321 RI->getValue() == RI->getParent()->getFirstNonPHI()) 4322 // The resume must unwind the exception that caused control to branch here. 4323 return simplifySingleResume(RI); 4324 4325 return false; 4326 } 4327 4328 // Check if cleanup block is empty 4329 static bool isCleanupBlockEmpty(iterator_range<BasicBlock::iterator> R) { 4330 for (Instruction &I : R) { 4331 auto *II = dyn_cast<IntrinsicInst>(&I); 4332 if (!II) 4333 return false; 4334 4335 Intrinsic::ID IntrinsicID = II->getIntrinsicID(); 4336 switch (IntrinsicID) { 4337 case Intrinsic::dbg_declare: 4338 case Intrinsic::dbg_value: 4339 case Intrinsic::dbg_label: 4340 case Intrinsic::lifetime_end: 4341 break; 4342 default: 4343 return false; 4344 } 4345 } 4346 return true; 4347 } 4348 4349 // Simplify resume that is shared by several landing pads (phi of landing pad). 4350 bool SimplifyCFGOpt::simplifyCommonResume(ResumeInst *RI) { 4351 BasicBlock *BB = RI->getParent(); 4352 4353 // Check that there are no other instructions except for debug and lifetime 4354 // intrinsics between the phi's and resume instruction. 4355 if (!isCleanupBlockEmpty( 4356 make_range(RI->getParent()->getFirstNonPHI(), BB->getTerminator()))) 4357 return false; 4358 4359 SmallSetVector<BasicBlock *, 4> TrivialUnwindBlocks; 4360 auto *PhiLPInst = cast<PHINode>(RI->getValue()); 4361 4362 // Check incoming blocks to see if any of them are trivial. 4363 for (unsigned Idx = 0, End = PhiLPInst->getNumIncomingValues(); Idx != End; 4364 Idx++) { 4365 auto *IncomingBB = PhiLPInst->getIncomingBlock(Idx); 4366 auto *IncomingValue = PhiLPInst->getIncomingValue(Idx); 4367 4368 // If the block has other successors, we can not delete it because 4369 // it has other dependents. 4370 if (IncomingBB->getUniqueSuccessor() != BB) 4371 continue; 4372 4373 auto *LandingPad = dyn_cast<LandingPadInst>(IncomingBB->getFirstNonPHI()); 4374 // Not the landing pad that caused the control to branch here. 4375 if (IncomingValue != LandingPad) 4376 continue; 4377 4378 if (isCleanupBlockEmpty( 4379 make_range(LandingPad->getNextNode(), IncomingBB->getTerminator()))) 4380 TrivialUnwindBlocks.insert(IncomingBB); 4381 } 4382 4383 // If no trivial unwind blocks, don't do any simplifications. 4384 if (TrivialUnwindBlocks.empty()) 4385 return false; 4386 4387 // Turn all invokes that unwind here into calls. 4388 for (auto *TrivialBB : TrivialUnwindBlocks) { 4389 // Blocks that will be simplified should be removed from the phi node. 4390 // Note there could be multiple edges to the resume block, and we need 4391 // to remove them all. 4392 while (PhiLPInst->getBasicBlockIndex(TrivialBB) != -1) 4393 BB->removePredecessor(TrivialBB, true); 4394 4395 for (BasicBlock *Pred : 4396 llvm::make_early_inc_range(predecessors(TrivialBB))) { 4397 removeUnwindEdge(Pred, DTU); 4398 ++NumInvokes; 4399 } 4400 4401 // In each SimplifyCFG run, only the current processed block can be erased. 4402 // Otherwise, it will break the iteration of SimplifyCFG pass. So instead 4403 // of erasing TrivialBB, we only remove the branch to the common resume 4404 // block so that we can later erase the resume block since it has no 4405 // predecessors. 4406 TrivialBB->getTerminator()->eraseFromParent(); 4407 new UnreachableInst(RI->getContext(), TrivialBB); 4408 if (DTU) 4409 DTU->applyUpdates({{DominatorTree::Delete, TrivialBB, BB}}); 4410 } 4411 4412 // Delete the resume block if all its predecessors have been removed. 4413 if (pred_empty(BB)) 4414 DeleteDeadBlock(BB, DTU); 4415 4416 return !TrivialUnwindBlocks.empty(); 4417 } 4418 4419 // Simplify resume that is only used by a single (non-phi) landing pad. 4420 bool SimplifyCFGOpt::simplifySingleResume(ResumeInst *RI) { 4421 BasicBlock *BB = RI->getParent(); 4422 auto *LPInst = cast<LandingPadInst>(BB->getFirstNonPHI()); 4423 assert(RI->getValue() == LPInst && 4424 "Resume must unwind the exception that caused control to here"); 4425 4426 // Check that there are no other instructions except for debug intrinsics. 4427 if (!isCleanupBlockEmpty( 4428 make_range<Instruction *>(LPInst->getNextNode(), RI))) 4429 return false; 4430 4431 // Turn all invokes that unwind here into calls and delete the basic block. 4432 for (BasicBlock *Pred : llvm::make_early_inc_range(predecessors(BB))) { 4433 removeUnwindEdge(Pred, DTU); 4434 ++NumInvokes; 4435 } 4436 4437 // The landingpad is now unreachable. Zap it. 4438 DeleteDeadBlock(BB, DTU); 4439 return true; 4440 } 4441 4442 static bool removeEmptyCleanup(CleanupReturnInst *RI, DomTreeUpdater *DTU) { 4443 // If this is a trivial cleanup pad that executes no instructions, it can be 4444 // eliminated. If the cleanup pad continues to the caller, any predecessor 4445 // that is an EH pad will be updated to continue to the caller and any 4446 // predecessor that terminates with an invoke instruction will have its invoke 4447 // instruction converted to a call instruction. If the cleanup pad being 4448 // simplified does not continue to the caller, each predecessor will be 4449 // updated to continue to the unwind destination of the cleanup pad being 4450 // simplified. 4451 BasicBlock *BB = RI->getParent(); 4452 CleanupPadInst *CPInst = RI->getCleanupPad(); 4453 if (CPInst->getParent() != BB) 4454 // This isn't an empty cleanup. 4455 return false; 4456 4457 // We cannot kill the pad if it has multiple uses. This typically arises 4458 // from unreachable basic blocks. 4459 if (!CPInst->hasOneUse()) 4460 return false; 4461 4462 // Check that there are no other instructions except for benign intrinsics. 4463 if (!isCleanupBlockEmpty( 4464 make_range<Instruction *>(CPInst->getNextNode(), RI))) 4465 return false; 4466 4467 // If the cleanup return we are simplifying unwinds to the caller, this will 4468 // set UnwindDest to nullptr. 4469 BasicBlock *UnwindDest = RI->getUnwindDest(); 4470 Instruction *DestEHPad = UnwindDest ? UnwindDest->getFirstNonPHI() : nullptr; 4471 4472 // We're about to remove BB from the control flow. Before we do, sink any 4473 // PHINodes into the unwind destination. Doing this before changing the 4474 // control flow avoids some potentially slow checks, since we can currently 4475 // be certain that UnwindDest and BB have no common predecessors (since they 4476 // are both EH pads). 4477 if (UnwindDest) { 4478 // First, go through the PHI nodes in UnwindDest and update any nodes that 4479 // reference the block we are removing 4480 for (PHINode &DestPN : UnwindDest->phis()) { 4481 int Idx = DestPN.getBasicBlockIndex(BB); 4482 // Since BB unwinds to UnwindDest, it has to be in the PHI node. 4483 assert(Idx != -1); 4484 // This PHI node has an incoming value that corresponds to a control 4485 // path through the cleanup pad we are removing. If the incoming 4486 // value is in the cleanup pad, it must be a PHINode (because we 4487 // verified above that the block is otherwise empty). Otherwise, the 4488 // value is either a constant or a value that dominates the cleanup 4489 // pad being removed. 4490 // 4491 // Because BB and UnwindDest are both EH pads, all of their 4492 // predecessors must unwind to these blocks, and since no instruction 4493 // can have multiple unwind destinations, there will be no overlap in 4494 // incoming blocks between SrcPN and DestPN. 4495 Value *SrcVal = DestPN.getIncomingValue(Idx); 4496 PHINode *SrcPN = dyn_cast<PHINode>(SrcVal); 4497 4498 bool NeedPHITranslation = SrcPN && SrcPN->getParent() == BB; 4499 for (auto *Pred : predecessors(BB)) { 4500 Value *Incoming = 4501 NeedPHITranslation ? SrcPN->getIncomingValueForBlock(Pred) : SrcVal; 4502 DestPN.addIncoming(Incoming, Pred); 4503 } 4504 } 4505 4506 // Sink any remaining PHI nodes directly into UnwindDest. 4507 Instruction *InsertPt = DestEHPad; 4508 for (PHINode &PN : make_early_inc_range(BB->phis())) { 4509 if (PN.use_empty() || !PN.isUsedOutsideOfBlock(BB)) 4510 // If the PHI node has no uses or all of its uses are in this basic 4511 // block (meaning they are debug or lifetime intrinsics), just leave 4512 // it. It will be erased when we erase BB below. 4513 continue; 4514 4515 // Otherwise, sink this PHI node into UnwindDest. 4516 // Any predecessors to UnwindDest which are not already represented 4517 // must be back edges which inherit the value from the path through 4518 // BB. In this case, the PHI value must reference itself. 4519 for (auto *pred : predecessors(UnwindDest)) 4520 if (pred != BB) 4521 PN.addIncoming(&PN, pred); 4522 PN.moveBefore(InsertPt); 4523 // Also, add a dummy incoming value for the original BB itself, 4524 // so that the PHI is well-formed until we drop said predecessor. 4525 PN.addIncoming(UndefValue::get(PN.getType()), BB); 4526 } 4527 } 4528 4529 std::vector<DominatorTree::UpdateType> Updates; 4530 4531 // We use make_early_inc_range here because we will remove all predecessors. 4532 for (BasicBlock *PredBB : llvm::make_early_inc_range(predecessors(BB))) { 4533 if (UnwindDest == nullptr) { 4534 if (DTU) { 4535 DTU->applyUpdates(Updates); 4536 Updates.clear(); 4537 } 4538 removeUnwindEdge(PredBB, DTU); 4539 ++NumInvokes; 4540 } else { 4541 BB->removePredecessor(PredBB); 4542 Instruction *TI = PredBB->getTerminator(); 4543 TI->replaceUsesOfWith(BB, UnwindDest); 4544 if (DTU) { 4545 Updates.push_back({DominatorTree::Insert, PredBB, UnwindDest}); 4546 Updates.push_back({DominatorTree::Delete, PredBB, BB}); 4547 } 4548 } 4549 } 4550 4551 if (DTU) 4552 DTU->applyUpdates(Updates); 4553 4554 DeleteDeadBlock(BB, DTU); 4555 4556 return true; 4557 } 4558 4559 // Try to merge two cleanuppads together. 4560 static bool mergeCleanupPad(CleanupReturnInst *RI) { 4561 // Skip any cleanuprets which unwind to caller, there is nothing to merge 4562 // with. 4563 BasicBlock *UnwindDest = RI->getUnwindDest(); 4564 if (!UnwindDest) 4565 return false; 4566 4567 // This cleanupret isn't the only predecessor of this cleanuppad, it wouldn't 4568 // be safe to merge without code duplication. 4569 if (UnwindDest->getSinglePredecessor() != RI->getParent()) 4570 return false; 4571 4572 // Verify that our cleanuppad's unwind destination is another cleanuppad. 4573 auto *SuccessorCleanupPad = dyn_cast<CleanupPadInst>(&UnwindDest->front()); 4574 if (!SuccessorCleanupPad) 4575 return false; 4576 4577 CleanupPadInst *PredecessorCleanupPad = RI->getCleanupPad(); 4578 // Replace any uses of the successor cleanupad with the predecessor pad 4579 // The only cleanuppad uses should be this cleanupret, it's cleanupret and 4580 // funclet bundle operands. 4581 SuccessorCleanupPad->replaceAllUsesWith(PredecessorCleanupPad); 4582 // Remove the old cleanuppad. 4583 SuccessorCleanupPad->eraseFromParent(); 4584 // Now, we simply replace the cleanupret with a branch to the unwind 4585 // destination. 4586 BranchInst::Create(UnwindDest, RI->getParent()); 4587 RI->eraseFromParent(); 4588 4589 return true; 4590 } 4591 4592 bool SimplifyCFGOpt::simplifyCleanupReturn(CleanupReturnInst *RI) { 4593 // It is possible to transiantly have an undef cleanuppad operand because we 4594 // have deleted some, but not all, dead blocks. 4595 // Eventually, this block will be deleted. 4596 if (isa<UndefValue>(RI->getOperand(0))) 4597 return false; 4598 4599 if (mergeCleanupPad(RI)) 4600 return true; 4601 4602 if (removeEmptyCleanup(RI, DTU)) 4603 return true; 4604 4605 return false; 4606 } 4607 4608 // WARNING: keep in sync with InstCombinerImpl::visitUnreachableInst()! 4609 bool SimplifyCFGOpt::simplifyUnreachable(UnreachableInst *UI) { 4610 BasicBlock *BB = UI->getParent(); 4611 4612 bool Changed = false; 4613 4614 // If there are any instructions immediately before the unreachable that can 4615 // be removed, do so. 4616 while (UI->getIterator() != BB->begin()) { 4617 BasicBlock::iterator BBI = UI->getIterator(); 4618 --BBI; 4619 4620 if (!isGuaranteedToTransferExecutionToSuccessor(&*BBI)) 4621 break; // Can not drop any more instructions. We're done here. 4622 // Otherwise, this instruction can be freely erased, 4623 // even if it is not side-effect free. 4624 4625 // Note that deleting EH's here is in fact okay, although it involves a bit 4626 // of subtle reasoning. If this inst is an EH, all the predecessors of this 4627 // block will be the unwind edges of Invoke/CatchSwitch/CleanupReturn, 4628 // and we can therefore guarantee this block will be erased. 4629 4630 // Delete this instruction (any uses are guaranteed to be dead) 4631 BBI->replaceAllUsesWith(PoisonValue::get(BBI->getType())); 4632 BBI->eraseFromParent(); 4633 Changed = true; 4634 } 4635 4636 // If the unreachable instruction is the first in the block, take a gander 4637 // at all of the predecessors of this instruction, and simplify them. 4638 if (&BB->front() != UI) 4639 return Changed; 4640 4641 std::vector<DominatorTree::UpdateType> Updates; 4642 4643 SmallSetVector<BasicBlock *, 8> Preds(pred_begin(BB), pred_end(BB)); 4644 for (unsigned i = 0, e = Preds.size(); i != e; ++i) { 4645 auto *Predecessor = Preds[i]; 4646 Instruction *TI = Predecessor->getTerminator(); 4647 IRBuilder<> Builder(TI); 4648 if (auto *BI = dyn_cast<BranchInst>(TI)) { 4649 // We could either have a proper unconditional branch, 4650 // or a degenerate conditional branch with matching destinations. 4651 if (all_of(BI->successors(), 4652 [BB](auto *Successor) { return Successor == BB; })) { 4653 new UnreachableInst(TI->getContext(), TI); 4654 TI->eraseFromParent(); 4655 Changed = true; 4656 } else { 4657 assert(BI->isConditional() && "Can't get here with an uncond branch."); 4658 Value* Cond = BI->getCondition(); 4659 assert(BI->getSuccessor(0) != BI->getSuccessor(1) && 4660 "The destinations are guaranteed to be different here."); 4661 if (BI->getSuccessor(0) == BB) { 4662 Builder.CreateAssumption(Builder.CreateNot(Cond)); 4663 Builder.CreateBr(BI->getSuccessor(1)); 4664 } else { 4665 assert(BI->getSuccessor(1) == BB && "Incorrect CFG"); 4666 Builder.CreateAssumption(Cond); 4667 Builder.CreateBr(BI->getSuccessor(0)); 4668 } 4669 EraseTerminatorAndDCECond(BI); 4670 Changed = true; 4671 } 4672 if (DTU) 4673 Updates.push_back({DominatorTree::Delete, Predecessor, BB}); 4674 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) { 4675 SwitchInstProfUpdateWrapper SU(*SI); 4676 for (auto i = SU->case_begin(), e = SU->case_end(); i != e;) { 4677 if (i->getCaseSuccessor() != BB) { 4678 ++i; 4679 continue; 4680 } 4681 BB->removePredecessor(SU->getParent()); 4682 i = SU.removeCase(i); 4683 e = SU->case_end(); 4684 Changed = true; 4685 } 4686 // Note that the default destination can't be removed! 4687 if (DTU && SI->getDefaultDest() != BB) 4688 Updates.push_back({DominatorTree::Delete, Predecessor, BB}); 4689 } else if (auto *II = dyn_cast<InvokeInst>(TI)) { 4690 if (II->getUnwindDest() == BB) { 4691 if (DTU) { 4692 DTU->applyUpdates(Updates); 4693 Updates.clear(); 4694 } 4695 removeUnwindEdge(TI->getParent(), DTU); 4696 Changed = true; 4697 } 4698 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) { 4699 if (CSI->getUnwindDest() == BB) { 4700 if (DTU) { 4701 DTU->applyUpdates(Updates); 4702 Updates.clear(); 4703 } 4704 removeUnwindEdge(TI->getParent(), DTU); 4705 Changed = true; 4706 continue; 4707 } 4708 4709 for (CatchSwitchInst::handler_iterator I = CSI->handler_begin(), 4710 E = CSI->handler_end(); 4711 I != E; ++I) { 4712 if (*I == BB) { 4713 CSI->removeHandler(I); 4714 --I; 4715 --E; 4716 Changed = true; 4717 } 4718 } 4719 if (DTU) 4720 Updates.push_back({DominatorTree::Delete, Predecessor, BB}); 4721 if (CSI->getNumHandlers() == 0) { 4722 if (CSI->hasUnwindDest()) { 4723 // Redirect all predecessors of the block containing CatchSwitchInst 4724 // to instead branch to the CatchSwitchInst's unwind destination. 4725 if (DTU) { 4726 for (auto *PredecessorOfPredecessor : predecessors(Predecessor)) { 4727 Updates.push_back({DominatorTree::Insert, 4728 PredecessorOfPredecessor, 4729 CSI->getUnwindDest()}); 4730 Updates.push_back({DominatorTree::Delete, 4731 PredecessorOfPredecessor, Predecessor}); 4732 } 4733 } 4734 Predecessor->replaceAllUsesWith(CSI->getUnwindDest()); 4735 } else { 4736 // Rewrite all preds to unwind to caller (or from invoke to call). 4737 if (DTU) { 4738 DTU->applyUpdates(Updates); 4739 Updates.clear(); 4740 } 4741 SmallVector<BasicBlock *, 8> EHPreds(predecessors(Predecessor)); 4742 for (BasicBlock *EHPred : EHPreds) 4743 removeUnwindEdge(EHPred, DTU); 4744 } 4745 // The catchswitch is no longer reachable. 4746 new UnreachableInst(CSI->getContext(), CSI); 4747 CSI->eraseFromParent(); 4748 Changed = true; 4749 } 4750 } else if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) { 4751 (void)CRI; 4752 assert(CRI->hasUnwindDest() && CRI->getUnwindDest() == BB && 4753 "Expected to always have an unwind to BB."); 4754 if (DTU) 4755 Updates.push_back({DominatorTree::Delete, Predecessor, BB}); 4756 new UnreachableInst(TI->getContext(), TI); 4757 TI->eraseFromParent(); 4758 Changed = true; 4759 } 4760 } 4761 4762 if (DTU) 4763 DTU->applyUpdates(Updates); 4764 4765 // If this block is now dead, remove it. 4766 if (pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) { 4767 DeleteDeadBlock(BB, DTU); 4768 return true; 4769 } 4770 4771 return Changed; 4772 } 4773 4774 static bool CasesAreContiguous(SmallVectorImpl<ConstantInt *> &Cases) { 4775 assert(Cases.size() >= 1); 4776 4777 array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate); 4778 for (size_t I = 1, E = Cases.size(); I != E; ++I) { 4779 if (Cases[I - 1]->getValue() != Cases[I]->getValue() + 1) 4780 return false; 4781 } 4782 return true; 4783 } 4784 4785 /// Turn a switch with two reachable destinations into an integer range 4786 /// comparison and branch. 4787 bool SimplifyCFGOpt::TurnSwitchRangeIntoICmp(SwitchInst *SI, 4788 IRBuilder<> &Builder) { 4789 assert(SI->getNumCases() > 1 && "Degenerate switch?"); 4790 4791 bool HasDefault = 4792 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg()); 4793 4794 auto *BB = SI->getParent(); 4795 4796 // Partition the cases into two sets with different destinations. 4797 BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr; 4798 BasicBlock *DestB = nullptr; 4799 SmallVector<ConstantInt *, 16> CasesA; 4800 SmallVector<ConstantInt *, 16> CasesB; 4801 4802 for (auto Case : SI->cases()) { 4803 BasicBlock *Dest = Case.getCaseSuccessor(); 4804 if (!DestA) 4805 DestA = Dest; 4806 if (Dest == DestA) { 4807 CasesA.push_back(Case.getCaseValue()); 4808 continue; 4809 } 4810 if (!DestB) 4811 DestB = Dest; 4812 if (Dest == DestB) { 4813 CasesB.push_back(Case.getCaseValue()); 4814 continue; 4815 } 4816 return false; // More than two destinations. 4817 } 4818 4819 assert(DestA && DestB && 4820 "Single-destination switch should have been folded."); 4821 assert(DestA != DestB); 4822 assert(DestB != SI->getDefaultDest()); 4823 assert(!CasesB.empty() && "There must be non-default cases."); 4824 assert(!CasesA.empty() || HasDefault); 4825 4826 // Figure out if one of the sets of cases form a contiguous range. 4827 SmallVectorImpl<ConstantInt *> *ContiguousCases = nullptr; 4828 BasicBlock *ContiguousDest = nullptr; 4829 BasicBlock *OtherDest = nullptr; 4830 if (!CasesA.empty() && CasesAreContiguous(CasesA)) { 4831 ContiguousCases = &CasesA; 4832 ContiguousDest = DestA; 4833 OtherDest = DestB; 4834 } else if (CasesAreContiguous(CasesB)) { 4835 ContiguousCases = &CasesB; 4836 ContiguousDest = DestB; 4837 OtherDest = DestA; 4838 } else 4839 return false; 4840 4841 // Start building the compare and branch. 4842 4843 Constant *Offset = ConstantExpr::getNeg(ContiguousCases->back()); 4844 Constant *NumCases = 4845 ConstantInt::get(Offset->getType(), ContiguousCases->size()); 4846 4847 Value *Sub = SI->getCondition(); 4848 if (!Offset->isNullValue()) 4849 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off"); 4850 4851 Value *Cmp; 4852 // If NumCases overflowed, then all possible values jump to the successor. 4853 if (NumCases->isNullValue() && !ContiguousCases->empty()) 4854 Cmp = ConstantInt::getTrue(SI->getContext()); 4855 else 4856 Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch"); 4857 BranchInst *NewBI = Builder.CreateCondBr(Cmp, ContiguousDest, OtherDest); 4858 4859 // Update weight for the newly-created conditional branch. 4860 if (HasBranchWeights(SI)) { 4861 SmallVector<uint64_t, 8> Weights; 4862 GetBranchWeights(SI, Weights); 4863 if (Weights.size() == 1 + SI->getNumCases()) { 4864 uint64_t TrueWeight = 0; 4865 uint64_t FalseWeight = 0; 4866 for (size_t I = 0, E = Weights.size(); I != E; ++I) { 4867 if (SI->getSuccessor(I) == ContiguousDest) 4868 TrueWeight += Weights[I]; 4869 else 4870 FalseWeight += Weights[I]; 4871 } 4872 while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) { 4873 TrueWeight /= 2; 4874 FalseWeight /= 2; 4875 } 4876 setBranchWeights(NewBI, TrueWeight, FalseWeight); 4877 } 4878 } 4879 4880 // Prune obsolete incoming values off the successors' PHI nodes. 4881 for (auto BBI = ContiguousDest->begin(); isa<PHINode>(BBI); ++BBI) { 4882 unsigned PreviousEdges = ContiguousCases->size(); 4883 if (ContiguousDest == SI->getDefaultDest()) 4884 ++PreviousEdges; 4885 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I) 4886 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent()); 4887 } 4888 for (auto BBI = OtherDest->begin(); isa<PHINode>(BBI); ++BBI) { 4889 unsigned PreviousEdges = SI->getNumCases() - ContiguousCases->size(); 4890 if (OtherDest == SI->getDefaultDest()) 4891 ++PreviousEdges; 4892 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I) 4893 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent()); 4894 } 4895 4896 // Clean up the default block - it may have phis or other instructions before 4897 // the unreachable terminator. 4898 if (!HasDefault) 4899 createUnreachableSwitchDefault(SI, DTU); 4900 4901 auto *UnreachableDefault = SI->getDefaultDest(); 4902 4903 // Drop the switch. 4904 SI->eraseFromParent(); 4905 4906 if (!HasDefault && DTU) 4907 DTU->applyUpdates({{DominatorTree::Delete, BB, UnreachableDefault}}); 4908 4909 return true; 4910 } 4911 4912 /// Compute masked bits for the condition of a switch 4913 /// and use it to remove dead cases. 4914 static bool eliminateDeadSwitchCases(SwitchInst *SI, DomTreeUpdater *DTU, 4915 AssumptionCache *AC, 4916 const DataLayout &DL) { 4917 Value *Cond = SI->getCondition(); 4918 unsigned Bits = Cond->getType()->getIntegerBitWidth(); 4919 KnownBits Known = computeKnownBits(Cond, DL, 0, AC, SI); 4920 4921 // We can also eliminate cases by determining that their values are outside of 4922 // the limited range of the condition based on how many significant (non-sign) 4923 // bits are in the condition value. 4924 unsigned ExtraSignBits = ComputeNumSignBits(Cond, DL, 0, AC, SI) - 1; 4925 unsigned MaxSignificantBitsInCond = Bits - ExtraSignBits; 4926 4927 // Gather dead cases. 4928 SmallVector<ConstantInt *, 8> DeadCases; 4929 SmallDenseMap<BasicBlock *, int, 8> NumPerSuccessorCases; 4930 for (auto &Case : SI->cases()) { 4931 auto *Successor = Case.getCaseSuccessor(); 4932 if (DTU) 4933 ++NumPerSuccessorCases[Successor]; 4934 const APInt &CaseVal = Case.getCaseValue()->getValue(); 4935 if (Known.Zero.intersects(CaseVal) || !Known.One.isSubsetOf(CaseVal) || 4936 (CaseVal.getMinSignedBits() > MaxSignificantBitsInCond)) { 4937 DeadCases.push_back(Case.getCaseValue()); 4938 if (DTU) 4939 --NumPerSuccessorCases[Successor]; 4940 LLVM_DEBUG(dbgs() << "SimplifyCFG: switch case " << CaseVal 4941 << " is dead.\n"); 4942 } 4943 } 4944 4945 // If we can prove that the cases must cover all possible values, the 4946 // default destination becomes dead and we can remove it. If we know some 4947 // of the bits in the value, we can use that to more precisely compute the 4948 // number of possible unique case values. 4949 bool HasDefault = 4950 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg()); 4951 const unsigned NumUnknownBits = 4952 Bits - (Known.Zero | Known.One).countPopulation(); 4953 assert(NumUnknownBits <= Bits); 4954 if (HasDefault && DeadCases.empty() && 4955 NumUnknownBits < 64 /* avoid overflow */ && 4956 SI->getNumCases() == (1ULL << NumUnknownBits)) { 4957 createUnreachableSwitchDefault(SI, DTU); 4958 return true; 4959 } 4960 4961 if (DeadCases.empty()) 4962 return false; 4963 4964 SwitchInstProfUpdateWrapper SIW(*SI); 4965 for (ConstantInt *DeadCase : DeadCases) { 4966 SwitchInst::CaseIt CaseI = SI->findCaseValue(DeadCase); 4967 assert(CaseI != SI->case_default() && 4968 "Case was not found. Probably mistake in DeadCases forming."); 4969 // Prune unused values from PHI nodes. 4970 CaseI->getCaseSuccessor()->removePredecessor(SI->getParent()); 4971 SIW.removeCase(CaseI); 4972 } 4973 4974 if (DTU) { 4975 std::vector<DominatorTree::UpdateType> Updates; 4976 for (const std::pair<BasicBlock *, int> &I : NumPerSuccessorCases) 4977 if (I.second == 0) 4978 Updates.push_back({DominatorTree::Delete, SI->getParent(), I.first}); 4979 DTU->applyUpdates(Updates); 4980 } 4981 4982 return true; 4983 } 4984 4985 /// If BB would be eligible for simplification by 4986 /// TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated 4987 /// by an unconditional branch), look at the phi node for BB in the successor 4988 /// block and see if the incoming value is equal to CaseValue. If so, return 4989 /// the phi node, and set PhiIndex to BB's index in the phi node. 4990 static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue, 4991 BasicBlock *BB, int *PhiIndex) { 4992 if (BB->getFirstNonPHIOrDbg() != BB->getTerminator()) 4993 return nullptr; // BB must be empty to be a candidate for simplification. 4994 if (!BB->getSinglePredecessor()) 4995 return nullptr; // BB must be dominated by the switch. 4996 4997 BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator()); 4998 if (!Branch || !Branch->isUnconditional()) 4999 return nullptr; // Terminator must be unconditional branch. 5000 5001 BasicBlock *Succ = Branch->getSuccessor(0); 5002 5003 for (PHINode &PHI : Succ->phis()) { 5004 int Idx = PHI.getBasicBlockIndex(BB); 5005 assert(Idx >= 0 && "PHI has no entry for predecessor?"); 5006 5007 Value *InValue = PHI.getIncomingValue(Idx); 5008 if (InValue != CaseValue) 5009 continue; 5010 5011 *PhiIndex = Idx; 5012 return &PHI; 5013 } 5014 5015 return nullptr; 5016 } 5017 5018 /// Try to forward the condition of a switch instruction to a phi node 5019 /// dominated by the switch, if that would mean that some of the destination 5020 /// blocks of the switch can be folded away. Return true if a change is made. 5021 static bool ForwardSwitchConditionToPHI(SwitchInst *SI) { 5022 using ForwardingNodesMap = DenseMap<PHINode *, SmallVector<int, 4>>; 5023 5024 ForwardingNodesMap ForwardingNodes; 5025 BasicBlock *SwitchBlock = SI->getParent(); 5026 bool Changed = false; 5027 for (auto &Case : SI->cases()) { 5028 ConstantInt *CaseValue = Case.getCaseValue(); 5029 BasicBlock *CaseDest = Case.getCaseSuccessor(); 5030 5031 // Replace phi operands in successor blocks that are using the constant case 5032 // value rather than the switch condition variable: 5033 // switchbb: 5034 // switch i32 %x, label %default [ 5035 // i32 17, label %succ 5036 // ... 5037 // succ: 5038 // %r = phi i32 ... [ 17, %switchbb ] ... 5039 // --> 5040 // %r = phi i32 ... [ %x, %switchbb ] ... 5041 5042 for (PHINode &Phi : CaseDest->phis()) { 5043 // This only works if there is exactly 1 incoming edge from the switch to 5044 // a phi. If there is >1, that means multiple cases of the switch map to 1 5045 // value in the phi, and that phi value is not the switch condition. Thus, 5046 // this transform would not make sense (the phi would be invalid because 5047 // a phi can't have different incoming values from the same block). 5048 int SwitchBBIdx = Phi.getBasicBlockIndex(SwitchBlock); 5049 if (Phi.getIncomingValue(SwitchBBIdx) == CaseValue && 5050 count(Phi.blocks(), SwitchBlock) == 1) { 5051 Phi.setIncomingValue(SwitchBBIdx, SI->getCondition()); 5052 Changed = true; 5053 } 5054 } 5055 5056 // Collect phi nodes that are indirectly using this switch's case constants. 5057 int PhiIdx; 5058 if (auto *Phi = FindPHIForConditionForwarding(CaseValue, CaseDest, &PhiIdx)) 5059 ForwardingNodes[Phi].push_back(PhiIdx); 5060 } 5061 5062 for (auto &ForwardingNode : ForwardingNodes) { 5063 PHINode *Phi = ForwardingNode.first; 5064 SmallVectorImpl<int> &Indexes = ForwardingNode.second; 5065 if (Indexes.size() < 2) 5066 continue; 5067 5068 for (int Index : Indexes) 5069 Phi->setIncomingValue(Index, SI->getCondition()); 5070 Changed = true; 5071 } 5072 5073 return Changed; 5074 } 5075 5076 /// Return true if the backend will be able to handle 5077 /// initializing an array of constants like C. 5078 static bool ValidLookupTableConstant(Constant *C, const TargetTransformInfo &TTI) { 5079 if (C->isThreadDependent()) 5080 return false; 5081 if (C->isDLLImportDependent()) 5082 return false; 5083 5084 if (!isa<ConstantFP>(C) && !isa<ConstantInt>(C) && 5085 !isa<ConstantPointerNull>(C) && !isa<GlobalValue>(C) && 5086 !isa<UndefValue>(C) && !isa<ConstantExpr>(C)) 5087 return false; 5088 5089 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 5090 // Pointer casts and in-bounds GEPs will not prohibit the backend from 5091 // materializing the array of constants. 5092 Constant *StrippedC = cast<Constant>(CE->stripInBoundsConstantOffsets()); 5093 if (StrippedC == C || !ValidLookupTableConstant(StrippedC, TTI)) 5094 return false; 5095 } 5096 5097 if (!TTI.shouldBuildLookupTablesForConstant(C)) 5098 return false; 5099 5100 return true; 5101 } 5102 5103 /// If V is a Constant, return it. Otherwise, try to look up 5104 /// its constant value in ConstantPool, returning 0 if it's not there. 5105 static Constant * 5106 LookupConstant(Value *V, 5107 const SmallDenseMap<Value *, Constant *> &ConstantPool) { 5108 if (Constant *C = dyn_cast<Constant>(V)) 5109 return C; 5110 return ConstantPool.lookup(V); 5111 } 5112 5113 /// Try to fold instruction I into a constant. This works for 5114 /// simple instructions such as binary operations where both operands are 5115 /// constant or can be replaced by constants from the ConstantPool. Returns the 5116 /// resulting constant on success, 0 otherwise. 5117 static Constant * 5118 ConstantFold(Instruction *I, const DataLayout &DL, 5119 const SmallDenseMap<Value *, Constant *> &ConstantPool) { 5120 if (SelectInst *Select = dyn_cast<SelectInst>(I)) { 5121 Constant *A = LookupConstant(Select->getCondition(), ConstantPool); 5122 if (!A) 5123 return nullptr; 5124 if (A->isAllOnesValue()) 5125 return LookupConstant(Select->getTrueValue(), ConstantPool); 5126 if (A->isNullValue()) 5127 return LookupConstant(Select->getFalseValue(), ConstantPool); 5128 return nullptr; 5129 } 5130 5131 SmallVector<Constant *, 4> COps; 5132 for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) { 5133 if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool)) 5134 COps.push_back(A); 5135 else 5136 return nullptr; 5137 } 5138 5139 if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) { 5140 return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0], 5141 COps[1], DL); 5142 } 5143 5144 return ConstantFoldInstOperands(I, COps, DL); 5145 } 5146 5147 /// Try to determine the resulting constant values in phi nodes 5148 /// at the common destination basic block, *CommonDest, for one of the case 5149 /// destionations CaseDest corresponding to value CaseVal (0 for the default 5150 /// case), of a switch instruction SI. 5151 static bool 5152 GetCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest, 5153 BasicBlock **CommonDest, 5154 SmallVectorImpl<std::pair<PHINode *, Constant *>> &Res, 5155 const DataLayout &DL, const TargetTransformInfo &TTI) { 5156 // The block from which we enter the common destination. 5157 BasicBlock *Pred = SI->getParent(); 5158 5159 // If CaseDest is empty except for some side-effect free instructions through 5160 // which we can constant-propagate the CaseVal, continue to its successor. 5161 SmallDenseMap<Value *, Constant *> ConstantPool; 5162 ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal)); 5163 for (Instruction &I : CaseDest->instructionsWithoutDebug(false)) { 5164 if (I.isTerminator()) { 5165 // If the terminator is a simple branch, continue to the next block. 5166 if (I.getNumSuccessors() != 1 || I.isExceptionalTerminator()) 5167 return false; 5168 Pred = CaseDest; 5169 CaseDest = I.getSuccessor(0); 5170 } else if (Constant *C = ConstantFold(&I, DL, ConstantPool)) { 5171 // Instruction is side-effect free and constant. 5172 5173 // If the instruction has uses outside this block or a phi node slot for 5174 // the block, it is not safe to bypass the instruction since it would then 5175 // no longer dominate all its uses. 5176 for (auto &Use : I.uses()) { 5177 User *User = Use.getUser(); 5178 if (Instruction *I = dyn_cast<Instruction>(User)) 5179 if (I->getParent() == CaseDest) 5180 continue; 5181 if (PHINode *Phi = dyn_cast<PHINode>(User)) 5182 if (Phi->getIncomingBlock(Use) == CaseDest) 5183 continue; 5184 return false; 5185 } 5186 5187 ConstantPool.insert(std::make_pair(&I, C)); 5188 } else { 5189 break; 5190 } 5191 } 5192 5193 // If we did not have a CommonDest before, use the current one. 5194 if (!*CommonDest) 5195 *CommonDest = CaseDest; 5196 // If the destination isn't the common one, abort. 5197 if (CaseDest != *CommonDest) 5198 return false; 5199 5200 // Get the values for this case from phi nodes in the destination block. 5201 for (PHINode &PHI : (*CommonDest)->phis()) { 5202 int Idx = PHI.getBasicBlockIndex(Pred); 5203 if (Idx == -1) 5204 continue; 5205 5206 Constant *ConstVal = 5207 LookupConstant(PHI.getIncomingValue(Idx), ConstantPool); 5208 if (!ConstVal) 5209 return false; 5210 5211 // Be conservative about which kinds of constants we support. 5212 if (!ValidLookupTableConstant(ConstVal, TTI)) 5213 return false; 5214 5215 Res.push_back(std::make_pair(&PHI, ConstVal)); 5216 } 5217 5218 return Res.size() > 0; 5219 } 5220 5221 // Helper function used to add CaseVal to the list of cases that generate 5222 // Result. Returns the updated number of cases that generate this result. 5223 static uintptr_t MapCaseToResult(ConstantInt *CaseVal, 5224 SwitchCaseResultVectorTy &UniqueResults, 5225 Constant *Result) { 5226 for (auto &I : UniqueResults) { 5227 if (I.first == Result) { 5228 I.second.push_back(CaseVal); 5229 return I.second.size(); 5230 } 5231 } 5232 UniqueResults.push_back( 5233 std::make_pair(Result, SmallVector<ConstantInt *, 4>(1, CaseVal))); 5234 return 1; 5235 } 5236 5237 // Helper function that initializes a map containing 5238 // results for the PHI node of the common destination block for a switch 5239 // instruction. Returns false if multiple PHI nodes have been found or if 5240 // there is not a common destination block for the switch. 5241 static bool 5242 InitializeUniqueCases(SwitchInst *SI, PHINode *&PHI, BasicBlock *&CommonDest, 5243 SwitchCaseResultVectorTy &UniqueResults, 5244 Constant *&DefaultResult, const DataLayout &DL, 5245 const TargetTransformInfo &TTI, 5246 uintptr_t MaxUniqueResults, uintptr_t MaxCasesPerResult) { 5247 for (auto &I : SI->cases()) { 5248 ConstantInt *CaseVal = I.getCaseValue(); 5249 5250 // Resulting value at phi nodes for this case value. 5251 SwitchCaseResultsTy Results; 5252 if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results, 5253 DL, TTI)) 5254 return false; 5255 5256 // Only one value per case is permitted. 5257 if (Results.size() > 1) 5258 return false; 5259 5260 // Add the case->result mapping to UniqueResults. 5261 const uintptr_t NumCasesForResult = 5262 MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second); 5263 5264 // Early out if there are too many cases for this result. 5265 if (NumCasesForResult > MaxCasesPerResult) 5266 return false; 5267 5268 // Early out if there are too many unique results. 5269 if (UniqueResults.size() > MaxUniqueResults) 5270 return false; 5271 5272 // Check the PHI consistency. 5273 if (!PHI) 5274 PHI = Results[0].first; 5275 else if (PHI != Results[0].first) 5276 return false; 5277 } 5278 // Find the default result value. 5279 SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults; 5280 BasicBlock *DefaultDest = SI->getDefaultDest(); 5281 GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults, 5282 DL, TTI); 5283 // If the default value is not found abort unless the default destination 5284 // is unreachable. 5285 DefaultResult = 5286 DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr; 5287 if ((!DefaultResult && 5288 !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg()))) 5289 return false; 5290 5291 return true; 5292 } 5293 5294 // Helper function that checks if it is possible to transform a switch with only 5295 // two cases (or two cases + default) that produces a result into a select. 5296 // Example: 5297 // switch (a) { 5298 // case 10: %0 = icmp eq i32 %a, 10 5299 // return 10; %1 = select i1 %0, i32 10, i32 4 5300 // case 20: ----> %2 = icmp eq i32 %a, 20 5301 // return 2; %3 = select i1 %2, i32 2, i32 %1 5302 // default: 5303 // return 4; 5304 // } 5305 static Value *ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector, 5306 Constant *DefaultResult, Value *Condition, 5307 IRBuilder<> &Builder) { 5308 // If we are selecting between only two cases transform into a simple 5309 // select or a two-way select if default is possible. 5310 if (ResultVector.size() == 2 && ResultVector[0].second.size() == 1 && 5311 ResultVector[1].second.size() == 1) { 5312 ConstantInt *const FirstCase = ResultVector[0].second[0]; 5313 ConstantInt *const SecondCase = ResultVector[1].second[0]; 5314 5315 bool DefaultCanTrigger = DefaultResult; 5316 Value *SelectValue = ResultVector[1].first; 5317 if (DefaultCanTrigger) { 5318 Value *const ValueCompare = 5319 Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp"); 5320 SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first, 5321 DefaultResult, "switch.select"); 5322 } 5323 Value *const ValueCompare = 5324 Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp"); 5325 return Builder.CreateSelect(ValueCompare, ResultVector[0].first, 5326 SelectValue, "switch.select"); 5327 } 5328 5329 // Handle the degenerate case where two cases have the same value. 5330 if (ResultVector.size() == 1 && ResultVector[0].second.size() == 2 && 5331 DefaultResult) { 5332 Value *Cmp1 = Builder.CreateICmpEQ( 5333 Condition, ResultVector[0].second[0], "switch.selectcmp.case1"); 5334 Value *Cmp2 = Builder.CreateICmpEQ( 5335 Condition, ResultVector[0].second[1], "switch.selectcmp.case2"); 5336 Value *Cmp = Builder.CreateOr(Cmp1, Cmp2, "switch.selectcmp"); 5337 return Builder.CreateSelect(Cmp, ResultVector[0].first, DefaultResult); 5338 } 5339 5340 return nullptr; 5341 } 5342 5343 // Helper function to cleanup a switch instruction that has been converted into 5344 // a select, fixing up PHI nodes and basic blocks. 5345 static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI, 5346 Value *SelectValue, 5347 IRBuilder<> &Builder, 5348 DomTreeUpdater *DTU) { 5349 std::vector<DominatorTree::UpdateType> Updates; 5350 5351 BasicBlock *SelectBB = SI->getParent(); 5352 BasicBlock *DestBB = PHI->getParent(); 5353 5354 if (DTU && !is_contained(predecessors(DestBB), SelectBB)) 5355 Updates.push_back({DominatorTree::Insert, SelectBB, DestBB}); 5356 Builder.CreateBr(DestBB); 5357 5358 // Remove the switch. 5359 5360 while (PHI->getBasicBlockIndex(SelectBB) >= 0) 5361 PHI->removeIncomingValue(SelectBB); 5362 PHI->addIncoming(SelectValue, SelectBB); 5363 5364 SmallPtrSet<BasicBlock *, 4> RemovedSuccessors; 5365 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) { 5366 BasicBlock *Succ = SI->getSuccessor(i); 5367 5368 if (Succ == DestBB) 5369 continue; 5370 Succ->removePredecessor(SelectBB); 5371 if (DTU && RemovedSuccessors.insert(Succ).second) 5372 Updates.push_back({DominatorTree::Delete, SelectBB, Succ}); 5373 } 5374 SI->eraseFromParent(); 5375 if (DTU) 5376 DTU->applyUpdates(Updates); 5377 } 5378 5379 /// If the switch is only used to initialize one or more 5380 /// phi nodes in a common successor block with only two different 5381 /// constant values, replace the switch with select. 5382 static bool switchToSelect(SwitchInst *SI, IRBuilder<> &Builder, 5383 DomTreeUpdater *DTU, const DataLayout &DL, 5384 const TargetTransformInfo &TTI) { 5385 Value *const Cond = SI->getCondition(); 5386 PHINode *PHI = nullptr; 5387 BasicBlock *CommonDest = nullptr; 5388 Constant *DefaultResult; 5389 SwitchCaseResultVectorTy UniqueResults; 5390 // Collect all the cases that will deliver the same value from the switch. 5391 if (!InitializeUniqueCases(SI, PHI, CommonDest, UniqueResults, DefaultResult, 5392 DL, TTI, /*MaxUniqueResults*/2, 5393 /*MaxCasesPerResult*/2)) 5394 return false; 5395 assert(PHI != nullptr && "PHI for value select not found"); 5396 5397 Builder.SetInsertPoint(SI); 5398 Value *SelectValue = 5399 ConvertTwoCaseSwitch(UniqueResults, DefaultResult, Cond, Builder); 5400 if (SelectValue) { 5401 RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder, DTU); 5402 return true; 5403 } 5404 // The switch couldn't be converted into a select. 5405 return false; 5406 } 5407 5408 namespace { 5409 5410 /// This class represents a lookup table that can be used to replace a switch. 5411 class SwitchLookupTable { 5412 public: 5413 /// Create a lookup table to use as a switch replacement with the contents 5414 /// of Values, using DefaultValue to fill any holes in the table. 5415 SwitchLookupTable( 5416 Module &M, uint64_t TableSize, ConstantInt *Offset, 5417 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values, 5418 Constant *DefaultValue, const DataLayout &DL, const StringRef &FuncName); 5419 5420 /// Build instructions with Builder to retrieve the value at 5421 /// the position given by Index in the lookup table. 5422 Value *BuildLookup(Value *Index, IRBuilder<> &Builder); 5423 5424 /// Return true if a table with TableSize elements of 5425 /// type ElementType would fit in a target-legal register. 5426 static bool WouldFitInRegister(const DataLayout &DL, uint64_t TableSize, 5427 Type *ElementType); 5428 5429 private: 5430 // Depending on the contents of the table, it can be represented in 5431 // different ways. 5432 enum { 5433 // For tables where each element contains the same value, we just have to 5434 // store that single value and return it for each lookup. 5435 SingleValueKind, 5436 5437 // For tables where there is a linear relationship between table index 5438 // and values. We calculate the result with a simple multiplication 5439 // and addition instead of a table lookup. 5440 LinearMapKind, 5441 5442 // For small tables with integer elements, we can pack them into a bitmap 5443 // that fits into a target-legal register. Values are retrieved by 5444 // shift and mask operations. 5445 BitMapKind, 5446 5447 // The table is stored as an array of values. Values are retrieved by load 5448 // instructions from the table. 5449 ArrayKind 5450 } Kind; 5451 5452 // For SingleValueKind, this is the single value. 5453 Constant *SingleValue = nullptr; 5454 5455 // For BitMapKind, this is the bitmap. 5456 ConstantInt *BitMap = nullptr; 5457 IntegerType *BitMapElementTy = nullptr; 5458 5459 // For LinearMapKind, these are the constants used to derive the value. 5460 ConstantInt *LinearOffset = nullptr; 5461 ConstantInt *LinearMultiplier = nullptr; 5462 5463 // For ArrayKind, this is the array. 5464 GlobalVariable *Array = nullptr; 5465 }; 5466 5467 } // end anonymous namespace 5468 5469 SwitchLookupTable::SwitchLookupTable( 5470 Module &M, uint64_t TableSize, ConstantInt *Offset, 5471 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values, 5472 Constant *DefaultValue, const DataLayout &DL, const StringRef &FuncName) { 5473 assert(Values.size() && "Can't build lookup table without values!"); 5474 assert(TableSize >= Values.size() && "Can't fit values in table!"); 5475 5476 // If all values in the table are equal, this is that value. 5477 SingleValue = Values.begin()->second; 5478 5479 Type *ValueType = Values.begin()->second->getType(); 5480 5481 // Build up the table contents. 5482 SmallVector<Constant *, 64> TableContents(TableSize); 5483 for (size_t I = 0, E = Values.size(); I != E; ++I) { 5484 ConstantInt *CaseVal = Values[I].first; 5485 Constant *CaseRes = Values[I].second; 5486 assert(CaseRes->getType() == ValueType); 5487 5488 uint64_t Idx = (CaseVal->getValue() - Offset->getValue()).getLimitedValue(); 5489 TableContents[Idx] = CaseRes; 5490 5491 if (CaseRes != SingleValue) 5492 SingleValue = nullptr; 5493 } 5494 5495 // Fill in any holes in the table with the default result. 5496 if (Values.size() < TableSize) { 5497 assert(DefaultValue && 5498 "Need a default value to fill the lookup table holes."); 5499 assert(DefaultValue->getType() == ValueType); 5500 for (uint64_t I = 0; I < TableSize; ++I) { 5501 if (!TableContents[I]) 5502 TableContents[I] = DefaultValue; 5503 } 5504 5505 if (DefaultValue != SingleValue) 5506 SingleValue = nullptr; 5507 } 5508 5509 // If each element in the table contains the same value, we only need to store 5510 // that single value. 5511 if (SingleValue) { 5512 Kind = SingleValueKind; 5513 return; 5514 } 5515 5516 // Check if we can derive the value with a linear transformation from the 5517 // table index. 5518 if (isa<IntegerType>(ValueType)) { 5519 bool LinearMappingPossible = true; 5520 APInt PrevVal; 5521 APInt DistToPrev; 5522 assert(TableSize >= 2 && "Should be a SingleValue table."); 5523 // Check if there is the same distance between two consecutive values. 5524 for (uint64_t I = 0; I < TableSize; ++I) { 5525 ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]); 5526 if (!ConstVal) { 5527 // This is an undef. We could deal with it, but undefs in lookup tables 5528 // are very seldom. It's probably not worth the additional complexity. 5529 LinearMappingPossible = false; 5530 break; 5531 } 5532 const APInt &Val = ConstVal->getValue(); 5533 if (I != 0) { 5534 APInt Dist = Val - PrevVal; 5535 if (I == 1) { 5536 DistToPrev = Dist; 5537 } else if (Dist != DistToPrev) { 5538 LinearMappingPossible = false; 5539 break; 5540 } 5541 } 5542 PrevVal = Val; 5543 } 5544 if (LinearMappingPossible) { 5545 LinearOffset = cast<ConstantInt>(TableContents[0]); 5546 LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev); 5547 Kind = LinearMapKind; 5548 ++NumLinearMaps; 5549 return; 5550 } 5551 } 5552 5553 // If the type is integer and the table fits in a register, build a bitmap. 5554 if (WouldFitInRegister(DL, TableSize, ValueType)) { 5555 IntegerType *IT = cast<IntegerType>(ValueType); 5556 APInt TableInt(TableSize * IT->getBitWidth(), 0); 5557 for (uint64_t I = TableSize; I > 0; --I) { 5558 TableInt <<= IT->getBitWidth(); 5559 // Insert values into the bitmap. Undef values are set to zero. 5560 if (!isa<UndefValue>(TableContents[I - 1])) { 5561 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]); 5562 TableInt |= Val->getValue().zext(TableInt.getBitWidth()); 5563 } 5564 } 5565 BitMap = ConstantInt::get(M.getContext(), TableInt); 5566 BitMapElementTy = IT; 5567 Kind = BitMapKind; 5568 ++NumBitMaps; 5569 return; 5570 } 5571 5572 // Store the table in an array. 5573 ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize); 5574 Constant *Initializer = ConstantArray::get(ArrayTy, TableContents); 5575 5576 Array = new GlobalVariable(M, ArrayTy, /*isConstant=*/true, 5577 GlobalVariable::PrivateLinkage, Initializer, 5578 "switch.table." + FuncName); 5579 Array->setUnnamedAddr(GlobalValue::UnnamedAddr::Global); 5580 // Set the alignment to that of an array items. We will be only loading one 5581 // value out of it. 5582 Array->setAlignment(Align(DL.getPrefTypeAlignment(ValueType))); 5583 Kind = ArrayKind; 5584 } 5585 5586 Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) { 5587 switch (Kind) { 5588 case SingleValueKind: 5589 return SingleValue; 5590 case LinearMapKind: { 5591 // Derive the result value from the input value. 5592 Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(), 5593 false, "switch.idx.cast"); 5594 if (!LinearMultiplier->isOne()) 5595 Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult"); 5596 if (!LinearOffset->isZero()) 5597 Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset"); 5598 return Result; 5599 } 5600 case BitMapKind: { 5601 // Type of the bitmap (e.g. i59). 5602 IntegerType *MapTy = BitMap->getType(); 5603 5604 // Cast Index to the same type as the bitmap. 5605 // Note: The Index is <= the number of elements in the table, so 5606 // truncating it to the width of the bitmask is safe. 5607 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast"); 5608 5609 // Multiply the shift amount by the element width. 5610 ShiftAmt = Builder.CreateMul( 5611 ShiftAmt, ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()), 5612 "switch.shiftamt"); 5613 5614 // Shift down. 5615 Value *DownShifted = 5616 Builder.CreateLShr(BitMap, ShiftAmt, "switch.downshift"); 5617 // Mask off. 5618 return Builder.CreateTrunc(DownShifted, BitMapElementTy, "switch.masked"); 5619 } 5620 case ArrayKind: { 5621 // Make sure the table index will not overflow when treated as signed. 5622 IntegerType *IT = cast<IntegerType>(Index->getType()); 5623 uint64_t TableSize = 5624 Array->getInitializer()->getType()->getArrayNumElements(); 5625 if (TableSize > (1ULL << (IT->getBitWidth() - 1))) 5626 Index = Builder.CreateZExt( 5627 Index, IntegerType::get(IT->getContext(), IT->getBitWidth() + 1), 5628 "switch.tableidx.zext"); 5629 5630 Value *GEPIndices[] = {Builder.getInt32(0), Index}; 5631 Value *GEP = Builder.CreateInBoundsGEP(Array->getValueType(), Array, 5632 GEPIndices, "switch.gep"); 5633 return Builder.CreateLoad( 5634 cast<ArrayType>(Array->getValueType())->getElementType(), GEP, 5635 "switch.load"); 5636 } 5637 } 5638 llvm_unreachable("Unknown lookup table kind!"); 5639 } 5640 5641 bool SwitchLookupTable::WouldFitInRegister(const DataLayout &DL, 5642 uint64_t TableSize, 5643 Type *ElementType) { 5644 auto *IT = dyn_cast<IntegerType>(ElementType); 5645 if (!IT) 5646 return false; 5647 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values 5648 // are <= 15, we could try to narrow the type. 5649 5650 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width. 5651 if (TableSize >= UINT_MAX / IT->getBitWidth()) 5652 return false; 5653 return DL.fitsInLegalInteger(TableSize * IT->getBitWidth()); 5654 } 5655 5656 static bool isTypeLegalForLookupTable(Type *Ty, const TargetTransformInfo &TTI, 5657 const DataLayout &DL) { 5658 // Allow any legal type. 5659 if (TTI.isTypeLegal(Ty)) 5660 return true; 5661 5662 auto *IT = dyn_cast<IntegerType>(Ty); 5663 if (!IT) 5664 return false; 5665 5666 // Also allow power of 2 integer types that have at least 8 bits and fit in 5667 // a register. These types are common in frontend languages and targets 5668 // usually support loads of these types. 5669 // TODO: We could relax this to any integer that fits in a register and rely 5670 // on ABI alignment and padding in the table to allow the load to be widened. 5671 // Or we could widen the constants and truncate the load. 5672 unsigned BitWidth = IT->getBitWidth(); 5673 return BitWidth >= 8 && isPowerOf2_32(BitWidth) && 5674 DL.fitsInLegalInteger(IT->getBitWidth()); 5675 } 5676 5677 /// Determine whether a lookup table should be built for this switch, based on 5678 /// the number of cases, size of the table, and the types of the results. 5679 // TODO: We could support larger than legal types by limiting based on the 5680 // number of loads required and/or table size. If the constants are small we 5681 // could use smaller table entries and extend after the load. 5682 static bool 5683 ShouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize, 5684 const TargetTransformInfo &TTI, const DataLayout &DL, 5685 const SmallDenseMap<PHINode *, Type *> &ResultTypes) { 5686 if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10) 5687 return false; // TableSize overflowed, or mul below might overflow. 5688 5689 bool AllTablesFitInRegister = true; 5690 bool HasIllegalType = false; 5691 for (const auto &I : ResultTypes) { 5692 Type *Ty = I.second; 5693 5694 // Saturate this flag to true. 5695 HasIllegalType = HasIllegalType || !isTypeLegalForLookupTable(Ty, TTI, DL); 5696 5697 // Saturate this flag to false. 5698 AllTablesFitInRegister = 5699 AllTablesFitInRegister && 5700 SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty); 5701 5702 // If both flags saturate, we're done. NOTE: This *only* works with 5703 // saturating flags, and all flags have to saturate first due to the 5704 // non-deterministic behavior of iterating over a dense map. 5705 if (HasIllegalType && !AllTablesFitInRegister) 5706 break; 5707 } 5708 5709 // If each table would fit in a register, we should build it anyway. 5710 if (AllTablesFitInRegister) 5711 return true; 5712 5713 // Don't build a table that doesn't fit in-register if it has illegal types. 5714 if (HasIllegalType) 5715 return false; 5716 5717 // The table density should be at least 40%. This is the same criterion as for 5718 // jump tables, see SelectionDAGBuilder::handleJTSwitchCase. 5719 // FIXME: Find the best cut-off. 5720 return SI->getNumCases() * 10 >= TableSize * 4; 5721 } 5722 5723 /// Try to reuse the switch table index compare. Following pattern: 5724 /// \code 5725 /// if (idx < tablesize) 5726 /// r = table[idx]; // table does not contain default_value 5727 /// else 5728 /// r = default_value; 5729 /// if (r != default_value) 5730 /// ... 5731 /// \endcode 5732 /// Is optimized to: 5733 /// \code 5734 /// cond = idx < tablesize; 5735 /// if (cond) 5736 /// r = table[idx]; 5737 /// else 5738 /// r = default_value; 5739 /// if (cond) 5740 /// ... 5741 /// \endcode 5742 /// Jump threading will then eliminate the second if(cond). 5743 static void reuseTableCompare( 5744 User *PhiUser, BasicBlock *PhiBlock, BranchInst *RangeCheckBranch, 5745 Constant *DefaultValue, 5746 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values) { 5747 ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser); 5748 if (!CmpInst) 5749 return; 5750 5751 // We require that the compare is in the same block as the phi so that jump 5752 // threading can do its work afterwards. 5753 if (CmpInst->getParent() != PhiBlock) 5754 return; 5755 5756 Constant *CmpOp1 = dyn_cast<Constant>(CmpInst->getOperand(1)); 5757 if (!CmpOp1) 5758 return; 5759 5760 Value *RangeCmp = RangeCheckBranch->getCondition(); 5761 Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType()); 5762 Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType()); 5763 5764 // Check if the compare with the default value is constant true or false. 5765 Constant *DefaultConst = ConstantExpr::getICmp(CmpInst->getPredicate(), 5766 DefaultValue, CmpOp1, true); 5767 if (DefaultConst != TrueConst && DefaultConst != FalseConst) 5768 return; 5769 5770 // Check if the compare with the case values is distinct from the default 5771 // compare result. 5772 for (auto ValuePair : Values) { 5773 Constant *CaseConst = ConstantExpr::getICmp(CmpInst->getPredicate(), 5774 ValuePair.second, CmpOp1, true); 5775 if (!CaseConst || CaseConst == DefaultConst || isa<UndefValue>(CaseConst)) 5776 return; 5777 assert((CaseConst == TrueConst || CaseConst == FalseConst) && 5778 "Expect true or false as compare result."); 5779 } 5780 5781 // Check if the branch instruction dominates the phi node. It's a simple 5782 // dominance check, but sufficient for our needs. 5783 // Although this check is invariant in the calling loops, it's better to do it 5784 // at this late stage. Practically we do it at most once for a switch. 5785 BasicBlock *BranchBlock = RangeCheckBranch->getParent(); 5786 for (BasicBlock *Pred : predecessors(PhiBlock)) { 5787 if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock) 5788 return; 5789 } 5790 5791 if (DefaultConst == FalseConst) { 5792 // The compare yields the same result. We can replace it. 5793 CmpInst->replaceAllUsesWith(RangeCmp); 5794 ++NumTableCmpReuses; 5795 } else { 5796 // The compare yields the same result, just inverted. We can replace it. 5797 Value *InvertedTableCmp = BinaryOperator::CreateXor( 5798 RangeCmp, ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp", 5799 RangeCheckBranch); 5800 CmpInst->replaceAllUsesWith(InvertedTableCmp); 5801 ++NumTableCmpReuses; 5802 } 5803 } 5804 5805 /// If the switch is only used to initialize one or more phi nodes in a common 5806 /// successor block with different constant values, replace the switch with 5807 /// lookup tables. 5808 static bool SwitchToLookupTable(SwitchInst *SI, IRBuilder<> &Builder, 5809 DomTreeUpdater *DTU, const DataLayout &DL, 5810 const TargetTransformInfo &TTI) { 5811 assert(SI->getNumCases() > 1 && "Degenerate switch?"); 5812 5813 BasicBlock *BB = SI->getParent(); 5814 Function *Fn = BB->getParent(); 5815 // Only build lookup table when we have a target that supports it or the 5816 // attribute is not set. 5817 if (!TTI.shouldBuildLookupTables() || 5818 (Fn->getFnAttribute("no-jump-tables").getValueAsBool())) 5819 return false; 5820 5821 // FIXME: If the switch is too sparse for a lookup table, perhaps we could 5822 // split off a dense part and build a lookup table for that. 5823 5824 // FIXME: This creates arrays of GEPs to constant strings, which means each 5825 // GEP needs a runtime relocation in PIC code. We should just build one big 5826 // string and lookup indices into that. 5827 5828 // Ignore switches with less than three cases. Lookup tables will not make 5829 // them faster, so we don't analyze them. 5830 if (SI->getNumCases() < 3) 5831 return false; 5832 5833 // Figure out the corresponding result for each case value and phi node in the 5834 // common destination, as well as the min and max case values. 5835 assert(!SI->cases().empty()); 5836 SwitchInst::CaseIt CI = SI->case_begin(); 5837 ConstantInt *MinCaseVal = CI->getCaseValue(); 5838 ConstantInt *MaxCaseVal = CI->getCaseValue(); 5839 5840 BasicBlock *CommonDest = nullptr; 5841 5842 using ResultListTy = SmallVector<std::pair<ConstantInt *, Constant *>, 4>; 5843 SmallDenseMap<PHINode *, ResultListTy> ResultLists; 5844 5845 SmallDenseMap<PHINode *, Constant *> DefaultResults; 5846 SmallDenseMap<PHINode *, Type *> ResultTypes; 5847 SmallVector<PHINode *, 4> PHIs; 5848 5849 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) { 5850 ConstantInt *CaseVal = CI->getCaseValue(); 5851 if (CaseVal->getValue().slt(MinCaseVal->getValue())) 5852 MinCaseVal = CaseVal; 5853 if (CaseVal->getValue().sgt(MaxCaseVal->getValue())) 5854 MaxCaseVal = CaseVal; 5855 5856 // Resulting value at phi nodes for this case value. 5857 using ResultsTy = SmallVector<std::pair<PHINode *, Constant *>, 4>; 5858 ResultsTy Results; 5859 if (!GetCaseResults(SI, CaseVal, CI->getCaseSuccessor(), &CommonDest, 5860 Results, DL, TTI)) 5861 return false; 5862 5863 // Append the result from this case to the list for each phi. 5864 for (const auto &I : Results) { 5865 PHINode *PHI = I.first; 5866 Constant *Value = I.second; 5867 if (!ResultLists.count(PHI)) 5868 PHIs.push_back(PHI); 5869 ResultLists[PHI].push_back(std::make_pair(CaseVal, Value)); 5870 } 5871 } 5872 5873 // Keep track of the result types. 5874 for (PHINode *PHI : PHIs) { 5875 ResultTypes[PHI] = ResultLists[PHI][0].second->getType(); 5876 } 5877 5878 uint64_t NumResults = ResultLists[PHIs[0]].size(); 5879 APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue(); 5880 uint64_t TableSize = RangeSpread.getLimitedValue() + 1; 5881 bool TableHasHoles = (NumResults < TableSize); 5882 5883 // If the table has holes, we need a constant result for the default case 5884 // or a bitmask that fits in a register. 5885 SmallVector<std::pair<PHINode *, Constant *>, 4> DefaultResultsList; 5886 bool HasDefaultResults = 5887 GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, 5888 DefaultResultsList, DL, TTI); 5889 5890 bool NeedMask = (TableHasHoles && !HasDefaultResults); 5891 if (NeedMask) { 5892 // As an extra penalty for the validity test we require more cases. 5893 if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark). 5894 return false; 5895 if (!DL.fitsInLegalInteger(TableSize)) 5896 return false; 5897 } 5898 5899 for (const auto &I : DefaultResultsList) { 5900 PHINode *PHI = I.first; 5901 Constant *Result = I.second; 5902 DefaultResults[PHI] = Result; 5903 } 5904 5905 if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes)) 5906 return false; 5907 5908 std::vector<DominatorTree::UpdateType> Updates; 5909 5910 // Create the BB that does the lookups. 5911 Module &Mod = *CommonDest->getParent()->getParent(); 5912 BasicBlock *LookupBB = BasicBlock::Create( 5913 Mod.getContext(), "switch.lookup", CommonDest->getParent(), CommonDest); 5914 5915 // Compute the table index value. 5916 Builder.SetInsertPoint(SI); 5917 Value *TableIndex; 5918 if (MinCaseVal->isNullValue()) 5919 TableIndex = SI->getCondition(); 5920 else 5921 TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal, 5922 "switch.tableidx"); 5923 5924 // Compute the maximum table size representable by the integer type we are 5925 // switching upon. 5926 unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits(); 5927 uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize; 5928 assert(MaxTableSize >= TableSize && 5929 "It is impossible for a switch to have more entries than the max " 5930 "representable value of its input integer type's size."); 5931 5932 // If the default destination is unreachable, or if the lookup table covers 5933 // all values of the conditional variable, branch directly to the lookup table 5934 // BB. Otherwise, check that the condition is within the case range. 5935 const bool DefaultIsReachable = 5936 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg()); 5937 const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize); 5938 BranchInst *RangeCheckBranch = nullptr; 5939 5940 if (!DefaultIsReachable || GeneratingCoveredLookupTable) { 5941 Builder.CreateBr(LookupBB); 5942 if (DTU) 5943 Updates.push_back({DominatorTree::Insert, BB, LookupBB}); 5944 // Note: We call removeProdecessor later since we need to be able to get the 5945 // PHI value for the default case in case we're using a bit mask. 5946 } else { 5947 Value *Cmp = Builder.CreateICmpULT( 5948 TableIndex, ConstantInt::get(MinCaseVal->getType(), TableSize)); 5949 RangeCheckBranch = 5950 Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest()); 5951 if (DTU) 5952 Updates.push_back({DominatorTree::Insert, BB, LookupBB}); 5953 } 5954 5955 // Populate the BB that does the lookups. 5956 Builder.SetInsertPoint(LookupBB); 5957 5958 if (NeedMask) { 5959 // Before doing the lookup, we do the hole check. The LookupBB is therefore 5960 // re-purposed to do the hole check, and we create a new LookupBB. 5961 BasicBlock *MaskBB = LookupBB; 5962 MaskBB->setName("switch.hole_check"); 5963 LookupBB = BasicBlock::Create(Mod.getContext(), "switch.lookup", 5964 CommonDest->getParent(), CommonDest); 5965 5966 // Make the mask's bitwidth at least 8-bit and a power-of-2 to avoid 5967 // unnecessary illegal types. 5968 uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL)); 5969 APInt MaskInt(TableSizePowOf2, 0); 5970 APInt One(TableSizePowOf2, 1); 5971 // Build bitmask; fill in a 1 bit for every case. 5972 const ResultListTy &ResultList = ResultLists[PHIs[0]]; 5973 for (size_t I = 0, E = ResultList.size(); I != E; ++I) { 5974 uint64_t Idx = (ResultList[I].first->getValue() - MinCaseVal->getValue()) 5975 .getLimitedValue(); 5976 MaskInt |= One << Idx; 5977 } 5978 ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt); 5979 5980 // Get the TableIndex'th bit of the bitmask. 5981 // If this bit is 0 (meaning hole) jump to the default destination, 5982 // else continue with table lookup. 5983 IntegerType *MapTy = TableMask->getType(); 5984 Value *MaskIndex = 5985 Builder.CreateZExtOrTrunc(TableIndex, MapTy, "switch.maskindex"); 5986 Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex, "switch.shifted"); 5987 Value *LoBit = Builder.CreateTrunc( 5988 Shifted, Type::getInt1Ty(Mod.getContext()), "switch.lobit"); 5989 Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest()); 5990 if (DTU) { 5991 Updates.push_back({DominatorTree::Insert, MaskBB, LookupBB}); 5992 Updates.push_back({DominatorTree::Insert, MaskBB, SI->getDefaultDest()}); 5993 } 5994 Builder.SetInsertPoint(LookupBB); 5995 AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, BB); 5996 } 5997 5998 if (!DefaultIsReachable || GeneratingCoveredLookupTable) { 5999 // We cached PHINodes in PHIs. To avoid accessing deleted PHINodes later, 6000 // do not delete PHINodes here. 6001 SI->getDefaultDest()->removePredecessor(BB, 6002 /*KeepOneInputPHIs=*/true); 6003 if (DTU) 6004 Updates.push_back({DominatorTree::Delete, BB, SI->getDefaultDest()}); 6005 } 6006 6007 for (PHINode *PHI : PHIs) { 6008 const ResultListTy &ResultList = ResultLists[PHI]; 6009 6010 // If using a bitmask, use any value to fill the lookup table holes. 6011 Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI]; 6012 StringRef FuncName = Fn->getName(); 6013 SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL, 6014 FuncName); 6015 6016 Value *Result = Table.BuildLookup(TableIndex, Builder); 6017 6018 // Do a small peephole optimization: re-use the switch table compare if 6019 // possible. 6020 if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) { 6021 BasicBlock *PhiBlock = PHI->getParent(); 6022 // Search for compare instructions which use the phi. 6023 for (auto *User : PHI->users()) { 6024 reuseTableCompare(User, PhiBlock, RangeCheckBranch, DV, ResultList); 6025 } 6026 } 6027 6028 PHI->addIncoming(Result, LookupBB); 6029 } 6030 6031 Builder.CreateBr(CommonDest); 6032 if (DTU) 6033 Updates.push_back({DominatorTree::Insert, LookupBB, CommonDest}); 6034 6035 // Remove the switch. 6036 SmallPtrSet<BasicBlock *, 8> RemovedSuccessors; 6037 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) { 6038 BasicBlock *Succ = SI->getSuccessor(i); 6039 6040 if (Succ == SI->getDefaultDest()) 6041 continue; 6042 Succ->removePredecessor(BB); 6043 RemovedSuccessors.insert(Succ); 6044 } 6045 SI->eraseFromParent(); 6046 6047 if (DTU) { 6048 for (BasicBlock *RemovedSuccessor : RemovedSuccessors) 6049 Updates.push_back({DominatorTree::Delete, BB, RemovedSuccessor}); 6050 DTU->applyUpdates(Updates); 6051 } 6052 6053 ++NumLookupTables; 6054 if (NeedMask) 6055 ++NumLookupTablesHoles; 6056 return true; 6057 } 6058 6059 static bool isSwitchDense(ArrayRef<int64_t> Values) { 6060 // See also SelectionDAGBuilder::isDense(), which this function was based on. 6061 uint64_t Diff = (uint64_t)Values.back() - (uint64_t)Values.front(); 6062 uint64_t Range = Diff + 1; 6063 uint64_t NumCases = Values.size(); 6064 // 40% is the default density for building a jump table in optsize/minsize mode. 6065 uint64_t MinDensity = 40; 6066 6067 return NumCases * 100 >= Range * MinDensity; 6068 } 6069 6070 /// Try to transform a switch that has "holes" in it to a contiguous sequence 6071 /// of cases. 6072 /// 6073 /// A switch such as: switch(i) {case 5: case 9: case 13: case 17:} can be 6074 /// range-reduced to: switch ((i-5) / 4) {case 0: case 1: case 2: case 3:}. 6075 /// 6076 /// This converts a sparse switch into a dense switch which allows better 6077 /// lowering and could also allow transforming into a lookup table. 6078 static bool ReduceSwitchRange(SwitchInst *SI, IRBuilder<> &Builder, 6079 const DataLayout &DL, 6080 const TargetTransformInfo &TTI) { 6081 auto *CondTy = cast<IntegerType>(SI->getCondition()->getType()); 6082 if (CondTy->getIntegerBitWidth() > 64 || 6083 !DL.fitsInLegalInteger(CondTy->getIntegerBitWidth())) 6084 return false; 6085 // Only bother with this optimization if there are more than 3 switch cases; 6086 // SDAG will only bother creating jump tables for 4 or more cases. 6087 if (SI->getNumCases() < 4) 6088 return false; 6089 6090 // This transform is agnostic to the signedness of the input or case values. We 6091 // can treat the case values as signed or unsigned. We can optimize more common 6092 // cases such as a sequence crossing zero {-4,0,4,8} if we interpret case values 6093 // as signed. 6094 SmallVector<int64_t,4> Values; 6095 for (auto &C : SI->cases()) 6096 Values.push_back(C.getCaseValue()->getValue().getSExtValue()); 6097 llvm::sort(Values); 6098 6099 // If the switch is already dense, there's nothing useful to do here. 6100 if (isSwitchDense(Values)) 6101 return false; 6102 6103 // First, transform the values such that they start at zero and ascend. 6104 int64_t Base = Values[0]; 6105 for (auto &V : Values) 6106 V -= (uint64_t)(Base); 6107 6108 // Now we have signed numbers that have been shifted so that, given enough 6109 // precision, there are no negative values. Since the rest of the transform 6110 // is bitwise only, we switch now to an unsigned representation. 6111 6112 // This transform can be done speculatively because it is so cheap - it 6113 // results in a single rotate operation being inserted. 6114 // FIXME: It's possible that optimizing a switch on powers of two might also 6115 // be beneficial - flag values are often powers of two and we could use a CLZ 6116 // as the key function. 6117 6118 // countTrailingZeros(0) returns 64. As Values is guaranteed to have more than 6119 // one element and LLVM disallows duplicate cases, Shift is guaranteed to be 6120 // less than 64. 6121 unsigned Shift = 64; 6122 for (auto &V : Values) 6123 Shift = std::min(Shift, countTrailingZeros((uint64_t)V)); 6124 assert(Shift < 64); 6125 if (Shift > 0) 6126 for (auto &V : Values) 6127 V = (int64_t)((uint64_t)V >> Shift); 6128 6129 if (!isSwitchDense(Values)) 6130 // Transform didn't create a dense switch. 6131 return false; 6132 6133 // The obvious transform is to shift the switch condition right and emit a 6134 // check that the condition actually cleanly divided by GCD, i.e. 6135 // C & (1 << Shift - 1) == 0 6136 // inserting a new CFG edge to handle the case where it didn't divide cleanly. 6137 // 6138 // A cheaper way of doing this is a simple ROTR(C, Shift). This performs the 6139 // shift and puts the shifted-off bits in the uppermost bits. If any of these 6140 // are nonzero then the switch condition will be very large and will hit the 6141 // default case. 6142 6143 auto *Ty = cast<IntegerType>(SI->getCondition()->getType()); 6144 Builder.SetInsertPoint(SI); 6145 auto *ShiftC = ConstantInt::get(Ty, Shift); 6146 auto *Sub = Builder.CreateSub(SI->getCondition(), ConstantInt::get(Ty, Base)); 6147 auto *LShr = Builder.CreateLShr(Sub, ShiftC); 6148 auto *Shl = Builder.CreateShl(Sub, Ty->getBitWidth() - Shift); 6149 auto *Rot = Builder.CreateOr(LShr, Shl); 6150 SI->replaceUsesOfWith(SI->getCondition(), Rot); 6151 6152 for (auto Case : SI->cases()) { 6153 auto *Orig = Case.getCaseValue(); 6154 auto Sub = Orig->getValue() - APInt(Ty->getBitWidth(), Base); 6155 Case.setValue( 6156 cast<ConstantInt>(ConstantInt::get(Ty, Sub.lshr(ShiftC->getValue())))); 6157 } 6158 return true; 6159 } 6160 6161 bool SimplifyCFGOpt::simplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) { 6162 BasicBlock *BB = SI->getParent(); 6163 6164 if (isValueEqualityComparison(SI)) { 6165 // If we only have one predecessor, and if it is a branch on this value, 6166 // see if that predecessor totally determines the outcome of this switch. 6167 if (BasicBlock *OnlyPred = BB->getSinglePredecessor()) 6168 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder)) 6169 return requestResimplify(); 6170 6171 Value *Cond = SI->getCondition(); 6172 if (SelectInst *Select = dyn_cast<SelectInst>(Cond)) 6173 if (SimplifySwitchOnSelect(SI, Select)) 6174 return requestResimplify(); 6175 6176 // If the block only contains the switch, see if we can fold the block 6177 // away into any preds. 6178 if (SI == &*BB->instructionsWithoutDebug(false).begin()) 6179 if (FoldValueComparisonIntoPredecessors(SI, Builder)) 6180 return requestResimplify(); 6181 } 6182 6183 // Try to transform the switch into an icmp and a branch. 6184 if (TurnSwitchRangeIntoICmp(SI, Builder)) 6185 return requestResimplify(); 6186 6187 // Remove unreachable cases. 6188 if (eliminateDeadSwitchCases(SI, DTU, Options.AC, DL)) 6189 return requestResimplify(); 6190 6191 if (switchToSelect(SI, Builder, DTU, DL, TTI)) 6192 return requestResimplify(); 6193 6194 if (Options.ForwardSwitchCondToPhi && ForwardSwitchConditionToPHI(SI)) 6195 return requestResimplify(); 6196 6197 // The conversion from switch to lookup tables results in difficult-to-analyze 6198 // code and makes pruning branches much harder. This is a problem if the 6199 // switch expression itself can still be restricted as a result of inlining or 6200 // CVP. Therefore, only apply this transformation during late stages of the 6201 // optimisation pipeline. 6202 if (Options.ConvertSwitchToLookupTable && 6203 SwitchToLookupTable(SI, Builder, DTU, DL, TTI)) 6204 return requestResimplify(); 6205 6206 if (ReduceSwitchRange(SI, Builder, DL, TTI)) 6207 return requestResimplify(); 6208 6209 return false; 6210 } 6211 6212 bool SimplifyCFGOpt::simplifyIndirectBr(IndirectBrInst *IBI) { 6213 BasicBlock *BB = IBI->getParent(); 6214 bool Changed = false; 6215 6216 // Eliminate redundant destinations. 6217 SmallPtrSet<Value *, 8> Succs; 6218 SmallPtrSet<BasicBlock *, 8> RemovedSuccs; 6219 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) { 6220 BasicBlock *Dest = IBI->getDestination(i); 6221 if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) { 6222 if (!Dest->hasAddressTaken()) 6223 RemovedSuccs.insert(Dest); 6224 Dest->removePredecessor(BB); 6225 IBI->removeDestination(i); 6226 --i; 6227 --e; 6228 Changed = true; 6229 } 6230 } 6231 6232 if (DTU) { 6233 std::vector<DominatorTree::UpdateType> Updates; 6234 Updates.reserve(RemovedSuccs.size()); 6235 for (auto *RemovedSucc : RemovedSuccs) 6236 Updates.push_back({DominatorTree::Delete, BB, RemovedSucc}); 6237 DTU->applyUpdates(Updates); 6238 } 6239 6240 if (IBI->getNumDestinations() == 0) { 6241 // If the indirectbr has no successors, change it to unreachable. 6242 new UnreachableInst(IBI->getContext(), IBI); 6243 EraseTerminatorAndDCECond(IBI); 6244 return true; 6245 } 6246 6247 if (IBI->getNumDestinations() == 1) { 6248 // If the indirectbr has one successor, change it to a direct branch. 6249 BranchInst::Create(IBI->getDestination(0), IBI); 6250 EraseTerminatorAndDCECond(IBI); 6251 return true; 6252 } 6253 6254 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) { 6255 if (SimplifyIndirectBrOnSelect(IBI, SI)) 6256 return requestResimplify(); 6257 } 6258 return Changed; 6259 } 6260 6261 /// Given an block with only a single landing pad and a unconditional branch 6262 /// try to find another basic block which this one can be merged with. This 6263 /// handles cases where we have multiple invokes with unique landing pads, but 6264 /// a shared handler. 6265 /// 6266 /// We specifically choose to not worry about merging non-empty blocks 6267 /// here. That is a PRE/scheduling problem and is best solved elsewhere. In 6268 /// practice, the optimizer produces empty landing pad blocks quite frequently 6269 /// when dealing with exception dense code. (see: instcombine, gvn, if-else 6270 /// sinking in this file) 6271 /// 6272 /// This is primarily a code size optimization. We need to avoid performing 6273 /// any transform which might inhibit optimization (such as our ability to 6274 /// specialize a particular handler via tail commoning). We do this by not 6275 /// merging any blocks which require us to introduce a phi. Since the same 6276 /// values are flowing through both blocks, we don't lose any ability to 6277 /// specialize. If anything, we make such specialization more likely. 6278 /// 6279 /// TODO - This transformation could remove entries from a phi in the target 6280 /// block when the inputs in the phi are the same for the two blocks being 6281 /// merged. In some cases, this could result in removal of the PHI entirely. 6282 static bool TryToMergeLandingPad(LandingPadInst *LPad, BranchInst *BI, 6283 BasicBlock *BB, DomTreeUpdater *DTU) { 6284 auto Succ = BB->getUniqueSuccessor(); 6285 assert(Succ); 6286 // If there's a phi in the successor block, we'd likely have to introduce 6287 // a phi into the merged landing pad block. 6288 if (isa<PHINode>(*Succ->begin())) 6289 return false; 6290 6291 for (BasicBlock *OtherPred : predecessors(Succ)) { 6292 if (BB == OtherPred) 6293 continue; 6294 BasicBlock::iterator I = OtherPred->begin(); 6295 LandingPadInst *LPad2 = dyn_cast<LandingPadInst>(I); 6296 if (!LPad2 || !LPad2->isIdenticalTo(LPad)) 6297 continue; 6298 for (++I; isa<DbgInfoIntrinsic>(I); ++I) 6299 ; 6300 BranchInst *BI2 = dyn_cast<BranchInst>(I); 6301 if (!BI2 || !BI2->isIdenticalTo(BI)) 6302 continue; 6303 6304 std::vector<DominatorTree::UpdateType> Updates; 6305 6306 // We've found an identical block. Update our predecessors to take that 6307 // path instead and make ourselves dead. 6308 SmallPtrSet<BasicBlock *, 16> Preds(pred_begin(BB), pred_end(BB)); 6309 for (BasicBlock *Pred : Preds) { 6310 InvokeInst *II = cast<InvokeInst>(Pred->getTerminator()); 6311 assert(II->getNormalDest() != BB && II->getUnwindDest() == BB && 6312 "unexpected successor"); 6313 II->setUnwindDest(OtherPred); 6314 if (DTU) { 6315 Updates.push_back({DominatorTree::Insert, Pred, OtherPred}); 6316 Updates.push_back({DominatorTree::Delete, Pred, BB}); 6317 } 6318 } 6319 6320 // The debug info in OtherPred doesn't cover the merged control flow that 6321 // used to go through BB. We need to delete it or update it. 6322 for (Instruction &Inst : llvm::make_early_inc_range(*OtherPred)) 6323 if (isa<DbgInfoIntrinsic>(Inst)) 6324 Inst.eraseFromParent(); 6325 6326 SmallPtrSet<BasicBlock *, 16> Succs(succ_begin(BB), succ_end(BB)); 6327 for (BasicBlock *Succ : Succs) { 6328 Succ->removePredecessor(BB); 6329 if (DTU) 6330 Updates.push_back({DominatorTree::Delete, BB, Succ}); 6331 } 6332 6333 IRBuilder<> Builder(BI); 6334 Builder.CreateUnreachable(); 6335 BI->eraseFromParent(); 6336 if (DTU) 6337 DTU->applyUpdates(Updates); 6338 return true; 6339 } 6340 return false; 6341 } 6342 6343 bool SimplifyCFGOpt::simplifyBranch(BranchInst *Branch, IRBuilder<> &Builder) { 6344 return Branch->isUnconditional() ? simplifyUncondBranch(Branch, Builder) 6345 : simplifyCondBranch(Branch, Builder); 6346 } 6347 6348 bool SimplifyCFGOpt::simplifyUncondBranch(BranchInst *BI, 6349 IRBuilder<> &Builder) { 6350 BasicBlock *BB = BI->getParent(); 6351 BasicBlock *Succ = BI->getSuccessor(0); 6352 6353 // If the Terminator is the only non-phi instruction, simplify the block. 6354 // If LoopHeader is provided, check if the block or its successor is a loop 6355 // header. (This is for early invocations before loop simplify and 6356 // vectorization to keep canonical loop forms for nested loops. These blocks 6357 // can be eliminated when the pass is invoked later in the back-end.) 6358 // Note that if BB has only one predecessor then we do not introduce new 6359 // backedge, so we can eliminate BB. 6360 bool NeedCanonicalLoop = 6361 Options.NeedCanonicalLoop && 6362 (!LoopHeaders.empty() && BB->hasNPredecessorsOrMore(2) && 6363 (is_contained(LoopHeaders, BB) || is_contained(LoopHeaders, Succ))); 6364 BasicBlock::iterator I = BB->getFirstNonPHIOrDbg(true)->getIterator(); 6365 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() && 6366 !NeedCanonicalLoop && TryToSimplifyUncondBranchFromEmptyBlock(BB, DTU)) 6367 return true; 6368 6369 // If the only instruction in the block is a seteq/setne comparison against a 6370 // constant, try to simplify the block. 6371 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) 6372 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) { 6373 for (++I; isa<DbgInfoIntrinsic>(I); ++I) 6374 ; 6375 if (I->isTerminator() && 6376 tryToSimplifyUncondBranchWithICmpInIt(ICI, Builder)) 6377 return true; 6378 } 6379 6380 // See if we can merge an empty landing pad block with another which is 6381 // equivalent. 6382 if (LandingPadInst *LPad = dyn_cast<LandingPadInst>(I)) { 6383 for (++I; isa<DbgInfoIntrinsic>(I); ++I) 6384 ; 6385 if (I->isTerminator() && TryToMergeLandingPad(LPad, BI, BB, DTU)) 6386 return true; 6387 } 6388 6389 // If this basic block is ONLY a compare and a branch, and if a predecessor 6390 // branches to us and our successor, fold the comparison into the 6391 // predecessor and use logical operations to update the incoming value 6392 // for PHI nodes in common successor. 6393 if (FoldBranchToCommonDest(BI, DTU, /*MSSAU=*/nullptr, &TTI, 6394 Options.BonusInstThreshold)) 6395 return requestResimplify(); 6396 return false; 6397 } 6398 6399 static BasicBlock *allPredecessorsComeFromSameSource(BasicBlock *BB) { 6400 BasicBlock *PredPred = nullptr; 6401 for (auto *P : predecessors(BB)) { 6402 BasicBlock *PPred = P->getSinglePredecessor(); 6403 if (!PPred || (PredPred && PredPred != PPred)) 6404 return nullptr; 6405 PredPred = PPred; 6406 } 6407 return PredPred; 6408 } 6409 6410 bool SimplifyCFGOpt::simplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) { 6411 assert( 6412 !isa<ConstantInt>(BI->getCondition()) && 6413 BI->getSuccessor(0) != BI->getSuccessor(1) && 6414 "Tautological conditional branch should have been eliminated already."); 6415 6416 BasicBlock *BB = BI->getParent(); 6417 if (!Options.SimplifyCondBranch) 6418 return false; 6419 6420 // Conditional branch 6421 if (isValueEqualityComparison(BI)) { 6422 // If we only have one predecessor, and if it is a branch on this value, 6423 // see if that predecessor totally determines the outcome of this 6424 // switch. 6425 if (BasicBlock *OnlyPred = BB->getSinglePredecessor()) 6426 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder)) 6427 return requestResimplify(); 6428 6429 // This block must be empty, except for the setcond inst, if it exists. 6430 // Ignore dbg and pseudo intrinsics. 6431 auto I = BB->instructionsWithoutDebug(true).begin(); 6432 if (&*I == BI) { 6433 if (FoldValueComparisonIntoPredecessors(BI, Builder)) 6434 return requestResimplify(); 6435 } else if (&*I == cast<Instruction>(BI->getCondition())) { 6436 ++I; 6437 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder)) 6438 return requestResimplify(); 6439 } 6440 } 6441 6442 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction. 6443 if (SimplifyBranchOnICmpChain(BI, Builder, DL)) 6444 return true; 6445 6446 // If this basic block has dominating predecessor blocks and the dominating 6447 // blocks' conditions imply BI's condition, we know the direction of BI. 6448 Optional<bool> Imp = isImpliedByDomCondition(BI->getCondition(), BI, DL); 6449 if (Imp) { 6450 // Turn this into a branch on constant. 6451 auto *OldCond = BI->getCondition(); 6452 ConstantInt *TorF = *Imp ? ConstantInt::getTrue(BB->getContext()) 6453 : ConstantInt::getFalse(BB->getContext()); 6454 BI->setCondition(TorF); 6455 RecursivelyDeleteTriviallyDeadInstructions(OldCond); 6456 return requestResimplify(); 6457 } 6458 6459 // If this basic block is ONLY a compare and a branch, and if a predecessor 6460 // branches to us and one of our successors, fold the comparison into the 6461 // predecessor and use logical operations to pick the right destination. 6462 if (FoldBranchToCommonDest(BI, DTU, /*MSSAU=*/nullptr, &TTI, 6463 Options.BonusInstThreshold)) 6464 return requestResimplify(); 6465 6466 // We have a conditional branch to two blocks that are only reachable 6467 // from BI. We know that the condbr dominates the two blocks, so see if 6468 // there is any identical code in the "then" and "else" blocks. If so, we 6469 // can hoist it up to the branching block. 6470 if (BI->getSuccessor(0)->getSinglePredecessor()) { 6471 if (BI->getSuccessor(1)->getSinglePredecessor()) { 6472 if (HoistCommon && 6473 HoistThenElseCodeToIf(BI, TTI, !Options.HoistCommonInsts)) 6474 return requestResimplify(); 6475 } else { 6476 // If Successor #1 has multiple preds, we may be able to conditionally 6477 // execute Successor #0 if it branches to Successor #1. 6478 Instruction *Succ0TI = BI->getSuccessor(0)->getTerminator(); 6479 if (Succ0TI->getNumSuccessors() == 1 && 6480 Succ0TI->getSuccessor(0) == BI->getSuccessor(1)) 6481 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), TTI)) 6482 return requestResimplify(); 6483 } 6484 } else if (BI->getSuccessor(1)->getSinglePredecessor()) { 6485 // If Successor #0 has multiple preds, we may be able to conditionally 6486 // execute Successor #1 if it branches to Successor #0. 6487 Instruction *Succ1TI = BI->getSuccessor(1)->getTerminator(); 6488 if (Succ1TI->getNumSuccessors() == 1 && 6489 Succ1TI->getSuccessor(0) == BI->getSuccessor(0)) 6490 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), TTI)) 6491 return requestResimplify(); 6492 } 6493 6494 // If this is a branch on a phi node in the current block, thread control 6495 // through this block if any PHI node entries are constants. 6496 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition())) 6497 if (PN->getParent() == BI->getParent()) 6498 if (FoldCondBranchOnPHI(BI, DTU, DL, Options.AC)) 6499 return requestResimplify(); 6500 6501 // Scan predecessor blocks for conditional branches. 6502 for (BasicBlock *Pred : predecessors(BB)) 6503 if (BranchInst *PBI = dyn_cast<BranchInst>(Pred->getTerminator())) 6504 if (PBI != BI && PBI->isConditional()) 6505 if (SimplifyCondBranchToCondBranch(PBI, BI, DTU, DL, TTI)) 6506 return requestResimplify(); 6507 6508 // Look for diamond patterns. 6509 if (MergeCondStores) 6510 if (BasicBlock *PrevBB = allPredecessorsComeFromSameSource(BB)) 6511 if (BranchInst *PBI = dyn_cast<BranchInst>(PrevBB->getTerminator())) 6512 if (PBI != BI && PBI->isConditional()) 6513 if (mergeConditionalStores(PBI, BI, DTU, DL, TTI)) 6514 return requestResimplify(); 6515 6516 return false; 6517 } 6518 6519 /// Check if passing a value to an instruction will cause undefined behavior. 6520 static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I, bool PtrValueMayBeModified) { 6521 Constant *C = dyn_cast<Constant>(V); 6522 if (!C) 6523 return false; 6524 6525 if (I->use_empty()) 6526 return false; 6527 6528 if (C->isNullValue() || isa<UndefValue>(C)) { 6529 // Only look at the first use, avoid hurting compile time with long uselists 6530 auto *Use = cast<Instruction>(*I->user_begin()); 6531 // Bail out if Use is not in the same BB as I or Use == I or Use comes 6532 // before I in the block. The latter two can be the case if Use is a PHI 6533 // node. 6534 if (Use->getParent() != I->getParent() || Use == I || Use->comesBefore(I)) 6535 return false; 6536 6537 // Now make sure that there are no instructions in between that can alter 6538 // control flow (eg. calls) 6539 auto InstrRange = 6540 make_range(std::next(I->getIterator()), Use->getIterator()); 6541 if (any_of(InstrRange, [](Instruction &I) { 6542 return !isGuaranteedToTransferExecutionToSuccessor(&I); 6543 })) 6544 return false; 6545 6546 // Look through GEPs. A load from a GEP derived from NULL is still undefined 6547 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use)) 6548 if (GEP->getPointerOperand() == I) { 6549 if (!GEP->isInBounds() || !GEP->hasAllZeroIndices()) 6550 PtrValueMayBeModified = true; 6551 return passingValueIsAlwaysUndefined(V, GEP, PtrValueMayBeModified); 6552 } 6553 6554 // Look through bitcasts. 6555 if (BitCastInst *BC = dyn_cast<BitCastInst>(Use)) 6556 return passingValueIsAlwaysUndefined(V, BC, PtrValueMayBeModified); 6557 6558 // Load from null is undefined. 6559 if (LoadInst *LI = dyn_cast<LoadInst>(Use)) 6560 if (!LI->isVolatile()) 6561 return !NullPointerIsDefined(LI->getFunction(), 6562 LI->getPointerAddressSpace()); 6563 6564 // Store to null is undefined. 6565 if (StoreInst *SI = dyn_cast<StoreInst>(Use)) 6566 if (!SI->isVolatile()) 6567 return (!NullPointerIsDefined(SI->getFunction(), 6568 SI->getPointerAddressSpace())) && 6569 SI->getPointerOperand() == I; 6570 6571 if (auto *CB = dyn_cast<CallBase>(Use)) { 6572 if (C->isNullValue() && NullPointerIsDefined(CB->getFunction())) 6573 return false; 6574 // A call to null is undefined. 6575 if (CB->getCalledOperand() == I) 6576 return true; 6577 6578 if (C->isNullValue()) { 6579 for (const llvm::Use &Arg : CB->args()) 6580 if (Arg == I) { 6581 unsigned ArgIdx = CB->getArgOperandNo(&Arg); 6582 if (CB->isPassingUndefUB(ArgIdx) && 6583 CB->paramHasAttr(ArgIdx, Attribute::NonNull)) { 6584 // Passing null to a nonnnull+noundef argument is undefined. 6585 return !PtrValueMayBeModified; 6586 } 6587 } 6588 } else if (isa<UndefValue>(C)) { 6589 // Passing undef to a noundef argument is undefined. 6590 for (const llvm::Use &Arg : CB->args()) 6591 if (Arg == I) { 6592 unsigned ArgIdx = CB->getArgOperandNo(&Arg); 6593 if (CB->isPassingUndefUB(ArgIdx)) { 6594 // Passing undef to a noundef argument is undefined. 6595 return true; 6596 } 6597 } 6598 } 6599 } 6600 } 6601 return false; 6602 } 6603 6604 /// If BB has an incoming value that will always trigger undefined behavior 6605 /// (eg. null pointer dereference), remove the branch leading here. 6606 static bool removeUndefIntroducingPredecessor(BasicBlock *BB, 6607 DomTreeUpdater *DTU) { 6608 for (PHINode &PHI : BB->phis()) 6609 for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) 6610 if (passingValueIsAlwaysUndefined(PHI.getIncomingValue(i), &PHI)) { 6611 BasicBlock *Predecessor = PHI.getIncomingBlock(i); 6612 Instruction *T = Predecessor->getTerminator(); 6613 IRBuilder<> Builder(T); 6614 if (BranchInst *BI = dyn_cast<BranchInst>(T)) { 6615 BB->removePredecessor(Predecessor); 6616 // Turn uncoditional branches into unreachables and remove the dead 6617 // destination from conditional branches. 6618 if (BI->isUnconditional()) 6619 Builder.CreateUnreachable(); 6620 else { 6621 // Preserve guarding condition in assume, because it might not be 6622 // inferrable from any dominating condition. 6623 Value *Cond = BI->getCondition(); 6624 if (BI->getSuccessor(0) == BB) 6625 Builder.CreateAssumption(Builder.CreateNot(Cond)); 6626 else 6627 Builder.CreateAssumption(Cond); 6628 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) 6629 : BI->getSuccessor(0)); 6630 } 6631 BI->eraseFromParent(); 6632 if (DTU) 6633 DTU->applyUpdates({{DominatorTree::Delete, Predecessor, BB}}); 6634 return true; 6635 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) { 6636 // Redirect all branches leading to UB into 6637 // a newly created unreachable block. 6638 BasicBlock *Unreachable = BasicBlock::Create( 6639 Predecessor->getContext(), "unreachable", BB->getParent(), BB); 6640 Builder.SetInsertPoint(Unreachable); 6641 // The new block contains only one instruction: Unreachable 6642 Builder.CreateUnreachable(); 6643 for (auto &Case : SI->cases()) 6644 if (Case.getCaseSuccessor() == BB) { 6645 BB->removePredecessor(Predecessor); 6646 Case.setSuccessor(Unreachable); 6647 } 6648 if (SI->getDefaultDest() == BB) { 6649 BB->removePredecessor(Predecessor); 6650 SI->setDefaultDest(Unreachable); 6651 } 6652 6653 if (DTU) 6654 DTU->applyUpdates( 6655 { { DominatorTree::Insert, Predecessor, Unreachable }, 6656 { DominatorTree::Delete, Predecessor, BB } }); 6657 return true; 6658 } 6659 } 6660 6661 return false; 6662 } 6663 6664 bool SimplifyCFGOpt::simplifyOnce(BasicBlock *BB) { 6665 bool Changed = false; 6666 6667 assert(BB && BB->getParent() && "Block not embedded in function!"); 6668 assert(BB->getTerminator() && "Degenerate basic block encountered!"); 6669 6670 // Remove basic blocks that have no predecessors (except the entry block)... 6671 // or that just have themself as a predecessor. These are unreachable. 6672 if ((pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) || 6673 BB->getSinglePredecessor() == BB) { 6674 LLVM_DEBUG(dbgs() << "Removing BB: \n" << *BB); 6675 DeleteDeadBlock(BB, DTU); 6676 return true; 6677 } 6678 6679 // Check to see if we can constant propagate this terminator instruction 6680 // away... 6681 Changed |= ConstantFoldTerminator(BB, /*DeleteDeadConditions=*/true, 6682 /*TLI=*/nullptr, DTU); 6683 6684 // Check for and eliminate duplicate PHI nodes in this block. 6685 Changed |= EliminateDuplicatePHINodes(BB); 6686 6687 // Check for and remove branches that will always cause undefined behavior. 6688 if (removeUndefIntroducingPredecessor(BB, DTU)) 6689 return requestResimplify(); 6690 6691 // Merge basic blocks into their predecessor if there is only one distinct 6692 // pred, and if there is only one distinct successor of the predecessor, and 6693 // if there are no PHI nodes. 6694 if (MergeBlockIntoPredecessor(BB, DTU)) 6695 return true; 6696 6697 if (SinkCommon && Options.SinkCommonInsts) 6698 if (SinkCommonCodeFromPredecessors(BB, DTU)) { 6699 // SinkCommonCodeFromPredecessors() does not automatically CSE PHI's, 6700 // so we may now how duplicate PHI's. 6701 // Let's rerun EliminateDuplicatePHINodes() first, 6702 // before FoldTwoEntryPHINode() potentially converts them into select's, 6703 // after which we'd need a whole EarlyCSE pass run to cleanup them. 6704 return true; 6705 } 6706 6707 IRBuilder<> Builder(BB); 6708 6709 if (Options.FoldTwoEntryPHINode) { 6710 // If there is a trivial two-entry PHI node in this basic block, and we can 6711 // eliminate it, do so now. 6712 if (auto *PN = dyn_cast<PHINode>(BB->begin())) 6713 if (PN->getNumIncomingValues() == 2) 6714 if (FoldTwoEntryPHINode(PN, TTI, DTU, DL)) 6715 return true; 6716 } 6717 6718 Instruction *Terminator = BB->getTerminator(); 6719 Builder.SetInsertPoint(Terminator); 6720 switch (Terminator->getOpcode()) { 6721 case Instruction::Br: 6722 Changed |= simplifyBranch(cast<BranchInst>(Terminator), Builder); 6723 break; 6724 case Instruction::Resume: 6725 Changed |= simplifyResume(cast<ResumeInst>(Terminator), Builder); 6726 break; 6727 case Instruction::CleanupRet: 6728 Changed |= simplifyCleanupReturn(cast<CleanupReturnInst>(Terminator)); 6729 break; 6730 case Instruction::Switch: 6731 Changed |= simplifySwitch(cast<SwitchInst>(Terminator), Builder); 6732 break; 6733 case Instruction::Unreachable: 6734 Changed |= simplifyUnreachable(cast<UnreachableInst>(Terminator)); 6735 break; 6736 case Instruction::IndirectBr: 6737 Changed |= simplifyIndirectBr(cast<IndirectBrInst>(Terminator)); 6738 break; 6739 } 6740 6741 return Changed; 6742 } 6743 6744 bool SimplifyCFGOpt::run(BasicBlock *BB) { 6745 bool Changed = false; 6746 6747 // Repeated simplify BB as long as resimplification is requested. 6748 do { 6749 Resimplify = false; 6750 6751 // Perform one round of simplifcation. Resimplify flag will be set if 6752 // another iteration is requested. 6753 Changed |= simplifyOnce(BB); 6754 } while (Resimplify); 6755 6756 return Changed; 6757 } 6758 6759 bool llvm::simplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI, 6760 DomTreeUpdater *DTU, const SimplifyCFGOptions &Options, 6761 ArrayRef<WeakVH> LoopHeaders) { 6762 return SimplifyCFGOpt(TTI, DTU, BB->getModule()->getDataLayout(), LoopHeaders, 6763 Options) 6764 .run(BB); 6765 } 6766