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/Function.h"
13 #include "llvm/IR/Instructions.h"
14 #include "llvm/IR/Intrinsics.h"
15 #include "llvm/IR/Module.h"
16 #include "llvm/IR/Type.h"
17 #include "llvm/InitializePasses.h"
18 #include "llvm/Pass.h"
19 #include "llvm/Transforms/Utils.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 == "llvm.arm.gnu.eabi.mcount" ||
30       Func == "\01_mcount" ||
31       Func == "\01mcount" ||
32       Func == "__mcount" ||
33       Func == "_mcount" ||
34       Func == "__cyg_profile_func_enter_bare") {
35     FunctionCallee 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     FunctionCallee 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 = DILocation::get(SP->getContext(), 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       Instruction *T = BB.getTerminator();
96       if (!isa<ReturnInst>(T))
97         continue;
98 
99       // If T is preceded by a musttail call, that's the real terminator.
100       if (CallInst *CI = BB.getTerminatingMustTailCall())
101         T = CI;
102 
103       DebugLoc DL;
104       if (DebugLoc TerminatorDL = T->getDebugLoc())
105         DL = TerminatorDL;
106       else if (auto SP = F.getSubprogram())
107         DL = DILocation::get(SP->getContext(), 0, 0, SP);
108 
109       insertCall(F, ExitFunc, T, DL);
110       Changed = true;
111     }
112     F.removeAttribute(AttributeList::FunctionIndex, ExitAttr);
113   }
114 
115   return Changed;
116 }
117 
118 namespace {
119 struct EntryExitInstrumenter : public FunctionPass {
120   static char ID;
121   EntryExitInstrumenter() : FunctionPass(ID) {
122     initializeEntryExitInstrumenterPass(*PassRegistry::getPassRegistry());
123   }
124   void getAnalysisUsage(AnalysisUsage &AU) const override {
125     AU.addPreserved<GlobalsAAWrapperPass>();
126   }
127   bool runOnFunction(Function &F) override { return ::runOnFunction(F, false); }
128 };
129 char EntryExitInstrumenter::ID = 0;
130 
131 struct PostInlineEntryExitInstrumenter : public FunctionPass {
132   static char ID;
133   PostInlineEntryExitInstrumenter() : FunctionPass(ID) {
134     initializePostInlineEntryExitInstrumenterPass(
135         *PassRegistry::getPassRegistry());
136   }
137   void getAnalysisUsage(AnalysisUsage &AU) const override {
138     AU.addPreserved<GlobalsAAWrapperPass>();
139   }
140   bool runOnFunction(Function &F) override { return ::runOnFunction(F, true); }
141 };
142 char PostInlineEntryExitInstrumenter::ID = 0;
143 }
144 
145 INITIALIZE_PASS(
146     EntryExitInstrumenter, "ee-instrument",
147     "Instrument function entry/exit with calls to e.g. mcount() (pre inlining)",
148     false, false)
149 INITIALIZE_PASS(PostInlineEntryExitInstrumenter, "post-inline-ee-instrument",
150                 "Instrument function entry/exit with calls to e.g. mcount() "
151                 "(post inlining)",
152                 false, false)
153 
154 FunctionPass *llvm::createEntryExitInstrumenterPass() {
155   return new EntryExitInstrumenter();
156 }
157 
158 FunctionPass *llvm::createPostInlineEntryExitInstrumenterPass() {
159   return new PostInlineEntryExitInstrumenter();
160 }
161 
162 PreservedAnalyses
163 llvm::EntryExitInstrumenterPass::run(Function &F, FunctionAnalysisManager &AM) {
164   runOnFunction(F, PostInlining);
165   PreservedAnalyses PA;
166   PA.preserveSet<CFGAnalyses>();
167   return PA;
168 }
169