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 if (User->getParent() == PredBlock) { 2990 // The "exteral" use is in the block into which we just cloned the 2991 // bonus instruction. This means two things: 1. we are in an 2992 // unreachable block 2. the instruction is self-referencing. 2993 // So let's just rewrite it... 2994 return true; 2995 } 2996 (void)BI; 2997 assert(isa<PHINode>(User) && "All external users must be PHI's."); 2998 auto *PN = cast<PHINode>(User); 2999 assert(is_contained(successors(BB), User->getParent()) && 3000 "All external users must be in successors of BB."); 3001 assert((PN->getIncomingBlock(U) == BB || 3002 PN->getIncomingBlock(U) == PredBlock) && 3003 "The incoming block for that incoming value external use " 3004 "must be either the original block with bonus instructions, " 3005 "or the new predecessor block."); 3006 // UniqueSucc is the block for which we change it's predecessors, 3007 // so it is the only block in which we'll need to update PHI nodes. 3008 if (User->getParent() != UniqueSucc) 3009 return false; 3010 // Update the incoming value for the new predecessor. 3011 return PN->getIncomingBlock(U) == 3012 (BI->isConditional() ? PredBlock : BB); 3013 }); 3014 } 3015 3016 // Now that the Cond was cloned into the predecessor basic block, 3017 // or/and the two conditions together. 3018 if (BI->isConditional()) { 3019 Instruction *NewCond = cast<Instruction>( 3020 Builder.CreateBinOp(Opc, PBI->getCondition(), CondInPred, "or.cond")); 3021 PBI->setCondition(NewCond); 3022 3023 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight; 3024 bool HasWeights = 3025 extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight, 3026 SuccTrueWeight, SuccFalseWeight); 3027 SmallVector<uint64_t, 8> NewWeights; 3028 3029 if (PBI->getSuccessor(0) == BB) { 3030 if (HasWeights) { 3031 // PBI: br i1 %x, BB, FalseDest 3032 // BI: br i1 %y, UniqueSucc, FalseDest 3033 // TrueWeight is TrueWeight for PBI * TrueWeight for BI. 3034 NewWeights.push_back(PredTrueWeight * SuccTrueWeight); 3035 // FalseWeight is FalseWeight for PBI * TotalWeight for BI + 3036 // TrueWeight for PBI * FalseWeight for BI. 3037 // We assume that total weights of a BranchInst can fit into 32 bits. 3038 // Therefore, we will not have overflow using 64-bit arithmetic. 3039 NewWeights.push_back(PredFalseWeight * 3040 (SuccFalseWeight + SuccTrueWeight) + 3041 PredTrueWeight * SuccFalseWeight); 3042 } 3043 PBI->setSuccessor(0, UniqueSucc); 3044 } 3045 if (PBI->getSuccessor(1) == BB) { 3046 if (HasWeights) { 3047 // PBI: br i1 %x, TrueDest, BB 3048 // BI: br i1 %y, TrueDest, UniqueSucc 3049 // TrueWeight is TrueWeight for PBI * TotalWeight for BI + 3050 // FalseWeight for PBI * TrueWeight for BI. 3051 NewWeights.push_back(PredTrueWeight * 3052 (SuccFalseWeight + SuccTrueWeight) + 3053 PredFalseWeight * SuccTrueWeight); 3054 // FalseWeight is FalseWeight for PBI * FalseWeight for BI. 3055 NewWeights.push_back(PredFalseWeight * SuccFalseWeight); 3056 } 3057 PBI->setSuccessor(1, UniqueSucc); 3058 } 3059 if (NewWeights.size() == 2) { 3060 // Halve the weights if any of them cannot fit in an uint32_t 3061 FitWeights(NewWeights); 3062 3063 SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(), 3064 NewWeights.end()); 3065 setBranchWeights(PBI, MDWeights[0], MDWeights[1]); 3066 } else 3067 PBI->setMetadata(LLVMContext::MD_prof, nullptr); 3068 3069 Updates.push_back({DominatorTree::Delete, PredBlock, BB}); 3070 Updates.push_back({DominatorTree::Insert, PredBlock, UniqueSucc}); 3071 } else { 3072 // Update PHI nodes in the common successors. 3073 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) { 3074 ConstantInt *PBI_C = cast<ConstantInt>( 3075 PHIs[i]->getIncomingValueForBlock(PBI->getParent())); 3076 assert(PBI_C->getType()->isIntegerTy(1)); 3077 Instruction *MergedCond = nullptr; 3078 if (PBI->getSuccessor(0) == UniqueSucc) { 3079 // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value) 3080 // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value) 3081 // is false: !PBI_Cond and BI_Value 3082 Instruction *NotCond = cast<Instruction>( 3083 Builder.CreateNot(PBI->getCondition(), "not.cond")); 3084 MergedCond = cast<Instruction>( 3085 Builder.CreateBinOp(Instruction::And, NotCond, CondInPred, 3086 "and.cond")); 3087 if (PBI_C->isOne()) 3088 MergedCond = cast<Instruction>(Builder.CreateBinOp( 3089 Instruction::Or, PBI->getCondition(), MergedCond, "or.cond")); 3090 } else { 3091 // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C) 3092 // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond) 3093 // is false: PBI_Cond and BI_Value 3094 MergedCond = cast<Instruction>(Builder.CreateBinOp( 3095 Instruction::And, PBI->getCondition(), CondInPred, "and.cond")); 3096 if (PBI_C->isOne()) { 3097 Instruction *NotCond = cast<Instruction>( 3098 Builder.CreateNot(PBI->getCondition(), "not.cond")); 3099 MergedCond = cast<Instruction>(Builder.CreateBinOp( 3100 Instruction::Or, NotCond, MergedCond, "or.cond")); 3101 } 3102 } 3103 // Update PHI Node. 3104 PHIs[i]->setIncomingValueForBlock(PBI->getParent(), MergedCond); 3105 } 3106 3107 // PBI is changed to branch to UniqueSucc below. Remove itself from 3108 // potential phis from all other successors. 3109 if (MSSAU) 3110 MSSAU->changeCondBranchToUnconditionalTo(PBI, UniqueSucc); 3111 3112 // Change PBI from Conditional to Unconditional. 3113 BranchInst *New_PBI = BranchInst::Create(UniqueSucc, PBI); 3114 EraseTerminatorAndDCECond(PBI, MSSAU); 3115 PBI = New_PBI; 3116 } 3117 3118 if (DTU) 3119 DTU->applyUpdatesPermissive(Updates); 3120 3121 // If BI was a loop latch, it may have had associated loop metadata. 3122 // We need to copy it to the new latch, that is, PBI. 3123 if (MDNode *LoopMD = BI->getMetadata(LLVMContext::MD_loop)) 3124 PBI->setMetadata(LLVMContext::MD_loop, LoopMD); 3125 3126 // TODO: If BB is reachable from all paths through PredBlock, then we 3127 // could replace PBI's branch probabilities with BI's. 3128 3129 // Copy any debug value intrinsics into the end of PredBlock. 3130 for (Instruction &I : *BB) { 3131 if (isa<DbgInfoIntrinsic>(I)) { 3132 Instruction *NewI = I.clone(); 3133 RemapInstruction(NewI, VMap, 3134 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals); 3135 NewI->insertBefore(PBI); 3136 } 3137 } 3138 3139 return Changed; 3140 } 3141 return Changed; 3142 } 3143 3144 // If there is only one store in BB1 and BB2, return it, otherwise return 3145 // nullptr. 3146 static StoreInst *findUniqueStoreInBlocks(BasicBlock *BB1, BasicBlock *BB2) { 3147 StoreInst *S = nullptr; 3148 for (auto *BB : {BB1, BB2}) { 3149 if (!BB) 3150 continue; 3151 for (auto &I : *BB) 3152 if (auto *SI = dyn_cast<StoreInst>(&I)) { 3153 if (S) 3154 // Multiple stores seen. 3155 return nullptr; 3156 else 3157 S = SI; 3158 } 3159 } 3160 return S; 3161 } 3162 3163 static Value *ensureValueAvailableInSuccessor(Value *V, BasicBlock *BB, 3164 Value *AlternativeV = nullptr) { 3165 // PHI is going to be a PHI node that allows the value V that is defined in 3166 // BB to be referenced in BB's only successor. 3167 // 3168 // If AlternativeV is nullptr, the only value we care about in PHI is V. It 3169 // doesn't matter to us what the other operand is (it'll never get used). We 3170 // could just create a new PHI with an undef incoming value, but that could 3171 // increase register pressure if EarlyCSE/InstCombine can't fold it with some 3172 // other PHI. So here we directly look for some PHI in BB's successor with V 3173 // as an incoming operand. If we find one, we use it, else we create a new 3174 // one. 3175 // 3176 // If AlternativeV is not nullptr, we care about both incoming values in PHI. 3177 // PHI must be exactly: phi <ty> [ %BB, %V ], [ %OtherBB, %AlternativeV] 3178 // where OtherBB is the single other predecessor of BB's only successor. 3179 PHINode *PHI = nullptr; 3180 BasicBlock *Succ = BB->getSingleSuccessor(); 3181 3182 for (auto I = Succ->begin(); isa<PHINode>(I); ++I) 3183 if (cast<PHINode>(I)->getIncomingValueForBlock(BB) == V) { 3184 PHI = cast<PHINode>(I); 3185 if (!AlternativeV) 3186 break; 3187 3188 assert(Succ->hasNPredecessors(2)); 3189 auto PredI = pred_begin(Succ); 3190 BasicBlock *OtherPredBB = *PredI == BB ? *++PredI : *PredI; 3191 if (PHI->getIncomingValueForBlock(OtherPredBB) == AlternativeV) 3192 break; 3193 PHI = nullptr; 3194 } 3195 if (PHI) 3196 return PHI; 3197 3198 // If V is not an instruction defined in BB, just return it. 3199 if (!AlternativeV && 3200 (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB)) 3201 return V; 3202 3203 PHI = PHINode::Create(V->getType(), 2, "simplifycfg.merge", &Succ->front()); 3204 PHI->addIncoming(V, BB); 3205 for (BasicBlock *PredBB : predecessors(Succ)) 3206 if (PredBB != BB) 3207 PHI->addIncoming( 3208 AlternativeV ? AlternativeV : UndefValue::get(V->getType()), PredBB); 3209 return PHI; 3210 } 3211 3212 static bool mergeConditionalStoreToAddress(BasicBlock *PTB, BasicBlock *PFB, 3213 BasicBlock *QTB, BasicBlock *QFB, 3214 BasicBlock *PostBB, Value *Address, 3215 bool InvertPCond, bool InvertQCond, 3216 const DataLayout &DL, 3217 const TargetTransformInfo &TTI) { 3218 // For every pointer, there must be exactly two stores, one coming from 3219 // PTB or PFB, and the other from QTB or QFB. We don't support more than one 3220 // store (to any address) in PTB,PFB or QTB,QFB. 3221 // FIXME: We could relax this restriction with a bit more work and performance 3222 // testing. 3223 StoreInst *PStore = findUniqueStoreInBlocks(PTB, PFB); 3224 StoreInst *QStore = findUniqueStoreInBlocks(QTB, QFB); 3225 if (!PStore || !QStore) 3226 return false; 3227 3228 // Now check the stores are compatible. 3229 if (!QStore->isUnordered() || !PStore->isUnordered()) 3230 return false; 3231 3232 // Check that sinking the store won't cause program behavior changes. Sinking 3233 // the store out of the Q blocks won't change any behavior as we're sinking 3234 // from a block to its unconditional successor. But we're moving a store from 3235 // the P blocks down through the middle block (QBI) and past both QFB and QTB. 3236 // So we need to check that there are no aliasing loads or stores in 3237 // QBI, QTB and QFB. We also need to check there are no conflicting memory 3238 // operations between PStore and the end of its parent block. 3239 // 3240 // The ideal way to do this is to query AliasAnalysis, but we don't 3241 // preserve AA currently so that is dangerous. Be super safe and just 3242 // check there are no other memory operations at all. 3243 for (auto &I : *QFB->getSinglePredecessor()) 3244 if (I.mayReadOrWriteMemory()) 3245 return false; 3246 for (auto &I : *QFB) 3247 if (&I != QStore && I.mayReadOrWriteMemory()) 3248 return false; 3249 if (QTB) 3250 for (auto &I : *QTB) 3251 if (&I != QStore && I.mayReadOrWriteMemory()) 3252 return false; 3253 for (auto I = BasicBlock::iterator(PStore), E = PStore->getParent()->end(); 3254 I != E; ++I) 3255 if (&*I != PStore && I->mayReadOrWriteMemory()) 3256 return false; 3257 3258 // If we're not in aggressive mode, we only optimize if we have some 3259 // confidence that by optimizing we'll allow P and/or Q to be if-converted. 3260 auto IsWorthwhile = [&](BasicBlock *BB, ArrayRef<StoreInst *> FreeStores) { 3261 if (!BB) 3262 return true; 3263 // Heuristic: if the block can be if-converted/phi-folded and the 3264 // instructions inside are all cheap (arithmetic/GEPs), it's worthwhile to 3265 // thread this store. 3266 int BudgetRemaining = 3267 PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic; 3268 for (auto &I : BB->instructionsWithoutDebug()) { 3269 // Consider terminator instruction to be free. 3270 if (I.isTerminator()) 3271 continue; 3272 // If this is one the stores that we want to speculate out of this BB, 3273 // then don't count it's cost, consider it to be free. 3274 if (auto *S = dyn_cast<StoreInst>(&I)) 3275 if (llvm::find(FreeStores, S)) 3276 continue; 3277 // Else, we have a white-list of instructions that we are ak speculating. 3278 if (!isa<BinaryOperator>(I) && !isa<GetElementPtrInst>(I)) 3279 return false; // Not in white-list - not worthwhile folding. 3280 // And finally, if this is a non-free instruction that we are okay 3281 // speculating, ensure that we consider the speculation budget. 3282 BudgetRemaining -= TTI.getUserCost(&I, TargetTransformInfo::TCK_SizeAndLatency); 3283 if (BudgetRemaining < 0) 3284 return false; // Eagerly refuse to fold as soon as we're out of budget. 3285 } 3286 assert(BudgetRemaining >= 0 && 3287 "When we run out of budget we will eagerly return from within the " 3288 "per-instruction loop."); 3289 return true; 3290 }; 3291 3292 const std::array<StoreInst *, 2> FreeStores = {PStore, QStore}; 3293 if (!MergeCondStoresAggressively && 3294 (!IsWorthwhile(PTB, FreeStores) || !IsWorthwhile(PFB, FreeStores) || 3295 !IsWorthwhile(QTB, FreeStores) || !IsWorthwhile(QFB, FreeStores))) 3296 return false; 3297 3298 // If PostBB has more than two predecessors, we need to split it so we can 3299 // sink the store. 3300 if (std::next(pred_begin(PostBB), 2) != pred_end(PostBB)) { 3301 // We know that QFB's only successor is PostBB. And QFB has a single 3302 // predecessor. If QTB exists, then its only successor is also PostBB. 3303 // If QTB does not exist, then QFB's only predecessor has a conditional 3304 // branch to QFB and PostBB. 3305 BasicBlock *TruePred = QTB ? QTB : QFB->getSinglePredecessor(); 3306 BasicBlock *NewBB = SplitBlockPredecessors(PostBB, { QFB, TruePred}, 3307 "condstore.split"); 3308 if (!NewBB) 3309 return false; 3310 PostBB = NewBB; 3311 } 3312 3313 // OK, we're going to sink the stores to PostBB. The store has to be 3314 // conditional though, so first create the predicate. 3315 Value *PCond = cast<BranchInst>(PFB->getSinglePredecessor()->getTerminator()) 3316 ->getCondition(); 3317 Value *QCond = cast<BranchInst>(QFB->getSinglePredecessor()->getTerminator()) 3318 ->getCondition(); 3319 3320 Value *PPHI = ensureValueAvailableInSuccessor(PStore->getValueOperand(), 3321 PStore->getParent()); 3322 Value *QPHI = ensureValueAvailableInSuccessor(QStore->getValueOperand(), 3323 QStore->getParent(), PPHI); 3324 3325 IRBuilder<> QB(&*PostBB->getFirstInsertionPt()); 3326 3327 Value *PPred = PStore->getParent() == PTB ? PCond : QB.CreateNot(PCond); 3328 Value *QPred = QStore->getParent() == QTB ? QCond : QB.CreateNot(QCond); 3329 3330 if (InvertPCond) 3331 PPred = QB.CreateNot(PPred); 3332 if (InvertQCond) 3333 QPred = QB.CreateNot(QPred); 3334 Value *CombinedPred = QB.CreateOr(PPred, QPred); 3335 3336 auto *T = 3337 SplitBlockAndInsertIfThen(CombinedPred, &*QB.GetInsertPoint(), false); 3338 QB.SetInsertPoint(T); 3339 StoreInst *SI = cast<StoreInst>(QB.CreateStore(QPHI, Address)); 3340 AAMDNodes AAMD; 3341 PStore->getAAMetadata(AAMD, /*Merge=*/false); 3342 PStore->getAAMetadata(AAMD, /*Merge=*/true); 3343 SI->setAAMetadata(AAMD); 3344 // Choose the minimum alignment. If we could prove both stores execute, we 3345 // could use biggest one. In this case, though, we only know that one of the 3346 // stores executes. And we don't know it's safe to take the alignment from a 3347 // store that doesn't execute. 3348 SI->setAlignment(std::min(PStore->getAlign(), QStore->getAlign())); 3349 3350 QStore->eraseFromParent(); 3351 PStore->eraseFromParent(); 3352 3353 return true; 3354 } 3355 3356 static bool mergeConditionalStores(BranchInst *PBI, BranchInst *QBI, 3357 const DataLayout &DL, 3358 const TargetTransformInfo &TTI) { 3359 // The intention here is to find diamonds or triangles (see below) where each 3360 // conditional block contains a store to the same address. Both of these 3361 // stores are conditional, so they can't be unconditionally sunk. But it may 3362 // be profitable to speculatively sink the stores into one merged store at the 3363 // end, and predicate the merged store on the union of the two conditions of 3364 // PBI and QBI. 3365 // 3366 // This can reduce the number of stores executed if both of the conditions are 3367 // true, and can allow the blocks to become small enough to be if-converted. 3368 // This optimization will also chain, so that ladders of test-and-set 3369 // sequences can be if-converted away. 3370 // 3371 // We only deal with simple diamonds or triangles: 3372 // 3373 // PBI or PBI or a combination of the two 3374 // / \ | \ 3375 // PTB PFB | PFB 3376 // \ / | / 3377 // QBI QBI 3378 // / \ | \ 3379 // QTB QFB | QFB 3380 // \ / | / 3381 // PostBB PostBB 3382 // 3383 // We model triangles as a type of diamond with a nullptr "true" block. 3384 // Triangles are canonicalized so that the fallthrough edge is represented by 3385 // a true condition, as in the diagram above. 3386 BasicBlock *PTB = PBI->getSuccessor(0); 3387 BasicBlock *PFB = PBI->getSuccessor(1); 3388 BasicBlock *QTB = QBI->getSuccessor(0); 3389 BasicBlock *QFB = QBI->getSuccessor(1); 3390 BasicBlock *PostBB = QFB->getSingleSuccessor(); 3391 3392 // Make sure we have a good guess for PostBB. If QTB's only successor is 3393 // QFB, then QFB is a better PostBB. 3394 if (QTB->getSingleSuccessor() == QFB) 3395 PostBB = QFB; 3396 3397 // If we couldn't find a good PostBB, stop. 3398 if (!PostBB) 3399 return false; 3400 3401 bool InvertPCond = false, InvertQCond = false; 3402 // Canonicalize fallthroughs to the true branches. 3403 if (PFB == QBI->getParent()) { 3404 std::swap(PFB, PTB); 3405 InvertPCond = true; 3406 } 3407 if (QFB == PostBB) { 3408 std::swap(QFB, QTB); 3409 InvertQCond = true; 3410 } 3411 3412 // From this point on we can assume PTB or QTB may be fallthroughs but PFB 3413 // and QFB may not. Model fallthroughs as a nullptr block. 3414 if (PTB == QBI->getParent()) 3415 PTB = nullptr; 3416 if (QTB == PostBB) 3417 QTB = nullptr; 3418 3419 // Legality bailouts. We must have at least the non-fallthrough blocks and 3420 // the post-dominating block, and the non-fallthroughs must only have one 3421 // predecessor. 3422 auto HasOnePredAndOneSucc = [](BasicBlock *BB, BasicBlock *P, BasicBlock *S) { 3423 return BB->getSinglePredecessor() == P && BB->getSingleSuccessor() == S; 3424 }; 3425 if (!HasOnePredAndOneSucc(PFB, PBI->getParent(), QBI->getParent()) || 3426 !HasOnePredAndOneSucc(QFB, QBI->getParent(), PostBB)) 3427 return false; 3428 if ((PTB && !HasOnePredAndOneSucc(PTB, PBI->getParent(), QBI->getParent())) || 3429 (QTB && !HasOnePredAndOneSucc(QTB, QBI->getParent(), PostBB))) 3430 return false; 3431 if (!QBI->getParent()->hasNUses(2)) 3432 return false; 3433 3434 // OK, this is a sequence of two diamonds or triangles. 3435 // Check if there are stores in PTB or PFB that are repeated in QTB or QFB. 3436 SmallPtrSet<Value *, 4> PStoreAddresses, QStoreAddresses; 3437 for (auto *BB : {PTB, PFB}) { 3438 if (!BB) 3439 continue; 3440 for (auto &I : *BB) 3441 if (StoreInst *SI = dyn_cast<StoreInst>(&I)) 3442 PStoreAddresses.insert(SI->getPointerOperand()); 3443 } 3444 for (auto *BB : {QTB, QFB}) { 3445 if (!BB) 3446 continue; 3447 for (auto &I : *BB) 3448 if (StoreInst *SI = dyn_cast<StoreInst>(&I)) 3449 QStoreAddresses.insert(SI->getPointerOperand()); 3450 } 3451 3452 set_intersect(PStoreAddresses, QStoreAddresses); 3453 // set_intersect mutates PStoreAddresses in place. Rename it here to make it 3454 // clear what it contains. 3455 auto &CommonAddresses = PStoreAddresses; 3456 3457 bool Changed = false; 3458 for (auto *Address : CommonAddresses) 3459 Changed |= mergeConditionalStoreToAddress( 3460 PTB, PFB, QTB, QFB, PostBB, Address, InvertPCond, InvertQCond, DL, TTI); 3461 return Changed; 3462 } 3463 3464 3465 /// If the previous block ended with a widenable branch, determine if reusing 3466 /// the target block is profitable and legal. This will have the effect of 3467 /// "widening" PBI, but doesn't require us to reason about hosting safety. 3468 static bool tryWidenCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI) { 3469 // TODO: This can be generalized in two important ways: 3470 // 1) We can allow phi nodes in IfFalseBB and simply reuse all the input 3471 // values from the PBI edge. 3472 // 2) We can sink side effecting instructions into BI's fallthrough 3473 // successor provided they doesn't contribute to computation of 3474 // BI's condition. 3475 Value *CondWB, *WC; 3476 BasicBlock *IfTrueBB, *IfFalseBB; 3477 if (!parseWidenableBranch(PBI, CondWB, WC, IfTrueBB, IfFalseBB) || 3478 IfTrueBB != BI->getParent() || !BI->getParent()->getSinglePredecessor()) 3479 return false; 3480 if (!IfFalseBB->phis().empty()) 3481 return false; // TODO 3482 // Use lambda to lazily compute expensive condition after cheap ones. 3483 auto NoSideEffects = [](BasicBlock &BB) { 3484 return !llvm::any_of(BB, [](const Instruction &I) { 3485 return I.mayWriteToMemory() || I.mayHaveSideEffects(); 3486 }); 3487 }; 3488 if (BI->getSuccessor(1) != IfFalseBB && // no inf looping 3489 BI->getSuccessor(1)->getTerminatingDeoptimizeCall() && // profitability 3490 NoSideEffects(*BI->getParent())) { 3491 BI->getSuccessor(1)->removePredecessor(BI->getParent()); 3492 BI->setSuccessor(1, IfFalseBB); 3493 return true; 3494 } 3495 if (BI->getSuccessor(0) != IfFalseBB && // no inf looping 3496 BI->getSuccessor(0)->getTerminatingDeoptimizeCall() && // profitability 3497 NoSideEffects(*BI->getParent())) { 3498 BI->getSuccessor(0)->removePredecessor(BI->getParent()); 3499 BI->setSuccessor(0, IfFalseBB); 3500 return true; 3501 } 3502 return false; 3503 } 3504 3505 /// If we have a conditional branch as a predecessor of another block, 3506 /// this function tries to simplify it. We know 3507 /// that PBI and BI are both conditional branches, and BI is in one of the 3508 /// successor blocks of PBI - PBI branches to BI. 3509 static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI, 3510 const DataLayout &DL, 3511 const TargetTransformInfo &TTI) { 3512 assert(PBI->isConditional() && BI->isConditional()); 3513 BasicBlock *BB = BI->getParent(); 3514 3515 // If this block ends with a branch instruction, and if there is a 3516 // predecessor that ends on a branch of the same condition, make 3517 // this conditional branch redundant. 3518 if (PBI->getCondition() == BI->getCondition() && 3519 PBI->getSuccessor(0) != PBI->getSuccessor(1)) { 3520 // Okay, the outcome of this conditional branch is statically 3521 // knowable. If this block had a single pred, handle specially. 3522 if (BB->getSinglePredecessor()) { 3523 // Turn this into a branch on constant. 3524 bool CondIsTrue = PBI->getSuccessor(0) == BB; 3525 BI->setCondition( 3526 ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue)); 3527 return true; // Nuke the branch on constant. 3528 } 3529 3530 // Otherwise, if there are multiple predecessors, insert a PHI that merges 3531 // in the constant and simplify the block result. Subsequent passes of 3532 // simplifycfg will thread the block. 3533 if (BlockIsSimpleEnoughToThreadThrough(BB)) { 3534 pred_iterator PB = pred_begin(BB), PE = pred_end(BB); 3535 PHINode *NewPN = PHINode::Create( 3536 Type::getInt1Ty(BB->getContext()), std::distance(PB, PE), 3537 BI->getCondition()->getName() + ".pr", &BB->front()); 3538 // Okay, we're going to insert the PHI node. Since PBI is not the only 3539 // predecessor, compute the PHI'd conditional value for all of the preds. 3540 // Any predecessor where the condition is not computable we keep symbolic. 3541 for (pred_iterator PI = PB; PI != PE; ++PI) { 3542 BasicBlock *P = *PI; 3543 if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) && PBI != BI && 3544 PBI->isConditional() && PBI->getCondition() == BI->getCondition() && 3545 PBI->getSuccessor(0) != PBI->getSuccessor(1)) { 3546 bool CondIsTrue = PBI->getSuccessor(0) == BB; 3547 NewPN->addIncoming( 3548 ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue), 3549 P); 3550 } else { 3551 NewPN->addIncoming(BI->getCondition(), P); 3552 } 3553 } 3554 3555 BI->setCondition(NewPN); 3556 return true; 3557 } 3558 } 3559 3560 // If the previous block ended with a widenable branch, determine if reusing 3561 // the target block is profitable and legal. This will have the effect of 3562 // "widening" PBI, but doesn't require us to reason about hosting safety. 3563 if (tryWidenCondBranchToCondBranch(PBI, BI)) 3564 return true; 3565 3566 if (auto *CE = dyn_cast<ConstantExpr>(BI->getCondition())) 3567 if (CE->canTrap()) 3568 return false; 3569 3570 // If both branches are conditional and both contain stores to the same 3571 // address, remove the stores from the conditionals and create a conditional 3572 // merged store at the end. 3573 if (MergeCondStores && mergeConditionalStores(PBI, BI, DL, TTI)) 3574 return true; 3575 3576 // If this is a conditional branch in an empty block, and if any 3577 // predecessors are a conditional branch to one of our destinations, 3578 // fold the conditions into logical ops and one cond br. 3579 3580 // Ignore dbg intrinsics. 3581 if (&*BB->instructionsWithoutDebug().begin() != BI) 3582 return false; 3583 3584 int PBIOp, BIOp; 3585 if (PBI->getSuccessor(0) == BI->getSuccessor(0)) { 3586 PBIOp = 0; 3587 BIOp = 0; 3588 } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) { 3589 PBIOp = 0; 3590 BIOp = 1; 3591 } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) { 3592 PBIOp = 1; 3593 BIOp = 0; 3594 } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) { 3595 PBIOp = 1; 3596 BIOp = 1; 3597 } else { 3598 return false; 3599 } 3600 3601 // Check to make sure that the other destination of this branch 3602 // isn't BB itself. If so, this is an infinite loop that will 3603 // keep getting unwound. 3604 if (PBI->getSuccessor(PBIOp) == BB) 3605 return false; 3606 3607 // Do not perform this transformation if it would require 3608 // insertion of a large number of select instructions. For targets 3609 // without predication/cmovs, this is a big pessimization. 3610 3611 // Also do not perform this transformation if any phi node in the common 3612 // destination block can trap when reached by BB or PBB (PR17073). In that 3613 // case, it would be unsafe to hoist the operation into a select instruction. 3614 3615 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp); 3616 unsigned NumPhis = 0; 3617 for (BasicBlock::iterator II = CommonDest->begin(); isa<PHINode>(II); 3618 ++II, ++NumPhis) { 3619 if (NumPhis > 2) // Disable this xform. 3620 return false; 3621 3622 PHINode *PN = cast<PHINode>(II); 3623 Value *BIV = PN->getIncomingValueForBlock(BB); 3624 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV)) 3625 if (CE->canTrap()) 3626 return false; 3627 3628 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent()); 3629 Value *PBIV = PN->getIncomingValue(PBBIdx); 3630 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV)) 3631 if (CE->canTrap()) 3632 return false; 3633 } 3634 3635 // Finally, if everything is ok, fold the branches to logical ops. 3636 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1); 3637 3638 LLVM_DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent() 3639 << "AND: " << *BI->getParent()); 3640 3641 // If OtherDest *is* BB, then BB is a basic block with a single conditional 3642 // branch in it, where one edge (OtherDest) goes back to itself but the other 3643 // exits. We don't *know* that the program avoids the infinite loop 3644 // (even though that seems likely). If we do this xform naively, we'll end up 3645 // recursively unpeeling the loop. Since we know that (after the xform is 3646 // done) that the block *is* infinite if reached, we just make it an obviously 3647 // infinite loop with no cond branch. 3648 if (OtherDest == BB) { 3649 // Insert it at the end of the function, because it's either code, 3650 // or it won't matter if it's hot. :) 3651 BasicBlock *InfLoopBlock = 3652 BasicBlock::Create(BB->getContext(), "infloop", BB->getParent()); 3653 BranchInst::Create(InfLoopBlock, InfLoopBlock); 3654 OtherDest = InfLoopBlock; 3655 } 3656 3657 LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent()); 3658 3659 // BI may have other predecessors. Because of this, we leave 3660 // it alone, but modify PBI. 3661 3662 // Make sure we get to CommonDest on True&True directions. 3663 Value *PBICond = PBI->getCondition(); 3664 IRBuilder<NoFolder> Builder(PBI); 3665 if (PBIOp) 3666 PBICond = Builder.CreateNot(PBICond, PBICond->getName() + ".not"); 3667 3668 Value *BICond = BI->getCondition(); 3669 if (BIOp) 3670 BICond = Builder.CreateNot(BICond, BICond->getName() + ".not"); 3671 3672 // Merge the conditions. 3673 Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge"); 3674 3675 // Modify PBI to branch on the new condition to the new dests. 3676 PBI->setCondition(Cond); 3677 PBI->setSuccessor(0, CommonDest); 3678 PBI->setSuccessor(1, OtherDest); 3679 3680 // Update branch weight for PBI. 3681 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight; 3682 uint64_t PredCommon, PredOther, SuccCommon, SuccOther; 3683 bool HasWeights = 3684 extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight, 3685 SuccTrueWeight, SuccFalseWeight); 3686 if (HasWeights) { 3687 PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight; 3688 PredOther = PBIOp ? PredTrueWeight : PredFalseWeight; 3689 SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight; 3690 SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight; 3691 // The weight to CommonDest should be PredCommon * SuccTotal + 3692 // PredOther * SuccCommon. 3693 // The weight to OtherDest should be PredOther * SuccOther. 3694 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) + 3695 PredOther * SuccCommon, 3696 PredOther * SuccOther}; 3697 // Halve the weights if any of them cannot fit in an uint32_t 3698 FitWeights(NewWeights); 3699 3700 setBranchWeights(PBI, NewWeights[0], NewWeights[1]); 3701 } 3702 3703 // OtherDest may have phi nodes. If so, add an entry from PBI's 3704 // block that are identical to the entries for BI's block. 3705 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB); 3706 3707 // We know that the CommonDest already had an edge from PBI to 3708 // it. If it has PHIs though, the PHIs may have different 3709 // entries for BB and PBI's BB. If so, insert a select to make 3710 // them agree. 3711 for (PHINode &PN : CommonDest->phis()) { 3712 Value *BIV = PN.getIncomingValueForBlock(BB); 3713 unsigned PBBIdx = PN.getBasicBlockIndex(PBI->getParent()); 3714 Value *PBIV = PN.getIncomingValue(PBBIdx); 3715 if (BIV != PBIV) { 3716 // Insert a select in PBI to pick the right value. 3717 SelectInst *NV = cast<SelectInst>( 3718 Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName() + ".mux")); 3719 PN.setIncomingValue(PBBIdx, NV); 3720 // Although the select has the same condition as PBI, the original branch 3721 // weights for PBI do not apply to the new select because the select's 3722 // 'logical' edges are incoming edges of the phi that is eliminated, not 3723 // the outgoing edges of PBI. 3724 if (HasWeights) { 3725 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight; 3726 uint64_t PredOther = PBIOp ? PredTrueWeight : PredFalseWeight; 3727 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight; 3728 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight; 3729 // The weight to PredCommonDest should be PredCommon * SuccTotal. 3730 // The weight to PredOtherDest should be PredOther * SuccCommon. 3731 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther), 3732 PredOther * SuccCommon}; 3733 3734 FitWeights(NewWeights); 3735 3736 setBranchWeights(NV, NewWeights[0], NewWeights[1]); 3737 } 3738 } 3739 } 3740 3741 LLVM_DEBUG(dbgs() << "INTO: " << *PBI->getParent()); 3742 LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent()); 3743 3744 // This basic block is probably dead. We know it has at least 3745 // one fewer predecessor. 3746 return true; 3747 } 3748 3749 // Simplifies a terminator by replacing it with a branch to TrueBB if Cond is 3750 // true or to FalseBB if Cond is false. 3751 // Takes care of updating the successors and removing the old terminator. 3752 // Also makes sure not to introduce new successors by assuming that edges to 3753 // non-successor TrueBBs and FalseBBs aren't reachable. 3754 bool SimplifyCFGOpt::SimplifyTerminatorOnSelect(Instruction *OldTerm, 3755 Value *Cond, BasicBlock *TrueBB, 3756 BasicBlock *FalseBB, 3757 uint32_t TrueWeight, 3758 uint32_t FalseWeight) { 3759 // Remove any superfluous successor edges from the CFG. 3760 // First, figure out which successors to preserve. 3761 // If TrueBB and FalseBB are equal, only try to preserve one copy of that 3762 // successor. 3763 BasicBlock *KeepEdge1 = TrueBB; 3764 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr; 3765 3766 // Then remove the rest. 3767 for (BasicBlock *Succ : successors(OldTerm)) { 3768 // Make sure only to keep exactly one copy of each edge. 3769 if (Succ == KeepEdge1) 3770 KeepEdge1 = nullptr; 3771 else if (Succ == KeepEdge2) 3772 KeepEdge2 = nullptr; 3773 else 3774 Succ->removePredecessor(OldTerm->getParent(), 3775 /*KeepOneInputPHIs=*/true); 3776 } 3777 3778 IRBuilder<> Builder(OldTerm); 3779 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc()); 3780 3781 // Insert an appropriate new terminator. 3782 if (!KeepEdge1 && !KeepEdge2) { 3783 if (TrueBB == FalseBB) 3784 // We were only looking for one successor, and it was present. 3785 // Create an unconditional branch to it. 3786 Builder.CreateBr(TrueBB); 3787 else { 3788 // We found both of the successors we were looking for. 3789 // Create a conditional branch sharing the condition of the select. 3790 BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB); 3791 if (TrueWeight != FalseWeight) 3792 setBranchWeights(NewBI, TrueWeight, FalseWeight); 3793 } 3794 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) { 3795 // Neither of the selected blocks were successors, so this 3796 // terminator must be unreachable. 3797 new UnreachableInst(OldTerm->getContext(), OldTerm); 3798 } else { 3799 // One of the selected values was a successor, but the other wasn't. 3800 // Insert an unconditional branch to the one that was found; 3801 // the edge to the one that wasn't must be unreachable. 3802 if (!KeepEdge1) 3803 // Only TrueBB was found. 3804 Builder.CreateBr(TrueBB); 3805 else 3806 // Only FalseBB was found. 3807 Builder.CreateBr(FalseBB); 3808 } 3809 3810 EraseTerminatorAndDCECond(OldTerm); 3811 return true; 3812 } 3813 3814 // Replaces 3815 // (switch (select cond, X, Y)) on constant X, Y 3816 // with a branch - conditional if X and Y lead to distinct BBs, 3817 // unconditional otherwise. 3818 bool SimplifyCFGOpt::SimplifySwitchOnSelect(SwitchInst *SI, 3819 SelectInst *Select) { 3820 // Check for constant integer values in the select. 3821 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue()); 3822 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue()); 3823 if (!TrueVal || !FalseVal) 3824 return false; 3825 3826 // Find the relevant condition and destinations. 3827 Value *Condition = Select->getCondition(); 3828 BasicBlock *TrueBB = SI->findCaseValue(TrueVal)->getCaseSuccessor(); 3829 BasicBlock *FalseBB = SI->findCaseValue(FalseVal)->getCaseSuccessor(); 3830 3831 // Get weight for TrueBB and FalseBB. 3832 uint32_t TrueWeight = 0, FalseWeight = 0; 3833 SmallVector<uint64_t, 8> Weights; 3834 bool HasWeights = HasBranchWeights(SI); 3835 if (HasWeights) { 3836 GetBranchWeights(SI, Weights); 3837 if (Weights.size() == 1 + SI->getNumCases()) { 3838 TrueWeight = 3839 (uint32_t)Weights[SI->findCaseValue(TrueVal)->getSuccessorIndex()]; 3840 FalseWeight = 3841 (uint32_t)Weights[SI->findCaseValue(FalseVal)->getSuccessorIndex()]; 3842 } 3843 } 3844 3845 // Perform the actual simplification. 3846 return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB, TrueWeight, 3847 FalseWeight); 3848 } 3849 3850 // Replaces 3851 // (indirectbr (select cond, blockaddress(@fn, BlockA), 3852 // blockaddress(@fn, BlockB))) 3853 // with 3854 // (br cond, BlockA, BlockB). 3855 bool SimplifyCFGOpt::SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, 3856 SelectInst *SI) { 3857 // Check that both operands of the select are block addresses. 3858 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue()); 3859 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue()); 3860 if (!TBA || !FBA) 3861 return false; 3862 3863 // Extract the actual blocks. 3864 BasicBlock *TrueBB = TBA->getBasicBlock(); 3865 BasicBlock *FalseBB = FBA->getBasicBlock(); 3866 3867 // Perform the actual simplification. 3868 return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB, 0, 3869 0); 3870 } 3871 3872 /// This is called when we find an icmp instruction 3873 /// (a seteq/setne with a constant) as the only instruction in a 3874 /// block that ends with an uncond branch. We are looking for a very specific 3875 /// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In 3876 /// this case, we merge the first two "or's of icmp" into a switch, but then the 3877 /// default value goes to an uncond block with a seteq in it, we get something 3878 /// like: 3879 /// 3880 /// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ] 3881 /// DEFAULT: 3882 /// %tmp = icmp eq i8 %A, 92 3883 /// br label %end 3884 /// end: 3885 /// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ] 3886 /// 3887 /// We prefer to split the edge to 'end' so that there is a true/false entry to 3888 /// the PHI, merging the third icmp into the switch. 3889 bool SimplifyCFGOpt::tryToSimplifyUncondBranchWithICmpInIt( 3890 ICmpInst *ICI, IRBuilder<> &Builder) { 3891 BasicBlock *BB = ICI->getParent(); 3892 3893 // If the block has any PHIs in it or the icmp has multiple uses, it is too 3894 // complex. 3895 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) 3896 return false; 3897 3898 Value *V = ICI->getOperand(0); 3899 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1)); 3900 3901 // The pattern we're looking for is where our only predecessor is a switch on 3902 // 'V' and this block is the default case for the switch. In this case we can 3903 // fold the compared value into the switch to simplify things. 3904 BasicBlock *Pred = BB->getSinglePredecessor(); 3905 if (!Pred || !isa<SwitchInst>(Pred->getTerminator())) 3906 return false; 3907 3908 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator()); 3909 if (SI->getCondition() != V) 3910 return false; 3911 3912 // If BB is reachable on a non-default case, then we simply know the value of 3913 // V in this block. Substitute it and constant fold the icmp instruction 3914 // away. 3915 if (SI->getDefaultDest() != BB) { 3916 ConstantInt *VVal = SI->findCaseDest(BB); 3917 assert(VVal && "Should have a unique destination value"); 3918 ICI->setOperand(0, VVal); 3919 3920 if (Value *V = SimplifyInstruction(ICI, {DL, ICI})) { 3921 ICI->replaceAllUsesWith(V); 3922 ICI->eraseFromParent(); 3923 } 3924 // BB is now empty, so it is likely to simplify away. 3925 return requestResimplify(); 3926 } 3927 3928 // Ok, the block is reachable from the default dest. If the constant we're 3929 // comparing exists in one of the other edges, then we can constant fold ICI 3930 // and zap it. 3931 if (SI->findCaseValue(Cst) != SI->case_default()) { 3932 Value *V; 3933 if (ICI->getPredicate() == ICmpInst::ICMP_EQ) 3934 V = ConstantInt::getFalse(BB->getContext()); 3935 else 3936 V = ConstantInt::getTrue(BB->getContext()); 3937 3938 ICI->replaceAllUsesWith(V); 3939 ICI->eraseFromParent(); 3940 // BB is now empty, so it is likely to simplify away. 3941 return requestResimplify(); 3942 } 3943 3944 // The use of the icmp has to be in the 'end' block, by the only PHI node in 3945 // the block. 3946 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0); 3947 PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back()); 3948 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() || 3949 isa<PHINode>(++BasicBlock::iterator(PHIUse))) 3950 return false; 3951 3952 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets 3953 // true in the PHI. 3954 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext()); 3955 Constant *NewCst = ConstantInt::getFalse(BB->getContext()); 3956 3957 if (ICI->getPredicate() == ICmpInst::ICMP_EQ) 3958 std::swap(DefaultCst, NewCst); 3959 3960 // Replace ICI (which is used by the PHI for the default value) with true or 3961 // false depending on if it is EQ or NE. 3962 ICI->replaceAllUsesWith(DefaultCst); 3963 ICI->eraseFromParent(); 3964 3965 // Okay, the switch goes to this block on a default value. Add an edge from 3966 // the switch to the merge point on the compared value. 3967 BasicBlock *NewBB = 3968 BasicBlock::Create(BB->getContext(), "switch.edge", BB->getParent(), BB); 3969 { 3970 SwitchInstProfUpdateWrapper SIW(*SI); 3971 auto W0 = SIW.getSuccessorWeight(0); 3972 SwitchInstProfUpdateWrapper::CaseWeightOpt NewW; 3973 if (W0) { 3974 NewW = ((uint64_t(*W0) + 1) >> 1); 3975 SIW.setSuccessorWeight(0, *NewW); 3976 } 3977 SIW.addCase(Cst, NewBB, NewW); 3978 } 3979 3980 // NewBB branches to the phi block, add the uncond branch and the phi entry. 3981 Builder.SetInsertPoint(NewBB); 3982 Builder.SetCurrentDebugLocation(SI->getDebugLoc()); 3983 Builder.CreateBr(SuccBlock); 3984 PHIUse->addIncoming(NewCst, NewBB); 3985 return true; 3986 } 3987 3988 /// The specified branch is a conditional branch. 3989 /// Check to see if it is branching on an or/and chain of icmp instructions, and 3990 /// fold it into a switch instruction if so. 3991 bool SimplifyCFGOpt::SimplifyBranchOnICmpChain(BranchInst *BI, 3992 IRBuilder<> &Builder, 3993 const DataLayout &DL) { 3994 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition()); 3995 if (!Cond) 3996 return false; 3997 3998 // Change br (X == 0 | X == 1), T, F into a switch instruction. 3999 // If this is a bunch of seteq's or'd together, or if it's a bunch of 4000 // 'setne's and'ed together, collect them. 4001 4002 // Try to gather values from a chain of and/or to be turned into a switch 4003 ConstantComparesGatherer ConstantCompare(Cond, DL); 4004 // Unpack the result 4005 SmallVectorImpl<ConstantInt *> &Values = ConstantCompare.Vals; 4006 Value *CompVal = ConstantCompare.CompValue; 4007 unsigned UsedICmps = ConstantCompare.UsedICmps; 4008 Value *ExtraCase = ConstantCompare.Extra; 4009 4010 // If we didn't have a multiply compared value, fail. 4011 if (!CompVal) 4012 return false; 4013 4014 // Avoid turning single icmps into a switch. 4015 if (UsedICmps <= 1) 4016 return false; 4017 4018 bool TrueWhenEqual = (Cond->getOpcode() == Instruction::Or); 4019 4020 // There might be duplicate constants in the list, which the switch 4021 // instruction can't handle, remove them now. 4022 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate); 4023 Values.erase(std::unique(Values.begin(), Values.end()), Values.end()); 4024 4025 // If Extra was used, we require at least two switch values to do the 4026 // transformation. A switch with one value is just a conditional branch. 4027 if (ExtraCase && Values.size() < 2) 4028 return false; 4029 4030 // TODO: Preserve branch weight metadata, similarly to how 4031 // FoldValueComparisonIntoPredecessors preserves it. 4032 4033 // Figure out which block is which destination. 4034 BasicBlock *DefaultBB = BI->getSuccessor(1); 4035 BasicBlock *EdgeBB = BI->getSuccessor(0); 4036 if (!TrueWhenEqual) 4037 std::swap(DefaultBB, EdgeBB); 4038 4039 BasicBlock *BB = BI->getParent(); 4040 4041 // MSAN does not like undefs as branch condition which can be introduced 4042 // with "explicit branch". 4043 if (ExtraCase && BB->getParent()->hasFnAttribute(Attribute::SanitizeMemory)) 4044 return false; 4045 4046 LLVM_DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size() 4047 << " cases into SWITCH. BB is:\n" 4048 << *BB); 4049 4050 // If there are any extra values that couldn't be folded into the switch 4051 // then we evaluate them with an explicit branch first. Split the block 4052 // right before the condbr to handle it. 4053 if (ExtraCase) { 4054 BasicBlock *NewBB = 4055 BB->splitBasicBlock(BI->getIterator(), "switch.early.test"); 4056 // Remove the uncond branch added to the old block. 4057 Instruction *OldTI = BB->getTerminator(); 4058 Builder.SetInsertPoint(OldTI); 4059 4060 if (TrueWhenEqual) 4061 Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB); 4062 else 4063 Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB); 4064 4065 OldTI->eraseFromParent(); 4066 4067 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them 4068 // for the edge we just added. 4069 AddPredecessorToBlock(EdgeBB, BB, NewBB); 4070 4071 LLVM_DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase 4072 << "\nEXTRABB = " << *BB); 4073 BB = NewBB; 4074 } 4075 4076 Builder.SetInsertPoint(BI); 4077 // Convert pointer to int before we switch. 4078 if (CompVal->getType()->isPointerTy()) { 4079 CompVal = Builder.CreatePtrToInt( 4080 CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr"); 4081 } 4082 4083 // Create the new switch instruction now. 4084 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size()); 4085 4086 // Add all of the 'cases' to the switch instruction. 4087 for (unsigned i = 0, e = Values.size(); i != e; ++i) 4088 New->addCase(Values[i], EdgeBB); 4089 4090 // We added edges from PI to the EdgeBB. As such, if there were any 4091 // PHI nodes in EdgeBB, they need entries to be added corresponding to 4092 // the number of edges added. 4093 for (BasicBlock::iterator BBI = EdgeBB->begin(); isa<PHINode>(BBI); ++BBI) { 4094 PHINode *PN = cast<PHINode>(BBI); 4095 Value *InVal = PN->getIncomingValueForBlock(BB); 4096 for (unsigned i = 0, e = Values.size() - 1; i != e; ++i) 4097 PN->addIncoming(InVal, BB); 4098 } 4099 4100 // Erase the old branch instruction. 4101 EraseTerminatorAndDCECond(BI); 4102 4103 LLVM_DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n'); 4104 return true; 4105 } 4106 4107 bool SimplifyCFGOpt::simplifyResume(ResumeInst *RI, IRBuilder<> &Builder) { 4108 if (isa<PHINode>(RI->getValue())) 4109 return simplifyCommonResume(RI); 4110 else if (isa<LandingPadInst>(RI->getParent()->getFirstNonPHI()) && 4111 RI->getValue() == RI->getParent()->getFirstNonPHI()) 4112 // The resume must unwind the exception that caused control to branch here. 4113 return simplifySingleResume(RI); 4114 4115 return false; 4116 } 4117 4118 // Check if cleanup block is empty 4119 static bool isCleanupBlockEmpty(iterator_range<BasicBlock::iterator> R) { 4120 for (Instruction &I : R) { 4121 auto *II = dyn_cast<IntrinsicInst>(&I); 4122 if (!II) 4123 return false; 4124 4125 Intrinsic::ID IntrinsicID = II->getIntrinsicID(); 4126 switch (IntrinsicID) { 4127 case Intrinsic::dbg_declare: 4128 case Intrinsic::dbg_value: 4129 case Intrinsic::dbg_label: 4130 case Intrinsic::lifetime_end: 4131 break; 4132 default: 4133 return false; 4134 } 4135 } 4136 return true; 4137 } 4138 4139 // Simplify resume that is shared by several landing pads (phi of landing pad). 4140 bool SimplifyCFGOpt::simplifyCommonResume(ResumeInst *RI) { 4141 BasicBlock *BB = RI->getParent(); 4142 4143 // Check that there are no other instructions except for debug and lifetime 4144 // intrinsics between the phi's and resume instruction. 4145 if (!isCleanupBlockEmpty( 4146 make_range(RI->getParent()->getFirstNonPHI(), BB->getTerminator()))) 4147 return false; 4148 4149 SmallSetVector<BasicBlock *, 4> TrivialUnwindBlocks; 4150 auto *PhiLPInst = cast<PHINode>(RI->getValue()); 4151 4152 // Check incoming blocks to see if any of them are trivial. 4153 for (unsigned Idx = 0, End = PhiLPInst->getNumIncomingValues(); Idx != End; 4154 Idx++) { 4155 auto *IncomingBB = PhiLPInst->getIncomingBlock(Idx); 4156 auto *IncomingValue = PhiLPInst->getIncomingValue(Idx); 4157 4158 // If the block has other successors, we can not delete it because 4159 // it has other dependents. 4160 if (IncomingBB->getUniqueSuccessor() != BB) 4161 continue; 4162 4163 auto *LandingPad = dyn_cast<LandingPadInst>(IncomingBB->getFirstNonPHI()); 4164 // Not the landing pad that caused the control to branch here. 4165 if (IncomingValue != LandingPad) 4166 continue; 4167 4168 if (isCleanupBlockEmpty( 4169 make_range(LandingPad->getNextNode(), IncomingBB->getTerminator()))) 4170 TrivialUnwindBlocks.insert(IncomingBB); 4171 } 4172 4173 // If no trivial unwind blocks, don't do any simplifications. 4174 if (TrivialUnwindBlocks.empty()) 4175 return false; 4176 4177 // Turn all invokes that unwind here into calls. 4178 for (auto *TrivialBB : TrivialUnwindBlocks) { 4179 // Blocks that will be simplified should be removed from the phi node. 4180 // Note there could be multiple edges to the resume block, and we need 4181 // to remove them all. 4182 while (PhiLPInst->getBasicBlockIndex(TrivialBB) != -1) 4183 BB->removePredecessor(TrivialBB, true); 4184 4185 for (pred_iterator PI = pred_begin(TrivialBB), PE = pred_end(TrivialBB); 4186 PI != PE;) { 4187 BasicBlock *Pred = *PI++; 4188 removeUnwindEdge(Pred, DTU); 4189 ++NumInvokes; 4190 } 4191 4192 // In each SimplifyCFG run, only the current processed block can be erased. 4193 // Otherwise, it will break the iteration of SimplifyCFG pass. So instead 4194 // of erasing TrivialBB, we only remove the branch to the common resume 4195 // block so that we can later erase the resume block since it has no 4196 // predecessors. 4197 TrivialBB->getTerminator()->eraseFromParent(); 4198 new UnreachableInst(RI->getContext(), TrivialBB); 4199 if (DTU) 4200 DTU->applyUpdatesPermissive({{DominatorTree::Delete, TrivialBB, BB}}); 4201 } 4202 4203 // Delete the resume block if all its predecessors have been removed. 4204 if (pred_empty(BB)) { 4205 if (DTU) 4206 DTU->deleteBB(BB); 4207 else 4208 BB->eraseFromParent(); 4209 } 4210 4211 return !TrivialUnwindBlocks.empty(); 4212 } 4213 4214 // Simplify resume that is only used by a single (non-phi) landing pad. 4215 bool SimplifyCFGOpt::simplifySingleResume(ResumeInst *RI) { 4216 BasicBlock *BB = RI->getParent(); 4217 auto *LPInst = cast<LandingPadInst>(BB->getFirstNonPHI()); 4218 assert(RI->getValue() == LPInst && 4219 "Resume must unwind the exception that caused control to here"); 4220 4221 // Check that there are no other instructions except for debug intrinsics. 4222 if (!isCleanupBlockEmpty( 4223 make_range<Instruction *>(LPInst->getNextNode(), RI))) 4224 return false; 4225 4226 // Turn all invokes that unwind here into calls and delete the basic block. 4227 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) { 4228 BasicBlock *Pred = *PI++; 4229 removeUnwindEdge(Pred, DTU); 4230 ++NumInvokes; 4231 } 4232 4233 // The landingpad is now unreachable. Zap it. 4234 if (LoopHeaders) 4235 LoopHeaders->erase(BB); 4236 if (DTU) 4237 DTU->deleteBB(BB); 4238 else 4239 BB->eraseFromParent(); 4240 return true; 4241 } 4242 4243 static bool removeEmptyCleanup(CleanupReturnInst *RI, DomTreeUpdater *DTU) { 4244 // If this is a trivial cleanup pad that executes no instructions, it can be 4245 // eliminated. If the cleanup pad continues to the caller, any predecessor 4246 // that is an EH pad will be updated to continue to the caller and any 4247 // predecessor that terminates with an invoke instruction will have its invoke 4248 // instruction converted to a call instruction. If the cleanup pad being 4249 // simplified does not continue to the caller, each predecessor will be 4250 // updated to continue to the unwind destination of the cleanup pad being 4251 // simplified. 4252 BasicBlock *BB = RI->getParent(); 4253 CleanupPadInst *CPInst = RI->getCleanupPad(); 4254 if (CPInst->getParent() != BB) 4255 // This isn't an empty cleanup. 4256 return false; 4257 4258 // We cannot kill the pad if it has multiple uses. This typically arises 4259 // from unreachable basic blocks. 4260 if (!CPInst->hasOneUse()) 4261 return false; 4262 4263 // Check that there are no other instructions except for benign intrinsics. 4264 if (!isCleanupBlockEmpty( 4265 make_range<Instruction *>(CPInst->getNextNode(), RI))) 4266 return false; 4267 4268 // If the cleanup return we are simplifying unwinds to the caller, this will 4269 // set UnwindDest to nullptr. 4270 BasicBlock *UnwindDest = RI->getUnwindDest(); 4271 Instruction *DestEHPad = UnwindDest ? UnwindDest->getFirstNonPHI() : nullptr; 4272 4273 // We're about to remove BB from the control flow. Before we do, sink any 4274 // PHINodes into the unwind destination. Doing this before changing the 4275 // control flow avoids some potentially slow checks, since we can currently 4276 // be certain that UnwindDest and BB have no common predecessors (since they 4277 // are both EH pads). 4278 if (UnwindDest) { 4279 // First, go through the PHI nodes in UnwindDest and update any nodes that 4280 // reference the block we are removing 4281 for (BasicBlock::iterator I = UnwindDest->begin(), 4282 IE = DestEHPad->getIterator(); 4283 I != IE; ++I) { 4284 PHINode *DestPN = cast<PHINode>(I); 4285 4286 int Idx = DestPN->getBasicBlockIndex(BB); 4287 // Since BB unwinds to UnwindDest, it has to be in the PHI node. 4288 assert(Idx != -1); 4289 // This PHI node has an incoming value that corresponds to a control 4290 // path through the cleanup pad we are removing. If the incoming 4291 // value is in the cleanup pad, it must be a PHINode (because we 4292 // verified above that the block is otherwise empty). Otherwise, the 4293 // value is either a constant or a value that dominates the cleanup 4294 // pad being removed. 4295 // 4296 // Because BB and UnwindDest are both EH pads, all of their 4297 // predecessors must unwind to these blocks, and since no instruction 4298 // can have multiple unwind destinations, there will be no overlap in 4299 // incoming blocks between SrcPN and DestPN. 4300 Value *SrcVal = DestPN->getIncomingValue(Idx); 4301 PHINode *SrcPN = dyn_cast<PHINode>(SrcVal); 4302 4303 // Remove the entry for the block we are deleting. 4304 DestPN->removeIncomingValue(Idx, false); 4305 4306 if (SrcPN && SrcPN->getParent() == BB) { 4307 // If the incoming value was a PHI node in the cleanup pad we are 4308 // removing, we need to merge that PHI node's incoming values into 4309 // DestPN. 4310 for (unsigned SrcIdx = 0, SrcE = SrcPN->getNumIncomingValues(); 4311 SrcIdx != SrcE; ++SrcIdx) { 4312 DestPN->addIncoming(SrcPN->getIncomingValue(SrcIdx), 4313 SrcPN->getIncomingBlock(SrcIdx)); 4314 } 4315 } else { 4316 // Otherwise, the incoming value came from above BB and 4317 // so we can just reuse it. We must associate all of BB's 4318 // predecessors with this value. 4319 for (auto *pred : predecessors(BB)) { 4320 DestPN->addIncoming(SrcVal, pred); 4321 } 4322 } 4323 } 4324 4325 // Sink any remaining PHI nodes directly into UnwindDest. 4326 Instruction *InsertPt = DestEHPad; 4327 for (BasicBlock::iterator I = BB->begin(), 4328 IE = BB->getFirstNonPHI()->getIterator(); 4329 I != IE;) { 4330 // The iterator must be incremented here because the instructions are 4331 // being moved to another block. 4332 PHINode *PN = cast<PHINode>(I++); 4333 if (PN->use_empty() || !PN->isUsedOutsideOfBlock(BB)) 4334 // If the PHI node has no uses or all of its uses are in this basic 4335 // block (meaning they are debug or lifetime intrinsics), just leave 4336 // it. It will be erased when we erase BB below. 4337 continue; 4338 4339 // Otherwise, sink this PHI node into UnwindDest. 4340 // Any predecessors to UnwindDest which are not already represented 4341 // must be back edges which inherit the value from the path through 4342 // BB. In this case, the PHI value must reference itself. 4343 for (auto *pred : predecessors(UnwindDest)) 4344 if (pred != BB) 4345 PN->addIncoming(PN, pred); 4346 PN->moveBefore(InsertPt); 4347 } 4348 } 4349 4350 std::vector<DominatorTree::UpdateType> Updates; 4351 4352 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) { 4353 // The iterator must be updated here because we are removing this pred. 4354 BasicBlock *PredBB = *PI++; 4355 if (UnwindDest == nullptr) { 4356 if (DTU) 4357 DTU->applyUpdatesPermissive(Updates); 4358 Updates.clear(); 4359 removeUnwindEdge(PredBB, DTU); 4360 ++NumInvokes; 4361 } else { 4362 Instruction *TI = PredBB->getTerminator(); 4363 TI->replaceUsesOfWith(BB, UnwindDest); 4364 Updates.push_back({DominatorTree::Delete, PredBB, BB}); 4365 Updates.push_back({DominatorTree::Insert, PredBB, UnwindDest}); 4366 } 4367 } 4368 4369 if (DTU) { 4370 DTU->applyUpdatesPermissive(Updates); 4371 DTU->deleteBB(BB); 4372 } else 4373 // The cleanup pad is now unreachable. Zap it. 4374 BB->eraseFromParent(); 4375 4376 return true; 4377 } 4378 4379 // Try to merge two cleanuppads together. 4380 static bool mergeCleanupPad(CleanupReturnInst *RI) { 4381 // Skip any cleanuprets which unwind to caller, there is nothing to merge 4382 // with. 4383 BasicBlock *UnwindDest = RI->getUnwindDest(); 4384 if (!UnwindDest) 4385 return false; 4386 4387 // This cleanupret isn't the only predecessor of this cleanuppad, it wouldn't 4388 // be safe to merge without code duplication. 4389 if (UnwindDest->getSinglePredecessor() != RI->getParent()) 4390 return false; 4391 4392 // Verify that our cleanuppad's unwind destination is another cleanuppad. 4393 auto *SuccessorCleanupPad = dyn_cast<CleanupPadInst>(&UnwindDest->front()); 4394 if (!SuccessorCleanupPad) 4395 return false; 4396 4397 CleanupPadInst *PredecessorCleanupPad = RI->getCleanupPad(); 4398 // Replace any uses of the successor cleanupad with the predecessor pad 4399 // The only cleanuppad uses should be this cleanupret, it's cleanupret and 4400 // funclet bundle operands. 4401 SuccessorCleanupPad->replaceAllUsesWith(PredecessorCleanupPad); 4402 // Remove the old cleanuppad. 4403 SuccessorCleanupPad->eraseFromParent(); 4404 // Now, we simply replace the cleanupret with a branch to the unwind 4405 // destination. 4406 BranchInst::Create(UnwindDest, RI->getParent()); 4407 RI->eraseFromParent(); 4408 4409 return true; 4410 } 4411 4412 bool SimplifyCFGOpt::simplifyCleanupReturn(CleanupReturnInst *RI) { 4413 // It is possible to transiantly have an undef cleanuppad operand because we 4414 // have deleted some, but not all, dead blocks. 4415 // Eventually, this block will be deleted. 4416 if (isa<UndefValue>(RI->getOperand(0))) 4417 return false; 4418 4419 if (mergeCleanupPad(RI)) 4420 return true; 4421 4422 if (removeEmptyCleanup(RI, DTU)) 4423 return true; 4424 4425 return false; 4426 } 4427 4428 bool SimplifyCFGOpt::simplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) { 4429 BasicBlock *BB = RI->getParent(); 4430 if (!BB->getFirstNonPHIOrDbg()->isTerminator()) 4431 return false; 4432 4433 // Find predecessors that end with branches. 4434 SmallVector<BasicBlock *, 8> UncondBranchPreds; 4435 SmallVector<BranchInst *, 8> CondBranchPreds; 4436 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) { 4437 BasicBlock *P = *PI; 4438 Instruction *PTI = P->getTerminator(); 4439 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) { 4440 if (BI->isUnconditional()) 4441 UncondBranchPreds.push_back(P); 4442 else 4443 CondBranchPreds.push_back(BI); 4444 } 4445 } 4446 4447 // If we found some, do the transformation! 4448 if (!UncondBranchPreds.empty() && DupRet) { 4449 while (!UncondBranchPreds.empty()) { 4450 BasicBlock *Pred = UncondBranchPreds.pop_back_val(); 4451 LLVM_DEBUG(dbgs() << "FOLDING: " << *BB 4452 << "INTO UNCOND BRANCH PRED: " << *Pred); 4453 (void)FoldReturnIntoUncondBranch(RI, BB, Pred, DTU); 4454 } 4455 4456 // If we eliminated all predecessors of the block, delete the block now. 4457 if (pred_empty(BB)) { 4458 // We know there are no successors, so just nuke the block. 4459 if (LoopHeaders) 4460 LoopHeaders->erase(BB); 4461 if (DTU) 4462 DTU->deleteBB(BB); 4463 else 4464 BB->eraseFromParent(); 4465 } 4466 4467 return true; 4468 } 4469 4470 // Check out all of the conditional branches going to this return 4471 // instruction. If any of them just select between returns, change the 4472 // branch itself into a select/return pair. 4473 while (!CondBranchPreds.empty()) { 4474 BranchInst *BI = CondBranchPreds.pop_back_val(); 4475 4476 // Check to see if the non-BB successor is also a return block. 4477 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) && 4478 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) && 4479 SimplifyCondBranchToTwoReturns(BI, Builder)) 4480 return true; 4481 } 4482 return false; 4483 } 4484 4485 bool SimplifyCFGOpt::simplifyUnreachable(UnreachableInst *UI) { 4486 BasicBlock *BB = UI->getParent(); 4487 4488 bool Changed = false; 4489 4490 // If there are any instructions immediately before the unreachable that can 4491 // be removed, do so. 4492 while (UI->getIterator() != BB->begin()) { 4493 BasicBlock::iterator BBI = UI->getIterator(); 4494 --BBI; 4495 // Do not delete instructions that can have side effects which might cause 4496 // the unreachable to not be reachable; specifically, calls and volatile 4497 // operations may have this effect. 4498 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) 4499 break; 4500 4501 if (BBI->mayHaveSideEffects()) { 4502 if (auto *SI = dyn_cast<StoreInst>(BBI)) { 4503 if (SI->isVolatile()) 4504 break; 4505 } else if (auto *LI = dyn_cast<LoadInst>(BBI)) { 4506 if (LI->isVolatile()) 4507 break; 4508 } else if (auto *RMWI = dyn_cast<AtomicRMWInst>(BBI)) { 4509 if (RMWI->isVolatile()) 4510 break; 4511 } else if (auto *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) { 4512 if (CXI->isVolatile()) 4513 break; 4514 } else if (isa<CatchPadInst>(BBI)) { 4515 // A catchpad may invoke exception object constructors and such, which 4516 // in some languages can be arbitrary code, so be conservative by 4517 // default. 4518 // For CoreCLR, it just involves a type test, so can be removed. 4519 if (classifyEHPersonality(BB->getParent()->getPersonalityFn()) != 4520 EHPersonality::CoreCLR) 4521 break; 4522 } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) && 4523 !isa<LandingPadInst>(BBI)) { 4524 break; 4525 } 4526 // Note that deleting LandingPad's here is in fact okay, although it 4527 // involves a bit of subtle reasoning. If this inst is a LandingPad, 4528 // all the predecessors of this block will be the unwind edges of Invokes, 4529 // and we can therefore guarantee this block will be erased. 4530 } 4531 4532 // Delete this instruction (any uses are guaranteed to be dead) 4533 if (!BBI->use_empty()) 4534 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType())); 4535 BBI->eraseFromParent(); 4536 Changed = true; 4537 } 4538 4539 // If the unreachable instruction is the first in the block, take a gander 4540 // at all of the predecessors of this instruction, and simplify them. 4541 if (&BB->front() != UI) 4542 return Changed; 4543 4544 std::vector<DominatorTree::UpdateType> Updates; 4545 4546 SmallVector<BasicBlock *, 8> Preds(pred_begin(BB), pred_end(BB)); 4547 for (unsigned i = 0, e = Preds.size(); i != e; ++i) { 4548 auto *Predecessor = Preds[i]; 4549 Instruction *TI = Predecessor->getTerminator(); 4550 IRBuilder<> Builder(TI); 4551 if (auto *BI = dyn_cast<BranchInst>(TI)) { 4552 if (BI->isUnconditional()) { 4553 assert(BI->getSuccessor(0) == BB && "Incorrect CFG"); 4554 new UnreachableInst(TI->getContext(), TI); 4555 TI->eraseFromParent(); 4556 Changed = true; 4557 } else { 4558 Value* Cond = BI->getCondition(); 4559 assert(BI->getSuccessor(0) != BI->getSuccessor(1) && 4560 "Same-destination conditional branch instruction was " 4561 "already canonicalized into an unconditional branch."); 4562 if (BI->getSuccessor(0) == BB) { 4563 Builder.CreateAssumption(Builder.CreateNot(Cond)); 4564 Builder.CreateBr(BI->getSuccessor(1)); 4565 } else { 4566 assert(BI->getSuccessor(1) == BB && "Incorrect CFG"); 4567 Builder.CreateAssumption(Cond); 4568 Builder.CreateBr(BI->getSuccessor(0)); 4569 } 4570 EraseTerminatorAndDCECond(BI); 4571 Changed = true; 4572 } 4573 Updates.push_back({DominatorTree::Delete, Predecessor, BB}); 4574 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) { 4575 SwitchInstProfUpdateWrapper SU(*SI); 4576 for (auto i = SU->case_begin(), e = SU->case_end(); i != e;) { 4577 if (i->getCaseSuccessor() != BB) { 4578 ++i; 4579 continue; 4580 } 4581 BB->removePredecessor(SU->getParent()); 4582 i = SU.removeCase(i); 4583 e = SU->case_end(); 4584 Changed = true; 4585 } 4586 Updates.push_back({DominatorTree::Delete, Predecessor, BB}); 4587 } else if (auto *II = dyn_cast<InvokeInst>(TI)) { 4588 if (II->getUnwindDest() == BB) { 4589 if (DTU) 4590 DTU->applyUpdatesPermissive(Updates); 4591 Updates.clear(); 4592 removeUnwindEdge(TI->getParent(), DTU); 4593 Changed = true; 4594 } 4595 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) { 4596 if (CSI->getUnwindDest() == BB) { 4597 if (DTU) 4598 DTU->applyUpdatesPermissive(Updates); 4599 Updates.clear(); 4600 removeUnwindEdge(TI->getParent(), DTU); 4601 Changed = true; 4602 continue; 4603 } 4604 4605 for (CatchSwitchInst::handler_iterator I = CSI->handler_begin(), 4606 E = CSI->handler_end(); 4607 I != E; ++I) { 4608 if (*I == BB) { 4609 CSI->removeHandler(I); 4610 --I; 4611 --E; 4612 Changed = true; 4613 } 4614 } 4615 Updates.push_back({DominatorTree::Delete, Predecessor, BB}); 4616 if (CSI->getNumHandlers() == 0) { 4617 if (CSI->hasUnwindDest()) { 4618 // Redirect all predecessors of the block containing CatchSwitchInst 4619 // to instead branch to the CatchSwitchInst's unwind destination. 4620 for (auto *PredecessorOfPredecessor : predecessors(Predecessor)) { 4621 Updates.push_back( 4622 {DominatorTree::Delete, PredecessorOfPredecessor, Predecessor}); 4623 Updates.push_back({DominatorTree::Insert, PredecessorOfPredecessor, 4624 CSI->getUnwindDest()}); 4625 } 4626 Predecessor->replaceAllUsesWith(CSI->getUnwindDest()); 4627 } else { 4628 // Rewrite all preds to unwind to caller (or from invoke to call). 4629 if (DTU) 4630 DTU->applyUpdatesPermissive(Updates); 4631 Updates.clear(); 4632 SmallVector<BasicBlock *, 8> EHPreds(predecessors(Predecessor)); 4633 for (BasicBlock *EHPred : EHPreds) 4634 removeUnwindEdge(EHPred, DTU); 4635 } 4636 // The catchswitch is no longer reachable. 4637 new UnreachableInst(CSI->getContext(), CSI); 4638 CSI->eraseFromParent(); 4639 Changed = true; 4640 } 4641 } else if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) { 4642 (void)CRI; 4643 assert(CRI->hasUnwindDest() && CRI->getUnwindDest() == BB && 4644 "Expected to always have an unwind to BB."); 4645 Updates.push_back({DominatorTree::Delete, Predecessor, BB}); 4646 new UnreachableInst(TI->getContext(), TI); 4647 TI->eraseFromParent(); 4648 Changed = true; 4649 } 4650 } 4651 4652 if (DTU) 4653 DTU->applyUpdatesPermissive(Updates); 4654 4655 // If this block is now dead, remove it. 4656 if (pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) { 4657 // We know there are no successors, so just nuke the block. 4658 if (LoopHeaders) 4659 LoopHeaders->erase(BB); 4660 if (DTU) 4661 DTU->deleteBB(BB); 4662 else 4663 BB->eraseFromParent(); 4664 return true; 4665 } 4666 4667 return Changed; 4668 } 4669 4670 static bool CasesAreContiguous(SmallVectorImpl<ConstantInt *> &Cases) { 4671 assert(Cases.size() >= 1); 4672 4673 array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate); 4674 for (size_t I = 1, E = Cases.size(); I != E; ++I) { 4675 if (Cases[I - 1]->getValue() != Cases[I]->getValue() + 1) 4676 return false; 4677 } 4678 return true; 4679 } 4680 4681 static void createUnreachableSwitchDefault(SwitchInst *Switch) { 4682 LLVM_DEBUG(dbgs() << "SimplifyCFG: switch default is dead.\n"); 4683 BasicBlock *NewDefaultBlock = 4684 SplitBlockPredecessors(Switch->getDefaultDest(), Switch->getParent(), ""); 4685 Switch->setDefaultDest(&*NewDefaultBlock); 4686 SplitBlock(&*NewDefaultBlock, &NewDefaultBlock->front()); 4687 auto *NewTerminator = NewDefaultBlock->getTerminator(); 4688 new UnreachableInst(Switch->getContext(), NewTerminator); 4689 EraseTerminatorAndDCECond(NewTerminator); 4690 } 4691 4692 /// Turn a switch with two reachable destinations into an integer range 4693 /// comparison and branch. 4694 bool SimplifyCFGOpt::TurnSwitchRangeIntoICmp(SwitchInst *SI, 4695 IRBuilder<> &Builder) { 4696 assert(SI->getNumCases() > 1 && "Degenerate switch?"); 4697 4698 bool HasDefault = 4699 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg()); 4700 4701 // Partition the cases into two sets with different destinations. 4702 BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr; 4703 BasicBlock *DestB = nullptr; 4704 SmallVector<ConstantInt *, 16> CasesA; 4705 SmallVector<ConstantInt *, 16> CasesB; 4706 4707 for (auto Case : SI->cases()) { 4708 BasicBlock *Dest = Case.getCaseSuccessor(); 4709 if (!DestA) 4710 DestA = Dest; 4711 if (Dest == DestA) { 4712 CasesA.push_back(Case.getCaseValue()); 4713 continue; 4714 } 4715 if (!DestB) 4716 DestB = Dest; 4717 if (Dest == DestB) { 4718 CasesB.push_back(Case.getCaseValue()); 4719 continue; 4720 } 4721 return false; // More than two destinations. 4722 } 4723 4724 assert(DestA && DestB && 4725 "Single-destination switch should have been folded."); 4726 assert(DestA != DestB); 4727 assert(DestB != SI->getDefaultDest()); 4728 assert(!CasesB.empty() && "There must be non-default cases."); 4729 assert(!CasesA.empty() || HasDefault); 4730 4731 // Figure out if one of the sets of cases form a contiguous range. 4732 SmallVectorImpl<ConstantInt *> *ContiguousCases = nullptr; 4733 BasicBlock *ContiguousDest = nullptr; 4734 BasicBlock *OtherDest = nullptr; 4735 if (!CasesA.empty() && CasesAreContiguous(CasesA)) { 4736 ContiguousCases = &CasesA; 4737 ContiguousDest = DestA; 4738 OtherDest = DestB; 4739 } else if (CasesAreContiguous(CasesB)) { 4740 ContiguousCases = &CasesB; 4741 ContiguousDest = DestB; 4742 OtherDest = DestA; 4743 } else 4744 return false; 4745 4746 // Start building the compare and branch. 4747 4748 Constant *Offset = ConstantExpr::getNeg(ContiguousCases->back()); 4749 Constant *NumCases = 4750 ConstantInt::get(Offset->getType(), ContiguousCases->size()); 4751 4752 Value *Sub = SI->getCondition(); 4753 if (!Offset->isNullValue()) 4754 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off"); 4755 4756 Value *Cmp; 4757 // If NumCases overflowed, then all possible values jump to the successor. 4758 if (NumCases->isNullValue() && !ContiguousCases->empty()) 4759 Cmp = ConstantInt::getTrue(SI->getContext()); 4760 else 4761 Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch"); 4762 BranchInst *NewBI = Builder.CreateCondBr(Cmp, ContiguousDest, OtherDest); 4763 4764 // Update weight for the newly-created conditional branch. 4765 if (HasBranchWeights(SI)) { 4766 SmallVector<uint64_t, 8> Weights; 4767 GetBranchWeights(SI, Weights); 4768 if (Weights.size() == 1 + SI->getNumCases()) { 4769 uint64_t TrueWeight = 0; 4770 uint64_t FalseWeight = 0; 4771 for (size_t I = 0, E = Weights.size(); I != E; ++I) { 4772 if (SI->getSuccessor(I) == ContiguousDest) 4773 TrueWeight += Weights[I]; 4774 else 4775 FalseWeight += Weights[I]; 4776 } 4777 while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) { 4778 TrueWeight /= 2; 4779 FalseWeight /= 2; 4780 } 4781 setBranchWeights(NewBI, TrueWeight, FalseWeight); 4782 } 4783 } 4784 4785 // Prune obsolete incoming values off the successors' PHI nodes. 4786 for (auto BBI = ContiguousDest->begin(); isa<PHINode>(BBI); ++BBI) { 4787 unsigned PreviousEdges = ContiguousCases->size(); 4788 if (ContiguousDest == SI->getDefaultDest()) 4789 ++PreviousEdges; 4790 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I) 4791 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent()); 4792 } 4793 for (auto BBI = OtherDest->begin(); isa<PHINode>(BBI); ++BBI) { 4794 unsigned PreviousEdges = SI->getNumCases() - ContiguousCases->size(); 4795 if (OtherDest == SI->getDefaultDest()) 4796 ++PreviousEdges; 4797 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I) 4798 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent()); 4799 } 4800 4801 // Clean up the default block - it may have phis or other instructions before 4802 // the unreachable terminator. 4803 if (!HasDefault) 4804 createUnreachableSwitchDefault(SI); 4805 4806 // Drop the switch. 4807 SI->eraseFromParent(); 4808 4809 return true; 4810 } 4811 4812 /// Compute masked bits for the condition of a switch 4813 /// and use it to remove dead cases. 4814 static bool eliminateDeadSwitchCases(SwitchInst *SI, AssumptionCache *AC, 4815 const DataLayout &DL) { 4816 Value *Cond = SI->getCondition(); 4817 unsigned Bits = Cond->getType()->getIntegerBitWidth(); 4818 KnownBits Known = computeKnownBits(Cond, DL, 0, AC, SI); 4819 4820 // We can also eliminate cases by determining that their values are outside of 4821 // the limited range of the condition based on how many significant (non-sign) 4822 // bits are in the condition value. 4823 unsigned ExtraSignBits = ComputeNumSignBits(Cond, DL, 0, AC, SI) - 1; 4824 unsigned MaxSignificantBitsInCond = Bits - ExtraSignBits; 4825 4826 // Gather dead cases. 4827 SmallVector<ConstantInt *, 8> DeadCases; 4828 for (auto &Case : SI->cases()) { 4829 const APInt &CaseVal = Case.getCaseValue()->getValue(); 4830 if (Known.Zero.intersects(CaseVal) || !Known.One.isSubsetOf(CaseVal) || 4831 (CaseVal.getMinSignedBits() > MaxSignificantBitsInCond)) { 4832 DeadCases.push_back(Case.getCaseValue()); 4833 LLVM_DEBUG(dbgs() << "SimplifyCFG: switch case " << CaseVal 4834 << " is dead.\n"); 4835 } 4836 } 4837 4838 // If we can prove that the cases must cover all possible values, the 4839 // default destination becomes dead and we can remove it. If we know some 4840 // of the bits in the value, we can use that to more precisely compute the 4841 // number of possible unique case values. 4842 bool HasDefault = 4843 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg()); 4844 const unsigned NumUnknownBits = 4845 Bits - (Known.Zero | Known.One).countPopulation(); 4846 assert(NumUnknownBits <= Bits); 4847 if (HasDefault && DeadCases.empty() && 4848 NumUnknownBits < 64 /* avoid overflow */ && 4849 SI->getNumCases() == (1ULL << NumUnknownBits)) { 4850 createUnreachableSwitchDefault(SI); 4851 return true; 4852 } 4853 4854 if (DeadCases.empty()) 4855 return false; 4856 4857 SwitchInstProfUpdateWrapper SIW(*SI); 4858 for (ConstantInt *DeadCase : DeadCases) { 4859 SwitchInst::CaseIt CaseI = SI->findCaseValue(DeadCase); 4860 assert(CaseI != SI->case_default() && 4861 "Case was not found. Probably mistake in DeadCases forming."); 4862 // Prune unused values from PHI nodes. 4863 CaseI->getCaseSuccessor()->removePredecessor(SI->getParent()); 4864 SIW.removeCase(CaseI); 4865 } 4866 4867 return true; 4868 } 4869 4870 /// If BB would be eligible for simplification by 4871 /// TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated 4872 /// by an unconditional branch), look at the phi node for BB in the successor 4873 /// block and see if the incoming value is equal to CaseValue. If so, return 4874 /// the phi node, and set PhiIndex to BB's index in the phi node. 4875 static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue, 4876 BasicBlock *BB, int *PhiIndex) { 4877 if (BB->getFirstNonPHIOrDbg() != BB->getTerminator()) 4878 return nullptr; // BB must be empty to be a candidate for simplification. 4879 if (!BB->getSinglePredecessor()) 4880 return nullptr; // BB must be dominated by the switch. 4881 4882 BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator()); 4883 if (!Branch || !Branch->isUnconditional()) 4884 return nullptr; // Terminator must be unconditional branch. 4885 4886 BasicBlock *Succ = Branch->getSuccessor(0); 4887 4888 for (PHINode &PHI : Succ->phis()) { 4889 int Idx = PHI.getBasicBlockIndex(BB); 4890 assert(Idx >= 0 && "PHI has no entry for predecessor?"); 4891 4892 Value *InValue = PHI.getIncomingValue(Idx); 4893 if (InValue != CaseValue) 4894 continue; 4895 4896 *PhiIndex = Idx; 4897 return &PHI; 4898 } 4899 4900 return nullptr; 4901 } 4902 4903 /// Try to forward the condition of a switch instruction to a phi node 4904 /// dominated by the switch, if that would mean that some of the destination 4905 /// blocks of the switch can be folded away. Return true if a change is made. 4906 static bool ForwardSwitchConditionToPHI(SwitchInst *SI) { 4907 using ForwardingNodesMap = DenseMap<PHINode *, SmallVector<int, 4>>; 4908 4909 ForwardingNodesMap ForwardingNodes; 4910 BasicBlock *SwitchBlock = SI->getParent(); 4911 bool Changed = false; 4912 for (auto &Case : SI->cases()) { 4913 ConstantInt *CaseValue = Case.getCaseValue(); 4914 BasicBlock *CaseDest = Case.getCaseSuccessor(); 4915 4916 // Replace phi operands in successor blocks that are using the constant case 4917 // value rather than the switch condition variable: 4918 // switchbb: 4919 // switch i32 %x, label %default [ 4920 // i32 17, label %succ 4921 // ... 4922 // succ: 4923 // %r = phi i32 ... [ 17, %switchbb ] ... 4924 // --> 4925 // %r = phi i32 ... [ %x, %switchbb ] ... 4926 4927 for (PHINode &Phi : CaseDest->phis()) { 4928 // This only works if there is exactly 1 incoming edge from the switch to 4929 // a phi. If there is >1, that means multiple cases of the switch map to 1 4930 // value in the phi, and that phi value is not the switch condition. Thus, 4931 // this transform would not make sense (the phi would be invalid because 4932 // a phi can't have different incoming values from the same block). 4933 int SwitchBBIdx = Phi.getBasicBlockIndex(SwitchBlock); 4934 if (Phi.getIncomingValue(SwitchBBIdx) == CaseValue && 4935 count(Phi.blocks(), SwitchBlock) == 1) { 4936 Phi.setIncomingValue(SwitchBBIdx, SI->getCondition()); 4937 Changed = true; 4938 } 4939 } 4940 4941 // Collect phi nodes that are indirectly using this switch's case constants. 4942 int PhiIdx; 4943 if (auto *Phi = FindPHIForConditionForwarding(CaseValue, CaseDest, &PhiIdx)) 4944 ForwardingNodes[Phi].push_back(PhiIdx); 4945 } 4946 4947 for (auto &ForwardingNode : ForwardingNodes) { 4948 PHINode *Phi = ForwardingNode.first; 4949 SmallVectorImpl<int> &Indexes = ForwardingNode.second; 4950 if (Indexes.size() < 2) 4951 continue; 4952 4953 for (int Index : Indexes) 4954 Phi->setIncomingValue(Index, SI->getCondition()); 4955 Changed = true; 4956 } 4957 4958 return Changed; 4959 } 4960 4961 /// Return true if the backend will be able to handle 4962 /// initializing an array of constants like C. 4963 static bool ValidLookupTableConstant(Constant *C, const TargetTransformInfo &TTI) { 4964 if (C->isThreadDependent()) 4965 return false; 4966 if (C->isDLLImportDependent()) 4967 return false; 4968 4969 if (!isa<ConstantFP>(C) && !isa<ConstantInt>(C) && 4970 !isa<ConstantPointerNull>(C) && !isa<GlobalValue>(C) && 4971 !isa<UndefValue>(C) && !isa<ConstantExpr>(C)) 4972 return false; 4973 4974 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 4975 if (!CE->isGEPWithNoNotionalOverIndexing()) 4976 return false; 4977 if (!ValidLookupTableConstant(CE->getOperand(0), TTI)) 4978 return false; 4979 } 4980 4981 if (!TTI.shouldBuildLookupTablesForConstant(C)) 4982 return false; 4983 4984 return true; 4985 } 4986 4987 /// If V is a Constant, return it. Otherwise, try to look up 4988 /// its constant value in ConstantPool, returning 0 if it's not there. 4989 static Constant * 4990 LookupConstant(Value *V, 4991 const SmallDenseMap<Value *, Constant *> &ConstantPool) { 4992 if (Constant *C = dyn_cast<Constant>(V)) 4993 return C; 4994 return ConstantPool.lookup(V); 4995 } 4996 4997 /// Try to fold instruction I into a constant. This works for 4998 /// simple instructions such as binary operations where both operands are 4999 /// constant or can be replaced by constants from the ConstantPool. Returns the 5000 /// resulting constant on success, 0 otherwise. 5001 static Constant * 5002 ConstantFold(Instruction *I, const DataLayout &DL, 5003 const SmallDenseMap<Value *, Constant *> &ConstantPool) { 5004 if (SelectInst *Select = dyn_cast<SelectInst>(I)) { 5005 Constant *A = LookupConstant(Select->getCondition(), ConstantPool); 5006 if (!A) 5007 return nullptr; 5008 if (A->isAllOnesValue()) 5009 return LookupConstant(Select->getTrueValue(), ConstantPool); 5010 if (A->isNullValue()) 5011 return LookupConstant(Select->getFalseValue(), ConstantPool); 5012 return nullptr; 5013 } 5014 5015 SmallVector<Constant *, 4> COps; 5016 for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) { 5017 if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool)) 5018 COps.push_back(A); 5019 else 5020 return nullptr; 5021 } 5022 5023 if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) { 5024 return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0], 5025 COps[1], DL); 5026 } 5027 5028 return ConstantFoldInstOperands(I, COps, DL); 5029 } 5030 5031 /// Try to determine the resulting constant values in phi nodes 5032 /// at the common destination basic block, *CommonDest, for one of the case 5033 /// destionations CaseDest corresponding to value CaseVal (0 for the default 5034 /// case), of a switch instruction SI. 5035 static bool 5036 GetCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest, 5037 BasicBlock **CommonDest, 5038 SmallVectorImpl<std::pair<PHINode *, Constant *>> &Res, 5039 const DataLayout &DL, const TargetTransformInfo &TTI) { 5040 // The block from which we enter the common destination. 5041 BasicBlock *Pred = SI->getParent(); 5042 5043 // If CaseDest is empty except for some side-effect free instructions through 5044 // which we can constant-propagate the CaseVal, continue to its successor. 5045 SmallDenseMap<Value *, Constant *> ConstantPool; 5046 ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal)); 5047 for (Instruction &I :CaseDest->instructionsWithoutDebug()) { 5048 if (I.isTerminator()) { 5049 // If the terminator is a simple branch, continue to the next block. 5050 if (I.getNumSuccessors() != 1 || I.isExceptionalTerminator()) 5051 return false; 5052 Pred = CaseDest; 5053 CaseDest = I.getSuccessor(0); 5054 } else if (Constant *C = ConstantFold(&I, DL, ConstantPool)) { 5055 // Instruction is side-effect free and constant. 5056 5057 // If the instruction has uses outside this block or a phi node slot for 5058 // the block, it is not safe to bypass the instruction since it would then 5059 // no longer dominate all its uses. 5060 for (auto &Use : I.uses()) { 5061 User *User = Use.getUser(); 5062 if (Instruction *I = dyn_cast<Instruction>(User)) 5063 if (I->getParent() == CaseDest) 5064 continue; 5065 if (PHINode *Phi = dyn_cast<PHINode>(User)) 5066 if (Phi->getIncomingBlock(Use) == CaseDest) 5067 continue; 5068 return false; 5069 } 5070 5071 ConstantPool.insert(std::make_pair(&I, C)); 5072 } else { 5073 break; 5074 } 5075 } 5076 5077 // If we did not have a CommonDest before, use the current one. 5078 if (!*CommonDest) 5079 *CommonDest = CaseDest; 5080 // If the destination isn't the common one, abort. 5081 if (CaseDest != *CommonDest) 5082 return false; 5083 5084 // Get the values for this case from phi nodes in the destination block. 5085 for (PHINode &PHI : (*CommonDest)->phis()) { 5086 int Idx = PHI.getBasicBlockIndex(Pred); 5087 if (Idx == -1) 5088 continue; 5089 5090 Constant *ConstVal = 5091 LookupConstant(PHI.getIncomingValue(Idx), ConstantPool); 5092 if (!ConstVal) 5093 return false; 5094 5095 // Be conservative about which kinds of constants we support. 5096 if (!ValidLookupTableConstant(ConstVal, TTI)) 5097 return false; 5098 5099 Res.push_back(std::make_pair(&PHI, ConstVal)); 5100 } 5101 5102 return Res.size() > 0; 5103 } 5104 5105 // Helper function used to add CaseVal to the list of cases that generate 5106 // Result. Returns the updated number of cases that generate this result. 5107 static uintptr_t MapCaseToResult(ConstantInt *CaseVal, 5108 SwitchCaseResultVectorTy &UniqueResults, 5109 Constant *Result) { 5110 for (auto &I : UniqueResults) { 5111 if (I.first == Result) { 5112 I.second.push_back(CaseVal); 5113 return I.second.size(); 5114 } 5115 } 5116 UniqueResults.push_back( 5117 std::make_pair(Result, SmallVector<ConstantInt *, 4>(1, CaseVal))); 5118 return 1; 5119 } 5120 5121 // Helper function that initializes a map containing 5122 // results for the PHI node of the common destination block for a switch 5123 // instruction. Returns false if multiple PHI nodes have been found or if 5124 // there is not a common destination block for the switch. 5125 static bool 5126 InitializeUniqueCases(SwitchInst *SI, PHINode *&PHI, BasicBlock *&CommonDest, 5127 SwitchCaseResultVectorTy &UniqueResults, 5128 Constant *&DefaultResult, const DataLayout &DL, 5129 const TargetTransformInfo &TTI, 5130 uintptr_t MaxUniqueResults, uintptr_t MaxCasesPerResult) { 5131 for (auto &I : SI->cases()) { 5132 ConstantInt *CaseVal = I.getCaseValue(); 5133 5134 // Resulting value at phi nodes for this case value. 5135 SwitchCaseResultsTy Results; 5136 if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results, 5137 DL, TTI)) 5138 return false; 5139 5140 // Only one value per case is permitted. 5141 if (Results.size() > 1) 5142 return false; 5143 5144 // Add the case->result mapping to UniqueResults. 5145 const uintptr_t NumCasesForResult = 5146 MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second); 5147 5148 // Early out if there are too many cases for this result. 5149 if (NumCasesForResult > MaxCasesPerResult) 5150 return false; 5151 5152 // Early out if there are too many unique results. 5153 if (UniqueResults.size() > MaxUniqueResults) 5154 return false; 5155 5156 // Check the PHI consistency. 5157 if (!PHI) 5158 PHI = Results[0].first; 5159 else if (PHI != Results[0].first) 5160 return false; 5161 } 5162 // Find the default result value. 5163 SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults; 5164 BasicBlock *DefaultDest = SI->getDefaultDest(); 5165 GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults, 5166 DL, TTI); 5167 // If the default value is not found abort unless the default destination 5168 // is unreachable. 5169 DefaultResult = 5170 DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr; 5171 if ((!DefaultResult && 5172 !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg()))) 5173 return false; 5174 5175 return true; 5176 } 5177 5178 // Helper function that checks if it is possible to transform a switch with only 5179 // two cases (or two cases + default) that produces a result into a select. 5180 // Example: 5181 // switch (a) { 5182 // case 10: %0 = icmp eq i32 %a, 10 5183 // return 10; %1 = select i1 %0, i32 10, i32 4 5184 // case 20: ----> %2 = icmp eq i32 %a, 20 5185 // return 2; %3 = select i1 %2, i32 2, i32 %1 5186 // default: 5187 // return 4; 5188 // } 5189 static Value *ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector, 5190 Constant *DefaultResult, Value *Condition, 5191 IRBuilder<> &Builder) { 5192 assert(ResultVector.size() == 2 && 5193 "We should have exactly two unique results at this point"); 5194 // If we are selecting between only two cases transform into a simple 5195 // select or a two-way select if default is possible. 5196 if (ResultVector[0].second.size() == 1 && 5197 ResultVector[1].second.size() == 1) { 5198 ConstantInt *const FirstCase = ResultVector[0].second[0]; 5199 ConstantInt *const SecondCase = ResultVector[1].second[0]; 5200 5201 bool DefaultCanTrigger = DefaultResult; 5202 Value *SelectValue = ResultVector[1].first; 5203 if (DefaultCanTrigger) { 5204 Value *const ValueCompare = 5205 Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp"); 5206 SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first, 5207 DefaultResult, "switch.select"); 5208 } 5209 Value *const ValueCompare = 5210 Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp"); 5211 return Builder.CreateSelect(ValueCompare, ResultVector[0].first, 5212 SelectValue, "switch.select"); 5213 } 5214 5215 return nullptr; 5216 } 5217 5218 // Helper function to cleanup a switch instruction that has been converted into 5219 // a select, fixing up PHI nodes and basic blocks. 5220 static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI, 5221 Value *SelectValue, 5222 IRBuilder<> &Builder) { 5223 BasicBlock *SelectBB = SI->getParent(); 5224 while (PHI->getBasicBlockIndex(SelectBB) >= 0) 5225 PHI->removeIncomingValue(SelectBB); 5226 PHI->addIncoming(SelectValue, SelectBB); 5227 5228 Builder.CreateBr(PHI->getParent()); 5229 5230 // Remove the switch. 5231 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) { 5232 BasicBlock *Succ = SI->getSuccessor(i); 5233 5234 if (Succ == PHI->getParent()) 5235 continue; 5236 Succ->removePredecessor(SelectBB); 5237 } 5238 SI->eraseFromParent(); 5239 } 5240 5241 /// If the switch is only used to initialize one or more 5242 /// phi nodes in a common successor block with only two different 5243 /// constant values, replace the switch with select. 5244 static bool switchToSelect(SwitchInst *SI, IRBuilder<> &Builder, 5245 const DataLayout &DL, 5246 const TargetTransformInfo &TTI) { 5247 Value *const Cond = SI->getCondition(); 5248 PHINode *PHI = nullptr; 5249 BasicBlock *CommonDest = nullptr; 5250 Constant *DefaultResult; 5251 SwitchCaseResultVectorTy UniqueResults; 5252 // Collect all the cases that will deliver the same value from the switch. 5253 if (!InitializeUniqueCases(SI, PHI, CommonDest, UniqueResults, DefaultResult, 5254 DL, TTI, 2, 1)) 5255 return false; 5256 // Selects choose between maximum two values. 5257 if (UniqueResults.size() != 2) 5258 return false; 5259 assert(PHI != nullptr && "PHI for value select not found"); 5260 5261 Builder.SetInsertPoint(SI); 5262 Value *SelectValue = 5263 ConvertTwoCaseSwitch(UniqueResults, DefaultResult, Cond, Builder); 5264 if (SelectValue) { 5265 RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder); 5266 return true; 5267 } 5268 // The switch couldn't be converted into a select. 5269 return false; 5270 } 5271 5272 namespace { 5273 5274 /// This class represents a lookup table that can be used to replace a switch. 5275 class SwitchLookupTable { 5276 public: 5277 /// Create a lookup table to use as a switch replacement with the contents 5278 /// of Values, using DefaultValue to fill any holes in the table. 5279 SwitchLookupTable( 5280 Module &M, uint64_t TableSize, ConstantInt *Offset, 5281 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values, 5282 Constant *DefaultValue, const DataLayout &DL, const StringRef &FuncName); 5283 5284 /// Build instructions with Builder to retrieve the value at 5285 /// the position given by Index in the lookup table. 5286 Value *BuildLookup(Value *Index, IRBuilder<> &Builder); 5287 5288 /// Return true if a table with TableSize elements of 5289 /// type ElementType would fit in a target-legal register. 5290 static bool WouldFitInRegister(const DataLayout &DL, uint64_t TableSize, 5291 Type *ElementType); 5292 5293 private: 5294 // Depending on the contents of the table, it can be represented in 5295 // different ways. 5296 enum { 5297 // For tables where each element contains the same value, we just have to 5298 // store that single value and return it for each lookup. 5299 SingleValueKind, 5300 5301 // For tables where there is a linear relationship between table index 5302 // and values. We calculate the result with a simple multiplication 5303 // and addition instead of a table lookup. 5304 LinearMapKind, 5305 5306 // For small tables with integer elements, we can pack them into a bitmap 5307 // that fits into a target-legal register. Values are retrieved by 5308 // shift and mask operations. 5309 BitMapKind, 5310 5311 // The table is stored as an array of values. Values are retrieved by load 5312 // instructions from the table. 5313 ArrayKind 5314 } Kind; 5315 5316 // For SingleValueKind, this is the single value. 5317 Constant *SingleValue = nullptr; 5318 5319 // For BitMapKind, this is the bitmap. 5320 ConstantInt *BitMap = nullptr; 5321 IntegerType *BitMapElementTy = nullptr; 5322 5323 // For LinearMapKind, these are the constants used to derive the value. 5324 ConstantInt *LinearOffset = nullptr; 5325 ConstantInt *LinearMultiplier = nullptr; 5326 5327 // For ArrayKind, this is the array. 5328 GlobalVariable *Array = nullptr; 5329 }; 5330 5331 } // end anonymous namespace 5332 5333 SwitchLookupTable::SwitchLookupTable( 5334 Module &M, uint64_t TableSize, ConstantInt *Offset, 5335 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values, 5336 Constant *DefaultValue, const DataLayout &DL, const StringRef &FuncName) { 5337 assert(Values.size() && "Can't build lookup table without values!"); 5338 assert(TableSize >= Values.size() && "Can't fit values in table!"); 5339 5340 // If all values in the table are equal, this is that value. 5341 SingleValue = Values.begin()->second; 5342 5343 Type *ValueType = Values.begin()->second->getType(); 5344 5345 // Build up the table contents. 5346 SmallVector<Constant *, 64> TableContents(TableSize); 5347 for (size_t I = 0, E = Values.size(); I != E; ++I) { 5348 ConstantInt *CaseVal = Values[I].first; 5349 Constant *CaseRes = Values[I].second; 5350 assert(CaseRes->getType() == ValueType); 5351 5352 uint64_t Idx = (CaseVal->getValue() - Offset->getValue()).getLimitedValue(); 5353 TableContents[Idx] = CaseRes; 5354 5355 if (CaseRes != SingleValue) 5356 SingleValue = nullptr; 5357 } 5358 5359 // Fill in any holes in the table with the default result. 5360 if (Values.size() < TableSize) { 5361 assert(DefaultValue && 5362 "Need a default value to fill the lookup table holes."); 5363 assert(DefaultValue->getType() == ValueType); 5364 for (uint64_t I = 0; I < TableSize; ++I) { 5365 if (!TableContents[I]) 5366 TableContents[I] = DefaultValue; 5367 } 5368 5369 if (DefaultValue != SingleValue) 5370 SingleValue = nullptr; 5371 } 5372 5373 // If each element in the table contains the same value, we only need to store 5374 // that single value. 5375 if (SingleValue) { 5376 Kind = SingleValueKind; 5377 return; 5378 } 5379 5380 // Check if we can derive the value with a linear transformation from the 5381 // table index. 5382 if (isa<IntegerType>(ValueType)) { 5383 bool LinearMappingPossible = true; 5384 APInt PrevVal; 5385 APInt DistToPrev; 5386 assert(TableSize >= 2 && "Should be a SingleValue table."); 5387 // Check if there is the same distance between two consecutive values. 5388 for (uint64_t I = 0; I < TableSize; ++I) { 5389 ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]); 5390 if (!ConstVal) { 5391 // This is an undef. We could deal with it, but undefs in lookup tables 5392 // are very seldom. It's probably not worth the additional complexity. 5393 LinearMappingPossible = false; 5394 break; 5395 } 5396 const APInt &Val = ConstVal->getValue(); 5397 if (I != 0) { 5398 APInt Dist = Val - PrevVal; 5399 if (I == 1) { 5400 DistToPrev = Dist; 5401 } else if (Dist != DistToPrev) { 5402 LinearMappingPossible = false; 5403 break; 5404 } 5405 } 5406 PrevVal = Val; 5407 } 5408 if (LinearMappingPossible) { 5409 LinearOffset = cast<ConstantInt>(TableContents[0]); 5410 LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev); 5411 Kind = LinearMapKind; 5412 ++NumLinearMaps; 5413 return; 5414 } 5415 } 5416 5417 // If the type is integer and the table fits in a register, build a bitmap. 5418 if (WouldFitInRegister(DL, TableSize, ValueType)) { 5419 IntegerType *IT = cast<IntegerType>(ValueType); 5420 APInt TableInt(TableSize * IT->getBitWidth(), 0); 5421 for (uint64_t I = TableSize; I > 0; --I) { 5422 TableInt <<= IT->getBitWidth(); 5423 // Insert values into the bitmap. Undef values are set to zero. 5424 if (!isa<UndefValue>(TableContents[I - 1])) { 5425 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]); 5426 TableInt |= Val->getValue().zext(TableInt.getBitWidth()); 5427 } 5428 } 5429 BitMap = ConstantInt::get(M.getContext(), TableInt); 5430 BitMapElementTy = IT; 5431 Kind = BitMapKind; 5432 ++NumBitMaps; 5433 return; 5434 } 5435 5436 // Store the table in an array. 5437 ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize); 5438 Constant *Initializer = ConstantArray::get(ArrayTy, TableContents); 5439 5440 Array = new GlobalVariable(M, ArrayTy, /*isConstant=*/true, 5441 GlobalVariable::PrivateLinkage, Initializer, 5442 "switch.table." + FuncName); 5443 Array->setUnnamedAddr(GlobalValue::UnnamedAddr::Global); 5444 // Set the alignment to that of an array items. We will be only loading one 5445 // value out of it. 5446 Array->setAlignment(Align(DL.getPrefTypeAlignment(ValueType))); 5447 Kind = ArrayKind; 5448 } 5449 5450 Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) { 5451 switch (Kind) { 5452 case SingleValueKind: 5453 return SingleValue; 5454 case LinearMapKind: { 5455 // Derive the result value from the input value. 5456 Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(), 5457 false, "switch.idx.cast"); 5458 if (!LinearMultiplier->isOne()) 5459 Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult"); 5460 if (!LinearOffset->isZero()) 5461 Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset"); 5462 return Result; 5463 } 5464 case BitMapKind: { 5465 // Type of the bitmap (e.g. i59). 5466 IntegerType *MapTy = BitMap->getType(); 5467 5468 // Cast Index to the same type as the bitmap. 5469 // Note: The Index is <= the number of elements in the table, so 5470 // truncating it to the width of the bitmask is safe. 5471 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast"); 5472 5473 // Multiply the shift amount by the element width. 5474 ShiftAmt = Builder.CreateMul( 5475 ShiftAmt, ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()), 5476 "switch.shiftamt"); 5477 5478 // Shift down. 5479 Value *DownShifted = 5480 Builder.CreateLShr(BitMap, ShiftAmt, "switch.downshift"); 5481 // Mask off. 5482 return Builder.CreateTrunc(DownShifted, BitMapElementTy, "switch.masked"); 5483 } 5484 case ArrayKind: { 5485 // Make sure the table index will not overflow when treated as signed. 5486 IntegerType *IT = cast<IntegerType>(Index->getType()); 5487 uint64_t TableSize = 5488 Array->getInitializer()->getType()->getArrayNumElements(); 5489 if (TableSize > (1ULL << (IT->getBitWidth() - 1))) 5490 Index = Builder.CreateZExt( 5491 Index, IntegerType::get(IT->getContext(), IT->getBitWidth() + 1), 5492 "switch.tableidx.zext"); 5493 5494 Value *GEPIndices[] = {Builder.getInt32(0), Index}; 5495 Value *GEP = Builder.CreateInBoundsGEP(Array->getValueType(), Array, 5496 GEPIndices, "switch.gep"); 5497 return Builder.CreateLoad( 5498 cast<ArrayType>(Array->getValueType())->getElementType(), GEP, 5499 "switch.load"); 5500 } 5501 } 5502 llvm_unreachable("Unknown lookup table kind!"); 5503 } 5504 5505 bool SwitchLookupTable::WouldFitInRegister(const DataLayout &DL, 5506 uint64_t TableSize, 5507 Type *ElementType) { 5508 auto *IT = dyn_cast<IntegerType>(ElementType); 5509 if (!IT) 5510 return false; 5511 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values 5512 // are <= 15, we could try to narrow the type. 5513 5514 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width. 5515 if (TableSize >= UINT_MAX / IT->getBitWidth()) 5516 return false; 5517 return DL.fitsInLegalInteger(TableSize * IT->getBitWidth()); 5518 } 5519 5520 /// Determine whether a lookup table should be built for this switch, based on 5521 /// the number of cases, size of the table, and the types of the results. 5522 static bool 5523 ShouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize, 5524 const TargetTransformInfo &TTI, const DataLayout &DL, 5525 const SmallDenseMap<PHINode *, Type *> &ResultTypes) { 5526 if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10) 5527 return false; // TableSize overflowed, or mul below might overflow. 5528 5529 bool AllTablesFitInRegister = true; 5530 bool HasIllegalType = false; 5531 for (const auto &I : ResultTypes) { 5532 Type *Ty = I.second; 5533 5534 // Saturate this flag to true. 5535 HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty); 5536 5537 // Saturate this flag to false. 5538 AllTablesFitInRegister = 5539 AllTablesFitInRegister && 5540 SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty); 5541 5542 // If both flags saturate, we're done. NOTE: This *only* works with 5543 // saturating flags, and all flags have to saturate first due to the 5544 // non-deterministic behavior of iterating over a dense map. 5545 if (HasIllegalType && !AllTablesFitInRegister) 5546 break; 5547 } 5548 5549 // If each table would fit in a register, we should build it anyway. 5550 if (AllTablesFitInRegister) 5551 return true; 5552 5553 // Don't build a table that doesn't fit in-register if it has illegal types. 5554 if (HasIllegalType) 5555 return false; 5556 5557 // The table density should be at least 40%. This is the same criterion as for 5558 // jump tables, see SelectionDAGBuilder::handleJTSwitchCase. 5559 // FIXME: Find the best cut-off. 5560 return SI->getNumCases() * 10 >= TableSize * 4; 5561 } 5562 5563 /// Try to reuse the switch table index compare. Following pattern: 5564 /// \code 5565 /// if (idx < tablesize) 5566 /// r = table[idx]; // table does not contain default_value 5567 /// else 5568 /// r = default_value; 5569 /// if (r != default_value) 5570 /// ... 5571 /// \endcode 5572 /// Is optimized to: 5573 /// \code 5574 /// cond = idx < tablesize; 5575 /// if (cond) 5576 /// r = table[idx]; 5577 /// else 5578 /// r = default_value; 5579 /// if (cond) 5580 /// ... 5581 /// \endcode 5582 /// Jump threading will then eliminate the second if(cond). 5583 static void reuseTableCompare( 5584 User *PhiUser, BasicBlock *PhiBlock, BranchInst *RangeCheckBranch, 5585 Constant *DefaultValue, 5586 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values) { 5587 ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser); 5588 if (!CmpInst) 5589 return; 5590 5591 // We require that the compare is in the same block as the phi so that jump 5592 // threading can do its work afterwards. 5593 if (CmpInst->getParent() != PhiBlock) 5594 return; 5595 5596 Constant *CmpOp1 = dyn_cast<Constant>(CmpInst->getOperand(1)); 5597 if (!CmpOp1) 5598 return; 5599 5600 Value *RangeCmp = RangeCheckBranch->getCondition(); 5601 Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType()); 5602 Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType()); 5603 5604 // Check if the compare with the default value is constant true or false. 5605 Constant *DefaultConst = ConstantExpr::getICmp(CmpInst->getPredicate(), 5606 DefaultValue, CmpOp1, true); 5607 if (DefaultConst != TrueConst && DefaultConst != FalseConst) 5608 return; 5609 5610 // Check if the compare with the case values is distinct from the default 5611 // compare result. 5612 for (auto ValuePair : Values) { 5613 Constant *CaseConst = ConstantExpr::getICmp(CmpInst->getPredicate(), 5614 ValuePair.second, CmpOp1, true); 5615 if (!CaseConst || CaseConst == DefaultConst || isa<UndefValue>(CaseConst)) 5616 return; 5617 assert((CaseConst == TrueConst || CaseConst == FalseConst) && 5618 "Expect true or false as compare result."); 5619 } 5620 5621 // Check if the branch instruction dominates the phi node. It's a simple 5622 // dominance check, but sufficient for our needs. 5623 // Although this check is invariant in the calling loops, it's better to do it 5624 // at this late stage. Practically we do it at most once for a switch. 5625 BasicBlock *BranchBlock = RangeCheckBranch->getParent(); 5626 for (auto PI = pred_begin(PhiBlock), E = pred_end(PhiBlock); PI != E; ++PI) { 5627 BasicBlock *Pred = *PI; 5628 if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock) 5629 return; 5630 } 5631 5632 if (DefaultConst == FalseConst) { 5633 // The compare yields the same result. We can replace it. 5634 CmpInst->replaceAllUsesWith(RangeCmp); 5635 ++NumTableCmpReuses; 5636 } else { 5637 // The compare yields the same result, just inverted. We can replace it. 5638 Value *InvertedTableCmp = BinaryOperator::CreateXor( 5639 RangeCmp, ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp", 5640 RangeCheckBranch); 5641 CmpInst->replaceAllUsesWith(InvertedTableCmp); 5642 ++NumTableCmpReuses; 5643 } 5644 } 5645 5646 /// If the switch is only used to initialize one or more phi nodes in a common 5647 /// successor block with different constant values, replace the switch with 5648 /// lookup tables. 5649 static bool SwitchToLookupTable(SwitchInst *SI, IRBuilder<> &Builder, 5650 const DataLayout &DL, 5651 const TargetTransformInfo &TTI) { 5652 assert(SI->getNumCases() > 1 && "Degenerate switch?"); 5653 5654 Function *Fn = SI->getParent()->getParent(); 5655 // Only build lookup table when we have a target that supports it or the 5656 // attribute is not set. 5657 if (!TTI.shouldBuildLookupTables() || 5658 (Fn->getFnAttribute("no-jump-tables").getValueAsString() == "true")) 5659 return false; 5660 5661 // FIXME: If the switch is too sparse for a lookup table, perhaps we could 5662 // split off a dense part and build a lookup table for that. 5663 5664 // FIXME: This creates arrays of GEPs to constant strings, which means each 5665 // GEP needs a runtime relocation in PIC code. We should just build one big 5666 // string and lookup indices into that. 5667 5668 // Ignore switches with less than three cases. Lookup tables will not make 5669 // them faster, so we don't analyze them. 5670 if (SI->getNumCases() < 3) 5671 return false; 5672 5673 // Figure out the corresponding result for each case value and phi node in the 5674 // common destination, as well as the min and max case values. 5675 assert(!SI->cases().empty()); 5676 SwitchInst::CaseIt CI = SI->case_begin(); 5677 ConstantInt *MinCaseVal = CI->getCaseValue(); 5678 ConstantInt *MaxCaseVal = CI->getCaseValue(); 5679 5680 BasicBlock *CommonDest = nullptr; 5681 5682 using ResultListTy = SmallVector<std::pair<ConstantInt *, Constant *>, 4>; 5683 SmallDenseMap<PHINode *, ResultListTy> ResultLists; 5684 5685 SmallDenseMap<PHINode *, Constant *> DefaultResults; 5686 SmallDenseMap<PHINode *, Type *> ResultTypes; 5687 SmallVector<PHINode *, 4> PHIs; 5688 5689 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) { 5690 ConstantInt *CaseVal = CI->getCaseValue(); 5691 if (CaseVal->getValue().slt(MinCaseVal->getValue())) 5692 MinCaseVal = CaseVal; 5693 if (CaseVal->getValue().sgt(MaxCaseVal->getValue())) 5694 MaxCaseVal = CaseVal; 5695 5696 // Resulting value at phi nodes for this case value. 5697 using ResultsTy = SmallVector<std::pair<PHINode *, Constant *>, 4>; 5698 ResultsTy Results; 5699 if (!GetCaseResults(SI, CaseVal, CI->getCaseSuccessor(), &CommonDest, 5700 Results, DL, TTI)) 5701 return false; 5702 5703 // Append the result from this case to the list for each phi. 5704 for (const auto &I : Results) { 5705 PHINode *PHI = I.first; 5706 Constant *Value = I.second; 5707 if (!ResultLists.count(PHI)) 5708 PHIs.push_back(PHI); 5709 ResultLists[PHI].push_back(std::make_pair(CaseVal, Value)); 5710 } 5711 } 5712 5713 // Keep track of the result types. 5714 for (PHINode *PHI : PHIs) { 5715 ResultTypes[PHI] = ResultLists[PHI][0].second->getType(); 5716 } 5717 5718 uint64_t NumResults = ResultLists[PHIs[0]].size(); 5719 APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue(); 5720 uint64_t TableSize = RangeSpread.getLimitedValue() + 1; 5721 bool TableHasHoles = (NumResults < TableSize); 5722 5723 // If the table has holes, we need a constant result for the default case 5724 // or a bitmask that fits in a register. 5725 SmallVector<std::pair<PHINode *, Constant *>, 4> DefaultResultsList; 5726 bool HasDefaultResults = 5727 GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, 5728 DefaultResultsList, DL, TTI); 5729 5730 bool NeedMask = (TableHasHoles && !HasDefaultResults); 5731 if (NeedMask) { 5732 // As an extra penalty for the validity test we require more cases. 5733 if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark). 5734 return false; 5735 if (!DL.fitsInLegalInteger(TableSize)) 5736 return false; 5737 } 5738 5739 for (const auto &I : DefaultResultsList) { 5740 PHINode *PHI = I.first; 5741 Constant *Result = I.second; 5742 DefaultResults[PHI] = Result; 5743 } 5744 5745 if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes)) 5746 return false; 5747 5748 // Create the BB that does the lookups. 5749 Module &Mod = *CommonDest->getParent()->getParent(); 5750 BasicBlock *LookupBB = BasicBlock::Create( 5751 Mod.getContext(), "switch.lookup", CommonDest->getParent(), CommonDest); 5752 5753 // Compute the table index value. 5754 Builder.SetInsertPoint(SI); 5755 Value *TableIndex; 5756 if (MinCaseVal->isNullValue()) 5757 TableIndex = SI->getCondition(); 5758 else 5759 TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal, 5760 "switch.tableidx"); 5761 5762 // Compute the maximum table size representable by the integer type we are 5763 // switching upon. 5764 unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits(); 5765 uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize; 5766 assert(MaxTableSize >= TableSize && 5767 "It is impossible for a switch to have more entries than the max " 5768 "representable value of its input integer type's size."); 5769 5770 // If the default destination is unreachable, or if the lookup table covers 5771 // all values of the conditional variable, branch directly to the lookup table 5772 // BB. Otherwise, check that the condition is within the case range. 5773 const bool DefaultIsReachable = 5774 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg()); 5775 const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize); 5776 BranchInst *RangeCheckBranch = nullptr; 5777 5778 if (!DefaultIsReachable || GeneratingCoveredLookupTable) { 5779 Builder.CreateBr(LookupBB); 5780 // Note: We call removeProdecessor later since we need to be able to get the 5781 // PHI value for the default case in case we're using a bit mask. 5782 } else { 5783 Value *Cmp = Builder.CreateICmpULT( 5784 TableIndex, ConstantInt::get(MinCaseVal->getType(), TableSize)); 5785 RangeCheckBranch = 5786 Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest()); 5787 } 5788 5789 // Populate the BB that does the lookups. 5790 Builder.SetInsertPoint(LookupBB); 5791 5792 if (NeedMask) { 5793 // Before doing the lookup, we do the hole check. The LookupBB is therefore 5794 // re-purposed to do the hole check, and we create a new LookupBB. 5795 BasicBlock *MaskBB = LookupBB; 5796 MaskBB->setName("switch.hole_check"); 5797 LookupBB = BasicBlock::Create(Mod.getContext(), "switch.lookup", 5798 CommonDest->getParent(), CommonDest); 5799 5800 // Make the mask's bitwidth at least 8-bit and a power-of-2 to avoid 5801 // unnecessary illegal types. 5802 uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL)); 5803 APInt MaskInt(TableSizePowOf2, 0); 5804 APInt One(TableSizePowOf2, 1); 5805 // Build bitmask; fill in a 1 bit for every case. 5806 const ResultListTy &ResultList = ResultLists[PHIs[0]]; 5807 for (size_t I = 0, E = ResultList.size(); I != E; ++I) { 5808 uint64_t Idx = (ResultList[I].first->getValue() - MinCaseVal->getValue()) 5809 .getLimitedValue(); 5810 MaskInt |= One << Idx; 5811 } 5812 ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt); 5813 5814 // Get the TableIndex'th bit of the bitmask. 5815 // If this bit is 0 (meaning hole) jump to the default destination, 5816 // else continue with table lookup. 5817 IntegerType *MapTy = TableMask->getType(); 5818 Value *MaskIndex = 5819 Builder.CreateZExtOrTrunc(TableIndex, MapTy, "switch.maskindex"); 5820 Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex, "switch.shifted"); 5821 Value *LoBit = Builder.CreateTrunc( 5822 Shifted, Type::getInt1Ty(Mod.getContext()), "switch.lobit"); 5823 Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest()); 5824 5825 Builder.SetInsertPoint(LookupBB); 5826 AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent()); 5827 } 5828 5829 if (!DefaultIsReachable || GeneratingCoveredLookupTable) { 5830 // We cached PHINodes in PHIs. To avoid accessing deleted PHINodes later, 5831 // do not delete PHINodes here. 5832 SI->getDefaultDest()->removePredecessor(SI->getParent(), 5833 /*KeepOneInputPHIs=*/true); 5834 } 5835 5836 bool ReturnedEarly = false; 5837 for (PHINode *PHI : PHIs) { 5838 const ResultListTy &ResultList = ResultLists[PHI]; 5839 5840 // If using a bitmask, use any value to fill the lookup table holes. 5841 Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI]; 5842 StringRef FuncName = Fn->getName(); 5843 SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL, 5844 FuncName); 5845 5846 Value *Result = Table.BuildLookup(TableIndex, Builder); 5847 5848 // If the result is used to return immediately from the function, we want to 5849 // do that right here. 5850 if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) && 5851 PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) { 5852 Builder.CreateRet(Result); 5853 ReturnedEarly = true; 5854 break; 5855 } 5856 5857 // Do a small peephole optimization: re-use the switch table compare if 5858 // possible. 5859 if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) { 5860 BasicBlock *PhiBlock = PHI->getParent(); 5861 // Search for compare instructions which use the phi. 5862 for (auto *User : PHI->users()) { 5863 reuseTableCompare(User, PhiBlock, RangeCheckBranch, DV, ResultList); 5864 } 5865 } 5866 5867 PHI->addIncoming(Result, LookupBB); 5868 } 5869 5870 if (!ReturnedEarly) 5871 Builder.CreateBr(CommonDest); 5872 5873 // Remove the switch. 5874 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) { 5875 BasicBlock *Succ = SI->getSuccessor(i); 5876 5877 if (Succ == SI->getDefaultDest()) 5878 continue; 5879 Succ->removePredecessor(SI->getParent()); 5880 } 5881 SI->eraseFromParent(); 5882 5883 ++NumLookupTables; 5884 if (NeedMask) 5885 ++NumLookupTablesHoles; 5886 return true; 5887 } 5888 5889 static bool isSwitchDense(ArrayRef<int64_t> Values) { 5890 // See also SelectionDAGBuilder::isDense(), which this function was based on. 5891 uint64_t Diff = (uint64_t)Values.back() - (uint64_t)Values.front(); 5892 uint64_t Range = Diff + 1; 5893 uint64_t NumCases = Values.size(); 5894 // 40% is the default density for building a jump table in optsize/minsize mode. 5895 uint64_t MinDensity = 40; 5896 5897 return NumCases * 100 >= Range * MinDensity; 5898 } 5899 5900 /// Try to transform a switch that has "holes" in it to a contiguous sequence 5901 /// of cases. 5902 /// 5903 /// A switch such as: switch(i) {case 5: case 9: case 13: case 17:} can be 5904 /// range-reduced to: switch ((i-5) / 4) {case 0: case 1: case 2: case 3:}. 5905 /// 5906 /// This converts a sparse switch into a dense switch which allows better 5907 /// lowering and could also allow transforming into a lookup table. 5908 static bool ReduceSwitchRange(SwitchInst *SI, IRBuilder<> &Builder, 5909 const DataLayout &DL, 5910 const TargetTransformInfo &TTI) { 5911 auto *CondTy = cast<IntegerType>(SI->getCondition()->getType()); 5912 if (CondTy->getIntegerBitWidth() > 64 || 5913 !DL.fitsInLegalInteger(CondTy->getIntegerBitWidth())) 5914 return false; 5915 // Only bother with this optimization if there are more than 3 switch cases; 5916 // SDAG will only bother creating jump tables for 4 or more cases. 5917 if (SI->getNumCases() < 4) 5918 return false; 5919 5920 // This transform is agnostic to the signedness of the input or case values. We 5921 // can treat the case values as signed or unsigned. We can optimize more common 5922 // cases such as a sequence crossing zero {-4,0,4,8} if we interpret case values 5923 // as signed. 5924 SmallVector<int64_t,4> Values; 5925 for (auto &C : SI->cases()) 5926 Values.push_back(C.getCaseValue()->getValue().getSExtValue()); 5927 llvm::sort(Values); 5928 5929 // If the switch is already dense, there's nothing useful to do here. 5930 if (isSwitchDense(Values)) 5931 return false; 5932 5933 // First, transform the values such that they start at zero and ascend. 5934 int64_t Base = Values[0]; 5935 for (auto &V : Values) 5936 V -= (uint64_t)(Base); 5937 5938 // Now we have signed numbers that have been shifted so that, given enough 5939 // precision, there are no negative values. Since the rest of the transform 5940 // is bitwise only, we switch now to an unsigned representation. 5941 5942 // This transform can be done speculatively because it is so cheap - it 5943 // results in a single rotate operation being inserted. 5944 // FIXME: It's possible that optimizing a switch on powers of two might also 5945 // be beneficial - flag values are often powers of two and we could use a CLZ 5946 // as the key function. 5947 5948 // countTrailingZeros(0) returns 64. As Values is guaranteed to have more than 5949 // one element and LLVM disallows duplicate cases, Shift is guaranteed to be 5950 // less than 64. 5951 unsigned Shift = 64; 5952 for (auto &V : Values) 5953 Shift = std::min(Shift, countTrailingZeros((uint64_t)V)); 5954 assert(Shift < 64); 5955 if (Shift > 0) 5956 for (auto &V : Values) 5957 V = (int64_t)((uint64_t)V >> Shift); 5958 5959 if (!isSwitchDense(Values)) 5960 // Transform didn't create a dense switch. 5961 return false; 5962 5963 // The obvious transform is to shift the switch condition right and emit a 5964 // check that the condition actually cleanly divided by GCD, i.e. 5965 // C & (1 << Shift - 1) == 0 5966 // inserting a new CFG edge to handle the case where it didn't divide cleanly. 5967 // 5968 // A cheaper way of doing this is a simple ROTR(C, Shift). This performs the 5969 // shift and puts the shifted-off bits in the uppermost bits. If any of these 5970 // are nonzero then the switch condition will be very large and will hit the 5971 // default case. 5972 5973 auto *Ty = cast<IntegerType>(SI->getCondition()->getType()); 5974 Builder.SetInsertPoint(SI); 5975 auto *ShiftC = ConstantInt::get(Ty, Shift); 5976 auto *Sub = Builder.CreateSub(SI->getCondition(), ConstantInt::get(Ty, Base)); 5977 auto *LShr = Builder.CreateLShr(Sub, ShiftC); 5978 auto *Shl = Builder.CreateShl(Sub, Ty->getBitWidth() - Shift); 5979 auto *Rot = Builder.CreateOr(LShr, Shl); 5980 SI->replaceUsesOfWith(SI->getCondition(), Rot); 5981 5982 for (auto Case : SI->cases()) { 5983 auto *Orig = Case.getCaseValue(); 5984 auto Sub = Orig->getValue() - APInt(Ty->getBitWidth(), Base); 5985 Case.setValue( 5986 cast<ConstantInt>(ConstantInt::get(Ty, Sub.lshr(ShiftC->getValue())))); 5987 } 5988 return true; 5989 } 5990 5991 bool SimplifyCFGOpt::simplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) { 5992 BasicBlock *BB = SI->getParent(); 5993 5994 if (isValueEqualityComparison(SI)) { 5995 // If we only have one predecessor, and if it is a branch on this value, 5996 // see if that predecessor totally determines the outcome of this switch. 5997 if (BasicBlock *OnlyPred = BB->getSinglePredecessor()) 5998 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder)) 5999 return requestResimplify(); 6000 6001 Value *Cond = SI->getCondition(); 6002 if (SelectInst *Select = dyn_cast<SelectInst>(Cond)) 6003 if (SimplifySwitchOnSelect(SI, Select)) 6004 return requestResimplify(); 6005 6006 // If the block only contains the switch, see if we can fold the block 6007 // away into any preds. 6008 if (SI == &*BB->instructionsWithoutDebug().begin()) 6009 if (FoldValueComparisonIntoPredecessors(SI, Builder)) 6010 return requestResimplify(); 6011 } 6012 6013 // Try to transform the switch into an icmp and a branch. 6014 if (TurnSwitchRangeIntoICmp(SI, Builder)) 6015 return requestResimplify(); 6016 6017 // Remove unreachable cases. 6018 if (eliminateDeadSwitchCases(SI, Options.AC, DL)) 6019 return requestResimplify(); 6020 6021 if (switchToSelect(SI, Builder, DL, TTI)) 6022 return requestResimplify(); 6023 6024 if (Options.ForwardSwitchCondToPhi && ForwardSwitchConditionToPHI(SI)) 6025 return requestResimplify(); 6026 6027 // The conversion from switch to lookup tables results in difficult-to-analyze 6028 // code and makes pruning branches much harder. This is a problem if the 6029 // switch expression itself can still be restricted as a result of inlining or 6030 // CVP. Therefore, only apply this transformation during late stages of the 6031 // optimisation pipeline. 6032 if (Options.ConvertSwitchToLookupTable && 6033 SwitchToLookupTable(SI, Builder, DL, TTI)) 6034 return requestResimplify(); 6035 6036 if (ReduceSwitchRange(SI, Builder, DL, TTI)) 6037 return requestResimplify(); 6038 6039 return false; 6040 } 6041 6042 bool SimplifyCFGOpt::simplifyIndirectBr(IndirectBrInst *IBI) { 6043 BasicBlock *BB = IBI->getParent(); 6044 bool Changed = false; 6045 6046 // Eliminate redundant destinations. 6047 SmallPtrSet<Value *, 8> Succs; 6048 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) { 6049 BasicBlock *Dest = IBI->getDestination(i); 6050 if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) { 6051 Dest->removePredecessor(BB); 6052 IBI->removeDestination(i); 6053 --i; 6054 --e; 6055 Changed = true; 6056 } 6057 } 6058 6059 if (IBI->getNumDestinations() == 0) { 6060 // If the indirectbr has no successors, change it to unreachable. 6061 new UnreachableInst(IBI->getContext(), IBI); 6062 EraseTerminatorAndDCECond(IBI); 6063 return true; 6064 } 6065 6066 if (IBI->getNumDestinations() == 1) { 6067 // If the indirectbr has one successor, change it to a direct branch. 6068 BranchInst::Create(IBI->getDestination(0), IBI); 6069 EraseTerminatorAndDCECond(IBI); 6070 return true; 6071 } 6072 6073 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) { 6074 if (SimplifyIndirectBrOnSelect(IBI, SI)) 6075 return requestResimplify(); 6076 } 6077 return Changed; 6078 } 6079 6080 /// Given an block with only a single landing pad and a unconditional branch 6081 /// try to find another basic block which this one can be merged with. This 6082 /// handles cases where we have multiple invokes with unique landing pads, but 6083 /// a shared handler. 6084 /// 6085 /// We specifically choose to not worry about merging non-empty blocks 6086 /// here. That is a PRE/scheduling problem and is best solved elsewhere. In 6087 /// practice, the optimizer produces empty landing pad blocks quite frequently 6088 /// when dealing with exception dense code. (see: instcombine, gvn, if-else 6089 /// sinking in this file) 6090 /// 6091 /// This is primarily a code size optimization. We need to avoid performing 6092 /// any transform which might inhibit optimization (such as our ability to 6093 /// specialize a particular handler via tail commoning). We do this by not 6094 /// merging any blocks which require us to introduce a phi. Since the same 6095 /// values are flowing through both blocks, we don't lose any ability to 6096 /// specialize. If anything, we make such specialization more likely. 6097 /// 6098 /// TODO - This transformation could remove entries from a phi in the target 6099 /// block when the inputs in the phi are the same for the two blocks being 6100 /// merged. In some cases, this could result in removal of the PHI entirely. 6101 static bool TryToMergeLandingPad(LandingPadInst *LPad, BranchInst *BI, 6102 BasicBlock *BB, DomTreeUpdater *DTU) { 6103 auto Succ = BB->getUniqueSuccessor(); 6104 assert(Succ); 6105 // If there's a phi in the successor block, we'd likely have to introduce 6106 // a phi into the merged landing pad block. 6107 if (isa<PHINode>(*Succ->begin())) 6108 return false; 6109 6110 for (BasicBlock *OtherPred : predecessors(Succ)) { 6111 if (BB == OtherPred) 6112 continue; 6113 BasicBlock::iterator I = OtherPred->begin(); 6114 LandingPadInst *LPad2 = dyn_cast<LandingPadInst>(I); 6115 if (!LPad2 || !LPad2->isIdenticalTo(LPad)) 6116 continue; 6117 for (++I; isa<DbgInfoIntrinsic>(I); ++I) 6118 ; 6119 BranchInst *BI2 = dyn_cast<BranchInst>(I); 6120 if (!BI2 || !BI2->isIdenticalTo(BI)) 6121 continue; 6122 6123 std::vector<DominatorTree::UpdateType> Updates; 6124 6125 // We've found an identical block. Update our predecessors to take that 6126 // path instead and make ourselves dead. 6127 SmallPtrSet<BasicBlock *, 16> Preds; 6128 Preds.insert(pred_begin(BB), pred_end(BB)); 6129 for (BasicBlock *Pred : Preds) { 6130 InvokeInst *II = cast<InvokeInst>(Pred->getTerminator()); 6131 assert(II->getNormalDest() != BB && II->getUnwindDest() == BB && 6132 "unexpected successor"); 6133 II->setUnwindDest(OtherPred); 6134 Updates.push_back({DominatorTree::Delete, Pred, BB}); 6135 Updates.push_back({DominatorTree::Insert, Pred, OtherPred}); 6136 } 6137 6138 // The debug info in OtherPred doesn't cover the merged control flow that 6139 // used to go through BB. We need to delete it or update it. 6140 for (auto I = OtherPred->begin(), E = OtherPred->end(); I != E;) { 6141 Instruction &Inst = *I; 6142 I++; 6143 if (isa<DbgInfoIntrinsic>(Inst)) 6144 Inst.eraseFromParent(); 6145 } 6146 6147 SmallPtrSet<BasicBlock *, 16> Succs; 6148 Succs.insert(succ_begin(BB), succ_end(BB)); 6149 for (BasicBlock *Succ : Succs) { 6150 Succ->removePredecessor(BB); 6151 Updates.push_back({DominatorTree::Delete, BB, Succ}); 6152 } 6153 6154 IRBuilder<> Builder(BI); 6155 Builder.CreateUnreachable(); 6156 BI->eraseFromParent(); 6157 if (DTU) 6158 DTU->applyUpdatesPermissive(Updates); 6159 return true; 6160 } 6161 return false; 6162 } 6163 6164 bool SimplifyCFGOpt::simplifyBranch(BranchInst *Branch, IRBuilder<> &Builder) { 6165 return Branch->isUnconditional() ? simplifyUncondBranch(Branch, Builder) 6166 : simplifyCondBranch(Branch, Builder); 6167 } 6168 6169 bool SimplifyCFGOpt::simplifyUncondBranch(BranchInst *BI, 6170 IRBuilder<> &Builder) { 6171 BasicBlock *BB = BI->getParent(); 6172 BasicBlock *Succ = BI->getSuccessor(0); 6173 6174 // If the Terminator is the only non-phi instruction, simplify the block. 6175 // If LoopHeader is provided, check if the block or its successor is a loop 6176 // header. (This is for early invocations before loop simplify and 6177 // vectorization to keep canonical loop forms for nested loops. These blocks 6178 // can be eliminated when the pass is invoked later in the back-end.) 6179 // Note that if BB has only one predecessor then we do not introduce new 6180 // backedge, so we can eliminate BB. 6181 bool NeedCanonicalLoop = 6182 Options.NeedCanonicalLoop && 6183 (LoopHeaders && BB->hasNPredecessorsOrMore(2) && 6184 (LoopHeaders->count(BB) || LoopHeaders->count(Succ))); 6185 BasicBlock::iterator I = BB->getFirstNonPHIOrDbg()->getIterator(); 6186 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() && 6187 !NeedCanonicalLoop && TryToSimplifyUncondBranchFromEmptyBlock(BB, DTU)) 6188 return true; 6189 6190 // If the only instruction in the block is a seteq/setne comparison against a 6191 // constant, try to simplify the block. 6192 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) 6193 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) { 6194 for (++I; isa<DbgInfoIntrinsic>(I); ++I) 6195 ; 6196 if (I->isTerminator() && 6197 tryToSimplifyUncondBranchWithICmpInIt(ICI, Builder)) 6198 return true; 6199 } 6200 6201 // See if we can merge an empty landing pad block with another which is 6202 // equivalent. 6203 if (LandingPadInst *LPad = dyn_cast<LandingPadInst>(I)) { 6204 for (++I; isa<DbgInfoIntrinsic>(I); ++I) 6205 ; 6206 if (I->isTerminator() && TryToMergeLandingPad(LPad, BI, BB, DTU)) 6207 return true; 6208 } 6209 6210 // If this basic block is ONLY a compare and a branch, and if a predecessor 6211 // branches to us and our successor, fold the comparison into the 6212 // predecessor and use logical operations to update the incoming value 6213 // for PHI nodes in common successor. 6214 if (FoldBranchToCommonDest(BI, DTU, /*MSSAU=*/nullptr, &TTI, 6215 Options.BonusInstThreshold)) 6216 return requestResimplify(); 6217 return false; 6218 } 6219 6220 static BasicBlock *allPredecessorsComeFromSameSource(BasicBlock *BB) { 6221 BasicBlock *PredPred = nullptr; 6222 for (auto *P : predecessors(BB)) { 6223 BasicBlock *PPred = P->getSinglePredecessor(); 6224 if (!PPred || (PredPred && PredPred != PPred)) 6225 return nullptr; 6226 PredPred = PPred; 6227 } 6228 return PredPred; 6229 } 6230 6231 bool SimplifyCFGOpt::simplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) { 6232 BasicBlock *BB = BI->getParent(); 6233 if (!Options.SimplifyCondBranch) 6234 return false; 6235 6236 // Conditional branch 6237 if (isValueEqualityComparison(BI)) { 6238 // If we only have one predecessor, and if it is a branch on this value, 6239 // see if that predecessor totally determines the outcome of this 6240 // switch. 6241 if (BasicBlock *OnlyPred = BB->getSinglePredecessor()) 6242 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder)) 6243 return requestResimplify(); 6244 6245 // This block must be empty, except for the setcond inst, if it exists. 6246 // Ignore dbg intrinsics. 6247 auto I = BB->instructionsWithoutDebug().begin(); 6248 if (&*I == BI) { 6249 if (FoldValueComparisonIntoPredecessors(BI, Builder)) 6250 return requestResimplify(); 6251 } else if (&*I == cast<Instruction>(BI->getCondition())) { 6252 ++I; 6253 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder)) 6254 return requestResimplify(); 6255 } 6256 } 6257 6258 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction. 6259 if (SimplifyBranchOnICmpChain(BI, Builder, DL)) 6260 return true; 6261 6262 // If this basic block has dominating predecessor blocks and the dominating 6263 // blocks' conditions imply BI's condition, we know the direction of BI. 6264 Optional<bool> Imp = isImpliedByDomCondition(BI->getCondition(), BI, DL); 6265 if (Imp) { 6266 // Turn this into a branch on constant. 6267 auto *OldCond = BI->getCondition(); 6268 ConstantInt *TorF = *Imp ? ConstantInt::getTrue(BB->getContext()) 6269 : ConstantInt::getFalse(BB->getContext()); 6270 BI->setCondition(TorF); 6271 RecursivelyDeleteTriviallyDeadInstructions(OldCond); 6272 return requestResimplify(); 6273 } 6274 6275 // If this basic block is ONLY a compare and a branch, and if a predecessor 6276 // branches to us and one of our successors, fold the comparison into the 6277 // predecessor and use logical operations to pick the right destination. 6278 if (FoldBranchToCommonDest(BI, DTU, /*MSSAU=*/nullptr, &TTI, 6279 Options.BonusInstThreshold)) 6280 return requestResimplify(); 6281 6282 // We have a conditional branch to two blocks that are only reachable 6283 // from BI. We know that the condbr dominates the two blocks, so see if 6284 // there is any identical code in the "then" and "else" blocks. If so, we 6285 // can hoist it up to the branching block. 6286 if (BI->getSuccessor(0)->getSinglePredecessor()) { 6287 if (BI->getSuccessor(1)->getSinglePredecessor()) { 6288 if (HoistCommon && Options.HoistCommonInsts) 6289 if (HoistThenElseCodeToIf(BI, TTI)) 6290 return requestResimplify(); 6291 } else { 6292 // If Successor #1 has multiple preds, we may be able to conditionally 6293 // execute Successor #0 if it branches to Successor #1. 6294 Instruction *Succ0TI = BI->getSuccessor(0)->getTerminator(); 6295 if (Succ0TI->getNumSuccessors() == 1 && 6296 Succ0TI->getSuccessor(0) == BI->getSuccessor(1)) 6297 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), TTI)) 6298 return requestResimplify(); 6299 } 6300 } else if (BI->getSuccessor(1)->getSinglePredecessor()) { 6301 // If Successor #0 has multiple preds, we may be able to conditionally 6302 // execute Successor #1 if it branches to Successor #0. 6303 Instruction *Succ1TI = BI->getSuccessor(1)->getTerminator(); 6304 if (Succ1TI->getNumSuccessors() == 1 && 6305 Succ1TI->getSuccessor(0) == BI->getSuccessor(0)) 6306 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), TTI)) 6307 return requestResimplify(); 6308 } 6309 6310 // If this is a branch on a phi node in the current block, thread control 6311 // through this block if any PHI node entries are constants. 6312 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition())) 6313 if (PN->getParent() == BI->getParent()) 6314 if (FoldCondBranchOnPHI(BI, DL, Options.AC)) 6315 return requestResimplify(); 6316 6317 // Scan predecessor blocks for conditional branches. 6318 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) 6319 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator())) 6320 if (PBI != BI && PBI->isConditional()) 6321 if (SimplifyCondBranchToCondBranch(PBI, BI, DL, TTI)) 6322 return requestResimplify(); 6323 6324 // Look for diamond patterns. 6325 if (MergeCondStores) 6326 if (BasicBlock *PrevBB = allPredecessorsComeFromSameSource(BB)) 6327 if (BranchInst *PBI = dyn_cast<BranchInst>(PrevBB->getTerminator())) 6328 if (PBI != BI && PBI->isConditional()) 6329 if (mergeConditionalStores(PBI, BI, DL, TTI)) 6330 return requestResimplify(); 6331 6332 return false; 6333 } 6334 6335 /// Check if passing a value to an instruction will cause undefined behavior. 6336 static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) { 6337 Constant *C = dyn_cast<Constant>(V); 6338 if (!C) 6339 return false; 6340 6341 if (I->use_empty()) 6342 return false; 6343 6344 if (C->isNullValue() || isa<UndefValue>(C)) { 6345 // Only look at the first use, avoid hurting compile time with long uselists 6346 User *Use = *I->user_begin(); 6347 6348 // Now make sure that there are no instructions in between that can alter 6349 // control flow (eg. calls) 6350 for (BasicBlock::iterator 6351 i = ++BasicBlock::iterator(I), 6352 UI = BasicBlock::iterator(dyn_cast<Instruction>(Use)); 6353 i != UI; ++i) 6354 if (i == I->getParent()->end() || i->mayHaveSideEffects()) 6355 return false; 6356 6357 // Look through GEPs. A load from a GEP derived from NULL is still undefined 6358 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use)) 6359 if (GEP->getPointerOperand() == I) 6360 return passingValueIsAlwaysUndefined(V, GEP); 6361 6362 // Look through bitcasts. 6363 if (BitCastInst *BC = dyn_cast<BitCastInst>(Use)) 6364 return passingValueIsAlwaysUndefined(V, BC); 6365 6366 // Load from null is undefined. 6367 if (LoadInst *LI = dyn_cast<LoadInst>(Use)) 6368 if (!LI->isVolatile()) 6369 return !NullPointerIsDefined(LI->getFunction(), 6370 LI->getPointerAddressSpace()); 6371 6372 // Store to null is undefined. 6373 if (StoreInst *SI = dyn_cast<StoreInst>(Use)) 6374 if (!SI->isVolatile()) 6375 return (!NullPointerIsDefined(SI->getFunction(), 6376 SI->getPointerAddressSpace())) && 6377 SI->getPointerOperand() == I; 6378 6379 // A call to null is undefined. 6380 if (auto *CB = dyn_cast<CallBase>(Use)) 6381 return !NullPointerIsDefined(CB->getFunction()) && 6382 CB->getCalledOperand() == I; 6383 } 6384 return false; 6385 } 6386 6387 /// If BB has an incoming value that will always trigger undefined behavior 6388 /// (eg. null pointer dereference), remove the branch leading here. 6389 static bool removeUndefIntroducingPredecessor(BasicBlock *BB) { 6390 for (PHINode &PHI : BB->phis()) 6391 for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) 6392 if (passingValueIsAlwaysUndefined(PHI.getIncomingValue(i), &PHI)) { 6393 Instruction *T = PHI.getIncomingBlock(i)->getTerminator(); 6394 IRBuilder<> Builder(T); 6395 if (BranchInst *BI = dyn_cast<BranchInst>(T)) { 6396 BB->removePredecessor(PHI.getIncomingBlock(i)); 6397 // Turn uncoditional branches into unreachables and remove the dead 6398 // destination from conditional branches. 6399 if (BI->isUnconditional()) 6400 Builder.CreateUnreachable(); 6401 else 6402 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) 6403 : BI->getSuccessor(0)); 6404 BI->eraseFromParent(); 6405 return true; 6406 } 6407 // TODO: SwitchInst. 6408 } 6409 6410 return false; 6411 } 6412 6413 bool SimplifyCFGOpt::simplifyOnceImpl(BasicBlock *BB) { 6414 bool Changed = false; 6415 6416 assert(BB && BB->getParent() && "Block not embedded in function!"); 6417 assert(BB->getTerminator() && "Degenerate basic block encountered!"); 6418 6419 // Remove basic blocks that have no predecessors (except the entry block)... 6420 // or that just have themself as a predecessor. These are unreachable. 6421 if ((pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) || 6422 BB->getSinglePredecessor() == BB) { 6423 LLVM_DEBUG(dbgs() << "Removing BB: \n" << *BB); 6424 DeleteDeadBlock(BB, DTU); 6425 return true; 6426 } 6427 6428 // Check to see if we can constant propagate this terminator instruction 6429 // away... 6430 Changed |= ConstantFoldTerminator(BB, /*DeleteDeadConditions=*/true, 6431 /*TLI=*/nullptr, DTU); 6432 6433 // Check for and eliminate duplicate PHI nodes in this block. 6434 Changed |= EliminateDuplicatePHINodes(BB); 6435 6436 // Check for and remove branches that will always cause undefined behavior. 6437 Changed |= removeUndefIntroducingPredecessor(BB); 6438 6439 // Merge basic blocks into their predecessor if there is only one distinct 6440 // pred, and if there is only one distinct successor of the predecessor, and 6441 // if there are no PHI nodes. 6442 if (MergeBlockIntoPredecessor(BB, DTU)) 6443 return true; 6444 6445 if (SinkCommon && Options.SinkCommonInsts) 6446 Changed |= SinkCommonCodeFromPredecessors(BB); 6447 6448 IRBuilder<> Builder(BB); 6449 6450 if (Options.FoldTwoEntryPHINode) { 6451 // If there is a trivial two-entry PHI node in this basic block, and we can 6452 // eliminate it, do so now. 6453 if (auto *PN = dyn_cast<PHINode>(BB->begin())) 6454 if (PN->getNumIncomingValues() == 2) 6455 Changed |= FoldTwoEntryPHINode(PN, TTI, DTU, DL); 6456 } 6457 6458 Instruction *Terminator = BB->getTerminator(); 6459 Builder.SetInsertPoint(Terminator); 6460 switch (Terminator->getOpcode()) { 6461 case Instruction::Br: 6462 Changed |= simplifyBranch(cast<BranchInst>(Terminator), Builder); 6463 break; 6464 case Instruction::Ret: 6465 Changed |= simplifyReturn(cast<ReturnInst>(Terminator), Builder); 6466 break; 6467 case Instruction::Resume: 6468 Changed |= simplifyResume(cast<ResumeInst>(Terminator), Builder); 6469 break; 6470 case Instruction::CleanupRet: 6471 Changed |= simplifyCleanupReturn(cast<CleanupReturnInst>(Terminator)); 6472 break; 6473 case Instruction::Switch: 6474 Changed |= simplifySwitch(cast<SwitchInst>(Terminator), Builder); 6475 break; 6476 case Instruction::Unreachable: 6477 Changed |= simplifyUnreachable(cast<UnreachableInst>(Terminator)); 6478 break; 6479 case Instruction::IndirectBr: 6480 Changed |= simplifyIndirectBr(cast<IndirectBrInst>(Terminator)); 6481 break; 6482 } 6483 6484 return Changed; 6485 } 6486 6487 bool SimplifyCFGOpt::simplifyOnce(BasicBlock *BB) { 6488 assert((!RequireAndPreserveDomTree || 6489 (DTU && 6490 DTU->getDomTree().verify(DominatorTree::VerificationLevel::Full))) && 6491 "Original domtree is invalid?"); 6492 6493 bool Changed = simplifyOnceImpl(BB); 6494 6495 assert((!RequireAndPreserveDomTree || 6496 (DTU && 6497 DTU->getDomTree().verify(DominatorTree::VerificationLevel::Full))) && 6498 "Failed to maintain validity of domtree!"); 6499 6500 return Changed; 6501 } 6502 6503 bool SimplifyCFGOpt::run(BasicBlock *BB) { 6504 bool Changed = false; 6505 6506 // Repeated simplify BB as long as resimplification is requested. 6507 do { 6508 Resimplify = false; 6509 6510 // Perform one round of simplifcation. Resimplify flag will be set if 6511 // another iteration is requested. 6512 Changed |= simplifyOnce(BB); 6513 } while (Resimplify); 6514 6515 return Changed; 6516 } 6517 6518 bool llvm::simplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI, 6519 DomTreeUpdater *DTU, const SimplifyCFGOptions &Options, 6520 SmallPtrSetImpl<BasicBlock *> *LoopHeaders) { 6521 return SimplifyCFGOpt(TTI, DTU, BB->getModule()->getDataLayout(), LoopHeaders, 6522 Options) 6523 .run(BB); 6524 } 6525