37#include "llvm/IR/IntrinsicsAArch64.h"
53#define DEBUG_TYPE "aarch64-stack-tagging"
59class InitializerBuilder {
75 std::map<uint64_t, Value *> Out;
78 InitializerBuilder(
uint64_t Size,
const DataLayout *DL,
Value *BasePtr,
81 : Size(Size), DL(DL), BasePtr(BasePtr), SetTagFn(SetTagFn),
82 SetTagZeroFn(SetTagZeroFn), StgpFn(StgpFn) {}
89 if (
I != Ranges.end() &&
End >
I->Start) {
97 bool addStore(
uint64_t Offset, StoreInst *SI,
const DataLayout *DL) {
98 int64_t StoreSize = DL->getTypeStoreSize(
SI->getOperand(0)->getType());
124 uint64_t Cst = 0x0101010101010101UL;
127 Cst = (Cst >> LowBits) << LowBits;
130 Cst = (Cst << HighBits) >> HighBits;
132 ConstantInt::get(IRB.
getInt64Ty(), Cst *
V->getZExtValue());
159 Value *StoredValue) {
160 StoredValue = flatten(IRB, StoredValue);
162 Value *
V = sliceValue(IRB, StoredValue,
Offset - Start);
167 CurrentV = IRB.
CreateOr(CurrentV, V);
175 if (Ranges.empty()) {
176 emitUndef(IRB, 0, Size);
186 auto I2 = Out.find(
Offset + 8);
187 if (I1 == Out.end() && I2 == Out.end())
191 emitZeroes(IRB, LastOffset,
Offset - LastOffset);
197 emitPair(IRB,
Offset, Store1, Store2);
203 if (LastOffset < Size)
204 emitZeroes(IRB, LastOffset, Size - LastOffset);
206 for (
const auto &R : Ranges) {
207 R.Inst->eraseFromParent();
214 Value *Ptr = BasePtr;
218 {Ptr, ConstantInt::get(IRB.
getInt64Ty(), Size)});
224 Value *Ptr = BasePtr;
233 Value *Ptr = BasePtr;
240 if (
V->getType()->isIntegerTy())
245 Type *EltTy = VecTy->getElementType();
247 uint32_t EltSize = DL->getTypeSizeInBits(EltTy);
255 V, IRB.
getIntNTy(DL->getTypeStoreSize(
V->getType()) * 8));
262 const bool MergeInit;
263 const bool UseStackSafety;
268 AArch64StackTagging(
const AArch64Options *Opts =
nullptr,
269 bool IsOptNone =
false)
271 MergeInit(!Opts ||
valueOr(Opts->stack_tagging_merge_init, !IsOptNone)),
272 UseStackSafety(!Opts ||
valueOr(Opts->stack_tagging_use_stack_safety,
275 void tagAlloca(AllocaInst *AI, Instruction *InsertBefore,
Value *Ptr,
277 void untagAlloca(AllocaInst *AI, Instruction *InsertBefore,
uint64_t Size);
284 const MapVector<AllocaInst *, memtag::AllocaInfo> &Allocas,
285 const DominatorTree *DT);
288 StringRef getPassName()
const override {
return "AArch64 Stack Tagging"; }
291 const AArch64Options *CLOpts =
nullptr;
294 const DataLayout *DL =
nullptr;
295 AAResults *AA =
nullptr;
296 const StackSafetyGlobalInfo *SSI =
nullptr;
298 void getAnalysisUsage(AnalysisUsage &AU)
const override {
301 AU.
addRequired<StackSafetyGlobalInfoWrapperPass>();
310char AArch64StackTagging::ID = 0;
322 return new AArch64StackTagging(&CLOpts, IsOptNone);
328 InitializerBuilder &IB) {
334 for (;
Count < CLOpts->stack_tagging_merge_init_scan_limit &&
346 if (BI->mayWriteToMemory() || BI->mayReadFromMemory())
352 if (!NextStore->isSimple())
356 std::optional<int64_t>
Offset =
357 NextStore->getPointerOperand()->getPointerOffsetFrom(StartPtr, *
DL);
363 LastInst = NextStore;
374 std::optional<int64_t>
Offset =
387void AArch64StackTagging::tagAlloca(AllocaInst *AI, Instruction *InsertBefore,
390 F->getParent(), Intrinsic::aarch64_settag_zero);
392 Intrinsic::aarch64_stgp);
394 InitializerBuilder
IB(
Size,
DL, Ptr, SetTagFunc, SetTagZeroFunc, StgpFunc);
397 if (AA && !
F->hasOptNone() && LittleEndian &&
400 <<
", size = " <<
Size <<
"\n");
401 InsertBefore = collectInitializers(InsertBefore, Ptr,
Size, IB);
408void AArch64StackTagging::untagAlloca(AllocaInst *AI, Instruction *InsertBefore,
416 const Triple &TargetTriple,
417 bool HasInstrumentedAllocas) {
418 if (!HasInstrumentedAllocas)
421 auto Mode = CLOpts.stack_tagging_record_stack_history;
434Instruction *AArch64StackTagging::insertBaseTaggedPointer(
436 const MapVector<AllocaInst *, memtag::AllocaInfo> &AllocasToInstrument,
437 const DominatorTree *DT) {
440 for (
auto &
I : AllocasToInstrument) {
441 const memtag::AllocaInfo &
Info =
I.second;
442 AllocaInst *AI =
Info.AI;
453 Intrinsic::aarch64_irg_sp, {},
456 const Triple &TargetTriple =
M.getTargetTriple();
463 !AllocasToInstrument.empty())) {
464 constexpr uint64_t TagMask = 0xFULL << 56;
466 auto *ThreadLong = IRB.
CreateLoad(IntptrTy, SlotPtr);
483bool AArch64StackTagging::runOnFunction(
Function &Fn) {
488 SSI = UseStackSafety &&
valueOr(CLOpts->stack_tagging_use_stack_safety,
true)
489 ? &getAnalysis<StackSafetyGlobalInfoWrapperPass>().getResult()
493 AA = MergeInit &&
valueOr(CLOpts->stack_tagging_merge_init,
true)
494 ? &getAnalysis<AAResultsWrapperPass>().getAAResults()
497 std::unique_ptr<OptimizationRemarkEmitter> DeleteORE;
498 OptimizationRemarkEmitter *ORE =
nullptr;
499 if (
auto *
P = getAnalysisIfAvailable<OptimizationRemarkEmitterWrapperPass>())
502 if (ORE ==
nullptr) {
503 DeleteORE = std::make_unique<OptimizationRemarkEmitter>(
F);
504 ORE = DeleteORE.get();
507 memtag::StackInfoBuilder SIB(SSI,
DEBUG_TYPE);
510 memtag::StackInfo &SInfo = SIB.get();
515 std::unique_ptr<DominatorTree> DeleteDT;
516 DominatorTree *DT =
nullptr;
517 if (
auto *
P = getAnalysisIfAvailable<DominatorTreeWrapperPass>())
518 DT = &
P->getDomTree();
521 DeleteDT = std::make_unique<DominatorTree>(*
F);
525 std::unique_ptr<PostDominatorTree> DeletePDT;
526 PostDominatorTree *PDT =
nullptr;
527 if (
auto *
P = getAnalysisIfAvailable<PostDominatorTreeWrapperPass>())
528 PDT = &
P->getPostDomTree();
530 if (PDT ==
nullptr) {
531 DeletePDT = std::make_unique<PostDominatorTree>(*
F);
532 PDT = DeletePDT.get();
535 std::unique_ptr<LoopInfo> DeleteLI;
536 LoopInfo *LI =
nullptr;
537 if (
auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>()) {
538 LI = &LIWP->getLoopInfo();
540 DeleteLI = std::make_unique<LoopInfo>(*DT);
545 Intrinsic::aarch64_settag);
550 unsigned int NextTag = 0;
552 memtag::AllocaInfo &
Info =
I.second;
556 AllocaInst *AI =
Info.AI;
557 unsigned int Tag = NextTag;
558 NextTag = (NextTag + 1) % 16;
562 Intrinsic::aarch64_tagp, {
Info.AI->getType()},
565 if (
Info.AI->hasName())
568 Info.AI->replaceUsesWithIf(TagPCall, [&](
const Use &U) {
577 bool StandardLifetime =
579 if (StandardLifetime) {
582 for (IntrinsicInst *Start :
Info.LifetimeStart)
583 tagAlloca(AI,
Start->getNextNode(), TagPCall,
Size);
591 for (
auto *RI : SInfo.
RetVec) {
592 untagAlloca(AI, RI,
Size);
596 for (
auto *
II :
Info.LifetimeStart)
597 II->eraseFromParent();
598 for (
auto *
II :
Info.LifetimeEnd)
599 II->eraseFromParent();
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static Value * getSlotPtr(const AArch64Options &CLOpts, IRBuilder<> &IRB, const Triple &TargetTriple, bool HasInstrumentedAllocas)
static const Align kTagGranuleSize
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains constants used for implementing Dwarf debug support.
static bool runOnFunction(Function &F, bool PostInlining)
This header defines various interfaces for pass management in LLVM.
Machine Check Debug Module
This file implements a map that provides insertion order iteration.
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
ModRefInfo getModRefInfo(const Instruction *I, const std::optional< MemoryLocation > &OptLoc)
Check whether or not an instruction may read or write the optionally specified memory location.
AnalysisUsage & addUsedIfAvailable()
Add the specified Pass class to the set of analyses used by this pass.
AnalysisUsage & addRequired()
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
const Instruction & front() const
InstListType::iterator iterator
Instruction iterators...
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
LLVM_ABI Instruction * findNearestCommonDominator(Instruction *I1, Instruction *I2) const
Find the nearest instruction I that dominates both I1 and I2, in the sense that a result produced bef...
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
FunctionPass class - This class is used to implement most global optimizations.
const DataLayout & getDataLayout() const
Get the data layout of the module this function belongs to.
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Module * getParent()
Get the module that this global value is contained inside of...
LLVM_ABI CallInst * CreateIntrinsicWithoutFolding(Intrinsic::ID ID, ArrayRef< Type * > OverloadTypes, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="", ArrayRef< OperandBundleDef > OpBundles={})
Create a call to intrinsic ID with Args, mangled using OverloadTypes.
Value * CreateConstGEP1_64(Type *Ty, Value *Ptr, uint64_t Idx0, const Twine &Name="")
Value * CreateConstGEP1_32(Type *Ty, Value *Ptr, unsigned Idx0, const Twine &Name="")
IntegerType * getIntNTy(unsigned N)
Fetch the type representing an N-bit integer.
Value * CreateZExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a ZExt or Trunc from the integer value V to DestTy.
Value * CreatePointerCast(Value *V, Type *DestTy, const Twine &Name="")
BasicBlock::iterator GetInsertPoint() const
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
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...
IntegerType * getInt64Ty()
Fetch the type representing a 64-bit integer.
Value * CreateBitOrPointerCast(Value *V, Type *DestTy, const Twine &Name="")
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
LLVMContext & getContext() const
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args={}, const Twine &Name="", MDNode *FPMathTag=nullptr)
PointerType * getPtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer.
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
IntegerType * getInt8Ty()
Fetch the type representing an 8-bit integer.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
LLVM_ABI cl::LibraryOptionsContext & getLibraryOptions() const
The library options this context reads in place of their process-wide values.
Value * getLength() const
Value * getDest() const
This is just like getRawDest, but it strips off any cast instructions (including addrspacecast) that ...
Representation for a specific memory location.
const Triple & getTargetTriple() const
Get the target triple which is a string describing the target host.
This pass performs the global (interprocedural) stack safety analysis (legacy pass manager).
Triple - Helper class for working with autoconf configuration names.
bool isAndroidVersionLT(unsigned Major) const
bool isAndroid() const
Tests whether the target is Android.
LLVM_ABI bool isLittleEndian() const
Tests whether the target triple is little endian.
bool isSimulatorEnvironment() const
bool isOSDarwin() const
Is this a "Darwin" OS (macOS, iOS, tvOS, watchOS, DriverKit, XROS, or bridgeOS).
bool isAArch64() const
Tests whether the target is AArch64 (little and big endian).
bool isPointerTy() const
True if this is an instance of PointerType.
void setOperand(unsigned i, Value *Val)
LLVM Value Representation.
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
LLVM_ABI std::optional< int64_t > getPointerOffsetFrom(const Value *Other, const DataLayout &DL) const
If this ptr is provably equal to Other plus a constant offset, return that offset in bytes.
const ParentTy * getParent() const
@ BasicBlock
Various leaf nodes.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
LLVM_ABI Value * getFP(IRBuilder<> &IRB)
LLVM_ABI void forAllReachableExits(const DominatorTree &DT, const PostDominatorTree &PDT, const LoopInfo &LI, const AllocaInfo &AInfo, const SmallVectorImpl< Instruction * > &RetVec, llvm::function_ref< void(Instruction *)> Callback)
LLVM_ABI bool isSupportedLifetime(const AllocaInfo &AInfo, const DominatorTree *DT, const LoopInfo *LI)
LLVM_ABI Value * getDarwinSlotPtr(IRBuilder<> &IRB, int Slot)
LLVM_ABI Value * getAndroidSlotPtr(IRBuilder<> &IRB, int Slot)
LLVM_ABI void annotateDebugRecords(AllocaInfo &Info, unsigned int Tag)
LLVM_ABI void alignAndPadAlloca(memtag::AllocaInfo &Info, llvm::Align Align)
LLVM_ABI Value * getPC(const Triple &TargetTriple, IRBuilder<> &IRB)
LLVM_ABI Value * incrementThreadLong(IRBuilder<> &IRB, Value *ThreadLong, unsigned int Inc, bool IsMemtagDarwin=false)
NodeAddr< NodeBase * > Node
friend class Instruction
Iterator for Instructions in a `BasicBlock.
unsigned getNumElements(Type *Ty)
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.
FunctionPass * createAArch64StackTaggingPass(const AArch64Options &CLOpts, bool IsOptNone)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
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...
auto lower_bound(R &&Range, T &&Value)
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
constexpr bool valueOr(BoolOrDefault X, bool Default)
@ End
Run the machine verifier once, at the end of the pipeline.
bool isNoModRef(const ModRefInfo MRI)
This struct is a compact representation of a valid (non-zero power of two) alignment.
MapVector< AllocaInst *, AllocaInfo > AllocasToInstrument
SmallVector< Instruction *, 8 > RetVec