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 = InstrumentationOptions::Global;
176 assert((!Opts.memprof_histogram ||
178 "Memprof with histogram only supports default mapping granularity");
180 MemProfiler Profiler(Opts, M);
181 if (Profiler.instrumentFunction(
F))
191 ModuleMemProfiler Profiler(InstrumentationOptions::Global, M);
192 if (Profiler.instrumentModule(M))
199 Shadow = IRB.
CreateAnd(Shadow, Mapping.Mask);
200 Shadow = IRB.
CreateLShr(Shadow, Mapping.Scale);
202 assert(DynamicShadowOffset);
203 return IRB.
CreateAdd(Shadow, DynamicShadowOffset);
211 {
MI->getOperand(0),
MI->getOperand(1),
220 MI->eraseFromParent();
223std::optional<InterestingMemoryAccess>
224MemProfiler::isInterestingMemoryAccess(
Instruction *
I)
const {
226 if (DynamicShadowOffset ==
I)
229 InterestingMemoryAccess
Access;
232 if (!Opts.memprof_instrument_reads)
235 Access.AccessTy = LI->getType();
236 Access.Addr = LI->getPointerOperand();
238 if (!Opts.memprof_instrument_writes)
241 Access.AccessTy =
SI->getValueOperand()->getType();
242 Access.Addr =
SI->getPointerOperand();
244 if (!Opts.memprof_instrument_atomics)
247 Access.AccessTy = RMW->getValOperand()->getType();
248 Access.Addr = RMW->getPointerOperand();
250 if (!Opts.memprof_instrument_atomics)
253 Access.AccessTy = XCHG->getCompareOperand()->getType();
254 Access.Addr = XCHG->getPointerOperand();
256 auto *
F = CI->getCalledFunction();
257 if (
F && (
F->getIntrinsicID() == Intrinsic::masked_load ||
258 F->getIntrinsicID() == Intrinsic::masked_store)) {
259 unsigned OpOffset = 0;
260 if (
F->getIntrinsicID() == Intrinsic::masked_store) {
261 if (!Opts.memprof_instrument_writes)
265 Access.AccessTy = CI->getArgOperand(0)->getType();
268 if (!Opts.memprof_instrument_reads)
270 Access.AccessTy = CI->getType();
274 auto *
BasePtr = CI->getOperand(0 + OpOffset);
275 Access.MaybeMask = CI->getOperand(1 + OpOffset);
293 if (
Access.Addr->isSwiftError())
297 auto *Addr =
Access.Addr->stripInBoundsOffsets();
301 if (GV->hasSection()) {
304 auto OF =
I->getModule()->getTargetTriple().getObjectFormat();
311 if (GV->getName().starts_with(
"__llvm") ||
321 Type *AccessTy,
bool IsWrite) {
323 unsigned Num = VTy->getNumElements();
324 auto *
Zero = ConstantInt::get(IntptrTy, 0);
325 for (
unsigned Idx = 0;
Idx < Num; ++
Idx) {
326 Value *InstrumentedAddress =
nullptr;
341 InsertBefore = ThenTerm;
345 InstrumentedAddress =
346 IRB.
CreateGEP(VTy, Addr, {
Zero, ConstantInt::get(IntptrTy, Idx)});
352 InterestingMemoryAccess &
Access) {
354 if (!Opts.memprof_instrument_stack &&
357 ++NumSkippedStackWrites;
359 ++NumSkippedStackReads;
364 NumInstrumentedWrites++;
366 NumInstrumentedReads++;
379void MemProfiler::instrumentAddress(
Instruction *OrigIns,
385 if (Opts.memprof_use_callbacks) {
386 IRB.
CreateCall(MemProfMemoryAccessCallback[IsWrite], AddrLong);
394 Value *ShadowPtr = memToShadow(AddrLong, IRB);
398 if (Opts.memprof_histogram) {
405 Value *Inc = ConstantInt::get(ShadowTy, 1);
406 ShadowValue = IRB.
CreateAdd(ShadowValue, Inc);
414 if (!MemProfFilename)
417 "Unexpected MemProfProfileFilename metadata with empty string");
419 M.getContext(), MemProfFilename->
getString(),
true);
421 M, ProfileNameConst->
getType(),
true,
423 const Triple &TT = M.getTargetTriple();
424 if (TT.supportsCOMDAT()) {
440 const Triple &TT = M.getTargetTriple();
441 if (TT.supportsCOMDAT()) {
443 MemprofHistogramFlag->setComdat(M.getOrInsertComdat(VarName));
451 M.getContext(), Opts.memprof_runtime_default_options,
true);
456 const Triple &TT = M.getTargetTriple();
457 if (TT.supportsCOMDAT()) {
463bool ModuleMemProfiler::instrumentModule(
Module &M) {
467 std::string VersionCheckName =
468 Opts.memprof_guard_against_version_mismatch
471 std::tie(MemProfCtorFunction, std::ignore) =
474 {}, VersionCheckName);
476 const uint64_t Priority = getCtorAndDtorPriority(TargetTriple);
488void MemProfiler::initializeCallbacks(
Module &M) {
491 for (
size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
492 const std::string TypeStr = AccessIsWrite ?
"store" :
"load";
493 const std::string HistPrefix = Opts.memprof_histogram ?
"hist_" :
"";
496 MemProfMemoryAccessCallback[AccessIsWrite] =
M.getOrInsertFunction(
497 (Opts.memprof_memory_access_callback_prefix + HistPrefix + TypeStr)
501 MemProfMemmove =
M.getOrInsertFunction(
502 (Opts.memprof_memory_access_callback_prefix +
"memmove").str(), PtrTy,
503 PtrTy, PtrTy, IntptrTy);
504 MemProfMemcpy =
M.getOrInsertFunction(
505 (Opts.memprof_memory_access_callback_prefix +
"memcpy").str(), PtrTy,
506 PtrTy, PtrTy, IntptrTy);
507 MemProfMemset =
M.getOrInsertFunction(
508 (Opts.memprof_memory_access_callback_prefix +
"memset").str(), PtrTy,
512bool MemProfiler::maybeInsertMemProfInitAtFunctionEntry(
Function &
F) {
520 if (
F.getName().contains(
" load]")) {
530bool MemProfiler::insertDynamicShadowAtFunctionEntry(
Function &
F) {
532 Value *GlobalDynamicAddress =
F.getParent()->getOrInsertGlobal(
536 DynamicShadowOffset = IRB.
CreateLoad(IntptrTy, GlobalDynamicAddress);
540bool MemProfiler::instrumentFunction(
Function &
F) {
543 if (Opts.memprof_debug_func ==
F.getName())
545 if (
F.getName().starts_with(
"__memprof_"))
548 bool FunctionModified =
false;
553 if (maybeInsertMemProfInitAtFunctionEntry(
F))
554 FunctionModified =
true;
558 initializeCallbacks(*
F.getParent());
564 for (
auto &Inst : BB) {
570 if (ToInstrument.
empty()) {
571 LLVM_DEBUG(
dbgs() <<
"MEMPROF done instrumenting: " << FunctionModified
572 <<
" " <<
F <<
"\n");
574 return FunctionModified;
577 FunctionModified |= insertDynamicShadowAtFunctionEntry(
F);
579 int NumInstrumented = 0;
580 for (
auto *Inst : ToInstrument) {
581 if (Opts.memprof_debug_min < 0 || Opts.memprof_debug_max < 0 ||
582 (NumInstrumented >= Opts.memprof_debug_min &&
583 NumInstrumented <= Opts.memprof_debug_max)) {
584 std::optional<InterestingMemoryAccess>
Access =
585 isInterestingMemoryAccess(Inst);
587 instrumentMop(Inst,
F.getDataLayout(), *
Access);
594 if (NumInstrumented > 0)
595 FunctionModified =
true;
597 LLVM_DEBUG(
dbgs() <<
"MEMPROF done instrumenting: " << FunctionModified <<
" "
600 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 ...