R600: Coding style - remove empty spaces from the beginning of functions
[oota-llvm.git] / lib / Target / R600 / SIAnnotateControlFlow.cpp
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
17 #include "llvm/Pass.h"
18 #include "llvm/Module.h"
19 #include "llvm/Analysis/Dominators.h"
20 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
21 #include "llvm/ADT/DepthFirstIterator.h"
22 #include "llvm/Transforms/Utils/SSAUpdater.h"
23
24 using namespace llvm;
25
26 namespace {
27
28 // Complex types used in this pass
29 typedef std::pair<BasicBlock *, Value *> StackEntry;
30 typedef SmallVector<StackEntry, 16> StackVector;
31
32 // Intrinsic names the control flow is annotated with
33 static const char *IfIntrinsic = "llvm.SI.if";
34 static const char *ElseIntrinsic = "llvm.SI.else";
35 static const char *BreakIntrinsic = "llvm.SI.break";
36 static const char *IfBreakIntrinsic = "llvm.SI.if.break";
37 static const char *ElseBreakIntrinsic = "llvm.SI.else.break";
38 static const char *LoopIntrinsic = "llvm.SI.loop";
39 static const char *EndCfIntrinsic = "llvm.SI.end.cf";
40
41 class SIAnnotateControlFlow : public FunctionPass {
42
43   static char ID;
44
45   Type *Boolean;
46   Type *Void;
47   Type *Int64;
48   Type *ReturnStruct;
49
50   ConstantInt *BoolTrue;
51   ConstantInt *BoolFalse;
52   UndefValue *BoolUndef;
53   Constant *Int64Zero;
54
55   Constant *If;
56   Constant *Else;
57   Constant *Break;
58   Constant *IfBreak;
59   Constant *ElseBreak;
60   Constant *Loop;
61   Constant *EndCf;
62
63   DominatorTree *DT;
64   StackVector Stack;
65   SSAUpdater PhiInserter;
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   void eraseIfUnused(PHINode *Phi);
76
77   void openIf(BranchInst *Term);
78
79   void insertElse(BranchInst *Term);
80
81   void handleLoopCondition(Value *Cond);
82
83   void handleLoop(BranchInst *Term);
84
85   void closeControlFlow(BasicBlock *BB);
86
87 public:
88   SIAnnotateControlFlow():
89     FunctionPass(ID) { }
90
91   virtual bool doInitialization(Module &M);
92
93   virtual bool runOnFunction(Function &F);
94
95   virtual const char *getPassName() const {
96     return "SI annotate control flow";
97   }
98
99   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
100     AU.addRequired<DominatorTree>();
101     AU.addPreserved<DominatorTree>();
102     FunctionPass::getAnalysisUsage(AU);
103   }
104
105 };
106
107 } // end anonymous namespace
108
109 char SIAnnotateControlFlow::ID = 0;
110
111 /// \brief Initialize all the types and constants used in the pass
112 bool SIAnnotateControlFlow::doInitialization(Module &M) {
113   LLVMContext &Context = M.getContext();
114
115   Void = Type::getVoidTy(Context);
116   Boolean = Type::getInt1Ty(Context);
117   Int64 = Type::getInt64Ty(Context);
118   ReturnStruct = StructType::get(Boolean, Int64, (Type *)0);
119
120   BoolTrue = ConstantInt::getTrue(Context);
121   BoolFalse = ConstantInt::getFalse(Context);
122   BoolUndef = UndefValue::get(Boolean);
123   Int64Zero = ConstantInt::get(Int64, 0);
124
125   If = M.getOrInsertFunction(
126     IfIntrinsic, ReturnStruct, Boolean, (Type *)0);
127
128   Else = M.getOrInsertFunction(
129     ElseIntrinsic, ReturnStruct, Int64, (Type *)0);
130
131   Break = M.getOrInsertFunction(
132     BreakIntrinsic, Int64, Int64, (Type *)0);
133
134   IfBreak = M.getOrInsertFunction(
135     IfBreakIntrinsic, Int64, Boolean, Int64, (Type *)0);
136
137   ElseBreak = M.getOrInsertFunction(
138     ElseBreakIntrinsic, Int64, Int64, Int64, (Type *)0);
139
140   Loop = M.getOrInsertFunction(
141     LoopIntrinsic, Boolean, Int64, (Type *)0);
142
143   EndCf = M.getOrInsertFunction(
144     EndCfIntrinsic, Void, Int64, (Type *)0);
145
146   return false;
147 }
148
149 /// \brief Is BB the last block saved on the stack ?
150 bool SIAnnotateControlFlow::isTopOfStack(BasicBlock *BB) {
151   return Stack.back().first == BB;
152 }
153
154 /// \brief Pop the last saved value from the control flow stack
155 Value *SIAnnotateControlFlow::popSaved() {
156   return Stack.pop_back_val().second;
157 }
158
159 /// \brief Push a BB and saved value to the control flow stack
160 void SIAnnotateControlFlow::push(BasicBlock *BB, Value *Saved) {
161   Stack.push_back(std::make_pair(BB, Saved));
162 }
163
164 /// \brief Can the condition represented by this PHI node treated like
165 /// an "Else" block?
166 bool SIAnnotateControlFlow::isElse(PHINode *Phi) {
167   BasicBlock *IDom = DT->getNode(Phi->getParent())->getIDom()->getBlock();
168   for (unsigned i = 0, e = Phi->getNumIncomingValues(); i != e; ++i) {
169     if (Phi->getIncomingBlock(i) == IDom) {
170
171       if (Phi->getIncomingValue(i) != BoolTrue)
172         return false;
173
174     } else {
175       if (Phi->getIncomingValue(i) != BoolFalse)
176         return false;
177  
178     }
179   }
180   return true;
181 }
182
183 // \brief Erase "Phi" if it is not used any more
184 void SIAnnotateControlFlow::eraseIfUnused(PHINode *Phi) {
185   if (!Phi->hasNUsesOrMore(1))
186     Phi->eraseFromParent();
187 }
188
189 /// \brief Open a new "If" block
190 void SIAnnotateControlFlow::openIf(BranchInst *Term) {
191   Value *Ret = CallInst::Create(If, Term->getCondition(), "", Term);
192   Term->setCondition(ExtractValueInst::Create(Ret, 0, "", Term));
193   push(Term->getSuccessor(1), ExtractValueInst::Create(Ret, 1, "", Term));
194 }
195
196 /// \brief Close the last "If" block and open a new "Else" block
197 void SIAnnotateControlFlow::insertElse(BranchInst *Term) {
198   Value *Ret = CallInst::Create(Else, popSaved(), "", Term);
199   Term->setCondition(ExtractValueInst::Create(Ret, 0, "", Term));
200   push(Term->getSuccessor(1), ExtractValueInst::Create(Ret, 1, "", Term));
201 }
202
203 /// \brief Recursively handle the condition leading to a loop
204 void SIAnnotateControlFlow::handleLoopCondition(Value *Cond) {
205   if (PHINode *Phi = dyn_cast<PHINode>(Cond)) {
206
207     // Handle all non constant incoming values first
208     for (unsigned i = 0, e = Phi->getNumIncomingValues(); i != e; ++i) {
209       Value *Incoming = Phi->getIncomingValue(i);
210       if (isa<ConstantInt>(Incoming))
211         continue;
212
213       Phi->setIncomingValue(i, BoolFalse);
214       handleLoopCondition(Incoming);
215     }
216
217     BasicBlock *Parent = Phi->getParent();
218     BasicBlock *IDom = DT->getNode(Parent)->getIDom()->getBlock();
219
220     for (unsigned i = 0, e = Phi->getNumIncomingValues(); i != e; ++i) {
221
222       Value *Incoming = Phi->getIncomingValue(i);
223       if (Incoming != BoolTrue)
224         continue;
225
226       BasicBlock *From = Phi->getIncomingBlock(i);
227       if (From == IDom) {
228         CallInst *OldEnd = dyn_cast<CallInst>(Parent->getFirstInsertionPt());
229         if (OldEnd && OldEnd->getCalledFunction() == EndCf) {
230           Value *Args[] = {
231             OldEnd->getArgOperand(0),
232             PhiInserter.GetValueAtEndOfBlock(Parent)
233           };
234           Value *Ret = CallInst::Create(ElseBreak, Args, "", OldEnd);
235           PhiInserter.AddAvailableValue(Parent, Ret);
236           continue;
237         }
238       }
239
240       TerminatorInst *Insert = From->getTerminator();
241       Value *Arg = PhiInserter.GetValueAtEndOfBlock(From);
242       Value *Ret = CallInst::Create(Break, Arg, "", Insert);
243       PhiInserter.AddAvailableValue(From, Ret);
244     }
245     eraseIfUnused(Phi);
246
247   } else if (Instruction *Inst = dyn_cast<Instruction>(Cond)) {
248     BasicBlock *Parent = Inst->getParent();
249     TerminatorInst *Insert = Parent->getTerminator();
250     Value *Args[] = { Cond, PhiInserter.GetValueAtEndOfBlock(Parent) };
251     Value *Ret = CallInst::Create(IfBreak, Args, "", Insert);
252     PhiInserter.AddAvailableValue(Parent, Ret);
253
254   } else {
255     assert(0 && "Unhandled loop condition!");
256   }
257 }
258
259 /// \brief Handle a back edge (loop)
260 void SIAnnotateControlFlow::handleLoop(BranchInst *Term) {
261   BasicBlock *Target = Term->getSuccessor(1);
262   PHINode *Broken = PHINode::Create(Int64, 0, "", &Target->front());
263
264   PhiInserter.Initialize(Int64, "");
265   PhiInserter.AddAvailableValue(Target, Broken);
266
267   Value *Cond = Term->getCondition();
268   Term->setCondition(BoolTrue);
269   handleLoopCondition(Cond);
270
271   BasicBlock *BB = Term->getParent();
272   Value *Arg = PhiInserter.GetValueAtEndOfBlock(BB);
273   for (pred_iterator PI = pred_begin(Target), PE = pred_end(Target);
274        PI != PE; ++PI) {
275
276     Broken->addIncoming(*PI == BB ? Arg : Int64Zero, *PI);
277   }
278
279   Term->setCondition(CallInst::Create(Loop, Arg, "", Term));
280   push(Term->getSuccessor(0), Arg);
281 }
282
283 /// \brief Close the last opened control flow
284 void SIAnnotateControlFlow::closeControlFlow(BasicBlock *BB) {
285   CallInst::Create(EndCf, popSaved(), "", BB->getFirstInsertionPt());
286 }
287
288 /// \brief Annotate the control flow with intrinsics so the backend can
289 /// recognize if/then/else and loops.
290 bool SIAnnotateControlFlow::runOnFunction(Function &F) {
291   DT = &getAnalysis<DominatorTree>();
292
293   for (df_iterator<BasicBlock *> I = df_begin(&F.getEntryBlock()),
294        E = df_end(&F.getEntryBlock()); I != E; ++I) {
295
296     BranchInst *Term = dyn_cast<BranchInst>((*I)->getTerminator());
297
298     if (!Term || Term->isUnconditional()) {
299       if (isTopOfStack(*I))
300         closeControlFlow(*I);
301       continue;
302     }
303
304     if (I.nodeVisited(Term->getSuccessor(1))) {
305       if (isTopOfStack(*I))
306         closeControlFlow(*I);
307       handleLoop(Term);
308       continue;
309     }
310
311     if (isTopOfStack(*I)) {
312       PHINode *Phi = dyn_cast<PHINode>(Term->getCondition());
313       if (Phi && Phi->getParent() == *I && isElse(Phi)) {
314         insertElse(Term);
315         eraseIfUnused(Phi);
316         continue;
317       }
318       closeControlFlow(*I);
319     }
320     openIf(Term);
321   }
322
323   assert(Stack.empty());
324   return true;
325 }
326
327 /// \brief Create the annotation pass
328 FunctionPass *llvm::createSIAnnotateControlFlowPass() {
329   return new SIAnnotateControlFlow();
330 }