LLVM 22.0.0git
EntryExitInstrumenter.cpp
Go to the documentation of this file.
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
12#include "llvm/IR/Dominators.h"
13#include "llvm/IR/Function.h"
15#include "llvm/IR/Intrinsics.h"
16#include "llvm/IR/Module.h"
17#include "llvm/IR/Type.h"
20#include "llvm/Pass.h"
22
23using namespace llvm;
24
25static void insertCall(Function &CurFn, StringRef Func,
26 BasicBlock::iterator 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 = PointerType::getUnqual(C);
42 GlobalVariable *GV = new GlobalVariable(M, SizeTy, /*isConstant=*/false,
44 ConstantInt::get(SizeTy, 0));
46 M.getOrInsertFunction(Func,
47 FunctionType::get(Type::getVoidTy(C), {SizePtrTy},
48 /*isVarArg=*/false)),
49 {GV}, "", InsertionPt);
50 Call->setDebugLoc(DL);
51 } else if (TargetTriple.isRISCV() || TargetTriple.isAArch64() ||
52 TargetTriple.isLoongArch()) {
53 // On RISC-V, AArch64, and LoongArch, the `_mcount` function takes
54 // `__builtin_return_address(0)` as an argument since
55 // `__builtin_return_address(1)` is not available on these platforms.
57 Intrinsic::getOrInsertDeclaration(&M, Intrinsic::returnaddress),
58 ConstantInt::get(Type::getInt32Ty(C), 0), "", InsertionPt);
59 RetAddr->setDebugLoc(DL);
60
61 FunctionCallee Fn = M.getOrInsertFunction(
62 Func, FunctionType::get(Type::getVoidTy(C), PointerType::getUnqual(C),
63 false));
64 CallInst *Call = CallInst::Create(Fn, RetAddr, "", InsertionPt);
65 Call->setDebugLoc(DL);
66 } else if (TargetTriple.isSystemZ()) {
67 // skip insertion for `mcount` on SystemZ. This will be handled later in
68 // `emitPrologue`. Add custom attribute to denote this.
69 CurFn.addFnAttr(
70 llvm::Attribute::get(C, "systemz-instrument-function-entry", Func));
71 } else {
72 FunctionCallee Fn = M.getOrInsertFunction(Func, Type::getVoidTy(C));
73 CallInst *Call = CallInst::Create(Fn, "", InsertionPt);
74 Call->setDebugLoc(DL);
75 }
76 return;
77 }
78
79 if (Func == "__cyg_profile_func_enter" || Func == "__cyg_profile_func_exit") {
80 Type *ArgTypes[] = {PointerType::getUnqual(C), PointerType::getUnqual(C)};
81
82 FunctionCallee Fn = M.getOrInsertFunction(
83 Func, FunctionType::get(Type::getVoidTy(C), ArgTypes, false));
84
86 Intrinsic::getOrInsertDeclaration(&M, Intrinsic::returnaddress),
87 ArrayRef<Value *>(ConstantInt::get(Type::getInt32Ty(C), 0)), "",
88 InsertionPt);
89 RetAddr->setDebugLoc(DL);
90
91 Value *Args[] = {&CurFn, RetAddr};
92 CallInst *Call =
93 CallInst::Create(Fn, ArrayRef<Value *>(Args), "", InsertionPt);
94 Call->setDebugLoc(DL);
95 return;
96 }
97
98 // We only know how to call a fixed set of instrumentation functions, because
99 // they all expect different arguments, etc.
100 report_fatal_error(Twine("Unknown instrumentation function: '") + Func + "'");
101}
102
103static bool runOnFunction(Function &F, bool PostInlining) {
104 // The asm in a naked function may reasonably expect the argument registers
105 // and the return address register (if present) to be live. An inserted
106 // function call will clobber these registers. Simply skip naked functions for
107 // all targets.
108 if (F.hasFnAttribute(Attribute::Naked))
109 return false;
110
111 // available_externally functions may not have definitions external to the
112 // module (e.g. gnu::always_inline). Instrumenting them might lead to linker
113 // errors if they are optimized out. Skip them like GCC.
114 if (F.hasAvailableExternallyLinkage())
115 return false;
116
117 StringRef EntryAttr = PostInlining ? "instrument-function-entry-inlined"
118 : "instrument-function-entry";
119
120 StringRef ExitAttr = PostInlining ? "instrument-function-exit-inlined"
121 : "instrument-function-exit";
122
123 StringRef EntryFunc = F.getFnAttribute(EntryAttr).getValueAsString();
124 StringRef ExitFunc = F.getFnAttribute(ExitAttr).getValueAsString();
125
126 bool Changed = false;
127
128 // If the attribute is specified, insert instrumentation and then "consume"
129 // the attribute so that it's not inserted again if the pass should happen to
130 // run later for some reason.
131
132 if (!EntryFunc.empty()) {
133 DebugLoc DL;
134 if (auto SP = F.getSubprogram())
135 DL = DILocation::get(SP->getContext(), SP->getScopeLine(), 0, SP);
136
137 insertCall(F, EntryFunc, F.begin()->getFirstInsertionPt(), DL);
138 Changed = true;
139 F.removeFnAttr(EntryAttr);
140 }
141
142 if (!ExitFunc.empty()) {
143 for (BasicBlock &BB : F) {
144 Instruction *T = BB.getTerminator();
145 if (!isa<ReturnInst>(T))
146 continue;
147
148 // If T is preceded by a musttail call, that's the real terminator.
149 if (CallInst *CI = BB.getTerminatingMustTailCall())
150 T = CI;
151
152 DebugLoc DL;
153 if (DebugLoc TerminatorDL = T->getDebugLoc())
154 DL = TerminatorDL;
155 else if (auto SP = F.getSubprogram())
156 DL = DILocation::get(SP->getContext(), 0, 0, SP);
157
158 insertCall(F, ExitFunc, T->getIterator(), DL);
159 Changed = true;
160 }
161 F.removeFnAttr(ExitAttr);
162 }
163
164 return Changed;
165}
166
167namespace {
168struct PostInlineEntryExitInstrumenter : public FunctionPass {
169 static char ID;
170 PostInlineEntryExitInstrumenter() : FunctionPass(ID) {
173 }
174 void getAnalysisUsage(AnalysisUsage &AU) const override {
177 }
178 bool runOnFunction(Function &F) override { return ::runOnFunction(F, true); }
179};
180char PostInlineEntryExitInstrumenter::ID = 0;
181}
182
184 PostInlineEntryExitInstrumenter, "post-inline-ee-instrument",
185 "Instrument function entry/exit with calls to e.g. mcount() "
186 "(post inlining)",
187 false, false)
190 PostInlineEntryExitInstrumenter, "post-inline-ee-instrument",
191 "Instrument function entry/exit with calls to e.g. mcount() "
192 "(post inlining)",
194
196 return new PostInlineEntryExitInstrumenter();
197}
198
202 return PreservedAnalyses::all();
205 return PA;
206}
207
209 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
211 ->printPipeline(OS, MapClassName2PassName);
212 OS << '<';
213 if (PostInlining)
214 OS << "post-inline";
215 OS << '>';
216}
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
always inline
Performs the initial survey of the specified function
post inline ee instrument
static bool runOnFunction(Function &F, bool PostInlining)
post inline ee Instrument function entry exit with calls to e g mcount() " "(post inlining)"
static void insertCall(Function &CurFn, StringRef Func, BasicBlock::iterator InsertionPt, DebugLoc DL)
This is the interface for a simple mod/ref and alias analysis over globals.
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition: MD5.cpp:55
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:39
raw_pwrite_stream & OS
INLINE void g(uint32_t *state, size_t a, size_t b, size_t c, size_t d, uint32_t x, uint32_t y)
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:255
Represent the analysis usage information of a pass.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
static LLVM_ABI Attribute get(LLVMContext &Context, AttrKind Kind, uint64_t Val=0)
Return a uniquified Attribute object.
Definition: Attributes.cpp:95
LLVM Basic Block Representation.
Definition: BasicBlock.h:62
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:170
Represents analyses that only rely on functions' control flow.
Definition: Analysis.h:73
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
A debug info location.
Definition: DebugLoc.h:124
Legacy analysis pass which computes a DominatorTree.
Definition: Dominators.h:322
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
Definition: DerivedTypes.h:170
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:314
virtual bool runOnFunction(Function &F)=0
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
void addFnAttr(Attribute::AttrKind Kind)
Add function attributes to this function.
Definition: Function.cpp:637
@ InternalLinkage
Rename collisions when linking (static functions).
Definition: GlobalValue.h:60
Legacy wrapper pass to provide the GlobalsAAResult object.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
Definition: Instruction.h:510
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:68
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:67
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition: Pass.cpp:112
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition: Analysis.h:151
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:55
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:151
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:47
bool isRISCV() const
Tests whether the target is RISC-V (32- and 64-bit).
Definition: Triple.h:1080
bool isOSAIX() const
Tests whether the OS is AIX.
Definition: Triple.h:757
bool isAArch64() const
Tests whether the target is AArch64 (little and big endian).
Definition: Triple.h:995
bool isSystemZ() const
Tests whether the target is SystemZ.
Definition: Triple.h:1094
bool isLoongArch() const
Tests whether the target is LoongArch (32- and 64-bit).
Definition: Triple.h:1019
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
LLVM Value Representation.
Definition: Value.h:75
An efficient, type-erasing, non-owning reference to a callable.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:53
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > Tys={})
Look up the Function declaration of the intrinsic id in the Module M.
Definition: Intrinsics.cpp:751
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
LLVM_ABI FunctionPass * createPostInlineEntryExitInstrumenterPass()
LLVM_ABI void initializePostInlineEntryExitInstrumenterPass(PassRegistry &)
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition: Error.cpp:167
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
A CRTP mix-in to automatically provide informational APIs needed for passes.
Definition: PassManager.h:70