LLVM 23.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"
40#include "llvm/IR/Value.h"
42#include "llvm/Pass.h"
44#include "llvm/Support/Debug.h"
48#include <cassert>
49#include <memory>
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
71// Mode for selecting how to insert frame record info into the stack ring
72// buffer.
74 // Do not record frame record info.
76
77 // Insert instructions into the prologue for storing into the stack ring
78 // buffer directly.
80};
81
83 "stack-tagging-record-stack-history",
84 cl::desc("Record stack frames with tagged allocations in a thread-local "
85 "ring buffer"),
86 cl::values(clEnumVal(none, "Do not record stack ring history"),
87 clEnumVal(instr, "Insert instructions into the prologue for "
88 "storing into the stack ring buffer")),
90
91static const Align kTagGranuleSize = Align(16);
92
93namespace {
94
95class InitializerBuilder {
97 const DataLayout *DL;
98 Value *BasePtr;
99 Function *SetTagFn;
100 Function *SetTagZeroFn;
101 Function *StgpFn;
102
103 // List of initializers sorted by start offset.
104 struct Range {
105 uint64_t Start, End;
106 Instruction *Inst;
107 };
109 // 8-aligned offset => 8-byte initializer
110 // Missing keys are zero initialized.
111 std::map<uint64_t, Value *> Out;
112
113public:
114 InitializerBuilder(uint64_t Size, const DataLayout *DL, Value *BasePtr,
115 Function *SetTagFn, Function *SetTagZeroFn,
116 Function *StgpFn)
117 : Size(Size), DL(DL), BasePtr(BasePtr), SetTagFn(SetTagFn),
118 SetTagZeroFn(SetTagZeroFn), StgpFn(StgpFn) {}
119
120 bool addRange(uint64_t Start, uint64_t End, Instruction *Inst) {
121 auto I =
122 llvm::lower_bound(Ranges, Start, [](const Range &LHS, uint64_t RHS) {
123 return LHS.End <= RHS;
124 });
125 if (I != Ranges.end() && End > I->Start) {
126 // Overlap - bail.
127 return false;
128 }
129 Ranges.insert(I, {Start, End, Inst});
130 return true;
131 }
132
133 bool addStore(uint64_t Offset, StoreInst *SI, const DataLayout *DL) {
134 int64_t StoreSize = DL->getTypeStoreSize(SI->getOperand(0)->getType());
135 if (!addRange(Offset, Offset + StoreSize, SI))
136 return false;
137 IRBuilder<> IRB(SI);
138 applyStore(IRB, Offset, Offset + StoreSize, SI->getOperand(0));
139 return true;
140 }
141
142 bool addMemSet(uint64_t Offset, MemSetInst *MSI) {
143 uint64_t StoreSize = cast<ConstantInt>(MSI->getLength())->getZExtValue();
144 if (!addRange(Offset, Offset + StoreSize, MSI))
145 return false;
146 IRBuilder<> IRB(MSI);
147 applyMemSet(IRB, Offset, Offset + StoreSize,
149 return true;
150 }
151
152 void applyMemSet(IRBuilder<> &IRB, int64_t Start, int64_t End,
153 ConstantInt *V) {
154 // Out[] does not distinguish between zero and undef, and we already know
155 // that this memset does not overlap with any other initializer. Nothing to
156 // do for memset(0).
157 if (V->isZero())
158 return;
159 for (int64_t Offset = Start - Start % 8; Offset < End; Offset += 8) {
160 uint64_t Cst = 0x0101010101010101UL;
161 int LowBits = Offset < Start ? (Start - Offset) * 8 : 0;
162 if (LowBits)
163 Cst = (Cst >> LowBits) << LowBits;
164 int HighBits = End - Offset < 8 ? (8 - (End - Offset)) * 8 : 0;
165 if (HighBits)
166 Cst = (Cst << HighBits) >> HighBits;
167 ConstantInt *C =
168 ConstantInt::get(IRB.getInt64Ty(), Cst * V->getZExtValue());
169
170 Value *&CurrentV = Out[Offset];
171 if (!CurrentV) {
172 CurrentV = C;
173 } else {
174 CurrentV = IRB.CreateOr(CurrentV, C);
175 }
176 }
177 }
178
179 // Take a 64-bit slice of the value starting at the given offset (in bytes).
180 // Offset can be negative. Pad with zeroes on both sides when necessary.
181 Value *sliceValue(IRBuilder<> &IRB, Value *V, int64_t Offset) {
182 if (Offset > 0) {
183 V = IRB.CreateLShr(V, Offset * 8);
184 V = IRB.CreateZExtOrTrunc(V, IRB.getInt64Ty());
185 } else if (Offset < 0) {
186 V = IRB.CreateZExtOrTrunc(V, IRB.getInt64Ty());
187 V = IRB.CreateShl(V, -Offset * 8);
188 } else {
189 V = IRB.CreateZExtOrTrunc(V, IRB.getInt64Ty());
190 }
191 return V;
192 }
193
194 void applyStore(IRBuilder<> &IRB, int64_t Start, int64_t End,
195 Value *StoredValue) {
196 StoredValue = flatten(IRB, StoredValue);
197 for (int64_t Offset = Start - Start % 8; Offset < End; Offset += 8) {
198 Value *V = sliceValue(IRB, StoredValue, Offset - Start);
199 Value *&CurrentV = Out[Offset];
200 if (!CurrentV) {
201 CurrentV = V;
202 } else {
203 CurrentV = IRB.CreateOr(CurrentV, V);
204 }
205 }
206 }
207
208 void generate(IRBuilder<> &IRB) {
209 LLVM_DEBUG(dbgs() << "Combined initializer\n");
210 // No initializers => the entire allocation is undef.
211 if (Ranges.empty()) {
212 emitUndef(IRB, 0, Size);
213 return;
214 }
215
216 // Look through 8-byte initializer list 16 bytes at a time;
217 // If one of the two 8-byte halfs is non-zero non-undef, emit STGP.
218 // Otherwise, emit zeroes up to next available item.
219 uint64_t LastOffset = 0;
220 for (uint64_t Offset = 0; Offset < Size; Offset += 16) {
221 auto I1 = Out.find(Offset);
222 auto I2 = Out.find(Offset + 8);
223 if (I1 == Out.end() && I2 == Out.end())
224 continue;
225
226 if (Offset > LastOffset)
227 emitZeroes(IRB, LastOffset, Offset - LastOffset);
228
229 Value *Store1 = I1 == Out.end() ? Constant::getNullValue(IRB.getInt64Ty())
230 : I1->second;
231 Value *Store2 = I2 == Out.end() ? Constant::getNullValue(IRB.getInt64Ty())
232 : I2->second;
233 emitPair(IRB, Offset, Store1, Store2);
234 LastOffset = Offset + 16;
235 }
236
237 // memset(0) does not update Out[], therefore the tail can be either undef
238 // or zero.
239 if (LastOffset < Size)
240 emitZeroes(IRB, LastOffset, Size - LastOffset);
241
242 for (const auto &R : Ranges) {
243 R.Inst->eraseFromParent();
244 }
245 }
246
247 void emitZeroes(IRBuilder<> &IRB, uint64_t Offset, uint64_t Size) {
248 LLVM_DEBUG(dbgs() << " [" << Offset << ", " << Offset + Size
249 << ") zero\n");
250 Value *Ptr = BasePtr;
251 if (Offset)
252 Ptr = IRB.CreateConstGEP1_32(IRB.getInt8Ty(), Ptr, Offset);
253 IRB.CreateCall(SetTagZeroFn,
254 {Ptr, ConstantInt::get(IRB.getInt64Ty(), Size)});
255 }
256
257 void emitUndef(IRBuilder<> &IRB, uint64_t Offset, uint64_t Size) {
258 LLVM_DEBUG(dbgs() << " [" << Offset << ", " << Offset + Size
259 << ") undef\n");
260 Value *Ptr = BasePtr;
261 if (Offset)
262 Ptr = IRB.CreateConstGEP1_32(IRB.getInt8Ty(), Ptr, Offset);
263 IRB.CreateCall(SetTagFn, {Ptr, ConstantInt::get(IRB.getInt64Ty(), Size)});
264 }
265
266 void emitPair(IRBuilder<> &IRB, uint64_t Offset, Value *A, Value *B) {
267 LLVM_DEBUG(dbgs() << " [" << Offset << ", " << Offset + 16 << "):\n");
268 LLVM_DEBUG(dbgs() << " " << *A << "\n " << *B << "\n");
269 Value *Ptr = BasePtr;
270 if (Offset)
271 Ptr = IRB.CreateConstGEP1_32(IRB.getInt8Ty(), Ptr, Offset);
272 IRB.CreateCall(StgpFn, {Ptr, A, B});
273 }
274
275 Value *flatten(IRBuilder<> &IRB, Value *V) {
276 if (V->getType()->isIntegerTy())
277 return V;
278 // vector of pointers -> vector of ints
279 if (VectorType *VecTy = dyn_cast<VectorType>(V->getType())) {
280 LLVMContext &Ctx = IRB.getContext();
281 Type *EltTy = VecTy->getElementType();
282 if (EltTy->isPointerTy()) {
283 uint32_t EltSize = DL->getTypeSizeInBits(EltTy);
284 auto *NewTy = FixedVectorType::get(
285 IntegerType::get(Ctx, EltSize),
287 V = IRB.CreatePointerCast(V, NewTy);
288 }
289 }
290 return IRB.CreateBitOrPointerCast(
291 V, IRB.getIntNTy(DL->getTypeStoreSize(V->getType()) * 8));
292 }
293};
294
295class AArch64StackTagging : public FunctionPass {
296 const bool MergeInit;
297 const bool UseStackSafety;
298
299public:
300 static char ID; // Pass ID, replacement for typeid
301
302 AArch64StackTagging(bool IsOptNone = false)
303 : FunctionPass(ID),
304 MergeInit(ClMergeInit.getNumOccurrences() ? ClMergeInit : !IsOptNone),
305 UseStackSafety(ClUseStackSafety.getNumOccurrences() ? ClUseStackSafety
306 : !IsOptNone) {}
307
308 void tagAlloca(AllocaInst *AI, Instruction *InsertBefore, Value *Ptr,
309 uint64_t Size);
310 void untagAlloca(AllocaInst *AI, Instruction *InsertBefore, uint64_t Size);
311
312 Instruction *collectInitializers(Instruction *StartInst, Value *StartPtr,
313 uint64_t Size, InitializerBuilder &IB);
314
315 Instruction *insertBaseTaggedPointer(
316 const Module &M,
317 const MapVector<AllocaInst *, memtag::AllocaInfo> &Allocas,
318 const DominatorTree *DT);
319 bool runOnFunction(Function &F) override;
320
321 StringRef getPassName() const override { return "AArch64 Stack Tagging"; }
322
323private:
324 Function *F = nullptr;
325 Function *SetTagFunc = nullptr;
326 const DataLayout *DL = nullptr;
327 AAResults *AA = nullptr;
328 const StackSafetyGlobalInfo *SSI = nullptr;
329
330 void getAnalysisUsage(AnalysisUsage &AU) const override {
331 AU.setPreservesCFG();
332 if (UseStackSafety)
333 AU.addRequired<StackSafetyGlobalInfoWrapperPass>();
334 if (MergeInit)
335 AU.addRequired<AAResultsWrapperPass>();
336 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
337 }
338};
339
340} // end anonymous namespace
341
342char AArch64StackTagging::ID = 0;
343
344INITIALIZE_PASS_BEGIN(AArch64StackTagging, DEBUG_TYPE, "AArch64 Stack Tagging",
345 false, false)
349INITIALIZE_PASS_END(AArch64StackTagging, DEBUG_TYPE, "AArch64 Stack Tagging",
351
353 return new AArch64StackTagging(IsOptNone);
354}
355
356Instruction *AArch64StackTagging::collectInitializers(Instruction *StartInst,
357 Value *StartPtr,
359 InitializerBuilder &IB) {
360 MemoryLocation AllocaLoc{StartPtr, Size};
361 Instruction *LastInst = StartInst;
362 BasicBlock::iterator BI(StartInst);
363
364 unsigned Count = 0;
365 for (; Count < ClScanLimit && !BI->isTerminator(); ++BI) {
366 ++Count;
367
368 if (isNoModRef(AA->getModRefInfo(&*BI, AllocaLoc)))
369 continue;
370
371 if (!isa<StoreInst>(BI) && !isa<MemSetInst>(BI)) {
372 // If the instruction is readnone, ignore it, otherwise bail out. We
373 // don't even allow readonly here because we don't want something like:
374 // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
375 if (BI->mayWriteToMemory() || BI->mayReadFromMemory())
376 break;
377 continue;
378 }
379
380 if (StoreInst *NextStore = dyn_cast<StoreInst>(BI)) {
381 if (!NextStore->isSimple())
382 break;
383
384 // Check to see if this store is to a constant offset from the start ptr.
385 std::optional<int64_t> Offset =
386 NextStore->getPointerOperand()->getPointerOffsetFrom(StartPtr, *DL);
387 if (!Offset)
388 break;
389
390 if (!IB.addStore(*Offset, NextStore, DL))
391 break;
392 LastInst = NextStore;
393 } else {
394 MemSetInst *MSI = cast<MemSetInst>(BI);
395
396 if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength()))
397 break;
398
399 if (!isa<ConstantInt>(MSI->getValue()))
400 break;
401
402 // Check to see if this store is to a constant offset from the start ptr.
403 std::optional<int64_t> Offset =
404 MSI->getDest()->getPointerOffsetFrom(StartPtr, *DL);
405 if (!Offset)
406 break;
407
408 if (!IB.addMemSet(*Offset, MSI))
409 break;
410 LastInst = MSI;
411 }
412 }
413 return LastInst;
414}
415
416void AArch64StackTagging::tagAlloca(AllocaInst *AI, Instruction *InsertBefore,
417 Value *Ptr, uint64_t Size) {
418 auto SetTagZeroFunc = Intrinsic::getOrInsertDeclaration(
419 F->getParent(), Intrinsic::aarch64_settag_zero);
420 auto StgpFunc = Intrinsic::getOrInsertDeclaration(F->getParent(),
421 Intrinsic::aarch64_stgp);
422
423 InitializerBuilder IB(Size, DL, Ptr, SetTagFunc, SetTagZeroFunc, StgpFunc);
424 bool LittleEndian = AI->getModule()->getTargetTriple().isLittleEndian();
425 // Current implementation of initializer merging assumes little endianness.
426 if (MergeInit && !F->hasOptNone() && LittleEndian &&
428 LLVM_DEBUG(dbgs() << "collecting initializers for " << *AI
429 << ", size = " << Size << "\n");
430 InsertBefore = collectInitializers(InsertBefore, Ptr, Size, IB);
431 }
432
433 IRBuilder<> IRB(InsertBefore);
434 IB.generate(IRB);
435}
436
437void AArch64StackTagging::untagAlloca(AllocaInst *AI, Instruction *InsertBefore,
438 uint64_t Size) {
439 IRBuilder<> IRB(InsertBefore);
440 IRB.CreateCall(SetTagFunc, {IRB.CreatePointerCast(AI, IRB.getPtrTy()),
441 ConstantInt::get(IRB.getInt64Ty(), Size)});
442}
443
444static Value *getSlotPtr(IRBuilder<> &IRB, const Triple &TargetTriple,
445 bool HasInstrumentedAllocas) {
446 if (!HasInstrumentedAllocas)
447 return nullptr;
448
450 (!ClRecordStackHistory.getNumOccurrences() &&
451 TargetTriple.isOSDarwin())) {
452 if (TargetTriple.isAndroid() && TargetTriple.isAArch64() &&
453 !TargetTriple.isAndroidVersionLT(35))
454 return memtag::getAndroidSlotPtr(IRB, -3);
455 if (TargetTriple.isOSDarwin() && TargetTriple.isAArch64() &&
456 !TargetTriple.isSimulatorEnvironment())
457 return memtag::getDarwinSlotPtr(IRB, 231);
458 }
459 return nullptr;
460}
461
462Instruction *AArch64StackTagging::insertBaseTaggedPointer(
463 const Module &M,
464 const MapVector<AllocaInst *, memtag::AllocaInfo> &AllocasToInstrument,
465 const DominatorTree *DT) {
466 BasicBlock *PrologueBB = nullptr;
467 // Try sinking IRG as deep as possible to avoid hurting shrink wrap.
468 for (auto &I : AllocasToInstrument) {
469 const memtag::AllocaInfo &Info = I.second;
470 AllocaInst *AI = Info.AI;
471 if (!PrologueBB) {
472 PrologueBB = AI->getParent();
473 continue;
474 }
475 PrologueBB = DT->findNearestCommonDominator(PrologueBB, AI->getParent());
476 }
477 assert(PrologueBB);
478
479 IRBuilder<> IRB(&PrologueBB->front());
481 IRB.CreateIntrinsic(Intrinsic::aarch64_irg_sp, {},
483 Base->setName("basetag");
484 const Triple &TargetTriple = M.getTargetTriple();
485 // This ABI will make it into Android API level 35.
486 // The ThreadLong format is the same as with HWASan, but the entries for
487 // stack MTE take two slots (16 bytes).
488 //
489 // Stack history is recorded by default on Darwin.
490 if (Value *SlotPtr =
491 getSlotPtr(IRB, TargetTriple, !AllocasToInstrument.empty())) {
492 constexpr uint64_t TagMask = 0xFULL << 56;
493 auto *IntptrTy = IRB.getIntPtrTy(M.getDataLayout());
494 auto *ThreadLong = IRB.CreateLoad(IntptrTy, SlotPtr);
495 Value *FP = memtag::getFP(IRB);
496 Value *Tag = IRB.CreateAnd(IRB.CreatePtrToInt(Base, IntptrTy), TagMask);
497 Value *TaggedFP = IRB.CreateOr(FP, Tag);
498 Value *PC = memtag::getPC(TargetTriple, IRB);
499 Value *RecordPtr = IRB.CreateIntToPtr(ThreadLong, IRB.getPtrTy(0));
500 IRB.CreateStore(PC, RecordPtr);
501 IRB.CreateStore(TaggedFP, IRB.CreateConstGEP1_64(IntptrTy, RecordPtr, 1));
502
503 IRB.CreateStore(memtag::incrementThreadLong(IRB, ThreadLong, 16,
504 TargetTriple.isOSDarwin()),
505 SlotPtr);
506 }
507 return Base;
508}
509
510// FIXME: check for MTE extension
511bool AArch64StackTagging::runOnFunction(Function &Fn) {
512 if (!Fn.hasFnAttribute(Attribute::SanitizeMemTag))
513 return false;
514
515 if (UseStackSafety)
516 SSI = &getAnalysis<StackSafetyGlobalInfoWrapperPass>().getResult();
517 F = &Fn;
518 DL = &Fn.getDataLayout();
519 if (MergeInit)
520 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
521 OptimizationRemarkEmitter &ORE =
522 getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
523
524 memtag::StackInfoBuilder SIB(SSI, DEBUG_TYPE);
525 for (Instruction &I : instructions(F))
526 SIB.visit(ORE, I);
527 memtag::StackInfo &SInfo = SIB.get();
528
529 if (SInfo.AllocasToInstrument.empty())
530 return false;
531
532 std::unique_ptr<DominatorTree> DeleteDT;
533 DominatorTree *DT = nullptr;
534 if (auto *P = getAnalysisIfAvailable<DominatorTreeWrapperPass>())
535 DT = &P->getDomTree();
536
537 if (DT == nullptr) {
538 DeleteDT = std::make_unique<DominatorTree>(*F);
539 DT = DeleteDT.get();
540 }
541
542 std::unique_ptr<PostDominatorTree> DeletePDT;
543 PostDominatorTree *PDT = nullptr;
544 if (auto *P = getAnalysisIfAvailable<PostDominatorTreeWrapperPass>())
545 PDT = &P->getPostDomTree();
546
547 if (PDT == nullptr) {
548 DeletePDT = std::make_unique<PostDominatorTree>(*F);
549 PDT = DeletePDT.get();
550 }
551
552 std::unique_ptr<LoopInfo> DeleteLI;
553 LoopInfo *LI = nullptr;
554 if (auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>()) {
555 LI = &LIWP->getLoopInfo();
556 } else {
557 DeleteLI = std::make_unique<LoopInfo>(*DT);
558 LI = DeleteLI.get();
559 }
560
561 SetTagFunc = Intrinsic::getOrInsertDeclaration(F->getParent(),
562 Intrinsic::aarch64_settag);
563
565 insertBaseTaggedPointer(*Fn.getParent(), SInfo.AllocasToInstrument, DT);
566
567 unsigned int NextTag = 0;
568 for (auto &I : SInfo.AllocasToInstrument) {
569 memtag::AllocaInfo &Info = I.second;
570 assert(Info.AI && SIB.getAllocaInterestingness(*Info.AI) ==
573 AllocaInst *AI = Info.AI;
574 unsigned int Tag = NextTag;
575 NextTag = (NextTag + 1) % 16;
576 // Replace alloca with tagp(alloca).
577 IRBuilder<> IRB(Info.AI->getNextNode());
578 Instruction *TagPCall =
579 IRB.CreateIntrinsic(Intrinsic::aarch64_tagp, {Info.AI->getType()},
580 {Constant::getNullValue(Info.AI->getType()), Base,
581 ConstantInt::get(IRB.getInt64Ty(), Tag)});
582 if (Info.AI->hasName())
583 TagPCall->setName(Info.AI->getName() + ".tag");
584 // Does not replace metadata, so we don't have to handle DbgVariableRecords.
585 Info.AI->replaceUsesWithIf(TagPCall, [&](const Use &U) {
586 return !isa<LifetimeIntrinsic>(U.getUser());
587 });
588 TagPCall->setOperand(0, Info.AI);
589
590 // Calls to functions that may return twice (e.g. setjmp) confuse the
591 // postdominator analysis, and will leave us to keep memory tagged after
592 // function return. Work around this by always untagging at every return
593 // statement if return_twice functions are called.
594 bool StandardLifetime =
595 !SInfo.CallsReturnTwice && memtag::isSupportedLifetime(Info, DT, LI);
596 if (StandardLifetime) {
597 uint64_t Size = *Info.AI->getAllocationSize(*DL);
599 for (IntrinsicInst *Start : Info.LifetimeStart)
600 tagAlloca(AI, Start->getNextNode(), TagPCall, Size);
601
602 auto TagEnd = [&](Instruction *Node) { untagAlloca(AI, Node, Size); };
603 if (!DT || !PDT ||
604 !memtag::forAllReachableExits(*DT, *PDT, *LI, Info, SInfo.RetVec,
605 TagEnd)) {
606 for (auto *End : Info.LifetimeEnd)
607 End->eraseFromParent();
608 }
609 } else {
610 uint64_t Size = *Info.AI->getAllocationSize(*DL);
611 Value *Ptr = IRB.CreatePointerCast(TagPCall, IRB.getPtrTy());
612 tagAlloca(AI, &*IRB.GetInsertPoint(), Ptr, Size);
613 for (auto *RI : SInfo.RetVec) {
614 untagAlloca(AI, RI, Size);
615 }
616 // We may have inserted tag/untag outside of any lifetime interval.
617 // Remove all lifetime intrinsics for this alloca.
618 for (auto *II : Info.LifetimeStart)
619 II->eraseFromParent();
620 for (auto *II : Info.LifetimeEnd)
621 II->eraseFromParent();
622 }
623
625 }
626
627 return true;
628}
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 Value * getSlotPtr(IRBuilder<> &IRB, const Triple &TargetTriple, bool HasInstrumentedAllocas)
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 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")
#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:493
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:64
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:362
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:729
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:1988
Value * CreateConstGEP1_32(Type *Ty, Value *Ptr, unsigned Idx0, const Twine &Name="")
Definition IRBuilder.h:1957
IntegerType * getIntNTy(unsigned N)
Fetch the type representing an N-bit integer.
Definition IRBuilder.h:574
Value * CreateZExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a ZExt or Trunc from the integer value V to DestTy.
Definition IRBuilder.h:2072
Value * CreatePointerCast(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2223
BasicBlock::iterator GetInsertPoint() const
Definition IRBuilder.h:202
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2171
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition IRBuilder.h:1516
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:610
IntegerType * getInt64Ty()
Fetch the type representing a 64-bit integer.
Definition IRBuilder.h:566
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:2258
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:1854
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1495
LLVMContext & getContext() const
Definition IRBuilder.h:203
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:1554
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition IRBuilder.h:1867
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2166
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args={}, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2487
PointerType * getPtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer.
Definition IRBuilder.h:604
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Definition IRBuilder.h:1576
IntegerType * getInt8Ty()
Fetch the type representing an 8-bit integer.
Definition IRBuilder.h:551
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2788
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).
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:47
bool isAndroidVersionLT(unsigned Major) const
Definition Triple.h:861
bool isAndroid() const
Tests whether the target is Android.
Definition Triple.h:859
LLVM_ABI bool isLittleEndian() const
Tests whether the target triple is little endian.
Definition Triple.cpp:2118
bool isSimulatorEnvironment() const
Definition Triple.h:646
bool isOSDarwin() const
Is this a "Darwin" OS (macOS, iOS, tvOS, watchOS, DriverKit, XROS, or bridgeOS).
Definition Triple.h:639
bool isAArch64() const
Tests whether the target is AArch64 (little and big endian).
Definition Triple.h:1048
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:267
void setOperand(unsigned i, Value *Val)
Definition User.h:212
LLVM Value Representation.
Definition Value.h:75
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:397
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:1063
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 isSupportedLifetime(const AllocaInfo &AInfo, const DominatorTree *DT, const LoopInfo *LI)
Value * getDarwinSlotPtr(IRBuilder<> &IRB, int Slot)
Value * getAndroidSlotPtr(IRBuilder<> &IRB, int Slot)
void annotateDebugRecords(AllocaInfo &Info, unsigned int Tag)
void alignAndPadAlloca(memtag::AllocaInfo &Info, llvm::Align Align)
Value * getPC(const Triple &TargetTriple, IRBuilder<> &IRB)
Value * incrementThreadLong(IRBuilder<> &IRB, Value *ThreadLong, unsigned int Inc, bool IsMemtagDarwin=false)
bool forAllReachableExits(const DominatorTree &DT, const PostDominatorTree &PDT, const LoopInfo &LI, const AllocaInfo &AInfo, const SmallVectorImpl< Instruction * > &RetVec, llvm::function_ref< void(Instruction *)> Callback)
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.
Definition Types.h:26
@ Offset
Definition DWP.cpp:532
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:2052
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