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