LLVM 24.0.0git
SIAnnotateControlFlow.cpp
Go to the documentation of this file.
1//===- SIAnnotateControlFlow.cpp ------------------------------------------===//
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/// \file
10/// Annotates the control flow with hardware specific intrinsics.
11//
12//===----------------------------------------------------------------------===//
13
14#include "AMDGPU.h"
15#include "AMDGPUTargetMachine.h"
16#include "GCNSubtarget.h"
21#include "llvm/IR/BasicBlock.h"
22#include "llvm/IR/Constants.h"
23#include "llvm/IR/Dominators.h"
24#include "llvm/IR/IRBuilder.h"
25#include "llvm/IR/IntrinsicsAMDGPU.h"
30
31using namespace llvm;
32
33#define DEBUG_TYPE "si-annotate-control-flow"
34
35namespace {
36
37// Complex types used in this pass
38using StackEntry = std::pair<BasicBlock *, Value *>;
39using StackVector = SmallVector<StackEntry, 16>;
40
41class SIAnnotateControlFlow {
42private:
43 Function *F;
45
46 Type *IntMask;
47
48 ConstantInt *BoolTrue;
49 ConstantInt *BoolFalse;
50 Constant *IntMaskZero;
51
52 Function *If = nullptr;
53 Function *Else = nullptr;
54 Function *IfBreak = nullptr;
55 Function *Loop = nullptr;
56 Function *EndCf = nullptr;
57
58 DominatorTree *DT;
59 StackVector Stack;
60
61 LoopInfo *LI;
62
63 void initialize(const GCNSubtarget &ST);
64
65 bool isUniform(CondBrInst *T);
66
67 bool isTopOfStack(BasicBlock *BB);
68
69 Value *popSaved();
70
71 void push(BasicBlock *BB, Value *Saved);
72
73 bool isElse(PHINode *Phi);
74
75 bool hasKill(const BasicBlock *BB);
76
77 bool eraseIfUnused(PHINode *Phi);
78
79 bool openIf(CondBrInst *Term);
80
81 bool insertElse(CondBrInst *Term);
82
83 Value *handleLoopCondition(Value *Cond, PHINode *Broken, llvm::Loop *L,
84 CondBrInst *Term);
85
86 bool handleLoop(CondBrInst *Term);
87
88 bool closeControlFlow(BasicBlock *BB);
89
90 Function *getDecl(Function *&Cache, Intrinsic::ID ID, ArrayRef<Type *> Tys) {
91 if (!Cache)
92 Cache = Intrinsic::getOrInsertDeclaration(F->getParent(), ID, Tys);
93 return Cache;
94 }
95
96public:
97 SIAnnotateControlFlow(Function &F, const GCNSubtarget &ST, DominatorTree &DT,
98 LoopInfo &LI, UniformityInfo &UA)
99 : F(&F), UA(&UA), DT(&DT), LI(&LI) {
100 initialize(ST);
101 }
102
103 bool run();
104};
105
106} // end anonymous namespace
107
108/// Initialize all the types and constants used in the pass
109void SIAnnotateControlFlow::initialize(const GCNSubtarget &ST) {
110 LLVMContext &Context = F->getContext();
111
112 IntMask =
113 ST.isWave32() ? Type::getInt32Ty(Context) : Type::getInt64Ty(Context);
114
115 BoolTrue = ConstantInt::getTrue(Context);
116 BoolFalse = ConstantInt::getFalse(Context);
117 IntMaskZero = ConstantInt::get(IntMask, 0);
118}
119
120/// Is the branch condition uniform or did the StructurizeCFG pass
121/// consider it as such?
122bool SIAnnotateControlFlow::isUniform(CondBrInst *T) {
123 return UA->isUniformTerminator(T) || T->hasMetadata("structurizecfg.uniform");
124}
125
126/// Is BB the last block saved on the stack ?
127bool SIAnnotateControlFlow::isTopOfStack(BasicBlock *BB) {
128 return !Stack.empty() && Stack.back().first == BB;
129}
130
131/// Pop the last saved value from the control flow stack
132Value *SIAnnotateControlFlow::popSaved() {
133 return Stack.pop_back_val().second;
134}
135
136/// Push a BB and saved value to the control flow stack
137void SIAnnotateControlFlow::push(BasicBlock *BB, Value *Saved) {
138 Stack.push_back(std::pair(BB, Saved));
139}
140
141/// Can the condition represented by this PHI node treated like
142/// an "Else" block?
143bool SIAnnotateControlFlow::isElse(PHINode *Phi) {
144 BasicBlock *IDom = DT->getNode(Phi->getParent())->getIDom()->getBlock();
145 for (unsigned i = 0, e = Phi->getNumIncomingValues(); i != e; ++i) {
146 if (Phi->getIncomingBlock(i) == IDom) {
147
148 if (Phi->getIncomingValue(i) != BoolTrue)
149 return false;
150
151 } else {
152 if (Phi->getIncomingValue(i) != BoolFalse)
153 return false;
154
155 }
156 }
157 return true;
158}
159
160bool SIAnnotateControlFlow::hasKill(const BasicBlock *BB) {
161 for (const Instruction &I : *BB) {
162 if (const CallInst *CI = dyn_cast<CallInst>(&I))
163 if (CI->getIntrinsicID() == Intrinsic::amdgcn_kill)
164 return true;
165 }
166 return false;
167}
168
169// Erase "Phi" if it is not used any more. Return true if any change was made.
170bool SIAnnotateControlFlow::eraseIfUnused(PHINode *Phi) {
172 if (Changed)
173 LLVM_DEBUG(dbgs() << "Erased unused condition phi\n");
174 return Changed;
175}
176
177/// Open a new "If" block
178bool SIAnnotateControlFlow::openIf(CondBrInst *Term) {
179 if (isUniform(Term))
180 return false;
181
182 IRBuilder<> IRB(Term);
183 Value *IfCall = IRB.CreateCall(getDecl(If, Intrinsic::amdgcn_if, IntMask),
184 {Term->getCondition()});
185 Value *Cond = IRB.CreateExtractValue(IfCall, {0});
186 Value *Mask = IRB.CreateExtractValue(IfCall, {1});
187 Term->setCondition(Cond);
188 push(Term->getSuccessor(1), Mask);
189 return true;
190}
191
192/// Close the last "If" block and open a new "Else" block
193bool SIAnnotateControlFlow::insertElse(CondBrInst *Term) {
194 if (isUniform(Term)) {
195 return false;
196 }
197
198 IRBuilder<> IRB(Term);
199 Value *ElseCall = IRB.CreateCall(
200 getDecl(Else, Intrinsic::amdgcn_else, {IntMask, IntMask}), {popSaved()});
201 Value *Cond = IRB.CreateExtractValue(ElseCall, {0});
202 Value *Mask = IRB.CreateExtractValue(ElseCall, {1});
203 Term->setCondition(Cond);
204 push(Term->getSuccessor(1), Mask);
205 return true;
206}
207
208/// Recursively handle the condition leading to a loop
209Value *SIAnnotateControlFlow::handleLoopCondition(Value *Cond, PHINode *Broken,
210 llvm::Loop *L,
211 CondBrInst *Term) {
212
213 auto CreateBreak = [this, Cond, Broken](Instruction *I) -> CallInst * {
214 return IRBuilder<>(I).CreateCall(
215 getDecl(IfBreak, Intrinsic::amdgcn_if_break, IntMask), {Cond, Broken});
216 };
217
218 if (Instruction *Inst = dyn_cast<Instruction>(Cond)) {
219 BasicBlock *Parent = Inst->getParent();
221 if (LI->getLoopFor(Parent) == L) {
222 // Insert IfBreak in the same BB as Cond, which can help
223 // SILowerControlFlow to know that it does not have to insert an
224 // AND with EXEC.
225 Insert = Parent->getTerminator();
226 } else if (L->contains(Inst)) {
227 Insert = Term;
228 } else {
229 Insert = &*L->getHeader()->getFirstNonPHIOrLifetime();
230 }
231
232 return CreateBreak(Insert);
233 }
234
235 // Insert IfBreak in the loop header TERM for constant COND other than true.
236 if (isa<Constant>(Cond)) {
237 Instruction *Insert = Cond == BoolTrue ?
238 Term : L->getHeader()->getTerminator();
239
240 return CreateBreak(Insert);
241 }
242
243 if (isa<Argument>(Cond)) {
244 Instruction *Insert = &*L->getHeader()->getFirstNonPHIOrLifetime();
245 return CreateBreak(Insert);
246 }
247
248 llvm_unreachable("Unhandled loop condition!");
249}
250
251/// Handle a back edge (loop)
252bool SIAnnotateControlFlow::handleLoop(CondBrInst *Term) {
253 if (isUniform(Term))
254 return false;
255
256 BasicBlock *BB = Term->getParent();
257 llvm::Loop *L = LI->getLoopFor(BB);
258 if (!L)
259 return false;
260
261 BasicBlock *Target = Term->getSuccessor(1);
262 PHINode *Broken = PHINode::Create(IntMask, 0, "phi.broken");
263 Broken->insertBefore(Target->begin());
264
265 Value *Cond = Term->getCondition();
266 Term->setCondition(BoolTrue);
267 Value *Arg = handleLoopCondition(Cond, Broken, L, Term);
268
269 for (BasicBlock *Pred : predecessors(Target)) {
270 Value *PHIValue = IntMaskZero;
271 if (Pred == BB) // Remember the value of the previous iteration.
272 PHIValue = Arg;
273 // If the backedge from Pred to Target could be executed before the exit
274 // of the loop at BB, it should not reset or change "Broken", which keeps
275 // track of the number of threads exited the loop at BB.
276 else if (L->contains(Pred) && DT->dominates(Pred, BB))
277 PHIValue = Broken;
278 Broken->addIncoming(PHIValue, Pred);
279 }
280
281 CallInst *LoopCall = IRBuilder<>(Term).CreateCall(
282 getDecl(Loop, Intrinsic::amdgcn_loop, IntMask), {Arg});
283 Term->setCondition(LoopCall);
284
285 push(Term->getSuccessor(0), Arg);
286
287 return true;
288}
289
290/// Close the last opened control flow
291bool SIAnnotateControlFlow::closeControlFlow(BasicBlock *BB) {
292 llvm::Loop *L = LI->getLoopFor(BB);
293
294 assert(Stack.back().first == BB);
295
296 if (L && L->getHeader() == BB) {
297 // We can't insert an EndCF call into a loop header, because it will
298 // get executed on every iteration of the loop, when it should be
299 // executed only once before the loop.
300 SmallVector <BasicBlock *, 8> Latches;
301 L->getLoopLatches(Latches);
302
304 for (BasicBlock *Pred : predecessors(BB)) {
305 if (!is_contained(Latches, Pred))
306 Preds.push_back(Pred);
307 }
308
309 BB = SplitBlockPredecessors(BB, Preds, "endcf.split", DT, LI, nullptr,
310 false);
311 }
312
313 Value *Exec = popSaved();
314 BasicBlock::iterator FirstInsertionPt = BB->getFirstInsertionPt();
315 if (!isa<UndefValue>(Exec) && !isa<UnreachableInst>(FirstInsertionPt)) {
316 Instruction *ExecDef = cast<Instruction>(Exec);
317 BasicBlock *DefBB = ExecDef->getParent();
318 if (!DT->dominates(DefBB, BB)) {
319 // Split edge to make Def dominate Use
320 FirstInsertionPt = SplitEdge(DefBB, BB, DT, LI)->getFirstInsertionPt();
321 }
322 IRBuilder<> IRB(FirstInsertionPt);
323 // TODO: StructurizeCFG 'Flow' blocks have debug locations from the
324 // condition, for now just avoid copying these DebugLocs so that stepping
325 // out of the then/else block in a debugger doesn't step to the condition.
326 IRB.SetCurrentDebugLocation(DebugLoc());
327 IRB.CreateCall(getDecl(EndCf, Intrinsic::amdgcn_end_cf, IntMask), {Exec});
328 }
329
330 return true;
331}
332
333/// Annotate the control flow with intrinsics so the backend can
334/// recognize if/then/else and loops.
335bool SIAnnotateControlFlow::run() {
336 bool Changed = false;
337
338 for (df_iterator<BasicBlock *> I = df_begin(&F->getEntryBlock()),
339 E = df_end(&F->getEntryBlock());
340 I != E; ++I) {
341 BasicBlock *BB = *I;
342 CondBrInst *Term = dyn_cast<CondBrInst>(BB->getTerminator());
343
344 if (!Term) {
345 if (isTopOfStack(BB))
346 Changed |= closeControlFlow(BB);
347
348 continue;
349 }
350
351 if (I.nodeVisited(Term->getSuccessor(1))) {
352 if (isTopOfStack(BB))
353 Changed |= closeControlFlow(BB);
354
355 if (DT->dominates(Term->getSuccessor(1), BB))
356 Changed |= handleLoop(Term);
357 continue;
358 }
359
360 if (isTopOfStack(BB)) {
361 PHINode *Phi = dyn_cast<PHINode>(Term->getCondition());
362 if (Phi && Phi->getParent() == BB && isElse(Phi) && !hasKill(BB)) {
363 Changed |= insertElse(Term);
364 Changed |= eraseIfUnused(Phi);
365 continue;
366 }
367
368 Changed |= closeControlFlow(BB);
369 }
370
371 Changed |= openIf(Term);
372 }
373
374 if (!Stack.empty()) {
375 // CFG was probably not structured.
376 report_fatal_error("failed to annotate CFG");
377 }
378
379 return Changed;
380}
381
384 const GCNSubtarget &ST = TM.getSubtarget<GCNSubtarget>(F);
385
386 DominatorTree &DT = FAM.getResult<DominatorTreeAnalysis>(F);
387 UniformityInfo &UI = FAM.getResult<UniformityInfoAnalysis>(F);
388 LoopInfo &LI = FAM.getResult<LoopAnalysis>(F);
389
390 SIAnnotateControlFlow Impl(F, ST, DT, LI, UI);
391
392 bool Changed = Impl.run();
393 if (!Changed)
394 return PreservedAnalyses::all();
395
396 // TODO: Is LoopInfo preserved?
399 return PA;
400}
401
403public:
404 static char ID;
405
407
408 StringRef getPassName() const override { return "SI annotate control flow"; }
409
419
420 bool runOnFunction(Function &F) override {
422 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
423 UniformityInfo &UI =
424 getAnalysis<UniformityInfoWrapperPass>().getUniformityInfo();
426 const TargetMachine &TM = TPC.getTM<TargetMachine>();
427 const GCNSubtarget &ST = TM.getSubtarget<GCNSubtarget>(F);
428
429 SIAnnotateControlFlow Impl(F, ST, DT, LI, UI);
430 return Impl.run();
431 }
432};
433
435 "Annotate SI Control Flow", false, false)
440 "Annotate SI Control Flow", false, false)
441
442char SIAnnotateControlFlowLegacy::ID = 0;
443
444/// Create the annotation pass
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
The AMDGPU TargetMachine interface definition for hw codegen targets.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Fixup Statepoint Caller Saved
AMD GCN specific subclass of TargetSubtarget.
#define DEBUG_TYPE
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
FunctionAnalysisManager FAM
#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
SmallVector< MachineOperand, 4 > Cond
#define LLVM_DEBUG(...)
Definition Debug.h:119
static void initialize(TargetLibraryInfoImpl &TLI, const Triple &T, const llvm::StringTable &StandardNames, VectorLibrary VecLib)
Initialize the set of available library functions based on the specified target triple.
Target-Independent Code Generator Pass Configuration Options pass.
LLVM IR instance of the generic uniformity analysis.
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
StringRef getPassName() const override
getPassName - Return a nice clean name for a pass.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
LLVM Basic Block Representation.
Definition BasicBlock.h:62
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
Conditional Branch instruction.
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
This is an important base class in LLVM.
Definition Constant.h:44
DomTreeNodeBase * getIDom() const
NodeT * getBlock() const
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:277
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
FunctionPass(char &pid)
Definition Pass.h:314
bool isUniformTerminator(const InstructionT *I) const
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:598
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
The legacy pass manager's analysis pass to compute loop information.
Definition LoopInfo.h:623
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition Pass.cpp:114
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:133
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Primary interface to the complete machine description for the target machine.
const STC & getSubtarget(const Function &F) const
This method returns a pointer to the specified type of TargetSubtargetInfo.
Target-Independent Code Generator Pass Configuration Options.
TMC & getTM() const
Get the right type of TargetMachine for this target.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
Analysis pass which computes UniformityInfo.
Legacy analysis pass which computes a CycleInfo.
LLVM Value Representation.
Definition Value.h:75
const ParentTy * getParent() const
Definition ilist_node.h:34
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
GenericUniformityInfo< SSAContext > UniformityInfo
FunctionPass * createSIAnnotateControlFlowLegacyPass()
Create the annotation pass.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
df_iterator< T > df_begin(const T &G)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
LLVM_ABI bool RecursivelyDeleteDeadPHINode(PHINode *PN, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, SmallPtrSetImpl< PHINode * > *KnownNonDeadPHIs=nullptr)
If the specified value is an effectively dead PHI node, due to being a def-use chain of single-use no...
Definition Local.cpp:622
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI BasicBlock * SplitBlockPredecessors(BasicBlock *BB, ArrayRef< BasicBlock * > Preds, const char *Suffix, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, bool PreserveLCSSA=false)
This method introduces at least one new basic block into the function and moves some of the predecess...
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
df_iterator< T > df_end(const T &G)
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI BasicBlock * SplitEdge(BasicBlock *From, BasicBlock *To, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the edge connecting the specified blocks, and return the newly created basic block between From...