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