1 //===- LowerSwitch.cpp - Eliminate Switch instructions --------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // The LowerSwitch transformation rewrites switch instructions with a sequence
10 // of branches, which allows targets to get away with not implementing the
11 // switch instruction until it is convenient.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/Analysis/AssumptionCache.h"
20 #include "llvm/Analysis/LazyValueInfo.h"
21 #include "llvm/Analysis/ValueTracking.h"
22 #include "llvm/IR/BasicBlock.h"
23 #include "llvm/IR/CFG.h"
24 #include "llvm/IR/ConstantRange.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/IR/InstrTypes.h"
28 #include "llvm/IR/Instructions.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/IR/Value.h"
31 #include "llvm/InitializePasses.h"
32 #include "llvm/Pass.h"
33 #include "llvm/Support/Casting.h"
34 #include "llvm/Support/Compiler.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/KnownBits.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Transforms/Utils.h"
39 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
40 #include <algorithm>
41 #include <cassert>
42 #include <cstdint>
43 #include <iterator>
44 #include <limits>
45 #include <vector>
46 
47 using namespace llvm;
48 
49 #define DEBUG_TYPE "lower-switch"
50 
51 namespace {
52 
53   struct IntRange {
54     int64_t Low, High;
55   };
56 
57 } // end anonymous namespace
58 
59 // Return true iff R is covered by Ranges.
60 static bool IsInRanges(const IntRange &R,
61                        const std::vector<IntRange> &Ranges) {
62   // Note: Ranges must be sorted, non-overlapping and non-adjacent.
63 
64   // Find the first range whose High field is >= R.High,
65   // then check if the Low field is <= R.Low. If so, we
66   // have a Range that covers R.
67   auto I = llvm::lower_bound(
68       Ranges, R, [](IntRange A, IntRange B) { return A.High < B.High; });
69   return I != Ranges.end() && I->Low <= R.Low;
70 }
71 
72 namespace {
73 
74   /// Replace all SwitchInst instructions with chained branch instructions.
75   class LowerSwitch : public FunctionPass {
76   public:
77     // Pass identification, replacement for typeid
78     static char ID;
79 
80     LowerSwitch() : FunctionPass(ID) {
81       initializeLowerSwitchPass(*PassRegistry::getPassRegistry());
82     }
83 
84     bool runOnFunction(Function &F) override;
85 
86     void getAnalysisUsage(AnalysisUsage &AU) const override {
87       AU.addRequired<LazyValueInfoWrapperPass>();
88     }
89 
90     struct CaseRange {
91       ConstantInt* Low;
92       ConstantInt* High;
93       BasicBlock* BB;
94 
95       CaseRange(ConstantInt *low, ConstantInt *high, BasicBlock *bb)
96           : Low(low), High(high), BB(bb) {}
97     };
98 
99     using CaseVector = std::vector<CaseRange>;
100     using CaseItr = std::vector<CaseRange>::iterator;
101 
102   private:
103     void processSwitchInst(SwitchInst *SI,
104                            SmallPtrSetImpl<BasicBlock *> &DeleteList,
105                            AssumptionCache *AC, LazyValueInfo *LVI);
106 
107     BasicBlock *switchConvert(CaseItr Begin, CaseItr End,
108                               ConstantInt *LowerBound, ConstantInt *UpperBound,
109                               Value *Val, BasicBlock *Predecessor,
110                               BasicBlock *OrigBlock, BasicBlock *Default,
111                               const std::vector<IntRange> &UnreachableRanges);
112     BasicBlock *newLeafBlock(CaseRange &Leaf, Value *Val,
113                              ConstantInt *LowerBound, ConstantInt *UpperBound,
114                              BasicBlock *OrigBlock, BasicBlock *Default);
115     unsigned Clusterify(CaseVector &Cases, SwitchInst *SI);
116   };
117 
118   /// The comparison function for sorting the switch case values in the vector.
119   /// WARNING: Case ranges should be disjoint!
120   struct CaseCmp {
121     bool operator()(const LowerSwitch::CaseRange& C1,
122                     const LowerSwitch::CaseRange& C2) {
123       const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
124       const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
125       return CI1->getValue().slt(CI2->getValue());
126     }
127   };
128 
129 } // end anonymous namespace
130 
131 char LowerSwitch::ID = 0;
132 
133 // Publicly exposed interface to pass...
134 char &llvm::LowerSwitchID = LowerSwitch::ID;
135 
136 INITIALIZE_PASS_BEGIN(LowerSwitch, "lowerswitch",
137                       "Lower SwitchInst's to branches", false, false)
138 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
139 INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass)
140 INITIALIZE_PASS_END(LowerSwitch, "lowerswitch",
141                     "Lower SwitchInst's to branches", false, false)
142 
143 // createLowerSwitchPass - Interface to this file...
144 FunctionPass *llvm::createLowerSwitchPass() {
145   return new LowerSwitch();
146 }
147 
148 bool LowerSwitch::runOnFunction(Function &F) {
149   LazyValueInfo *LVI = &getAnalysis<LazyValueInfoWrapperPass>().getLVI();
150   auto *ACT = getAnalysisIfAvailable<AssumptionCacheTracker>();
151   AssumptionCache *AC = ACT ? &ACT->getAssumptionCache(F) : nullptr;
152 
153   bool Changed = false;
154   SmallPtrSet<BasicBlock*, 8> DeleteList;
155 
156   for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
157     BasicBlock *Cur = &*I++; // Advance over block so we don't traverse new blocks
158 
159     // If the block is a dead Default block that will be deleted later, don't
160     // waste time processing it.
161     if (DeleteList.count(Cur))
162       continue;
163 
164     if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur->getTerminator())) {
165       Changed = true;
166       processSwitchInst(SI, DeleteList, AC, LVI);
167     }
168   }
169 
170   for (BasicBlock* BB: DeleteList) {
171     LVI->eraseBlock(BB);
172     DeleteDeadBlock(BB);
173   }
174 
175   return Changed;
176 }
177 
178 /// Used for debugging purposes.
179 LLVM_ATTRIBUTE_USED
180 static raw_ostream &operator<<(raw_ostream &O,
181                                const LowerSwitch::CaseVector &C) {
182   O << "[";
183 
184   for (LowerSwitch::CaseVector::const_iterator B = C.begin(), E = C.end();
185        B != E;) {
186     O << "[" << B->Low->getValue() << ", " << B->High->getValue() << "]";
187     if (++B != E)
188       O << ", ";
189   }
190 
191   return O << "]";
192 }
193 
194 /// Update the first occurrence of the "switch statement" BB in the PHI
195 /// node with the "new" BB. The other occurrences will:
196 ///
197 /// 1) Be updated by subsequent calls to this function.  Switch statements may
198 /// have more than one outcoming edge into the same BB if they all have the same
199 /// value. When the switch statement is converted these incoming edges are now
200 /// coming from multiple BBs.
201 /// 2) Removed if subsequent incoming values now share the same case, i.e.,
202 /// multiple outcome edges are condensed into one. This is necessary to keep the
203 /// number of phi values equal to the number of branches to SuccBB.
204 static void
205 fixPhis(BasicBlock *SuccBB, BasicBlock *OrigBB, BasicBlock *NewBB,
206         const unsigned NumMergedCases = std::numeric_limits<unsigned>::max()) {
207   for (BasicBlock::iterator I = SuccBB->begin(),
208                             IE = SuccBB->getFirstNonPHI()->getIterator();
209        I != IE; ++I) {
210     PHINode *PN = cast<PHINode>(I);
211 
212     // Only update the first occurrence.
213     unsigned Idx = 0, E = PN->getNumIncomingValues();
214     unsigned LocalNumMergedCases = NumMergedCases;
215     for (; Idx != E; ++Idx) {
216       if (PN->getIncomingBlock(Idx) == OrigBB) {
217         PN->setIncomingBlock(Idx, NewBB);
218         break;
219       }
220     }
221 
222     // Remove additional occurrences coming from condensed cases and keep the
223     // number of incoming values equal to the number of branches to SuccBB.
224     SmallVector<unsigned, 8> Indices;
225     for (++Idx; LocalNumMergedCases > 0 && Idx < E; ++Idx)
226       if (PN->getIncomingBlock(Idx) == OrigBB) {
227         Indices.push_back(Idx);
228         LocalNumMergedCases--;
229       }
230     // Remove incoming values in the reverse order to prevent invalidating
231     // *successive* index.
232     for (unsigned III : llvm::reverse(Indices))
233       PN->removeIncomingValue(III);
234   }
235 }
236 
237 /// Convert the switch statement into a binary lookup of the case values.
238 /// The function recursively builds this tree. LowerBound and UpperBound are
239 /// used to keep track of the bounds for Val that have already been checked by
240 /// a block emitted by one of the previous calls to switchConvert in the call
241 /// stack.
242 BasicBlock *
243 LowerSwitch::switchConvert(CaseItr Begin, CaseItr End, ConstantInt *LowerBound,
244                            ConstantInt *UpperBound, Value *Val,
245                            BasicBlock *Predecessor, BasicBlock *OrigBlock,
246                            BasicBlock *Default,
247                            const std::vector<IntRange> &UnreachableRanges) {
248   assert(LowerBound && UpperBound && "Bounds must be initialized");
249   unsigned Size = End - Begin;
250 
251   if (Size == 1) {
252     // Check if the Case Range is perfectly squeezed in between
253     // already checked Upper and Lower bounds. If it is then we can avoid
254     // emitting the code that checks if the value actually falls in the range
255     // because the bounds already tell us so.
256     if (Begin->Low == LowerBound && Begin->High == UpperBound) {
257       unsigned NumMergedCases = 0;
258       NumMergedCases = UpperBound->getSExtValue() - LowerBound->getSExtValue();
259       fixPhis(Begin->BB, OrigBlock, Predecessor, NumMergedCases);
260       return Begin->BB;
261     }
262     return newLeafBlock(*Begin, Val, LowerBound, UpperBound, OrigBlock,
263                         Default);
264   }
265 
266   unsigned Mid = Size / 2;
267   std::vector<CaseRange> LHS(Begin, Begin + Mid);
268   LLVM_DEBUG(dbgs() << "LHS: " << LHS << "\n");
269   std::vector<CaseRange> RHS(Begin + Mid, End);
270   LLVM_DEBUG(dbgs() << "RHS: " << RHS << "\n");
271 
272   CaseRange &Pivot = *(Begin + Mid);
273   LLVM_DEBUG(dbgs() << "Pivot ==> [" << Pivot.Low->getValue() << ", "
274                     << Pivot.High->getValue() << "]\n");
275 
276   // NewLowerBound here should never be the integer minimal value.
277   // This is because it is computed from a case range that is never
278   // the smallest, so there is always a case range that has at least
279   // a smaller value.
280   ConstantInt *NewLowerBound = Pivot.Low;
281 
282   // Because NewLowerBound is never the smallest representable integer
283   // it is safe here to subtract one.
284   ConstantInt *NewUpperBound = ConstantInt::get(NewLowerBound->getContext(),
285                                                 NewLowerBound->getValue() - 1);
286 
287   if (!UnreachableRanges.empty()) {
288     // Check if the gap between LHS's highest and NewLowerBound is unreachable.
289     int64_t GapLow = LHS.back().High->getSExtValue() + 1;
290     int64_t GapHigh = NewLowerBound->getSExtValue() - 1;
291     IntRange Gap = { GapLow, GapHigh };
292     if (GapHigh >= GapLow && IsInRanges(Gap, UnreachableRanges))
293       NewUpperBound = LHS.back().High;
294   }
295 
296   LLVM_DEBUG(dbgs() << "LHS Bounds ==> [" << LowerBound->getSExtValue() << ", "
297                     << NewUpperBound->getSExtValue() << "]\n"
298                     << "RHS Bounds ==> [" << NewLowerBound->getSExtValue()
299                     << ", " << UpperBound->getSExtValue() << "]\n");
300 
301   // Create a new node that checks if the value is < pivot. Go to the
302   // left branch if it is and right branch if not.
303   Function* F = OrigBlock->getParent();
304   BasicBlock* NewNode = BasicBlock::Create(Val->getContext(), "NodeBlock");
305 
306   ICmpInst* Comp = new ICmpInst(ICmpInst::ICMP_SLT,
307                                 Val, Pivot.Low, "Pivot");
308 
309   BasicBlock *LBranch = switchConvert(LHS.begin(), LHS.end(), LowerBound,
310                                       NewUpperBound, Val, NewNode, OrigBlock,
311                                       Default, UnreachableRanges);
312   BasicBlock *RBranch = switchConvert(RHS.begin(), RHS.end(), NewLowerBound,
313                                       UpperBound, Val, NewNode, OrigBlock,
314                                       Default, UnreachableRanges);
315 
316   F->getBasicBlockList().insert(++OrigBlock->getIterator(), NewNode);
317   NewNode->getInstList().push_back(Comp);
318 
319   BranchInst::Create(LBranch, RBranch, Comp, NewNode);
320   return NewNode;
321 }
322 
323 /// Create a new leaf block for the binary lookup tree. It checks if the
324 /// switch's value == the case's value. If not, then it jumps to the default
325 /// branch. At this point in the tree, the value can't be another valid case
326 /// value, so the jump to the "default" branch is warranted.
327 BasicBlock *LowerSwitch::newLeafBlock(CaseRange &Leaf, Value *Val,
328                                       ConstantInt *LowerBound,
329                                       ConstantInt *UpperBound,
330                                       BasicBlock *OrigBlock,
331                                       BasicBlock *Default) {
332   Function* F = OrigBlock->getParent();
333   BasicBlock* NewLeaf = BasicBlock::Create(Val->getContext(), "LeafBlock");
334   F->getBasicBlockList().insert(++OrigBlock->getIterator(), NewLeaf);
335 
336   // Emit comparison
337   ICmpInst* Comp = nullptr;
338   if (Leaf.Low == Leaf.High) {
339     // Make the seteq instruction...
340     Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_EQ, Val,
341                         Leaf.Low, "SwitchLeaf");
342   } else {
343     // Make range comparison
344     if (Leaf.Low == LowerBound) {
345       // Val >= Min && Val <= Hi --> Val <= Hi
346       Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_SLE, Val, Leaf.High,
347                           "SwitchLeaf");
348     } else if (Leaf.High == UpperBound) {
349       // Val <= Max && Val >= Lo --> Val >= Lo
350       Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_SGE, Val, Leaf.Low,
351                           "SwitchLeaf");
352     } else if (Leaf.Low->isZero()) {
353       // Val >= 0 && Val <= Hi --> Val <=u Hi
354       Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Val, Leaf.High,
355                           "SwitchLeaf");
356     } else {
357       // Emit V-Lo <=u Hi-Lo
358       Constant* NegLo = ConstantExpr::getNeg(Leaf.Low);
359       Instruction* Add = BinaryOperator::CreateAdd(Val, NegLo,
360                                                    Val->getName()+".off",
361                                                    NewLeaf);
362       Constant *UpperBound = ConstantExpr::getAdd(NegLo, Leaf.High);
363       Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Add, UpperBound,
364                           "SwitchLeaf");
365     }
366   }
367 
368   // Make the conditional branch...
369   BasicBlock* Succ = Leaf.BB;
370   BranchInst::Create(Succ, Default, Comp, NewLeaf);
371 
372   // If there were any PHI nodes in this successor, rewrite one entry
373   // from OrigBlock to come from NewLeaf.
374   for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
375     PHINode* PN = cast<PHINode>(I);
376     // Remove all but one incoming entries from the cluster
377     uint64_t Range = Leaf.High->getSExtValue() -
378                      Leaf.Low->getSExtValue();
379     for (uint64_t j = 0; j < Range; ++j) {
380       PN->removeIncomingValue(OrigBlock);
381     }
382 
383     int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
384     assert(BlockIdx != -1 && "Switch didn't go to this successor??");
385     PN->setIncomingBlock((unsigned)BlockIdx, NewLeaf);
386   }
387 
388   return NewLeaf;
389 }
390 
391 /// Transform simple list of \p SI's cases into list of CaseRange's \p Cases.
392 /// \post \p Cases wouldn't contain references to \p SI's default BB.
393 /// \returns Number of \p SI's cases that do not reference \p SI's default BB.
394 unsigned LowerSwitch::Clusterify(CaseVector& Cases, SwitchInst *SI) {
395   unsigned NumSimpleCases = 0;
396 
397   // Start with "simple" cases
398   for (auto Case : SI->cases()) {
399     if (Case.getCaseSuccessor() == SI->getDefaultDest())
400       continue;
401     Cases.push_back(CaseRange(Case.getCaseValue(), Case.getCaseValue(),
402                               Case.getCaseSuccessor()));
403     ++NumSimpleCases;
404   }
405 
406   llvm::sort(Cases, CaseCmp());
407 
408   // Merge case into clusters
409   if (Cases.size() >= 2) {
410     CaseItr I = Cases.begin();
411     for (CaseItr J = std::next(I), E = Cases.end(); J != E; ++J) {
412       int64_t nextValue = J->Low->getSExtValue();
413       int64_t currentValue = I->High->getSExtValue();
414       BasicBlock* nextBB = J->BB;
415       BasicBlock* currentBB = I->BB;
416 
417       // If the two neighboring cases go to the same destination, merge them
418       // into a single case.
419       assert(nextValue > currentValue && "Cases should be strictly ascending");
420       if ((nextValue == currentValue + 1) && (currentBB == nextBB)) {
421         I->High = J->High;
422         // FIXME: Combine branch weights.
423       } else if (++I != J) {
424         *I = *J;
425       }
426     }
427     Cases.erase(std::next(I), Cases.end());
428   }
429 
430   return NumSimpleCases;
431 }
432 
433 /// Replace the specified switch instruction with a sequence of chained if-then
434 /// insts in a balanced binary search.
435 void LowerSwitch::processSwitchInst(SwitchInst *SI,
436                                     SmallPtrSetImpl<BasicBlock *> &DeleteList,
437                                     AssumptionCache *AC, LazyValueInfo *LVI) {
438   BasicBlock *OrigBlock = SI->getParent();
439   Function *F = OrigBlock->getParent();
440   Value *Val = SI->getCondition();  // The value we are switching on...
441   BasicBlock* Default = SI->getDefaultDest();
442 
443   // Don't handle unreachable blocks. If there are successors with phis, this
444   // would leave them behind with missing predecessors.
445   if ((OrigBlock != &F->getEntryBlock() && pred_empty(OrigBlock)) ||
446       OrigBlock->getSinglePredecessor() == OrigBlock) {
447     DeleteList.insert(OrigBlock);
448     return;
449   }
450 
451   // Prepare cases vector.
452   CaseVector Cases;
453   const unsigned NumSimpleCases = Clusterify(Cases, SI);
454   LLVM_DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
455                     << ". Total non-default cases: " << NumSimpleCases
456                     << "\nCase clusters: " << Cases << "\n");
457 
458   // If there is only the default destination, just branch.
459   if (Cases.empty()) {
460     BranchInst::Create(Default, OrigBlock);
461     // Remove all the references from Default's PHIs to OrigBlock, but one.
462     fixPhis(Default, OrigBlock, OrigBlock);
463     SI->eraseFromParent();
464     return;
465   }
466 
467   ConstantInt *LowerBound = nullptr;
468   ConstantInt *UpperBound = nullptr;
469   bool DefaultIsUnreachableFromSwitch = false;
470 
471   if (isa<UnreachableInst>(Default->getFirstNonPHIOrDbg())) {
472     // Make the bounds tightly fitted around the case value range, because we
473     // know that the value passed to the switch must be exactly one of the case
474     // values.
475     LowerBound = Cases.front().Low;
476     UpperBound = Cases.back().High;
477     DefaultIsUnreachableFromSwitch = true;
478   } else {
479     // Constraining the range of the value being switched over helps eliminating
480     // unreachable BBs and minimizing the number of `add` instructions
481     // newLeafBlock ends up emitting. Running CorrelatedValuePropagation after
482     // LowerSwitch isn't as good, and also much more expensive in terms of
483     // compile time for the following reasons:
484     // 1. it processes many kinds of instructions, not just switches;
485     // 2. even if limited to icmp instructions only, it will have to process
486     //    roughly C icmp's per switch, where C is the number of cases in the
487     //    switch, while LowerSwitch only needs to call LVI once per switch.
488     const DataLayout &DL = F->getParent()->getDataLayout();
489     KnownBits Known = computeKnownBits(Val, DL, /*Depth=*/0, AC, SI);
490     // TODO Shouldn't this create a signed range?
491     ConstantRange KnownBitsRange =
492         ConstantRange::fromKnownBits(Known, /*IsSigned=*/false);
493     const ConstantRange LVIRange = LVI->getConstantRange(Val, OrigBlock, SI);
494     ConstantRange ValRange = KnownBitsRange.intersectWith(LVIRange);
495     // We delegate removal of unreachable non-default cases to other passes. In
496     // the unlikely event that some of them survived, we just conservatively
497     // maintain the invariant that all the cases lie between the bounds. This
498     // may, however, still render the default case effectively unreachable.
499     APInt Low = Cases.front().Low->getValue();
500     APInt High = Cases.back().High->getValue();
501     APInt Min = APIntOps::smin(ValRange.getSignedMin(), Low);
502     APInt Max = APIntOps::smax(ValRange.getSignedMax(), High);
503 
504     LowerBound = ConstantInt::get(SI->getContext(), Min);
505     UpperBound = ConstantInt::get(SI->getContext(), Max);
506     DefaultIsUnreachableFromSwitch = (Min + (NumSimpleCases - 1) == Max);
507   }
508 
509   std::vector<IntRange> UnreachableRanges;
510 
511   if (DefaultIsUnreachableFromSwitch) {
512     DenseMap<BasicBlock *, unsigned> Popularity;
513     unsigned MaxPop = 0;
514     BasicBlock *PopSucc = nullptr;
515 
516     IntRange R = {std::numeric_limits<int64_t>::min(),
517                   std::numeric_limits<int64_t>::max()};
518     UnreachableRanges.push_back(R);
519     for (const auto &I : Cases) {
520       int64_t Low = I.Low->getSExtValue();
521       int64_t High = I.High->getSExtValue();
522 
523       IntRange &LastRange = UnreachableRanges.back();
524       if (LastRange.Low == Low) {
525         // There is nothing left of the previous range.
526         UnreachableRanges.pop_back();
527       } else {
528         // Terminate the previous range.
529         assert(Low > LastRange.Low);
530         LastRange.High = Low - 1;
531       }
532       if (High != std::numeric_limits<int64_t>::max()) {
533         IntRange R = { High + 1, std::numeric_limits<int64_t>::max() };
534         UnreachableRanges.push_back(R);
535       }
536 
537       // Count popularity.
538       int64_t N = High - Low + 1;
539       unsigned &Pop = Popularity[I.BB];
540       if ((Pop += N) > MaxPop) {
541         MaxPop = Pop;
542         PopSucc = I.BB;
543       }
544     }
545 #ifndef NDEBUG
546     /* UnreachableRanges should be sorted and the ranges non-adjacent. */
547     for (auto I = UnreachableRanges.begin(), E = UnreachableRanges.end();
548          I != E; ++I) {
549       assert(I->Low <= I->High);
550       auto Next = I + 1;
551       if (Next != E) {
552         assert(Next->Low > I->High);
553       }
554     }
555 #endif
556 
557     // As the default block in the switch is unreachable, update the PHI nodes
558     // (remove all of the references to the default block) to reflect this.
559     const unsigned NumDefaultEdges = SI->getNumCases() + 1 - NumSimpleCases;
560     for (unsigned I = 0; I < NumDefaultEdges; ++I)
561       Default->removePredecessor(OrigBlock);
562 
563     // Use the most popular block as the new default, reducing the number of
564     // cases.
565     assert(MaxPop > 0 && PopSucc);
566     Default = PopSucc;
567     Cases.erase(
568         llvm::remove_if(
569             Cases, [PopSucc](const CaseRange &R) { return R.BB == PopSucc; }),
570         Cases.end());
571 
572     // If there are no cases left, just branch.
573     if (Cases.empty()) {
574       BranchInst::Create(Default, OrigBlock);
575       SI->eraseFromParent();
576       // As all the cases have been replaced with a single branch, only keep
577       // one entry in the PHI nodes.
578       for (unsigned I = 0 ; I < (MaxPop - 1) ; ++I)
579         PopSucc->removePredecessor(OrigBlock);
580       return;
581     }
582 
583     // If the condition was a PHI node with the switch block as a predecessor
584     // removing predecessors may have caused the condition to be erased.
585     // Getting the condition value again here protects against that.
586     Val = SI->getCondition();
587   }
588 
589   // Create a new, empty default block so that the new hierarchy of
590   // if-then statements go to this and the PHI nodes are happy.
591   BasicBlock *NewDefault = BasicBlock::Create(SI->getContext(), "NewDefault");
592   F->getBasicBlockList().insert(Default->getIterator(), NewDefault);
593   BranchInst::Create(Default, NewDefault);
594 
595   BasicBlock *SwitchBlock =
596       switchConvert(Cases.begin(), Cases.end(), LowerBound, UpperBound, Val,
597                     OrigBlock, OrigBlock, NewDefault, UnreachableRanges);
598 
599   // If there are entries in any PHI nodes for the default edge, make sure
600   // to update them as well.
601   fixPhis(Default, OrigBlock, NewDefault);
602 
603   // Branch to our shiny new if-then stuff...
604   BranchInst::Create(SwitchBlock, OrigBlock);
605 
606   // We are now done with the switch instruction, delete it.
607   BasicBlock *OldDefault = SI->getDefaultDest();
608   OrigBlock->getInstList().erase(SI);
609 
610   // If the Default block has no more predecessors just add it to DeleteList.
611   if (pred_begin(OldDefault) == pred_end(OldDefault))
612     DeleteList.insert(OldDefault);
613 }
614