LLVM 19.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"
19
20using namespace llvm;
21
22static void insertCall(Function &CurFn, StringRef Func,
23 BasicBlock::iterator 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 Triple TargetTriple(M.getTargetTriple());
36 if (TargetTriple.isOSAIX() && Func == "__mcount") {
37 Type *SizeTy = M.getDataLayout().getIntPtrType(C);
38 Type *SizePtrTy = PointerType::getUnqual(C);
39 GlobalVariable *GV = new GlobalVariable(M, SizeTy, /*isConstant=*/false,
41 ConstantInt::get(SizeTy, 0));
43 M.getOrInsertFunction(Func,
44 FunctionType::get(Type::getVoidTy(C), {SizePtrTy},
45 /*isVarArg=*/false)),
46 {GV}, "", InsertionPt);
47 Call->setDebugLoc(DL);
48 } else {
49 FunctionCallee Fn = M.getOrInsertFunction(Func, Type::getVoidTy(C));
50 CallInst *Call = CallInst::Create(Fn, "", InsertionPt);
51 Call->setDebugLoc(DL);
52 }
53 return;
54 }
55
56 if (Func == "__cyg_profile_func_enter" || Func == "__cyg_profile_func_exit") {
57 Type *ArgTypes[] = {PointerType::getUnqual(C), PointerType::getUnqual(C)};
58
59 FunctionCallee Fn = M.getOrInsertFunction(
60 Func, FunctionType::get(Type::getVoidTy(C), ArgTypes, false));
61
63 Intrinsic::getDeclaration(&M, Intrinsic::returnaddress),
64 ArrayRef<Value *>(ConstantInt::get(Type::getInt32Ty(C), 0)), "",
65 InsertionPt);
66 RetAddr->setDebugLoc(DL);
67
68 Value *Args[] = {&CurFn, RetAddr};
69 CallInst *Call =
70 CallInst::Create(Fn, ArrayRef<Value *>(Args), "", InsertionPt);
71 Call->setDebugLoc(DL);
72 return;
73 }
74
75 // We only know how to call a fixed set of instrumentation functions, because
76 // they all expect different arguments, etc.
77 report_fatal_error(Twine("Unknown instrumentation function: '") + Func + "'");
78}
79
80static bool runOnFunction(Function &F, bool PostInlining) {
81 // The asm in a naked function may reasonably expect the argument registers
82 // and the return address register (if present) to be live. An inserted
83 // function call will clobber these registers. Simply skip naked functions for
84 // all targets.
85 if (F.hasFnAttribute(Attribute::Naked))
86 return false;
87
88 StringRef EntryAttr = PostInlining ? "instrument-function-entry-inlined"
89 : "instrument-function-entry";
90
91 StringRef ExitAttr = PostInlining ? "instrument-function-exit-inlined"
92 : "instrument-function-exit";
93
94 StringRef EntryFunc = F.getFnAttribute(EntryAttr).getValueAsString();
95 StringRef ExitFunc = F.getFnAttribute(ExitAttr).getValueAsString();
96
97 bool Changed = false;
98
99 // If the attribute is specified, insert instrumentation and then "consume"
100 // the attribute so that it's not inserted again if the pass should happen to
101 // run later for some reason.
102
103 if (!EntryFunc.empty()) {
104 DebugLoc DL;
105 if (auto SP = F.getSubprogram())
106 DL = DILocation::get(SP->getContext(), SP->getScopeLine(), 0, SP);
107
108 insertCall(F, EntryFunc, F.begin()->getFirstInsertionPt(), DL);
109 Changed = true;
110 F.removeFnAttr(EntryAttr);
111 }
112
113 if (!ExitFunc.empty()) {
114 for (BasicBlock &BB : F) {
115 Instruction *T = BB.getTerminator();
116 if (!isa<ReturnInst>(T))
117 continue;
118
119 // If T is preceded by a musttail call, that's the real terminator.
120 if (CallInst *CI = BB.getTerminatingMustTailCall())
121 T = CI;
122
123 DebugLoc DL;
124 if (DebugLoc TerminatorDL = T->getDebugLoc())
125 DL = TerminatorDL;
126 else if (auto SP = F.getSubprogram())
127 DL = DILocation::get(SP->getContext(), 0, 0, SP);
128
129 insertCall(F, ExitFunc, T->getIterator(), DL);
130 Changed = true;
131 }
132 F.removeFnAttr(ExitAttr);
133 }
134
135 return Changed;
136}
137
143 return PA;
144}
145
147 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
149 ->printPipeline(OS, MapClassName2PassName);
150 OS << '<';
151 if (PostInlining)
152 OS << "post-inline";
153 OS << '>';
154}
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
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.
#define F(x, y, z)
Definition: MD5.cpp:55
Module.h This file contains the declarations for the Module class.
raw_pwrite_stream & OS
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:321
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
LLVM Basic Block Representation.
Definition: BasicBlock.h:60
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:165
Represents analyses that only rely on functions' control flow.
Definition: Analysis.h:70
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr, BasicBlock::iterator InsertBefore)
A debug info location.
Definition: DebugLoc.h:33
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
Definition: DerivedTypes.h:168
@ InternalLinkage
Rename collisions when linking (static functions).
Definition: GlobalValue.h:59
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
Definition: Instruction.h:451
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:109
void preserveSet()
Mark an analysis set as preserved.
Definition: Analysis.h:144
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:134
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
bool isOSAIX() const
Tests whether the OS is AIX.
Definition: Triple.h:694
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
static Type * getVoidTy(LLVMContext &C)
static IntegerType * getInt32Ty(LLVMContext &C)
LLVM Value Representation.
Definition: Value.h:74
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:52
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=std::nullopt)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Definition: Function.cpp:1469
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:156
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:74