LLVM 22.0.0git
TypeSanitizer.cpp
Go to the documentation of this file.
1//===----- TypeSanitizer.cpp - type-based-aliasing-violation detector -----===//
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// This file is a part of TypeSanitizer, a type-based-aliasing-violation
10// detector.
11//
12//===----------------------------------------------------------------------===//
13
15#include "llvm/ADT/SetVector.h"
17#include "llvm/ADT/Statistic.h"
21#include "llvm/IR/DataLayout.h"
22#include "llvm/IR/Function.h"
23#include "llvm/IR/IRBuilder.h"
27#include "llvm/IR/Intrinsics.h"
28#include "llvm/IR/LLVMContext.h"
29#include "llvm/IR/MDBuilder.h"
30#include "llvm/IR/Metadata.h"
31#include "llvm/IR/Module.h"
32#include "llvm/IR/Type.h"
35#include "llvm/Support/MD5.h"
36#include "llvm/Support/Regex.h"
40
41#include <cctype>
42
43using namespace llvm;
44
45#define DEBUG_TYPE "tysan"
46
47static const char *const kTysanModuleCtorName = "tysan.module_ctor";
48static const char *const kTysanInitName = "__tysan_init";
49static const char *const kTysanCheckName = "__tysan_check";
50static const char *const kTysanGVNamePrefix = "__tysan_v1_";
51
52static const char *const kTysanShadowMemoryAddress =
53 "__tysan_shadow_memory_address";
54static const char *const kTysanAppMemMask = "__tysan_app_memory_mask";
55
56static cl::opt<bool>
57 ClWritesAlwaysSetType("tysan-writes-always-set-type",
58 cl::desc("Writes always set the type"), cl::Hidden,
59 cl::init(false));
60
62 "tysan-outline-instrumentation",
63 cl::desc("Uses function calls for all TySan instrumentation, reducing "
64 "ELF size"),
65 cl::Hidden, cl::init(false));
66
68 "tysan-verify-outlined-instrumentation",
69 cl::desc("Check types twice with both inlined instrumentation and "
70 "function calls. This verifies that they behave the same."),
71 cl::Hidden, cl::init(false));
72
73STATISTIC(NumInstrumentedAccesses, "Number of instrumented accesses");
74
75namespace {
76
77/// TypeSanitizer: instrument the code in module to find type-based aliasing
78/// violations.
79struct TypeSanitizer {
80 TypeSanitizer(Module &M);
81 bool sanitizeFunction(Function &F, const TargetLibraryInfo &TLI);
82 void instrumentGlobals(Module &M);
83
84private:
86 TypeDescriptorsMapTy;
88
89 void initializeCallbacks(Module &M);
90
91 Instruction *getShadowBase(Function &F);
92 Instruction *getAppMemMask(Function &F);
93
94 bool instrumentWithShadowUpdate(IRBuilder<> &IRB, const MDNode *TBAAMD,
95 Value *Ptr, uint64_t AccessSize, bool IsRead,
96 bool IsWrite, Value *ShadowBase,
97 Value *AppMemMask, bool ForceSetType,
98 bool SanitizeFunction,
99 TypeDescriptorsMapTy &TypeDescriptors,
100 const DataLayout &DL);
101
102 /// Memory-related intrinsics/instructions reset the type of the destination
103 /// memory (including allocas and byval arguments).
104 bool instrumentMemInst(Value *I, Instruction *ShadowBase,
105 Instruction *AppMemMask, const DataLayout &DL);
106
107 std::string getAnonymousStructIdentifier(const MDNode *MD,
108 TypeNameMapTy &TypeNames);
109 bool generateTypeDescriptor(const MDNode *MD,
110 TypeDescriptorsMapTy &TypeDescriptors,
111 TypeNameMapTy &TypeNames, Module &M);
112 bool generateBaseTypeDescriptor(const MDNode *MD,
113 TypeDescriptorsMapTy &TypeDescriptors,
114 TypeNameMapTy &TypeNames, Module &M);
115
116 const Triple TargetTriple;
117 Regex AnonNameRegex;
118 Type *IntptrTy;
119 uint64_t PtrShift;
120 IntegerType *OrdTy, *U64Ty;
121
122 /// Callbacks to run-time library are computed in initializeCallbacks.
123 FunctionCallee TysanCheck;
124 FunctionCallee TysanCtorFunction;
125
126 FunctionCallee TysanIntrumentMemInst;
127 FunctionCallee TysanInstrumentWithShadowUpdate;
128 FunctionCallee TysanSetShadowType;
129
130 /// Callback to set types for gloabls.
131 Function *TysanGlobalsSetTypeFunction;
132};
133} // namespace
134
135TypeSanitizer::TypeSanitizer(Module &M)
136 : TargetTriple(M.getTargetTriple()),
137 AnonNameRegex("^_ZTS.*N[1-9][0-9]*_GLOBAL__N") {
138 const DataLayout &DL = M.getDataLayout();
139 IntptrTy = DL.getIntPtrType(M.getContext());
140 PtrShift = countr_zero(IntptrTy->getPrimitiveSizeInBits() / 8);
141
142 TysanGlobalsSetTypeFunction = M.getFunction("__tysan_set_globals_types");
143 initializeCallbacks(M);
144}
145
146void TypeSanitizer::initializeCallbacks(Module &M) {
147 IRBuilder<> IRB(M.getContext());
148 OrdTy = IRB.getInt32Ty();
149 U64Ty = IRB.getInt64Ty();
150 Type *BoolType = IRB.getInt1Ty();
151
152 AttributeList Attr;
153 Attr = Attr.addFnAttribute(M.getContext(), Attribute::NoUnwind);
154 // Initialize the callbacks.
155 TysanCheck =
156 M.getOrInsertFunction(kTysanCheckName, Attr, IRB.getVoidTy(),
157 IRB.getPtrTy(), // Pointer to data to be read.
158 OrdTy, // Size of the data in bytes.
159 IRB.getPtrTy(), // Pointer to type descriptor.
160 OrdTy // Flags.
161 );
162
163 TysanCtorFunction =
164 M.getOrInsertFunction(kTysanModuleCtorName, Attr, IRB.getVoidTy());
165
166 TysanIntrumentMemInst = M.getOrInsertFunction(
167 "__tysan_instrument_mem_inst", Attr, IRB.getVoidTy(),
168 IRB.getPtrTy(), // Pointer of data to be written to
169 IRB.getPtrTy(), // Pointer of data to write
170 U64Ty, // Size of the data in bytes
171 BoolType // Do we need to call memmove
172 );
173
174 TysanInstrumentWithShadowUpdate = M.getOrInsertFunction(
175 "__tysan_instrument_with_shadow_update", Attr, IRB.getVoidTy(),
176 IRB.getPtrTy(), // Pointer to data to be read
177 IRB.getPtrTy(), // Pointer to type descriptor
178 BoolType, // Do we need to type check this
179 U64Ty, // Size of data we access in bytes
180 OrdTy // Flags
181 );
182
183 TysanSetShadowType = M.getOrInsertFunction(
184 "__tysan_set_shadow_type", Attr, IRB.getVoidTy(),
185 IRB.getPtrTy(), // Pointer of data to be written to
186 IRB.getPtrTy(), // Pointer to the new type descriptor
187 U64Ty // Size of data we access in bytes
188 );
189}
190
191void TypeSanitizer::instrumentGlobals(Module &M) {
192 TysanGlobalsSetTypeFunction = nullptr;
193
194 NamedMDNode *Globals = M.getNamedMetadata("llvm.tysan.globals");
195 if (!Globals)
196 return;
197
198 TysanGlobalsSetTypeFunction = Function::Create(
199 FunctionType::get(Type::getVoidTy(M.getContext()), false),
200 GlobalValue::InternalLinkage, "__tysan_set_globals_types", &M);
201 BasicBlock *BB =
202 BasicBlock::Create(M.getContext(), "", TysanGlobalsSetTypeFunction);
203 ReturnInst::Create(M.getContext(), BB);
204
205 const DataLayout &DL = M.getDataLayout();
206 Value *ShadowBase = getShadowBase(*TysanGlobalsSetTypeFunction);
207 Value *AppMemMask = getAppMemMask(*TysanGlobalsSetTypeFunction);
208 TypeDescriptorsMapTy TypeDescriptors;
209 TypeNameMapTy TypeNames;
210
211 for (const auto &GMD : Globals->operands()) {
212 auto *GV = mdconst::dyn_extract_or_null<GlobalVariable>(GMD->getOperand(0));
213 if (!GV)
214 continue;
215 const MDNode *TBAAMD = cast<MDNode>(GMD->getOperand(1));
216 if (!generateBaseTypeDescriptor(TBAAMD, TypeDescriptors, TypeNames, M))
217 continue;
218
219 IRBuilder<> IRB(
220 TysanGlobalsSetTypeFunction->getEntryBlock().getTerminator());
221 Type *AccessTy = GV->getValueType();
222 assert(AccessTy->isSized());
223 uint64_t AccessSize = DL.getTypeStoreSize(AccessTy);
224 instrumentWithShadowUpdate(IRB, TBAAMD, GV, AccessSize, false, false,
225 ShadowBase, AppMemMask, true, false,
226 TypeDescriptors, DL);
227 }
228
229 if (TysanGlobalsSetTypeFunction) {
230 IRBuilder<> IRB(cast<Function>(TysanCtorFunction.getCallee())
231 ->getEntryBlock()
232 .getTerminator());
233 IRB.CreateCall(TysanGlobalsSetTypeFunction, {});
234 }
235}
236
237static const char LUT[] = "0123456789abcdef";
238
239static std::string encodeName(StringRef Name) {
240 size_t Length = Name.size();
241 std::string Output = kTysanGVNamePrefix;
242 Output.reserve(Output.size() + 3 * Length);
243 for (size_t i = 0; i < Length; ++i) {
244 const unsigned char c = Name[i];
245 if (isalnum(c)) {
246 Output.push_back(c);
247 continue;
248 }
249
250 if (c == '_') {
251 Output.append("__");
252 continue;
253 }
254
255 Output.push_back('_');
256 Output.push_back(LUT[c >> 4]);
257 Output.push_back(LUT[c & 15]);
258 }
259
260 return Output;
261}
262
263std::string
264TypeSanitizer::getAnonymousStructIdentifier(const MDNode *MD,
265 TypeNameMapTy &TypeNames) {
266 MD5 Hash;
267
268 for (int i = 1, e = MD->getNumOperands(); i < e; i += 2) {
269 const MDNode *MemberNode = dyn_cast<MDNode>(MD->getOperand(i));
270 if (!MemberNode)
271 return "";
272
273 auto TNI = TypeNames.find(MemberNode);
274 std::string MemberName;
275 if (TNI != TypeNames.end()) {
276 MemberName = TNI->second;
277 } else {
278 if (MemberNode->getNumOperands() < 1)
279 return "";
280 MDString *MemberNameNode = dyn_cast<MDString>(MemberNode->getOperand(0));
281 if (!MemberNameNode)
282 return "";
283 MemberName = MemberNameNode->getString().str();
284 if (MemberName.empty())
285 MemberName = getAnonymousStructIdentifier(MemberNode, TypeNames);
286 if (MemberName.empty())
287 return "";
288 TypeNames[MemberNode] = MemberName;
289 }
290
291 Hash.update(MemberName);
292 Hash.update("\0");
293
294 uint64_t Offset =
295 mdconst::extract<ConstantInt>(MD->getOperand(i + 1))->getZExtValue();
296 Hash.update(utostr(Offset));
297 Hash.update("\0");
298 }
299
300 MD5::MD5Result HashResult;
301 Hash.final(HashResult);
302 return "__anonymous_" + std::string(HashResult.digest().str());
303}
304
305bool TypeSanitizer::generateBaseTypeDescriptor(
306 const MDNode *MD, TypeDescriptorsMapTy &TypeDescriptors,
307 TypeNameMapTy &TypeNames, Module &M) {
308 if (MD->getNumOperands() < 1)
309 return false;
310
311 MDString *NameNode = dyn_cast<MDString>(MD->getOperand(0));
312 if (!NameNode)
313 return false;
314
315 std::string Name = NameNode->getString().str();
316 if (Name.empty())
317 Name = getAnonymousStructIdentifier(MD, TypeNames);
318 if (Name.empty())
319 return false;
320 TypeNames[MD] = Name;
321 std::string EncodedName = encodeName(Name);
322
323 GlobalVariable *GV =
324 dyn_cast_or_null<GlobalVariable>(M.getNamedValue(EncodedName));
325 if (GV) {
326 TypeDescriptors[MD] = GV;
327 return true;
328 }
329
331 for (int i = 1, e = MD->getNumOperands(); i < e; i += 2) {
332 const MDNode *MemberNode = dyn_cast<MDNode>(MD->getOperand(i));
333 if (!MemberNode)
334 return false;
335
337 auto TDI = TypeDescriptors.find(MemberNode);
338 if (TDI != TypeDescriptors.end()) {
339 Member = TDI->second;
340 } else {
341 if (!generateBaseTypeDescriptor(MemberNode, TypeDescriptors, TypeNames,
342 M))
343 return false;
344
345 Member = TypeDescriptors[MemberNode];
346 }
347
348 uint64_t Offset =
349 mdconst::extract<ConstantInt>(MD->getOperand(i + 1))->getZExtValue();
350
351 Members.push_back(std::make_pair(Member, Offset));
352 }
353
354 // The descriptor for a scalar is:
355 // [2, member count, [type pointer, offset]..., name]
356
357 LLVMContext &C = MD->getContext();
358 Constant *NameData = ConstantDataArray::getString(C, NameNode->getString());
359 SmallVector<Type *> TDSubTys;
360 SmallVector<Constant *> TDSubData;
361
362 auto PushTDSub = [&](Constant *C) {
363 TDSubTys.push_back(C->getType());
364 TDSubData.push_back(C);
365 };
366
367 PushTDSub(ConstantInt::get(IntptrTy, 2));
368 PushTDSub(ConstantInt::get(IntptrTy, Members.size()));
369
370 // Types that are in an anonymous namespace are local to this module.
371 // FIXME: This should really be marked by the frontend in the metadata
372 // instead of having us guess this from the mangled name. Moreover, the regex
373 // here can pick up (unlikely) names in the non-reserved namespace (because
374 // it needs to search into the type to pick up cases where the type in the
375 // anonymous namespace is a template parameter, etc.).
376 bool ShouldBeComdat = !AnonNameRegex.match(NameNode->getString());
377 for (auto &Member : Members) {
378 PushTDSub(Member.first);
379 PushTDSub(ConstantInt::get(IntptrTy, Member.second));
380 }
381
382 PushTDSub(NameData);
383
384 StructType *TDTy = StructType::get(C, TDSubTys);
385 Constant *TD = ConstantStruct::get(TDTy, TDSubData);
386
387 GlobalVariable *TDGV =
388 new GlobalVariable(TDTy, true,
389 !ShouldBeComdat ? GlobalValue::InternalLinkage
391 TD, EncodedName);
392 M.insertGlobalVariable(TDGV);
393
394 if (ShouldBeComdat) {
395 if (TargetTriple.isOSBinFormatELF()) {
396 Comdat *TDComdat = M.getOrInsertComdat(EncodedName);
397 TDGV->setComdat(TDComdat);
398 }
399 appendToUsed(M, TDGV);
400 }
401
402 TypeDescriptors[MD] = TDGV;
403 return true;
404}
405
406bool TypeSanitizer::generateTypeDescriptor(
407 const MDNode *MD, TypeDescriptorsMapTy &TypeDescriptors,
408 TypeNameMapTy &TypeNames, Module &M) {
409 // Here we need to generate a type descriptor corresponding to this TBAA
410 // metadata node. Under the current scheme there are three kinds of TBAA
411 // metadata nodes: scalar nodes, struct nodes, and struct tag nodes.
412
413 if (MD->getNumOperands() < 3)
414 return false;
415
416 const MDNode *BaseNode = dyn_cast<MDNode>(MD->getOperand(0));
417 if (!BaseNode)
418 return false;
419
420 // This is a struct tag (element-access) node.
421
422 const MDNode *AccessNode = dyn_cast<MDNode>(MD->getOperand(1));
423 if (!AccessNode)
424 return false;
425
426 Constant *Base;
427 auto TDI = TypeDescriptors.find(BaseNode);
428 if (TDI != TypeDescriptors.end()) {
429 Base = TDI->second;
430 } else {
431 if (!generateBaseTypeDescriptor(BaseNode, TypeDescriptors, TypeNames, M))
432 return false;
433
434 Base = TypeDescriptors[BaseNode];
435 }
436
438 TDI = TypeDescriptors.find(AccessNode);
439 if (TDI != TypeDescriptors.end()) {
440 Access = TDI->second;
441 } else {
442 if (!generateBaseTypeDescriptor(AccessNode, TypeDescriptors, TypeNames, M))
443 return false;
444
445 Access = TypeDescriptors[AccessNode];
446 }
447
448 uint64_t Offset =
449 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue();
450 std::string EncodedName =
451 std::string(Base->getName()) + "_o_" + utostr(Offset);
452
453 GlobalVariable *GV =
454 dyn_cast_or_null<GlobalVariable>(M.getNamedValue(EncodedName));
455 if (GV) {
456 TypeDescriptors[MD] = GV;
457 return true;
458 }
459
460 // The descriptor for a scalar is:
461 // [1, base-type pointer, access-type pointer, offset]
462
463 StructType *TDTy =
464 StructType::get(IntptrTy, Base->getType(), Access->getType(), IntptrTy);
465 Constant *TD =
466 ConstantStruct::get(TDTy, ConstantInt::get(IntptrTy, 1), Base, Access,
467 ConstantInt::get(IntptrTy, Offset));
468
469 bool ShouldBeComdat = cast<GlobalVariable>(Base)->getLinkage() ==
471
472 GlobalVariable *TDGV =
473 new GlobalVariable(TDTy, true,
474 !ShouldBeComdat ? GlobalValue::InternalLinkage
476 TD, EncodedName);
477 M.insertGlobalVariable(TDGV);
478
479 if (ShouldBeComdat) {
480 if (TargetTriple.isOSBinFormatELF()) {
481 Comdat *TDComdat = M.getOrInsertComdat(EncodedName);
482 TDGV->setComdat(TDComdat);
483 }
484 appendToUsed(M, TDGV);
485 }
486
487 TypeDescriptors[MD] = TDGV;
488 return true;
489}
490
491Instruction *TypeSanitizer::getShadowBase(Function &F) {
492 IRBuilder<> IRB(&F.front().front());
493 Constant *GlobalShadowAddress =
494 F.getParent()->getOrInsertGlobal(kTysanShadowMemoryAddress, IntptrTy);
495 return IRB.CreateLoad(IntptrTy, GlobalShadowAddress, "shadow.base");
496}
497
498Instruction *TypeSanitizer::getAppMemMask(Function &F) {
499 IRBuilder<> IRB(&F.front().front());
500 Value *GlobalAppMemMask =
501 F.getParent()->getOrInsertGlobal(kTysanAppMemMask, IntptrTy);
502 return IRB.CreateLoad(IntptrTy, GlobalAppMemMask, "app.mem.mask");
503}
504
505/// Collect all loads and stores, and for what TBAA nodes we need to generate
506/// type descriptors.
508 Function &F, const TargetLibraryInfo &TLI,
509 SmallVectorImpl<std::pair<Instruction *, MemoryLocation>> &MemoryAccesses,
511 SmallVectorImpl<Value *> &MemTypeResetInsts) {
512 // Traverse all instructions, collect loads/stores/returns, check for calls.
513 for (Instruction &Inst : instructions(F)) {
514 // Skip memory accesses inserted by another instrumentation.
515 if (Inst.getMetadata(LLVMContext::MD_nosanitize))
516 continue;
517
518 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst) ||
521
522 // Swift errors are special (we can't introduce extra uses on them).
523 if (MLoc.Ptr->isSwiftError())
524 continue;
525
526 // Skip non-address-space-0 pointers; we don't know how to handle them.
527 Type *PtrTy = cast<PointerType>(MLoc.Ptr->getType());
528 if (PtrTy->getPointerAddressSpace() != 0)
529 continue;
530
531 if (MLoc.AATags.TBAA)
532 TBAAMetadata.insert(MLoc.AATags.TBAA);
533 MemoryAccesses.push_back(std::make_pair(&Inst, MLoc));
534 } else if (isa<CallInst>(Inst) || isa<InvokeInst>(Inst)) {
535 if (CallInst *CI = dyn_cast<CallInst>(&Inst))
537
539 MemTypeResetInsts.push_back(&Inst);
540 } else if (isa<AllocaInst>(Inst)) {
541 MemTypeResetInsts.push_back(&Inst);
542 }
543 }
544}
545
546bool TypeSanitizer::sanitizeFunction(Function &F,
547 const TargetLibraryInfo &TLI) {
548 if (F.isDeclaration())
549 return false;
550 // This is required to prevent instrumenting call to __tysan_init from within
551 // the module constructor.
552 if (&F == TysanCtorFunction.getCallee() || &F == TysanGlobalsSetTypeFunction)
553 return false;
554 initializeCallbacks(*F.getParent());
555
556 // We need to collect all loads and stores, and know for what TBAA nodes we
557 // need to generate type descriptors.
559 SmallSetVector<const MDNode *, 8> TBAAMetadata;
560 SmallVector<Value *> MemTypeResetInsts;
561 collectMemAccessInfo(F, TLI, MemoryAccesses, TBAAMetadata, MemTypeResetInsts);
562
563 // byval arguments also need their types reset (they're new stack memory,
564 // just like allocas).
565 for (auto &A : F.args())
566 if (A.hasByValAttr())
567 MemTypeResetInsts.push_back(&A);
568
569 Module &M = *F.getParent();
570 TypeDescriptorsMapTy TypeDescriptors;
571 TypeNameMapTy TypeNames;
572 bool Res = false;
573 for (const MDNode *MD : TBAAMetadata) {
574 if (TypeDescriptors.count(MD))
575 continue;
576
577 if (!generateTypeDescriptor(MD, TypeDescriptors, TypeNames, M))
578 return Res; // Giving up.
579
580 Res = true;
581 }
582
583 const DataLayout &DL = F.getParent()->getDataLayout();
584 bool SanitizeFunction = F.hasFnAttribute(Attribute::SanitizeType);
585 bool NeedsInstrumentation =
586 MemTypeResetInsts.empty() && MemoryAccesses.empty();
587 Instruction *ShadowBase = NeedsInstrumentation ? nullptr : getShadowBase(F);
588 Instruction *AppMemMask = NeedsInstrumentation ? nullptr : getAppMemMask(F);
589 for (const auto &[I, MLoc] : MemoryAccesses) {
590 IRBuilder<> IRB(I);
591 assert(MLoc.Size.isPrecise());
592 if (instrumentWithShadowUpdate(
593 IRB, MLoc.AATags.TBAA, const_cast<Value *>(MLoc.Ptr),
594 MLoc.Size.getValue(), I->mayReadFromMemory(), I->mayWriteToMemory(),
595 ShadowBase, AppMemMask, false, SanitizeFunction, TypeDescriptors,
596 DL)) {
597 ++NumInstrumentedAccesses;
598 Res = true;
599 }
600 }
601
602 for (auto Inst : MemTypeResetInsts)
603 Res |= instrumentMemInst(Inst, ShadowBase, AppMemMask, DL);
604
605 return Res;
606}
607
609 Type *IntptrTy, uint64_t PtrShift,
610 Value *ShadowBase, Value *AppMemMask) {
611 return IRB.CreateAdd(
612 IRB.CreateShl(
613 IRB.CreateAnd(IRB.CreatePtrToInt(Ptr, IntptrTy, "app.ptr.int"),
614 AppMemMask, "app.ptr.masked"),
615 PtrShift, "app.ptr.shifted"),
616 ShadowBase, "shadow.ptr.int");
617}
618
619bool TypeSanitizer::instrumentWithShadowUpdate(
620 IRBuilder<> &IRB, const MDNode *TBAAMD, Value *Ptr, uint64_t AccessSize,
621 bool IsRead, bool IsWrite, Value *ShadowBase, Value *AppMemMask,
622 bool ForceSetType, bool SanitizeFunction,
623 TypeDescriptorsMapTy &TypeDescriptors, const DataLayout &DL) {
624 Constant *TDGV;
625 if (TBAAMD)
626 TDGV = TypeDescriptors[TBAAMD];
627 else
628 TDGV = Constant::getNullValue(IRB.getPtrTy());
629
630 Value *TD = IRB.CreateBitCast(TDGV, IRB.getPtrTy());
631
633 if (!ForceSetType && (!ClWritesAlwaysSetType || IsRead)) {
634 // We need to check the type here. If the type is unknown, then the read
635 // sets the type. If the type is known, then it is checked. If the type
636 // doesn't match, then we call the runtime type check (which may yet
637 // determine that the mismatch is okay).
638
639 Constant *Flags =
640 ConstantInt::get(OrdTy, (int)IsRead | (((int)IsWrite) << 1));
641
642 IRB.CreateCall(TysanInstrumentWithShadowUpdate,
643 {Ptr, TD,
644 SanitizeFunction ? IRB.getTrue() : IRB.getFalse(),
645 IRB.getInt64(AccessSize), Flags});
646 } else if (ForceSetType || IsWrite) {
647 // In the mode where writes always set the type, for a write (which does
648 // not also read), we just set the type.
649 IRB.CreateCall(TysanSetShadowType, {Ptr, TD, IRB.getInt64(AccessSize)});
650 }
651
652 return true;
653 }
654
655 Value *ShadowDataInt = convertToShadowDataInt(IRB, Ptr, IntptrTy, PtrShift,
656 ShadowBase, AppMemMask);
657 Type *Int8PtrPtrTy = PointerType::get(IRB.getContext(), 0);
658 Value *ShadowData =
659 IRB.CreateIntToPtr(ShadowDataInt, Int8PtrPtrTy, "shadow.ptr");
660
661 auto SetType = [&]() {
662 IRB.CreateStore(TD, ShadowData);
663
664 // Now fill the remainder of the shadow memory corresponding to the
665 // remainder of the the bytes of the type with a bad type descriptor.
666 for (uint64_t i = 1; i < AccessSize; ++i) {
667 Value *BadShadowData = IRB.CreateIntToPtr(
668 IRB.CreateAdd(ShadowDataInt,
669 ConstantInt::get(IntptrTy, i << PtrShift),
670 "shadow.byte." + Twine(i) + ".offset"),
671 Int8PtrPtrTy, "shadow.byte." + Twine(i) + ".ptr");
672
673 // This is the TD value, -i, which is used to indicate that the byte is
674 // i bytes after the first byte of the type.
675 Value *BadTD =
676 IRB.CreateIntToPtr(ConstantInt::getSigned(IntptrTy, -i),
677 IRB.getPtrTy(), "bad.descriptor" + Twine(i));
678 IRB.CreateStore(BadTD, BadShadowData);
679 }
680 };
681
682 if (ForceSetType || (ClWritesAlwaysSetType && IsWrite)) {
683 // In the mode where writes always set the type, for a write (which does
684 // not also read), we just set the type.
685 SetType();
686 return true;
687 }
688
689 assert((!ClWritesAlwaysSetType || IsRead) &&
690 "should have handled case above");
691 LLVMContext &C = IRB.getContext();
692 MDNode *UnlikelyBW = MDBuilder(C).createBranchWeights(1, 100000);
693
694 if (!SanitizeFunction) {
695 // If we're not sanitizing this function, then we only care whether we
696 // need to *set* the type.
697 Value *LoadedTD = IRB.CreateLoad(IRB.getPtrTy(), ShadowData, "shadow.desc");
698 Value *NullTDCmp = IRB.CreateIsNull(LoadedTD, "desc.set");
700 NullTDCmp, &*IRB.GetInsertPoint(), false, UnlikelyBW);
701 IRB.SetInsertPoint(NullTDTerm);
702 NullTDTerm->getParent()->setName("set.type");
703 SetType();
704 return true;
705 }
706 // We need to check the type here. If the type is unknown, then the read
707 // sets the type. If the type is known, then it is checked. If the type
708 // doesn't match, then we call the runtime (which may yet determine that
709 // the mismatch is okay).
710 //
711 // The checks generated below have the following structure.
712 //
713 // ; First we load the descriptor for the load from shadow memory and
714 // ; compare it against the type descriptor for the current access type.
715 // %shadow.desc = load ptr %shadow.data
716 // %bad.desc = icmp ne %shadow.desc, %td
717 // br %bad.desc, %bad.bb, %good.bb
718 //
719 // bad.bb:
720 // %shadow.desc.null = icmp eq %shadow.desc, null
721 // br %shadow.desc.null, %null.td.bb, %good.td.bb
722 //
723 // null.td.bb:
724 // ; The typ is unknown, set it if all bytes in the value are also unknown.
725 // ; To check, we load the shadow data for all bytes of the access. For the
726 // ; pseudo code below, assume an access of size 1.
727 // %shadow.data.int = add %shadow.data.int, 0
728 // %l = load (inttoptr %shadow.data.int)
729 // %is.not.null = icmp ne %l, null
730 // %not.all.unknown = %is.not.null
731 // br %no.all.unknown, before.set.type.bb
732 //
733 // before.set.type.bb:
734 // ; Call runtime to check mismatch.
735 // call void @__tysan_check()
736 // br %set.type.bb
737 //
738 // set.type.bb:
739 // ; Now fill the remainder of the shadow memory corresponding to the
740 // ; remainder of the the bytes of the type with a bad type descriptor.
741 // store %TD, %shadow.data
742 // br %continue.bb
743 //
744 // good.td.bb::
745 // ; We have a non-trivial mismatch. Call the runtime.
746 // call void @__tysan_check()
747 // br %continue.bb
748 //
749 // good.bb:
750 // ; We appear to have the right type. Make sure that all other bytes in
751 // ; the type are still marked as interior bytes. If not, call the runtime.
752 // %shadow.data.int = add %shadow.data.int, 0
753 // %l = load (inttoptr %shadow.data.int)
754 // %not.all.interior = icmp sge %l, 0
755 // br %not.all.interior, label %check.rt.bb, label %continue.bb
756 //
757 // check.rt.bb:
758 // call void @__tysan_check()
759 // br %continue.bb
760
761 Constant *Flags = ConstantInt::get(OrdTy, int(IsRead) | (int(IsWrite) << 1));
762
763 Value *LoadedTD = IRB.CreateLoad(IRB.getPtrTy(), ShadowData, "shadow.desc");
764 Value *BadTDCmp = IRB.CreateICmpNE(LoadedTD, TD, "bad.desc");
765 Instruction *BadTDTerm, *GoodTDTerm;
766 SplitBlockAndInsertIfThenElse(BadTDCmp, &*IRB.GetInsertPoint(), &BadTDTerm,
767 &GoodTDTerm, UnlikelyBW);
768 IRB.SetInsertPoint(BadTDTerm);
769
770 // We now know that the types did not match (we're on the slow path). If
771 // the type is unknown, then set it.
772 Value *NullTDCmp = IRB.CreateIsNull(LoadedTD);
773 Instruction *NullTDTerm, *MismatchTerm;
774 SplitBlockAndInsertIfThenElse(NullTDCmp, &*IRB.GetInsertPoint(), &NullTDTerm,
775 &MismatchTerm);
776
777 // If the type is unknown, then set the type.
778 IRB.SetInsertPoint(NullTDTerm);
779
780 // We're about to set the type. Make sure that all bytes in the value are
781 // also of unknown type.
782 Value *Size = ConstantInt::get(OrdTy, AccessSize);
783 Value *NotAllUnkTD = IRB.getFalse();
784 for (uint64_t i = 1; i < AccessSize; ++i) {
785 Value *UnkShadowData = IRB.CreateIntToPtr(
786 IRB.CreateAdd(ShadowDataInt, ConstantInt::get(IntptrTy, i << PtrShift)),
787 Int8PtrPtrTy);
788 Value *ILdTD = IRB.CreateLoad(IRB.getPtrTy(), UnkShadowData);
789 NotAllUnkTD = IRB.CreateOr(NotAllUnkTD, IRB.CreateIsNotNull(ILdTD));
790 }
791
792 Instruction *BeforeSetType = &*IRB.GetInsertPoint();
793 Instruction *BadUTDTerm =
794 SplitBlockAndInsertIfThen(NotAllUnkTD, BeforeSetType, false, UnlikelyBW);
795 IRB.SetInsertPoint(BadUTDTerm);
796 IRB.CreateCall(TysanCheck, {IRB.CreateBitCast(Ptr, IRB.getPtrTy()), Size,
797 (Value *)TD, (Value *)Flags});
798
799 IRB.SetInsertPoint(BeforeSetType);
800 SetType();
801
802 // We have a non-trivial mismatch. Call the runtime.
803 IRB.SetInsertPoint(MismatchTerm);
804 IRB.CreateCall(TysanCheck, {IRB.CreateBitCast(Ptr, IRB.getPtrTy()), Size,
805 (Value *)TD, (Value *)Flags});
806
807 // We appear to have the right type. Make sure that all other bytes in
808 // the type are still marked as interior bytes. If not, call the runtime.
809 IRB.SetInsertPoint(GoodTDTerm);
810 Value *NotAllBadTD = IRB.getFalse();
811 for (uint64_t i = 1; i < AccessSize; ++i) {
812 Value *BadShadowData = IRB.CreateIntToPtr(
813 IRB.CreateAdd(ShadowDataInt, ConstantInt::get(IntptrTy, i << PtrShift)),
814 Int8PtrPtrTy);
815 Value *ILdTD = IRB.CreatePtrToInt(
816 IRB.CreateLoad(IRB.getPtrTy(), BadShadowData), IntptrTy);
817 NotAllBadTD = IRB.CreateOr(
818 NotAllBadTD, IRB.CreateICmpSGE(ILdTD, ConstantInt::get(IntptrTy, 0)));
819 }
820
822 NotAllBadTD, &*IRB.GetInsertPoint(), false, UnlikelyBW);
823 IRB.SetInsertPoint(BadITDTerm);
824 IRB.CreateCall(TysanCheck, {IRB.CreateBitCast(Ptr, IRB.getPtrTy()), Size,
825 (Value *)TD, (Value *)Flags});
826 return true;
827}
828
829bool TypeSanitizer::instrumentMemInst(Value *V, Instruction *ShadowBase,
830 Instruction *AppMemMask,
831 const DataLayout &DL) {
833 BasicBlock *BB;
834 Function *F;
835
836 if (auto *I = dyn_cast<Instruction>(V)) {
838 BB = I->getParent();
839 F = BB->getParent();
840 } else {
841 auto *A = cast<Argument>(V);
842 F = A->getParent();
843 BB = &F->getEntryBlock();
844 IP = BB->getFirstInsertionPt();
845
846 // Find the next insert point after both ShadowBase and AppMemMask.
847 if (IP->comesBefore(ShadowBase))
848 IP = ShadowBase->getNextNode()->getIterator();
849 if (IP->comesBefore(AppMemMask))
850 IP = AppMemMask->getNextNode()->getIterator();
851 }
852
853 Value *Dest, *Size, *Src = nullptr;
854 bool NeedsMemMove = false;
855 IRBuilder<> IRB(BB, IP);
856
857 auto GetAllocaSize = [&](AllocaInst *AI) {
858 return IRB.CreateMul(
859 IRB.CreateZExtOrTrunc(AI->getArraySize(), IntptrTy),
860 ConstantInt::get(IntptrTy,
861 DL.getTypeAllocSize(AI->getAllocatedType())));
862 };
863
864 if (auto *A = dyn_cast<Argument>(V)) {
865 assert(A->hasByValAttr() && "Type reset for non-byval argument?");
866
867 Dest = A;
868 Size =
869 ConstantInt::get(IntptrTy, DL.getTypeAllocSize(A->getParamByValType()));
870 } else {
871 auto *I = cast<Instruction>(V);
872 if (auto *MI = dyn_cast<MemIntrinsic>(I)) {
873 if (MI->getDestAddressSpace() != 0)
874 return false;
875
876 Dest = MI->getDest();
877 Size = MI->getLength();
878
879 if (auto *MTI = dyn_cast<MemTransferInst>(MI)) {
880 if (MTI->getSourceAddressSpace() == 0) {
881 Src = MTI->getSource();
882 NeedsMemMove = isa<MemMoveInst>(MTI);
883 }
884 }
885 } else if (auto *II = dyn_cast<LifetimeIntrinsic>(I)) {
886 auto *AI = dyn_cast<AllocaInst>(II->getArgOperand(0));
887 if (!AI)
888 return false;
889
890 Size = GetAllocaSize(AI);
891 Dest = II->getArgOperand(0);
892 } else if (auto *AI = dyn_cast<AllocaInst>(I)) {
893 // We need to clear the types for new stack allocations (or else we might
894 // read stale type information from a previous function execution).
895
896 IRB.SetInsertPoint(&*std::next(BasicBlock::iterator(I)));
898
899 Size = GetAllocaSize(AI);
900 Dest = I;
901 } else {
902 return false;
903 }
904 }
905
907 if (!Src)
909
910 IRB.CreateCall(
911 TysanIntrumentMemInst,
912 {Dest, Src, Size, NeedsMemMove ? IRB.getTrue() : IRB.getFalse()});
913 return true;
914 } else {
915 if (!ShadowBase)
916 ShadowBase = getShadowBase(*F);
917 if (!AppMemMask)
918 AppMemMask = getAppMemMask(*F);
919
920 Value *ShadowDataInt = IRB.CreateAdd(
921 IRB.CreateShl(
922 IRB.CreateAnd(IRB.CreatePtrToInt(Dest, IntptrTy), AppMemMask),
923 PtrShift),
924 ShadowBase);
925 Value *ShadowData = IRB.CreateIntToPtr(ShadowDataInt, IRB.getPtrTy());
926
927 if (!Src) {
928 IRB.CreateMemSet(ShadowData, IRB.getInt8(0),
929 IRB.CreateShl(Size, PtrShift), Align(1ull << PtrShift));
930 return true;
931 }
932
933 Value *SrcShadowDataInt = IRB.CreateAdd(
934 IRB.CreateShl(
935 IRB.CreateAnd(IRB.CreatePtrToInt(Src, IntptrTy), AppMemMask),
936 PtrShift),
937 ShadowBase);
938 Value *SrcShadowData = IRB.CreateIntToPtr(SrcShadowDataInt, IRB.getPtrTy());
939
940 if (NeedsMemMove) {
941 IRB.CreateMemMove(ShadowData, Align(1ull << PtrShift), SrcShadowData,
942 Align(1ull << PtrShift), IRB.CreateShl(Size, PtrShift));
943 } else {
944 IRB.CreateMemCpy(ShadowData, Align(1ull << PtrShift), SrcShadowData,
945 Align(1ull << PtrShift), IRB.CreateShl(Size, PtrShift));
946 }
947 }
948
949 return true;
950}
951
954 Function *TysanCtorFunction;
955 std::tie(TysanCtorFunction, std::ignore) =
957 kTysanInitName, /*InitArgTypes=*/{},
958 /*InitArgs=*/{});
959
960 TypeSanitizer TySan(M);
961 TySan.instrumentGlobals(M);
962 appendToGlobalCtors(M, TysanCtorFunction, 0);
963
964 auto &FAM = MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
965 for (Function &F : M) {
966 const TargetLibraryInfo &TLI = FAM.getResult<TargetLibraryAnalysis>(F);
967 TySan.sanitizeFunction(F, TLI);
969 // Outlined instrumentation is a new option, and so this exists to
970 // verify there is no difference in behaviour between the options.
971 // If the outlined instrumentation triggers a verification failure
972 // when the original inlined instrumentation does not, or vice versa,
973 // then there is a discrepency which should be investigated.
975 TySan.sanitizeFunction(F, TLI);
977 }
978 }
979
981}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
DXIL Resource Access
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition MD5.cpp:55
#define I(x, y, z)
Definition MD5.cpp:58
Machine Check Debug Module
This file provides utility analysis objects describing memory locations.
This file contains the declarations for metadata subclasses.
uint64_t IntrinsicInst * II
FunctionAnalysisManager FAM
ModuleAnalysisManager MAM
This file implements a set that has insertion order iteration characteristics.
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 STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
This file contains some functions that are useful when dealing with strings.
static const char *const kTysanInitName
static Value * convertToShadowDataInt(IRBuilder<> &IRB, Value *Ptr, Type *IntptrTy, uint64_t PtrShift, Value *ShadowBase, Value *AppMemMask)
static const char *const kTysanShadowMemoryAddress
static const char LUT[]
static const char *const kTysanGVNamePrefix
static const char *const kTysanModuleCtorName
static const char *const kTysanAppMemMask
void collectMemAccessInfo(Function &F, const TargetLibraryInfo &TLI, SmallVectorImpl< std::pair< Instruction *, MemoryLocation > > &MemoryAccesses, SmallSetVector< const MDNode *, 8 > &TBAAMetadata, SmallVectorImpl< Value * > &MemTypeResetInsts)
Collect all loads and stores, and for what TBAA nodes we need to generate type descriptors.
static cl::opt< bool > ClVerifyOutlinedInstrumentation("tysan-verify-outlined-instrumentation", cl::desc("Check types twice with both inlined instrumentation and " "function calls. This verifies that they behave the same."), cl::Hidden, cl::init(false))
static cl::opt< bool > ClWritesAlwaysSetType("tysan-writes-always-set-type", cl::desc("Writes always set the type"), cl::Hidden, cl::init(false))
static cl::opt< bool > ClOutlineInstrumentation("tysan-outline-instrumentation", cl::desc("Uses function calls for all TySan instrumentation, reducing " "ELF size"), cl::Hidden, cl::init(false))
static const char *const kTysanCheckName
static std::string encodeName(StringRef Name)
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition BasicBlock.h:233
This class represents a function call, abstracting a target machine's calling convention.
static LLVM_ABI Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true)
This method constructs a CDS and initializes it with a text string.
static ConstantInt * getSigned(IntegerType *Ty, int64_t V)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:131
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
static LLVM_ABI Constant * get(StructType *T, ArrayRef< Constant * > V)
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
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition Function.h:166
const BasicBlock & getEntryBlock() const
Definition Function.h:807
LLVM_ABI void setComdat(Comdat *C)
Definition Globals.cpp:214
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:56
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
CallInst * CreateMemCpy(Value *Dst, MaybeAlign DstAlign, Value *Src, MaybeAlign SrcAlign, uint64_t Size, bool isVolatile=false, const AAMDNodes &AAInfo=AAMDNodes())
Create and insert a memcpy between the specified pointers.
Definition IRBuilder.h:687
ConstantInt * getTrue()
Get the constant value for i1 true.
Definition IRBuilder.h:502
Value * CreateICmpSGE(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2360
BasicBlock::iterator GetInsertPoint() const
Definition IRBuilder.h:202
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2202
ConstantInt * getInt8(uint8_t C)
Get a constant 8-bit value.
Definition IRBuilder.h:512
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2336
ConstantInt * getInt64(uint64_t C)
Get a constant 64-bit value.
Definition IRBuilder.h:527
CallInst * CreateMemMove(Value *Dst, MaybeAlign DstAlign, Value *Src, MaybeAlign SrcAlign, uint64_t Size, bool isVolatile=false, const AAMDNodes &AAInfo=AAMDNodes())
Definition IRBuilder.h:729
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2207
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
CallInst * CreateMemSet(Value *Ptr, Value *Val, uint64_t Size, MaybeAlign Align, bool isVolatile=false, const AAMDNodes &AAInfo=AAMDNodes())
Create and insert a memset to the specified pointer and the specified value.
Definition IRBuilder.h:630
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 * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1403
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2197
ConstantInt * getFalse()
Get the constant value for i1 false.
Definition IRBuilder.h:507
Value * CreateIsNotNull(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg != 0.
Definition IRBuilder.h:2659
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 * CreateIsNull(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg == 0.
Definition IRBuilder.h:2654
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:207
LLVM_ABI void SetInstDebugLocation(Instruction *I) const
If this builder has a current debug location, set it on the specified instruction.
Definition IRBuilder.cpp:65
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Definition IRBuilder.h:1573
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1437
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2788
Class to represent integer types.
LLVM_ABI void update(ArrayRef< uint8_t > Data)
Updates the hash for the byte stream provided.
Definition MD5.cpp:189
LLVM_ABI void final(MD5Result &Result)
Finishes off the hash and puts the result in result.
Definition MD5.cpp:234
Metadata node.
Definition Metadata.h:1078
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1442
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1448
LLVMContext & getContext() const
Definition Metadata.h:1242
LLVM_ABI StringRef getString() const
Definition Metadata.cpp:618
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
const DataLayout & getDataLayout() const
Return the DataLayout attached to the Module associated to this MF.
Representation for a specific memory location.
static LLVM_ABI MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
AAMDNodes AATags
The metadata nodes which describes the aliasing of the location (each member is null if that kind of ...
const Value * Ptr
The address of the start of the location.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
iterator_range< op_iterator > operands()
Definition Metadata.h:1853
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
LLVM_ABI bool match(StringRef String, SmallVectorImpl< StringRef > *Matches=nullptr, std::string *Error=nullptr) const
matches - Match the regex against a given String.
Definition Regex.cpp:83
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, InsertPosition InsertBefore=nullptr)
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:150
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:338
StringRef str() const
Explicit conversion to StringRef.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
std::string str() const
str - Get the contents as an std::string.
Definition StringRef.h:225
static LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition Type.cpp:414
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:47
bool isOSBinFormatELF() const
Tests whether the OS uses the ELF binary format.
Definition Triple.h:771
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:45
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:298
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:297
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition Type.h:311
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:294
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:256
LLVM_ABI bool isSwiftError() const
Return true if this value is a swifterror value.
Definition Value.cpp:1120
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
initializer< Ty > init(const Ty &Val)
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract_or_null(Y &&MD)
Extract a Value from Metadata, if any, allowing null.
Definition Metadata.h:708
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:667
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
@ Length
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
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
std::string utostr(uint64_t X, bool isNeg=false)
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:202
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
LLVM_ABI std::pair< Function *, FunctionCallee > createSanitizerCtorAndInitFunctions(Module &M, StringRef CtorName, StringRef InitName, ArrayRef< Type * > InitArgTypes, ArrayRef< Value * > InitArgs, StringRef VersionCheckName=StringRef(), bool Weak=false)
Creates sanitizer constructor function, and calls sanitizer's init function from it.
LLVM_ABI void SplitBlockAndInsertIfThenElse(Value *Cond, BasicBlock::iterator SplitBefore, Instruction **ThenTerm, Instruction **ElseTerm, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr)
SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen, but also creates the ElseBlock...
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 >
LLVM_ABI 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.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI Instruction * SplitBlockAndInsertIfThen(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
LLVM_ABI void maybeMarkSanitizerLibraryCallNoBuiltin(CallInst *CI, const TargetLibraryInfo *TLI)
Given a CallInst, check if it calls a string function known to CodeGen, and mark it with NoBuiltin if...
Definition Local.cpp:3861
LLVM_ABI void appendToUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.used list.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
MDNode * TBAA
The tag for type-based alias analysis.
Definition Metadata.h:778
LLVM_ABI SmallString< 32 > digest() const
Definition MD5.cpp:281
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)