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