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