Taints the non-acquire RMW's store address with the load part
[oota-llvm.git] / lib / Transforms / Utils / LowerSwitch.cpp
1 //===- LowerSwitch.cpp - Eliminate Switch instructions --------------------===//
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 // The LowerSwitch transformation rewrites switch instructions with a sequence
11 // of branches, which allows targets to get away with not implementing the
12 // switch instruction until it is convenient.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "llvm/Transforms/Scalar.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/IR/CFG.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/Function.h"
21 #include "llvm/IR/Instructions.h"
22 #include "llvm/IR/LLVMContext.h"
23 #include "llvm/Pass.h"
24 #include "llvm/Support/Compiler.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
28 #include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
29 #include <algorithm>
30 using namespace llvm;
31
32 #define DEBUG_TYPE "lower-switch"
33
34 namespace {
35   struct IntRange {
36     int64_t Low, High;
37   };
38   // Return true iff R is covered by Ranges.
39   static bool IsInRanges(const IntRange &R,
40                          const std::vector<IntRange> &Ranges) {
41     // Note: Ranges must be sorted, non-overlapping and non-adjacent.
42
43     // Find the first range whose High field is >= R.High,
44     // then check if the Low field is <= R.Low. If so, we
45     // have a Range that covers R.
46     auto I = std::lower_bound(
47         Ranges.begin(), Ranges.end(), R,
48         [](const IntRange &A, const IntRange &B) { return A.High < B.High; });
49     return I != Ranges.end() && I->Low <= R.Low;
50   }
51
52   /// Replace all SwitchInst instructions with chained branch instructions.
53   class LowerSwitch : public FunctionPass {
54   public:
55     static char ID; // Pass identification, replacement for typeid
56     LowerSwitch() : FunctionPass(ID) {
57       initializeLowerSwitchPass(*PassRegistry::getPassRegistry());
58     } 
59
60     bool runOnFunction(Function &F) override;
61
62     void getAnalysisUsage(AnalysisUsage &AU) const override {
63       // This is a cluster of orthogonal Transforms
64       AU.addPreserved<UnifyFunctionExitNodes>();
65       AU.addPreservedID(LowerInvokePassID);
66     }
67
68     struct CaseRange {
69       ConstantInt* Low;
70       ConstantInt* High;
71       BasicBlock* BB;
72
73       CaseRange(ConstantInt *low, ConstantInt *high, BasicBlock *bb)
74           : Low(low), High(high), BB(bb) {}
75     };
76
77     typedef std::vector<CaseRange> CaseVector;
78     typedef std::vector<CaseRange>::iterator CaseItr;
79   private:
80     void processSwitchInst(SwitchInst *SI, SmallPtrSetImpl<BasicBlock*> &DeleteList);
81
82     BasicBlock *switchConvert(CaseItr Begin, CaseItr End,
83                               ConstantInt *LowerBound, ConstantInt *UpperBound,
84                               Value *Val, BasicBlock *Predecessor,
85                               BasicBlock *OrigBlock, BasicBlock *Default,
86                               const std::vector<IntRange> &UnreachableRanges);
87     BasicBlock *newLeafBlock(CaseRange &Leaf, Value *Val, BasicBlock *OrigBlock,
88                              BasicBlock *Default);
89     unsigned Clusterify(CaseVector &Cases, SwitchInst *SI);
90   };
91
92   /// The comparison function for sorting the switch case values in the vector.
93   /// WARNING: Case ranges should be disjoint!
94   struct CaseCmp {
95     bool operator () (const LowerSwitch::CaseRange& C1,
96                       const LowerSwitch::CaseRange& C2) {
97
98       const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
99       const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
100       return CI1->getValue().slt(CI2->getValue());
101     }
102   };
103 }
104
105 char LowerSwitch::ID = 0;
106 INITIALIZE_PASS(LowerSwitch, "lowerswitch",
107                 "Lower SwitchInst's to branches", false, false)
108
109 // Publicly exposed interface to pass...
110 char &llvm::LowerSwitchID = LowerSwitch::ID;
111 // createLowerSwitchPass - Interface to this file...
112 FunctionPass *llvm::createLowerSwitchPass() {
113   return new LowerSwitch();
114 }
115
116 bool LowerSwitch::runOnFunction(Function &F) {
117   bool Changed = false;
118   SmallPtrSet<BasicBlock*, 8> DeleteList;
119
120   for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
121     BasicBlock *Cur = &*I++; // Advance over block so we don't traverse new blocks
122
123     // If the block is a dead Default block that will be deleted later, don't
124     // waste time processing it.
125     if (DeleteList.count(Cur))
126       continue;
127
128     if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur->getTerminator())) {
129       Changed = true;
130       processSwitchInst(SI, DeleteList);
131     }
132   }
133
134   for (BasicBlock* BB: DeleteList) {
135     DeleteDeadBlock(BB);
136   }
137
138   return Changed;
139 }
140
141 /// Used for debugging purposes.
142 static raw_ostream& operator<<(raw_ostream &O,
143                                const LowerSwitch::CaseVector &C)
144     LLVM_ATTRIBUTE_USED;
145 static raw_ostream& operator<<(raw_ostream &O,
146                                const LowerSwitch::CaseVector &C) {
147   O << "[";
148
149   for (LowerSwitch::CaseVector::const_iterator B = C.begin(),
150          E = C.end(); B != E; ) {
151     O << *B->Low << " -" << *B->High;
152     if (++B != E) O << ", ";
153   }
154
155   return O << "]";
156 }
157
158 /// \brief Update the first occurrence of the "switch statement" BB in the PHI
159 /// node with the "new" BB. The other occurrences will:
160 ///
161 /// 1) Be updated by subsequent calls to this function.  Switch statements may
162 /// have more than one outcoming edge into the same BB if they all have the same
163 /// value. When the switch statement is converted these incoming edges are now
164 /// coming from multiple BBs.
165 /// 2) Removed if subsequent incoming values now share the same case, i.e.,
166 /// multiple outcome edges are condensed into one. This is necessary to keep the
167 /// number of phi values equal to the number of branches to SuccBB.
168 static void fixPhis(BasicBlock *SuccBB, BasicBlock *OrigBB, BasicBlock *NewBB,
169                     unsigned NumMergedCases) {
170   for (BasicBlock::iterator I = SuccBB->begin(),
171                             IE = SuccBB->getFirstNonPHI()->getIterator();
172        I != IE; ++I) {
173     PHINode *PN = cast<PHINode>(I);
174
175     // Only update the first occurrence.
176     unsigned Idx = 0, E = PN->getNumIncomingValues();
177     unsigned LocalNumMergedCases = NumMergedCases;
178     for (; Idx != E; ++Idx) {
179       if (PN->getIncomingBlock(Idx) == OrigBB) {
180         PN->setIncomingBlock(Idx, NewBB);
181         break;
182       }
183     }
184
185     // Remove additional occurrences coming from condensed cases and keep the
186     // number of incoming values equal to the number of branches to SuccBB.
187     SmallVector<unsigned, 8> Indices;
188     for (++Idx; LocalNumMergedCases > 0 && Idx < E; ++Idx)
189       if (PN->getIncomingBlock(Idx) == OrigBB) {
190         Indices.push_back(Idx);
191         LocalNumMergedCases--;
192       }
193     // Remove incoming values in the reverse order to prevent invalidating
194     // *successive* index.
195     for (auto III = Indices.rbegin(), IIE = Indices.rend(); III != IIE; ++III)
196       PN->removeIncomingValue(*III);
197   }
198 }
199
200 /// Convert the switch statement into a binary lookup of the case values.
201 /// The function recursively builds this tree. LowerBound and UpperBound are
202 /// used to keep track of the bounds for Val that have already been checked by
203 /// a block emitted by one of the previous calls to switchConvert in the call
204 /// stack.
205 BasicBlock *
206 LowerSwitch::switchConvert(CaseItr Begin, CaseItr End, ConstantInt *LowerBound,
207                            ConstantInt *UpperBound, Value *Val,
208                            BasicBlock *Predecessor, BasicBlock *OrigBlock,
209                            BasicBlock *Default,
210                            const std::vector<IntRange> &UnreachableRanges) {
211   unsigned Size = End - Begin;
212
213   if (Size == 1) {
214     // Check if the Case Range is perfectly squeezed in between
215     // already checked Upper and Lower bounds. If it is then we can avoid
216     // emitting the code that checks if the value actually falls in the range
217     // because the bounds already tell us so.
218     if (Begin->Low == LowerBound && Begin->High == UpperBound) {
219       unsigned NumMergedCases = 0;
220       if (LowerBound && UpperBound)
221         NumMergedCases =
222             UpperBound->getSExtValue() - LowerBound->getSExtValue();
223       fixPhis(Begin->BB, OrigBlock, Predecessor, NumMergedCases);
224       return Begin->BB;
225     }
226     return newLeafBlock(*Begin, Val, OrigBlock, Default);
227   }
228
229   unsigned Mid = Size / 2;
230   std::vector<CaseRange> LHS(Begin, Begin + Mid);
231   DEBUG(dbgs() << "LHS: " << LHS << "\n");
232   std::vector<CaseRange> RHS(Begin + Mid, End);
233   DEBUG(dbgs() << "RHS: " << RHS << "\n");
234
235   CaseRange &Pivot = *(Begin + Mid);
236   DEBUG(dbgs() << "Pivot ==> "
237                << Pivot.Low->getValue()
238                << " -" << Pivot.High->getValue() << "\n");
239
240   // NewLowerBound here should never be the integer minimal value.
241   // This is because it is computed from a case range that is never
242   // the smallest, so there is always a case range that has at least
243   // a smaller value.
244   ConstantInt *NewLowerBound = Pivot.Low;
245
246   // Because NewLowerBound is never the smallest representable integer
247   // it is safe here to subtract one.
248   ConstantInt *NewUpperBound = ConstantInt::get(NewLowerBound->getContext(),
249                                                 NewLowerBound->getValue() - 1);
250
251   if (!UnreachableRanges.empty()) {
252     // Check if the gap between LHS's highest and NewLowerBound is unreachable.
253     int64_t GapLow = LHS.back().High->getSExtValue() + 1;
254     int64_t GapHigh = NewLowerBound->getSExtValue() - 1;
255     IntRange Gap = { GapLow, GapHigh };
256     if (GapHigh >= GapLow && IsInRanges(Gap, UnreachableRanges))
257       NewUpperBound = LHS.back().High;
258   }
259
260   DEBUG(dbgs() << "LHS Bounds ==> ";
261         if (LowerBound) {
262           dbgs() << LowerBound->getSExtValue();
263         } else {
264           dbgs() << "NONE";
265         }
266         dbgs() << " - " << NewUpperBound->getSExtValue() << "\n";
267         dbgs() << "RHS Bounds ==> ";
268         dbgs() << NewLowerBound->getSExtValue() << " - ";
269         if (UpperBound) {
270           dbgs() << UpperBound->getSExtValue() << "\n";
271         } else {
272           dbgs() << "NONE\n";
273         });
274
275   // Create a new node that checks if the value is < pivot. Go to the
276   // left branch if it is and right branch if not.
277   Function* F = OrigBlock->getParent();
278   BasicBlock* NewNode = BasicBlock::Create(Val->getContext(), "NodeBlock");
279
280   ICmpInst* Comp = new ICmpInst(ICmpInst::ICMP_SLT,
281                                 Val, Pivot.Low, "Pivot");
282
283   BasicBlock *LBranch = switchConvert(LHS.begin(), LHS.end(), LowerBound,
284                                       NewUpperBound, Val, NewNode, OrigBlock,
285                                       Default, UnreachableRanges);
286   BasicBlock *RBranch = switchConvert(RHS.begin(), RHS.end(), NewLowerBound,
287                                       UpperBound, Val, NewNode, OrigBlock,
288                                       Default, UnreachableRanges);
289
290   F->getBasicBlockList().insert(++OrigBlock->getIterator(), NewNode);
291   NewNode->getInstList().push_back(Comp);
292
293   BranchInst::Create(LBranch, RBranch, Comp, NewNode);
294   return NewNode;
295 }
296
297 /// Create a new leaf block for the binary lookup tree. It checks if the
298 /// switch's value == the case's value. If not, then it jumps to the default
299 /// branch. At this point in the tree, the value can't be another valid case
300 /// value, so the jump to the "default" branch is warranted.
301 BasicBlock* LowerSwitch::newLeafBlock(CaseRange& Leaf, Value* Val,
302                                       BasicBlock* OrigBlock,
303                                       BasicBlock* Default)
304 {
305   Function* F = OrigBlock->getParent();
306   BasicBlock* NewLeaf = BasicBlock::Create(Val->getContext(), "LeafBlock");
307   F->getBasicBlockList().insert(++OrigBlock->getIterator(), NewLeaf);
308
309   // Emit comparison
310   ICmpInst* Comp = nullptr;
311   if (Leaf.Low == Leaf.High) {
312     // Make the seteq instruction...
313     Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_EQ, Val,
314                         Leaf.Low, "SwitchLeaf");
315   } else {
316     // Make range comparison
317     if (Leaf.Low->isMinValue(true /*isSigned*/)) {
318       // Val >= Min && Val <= Hi --> Val <= Hi
319       Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_SLE, Val, Leaf.High,
320                           "SwitchLeaf");
321     } else if (Leaf.Low->isZero()) {
322       // Val >= 0 && Val <= Hi --> Val <=u Hi
323       Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Val, Leaf.High,
324                           "SwitchLeaf");      
325     } else {
326       // Emit V-Lo <=u Hi-Lo
327       Constant* NegLo = ConstantExpr::getNeg(Leaf.Low);
328       Instruction* Add = BinaryOperator::CreateAdd(Val, NegLo,
329                                                    Val->getName()+".off",
330                                                    NewLeaf);
331       Constant *UpperBound = ConstantExpr::getAdd(NegLo, Leaf.High);
332       Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Add, UpperBound,
333                           "SwitchLeaf");
334     }
335   }
336
337   // Make the conditional branch...
338   BasicBlock* Succ = Leaf.BB;
339   BranchInst::Create(Succ, Default, Comp, NewLeaf);
340
341   // If there were any PHI nodes in this successor, rewrite one entry
342   // from OrigBlock to come from NewLeaf.
343   for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
344     PHINode* PN = cast<PHINode>(I);
345     // Remove all but one incoming entries from the cluster
346     uint64_t Range = Leaf.High->getSExtValue() -
347                      Leaf.Low->getSExtValue();
348     for (uint64_t j = 0; j < Range; ++j) {
349       PN->removeIncomingValue(OrigBlock);
350     }
351     
352     int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
353     assert(BlockIdx != -1 && "Switch didn't go to this successor??");
354     PN->setIncomingBlock((unsigned)BlockIdx, NewLeaf);
355   }
356
357   return NewLeaf;
358 }
359
360 /// Transform simple list of Cases into list of CaseRange's.
361 unsigned LowerSwitch::Clusterify(CaseVector& Cases, SwitchInst *SI) {
362   unsigned numCmps = 0;
363
364   // Start with "simple" cases
365   for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i)
366     Cases.push_back(CaseRange(i.getCaseValue(), i.getCaseValue(),
367                               i.getCaseSuccessor()));
368   
369   std::sort(Cases.begin(), Cases.end(), CaseCmp());
370
371   // Merge case into clusters
372   if (Cases.size() >= 2) {
373     CaseItr I = Cases.begin();
374     for (CaseItr J = std::next(I), E = Cases.end(); J != E; ++J) {
375       int64_t nextValue = J->Low->getSExtValue();
376       int64_t currentValue = I->High->getSExtValue();
377       BasicBlock* nextBB = J->BB;
378       BasicBlock* currentBB = I->BB;
379
380       // If the two neighboring cases go to the same destination, merge them
381       // into a single case.
382       assert(nextValue > currentValue && "Cases should be strictly ascending");
383       if ((nextValue == currentValue + 1) && (currentBB == nextBB)) {
384         I->High = J->High;
385         // FIXME: Combine branch weights.
386       } else if (++I != J) {
387         *I = *J;
388       }
389     }
390     Cases.erase(std::next(I), Cases.end());
391   }
392
393   for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
394     if (I->Low != I->High)
395       // A range counts double, since it requires two compares.
396       ++numCmps;
397   }
398
399   return numCmps;
400 }
401
402 /// Replace the specified switch instruction with a sequence of chained if-then
403 /// insts in a balanced binary search.
404 void LowerSwitch::processSwitchInst(SwitchInst *SI,
405                                     SmallPtrSetImpl<BasicBlock*> &DeleteList) {
406   BasicBlock *CurBlock = SI->getParent();
407   BasicBlock *OrigBlock = CurBlock;
408   Function *F = CurBlock->getParent();
409   Value *Val = SI->getCondition();  // The value we are switching on...
410   BasicBlock* Default = SI->getDefaultDest();
411
412   // If there is only the default destination, just branch.
413   if (!SI->getNumCases()) {
414     BranchInst::Create(Default, CurBlock);
415     SI->eraseFromParent();
416     return;
417   }
418
419   // Prepare cases vector.
420   CaseVector Cases;
421   unsigned numCmps = Clusterify(Cases, SI);
422   DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
423                << ". Total compares: " << numCmps << "\n");
424   DEBUG(dbgs() << "Cases: " << Cases << "\n");
425   (void)numCmps;
426
427   ConstantInt *LowerBound = nullptr;
428   ConstantInt *UpperBound = nullptr;
429   std::vector<IntRange> UnreachableRanges;
430
431   if (isa<UnreachableInst>(Default->getFirstNonPHIOrDbg())) {
432     // Make the bounds tightly fitted around the case value range, because we
433     // know that the value passed to the switch must be exactly one of the case
434     // values.
435     assert(!Cases.empty());
436     LowerBound = Cases.front().Low;
437     UpperBound = Cases.back().High;
438
439     DenseMap<BasicBlock *, unsigned> Popularity;
440     unsigned MaxPop = 0;
441     BasicBlock *PopSucc = nullptr;
442
443     IntRange R = { INT64_MIN, INT64_MAX };
444     UnreachableRanges.push_back(R);
445     for (const auto &I : Cases) {
446       int64_t Low = I.Low->getSExtValue();
447       int64_t High = I.High->getSExtValue();
448
449       IntRange &LastRange = UnreachableRanges.back();
450       if (LastRange.Low == Low) {
451         // There is nothing left of the previous range.
452         UnreachableRanges.pop_back();
453       } else {
454         // Terminate the previous range.
455         assert(Low > LastRange.Low);
456         LastRange.High = Low - 1;
457       }
458       if (High != INT64_MAX) {
459         IntRange R = { High + 1, INT64_MAX };
460         UnreachableRanges.push_back(R);
461       }
462
463       // Count popularity.
464       int64_t N = High - Low + 1;
465       unsigned &Pop = Popularity[I.BB];
466       if ((Pop += N) > MaxPop) {
467         MaxPop = Pop;
468         PopSucc = I.BB;
469       }
470     }
471 #ifndef NDEBUG
472     /* UnreachableRanges should be sorted and the ranges non-adjacent. */
473     for (auto I = UnreachableRanges.begin(), E = UnreachableRanges.end();
474          I != E; ++I) {
475       assert(I->Low <= I->High);
476       auto Next = I + 1;
477       if (Next != E) {
478         assert(Next->Low > I->High);
479       }
480     }
481 #endif
482
483     // Use the most popular block as the new default, reducing the number of
484     // cases.
485     assert(MaxPop > 0 && PopSucc);
486     Default = PopSucc;
487     Cases.erase(std::remove_if(
488                     Cases.begin(), Cases.end(),
489                     [PopSucc](const CaseRange &R) { return R.BB == PopSucc; }),
490                 Cases.end());
491
492     // If there are no cases left, just branch.
493     if (Cases.empty()) {
494       BranchInst::Create(Default, CurBlock);
495       SI->eraseFromParent();
496       return;
497     }
498   }
499
500   // Create a new, empty default block so that the new hierarchy of
501   // if-then statements go to this and the PHI nodes are happy.
502   BasicBlock *NewDefault = BasicBlock::Create(SI->getContext(), "NewDefault");
503   F->getBasicBlockList().insert(Default->getIterator(), NewDefault);
504   BranchInst::Create(Default, NewDefault);
505
506   // If there is an entry in any PHI nodes for the default edge, make sure
507   // to update them as well.
508   for (BasicBlock::iterator I = Default->begin(); isa<PHINode>(I); ++I) {
509     PHINode *PN = cast<PHINode>(I);
510     int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
511     assert(BlockIdx != -1 && "Switch didn't go to this successor??");
512     PN->setIncomingBlock((unsigned)BlockIdx, NewDefault);
513   }
514
515   BasicBlock *SwitchBlock =
516       switchConvert(Cases.begin(), Cases.end(), LowerBound, UpperBound, Val,
517                     OrigBlock, OrigBlock, NewDefault, UnreachableRanges);
518
519   // Branch to our shiny new if-then stuff...
520   BranchInst::Create(SwitchBlock, OrigBlock);
521
522   // We are now done with the switch instruction, delete it.
523   BasicBlock *OldDefault = SI->getDefaultDest();
524   CurBlock->getInstList().erase(SI);
525
526   // If the Default block has no more predecessors just add it to DeleteList.
527   if (pred_begin(OldDefault) == pred_end(OldDefault))
528     DeleteList.insert(OldDefault);
529 }