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