LLVM 24.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,
48 /*isVarArg=*/false)),
49 {GV}, "", InsertionPt);
50 Call->setDebugLoc(DL);
51 } else if ((TargetTriple.isRISCV() || TargetTriple.isAArch64() ||
52 TargetTriple.isLoongArch()) &&
53 Func != "__cyg_profile_func_enter_bare") {
54 // On RISC-V, AArch64, and LoongArch, the `_mcount` function takes
55 // `__builtin_return_address(0)` as an argument since
56 // `__builtin_return_address(1)` is not available on these platforms.
57 auto ProgASPtr =
58 PointerType::get(C, M.getDataLayout().getProgramAddressSpace());
60 Intrinsic::getOrInsertDeclaration(&M, Intrinsic::returnaddress,
61 {ProgASPtr}),
62 ConstantInt::get(Type::getInt32Ty(C), 0), "", InsertionPt);
63 RetAddr->setDebugLoc(DL);
64
65 FunctionCallee Fn = M.getOrInsertFunction(
67 false));
68 CallInst *Call = CallInst::Create(Fn, RetAddr, "", InsertionPt);
69 Call->setDebugLoc(DL);
70 } else if (TargetTriple.isSystemZ()) {
71 // skip insertion for `mcount` on SystemZ. This will be handled later in
72 // `emitPrologue`. Add custom attribute to denote this.
73 CurFn.addFnAttr(
74 llvm::Attribute::get(C, "systemz-instrument-function-entry", Func));
75 } else {
76 FunctionCallee Fn = M.getOrInsertFunction(Func, Type::getVoidTy(C));
77 CallInst *Call = CallInst::Create(Fn, "", InsertionPt);
78 Call->setDebugLoc(DL);
79 }
80 return;
81 }
82
83 if (Func == "__cyg_profile_func_enter" || Func == "__cyg_profile_func_exit") {
84 auto ProgASPtr =
85 PointerType::get(C, M.getDataLayout().getProgramAddressSpace());
86 Type *ArgTypes[] = {ProgASPtr, ProgASPtr};
87
88 FunctionCallee Fn = M.getOrInsertFunction(
89 Func, FunctionType::get(Type::getVoidTy(C), ArgTypes, false));
90
92 Intrinsic::getOrInsertDeclaration(&M, Intrinsic::returnaddress,
93 {ProgASPtr}),
94 ArrayRef<Value *>(ConstantInt::get(Type::getInt32Ty(C), 0)), "",
95 InsertionPt);
96 RetAddr->setDebugLoc(DL);
97
98 Value *Args[] = {&CurFn, RetAddr};
99 CallInst *Call =
100 CallInst::Create(Fn, ArrayRef<Value *>(Args), "", InsertionPt);
101 Call->setDebugLoc(DL);
102 return;
103 }
104
105 // We only know how to call a fixed set of instrumentation functions, because
106 // they all expect different arguments, etc.
107 C.emitError("unknown instrumentation function '" + Func + "'");
108}
109
110static bool runOnFunction(Function &F, bool PostInlining) {
111 // The asm in a naked function may reasonably expect the argument registers
112 // and the return address register (if present) to be live. An inserted
113 // function call will clobber these registers. Simply skip naked functions for
114 // all targets.
115 if (F.hasFnAttribute(Attribute::Naked))
116 return false;
117
118 // available_externally functions may not have definitions external to the
119 // module (e.g. gnu::always_inline). Instrumenting them might lead to linker
120 // errors if they are optimized out. Skip them like GCC.
121 if (F.hasAvailableExternallyLinkage())
122 return false;
123
124 StringRef EntryAttr = PostInlining ? "instrument-function-entry-inlined"
125 : "instrument-function-entry";
126
127 StringRef ExitAttr = PostInlining ? "instrument-function-exit-inlined"
128 : "instrument-function-exit";
129
130 StringRef EntryFunc = F.getFnAttribute(EntryAttr).getValueAsString();
131 StringRef ExitFunc = F.getFnAttribute(ExitAttr).getValueAsString();
132
133 bool Changed = false;
134
135 // If the attribute is specified, insert instrumentation and then "consume"
136 // the attribute so that it's not inserted again if the pass should happen to
137 // run later for some reason.
138
139 if (!EntryFunc.empty()) {
140 DebugLoc DL;
141 if (auto SP = F.getSubprogram())
142 DL = DILocation::get(SP->getContext(), SP->getScopeLine(), 0, SP);
143
144 insertCall(F, EntryFunc, F.begin()->getFirstInsertionPt(), DL);
145 Changed = true;
146 F.removeFnAttr(EntryAttr);
147 }
148
149 if (!ExitFunc.empty()) {
150 for (BasicBlock &BB : F) {
151 Instruction *T = BB.getTerminator();
152 if (!isa<ReturnInst>(T))
153 continue;
154
155 // If T is preceded by a musttail call, that's the real terminator.
156 if (CallInst *CI = BB.getTerminatingMustTailCall())
157 T = CI;
158
159 DebugLoc DL;
160 if (DebugLoc TerminatorDL = T->getDebugLoc())
161 DL = TerminatorDL;
162 else if (auto SP = F.getSubprogram())
163 DL = DILocation::get(SP->getContext(), 0, 0, SP);
164
165 insertCall(F, ExitFunc, T->getIterator(), DL);
166 Changed = true;
167 }
168 F.removeFnAttr(ExitAttr);
169 }
170
171 return Changed;
172}
173
174namespace {
175struct PostInlineEntryExitInstrumenter : public FunctionPass {
176 static char ID;
177 PostInlineEntryExitInstrumenter() : FunctionPass(ID) {
180 }
181 void getAnalysisUsage(AnalysisUsage &AU) const override {
182 AU.addPreserved<GlobalsAAWrapperPass>();
183 AU.setPreservesCFG();
184 }
185 bool runOnFunction(Function &F) override { return ::runOnFunction(F, true); }
186};
187char PostInlineEntryExitInstrumenter::ID = 0;
188}
189
191 PostInlineEntryExitInstrumenter, "post-inline-ee-instrument",
192 "Instrument function entry/exit with calls to e.g. mcount() "
193 "(post inlining)",
194 false, false)
197 PostInlineEntryExitInstrumenter, "post-inline-ee-instrument",
198 "Instrument function entry/exit with calls to e.g. mcount() "
199 "(post inlining)",
201
203 return new PostInlineEntryExitInstrumenter();
204}
205
214
216 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
217 static_cast<PassInfoMixin<llvm::EntryExitInstrumenterPass> *>(this)
218 ->printPipeline(OS, MapClassName2PassName);
219 OS << '<';
220 if (PostInlining)
221 OS << "post-inline";
222 OS << '>';
223}
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static bool runOnFunction(Function &F, bool PostInlining)
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:54
#define T
#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
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:280
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
static LLVM_ABI Attribute get(LLVMContext &Context, AttrKind Kind, uint64_t Val=0)
Return a uniquified Attribute object.
LLVM Basic Block Representation.
Definition BasicBlock.h:61
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:169
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:126
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:277
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
void addFnAttr(Attribute::AttrKind Kind)
Add function attributes to this function.
Definition Function.cpp:641
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1588
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
static LLVM_ABI PointerType * get(LLVMContext &C, unsigned AddressSpace)
This constructs an opaque pointer to an object in a numbered address space.
Definition Type.cpp:882
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
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
bool isRISCV() const
Tests whether the target is RISC-V (32- and 64-bit).
Definition Triple.h:1190
bool isOSAIX() const
Tests whether the OS is AIX.
Definition Triple.h:859
bool isAArch64() const
Tests whether the target is AArch64 (little and big endian).
Definition Triple.h:1105
bool isSystemZ() const
Tests whether the target is SystemZ.
Definition Triple.h:1204
bool isLoongArch() const
Tests whether the target is LoongArch (32- and 64-bit).
Definition Triple.h:1131
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:294
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:267
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
CallInst * Call
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI FunctionPass * createPostInlineEntryExitInstrumenterPass()
LLVM_ABI void initializePostInlineEntryExitInstrumenterPass(PassRegistry &)
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
ArrayRef(const T &OneElt) -> ArrayRef< T >
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)