1 //===- EntryExitInstrumenter.cpp - Function Entry/Exit Instrumentation ----===//
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 #include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
11 #include "llvm/Analysis/GlobalsModRef.h"
12 #include "llvm/CodeGen/Passes.h"
13 #include "llvm/IR/DebugInfoMetadata.h"
14 #include "llvm/IR/Function.h"
15 #include "llvm/IR/Instructions.h"
16 #include "llvm/IR/Module.h"
17 #include "llvm/IR/Type.h"
18 #include "llvm/Pass.h"
19 #include "llvm/Transforms/Scalar.h"
20 using namespace llvm;
21 
22 static void insertCall(Function &CurFn, StringRef Func,
23                        Instruction *InsertionPt, DebugLoc DL) {
24   Module &M = *InsertionPt->getParent()->getParent()->getParent();
25   LLVMContext &C = InsertionPt->getParent()->getContext();
26 
27   if (Func == "mcount" ||
28       Func == ".mcount" ||
29       Func == "\01__gnu_mcount_nc" ||
30       Func == "\01_mcount" ||
31       Func == "\01mcount" ||
32       Func == "__mcount" ||
33       Func == "_mcount" ||
34       Func == "__cyg_profile_func_enter_bare") {
35     Constant *Fn = M.getOrInsertFunction(Func, Type::getVoidTy(C));
36     CallInst *Call = CallInst::Create(Fn, "", InsertionPt);
37     Call->setDebugLoc(DL);
38     return;
39   }
40 
41   if (Func == "__cyg_profile_func_enter" || Func == "__cyg_profile_func_exit") {
42     Type *ArgTypes[] = {Type::getInt8PtrTy(C), Type::getInt8PtrTy(C)};
43 
44     Constant *Fn = M.getOrInsertFunction(
45         Func, FunctionType::get(Type::getVoidTy(C), ArgTypes, false));
46 
47     Instruction *RetAddr = CallInst::Create(
48         Intrinsic::getDeclaration(&M, Intrinsic::returnaddress),
49         ArrayRef<Value *>(ConstantInt::get(Type::getInt32Ty(C), 0)), "",
50         InsertionPt);
51     RetAddr->setDebugLoc(DL);
52 
53     Value *Args[] = {ConstantExpr::getBitCast(&CurFn, Type::getInt8PtrTy(C)),
54                      RetAddr};
55 
56     CallInst *Call =
57         CallInst::Create(Fn, ArrayRef<Value *>(Args), "", InsertionPt);
58     Call->setDebugLoc(DL);
59     return;
60   }
61 
62   // We only know how to call a fixed set of instrumentation functions, because
63   // they all expect different arguments, etc.
64   report_fatal_error(Twine("Unknown instrumentation function: '") + Func + "'");
65 }
66 
67 static bool runOnFunction(Function &F, bool PostInlining) {
68   StringRef EntryAttr = PostInlining ? "instrument-function-entry-inlined"
69                                      : "instrument-function-entry";
70 
71   StringRef ExitAttr = PostInlining ? "instrument-function-exit-inlined"
72                                     : "instrument-function-exit";
73 
74   StringRef EntryFunc = F.getFnAttribute(EntryAttr).getValueAsString();
75   StringRef ExitFunc = F.getFnAttribute(ExitAttr).getValueAsString();
76 
77   bool Changed = false;
78 
79   // If the attribute is specified, insert instrumentation and then "consume"
80   // the attribute so that it's not inserted again if the pass should happen to
81   // run later for some reason.
82 
83   if (!EntryFunc.empty()) {
84     DebugLoc DL;
85     if (auto SP = F.getSubprogram())
86       DL = DebugLoc::get(SP->getScopeLine(), 0, SP);
87 
88     insertCall(F, EntryFunc, &*F.begin()->getFirstInsertionPt(), DL);
89     Changed = true;
90     F.removeAttribute(AttributeList::FunctionIndex, EntryAttr);
91   }
92 
93   if (!ExitFunc.empty()) {
94     for (BasicBlock &BB : F) {
95       TerminatorInst *T = BB.getTerminator();
96       DebugLoc DL;
97       if (DebugLoc TerminatorDL = T->getDebugLoc())
98         DL = TerminatorDL;
99       else if (auto SP = F.getSubprogram())
100         DL = DebugLoc::get(0, 0, SP);
101 
102       if (isa<ReturnInst>(T)) {
103         insertCall(F, ExitFunc, T, DL);
104         Changed = true;
105       }
106     }
107     F.removeAttribute(AttributeList::FunctionIndex, ExitAttr);
108   }
109 
110   return Changed;
111 }
112 
113 namespace {
114 struct EntryExitInstrumenter : public FunctionPass {
115   static char ID;
116   EntryExitInstrumenter() : FunctionPass(ID) {
117     initializeEntryExitInstrumenterPass(*PassRegistry::getPassRegistry());
118   }
119   void getAnalysisUsage(AnalysisUsage &AU) const override {
120     AU.addPreserved<GlobalsAAWrapperPass>();
121   }
122   bool runOnFunction(Function &F) override { return ::runOnFunction(F, false); }
123 };
124 char EntryExitInstrumenter::ID = 0;
125 
126 struct PostInlineEntryExitInstrumenter : public FunctionPass {
127   static char ID;
128   PostInlineEntryExitInstrumenter() : FunctionPass(ID) {
129     initializePostInlineEntryExitInstrumenterPass(
130         *PassRegistry::getPassRegistry());
131   }
132   void getAnalysisUsage(AnalysisUsage &AU) const override {
133     AU.addPreserved<GlobalsAAWrapperPass>();
134   }
135   bool runOnFunction(Function &F) override { return ::runOnFunction(F, true); }
136 };
137 char PostInlineEntryExitInstrumenter::ID = 0;
138 }
139 
140 INITIALIZE_PASS(
141     EntryExitInstrumenter, "ee-instrument",
142     "Instrument function entry/exit with calls to e.g. mcount() (pre inlining)",
143     false, false)
144 INITIALIZE_PASS(PostInlineEntryExitInstrumenter, "post-inline-ee-instrument",
145                 "Instrument function entry/exit with calls to e.g. mcount() "
146                 "(post inlining)",
147                 false, false)
148 
149 FunctionPass *llvm::createEntryExitInstrumenterPass() {
150   return new EntryExitInstrumenter();
151 }
152 
153 FunctionPass *llvm::createPostInlineEntryExitInstrumenterPass() {
154   return new PostInlineEntryExitInstrumenter();
155 }
156 
157 PreservedAnalyses
158 llvm::EntryExitInstrumenterPass::run(Function &F, FunctionAnalysisManager &AM) {
159   runOnFunction(F, PostInlining);
160   PreservedAnalyses PA;
161   PA.preserveSet<CFGAnalyses>();
162   return PA;
163 }
164