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