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