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