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