46#define DEBUG_TYPE "memprof"
62 "__memprof_version_mismatch_check_v";
65 "__memprof_shadow_memory_dynamic_address";
72STATISTIC(NumInstrumentedReads,
"Number of instrumented reads");
73STATISTIC(NumInstrumentedWrites,
"Number of instrumented writes");
74STATISTIC(NumSkippedStackReads,
"Number of non-instrumented stack reads");
75STATISTIC(NumSkippedStackWrites,
"Number of non-instrumented stack writes");
82 ShadowMapping(
const InstrumentationOptions &Opts) {
83 Scale = Opts.memprof_mapping_scale;
85 : Opts.memprof_mapping_granularity;
86 Mask = ~(Granularity - 1);
99struct InterestingMemoryAccess {
100 Value *Addr =
nullptr;
103 Value *MaybeMask =
nullptr;
109 MemProfiler(
const InstrumentationOptions &Opts,
Module &M)
110 : Opts(Opts), Mapping(Opts) {
111 C = &(
M.getContext());
112 LongSize =
M.getDataLayout().getPointerSizeInBits();
113 IntptrTy = Type::getIntNTy(*C, LongSize);
114 PtrTy = PointerType::getUnqual(*C);
120 std::optional<InterestingMemoryAccess>
121 isInterestingMemoryAccess(Instruction *
I)
const;
123 void instrumentMop(Instruction *
I,
const DataLayout &
DL,
124 InterestingMemoryAccess &
Access);
126 Value *Addr,
bool IsWrite);
127 void instrumentMaskedLoadOrStore(
const DataLayout &
DL,
Value *Mask,
130 void instrumentMemIntrinsic(MemIntrinsic *
MI);
133 bool maybeInsertMemProfInitAtFunctionEntry(
Function &
F);
134 bool insertDynamicShadowAtFunctionEntry(
Function &
F);
137 void initializeCallbacks(
Module &M);
139 const InstrumentationOptions &Opts;
144 ShadowMapping Mapping;
147 FunctionCallee MemProfMemoryAccessCallback[2];
149 FunctionCallee MemProfMemmove, MemProfMemcpy, MemProfMemset;
150 Value *DynamicShadowOffset =
nullptr;
153class ModuleMemProfiler {
155 ModuleMemProfiler(
const InstrumentationOptions &Opts,
Module &M)
156 : Opts(Opts), Mapping(Opts) {
157 TargetTriple =
M.getTargetTriple();
160 bool instrumentModule(
Module &);
163 const InstrumentationOptions &Opts;
165 ShadowMapping Mapping;
166 Function *MemProfCtorFunction =
nullptr;
175 const InstrumentationOptions &Opts =
176 F.getContext().getLibraryOptions().get<InstrumentationOptions>();
177 assert((!Opts.memprof_histogram ||
179 "Memprof with histogram only supports default mapping granularity");
181 MemProfiler Profiler(Opts, M);
182 if (Profiler.instrumentFunction(
F))
192 const InstrumentationOptions &Opts =
193 M.getContext().getLibraryOptions().get<InstrumentationOptions>();
194 ModuleMemProfiler Profiler(Opts, M);
195 if (Profiler.instrumentModule(M))
202 Shadow = IRB.
CreateAnd(Shadow, Mapping.Mask);
203 Shadow = IRB.
CreateLShr(Shadow, Mapping.Scale);
205 assert(DynamicShadowOffset);
206 return IRB.
CreateAdd(Shadow, DynamicShadowOffset);
214 {
MI->getOperand(0),
MI->getOperand(1),
223 MI->eraseFromParent();
226std::optional<InterestingMemoryAccess>
227MemProfiler::isInterestingMemoryAccess(
Instruction *
I)
const {
229 if (DynamicShadowOffset ==
I)
232 InterestingMemoryAccess
Access;
235 if (!Opts.memprof_instrument_reads)
238 Access.AccessTy = LI->getType();
239 Access.Addr = LI->getPointerOperand();
241 if (!Opts.memprof_instrument_writes)
244 Access.AccessTy =
SI->getValueOperand()->getType();
245 Access.Addr =
SI->getPointerOperand();
247 if (!Opts.memprof_instrument_atomics)
250 Access.AccessTy = RMW->getValOperand()->getType();
251 Access.Addr = RMW->getPointerOperand();
253 if (!Opts.memprof_instrument_atomics)
256 Access.AccessTy = XCHG->getCompareOperand()->getType();
257 Access.Addr = XCHG->getPointerOperand();
259 auto *
F = CI->getCalledFunction();
260 if (
F && (
F->getIntrinsicID() == Intrinsic::masked_load ||
261 F->getIntrinsicID() == Intrinsic::masked_store)) {
262 unsigned OpOffset = 0;
263 if (
F->getIntrinsicID() == Intrinsic::masked_store) {
264 if (!Opts.memprof_instrument_writes)
268 Access.AccessTy = CI->getArgOperand(0)->getType();
271 if (!Opts.memprof_instrument_reads)
273 Access.AccessTy = CI->getType();
277 auto *
BasePtr = CI->getOperand(0 + OpOffset);
278 Access.MaybeMask = CI->getOperand(1 + OpOffset);
296 if (
Access.Addr->isSwiftError())
300 auto *Addr =
Access.Addr->stripInBoundsOffsets();
304 if (GV->hasSection()) {
307 auto OF =
I->getModule()->getTargetTriple().getObjectFormat();
314 if (GV->getName().starts_with(
"__llvm") ||
324 Type *AccessTy,
bool IsWrite) {
326 unsigned Num = VTy->getNumElements();
327 auto *
Zero = ConstantInt::get(IntptrTy, 0);
328 for (
unsigned Idx = 0;
Idx < Num; ++
Idx) {
329 Value *InstrumentedAddress =
nullptr;
344 InsertBefore = ThenTerm;
348 InstrumentedAddress =
349 IRB.
CreateGEP(VTy, Addr, {
Zero, ConstantInt::get(IntptrTy, Idx)});
355 InterestingMemoryAccess &
Access) {
357 if (!Opts.memprof_instrument_stack &&
360 ++NumSkippedStackWrites;
362 ++NumSkippedStackReads;
367 NumInstrumentedWrites++;
369 NumInstrumentedReads++;
382void MemProfiler::instrumentAddress(
Instruction *OrigIns,
388 if (Opts.memprof_use_callbacks) {
389 IRB.
CreateCall(MemProfMemoryAccessCallback[IsWrite], AddrLong);
397 Value *ShadowPtr = memToShadow(AddrLong, IRB);
401 if (Opts.memprof_histogram) {
408 Value *Inc = ConstantInt::get(ShadowTy, 1);
409 ShadowValue = IRB.
CreateAdd(ShadowValue, Inc);
417 if (!MemProfFilename)
420 "Unexpected MemProfProfileFilename metadata with empty string");
422 M.getContext(), MemProfFilename->
getString(),
true);
424 M, ProfileNameConst->
getType(),
true,
426 const Triple &TT = M.getTargetTriple();
427 if (TT.supportsCOMDAT()) {
443 const Triple &TT = M.getTargetTriple();
444 if (TT.supportsCOMDAT()) {
446 MemprofHistogramFlag->setComdat(M.getOrInsertComdat(VarName));
454 M.getContext(), Opts.memprof_runtime_default_options,
true);
459 const Triple &TT = M.getTargetTriple();
460 if (TT.supportsCOMDAT()) {
466bool ModuleMemProfiler::instrumentModule(
Module &M) {
470 std::string VersionCheckName =
471 Opts.memprof_guard_against_version_mismatch
474 std::tie(MemProfCtorFunction, std::ignore) =
477 {}, VersionCheckName);
479 const uint64_t Priority = getCtorAndDtorPriority(TargetTriple);
491void MemProfiler::initializeCallbacks(
Module &M) {
494 for (
size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
495 const std::string TypeStr = AccessIsWrite ?
"store" :
"load";
496 const std::string HistPrefix = Opts.memprof_histogram ?
"hist_" :
"";
499 MemProfMemoryAccessCallback[AccessIsWrite] =
M.getOrInsertFunction(
500 (Opts.memprof_memory_access_callback_prefix + HistPrefix + TypeStr)
504 MemProfMemmove =
M.getOrInsertFunction(
505 (Opts.memprof_memory_access_callback_prefix +
"memmove").str(), PtrTy,
506 PtrTy, PtrTy, IntptrTy);
507 MemProfMemcpy =
M.getOrInsertFunction(
508 (Opts.memprof_memory_access_callback_prefix +
"memcpy").str(), PtrTy,
509 PtrTy, PtrTy, IntptrTy);
510 MemProfMemset =
M.getOrInsertFunction(
511 (Opts.memprof_memory_access_callback_prefix +
"memset").str(), PtrTy,
515bool MemProfiler::maybeInsertMemProfInitAtFunctionEntry(
Function &
F) {
523 if (
F.getName().contains(
" load]")) {
533bool MemProfiler::insertDynamicShadowAtFunctionEntry(
Function &
F) {
535 Value *GlobalDynamicAddress =
F.getParent()->getOrInsertGlobal(
539 DynamicShadowOffset = IRB.
CreateLoad(IntptrTy, GlobalDynamicAddress);
543bool MemProfiler::instrumentFunction(
Function &
F) {
546 if (Opts.memprof_debug_func ==
F.getName())
548 if (
F.getName().starts_with(
"__memprof_"))
551 bool FunctionModified =
false;
556 if (maybeInsertMemProfInitAtFunctionEntry(
F))
557 FunctionModified =
true;
561 initializeCallbacks(*
F.getParent());
567 for (
auto &Inst : BB) {
573 if (ToInstrument.
empty()) {
574 LLVM_DEBUG(
dbgs() <<
"MEMPROF done instrumenting: " << FunctionModified
575 <<
" " <<
F <<
"\n");
577 return FunctionModified;
580 FunctionModified |= insertDynamicShadowAtFunctionEntry(
F);
582 int NumInstrumented = 0;
583 for (
auto *Inst : ToInstrument) {
584 if (Opts.memprof_debug_min < 0 || Opts.memprof_debug_max < 0 ||
585 (NumInstrumented >= Opts.memprof_debug_min &&
586 NumInstrumented <= Opts.memprof_debug_max)) {
587 std::optional<InterestingMemoryAccess>
Access =
588 isInterestingMemoryAccess(Inst);
590 instrumentMop(Inst,
F.getDataLayout(), *
Access);
597 if (NumInstrumented > 0)
598 FunctionModified =
true;
600 LLVM_DEBUG(
dbgs() <<
"MEMPROF done instrumenting: " << FunctionModified <<
" "
603 return FunctionModified;
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
Module.h This file contains the declarations for the Module class.
constexpr char MemProfVersionCheckNamePrefix[]
constexpr uint64_t MemProfEmscriptenCtorAndDtorPriority
constexpr char MemProfShadowMemoryDynamicAddress[]
constexpr uint64_t MemProfCtorAndDtorPriority
constexpr int LLVM_MEM_PROFILER_VERSION
constexpr char MemProfInitName[]
constexpr char MemProfFilenameVar[]
constexpr uint64_t DefaultMemGranularity
constexpr uint64_t HistogramGranularity
constexpr char MemProfModuleCtorName[]
void createMemprofDefaultOptionsVar(const InstrumentationOptions &Opts, Module &M)
constexpr char MemProfHistogramFlagVar[]
void createMemprofHistogramFlagVar(const InstrumentationOptions &Opts, Module &M)
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Class for arbitrary precision integers.
A container for analyses that lazily runs them and caches their results.
An instruction that atomically checks whether a specified value is in a memory location,...
an instruction that atomically reads a memory location, combines it with another value,...
static LLVM_ABI Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true, bool ByteString=false)
This method constructs a CDS and initializes it with a text string.
This is an important base class in LLVM.
static LLVM_ABI Constant * getIntegerValue(Type *Ty, const APInt &V)
Return the value for an integer or pointer constant, or a vector thereof, with the given scalar value...
A parsed version of the target data layout string in and methods for querying it.
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
LLVM_ABI void setComdat(Comdat *C)
void setLinkage(LinkageTypes LT)
@ ExternalLinkage
Externally visible function.
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
@ AvailableExternallyLinkage
Available for inspection, not emission.
Value * CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name="")
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
Value * CreatePointerCast(Value *V, Type *DestTy, const Twine &Name="")
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
Value * CreateGEP(Type *Ty, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args={}, const Twine &Name="", MDNode *FPMathTag=nullptr)
Value * CreateIntCast(Value *V, Type *DestTy, bool isSigned, const Twine &Name="")
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Type * getVoidTy()
Fetch the type representing void.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
An instruction for reading from memory.
LLVM_ABI StringRef getString() const
This is the common base class for memset/memcpy/memmove.
LLVM_ABI MemProfilerPass()
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
LLVM_ABI ModuleMemProfilerPass()
A Module instance is used to store all the information related to an LLVM module.
static LLVM_ABI PointerType * get(LLVMContext &C, unsigned AddressSpace)
This constructs an opaque pointer to an object in a numbered address space.
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
Represent a constant reference to a string, i.e.
constexpr bool empty() const
Check if the string is empty.
Triple - Helper class for working with autoconf configuration names.
bool isOSEmscripten() const
Tests whether the OS is Emscripten.
The instances of the Type class are immutable: once they are created, they are never changed.
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
void instrumentAddress(Module &M, IRBuilder<> &IRB, Instruction *OrigIns, Instruction *InsertBefore, Value *Addr, Align Alignment, TypeSize TypeStoreSize, bool IsWrite, Value *SizeArgument, bool UseCalls, bool Recover, int AsanScale, int AsanOffset)
Instrument the memory operand Addr.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
llvm::StringRef getMemprofOptionsSymbolName()
This is an optimization pass for GlobalISel generic memory operations.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI std::string getInstrProfSectionName(InstrProfSectKind IPSK, Triple::ObjectFormatType OF, bool AddSegmentInfo=true)
Return the name of the profile section corresponding to IPSK.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
auto dyn_cast_or_null(const Y &Val)
LLVM_ABI FunctionCallee declareSanitizerInitFunction(Module &M, StringRef InitName, ArrayRef< Type * > InitArgTypes, bool Weak=false)
LLVM_ABI std::pair< Function *, FunctionCallee > createSanitizerCtorAndInitFunctions(Module &M, StringRef CtorName, StringRef InitName, ArrayRef< Type * > InitArgTypes, ArrayRef< Value * > InitArgs, StringRef VersionCheckName=StringRef(), bool Weak=false)
Creates sanitizer constructor function, and calls sanitizer's init function from it.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
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...
LLVM_ABI void appendToCompilerUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.compiler.used list.
StringRef getInstrProfVarPrefix()
Return the prefix of the name of the variables to function as a filter.
LLVM_ABI void createProfileFileNameVar(Module &M, StringRef InstrProfileOutput)
LLVM_ABI void appendToGlobalCtors(Module &M, Function *F, int Priority, Constant *Data=nullptr)
Append F to the list of global ctors of module M with the given Priority.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI Instruction * SplitBlockAndInsertIfThen(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...