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