LLVM 22.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
50using namespace llvm;
51
52#define DEBUG_TYPE "aarch64-stack-tagging"
53
55 "stack-tagging-merge-init", cl::Hidden, cl::init(true),
56 cl::desc("merge stack variable initializers with tagging when possible"));
57
58static cl::opt<bool>
59 ClUseStackSafety("stack-tagging-use-stack-safety", cl::Hidden,
60 cl::init(true),
61 cl::desc("Use Stack Safety analysis results"));
62
63static cl::opt<unsigned> ClScanLimit("stack-tagging-merge-init-scan-limit",
64 cl::init(40), cl::Hidden);
65
67 ClMergeInitSizeLimit("stack-tagging-merge-init-size-limit", cl::init(272),
69
71 "stack-tagging-max-lifetimes-for-alloca", cl::Hidden, cl::init(3),
73 cl::desc("How many lifetime ends to handle for a single alloca."),
75
76// Mode for selecting how to insert frame record info into the stack ring
77// buffer.
79 // Do not record frame record info.
81
82 // Insert instructions into the prologue for storing into the stack ring
83 // buffer directly.
85};
86
88 "stack-tagging-record-stack-history",
89 cl::desc("Record stack frames with tagged allocations in a thread-local "
90 "ring buffer"),
91 cl::values(clEnumVal(none, "Do not record stack ring history"),
92 clEnumVal(instr, "Insert instructions into the prologue for "
93 "storing into the stack ring buffer")),
95
96static const Align kTagGranuleSize = Align(16);
97
98namespace {
99
100class InitializerBuilder {
102 const DataLayout *DL;
103 Value *BasePtr;
104 Function *SetTagFn;
105 Function *SetTagZeroFn;
106 Function *StgpFn;
107
108 // List of initializers sorted by start offset.
109 struct Range {
110 uint64_t Start, End;
111 Instruction *Inst;
112 };
114 // 8-aligned offset => 8-byte initializer
115 // Missing keys are zero initialized.
116 std::map<uint64_t, Value *> Out;
117
118public:
119 InitializerBuilder(uint64_t Size, const DataLayout *DL, Value *BasePtr,
120 Function *SetTagFn, Function *SetTagZeroFn,
121 Function *StgpFn)
122 : Size(Size), DL(DL), BasePtr(BasePtr), SetTagFn(SetTagFn),
123 SetTagZeroFn(SetTagZeroFn), StgpFn(StgpFn) {}
124
125 bool addRange(uint64_t Start, uint64_t End, Instruction *Inst) {
126 auto I =
127 llvm::lower_bound(Ranges, Start, [](const Range &LHS, uint64_t RHS) {
128 return LHS.End <= RHS;
129 });
130 if (I != Ranges.end() && End > I->Start) {
131 // Overlap - bail.
132 return false;
133 }
134 Ranges.insert(I, {Start, End, Inst});
135 return true;
136 }
137
138 bool addStore(uint64_t Offset, StoreInst *SI, const DataLayout *DL) {
139 int64_t StoreSize = DL->getTypeStoreSize(SI->getOperand(0)->getType());
140 if (!addRange(Offset, Offset + StoreSize, SI))
141 return false;
142 IRBuilder<> IRB(SI);
143 applyStore(IRB, Offset, Offset + StoreSize, SI->getOperand(0));
144 return true;
145 }
146
147 bool addMemSet(uint64_t Offset, MemSetInst *MSI) {
148 uint64_t StoreSize = cast<ConstantInt>(MSI->getLength())->getZExtValue();
149 if (!addRange(Offset, Offset + StoreSize, MSI))
150 return false;
151 IRBuilder<> IRB(MSI);
152 applyMemSet(IRB, Offset, Offset + StoreSize,
154 return true;
155 }
156
157 void applyMemSet(IRBuilder<> &IRB, int64_t Start, int64_t End,
158 ConstantInt *V) {
159 // Out[] does not distinguish between zero and undef, and we already know
160 // that this memset does not overlap with any other initializer. Nothing to
161 // do for memset(0).
162 if (V->isZero())
163 return;
164 for (int64_t Offset = Start - Start % 8; Offset < End; Offset += 8) {
165 uint64_t Cst = 0x0101010101010101UL;
166 int LowBits = Offset < Start ? (Start - Offset) * 8 : 0;
167 if (LowBits)
168 Cst = (Cst >> LowBits) << LowBits;
169 int HighBits = End - Offset < 8 ? (8 - (End - Offset)) * 8 : 0;
170 if (HighBits)
171 Cst = (Cst << HighBits) >> HighBits;
172 ConstantInt *C =
173 ConstantInt::get(IRB.getInt64Ty(), Cst * V->getZExtValue());
174
175 Value *&CurrentV = Out[Offset];
176 if (!CurrentV) {
177 CurrentV = C;
178 } else {
179 CurrentV = IRB.CreateOr(CurrentV, C);
180 }
181 }
182 }
183
184 // Take a 64-bit slice of the value starting at the given offset (in bytes).
185 // Offset can be negative. Pad with zeroes on both sides when necessary.
186 Value *sliceValue(IRBuilder<> &IRB, Value *V, int64_t Offset) {
187 if (Offset > 0) {
188 V = IRB.CreateLShr(V, Offset * 8);
189 V = IRB.CreateZExtOrTrunc(V, IRB.getInt64Ty());
190 } else if (Offset < 0) {
191 V = IRB.CreateZExtOrTrunc(V, IRB.getInt64Ty());
192 V = IRB.CreateShl(V, -Offset * 8);
193 } else {
194 V = IRB.CreateZExtOrTrunc(V, IRB.getInt64Ty());
195 }
196 return V;
197 }
198
199 void applyStore(IRBuilder<> &IRB, int64_t Start, int64_t End,
200 Value *StoredValue) {
201 StoredValue = flatten(IRB, StoredValue);
202 for (int64_t Offset = Start - Start % 8; Offset < End; Offset += 8) {
203 Value *V = sliceValue(IRB, StoredValue, Offset - Start);
204 Value *&CurrentV = Out[Offset];
205 if (!CurrentV) {
206 CurrentV = V;
207 } else {
208 CurrentV = IRB.CreateOr(CurrentV, V);
209 }
210 }
211 }
212
213 void generate(IRBuilder<> &IRB) {
214 LLVM_DEBUG(dbgs() << "Combined initializer\n");
215 // No initializers => the entire allocation is undef.
216 if (Ranges.empty()) {
217 emitUndef(IRB, 0, Size);
218 return;
219 }
220
221 // Look through 8-byte initializer list 16 bytes at a time;
222 // If one of the two 8-byte halfs is non-zero non-undef, emit STGP.
223 // Otherwise, emit zeroes up to next available item.
224 uint64_t LastOffset = 0;
225 for (uint64_t Offset = 0; Offset < Size; Offset += 16) {
226 auto I1 = Out.find(Offset);
227 auto I2 = Out.find(Offset + 8);
228 if (I1 == Out.end() && I2 == Out.end())
229 continue;
230
231 if (Offset > LastOffset)
232 emitZeroes(IRB, LastOffset, Offset - LastOffset);
233
234 Value *Store1 = I1 == Out.end() ? Constant::getNullValue(IRB.getInt64Ty())
235 : I1->second;
236 Value *Store2 = I2 == Out.end() ? Constant::getNullValue(IRB.getInt64Ty())
237 : I2->second;
238 emitPair(IRB, Offset, Store1, Store2);
239 LastOffset = Offset + 16;
240 }
241
242 // memset(0) does not update Out[], therefore the tail can be either undef
243 // or zero.
244 if (LastOffset < Size)
245 emitZeroes(IRB, LastOffset, Size - LastOffset);
246
247 for (const auto &R : Ranges) {
248 R.Inst->eraseFromParent();
249 }
250 }
251
252 void emitZeroes(IRBuilder<> &IRB, uint64_t Offset, uint64_t Size) {
253 LLVM_DEBUG(dbgs() << " [" << Offset << ", " << Offset + Size
254 << ") zero\n");
255 Value *Ptr = BasePtr;
256 if (Offset)
258 IRB.CreateCall(SetTagZeroFn,
259 {Ptr, ConstantInt::get(IRB.getInt64Ty(), Size)});
260 }
261
262 void emitUndef(IRBuilder<> &IRB, uint64_t Offset, uint64_t Size) {
263 LLVM_DEBUG(dbgs() << " [" << Offset << ", " << Offset + Size
264 << ") undef\n");
265 Value *Ptr = BasePtr;
266 if (Offset)
268 IRB.CreateCall(SetTagFn, {Ptr, ConstantInt::get(IRB.getInt64Ty(), Size)});
269 }
270
271 void emitPair(IRBuilder<> &IRB, uint64_t Offset, Value *A, Value *B) {
272 LLVM_DEBUG(dbgs() << " [" << Offset << ", " << Offset + 16 << "):\n");
273 LLVM_DEBUG(dbgs() << " " << *A << "\n " << *B << "\n");
274 Value *Ptr = BasePtr;
275 if (Offset)
277 IRB.CreateCall(StgpFn, {Ptr, A, B});
278 }
279
280 Value *flatten(IRBuilder<> &IRB, Value *V) {
281 if (V->getType()->isIntegerTy())
282 return V;
283 // vector of pointers -> vector of ints
284 if (VectorType *VecTy = dyn_cast<VectorType>(V->getType())) {
285 LLVMContext &Ctx = IRB.getContext();
286 Type *EltTy = VecTy->getElementType();
287 if (EltTy->isPointerTy()) {
288 uint32_t EltSize = DL->getTypeSizeInBits(EltTy);
289 auto *NewTy = FixedVectorType::get(
290 IntegerType::get(Ctx, EltSize),
292 V = IRB.CreatePointerCast(V, NewTy);
293 }
294 }
295 return IRB.CreateBitOrPointerCast(
296 V, IRB.getIntNTy(DL->getTypeStoreSize(V->getType()) * 8));
297 }
298};
299
300class AArch64StackTagging : public FunctionPass {
301 const bool MergeInit;
302 const bool UseStackSafety;
303
304public:
305 static char ID; // Pass ID, replacement for typeid
306
307 AArch64StackTagging(bool IsOptNone = false)
308 : FunctionPass(ID),
309 MergeInit(ClMergeInit.getNumOccurrences() ? ClMergeInit : !IsOptNone),
310 UseStackSafety(ClUseStackSafety.getNumOccurrences() ? ClUseStackSafety
311 : !IsOptNone) {}
312
313 void tagAlloca(AllocaInst *AI, Instruction *InsertBefore, Value *Ptr,
314 uint64_t Size);
315 void untagAlloca(AllocaInst *AI, Instruction *InsertBefore, uint64_t Size);
316
317 Instruction *collectInitializers(Instruction *StartInst, Value *StartPtr,
318 uint64_t Size, InitializerBuilder &IB);
319
320 Instruction *insertBaseTaggedPointer(
321 const Module &M,
322 const MapVector<AllocaInst *, memtag::AllocaInfo> &Allocas,
323 const DominatorTree *DT);
324 bool runOnFunction(Function &F) override;
325
326 StringRef getPassName() const override { return "AArch64 Stack Tagging"; }
327
328private:
329 Function *F = nullptr;
330 Function *SetTagFunc = nullptr;
331 const DataLayout *DL = nullptr;
332 AAResults *AA = nullptr;
333 const StackSafetyGlobalInfo *SSI = nullptr;
334
335 void getAnalysisUsage(AnalysisUsage &AU) const override {
336 AU.setPreservesCFG();
337 if (UseStackSafety)
338 AU.addRequired<StackSafetyGlobalInfoWrapperPass>();
339 if (MergeInit)
340 AU.addRequired<AAResultsWrapperPass>();
341 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
342 }
343};
344
345} // end anonymous namespace
346
347char AArch64StackTagging::ID = 0;
348
349INITIALIZE_PASS_BEGIN(AArch64StackTagging, DEBUG_TYPE, "AArch64 Stack Tagging",
350 false, false)
354INITIALIZE_PASS_END(AArch64StackTagging, DEBUG_TYPE, "AArch64 Stack Tagging",
356
358 return new AArch64StackTagging(IsOptNone);
359}
360
361Instruction *AArch64StackTagging::collectInitializers(Instruction *StartInst,
362 Value *StartPtr,
364 InitializerBuilder &IB) {
365 MemoryLocation AllocaLoc{StartPtr, Size};
366 Instruction *LastInst = StartInst;
367 BasicBlock::iterator BI(StartInst);
368
369 unsigned Count = 0;
370 for (; Count < ClScanLimit && !BI->isTerminator(); ++BI) {
371 ++Count;
372
373 if (isNoModRef(AA->getModRefInfo(&*BI, AllocaLoc)))
374 continue;
375
376 if (!isa<StoreInst>(BI) && !isa<MemSetInst>(BI)) {
377 // If the instruction is readnone, ignore it, otherwise bail out. We
378 // don't even allow readonly here because we don't want something like:
379 // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
380 if (BI->mayWriteToMemory() || BI->mayReadFromMemory())
381 break;
382 continue;
383 }
384
385 if (StoreInst *NextStore = dyn_cast<StoreInst>(BI)) {
386 if (!NextStore->isSimple())
387 break;
388
389 // Check to see if this store is to a constant offset from the start ptr.
390 std::optional<int64_t> Offset =
391 NextStore->getPointerOperand()->getPointerOffsetFrom(StartPtr, *DL);
392 if (!Offset)
393 break;
394
395 if (!IB.addStore(*Offset, NextStore, DL))
396 break;
397 LastInst = NextStore;
398 } else {
399 MemSetInst *MSI = cast<MemSetInst>(BI);
400
401 if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength()))
402 break;
403
404 if (!isa<ConstantInt>(MSI->getValue()))
405 break;
406
407 // Check to see if this store is to a constant offset from the start ptr.
408 std::optional<int64_t> Offset =
409 MSI->getDest()->getPointerOffsetFrom(StartPtr, *DL);
410 if (!Offset)
411 break;
412
413 if (!IB.addMemSet(*Offset, MSI))
414 break;
415 LastInst = MSI;
416 }
417 }
418 return LastInst;
419}
420
421void AArch64StackTagging::tagAlloca(AllocaInst *AI, Instruction *InsertBefore,
422 Value *Ptr, uint64_t Size) {
423 auto SetTagZeroFunc = Intrinsic::getOrInsertDeclaration(
424 F->getParent(), Intrinsic::aarch64_settag_zero);
425 auto StgpFunc = Intrinsic::getOrInsertDeclaration(F->getParent(),
426 Intrinsic::aarch64_stgp);
427
428 InitializerBuilder IB(Size, DL, Ptr, SetTagFunc, SetTagZeroFunc, StgpFunc);
429 bool LittleEndian = AI->getModule()->getTargetTriple().isLittleEndian();
430 // Current implementation of initializer merging assumes little endianness.
431 if (MergeInit && !F->hasOptNone() && LittleEndian &&
433 LLVM_DEBUG(dbgs() << "collecting initializers for " << *AI
434 << ", size = " << Size << "\n");
435 InsertBefore = collectInitializers(InsertBefore, Ptr, Size, IB);
436 }
437
438 IRBuilder<> IRB(InsertBefore);
439 IB.generate(IRB);
440}
441
442void AArch64StackTagging::untagAlloca(AllocaInst *AI, Instruction *InsertBefore,
443 uint64_t Size) {
444 IRBuilder<> IRB(InsertBefore);
445 IRB.CreateCall(SetTagFunc, {IRB.CreatePointerCast(AI, IRB.getPtrTy()),
446 ConstantInt::get(IRB.getInt64Ty(), Size)});
447}
448
449Instruction *AArch64StackTagging::insertBaseTaggedPointer(
450 const Module &M,
451 const MapVector<AllocaInst *, memtag::AllocaInfo> &AllocasToInstrument,
452 const DominatorTree *DT) {
453 BasicBlock *PrologueBB = nullptr;
454 // Try sinking IRG as deep as possible to avoid hurting shrink wrap.
455 for (auto &I : AllocasToInstrument) {
456 const memtag::AllocaInfo &Info = I.second;
457 AllocaInst *AI = Info.AI;
458 if (!PrologueBB) {
459 PrologueBB = AI->getParent();
460 continue;
461 }
462 PrologueBB = DT->findNearestCommonDominator(PrologueBB, AI->getParent());
463 }
464 assert(PrologueBB);
465
466 IRBuilder<> IRB(&PrologueBB->front());
468 IRB.CreateIntrinsic(Intrinsic::aarch64_irg_sp, {},
470 Base->setName("basetag");
471 const Triple &TargetTriple = M.getTargetTriple();
472 // This ABI will make it into Android API level 35.
473 // The ThreadLong format is the same as with HWASan, but the entries for
474 // stack MTE take two slots (16 bytes).
475 if (ClRecordStackHistory == instr && TargetTriple.isAndroid() &&
476 TargetTriple.isAArch64() && !TargetTriple.isAndroidVersionLT(35) &&
477 !AllocasToInstrument.empty()) {
478 constexpr int StackMteSlot = -3;
479 constexpr uint64_t TagMask = 0xFULL << 56;
480
481 auto *IntptrTy = IRB.getIntPtrTy(M.getDataLayout());
482 Value *SlotPtr = memtag::getAndroidSlotPtr(IRB, StackMteSlot);
483 auto *ThreadLong = IRB.CreateLoad(IntptrTy, SlotPtr);
484 Value *FP = memtag::getFP(IRB);
485 Value *Tag = IRB.CreateAnd(IRB.CreatePtrToInt(Base, IntptrTy), TagMask);
486 Value *TaggedFP = IRB.CreateOr(FP, Tag);
487 Value *PC = memtag::getPC(TargetTriple, IRB);
488 Value *RecordPtr = IRB.CreateIntToPtr(ThreadLong, IRB.getPtrTy(0));
489 IRB.CreateStore(PC, RecordPtr);
490 IRB.CreateStore(TaggedFP, IRB.CreateConstGEP1_64(IntptrTy, RecordPtr, 1));
491
492 IRB.CreateStore(memtag::incrementThreadLong(IRB, ThreadLong, 16), SlotPtr);
493 }
494 return Base;
495}
496
497// FIXME: check for MTE extension
498bool AArch64StackTagging::runOnFunction(Function &Fn) {
499 if (!Fn.hasFnAttribute(Attribute::SanitizeMemTag))
500 return false;
501
502 if (UseStackSafety)
503 SSI = &getAnalysis<StackSafetyGlobalInfoWrapperPass>().getResult();
504 F = &Fn;
505 DL = &Fn.getDataLayout();
506 if (MergeInit)
507 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
508 OptimizationRemarkEmitter &ORE =
509 getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
510
511 memtag::StackInfoBuilder SIB(SSI, DEBUG_TYPE);
512 for (Instruction &I : instructions(F))
513 SIB.visit(ORE, I);
514 memtag::StackInfo &SInfo = SIB.get();
515
516 if (SInfo.AllocasToInstrument.empty())
517 return false;
518
519 std::unique_ptr<DominatorTree> DeleteDT;
520 DominatorTree *DT = nullptr;
521 if (auto *P = getAnalysisIfAvailable<DominatorTreeWrapperPass>())
522 DT = &P->getDomTree();
523
524 if (DT == nullptr) {
525 DeleteDT = std::make_unique<DominatorTree>(*F);
526 DT = DeleteDT.get();
527 }
528
529 std::unique_ptr<PostDominatorTree> DeletePDT;
530 PostDominatorTree *PDT = nullptr;
531 if (auto *P = getAnalysisIfAvailable<PostDominatorTreeWrapperPass>())
532 PDT = &P->getPostDomTree();
533
534 if (PDT == nullptr) {
535 DeletePDT = std::make_unique<PostDominatorTree>(*F);
536 PDT = DeletePDT.get();
537 }
538
539 std::unique_ptr<LoopInfo> DeleteLI;
540 LoopInfo *LI = nullptr;
541 if (auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>()) {
542 LI = &LIWP->getLoopInfo();
543 } else {
544 DeleteLI = std::make_unique<LoopInfo>(*DT);
545 LI = DeleteLI.get();
546 }
547
548 SetTagFunc = Intrinsic::getOrInsertDeclaration(F->getParent(),
549 Intrinsic::aarch64_settag);
550
552 insertBaseTaggedPointer(*Fn.getParent(), SInfo.AllocasToInstrument, DT);
553
554 unsigned int NextTag = 0;
555 for (auto &I : SInfo.AllocasToInstrument) {
556 memtag::AllocaInfo &Info = I.second;
557 assert(Info.AI && SIB.getAllocaInterestingness(*Info.AI) ==
560 AllocaInst *AI = Info.AI;
561 unsigned int Tag = NextTag;
562 NextTag = (NextTag + 1) % 16;
563 // Replace alloca with tagp(alloca).
564 IRBuilder<> IRB(Info.AI->getNextNode());
565 Instruction *TagPCall =
566 IRB.CreateIntrinsic(Intrinsic::aarch64_tagp, {Info.AI->getType()},
567 {Constant::getNullValue(Info.AI->getType()), Base,
568 ConstantInt::get(IRB.getInt64Ty(), Tag)});
569 if (Info.AI->hasName())
570 TagPCall->setName(Info.AI->getName() + ".tag");
571 // Does not replace metadata, so we don't have to handle DbgVariableRecords.
572 Info.AI->replaceUsesWithIf(TagPCall, [&](const Use &U) {
573 return !isa<LifetimeIntrinsic>(U.getUser());
574 });
575 TagPCall->setOperand(0, Info.AI);
576
577 // Calls to functions that may return twice (e.g. setjmp) confuse the
578 // postdominator analysis, and will leave us to keep memory tagged after
579 // function return. Work around this by always untagging at every return
580 // statement if return_twice functions are called.
581 bool StandardLifetime =
582 !SInfo.CallsReturnTwice &&
583 memtag::isStandardLifetime(Info.LifetimeStart, Info.LifetimeEnd, DT, LI,
585 if (StandardLifetime) {
586 IntrinsicInst *Start = Info.LifetimeStart[0];
587 uint64_t Size = *Info.AI->getAllocationSize(*DL);
589 tagAlloca(AI, Start->getNextNode(), TagPCall, Size);
590
591 auto TagEnd = [&](Instruction *Node) { untagAlloca(AI, Node, Size); };
592 if (!DT || !PDT ||
593 !memtag::forAllReachableExits(*DT, *PDT, *LI, Start, Info.LifetimeEnd,
594 SInfo.RetVec, TagEnd)) {
595 for (auto *End : Info.LifetimeEnd)
596 End->eraseFromParent();
597 }
598 } else {
599 uint64_t Size = *Info.AI->getAllocationSize(*DL);
600 Value *Ptr = IRB.CreatePointerCast(TagPCall, IRB.getPtrTy());
601 tagAlloca(AI, &*IRB.GetInsertPoint(), Ptr, Size);
602 for (auto *RI : SInfo.RetVec) {
603 untagAlloca(AI, RI, Size);
604 }
605 // We may have inserted tag/untag outside of any lifetime interval.
606 // Remove all lifetime intrinsics for this alloca.
607 for (auto *II : Info.LifetimeStart)
608 II->eraseFromParent();
609 for (auto *II : Info.LifetimeEnd)
610 II->eraseFromParent();
611 }
612
614 }
615
616 return true;
617}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
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)
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< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Analysis containing CSE Info
Definition CSEInfo.cpp:27
#define clEnumVal(ENUMVAL, DESC)
This file contains constants used for implementing Dwarf debug support.
static bool runOnFunction(Function &F, bool PostInlining)
#define DEBUG_TYPE
This header defines various interfaces for pass management in LLVM.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
This file implements a map that provides insertion order iteration.
static void addRange(SmallVectorImpl< ConstantInt * > &EndPoints, ConstantInt *Low, ConstantInt *High)
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:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
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...
#define LLVM_DEBUG(...)
Definition Debug.h:114
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.
AnalysisUsage & addRequired()
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:270
const Instruction & front() const
Definition BasicBlock.h:482
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
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.
Definition DataLayout.h:63
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)
Definition Type.cpp:802
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
const DataLayout & getDataLayout() const
Get the data layout of the module this function belongs to.
Definition Function.cpp:363
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:730
Module * getParent()
Get the module that this global value is contained inside of...
Value * CreateConstGEP1_64(Type *Ty, Value *Ptr, uint64_t Idx0, const Twine &Name="")
Definition IRBuilder.h:1986
Value * CreateConstGEP1_32(Type *Ty, Value *Ptr, unsigned Idx0, const Twine &Name="")
Definition IRBuilder.h:1939
IntegerType * getIntNTy(unsigned N)
Fetch the type representing an N-bit integer.
Definition IRBuilder.h:575
Value * CreateZExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a ZExt or Trunc from the integer value V to DestTy.
Definition IRBuilder.h:2103
Value * CreatePointerCast(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2254
BasicBlock::iterator GetInsertPoint() const
Definition IRBuilder.h:202
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2202
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition IRBuilder.h:1513
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:611
IntegerType * getInt64Ty()
Fetch the type representing a 64-bit integer.
Definition IRBuilder.h:567
LLVM_ABI CallInst * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > Types, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="")
Create a call to intrinsic ID with Args, mangled using Types.
Value * CreateBitOrPointerCast(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2289
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:1850
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1492
LLVMContext & getContext() const
Definition IRBuilder.h:203
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:1551
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition IRBuilder.h:1863
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2197
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args={}, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2511
PointerType * getPtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer.
Definition IRBuilder.h:605
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Definition IRBuilder.h:1573
IntegerType * getInt8Ty()
Fetch the type representing an 8-bit integer.
Definition IRBuilder.h:552
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.
Definition Type.cpp:318
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
Representation for a specific memory location.
const Triple & getTargetTriple() const
Get the target triple which is a string describing the target host.
Definition Module.h:281
OptimizationRemarkEmitter legacy analysis pass.
This pass performs the global (interprocedural) stack safety analysis (legacy pass manager).
bool isAndroidVersionLT(unsigned Major) const
Definition Triple.h:843
bool isAndroid() const
Tests whether the target is Android.
Definition Triple.h:841
LLVM_ABI bool isLittleEndian() const
Tests whether the target triple is little endian.
Definition Triple.cpp:2082
bool isAArch64() const
Tests whether the target is AArch64 (little and big endian).
Definition Triple.h:1022
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:267
void setOperand(unsigned i, Value *Val)
Definition User.h:237
LLVM Value Representation.
Definition Value.h:75
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:390
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.
Definition Value.cpp:1052
const ParentTy * getParent() const
Definition ilist_node.h:34
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > Tys={})
Look up the Function declaration of the intrinsic id in the Module M.
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
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)
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:477
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
FunctionAddr VTableAddr Count
Definition InstrProf.h:139
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...
Definition Casting.h:547
IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *, ArrayRef< OperandBundleDef >) -> IRBuilder< FolderTy, InserterTy >
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:1994
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:144
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
FunctionPass * createAArch64StackTaggingPass(bool IsOptNone)
bool isNoModRef(const ModRefInfo MRI)
Definition ModRef.h:40
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 *, 8 > RetVec