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