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