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