LLVM 19.0.0git
MemoryTaggingSupport.cpp
Go to the documentation of this file.
1//== MemoryTaggingSupport.cpp - helpers for memory tagging implementations ===//
2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
3// See https://llvm.org/LICENSE.txt for license information.
4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
5//
6//===----------------------------------------------------------------------===//
7//
8// This file declares common infrastructure for HWAddressSanitizer and
9// Aarch64StackTagging.
10//
11//===----------------------------------------------------------------------===//
12
14
15#include "llvm/ADT/STLExtras.h"
16#include "llvm/Analysis/CFG.h"
21#include "llvm/IR/BasicBlock.h"
22#include "llvm/IR/IRBuilder.h"
26
27namespace llvm {
28namespace memtag {
29namespace {
30bool maybeReachableFromEachOther(const SmallVectorImpl<IntrinsicInst *> &Insts,
31 const DominatorTree *DT, const LoopInfo *LI,
32 size_t MaxLifetimes) {
33 // If we have too many lifetime ends, give up, as the algorithm below is N^2.
34 if (Insts.size() > MaxLifetimes)
35 return true;
36 for (size_t I = 0; I < Insts.size(); ++I) {
37 for (size_t J = 0; J < Insts.size(); ++J) {
38 if (I == J)
39 continue;
40 if (isPotentiallyReachable(Insts[I], Insts[J], nullptr, DT, LI))
41 return true;
42 }
43 }
44 return false;
45}
46} // namespace
47
49 const LoopInfo &LI, const Instruction *Start,
52 llvm::function_ref<void(Instruction *)> Callback) {
53 if (Ends.size() == 1 && PDT.dominates(Ends[0], Start)) {
54 Callback(Ends[0]);
55 return true;
56 }
58 for (auto *End : Ends) {
59 EndBlocks.insert(End->getParent());
60 }
61 SmallVector<Instruction *, 8> ReachableRetVec;
62 unsigned NumCoveredExits = 0;
63 for (auto *RI : RetVec) {
64 if (!isPotentiallyReachable(Start, RI, nullptr, &DT, &LI))
65 continue;
66 ReachableRetVec.push_back(RI);
67 // If there is an end in the same basic block as the return, we know for
68 // sure that the return is covered. Otherwise, we can check whether there
69 // is a way to reach the RI from the start of the lifetime without passing
70 // through an end.
71 if (EndBlocks.contains(RI->getParent()) ||
72 !isPotentiallyReachable(Start, RI, &EndBlocks, &DT, &LI)) {
73 ++NumCoveredExits;
74 }
75 }
76 if (NumCoveredExits == ReachableRetVec.size()) {
77 for_each(Ends, Callback);
78 } else {
79 // If there's a mix of covered and non-covered exits, just put the untag
80 // on exits, so we avoid the redundancy of untagging twice.
81 for_each(ReachableRetVec, Callback);
82 // We may have inserted untag outside of the lifetime interval.
83 // Signal the caller to remove the lifetime end call for this alloca.
84 return false;
85 }
86 return true;
87}
88
90 const SmallVectorImpl<IntrinsicInst *> &LifetimeEnd,
91 const DominatorTree *DT, const LoopInfo *LI,
92 size_t MaxLifetimes) {
93 // An alloca that has exactly one start and end in every possible execution.
94 // If it has multiple ends, they have to be unreachable from each other, so
95 // at most one of them is actually used for each execution of the function.
96 return LifetimeStart.size() == 1 &&
97 (LifetimeEnd.size() == 1 ||
98 (LifetimeEnd.size() > 0 &&
99 !maybeReachableFromEachOther(LifetimeEnd, DT, LI, MaxLifetimes)));
100}
101
103 if (isa<ReturnInst>(Inst)) {
105 return CI;
106 return &Inst;
107 }
108 if (isa<ResumeInst, CleanupReturnInst>(Inst)) {
109 return &Inst;
110 }
111 return nullptr;
112}
113
115 // Visit non-intrinsic debug-info records attached to Inst.
117 auto AddIfInteresting = [&](Value *V) {
118 if (auto *AI = dyn_cast_or_null<AllocaInst>(V)) {
119 if (!isInterestingAlloca(*AI))
120 return;
121 AllocaInfo &AInfo = Info.AllocasToInstrument[AI];
122 auto &DVRVec = AInfo.DbgVariableRecords;
123 if (DVRVec.empty() || DVRVec.back() != &DVR)
124 DVRVec.push_back(&DVR);
125 }
126 };
127
128 for_each(DVR.location_ops(), AddIfInteresting);
129 if (DVR.isDbgAssign())
130 AddIfInteresting(DVR.getAddress());
131 }
132
133 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
134 if (CI->canReturnTwice()) {
135 Info.CallsReturnTwice = true;
136 }
137 }
138 if (AllocaInst *AI = dyn_cast<AllocaInst>(&Inst)) {
139 if (isInterestingAlloca(*AI)) {
140 Info.AllocasToInstrument[AI].AI = AI;
141 }
142 return;
143 }
144 auto *II = dyn_cast<IntrinsicInst>(&Inst);
145 if (II && (II->getIntrinsicID() == Intrinsic::lifetime_start ||
146 II->getIntrinsicID() == Intrinsic::lifetime_end)) {
147 AllocaInst *AI = findAllocaForValue(II->getArgOperand(1));
148 if (!AI) {
149 Info.UnrecognizedLifetimes.push_back(&Inst);
150 return;
151 }
152 if (!isInterestingAlloca(*AI))
153 return;
154 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
155 Info.AllocasToInstrument[AI].LifetimeStart.push_back(II);
156 else
157 Info.AllocasToInstrument[AI].LifetimeEnd.push_back(II);
158 return;
159 }
160 if (auto *DVI = dyn_cast<DbgVariableIntrinsic>(&Inst)) {
161 auto AddIfInteresting = [&](Value *V) {
162 if (auto *AI = dyn_cast_or_null<AllocaInst>(V)) {
163 if (!isInterestingAlloca(*AI))
164 return;
165 AllocaInfo &AInfo = Info.AllocasToInstrument[AI];
166 auto &DVIVec = AInfo.DbgVariableIntrinsics;
167 if (DVIVec.empty() || DVIVec.back() != DVI)
168 DVIVec.push_back(DVI);
169 }
170 };
171 for_each(DVI->location_ops(), AddIfInteresting);
172 if (auto *DAI = dyn_cast<DbgAssignIntrinsic>(DVI))
173 AddIfInteresting(DAI->getAddress());
174 }
175
177 if (ExitUntag)
178 Info.RetVec.push_back(ExitUntag);
179}
180
182 return (AI.getAllocatedType()->isSized() &&
183 // FIXME: instrument dynamic allocas, too
184 AI.isStaticAlloca() &&
185 // alloca() may be called with 0 size, ignore it.
187 // We are only interested in allocas not promotable to registers.
188 // Promotable allocas are common under -O0.
189 !isAllocaPromotable(&AI) &&
190 // inalloca allocas are not treated as static, and we don't want
191 // dynamic alloca instrumentation for them as well.
192 !AI.isUsedWithInAlloca() &&
193 // swifterror allocas are register promoted by ISel
194 !AI.isSwiftError()) &&
195 // safe allocas are not interesting
196 !(SSI && SSI->isSafe(AI));
197}
198
200 auto DL = AI.getModule()->getDataLayout();
201 return *AI.getAllocationSize(DL);
202}
203
205 const Align NewAlignment = std::max(Info.AI->getAlign(), Alignment);
206 Info.AI->setAlignment(NewAlignment);
207 auto &Ctx = Info.AI->getFunction()->getContext();
208
210 uint64_t AlignedSize = alignTo(Size, Alignment);
211 if (Size == AlignedSize)
212 return;
213
214 // Add padding to the alloca.
215 Type *AllocatedType =
216 Info.AI->isArrayAllocation()
218 Info.AI->getAllocatedType(),
219 cast<ConstantInt>(Info.AI->getArraySize())->getZExtValue())
220 : Info.AI->getAllocatedType();
221 Type *PaddingType = ArrayType::get(Type::getInt8Ty(Ctx), AlignedSize - Size);
222 Type *TypeWithPadding = StructType::get(AllocatedType, PaddingType);
223 auto *NewAI = new AllocaInst(TypeWithPadding, Info.AI->getAddressSpace(),
224 nullptr, "", Info.AI->getIterator());
225 NewAI->takeName(Info.AI);
226 NewAI->setAlignment(Info.AI->getAlign());
227 NewAI->setUsedWithInAlloca(Info.AI->isUsedWithInAlloca());
228 NewAI->setSwiftError(Info.AI->isSwiftError());
229 NewAI->copyMetadata(*Info.AI);
230
231 Value *NewPtr = NewAI;
232
233 // TODO: Remove when typed pointers dropped
234 if (Info.AI->getType() != NewAI->getType())
235 NewPtr = new BitCastInst(NewAI, Info.AI->getType(), "", Info.AI->getIterator());
236
237 Info.AI->replaceAllUsesWith(NewPtr);
238 Info.AI->eraseFromParent();
239 Info.AI = NewAI;
240}
241
243 auto *II = dyn_cast<IntrinsicInst>(V);
244 return II && II->isLifetimeStartOrEnd();
245}
246
248 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
249 Function *ReadRegister = Intrinsic::getDeclaration(
250 M, Intrinsic::read_register, IRB.getIntPtrTy(M->getDataLayout()));
251 MDNode *MD =
252 MDNode::get(M->getContext(), {MDString::get(M->getContext(), Name)});
253 Value *Args[] = {MetadataAsValue::get(M->getContext(), MD)};
254 return IRB.CreateCall(ReadRegister, Args);
255}
256
257Value *getPC(const Triple &TargetTriple, IRBuilder<> &IRB) {
258 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
259 if (TargetTriple.getArch() == Triple::aarch64)
260 return memtag::readRegister(IRB, "pc");
261 return IRB.CreatePtrToInt(IRB.GetInsertBlock()->getParent(),
262 IRB.getIntPtrTy(M->getDataLayout()));
263}
264
267 Module *M = F->getParent();
268 auto *GetStackPointerFn = Intrinsic::getDeclaration(
269 M, Intrinsic::frameaddress,
270 IRB.getPtrTy(M->getDataLayout().getAllocaAddrSpace()));
271 return IRB.CreatePtrToInt(
272 IRB.CreateCall(GetStackPointerFn,
273 {Constant::getNullValue(IRB.getInt32Ty())}),
274 IRB.getIntPtrTy(M->getDataLayout()));
275}
276
278 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
279 // Android provides a fixed TLS slot for sanitizers. See TLS_SLOT_SANITIZER
280 // in Bionic's libc/private/bionic_tls.h.
281 Function *ThreadPointerFunc =
282 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
283 return IRB.CreateConstGEP1_32(IRB.getInt8Ty(),
284 IRB.CreateCall(ThreadPointerFunc), 8 * Slot);
285}
286
288 return dyn_cast<DbgAssignIntrinsic>(DVI);
289}
290
292 return DVR->isDbgAssign() ? DVR : nullptr;
293}
294
296 // Helper utility for adding DW_OP_LLVM_tag_offset to debug-info records,
297 // abstracted over whether they're intrinsic-stored or DbgVariableRecord
298 // stored.
299 auto AnnotateDbgRecord = [&](auto *DPtr) {
300 // Prepend "tag_offset, N" to the dwarf expression.
301 // Tag offset logically applies to the alloca pointer, and it makes sense
302 // to put it at the beginning of the expression.
304 for (size_t LocNo = 0; LocNo < DPtr->getNumVariableLocationOps(); ++LocNo)
305 if (DPtr->getVariableLocationOp(LocNo) == Info.AI)
306 DPtr->setExpression(
307 DIExpression::appendOpsToArg(DPtr->getExpression(), NewOps, LocNo));
308 if (auto *DAI = DynCastToDbgAssign(DPtr)) {
309 if (DAI->getAddress() == Info.AI)
310 DAI->setAddressExpression(
311 DIExpression::prependOpcodes(DAI->getAddressExpression(), NewOps));
312 }
313 };
314
315 llvm::for_each(Info.DbgVariableIntrinsics, AnnotateDbgRecord);
316 llvm::for_each(Info.DbgVariableRecords, AnnotateDbgRecord);
317}
318
319} // namespace memtag
320} // namespace llvm
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Analysis containing CSE Info
Definition: CSEInfo.cpp:27
This file contains constants used for implementing Dwarf debug support.
std::string Name
uint64_t Size
bool End
Definition: ELF_riscv.cpp:480
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
This file contains some templates that are useful if you are working with the STL at all.
an instruction to allocate memory on the stack
Definition: Instructions.h:59
bool isSwiftError() const
Return true if this alloca is used as a swifterror argument to a call.
Definition: Instructions.h:157
bool isStaticAlloca() const
Return true if this alloca is in the entry block of the function and is a constant size.
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
Definition: Instructions.h:125
bool isUsedWithInAlloca() const
Return true if this alloca is used as an inalloca argument to a call.
Definition: Instructions.h:147
std::optional< TypeSize > getAllocationSize(const DataLayout &DL) const
Get allocation size in bytes.
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
Definition: Type.cpp:647
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:206
const CallInst * getTerminatingMustTailCall() const
Returns the call instruction marked 'musttail' prior to the terminating return instruction of this ba...
Definition: BasicBlock.cpp:293
This class represents a no-op cast from one type to another.
This class represents a function call, abstracting a target machine's calling convention.
static DIExpression * appendOpsToArg(const DIExpression *Expr, ArrayRef< uint64_t > Ops, unsigned ArgNo, bool StackValue=false)
Create a copy of Expr by appending the given list of Ops to each instance of the operand DW_OP_LLVM_a...
static DIExpression * prependOpcodes(const DIExpression *Expr, SmallVectorImpl< uint64_t > &Ops, bool StackValue=false, bool EntryValue=false)
Prepend DIExpr with the given opcodes and optionally turn it into a stack value.
This represents the llvm.dbg.assign instruction.
This is the common base class for debug info intrinsics for variables.
Record of a variable value-assignment, aka a non instruction representation of the dbg....
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:162
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:656
Value * CreateConstGEP1_32(Type *Ty, Value *Ptr, unsigned Idx0, const Twine &Name="")
Definition: IRBuilder.h:1881
IntegerType * getIntPtrTy(const DataLayout &DL, unsigned AddrSpace=0)
Fetch the type of an integer with size at least as big as that of a pointer in the given address spac...
Definition: IRBuilder.h:575
BasicBlock * GetInsertBlock() const
Definition: IRBuilder.h:174
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2117
PointerType * getPtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer.
Definition: IRBuilder.h:569
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args=std::nullopt, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:2412
IntegerType * getInt8Ty()
Fetch the type representing an 8-bit integer.
Definition: IRBuilder.h:516
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2666
iterator_range< simple_ilist< DbgRecord >::iterator > getDbgRecordRange() const
Return a range over the DbgRecords attached to this instruction.
Definition: Instruction.h:84
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Definition: Instruction.cpp:83
const BasicBlock * getParent() const
Definition: Instruction.h:152
Metadata node.
Definition: Metadata.h:1067
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1541
static MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition: Metadata.cpp:103
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Definition: Module.h:293
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
bool dominates(const Instruction *I1, const Instruction *I2) const
Return true if I1 dominates I2.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:342
bool contains(ConstPtrType Ptr) const
Definition: SmallPtrSet.h:366
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:427
size_t size() const
Definition: SmallVector.h:91
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:586
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
bool isSafe(const AllocaInst &AI) const
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
static StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition: Type.cpp:373
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
ArchType getArch() const
Get the parsed architecture type of this triple.
Definition: Triple.h:372
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition: Type.h:302
static IntegerType * getInt8Ty(LLVMContext &C)
LLVM Value Representation.
Definition: Value.h:74
An efficient, type-erasing, non-owning reference to a callable.
bool isInterestingAlloca(const AllocaInst &AI)
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
@ DW_OP_LLVM_tag_offset
Only used in LLVM metadata.
Definition: Dwarf.h:143
static DbgAssignIntrinsic * DynCastToDbgAssign(DbgVariableIntrinsic *DVI)
Value * getFP(IRBuilder<> &IRB)
bool isStandardLifetime(const SmallVectorImpl< IntrinsicInst * > &LifetimeStart, const SmallVectorImpl< IntrinsicInst * > &LifetimeEnd, const DominatorTree *DT, const LoopInfo *LI, size_t MaxLifetimes)
bool forAllReachableExits(const DominatorTree &DT, const PostDominatorTree &PDT, const LoopInfo &LI, const Instruction *Start, const SmallVectorImpl< IntrinsicInst * > &Ends, const SmallVectorImpl< Instruction * > &RetVec, llvm::function_ref< void(Instruction *)> Callback)
uint64_t getAllocaSizeInBytes(const AllocaInst &AI)
Value * getAndroidSlotPtr(IRBuilder<> &IRB, int Slot)
Value * readRegister(IRBuilder<> &IRB, StringRef Name)
void annotateDebugRecords(AllocaInfo &Info, unsigned int Tag)
Instruction * getUntagLocationIfFunctionExit(Instruction &Inst)
void alignAndPadAlloca(memtag::AllocaInfo &Info, llvm::Align Align)
Value * getPC(const Triple &TargetTriple, IRBuilder<> &IRB)
bool isLifetimeIntrinsic(Value *V)
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
UnaryFunction for_each(R &&Range, UnaryFunction F)
Provide wrappers to std::for_each which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1715
AllocaInst * findAllocaForValue(Value *V, bool OffsetZero=false)
Returns unique alloca where the value comes from, or nullptr.
bool isAllocaPromotable(const AllocaInst *AI)
Return true if this alloca is legal for promotion.
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition: Alignment.h:155
static auto filterDbgVars(iterator_range< simple_ilist< DbgRecord >::iterator > R)
Filter the DbgRecord range to DbgVariableRecord types only and downcast.
bool isPotentiallyReachable(const Instruction *From, const Instruction *To, const SmallPtrSetImpl< BasicBlock * > *ExclusionSet=nullptr, const DominatorTree *DT=nullptr, const LoopInfo *LI=nullptr)
Determine whether instruction 'To' is reachable from 'From', without passing through any blocks in Ex...
Definition: CFG.cpp:231
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
SmallVector< DbgVariableIntrinsic *, 2 > DbgVariableIntrinsics
SmallVector< DbgVariableRecord *, 2 > DbgVariableRecords
MapVector< AllocaInst *, AllocaInfo > AllocasToInstrument
SmallVector< Instruction *, 4 > UnrecognizedLifetimes
SmallVector< Instruction *, 8 > RetVec