xref: /freebsd/contrib/llvm-project/llvm/lib/Transforms/Utils/EntryExitInstrumenter.cpp (revision 2008043f386721d58158e37e0d7e50df8095942d)
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/ADT/Triple.h"
11 #include "llvm/Analysis/GlobalsModRef.h"
12 #include "llvm/IR/DebugInfoMetadata.h"
13 #include "llvm/IR/Dominators.h"
14 #include "llvm/IR/Function.h"
15 #include "llvm/IR/Instructions.h"
16 #include "llvm/IR/Intrinsics.h"
17 #include "llvm/IR/Module.h"
18 #include "llvm/IR/Type.h"
19 #include "llvm/InitializePasses.h"
20 #include "llvm/Pass.h"
21 #include "llvm/Transforms/Utils.h"
22 
23 using namespace llvm;
24 
25 static void insertCall(Function &CurFn, StringRef Func,
26                        Instruction *InsertionPt, DebugLoc DL) {
27   Module &M = *InsertionPt->getParent()->getParent()->getParent();
28   LLVMContext &C = InsertionPt->getParent()->getContext();
29 
30   if (Func == "mcount" ||
31       Func == ".mcount" ||
32       Func == "llvm.arm.gnu.eabi.mcount" ||
33       Func == "\01_mcount" ||
34       Func == "\01mcount" ||
35       Func == "__mcount" ||
36       Func == "_mcount" ||
37       Func == "__cyg_profile_func_enter_bare") {
38     Triple TargetTriple(M.getTargetTriple());
39     if (TargetTriple.isOSAIX() && Func == "__mcount") {
40       Type *SizeTy = M.getDataLayout().getIntPtrType(C);
41       Type *SizePtrTy = SizeTy->getPointerTo();
42       GlobalVariable *GV = new GlobalVariable(M, SizeTy, /*isConstant=*/false,
43                                               GlobalValue::InternalLinkage,
44                                               ConstantInt::get(SizeTy, 0));
45       CallInst *Call = CallInst::Create(
46           M.getOrInsertFunction(Func,
47                                 FunctionType::get(Type::getVoidTy(C), {SizePtrTy},
48                                                   /*isVarArg=*/false)),
49           {GV}, "", InsertionPt);
50       Call->setDebugLoc(DL);
51     } else {
52       FunctionCallee Fn = M.getOrInsertFunction(Func, Type::getVoidTy(C));
53       CallInst *Call = CallInst::Create(Fn, "", InsertionPt);
54       Call->setDebugLoc(DL);
55     }
56     return;
57   }
58 
59   if (Func == "__cyg_profile_func_enter" || Func == "__cyg_profile_func_exit") {
60     Type *ArgTypes[] = {Type::getInt8PtrTy(C), Type::getInt8PtrTy(C)};
61 
62     FunctionCallee Fn = M.getOrInsertFunction(
63         Func, FunctionType::get(Type::getVoidTy(C), ArgTypes, false));
64 
65     Instruction *RetAddr = CallInst::Create(
66         Intrinsic::getDeclaration(&M, Intrinsic::returnaddress),
67         ArrayRef<Value *>(ConstantInt::get(Type::getInt32Ty(C), 0)), "",
68         InsertionPt);
69     RetAddr->setDebugLoc(DL);
70 
71     Value *Args[] = {ConstantExpr::getBitCast(&CurFn, Type::getInt8PtrTy(C)),
72                      RetAddr};
73 
74     CallInst *Call =
75         CallInst::Create(Fn, ArrayRef<Value *>(Args), "", InsertionPt);
76     Call->setDebugLoc(DL);
77     return;
78   }
79 
80   // We only know how to call a fixed set of instrumentation functions, because
81   // they all expect different arguments, etc.
82   report_fatal_error(Twine("Unknown instrumentation function: '") + Func + "'");
83 }
84 
85 static bool runOnFunction(Function &F, bool PostInlining) {
86   StringRef EntryAttr = PostInlining ? "instrument-function-entry-inlined"
87                                      : "instrument-function-entry";
88 
89   StringRef ExitAttr = PostInlining ? "instrument-function-exit-inlined"
90                                     : "instrument-function-exit";
91 
92   StringRef EntryFunc = F.getFnAttribute(EntryAttr).getValueAsString();
93   StringRef ExitFunc = F.getFnAttribute(ExitAttr).getValueAsString();
94 
95   bool Changed = false;
96 
97   // If the attribute is specified, insert instrumentation and then "consume"
98   // the attribute so that it's not inserted again if the pass should happen to
99   // run later for some reason.
100 
101   if (!EntryFunc.empty()) {
102     DebugLoc DL;
103     if (auto SP = F.getSubprogram())
104       DL = DILocation::get(SP->getContext(), SP->getScopeLine(), 0, SP);
105 
106     insertCall(F, EntryFunc, &*F.begin()->getFirstInsertionPt(), DL);
107     Changed = true;
108     F.removeFnAttr(EntryAttr);
109   }
110 
111   if (!ExitFunc.empty()) {
112     for (BasicBlock &BB : F) {
113       Instruction *T = BB.getTerminator();
114       if (!isa<ReturnInst>(T))
115         continue;
116 
117       // If T is preceded by a musttail call, that's the real terminator.
118       if (CallInst *CI = BB.getTerminatingMustTailCall())
119         T = CI;
120 
121       DebugLoc DL;
122       if (DebugLoc TerminatorDL = T->getDebugLoc())
123         DL = TerminatorDL;
124       else if (auto SP = F.getSubprogram())
125         DL = DILocation::get(SP->getContext(), 0, 0, SP);
126 
127       insertCall(F, ExitFunc, T, DL);
128       Changed = true;
129     }
130     F.removeFnAttr(ExitAttr);
131   }
132 
133   return Changed;
134 }
135 
136 PreservedAnalyses
137 llvm::EntryExitInstrumenterPass::run(Function &F, FunctionAnalysisManager &AM) {
138   runOnFunction(F, PostInlining);
139   PreservedAnalyses PA;
140   PA.preserveSet<CFGAnalyses>();
141   return PA;
142 }
143 
144 void llvm::EntryExitInstrumenterPass::printPipeline(
145     raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
146   static_cast<PassInfoMixin<llvm::EntryExitInstrumenterPass> *>(this)
147       ->printPipeline(OS, MapClassName2PassName);
148   OS << "<";
149   if (PostInlining)
150     OS << "post-inline";
151   OS << ">";
152 }
153