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