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