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