Move Pass into anonymous namespace. NFC.
[oota-llvm.git] / lib / Transforms / Scalar / SpeculativeExecution.cpp
1 //===- SpeculativeExecution.cpp ---------------------------------*- C++ -*-===//
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 // This pass hoists instructions to enable speculative execution on
11 // targets where branches are expensive. This is aimed at GPUs. It
12 // currently works on simple if-then and if-then-else
13 // patterns.
14 //
15 // Removing branches is not the only motivation for this
16 // pass. E.g. consider this code and assume that there is no
17 // addressing mode for multiplying by sizeof(*a):
18 //
19 //   if (b > 0)
20 //     c = a[i + 1]
21 //   if (d > 0)
22 //     e = a[i + 2]
23 //
24 // turns into
25 //
26 //   p = &a[i + 1];
27 //   if (b > 0)
28 //     c = *p;
29 //   q = &a[i + 2];
30 //   if (d > 0)
31 //     e = *q;
32 //
33 // which could later be optimized to
34 //
35 //   r = &a[i];
36 //   if (b > 0)
37 //     c = r[1];
38 //   if (d > 0)
39 //     e = r[2];
40 //
41 // Later passes sink back much of the speculated code that did not enable
42 // further optimization.
43 //
44 //===----------------------------------------------------------------------===//
45
46 #include "llvm/ADT/SmallSet.h"
47 #include "llvm/Analysis/TargetTransformInfo.h"
48 #include "llvm/Analysis/ValueTracking.h"
49 #include "llvm/IR/Instructions.h"
50 #include "llvm/IR/Module.h"
51 #include "llvm/IR/Operator.h"
52 #include "llvm/Support/CommandLine.h"
53 #include "llvm/Support/Debug.h"
54
55 using namespace llvm;
56
57 #define DEBUG_TYPE "speculative-execution"
58
59 // The risk that speculation will not pay off increases with the
60 // number of instructions speculated, so we put a limit on that.
61 static cl::opt<unsigned> SpecExecMaxSpeculationCost(
62     "spec-exec-max-speculation-cost", cl::init(7), cl::Hidden,
63     cl::desc("Speculative execution is not applied to basic blocks where "
64              "the cost of the instructions to speculatively execute "
65              "exceeds this limit."));
66
67 // Speculating just a few instructions from a larger block tends not
68 // to be profitable and this limit prevents that. A reason for that is
69 // that small basic blocks are more likely to be candidates for
70 // further optimization.
71 static cl::opt<unsigned> SpecExecMaxNotHoisted(
72     "spec-exec-max-not-hoisted", cl::init(5), cl::Hidden,
73     cl::desc("Speculative execution is not applied to basic blocks where the "
74              "number of instructions that would not be speculatively executed "
75              "exceeds this limit."));
76
77 namespace {
78 class SpeculativeExecution : public FunctionPass {
79  public:
80   static char ID;
81   SpeculativeExecution(): FunctionPass(ID) {}
82
83   void getAnalysisUsage(AnalysisUsage &AU) const override;
84   bool runOnFunction(Function &F) override;
85
86  private:
87   bool runOnBasicBlock(BasicBlock &B);
88   bool considerHoistingFromTo(BasicBlock &FromBlock, BasicBlock &ToBlock);
89
90   const TargetTransformInfo *TTI = nullptr;
91 };
92 } // namespace
93
94 char SpeculativeExecution::ID = 0;
95 INITIALIZE_PASS_BEGIN(SpeculativeExecution, "speculative-execution",
96                       "Speculatively execute instructions", false, false)
97 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
98 INITIALIZE_PASS_END(SpeculativeExecution, "speculative-execution",
99                       "Speculatively execute instructions", false, false)
100
101 void SpeculativeExecution::getAnalysisUsage(AnalysisUsage &AU) const {
102   AU.addRequired<TargetTransformInfoWrapperPass>();
103 }
104
105 bool SpeculativeExecution::runOnFunction(Function &F) {
106   if (skipOptnoneFunction(F))
107     return false;
108
109   TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
110
111   bool Changed = false;
112   for (auto& B : F) {
113     Changed |= runOnBasicBlock(B);
114   }
115   return Changed;
116 }
117
118 bool SpeculativeExecution::runOnBasicBlock(BasicBlock &B) {
119   BranchInst *BI = dyn_cast<BranchInst>(B.getTerminator());
120   if (BI == nullptr)
121     return false;
122
123   if (BI->getNumSuccessors() != 2)
124     return false;
125   BasicBlock &Succ0 = *BI->getSuccessor(0);
126   BasicBlock &Succ1 = *BI->getSuccessor(1);
127
128   if (&B == &Succ0 || &B == &Succ1 || &Succ0 == &Succ1) {
129     return false;
130   }
131
132   // Hoist from if-then (triangle).
133   if (Succ0.getSinglePredecessor() != nullptr &&
134       Succ0.getSingleSuccessor() == &Succ1) {
135     return considerHoistingFromTo(Succ0, B);
136   }
137
138   // Hoist from if-else (triangle).
139   if (Succ1.getSinglePredecessor() != nullptr &&
140       Succ1.getSingleSuccessor() == &Succ0) {
141     return considerHoistingFromTo(Succ1, B);
142   }
143
144   // Hoist from if-then-else (diamond), but only if it is equivalent to
145   // an if-else or if-then due to one of the branches doing nothing.
146   if (Succ0.getSinglePredecessor() != nullptr &&
147       Succ1.getSinglePredecessor() != nullptr &&
148       Succ1.getSingleSuccessor() != nullptr &&
149       Succ1.getSingleSuccessor() != &B &&
150       Succ1.getSingleSuccessor() == Succ0.getSingleSuccessor()) {
151     // If a block has only one instruction, then that is a terminator
152     // instruction so that the block does nothing. This does happen.
153     if (Succ1.size() == 1) // equivalent to if-then
154       return considerHoistingFromTo(Succ0, B);
155     if (Succ0.size() == 1) // equivalent to if-else
156       return considerHoistingFromTo(Succ1, B);
157   }
158
159   return false;
160 }
161
162 static unsigned ComputeSpeculationCost(const Instruction *I,
163                                        const TargetTransformInfo &TTI) {
164   switch (Operator::getOpcode(I)) {
165     case Instruction::GetElementPtr:
166     case Instruction::Add:
167     case Instruction::Mul:
168     case Instruction::And:
169     case Instruction::Or:
170     case Instruction::Select:
171     case Instruction::Shl:
172     case Instruction::Sub:
173     case Instruction::LShr:
174     case Instruction::AShr:
175     case Instruction::Xor:
176     case Instruction::ZExt:
177     case Instruction::SExt:
178       return TTI.getUserCost(I);
179
180     default:
181       return UINT_MAX; // Disallow anything not whitelisted.
182   }
183 }
184
185 bool SpeculativeExecution::considerHoistingFromTo(BasicBlock &FromBlock,
186                                                   BasicBlock &ToBlock) {
187   SmallSet<const Instruction *, 8> NotHoisted;
188   const auto AllPrecedingUsesFromBlockHoisted = [&NotHoisted](User *U) {
189     for (Value* V : U->operand_values()) {
190       if (Instruction *I = dyn_cast<Instruction>(V)) {
191         if (NotHoisted.count(I) > 0)
192           return false;
193       }
194     }
195     return true;
196   };
197
198   unsigned TotalSpeculationCost = 0;
199   for (auto& I : FromBlock) {
200     const unsigned Cost = ComputeSpeculationCost(&I, *TTI);
201     if (Cost != UINT_MAX && isSafeToSpeculativelyExecute(&I) &&
202         AllPrecedingUsesFromBlockHoisted(&I)) {
203       TotalSpeculationCost += Cost;
204       if (TotalSpeculationCost > SpecExecMaxSpeculationCost)
205         return false;  // too much to hoist
206     } else {
207       NotHoisted.insert(&I);
208       if (NotHoisted.size() > SpecExecMaxNotHoisted)
209         return false; // too much left behind
210     }
211   }
212
213   if (TotalSpeculationCost == 0)
214     return false; // nothing to hoist
215
216   for (auto I = FromBlock.begin(); I != FromBlock.end();) {
217     // We have to increment I before moving Current as moving Current
218     // changes the list that I is iterating through.
219     auto Current = I;
220     ++I;
221     if (!NotHoisted.count(Current)) {
222       Current->moveBefore(ToBlock.getTerminator());
223     }
224   }
225   return true;
226 }
227
228 namespace llvm {
229
230 FunctionPass *createSpeculativeExecutionPass() {
231   return new SpeculativeExecution();
232 }
233
234 }  // namespace llvm