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