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