1 //===-- SIAnnotateControlFlow.cpp - ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// Annotates the control flow with hardware specific intrinsics.
13 //===----------------------------------------------------------------------===//
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"
28 // Complex types used in this pass
29 typedef std::pair<BasicBlock *, Value *> StackEntry;
30 typedef SmallVector<StackEntry, 16> StackVector;
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";
41 class SIAnnotateControlFlow : public FunctionPass {
50 ConstantInt *BoolTrue;
51 ConstantInt *BoolFalse;
52 UndefValue *BoolUndef;
65 SSAUpdater PhiInserter;
67 bool isTopOfStack(BasicBlock *BB);
71 void push(BasicBlock *BB, Value *Saved);
73 bool isElse(PHINode *Phi);
75 void eraseIfUnused(PHINode *Phi);
77 void openIf(BranchInst *Term);
79 void insertElse(BranchInst *Term);
81 void handleLoopCondition(Value *Cond);
83 void handleLoop(BranchInst *Term);
85 void closeControlFlow(BasicBlock *BB);
88 SIAnnotateControlFlow():
91 virtual bool doInitialization(Module &M);
93 virtual bool runOnFunction(Function &F);
95 virtual const char *getPassName() const {
96 return "SI annotate control flow";
99 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
100 AU.addRequired<DominatorTree>();
101 AU.addPreserved<DominatorTree>();
102 FunctionPass::getAnalysisUsage(AU);
107 } // end anonymous namespace
109 char SIAnnotateControlFlow::ID = 0;
111 /// \brief Initialize all the types and constants used in the pass
112 bool SIAnnotateControlFlow::doInitialization(Module &M) {
113 LLVMContext &Context = M.getContext();
115 Void = Type::getVoidTy(Context);
116 Boolean = Type::getInt1Ty(Context);
117 Int64 = Type::getInt64Ty(Context);
118 ReturnStruct = StructType::get(Boolean, Int64, (Type *)0);
120 BoolTrue = ConstantInt::getTrue(Context);
121 BoolFalse = ConstantInt::getFalse(Context);
122 BoolUndef = UndefValue::get(Boolean);
123 Int64Zero = ConstantInt::get(Int64, 0);
125 If = M.getOrInsertFunction(
126 IfIntrinsic, ReturnStruct, Boolean, (Type *)0);
128 Else = M.getOrInsertFunction(
129 ElseIntrinsic, ReturnStruct, Int64, (Type *)0);
131 Break = M.getOrInsertFunction(
132 BreakIntrinsic, Int64, Int64, (Type *)0);
134 IfBreak = M.getOrInsertFunction(
135 IfBreakIntrinsic, Int64, Boolean, Int64, (Type *)0);
137 ElseBreak = M.getOrInsertFunction(
138 ElseBreakIntrinsic, Int64, Int64, Int64, (Type *)0);
140 Loop = M.getOrInsertFunction(
141 LoopIntrinsic, Boolean, Int64, (Type *)0);
143 EndCf = M.getOrInsertFunction(
144 EndCfIntrinsic, Void, Int64, (Type *)0);
149 /// \brief Is BB the last block saved on the stack ?
150 bool SIAnnotateControlFlow::isTopOfStack(BasicBlock *BB) {
151 return Stack.back().first == BB;
154 /// \brief Pop the last saved value from the control flow stack
155 Value *SIAnnotateControlFlow::popSaved() {
156 return Stack.pop_back_val().second;
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));
164 /// \brief Can the condition represented by this PHI node treated like
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) {
171 if (Phi->getIncomingValue(i) != BoolTrue)
175 if (Phi->getIncomingValue(i) != BoolFalse)
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();
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));
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));
203 /// \brief Recursively handle the condition leading to a loop
204 void SIAnnotateControlFlow::handleLoopCondition(Value *Cond) {
205 if (PHINode *Phi = dyn_cast<PHINode>(Cond)) {
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))
213 Phi->setIncomingValue(i, BoolFalse);
214 handleLoopCondition(Incoming);
217 BasicBlock *Parent = Phi->getParent();
218 BasicBlock *IDom = DT->getNode(Parent)->getIDom()->getBlock();
220 for (unsigned i = 0, e = Phi->getNumIncomingValues(); i != e; ++i) {
222 Value *Incoming = Phi->getIncomingValue(i);
223 if (Incoming != BoolTrue)
226 BasicBlock *From = Phi->getIncomingBlock(i);
228 CallInst *OldEnd = dyn_cast<CallInst>(Parent->getFirstInsertionPt());
229 if (OldEnd && OldEnd->getCalledFunction() == EndCf) {
231 OldEnd->getArgOperand(0),
232 PhiInserter.GetValueAtEndOfBlock(Parent)
234 Value *Ret = CallInst::Create(ElseBreak, Args, "", OldEnd);
235 PhiInserter.AddAvailableValue(Parent, Ret);
240 TerminatorInst *Insert = From->getTerminator();
241 Value *Arg = PhiInserter.GetValueAtEndOfBlock(From);
242 Value *Ret = CallInst::Create(Break, Arg, "", Insert);
243 PhiInserter.AddAvailableValue(From, Ret);
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);
255 assert(0 && "Unhandled loop condition!");
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());
264 PhiInserter.Initialize(Int64, "");
265 PhiInserter.AddAvailableValue(Target, Broken);
267 Value *Cond = Term->getCondition();
268 Term->setCondition(BoolTrue);
269 handleLoopCondition(Cond);
271 BasicBlock *BB = Term->getParent();
272 Value *Arg = PhiInserter.GetValueAtEndOfBlock(BB);
273 for (pred_iterator PI = pred_begin(Target), PE = pred_end(Target);
276 Broken->addIncoming(*PI == BB ? Arg : Int64Zero, *PI);
279 Term->setCondition(CallInst::Create(Loop, Arg, "", Term));
280 push(Term->getSuccessor(0), Arg);
283 /// \brief Close the last opened control flow
284 void SIAnnotateControlFlow::closeControlFlow(BasicBlock *BB) {
285 CallInst::Create(EndCf, popSaved(), "", BB->getFirstInsertionPt());
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>();
293 for (df_iterator<BasicBlock *> I = df_begin(&F.getEntryBlock()),
294 E = df_end(&F.getEntryBlock()); I != E; ++I) {
296 BranchInst *Term = dyn_cast<BranchInst>((*I)->getTerminator());
298 if (!Term || Term->isUnconditional()) {
299 if (isTopOfStack(*I))
300 closeControlFlow(*I);
304 if (I.nodeVisited(Term->getSuccessor(1))) {
305 if (isTopOfStack(*I))
306 closeControlFlow(*I);
311 if (isTopOfStack(*I)) {
312 PHINode *Phi = dyn_cast<PHINode>(Term->getCondition());
313 if (Phi && Phi->getParent() == *I && isElse(Phi)) {
318 closeControlFlow(*I);
323 assert(Stack.empty());
327 /// \brief Create the annotation pass
328 FunctionPass *llvm::createSIAnnotateControlFlowPass() {
329 return new SIAnnotateControlFlow();