55 #define DEBUG_TYPE "hwasan" 61 "__hwasan_personality_thunk";
64 "__hwasan_shadow_memory_dynamic_address";
77 "hwasan-memory-access-callback-prefix",
83 cl::desc(
"instrument reads and writes with callbacks"),
87 cl::desc(
"instrument read instructions"),
91 "hwasan-instrument-writes",
cl::desc(
"instrument write instructions"),
95 "hwasan-instrument-atomics",
101 cl::desc(
"Enable recovery mode (continue-after-error)."),
105 cl::desc(
"instrument stack (allocas)"),
109 "hwasan-uar-retag-to-zero",
110 cl::desc(
"Clear alloca tags before returning from the function to allow " 111 "non-instrumented and instrumented function calls mix. When set " 112 "to false, allocas are retagged before returning from the " 113 "function to detect use after return."),
117 "hwasan-generate-tags-with-calls",
125 "hwasan-match-all-tag",
126 cl::desc(
"don't report bad accesses via pointers with this tag"),
131 cl::desc(
"Enable KernelHWAddressSanitizer instrumentation"),
140 cl::desc(
"HWASan shadow mapping offset [EXPERIMENTAL]"),
145 cl::desc(
"Access dynamic shadow through an ifunc global on " 146 "platforms that support this"),
151 cl::desc(
"Access dynamic shadow through an thread-local pointer on " 152 "platforms that support this"),
157 cl::desc(
"Record stack frames with tagged allocations " 158 "in a thread-local ring buffer"),
162 cl::desc(
"instrument memory intrinsics"),
171 "hwasan-use-short-granules",
176 "hwasan-instrument-personality-functions",
188 class HWAddressSanitizer {
190 explicit HWAddressSanitizer(
Module &M,
bool CompileKernel =
false,
191 bool Recover =
false) : M(M) {
200 void initializeModule();
202 void initializeCallbacks(
Module &M);
210 void instrumentMemAccessInline(
Value *Ptr,
bool IsWrite,
211 unsigned AccessSizeIndex,
216 uint64_t *
TypeSize,
unsigned *Alignment,
219 bool isInterestingAlloca(
const AllocaInst &AI);
223 bool instrumentStack(
236 void emitPrologue(
IRBuilder<> &IRB,
bool WithFrameRecord);
239 void instrumentGlobals();
241 void instrumentPersonalityFunctions();
258 struct ShadowMapping {
265 unsigned getObjectAlignment()
const {
return 1U << Scale; }
267 ShadowMapping Mapping;
278 bool UseShortGranules;
279 bool InstrumentLandingPads;
291 Value *LocalDynamicShadow =
nullptr;
292 Value *StackBaseTag =
nullptr;
296 class HWAddressSanitizerLegacyPass :
public FunctionPass {
301 explicit HWAddressSanitizerLegacyPass(
bool CompileKernel =
false,
302 bool Recover =
false)
303 :
FunctionPass(ID), CompileKernel(CompileKernel), Recover(Recover) {}
305 StringRef getPassName()
const override {
return "HWAddressSanitizer"; }
307 bool doInitialization(
Module &M)
override {
308 HWASan = std::make_unique<HWAddressSanitizer>(M, CompileKernel, Recover);
313 return HWASan->sanitizeFunction(F);
316 bool doFinalization(
Module &M)
override {
322 std::unique_ptr<HWAddressSanitizer> HWASan;
332 HWAddressSanitizerLegacyPass,
"hwasan",
333 "HWAddressSanitizer: detect memory bugs using tagged addressing.",
false,
337 "HWAddressSanitizer: detect memory bugs using tagged addressing.",
false,
342 assert(!CompileKernel || Recover);
343 return new HWAddressSanitizerLegacyPass(CompileKernel, Recover);
347 : CompileKernel(CompileKernel), Recover(Recover) {}
351 HWAddressSanitizer HWASan(M, CompileKernel, Recover);
354 Modified |= HWASan.sanitizeFunction(
F);
363 void HWAddressSanitizer::initializeModule() {
369 Mapping.init(TargetTriple);
378 HwasanCtorFunction =
nullptr;
394 if (!CompileKernel) {
395 std::tie(HwasanCtorFunction, std::ignore) =
397 M, kHwasanModuleCtorName, kHwasanInitName,
408 bool InstrumentGlobals =
410 if (InstrumentGlobals)
413 bool InstrumentPersonalityFunctions =
417 if (InstrumentPersonalityFunctions)
418 instrumentPersonalityFunctions();
425 "__hwasan_tls",
nullptr,
430 ThreadPtrGlobal = cast<GlobalVariable>(
C);
434 void HWAddressSanitizer::initializeCallbacks(
Module &M) {
436 for (
size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
437 const std::string TypeStr = AccessIsWrite ?
"store" :
"load";
438 const std::string EndingStr = Recover ?
"_noabort" :
"";
446 HwasanMemoryAccessCallback[AccessIsWrite][AccessSizeIndex] =
449 itostr(1ULL << AccessSizeIndex) + EndingStr,
455 "__hwasan_tag_memory", IRB.
getVoidTy(), Int8PtrTy, Int8Ty, IntptrTy);
456 HwasanGenerateTagFunc =
462 const std::string MemIntrinCallbackPrefix =
485 return IRB.
CreateCall(Asm, {ShadowGlobal},
".hwasan.shadow");
493 if (Mapping.InGlobal) {
494 return getDynamicShadowIfunc(IRB);
496 Value *GlobalDynamicAddress =
498 kHwasanShadowMemoryDynamicAddress, Int8PtrTy);
499 return IRB.
CreateLoad(Int8PtrTy, GlobalDynamicAddress);
512 if (LocalDynamicShadow == I)
515 Value *PtrOperand =
nullptr;
517 if (
LoadInst *LI = dyn_cast<LoadInst>(I)) {
521 *Alignment = LI->getAlignment();
522 PtrOperand = LI->getPointerOperand();
523 }
else if (
StoreInst *
SI = dyn_cast<StoreInst>(I)) {
527 *Alignment =
SI->getAlignment();
528 PtrOperand =
SI->getPointerOperand();
529 }
else if (
AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
534 PtrOperand = RMW->getPointerOperand();
540 PtrOperand = XCHG->getPointerOperand();
562 if (
LoadInst *LI = dyn_cast<LoadInst>(I))
563 return LI->getPointerOperandIndex();
565 return SI->getPointerOperandIndex();
567 return RMW->getPointerOperandIndex();
569 return XCHG->getPointerOperandIndex();
591 Value *HWAddressSanitizer::shadowBase() {
592 if (LocalDynamicShadow)
593 return LocalDynamicShadow;
601 if (Mapping.Offset == 0)
604 return IRB.
CreateGEP(Int8Ty, shadowBase(), Shadow);
607 void HWAddressSanitizer::instrumentMemAccessInline(
Value *Ptr,
bool IsWrite,
608 unsigned AccessSizeIndex,
610 const int64_t AccessInfo = Recover * 0x20 + IsWrite * 0x10 + AccessSizeIndex;
619 ? Intrinsic::hwasan_check_memaccess_shortgranules
620 : Intrinsic::hwasan_check_memaccess),
628 Value *AddrLong = untagPointer(IRB, PtrLong);
629 Value *Shadow = memToShadow(AddrLong, IRB);
635 if (matchAllTag != -1) {
638 TagMismatch = IRB.
CreateAnd(TagMismatch, TagNotIgnored);
646 Value *OutOfShortGranuleTagRange =
659 nullptr,
nullptr, CheckFailTerm->
getParent());
668 nullptr,
nullptr, CheckFailTerm->
getParent());
672 switch (TargetTriple.
getArch()) {
677 "int3\nnopl " +
itostr(0x40 + AccessInfo) +
"(%rax)",
686 "brk #" +
itostr(0x900 + AccessInfo),
695 cast<BranchInst>(CheckFailTerm)->setSuccessor(0, CheckTerm->
getParent());
698 void HWAddressSanitizer::instrumentMemIntrinsic(
MemIntrinsic *
MI) {
700 if (isa<MemTransferInst>(MI)) {
702 isa<MemMoveInst>(MI) ? HWAsanMemmove : HWAsanMemcpy,
706 }
else if (isa<MemSetInst>(MI)) {
716 bool HWAddressSanitizer::instrumentMemAccess(
Instruction *I) {
718 bool IsWrite =
false;
719 unsigned Alignment = 0;
720 uint64_t TypeSize = 0;
721 Value *MaybeMask =
nullptr;
724 instrumentMemIntrinsic(cast<MemIntrinsic>(I));
729 isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment, &MaybeMask);
740 (Alignment >= (1UL << Mapping.Scale) || Alignment == 0 ||
741 Alignment >= TypeSize / 8)) {
744 IRB.
CreateCall(HwasanMemoryAccessCallback[IsWrite][AccessSizeIndex],
747 instrumentMemAccessInline(Addr, IsWrite, AccessSizeIndex, I);
750 IRB.
CreateCall(HwasanMemoryAccessCallbackSized[IsWrite],
754 untagPointerOperand(I, Addr);
760 uint64_t ArraySize = 1;
763 assert(CI &&
"non-constant array size");
768 return SizeInBytes * ArraySize;
773 size_t AlignedSize =
alignTo(Size, Mapping.getObjectAlignment());
774 if (!UseShortGranules)
783 size_t ShadowSize = Size >> Mapping.Scale;
793 if (Size != AlignedSize) {
816 static unsigned FastMasks[] = {0, 128, 64, 192, 32, 96, 224, 112, 240,
817 48, 16, 120, 248, 56, 24, 8, 124, 252,
818 60, 28, 12, 4, 126, 254, 62, 30, 14,
819 6, 2, 127, 63, 31, 15, 7, 3, 1};
820 return FastMasks[AllocaNo % (
sizeof(FastMasks) /
sizeof(FastMasks[0]))];
829 return getNextTagWithCall(IRB);
836 M, Intrinsic::frameaddress,
847 "hwasan.stack.base.tag");
854 return getNextTagWithCall(IRB);
863 return getNextTagWithCall(IRB);
870 Value *TaggedPtrLong;
876 TaggedPtrLong = IRB.
CreateAnd(PtrLong, ShiftedTag);
880 TaggedPtrLong = IRB.
CreateOr(PtrLong, ShiftedTag);
887 Value *UntaggedPtrLong;
890 UntaggedPtrLong = IRB.
CreateOr(PtrLong,
897 return UntaggedPtrLong;
914 return ThreadPtrGlobal;
920 void HWAddressSanitizer::emitPrologue(
IRBuilder<> &IRB,
bool WithFrameRecord) {
921 if (!Mapping.InTls) {
922 LocalDynamicShadow = getDynamicShadowNonTls(IRB);
926 if (!WithFrameRecord && TargetTriple.
isAndroid()) {
927 LocalDynamicShadow = getDynamicShadowIfunc(IRB);
931 Value *SlotPtr = getHwasanThreadSlotPtr(IRB, IntptrTy);
936 Value *ThreadLongMaybeUntagged =
937 TargetTriple.
isAArch64() ? ThreadLong : untagPointer(IRB, ThreadLong);
939 if (WithFrameRecord) {
946 PC = readRegister(IRB,
"pc");
951 M, Intrinsic::frameaddress,
955 {Constant::getNullValue(IRB.getInt32Ty())}),
967 IRB.
CreateIntToPtr(ThreadLongMaybeUntagged, IntptrTy->getPointerTo(0));
990 ThreadLongMaybeUntagged,
993 LocalDynamicShadow = IRB.
CreateIntToPtr(LocalDynamicShadow, Int8PtrTy);
1005 bool HWAddressSanitizer::instrumentLandingPads(
1007 for (
auto *LP : LandingPadVec) {
1017 bool HWAddressSanitizer::instrumentStack(
1026 for (
unsigned N = 0;
N < Allocas.
size(); ++
N) {
1027 auto *AI = Allocas[
N];
1031 Value *Tag = getAllocaTag(IRB, StackTag, AI,
N);
1036 Replacement->
setName(Name +
".hwasan");
1039 [AILong](
Use &U) {
return U.
getUser() != AILong; });
1041 for (
auto *DDI : AllocaDbgMap.lookup(AI)) {
1049 DDI->getExpression(), NewOps)));
1053 tagAlloca(IRB, AI, Tag, Size);
1055 for (
auto RI : RetVec) {
1059 Value *Tag = getUARTag(IRB, StackTag);
1060 tagAlloca(IRB, AI, Tag,
alignTo(Size, Mapping.getObjectAlignment()));
1067 bool HWAddressSanitizer::isInterestingAlloca(
const AllocaInst &AI) {
1083 bool HWAddressSanitizer::sanitizeFunction(
Function &
F) {
1084 if (&F == HwasanCtorFunction)
1097 for (
auto &BB : F) {
1098 for (
auto &Inst : BB) {
1100 if (
AllocaInst *AI = dyn_cast<AllocaInst>(&Inst)) {
1101 if (isInterestingAlloca(*AI))
1106 if (isa<ReturnInst>(Inst) || isa<ResumeInst>(Inst) ||
1107 isa<CleanupReturnInst>(Inst))
1110 if (
auto *DDI = dyn_cast<DbgVariableIntrinsic>(&Inst))
1112 dyn_cast_or_null<AllocaInst>(DDI->getVariableLocation()))
1113 AllocaDbgMap[Alloca].push_back(DDI);
1115 if (InstrumentLandingPads && isa<LandingPadInst>(Inst))
1118 Value *MaybeMask =
nullptr;
1122 Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
1123 &Alignment, &MaybeMask);
1124 if (Addr || isa<MemIntrinsic>(Inst))
1125 ToInstrument.push_back(&Inst);
1129 initializeCallbacks(*F.getParent());
1131 if (!LandingPadVec.
empty())
1132 instrumentLandingPads(LandingPadVec);
1134 if (AllocasToInstrument.
empty() && F.hasPersonalityFn() &&
1138 F.setPersonalityFn(
nullptr);
1141 if (AllocasToInstrument.
empty() && ToInstrument.empty())
1144 assert(!LocalDynamicShadow);
1146 Instruction *InsertPt = &*F.getEntryBlock().begin();
1148 emitPrologue(EntryIRB,
1150 !AllocasToInstrument.
empty());
1152 bool Changed =
false;
1153 if (!AllocasToInstrument.
empty()) {
1156 Changed |= instrumentStack(AllocasToInstrument, AllocaDbgMap, RetVec,
1166 uint64_t AlignedSize =
alignTo(Size, Mapping.getObjectAlignment());
1169 if (Size != AlignedSize) {
1172 uint64_t ArraySize =
1184 NewAI->copyMetadata(*AI);
1187 AllocaToPaddedAllocaMap[AI] = NewAI;
1191 if (!AllocaToPaddedAllocaMap.
empty()) {
1193 for (
auto &Inst : BB)
1194 if (
auto *DVI = dyn_cast<DbgVariableIntrinsic>(&Inst))
1196 dyn_cast_or_null<AllocaInst>(DVI->getVariableLocation()))
1197 if (
auto *NewAI = AllocaToPaddedAllocaMap.
lookup(AI))
1200 for (
auto &
P : AllocaToPaddedAllocaMap)
1201 P.first->eraseFromParent();
1208 InsertPt = &*F.getEntryBlock().begin();
1213 if (
auto *AI = dyn_cast<AllocaInst>(I))
1219 for (
auto Inst : ToInstrument)
1220 Changed |= instrumentMemAccess(Inst);
1222 LocalDynamicShadow =
nullptr;
1223 StackBaseTag =
nullptr;
1228 void HWAddressSanitizer::instrumentGlobal(
GlobalVariable *GV, uint8_t Tag) {
1230 uint64_t SizeInBytes =
1232 uint64_t NewSize =
alignTo(SizeInBytes, Mapping.getObjectAlignment());
1233 if (SizeInBytes != NewSize) {
1236 std::vector<uint8_t>
Init(NewSize - SizeInBytes, 0);
1247 NewGV->copyMetadata(GV, 0);
1248 NewGV->setAlignment(
1268 const uint64_t MaxDescriptorSize = 0xfffff0;
1269 for (uint64_t DescriptorPos = 0; DescriptorPos < SizeInBytes;
1270 DescriptorPos += MaxDescriptorSize) {
1273 nullptr, GV->
getName() +
".hwasan.descriptor");
1281 uint32_t Size = std::min(SizeInBytes - DescriptorPos, MaxDescriptorSize);
1283 Descriptor->setComdat(NewGV->getComdat());
1285 Descriptor->setSection(
"hwasan_globals");
1286 Descriptor->setMetadata(LLVMContext::MD_associated,
1299 Alias->takeName(GV);
1304 void HWAddressSanitizer::instrumentGlobals() {
1334 nullptr,
"__start_hwasan_globals");
1336 Start->setDSOLocal(
true);
1339 nullptr,
"__stop_hwasan_globals");
1341 Stop->setDSOLocal(
true);
1347 auto *NoteTy =
StructType::get(Int32Ty, Int32Ty, Int32Ty, Name->getType(),
1352 Note->setSection(
".note.hwasan.globals");
1353 Note->setComdat(NoteComdat);
1354 Note->setAlignment(
Align(4));
1355 Note->setDSOLocal(
true);
1359 auto CreateRelPtr = [&](
Constant *Ptr) {
1369 Name, CreateRelPtr(Start), CreateRelPtr(Stop)}));
1377 Dummy->setSection(
"hwasan_globals");
1378 Dummy->setComdat(NoteComdat);
1379 Dummy->setMetadata(LLVMContext::MD_associated,
1383 std::vector<GlobalVariable *> Globals;
1399 Globals.push_back(&GV);
1406 uint8_t Tag = Hash[0];
1412 instrumentGlobal(GV, Tag++);
1416 void HWAddressSanitizer::instrumentPersonalityFunctions() {
1431 PersonalityFns[
nullptr].push_back(&F);
1435 if (PersonalityFns.
empty())
1439 "__hwasan_personality_wrapper", Int32Ty, Int32Ty, Int32Ty, Int64Ty,
1440 Int8PtrTy, Int8PtrTy, Int8PtrTy, Int8PtrTy, Int8PtrTy);
1441 FunctionCallee UnwindGetGR = M.getOrInsertFunction(
"_Unwind_GetGR", VoidTy);
1442 FunctionCallee UnwindGetCFA = M.getOrInsertFunction(
"_Unwind_GetCFA", VoidTy);
1444 for (
auto &
P : PersonalityFns) {
1447 ThunkName += (
"." +
P.first->getName()).str();
1449 Int32Ty, {
Int32Ty,
Int32Ty, Int64Ty, Int8PtrTy, Int8PtrTy},
false);
1450 bool IsLocal =
P.first && (!isa<GlobalValue>(
P.first) ||
1451 cast<GlobalValue>(
P.first)->hasLocalLinkage());
1458 ThunkFn->setComdat(M.getOrInsertComdat(ThunkName));
1464 HwasanPersonalityWrapper,
1465 {ThunkFn->getArg(0), ThunkFn->getArg(1), ThunkFn->getArg(2),
1466 ThunkFn->getArg(3), ThunkFn->getArg(4),
void setVisibility(VisibilityTypes V)
static cl::opt< int > ClMatchAllTag("hwasan-match-all-tag", cl::desc("don't report bad accesses via pointers with this tag"), cl::Hidden, cl::init(-1))
bool isDeclarationForLinker() const
void appendToCompilerUsed(Module &M, ArrayRef< GlobalValue *> Values)
Adds global values to the llvm.compiler.used list.
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
unsigned getAlignment() const
A parsed version of the target data layout string in and methods for querying it. ...
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
FunctionPass * createHWAddressSanitizerLegacyPassPass(bool CompileKernel=false, bool Recover=false)
Value * CreateConstGEP1_32(Value *Ptr, unsigned Idx0, const Twine &Name="")
LLVM_NODISCARD std::string str() const
str - Get the contents as an std::string.
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
static cl::opt< uint64_t > ClMappingOffset("hwasan-mapping-offset", cl::desc("HWASan shadow mapping offset [EXPERIMENTAL]"), cl::Hidden, cl::init(0))
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
This class represents lattice values for constants.
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
Value * CreateXor(Value *LHS, Value *RHS, const Twine &Name="")
A Module instance is used to store all the information related to an LLVM module. ...
bool isSized(SmallPtrSetImpl< Type *> *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
bool isOSBinFormatELF() const
Tests whether the OS uses the ELF binary format.
An instruction that atomically checks whether a specified value is in a memory location, and, if it is, stores a new value there.
static MDString * get(LLVMContext &Context, StringRef Str)
static cl::opt< bool > ClRecover("hwasan-recover", cl::desc("Enable recovery mode (continue-after-error)."), cl::Hidden, cl::init(false))
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
LLVM_NODISCARD bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
void push_back(const T &Elt)
This class represents a function call, abstracting a target machine's calling convention.
static Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
bool isSwiftError() const
Return true if this alloca is used as a swifterror argument to a call.
Like Internal, but omit from symbol table.
Externally visible function.
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
This class implements a map that also provides access to all stored values in a deterministic order...
StringRef getName() const
Get a short "name" for the module.
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
An instruction for reading from memory.
static IntegerType * getInt64Ty(LLVMContext &C)
an instruction that atomically reads a memory location, combines it with another value, and then stores the result back.
static Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static const char *const kHwasanInitName
static unsigned getPointerOperandIndex(Instruction *I)
static const size_t kDefaultShadowScale
TypeSize getTypeStoreSizeInBits(Type *Ty) const
Returns the maximum number of bits that may be overwritten by storing the specified type; always a mu...
bool isAllocaPromotable(const AllocaInst *AI)
Return true if this alloca is legal for promotion.
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
iterator begin()
Instruction iterator methods.
static Constant * getAdd(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static cl::opt< bool > ClInlineAllChecks("hwasan-inline-all-checks", cl::desc("inline all checks"), cl::Hidden, cl::init(false))
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
unsigned countTrailingZeros(T Val, ZeroBehavior ZB=ZB_Width)
Count number of 0's from the least significant bit to the most stopping at the first 1...
unsigned getAllocaAddrSpace() const
static const char *const kHwasanShadowMemoryDynamicAddress
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
unsigned getAlignment() const
Return the alignment of the memory that is being allocated by the instruction.
PointerType * getType() const
Overload to return most specific pointer type.
bool isAArch64() const
Tests whether the target is AArch64 (little and big endian).
void update(ArrayRef< uint8_t > Data)
Updates the hash for the byte stream provided.
LLVMContext & getContext() const
Get the global data context.
static cl::opt< bool > ClInstrumentWrites("hwasan-instrument-writes", cl::desc("instrument write instructions"), cl::Hidden, cl::init(true))
A Use represents the edge between a Value definition and its users.
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
PointerType * getPointerTo(unsigned AddrSpace=0) const
Return a pointer to the current type.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
ReturnInst * CreateRet(Value *V)
Create a 'ret <val>' instruction.
IntegerType * getIntPtrTy(const DataLayout &DL, unsigned AddrSpace=0)
Fetch the type representing a pointer to an integer value.
This file contains the simple types necessary to represent the attributes associated with functions a...
bool hasMetadata() const
Return true if this instruction has any metadata attached to it.
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
void setName(const Twine &Name)
Change the name of the value.
static StructType * get(LLVMContext &Context, ArrayRef< Type *> Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
bool hasCommonLinkage() const
Type * getVoidTy()
Fetch the type representing void.
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
User * getUser() const LLVM_READONLY
Returns the User that contains this Use.
Class to represent function types.
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Type * getType() const
All values are typed, get the type of this value.
Value * CreateICmpUGT(Value *LHS, Value *RHS, const Twine &Name="")
std::string itostr(int64_t X)
bool isSwiftError() const
Return true if this value is a swifterror value.
ArchType getArch() const
getArch - Get the parsed architecture type of this triple.
BasicBlock * GetInsertBlock() const
static const unsigned kShadowBaseAlignment
std::pair< Function *, FunctionCallee > getOrCreateSanitizerCtorAndInitFunctions(Module &M, StringRef CtorName, StringRef InitName, ArrayRef< Type *> InitArgTypes, ArrayRef< Value *> InitArgs, function_ref< void(Function *, FunctionCallee)> FunctionsCreatedCallback, StringRef VersionCheckName=StringRef())
Creates sanitizer constructor function lazily.
bool isUsedWithInAlloca() const
Return true if this alloca is used as an inalloca argument to a call.
void setComdat(Comdat *C)
This class represents a no-op cast from one type to another.
static const unsigned kPointerTagShift
An instruction for storing to memory.
bool hasPersonalityFn() const
Check whether this function has a personality function.
static cl::opt< bool > ClInstrumentMemIntrinsics("hwasan-instrument-mem-intrinsics", cl::desc("instrument memory intrinsics"), cl::Hidden, cl::init(true))
LinkageTypes getLinkage() const
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="")
void takeName(Value *V)
Transfer the name from V to this value.
static cl::opt< bool > ClGlobals("hwasan-globals", cl::desc("Instrument globals"), cl::Hidden, cl::init(false))
Function * getDeclaration(Module *M, ID id, ArrayRef< Type *> Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block...
void replaceUsesWithIf(Value *New, llvm::function_ref< bool(Use &U)> ShouldReplace)
Go through the uses list for this definition and make each use point to "V" if the callback ShouldRep...
Value * getOperand(unsigned i) const
const std::string & getSourceFileName() const
Get the module's original source file name.
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
static cl::opt< bool > ClInstrumentStack("hwasan-instrument-stack", cl::desc("instrument stack (allocas)"), cl::Hidden, cl::init(true))
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="")
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
static bool runOnFunction(Function &F, bool PostInlining)
Same, but only replaced by something equivalent.
initializer< Ty > init(const Ty &Val)
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
A set of analyses that are preserved following a run of a transformation pass.
Value * CreateAShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
VisibilityTypes getVisibility() const
The instances of the Type class are immutable: once they are created, they are never changed...
This is an important class for using LLVM in a threaded context.
static cl::opt< std::string > ClMemoryAccessCallbackPrefix("hwasan-memory-access-callback-prefix", cl::desc("Prefix for memory access callbacks"), cl::Hidden, cl::init("__hwasan_"))
This is an important base class in LLVM.
Only used in LLVM metadata.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static cl::opt< bool > ClGenerateTagsWithCalls("hwasan-generate-tags-with-calls", cl::desc("generate new tags with runtime library calls"), cl::Hidden, cl::init(false))
static const size_t kNumberOfAccessSizes
TypeSize getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it...
static cl::opt< bool > ClInstrumentAtomics("hwasan-instrument-atomics", cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden, cl::init(true))
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
static cl::opt< bool > ClUseShortGranules("hwasan-use-short-granules", cl::desc("use short granules in allocas and outlined checks"), cl::Hidden, cl::init(false), cl::ZeroOrMore)
static Type * getVoidTy(LLVMContext &C)
bool isAndroidVersionLT(unsigned Major) const
unsigned getAddressSpace() const
static DIExpression * prependOpcodes(const DIExpression *Expr, SmallVectorImpl< uint64_t > &Ops, bool StackValue=false, bool EntryValue=false)
Prepend DIExpr with the given opcodes and optionally turn it into a stack value.
FunctionPass class - This class is used to implement most global optimizations.
static FunctionType * get(Type *Result, ArrayRef< Type *> Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
unsigned getAddressSpace() const
Return the address space of the Pointer type.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
void setTailCall(bool isTC=true)
const Constant * stripPointerCasts() const
static constexpr const Align None()
Returns a default constructed Align which corresponds to no alignment.
Comdat * getOrInsertComdat(StringRef Name)
Return the Comdat in the module with the specified name.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
const Value * getArraySize() const
Get the number of elements allocated.
PointerType * getInt8PtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer to an 8-bit integer value.
MDNode * createBranchWeights(uint32_t TrueWeight, uint32_t FalseWeight)
Return metadata containing two branch weights.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="")
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
Triple - Helper class for working with autoconf configuration names.
Value * CreateGEP(Value *Ptr, ArrayRef< Value *> IdxList, const Twine &Name="")
This is the common base class for memset/memcpy/memmove.
This is the shared class of boolean and integer constants.
Align max(MaybeAlign Lhs, Align Rhs)
This struct is a compact representation of a valid (power of two) or undefined (0) alignment...
Value * CreateIntCast(Value *V, Type *DestTy, bool isSigned, const Twine &Name="")
Value * CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name="")
bool hasSection() const
Check if this global has a custom object file section.
Module.h This file contains the declarations for the Module class.
static Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
void appendToGlobalCtors(Module &M, Function *F, int Priority, Constant *Data=nullptr)
Append F to the list of global ctors of module M with the given Priority.
FunctionCallee getOrInsertFunction(StringRef Name, FunctionType *T, AttributeList AttributeList)
Look up the specified function in the module symbol table.
void setAlignment(MaybeAlign Align)
void setOperand(unsigned i, Value *Val)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
IntegerType * getInt8Ty()
Fetch the type representing an 8-bit integer.
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
static size_t TypeSizeToSizeIndex(uint32_t TypeSize)
Value * CreatePointerCast(Value *V, Type *DestTy, const Twine &Name="")
static cl::opt< bool > ClWithTls("hwasan-with-tls", cl::desc("Access dynamic shadow through an thread-local pointer on " "platforms that support this"), cl::Hidden, cl::init(true))
PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM)
static cl::opt< bool > ClEnableKhwasan("hwasan-kernel", cl::desc("Enable KernelHWAddressSanitizer instrumentation"), cl::Hidden, cl::init(false))
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Constant * getOrInsertGlobal(StringRef Name, Type *Ty, function_ref< GlobalVariable *()> CreateGlobalCallback)
Look up the specified global in the module symbol table.
LLVM_NODISCARD bool empty() const
static const uint64_t kDynamicShadowSentinel
StringRef getName() const
Return a constant reference to the value's name.
void copyAttributesFrom(const GlobalVariable *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a GlobalVariable) fro...
const Function * getParent() const
Return the enclosing method, or null if none.
static Constant * getPtrToInt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static unsigned RetagMask(unsigned AllocaNo)
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Type * getValueType() const
Rename collisions when linking (static functions).
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value *> Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)
static cl::opt< bool > ClRecordStackHistory("hwasan-record-stack-history", cl::desc("Record stack frames with tagged allocations " "in a thread-local ring buffer"), cl::Hidden, cl::init(true))
static InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT)
InlineAsm::get - Return the specified uniqued inline asm string.
static cl::opt< bool > ClWithIfunc("hwasan-with-ifunc", cl::desc("Access dynamic shadow through an ifunc global on " "platforms that support this"), cl::Hidden, cl::init(false))
static cl::opt< bool > ClInstrumentWithCalls("hwasan-instrument-with-calls", cl::desc("instrument reads and writes with callbacks"), cl::Hidden, cl::init(false))
LLVM_NODISCARD bool empty() const
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
static uint64_t getAllocaSizeInBytes(const AllocaInst &AI)
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
bool isArrayAllocation() const
Return true if there is an allocation size parameter to the allocation instruction that is not 1...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
Constant * getPersonalityFn() const
Get the personality function associated with this function.
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
bool isAndroid() const
Tests whether the target is Android.
static Constant * getAnon(ArrayRef< Constant *> V, bool Packed=false)
Return an anonymous struct that has the specified elements.
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
static Constant * get(LLVMContext &Context, ArrayRef< ElementTy > Elts)
get() constructor - Return a constant with array type with an element count and element type matching...
bool isThreadLocal() const
If the value is "Thread Local", its value isn't shared by the threads.
void final(MD5Result &Result)
Finishes off the hash and puts the result in result.
iterator_range< global_iterator > globals()
StringRef - Represent a constant reference to a string, i.e.
A container for analyses that lazily runs them and caches their results.
HWAddressSanitizerPass(bool CompileKernel=false, bool Recover=false)
void setPersonalityFn(Constant *Fn)
INITIALIZE_PASS_BEGIN(HWAddressSanitizerLegacyPass, "hwasan", "HWAddressSanitizer: detect memory bugs using tagged addressing.", false, false) INITIALIZE_PASS_END(HWAddressSanitizerLegacyPass
static cl::opt< bool > ClInstrumentPersonalityFunctions("hwasan-instrument-personality-functions", cl::desc("instrument personality functions"), cl::Hidden, cl::init(false), cl::ZeroOrMore)
bool isStaticAlloca() const
Return true if this alloca is in the entry block of the function and is a constant size...
static const char *const kHwasanNoteName
static const char *const kHwasanModuleCtorName
static const char *const kHwasanPersonalityThunkName
static GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
Instruction * SplitBlockAndInsertIfThen(Value *Cond, Instruction *SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
PointerType * getType() const
Global values are always pointers.
const BasicBlock * getParent() const
an instruction to allocate memory on the stack
static cl::opt< bool > ClUARRetagToZero("hwasan-uar-retag-to-zero", cl::desc("Clear alloca tags before returning from the function to allow " "non-instrumented and instrumented function calls mix. When set " "to false, allocas are retagged before returning from the " "function to detect use after return."), cl::Hidden, cl::init(true))
static cl::opt< bool > ClInstrumentReads("hwasan-instrument-reads", cl::desc("instrument read instructions"), cl::Hidden, cl::init(true))
CallInst * CreateMemSet(Value *Ptr, Value *Val, uint64_t Size, MaybeAlign Align, bool isVolatile=false, MDNode *TBAATag=nullptr, MDNode *ScopeTag=nullptr, MDNode *NoAliasTag=nullptr)
Create and insert a memset to the specified pointer and the specified value.
static cl::opt< bool > ClInstrumentLandingPads("hwasan-instrument-landing-pads", cl::desc("instrument landing pads"), cl::Hidden, cl::init(false), cl::ZeroOrMore)