1 //===- SIAnnotateControlFlow.cpp ------------------------------------------===//
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 /// \file
11 /// Annotates the control flow with hardware specific intrinsics.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "AMDGPU.h"
16 #include "llvm/ADT/DepthFirstIterator.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/Analysis/LegacyDivergenceAnalysis.h"
20 #include "llvm/Analysis/LoopInfo.h"
21 #include "llvm/Transforms/Utils/Local.h"
22 #include "llvm/IR/BasicBlock.h"
23 #include "llvm/IR/CFG.h"
24 #include "llvm/IR/Constant.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DerivedTypes.h"
27 #include "llvm/IR/Dominators.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/Instruction.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/Intrinsics.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/Type.h"
34 #include "llvm/IR/ValueHandle.h"
35 #include "llvm/Pass.h"
36 #include "llvm/Support/Casting.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
41 #include <cassert>
42 #include <utility>
43
44 using namespace llvm;
45
46 #define DEBUG_TYPE "si-annotate-control-flow"
47
48 namespace {
49
50 // Complex types used in this pass
51 using StackEntry = std::pair<BasicBlock *, Value *>;
52 using StackVector = SmallVector<StackEntry, 16>;
53
54 class SIAnnotateControlFlow : public FunctionPass {
55 LegacyDivergenceAnalysis *DA;
56
57 Type *Boolean;
58 Type *Void;
59 Type *Int64;
60 Type *ReturnStruct;
61
62 ConstantInt *BoolTrue;
63 ConstantInt *BoolFalse;
64 UndefValue *BoolUndef;
65 Constant *Int64Zero;
66
67 Function *If;
68 Function *Else;
69 Function *IfBreak;
70 Function *Loop;
71 Function *EndCf;
72
73 DominatorTree *DT;
74 StackVector Stack;
75
76 LoopInfo *LI;
77
78 bool isUniform(BranchInst *T);
79
80 bool isTopOfStack(BasicBlock *BB);
81
82 Value *popSaved();
83
84 void push(BasicBlock *BB, Value *Saved);
85
86 bool isElse(PHINode *Phi);
87
88 void eraseIfUnused(PHINode *Phi);
89
90 void openIf(BranchInst *Term);
91
92 void insertElse(BranchInst *Term);
93
94 Value *
95 handleLoopCondition(Value *Cond, PHINode *Broken, llvm::Loop *L,
96 BranchInst *Term);
97
98 void handleLoop(BranchInst *Term);
99
100 void closeControlFlow(BasicBlock *BB);
101
102 public:
103 static char ID;
104
SIAnnotateControlFlow()105 SIAnnotateControlFlow() : FunctionPass(ID) {}
106
107 bool doInitialization(Module &M) override;
108
109 bool runOnFunction(Function &F) override;
110
getPassName() const111 StringRef getPassName() const override { return "SI annotate control flow"; }
112
getAnalysisUsage(AnalysisUsage & AU) const113 void getAnalysisUsage(AnalysisUsage &AU) const override {
114 AU.addRequired<LoopInfoWrapperPass>();
115 AU.addRequired<DominatorTreeWrapperPass>();
116 AU.addRequired<LegacyDivergenceAnalysis>();
117 AU.addPreserved<DominatorTreeWrapperPass>();
118 FunctionPass::getAnalysisUsage(AU);
119 }
120 };
121
122 } // end anonymous namespace
123
124 INITIALIZE_PASS_BEGIN(SIAnnotateControlFlow, DEBUG_TYPE,
125 "Annotate SI Control Flow", false, false)
126 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
127 INITIALIZE_PASS_DEPENDENCY(LegacyDivergenceAnalysis)
128 INITIALIZE_PASS_END(SIAnnotateControlFlow, DEBUG_TYPE,
129 "Annotate SI Control Flow", false, false)
130
131 char SIAnnotateControlFlow::ID = 0;
132
133 /// Initialize all the types and constants used in the pass
doInitialization(Module & M)134 bool SIAnnotateControlFlow::doInitialization(Module &M) {
135 LLVMContext &Context = M.getContext();
136
137 Void = Type::getVoidTy(Context);
138 Boolean = Type::getInt1Ty(Context);
139 Int64 = Type::getInt64Ty(Context);
140 ReturnStruct = StructType::get(Boolean, Int64);
141
142 BoolTrue = ConstantInt::getTrue(Context);
143 BoolFalse = ConstantInt::getFalse(Context);
144 BoolUndef = UndefValue::get(Boolean);
145 Int64Zero = ConstantInt::get(Int64, 0);
146
147 If = Intrinsic::getDeclaration(&M, Intrinsic::amdgcn_if);
148 Else = Intrinsic::getDeclaration(&M, Intrinsic::amdgcn_else);
149 IfBreak = Intrinsic::getDeclaration(&M, Intrinsic::amdgcn_if_break);
150 Loop = Intrinsic::getDeclaration(&M, Intrinsic::amdgcn_loop);
151 EndCf = Intrinsic::getDeclaration(&M, Intrinsic::amdgcn_end_cf);
152 return false;
153 }
154
155 /// Is the branch condition uniform or did the StructurizeCFG pass
156 /// consider it as such?
isUniform(BranchInst * T)157 bool SIAnnotateControlFlow::isUniform(BranchInst *T) {
158 return DA->isUniform(T) ||
159 T->getMetadata("structurizecfg.uniform") != nullptr;
160 }
161
162 /// Is BB the last block saved on the stack ?
isTopOfStack(BasicBlock * BB)163 bool SIAnnotateControlFlow::isTopOfStack(BasicBlock *BB) {
164 return !Stack.empty() && Stack.back().first == BB;
165 }
166
167 /// Pop the last saved value from the control flow stack
popSaved()168 Value *SIAnnotateControlFlow::popSaved() {
169 return Stack.pop_back_val().second;
170 }
171
172 /// Push a BB and saved value to the control flow stack
push(BasicBlock * BB,Value * Saved)173 void SIAnnotateControlFlow::push(BasicBlock *BB, Value *Saved) {
174 Stack.push_back(std::make_pair(BB, Saved));
175 }
176
177 /// Can the condition represented by this PHI node treated like
178 /// an "Else" block?
isElse(PHINode * Phi)179 bool SIAnnotateControlFlow::isElse(PHINode *Phi) {
180 BasicBlock *IDom = DT->getNode(Phi->getParent())->getIDom()->getBlock();
181 for (unsigned i = 0, e = Phi->getNumIncomingValues(); i != e; ++i) {
182 if (Phi->getIncomingBlock(i) == IDom) {
183
184 if (Phi->getIncomingValue(i) != BoolTrue)
185 return false;
186
187 } else {
188 if (Phi->getIncomingValue(i) != BoolFalse)
189 return false;
190
191 }
192 }
193 return true;
194 }
195
196 // Erase "Phi" if it is not used any more
eraseIfUnused(PHINode * Phi)197 void SIAnnotateControlFlow::eraseIfUnused(PHINode *Phi) {
198 if (RecursivelyDeleteDeadPHINode(Phi)) {
199 LLVM_DEBUG(dbgs() << "Erased unused condition phi\n");
200 }
201 }
202
203 /// Open a new "If" block
openIf(BranchInst * Term)204 void SIAnnotateControlFlow::openIf(BranchInst *Term) {
205 if (isUniform(Term))
206 return;
207
208 Value *Ret = CallInst::Create(If, Term->getCondition(), "", Term);
209 Term->setCondition(ExtractValueInst::Create(Ret, 0, "", Term));
210 push(Term->getSuccessor(1), ExtractValueInst::Create(Ret, 1, "", Term));
211 }
212
213 /// Close the last "If" block and open a new "Else" block
insertElse(BranchInst * Term)214 void SIAnnotateControlFlow::insertElse(BranchInst *Term) {
215 if (isUniform(Term)) {
216 return;
217 }
218 Value *Ret = CallInst::Create(Else, popSaved(), "", Term);
219 Term->setCondition(ExtractValueInst::Create(Ret, 0, "", Term));
220 push(Term->getSuccessor(1), ExtractValueInst::Create(Ret, 1, "", Term));
221 }
222
223 /// Recursively handle the condition leading to a loop
handleLoopCondition(Value * Cond,PHINode * Broken,llvm::Loop * L,BranchInst * Term)224 Value *SIAnnotateControlFlow::handleLoopCondition(
225 Value *Cond, PHINode *Broken, llvm::Loop *L, BranchInst *Term) {
226 if (Instruction *Inst = dyn_cast<Instruction>(Cond)) {
227 BasicBlock *Parent = Inst->getParent();
228 Instruction *Insert;
229 if (L->contains(Inst)) {
230 Insert = Parent->getTerminator();
231 } else {
232 Insert = L->getHeader()->getFirstNonPHIOrDbgOrLifetime();
233 }
234
235 Value *Args[] = { Cond, Broken };
236 return CallInst::Create(IfBreak, Args, "", Insert);
237 }
238
239 // Insert IfBreak in the loop header TERM for constant COND other than true.
240 if (isa<Constant>(Cond)) {
241 Instruction *Insert = Cond == BoolTrue ?
242 Term : L->getHeader()->getTerminator();
243
244 Value *Args[] = { Cond, Broken };
245 return CallInst::Create(IfBreak, Args, "", Insert);
246 }
247
248 llvm_unreachable("Unhandled loop condition!");
249 }
250
251 /// Handle a back edge (loop)
handleLoop(BranchInst * Term)252 void SIAnnotateControlFlow::handleLoop(BranchInst *Term) {
253 if (isUniform(Term))
254 return;
255
256 BasicBlock *BB = Term->getParent();
257 llvm::Loop *L = LI->getLoopFor(BB);
258 if (!L)
259 return;
260
261 BasicBlock *Target = Term->getSuccessor(1);
262 PHINode *Broken = PHINode::Create(Int64, 0, "phi.broken", &Target->front());
263
264 Value *Cond = Term->getCondition();
265 Term->setCondition(BoolTrue);
266 Value *Arg = handleLoopCondition(Cond, Broken, L, Term);
267
268 for (BasicBlock *Pred : predecessors(Target))
269 Broken->addIncoming(Pred == BB ? Arg : Int64Zero, Pred);
270
271 Term->setCondition(CallInst::Create(Loop, Arg, "", Term));
272
273 push(Term->getSuccessor(0), Arg);
274 }
275
276 /// Close the last opened control flow
closeControlFlow(BasicBlock * BB)277 void SIAnnotateControlFlow::closeControlFlow(BasicBlock *BB) {
278 llvm::Loop *L = LI->getLoopFor(BB);
279
280 assert(Stack.back().first == BB);
281
282 if (L && L->getHeader() == BB) {
283 // We can't insert an EndCF call into a loop header, because it will
284 // get executed on every iteration of the loop, when it should be
285 // executed only once before the loop.
286 SmallVector <BasicBlock *, 8> Latches;
287 L->getLoopLatches(Latches);
288
289 SmallVector<BasicBlock *, 2> Preds;
290 for (BasicBlock *Pred : predecessors(BB)) {
291 if (!is_contained(Latches, Pred))
292 Preds.push_back(Pred);
293 }
294
295 BB = SplitBlockPredecessors(BB, Preds, "endcf.split", DT, LI, nullptr,
296 false);
297 }
298
299 Value *Exec = popSaved();
300 Instruction *FirstInsertionPt = &*BB->getFirstInsertionPt();
301 if (!isa<UndefValue>(Exec) && !isa<UnreachableInst>(FirstInsertionPt))
302 CallInst::Create(EndCf, Exec, "", FirstInsertionPt);
303 }
304
305 /// Annotate the control flow with intrinsics so the backend can
306 /// recognize if/then/else and loops.
runOnFunction(Function & F)307 bool SIAnnotateControlFlow::runOnFunction(Function &F) {
308 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
309 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
310 DA = &getAnalysis<LegacyDivergenceAnalysis>();
311
312 for (df_iterator<BasicBlock *> I = df_begin(&F.getEntryBlock()),
313 E = df_end(&F.getEntryBlock()); I != E; ++I) {
314 BasicBlock *BB = *I;
315 BranchInst *Term = dyn_cast<BranchInst>(BB->getTerminator());
316
317 if (!Term || Term->isUnconditional()) {
318 if (isTopOfStack(BB))
319 closeControlFlow(BB);
320
321 continue;
322 }
323
324 if (I.nodeVisited(Term->getSuccessor(1))) {
325 if (isTopOfStack(BB))
326 closeControlFlow(BB);
327
328 handleLoop(Term);
329 continue;
330 }
331
332 if (isTopOfStack(BB)) {
333 PHINode *Phi = dyn_cast<PHINode>(Term->getCondition());
334 if (Phi && Phi->getParent() == BB && isElse(Phi)) {
335 insertElse(Term);
336 eraseIfUnused(Phi);
337 continue;
338 }
339
340 closeControlFlow(BB);
341 }
342
343 openIf(Term);
344 }
345
346 if (!Stack.empty()) {
347 // CFG was probably not structured.
348 report_fatal_error("failed to annotate CFG");
349 }
350
351 return true;
352 }
353
354 /// Create the annotation pass
createSIAnnotateControlFlowPass()355 FunctionPass *llvm::createSIAnnotateControlFlowPass() {
356 return new SIAnnotateControlFlow();
357 }
358