blob: 91eb60beb6bbe39bb0abd9a397804cdcea91e627 [file] [log] [blame]
Tom Stellardf8794352012-12-19 22:10:31 +00001//===-- 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"
Tom Stellardf8794352012-12-19 22:10:31 +000016#include "llvm/ADT/DepthFirstIterator.h"
Tom Stellardb0804ec2013-06-07 20:28:43 +000017#include "llvm/IR/Constants.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000018#include "llvm/IR/Dominators.h"
Tom Stellardb0804ec2013-06-07 20:28:43 +000019#include "llvm/IR/Instructions.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000020#include "llvm/IR/Module.h"
Chandler Carruthbe810232013-01-02 10:22:59 +000021#include "llvm/Pass.h"
22#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Tom Stellardf8794352012-12-19 22:10:31 +000023#include "llvm/Transforms/Utils/SSAUpdater.h"
24
25using namespace llvm;
26
Chandler Carruth84e68b22014-04-22 02:41:26 +000027#define DEBUG_TYPE "si-annotate-control-flow"
28
Tom Stellardf8794352012-12-19 22:10:31 +000029namespace {
30
31// Complex types used in this pass
32typedef std::pair<BasicBlock *, Value *> StackEntry;
33typedef SmallVector<StackEntry, 16> StackVector;
34
35// Intrinsic names the control flow is annotated with
Craig Topperd3a34f82013-07-16 01:17:10 +000036static const char *const IfIntrinsic = "llvm.SI.if";
37static const char *const ElseIntrinsic = "llvm.SI.else";
38static const char *const BreakIntrinsic = "llvm.SI.break";
39static const char *const IfBreakIntrinsic = "llvm.SI.if.break";
40static const char *const ElseBreakIntrinsic = "llvm.SI.else.break";
41static const char *const LoopIntrinsic = "llvm.SI.loop";
42static const char *const EndCfIntrinsic = "llvm.SI.end.cf";
Tom Stellardf8794352012-12-19 22:10:31 +000043
44class SIAnnotateControlFlow : public FunctionPass {
45
46 static char ID;
47
48 Type *Boolean;
49 Type *Void;
50 Type *Int64;
51 Type *ReturnStruct;
52
53 ConstantInt *BoolTrue;
54 ConstantInt *BoolFalse;
55 UndefValue *BoolUndef;
56 Constant *Int64Zero;
57
58 Constant *If;
59 Constant *Else;
60 Constant *Break;
61 Constant *IfBreak;
62 Constant *ElseBreak;
63 Constant *Loop;
64 Constant *EndCf;
65
66 DominatorTree *DT;
67 StackVector Stack;
Tom Stellardf8794352012-12-19 22:10:31 +000068
69 bool isTopOfStack(BasicBlock *BB);
70
71 Value *popSaved();
72
73 void push(BasicBlock *BB, Value *Saved);
74
75 bool isElse(PHINode *Phi);
76
77 void eraseIfUnused(PHINode *Phi);
78
79 void openIf(BranchInst *Term);
80
81 void insertElse(BranchInst *Term);
82
Tom Stellardde16a2e2014-06-20 17:06:02 +000083 Value *handleLoopCondition(Value *Cond, PHINode *Broken);
Tom Stellardf8794352012-12-19 22:10:31 +000084
85 void handleLoop(BranchInst *Term);
86
87 void closeControlFlow(BasicBlock *BB);
88
89public:
90 SIAnnotateControlFlow():
91 FunctionPass(ID) { }
92
Craig Topper5656db42014-04-29 07:57:24 +000093 bool doInitialization(Module &M) override;
Tom Stellardf8794352012-12-19 22:10:31 +000094
Craig Topper5656db42014-04-29 07:57:24 +000095 bool runOnFunction(Function &F) override;
Tom Stellardf8794352012-12-19 22:10:31 +000096
Craig Topper5656db42014-04-29 07:57:24 +000097 const char *getPassName() const override {
Tom Stellardf8794352012-12-19 22:10:31 +000098 return "SI annotate control flow";
99 }
100
Craig Topper5656db42014-04-29 07:57:24 +0000101 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth73523022014-01-13 13:07:17 +0000102 AU.addRequired<DominatorTreeWrapperPass>();
103 AU.addPreserved<DominatorTreeWrapperPass>();
Tom Stellardf8794352012-12-19 22:10:31 +0000104 FunctionPass::getAnalysisUsage(AU);
105 }
106
107};
108
109} // end anonymous namespace
110
111char SIAnnotateControlFlow::ID = 0;
112
113/// \brief Initialize all the types and constants used in the pass
114bool SIAnnotateControlFlow::doInitialization(Module &M) {
Tom Stellardf8794352012-12-19 22:10:31 +0000115 LLVMContext &Context = M.getContext();
116
117 Void = Type::getVoidTy(Context);
118 Boolean = Type::getInt1Ty(Context);
119 Int64 = Type::getInt64Ty(Context);
Craig Topper062a2ba2014-04-25 05:30:21 +0000120 ReturnStruct = StructType::get(Boolean, Int64, (Type *)nullptr);
Tom Stellardf8794352012-12-19 22:10:31 +0000121
122 BoolTrue = ConstantInt::getTrue(Context);
123 BoolFalse = ConstantInt::getFalse(Context);
124 BoolUndef = UndefValue::get(Boolean);
125 Int64Zero = ConstantInt::get(Int64, 0);
126
127 If = M.getOrInsertFunction(
Craig Topper062a2ba2014-04-25 05:30:21 +0000128 IfIntrinsic, ReturnStruct, Boolean, (Type *)nullptr);
Tom Stellardf8794352012-12-19 22:10:31 +0000129
130 Else = M.getOrInsertFunction(
Craig Topper062a2ba2014-04-25 05:30:21 +0000131 ElseIntrinsic, ReturnStruct, Int64, (Type *)nullptr);
Tom Stellardf8794352012-12-19 22:10:31 +0000132
133 Break = M.getOrInsertFunction(
Craig Topper062a2ba2014-04-25 05:30:21 +0000134 BreakIntrinsic, Int64, Int64, (Type *)nullptr);
Tom Stellardf8794352012-12-19 22:10:31 +0000135
136 IfBreak = M.getOrInsertFunction(
Craig Topper062a2ba2014-04-25 05:30:21 +0000137 IfBreakIntrinsic, Int64, Boolean, Int64, (Type *)nullptr);
Tom Stellardf8794352012-12-19 22:10:31 +0000138
139 ElseBreak = M.getOrInsertFunction(
Craig Topper062a2ba2014-04-25 05:30:21 +0000140 ElseBreakIntrinsic, Int64, Int64, Int64, (Type *)nullptr);
Tom Stellardf8794352012-12-19 22:10:31 +0000141
142 Loop = M.getOrInsertFunction(
Craig Topper062a2ba2014-04-25 05:30:21 +0000143 LoopIntrinsic, Boolean, Int64, (Type *)nullptr);
Tom Stellardf8794352012-12-19 22:10:31 +0000144
145 EndCf = M.getOrInsertFunction(
Craig Topper062a2ba2014-04-25 05:30:21 +0000146 EndCfIntrinsic, Void, Int64, (Type *)nullptr);
Tom Stellardf8794352012-12-19 22:10:31 +0000147
148 return false;
149}
150
151/// \brief Is BB the last block saved on the stack ?
152bool SIAnnotateControlFlow::isTopOfStack(BasicBlock *BB) {
Michel Danzerae0a4032013-02-14 08:00:33 +0000153 return !Stack.empty() && Stack.back().first == BB;
Tom Stellardf8794352012-12-19 22:10:31 +0000154}
155
156/// \brief Pop the last saved value from the control flow stack
157Value *SIAnnotateControlFlow::popSaved() {
158 return Stack.pop_back_val().second;
159}
160
161/// \brief Push a BB and saved value to the control flow stack
162void SIAnnotateControlFlow::push(BasicBlock *BB, Value *Saved) {
163 Stack.push_back(std::make_pair(BB, Saved));
164}
165
166/// \brief Can the condition represented by this PHI node treated like
167/// an "Else" block?
168bool SIAnnotateControlFlow::isElse(PHINode *Phi) {
Tom Stellardf8794352012-12-19 22:10:31 +0000169 BasicBlock *IDom = DT->getNode(Phi->getParent())->getIDom()->getBlock();
170 for (unsigned i = 0, e = Phi->getNumIncomingValues(); i != e; ++i) {
171 if (Phi->getIncomingBlock(i) == IDom) {
172
173 if (Phi->getIncomingValue(i) != BoolTrue)
174 return false;
175
176 } else {
177 if (Phi->getIncomingValue(i) != BoolFalse)
178 return false;
Tom Stellardde16a2e2014-06-20 17:06:02 +0000179
Tom Stellardf8794352012-12-19 22:10:31 +0000180 }
181 }
182 return true;
183}
184
185// \brief Erase "Phi" if it is not used any more
186void SIAnnotateControlFlow::eraseIfUnused(PHINode *Phi) {
187 if (!Phi->hasNUsesOrMore(1))
188 Phi->eraseFromParent();
189}
190
191/// \brief Open a new "If" block
192void SIAnnotateControlFlow::openIf(BranchInst *Term) {
193 Value *Ret = CallInst::Create(If, Term->getCondition(), "", Term);
194 Term->setCondition(ExtractValueInst::Create(Ret, 0, "", Term));
195 push(Term->getSuccessor(1), ExtractValueInst::Create(Ret, 1, "", Term));
196}
197
198/// \brief Close the last "If" block and open a new "Else" block
199void SIAnnotateControlFlow::insertElse(BranchInst *Term) {
200 Value *Ret = CallInst::Create(Else, popSaved(), "", Term);
201 Term->setCondition(ExtractValueInst::Create(Ret, 0, "", Term));
202 push(Term->getSuccessor(1), ExtractValueInst::Create(Ret, 1, "", Term));
203}
204
205/// \brief Recursively handle the condition leading to a loop
Tom Stellardde16a2e2014-06-20 17:06:02 +0000206Value *SIAnnotateControlFlow::handleLoopCondition(Value *Cond, PHINode *Broken) {
Tom Stellardf8794352012-12-19 22:10:31 +0000207 if (PHINode *Phi = dyn_cast<PHINode>(Cond)) {
Tom Stellardde16a2e2014-06-20 17:06:02 +0000208 BasicBlock *Parent = Phi->getParent();
209 PHINode *NewPhi = PHINode::Create(Int64, 0, "", &Parent->front());
210 Value *Ret = NewPhi;
Tom Stellardf8794352012-12-19 22:10:31 +0000211
Alp Tokerf907b892013-12-05 05:44:44 +0000212 // Handle all non-constant incoming values first
Tom Stellardf8794352012-12-19 22:10:31 +0000213 for (unsigned i = 0, e = Phi->getNumIncomingValues(); i != e; ++i) {
214 Value *Incoming = Phi->getIncomingValue(i);
Tom Stellardde16a2e2014-06-20 17:06:02 +0000215 BasicBlock *From = Phi->getIncomingBlock(i);
216 if (isa<ConstantInt>(Incoming)) {
217 NewPhi->addIncoming(Broken, From);
Tom Stellardf8794352012-12-19 22:10:31 +0000218 continue;
Tom Stellardde16a2e2014-06-20 17:06:02 +0000219 }
Tom Stellardf8794352012-12-19 22:10:31 +0000220
221 Phi->setIncomingValue(i, BoolFalse);
Tom Stellardde16a2e2014-06-20 17:06:02 +0000222 Value *PhiArg = handleLoopCondition(Incoming, Broken);
223 NewPhi->addIncoming(PhiArg, From);
Tom Stellardf8794352012-12-19 22:10:31 +0000224 }
225
Tom Stellardf8794352012-12-19 22:10:31 +0000226 BasicBlock *IDom = DT->getNode(Parent)->getIDom()->getBlock();
227
228 for (unsigned i = 0, e = Phi->getNumIncomingValues(); i != e; ++i) {
229
230 Value *Incoming = Phi->getIncomingValue(i);
231 if (Incoming != BoolTrue)
232 continue;
233
234 BasicBlock *From = Phi->getIncomingBlock(i);
235 if (From == IDom) {
236 CallInst *OldEnd = dyn_cast<CallInst>(Parent->getFirstInsertionPt());
237 if (OldEnd && OldEnd->getCalledFunction() == EndCf) {
Tom Stellardde16a2e2014-06-20 17:06:02 +0000238 Value *Args[] = { OldEnd->getArgOperand(0), NewPhi };
239 Ret = CallInst::Create(ElseBreak, Args, "", OldEnd);
Tom Stellardf8794352012-12-19 22:10:31 +0000240 continue;
241 }
242 }
Tom Stellardf8794352012-12-19 22:10:31 +0000243 TerminatorInst *Insert = From->getTerminator();
Tom Stellardde16a2e2014-06-20 17:06:02 +0000244 Value *PhiArg = CallInst::Create(Break, Broken, "", Insert);
245 NewPhi->setIncomingValue(i, PhiArg);
Tom Stellardf8794352012-12-19 22:10:31 +0000246 }
247 eraseIfUnused(Phi);
Tom Stellardde16a2e2014-06-20 17:06:02 +0000248 return Ret;
Tom Stellardf8794352012-12-19 22:10:31 +0000249
250 } else if (Instruction *Inst = dyn_cast<Instruction>(Cond)) {
251 BasicBlock *Parent = Inst->getParent();
252 TerminatorInst *Insert = Parent->getTerminator();
Tom Stellardde16a2e2014-06-20 17:06:02 +0000253 Value *Args[] = { Cond, Broken };
254 return CallInst::Create(IfBreak, Args, "", Insert);
Tom Stellardf8794352012-12-19 22:10:31 +0000255
256 } else {
Matt Arsenaulteaa3a7e2013-12-10 21:37:42 +0000257 llvm_unreachable("Unhandled loop condition!");
Tom Stellardf8794352012-12-19 22:10:31 +0000258 }
Tom Stellardde16a2e2014-06-20 17:06:02 +0000259 return 0;
Tom Stellardf8794352012-12-19 22:10:31 +0000260}
261
262/// \brief Handle a back edge (loop)
263void SIAnnotateControlFlow::handleLoop(BranchInst *Term) {
Tom Stellardf8794352012-12-19 22:10:31 +0000264 BasicBlock *Target = Term->getSuccessor(1);
265 PHINode *Broken = PHINode::Create(Int64, 0, "", &Target->front());
266
Tom Stellardf8794352012-12-19 22:10:31 +0000267 Value *Cond = Term->getCondition();
268 Term->setCondition(BoolTrue);
Tom Stellardde16a2e2014-06-20 17:06:02 +0000269 Value *Arg = handleLoopCondition(Cond, Broken);
Tom Stellardf8794352012-12-19 22:10:31 +0000270
271 BasicBlock *BB = Term->getParent();
Tom Stellardf8794352012-12-19 22:10:31 +0000272 for (pred_iterator PI = pred_begin(Target), PE = pred_end(Target);
273 PI != PE; ++PI) {
274
275 Broken->addIncoming(*PI == BB ? Arg : Int64Zero, *PI);
276 }
277
278 Term->setCondition(CallInst::Create(Loop, Arg, "", Term));
279 push(Term->getSuccessor(0), Arg);
280}
281
282/// \brief Close the last opened control flow
283void SIAnnotateControlFlow::closeControlFlow(BasicBlock *BB) {
284 CallInst::Create(EndCf, popSaved(), "", BB->getFirstInsertionPt());
285}
286
287/// \brief Annotate the control flow with intrinsics so the backend can
288/// recognize if/then/else and loops.
289bool SIAnnotateControlFlow::runOnFunction(Function &F) {
Chandler Carruth73523022014-01-13 13:07:17 +0000290 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Tom Stellardf8794352012-12-19 22:10:31 +0000291
292 for (df_iterator<BasicBlock *> I = df_begin(&F.getEntryBlock()),
293 E = df_end(&F.getEntryBlock()); I != E; ++I) {
294
295 BranchInst *Term = dyn_cast<BranchInst>((*I)->getTerminator());
296
297 if (!Term || Term->isUnconditional()) {
298 if (isTopOfStack(*I))
299 closeControlFlow(*I);
300 continue;
301 }
302
303 if (I.nodeVisited(Term->getSuccessor(1))) {
304 if (isTopOfStack(*I))
305 closeControlFlow(*I);
306 handleLoop(Term);
307 continue;
308 }
309
310 if (isTopOfStack(*I)) {
311 PHINode *Phi = dyn_cast<PHINode>(Term->getCondition());
312 if (Phi && Phi->getParent() == *I && isElse(Phi)) {
313 insertElse(Term);
314 eraseIfUnused(Phi);
315 continue;
316 }
317 closeControlFlow(*I);
318 }
319 openIf(Term);
320 }
321
322 assert(Stack.empty());
323 return true;
324}
325
326/// \brief Create the annotation pass
327FunctionPass *llvm::createSIAnnotateControlFlowPass() {
Tom Stellardf8794352012-12-19 22:10:31 +0000328 return new SIAnnotateControlFlow();
329}