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