Coverage Report

Created: 2019-07-24 05:18

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