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