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 // We will delete Phis while threading, so Phis should not be accounted in 2237 // block's size 2238 if (!isa<PHINode>(I)) 2239 ++Size; 2240 2241 // We can only support instructions that do not define values that are 2242 // live outside of the current basic block. 2243 for (User *U : I.users()) { 2244 Instruction *UI = cast<Instruction>(U); 2245 if (UI->getParent() != BB || isa<PHINode>(UI)) 2246 return false; 2247 } 2248 2249 // Looks ok, continue checking. 2250 } 2251 2252 return true; 2253 } 2254 2255 /// If we have a conditional branch on a PHI node value that is defined in the 2256 /// same block as the branch and if any PHI entries are constants, thread edges 2257 /// corresponding to that entry to be branches to their ultimate destination. 2258 static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout &DL, 2259 AssumptionCache *AC) { 2260 BasicBlock *BB = BI->getParent(); 2261 PHINode *PN = dyn_cast<PHINode>(BI->getCondition()); 2262 // NOTE: we currently cannot transform this case if the PHI node is used 2263 // outside of the block. 2264 if (!PN || PN->getParent() != BB || !PN->hasOneUse()) 2265 return false; 2266 2267 // Degenerate case of a single entry PHI. 2268 if (PN->getNumIncomingValues() == 1) { 2269 FoldSingleEntryPHINodes(PN->getParent()); 2270 return true; 2271 } 2272 2273 // Now we know that this block has multiple preds and two succs. 2274 if (!BlockIsSimpleEnoughToThreadThrough(BB)) 2275 return false; 2276 2277 // Can't fold blocks that contain noduplicate or convergent calls. 2278 if (any_of(*BB, [](const Instruction &I) { 2279 const CallInst *CI = dyn_cast<CallInst>(&I); 2280 return CI && (CI->cannotDuplicate() || CI->isConvergent()); 2281 })) 2282 return false; 2283 2284 // Okay, this is a simple enough basic block. See if any phi values are 2285 // constants. 2286 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 2287 ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i)); 2288 if (!CB || !CB->getType()->isIntegerTy(1)) 2289 continue; 2290 2291 // Okay, we now know that all edges from PredBB should be revectored to 2292 // branch to RealDest. 2293 BasicBlock *PredBB = PN->getIncomingBlock(i); 2294 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue()); 2295 2296 if (RealDest == BB) 2297 continue; // Skip self loops. 2298 // Skip if the predecessor's terminator is an indirect branch. 2299 if (isa<IndirectBrInst>(PredBB->getTerminator())) 2300 continue; 2301 2302 // The dest block might have PHI nodes, other predecessors and other 2303 // difficult cases. Instead of being smart about this, just insert a new 2304 // block that jumps to the destination block, effectively splitting 2305 // the edge we are about to create. 2306 BasicBlock *EdgeBB = 2307 BasicBlock::Create(BB->getContext(), RealDest->getName() + ".critedge", 2308 RealDest->getParent(), RealDest); 2309 BranchInst *CritEdgeBranch = BranchInst::Create(RealDest, EdgeBB); 2310 CritEdgeBranch->setDebugLoc(BI->getDebugLoc()); 2311 2312 // Update PHI nodes. 2313 AddPredecessorToBlock(RealDest, EdgeBB, BB); 2314 2315 // BB may have instructions that are being threaded over. Clone these 2316 // instructions into EdgeBB. We know that there will be no uses of the 2317 // cloned instructions outside of EdgeBB. 2318 BasicBlock::iterator InsertPt = EdgeBB->begin(); 2319 DenseMap<Value *, Value *> TranslateMap; // Track translated values. 2320 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) { 2321 if (PHINode *PN = dyn_cast<PHINode>(BBI)) { 2322 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB); 2323 continue; 2324 } 2325 // Clone the instruction. 2326 Instruction *N = BBI->clone(); 2327 if (BBI->hasName()) 2328 N->setName(BBI->getName() + ".c"); 2329 2330 // Update operands due to translation. 2331 for (User::op_iterator i = N->op_begin(), e = N->op_end(); i != e; ++i) { 2332 DenseMap<Value *, Value *>::iterator PI = TranslateMap.find(*i); 2333 if (PI != TranslateMap.end()) 2334 *i = PI->second; 2335 } 2336 2337 // Check for trivial simplification. 2338 if (Value *V = SimplifyInstruction(N, {DL, nullptr, nullptr, AC})) { 2339 if (!BBI->use_empty()) 2340 TranslateMap[&*BBI] = V; 2341 if (!N->mayHaveSideEffects()) { 2342 N->deleteValue(); // Instruction folded away, don't need actual inst 2343 N = nullptr; 2344 } 2345 } else { 2346 if (!BBI->use_empty()) 2347 TranslateMap[&*BBI] = N; 2348 } 2349 if (N) { 2350 // Insert the new instruction into its new home. 2351 EdgeBB->getInstList().insert(InsertPt, N); 2352 2353 // Register the new instruction with the assumption cache if necessary. 2354 if (AC && match(N, m_Intrinsic<Intrinsic::assume>())) 2355 AC->registerAssumption(cast<IntrinsicInst>(N)); 2356 } 2357 } 2358 2359 // Loop over all of the edges from PredBB to BB, changing them to branch 2360 // to EdgeBB instead. 2361 Instruction *PredBBTI = PredBB->getTerminator(); 2362 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i) 2363 if (PredBBTI->getSuccessor(i) == BB) { 2364 BB->removePredecessor(PredBB); 2365 PredBBTI->setSuccessor(i, EdgeBB); 2366 } 2367 2368 // Recurse, simplifying any other constants. 2369 return FoldCondBranchOnPHI(BI, DL, AC) || true; 2370 } 2371 2372 return false; 2373 } 2374 2375 /// Given a BB that starts with the specified two-entry PHI node, 2376 /// see if we can eliminate it. 2377 static bool FoldTwoEntryPHINode(PHINode *PN, const TargetTransformInfo &TTI, 2378 const DataLayout &DL) { 2379 // Ok, this is a two entry PHI node. Check to see if this is a simple "if 2380 // statement", which has a very simple dominance structure. Basically, we 2381 // are trying to find the condition that is being branched on, which 2382 // subsequently causes this merge to happen. We really want control 2383 // dependence information for this check, but simplifycfg can't keep it up 2384 // to date, and this catches most of the cases we care about anyway. 2385 BasicBlock *BB = PN->getParent(); 2386 2387 BasicBlock *IfTrue, *IfFalse; 2388 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse); 2389 if (!IfCond || 2390 // Don't bother if the branch will be constant folded trivially. 2391 isa<ConstantInt>(IfCond)) 2392 return false; 2393 2394 // Okay, we found that we can merge this two-entry phi node into a select. 2395 // Doing so would require us to fold *all* two entry phi nodes in this block. 2396 // At some point this becomes non-profitable (particularly if the target 2397 // doesn't support cmov's). Only do this transformation if there are two or 2398 // fewer PHI nodes in this block. 2399 unsigned NumPhis = 0; 2400 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I) 2401 if (NumPhis > 2) 2402 return false; 2403 2404 // Loop over the PHI's seeing if we can promote them all to select 2405 // instructions. While we are at it, keep track of the instructions 2406 // that need to be moved to the dominating block. 2407 SmallPtrSet<Instruction *, 4> AggressiveInsts; 2408 int BudgetRemaining = 2409 TwoEntryPHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic; 2410 2411 bool Changed = false; 2412 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) { 2413 PHINode *PN = cast<PHINode>(II++); 2414 if (Value *V = SimplifyInstruction(PN, {DL, PN})) { 2415 PN->replaceAllUsesWith(V); 2416 PN->eraseFromParent(); 2417 Changed = true; 2418 continue; 2419 } 2420 2421 if (!DominatesMergePoint(PN->getIncomingValue(0), BB, AggressiveInsts, 2422 BudgetRemaining, TTI) || 2423 !DominatesMergePoint(PN->getIncomingValue(1), BB, AggressiveInsts, 2424 BudgetRemaining, TTI)) 2425 return Changed; 2426 } 2427 2428 // If we folded the first phi, PN dangles at this point. Refresh it. If 2429 // we ran out of PHIs then we simplified them all. 2430 PN = dyn_cast<PHINode>(BB->begin()); 2431 if (!PN) 2432 return true; 2433 2434 // Return true if at least one of these is a 'not', and another is either 2435 // a 'not' too, or a constant. 2436 auto CanHoistNotFromBothValues = [](Value *V0, Value *V1) { 2437 if (!match(V0, m_Not(m_Value()))) 2438 std::swap(V0, V1); 2439 auto Invertible = m_CombineOr(m_Not(m_Value()), m_AnyIntegralConstant()); 2440 return match(V0, m_Not(m_Value())) && match(V1, Invertible); 2441 }; 2442 2443 // Don't fold i1 branches on PHIs which contain binary operators, unless one 2444 // of the incoming values is an 'not' and another one is freely invertible. 2445 // These can often be turned into switches and other things. 2446 if (PN->getType()->isIntegerTy(1) && 2447 (isa<BinaryOperator>(PN->getIncomingValue(0)) || 2448 isa<BinaryOperator>(PN->getIncomingValue(1)) || 2449 isa<BinaryOperator>(IfCond)) && 2450 !CanHoistNotFromBothValues(PN->getIncomingValue(0), 2451 PN->getIncomingValue(1))) 2452 return Changed; 2453 2454 // If all PHI nodes are promotable, check to make sure that all instructions 2455 // in the predecessor blocks can be promoted as well. If not, we won't be able 2456 // to get rid of the control flow, so it's not worth promoting to select 2457 // instructions. 2458 BasicBlock *DomBlock = nullptr; 2459 BasicBlock *IfBlock1 = PN->getIncomingBlock(0); 2460 BasicBlock *IfBlock2 = PN->getIncomingBlock(1); 2461 if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) { 2462 IfBlock1 = nullptr; 2463 } else { 2464 DomBlock = *pred_begin(IfBlock1); 2465 for (BasicBlock::iterator I = IfBlock1->begin(); !I->isTerminator(); ++I) 2466 if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) { 2467 // This is not an aggressive instruction that we can promote. 2468 // Because of this, we won't be able to get rid of the control flow, so 2469 // the xform is not worth it. 2470 return Changed; 2471 } 2472 } 2473 2474 if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) { 2475 IfBlock2 = nullptr; 2476 } else { 2477 DomBlock = *pred_begin(IfBlock2); 2478 for (BasicBlock::iterator I = IfBlock2->begin(); !I->isTerminator(); ++I) 2479 if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) { 2480 // This is not an aggressive instruction that we can promote. 2481 // Because of this, we won't be able to get rid of the control flow, so 2482 // the xform is not worth it. 2483 return Changed; 2484 } 2485 } 2486 assert(DomBlock && "Failed to find root DomBlock"); 2487 2488 LLVM_DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond 2489 << " T: " << IfTrue->getName() 2490 << " F: " << IfFalse->getName() << "\n"); 2491 2492 // If we can still promote the PHI nodes after this gauntlet of tests, 2493 // do all of the PHI's now. 2494 Instruction *InsertPt = DomBlock->getTerminator(); 2495 IRBuilder<NoFolder> Builder(InsertPt); 2496 2497 // Move all 'aggressive' instructions, which are defined in the 2498 // conditional parts of the if's up to the dominating block. 2499 if (IfBlock1) 2500 hoistAllInstructionsInto(DomBlock, InsertPt, IfBlock1); 2501 if (IfBlock2) 2502 hoistAllInstructionsInto(DomBlock, InsertPt, IfBlock2); 2503 2504 // Propagate fast-math-flags from phi nodes to replacement selects. 2505 IRBuilder<>::FastMathFlagGuard FMFGuard(Builder); 2506 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) { 2507 if (isa<FPMathOperator>(PN)) 2508 Builder.setFastMathFlags(PN->getFastMathFlags()); 2509 2510 // Change the PHI node into a select instruction. 2511 Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse); 2512 Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue); 2513 2514 Value *Sel = Builder.CreateSelect(IfCond, TrueVal, FalseVal, "", InsertPt); 2515 PN->replaceAllUsesWith(Sel); 2516 Sel->takeName(PN); 2517 PN->eraseFromParent(); 2518 } 2519 2520 // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement 2521 // has been flattened. Change DomBlock to jump directly to our new block to 2522 // avoid other simplifycfg's kicking in on the diamond. 2523 Instruction *OldTI = DomBlock->getTerminator(); 2524 Builder.SetInsertPoint(OldTI); 2525 Builder.CreateBr(BB); 2526 OldTI->eraseFromParent(); 2527 return true; 2528 } 2529 2530 /// If we found a conditional branch that goes to two returning blocks, 2531 /// try to merge them together into one return, 2532 /// introducing a select if the return values disagree. 2533 bool SimplifyCFGOpt::SimplifyCondBranchToTwoReturns(BranchInst *BI, 2534 IRBuilder<> &Builder) { 2535 assert(BI->isConditional() && "Must be a conditional branch"); 2536 BasicBlock *TrueSucc = BI->getSuccessor(0); 2537 BasicBlock *FalseSucc = BI->getSuccessor(1); 2538 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator()); 2539 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator()); 2540 2541 // Check to ensure both blocks are empty (just a return) or optionally empty 2542 // with PHI nodes. If there are other instructions, merging would cause extra 2543 // computation on one path or the other. 2544 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator()) 2545 return false; 2546 if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator()) 2547 return false; 2548 2549 Builder.SetInsertPoint(BI); 2550 // Okay, we found a branch that is going to two return nodes. If 2551 // there is no return value for this function, just change the 2552 // branch into a return. 2553 if (FalseRet->getNumOperands() == 0) { 2554 TrueSucc->removePredecessor(BI->getParent()); 2555 FalseSucc->removePredecessor(BI->getParent()); 2556 Builder.CreateRetVoid(); 2557 EraseTerminatorAndDCECond(BI); 2558 return true; 2559 } 2560 2561 // Otherwise, figure out what the true and false return values are 2562 // so we can insert a new select instruction. 2563 Value *TrueValue = TrueRet->getReturnValue(); 2564 Value *FalseValue = FalseRet->getReturnValue(); 2565 2566 // Unwrap any PHI nodes in the return blocks. 2567 if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue)) 2568 if (TVPN->getParent() == TrueSucc) 2569 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent()); 2570 if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue)) 2571 if (FVPN->getParent() == FalseSucc) 2572 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent()); 2573 2574 // In order for this transformation to be safe, we must be able to 2575 // unconditionally execute both operands to the return. This is 2576 // normally the case, but we could have a potentially-trapping 2577 // constant expression that prevents this transformation from being 2578 // safe. 2579 if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue)) 2580 if (TCV->canTrap()) 2581 return false; 2582 if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue)) 2583 if (FCV->canTrap()) 2584 return false; 2585 2586 // Okay, we collected all the mapped values and checked them for sanity, and 2587 // defined to really do this transformation. First, update the CFG. 2588 TrueSucc->removePredecessor(BI->getParent()); 2589 FalseSucc->removePredecessor(BI->getParent()); 2590 2591 // Insert select instructions where needed. 2592 Value *BrCond = BI->getCondition(); 2593 if (TrueValue) { 2594 // Insert a select if the results differ. 2595 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) { 2596 } else if (isa<UndefValue>(TrueValue)) { 2597 TrueValue = FalseValue; 2598 } else { 2599 TrueValue = 2600 Builder.CreateSelect(BrCond, TrueValue, FalseValue, "retval", BI); 2601 } 2602 } 2603 2604 Value *RI = 2605 !TrueValue ? Builder.CreateRetVoid() : Builder.CreateRet(TrueValue); 2606 2607 (void)RI; 2608 2609 LLVM_DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:" 2610 << "\n " << *BI << "\nNewRet = " << *RI << "\nTRUEBLOCK: " 2611 << *TrueSucc << "\nFALSEBLOCK: " << *FalseSucc); 2612 2613 EraseTerminatorAndDCECond(BI); 2614 2615 return true; 2616 } 2617 2618 /// Return true if the given instruction is available 2619 /// in its predecessor block. If yes, the instruction will be removed. 2620 static bool tryCSEWithPredecessor(Instruction *Inst, BasicBlock *PB) { 2621 if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst)) 2622 return false; 2623 for (Instruction &I : *PB) { 2624 Instruction *PBI = &I; 2625 // Check whether Inst and PBI generate the same value. 2626 if (Inst->isIdenticalTo(PBI)) { 2627 Inst->replaceAllUsesWith(PBI); 2628 Inst->eraseFromParent(); 2629 return true; 2630 } 2631 } 2632 return false; 2633 } 2634 2635 /// Return true if either PBI or BI has branch weight available, and store 2636 /// the weights in {Pred|Succ}{True|False}Weight. If one of PBI and BI does 2637 /// not have branch weight, use 1:1 as its weight. 2638 static bool extractPredSuccWeights(BranchInst *PBI, BranchInst *BI, 2639 uint64_t &PredTrueWeight, 2640 uint64_t &PredFalseWeight, 2641 uint64_t &SuccTrueWeight, 2642 uint64_t &SuccFalseWeight) { 2643 bool PredHasWeights = 2644 PBI->extractProfMetadata(PredTrueWeight, PredFalseWeight); 2645 bool SuccHasWeights = 2646 BI->extractProfMetadata(SuccTrueWeight, SuccFalseWeight); 2647 if (PredHasWeights || SuccHasWeights) { 2648 if (!PredHasWeights) 2649 PredTrueWeight = PredFalseWeight = 1; 2650 if (!SuccHasWeights) 2651 SuccTrueWeight = SuccFalseWeight = 1; 2652 return true; 2653 } else { 2654 return false; 2655 } 2656 } 2657 2658 /// If this basic block is simple enough, and if a predecessor branches to us 2659 /// and one of our successors, fold the block into the predecessor and use 2660 /// logical operations to pick the right destination. 2661 bool llvm::FoldBranchToCommonDest(BranchInst *BI, MemorySSAUpdater *MSSAU, 2662 unsigned BonusInstThreshold) { 2663 BasicBlock *BB = BI->getParent(); 2664 2665 const unsigned PredCount = pred_size(BB); 2666 2667 bool Changed = false; 2668 2669 Instruction *Cond = nullptr; 2670 if (BI->isConditional()) 2671 Cond = dyn_cast<Instruction>(BI->getCondition()); 2672 else { 2673 // For unconditional branch, check for a simple CFG pattern, where 2674 // BB has a single predecessor and BB's successor is also its predecessor's 2675 // successor. If such pattern exists, check for CSE between BB and its 2676 // predecessor. 2677 if (BasicBlock *PB = BB->getSinglePredecessor()) 2678 if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator())) 2679 if (PBI->isConditional() && 2680 (BI->getSuccessor(0) == PBI->getSuccessor(0) || 2681 BI->getSuccessor(0) == PBI->getSuccessor(1))) { 2682 for (auto I = BB->instructionsWithoutDebug().begin(), 2683 E = BB->instructionsWithoutDebug().end(); 2684 I != E;) { 2685 Instruction *Curr = &*I++; 2686 if (isa<CmpInst>(Curr)) { 2687 Cond = Curr; 2688 break; 2689 } 2690 // Quit if we can't remove this instruction. 2691 if (!tryCSEWithPredecessor(Curr, PB)) 2692 return Changed; 2693 Changed = true; 2694 } 2695 } 2696 2697 if (!Cond) 2698 return Changed; 2699 } 2700 2701 if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) || 2702 Cond->getParent() != BB || !Cond->hasOneUse()) 2703 return Changed; 2704 2705 // Make sure the instruction after the condition is the cond branch. 2706 BasicBlock::iterator CondIt = ++Cond->getIterator(); 2707 2708 // Ignore dbg intrinsics. 2709 while (isa<DbgInfoIntrinsic>(CondIt)) 2710 ++CondIt; 2711 2712 if (&*CondIt != BI) 2713 return Changed; 2714 2715 // Only allow this transformation if computing the condition doesn't involve 2716 // too many instructions and these involved instructions can be executed 2717 // unconditionally. We denote all involved instructions except the condition 2718 // as "bonus instructions", and only allow this transformation when the 2719 // number of the bonus instructions we'll need to create when cloning into 2720 // each predecessor does not exceed a certain threshold. 2721 unsigned NumBonusInsts = 0; 2722 for (auto I = BB->begin(); Cond != &*I; ++I) { 2723 // Ignore dbg intrinsics. 2724 if (isa<DbgInfoIntrinsic>(I)) 2725 continue; 2726 if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(&*I)) 2727 return Changed; 2728 // I has only one use and can be executed unconditionally. 2729 Instruction *User = dyn_cast<Instruction>(I->user_back()); 2730 if (User == nullptr || User->getParent() != BB) 2731 return Changed; 2732 // I is used in the same BB. Since BI uses Cond and doesn't have more slots 2733 // to use any other instruction, User must be an instruction between next(I) 2734 // and Cond. 2735 2736 // Account for the cost of duplicating this instruction into each 2737 // predecessor. 2738 NumBonusInsts += PredCount; 2739 // Early exits once we reach the limit. 2740 if (NumBonusInsts > BonusInstThreshold) 2741 return Changed; 2742 } 2743 2744 // Cond is known to be a compare or binary operator. Check to make sure that 2745 // neither operand is a potentially-trapping constant expression. 2746 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0))) 2747 if (CE->canTrap()) 2748 return Changed; 2749 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1))) 2750 if (CE->canTrap()) 2751 return Changed; 2752 2753 // Finally, don't infinitely unroll conditional loops. 2754 BasicBlock *TrueDest = BI->getSuccessor(0); 2755 BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr; 2756 if (TrueDest == BB || FalseDest == BB) 2757 return Changed; 2758 2759 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) { 2760 BasicBlock *PredBlock = *PI; 2761 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator()); 2762 2763 // Check that we have two conditional branches. If there is a PHI node in 2764 // the common successor, verify that the same value flows in from both 2765 // blocks. 2766 SmallVector<PHINode *, 4> PHIs; 2767 if (!PBI || PBI->isUnconditional() || 2768 (BI->isConditional() && !SafeToMergeTerminators(BI, PBI)) || 2769 (!BI->isConditional() && 2770 !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs))) 2771 continue; 2772 2773 // Determine if the two branches share a common destination. 2774 Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd; 2775 bool InvertPredCond = false; 2776 2777 if (BI->isConditional()) { 2778 if (PBI->getSuccessor(0) == TrueDest) { 2779 Opc = Instruction::Or; 2780 } else if (PBI->getSuccessor(1) == FalseDest) { 2781 Opc = Instruction::And; 2782 } else if (PBI->getSuccessor(0) == FalseDest) { 2783 Opc = Instruction::And; 2784 InvertPredCond = true; 2785 } else if (PBI->getSuccessor(1) == TrueDest) { 2786 Opc = Instruction::Or; 2787 InvertPredCond = true; 2788 } else { 2789 continue; 2790 } 2791 } else { 2792 if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest) 2793 continue; 2794 } 2795 2796 LLVM_DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB); 2797 Changed = true; 2798 2799 IRBuilder<> Builder(PBI); 2800 2801 // If we need to invert the condition in the pred block to match, do so now. 2802 if (InvertPredCond) { 2803 Value *NewCond = PBI->getCondition(); 2804 2805 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) { 2806 CmpInst *CI = cast<CmpInst>(NewCond); 2807 CI->setPredicate(CI->getInversePredicate()); 2808 } else { 2809 NewCond = 2810 Builder.CreateNot(NewCond, PBI->getCondition()->getName() + ".not"); 2811 } 2812 2813 PBI->setCondition(NewCond); 2814 PBI->swapSuccessors(); 2815 } 2816 2817 // If we have bonus instructions, clone them into the predecessor block. 2818 // Note that there may be multiple predecessor blocks, so we cannot move 2819 // bonus instructions to a predecessor block. 2820 ValueToValueMapTy VMap; // maps original values to cloned values 2821 // We already make sure Cond is the last instruction before BI. Therefore, 2822 // all instructions before Cond other than DbgInfoIntrinsic are bonus 2823 // instructions. 2824 for (auto BonusInst = BB->begin(); Cond != &*BonusInst; ++BonusInst) { 2825 if (isa<DbgInfoIntrinsic>(BonusInst)) 2826 continue; 2827 Instruction *NewBonusInst = BonusInst->clone(); 2828 2829 // When we fold the bonus instructions we want to make sure we 2830 // reset their debug locations in order to avoid stepping on dead 2831 // code caused by folding dead branches. 2832 NewBonusInst->setDebugLoc(DebugLoc()); 2833 2834 RemapInstruction(NewBonusInst, VMap, 2835 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals); 2836 VMap[&*BonusInst] = NewBonusInst; 2837 2838 // If we moved a load, we cannot any longer claim any knowledge about 2839 // its potential value. The previous information might have been valid 2840 // only given the branch precondition. 2841 // For an analogous reason, we must also drop all the metadata whose 2842 // semantics we don't understand. 2843 NewBonusInst->dropUnknownNonDebugMetadata(); 2844 2845 PredBlock->getInstList().insert(PBI->getIterator(), NewBonusInst); 2846 NewBonusInst->takeName(&*BonusInst); 2847 BonusInst->setName(BonusInst->getName() + ".old"); 2848 } 2849 2850 // Clone Cond into the predecessor basic block, and or/and the 2851 // two conditions together. 2852 Instruction *CondInPred = Cond->clone(); 2853 2854 // Reset the condition debug location to avoid jumping on dead code 2855 // as the result of folding dead branches. 2856 CondInPred->setDebugLoc(DebugLoc()); 2857 2858 RemapInstruction(CondInPred, VMap, 2859 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals); 2860 PredBlock->getInstList().insert(PBI->getIterator(), CondInPred); 2861 CondInPred->takeName(Cond); 2862 Cond->setName(CondInPred->getName() + ".old"); 2863 2864 if (BI->isConditional()) { 2865 Instruction *NewCond = cast<Instruction>( 2866 Builder.CreateBinOp(Opc, PBI->getCondition(), CondInPred, "or.cond")); 2867 PBI->setCondition(NewCond); 2868 2869 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight; 2870 bool HasWeights = 2871 extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight, 2872 SuccTrueWeight, SuccFalseWeight); 2873 SmallVector<uint64_t, 8> NewWeights; 2874 2875 if (PBI->getSuccessor(0) == BB) { 2876 if (HasWeights) { 2877 // PBI: br i1 %x, BB, FalseDest 2878 // BI: br i1 %y, TrueDest, FalseDest 2879 // TrueWeight is TrueWeight for PBI * TrueWeight for BI. 2880 NewWeights.push_back(PredTrueWeight * SuccTrueWeight); 2881 // FalseWeight is FalseWeight for PBI * TotalWeight for BI + 2882 // TrueWeight for PBI * FalseWeight for BI. 2883 // We assume that total weights of a BranchInst can fit into 32 bits. 2884 // Therefore, we will not have overflow using 64-bit arithmetic. 2885 NewWeights.push_back(PredFalseWeight * 2886 (SuccFalseWeight + SuccTrueWeight) + 2887 PredTrueWeight * SuccFalseWeight); 2888 } 2889 AddPredecessorToBlock(TrueDest, PredBlock, BB, MSSAU); 2890 PBI->setSuccessor(0, TrueDest); 2891 } 2892 if (PBI->getSuccessor(1) == BB) { 2893 if (HasWeights) { 2894 // PBI: br i1 %x, TrueDest, BB 2895 // BI: br i1 %y, TrueDest, FalseDest 2896 // TrueWeight is TrueWeight for PBI * TotalWeight for BI + 2897 // FalseWeight for PBI * TrueWeight for BI. 2898 NewWeights.push_back(PredTrueWeight * 2899 (SuccFalseWeight + SuccTrueWeight) + 2900 PredFalseWeight * SuccTrueWeight); 2901 // FalseWeight is FalseWeight for PBI * FalseWeight for BI. 2902 NewWeights.push_back(PredFalseWeight * SuccFalseWeight); 2903 } 2904 AddPredecessorToBlock(FalseDest, PredBlock, BB, MSSAU); 2905 PBI->setSuccessor(1, FalseDest); 2906 } 2907 if (NewWeights.size() == 2) { 2908 // Halve the weights if any of them cannot fit in an uint32_t 2909 FitWeights(NewWeights); 2910 2911 SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(), 2912 NewWeights.end()); 2913 setBranchWeights(PBI, MDWeights[0], MDWeights[1]); 2914 } else 2915 PBI->setMetadata(LLVMContext::MD_prof, nullptr); 2916 } else { 2917 // Update PHI nodes in the common successors. 2918 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) { 2919 ConstantInt *PBI_C = cast<ConstantInt>( 2920 PHIs[i]->getIncomingValueForBlock(PBI->getParent())); 2921 assert(PBI_C->getType()->isIntegerTy(1)); 2922 Instruction *MergedCond = nullptr; 2923 if (PBI->getSuccessor(0) == TrueDest) { 2924 // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value) 2925 // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value) 2926 // is false: !PBI_Cond and BI_Value 2927 Instruction *NotCond = cast<Instruction>( 2928 Builder.CreateNot(PBI->getCondition(), "not.cond")); 2929 MergedCond = cast<Instruction>( 2930 Builder.CreateBinOp(Instruction::And, NotCond, CondInPred, 2931 "and.cond")); 2932 if (PBI_C->isOne()) 2933 MergedCond = cast<Instruction>(Builder.CreateBinOp( 2934 Instruction::Or, PBI->getCondition(), MergedCond, "or.cond")); 2935 } else { 2936 // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C) 2937 // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond) 2938 // is false: PBI_Cond and BI_Value 2939 MergedCond = cast<Instruction>(Builder.CreateBinOp( 2940 Instruction::And, PBI->getCondition(), CondInPred, "and.cond")); 2941 if (PBI_C->isOne()) { 2942 Instruction *NotCond = cast<Instruction>( 2943 Builder.CreateNot(PBI->getCondition(), "not.cond")); 2944 MergedCond = cast<Instruction>(Builder.CreateBinOp( 2945 Instruction::Or, NotCond, MergedCond, "or.cond")); 2946 } 2947 } 2948 // Update PHI Node. 2949 PHIs[i]->setIncomingValueForBlock(PBI->getParent(), MergedCond); 2950 } 2951 2952 // PBI is changed to branch to TrueDest below. Remove itself from 2953 // potential phis from all other successors. 2954 if (MSSAU) 2955 MSSAU->changeCondBranchToUnconditionalTo(PBI, TrueDest); 2956 2957 // Change PBI from Conditional to Unconditional. 2958 BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI); 2959 EraseTerminatorAndDCECond(PBI, MSSAU); 2960 PBI = New_PBI; 2961 } 2962 2963 // If BI was a loop latch, it may have had associated loop metadata. 2964 // We need to copy it to the new latch, that is, PBI. 2965 if (MDNode *LoopMD = BI->getMetadata(LLVMContext::MD_loop)) 2966 PBI->setMetadata(LLVMContext::MD_loop, LoopMD); 2967 2968 // TODO: If BB is reachable from all paths through PredBlock, then we 2969 // could replace PBI's branch probabilities with BI's. 2970 2971 // Copy any debug value intrinsics into the end of PredBlock. 2972 for (Instruction &I : *BB) { 2973 if (isa<DbgInfoIntrinsic>(I)) { 2974 Instruction *NewI = I.clone(); 2975 RemapInstruction(NewI, VMap, 2976 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals); 2977 NewI->insertBefore(PBI); 2978 } 2979 } 2980 2981 return Changed; 2982 } 2983 return Changed; 2984 } 2985 2986 // If there is only one store in BB1 and BB2, return it, otherwise return 2987 // nullptr. 2988 static StoreInst *findUniqueStoreInBlocks(BasicBlock *BB1, BasicBlock *BB2) { 2989 StoreInst *S = nullptr; 2990 for (auto *BB : {BB1, BB2}) { 2991 if (!BB) 2992 continue; 2993 for (auto &I : *BB) 2994 if (auto *SI = dyn_cast<StoreInst>(&I)) { 2995 if (S) 2996 // Multiple stores seen. 2997 return nullptr; 2998 else 2999 S = SI; 3000 } 3001 } 3002 return S; 3003 } 3004 3005 static Value *ensureValueAvailableInSuccessor(Value *V, BasicBlock *BB, 3006 Value *AlternativeV = nullptr) { 3007 // PHI is going to be a PHI node that allows the value V that is defined in 3008 // BB to be referenced in BB's only successor. 3009 // 3010 // If AlternativeV is nullptr, the only value we care about in PHI is V. It 3011 // doesn't matter to us what the other operand is (it'll never get used). We 3012 // could just create a new PHI with an undef incoming value, but that could 3013 // increase register pressure if EarlyCSE/InstCombine can't fold it with some 3014 // other PHI. So here we directly look for some PHI in BB's successor with V 3015 // as an incoming operand. If we find one, we use it, else we create a new 3016 // one. 3017 // 3018 // If AlternativeV is not nullptr, we care about both incoming values in PHI. 3019 // PHI must be exactly: phi <ty> [ %BB, %V ], [ %OtherBB, %AlternativeV] 3020 // where OtherBB is the single other predecessor of BB's only successor. 3021 PHINode *PHI = nullptr; 3022 BasicBlock *Succ = BB->getSingleSuccessor(); 3023 3024 for (auto I = Succ->begin(); isa<PHINode>(I); ++I) 3025 if (cast<PHINode>(I)->getIncomingValueForBlock(BB) == V) { 3026 PHI = cast<PHINode>(I); 3027 if (!AlternativeV) 3028 break; 3029 3030 assert(Succ->hasNPredecessors(2)); 3031 auto PredI = pred_begin(Succ); 3032 BasicBlock *OtherPredBB = *PredI == BB ? *++PredI : *PredI; 3033 if (PHI->getIncomingValueForBlock(OtherPredBB) == AlternativeV) 3034 break; 3035 PHI = nullptr; 3036 } 3037 if (PHI) 3038 return PHI; 3039 3040 // If V is not an instruction defined in BB, just return it. 3041 if (!AlternativeV && 3042 (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB)) 3043 return V; 3044 3045 PHI = PHINode::Create(V->getType(), 2, "simplifycfg.merge", &Succ->front()); 3046 PHI->addIncoming(V, BB); 3047 for (BasicBlock *PredBB : predecessors(Succ)) 3048 if (PredBB != BB) 3049 PHI->addIncoming( 3050 AlternativeV ? AlternativeV : UndefValue::get(V->getType()), PredBB); 3051 return PHI; 3052 } 3053 3054 static bool mergeConditionalStoreToAddress(BasicBlock *PTB, BasicBlock *PFB, 3055 BasicBlock *QTB, BasicBlock *QFB, 3056 BasicBlock *PostBB, Value *Address, 3057 bool InvertPCond, bool InvertQCond, 3058 const DataLayout &DL, 3059 const TargetTransformInfo &TTI) { 3060 // For every pointer, there must be exactly two stores, one coming from 3061 // PTB or PFB, and the other from QTB or QFB. We don't support more than one 3062 // store (to any address) in PTB,PFB or QTB,QFB. 3063 // FIXME: We could relax this restriction with a bit more work and performance 3064 // testing. 3065 StoreInst *PStore = findUniqueStoreInBlocks(PTB, PFB); 3066 StoreInst *QStore = findUniqueStoreInBlocks(QTB, QFB); 3067 if (!PStore || !QStore) 3068 return false; 3069 3070 // Now check the stores are compatible. 3071 if (!QStore->isUnordered() || !PStore->isUnordered()) 3072 return false; 3073 3074 // Check that sinking the store won't cause program behavior changes. Sinking 3075 // the store out of the Q blocks won't change any behavior as we're sinking 3076 // from a block to its unconditional successor. But we're moving a store from 3077 // the P blocks down through the middle block (QBI) and past both QFB and QTB. 3078 // So we need to check that there are no aliasing loads or stores in 3079 // QBI, QTB and QFB. We also need to check there are no conflicting memory 3080 // operations between PStore and the end of its parent block. 3081 // 3082 // The ideal way to do this is to query AliasAnalysis, but we don't 3083 // preserve AA currently so that is dangerous. Be super safe and just 3084 // check there are no other memory operations at all. 3085 for (auto &I : *QFB->getSinglePredecessor()) 3086 if (I.mayReadOrWriteMemory()) 3087 return false; 3088 for (auto &I : *QFB) 3089 if (&I != QStore && I.mayReadOrWriteMemory()) 3090 return false; 3091 if (QTB) 3092 for (auto &I : *QTB) 3093 if (&I != QStore && I.mayReadOrWriteMemory()) 3094 return false; 3095 for (auto I = BasicBlock::iterator(PStore), E = PStore->getParent()->end(); 3096 I != E; ++I) 3097 if (&*I != PStore && I->mayReadOrWriteMemory()) 3098 return false; 3099 3100 // If we're not in aggressive mode, we only optimize if we have some 3101 // confidence that by optimizing we'll allow P and/or Q to be if-converted. 3102 auto IsWorthwhile = [&](BasicBlock *BB, ArrayRef<StoreInst *> FreeStores) { 3103 if (!BB) 3104 return true; 3105 // Heuristic: if the block can be if-converted/phi-folded and the 3106 // instructions inside are all cheap (arithmetic/GEPs), it's worthwhile to 3107 // thread this store. 3108 int BudgetRemaining = 3109 PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic; 3110 for (auto &I : BB->instructionsWithoutDebug()) { 3111 // Consider terminator instruction to be free. 3112 if (I.isTerminator()) 3113 continue; 3114 // If this is one the stores that we want to speculate out of this BB, 3115 // then don't count it's cost, consider it to be free. 3116 if (auto *S = dyn_cast<StoreInst>(&I)) 3117 if (llvm::find(FreeStores, S)) 3118 continue; 3119 // Else, we have a white-list of instructions that we are ak speculating. 3120 if (!isa<BinaryOperator>(I) && !isa<GetElementPtrInst>(I)) 3121 return false; // Not in white-list - not worthwhile folding. 3122 // And finally, if this is a non-free instruction that we are okay 3123 // speculating, ensure that we consider the speculation budget. 3124 BudgetRemaining -= TTI.getUserCost(&I, TargetTransformInfo::TCK_SizeAndLatency); 3125 if (BudgetRemaining < 0) 3126 return false; // Eagerly refuse to fold as soon as we're out of budget. 3127 } 3128 assert(BudgetRemaining >= 0 && 3129 "When we run out of budget we will eagerly return from within the " 3130 "per-instruction loop."); 3131 return true; 3132 }; 3133 3134 const SmallVector<StoreInst *, 2> FreeStores = {PStore, QStore}; 3135 if (!MergeCondStoresAggressively && 3136 (!IsWorthwhile(PTB, FreeStores) || !IsWorthwhile(PFB, FreeStores) || 3137 !IsWorthwhile(QTB, FreeStores) || !IsWorthwhile(QFB, FreeStores))) 3138 return false; 3139 3140 // If PostBB has more than two predecessors, we need to split it so we can 3141 // sink the store. 3142 if (std::next(pred_begin(PostBB), 2) != pred_end(PostBB)) { 3143 // We know that QFB's only successor is PostBB. And QFB has a single 3144 // predecessor. If QTB exists, then its only successor is also PostBB. 3145 // If QTB does not exist, then QFB's only predecessor has a conditional 3146 // branch to QFB and PostBB. 3147 BasicBlock *TruePred = QTB ? QTB : QFB->getSinglePredecessor(); 3148 BasicBlock *NewBB = SplitBlockPredecessors(PostBB, { QFB, TruePred}, 3149 "condstore.split"); 3150 if (!NewBB) 3151 return false; 3152 PostBB = NewBB; 3153 } 3154 3155 // OK, we're going to sink the stores to PostBB. The store has to be 3156 // conditional though, so first create the predicate. 3157 Value *PCond = cast<BranchInst>(PFB->getSinglePredecessor()->getTerminator()) 3158 ->getCondition(); 3159 Value *QCond = cast<BranchInst>(QFB->getSinglePredecessor()->getTerminator()) 3160 ->getCondition(); 3161 3162 Value *PPHI = ensureValueAvailableInSuccessor(PStore->getValueOperand(), 3163 PStore->getParent()); 3164 Value *QPHI = ensureValueAvailableInSuccessor(QStore->getValueOperand(), 3165 QStore->getParent(), PPHI); 3166 3167 IRBuilder<> QB(&*PostBB->getFirstInsertionPt()); 3168 3169 Value *PPred = PStore->getParent() == PTB ? PCond : QB.CreateNot(PCond); 3170 Value *QPred = QStore->getParent() == QTB ? QCond : QB.CreateNot(QCond); 3171 3172 if (InvertPCond) 3173 PPred = QB.CreateNot(PPred); 3174 if (InvertQCond) 3175 QPred = QB.CreateNot(QPred); 3176 Value *CombinedPred = QB.CreateOr(PPred, QPred); 3177 3178 auto *T = 3179 SplitBlockAndInsertIfThen(CombinedPred, &*QB.GetInsertPoint(), false); 3180 QB.SetInsertPoint(T); 3181 StoreInst *SI = cast<StoreInst>(QB.CreateStore(QPHI, Address)); 3182 AAMDNodes AAMD; 3183 PStore->getAAMetadata(AAMD, /*Merge=*/false); 3184 PStore->getAAMetadata(AAMD, /*Merge=*/true); 3185 SI->setAAMetadata(AAMD); 3186 // Choose the minimum alignment. If we could prove both stores execute, we 3187 // could use biggest one. In this case, though, we only know that one of the 3188 // stores executes. And we don't know it's safe to take the alignment from a 3189 // store that doesn't execute. 3190 SI->setAlignment(std::min(PStore->getAlign(), QStore->getAlign())); 3191 3192 QStore->eraseFromParent(); 3193 PStore->eraseFromParent(); 3194 3195 return true; 3196 } 3197 3198 static bool mergeConditionalStores(BranchInst *PBI, BranchInst *QBI, 3199 const DataLayout &DL, 3200 const TargetTransformInfo &TTI) { 3201 // The intention here is to find diamonds or triangles (see below) where each 3202 // conditional block contains a store to the same address. Both of these 3203 // stores are conditional, so they can't be unconditionally sunk. But it may 3204 // be profitable to speculatively sink the stores into one merged store at the 3205 // end, and predicate the merged store on the union of the two conditions of 3206 // PBI and QBI. 3207 // 3208 // This can reduce the number of stores executed if both of the conditions are 3209 // true, and can allow the blocks to become small enough to be if-converted. 3210 // This optimization will also chain, so that ladders of test-and-set 3211 // sequences can be if-converted away. 3212 // 3213 // We only deal with simple diamonds or triangles: 3214 // 3215 // PBI or PBI or a combination of the two 3216 // / \ | \ 3217 // PTB PFB | PFB 3218 // \ / | / 3219 // QBI QBI 3220 // / \ | \ 3221 // QTB QFB | QFB 3222 // \ / | / 3223 // PostBB PostBB 3224 // 3225 // We model triangles as a type of diamond with a nullptr "true" block. 3226 // Triangles are canonicalized so that the fallthrough edge is represented by 3227 // a true condition, as in the diagram above. 3228 BasicBlock *PTB = PBI->getSuccessor(0); 3229 BasicBlock *PFB = PBI->getSuccessor(1); 3230 BasicBlock *QTB = QBI->getSuccessor(0); 3231 BasicBlock *QFB = QBI->getSuccessor(1); 3232 BasicBlock *PostBB = QFB->getSingleSuccessor(); 3233 3234 // Make sure we have a good guess for PostBB. If QTB's only successor is 3235 // QFB, then QFB is a better PostBB. 3236 if (QTB->getSingleSuccessor() == QFB) 3237 PostBB = QFB; 3238 3239 // If we couldn't find a good PostBB, stop. 3240 if (!PostBB) 3241 return false; 3242 3243 bool InvertPCond = false, InvertQCond = false; 3244 // Canonicalize fallthroughs to the true branches. 3245 if (PFB == QBI->getParent()) { 3246 std::swap(PFB, PTB); 3247 InvertPCond = true; 3248 } 3249 if (QFB == PostBB) { 3250 std::swap(QFB, QTB); 3251 InvertQCond = true; 3252 } 3253 3254 // From this point on we can assume PTB or QTB may be fallthroughs but PFB 3255 // and QFB may not. Model fallthroughs as a nullptr block. 3256 if (PTB == QBI->getParent()) 3257 PTB = nullptr; 3258 if (QTB == PostBB) 3259 QTB = nullptr; 3260 3261 // Legality bailouts. We must have at least the non-fallthrough blocks and 3262 // the post-dominating block, and the non-fallthroughs must only have one 3263 // predecessor. 3264 auto HasOnePredAndOneSucc = [](BasicBlock *BB, BasicBlock *P, BasicBlock *S) { 3265 return BB->getSinglePredecessor() == P && BB->getSingleSuccessor() == S; 3266 }; 3267 if (!HasOnePredAndOneSucc(PFB, PBI->getParent(), QBI->getParent()) || 3268 !HasOnePredAndOneSucc(QFB, QBI->getParent(), PostBB)) 3269 return false; 3270 if ((PTB && !HasOnePredAndOneSucc(PTB, PBI->getParent(), QBI->getParent())) || 3271 (QTB && !HasOnePredAndOneSucc(QTB, QBI->getParent(), PostBB))) 3272 return false; 3273 if (!QBI->getParent()->hasNUses(2)) 3274 return false; 3275 3276 // OK, this is a sequence of two diamonds or triangles. 3277 // Check if there are stores in PTB or PFB that are repeated in QTB or QFB. 3278 SmallPtrSet<Value *, 4> PStoreAddresses, QStoreAddresses; 3279 for (auto *BB : {PTB, PFB}) { 3280 if (!BB) 3281 continue; 3282 for (auto &I : *BB) 3283 if (StoreInst *SI = dyn_cast<StoreInst>(&I)) 3284 PStoreAddresses.insert(SI->getPointerOperand()); 3285 } 3286 for (auto *BB : {QTB, QFB}) { 3287 if (!BB) 3288 continue; 3289 for (auto &I : *BB) 3290 if (StoreInst *SI = dyn_cast<StoreInst>(&I)) 3291 QStoreAddresses.insert(SI->getPointerOperand()); 3292 } 3293 3294 set_intersect(PStoreAddresses, QStoreAddresses); 3295 // set_intersect mutates PStoreAddresses in place. Rename it here to make it 3296 // clear what it contains. 3297 auto &CommonAddresses = PStoreAddresses; 3298 3299 bool Changed = false; 3300 for (auto *Address : CommonAddresses) 3301 Changed |= mergeConditionalStoreToAddress( 3302 PTB, PFB, QTB, QFB, PostBB, Address, InvertPCond, InvertQCond, DL, TTI); 3303 return Changed; 3304 } 3305 3306 3307 /// If the previous block ended with a widenable branch, determine if reusing 3308 /// the target block is profitable and legal. This will have the effect of 3309 /// "widening" PBI, but doesn't require us to reason about hosting safety. 3310 static bool tryWidenCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI) { 3311 // TODO: This can be generalized in two important ways: 3312 // 1) We can allow phi nodes in IfFalseBB and simply reuse all the input 3313 // values from the PBI edge. 3314 // 2) We can sink side effecting instructions into BI's fallthrough 3315 // successor provided they doesn't contribute to computation of 3316 // BI's condition. 3317 Value *CondWB, *WC; 3318 BasicBlock *IfTrueBB, *IfFalseBB; 3319 if (!parseWidenableBranch(PBI, CondWB, WC, IfTrueBB, IfFalseBB) || 3320 IfTrueBB != BI->getParent() || !BI->getParent()->getSinglePredecessor()) 3321 return false; 3322 if (!IfFalseBB->phis().empty()) 3323 return false; // TODO 3324 // Use lambda to lazily compute expensive condition after cheap ones. 3325 auto NoSideEffects = [](BasicBlock &BB) { 3326 return !llvm::any_of(BB, [](const Instruction &I) { 3327 return I.mayWriteToMemory() || I.mayHaveSideEffects(); 3328 }); 3329 }; 3330 if (BI->getSuccessor(1) != IfFalseBB && // no inf looping 3331 BI->getSuccessor(1)->getTerminatingDeoptimizeCall() && // profitability 3332 NoSideEffects(*BI->getParent())) { 3333 BI->getSuccessor(1)->removePredecessor(BI->getParent()); 3334 BI->setSuccessor(1, IfFalseBB); 3335 return true; 3336 } 3337 if (BI->getSuccessor(0) != IfFalseBB && // no inf looping 3338 BI->getSuccessor(0)->getTerminatingDeoptimizeCall() && // profitability 3339 NoSideEffects(*BI->getParent())) { 3340 BI->getSuccessor(0)->removePredecessor(BI->getParent()); 3341 BI->setSuccessor(0, IfFalseBB); 3342 return true; 3343 } 3344 return false; 3345 } 3346 3347 /// If we have a conditional branch as a predecessor of another block, 3348 /// this function tries to simplify it. We know 3349 /// that PBI and BI are both conditional branches, and BI is in one of the 3350 /// successor blocks of PBI - PBI branches to BI. 3351 static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI, 3352 const DataLayout &DL, 3353 const TargetTransformInfo &TTI) { 3354 assert(PBI->isConditional() && BI->isConditional()); 3355 BasicBlock *BB = BI->getParent(); 3356 3357 // If this block ends with a branch instruction, and if there is a 3358 // predecessor that ends on a branch of the same condition, make 3359 // this conditional branch redundant. 3360 if (PBI->getCondition() == BI->getCondition() && 3361 PBI->getSuccessor(0) != PBI->getSuccessor(1)) { 3362 // Okay, the outcome of this conditional branch is statically 3363 // knowable. If this block had a single pred, handle specially. 3364 if (BB->getSinglePredecessor()) { 3365 // Turn this into a branch on constant. 3366 bool CondIsTrue = PBI->getSuccessor(0) == BB; 3367 BI->setCondition( 3368 ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue)); 3369 return true; // Nuke the branch on constant. 3370 } 3371 3372 // Otherwise, if there are multiple predecessors, insert a PHI that merges 3373 // in the constant and simplify the block result. Subsequent passes of 3374 // simplifycfg will thread the block. 3375 if (BlockIsSimpleEnoughToThreadThrough(BB)) { 3376 pred_iterator PB = pred_begin(BB), PE = pred_end(BB); 3377 PHINode *NewPN = PHINode::Create( 3378 Type::getInt1Ty(BB->getContext()), std::distance(PB, PE), 3379 BI->getCondition()->getName() + ".pr", &BB->front()); 3380 // Okay, we're going to insert the PHI node. Since PBI is not the only 3381 // predecessor, compute the PHI'd conditional value for all of the preds. 3382 // Any predecessor where the condition is not computable we keep symbolic. 3383 for (pred_iterator PI = PB; PI != PE; ++PI) { 3384 BasicBlock *P = *PI; 3385 if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) && PBI != BI && 3386 PBI->isConditional() && PBI->getCondition() == BI->getCondition() && 3387 PBI->getSuccessor(0) != PBI->getSuccessor(1)) { 3388 bool CondIsTrue = PBI->getSuccessor(0) == BB; 3389 NewPN->addIncoming( 3390 ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue), 3391 P); 3392 } else { 3393 NewPN->addIncoming(BI->getCondition(), P); 3394 } 3395 } 3396 3397 BI->setCondition(NewPN); 3398 return true; 3399 } 3400 } 3401 3402 // If the previous block ended with a widenable branch, determine if reusing 3403 // the target block is profitable and legal. This will have the effect of 3404 // "widening" PBI, but doesn't require us to reason about hosting safety. 3405 if (tryWidenCondBranchToCondBranch(PBI, BI)) 3406 return true; 3407 3408 if (auto *CE = dyn_cast<ConstantExpr>(BI->getCondition())) 3409 if (CE->canTrap()) 3410 return false; 3411 3412 // If both branches are conditional and both contain stores to the same 3413 // address, remove the stores from the conditionals and create a conditional 3414 // merged store at the end. 3415 if (MergeCondStores && mergeConditionalStores(PBI, BI, DL, TTI)) 3416 return true; 3417 3418 // If this is a conditional branch in an empty block, and if any 3419 // predecessors are a conditional branch to one of our destinations, 3420 // fold the conditions into logical ops and one cond br. 3421 3422 // Ignore dbg intrinsics. 3423 if (&*BB->instructionsWithoutDebug().begin() != BI) 3424 return false; 3425 3426 int PBIOp, BIOp; 3427 if (PBI->getSuccessor(0) == BI->getSuccessor(0)) { 3428 PBIOp = 0; 3429 BIOp = 0; 3430 } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) { 3431 PBIOp = 0; 3432 BIOp = 1; 3433 } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) { 3434 PBIOp = 1; 3435 BIOp = 0; 3436 } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) { 3437 PBIOp = 1; 3438 BIOp = 1; 3439 } else { 3440 return false; 3441 } 3442 3443 // Check to make sure that the other destination of this branch 3444 // isn't BB itself. If so, this is an infinite loop that will 3445 // keep getting unwound. 3446 if (PBI->getSuccessor(PBIOp) == BB) 3447 return false; 3448 3449 // Do not perform this transformation if it would require 3450 // insertion of a large number of select instructions. For targets 3451 // without predication/cmovs, this is a big pessimization. 3452 3453 // Also do not perform this transformation if any phi node in the common 3454 // destination block can trap when reached by BB or PBB (PR17073). In that 3455 // case, it would be unsafe to hoist the operation into a select instruction. 3456 3457 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp); 3458 unsigned NumPhis = 0; 3459 for (BasicBlock::iterator II = CommonDest->begin(); isa<PHINode>(II); 3460 ++II, ++NumPhis) { 3461 if (NumPhis > 2) // Disable this xform. 3462 return false; 3463 3464 PHINode *PN = cast<PHINode>(II); 3465 Value *BIV = PN->getIncomingValueForBlock(BB); 3466 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV)) 3467 if (CE->canTrap()) 3468 return false; 3469 3470 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent()); 3471 Value *PBIV = PN->getIncomingValue(PBBIdx); 3472 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV)) 3473 if (CE->canTrap()) 3474 return false; 3475 } 3476 3477 // Finally, if everything is ok, fold the branches to logical ops. 3478 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1); 3479 3480 LLVM_DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent() 3481 << "AND: " << *BI->getParent()); 3482 3483 // If OtherDest *is* BB, then BB is a basic block with a single conditional 3484 // branch in it, where one edge (OtherDest) goes back to itself but the other 3485 // exits. We don't *know* that the program avoids the infinite loop 3486 // (even though that seems likely). If we do this xform naively, we'll end up 3487 // recursively unpeeling the loop. Since we know that (after the xform is 3488 // done) that the block *is* infinite if reached, we just make it an obviously 3489 // infinite loop with no cond branch. 3490 if (OtherDest == BB) { 3491 // Insert it at the end of the function, because it's either code, 3492 // or it won't matter if it's hot. :) 3493 BasicBlock *InfLoopBlock = 3494 BasicBlock::Create(BB->getContext(), "infloop", BB->getParent()); 3495 BranchInst::Create(InfLoopBlock, InfLoopBlock); 3496 OtherDest = InfLoopBlock; 3497 } 3498 3499 LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent()); 3500 3501 // BI may have other predecessors. Because of this, we leave 3502 // it alone, but modify PBI. 3503 3504 // Make sure we get to CommonDest on True&True directions. 3505 Value *PBICond = PBI->getCondition(); 3506 IRBuilder<NoFolder> Builder(PBI); 3507 if (PBIOp) 3508 PBICond = Builder.CreateNot(PBICond, PBICond->getName() + ".not"); 3509 3510 Value *BICond = BI->getCondition(); 3511 if (BIOp) 3512 BICond = Builder.CreateNot(BICond, BICond->getName() + ".not"); 3513 3514 // Merge the conditions. 3515 Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge"); 3516 3517 // Modify PBI to branch on the new condition to the new dests. 3518 PBI->setCondition(Cond); 3519 PBI->setSuccessor(0, CommonDest); 3520 PBI->setSuccessor(1, OtherDest); 3521 3522 // Update branch weight for PBI. 3523 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight; 3524 uint64_t PredCommon, PredOther, SuccCommon, SuccOther; 3525 bool HasWeights = 3526 extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight, 3527 SuccTrueWeight, SuccFalseWeight); 3528 if (HasWeights) { 3529 PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight; 3530 PredOther = PBIOp ? PredTrueWeight : PredFalseWeight; 3531 SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight; 3532 SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight; 3533 // The weight to CommonDest should be PredCommon * SuccTotal + 3534 // PredOther * SuccCommon. 3535 // The weight to OtherDest should be PredOther * SuccOther. 3536 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) + 3537 PredOther * SuccCommon, 3538 PredOther * SuccOther}; 3539 // Halve the weights if any of them cannot fit in an uint32_t 3540 FitWeights(NewWeights); 3541 3542 setBranchWeights(PBI, NewWeights[0], NewWeights[1]); 3543 } 3544 3545 // OtherDest may have phi nodes. If so, add an entry from PBI's 3546 // block that are identical to the entries for BI's block. 3547 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB); 3548 3549 // We know that the CommonDest already had an edge from PBI to 3550 // it. If it has PHIs though, the PHIs may have different 3551 // entries for BB and PBI's BB. If so, insert a select to make 3552 // them agree. 3553 for (PHINode &PN : CommonDest->phis()) { 3554 Value *BIV = PN.getIncomingValueForBlock(BB); 3555 unsigned PBBIdx = PN.getBasicBlockIndex(PBI->getParent()); 3556 Value *PBIV = PN.getIncomingValue(PBBIdx); 3557 if (BIV != PBIV) { 3558 // Insert a select in PBI to pick the right value. 3559 SelectInst *NV = cast<SelectInst>( 3560 Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName() + ".mux")); 3561 PN.setIncomingValue(PBBIdx, NV); 3562 // Although the select has the same condition as PBI, the original branch 3563 // weights for PBI do not apply to the new select because the select's 3564 // 'logical' edges are incoming edges of the phi that is eliminated, not 3565 // the outgoing edges of PBI. 3566 if (HasWeights) { 3567 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight; 3568 uint64_t PredOther = PBIOp ? PredTrueWeight : PredFalseWeight; 3569 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight; 3570 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight; 3571 // The weight to PredCommonDest should be PredCommon * SuccTotal. 3572 // The weight to PredOtherDest should be PredOther * SuccCommon. 3573 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther), 3574 PredOther * SuccCommon}; 3575 3576 FitWeights(NewWeights); 3577 3578 setBranchWeights(NV, NewWeights[0], NewWeights[1]); 3579 } 3580 } 3581 } 3582 3583 LLVM_DEBUG(dbgs() << "INTO: " << *PBI->getParent()); 3584 LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent()); 3585 3586 // This basic block is probably dead. We know it has at least 3587 // one fewer predecessor. 3588 return true; 3589 } 3590 3591 // Simplifies a terminator by replacing it with a branch to TrueBB if Cond is 3592 // true or to FalseBB if Cond is false. 3593 // Takes care of updating the successors and removing the old terminator. 3594 // Also makes sure not to introduce new successors by assuming that edges to 3595 // non-successor TrueBBs and FalseBBs aren't reachable. 3596 bool SimplifyCFGOpt::SimplifyTerminatorOnSelect(Instruction *OldTerm, 3597 Value *Cond, BasicBlock *TrueBB, 3598 BasicBlock *FalseBB, 3599 uint32_t TrueWeight, 3600 uint32_t FalseWeight) { 3601 // Remove any superfluous successor edges from the CFG. 3602 // First, figure out which successors to preserve. 3603 // If TrueBB and FalseBB are equal, only try to preserve one copy of that 3604 // successor. 3605 BasicBlock *KeepEdge1 = TrueBB; 3606 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr; 3607 3608 // Then remove the rest. 3609 for (BasicBlock *Succ : successors(OldTerm)) { 3610 // Make sure only to keep exactly one copy of each edge. 3611 if (Succ == KeepEdge1) 3612 KeepEdge1 = nullptr; 3613 else if (Succ == KeepEdge2) 3614 KeepEdge2 = nullptr; 3615 else 3616 Succ->removePredecessor(OldTerm->getParent(), 3617 /*KeepOneInputPHIs=*/true); 3618 } 3619 3620 IRBuilder<> Builder(OldTerm); 3621 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc()); 3622 3623 // Insert an appropriate new terminator. 3624 if (!KeepEdge1 && !KeepEdge2) { 3625 if (TrueBB == FalseBB) 3626 // We were only looking for one successor, and it was present. 3627 // Create an unconditional branch to it. 3628 Builder.CreateBr(TrueBB); 3629 else { 3630 // We found both of the successors we were looking for. 3631 // Create a conditional branch sharing the condition of the select. 3632 BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB); 3633 if (TrueWeight != FalseWeight) 3634 setBranchWeights(NewBI, TrueWeight, FalseWeight); 3635 } 3636 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) { 3637 // Neither of the selected blocks were successors, so this 3638 // terminator must be unreachable. 3639 new UnreachableInst(OldTerm->getContext(), OldTerm); 3640 } else { 3641 // One of the selected values was a successor, but the other wasn't. 3642 // Insert an unconditional branch to the one that was found; 3643 // the edge to the one that wasn't must be unreachable. 3644 if (!KeepEdge1) 3645 // Only TrueBB was found. 3646 Builder.CreateBr(TrueBB); 3647 else 3648 // Only FalseBB was found. 3649 Builder.CreateBr(FalseBB); 3650 } 3651 3652 EraseTerminatorAndDCECond(OldTerm); 3653 return true; 3654 } 3655 3656 // Replaces 3657 // (switch (select cond, X, Y)) on constant X, Y 3658 // with a branch - conditional if X and Y lead to distinct BBs, 3659 // unconditional otherwise. 3660 bool SimplifyCFGOpt::SimplifySwitchOnSelect(SwitchInst *SI, 3661 SelectInst *Select) { 3662 // Check for constant integer values in the select. 3663 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue()); 3664 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue()); 3665 if (!TrueVal || !FalseVal) 3666 return false; 3667 3668 // Find the relevant condition and destinations. 3669 Value *Condition = Select->getCondition(); 3670 BasicBlock *TrueBB = SI->findCaseValue(TrueVal)->getCaseSuccessor(); 3671 BasicBlock *FalseBB = SI->findCaseValue(FalseVal)->getCaseSuccessor(); 3672 3673 // Get weight for TrueBB and FalseBB. 3674 uint32_t TrueWeight = 0, FalseWeight = 0; 3675 SmallVector<uint64_t, 8> Weights; 3676 bool HasWeights = HasBranchWeights(SI); 3677 if (HasWeights) { 3678 GetBranchWeights(SI, Weights); 3679 if (Weights.size() == 1 + SI->getNumCases()) { 3680 TrueWeight = 3681 (uint32_t)Weights[SI->findCaseValue(TrueVal)->getSuccessorIndex()]; 3682 FalseWeight = 3683 (uint32_t)Weights[SI->findCaseValue(FalseVal)->getSuccessorIndex()]; 3684 } 3685 } 3686 3687 // Perform the actual simplification. 3688 return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB, TrueWeight, 3689 FalseWeight); 3690 } 3691 3692 // Replaces 3693 // (indirectbr (select cond, blockaddress(@fn, BlockA), 3694 // blockaddress(@fn, BlockB))) 3695 // with 3696 // (br cond, BlockA, BlockB). 3697 bool SimplifyCFGOpt::SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, 3698 SelectInst *SI) { 3699 // Check that both operands of the select are block addresses. 3700 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue()); 3701 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue()); 3702 if (!TBA || !FBA) 3703 return false; 3704 3705 // Extract the actual blocks. 3706 BasicBlock *TrueBB = TBA->getBasicBlock(); 3707 BasicBlock *FalseBB = FBA->getBasicBlock(); 3708 3709 // Perform the actual simplification. 3710 return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB, 0, 3711 0); 3712 } 3713 3714 /// This is called when we find an icmp instruction 3715 /// (a seteq/setne with a constant) as the only instruction in a 3716 /// block that ends with an uncond branch. We are looking for a very specific 3717 /// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In 3718 /// this case, we merge the first two "or's of icmp" into a switch, but then the 3719 /// default value goes to an uncond block with a seteq in it, we get something 3720 /// like: 3721 /// 3722 /// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ] 3723 /// DEFAULT: 3724 /// %tmp = icmp eq i8 %A, 92 3725 /// br label %end 3726 /// end: 3727 /// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ] 3728 /// 3729 /// We prefer to split the edge to 'end' so that there is a true/false entry to 3730 /// the PHI, merging the third icmp into the switch. 3731 bool SimplifyCFGOpt::tryToSimplifyUncondBranchWithICmpInIt( 3732 ICmpInst *ICI, IRBuilder<> &Builder) { 3733 BasicBlock *BB = ICI->getParent(); 3734 3735 // If the block has any PHIs in it or the icmp has multiple uses, it is too 3736 // complex. 3737 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) 3738 return false; 3739 3740 Value *V = ICI->getOperand(0); 3741 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1)); 3742 3743 // The pattern we're looking for is where our only predecessor is a switch on 3744 // 'V' and this block is the default case for the switch. In this case we can 3745 // fold the compared value into the switch to simplify things. 3746 BasicBlock *Pred = BB->getSinglePredecessor(); 3747 if (!Pred || !isa<SwitchInst>(Pred->getTerminator())) 3748 return false; 3749 3750 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator()); 3751 if (SI->getCondition() != V) 3752 return false; 3753 3754 // If BB is reachable on a non-default case, then we simply know the value of 3755 // V in this block. Substitute it and constant fold the icmp instruction 3756 // away. 3757 if (SI->getDefaultDest() != BB) { 3758 ConstantInt *VVal = SI->findCaseDest(BB); 3759 assert(VVal && "Should have a unique destination value"); 3760 ICI->setOperand(0, VVal); 3761 3762 if (Value *V = SimplifyInstruction(ICI, {DL, ICI})) { 3763 ICI->replaceAllUsesWith(V); 3764 ICI->eraseFromParent(); 3765 } 3766 // BB is now empty, so it is likely to simplify away. 3767 return requestResimplify(); 3768 } 3769 3770 // Ok, the block is reachable from the default dest. If the constant we're 3771 // comparing exists in one of the other edges, then we can constant fold ICI 3772 // and zap it. 3773 if (SI->findCaseValue(Cst) != SI->case_default()) { 3774 Value *V; 3775 if (ICI->getPredicate() == ICmpInst::ICMP_EQ) 3776 V = ConstantInt::getFalse(BB->getContext()); 3777 else 3778 V = ConstantInt::getTrue(BB->getContext()); 3779 3780 ICI->replaceAllUsesWith(V); 3781 ICI->eraseFromParent(); 3782 // BB is now empty, so it is likely to simplify away. 3783 return requestResimplify(); 3784 } 3785 3786 // The use of the icmp has to be in the 'end' block, by the only PHI node in 3787 // the block. 3788 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0); 3789 PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back()); 3790 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() || 3791 isa<PHINode>(++BasicBlock::iterator(PHIUse))) 3792 return false; 3793 3794 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets 3795 // true in the PHI. 3796 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext()); 3797 Constant *NewCst = ConstantInt::getFalse(BB->getContext()); 3798 3799 if (ICI->getPredicate() == ICmpInst::ICMP_EQ) 3800 std::swap(DefaultCst, NewCst); 3801 3802 // Replace ICI (which is used by the PHI for the default value) with true or 3803 // false depending on if it is EQ or NE. 3804 ICI->replaceAllUsesWith(DefaultCst); 3805 ICI->eraseFromParent(); 3806 3807 // Okay, the switch goes to this block on a default value. Add an edge from 3808 // the switch to the merge point on the compared value. 3809 BasicBlock *NewBB = 3810 BasicBlock::Create(BB->getContext(), "switch.edge", BB->getParent(), BB); 3811 { 3812 SwitchInstProfUpdateWrapper SIW(*SI); 3813 auto W0 = SIW.getSuccessorWeight(0); 3814 SwitchInstProfUpdateWrapper::CaseWeightOpt NewW; 3815 if (W0) { 3816 NewW = ((uint64_t(*W0) + 1) >> 1); 3817 SIW.setSuccessorWeight(0, *NewW); 3818 } 3819 SIW.addCase(Cst, NewBB, NewW); 3820 } 3821 3822 // NewBB branches to the phi block, add the uncond branch and the phi entry. 3823 Builder.SetInsertPoint(NewBB); 3824 Builder.SetCurrentDebugLocation(SI->getDebugLoc()); 3825 Builder.CreateBr(SuccBlock); 3826 PHIUse->addIncoming(NewCst, NewBB); 3827 return true; 3828 } 3829 3830 /// The specified branch is a conditional branch. 3831 /// Check to see if it is branching on an or/and chain of icmp instructions, and 3832 /// fold it into a switch instruction if so. 3833 bool SimplifyCFGOpt::SimplifyBranchOnICmpChain(BranchInst *BI, 3834 IRBuilder<> &Builder, 3835 const DataLayout &DL) { 3836 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition()); 3837 if (!Cond) 3838 return false; 3839 3840 // Change br (X == 0 | X == 1), T, F into a switch instruction. 3841 // If this is a bunch of seteq's or'd together, or if it's a bunch of 3842 // 'setne's and'ed together, collect them. 3843 3844 // Try to gather values from a chain of and/or to be turned into a switch 3845 ConstantComparesGatherer ConstantCompare(Cond, DL); 3846 // Unpack the result 3847 SmallVectorImpl<ConstantInt *> &Values = ConstantCompare.Vals; 3848 Value *CompVal = ConstantCompare.CompValue; 3849 unsigned UsedICmps = ConstantCompare.UsedICmps; 3850 Value *ExtraCase = ConstantCompare.Extra; 3851 3852 // If we didn't have a multiply compared value, fail. 3853 if (!CompVal) 3854 return false; 3855 3856 // Avoid turning single icmps into a switch. 3857 if (UsedICmps <= 1) 3858 return false; 3859 3860 bool TrueWhenEqual = (Cond->getOpcode() == Instruction::Or); 3861 3862 // There might be duplicate constants in the list, which the switch 3863 // instruction can't handle, remove them now. 3864 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate); 3865 Values.erase(std::unique(Values.begin(), Values.end()), Values.end()); 3866 3867 // If Extra was used, we require at least two switch values to do the 3868 // transformation. A switch with one value is just a conditional branch. 3869 if (ExtraCase && Values.size() < 2) 3870 return false; 3871 3872 // TODO: Preserve branch weight metadata, similarly to how 3873 // FoldValueComparisonIntoPredecessors preserves it. 3874 3875 // Figure out which block is which destination. 3876 BasicBlock *DefaultBB = BI->getSuccessor(1); 3877 BasicBlock *EdgeBB = BI->getSuccessor(0); 3878 if (!TrueWhenEqual) 3879 std::swap(DefaultBB, EdgeBB); 3880 3881 BasicBlock *BB = BI->getParent(); 3882 3883 // MSAN does not like undefs as branch condition which can be introduced 3884 // with "explicit branch". 3885 if (ExtraCase && BB->getParent()->hasFnAttribute(Attribute::SanitizeMemory)) 3886 return false; 3887 3888 LLVM_DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size() 3889 << " cases into SWITCH. BB is:\n" 3890 << *BB); 3891 3892 // If there are any extra values that couldn't be folded into the switch 3893 // then we evaluate them with an explicit branch first. Split the block 3894 // right before the condbr to handle it. 3895 if (ExtraCase) { 3896 BasicBlock *NewBB = 3897 BB->splitBasicBlock(BI->getIterator(), "switch.early.test"); 3898 // Remove the uncond branch added to the old block. 3899 Instruction *OldTI = BB->getTerminator(); 3900 Builder.SetInsertPoint(OldTI); 3901 3902 if (TrueWhenEqual) 3903 Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB); 3904 else 3905 Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB); 3906 3907 OldTI->eraseFromParent(); 3908 3909 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them 3910 // for the edge we just added. 3911 AddPredecessorToBlock(EdgeBB, BB, NewBB); 3912 3913 LLVM_DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase 3914 << "\nEXTRABB = " << *BB); 3915 BB = NewBB; 3916 } 3917 3918 Builder.SetInsertPoint(BI); 3919 // Convert pointer to int before we switch. 3920 if (CompVal->getType()->isPointerTy()) { 3921 CompVal = Builder.CreatePtrToInt( 3922 CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr"); 3923 } 3924 3925 // Create the new switch instruction now. 3926 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size()); 3927 3928 // Add all of the 'cases' to the switch instruction. 3929 for (unsigned i = 0, e = Values.size(); i != e; ++i) 3930 New->addCase(Values[i], EdgeBB); 3931 3932 // We added edges from PI to the EdgeBB. As such, if there were any 3933 // PHI nodes in EdgeBB, they need entries to be added corresponding to 3934 // the number of edges added. 3935 for (BasicBlock::iterator BBI = EdgeBB->begin(); isa<PHINode>(BBI); ++BBI) { 3936 PHINode *PN = cast<PHINode>(BBI); 3937 Value *InVal = PN->getIncomingValueForBlock(BB); 3938 for (unsigned i = 0, e = Values.size() - 1; i != e; ++i) 3939 PN->addIncoming(InVal, BB); 3940 } 3941 3942 // Erase the old branch instruction. 3943 EraseTerminatorAndDCECond(BI); 3944 3945 LLVM_DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n'); 3946 return true; 3947 } 3948 3949 bool SimplifyCFGOpt::simplifyResume(ResumeInst *RI, IRBuilder<> &Builder) { 3950 if (isa<PHINode>(RI->getValue())) 3951 return simplifyCommonResume(RI); 3952 else if (isa<LandingPadInst>(RI->getParent()->getFirstNonPHI()) && 3953 RI->getValue() == RI->getParent()->getFirstNonPHI()) 3954 // The resume must unwind the exception that caused control to branch here. 3955 return simplifySingleResume(RI); 3956 3957 return false; 3958 } 3959 3960 // Simplify resume that is shared by several landing pads (phi of landing pad). 3961 bool SimplifyCFGOpt::simplifyCommonResume(ResumeInst *RI) { 3962 BasicBlock *BB = RI->getParent(); 3963 3964 // Check that there are no other instructions except for debug intrinsics 3965 // between the phi of landing pads (RI->getValue()) and resume instruction. 3966 BasicBlock::iterator I = cast<Instruction>(RI->getValue())->getIterator(), 3967 E = RI->getIterator(); 3968 while (++I != E) 3969 if (!isa<DbgInfoIntrinsic>(I)) 3970 return false; 3971 3972 SmallSetVector<BasicBlock *, 4> TrivialUnwindBlocks; 3973 auto *PhiLPInst = cast<PHINode>(RI->getValue()); 3974 3975 // Check incoming blocks to see if any of them are trivial. 3976 for (unsigned Idx = 0, End = PhiLPInst->getNumIncomingValues(); Idx != End; 3977 Idx++) { 3978 auto *IncomingBB = PhiLPInst->getIncomingBlock(Idx); 3979 auto *IncomingValue = PhiLPInst->getIncomingValue(Idx); 3980 3981 // If the block has other successors, we can not delete it because 3982 // it has other dependents. 3983 if (IncomingBB->getUniqueSuccessor() != BB) 3984 continue; 3985 3986 auto *LandingPad = dyn_cast<LandingPadInst>(IncomingBB->getFirstNonPHI()); 3987 // Not the landing pad that caused the control to branch here. 3988 if (IncomingValue != LandingPad) 3989 continue; 3990 3991 bool isTrivial = true; 3992 3993 I = IncomingBB->getFirstNonPHI()->getIterator(); 3994 E = IncomingBB->getTerminator()->getIterator(); 3995 while (++I != E) 3996 if (!isa<DbgInfoIntrinsic>(I)) { 3997 isTrivial = false; 3998 break; 3999 } 4000 4001 if (isTrivial) 4002 TrivialUnwindBlocks.insert(IncomingBB); 4003 } 4004 4005 // If no trivial unwind blocks, don't do any simplifications. 4006 if (TrivialUnwindBlocks.empty()) 4007 return false; 4008 4009 // Turn all invokes that unwind here into calls. 4010 for (auto *TrivialBB : TrivialUnwindBlocks) { 4011 // Blocks that will be simplified should be removed from the phi node. 4012 // Note there could be multiple edges to the resume block, and we need 4013 // to remove them all. 4014 while (PhiLPInst->getBasicBlockIndex(TrivialBB) != -1) 4015 BB->removePredecessor(TrivialBB, true); 4016 4017 for (pred_iterator PI = pred_begin(TrivialBB), PE = pred_end(TrivialBB); 4018 PI != PE;) { 4019 BasicBlock *Pred = *PI++; 4020 removeUnwindEdge(Pred); 4021 } 4022 4023 // In each SimplifyCFG run, only the current processed block can be erased. 4024 // Otherwise, it will break the iteration of SimplifyCFG pass. So instead 4025 // of erasing TrivialBB, we only remove the branch to the common resume 4026 // block so that we can later erase the resume block since it has no 4027 // predecessors. 4028 TrivialBB->getTerminator()->eraseFromParent(); 4029 new UnreachableInst(RI->getContext(), TrivialBB); 4030 } 4031 4032 // Delete the resume block if all its predecessors have been removed. 4033 if (pred_empty(BB)) 4034 BB->eraseFromParent(); 4035 4036 return !TrivialUnwindBlocks.empty(); 4037 } 4038 4039 // Check if cleanup block is empty 4040 static bool isCleanupBlockEmpty(Instruction *Inst, Instruction *RI) { 4041 BasicBlock::iterator I = Inst->getIterator(), E = RI->getIterator(); 4042 while (++I != E) { 4043 auto *II = dyn_cast<IntrinsicInst>(I); 4044 if (!II) 4045 return false; 4046 4047 Intrinsic::ID IntrinsicID = II->getIntrinsicID(); 4048 switch (IntrinsicID) { 4049 case Intrinsic::dbg_declare: 4050 case Intrinsic::dbg_value: 4051 case Intrinsic::dbg_label: 4052 case Intrinsic::lifetime_end: 4053 break; 4054 default: 4055 return false; 4056 } 4057 } 4058 return true; 4059 } 4060 4061 // Simplify resume that is only used by a single (non-phi) landing pad. 4062 bool SimplifyCFGOpt::simplifySingleResume(ResumeInst *RI) { 4063 BasicBlock *BB = RI->getParent(); 4064 auto *LPInst = cast<LandingPadInst>(BB->getFirstNonPHI()); 4065 assert(RI->getValue() == LPInst && 4066 "Resume must unwind the exception that caused control to here"); 4067 4068 // Check that there are no other instructions except for debug intrinsics. 4069 if (!isCleanupBlockEmpty(LPInst, RI)) 4070 return false; 4071 4072 // Turn all invokes that unwind here into calls and delete the basic block. 4073 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) { 4074 BasicBlock *Pred = *PI++; 4075 removeUnwindEdge(Pred); 4076 } 4077 4078 // The landingpad is now unreachable. Zap it. 4079 if (LoopHeaders) 4080 LoopHeaders->erase(BB); 4081 BB->eraseFromParent(); 4082 return true; 4083 } 4084 4085 static bool removeEmptyCleanup(CleanupReturnInst *RI) { 4086 // If this is a trivial cleanup pad that executes no instructions, it can be 4087 // eliminated. If the cleanup pad continues to the caller, any predecessor 4088 // that is an EH pad will be updated to continue to the caller and any 4089 // predecessor that terminates with an invoke instruction will have its invoke 4090 // instruction converted to a call instruction. If the cleanup pad being 4091 // simplified does not continue to the caller, each predecessor will be 4092 // updated to continue to the unwind destination of the cleanup pad being 4093 // simplified. 4094 BasicBlock *BB = RI->getParent(); 4095 CleanupPadInst *CPInst = RI->getCleanupPad(); 4096 if (CPInst->getParent() != BB) 4097 // This isn't an empty cleanup. 4098 return false; 4099 4100 // We cannot kill the pad if it has multiple uses. This typically arises 4101 // from unreachable basic blocks. 4102 if (!CPInst->hasOneUse()) 4103 return false; 4104 4105 // Check that there are no other instructions except for benign intrinsics. 4106 if (!isCleanupBlockEmpty(CPInst, RI)) 4107 return false; 4108 4109 // If the cleanup return we are simplifying unwinds to the caller, this will 4110 // set UnwindDest to nullptr. 4111 BasicBlock *UnwindDest = RI->getUnwindDest(); 4112 Instruction *DestEHPad = UnwindDest ? UnwindDest->getFirstNonPHI() : nullptr; 4113 4114 // We're about to remove BB from the control flow. Before we do, sink any 4115 // PHINodes into the unwind destination. Doing this before changing the 4116 // control flow avoids some potentially slow checks, since we can currently 4117 // be certain that UnwindDest and BB have no common predecessors (since they 4118 // are both EH pads). 4119 if (UnwindDest) { 4120 // First, go through the PHI nodes in UnwindDest and update any nodes that 4121 // reference the block we are removing 4122 for (BasicBlock::iterator I = UnwindDest->begin(), 4123 IE = DestEHPad->getIterator(); 4124 I != IE; ++I) { 4125 PHINode *DestPN = cast<PHINode>(I); 4126 4127 int Idx = DestPN->getBasicBlockIndex(BB); 4128 // Since BB unwinds to UnwindDest, it has to be in the PHI node. 4129 assert(Idx != -1); 4130 // This PHI node has an incoming value that corresponds to a control 4131 // path through the cleanup pad we are removing. If the incoming 4132 // value is in the cleanup pad, it must be a PHINode (because we 4133 // verified above that the block is otherwise empty). Otherwise, the 4134 // value is either a constant or a value that dominates the cleanup 4135 // pad being removed. 4136 // 4137 // Because BB and UnwindDest are both EH pads, all of their 4138 // predecessors must unwind to these blocks, and since no instruction 4139 // can have multiple unwind destinations, there will be no overlap in 4140 // incoming blocks between SrcPN and DestPN. 4141 Value *SrcVal = DestPN->getIncomingValue(Idx); 4142 PHINode *SrcPN = dyn_cast<PHINode>(SrcVal); 4143 4144 // Remove the entry for the block we are deleting. 4145 DestPN->removeIncomingValue(Idx, false); 4146 4147 if (SrcPN && SrcPN->getParent() == BB) { 4148 // If the incoming value was a PHI node in the cleanup pad we are 4149 // removing, we need to merge that PHI node's incoming values into 4150 // DestPN. 4151 for (unsigned SrcIdx = 0, SrcE = SrcPN->getNumIncomingValues(); 4152 SrcIdx != SrcE; ++SrcIdx) { 4153 DestPN->addIncoming(SrcPN->getIncomingValue(SrcIdx), 4154 SrcPN->getIncomingBlock(SrcIdx)); 4155 } 4156 } else { 4157 // Otherwise, the incoming value came from above BB and 4158 // so we can just reuse it. We must associate all of BB's 4159 // predecessors with this value. 4160 for (auto *pred : predecessors(BB)) { 4161 DestPN->addIncoming(SrcVal, pred); 4162 } 4163 } 4164 } 4165 4166 // Sink any remaining PHI nodes directly into UnwindDest. 4167 Instruction *InsertPt = DestEHPad; 4168 for (BasicBlock::iterator I = BB->begin(), 4169 IE = BB->getFirstNonPHI()->getIterator(); 4170 I != IE;) { 4171 // The iterator must be incremented here because the instructions are 4172 // being moved to another block. 4173 PHINode *PN = cast<PHINode>(I++); 4174 if (PN->use_empty() || !PN->isUsedOutsideOfBlock(BB)) 4175 // If the PHI node has no uses or all of its uses are in this basic 4176 // block (meaning they are debug or lifetime intrinsics), just leave 4177 // it. It will be erased when we erase BB below. 4178 continue; 4179 4180 // Otherwise, sink this PHI node into UnwindDest. 4181 // Any predecessors to UnwindDest which are not already represented 4182 // must be back edges which inherit the value from the path through 4183 // BB. In this case, the PHI value must reference itself. 4184 for (auto *pred : predecessors(UnwindDest)) 4185 if (pred != BB) 4186 PN->addIncoming(PN, pred); 4187 PN->moveBefore(InsertPt); 4188 } 4189 } 4190 4191 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) { 4192 // The iterator must be updated here because we are removing this pred. 4193 BasicBlock *PredBB = *PI++; 4194 if (UnwindDest == nullptr) { 4195 removeUnwindEdge(PredBB); 4196 } else { 4197 Instruction *TI = PredBB->getTerminator(); 4198 TI->replaceUsesOfWith(BB, UnwindDest); 4199 } 4200 } 4201 4202 // The cleanup pad is now unreachable. Zap it. 4203 BB->eraseFromParent(); 4204 return true; 4205 } 4206 4207 // Try to merge two cleanuppads together. 4208 static bool mergeCleanupPad(CleanupReturnInst *RI) { 4209 // Skip any cleanuprets which unwind to caller, there is nothing to merge 4210 // with. 4211 BasicBlock *UnwindDest = RI->getUnwindDest(); 4212 if (!UnwindDest) 4213 return false; 4214 4215 // This cleanupret isn't the only predecessor of this cleanuppad, it wouldn't 4216 // be safe to merge without code duplication. 4217 if (UnwindDest->getSinglePredecessor() != RI->getParent()) 4218 return false; 4219 4220 // Verify that our cleanuppad's unwind destination is another cleanuppad. 4221 auto *SuccessorCleanupPad = dyn_cast<CleanupPadInst>(&UnwindDest->front()); 4222 if (!SuccessorCleanupPad) 4223 return false; 4224 4225 CleanupPadInst *PredecessorCleanupPad = RI->getCleanupPad(); 4226 // Replace any uses of the successor cleanupad with the predecessor pad 4227 // The only cleanuppad uses should be this cleanupret, it's cleanupret and 4228 // funclet bundle operands. 4229 SuccessorCleanupPad->replaceAllUsesWith(PredecessorCleanupPad); 4230 // Remove the old cleanuppad. 4231 SuccessorCleanupPad->eraseFromParent(); 4232 // Now, we simply replace the cleanupret with a branch to the unwind 4233 // destination. 4234 BranchInst::Create(UnwindDest, RI->getParent()); 4235 RI->eraseFromParent(); 4236 4237 return true; 4238 } 4239 4240 bool SimplifyCFGOpt::simplifyCleanupReturn(CleanupReturnInst *RI) { 4241 // It is possible to transiantly have an undef cleanuppad operand because we 4242 // have deleted some, but not all, dead blocks. 4243 // Eventually, this block will be deleted. 4244 if (isa<UndefValue>(RI->getOperand(0))) 4245 return false; 4246 4247 if (mergeCleanupPad(RI)) 4248 return true; 4249 4250 if (removeEmptyCleanup(RI)) 4251 return true; 4252 4253 return false; 4254 } 4255 4256 bool SimplifyCFGOpt::simplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) { 4257 BasicBlock *BB = RI->getParent(); 4258 if (!BB->getFirstNonPHIOrDbg()->isTerminator()) 4259 return false; 4260 4261 // Find predecessors that end with branches. 4262 SmallVector<BasicBlock *, 8> UncondBranchPreds; 4263 SmallVector<BranchInst *, 8> CondBranchPreds; 4264 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) { 4265 BasicBlock *P = *PI; 4266 Instruction *PTI = P->getTerminator(); 4267 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) { 4268 if (BI->isUnconditional()) 4269 UncondBranchPreds.push_back(P); 4270 else 4271 CondBranchPreds.push_back(BI); 4272 } 4273 } 4274 4275 // If we found some, do the transformation! 4276 if (!UncondBranchPreds.empty() && DupRet) { 4277 while (!UncondBranchPreds.empty()) { 4278 BasicBlock *Pred = UncondBranchPreds.pop_back_val(); 4279 LLVM_DEBUG(dbgs() << "FOLDING: " << *BB 4280 << "INTO UNCOND BRANCH PRED: " << *Pred); 4281 (void)FoldReturnIntoUncondBranch(RI, BB, Pred); 4282 } 4283 4284 // If we eliminated all predecessors of the block, delete the block now. 4285 if (pred_empty(BB)) { 4286 // We know there are no successors, so just nuke the block. 4287 if (LoopHeaders) 4288 LoopHeaders->erase(BB); 4289 BB->eraseFromParent(); 4290 } 4291 4292 return true; 4293 } 4294 4295 // Check out all of the conditional branches going to this return 4296 // instruction. If any of them just select between returns, change the 4297 // branch itself into a select/return pair. 4298 while (!CondBranchPreds.empty()) { 4299 BranchInst *BI = CondBranchPreds.pop_back_val(); 4300 4301 // Check to see if the non-BB successor is also a return block. 4302 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) && 4303 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) && 4304 SimplifyCondBranchToTwoReturns(BI, Builder)) 4305 return true; 4306 } 4307 return false; 4308 } 4309 4310 bool SimplifyCFGOpt::simplifyUnreachable(UnreachableInst *UI) { 4311 BasicBlock *BB = UI->getParent(); 4312 4313 bool Changed = false; 4314 4315 // If there are any instructions immediately before the unreachable that can 4316 // be removed, do so. 4317 while (UI->getIterator() != BB->begin()) { 4318 BasicBlock::iterator BBI = UI->getIterator(); 4319 --BBI; 4320 // Do not delete instructions that can have side effects which might cause 4321 // the unreachable to not be reachable; specifically, calls and volatile 4322 // operations may have this effect. 4323 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) 4324 break; 4325 4326 if (BBI->mayHaveSideEffects()) { 4327 if (auto *SI = dyn_cast<StoreInst>(BBI)) { 4328 if (SI->isVolatile()) 4329 break; 4330 } else if (auto *LI = dyn_cast<LoadInst>(BBI)) { 4331 if (LI->isVolatile()) 4332 break; 4333 } else if (auto *RMWI = dyn_cast<AtomicRMWInst>(BBI)) { 4334 if (RMWI->isVolatile()) 4335 break; 4336 } else if (auto *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) { 4337 if (CXI->isVolatile()) 4338 break; 4339 } else if (isa<CatchPadInst>(BBI)) { 4340 // A catchpad may invoke exception object constructors and such, which 4341 // in some languages can be arbitrary code, so be conservative by 4342 // default. 4343 // For CoreCLR, it just involves a type test, so can be removed. 4344 if (classifyEHPersonality(BB->getParent()->getPersonalityFn()) != 4345 EHPersonality::CoreCLR) 4346 break; 4347 } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) && 4348 !isa<LandingPadInst>(BBI)) { 4349 break; 4350 } 4351 // Note that deleting LandingPad's here is in fact okay, although it 4352 // involves a bit of subtle reasoning. If this inst is a LandingPad, 4353 // all the predecessors of this block will be the unwind edges of Invokes, 4354 // and we can therefore guarantee this block will be erased. 4355 } 4356 4357 // Delete this instruction (any uses are guaranteed to be dead) 4358 if (!BBI->use_empty()) 4359 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType())); 4360 BBI->eraseFromParent(); 4361 Changed = true; 4362 } 4363 4364 // If the unreachable instruction is the first in the block, take a gander 4365 // at all of the predecessors of this instruction, and simplify them. 4366 if (&BB->front() != UI) 4367 return Changed; 4368 4369 SmallVector<BasicBlock *, 8> Preds(pred_begin(BB), pred_end(BB)); 4370 for (unsigned i = 0, e = Preds.size(); i != e; ++i) { 4371 Instruction *TI = Preds[i]->getTerminator(); 4372 IRBuilder<> Builder(TI); 4373 if (auto *BI = dyn_cast<BranchInst>(TI)) { 4374 if (BI->isUnconditional()) { 4375 assert(BI->getSuccessor(0) == BB && "Incorrect CFG"); 4376 new UnreachableInst(TI->getContext(), TI); 4377 TI->eraseFromParent(); 4378 Changed = true; 4379 } else { 4380 Value* Cond = BI->getCondition(); 4381 if (BI->getSuccessor(0) == BB) { 4382 Builder.CreateAssumption(Builder.CreateNot(Cond)); 4383 Builder.CreateBr(BI->getSuccessor(1)); 4384 } else { 4385 assert(BI->getSuccessor(1) == BB && "Incorrect CFG"); 4386 Builder.CreateAssumption(Cond); 4387 Builder.CreateBr(BI->getSuccessor(0)); 4388 } 4389 EraseTerminatorAndDCECond(BI); 4390 Changed = true; 4391 } 4392 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) { 4393 SwitchInstProfUpdateWrapper SU(*SI); 4394 for (auto i = SU->case_begin(), e = SU->case_end(); i != e;) { 4395 if (i->getCaseSuccessor() != BB) { 4396 ++i; 4397 continue; 4398 } 4399 BB->removePredecessor(SU->getParent()); 4400 i = SU.removeCase(i); 4401 e = SU->case_end(); 4402 Changed = true; 4403 } 4404 } else if (auto *II = dyn_cast<InvokeInst>(TI)) { 4405 if (II->getUnwindDest() == BB) { 4406 removeUnwindEdge(TI->getParent()); 4407 Changed = true; 4408 } 4409 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) { 4410 if (CSI->getUnwindDest() == BB) { 4411 removeUnwindEdge(TI->getParent()); 4412 Changed = true; 4413 continue; 4414 } 4415 4416 for (CatchSwitchInst::handler_iterator I = CSI->handler_begin(), 4417 E = CSI->handler_end(); 4418 I != E; ++I) { 4419 if (*I == BB) { 4420 CSI->removeHandler(I); 4421 --I; 4422 --E; 4423 Changed = true; 4424 } 4425 } 4426 if (CSI->getNumHandlers() == 0) { 4427 BasicBlock *CatchSwitchBB = CSI->getParent(); 4428 if (CSI->hasUnwindDest()) { 4429 // Redirect preds to the unwind dest 4430 CatchSwitchBB->replaceAllUsesWith(CSI->getUnwindDest()); 4431 } else { 4432 // Rewrite all preds to unwind to caller (or from invoke to call). 4433 SmallVector<BasicBlock *, 8> EHPreds(predecessors(CatchSwitchBB)); 4434 for (BasicBlock *EHPred : EHPreds) 4435 removeUnwindEdge(EHPred); 4436 } 4437 // The catchswitch is no longer reachable. 4438 new UnreachableInst(CSI->getContext(), CSI); 4439 CSI->eraseFromParent(); 4440 Changed = true; 4441 } 4442 } else if (isa<CleanupReturnInst>(TI)) { 4443 new UnreachableInst(TI->getContext(), TI); 4444 TI->eraseFromParent(); 4445 Changed = true; 4446 } 4447 } 4448 4449 // If this block is now dead, remove it. 4450 if (pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) { 4451 // We know there are no successors, so just nuke the block. 4452 if (LoopHeaders) 4453 LoopHeaders->erase(BB); 4454 BB->eraseFromParent(); 4455 return true; 4456 } 4457 4458 return Changed; 4459 } 4460 4461 static bool CasesAreContiguous(SmallVectorImpl<ConstantInt *> &Cases) { 4462 assert(Cases.size() >= 1); 4463 4464 array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate); 4465 for (size_t I = 1, E = Cases.size(); I != E; ++I) { 4466 if (Cases[I - 1]->getValue() != Cases[I]->getValue() + 1) 4467 return false; 4468 } 4469 return true; 4470 } 4471 4472 static void createUnreachableSwitchDefault(SwitchInst *Switch) { 4473 LLVM_DEBUG(dbgs() << "SimplifyCFG: switch default is dead.\n"); 4474 BasicBlock *NewDefaultBlock = 4475 SplitBlockPredecessors(Switch->getDefaultDest(), Switch->getParent(), ""); 4476 Switch->setDefaultDest(&*NewDefaultBlock); 4477 SplitBlock(&*NewDefaultBlock, &NewDefaultBlock->front()); 4478 auto *NewTerminator = NewDefaultBlock->getTerminator(); 4479 new UnreachableInst(Switch->getContext(), NewTerminator); 4480 EraseTerminatorAndDCECond(NewTerminator); 4481 } 4482 4483 /// Turn a switch with two reachable destinations into an integer range 4484 /// comparison and branch. 4485 bool SimplifyCFGOpt::TurnSwitchRangeIntoICmp(SwitchInst *SI, 4486 IRBuilder<> &Builder) { 4487 assert(SI->getNumCases() > 1 && "Degenerate switch?"); 4488 4489 bool HasDefault = 4490 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg()); 4491 4492 // Partition the cases into two sets with different destinations. 4493 BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr; 4494 BasicBlock *DestB = nullptr; 4495 SmallVector<ConstantInt *, 16> CasesA; 4496 SmallVector<ConstantInt *, 16> CasesB; 4497 4498 for (auto Case : SI->cases()) { 4499 BasicBlock *Dest = Case.getCaseSuccessor(); 4500 if (!DestA) 4501 DestA = Dest; 4502 if (Dest == DestA) { 4503 CasesA.push_back(Case.getCaseValue()); 4504 continue; 4505 } 4506 if (!DestB) 4507 DestB = Dest; 4508 if (Dest == DestB) { 4509 CasesB.push_back(Case.getCaseValue()); 4510 continue; 4511 } 4512 return false; // More than two destinations. 4513 } 4514 4515 assert(DestA && DestB && 4516 "Single-destination switch should have been folded."); 4517 assert(DestA != DestB); 4518 assert(DestB != SI->getDefaultDest()); 4519 assert(!CasesB.empty() && "There must be non-default cases."); 4520 assert(!CasesA.empty() || HasDefault); 4521 4522 // Figure out if one of the sets of cases form a contiguous range. 4523 SmallVectorImpl<ConstantInt *> *ContiguousCases = nullptr; 4524 BasicBlock *ContiguousDest = nullptr; 4525 BasicBlock *OtherDest = nullptr; 4526 if (!CasesA.empty() && CasesAreContiguous(CasesA)) { 4527 ContiguousCases = &CasesA; 4528 ContiguousDest = DestA; 4529 OtherDest = DestB; 4530 } else if (CasesAreContiguous(CasesB)) { 4531 ContiguousCases = &CasesB; 4532 ContiguousDest = DestB; 4533 OtherDest = DestA; 4534 } else 4535 return false; 4536 4537 // Start building the compare and branch. 4538 4539 Constant *Offset = ConstantExpr::getNeg(ContiguousCases->back()); 4540 Constant *NumCases = 4541 ConstantInt::get(Offset->getType(), ContiguousCases->size()); 4542 4543 Value *Sub = SI->getCondition(); 4544 if (!Offset->isNullValue()) 4545 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off"); 4546 4547 Value *Cmp; 4548 // If NumCases overflowed, then all possible values jump to the successor. 4549 if (NumCases->isNullValue() && !ContiguousCases->empty()) 4550 Cmp = ConstantInt::getTrue(SI->getContext()); 4551 else 4552 Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch"); 4553 BranchInst *NewBI = Builder.CreateCondBr(Cmp, ContiguousDest, OtherDest); 4554 4555 // Update weight for the newly-created conditional branch. 4556 if (HasBranchWeights(SI)) { 4557 SmallVector<uint64_t, 8> Weights; 4558 GetBranchWeights(SI, Weights); 4559 if (Weights.size() == 1 + SI->getNumCases()) { 4560 uint64_t TrueWeight = 0; 4561 uint64_t FalseWeight = 0; 4562 for (size_t I = 0, E = Weights.size(); I != E; ++I) { 4563 if (SI->getSuccessor(I) == ContiguousDest) 4564 TrueWeight += Weights[I]; 4565 else 4566 FalseWeight += Weights[I]; 4567 } 4568 while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) { 4569 TrueWeight /= 2; 4570 FalseWeight /= 2; 4571 } 4572 setBranchWeights(NewBI, TrueWeight, FalseWeight); 4573 } 4574 } 4575 4576 // Prune obsolete incoming values off the successors' PHI nodes. 4577 for (auto BBI = ContiguousDest->begin(); isa<PHINode>(BBI); ++BBI) { 4578 unsigned PreviousEdges = ContiguousCases->size(); 4579 if (ContiguousDest == SI->getDefaultDest()) 4580 ++PreviousEdges; 4581 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I) 4582 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent()); 4583 } 4584 for (auto BBI = OtherDest->begin(); isa<PHINode>(BBI); ++BBI) { 4585 unsigned PreviousEdges = SI->getNumCases() - ContiguousCases->size(); 4586 if (OtherDest == SI->getDefaultDest()) 4587 ++PreviousEdges; 4588 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I) 4589 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent()); 4590 } 4591 4592 // Clean up the default block - it may have phis or other instructions before 4593 // the unreachable terminator. 4594 if (!HasDefault) 4595 createUnreachableSwitchDefault(SI); 4596 4597 // Drop the switch. 4598 SI->eraseFromParent(); 4599 4600 return true; 4601 } 4602 4603 /// Compute masked bits for the condition of a switch 4604 /// and use it to remove dead cases. 4605 static bool eliminateDeadSwitchCases(SwitchInst *SI, AssumptionCache *AC, 4606 const DataLayout &DL) { 4607 Value *Cond = SI->getCondition(); 4608 unsigned Bits = Cond->getType()->getIntegerBitWidth(); 4609 KnownBits Known = computeKnownBits(Cond, DL, 0, AC, SI); 4610 4611 // We can also eliminate cases by determining that their values are outside of 4612 // the limited range of the condition based on how many significant (non-sign) 4613 // bits are in the condition value. 4614 unsigned ExtraSignBits = ComputeNumSignBits(Cond, DL, 0, AC, SI) - 1; 4615 unsigned MaxSignificantBitsInCond = Bits - ExtraSignBits; 4616 4617 // Gather dead cases. 4618 SmallVector<ConstantInt *, 8> DeadCases; 4619 for (auto &Case : SI->cases()) { 4620 const APInt &CaseVal = Case.getCaseValue()->getValue(); 4621 if (Known.Zero.intersects(CaseVal) || !Known.One.isSubsetOf(CaseVal) || 4622 (CaseVal.getMinSignedBits() > MaxSignificantBitsInCond)) { 4623 DeadCases.push_back(Case.getCaseValue()); 4624 LLVM_DEBUG(dbgs() << "SimplifyCFG: switch case " << CaseVal 4625 << " is dead.\n"); 4626 } 4627 } 4628 4629 // If we can prove that the cases must cover all possible values, the 4630 // default destination becomes dead and we can remove it. If we know some 4631 // of the bits in the value, we can use that to more precisely compute the 4632 // number of possible unique case values. 4633 bool HasDefault = 4634 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg()); 4635 const unsigned NumUnknownBits = 4636 Bits - (Known.Zero | Known.One).countPopulation(); 4637 assert(NumUnknownBits <= Bits); 4638 if (HasDefault && DeadCases.empty() && 4639 NumUnknownBits < 64 /* avoid overflow */ && 4640 SI->getNumCases() == (1ULL << NumUnknownBits)) { 4641 createUnreachableSwitchDefault(SI); 4642 return true; 4643 } 4644 4645 if (DeadCases.empty()) 4646 return false; 4647 4648 SwitchInstProfUpdateWrapper SIW(*SI); 4649 for (ConstantInt *DeadCase : DeadCases) { 4650 SwitchInst::CaseIt CaseI = SI->findCaseValue(DeadCase); 4651 assert(CaseI != SI->case_default() && 4652 "Case was not found. Probably mistake in DeadCases forming."); 4653 // Prune unused values from PHI nodes. 4654 CaseI->getCaseSuccessor()->removePredecessor(SI->getParent()); 4655 SIW.removeCase(CaseI); 4656 } 4657 4658 return true; 4659 } 4660 4661 /// If BB would be eligible for simplification by 4662 /// TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated 4663 /// by an unconditional branch), look at the phi node for BB in the successor 4664 /// block and see if the incoming value is equal to CaseValue. If so, return 4665 /// the phi node, and set PhiIndex to BB's index in the phi node. 4666 static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue, 4667 BasicBlock *BB, int *PhiIndex) { 4668 if (BB->getFirstNonPHIOrDbg() != BB->getTerminator()) 4669 return nullptr; // BB must be empty to be a candidate for simplification. 4670 if (!BB->getSinglePredecessor()) 4671 return nullptr; // BB must be dominated by the switch. 4672 4673 BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator()); 4674 if (!Branch || !Branch->isUnconditional()) 4675 return nullptr; // Terminator must be unconditional branch. 4676 4677 BasicBlock *Succ = Branch->getSuccessor(0); 4678 4679 for (PHINode &PHI : Succ->phis()) { 4680 int Idx = PHI.getBasicBlockIndex(BB); 4681 assert(Idx >= 0 && "PHI has no entry for predecessor?"); 4682 4683 Value *InValue = PHI.getIncomingValue(Idx); 4684 if (InValue != CaseValue) 4685 continue; 4686 4687 *PhiIndex = Idx; 4688 return &PHI; 4689 } 4690 4691 return nullptr; 4692 } 4693 4694 /// Try to forward the condition of a switch instruction to a phi node 4695 /// dominated by the switch, if that would mean that some of the destination 4696 /// blocks of the switch can be folded away. Return true if a change is made. 4697 static bool ForwardSwitchConditionToPHI(SwitchInst *SI) { 4698 using ForwardingNodesMap = DenseMap<PHINode *, SmallVector<int, 4>>; 4699 4700 ForwardingNodesMap ForwardingNodes; 4701 BasicBlock *SwitchBlock = SI->getParent(); 4702 bool Changed = false; 4703 for (auto &Case : SI->cases()) { 4704 ConstantInt *CaseValue = Case.getCaseValue(); 4705 BasicBlock *CaseDest = Case.getCaseSuccessor(); 4706 4707 // Replace phi operands in successor blocks that are using the constant case 4708 // value rather than the switch condition variable: 4709 // switchbb: 4710 // switch i32 %x, label %default [ 4711 // i32 17, label %succ 4712 // ... 4713 // succ: 4714 // %r = phi i32 ... [ 17, %switchbb ] ... 4715 // --> 4716 // %r = phi i32 ... [ %x, %switchbb ] ... 4717 4718 for (PHINode &Phi : CaseDest->phis()) { 4719 // This only works if there is exactly 1 incoming edge from the switch to 4720 // a phi. If there is >1, that means multiple cases of the switch map to 1 4721 // value in the phi, and that phi value is not the switch condition. Thus, 4722 // this transform would not make sense (the phi would be invalid because 4723 // a phi can't have different incoming values from the same block). 4724 int SwitchBBIdx = Phi.getBasicBlockIndex(SwitchBlock); 4725 if (Phi.getIncomingValue(SwitchBBIdx) == CaseValue && 4726 count(Phi.blocks(), SwitchBlock) == 1) { 4727 Phi.setIncomingValue(SwitchBBIdx, SI->getCondition()); 4728 Changed = true; 4729 } 4730 } 4731 4732 // Collect phi nodes that are indirectly using this switch's case constants. 4733 int PhiIdx; 4734 if (auto *Phi = FindPHIForConditionForwarding(CaseValue, CaseDest, &PhiIdx)) 4735 ForwardingNodes[Phi].push_back(PhiIdx); 4736 } 4737 4738 for (auto &ForwardingNode : ForwardingNodes) { 4739 PHINode *Phi = ForwardingNode.first; 4740 SmallVectorImpl<int> &Indexes = ForwardingNode.second; 4741 if (Indexes.size() < 2) 4742 continue; 4743 4744 for (int Index : Indexes) 4745 Phi->setIncomingValue(Index, SI->getCondition()); 4746 Changed = true; 4747 } 4748 4749 return Changed; 4750 } 4751 4752 /// Return true if the backend will be able to handle 4753 /// initializing an array of constants like C. 4754 static bool ValidLookupTableConstant(Constant *C, const TargetTransformInfo &TTI) { 4755 if (C->isThreadDependent()) 4756 return false; 4757 if (C->isDLLImportDependent()) 4758 return false; 4759 4760 if (!isa<ConstantFP>(C) && !isa<ConstantInt>(C) && 4761 !isa<ConstantPointerNull>(C) && !isa<GlobalValue>(C) && 4762 !isa<UndefValue>(C) && !isa<ConstantExpr>(C)) 4763 return false; 4764 4765 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 4766 if (!CE->isGEPWithNoNotionalOverIndexing()) 4767 return false; 4768 if (!ValidLookupTableConstant(CE->getOperand(0), TTI)) 4769 return false; 4770 } 4771 4772 if (!TTI.shouldBuildLookupTablesForConstant(C)) 4773 return false; 4774 4775 return true; 4776 } 4777 4778 /// If V is a Constant, return it. Otherwise, try to look up 4779 /// its constant value in ConstantPool, returning 0 if it's not there. 4780 static Constant * 4781 LookupConstant(Value *V, 4782 const SmallDenseMap<Value *, Constant *> &ConstantPool) { 4783 if (Constant *C = dyn_cast<Constant>(V)) 4784 return C; 4785 return ConstantPool.lookup(V); 4786 } 4787 4788 /// Try to fold instruction I into a constant. This works for 4789 /// simple instructions such as binary operations where both operands are 4790 /// constant or can be replaced by constants from the ConstantPool. Returns the 4791 /// resulting constant on success, 0 otherwise. 4792 static Constant * 4793 ConstantFold(Instruction *I, const DataLayout &DL, 4794 const SmallDenseMap<Value *, Constant *> &ConstantPool) { 4795 if (SelectInst *Select = dyn_cast<SelectInst>(I)) { 4796 Constant *A = LookupConstant(Select->getCondition(), ConstantPool); 4797 if (!A) 4798 return nullptr; 4799 if (A->isAllOnesValue()) 4800 return LookupConstant(Select->getTrueValue(), ConstantPool); 4801 if (A->isNullValue()) 4802 return LookupConstant(Select->getFalseValue(), ConstantPool); 4803 return nullptr; 4804 } 4805 4806 SmallVector<Constant *, 4> COps; 4807 for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) { 4808 if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool)) 4809 COps.push_back(A); 4810 else 4811 return nullptr; 4812 } 4813 4814 if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) { 4815 return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0], 4816 COps[1], DL); 4817 } 4818 4819 return ConstantFoldInstOperands(I, COps, DL); 4820 } 4821 4822 /// Try to determine the resulting constant values in phi nodes 4823 /// at the common destination basic block, *CommonDest, for one of the case 4824 /// destionations CaseDest corresponding to value CaseVal (0 for the default 4825 /// case), of a switch instruction SI. 4826 static bool 4827 GetCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest, 4828 BasicBlock **CommonDest, 4829 SmallVectorImpl<std::pair<PHINode *, Constant *>> &Res, 4830 const DataLayout &DL, const TargetTransformInfo &TTI) { 4831 // The block from which we enter the common destination. 4832 BasicBlock *Pred = SI->getParent(); 4833 4834 // If CaseDest is empty except for some side-effect free instructions through 4835 // which we can constant-propagate the CaseVal, continue to its successor. 4836 SmallDenseMap<Value *, Constant *> ConstantPool; 4837 ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal)); 4838 for (Instruction &I :CaseDest->instructionsWithoutDebug()) { 4839 if (I.isTerminator()) { 4840 // If the terminator is a simple branch, continue to the next block. 4841 if (I.getNumSuccessors() != 1 || I.isExceptionalTerminator()) 4842 return false; 4843 Pred = CaseDest; 4844 CaseDest = I.getSuccessor(0); 4845 } else if (Constant *C = ConstantFold(&I, DL, ConstantPool)) { 4846 // Instruction is side-effect free and constant. 4847 4848 // If the instruction has uses outside this block or a phi node slot for 4849 // the block, it is not safe to bypass the instruction since it would then 4850 // no longer dominate all its uses. 4851 for (auto &Use : I.uses()) { 4852 User *User = Use.getUser(); 4853 if (Instruction *I = dyn_cast<Instruction>(User)) 4854 if (I->getParent() == CaseDest) 4855 continue; 4856 if (PHINode *Phi = dyn_cast<PHINode>(User)) 4857 if (Phi->getIncomingBlock(Use) == CaseDest) 4858 continue; 4859 return false; 4860 } 4861 4862 ConstantPool.insert(std::make_pair(&I, C)); 4863 } else { 4864 break; 4865 } 4866 } 4867 4868 // If we did not have a CommonDest before, use the current one. 4869 if (!*CommonDest) 4870 *CommonDest = CaseDest; 4871 // If the destination isn't the common one, abort. 4872 if (CaseDest != *CommonDest) 4873 return false; 4874 4875 // Get the values for this case from phi nodes in the destination block. 4876 for (PHINode &PHI : (*CommonDest)->phis()) { 4877 int Idx = PHI.getBasicBlockIndex(Pred); 4878 if (Idx == -1) 4879 continue; 4880 4881 Constant *ConstVal = 4882 LookupConstant(PHI.getIncomingValue(Idx), ConstantPool); 4883 if (!ConstVal) 4884 return false; 4885 4886 // Be conservative about which kinds of constants we support. 4887 if (!ValidLookupTableConstant(ConstVal, TTI)) 4888 return false; 4889 4890 Res.push_back(std::make_pair(&PHI, ConstVal)); 4891 } 4892 4893 return Res.size() > 0; 4894 } 4895 4896 // Helper function used to add CaseVal to the list of cases that generate 4897 // Result. Returns the updated number of cases that generate this result. 4898 static uintptr_t MapCaseToResult(ConstantInt *CaseVal, 4899 SwitchCaseResultVectorTy &UniqueResults, 4900 Constant *Result) { 4901 for (auto &I : UniqueResults) { 4902 if (I.first == Result) { 4903 I.second.push_back(CaseVal); 4904 return I.second.size(); 4905 } 4906 } 4907 UniqueResults.push_back( 4908 std::make_pair(Result, SmallVector<ConstantInt *, 4>(1, CaseVal))); 4909 return 1; 4910 } 4911 4912 // Helper function that initializes a map containing 4913 // results for the PHI node of the common destination block for a switch 4914 // instruction. Returns false if multiple PHI nodes have been found or if 4915 // there is not a common destination block for the switch. 4916 static bool 4917 InitializeUniqueCases(SwitchInst *SI, PHINode *&PHI, BasicBlock *&CommonDest, 4918 SwitchCaseResultVectorTy &UniqueResults, 4919 Constant *&DefaultResult, const DataLayout &DL, 4920 const TargetTransformInfo &TTI, 4921 uintptr_t MaxUniqueResults, uintptr_t MaxCasesPerResult) { 4922 for (auto &I : SI->cases()) { 4923 ConstantInt *CaseVal = I.getCaseValue(); 4924 4925 // Resulting value at phi nodes for this case value. 4926 SwitchCaseResultsTy Results; 4927 if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results, 4928 DL, TTI)) 4929 return false; 4930 4931 // Only one value per case is permitted. 4932 if (Results.size() > 1) 4933 return false; 4934 4935 // Add the case->result mapping to UniqueResults. 4936 const uintptr_t NumCasesForResult = 4937 MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second); 4938 4939 // Early out if there are too many cases for this result. 4940 if (NumCasesForResult > MaxCasesPerResult) 4941 return false; 4942 4943 // Early out if there are too many unique results. 4944 if (UniqueResults.size() > MaxUniqueResults) 4945 return false; 4946 4947 // Check the PHI consistency. 4948 if (!PHI) 4949 PHI = Results[0].first; 4950 else if (PHI != Results[0].first) 4951 return false; 4952 } 4953 // Find the default result value. 4954 SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults; 4955 BasicBlock *DefaultDest = SI->getDefaultDest(); 4956 GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults, 4957 DL, TTI); 4958 // If the default value is not found abort unless the default destination 4959 // is unreachable. 4960 DefaultResult = 4961 DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr; 4962 if ((!DefaultResult && 4963 !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg()))) 4964 return false; 4965 4966 return true; 4967 } 4968 4969 // Helper function that checks if it is possible to transform a switch with only 4970 // two cases (or two cases + default) that produces a result into a select. 4971 // Example: 4972 // switch (a) { 4973 // case 10: %0 = icmp eq i32 %a, 10 4974 // return 10; %1 = select i1 %0, i32 10, i32 4 4975 // case 20: ----> %2 = icmp eq i32 %a, 20 4976 // return 2; %3 = select i1 %2, i32 2, i32 %1 4977 // default: 4978 // return 4; 4979 // } 4980 static Value *ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector, 4981 Constant *DefaultResult, Value *Condition, 4982 IRBuilder<> &Builder) { 4983 assert(ResultVector.size() == 2 && 4984 "We should have exactly two unique results at this point"); 4985 // If we are selecting between only two cases transform into a simple 4986 // select or a two-way select if default is possible. 4987 if (ResultVector[0].second.size() == 1 && 4988 ResultVector[1].second.size() == 1) { 4989 ConstantInt *const FirstCase = ResultVector[0].second[0]; 4990 ConstantInt *const SecondCase = ResultVector[1].second[0]; 4991 4992 bool DefaultCanTrigger = DefaultResult; 4993 Value *SelectValue = ResultVector[1].first; 4994 if (DefaultCanTrigger) { 4995 Value *const ValueCompare = 4996 Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp"); 4997 SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first, 4998 DefaultResult, "switch.select"); 4999 } 5000 Value *const ValueCompare = 5001 Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp"); 5002 return Builder.CreateSelect(ValueCompare, ResultVector[0].first, 5003 SelectValue, "switch.select"); 5004 } 5005 5006 return nullptr; 5007 } 5008 5009 // Helper function to cleanup a switch instruction that has been converted into 5010 // a select, fixing up PHI nodes and basic blocks. 5011 static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI, 5012 Value *SelectValue, 5013 IRBuilder<> &Builder) { 5014 BasicBlock *SelectBB = SI->getParent(); 5015 while (PHI->getBasicBlockIndex(SelectBB) >= 0) 5016 PHI->removeIncomingValue(SelectBB); 5017 PHI->addIncoming(SelectValue, SelectBB); 5018 5019 Builder.CreateBr(PHI->getParent()); 5020 5021 // Remove the switch. 5022 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) { 5023 BasicBlock *Succ = SI->getSuccessor(i); 5024 5025 if (Succ == PHI->getParent()) 5026 continue; 5027 Succ->removePredecessor(SelectBB); 5028 } 5029 SI->eraseFromParent(); 5030 } 5031 5032 /// If the switch is only used to initialize one or more 5033 /// phi nodes in a common successor block with only two different 5034 /// constant values, replace the switch with select. 5035 static bool switchToSelect(SwitchInst *SI, IRBuilder<> &Builder, 5036 const DataLayout &DL, 5037 const TargetTransformInfo &TTI) { 5038 Value *const Cond = SI->getCondition(); 5039 PHINode *PHI = nullptr; 5040 BasicBlock *CommonDest = nullptr; 5041 Constant *DefaultResult; 5042 SwitchCaseResultVectorTy UniqueResults; 5043 // Collect all the cases that will deliver the same value from the switch. 5044 if (!InitializeUniqueCases(SI, PHI, CommonDest, UniqueResults, DefaultResult, 5045 DL, TTI, 2, 1)) 5046 return false; 5047 // Selects choose between maximum two values. 5048 if (UniqueResults.size() != 2) 5049 return false; 5050 assert(PHI != nullptr && "PHI for value select not found"); 5051 5052 Builder.SetInsertPoint(SI); 5053 Value *SelectValue = 5054 ConvertTwoCaseSwitch(UniqueResults, DefaultResult, Cond, Builder); 5055 if (SelectValue) { 5056 RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder); 5057 return true; 5058 } 5059 // The switch couldn't be converted into a select. 5060 return false; 5061 } 5062 5063 namespace { 5064 5065 /// This class represents a lookup table that can be used to replace a switch. 5066 class SwitchLookupTable { 5067 public: 5068 /// Create a lookup table to use as a switch replacement with the contents 5069 /// of Values, using DefaultValue to fill any holes in the table. 5070 SwitchLookupTable( 5071 Module &M, uint64_t TableSize, ConstantInt *Offset, 5072 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values, 5073 Constant *DefaultValue, const DataLayout &DL, const StringRef &FuncName); 5074 5075 /// Build instructions with Builder to retrieve the value at 5076 /// the position given by Index in the lookup table. 5077 Value *BuildLookup(Value *Index, IRBuilder<> &Builder); 5078 5079 /// Return true if a table with TableSize elements of 5080 /// type ElementType would fit in a target-legal register. 5081 static bool WouldFitInRegister(const DataLayout &DL, uint64_t TableSize, 5082 Type *ElementType); 5083 5084 private: 5085 // Depending on the contents of the table, it can be represented in 5086 // different ways. 5087 enum { 5088 // For tables where each element contains the same value, we just have to 5089 // store that single value and return it for each lookup. 5090 SingleValueKind, 5091 5092 // For tables where there is a linear relationship between table index 5093 // and values. We calculate the result with a simple multiplication 5094 // and addition instead of a table lookup. 5095 LinearMapKind, 5096 5097 // For small tables with integer elements, we can pack them into a bitmap 5098 // that fits into a target-legal register. Values are retrieved by 5099 // shift and mask operations. 5100 BitMapKind, 5101 5102 // The table is stored as an array of values. Values are retrieved by load 5103 // instructions from the table. 5104 ArrayKind 5105 } Kind; 5106 5107 // For SingleValueKind, this is the single value. 5108 Constant *SingleValue = nullptr; 5109 5110 // For BitMapKind, this is the bitmap. 5111 ConstantInt *BitMap = nullptr; 5112 IntegerType *BitMapElementTy = nullptr; 5113 5114 // For LinearMapKind, these are the constants used to derive the value. 5115 ConstantInt *LinearOffset = nullptr; 5116 ConstantInt *LinearMultiplier = nullptr; 5117 5118 // For ArrayKind, this is the array. 5119 GlobalVariable *Array = nullptr; 5120 }; 5121 5122 } // end anonymous namespace 5123 5124 SwitchLookupTable::SwitchLookupTable( 5125 Module &M, uint64_t TableSize, ConstantInt *Offset, 5126 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values, 5127 Constant *DefaultValue, const DataLayout &DL, const StringRef &FuncName) { 5128 assert(Values.size() && "Can't build lookup table without values!"); 5129 assert(TableSize >= Values.size() && "Can't fit values in table!"); 5130 5131 // If all values in the table are equal, this is that value. 5132 SingleValue = Values.begin()->second; 5133 5134 Type *ValueType = Values.begin()->second->getType(); 5135 5136 // Build up the table contents. 5137 SmallVector<Constant *, 64> TableContents(TableSize); 5138 for (size_t I = 0, E = Values.size(); I != E; ++I) { 5139 ConstantInt *CaseVal = Values[I].first; 5140 Constant *CaseRes = Values[I].second; 5141 assert(CaseRes->getType() == ValueType); 5142 5143 uint64_t Idx = (CaseVal->getValue() - Offset->getValue()).getLimitedValue(); 5144 TableContents[Idx] = CaseRes; 5145 5146 if (CaseRes != SingleValue) 5147 SingleValue = nullptr; 5148 } 5149 5150 // Fill in any holes in the table with the default result. 5151 if (Values.size() < TableSize) { 5152 assert(DefaultValue && 5153 "Need a default value to fill the lookup table holes."); 5154 assert(DefaultValue->getType() == ValueType); 5155 for (uint64_t I = 0; I < TableSize; ++I) { 5156 if (!TableContents[I]) 5157 TableContents[I] = DefaultValue; 5158 } 5159 5160 if (DefaultValue != SingleValue) 5161 SingleValue = nullptr; 5162 } 5163 5164 // If each element in the table contains the same value, we only need to store 5165 // that single value. 5166 if (SingleValue) { 5167 Kind = SingleValueKind; 5168 return; 5169 } 5170 5171 // Check if we can derive the value with a linear transformation from the 5172 // table index. 5173 if (isa<IntegerType>(ValueType)) { 5174 bool LinearMappingPossible = true; 5175 APInt PrevVal; 5176 APInt DistToPrev; 5177 assert(TableSize >= 2 && "Should be a SingleValue table."); 5178 // Check if there is the same distance between two consecutive values. 5179 for (uint64_t I = 0; I < TableSize; ++I) { 5180 ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]); 5181 if (!ConstVal) { 5182 // This is an undef. We could deal with it, but undefs in lookup tables 5183 // are very seldom. It's probably not worth the additional complexity. 5184 LinearMappingPossible = false; 5185 break; 5186 } 5187 const APInt &Val = ConstVal->getValue(); 5188 if (I != 0) { 5189 APInt Dist = Val - PrevVal; 5190 if (I == 1) { 5191 DistToPrev = Dist; 5192 } else if (Dist != DistToPrev) { 5193 LinearMappingPossible = false; 5194 break; 5195 } 5196 } 5197 PrevVal = Val; 5198 } 5199 if (LinearMappingPossible) { 5200 LinearOffset = cast<ConstantInt>(TableContents[0]); 5201 LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev); 5202 Kind = LinearMapKind; 5203 ++NumLinearMaps; 5204 return; 5205 } 5206 } 5207 5208 // If the type is integer and the table fits in a register, build a bitmap. 5209 if (WouldFitInRegister(DL, TableSize, ValueType)) { 5210 IntegerType *IT = cast<IntegerType>(ValueType); 5211 APInt TableInt(TableSize * IT->getBitWidth(), 0); 5212 for (uint64_t I = TableSize; I > 0; --I) { 5213 TableInt <<= IT->getBitWidth(); 5214 // Insert values into the bitmap. Undef values are set to zero. 5215 if (!isa<UndefValue>(TableContents[I - 1])) { 5216 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]); 5217 TableInt |= Val->getValue().zext(TableInt.getBitWidth()); 5218 } 5219 } 5220 BitMap = ConstantInt::get(M.getContext(), TableInt); 5221 BitMapElementTy = IT; 5222 Kind = BitMapKind; 5223 ++NumBitMaps; 5224 return; 5225 } 5226 5227 // Store the table in an array. 5228 ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize); 5229 Constant *Initializer = ConstantArray::get(ArrayTy, TableContents); 5230 5231 Array = new GlobalVariable(M, ArrayTy, /*isConstant=*/true, 5232 GlobalVariable::PrivateLinkage, Initializer, 5233 "switch.table." + FuncName); 5234 Array->setUnnamedAddr(GlobalValue::UnnamedAddr::Global); 5235 // Set the alignment to that of an array items. We will be only loading one 5236 // value out of it. 5237 Array->setAlignment(Align(DL.getPrefTypeAlignment(ValueType))); 5238 Kind = ArrayKind; 5239 } 5240 5241 Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) { 5242 switch (Kind) { 5243 case SingleValueKind: 5244 return SingleValue; 5245 case LinearMapKind: { 5246 // Derive the result value from the input value. 5247 Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(), 5248 false, "switch.idx.cast"); 5249 if (!LinearMultiplier->isOne()) 5250 Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult"); 5251 if (!LinearOffset->isZero()) 5252 Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset"); 5253 return Result; 5254 } 5255 case BitMapKind: { 5256 // Type of the bitmap (e.g. i59). 5257 IntegerType *MapTy = BitMap->getType(); 5258 5259 // Cast Index to the same type as the bitmap. 5260 // Note: The Index is <= the number of elements in the table, so 5261 // truncating it to the width of the bitmask is safe. 5262 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast"); 5263 5264 // Multiply the shift amount by the element width. 5265 ShiftAmt = Builder.CreateMul( 5266 ShiftAmt, ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()), 5267 "switch.shiftamt"); 5268 5269 // Shift down. 5270 Value *DownShifted = 5271 Builder.CreateLShr(BitMap, ShiftAmt, "switch.downshift"); 5272 // Mask off. 5273 return Builder.CreateTrunc(DownShifted, BitMapElementTy, "switch.masked"); 5274 } 5275 case ArrayKind: { 5276 // Make sure the table index will not overflow when treated as signed. 5277 IntegerType *IT = cast<IntegerType>(Index->getType()); 5278 uint64_t TableSize = 5279 Array->getInitializer()->getType()->getArrayNumElements(); 5280 if (TableSize > (1ULL << (IT->getBitWidth() - 1))) 5281 Index = Builder.CreateZExt( 5282 Index, IntegerType::get(IT->getContext(), IT->getBitWidth() + 1), 5283 "switch.tableidx.zext"); 5284 5285 Value *GEPIndices[] = {Builder.getInt32(0), Index}; 5286 Value *GEP = Builder.CreateInBoundsGEP(Array->getValueType(), Array, 5287 GEPIndices, "switch.gep"); 5288 return Builder.CreateLoad( 5289 cast<ArrayType>(Array->getValueType())->getElementType(), GEP, 5290 "switch.load"); 5291 } 5292 } 5293 llvm_unreachable("Unknown lookup table kind!"); 5294 } 5295 5296 bool SwitchLookupTable::WouldFitInRegister(const DataLayout &DL, 5297 uint64_t TableSize, 5298 Type *ElementType) { 5299 auto *IT = dyn_cast<IntegerType>(ElementType); 5300 if (!IT) 5301 return false; 5302 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values 5303 // are <= 15, we could try to narrow the type. 5304 5305 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width. 5306 if (TableSize >= UINT_MAX / IT->getBitWidth()) 5307 return false; 5308 return DL.fitsInLegalInteger(TableSize * IT->getBitWidth()); 5309 } 5310 5311 /// Determine whether a lookup table should be built for this switch, based on 5312 /// the number of cases, size of the table, and the types of the results. 5313 static bool 5314 ShouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize, 5315 const TargetTransformInfo &TTI, const DataLayout &DL, 5316 const SmallDenseMap<PHINode *, Type *> &ResultTypes) { 5317 if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10) 5318 return false; // TableSize overflowed, or mul below might overflow. 5319 5320 bool AllTablesFitInRegister = true; 5321 bool HasIllegalType = false; 5322 for (const auto &I : ResultTypes) { 5323 Type *Ty = I.second; 5324 5325 // Saturate this flag to true. 5326 HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty); 5327 5328 // Saturate this flag to false. 5329 AllTablesFitInRegister = 5330 AllTablesFitInRegister && 5331 SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty); 5332 5333 // If both flags saturate, we're done. NOTE: This *only* works with 5334 // saturating flags, and all flags have to saturate first due to the 5335 // non-deterministic behavior of iterating over a dense map. 5336 if (HasIllegalType && !AllTablesFitInRegister) 5337 break; 5338 } 5339 5340 // If each table would fit in a register, we should build it anyway. 5341 if (AllTablesFitInRegister) 5342 return true; 5343 5344 // Don't build a table that doesn't fit in-register if it has illegal types. 5345 if (HasIllegalType) 5346 return false; 5347 5348 // The table density should be at least 40%. This is the same criterion as for 5349 // jump tables, see SelectionDAGBuilder::handleJTSwitchCase. 5350 // FIXME: Find the best cut-off. 5351 return SI->getNumCases() * 10 >= TableSize * 4; 5352 } 5353 5354 /// Try to reuse the switch table index compare. Following pattern: 5355 /// \code 5356 /// if (idx < tablesize) 5357 /// r = table[idx]; // table does not contain default_value 5358 /// else 5359 /// r = default_value; 5360 /// if (r != default_value) 5361 /// ... 5362 /// \endcode 5363 /// Is optimized to: 5364 /// \code 5365 /// cond = idx < tablesize; 5366 /// if (cond) 5367 /// r = table[idx]; 5368 /// else 5369 /// r = default_value; 5370 /// if (cond) 5371 /// ... 5372 /// \endcode 5373 /// Jump threading will then eliminate the second if(cond). 5374 static void reuseTableCompare( 5375 User *PhiUser, BasicBlock *PhiBlock, BranchInst *RangeCheckBranch, 5376 Constant *DefaultValue, 5377 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values) { 5378 ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser); 5379 if (!CmpInst) 5380 return; 5381 5382 // We require that the compare is in the same block as the phi so that jump 5383 // threading can do its work afterwards. 5384 if (CmpInst->getParent() != PhiBlock) 5385 return; 5386 5387 Constant *CmpOp1 = dyn_cast<Constant>(CmpInst->getOperand(1)); 5388 if (!CmpOp1) 5389 return; 5390 5391 Value *RangeCmp = RangeCheckBranch->getCondition(); 5392 Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType()); 5393 Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType()); 5394 5395 // Check if the compare with the default value is constant true or false. 5396 Constant *DefaultConst = ConstantExpr::getICmp(CmpInst->getPredicate(), 5397 DefaultValue, CmpOp1, true); 5398 if (DefaultConst != TrueConst && DefaultConst != FalseConst) 5399 return; 5400 5401 // Check if the compare with the case values is distinct from the default 5402 // compare result. 5403 for (auto ValuePair : Values) { 5404 Constant *CaseConst = ConstantExpr::getICmp(CmpInst->getPredicate(), 5405 ValuePair.second, CmpOp1, true); 5406 if (!CaseConst || CaseConst == DefaultConst || isa<UndefValue>(CaseConst)) 5407 return; 5408 assert((CaseConst == TrueConst || CaseConst == FalseConst) && 5409 "Expect true or false as compare result."); 5410 } 5411 5412 // Check if the branch instruction dominates the phi node. It's a simple 5413 // dominance check, but sufficient for our needs. 5414 // Although this check is invariant in the calling loops, it's better to do it 5415 // at this late stage. Practically we do it at most once for a switch. 5416 BasicBlock *BranchBlock = RangeCheckBranch->getParent(); 5417 for (auto PI = pred_begin(PhiBlock), E = pred_end(PhiBlock); PI != E; ++PI) { 5418 BasicBlock *Pred = *PI; 5419 if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock) 5420 return; 5421 } 5422 5423 if (DefaultConst == FalseConst) { 5424 // The compare yields the same result. We can replace it. 5425 CmpInst->replaceAllUsesWith(RangeCmp); 5426 ++NumTableCmpReuses; 5427 } else { 5428 // The compare yields the same result, just inverted. We can replace it. 5429 Value *InvertedTableCmp = BinaryOperator::CreateXor( 5430 RangeCmp, ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp", 5431 RangeCheckBranch); 5432 CmpInst->replaceAllUsesWith(InvertedTableCmp); 5433 ++NumTableCmpReuses; 5434 } 5435 } 5436 5437 /// If the switch is only used to initialize one or more phi nodes in a common 5438 /// successor block with different constant values, replace the switch with 5439 /// lookup tables. 5440 static bool SwitchToLookupTable(SwitchInst *SI, IRBuilder<> &Builder, 5441 const DataLayout &DL, 5442 const TargetTransformInfo &TTI) { 5443 assert(SI->getNumCases() > 1 && "Degenerate switch?"); 5444 5445 Function *Fn = SI->getParent()->getParent(); 5446 // Only build lookup table when we have a target that supports it or the 5447 // attribute is not set. 5448 if (!TTI.shouldBuildLookupTables() || 5449 (Fn->getFnAttribute("no-jump-tables").getValueAsString() == "true")) 5450 return false; 5451 5452 // FIXME: If the switch is too sparse for a lookup table, perhaps we could 5453 // split off a dense part and build a lookup table for that. 5454 5455 // FIXME: This creates arrays of GEPs to constant strings, which means each 5456 // GEP needs a runtime relocation in PIC code. We should just build one big 5457 // string and lookup indices into that. 5458 5459 // Ignore switches with less than three cases. Lookup tables will not make 5460 // them faster, so we don't analyze them. 5461 if (SI->getNumCases() < 3) 5462 return false; 5463 5464 // Figure out the corresponding result for each case value and phi node in the 5465 // common destination, as well as the min and max case values. 5466 assert(!SI->cases().empty()); 5467 SwitchInst::CaseIt CI = SI->case_begin(); 5468 ConstantInt *MinCaseVal = CI->getCaseValue(); 5469 ConstantInt *MaxCaseVal = CI->getCaseValue(); 5470 5471 BasicBlock *CommonDest = nullptr; 5472 5473 using ResultListTy = SmallVector<std::pair<ConstantInt *, Constant *>, 4>; 5474 SmallDenseMap<PHINode *, ResultListTy> ResultLists; 5475 5476 SmallDenseMap<PHINode *, Constant *> DefaultResults; 5477 SmallDenseMap<PHINode *, Type *> ResultTypes; 5478 SmallVector<PHINode *, 4> PHIs; 5479 5480 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) { 5481 ConstantInt *CaseVal = CI->getCaseValue(); 5482 if (CaseVal->getValue().slt(MinCaseVal->getValue())) 5483 MinCaseVal = CaseVal; 5484 if (CaseVal->getValue().sgt(MaxCaseVal->getValue())) 5485 MaxCaseVal = CaseVal; 5486 5487 // Resulting value at phi nodes for this case value. 5488 using ResultsTy = SmallVector<std::pair<PHINode *, Constant *>, 4>; 5489 ResultsTy Results; 5490 if (!GetCaseResults(SI, CaseVal, CI->getCaseSuccessor(), &CommonDest, 5491 Results, DL, TTI)) 5492 return false; 5493 5494 // Append the result from this case to the list for each phi. 5495 for (const auto &I : Results) { 5496 PHINode *PHI = I.first; 5497 Constant *Value = I.second; 5498 if (!ResultLists.count(PHI)) 5499 PHIs.push_back(PHI); 5500 ResultLists[PHI].push_back(std::make_pair(CaseVal, Value)); 5501 } 5502 } 5503 5504 // Keep track of the result types. 5505 for (PHINode *PHI : PHIs) { 5506 ResultTypes[PHI] = ResultLists[PHI][0].second->getType(); 5507 } 5508 5509 uint64_t NumResults = ResultLists[PHIs[0]].size(); 5510 APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue(); 5511 uint64_t TableSize = RangeSpread.getLimitedValue() + 1; 5512 bool TableHasHoles = (NumResults < TableSize); 5513 5514 // If the table has holes, we need a constant result for the default case 5515 // or a bitmask that fits in a register. 5516 SmallVector<std::pair<PHINode *, Constant *>, 4> DefaultResultsList; 5517 bool HasDefaultResults = 5518 GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, 5519 DefaultResultsList, DL, TTI); 5520 5521 bool NeedMask = (TableHasHoles && !HasDefaultResults); 5522 if (NeedMask) { 5523 // As an extra penalty for the validity test we require more cases. 5524 if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark). 5525 return false; 5526 if (!DL.fitsInLegalInteger(TableSize)) 5527 return false; 5528 } 5529 5530 for (const auto &I : DefaultResultsList) { 5531 PHINode *PHI = I.first; 5532 Constant *Result = I.second; 5533 DefaultResults[PHI] = Result; 5534 } 5535 5536 if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes)) 5537 return false; 5538 5539 // Create the BB that does the lookups. 5540 Module &Mod = *CommonDest->getParent()->getParent(); 5541 BasicBlock *LookupBB = BasicBlock::Create( 5542 Mod.getContext(), "switch.lookup", CommonDest->getParent(), CommonDest); 5543 5544 // Compute the table index value. 5545 Builder.SetInsertPoint(SI); 5546 Value *TableIndex; 5547 if (MinCaseVal->isNullValue()) 5548 TableIndex = SI->getCondition(); 5549 else 5550 TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal, 5551 "switch.tableidx"); 5552 5553 // Compute the maximum table size representable by the integer type we are 5554 // switching upon. 5555 unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits(); 5556 uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize; 5557 assert(MaxTableSize >= TableSize && 5558 "It is impossible for a switch to have more entries than the max " 5559 "representable value of its input integer type's size."); 5560 5561 // If the default destination is unreachable, or if the lookup table covers 5562 // all values of the conditional variable, branch directly to the lookup table 5563 // BB. Otherwise, check that the condition is within the case range. 5564 const bool DefaultIsReachable = 5565 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg()); 5566 const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize); 5567 BranchInst *RangeCheckBranch = nullptr; 5568 5569 if (!DefaultIsReachable || GeneratingCoveredLookupTable) { 5570 Builder.CreateBr(LookupBB); 5571 // Note: We call removeProdecessor later since we need to be able to get the 5572 // PHI value for the default case in case we're using a bit mask. 5573 } else { 5574 Value *Cmp = Builder.CreateICmpULT( 5575 TableIndex, ConstantInt::get(MinCaseVal->getType(), TableSize)); 5576 RangeCheckBranch = 5577 Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest()); 5578 } 5579 5580 // Populate the BB that does the lookups. 5581 Builder.SetInsertPoint(LookupBB); 5582 5583 if (NeedMask) { 5584 // Before doing the lookup, we do the hole check. The LookupBB is therefore 5585 // re-purposed to do the hole check, and we create a new LookupBB. 5586 BasicBlock *MaskBB = LookupBB; 5587 MaskBB->setName("switch.hole_check"); 5588 LookupBB = BasicBlock::Create(Mod.getContext(), "switch.lookup", 5589 CommonDest->getParent(), CommonDest); 5590 5591 // Make the mask's bitwidth at least 8-bit and a power-of-2 to avoid 5592 // unnecessary illegal types. 5593 uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL)); 5594 APInt MaskInt(TableSizePowOf2, 0); 5595 APInt One(TableSizePowOf2, 1); 5596 // Build bitmask; fill in a 1 bit for every case. 5597 const ResultListTy &ResultList = ResultLists[PHIs[0]]; 5598 for (size_t I = 0, E = ResultList.size(); I != E; ++I) { 5599 uint64_t Idx = (ResultList[I].first->getValue() - MinCaseVal->getValue()) 5600 .getLimitedValue(); 5601 MaskInt |= One << Idx; 5602 } 5603 ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt); 5604 5605 // Get the TableIndex'th bit of the bitmask. 5606 // If this bit is 0 (meaning hole) jump to the default destination, 5607 // else continue with table lookup. 5608 IntegerType *MapTy = TableMask->getType(); 5609 Value *MaskIndex = 5610 Builder.CreateZExtOrTrunc(TableIndex, MapTy, "switch.maskindex"); 5611 Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex, "switch.shifted"); 5612 Value *LoBit = Builder.CreateTrunc( 5613 Shifted, Type::getInt1Ty(Mod.getContext()), "switch.lobit"); 5614 Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest()); 5615 5616 Builder.SetInsertPoint(LookupBB); 5617 AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent()); 5618 } 5619 5620 if (!DefaultIsReachable || GeneratingCoveredLookupTable) { 5621 // We cached PHINodes in PHIs. To avoid accessing deleted PHINodes later, 5622 // do not delete PHINodes here. 5623 SI->getDefaultDest()->removePredecessor(SI->getParent(), 5624 /*KeepOneInputPHIs=*/true); 5625 } 5626 5627 bool ReturnedEarly = false; 5628 for (PHINode *PHI : PHIs) { 5629 const ResultListTy &ResultList = ResultLists[PHI]; 5630 5631 // If using a bitmask, use any value to fill the lookup table holes. 5632 Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI]; 5633 StringRef FuncName = Fn->getName(); 5634 SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL, 5635 FuncName); 5636 5637 Value *Result = Table.BuildLookup(TableIndex, Builder); 5638 5639 // If the result is used to return immediately from the function, we want to 5640 // do that right here. 5641 if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) && 5642 PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) { 5643 Builder.CreateRet(Result); 5644 ReturnedEarly = true; 5645 break; 5646 } 5647 5648 // Do a small peephole optimization: re-use the switch table compare if 5649 // possible. 5650 if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) { 5651 BasicBlock *PhiBlock = PHI->getParent(); 5652 // Search for compare instructions which use the phi. 5653 for (auto *User : PHI->users()) { 5654 reuseTableCompare(User, PhiBlock, RangeCheckBranch, DV, ResultList); 5655 } 5656 } 5657 5658 PHI->addIncoming(Result, LookupBB); 5659 } 5660 5661 if (!ReturnedEarly) 5662 Builder.CreateBr(CommonDest); 5663 5664 // Remove the switch. 5665 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) { 5666 BasicBlock *Succ = SI->getSuccessor(i); 5667 5668 if (Succ == SI->getDefaultDest()) 5669 continue; 5670 Succ->removePredecessor(SI->getParent()); 5671 } 5672 SI->eraseFromParent(); 5673 5674 ++NumLookupTables; 5675 if (NeedMask) 5676 ++NumLookupTablesHoles; 5677 return true; 5678 } 5679 5680 static bool isSwitchDense(ArrayRef<int64_t> Values) { 5681 // See also SelectionDAGBuilder::isDense(), which this function was based on. 5682 uint64_t Diff = (uint64_t)Values.back() - (uint64_t)Values.front(); 5683 uint64_t Range = Diff + 1; 5684 uint64_t NumCases = Values.size(); 5685 // 40% is the default density for building a jump table in optsize/minsize mode. 5686 uint64_t MinDensity = 40; 5687 5688 return NumCases * 100 >= Range * MinDensity; 5689 } 5690 5691 /// Try to transform a switch that has "holes" in it to a contiguous sequence 5692 /// of cases. 5693 /// 5694 /// A switch such as: switch(i) {case 5: case 9: case 13: case 17:} can be 5695 /// range-reduced to: switch ((i-5) / 4) {case 0: case 1: case 2: case 3:}. 5696 /// 5697 /// This converts a sparse switch into a dense switch which allows better 5698 /// lowering and could also allow transforming into a lookup table. 5699 static bool ReduceSwitchRange(SwitchInst *SI, IRBuilder<> &Builder, 5700 const DataLayout &DL, 5701 const TargetTransformInfo &TTI) { 5702 auto *CondTy = cast<IntegerType>(SI->getCondition()->getType()); 5703 if (CondTy->getIntegerBitWidth() > 64 || 5704 !DL.fitsInLegalInteger(CondTy->getIntegerBitWidth())) 5705 return false; 5706 // Only bother with this optimization if there are more than 3 switch cases; 5707 // SDAG will only bother creating jump tables for 4 or more cases. 5708 if (SI->getNumCases() < 4) 5709 return false; 5710 5711 // This transform is agnostic to the signedness of the input or case values. We 5712 // can treat the case values as signed or unsigned. We can optimize more common 5713 // cases such as a sequence crossing zero {-4,0,4,8} if we interpret case values 5714 // as signed. 5715 SmallVector<int64_t,4> Values; 5716 for (auto &C : SI->cases()) 5717 Values.push_back(C.getCaseValue()->getValue().getSExtValue()); 5718 llvm::sort(Values); 5719 5720 // If the switch is already dense, there's nothing useful to do here. 5721 if (isSwitchDense(Values)) 5722 return false; 5723 5724 // First, transform the values such that they start at zero and ascend. 5725 int64_t Base = Values[0]; 5726 for (auto &V : Values) 5727 V -= (uint64_t)(Base); 5728 5729 // Now we have signed numbers that have been shifted so that, given enough 5730 // precision, there are no negative values. Since the rest of the transform 5731 // is bitwise only, we switch now to an unsigned representation. 5732 5733 // This transform can be done speculatively because it is so cheap - it 5734 // results in a single rotate operation being inserted. 5735 // FIXME: It's possible that optimizing a switch on powers of two might also 5736 // be beneficial - flag values are often powers of two and we could use a CLZ 5737 // as the key function. 5738 5739 // countTrailingZeros(0) returns 64. As Values is guaranteed to have more than 5740 // one element and LLVM disallows duplicate cases, Shift is guaranteed to be 5741 // less than 64. 5742 unsigned Shift = 64; 5743 for (auto &V : Values) 5744 Shift = std::min(Shift, countTrailingZeros((uint64_t)V)); 5745 assert(Shift < 64); 5746 if (Shift > 0) 5747 for (auto &V : Values) 5748 V = (int64_t)((uint64_t)V >> Shift); 5749 5750 if (!isSwitchDense(Values)) 5751 // Transform didn't create a dense switch. 5752 return false; 5753 5754 // The obvious transform is to shift the switch condition right and emit a 5755 // check that the condition actually cleanly divided by GCD, i.e. 5756 // C & (1 << Shift - 1) == 0 5757 // inserting a new CFG edge to handle the case where it didn't divide cleanly. 5758 // 5759 // A cheaper way of doing this is a simple ROTR(C, Shift). This performs the 5760 // shift and puts the shifted-off bits in the uppermost bits. If any of these 5761 // are nonzero then the switch condition will be very large and will hit the 5762 // default case. 5763 5764 auto *Ty = cast<IntegerType>(SI->getCondition()->getType()); 5765 Builder.SetInsertPoint(SI); 5766 auto *ShiftC = ConstantInt::get(Ty, Shift); 5767 auto *Sub = Builder.CreateSub(SI->getCondition(), ConstantInt::get(Ty, Base)); 5768 auto *LShr = Builder.CreateLShr(Sub, ShiftC); 5769 auto *Shl = Builder.CreateShl(Sub, Ty->getBitWidth() - Shift); 5770 auto *Rot = Builder.CreateOr(LShr, Shl); 5771 SI->replaceUsesOfWith(SI->getCondition(), Rot); 5772 5773 for (auto Case : SI->cases()) { 5774 auto *Orig = Case.getCaseValue(); 5775 auto Sub = Orig->getValue() - APInt(Ty->getBitWidth(), Base); 5776 Case.setValue( 5777 cast<ConstantInt>(ConstantInt::get(Ty, Sub.lshr(ShiftC->getValue())))); 5778 } 5779 return true; 5780 } 5781 5782 bool SimplifyCFGOpt::simplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) { 5783 BasicBlock *BB = SI->getParent(); 5784 5785 if (isValueEqualityComparison(SI)) { 5786 // If we only have one predecessor, and if it is a branch on this value, 5787 // see if that predecessor totally determines the outcome of this switch. 5788 if (BasicBlock *OnlyPred = BB->getSinglePredecessor()) 5789 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder)) 5790 return requestResimplify(); 5791 5792 Value *Cond = SI->getCondition(); 5793 if (SelectInst *Select = dyn_cast<SelectInst>(Cond)) 5794 if (SimplifySwitchOnSelect(SI, Select)) 5795 return requestResimplify(); 5796 5797 // If the block only contains the switch, see if we can fold the block 5798 // away into any preds. 5799 if (SI == &*BB->instructionsWithoutDebug().begin()) 5800 if (FoldValueComparisonIntoPredecessors(SI, Builder)) 5801 return requestResimplify(); 5802 } 5803 5804 // Try to transform the switch into an icmp and a branch. 5805 if (TurnSwitchRangeIntoICmp(SI, Builder)) 5806 return requestResimplify(); 5807 5808 // Remove unreachable cases. 5809 if (eliminateDeadSwitchCases(SI, Options.AC, DL)) 5810 return requestResimplify(); 5811 5812 if (switchToSelect(SI, Builder, DL, TTI)) 5813 return requestResimplify(); 5814 5815 if (Options.ForwardSwitchCondToPhi && ForwardSwitchConditionToPHI(SI)) 5816 return requestResimplify(); 5817 5818 // The conversion from switch to lookup tables results in difficult-to-analyze 5819 // code and makes pruning branches much harder. This is a problem if the 5820 // switch expression itself can still be restricted as a result of inlining or 5821 // CVP. Therefore, only apply this transformation during late stages of the 5822 // optimisation pipeline. 5823 if (Options.ConvertSwitchToLookupTable && 5824 SwitchToLookupTable(SI, Builder, DL, TTI)) 5825 return requestResimplify(); 5826 5827 if (ReduceSwitchRange(SI, Builder, DL, TTI)) 5828 return requestResimplify(); 5829 5830 return false; 5831 } 5832 5833 bool SimplifyCFGOpt::simplifyIndirectBr(IndirectBrInst *IBI) { 5834 BasicBlock *BB = IBI->getParent(); 5835 bool Changed = false; 5836 5837 // Eliminate redundant destinations. 5838 SmallPtrSet<Value *, 8> Succs; 5839 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) { 5840 BasicBlock *Dest = IBI->getDestination(i); 5841 if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) { 5842 Dest->removePredecessor(BB); 5843 IBI->removeDestination(i); 5844 --i; 5845 --e; 5846 Changed = true; 5847 } 5848 } 5849 5850 if (IBI->getNumDestinations() == 0) { 5851 // If the indirectbr has no successors, change it to unreachable. 5852 new UnreachableInst(IBI->getContext(), IBI); 5853 EraseTerminatorAndDCECond(IBI); 5854 return true; 5855 } 5856 5857 if (IBI->getNumDestinations() == 1) { 5858 // If the indirectbr has one successor, change it to a direct branch. 5859 BranchInst::Create(IBI->getDestination(0), IBI); 5860 EraseTerminatorAndDCECond(IBI); 5861 return true; 5862 } 5863 5864 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) { 5865 if (SimplifyIndirectBrOnSelect(IBI, SI)) 5866 return requestResimplify(); 5867 } 5868 return Changed; 5869 } 5870 5871 /// Given an block with only a single landing pad and a unconditional branch 5872 /// try to find another basic block which this one can be merged with. This 5873 /// handles cases where we have multiple invokes with unique landing pads, but 5874 /// a shared handler. 5875 /// 5876 /// We specifically choose to not worry about merging non-empty blocks 5877 /// here. That is a PRE/scheduling problem and is best solved elsewhere. In 5878 /// practice, the optimizer produces empty landing pad blocks quite frequently 5879 /// when dealing with exception dense code. (see: instcombine, gvn, if-else 5880 /// sinking in this file) 5881 /// 5882 /// This is primarily a code size optimization. We need to avoid performing 5883 /// any transform which might inhibit optimization (such as our ability to 5884 /// specialize a particular handler via tail commoning). We do this by not 5885 /// merging any blocks which require us to introduce a phi. Since the same 5886 /// values are flowing through both blocks, we don't lose any ability to 5887 /// specialize. If anything, we make such specialization more likely. 5888 /// 5889 /// TODO - This transformation could remove entries from a phi in the target 5890 /// block when the inputs in the phi are the same for the two blocks being 5891 /// merged. In some cases, this could result in removal of the PHI entirely. 5892 static bool TryToMergeLandingPad(LandingPadInst *LPad, BranchInst *BI, 5893 BasicBlock *BB) { 5894 auto Succ = BB->getUniqueSuccessor(); 5895 assert(Succ); 5896 // If there's a phi in the successor block, we'd likely have to introduce 5897 // a phi into the merged landing pad block. 5898 if (isa<PHINode>(*Succ->begin())) 5899 return false; 5900 5901 for (BasicBlock *OtherPred : predecessors(Succ)) { 5902 if (BB == OtherPred) 5903 continue; 5904 BasicBlock::iterator I = OtherPred->begin(); 5905 LandingPadInst *LPad2 = dyn_cast<LandingPadInst>(I); 5906 if (!LPad2 || !LPad2->isIdenticalTo(LPad)) 5907 continue; 5908 for (++I; isa<DbgInfoIntrinsic>(I); ++I) 5909 ; 5910 BranchInst *BI2 = dyn_cast<BranchInst>(I); 5911 if (!BI2 || !BI2->isIdenticalTo(BI)) 5912 continue; 5913 5914 // We've found an identical block. Update our predecessors to take that 5915 // path instead and make ourselves dead. 5916 SmallPtrSet<BasicBlock *, 16> Preds; 5917 Preds.insert(pred_begin(BB), pred_end(BB)); 5918 for (BasicBlock *Pred : Preds) { 5919 InvokeInst *II = cast<InvokeInst>(Pred->getTerminator()); 5920 assert(II->getNormalDest() != BB && II->getUnwindDest() == BB && 5921 "unexpected successor"); 5922 II->setUnwindDest(OtherPred); 5923 } 5924 5925 // The debug info in OtherPred doesn't cover the merged control flow that 5926 // used to go through BB. We need to delete it or update it. 5927 for (auto I = OtherPred->begin(), E = OtherPred->end(); I != E;) { 5928 Instruction &Inst = *I; 5929 I++; 5930 if (isa<DbgInfoIntrinsic>(Inst)) 5931 Inst.eraseFromParent(); 5932 } 5933 5934 SmallPtrSet<BasicBlock *, 16> Succs; 5935 Succs.insert(succ_begin(BB), succ_end(BB)); 5936 for (BasicBlock *Succ : Succs) { 5937 Succ->removePredecessor(BB); 5938 } 5939 5940 IRBuilder<> Builder(BI); 5941 Builder.CreateUnreachable(); 5942 BI->eraseFromParent(); 5943 return true; 5944 } 5945 return false; 5946 } 5947 5948 bool SimplifyCFGOpt::simplifyBranch(BranchInst *Branch, IRBuilder<> &Builder) { 5949 return Branch->isUnconditional() ? simplifyUncondBranch(Branch, Builder) 5950 : simplifyCondBranch(Branch, Builder); 5951 } 5952 5953 bool SimplifyCFGOpt::simplifyUncondBranch(BranchInst *BI, 5954 IRBuilder<> &Builder) { 5955 BasicBlock *BB = BI->getParent(); 5956 BasicBlock *Succ = BI->getSuccessor(0); 5957 5958 // If the Terminator is the only non-phi instruction, simplify the block. 5959 // If LoopHeader is provided, check if the block or its successor is a loop 5960 // header. (This is for early invocations before loop simplify and 5961 // vectorization to keep canonical loop forms for nested loops. These blocks 5962 // can be eliminated when the pass is invoked later in the back-end.) 5963 // Note that if BB has only one predecessor then we do not introduce new 5964 // backedge, so we can eliminate BB. 5965 bool NeedCanonicalLoop = 5966 Options.NeedCanonicalLoop && 5967 (LoopHeaders && BB->hasNPredecessorsOrMore(2) && 5968 (LoopHeaders->count(BB) || LoopHeaders->count(Succ))); 5969 BasicBlock::iterator I = BB->getFirstNonPHIOrDbg()->getIterator(); 5970 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() && 5971 !NeedCanonicalLoop && TryToSimplifyUncondBranchFromEmptyBlock(BB)) 5972 return true; 5973 5974 // If the only instruction in the block is a seteq/setne comparison against a 5975 // constant, try to simplify the block. 5976 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) 5977 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) { 5978 for (++I; isa<DbgInfoIntrinsic>(I); ++I) 5979 ; 5980 if (I->isTerminator() && 5981 tryToSimplifyUncondBranchWithICmpInIt(ICI, Builder)) 5982 return true; 5983 } 5984 5985 // See if we can merge an empty landing pad block with another which is 5986 // equivalent. 5987 if (LandingPadInst *LPad = dyn_cast<LandingPadInst>(I)) { 5988 for (++I; isa<DbgInfoIntrinsic>(I); ++I) 5989 ; 5990 if (I->isTerminator() && TryToMergeLandingPad(LPad, BI, BB)) 5991 return true; 5992 } 5993 5994 // If this basic block is ONLY a compare and a branch, and if a predecessor 5995 // branches to us and our successor, fold the comparison into the 5996 // predecessor and use logical operations to update the incoming value 5997 // for PHI nodes in common successor. 5998 if (FoldBranchToCommonDest(BI, nullptr, Options.BonusInstThreshold)) 5999 return requestResimplify(); 6000 return false; 6001 } 6002 6003 static BasicBlock *allPredecessorsComeFromSameSource(BasicBlock *BB) { 6004 BasicBlock *PredPred = nullptr; 6005 for (auto *P : predecessors(BB)) { 6006 BasicBlock *PPred = P->getSinglePredecessor(); 6007 if (!PPred || (PredPred && PredPred != PPred)) 6008 return nullptr; 6009 PredPred = PPred; 6010 } 6011 return PredPred; 6012 } 6013 6014 bool SimplifyCFGOpt::simplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) { 6015 BasicBlock *BB = BI->getParent(); 6016 if (!Options.SimplifyCondBranch) 6017 return false; 6018 6019 // Conditional branch 6020 if (isValueEqualityComparison(BI)) { 6021 // If we only have one predecessor, and if it is a branch on this value, 6022 // see if that predecessor totally determines the outcome of this 6023 // switch. 6024 if (BasicBlock *OnlyPred = BB->getSinglePredecessor()) 6025 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder)) 6026 return requestResimplify(); 6027 6028 // This block must be empty, except for the setcond inst, if it exists. 6029 // Ignore dbg intrinsics. 6030 auto I = BB->instructionsWithoutDebug().begin(); 6031 if (&*I == BI) { 6032 if (FoldValueComparisonIntoPredecessors(BI, Builder)) 6033 return requestResimplify(); 6034 } else if (&*I == cast<Instruction>(BI->getCondition())) { 6035 ++I; 6036 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder)) 6037 return requestResimplify(); 6038 } 6039 } 6040 6041 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction. 6042 if (SimplifyBranchOnICmpChain(BI, Builder, DL)) 6043 return true; 6044 6045 // If this basic block has dominating predecessor blocks and the dominating 6046 // blocks' conditions imply BI's condition, we know the direction of BI. 6047 Optional<bool> Imp = isImpliedByDomCondition(BI->getCondition(), BI, DL); 6048 if (Imp) { 6049 // Turn this into a branch on constant. 6050 auto *OldCond = BI->getCondition(); 6051 ConstantInt *TorF = *Imp ? ConstantInt::getTrue(BB->getContext()) 6052 : ConstantInt::getFalse(BB->getContext()); 6053 BI->setCondition(TorF); 6054 RecursivelyDeleteTriviallyDeadInstructions(OldCond); 6055 return requestResimplify(); 6056 } 6057 6058 // If this basic block is ONLY a compare and a branch, and if a predecessor 6059 // branches to us and one of our successors, fold the comparison into the 6060 // predecessor and use logical operations to pick the right destination. 6061 if (FoldBranchToCommonDest(BI, nullptr, Options.BonusInstThreshold)) 6062 return requestResimplify(); 6063 6064 // We have a conditional branch to two blocks that are only reachable 6065 // from BI. We know that the condbr dominates the two blocks, so see if 6066 // there is any identical code in the "then" and "else" blocks. If so, we 6067 // can hoist it up to the branching block. 6068 if (BI->getSuccessor(0)->getSinglePredecessor()) { 6069 if (BI->getSuccessor(1)->getSinglePredecessor()) { 6070 if (HoistCommon && Options.HoistCommonInsts) 6071 if (HoistThenElseCodeToIf(BI, TTI)) 6072 return requestResimplify(); 6073 } else { 6074 // If Successor #1 has multiple preds, we may be able to conditionally 6075 // execute Successor #0 if it branches to Successor #1. 6076 Instruction *Succ0TI = BI->getSuccessor(0)->getTerminator(); 6077 if (Succ0TI->getNumSuccessors() == 1 && 6078 Succ0TI->getSuccessor(0) == BI->getSuccessor(1)) 6079 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), TTI)) 6080 return requestResimplify(); 6081 } 6082 } else if (BI->getSuccessor(1)->getSinglePredecessor()) { 6083 // If Successor #0 has multiple preds, we may be able to conditionally 6084 // execute Successor #1 if it branches to Successor #0. 6085 Instruction *Succ1TI = BI->getSuccessor(1)->getTerminator(); 6086 if (Succ1TI->getNumSuccessors() == 1 && 6087 Succ1TI->getSuccessor(0) == BI->getSuccessor(0)) 6088 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), TTI)) 6089 return requestResimplify(); 6090 } 6091 6092 // If this is a branch on a phi node in the current block, thread control 6093 // through this block if any PHI node entries are constants. 6094 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition())) 6095 if (PN->getParent() == BI->getParent()) 6096 if (FoldCondBranchOnPHI(BI, DL, Options.AC)) 6097 return requestResimplify(); 6098 6099 // Scan predecessor blocks for conditional branches. 6100 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) 6101 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator())) 6102 if (PBI != BI && PBI->isConditional()) 6103 if (SimplifyCondBranchToCondBranch(PBI, BI, DL, TTI)) 6104 return requestResimplify(); 6105 6106 // Look for diamond patterns. 6107 if (MergeCondStores) 6108 if (BasicBlock *PrevBB = allPredecessorsComeFromSameSource(BB)) 6109 if (BranchInst *PBI = dyn_cast<BranchInst>(PrevBB->getTerminator())) 6110 if (PBI != BI && PBI->isConditional()) 6111 if (mergeConditionalStores(PBI, BI, DL, TTI)) 6112 return requestResimplify(); 6113 6114 return false; 6115 } 6116 6117 /// Check if passing a value to an instruction will cause undefined behavior. 6118 static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) { 6119 Constant *C = dyn_cast<Constant>(V); 6120 if (!C) 6121 return false; 6122 6123 if (I->use_empty()) 6124 return false; 6125 6126 if (C->isNullValue() || isa<UndefValue>(C)) { 6127 // Only look at the first use, avoid hurting compile time with long uselists 6128 User *Use = *I->user_begin(); 6129 6130 // Now make sure that there are no instructions in between that can alter 6131 // control flow (eg. calls) 6132 for (BasicBlock::iterator 6133 i = ++BasicBlock::iterator(I), 6134 UI = BasicBlock::iterator(dyn_cast<Instruction>(Use)); 6135 i != UI; ++i) 6136 if (i == I->getParent()->end() || i->mayHaveSideEffects()) 6137 return false; 6138 6139 // Look through GEPs. A load from a GEP derived from NULL is still undefined 6140 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use)) 6141 if (GEP->getPointerOperand() == I) 6142 return passingValueIsAlwaysUndefined(V, GEP); 6143 6144 // Look through bitcasts. 6145 if (BitCastInst *BC = dyn_cast<BitCastInst>(Use)) 6146 return passingValueIsAlwaysUndefined(V, BC); 6147 6148 // Load from null is undefined. 6149 if (LoadInst *LI = dyn_cast<LoadInst>(Use)) 6150 if (!LI->isVolatile()) 6151 return !NullPointerIsDefined(LI->getFunction(), 6152 LI->getPointerAddressSpace()); 6153 6154 // Store to null is undefined. 6155 if (StoreInst *SI = dyn_cast<StoreInst>(Use)) 6156 if (!SI->isVolatile()) 6157 return (!NullPointerIsDefined(SI->getFunction(), 6158 SI->getPointerAddressSpace())) && 6159 SI->getPointerOperand() == I; 6160 6161 // A call to null is undefined. 6162 if (auto *CB = dyn_cast<CallBase>(Use)) 6163 return !NullPointerIsDefined(CB->getFunction()) && 6164 CB->getCalledOperand() == I; 6165 } 6166 return false; 6167 } 6168 6169 /// If BB has an incoming value that will always trigger undefined behavior 6170 /// (eg. null pointer dereference), remove the branch leading here. 6171 static bool removeUndefIntroducingPredecessor(BasicBlock *BB) { 6172 for (PHINode &PHI : BB->phis()) 6173 for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) 6174 if (passingValueIsAlwaysUndefined(PHI.getIncomingValue(i), &PHI)) { 6175 Instruction *T = PHI.getIncomingBlock(i)->getTerminator(); 6176 IRBuilder<> Builder(T); 6177 if (BranchInst *BI = dyn_cast<BranchInst>(T)) { 6178 BB->removePredecessor(PHI.getIncomingBlock(i)); 6179 // Turn uncoditional branches into unreachables and remove the dead 6180 // destination from conditional branches. 6181 if (BI->isUnconditional()) 6182 Builder.CreateUnreachable(); 6183 else 6184 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) 6185 : BI->getSuccessor(0)); 6186 BI->eraseFromParent(); 6187 return true; 6188 } 6189 // TODO: SwitchInst. 6190 } 6191 6192 return false; 6193 } 6194 6195 bool SimplifyCFGOpt::simplifyOnce(BasicBlock *BB) { 6196 bool Changed = false; 6197 6198 assert(BB && BB->getParent() && "Block not embedded in function!"); 6199 assert(BB->getTerminator() && "Degenerate basic block encountered!"); 6200 6201 // Remove basic blocks that have no predecessors (except the entry block)... 6202 // or that just have themself as a predecessor. These are unreachable. 6203 if ((pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) || 6204 BB->getSinglePredecessor() == BB) { 6205 LLVM_DEBUG(dbgs() << "Removing BB: \n" << *BB); 6206 DeleteDeadBlock(BB); 6207 return true; 6208 } 6209 6210 // Check to see if we can constant propagate this terminator instruction 6211 // away... 6212 Changed |= ConstantFoldTerminator(BB, true); 6213 6214 // Check for and eliminate duplicate PHI nodes in this block. 6215 Changed |= EliminateDuplicatePHINodes(BB); 6216 6217 // Check for and remove branches that will always cause undefined behavior. 6218 Changed |= removeUndefIntroducingPredecessor(BB); 6219 6220 // Merge basic blocks into their predecessor if there is only one distinct 6221 // pred, and if there is only one distinct successor of the predecessor, and 6222 // if there are no PHI nodes. 6223 if (MergeBlockIntoPredecessor(BB)) 6224 return true; 6225 6226 if (SinkCommon && Options.SinkCommonInsts) 6227 Changed |= SinkCommonCodeFromPredecessors(BB); 6228 6229 IRBuilder<> Builder(BB); 6230 6231 if (Options.FoldTwoEntryPHINode) { 6232 // If there is a trivial two-entry PHI node in this basic block, and we can 6233 // eliminate it, do so now. 6234 if (auto *PN = dyn_cast<PHINode>(BB->begin())) 6235 if (PN->getNumIncomingValues() == 2) 6236 Changed |= FoldTwoEntryPHINode(PN, TTI, DL); 6237 } 6238 6239 Instruction *Terminator = BB->getTerminator(); 6240 Builder.SetInsertPoint(Terminator); 6241 switch (Terminator->getOpcode()) { 6242 case Instruction::Br: 6243 Changed |= simplifyBranch(cast<BranchInst>(Terminator), Builder); 6244 break; 6245 case Instruction::Ret: 6246 Changed |= simplifyReturn(cast<ReturnInst>(Terminator), Builder); 6247 break; 6248 case Instruction::Resume: 6249 Changed |= simplifyResume(cast<ResumeInst>(Terminator), Builder); 6250 break; 6251 case Instruction::CleanupRet: 6252 Changed |= simplifyCleanupReturn(cast<CleanupReturnInst>(Terminator)); 6253 break; 6254 case Instruction::Switch: 6255 Changed |= simplifySwitch(cast<SwitchInst>(Terminator), Builder); 6256 break; 6257 case Instruction::Unreachable: 6258 Changed |= simplifyUnreachable(cast<UnreachableInst>(Terminator)); 6259 break; 6260 case Instruction::IndirectBr: 6261 Changed |= simplifyIndirectBr(cast<IndirectBrInst>(Terminator)); 6262 break; 6263 } 6264 6265 return Changed; 6266 } 6267 6268 bool SimplifyCFGOpt::run(BasicBlock *BB) { 6269 bool Changed = false; 6270 6271 // Repeated simplify BB as long as resimplification is requested. 6272 do { 6273 Resimplify = false; 6274 6275 // Perform one round of simplifcation. Resimplify flag will be set if 6276 // another iteration is requested. 6277 Changed |= simplifyOnce(BB); 6278 } while (Resimplify); 6279 6280 return Changed; 6281 } 6282 6283 bool llvm::simplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI, 6284 const SimplifyCFGOptions &Options, 6285 SmallPtrSetImpl<BasicBlock *> *LoopHeaders) { 6286 return SimplifyCFGOpt(TTI, BB->getModule()->getDataLayout(), LoopHeaders, 6287 Options) 6288 .run(BB); 6289 } 6290