LLVM 20.0.0git
AArch64StackTagging.cpp
Go to the documentation of this file.
1//===- AArch64StackTagging.cpp - Stack tagging in IR --===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//===----------------------------------------------------------------------===//
9
10#include "AArch64.h"
11#include "AArch64Subtarget.h"
12#include "llvm/ADT/APInt.h"
13#include "llvm/ADT/MapVector.h"
15#include "llvm/ADT/Statistic.h"
17#include "llvm/Analysis/CFG.h"
29#include "llvm/IR/DebugLoc.h"
30#include "llvm/IR/Dominators.h"
31#include "llvm/IR/Function.h"
32#include "llvm/IR/IRBuilder.h"
34#include "llvm/IR/Instruction.h"
37#include "llvm/IR/IntrinsicsAArch64.h"
38#include "llvm/IR/Metadata.h"
39#include "llvm/IR/PassManager.h"
41#include "llvm/Pass.h"
43#include "llvm/Support/Debug.h"
47#include <cassert>
48#include <memory>
49#include <utility>
50
51using namespace llvm;
52
53#define DEBUG_TYPE "aarch64-stack-tagging"
54
56 "stack-tagging-merge-init", cl::Hidden, cl::init(true),
57 cl::desc("merge stack variable initializers with tagging when possible"));
58
59static cl::opt<bool>
60 ClUseStackSafety("stack-tagging-use-stack-safety", cl::Hidden,
61 cl::init(true),
62 cl::desc("Use Stack Safety analysis results"));
63
64static cl::opt<unsigned> ClScanLimit("stack-tagging-merge-init-scan-limit",
65 cl::init(40), cl::Hidden);
66
68 ClMergeInitSizeLimit("stack-tagging-merge-init-size-limit", cl::init(272),
70
72 "stack-tagging-max-lifetimes-for-alloca", cl::Hidden, cl::init(3),
74 cl::desc("How many lifetime ends to handle for a single alloca."),
76
77// Mode for selecting how to insert frame record info into the stack ring
78// buffer.
80 // Do not record frame record info.
82
83 // Insert instructions into the prologue for storing into the stack ring
84 // buffer directly.
86};
87
89 "stack-tagging-record-stack-history",
90 cl::desc("Record stack frames with tagged allocations in a thread-local "
91 "ring buffer"),
92 cl::values(clEnumVal(none, "Do not record stack ring history"),
93 clEnumVal(instr, "Insert instructions into the prologue for "
94 "storing into the stack ring buffer")),
96
97static const Align kTagGranuleSize = Align(16);
98
99namespace {
100
101class InitializerBuilder {
102 uint64_t Size;
103 const DataLayout *DL;
104 Value *BasePtr;
105 Function *SetTagFn;
106 Function *SetTagZeroFn;
107 Function *StgpFn;
108
109 // List of initializers sorted by start offset.
110 struct Range {
111 uint64_t Start, End;
112 Instruction *Inst;
113 };
115 // 8-aligned offset => 8-byte initializer
116 // Missing keys are zero initialized.
117 std::map<uint64_t, Value *> Out;
118
119public:
120 InitializerBuilder(uint64_t Size, const DataLayout *DL, Value *BasePtr,
121 Function *SetTagFn, Function *SetTagZeroFn,
122 Function *StgpFn)
123 : Size(Size), DL(DL), BasePtr(BasePtr), SetTagFn(SetTagFn),
124 SetTagZeroFn(SetTagZeroFn), StgpFn(StgpFn) {}
125
126 bool addRange(uint64_t Start, uint64_t End, Instruction *Inst) {
127 auto I =
128 llvm::lower_bound(Ranges, Start, [](const Range &LHS, uint64_t RHS) {
129 return LHS.End <= RHS;
130 });
131 if (I != Ranges.end() && End > I->Start) {
132 // Overlap - bail.
133 return false;
134 }
135 Ranges.insert(I, {Start, End, Inst});
136 return true;
137 }
138
139 bool addStore(uint64_t Offset, StoreInst *SI, const DataLayout *DL) {
140 int64_t StoreSize = DL->getTypeStoreSize(SI->getOperand(0)->getType());
141 if (!addRange(Offset, Offset + StoreSize, SI))
142 return false;
143 IRBuilder<> IRB(SI);
144 applyStore(IRB, Offset, Offset + StoreSize, SI->getOperand(0));
145 return true;
146 }
147
148 bool addMemSet(uint64_t Offset, MemSetInst *MSI) {
149 uint64_t StoreSize = cast<ConstantInt>(MSI->getLength())->getZExtValue();
150 if (!addRange(Offset, Offset + StoreSize, MSI))
151 return false;
152 IRBuilder<> IRB(MSI);
153 applyMemSet(IRB, Offset, Offset + StoreSize,
154 cast<ConstantInt>(MSI->getValue()));
155 return true;
156 }
157
158 void applyMemSet(IRBuilder<> &IRB, int64_t Start, int64_t End,
159 ConstantInt *V) {
160 // Out[] does not distinguish between zero and undef, and we already know
161 // that this memset does not overlap with any other initializer. Nothing to
162 // do for memset(0).
163 if (V->isZero())
164 return;
165 for (int64_t Offset = Start - Start % 8; Offset < End; Offset += 8) {
166 uint64_t Cst = 0x0101010101010101UL;
167 int LowBits = Offset < Start ? (Start - Offset) * 8 : 0;
168 if (LowBits)
169 Cst = (Cst >> LowBits) << LowBits;
170 int HighBits = End - Offset < 8 ? (8 - (End - Offset)) * 8 : 0;
171 if (HighBits)
172 Cst = (Cst << HighBits) >> HighBits;
173 ConstantInt *C =
174 ConstantInt::get(IRB.getInt64Ty(), Cst * V->getZExtValue());
175
176 Value *&CurrentV = Out[Offset];
177 if (!CurrentV) {
178 CurrentV = C;
179 } else {
180 CurrentV = IRB.CreateOr(CurrentV, C);
181 }
182 }
183 }
184
185 // Take a 64-bit slice of the value starting at the given offset (in bytes).
186 // Offset can be negative. Pad with zeroes on both sides when necessary.
187 Value *sliceValue(IRBuilder<> &IRB, Value *V, int64_t Offset) {
188 if (Offset > 0) {
189 V = IRB.CreateLShr(V, Offset * 8);
190 V = IRB.CreateZExtOrTrunc(V, IRB.getInt64Ty());
191 } else if (Offset < 0) {
192 V = IRB.CreateZExtOrTrunc(V, IRB.getInt64Ty());
193 V = IRB.CreateShl(V, -Offset * 8);
194 } else {
195 V = IRB.CreateZExtOrTrunc(V, IRB.getInt64Ty());
196 }
197 return V;
198 }
199
200 void applyStore(IRBuilder<> &IRB, int64_t Start, int64_t End,
201 Value *StoredValue) {
202 StoredValue = flatten(IRB, StoredValue);
203 for (int64_t Offset = Start - Start % 8; Offset < End; Offset += 8) {
204 Value *V = sliceValue(IRB, StoredValue, Offset - Start);
205 Value *&CurrentV = Out[Offset];
206 if (!CurrentV) {
207 CurrentV = V;
208 } else {
209 CurrentV = IRB.CreateOr(CurrentV, V);
210 }
211 }
212 }
213
214 void generate(IRBuilder<> &IRB) {
215 LLVM_DEBUG(dbgs() << "Combined initializer\n");
216 // No initializers => the entire allocation is undef.
217 if (Ranges.empty()) {
218 emitUndef(IRB, 0, Size);
219 return;
220 }
221
222 // Look through 8-byte initializer list 16 bytes at a time;
223 // If one of the two 8-byte halfs is non-zero non-undef, emit STGP.
224 // Otherwise, emit zeroes up to next available item.
225 uint64_t LastOffset = 0;
226 for (uint64_t Offset = 0; Offset < Size; Offset += 16) {
227 auto I1 = Out.find(Offset);
228 auto I2 = Out.find(Offset + 8);
229 if (I1 == Out.end() && I2 == Out.end())
230 continue;
231
232 if (Offset > LastOffset)
233 emitZeroes(IRB, LastOffset, Offset - LastOffset);
234
235 Value *Store1 = I1 == Out.end() ? Constant::getNullValue(IRB.getInt64Ty())
236 : I1->second;
237 Value *Store2 = I2 == Out.end() ? Constant::getNullValue(IRB.getInt64Ty())
238 : I2->second;
239 emitPair(IRB, Offset, Store1, Store2);
240 LastOffset = Offset + 16;
241 }
242
243 // memset(0) does not update Out[], therefore the tail can be either undef
244 // or zero.
245 if (LastOffset < Size)
246 emitZeroes(IRB, LastOffset, Size - LastOffset);
247
248 for (const auto &R : Ranges) {
249 R.Inst->eraseFromParent();
250 }
251 }
252
253 void emitZeroes(IRBuilder<> &IRB, uint64_t Offset, uint64_t Size) {
254 LLVM_DEBUG(dbgs() << " [" << Offset << ", " << Offset + Size
255 << ") zero\n");
256 Value *Ptr = BasePtr;
257 if (Offset)
259 IRB.CreateCall(SetTagZeroFn,
260 {Ptr, ConstantInt::get(IRB.getInt64Ty(), Size)});
261 }
262
263 void emitUndef(IRBuilder<> &IRB, uint64_t Offset, uint64_t Size) {
264 LLVM_DEBUG(dbgs() << " [" << Offset << ", " << Offset + Size
265 << ") undef\n");
266 Value *Ptr = BasePtr;
267 if (Offset)
269 IRB.CreateCall(SetTagFn, {Ptr, ConstantInt::get(IRB.getInt64Ty(), Size)});
270 }
271
272 void emitPair(IRBuilder<> &IRB, uint64_t Offset, Value *A, Value *B) {
273 LLVM_DEBUG(dbgs() << " [" << Offset << ", " << Offset + 16 << "):\n");
274 LLVM_DEBUG(dbgs() << " " << *A << "\n " << *B << "\n");
275 Value *Ptr = BasePtr;
276 if (Offset)
278 IRB.CreateCall(StgpFn, {Ptr, A, B});
279 }
280
281 Value *flatten(IRBuilder<> &IRB, Value *V) {
282 if (V->getType()->isIntegerTy())
283 return V;
284 // vector of pointers -> vector of ints
285 if (VectorType *VecTy = dyn_cast<VectorType>(V->getType())) {
286 LLVMContext &Ctx = IRB.getContext();
287 Type *EltTy = VecTy->getElementType();
288 if (EltTy->isPointerTy()) {
289 uint32_t EltSize = DL->getTypeSizeInBits(EltTy);
290 auto *NewTy = FixedVectorType::get(
291 IntegerType::get(Ctx, EltSize),
292 cast<FixedVectorType>(VecTy)->getNumElements());
293 V = IRB.CreatePointerCast(V, NewTy);
294 }
295 }
296 return IRB.CreateBitOrPointerCast(
297 V, IRB.getIntNTy(DL->getTypeStoreSize(V->getType()) * 8));
298 }
299};
300
301class AArch64StackTagging : public FunctionPass {
302 const bool MergeInit;
303 const bool UseStackSafety;
304
305public:
306 static char ID; // Pass ID, replacement for typeid
307
308 AArch64StackTagging(bool IsOptNone = false)
309 : FunctionPass(ID),
310 MergeInit(ClMergeInit.getNumOccurrences() ? ClMergeInit : !IsOptNone),
311 UseStackSafety(ClUseStackSafety.getNumOccurrences() ? ClUseStackSafety
312 : !IsOptNone) {
314 }
315
316 void tagAlloca(AllocaInst *AI, Instruction *InsertBefore, Value *Ptr,
317 uint64_t Size);
318 void untagAlloca(AllocaInst *AI, Instruction *InsertBefore, uint64_t Size);
319
320 Instruction *collectInitializers(Instruction *StartInst, Value *StartPtr,
321 uint64_t Size, InitializerBuilder &IB);
322
323 Instruction *insertBaseTaggedPointer(
324 const Module &M,
326 const DominatorTree *DT);
327 bool runOnFunction(Function &F) override;
328
329 StringRef getPassName() const override { return "AArch64 Stack Tagging"; }
330
331private:
332 Function *F = nullptr;
333 Function *SetTagFunc = nullptr;
334 const DataLayout *DL = nullptr;
335 AAResults *AA = nullptr;
336 const StackSafetyGlobalInfo *SSI = nullptr;
337
338 void getAnalysisUsage(AnalysisUsage &AU) const override {
339 AU.setPreservesCFG();
340 if (UseStackSafety)
342 if (MergeInit)
345 }
346};
347
348} // end anonymous namespace
349
350char AArch64StackTagging::ID = 0;
351
352INITIALIZE_PASS_BEGIN(AArch64StackTagging, DEBUG_TYPE, "AArch64 Stack Tagging",
353 false, false)
357INITIALIZE_PASS_END(AArch64StackTagging, DEBUG_TYPE, "AArch64 Stack Tagging",
359
361 return new AArch64StackTagging(IsOptNone);
362}
363
364Instruction *AArch64StackTagging::collectInitializers(Instruction *StartInst,
365 Value *StartPtr,
367 InitializerBuilder &IB) {
368 MemoryLocation AllocaLoc{StartPtr, Size};
369 Instruction *LastInst = StartInst;
370 BasicBlock::iterator BI(StartInst);
371
372 unsigned Count = 0;
373 for (; Count < ClScanLimit && !BI->isTerminator(); ++BI) {
374 if (!isa<DbgInfoIntrinsic>(*BI))
375 ++Count;
376
377 if (isNoModRef(AA->getModRefInfo(&*BI, AllocaLoc)))
378 continue;
379
380 if (!isa<StoreInst>(BI) && !isa<MemSetInst>(BI)) {
381 // If the instruction is readnone, ignore it, otherwise bail out. We
382 // don't even allow readonly here because we don't want something like:
383 // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
384 if (BI->mayWriteToMemory() || BI->mayReadFromMemory())
385 break;
386 continue;
387 }
388
389 if (StoreInst *NextStore = dyn_cast<StoreInst>(BI)) {
390 if (!NextStore->isSimple())
391 break;
392
393 // Check to see if this store is to a constant offset from the start ptr.
394 std::optional<int64_t> Offset =
395 NextStore->getPointerOperand()->getPointerOffsetFrom(StartPtr, *DL);
396 if (!Offset)
397 break;
398
399 if (!IB.addStore(*Offset, NextStore, DL))
400 break;
401 LastInst = NextStore;
402 } else {
403 MemSetInst *MSI = cast<MemSetInst>(BI);
404
405 if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength()))
406 break;
407
408 if (!isa<ConstantInt>(MSI->getValue()))
409 break;
410
411 // Check to see if this store is to a constant offset from the start ptr.
412 std::optional<int64_t> Offset =
413 MSI->getDest()->getPointerOffsetFrom(StartPtr, *DL);
414 if (!Offset)
415 break;
416
417 if (!IB.addMemSet(*Offset, MSI))
418 break;
419 LastInst = MSI;
420 }
421 }
422 return LastInst;
423}
424
425void AArch64StackTagging::tagAlloca(AllocaInst *AI, Instruction *InsertBefore,
427 auto SetTagZeroFunc = Intrinsic::getOrInsertDeclaration(
428 F->getParent(), Intrinsic::aarch64_settag_zero);
429 auto StgpFunc = Intrinsic::getOrInsertDeclaration(F->getParent(),
430 Intrinsic::aarch64_stgp);
431
432 InitializerBuilder IB(Size, DL, Ptr, SetTagFunc, SetTagZeroFunc, StgpFunc);
433 bool LittleEndian =
435 // Current implementation of initializer merging assumes little endianness.
436 if (MergeInit && !F->hasOptNone() && LittleEndian &&
438 LLVM_DEBUG(dbgs() << "collecting initializers for " << *AI
439 << ", size = " << Size << "\n");
440 InsertBefore = collectInitializers(InsertBefore, Ptr, Size, IB);
441 }
442
443 IRBuilder<> IRB(InsertBefore);
444 IB.generate(IRB);
445}
446
447void AArch64StackTagging::untagAlloca(AllocaInst *AI, Instruction *InsertBefore,
448 uint64_t Size) {
449 IRBuilder<> IRB(InsertBefore);
450 IRB.CreateCall(SetTagFunc, {IRB.CreatePointerCast(AI, IRB.getPtrTy()),
451 ConstantInt::get(IRB.getInt64Ty(), Size)});
452}
453
454Instruction *AArch64StackTagging::insertBaseTaggedPointer(
455 const Module &M,
456 const MapVector<AllocaInst *, memtag::AllocaInfo> &AllocasToInstrument,
457 const DominatorTree *DT) {
458 BasicBlock *PrologueBB = nullptr;
459 // Try sinking IRG as deep as possible to avoid hurting shrink wrap.
460 for (auto &I : AllocasToInstrument) {
461 const memtag::AllocaInfo &Info = I.second;
462 AllocaInst *AI = Info.AI;
463 if (!PrologueBB) {
464 PrologueBB = AI->getParent();
465 continue;
466 }
467 PrologueBB = DT->findNearestCommonDominator(PrologueBB, AI->getParent());
468 }
469 assert(PrologueBB);
470
471 IRBuilder<> IRB(&PrologueBB->front());
473 IRB.CreateIntrinsic(Intrinsic::aarch64_irg_sp, {},
475 Base->setName("basetag");
476 auto TargetTriple = Triple(M.getTargetTriple());
477 // This ABI will make it into Android API level 35.
478 // The ThreadLong format is the same as with HWASan, but the entries for
479 // stack MTE take two slots (16 bytes).
480 if (ClRecordStackHistory == instr && TargetTriple.isAndroid() &&
481 TargetTriple.isAArch64() && !TargetTriple.isAndroidVersionLT(35) &&
482 !AllocasToInstrument.empty()) {
483 constexpr int StackMteSlot = -3;
484 constexpr uint64_t TagMask = 0xFULL << 56;
485
486 auto *IntptrTy = IRB.getIntPtrTy(M.getDataLayout());
487 Value *SlotPtr = memtag::getAndroidSlotPtr(IRB, StackMteSlot);
488 auto *ThreadLong = IRB.CreateLoad(IntptrTy, SlotPtr);
489 Value *FP = memtag::getFP(IRB);
490 Value *Tag = IRB.CreateAnd(IRB.CreatePtrToInt(Base, IntptrTy), TagMask);
491 Value *TaggedFP = IRB.CreateOr(FP, Tag);
492 Value *PC = memtag::getPC(TargetTriple, IRB);
493 Value *RecordPtr = IRB.CreateIntToPtr(ThreadLong, IRB.getPtrTy(0));
494 IRB.CreateStore(PC, RecordPtr);
495 IRB.CreateStore(TaggedFP, IRB.CreateConstGEP1_64(IntptrTy, RecordPtr, 1));
496
497 IRB.CreateStore(memtag::incrementThreadLong(IRB, ThreadLong, 16), SlotPtr);
498 }
499 return Base;
500}
501
502// FIXME: check for MTE extension
503bool AArch64StackTagging::runOnFunction(Function &Fn) {
504 if (!Fn.hasFnAttribute(Attribute::SanitizeMemTag))
505 return false;
506
507 if (UseStackSafety)
508 SSI = &getAnalysis<StackSafetyGlobalInfoWrapperPass>().getResult();
509 F = &Fn;
510 DL = &Fn.getDataLayout();
511 if (MergeInit)
512 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
514 getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
515
517 for (Instruction &I : instructions(F))
518 SIB.visit(ORE, I);
519 memtag::StackInfo &SInfo = SIB.get();
520
521 if (SInfo.AllocasToInstrument.empty())
522 return false;
523
524 std::unique_ptr<DominatorTree> DeleteDT;
525 DominatorTree *DT = nullptr;
526 if (auto *P = getAnalysisIfAvailable<DominatorTreeWrapperPass>())
527 DT = &P->getDomTree();
528
529 if (DT == nullptr) {
530 DeleteDT = std::make_unique<DominatorTree>(*F);
531 DT = DeleteDT.get();
532 }
533
534 std::unique_ptr<PostDominatorTree> DeletePDT;
535 PostDominatorTree *PDT = nullptr;
536 if (auto *P = getAnalysisIfAvailable<PostDominatorTreeWrapperPass>())
537 PDT = &P->getPostDomTree();
538
539 if (PDT == nullptr) {
540 DeletePDT = std::make_unique<PostDominatorTree>(*F);
541 PDT = DeletePDT.get();
542 }
543
544 std::unique_ptr<LoopInfo> DeleteLI;
545 LoopInfo *LI = nullptr;
546 if (auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>()) {
547 LI = &LIWP->getLoopInfo();
548 } else {
549 DeleteLI = std::make_unique<LoopInfo>(*DT);
550 LI = DeleteLI.get();
551 }
552
553 SetTagFunc = Intrinsic::getOrInsertDeclaration(F->getParent(),
554 Intrinsic::aarch64_settag);
555
557 insertBaseTaggedPointer(*Fn.getParent(), SInfo.AllocasToInstrument, DT);
558
559 unsigned int NextTag = 0;
560 for (auto &I : SInfo.AllocasToInstrument) {
561 memtag::AllocaInfo &Info = I.second;
562 assert(Info.AI && SIB.getAllocaInterestingness(*Info.AI) ==
565 AllocaInst *AI = Info.AI;
566 unsigned int Tag = NextTag;
567 NextTag = (NextTag + 1) % 16;
568 // Replace alloca with tagp(alloca).
569 IRBuilder<> IRB(Info.AI->getNextNode());
570 Instruction *TagPCall =
571 IRB.CreateIntrinsic(Intrinsic::aarch64_tagp, {Info.AI->getType()},
572 {Constant::getNullValue(Info.AI->getType()), Base,
573 ConstantInt::get(IRB.getInt64Ty(), Tag)});
574 if (Info.AI->hasName())
575 TagPCall->setName(Info.AI->getName() + ".tag");
576 // Does not replace metadata, so we don't have to handle DbgVariableRecords.
577 Info.AI->replaceUsesWithIf(TagPCall, [&](const Use &U) {
578 return !memtag::isLifetimeIntrinsic(U.getUser());
579 });
580 TagPCall->setOperand(0, Info.AI);
581
582 // Calls to functions that may return twice (e.g. setjmp) confuse the
583 // postdominator analysis, and will leave us to keep memory tagged after
584 // function return. Work around this by always untagging at every return
585 // statement if return_twice functions are called.
586 bool StandardLifetime =
587 !SInfo.CallsReturnTwice &&
588 SInfo.UnrecognizedLifetimes.empty() &&
589 memtag::isStandardLifetime(Info.LifetimeStart, Info.LifetimeEnd, DT, LI,
591 if (StandardLifetime) {
592 IntrinsicInst *Start = Info.LifetimeStart[0];
593 uint64_t Size =
594 cast<ConstantInt>(Start->getArgOperand(0))->getZExtValue();
596 tagAlloca(AI, Start->getNextNode(), TagPCall, Size);
597
598 auto TagEnd = [&](Instruction *Node) { untagAlloca(AI, Node, Size); };
599 if (!DT || !PDT ||
600 !memtag::forAllReachableExits(*DT, *PDT, *LI, Start, Info.LifetimeEnd,
601 SInfo.RetVec, TagEnd)) {
602 for (auto *End : Info.LifetimeEnd)
603 End->eraseFromParent();
604 }
605 } else {
606 uint64_t Size = *Info.AI->getAllocationSize(*DL);
607 Value *Ptr = IRB.CreatePointerCast(TagPCall, IRB.getPtrTy());
608 tagAlloca(AI, &*IRB.GetInsertPoint(), Ptr, Size);
609 for (auto *RI : SInfo.RetVec) {
610 untagAlloca(AI, RI, Size);
611 }
612 // We may have inserted tag/untag outside of any lifetime interval.
613 // Remove all lifetime intrinsics for this alloca.
614 for (auto *II : Info.LifetimeStart)
615 II->eraseFromParent();
616 for (auto *II : Info.LifetimeEnd)
617 II->eraseFromParent();
618 }
619
621 }
622
623 // If we have instrumented at least one alloca, all unrecognized lifetime
624 // intrinsics have to go.
625 for (auto *I : SInfo.UnrecognizedLifetimes)
626 I->eraseFromParent();
627
628 return true;
629}
static cl::opt< bool > ClMergeInit("stack-tagging-merge-init", cl::Hidden, cl::init(true), cl::desc("merge stack variable initializers with tagging when possible"))
StackTaggingRecordStackHistoryMode
static cl::opt< unsigned > ClMergeInitSizeLimit("stack-tagging-merge-init-size-limit", cl::init(272), cl::Hidden)
static cl::opt< unsigned > ClScanLimit("stack-tagging-merge-init-scan-limit", cl::init(40), cl::Hidden)
static cl::opt< bool > ClUseStackSafety("stack-tagging-use-stack-safety", cl::Hidden, cl::init(true), cl::desc("Use Stack Safety analysis results"))
static cl::opt< size_t > ClMaxLifetimes("stack-tagging-max-lifetimes-for-alloca", cl::Hidden, cl::init(3), cl::ReallyHidden, cl::desc("How many lifetime ends to handle for a single alloca."), cl::Optional)
AArch64 Stack Tagging
#define DEBUG_TYPE
static const Align kTagGranuleSize
static cl::opt< StackTaggingRecordStackHistoryMode > ClRecordStackHistory("stack-tagging-record-stack-history", cl::desc("Record stack frames with tagged allocations in a thread-local " "ring buffer"), cl::values(clEnumVal(none, "Do not record stack ring history"), clEnumVal(instr, "Insert instructions into the prologue for " "storing into the stack ring buffer")), cl::Hidden, cl::init(none))
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< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
Analysis containing CSE Info
Definition: CSEInfo.cpp:27
#define clEnumVal(ENUMVAL, DESC)
Definition: CommandLine.h:684
#define LLVM_DEBUG(...)
Definition: Debug.h:106
This file contains constants used for implementing Dwarf debug support.
uint64_t Size
bool End
Definition: ELF_riscv.cpp:480
This header defines various interfaces for pass management in LLVM.
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
This file implements a map that provides insertion order iteration.
static void addRange(SmallVectorImpl< ConstantInt * > &EndPoints, ConstantInt *Low, ConstantInt *High)
Definition: Metadata.cpp:1274
This file contains the declarations for metadata subclasses.
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:55
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:57
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:52
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static unsigned getNumElements(Type *Ty)
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
Value * RHS
Value * LHS
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.
an instruction to allocate memory on the stack
Definition: Instructions.h:63
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:256
LLVM Basic Block Representation.
Definition: BasicBlock.h:61
const Instruction & front() const
Definition: BasicBlock.h:471
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:177
This is the shared class of boolean and integer constants.
Definition: Constants.h:83
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Definition: Constants.cpp:373
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:63
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:162
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...
Definition: Dominators.cpp:344
static FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition: Type.cpp:791
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:310
virtual bool runOnFunction(Function &F)=0
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
const DataLayout & getDataLayout() const
Get the data layout of the module this function belongs to.
Definition: Function.cpp:373
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition: Function.cpp:731
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:656
Value * CreateConstGEP1_64(Type *Ty, Value *Ptr, uint64_t Idx0, const Twine &Name="")
Definition: IRBuilder.h:1949
Value * CreateConstGEP1_32(Type *Ty, Value *Ptr, unsigned Idx0, const Twine &Name="")
Definition: IRBuilder.h:1902
IntegerType * getIntNTy(unsigned N)
Fetch the type representing an N-bit integer.
Definition: IRBuilder.h:536
Value * CreateZExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a ZExt or Trunc from the integer value V to DestTy.
Definition: IRBuilder.h:2066
Value * CreatePointerCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2201
CallInst * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > Types, ArrayRef< Value * > Args, Instruction *FMFSource=nullptr, const Twine &Name="")
Create a call to intrinsic ID with Args, mangled using Types.
Definition: IRBuilder.cpp:890
BasicBlock::iterator GetInsertPoint() const
Definition: IRBuilder.h:172
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2150
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition: IRBuilder.h:1460
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:572
IntegerType * getInt64Ty()
Fetch the type representing a 64-bit integer.
Definition: IRBuilder.h:528
Value * CreateBitOrPointerCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2236
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
Definition: IRBuilder.h:1813
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1439
LLVMContext & getContext() const
Definition: IRBuilder.h:173
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1498
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition: IRBuilder.h:1826
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2145
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args={}, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:2444
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1520
PointerType * getPtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer.
Definition: IRBuilder.h:566
IntegerType * getInt8Ty()
Fetch the type representing an 8-bit integer.
Definition: IRBuilder.h:513
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2697
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Definition: Instruction.cpp:66
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition: Type.cpp:311
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:48
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
This class implements a map that also provides access to all stored values in a deterministic order.
Definition: MapVector.h:36
Value * getLength() const
Value * getDest() const
This is just like getRawDest, but it strips off any cast instructions (including addrspacecast) that ...
bool isVolatile() const
Value * getValue() const
This class wraps the llvm.memset and llvm.memset.inline intrinsics.
Representation for a specific memory location.
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
Definition: Module.h:298
OptimizationRemarkEmitter legacy analysis pass.
The optimization diagnostic interface.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition: Pass.cpp:98
virtual StringRef getPassName() const
getPassName - Return a nice clean name for a pass.
Definition: Pass.cpp:81
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1196
This pass performs the global (interprocedural) stack safety analysis (legacy pass manager).
An instruction for storing to memory.
Definition: Instructions.h:292
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:51
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
bool isLittleEndian() const
Tests whether the target triple is little endian.
Definition: Triple.cpp:1954
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
bool isPointerTy() const
True if this is an instance of PointerType.
Definition: Type.h:264
A Use represents the edge between a Value definition and its users.
Definition: Use.h:43
void setOperand(unsigned i, Value *Val)
Definition: User.h:233
LLVM Value Representation.
Definition: Value.h:74
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:377
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.
Definition: Value.cpp:1028
const ParentTy * getParent() const
Definition: ilist_node.h:32
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > Tys={})
Look up the Function declaration of the intrinsic id in the Module M.
Definition: Intrinsics.cpp:731
@ ReallyHidden
Definition: CommandLine.h:138
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
Definition: CommandLine.h:711
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
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)
Value * getAndroidSlotPtr(IRBuilder<> &IRB, int Slot)
Value * incrementThreadLong(IRBuilder<> &IRB, Value *ThreadLong, unsigned int Inc)
void annotateDebugRecords(AllocaInfo &Info, unsigned int Tag)
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
@ Offset
Definition: DWP.cpp:480
void initializeAArch64StackTaggingPass(PassRegistry &)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
auto lower_bound(R &&Range, T &&Value)
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1978
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition: Alignment.h:155
FunctionPass * createAArch64StackTaggingPass(bool IsOptNone)
bool isNoModRef(const ModRefInfo MRI)
Definition: ModRef.h:39
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
MapVector< AllocaInst *, AllocaInfo > AllocasToInstrument
SmallVector< Instruction *, 4 > UnrecognizedLifetimes
SmallVector< Instruction *, 8 > RetVec