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