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 //===----------------------------------------------------------------------===//
16 #include "llvm/ADT/DepthFirstIterator.h"
17 #include "llvm/IR/Constants.h"
18 #include "llvm/IR/Dominators.h"
19 #include "llvm/IR/Instructions.h"
20 #include "llvm/IR/Module.h"
21 #include "llvm/Pass.h"
22 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
23 #include "llvm/Transforms/Utils/SSAUpdater.h"
27 #define DEBUG_TYPE "si-annotate-control-flow"
31 // Complex types used in this pass
32 typedef std::pair<BasicBlock *, Value *> StackEntry;
33 typedef SmallVector<StackEntry, 16> StackVector;
35 // Intrinsic names the control flow is annotated with
36 static const char *const IfIntrinsic = "llvm.SI.if";
37 static const char *const ElseIntrinsic = "llvm.SI.else";
38 static const char *const BreakIntrinsic = "llvm.SI.break";
39 static const char *const IfBreakIntrinsic = "llvm.SI.if.break";
40 static const char *const ElseBreakIntrinsic = "llvm.SI.else.break";
41 static const char *const LoopIntrinsic = "llvm.SI.loop";
42 static const char *const EndCfIntrinsic = "llvm.SI.end.cf";
44 class SIAnnotateControlFlow : public FunctionPass {
53 ConstantInt *BoolTrue;
54 ConstantInt *BoolFalse;
55 UndefValue *BoolUndef;
68 SSAUpdater PhiInserter;
70 bool isTopOfStack(BasicBlock *BB);
74 void push(BasicBlock *BB, Value *Saved);
76 bool isElse(PHINode *Phi);
78 void eraseIfUnused(PHINode *Phi);
80 void openIf(BranchInst *Term);
82 void insertElse(BranchInst *Term);
84 void handleLoopCondition(Value *Cond);
86 void handleLoop(BranchInst *Term);
88 void closeControlFlow(BasicBlock *BB);
91 SIAnnotateControlFlow():
94 bool doInitialization(Module &M) override;
96 bool runOnFunction(Function &F) override;
98 const char *getPassName() const override {
99 return "SI annotate control flow";
102 void getAnalysisUsage(AnalysisUsage &AU) const override {
103 AU.addRequired<DominatorTreeWrapperPass>();
104 AU.addPreserved<DominatorTreeWrapperPass>();
105 FunctionPass::getAnalysisUsage(AU);
110 } // end anonymous namespace
112 char SIAnnotateControlFlow::ID = 0;
114 /// \brief Initialize all the types and constants used in the pass
115 bool SIAnnotateControlFlow::doInitialization(Module &M) {
116 LLVMContext &Context = M.getContext();
118 Void = Type::getVoidTy(Context);
119 Boolean = Type::getInt1Ty(Context);
120 Int64 = Type::getInt64Ty(Context);
121 ReturnStruct = StructType::get(Boolean, Int64, (Type *)nullptr);
123 BoolTrue = ConstantInt::getTrue(Context);
124 BoolFalse = ConstantInt::getFalse(Context);
125 BoolUndef = UndefValue::get(Boolean);
126 Int64Zero = ConstantInt::get(Int64, 0);
128 If = M.getOrInsertFunction(
129 IfIntrinsic, ReturnStruct, Boolean, (Type *)nullptr);
131 Else = M.getOrInsertFunction(
132 ElseIntrinsic, ReturnStruct, Int64, (Type *)nullptr);
134 Break = M.getOrInsertFunction(
135 BreakIntrinsic, Int64, Int64, (Type *)nullptr);
137 IfBreak = M.getOrInsertFunction(
138 IfBreakIntrinsic, Int64, Boolean, Int64, (Type *)nullptr);
140 ElseBreak = M.getOrInsertFunction(
141 ElseBreakIntrinsic, Int64, Int64, Int64, (Type *)nullptr);
143 Loop = M.getOrInsertFunction(
144 LoopIntrinsic, Boolean, Int64, (Type *)nullptr);
146 EndCf = M.getOrInsertFunction(
147 EndCfIntrinsic, Void, Int64, (Type *)nullptr);
152 /// \brief Is BB the last block saved on the stack ?
153 bool SIAnnotateControlFlow::isTopOfStack(BasicBlock *BB) {
154 return !Stack.empty() && Stack.back().first == BB;
157 /// \brief Pop the last saved value from the control flow stack
158 Value *SIAnnotateControlFlow::popSaved() {
159 return Stack.pop_back_val().second;
162 /// \brief Push a BB and saved value to the control flow stack
163 void SIAnnotateControlFlow::push(BasicBlock *BB, Value *Saved) {
164 Stack.push_back(std::make_pair(BB, Saved));
167 /// \brief Can the condition represented by this PHI node treated like
169 bool SIAnnotateControlFlow::isElse(PHINode *Phi) {
170 BasicBlock *IDom = DT->getNode(Phi->getParent())->getIDom()->getBlock();
171 for (unsigned i = 0, e = Phi->getNumIncomingValues(); i != e; ++i) {
172 if (Phi->getIncomingBlock(i) == IDom) {
174 if (Phi->getIncomingValue(i) != BoolTrue)
178 if (Phi->getIncomingValue(i) != BoolFalse)
186 // \brief Erase "Phi" if it is not used any more
187 void SIAnnotateControlFlow::eraseIfUnused(PHINode *Phi) {
188 if (!Phi->hasNUsesOrMore(1))
189 Phi->eraseFromParent();
192 /// \brief Open a new "If" block
193 void SIAnnotateControlFlow::openIf(BranchInst *Term) {
194 Value *Ret = CallInst::Create(If, Term->getCondition(), "", Term);
195 Term->setCondition(ExtractValueInst::Create(Ret, 0, "", Term));
196 push(Term->getSuccessor(1), ExtractValueInst::Create(Ret, 1, "", Term));
199 /// \brief Close the last "If" block and open a new "Else" block
200 void SIAnnotateControlFlow::insertElse(BranchInst *Term) {
201 Value *Ret = CallInst::Create(Else, popSaved(), "", Term);
202 Term->setCondition(ExtractValueInst::Create(Ret, 0, "", Term));
203 push(Term->getSuccessor(1), ExtractValueInst::Create(Ret, 1, "", Term));
206 /// \brief Recursively handle the condition leading to a loop
207 void SIAnnotateControlFlow::handleLoopCondition(Value *Cond) {
208 if (PHINode *Phi = dyn_cast<PHINode>(Cond)) {
210 // Handle all non-constant incoming values first
211 for (unsigned i = 0, e = Phi->getNumIncomingValues(); i != e; ++i) {
212 Value *Incoming = Phi->getIncomingValue(i);
213 if (isa<ConstantInt>(Incoming))
216 Phi->setIncomingValue(i, BoolFalse);
217 handleLoopCondition(Incoming);
220 BasicBlock *Parent = Phi->getParent();
221 BasicBlock *IDom = DT->getNode(Parent)->getIDom()->getBlock();
223 for (unsigned i = 0, e = Phi->getNumIncomingValues(); i != e; ++i) {
225 Value *Incoming = Phi->getIncomingValue(i);
226 if (Incoming != BoolTrue)
229 BasicBlock *From = Phi->getIncomingBlock(i);
231 CallInst *OldEnd = dyn_cast<CallInst>(Parent->getFirstInsertionPt());
232 if (OldEnd && OldEnd->getCalledFunction() == EndCf) {
234 OldEnd->getArgOperand(0),
235 PhiInserter.GetValueAtEndOfBlock(Parent)
237 Value *Ret = CallInst::Create(ElseBreak, Args, "", OldEnd);
238 PhiInserter.AddAvailableValue(Parent, Ret);
243 TerminatorInst *Insert = From->getTerminator();
244 Value *Arg = PhiInserter.GetValueAtEndOfBlock(From);
245 Value *Ret = CallInst::Create(Break, Arg, "", Insert);
246 PhiInserter.AddAvailableValue(From, Ret);
250 } else if (Instruction *Inst = dyn_cast<Instruction>(Cond)) {
251 BasicBlock *Parent = Inst->getParent();
252 TerminatorInst *Insert = Parent->getTerminator();
253 Value *Args[] = { Cond, PhiInserter.GetValueAtEndOfBlock(Parent) };
254 Value *Ret = CallInst::Create(IfBreak, Args, "", Insert);
255 PhiInserter.AddAvailableValue(Parent, Ret);
258 llvm_unreachable("Unhandled loop condition!");
262 /// \brief Handle a back edge (loop)
263 void SIAnnotateControlFlow::handleLoop(BranchInst *Term) {
264 BasicBlock *Target = Term->getSuccessor(1);
265 PHINode *Broken = PHINode::Create(Int64, 0, "", &Target->front());
267 PhiInserter.Initialize(Int64, "");
268 PhiInserter.AddAvailableValue(Target, Broken);
270 Value *Cond = Term->getCondition();
271 Term->setCondition(BoolTrue);
272 handleLoopCondition(Cond);
274 BasicBlock *BB = Term->getParent();
275 Value *Arg = PhiInserter.GetValueAtEndOfBlock(BB);
276 for (pred_iterator PI = pred_begin(Target), PE = pred_end(Target);
279 Broken->addIncoming(*PI == BB ? Arg : Int64Zero, *PI);
282 Term->setCondition(CallInst::Create(Loop, Arg, "", Term));
283 push(Term->getSuccessor(0), Arg);
286 /// \brief Close the last opened control flow
287 void SIAnnotateControlFlow::closeControlFlow(BasicBlock *BB) {
288 CallInst::Create(EndCf, popSaved(), "", BB->getFirstInsertionPt());
291 /// \brief Annotate the control flow with intrinsics so the backend can
292 /// recognize if/then/else and loops.
293 bool SIAnnotateControlFlow::runOnFunction(Function &F) {
294 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
296 for (df_iterator<BasicBlock *> I = df_begin(&F.getEntryBlock()),
297 E = df_end(&F.getEntryBlock()); I != E; ++I) {
299 BranchInst *Term = dyn_cast<BranchInst>((*I)->getTerminator());
301 if (!Term || Term->isUnconditional()) {
302 if (isTopOfStack(*I))
303 closeControlFlow(*I);
307 if (I.nodeVisited(Term->getSuccessor(1))) {
308 if (isTopOfStack(*I))
309 closeControlFlow(*I);
314 if (isTopOfStack(*I)) {
315 PHINode *Phi = dyn_cast<PHINode>(Term->getCondition());
316 if (Phi && Phi->getParent() == *I && isElse(Phi)) {
321 closeControlFlow(*I);
326 assert(Stack.empty());
330 /// \brief Create the annotation pass
331 FunctionPass *llvm::createSIAnnotateControlFlowPass() {
332 return new SIAnnotateControlFlow();