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