Add a speculative execution pass
[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 class SpeculativeExecution : public FunctionPass {
78  public:
79   static char ID;
80   SpeculativeExecution(): FunctionPass(ID) {}
81
82   void getAnalysisUsage(AnalysisUsage &AU) const override;
83   bool runOnFunction(Function &F) override;
84
85  private:
86   bool runOnBasicBlock(BasicBlock &B);
87   bool considerHoistingFromTo(BasicBlock &FromBlock, BasicBlock &ToBlock);
88
89   const TargetTransformInfo *TTI = nullptr;
90 };
91
92 char SpeculativeExecution::ID = 0;
93 INITIALIZE_PASS_BEGIN(SpeculativeExecution, "speculative-execution",
94                       "Speculatively execute instructions", false, false)
95 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
96 INITIALIZE_PASS_END(SpeculativeExecution, "speculative-execution",
97                       "Speculatively execute instructions", false, false)
98
99 void SpeculativeExecution::getAnalysisUsage(AnalysisUsage &AU) const {
100   AU.addRequired<TargetTransformInfoWrapperPass>();
101 }
102
103 bool SpeculativeExecution::runOnFunction(Function &F) {
104   if (skipOptnoneFunction(F))
105     return false;
106
107   TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
108
109   bool Changed = false;
110   for (auto& B : F) {
111     Changed |= runOnBasicBlock(B);
112   }
113   return Changed;
114 }
115
116 bool SpeculativeExecution::runOnBasicBlock(BasicBlock &B) {
117   BranchInst *BI = dyn_cast<BranchInst>(B.getTerminator());
118   if (BI == nullptr)
119     return false;
120
121   if (BI->getNumSuccessors() != 2)
122     return false;
123   BasicBlock &Succ0 = *BI->getSuccessor(0);
124   BasicBlock &Succ1 = *BI->getSuccessor(1);
125
126   if (&B == &Succ0 || &B == &Succ1 || &Succ0 == &Succ1) {
127     return false;
128   }
129
130   // Hoist from if-then (triangle).
131   if (Succ0.getSinglePredecessor() != nullptr &&
132       Succ0.getSingleSuccessor() == &Succ1) {
133     return considerHoistingFromTo(Succ0, B);
134   }
135
136   // Hoist from if-else (triangle).
137   if (Succ1.getSinglePredecessor() != nullptr &&
138       Succ1.getSingleSuccessor() == &Succ0) {
139     return considerHoistingFromTo(Succ1, B);
140   }
141
142   // Hoist from if-then-else (diamond), but only if it is equivalent to
143   // an if-else or if-then due to one of the branches doing nothing.
144   if (Succ0.getSinglePredecessor() != nullptr &&
145       Succ1.getSinglePredecessor() != nullptr &&
146       Succ1.getSingleSuccessor() != nullptr &&
147       Succ1.getSingleSuccessor() != &B &&
148       Succ1.getSingleSuccessor() == Succ0.getSingleSuccessor()) {
149     // If a block has only one instruction, then that is a terminator
150     // instruction so that the block does nothing. This does happen.
151     if (Succ1.size() == 1) // equivalent to if-then
152       return considerHoistingFromTo(Succ0, B);
153     if (Succ0.size() == 1) // equivalent to if-else
154       return considerHoistingFromTo(Succ1, B);
155   }
156
157   return false;
158 }
159
160 static unsigned ComputeSpeculationCost(const Instruction *I,
161                                        const TargetTransformInfo &TTI) {
162   switch (Operator::getOpcode(I)) {
163     case Instruction::GetElementPtr:
164     case Instruction::Add:
165     case Instruction::Mul:
166     case Instruction::And:
167     case Instruction::Or:
168     case Instruction::Select:
169     case Instruction::Shl:
170     case Instruction::Sub:
171     case Instruction::LShr:
172     case Instruction::AShr:
173     case Instruction::Xor:
174     case Instruction::ZExt:
175     case Instruction::SExt:
176       return TTI.getUserCost(I);
177
178     default:
179       return UINT_MAX; // Disallow anything not whitelisted.
180   }
181 }
182
183 bool SpeculativeExecution::considerHoistingFromTo(BasicBlock &FromBlock,
184                                                   BasicBlock &ToBlock) {
185   SmallSet<const Instruction *, 8> NotHoisted;
186   const auto AllPrecedingUsesFromBlockHoisted = [&NotHoisted](User *U) {
187     for (Value* V : U->operand_values()) {
188       if (Instruction *I = dyn_cast<Instruction>(V)) {
189         if (NotHoisted.count(I) > 0)
190           return false;
191       }
192     }
193     return true;
194   };
195
196   unsigned TotalSpeculationCost = 0;
197   for (auto& I : FromBlock) {
198     const unsigned Cost = ComputeSpeculationCost(&I, *TTI);
199     if (Cost != UINT_MAX && isSafeToSpeculativelyExecute(&I) &&
200         AllPrecedingUsesFromBlockHoisted(&I)) {
201       TotalSpeculationCost += Cost;
202       if (TotalSpeculationCost > SpecExecMaxSpeculationCost)
203         return false;  // too much to hoist
204     } else {
205       NotHoisted.insert(&I);
206       if (NotHoisted.size() > SpecExecMaxNotHoisted)
207         return false; // too much left behind
208     }
209   }
210
211   if (TotalSpeculationCost == 0)
212     return false; // nothing to hoist
213
214   for (auto I = FromBlock.begin(); I != FromBlock.end();) {
215     // We have to increment I before moving Current as moving Current
216     // changes the list that I is iterating through.
217     auto Current = I;
218     ++I;
219     if (!NotHoisted.count(Current)) {
220       Current->moveBefore(ToBlock.getTerminator());
221     }
222   }
223   return true;
224 }
225
226 namespace llvm {
227
228 FunctionPass *createSpeculativeExecutionPass() {
229   return new SpeculativeExecution();
230 }
231
232 }  // namespace llvm