45 #include "llvm/IR/IntrinsicsAArch64.h" 58 #define DEBUG_TYPE "stack-tagging" 62 cl::desc(
"merge stack variable initializers with tagging when possible"));
71 class InitializerBuilder {
87 std::map<uint64_t, Value *> Out;
93 : Size(Size), DL(DL), BasePtr(BasePtr), SetTagFn(SetTagFn),
94 SetTagZeroFn(SetTagZeroFn), StgpFn(StgpFn) {}
99 [](
const Range &LHS, uint64_t RHS) {
return LHS.End <= RHS; });
100 if (
I != Ranges.
end() && End >
I->Start) {
104 Ranges.
insert(
I, {Start, End, Inst});
110 if (!
addRange(Offset, Offset + StoreSize, SI))
113 applyStore(IRB, Offset, Offset + StoreSize, SI->
getOperand(0));
117 bool addMemSet(uint64_t Offset,
MemSetInst *MSI) {
118 uint64_t StoreSize = cast<ConstantInt>(MSI->
getLength())->getZExtValue();
119 if (!
addRange(Offset, Offset + StoreSize, MSI))
122 applyMemSet(IRB, Offset, Offset + StoreSize,
123 cast<ConstantInt>(MSI->
getValue()));
127 void applyMemSet(
IRBuilder<> &IRB, int64_t Start, int64_t End,
134 for (int64_t Offset = Start - Start % 8; Offset < End; Offset += 8) {
135 uint64_t Cst = 0x0101010101010101UL;
136 int LowBits = Offset < Start ? (Start -
Offset) * 8 : 0;
138 Cst = (Cst >> LowBits) << LowBits;
139 int HighBits = End - Offset < 8 ? (8 - (End -
Offset)) * 8 : 0;
141 Cst = (Cst << HighBits) >> HighBits;
149 CurrentV = IRB.
CreateOr(CurrentV, C);
160 }
else if (Offset < 0) {
169 void applyStore(
IRBuilder<> &IRB, int64_t Start, int64_t End,
170 Value *StoredValue) {
171 StoredValue = flatten(IRB, StoredValue);
172 for (int64_t Offset = Start - Start % 8; Offset < End; Offset += 8) {
173 Value *V = sliceValue(IRB, StoredValue, Offset - Start);
178 CurrentV = IRB.
CreateOr(CurrentV, V);
186 if (Ranges.
empty()) {
187 emitUndef(IRB, 0, Size);
194 uint64_t LastOffset = 0;
195 for (uint64_t Offset = 0; Offset <
Size; Offset += 16) {
196 auto I1 = Out.find(Offset);
197 auto I2 = Out.find(Offset + 8);
198 if (I1 == Out.end() && I2 == Out.end())
201 if (Offset > LastOffset)
202 emitZeroes(IRB, LastOffset, Offset - LastOffset);
208 emitPair(IRB, Offset, Store1, Store2);
209 LastOffset = Offset + 16;
214 if (LastOffset < Size)
215 emitZeroes(IRB, LastOffset, Size - LastOffset);
217 for (
const auto &R : Ranges) {
218 R.Inst->eraseFromParent();
222 void emitZeroes(
IRBuilder<> &IRB, uint64_t Offset, uint64_t Size) {
225 Value *Ptr = BasePtr;
232 void emitUndef(
IRBuilder<> &IRB, uint64_t Offset, uint64_t Size) {
235 Value *Ptr = BasePtr;
242 LLVM_DEBUG(
dbgs() <<
" [" << Offset <<
", " << Offset + 16 <<
"):\n");
244 Value *Ptr = BasePtr;
256 Type *EltTy = VecTy->getElementType();
260 VecTy->getNumElements());
283 AArch64StackTagging(
bool MergeInit =
true)
290 bool isInterestingAlloca(
const AllocaInst &AI);
291 void alignAndPadAlloca(AllocaInfo &
Info);
298 uint64_t Size, InitializerBuilder &IB);
305 StringRef getPassName()
const override {
return "AArch64 Stack Tagging"; }
330 return new AArch64StackTagging(MergeInit);
336 InitializerBuilder &IB) {
342 for (; Count <
ClScanLimit && !BI->isTerminator(); ++BI) {
343 if (!isa<DbgInfoIntrinsic>(*BI))
349 if (!isa<StoreInst>(BI) && !isa<MemSetInst>(BI)) {
353 if (BI->mayWriteToMemory() || BI->mayReadFromMemory())
358 if (
StoreInst *NextStore = dyn_cast<StoreInst>(BI)) {
359 if (!NextStore->isSimple())
368 if (!IB.addStore(*Offset, NextStore, DL))
370 LastInst = NextStore;
377 if (!isa<ConstantInt>(MSI->
getValue()))
385 if (!IB.addMemSet(*Offset, MSI))
393 bool AArch64StackTagging::isInterestingAlloca(
const AllocaInst &AI) {
404 return IsInteresting;
408 Value *Ptr, uint64_t Size) {
409 auto SetTagZeroFunc =
414 InitializerBuilder IB(Size, DL, Ptr, SetTagFunc, SetTagZeroFunc, StgpFunc);
418 if (MergeInit && !F->
hasOptNone() && LittleEndian) {
420 <<
", size = " << Size <<
"\n");
421 InsertBefore = collectInitializers(InsertBefore, Ptr, Size, IB);
435 Instruction *AArch64StackTagging::insertBaseTaggedPointer(
440 for (
auto &
I : Allocas) {
441 const AllocaInfo &
Info =
I.second;
462 void AArch64StackTagging::alignAndPadAlloca(AllocaInfo &
Info) {
463 const Align NewAlignment =
465 Info.AI->setAlignment(NewAlignment);
467 uint64_t Size = Info.AI->getAllocationSizeInBits(*DL).getValue() / 8;
468 uint64_t AlignedSize =
alignTo(Size, kTagGranuleSize);
469 if (Size == AlignedSize)
473 Type *AllocatedType =
474 Info.AI->isArrayAllocation()
476 Info.AI->getAllocatedType(),
477 cast<ConstantInt>(Info.AI->getArraySize())->getZExtValue())
478 : Info.AI->getAllocatedType();
483 TypeWithPadding, Info.AI->getType()->getAddressSpace(),
nullptr,
"", Info.AI);
485 NewAI->setAlignment(
MaybeAlign(Info.AI->getAlignment()));
486 NewAI->setUsedWithInAlloca(Info.AI->isUsedWithInAlloca());
487 NewAI->setSwiftError(Info.AI->isSwiftError());
488 NewAI->copyMetadata(*Info.AI);
490 auto *NewPtr =
new BitCastInst(NewAI, Info.AI->getType(),
"", Info.AI);
491 Info.AI->replaceAllUsesWith(NewPtr);
492 Info.AI->eraseFromParent();
522 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
529 for (
auto &BB : *F) {
532 if (
auto *AI = dyn_cast<AllocaInst>(I)) {
537 if (
auto *DVI = dyn_cast<DbgVariableIntrinsic>(I)) {
539 dyn_cast_or_null<AllocaInst>(DVI->getVariableLocation())) {
540 Allocas[AI].DbgVariableIntrinsics.push_back(DVI);
546 if (II && (II->getIntrinsicID() == Intrinsic::lifetime_start ||
547 II->getIntrinsicID() == Intrinsic::lifetime_end)) {
554 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
555 Allocas[AI].LifetimeStart.push_back(II);
557 Allocas[AI].LifetimeEnd.push_back(II);
560 if (isa<ReturnInst>(I) || isa<ResumeInst>(I) || isa<CleanupReturnInst>(I))
569 int NumInterestingAllocas = 0;
570 for (
auto &
I : Allocas) {
571 AllocaInfo &Info =
I.second;
574 if (!isInterestingAlloca(*Info.AI)) {
579 alignAndPadAlloca(Info);
580 NumInterestingAllocas++;
582 NextTag = (NextTag + 1) % 16;
585 if (NumInterestingAllocas == 0)
588 std::unique_ptr<DominatorTree> DeleteDT;
590 if (
auto *
P = getAnalysisIfAvailable<DominatorTreeWrapperPass>())
591 DT = &
P->getDomTree();
593 if (DT ==
nullptr && (NumInterestingAllocas > 1 ||
594 !F->hasFnAttribute(Attribute::OptimizeNone))) {
595 DeleteDT = std::make_unique<DominatorTree>(*F);
599 std::unique_ptr<PostDominatorTree> DeletePDT;
601 if (
auto *
P = getAnalysisIfAvailable<PostDominatorTreeWrapperPass>())
602 PDT = &
P->getPostDomTree();
604 if (PDT ==
nullptr && !F->hasFnAttribute(Attribute::OptimizeNone)) {
605 DeletePDT = std::make_unique<PostDominatorTree>(*F);
606 PDT = DeletePDT.get();
614 for (
auto &
I : Allocas) {
615 const AllocaInfo &Info =
I.second;
623 F->getParent(), Intrinsic::aarch64_tagp, {Info.AI->getType()});
627 if (Info.AI->hasName())
628 TagPCall->
setName(Info.AI->getName() +
".tag");
629 Info.AI->replaceAllUsesWith(TagPCall);
630 TagPCall->setOperand(0, Info.AI);
632 if (UnrecognizedLifetimes.
empty() && Info.LifetimeStart.size() == 1 &&
633 Info.LifetimeEnd.size() == 1) {
638 Size =
alignTo(Size, kTagGranuleSize);
643 untagAlloca(AI, End, Size);
646 unsigned NumCoveredExits = 0;
647 for (
auto &RI : RetVec) {
651 if (DT !=
nullptr && DT->
dominates(End, RI))
656 if (NumCoveredExits == ReachableRetVec.
size()) {
657 untagAlloca(AI, End, Size);
659 for (
auto &RI : ReachableRetVec)
660 untagAlloca(AI, RI, Size);
667 uint64_t Size = Info.AI->getAllocationSizeInBits(*DL).getValue() / 8;
670 for (
auto &RI : RetVec) {
671 untagAlloca(AI, RI, Size);
675 for (
auto &II : Info.LifetimeStart)
676 II->eraseFromParent();
677 for (
auto &II : Info.LifetimeEnd)
678 II->eraseFromParent();
682 for (
auto DVI : Info.DbgVariableIntrinsics)
690 for (
auto &
I : UnrecognizedLifetimes)
691 I->eraseFromParent();
auto lower_bound(R &&Range, T &&Value) -> decltype(adl_begin(Range))
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
A parsed version of the target data layout string in and methods for querying it. ...
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
Value * CreateConstGEP1_32(Value *Ptr, unsigned Idx0, const Twine &Name="")
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
LLVMContext & getContext() const
Value * CreateZExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a ZExt or Trunc from the integer value V to DestTy.
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
This class represents lattice values for constants.
bool hasOptNone() const
Do not optimize this function (-O0).
bool isSized(SmallPtrSetImpl< Type *> *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
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...
void push_back(const T &Elt)
bool isSwiftError() const
Return true if this alloca is used as a swifterror argument to a call.
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
NodeT * findNearestCommonDominator(NodeT *A, NodeT *B) const
findNearestCommonDominator - Find nearest common dominator basic block for basic block A and B...
This class wraps the llvm.memset intrinsic.
This class implements a map that also provides access to all stored values in a deterministic order...
TypeSize getTypeSizeInBits(Type *Ty) const
Size examples:
Value * getLength() const
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Value * getDest() const
This is just like getRawDest, but it strips off any cast instructions (including addrspacecast) that ...
static bool postDominates(const PostDominatorTree *PDT, const IntrinsicInst *A, const IntrinsicInst *B)
Value * getArgOperand(unsigned i) const
AnalysisUsage & addRequired()
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
IntegerType * getInt64Ty()
Fetch the type representing a 64-bit integer.
bool isIntegerTy() const
True if this is an instance of IntegerType.
FunctionPass * createAArch64StackTaggingPass(bool MergeInit)
void setName(const Twine &Name)
Change the name of the value.
static StructType * get(LLVMContext &Context, ArrayRef< Type *> Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Type * getType() const
All values are typed, get the type of this value.
TypeSize getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type...
const T & getValue() const LLVM_LVALUE_FUNCTION
bool isUsedWithInAlloca() const
Return true if this alloca is used as an inalloca argument to a call.
This class represents a no-op cast from one type to another.
An instruction for storing to memory.
void takeName(Value *V)
Transfer the name from V to this value.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Function * getDeclaration(Module *M, ID id, ArrayRef< Type *> Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Value * getOperand(unsigned i) const
Analysis containing CSE Info
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="")
static bool runOnFunction(Function &F, bool PostInlining)
initializer< Ty > init(const Ty &Val)
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
LLVM Basic Block Representation.
bool dominates(const Instruction *I1, const Instruction *I2) const
Return true if I1 dominates I2.
The instances of the Type class are immutable: once they are created, they are never changed...
This is an important class for using LLVM in a threaded context.
bool isPointerTy() const
True if this is an instance of PointerType.
const Instruction & front() const
Represent the analysis usage information of a pass.
AllocaInst * findAllocaForValue(Value *V, DenseMap< Value *, AllocaInst *> &AllocaForValue)
Finds alloca where the value comes from.
static cl::opt< unsigned > ClScanLimit("stack-tagging-merge-init-scan-limit", cl::init(40), cl::Hidden)
FunctionPass class - This class is used to implement most global optimizations.
static cl::opt< bool > ClMergeInit("stack-tagging-merge-init", cl::Hidden, cl::init(true), cl::ZeroOrMore, cl::desc("merge stack variable initializers with tagging when possible"))
IntegerType * getIntNTy(unsigned N)
Fetch the type representing an N-bit integer.
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
PointerType * getInt8PtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer to an 8-bit integer value.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
This struct is a compact representation of a valid (non-zero power of two) alignment.
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
Triple - Helper class for working with autoconf configuration names.
Optional< uint64_t > getAllocationSizeInBits(const DataLayout &DL) const
Get allocation size in bits.
Representation for a specific memory location.
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Iterator for intrusive lists based on ilist_node.
This is the shared class of boolean and integer constants.
Align max(MaybeAlign Lhs, Align Rhs)
This struct is a compact representation of a valid (power of two) or undefined (0) alignment...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
void setPreservesCFG()
This function should be called by the pass, iff they do not:
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void initializeAArch64StackTaggingPass(PassRegistry &)
Optional< int64_t > isPointerOffset(const Value *Ptr1, const Value *Ptr2, const DataLayout &DL)
If Ptr1 is provably equal to Ptr2 plus a constant offset, return that offset.
Class to represent vector types.
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
LLVM_NODISCARD bool isNoModRef(const ModRefInfo MRI)
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
iterator insert(iterator I, T &&Elt)
Value * CreatePointerCast(Value *V, Type *DestTy, const Twine &Name="")
Value * CreateBitOrPointerCast(Value *V, Type *DestTy, const Twine &Name="")
static cl::opt< ITMode > IT(cl::desc("IT block support"), cl::Hidden, cl::init(DefaultIT), cl::ZeroOrMore, cl::values(clEnumValN(DefaultIT, "arm-default-it", "Generate IT block based on arch"), clEnumValN(RestrictedIT, "arm-restrict-it", "Disallow deprecated IT based on ARMv8"), clEnumValN(NoRestrictedIT, "arm-no-restrict-it", "Allow IT blocks based on ARMv7")))
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
INITIALIZE_PASS_BEGIN(AArch64StackTagging, DEBUG_TYPE, "AArch64 Stack Tagging", false, false) INITIALIZE_PASS_END(AArch64StackTagging
LLVM_NODISCARD bool empty() const
static VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value *> Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
static const Align kTagGranuleSize
BasicBlock::iterator GetInsertPoint() const
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
StringRef - Represent a constant reference to a string, i.e.
bool isStaticAlloca() const
Return true if this alloca is in the entry block of the function and is a constant size...
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc)
getModRefInfo (for call sites) - Return information about whether a particular call site modifies or ...
static IntegerType * getInt8Ty(LLVMContext &C)
A wrapper class for inspecting calls to intrinsic functions.
const BasicBlock * getParent() const
an instruction to allocate memory on the stack