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;
69 bool isTopOfStack(BasicBlock *BB);
73 void push(BasicBlock *BB, Value *Saved);
75 bool isElse(PHINode *Phi);
77 void eraseIfUnused(PHINode *Phi);
79 void openIf(BranchInst *Term);
81 void insertElse(BranchInst *Term);
83 Value *handleLoopCondition(Value *Cond, PHINode *Broken);
85 void handleLoop(BranchInst *Term);
87 void closeControlFlow(BasicBlock *BB);
90 SIAnnotateControlFlow():
93 bool doInitialization(Module &M) override;
95 bool runOnFunction(Function &F) override;
97 const char *getPassName() const override {
98 return "SI annotate control flow";
101 void getAnalysisUsage(AnalysisUsage &AU) const override {
102 AU.addRequired<DominatorTreeWrapperPass>();
103 AU.addPreserved<DominatorTreeWrapperPass>();
104 FunctionPass::getAnalysisUsage(AU);
109 } // end anonymous namespace
111 char SIAnnotateControlFlow::ID = 0;
113 /// \brief Initialize all the types and constants used in the pass
114 bool SIAnnotateControlFlow::doInitialization(Module &M) {
115 LLVMContext &Context = M.getContext();
117 Void = Type::getVoidTy(Context);
118 Boolean = Type::getInt1Ty(Context);
119 Int64 = Type::getInt64Ty(Context);
120 ReturnStruct = StructType::get(Boolean, Int64, (Type *)nullptr);
122 BoolTrue = ConstantInt::getTrue(Context);
123 BoolFalse = ConstantInt::getFalse(Context);
124 BoolUndef = UndefValue::get(Boolean);
125 Int64Zero = ConstantInt::get(Int64, 0);
127 If = M.getOrInsertFunction(
128 IfIntrinsic, ReturnStruct, Boolean, (Type *)nullptr);
130 Else = M.getOrInsertFunction(
131 ElseIntrinsic, ReturnStruct, Int64, (Type *)nullptr);
133 Break = M.getOrInsertFunction(
134 BreakIntrinsic, Int64, Int64, (Type *)nullptr);
136 IfBreak = M.getOrInsertFunction(
137 IfBreakIntrinsic, Int64, Boolean, Int64, (Type *)nullptr);
139 ElseBreak = M.getOrInsertFunction(
140 ElseBreakIntrinsic, Int64, Int64, Int64, (Type *)nullptr);
142 Loop = M.getOrInsertFunction(
143 LoopIntrinsic, Boolean, Int64, (Type *)nullptr);
145 EndCf = M.getOrInsertFunction(
146 EndCfIntrinsic, Void, Int64, (Type *)nullptr);
151 /// \brief Is BB the last block saved on the stack ?
152 bool SIAnnotateControlFlow::isTopOfStack(BasicBlock *BB) {
153 return !Stack.empty() && Stack.back().first == BB;
156 /// \brief Pop the last saved value from the control flow stack
157 Value *SIAnnotateControlFlow::popSaved() {
158 return Stack.pop_back_val().second;
161 /// \brief Push a BB and saved value to the control flow stack
162 void SIAnnotateControlFlow::push(BasicBlock *BB, Value *Saved) {
163 Stack.push_back(std::make_pair(BB, Saved));
166 /// \brief Can the condition represented by this PHI node treated like
168 bool SIAnnotateControlFlow::isElse(PHINode *Phi) {
169 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) {
173 if (Phi->getIncomingValue(i) != BoolTrue)
177 if (Phi->getIncomingValue(i) != BoolFalse)
185 // \brief Erase "Phi" if it is not used any more
186 void SIAnnotateControlFlow::eraseIfUnused(PHINode *Phi) {
187 if (!Phi->hasNUsesOrMore(1))
188 Phi->eraseFromParent();
191 /// \brief Open a new "If" block
192 void 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));
198 /// \brief Close the last "If" block and open a new "Else" block
199 void 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));
205 /// \brief Recursively handle the condition leading to a loop
206 Value *SIAnnotateControlFlow::handleLoopCondition(Value *Cond, PHINode *Broken) {
207 if (PHINode *Phi = dyn_cast<PHINode>(Cond)) {
208 BasicBlock *Parent = Phi->getParent();
209 PHINode *NewPhi = PHINode::Create(Int64, 0, "", &Parent->front());
212 // Handle all non-constant incoming values first
213 for (unsigned i = 0, e = Phi->getNumIncomingValues(); i != e; ++i) {
214 Value *Incoming = Phi->getIncomingValue(i);
215 BasicBlock *From = Phi->getIncomingBlock(i);
216 if (isa<ConstantInt>(Incoming)) {
217 NewPhi->addIncoming(Broken, From);
221 Phi->setIncomingValue(i, BoolFalse);
222 Value *PhiArg = handleLoopCondition(Incoming, Broken);
223 NewPhi->addIncoming(PhiArg, From);
226 BasicBlock *IDom = DT->getNode(Parent)->getIDom()->getBlock();
228 for (unsigned i = 0, e = Phi->getNumIncomingValues(); i != e; ++i) {
230 Value *Incoming = Phi->getIncomingValue(i);
231 if (Incoming != BoolTrue)
234 BasicBlock *From = Phi->getIncomingBlock(i);
236 CallInst *OldEnd = dyn_cast<CallInst>(Parent->getFirstInsertionPt());
237 if (OldEnd && OldEnd->getCalledFunction() == EndCf) {
238 Value *Args[] = { OldEnd->getArgOperand(0), NewPhi };
239 Ret = CallInst::Create(ElseBreak, Args, "", OldEnd);
243 TerminatorInst *Insert = From->getTerminator();
244 Value *PhiArg = CallInst::Create(Break, Broken, "", Insert);
245 NewPhi->setIncomingValue(i, PhiArg);
250 } else if (Instruction *Inst = dyn_cast<Instruction>(Cond)) {
251 BasicBlock *Parent = Inst->getParent();
252 TerminatorInst *Insert = Parent->getTerminator();
253 Value *Args[] = { Cond, Broken };
254 return CallInst::Create(IfBreak, Args, "", Insert);
257 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 Value *Cond = Term->getCondition();
268 Term->setCondition(BoolTrue);
269 Value *Arg = handleLoopCondition(Cond, Broken);
271 BasicBlock *BB = Term->getParent();
272 for (pred_iterator PI = pred_begin(Target), PE = pred_end(Target);
275 Broken->addIncoming(*PI == BB ? Arg : Int64Zero, *PI);
278 Term->setCondition(CallInst::Create(Loop, Arg, "", Term));
279 push(Term->getSuccessor(0), Arg);
282 /// \brief Close the last opened control flow
283 void SIAnnotateControlFlow::closeControlFlow(BasicBlock *BB) {
284 CallInst::Create(EndCf, popSaved(), "", BB->getFirstInsertionPt());
287 /// \brief Annotate the control flow with intrinsics so the backend can
288 /// recognize if/then/else and loops.
289 bool SIAnnotateControlFlow::runOnFunction(Function &F) {
290 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
292 for (df_iterator<BasicBlock *> I = df_begin(&F.getEntryBlock()),
293 E = df_end(&F.getEntryBlock()); I != E; ++I) {
295 BranchInst *Term = dyn_cast<BranchInst>((*I)->getTerminator());
297 if (!Term || Term->isUnconditional()) {
298 if (isTopOfStack(*I))
299 closeControlFlow(*I);
303 if (I.nodeVisited(Term->getSuccessor(1))) {
304 if (isTopOfStack(*I))
305 closeControlFlow(*I);
310 if (isTopOfStack(*I)) {
311 PHINode *Phi = dyn_cast<PHINode>(Term->getCondition());
312 if (Phi && Phi->getParent() == *I && isElse(Phi)) {
317 closeControlFlow(*I);
322 assert(Stack.empty());
326 /// \brief Create the annotation pass
327 FunctionPass *llvm::createSIAnnotateControlFlowPass() {
328 return new SIAnnotateControlFlow();