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