LLVM 24.0.0git
SpeculativeExecution.cpp
Go to the documentation of this file.
1//===- SpeculativeExecution.cpp ---------------------------------*- C++ -*-===//
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// This pass hoists instructions to enable speculative execution on
10// targets where branches are expensive. This is aimed at GPUs. It
11// currently works on simple if-then and if-then-else
12// patterns.
13//
14// Removing branches is not the only motivation for this
15// pass. E.g. consider this code and assume that there is no
16// addressing mode for multiplying by sizeof(*a):
17//
18// if (b > 0)
19// c = a[i + 1]
20// if (d > 0)
21// e = a[i + 2]
22//
23// turns into
24//
25// p = &a[i + 1];
26// if (b > 0)
27// c = *p;
28// q = &a[i + 2];
29// if (d > 0)
30// e = *q;
31//
32// which could later be optimized to
33//
34// r = &a[i];
35// if (b > 0)
36// c = r[1];
37// if (d > 0)
38// e = r[2];
39//
40// Later passes sink back much of the speculated code that did not enable
41// further optimization.
42//
43// This pass is more aggressive than the function SpeculativeyExecuteBB in
44// SimplifyCFG. SimplifyCFG will not speculate if no selects are introduced and
45// it will speculate at most one instruction. It also will not speculate if
46// there is a value defined in the if-block that is only used in the then-block.
47// These restrictions make sense since the speculation in SimplifyCFG seems
48// aimed at introducing cheap selects, while this pass is intended to do more
49// aggressive speculation while counting on later passes to either capitalize on
50// that or clean it up.
51//
52// If the pass was created by calling
53// createSpeculativeExecutionIfHasBranchDivergencePass or the
54// -spec-exec-only-if-divergent-target option is present, this pass only has an
55// effect on targets where TargetTransformInfo::hasBranchDivergence() is true;
56// on other targets, it is a nop.
57//
58// This lets you include this pass unconditionally in the IR pass pipeline, but
59// only enable it for relevant targets.
60//
61//===----------------------------------------------------------------------===//
62
64#include "ScalarOptions.h"
70#include "llvm/IR/Operator.h"
72#include "llvm/Support/Debug.h"
74
75using namespace llvm;
76
77#define DEBUG_TYPE "speculative-execution"
78
79namespace {
80
81class SpeculativeExecutionLegacyPass : public FunctionPass {
82public:
83 static char ID;
84 explicit SpeculativeExecutionLegacyPass(bool OnlyIfDivergentTarget = false)
85 : FunctionPass(ID), OnlyIfDivergentTarget(OnlyIfDivergentTarget),
86 Impl(OnlyIfDivergentTarget) {}
87
88 void getAnalysisUsage(AnalysisUsage &AU) const override;
89 bool runOnFunction(Function &F) override;
90
91 StringRef getPassName() const override {
92 if (OnlyIfDivergentTarget)
93 return "Speculatively execute instructions if target has divergent "
94 "branches";
95 return "Speculatively execute instructions";
96 }
97
98private:
99 // Variable preserved purely for correct name printing.
100 const bool OnlyIfDivergentTarget;
101
103};
104} // namespace
105
106char SpeculativeExecutionLegacyPass::ID = 0;
107INITIALIZE_PASS_BEGIN(SpeculativeExecutionLegacyPass, "speculative-execution",
108 "Speculatively execute instructions", false, false)
110INITIALIZE_PASS_END(SpeculativeExecutionLegacyPass, "speculative-execution",
111 "Speculatively execute instructions", false, false)
112
113void SpeculativeExecutionLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const {
114 AU.addRequired<TargetTransformInfoWrapperPass>();
115 AU.addPreserved<GlobalsAAWrapperPass>();
116 AU.setPreservesCFG();
117}
118
119bool SpeculativeExecutionLegacyPass::runOnFunction(Function &F) {
120 if (skipFunction(F))
121 return false;
122
123 auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
124 return Impl.runImpl(F, TTI);
125}
126
128 Opts = &F.getContext().getLibraryOptions().get<ScalarOptions>();
129 if ((OnlyIfDivergentTarget || Opts->spec_exec_only_if_divergent_target) &&
130 !TTI->hasBranchDivergence(&F)) {
131 LLVM_DEBUG(dbgs() << "Not running SpeculativeExecution because "
132 "TTI->hasBranchDivergence() is false.\n");
133 return false;
134 }
135
136 this->TTI = TTI;
137 bool Changed = false;
138 for (auto& B : F) {
140 }
141 return Changed;
142}
143
144bool SpeculativeExecutionPass::runOnBasicBlock(BasicBlock &B) {
145 CondBrInst *BI = dyn_cast<CondBrInst>(B.getTerminator());
146 if (!BI)
147 return false;
148
149 BasicBlock &Succ0 = *BI->getSuccessor(0);
150 BasicBlock &Succ1 = *BI->getSuccessor(1);
151
152 if (&B == &Succ0 || &B == &Succ1 || &Succ0 == &Succ1) {
153 return false;
154 }
155
156 // Hoist from if-then (triangle).
157 if (Succ0.getSinglePredecessor() != nullptr &&
158 Succ0.getSingleSuccessor() == &Succ1) {
159 return considerHoistingFromTo(Succ0, B);
160 }
161
162 // Hoist from if-else (triangle).
163 if (Succ1.getSinglePredecessor() != nullptr &&
164 Succ1.getSingleSuccessor() == &Succ0) {
165 return considerHoistingFromTo(Succ1, B);
166 }
167
168 // Hoist from if-then-else (diamond), but only if it is equivalent to
169 // an if-else or if-then due to one of the branches doing nothing.
170 if (Succ0.getSinglePredecessor() != nullptr &&
171 Succ1.getSinglePredecessor() != nullptr &&
172 Succ1.getSingleSuccessor() != nullptr &&
173 Succ1.getSingleSuccessor() != &B &&
174 Succ1.getSingleSuccessor() == Succ0.getSingleSuccessor()) {
175 // If a block has only one instruction, then that is a terminator
176 // instruction so that the block does nothing. This does happen.
177 if (Succ1.size() == 1) // equivalent to if-then
178 return considerHoistingFromTo(Succ0, B);
179 if (Succ0.size() == 1) // equivalent to if-else
180 return considerHoistingFromTo(Succ1, B);
181 }
182
183 return false;
184}
185
187 const TargetTransformInfo &TTI) {
188 switch (Operator::getOpcode(I)) {
189 case Instruction::GetElementPtr:
190 case Instruction::Add:
191 case Instruction::Mul:
192 case Instruction::And:
193 case Instruction::Or:
194 case Instruction::Select:
195 case Instruction::Shl:
196 case Instruction::Sub:
197 case Instruction::LShr:
198 case Instruction::AShr:
199 case Instruction::Xor:
200 case Instruction::ZExt:
201 case Instruction::SExt:
202 case Instruction::Call:
203 case Instruction::BitCast:
204 case Instruction::PtrToInt:
205 case Instruction::PtrToAddr:
206 case Instruction::IntToPtr:
207 case Instruction::AddrSpaceCast:
208 case Instruction::FPToUI:
209 case Instruction::FPToSI:
210 case Instruction::UIToFP:
211 case Instruction::SIToFP:
212 case Instruction::FPExt:
213 case Instruction::FPTrunc:
214 case Instruction::FAdd:
215 case Instruction::FSub:
216 case Instruction::FMul:
217 case Instruction::FDiv:
218 case Instruction::FRem:
219 case Instruction::FNeg:
220 case Instruction::ICmp:
221 case Instruction::FCmp:
222 case Instruction::Trunc:
223 case Instruction::Freeze:
224 case Instruction::ExtractElement:
225 case Instruction::InsertElement:
226 case Instruction::ShuffleVector:
227 case Instruction::ExtractValue:
228 case Instruction::InsertValue:
229 return TTI.getInstructionCost(I, TargetTransformInfo::TCK_SizeAndLatency);
230
231 default:
232 return InstructionCost::getInvalid(); // Disallow anything not explicitly
233 // listed.
234 }
235}
236
237// Do not hoist any debug info intrinsics.
238// ...
239// if (cond) {
240// x = y * z;
241// foo();
242// }
243// ...
244// -------- Which then becomes:
245// ...
246// if.then:
247// %x = mul i32 %y, %z
248// call void @llvm.dbg.value(%x, !"x", !DIExpression())
249// call void foo()
250//
251// SpeculativeExecution might decide to hoist the 'y * z' calculation
252// out of the 'if' block, because it is more efficient that way, so the
253// '%x = mul i32 %y, %z' moves to the block above. But it might also
254// decide to hoist the 'llvm.dbg.value' call.
255// This is incorrect, because even if we've moved the calculation of
256// 'y * z', we should not see the value of 'x' change unless we
257// actually go inside the 'if' block.
258
259bool SpeculativeExecutionPass::considerHoistingFromTo(
260 BasicBlock &FromBlock, BasicBlock &ToBlock) {
261 SmallPtrSet<const Instruction *, 8> NotHoisted;
262 auto HasNoUnhoistedInstr = [&NotHoisted](auto Values) {
263 for (const Value *V : Values) {
264 if (const auto *I = dyn_cast_or_null<Instruction>(V))
265 if (NotHoisted.contains(I))
266 return false;
267 }
268 return true;
269 };
270 auto AllPrecedingUsesFromBlockHoisted =
271 [&HasNoUnhoistedInstr](const User *U) {
272 return HasNoUnhoistedInstr(U->operand_values());
273 };
274
275 InstructionCost TotalSpeculationCost = 0;
276 unsigned NotHoistedInstCount = 0;
277 for (const auto &I : FromBlock) {
280 AllPrecedingUsesFromBlockHoisted(&I)) {
281 TotalSpeculationCost += Cost;
282 if (TotalSpeculationCost > Opts->spec_exec_max_speculation_cost)
283 return false; // too much to hoist
284 } else {
285 NotHoistedInstCount++;
286 if (NotHoistedInstCount > Opts->spec_exec_max_not_hoisted)
287 return false; // too much left behind
288 NotHoisted.insert(&I);
289 }
290 }
291
292 for (auto I = FromBlock.begin(); I != FromBlock.end();) {
293 // We have to increment I before moving Current as moving Current
294 // changes the list that I is iterating through.
295 auto Current = I;
296 ++I;
297 if (!NotHoisted.count(&*Current)) {
298 Current->moveBefore(ToBlock.getTerminator()->getIterator());
299 Current->dropLocation();
300 }
301 }
302 return true;
303}
304
306 return new SpeculativeExecutionLegacyPass();
307}
308
310 return new SpeculativeExecutionLegacyPass(/* OnlyIfDivergentTarget = */ true);
311}
312
314 : OnlyIfDivergentTarget(OnlyIfDivergentTarget) {}
315
318 auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
319
320 bool Changed = runImpl(F, TTI);
321
322 if (!Changed)
323 return PreservedAnalyses::all();
326 return PA;
327}
328
330 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
331 static_cast<PassInfoMixin<SpeculativeExecutionPass> *>(this)->printPipeline(
332 OS, MapClassName2PassName);
333 OS << '<';
334 if (OnlyIfDivergentTarget)
335 OS << "only-if-divergent-target";
336 OS << '>';
337}
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static bool runOnFunction(Function &F, bool PostInlining)
This is the interface for a simple mod/ref and alias analysis over globals.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static bool runOnBasicBlock(MachineBasicBlock *MBB, unsigned BasicBlockNum, VRegRenamer &Renamer)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
This file defines the SmallPtrSet class.
static InstructionCost ComputeSpeculationCost(const Instruction *I, const TargetTransformInfo &TTI)
#define LLVM_DEBUG(...)
Definition Debug.h:119
This pass exposes codegen information to IR-level passes.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
LLVM_ABI const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
size_t size() const
Definition BasicBlock.h:461
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
Conditional Branch instruction.
BasicBlock * getSuccessor(unsigned i) const
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
Legacy wrapper pass to provide the GlobalsAAResult object.
static InstructionCost getInvalid(CostType Val=0)
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
Definition Operator.h:43
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
LLVM_ABI bool runImpl(Function &F, TargetTransformInfo *TTI)
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
LLVM_ABI SpeculativeExecutionPass(bool OnlyIfDivergentTarget=false)
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Analysis pass providing the TargetTransformInfo.
Wrapper pass for TargetTransformInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
@ TCK_SizeAndLatency
The weighted sum of size and latency.
An efficient, type-erasing, non-owning reference to a callable.
self_iterator getIterator()
Definition ilist_node.h:123
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
Changed
@ User
could "use" a pointer
This is an optimization pass for GlobalISel generic memory operations.
InstructionCost Cost
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI FunctionPass * createSpeculativeExecutionIfHasBranchDivergencePass()
LLVM_ABI bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
Return true if the instruction does not have any effects besides calculating the result and does not ...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI FunctionPass * createSpeculativeExecutionPass()
TargetTransformInfo TTI
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.