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