LLVM 24.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(true));
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 LLVMContext &C = M.getContext();
148 IRBuilder<> IRB(C);
149 OrdTy = IRB.getInt32Ty();
150 U64Ty = IRB.getInt64Ty();
151 Type *BoolType = IRB.getInt1Ty();
152
153 AttributeList Attr;
154 Attr = Attr.addFnAttribute(C, Attribute::NoUnwind);
155 Attribute::AttrKind SExtAttr =
156 TargetLibraryInfo::getExtAttrForI32Param(TargetTriple, /*Signed=*/true);
157 Attribute::AttrKind BoolExtAttr =
159
160 // Initialize the callbacks. TODO: use TLI/emitLibFunc() for these functions.
161 TysanCheck =
162 M.getOrInsertFunction(kTysanCheckName,
163 Attr.maybeAddParamAttribute(C, 1, SExtAttr)
164 .maybeAddParamAttribute(C, 3, SExtAttr),
165 IRB.getVoidTy(),
166 IRB.getPtrTy(), // Pointer to data to be read.
167 OrdTy, // Size of the data in bytes.
168 IRB.getPtrTy(), // Pointer to type descriptor.
169 OrdTy // Flags.
170 );
171
172 TysanCtorFunction =
173 M.getOrInsertFunction(kTysanModuleCtorName, Attr, IRB.getVoidTy());
174
175 TysanIntrumentMemInst = M.getOrInsertFunction(
176 "__tysan_instrument_mem_inst",
177 Attr.maybeAddParamAttribute(C, 3, BoolExtAttr), IRB.getVoidTy(),
178 IRB.getPtrTy(), // Pointer of data to be written to
179 IRB.getPtrTy(), // Pointer of data to write
180 U64Ty, // Size of the data in bytes
181 BoolType // Do we need to call memmove
182 );
183
184 TysanInstrumentWithShadowUpdate =
185 M.getOrInsertFunction("__tysan_instrument_with_shadow_update",
186 Attr.maybeAddParamAttribute(C, 2, BoolExtAttr)
187 .maybeAddParamAttribute(C, 4, SExtAttr),
188 IRB.getVoidTy(),
189 IRB.getPtrTy(), // Pointer to data to be read
190 IRB.getPtrTy(), // Pointer to type descriptor
191 BoolType, // Do we need to type check this
192 U64Ty, // Size of data we access in bytes
193 OrdTy // Flags
194 );
195
196 TysanSetShadowType = M.getOrInsertFunction(
197 "__tysan_set_shadow_type", Attr, IRB.getVoidTy(),
198 IRB.getPtrTy(), // Pointer of data to be written to
199 IRB.getPtrTy(), // Pointer to the new type descriptor
200 U64Ty // Size of data we access in bytes
201 );
202}
203
204void TypeSanitizer::instrumentGlobals(Module &M) {
205 TysanGlobalsSetTypeFunction = nullptr;
206
207 NamedMDNode *Globals = M.getNamedMetadata("llvm.tysan.globals");
208 if (!Globals)
209 return;
210
211 TysanGlobalsSetTypeFunction = Function::Create(
212 FunctionType::get(Type::getVoidTy(M.getContext()), false),
213 GlobalValue::InternalLinkage, "__tysan_set_globals_types", &M);
214 BasicBlock *BB =
215 BasicBlock::Create(M.getContext(), "", TysanGlobalsSetTypeFunction);
216 ReturnInst::Create(M.getContext(), BB);
217
218 const DataLayout &DL = M.getDataLayout();
219 Value *ShadowBase = getShadowBase(*TysanGlobalsSetTypeFunction);
220 Value *AppMemMask = getAppMemMask(*TysanGlobalsSetTypeFunction);
221 TypeDescriptorsMapTy TypeDescriptors;
222 TypeNameMapTy TypeNames;
223
224 for (const auto &GMD : Globals->operands()) {
225 auto *GV = mdconst::dyn_extract_or_null<GlobalVariable>(GMD->getOperand(0));
226 if (!GV)
227 continue;
228 const MDNode *TBAAMD = cast<MDNode>(GMD->getOperand(1));
229 if (!generateBaseTypeDescriptor(TBAAMD, TypeDescriptors, TypeNames, M))
230 continue;
231
232 IRBuilder<> IRB(
233 TysanGlobalsSetTypeFunction->getEntryBlock().getTerminator());
234 Type *AccessTy = GV->getValueType();
235 assert(AccessTy->isSized());
236 uint64_t AccessSize = DL.getTypeStoreSize(AccessTy);
237 instrumentWithShadowUpdate(IRB, TBAAMD, GV, AccessSize, false, false,
238 ShadowBase, AppMemMask, true, false,
239 TypeDescriptors, DL);
240 }
241
242 if (TysanGlobalsSetTypeFunction) {
243 IRBuilder<> IRB(cast<Function>(TysanCtorFunction.getCallee())
244 ->getEntryBlock()
245 .getTerminator());
246 IRB.CreateCall(TysanGlobalsSetTypeFunction, {});
247 }
248}
249
250static const char LUT[] = "0123456789abcdef";
251
252static std::string encodeName(StringRef Name) {
253 size_t Length = Name.size();
254 std::string Output = kTysanGVNamePrefix;
255 Output.reserve(Output.size() + 3 * Length);
256 for (size_t i = 0; i < Length; ++i) {
257 const unsigned char c = Name[i];
258 if (isalnum(c)) {
259 Output.push_back(c);
260 continue;
261 }
262
263 if (c == '_') {
264 Output.append("__");
265 continue;
266 }
267
268 Output.push_back('_');
269 Output.push_back(LUT[c >> 4]);
270 Output.push_back(LUT[c & 15]);
271 }
272
273 return Output;
274}
275
276std::string
277TypeSanitizer::getAnonymousStructIdentifier(const MDNode *MD,
278 TypeNameMapTy &TypeNames) {
279 MD5 Hash;
280
281 for (int i = 1, e = MD->getNumOperands(); i < e; i += 2) {
282 const MDNode *MemberNode = dyn_cast<MDNode>(MD->getOperand(i));
283 if (!MemberNode)
284 return "";
285
286 auto TNI = TypeNames.find(MemberNode);
287 std::string MemberName;
288 if (TNI != TypeNames.end()) {
289 MemberName = TNI->second;
290 } else {
291 if (MemberNode->getNumOperands() < 1)
292 return "";
293 MDString *MemberNameNode = dyn_cast<MDString>(MemberNode->getOperand(0));
294 if (!MemberNameNode)
295 return "";
296 MemberName = MemberNameNode->getString().str();
297 if (MemberName.empty())
298 MemberName = getAnonymousStructIdentifier(MemberNode, TypeNames);
299 if (MemberName.empty())
300 return "";
301 TypeNames[MemberNode] = MemberName;
302 }
303
304 Hash.update(MemberName);
305 Hash.update("\0");
306
308 mdconst::extract<ConstantInt>(MD->getOperand(i + 1))->getZExtValue();
309 Hash.update(utostr(Offset));
310 Hash.update("\0");
311 }
312
313 MD5::MD5Result HashResult;
314 Hash.final(HashResult);
315 return "__anonymous_" + std::string(HashResult.digest().str());
316}
317
318bool TypeSanitizer::generateBaseTypeDescriptor(
319 const MDNode *MD, TypeDescriptorsMapTy &TypeDescriptors,
320 TypeNameMapTy &TypeNames, Module &M) {
321 if (MD->getNumOperands() < 1)
322 return false;
323
324 MDString *NameNode = dyn_cast<MDString>(MD->getOperand(0));
325 if (!NameNode)
326 return false;
327
328 std::string Name = NameNode->getString().str();
329 if (Name.empty())
330 Name = getAnonymousStructIdentifier(MD, TypeNames);
331 if (Name.empty())
332 return false;
333 TypeNames[MD] = Name;
334 std::string EncodedName = encodeName(Name);
335
336 GlobalVariable *GV =
337 dyn_cast_or_null<GlobalVariable>(M.getNamedValue(EncodedName));
338 if (GV) {
339 TypeDescriptors[MD] = GV;
340 return true;
341 }
342
344 for (int i = 1, e = MD->getNumOperands(); i < e; i += 2) {
345 const MDNode *MemberNode = dyn_cast<MDNode>(MD->getOperand(i));
346 if (!MemberNode)
347 return false;
348
350 auto TDI = TypeDescriptors.find(MemberNode);
351 if (TDI != TypeDescriptors.end()) {
352 Member = TDI->second;
353 } else {
354 if (!generateBaseTypeDescriptor(MemberNode, TypeDescriptors, TypeNames,
355 M))
356 return false;
357
358 Member = TypeDescriptors[MemberNode];
359 }
360
362 mdconst::extract<ConstantInt>(MD->getOperand(i + 1))->getZExtValue();
363
364 Members.push_back(std::make_pair(Member, Offset));
365 }
366
367 // The descriptor for a scalar is:
368 // [2, member count, [type pointer, offset]..., name]
369
370 LLVMContext &C = MD->getContext();
371 Constant *NameData = ConstantDataArray::getString(C, NameNode->getString());
372 SmallVector<Type *> TDSubTys;
373 SmallVector<Constant *> TDSubData;
374
375 auto PushTDSub = [&](Constant *C) {
376 TDSubTys.push_back(C->getType());
377 TDSubData.push_back(C);
378 };
379
380 PushTDSub(ConstantInt::get(IntptrTy, 2));
381 PushTDSub(ConstantInt::get(IntptrTy, Members.size()));
382
383 // Types that are in an anonymous namespace are local to this module.
384 // FIXME: This should really be marked by the frontend in the metadata
385 // instead of having us guess this from the mangled name. Moreover, the regex
386 // here can pick up (unlikely) names in the non-reserved namespace (because
387 // it needs to search into the type to pick up cases where the type in the
388 // anonymous namespace is a template parameter, etc.).
389 bool ShouldBeComdat = !AnonNameRegex.match(NameNode->getString());
390 for (auto &Member : Members) {
391 PushTDSub(Member.first);
392 PushTDSub(ConstantInt::get(IntptrTy, Member.second));
393 }
394
395 PushTDSub(NameData);
396
397 StructType *TDTy = StructType::get(C, TDSubTys);
398 Constant *TD = ConstantStruct::get(TDTy, TDSubData);
399
400 GlobalVariable *TDGV =
401 new GlobalVariable(TDTy, true,
402 !ShouldBeComdat ? GlobalValue::InternalLinkage
404 TD, EncodedName);
405 M.insertGlobalVariable(TDGV);
406
407 if (ShouldBeComdat) {
408 if (TargetTriple.isOSBinFormatELF()) {
409 Comdat *TDComdat = M.getOrInsertComdat(EncodedName);
410 TDGV->setComdat(TDComdat);
411 }
412 appendToUsed(M, TDGV);
413 }
414
415 TypeDescriptors[MD] = TDGV;
416 return true;
417}
418
419bool TypeSanitizer::generateTypeDescriptor(
420 const MDNode *MD, TypeDescriptorsMapTy &TypeDescriptors,
421 TypeNameMapTy &TypeNames, Module &M) {
422 // Here we need to generate a type descriptor corresponding to this TBAA
423 // metadata node. Under the current scheme there are three kinds of TBAA
424 // metadata nodes: scalar nodes, struct nodes, and struct tag nodes.
425
426 if (MD->getNumOperands() < 3)
427 return false;
428
429 const MDNode *BaseNode = dyn_cast<MDNode>(MD->getOperand(0));
430 if (!BaseNode)
431 return false;
432
433 // This is a struct tag (element-access) node.
434
435 const MDNode *AccessNode = dyn_cast<MDNode>(MD->getOperand(1));
436 if (!AccessNode)
437 return false;
438
439 Constant *Base;
440 auto TDI = TypeDescriptors.find(BaseNode);
441 if (TDI != TypeDescriptors.end()) {
442 Base = TDI->second;
443 } else {
444 if (!generateBaseTypeDescriptor(BaseNode, TypeDescriptors, TypeNames, M))
445 return false;
446
447 Base = TypeDescriptors[BaseNode];
448 }
449
451 TDI = TypeDescriptors.find(AccessNode);
452 if (TDI != TypeDescriptors.end()) {
453 Access = TDI->second;
454 } else {
455 if (!generateBaseTypeDescriptor(AccessNode, TypeDescriptors, TypeNames, M))
456 return false;
457
458 Access = TypeDescriptors[AccessNode];
459 }
460
462 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue();
463 std::string EncodedName =
464 std::string(Base->getName()) + "_o_" + utostr(Offset);
465
466 GlobalVariable *GV =
467 dyn_cast_or_null<GlobalVariable>(M.getNamedValue(EncodedName));
468 if (GV) {
469 TypeDescriptors[MD] = GV;
470 return true;
471 }
472
473 // The descriptor for a scalar is:
474 // [1, base-type pointer, access-type pointer, offset]
475
476 StructType *TDTy =
477 StructType::get(IntptrTy, Base->getType(), Access->getType(), IntptrTy);
478 Constant *TD =
479 ConstantStruct::get(TDTy, ConstantInt::get(IntptrTy, 1), Base, Access,
480 ConstantInt::get(IntptrTy, Offset));
481
482 bool ShouldBeComdat = cast<GlobalVariable>(Base)->getLinkage() ==
484
485 GlobalVariable *TDGV =
486 new GlobalVariable(TDTy, true,
487 !ShouldBeComdat ? GlobalValue::InternalLinkage
489 TD, EncodedName);
490 M.insertGlobalVariable(TDGV);
491
492 if (ShouldBeComdat) {
493 if (TargetTriple.isOSBinFormatELF()) {
494 Comdat *TDComdat = M.getOrInsertComdat(EncodedName);
495 TDGV->setComdat(TDComdat);
496 }
497 appendToUsed(M, TDGV);
498 }
499
500 TypeDescriptors[MD] = TDGV;
501 return true;
502}
503
504Instruction *TypeSanitizer::getShadowBase(Function &F) {
505 IRBuilder<> IRB(&F.front().front());
506 Constant *GlobalShadowAddress =
507 F.getParent()->getOrInsertGlobal(kTysanShadowMemoryAddress, IntptrTy);
508 return IRB.CreateLoad(IntptrTy, GlobalShadowAddress, "shadow.base");
509}
510
511Instruction *TypeSanitizer::getAppMemMask(Function &F) {
512 IRBuilder<> IRB(&F.front().front());
513 Value *GlobalAppMemMask =
514 F.getParent()->getOrInsertGlobal(kTysanAppMemMask, IntptrTy);
515 return IRB.CreateLoad(IntptrTy, GlobalAppMemMask, "app.mem.mask");
516}
517
518/// Collect all loads and stores, and for what TBAA nodes we need to generate
519/// type descriptors.
521 Function &F, const TargetLibraryInfo &TLI,
522 SmallVectorImpl<std::pair<Instruction *, MemoryLocation>> &MemoryAccesses,
524 SmallVectorImpl<Value *> &MemTypeResetInsts) {
525 // Traverse all instructions, collect loads/stores/returns, check for calls.
526 for (Instruction &Inst : instructions(F)) {
527 // Skip memory accesses inserted by another instrumentation.
528 if (Inst.getMetadata(LLVMContext::MD_nosanitize))
529 continue;
530
531 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst) ||
534
535 // Swift errors are special (we can't introduce extra uses on them).
536 if (MLoc.Ptr->isSwiftError())
537 continue;
538
539 // Skip non-address-space-0 pointers; we don't know how to handle them.
540 Type *PtrTy = cast<PointerType>(MLoc.Ptr->getType());
541 if (PtrTy->getPointerAddressSpace() != 0)
542 continue;
543
544 if (MLoc.AATags.TBAA)
545 TBAAMetadata.insert(MLoc.AATags.TBAA);
546 MemoryAccesses.push_back(std::make_pair(&Inst, MLoc));
547 } else if (isa<CallInst>(Inst) || isa<InvokeInst>(Inst)) {
548 if (CallInst *CI = dyn_cast<CallInst>(&Inst))
550
552 MemTypeResetInsts.push_back(&Inst);
553 } else if (isa<AllocaInst>(Inst)) {
554 MemTypeResetInsts.push_back(&Inst);
555 }
556 }
557}
558
559bool TypeSanitizer::sanitizeFunction(Function &F,
560 const TargetLibraryInfo &TLI) {
561 if (F.isDeclaration())
562 return false;
563 // This is required to prevent instrumenting call to __tysan_init from within
564 // the module constructor.
565 if (&F == TysanCtorFunction.getCallee() || &F == TysanGlobalsSetTypeFunction)
566 return false;
567 initializeCallbacks(*F.getParent());
568
569 // We need to collect all loads and stores, and know for what TBAA nodes we
570 // need to generate type descriptors.
572 SmallSetVector<const MDNode *, 8> TBAAMetadata;
573 SmallVector<Value *> MemTypeResetInsts;
574 collectMemAccessInfo(F, TLI, MemoryAccesses, TBAAMetadata, MemTypeResetInsts);
575
576 // byval arguments also need their types reset (they're new stack memory,
577 // just like allocas).
578 for (auto &A : F.args())
579 if (A.hasByValAttr())
580 MemTypeResetInsts.push_back(&A);
581
582 Module &M = *F.getParent();
583 TypeDescriptorsMapTy TypeDescriptors;
584 TypeNameMapTy TypeNames;
585 bool Res = false;
586 for (const MDNode *MD : TBAAMetadata) {
587 if (TypeDescriptors.count(MD))
588 continue;
589
590 if (!generateTypeDescriptor(MD, TypeDescriptors, TypeNames, M))
591 return Res; // Giving up.
592
593 Res = true;
594 }
595
596 const DataLayout &DL = F.getParent()->getDataLayout();
597 bool SanitizeFunction = F.hasFnAttribute(Attribute::SanitizeType);
598 bool NeedsInstrumentation =
599 MemTypeResetInsts.empty() && MemoryAccesses.empty();
600 Instruction *ShadowBase = NeedsInstrumentation ? nullptr : getShadowBase(F);
601 Instruction *AppMemMask = NeedsInstrumentation ? nullptr : getAppMemMask(F);
602 for (const auto &[I, MLoc] : MemoryAccesses) {
603 IRBuilder<> IRB(I);
604 assert(MLoc.Size.isPrecise());
605 if (instrumentWithShadowUpdate(
606 IRB, MLoc.AATags.TBAA, const_cast<Value *>(MLoc.Ptr),
607 MLoc.Size.getValue(), I->mayReadFromMemory(), I->mayWriteToMemory(),
608 ShadowBase, AppMemMask, false, SanitizeFunction, TypeDescriptors,
609 DL)) {
610 ++NumInstrumentedAccesses;
611 Res = true;
612 }
613 }
614
615 for (auto Inst : MemTypeResetInsts)
616 Res |= instrumentMemInst(Inst, ShadowBase, AppMemMask, DL);
617
618 return Res;
619}
620
622 Type *IntptrTy, uint64_t PtrShift,
623 Value *ShadowBase, Value *AppMemMask) {
624 return IRB.CreateAdd(
625 IRB.CreateShl(
626 IRB.CreateAnd(IRB.CreatePtrToInt(Ptr, IntptrTy, "app.ptr.int"),
627 AppMemMask, "app.ptr.masked"),
628 PtrShift, "app.ptr.shifted"),
629 ShadowBase, "shadow.ptr.int");
630}
631
632bool TypeSanitizer::instrumentWithShadowUpdate(
633 IRBuilder<> &IRB, const MDNode *TBAAMD, Value *Ptr, uint64_t AccessSize,
634 bool IsRead, bool IsWrite, Value *ShadowBase, Value *AppMemMask,
635 bool ForceSetType, bool SanitizeFunction,
636 TypeDescriptorsMapTy &TypeDescriptors, const DataLayout &DL) {
637 Constant *TDGV;
638 if (TBAAMD)
639 TDGV = TypeDescriptors[TBAAMD];
640 else
641 TDGV = Constant::getNullValue(IRB.getPtrTy());
642
643 Value *TD = IRB.CreateBitCast(TDGV, IRB.getPtrTy());
644
646 if (!ForceSetType && (!ClWritesAlwaysSetType || IsRead)) {
647 // We need to check the type here. If the type is unknown, then the read
648 // sets the type. If the type is known, then it is checked. If the type
649 // doesn't match, then we call the runtime type check (which may yet
650 // determine that the mismatch is okay).
651
652 Constant *Flags =
653 ConstantInt::get(OrdTy, (int)IsRead | (((int)IsWrite) << 1));
654
655 IRB.CreateCall(TysanInstrumentWithShadowUpdate,
656 {Ptr, TD,
657 SanitizeFunction ? IRB.getTrue() : IRB.getFalse(),
658 IRB.getInt64(AccessSize), Flags});
659 } else if (ForceSetType || IsWrite) {
660 // In the mode where writes always set the type, for a write (which does
661 // not also read), we just set the type.
662 IRB.CreateCall(TysanSetShadowType, {Ptr, TD, IRB.getInt64(AccessSize)});
663 }
664
665 return true;
666 }
667
668 Value *ShadowDataInt = convertToShadowDataInt(IRB, Ptr, IntptrTy, PtrShift,
669 ShadowBase, AppMemMask);
670 Type *Int8PtrPtrTy = PointerType::get(IRB.getContext(), 0);
671 Value *ShadowData =
672 IRB.CreateIntToPtr(ShadowDataInt, Int8PtrPtrTy, "shadow.ptr");
673
674 auto SetType = [&]() {
675 IRB.CreateStore(TD, ShadowData);
676
677 // Now fill the remainder of the shadow memory corresponding to the
678 // remainder of the the bytes of the type with a bad type descriptor.
679 for (uint64_t i = 1; i < AccessSize; ++i) {
680 Value *BadShadowData = IRB.CreateIntToPtr(
681 IRB.CreateAdd(ShadowDataInt,
682 ConstantInt::get(IntptrTy, i << PtrShift),
683 "shadow.byte." + Twine(i) + ".offset"),
684 Int8PtrPtrTy, "shadow.byte." + Twine(i) + ".ptr");
685
686 // This is the TD value, -i, which is used to indicate that the byte is
687 // i bytes after the first byte of the type.
688 Value *BadTD =
689 IRB.CreateIntToPtr(ConstantInt::getSigned(IntptrTy, -i),
690 IRB.getPtrTy(), "bad.descriptor" + Twine(i));
691 IRB.CreateStore(BadTD, BadShadowData);
692 }
693 };
694
695 if (ForceSetType || (ClWritesAlwaysSetType && IsWrite)) {
696 // In the mode where writes always set the type, for a write (which does
697 // not also read), we just set the type.
698 SetType();
699 return true;
700 }
701
702 assert((!ClWritesAlwaysSetType || IsRead) &&
703 "should have handled case above");
704 LLVMContext &C = IRB.getContext();
705 MDNode *UnlikelyBW = MDBuilder(C).createBranchWeights(1, 100000);
706
707 if (!SanitizeFunction) {
708 // If we're not sanitizing this function, then we only care whether we
709 // need to *set* the type.
710 Value *LoadedTD = IRB.CreateLoad(IRB.getPtrTy(), ShadowData, "shadow.desc");
711 Value *NullTDCmp = IRB.CreateIsNull(LoadedTD, "desc.set");
713 NullTDCmp, &*IRB.GetInsertPoint(), false, UnlikelyBW);
714 IRB.SetInsertPoint(NullTDTerm);
715 NullTDTerm->getParent()->setName("set.type");
716 SetType();
717 return true;
718 }
719 // We need to check the type here. If the type is unknown, then the read
720 // sets the type. If the type is known, then it is checked. If the type
721 // doesn't match, then we call the runtime (which may yet determine that
722 // the mismatch is okay).
723 //
724 // The checks generated below have the following structure.
725 //
726 // ; First we load the descriptor for the load from shadow memory and
727 // ; compare it against the type descriptor for the current access type.
728 // %shadow.desc = load ptr %shadow.data
729 // %bad.desc = icmp ne %shadow.desc, %td
730 // br %bad.desc, %bad.bb, %good.bb
731 //
732 // bad.bb:
733 // %shadow.desc.null = icmp eq %shadow.desc, null
734 // br %shadow.desc.null, %null.td.bb, %good.td.bb
735 //
736 // null.td.bb:
737 // ; The typ is unknown, set it if all bytes in the value are also unknown.
738 // ; To check, we load the shadow data for all bytes of the access. For the
739 // ; pseudo code below, assume an access of size 1.
740 // %shadow.data.int = add %shadow.data.int, 0
741 // %l = load (inttoptr %shadow.data.int)
742 // %is.not.null = icmp ne %l, null
743 // %not.all.unknown = %is.not.null
744 // br %no.all.unknown, before.set.type.bb
745 //
746 // before.set.type.bb:
747 // ; Call runtime to check mismatch.
748 // call void @__tysan_check()
749 // br %set.type.bb
750 //
751 // set.type.bb:
752 // ; Now fill the remainder of the shadow memory corresponding to the
753 // ; remainder of the the bytes of the type with a bad type descriptor.
754 // store %TD, %shadow.data
755 // br %continue.bb
756 //
757 // good.td.bb::
758 // ; We have a non-trivial mismatch. Call the runtime.
759 // call void @__tysan_check()
760 // br %continue.bb
761 //
762 // good.bb:
763 // ; We appear to have the right type. Make sure that all other bytes in
764 // ; the type are still marked as interior bytes. If not, call the runtime.
765 // %shadow.data.int = add %shadow.data.int, 0
766 // %l = load (inttoptr %shadow.data.int)
767 // %not.all.interior = icmp sge %l, 0
768 // br %not.all.interior, label %check.rt.bb, label %continue.bb
769 //
770 // check.rt.bb:
771 // call void @__tysan_check()
772 // br %continue.bb
773
774 Constant *Flags = ConstantInt::get(OrdTy, int(IsRead) | (int(IsWrite) << 1));
775
776 Value *LoadedTD = IRB.CreateLoad(IRB.getPtrTy(), ShadowData, "shadow.desc");
777 Value *BadTDCmp = IRB.CreateICmpNE(LoadedTD, TD, "bad.desc");
778 Instruction *BadTDTerm, *GoodTDTerm;
779 SplitBlockAndInsertIfThenElse(BadTDCmp, &*IRB.GetInsertPoint(), &BadTDTerm,
780 &GoodTDTerm, UnlikelyBW);
781 IRB.SetInsertPoint(BadTDTerm);
782
783 // We now know that the types did not match (we're on the slow path). If
784 // the type is unknown, then set it.
785 Value *NullTDCmp = IRB.CreateIsNull(LoadedTD);
786 Instruction *NullTDTerm, *MismatchTerm;
787 SplitBlockAndInsertIfThenElse(NullTDCmp, &*IRB.GetInsertPoint(), &NullTDTerm,
788 &MismatchTerm);
789
790 // If the type is unknown, then set the type.
791 IRB.SetInsertPoint(NullTDTerm);
792
793 // We're about to set the type. Make sure that all bytes in the value are
794 // also of unknown type.
795 Value *Size = ConstantInt::get(OrdTy, AccessSize);
796 Value *NotAllUnkTD = IRB.getFalse();
797 for (uint64_t i = 1; i < AccessSize; ++i) {
798 Value *UnkShadowData = IRB.CreateIntToPtr(
799 IRB.CreateAdd(ShadowDataInt, ConstantInt::get(IntptrTy, i << PtrShift)),
800 Int8PtrPtrTy);
801 Value *ILdTD = IRB.CreateLoad(IRB.getPtrTy(), UnkShadowData);
802 NotAllUnkTD = IRB.CreateOr(NotAllUnkTD, IRB.CreateIsNotNull(ILdTD));
803 }
804
805 Instruction *BeforeSetType = &*IRB.GetInsertPoint();
806 Instruction *BadUTDTerm =
807 SplitBlockAndInsertIfThen(NotAllUnkTD, BeforeSetType, false, UnlikelyBW);
808 IRB.SetInsertPoint(BadUTDTerm);
809 IRB.CreateCall(TysanCheck, {IRB.CreateBitCast(Ptr, IRB.getPtrTy()), Size,
810 (Value *)TD, (Value *)Flags});
811
812 IRB.SetInsertPoint(BeforeSetType);
813 SetType();
814
815 // We have a non-trivial mismatch. Call the runtime.
816 IRB.SetInsertPoint(MismatchTerm);
817 IRB.CreateCall(TysanCheck, {IRB.CreateBitCast(Ptr, IRB.getPtrTy()), Size,
818 (Value *)TD, (Value *)Flags});
819
820 // We appear to have the right type. Make sure that all other bytes in
821 // the type are still marked as interior bytes. If not, call the runtime.
822 IRB.SetInsertPoint(GoodTDTerm);
823 Value *NotAllBadTD = IRB.getFalse();
824 for (uint64_t i = 1; i < AccessSize; ++i) {
825 Value *BadShadowData = IRB.CreateIntToPtr(
826 IRB.CreateAdd(ShadowDataInt, ConstantInt::get(IntptrTy, i << PtrShift)),
827 Int8PtrPtrTy);
828 Value *ILdTD = IRB.CreatePtrToInt(
829 IRB.CreateLoad(IRB.getPtrTy(), BadShadowData), IntptrTy);
830 NotAllBadTD = IRB.CreateOr(
831 NotAllBadTD, IRB.CreateICmpSGE(ILdTD, ConstantInt::get(IntptrTy, 0)));
832 }
833
835 NotAllBadTD, &*IRB.GetInsertPoint(), false, UnlikelyBW);
836 IRB.SetInsertPoint(BadITDTerm);
837 IRB.CreateCall(TysanCheck, {IRB.CreateBitCast(Ptr, IRB.getPtrTy()), Size,
838 (Value *)TD, (Value *)Flags});
839 return true;
840}
841
842bool TypeSanitizer::instrumentMemInst(Value *V, Instruction *ShadowBase,
843 Instruction *AppMemMask,
844 const DataLayout &DL) {
846 BasicBlock *BB;
847 Function *F;
848
849 if (auto *I = dyn_cast<Instruction>(V)) {
851 BB = I->getParent();
852 F = BB->getParent();
853 } else {
854 auto *A = cast<Argument>(V);
855 F = A->getParent();
856 BB = &F->getEntryBlock();
857 IP = BB->getFirstInsertionPt();
858
859 // Find the next insert point after both ShadowBase and AppMemMask.
860 if (IP->comesBefore(ShadowBase))
861 IP = ShadowBase->getNextNode()->getIterator();
862 if (IP->comesBefore(AppMemMask))
863 IP = AppMemMask->getNextNode()->getIterator();
864 }
865
866 Value *Dest, *Size, *Src = nullptr;
867 bool NeedsMemMove = false;
868 IRBuilder<> IRB(BB, IP);
869
870 if (auto *A = dyn_cast<Argument>(V)) {
871 assert(A->hasByValAttr() && "Type reset for non-byval argument?");
872
873 Dest = A;
874 Size =
875 ConstantInt::get(IntptrTy, DL.getTypeAllocSize(A->getParamByValType()));
876 } else {
877 auto *I = cast<Instruction>(V);
878 if (auto *MI = dyn_cast<MemIntrinsic>(I)) {
879 if (MI->getDestAddressSpace() != 0)
880 return false;
881
882 Dest = MI->getDest();
883 Size = MI->getLength();
884
885 if (auto *MTI = dyn_cast<MemTransferInst>(MI)) {
886 if (MTI->getSourceAddressSpace() == 0) {
887 Src = MTI->getSource();
888 NeedsMemMove = isa<MemMoveInst>(MTI);
889 }
890 }
891 } else if (auto *II = dyn_cast<LifetimeIntrinsic>(I)) {
892 auto *AI = dyn_cast<AllocaInst>(II->getArgOperand(0));
893 if (!AI)
894 return false;
895
896 Size = IRB.CreateAllocationSize(IntptrTy, AI);
897 Dest = II->getArgOperand(0);
898 } else if (auto *AI = dyn_cast<AllocaInst>(I)) {
899 // We need to clear the types for new stack allocations (or else we might
900 // read stale type information from a previous function execution).
901
902 IRB.SetInsertPoint(&*std::next(BasicBlock::iterator(I)));
904
905 Size = IRB.CreateAllocationSize(IntptrTy, AI);
906 Dest = I;
907 } else {
908 return false;
909 }
910 }
911
913 if (!Src)
915
916 // The runtime function expects a uint64_t size parameter. On 32-bit
917 // targets, Size may be IntptrTy (i32), so extend it to match.
918 Value *Size64 = IRB.CreateZExtOrTrunc(Size, U64Ty);
919 IRB.CreateCall(
920 TysanIntrumentMemInst,
921 {Dest, Src, Size64, NeedsMemMove ? IRB.getTrue() : IRB.getFalse()});
922 return true;
923 } else {
924 if (!ShadowBase)
925 ShadowBase = getShadowBase(*F);
926 if (!AppMemMask)
927 AppMemMask = getAppMemMask(*F);
928
929 Value *ShadowDataInt = IRB.CreateAdd(
930 IRB.CreateShl(
931 IRB.CreateAnd(IRB.CreatePtrToInt(Dest, IntptrTy), AppMemMask),
932 PtrShift),
933 ShadowBase);
934 Value *ShadowData = IRB.CreateIntToPtr(ShadowDataInt, IRB.getPtrTy());
935
936 if (!Src) {
937 IRB.CreateMemSet(ShadowData, IRB.getInt8(0),
938 IRB.CreateShl(Size, PtrShift), Align(1ull << PtrShift));
939 return true;
940 }
941
942 Value *SrcShadowDataInt = IRB.CreateAdd(
943 IRB.CreateShl(
944 IRB.CreateAnd(IRB.CreatePtrToInt(Src, IntptrTy), AppMemMask),
945 PtrShift),
946 ShadowBase);
947 Value *SrcShadowData = IRB.CreateIntToPtr(SrcShadowDataInt, IRB.getPtrTy());
948
949 if (NeedsMemMove) {
950 IRB.CreateMemMove(ShadowData, Align(1ull << PtrShift), SrcShadowData,
951 Align(1ull << PtrShift), IRB.CreateShl(Size, PtrShift));
952 } else {
953 IRB.CreateMemCpy(ShadowData, Align(1ull << PtrShift), SrcShadowData,
954 Align(1ull << PtrShift), IRB.CreateShl(Size, PtrShift));
955 }
956 }
957
958 return true;
959}
960
963 Function *TysanCtorFunction;
964 std::tie(TysanCtorFunction, std::ignore) =
966 kTysanInitName, /*InitArgTypes=*/{},
967 /*InitArgs=*/{});
968
969 TypeSanitizer TySan(M);
970 TySan.instrumentGlobals(M);
971 appendToGlobalCtors(M, TysanCtorFunction, 0);
972
973 auto &FAM = MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
974 for (Function &F : M) {
975 const TargetLibraryInfo &TLI = FAM.getResult<TargetLibraryAnalysis>(F);
976 TySan.sanitizeFunction(F, TLI);
978 // Outlined instrumentation is a new option, and so this exists to
979 // verify there is no difference in behaviour between the options.
980 // If the outlined instrumentation triggers a verification failure
981 // when the original inlined instrumentation does not, or vice versa,
982 // then there is a discrepency which should be investigated.
984 TySan.sanitizeFunction(F, TLI);
986 }
987 }
988
990}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
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:54
#define I(x, y, z)
Definition MD5.cpp:57
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 cl::opt< bool > ClOutlineInstrumentation("tysan-outline-instrumentation", cl::desc("Uses function calls for all TySan instrumentation, reducing " "ELF size"), cl::Hidden, cl::init(true))
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 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; assumes that the block is well-formed.
Definition BasicBlock.h:237
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, bool ByteString=false)
This method constructs a CDS and initializes it with a text string.
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
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:64
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:169
const BasicBlock & getEntryBlock() const
Definition Function.h:794
LLVM_ABI void setComdat(Comdat *C)
Definition Globals.cpp:287
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:56
LLVM_ABI Value * CreateAllocationSize(Type *DestTy, AllocaInst *AI)
Get allocation size of an alloca as a runtime Value* (handles both static and dynamic allocas and vsc...
Value * CreateZExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a ZExt or Trunc from the integer value V to DestTy.
Definition IRBuilder.h:2147
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:663
ConstantInt * getTrue()
Get the constant value for i1 true.
Definition IRBuilder.h:457
Value * CreateICmpSGE(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2418
BasicBlock::iterator GetInsertPoint() const
Definition IRBuilder.h:176
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2246
ConstantInt * getInt8(uint8_t C)
Get a constant 8-bit value.
Definition IRBuilder.h:467
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2394
ConstantInt * getInt64(uint64_t C)
Get a constant 64-bit value.
Definition IRBuilder.h:482
CallInst * CreateMemMove(Value *Dst, MaybeAlign DstAlign, Value *Src, MaybeAlign SrcAlign, uint64_t Size, bool isVolatile=false, const AAMDNodes &AAInfo=AAMDNodes())
Definition IRBuilder.h:705
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2251
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:1914
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1519
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:608
LLVMContext & getContext() const
Definition IRBuilder.h:177
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:1578
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition IRBuilder.h:1933
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1430
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2241
ConstantInt * getFalse()
Get the constant value for i1 false.
Definition IRBuilder.h:462
Value * CreateIsNotNull(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg != 0.
Definition IRBuilder.h:2757
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args={}, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2569
PointerType * getPtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer.
Definition IRBuilder.h:577
Value * CreateIsNull(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg == 0.
Definition IRBuilder.h:2752
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:181
LLVM_ABI void SetInstDebugLocation(Instruction *I) const
If this builder has a current debug location, set it on the specified instruction.
Definition IRBuilder.cpp:66
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Definition IRBuilder.h:1600
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2903
Class to represent integer types.
LLVM_ABI void update(ArrayRef< uint8_t > Data)
Updates the hash for the byte stream provided.
Definition MD5.cpp:188
LLVM_ABI void final(MD5Result &Result)
Finishes off the hash and puts the result in result.
Definition MD5.cpp:233
Metadata node.
Definition Metadata.h:1081
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1437
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1443
LLVMContext & getContext() const
Definition Metadata.h:1245
LLVM_ABI StringRef getString() const
Definition Metadata.cpp:615
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:68
iterator_range< op_iterator > operands()
Definition Metadata.h:1863
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:84
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:157
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:345
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)
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::string str() const
Get the contents as an std::string.
Definition StringRef.h:222
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:467
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
static Attribute::AttrKind getExtAttrForBoolParam(const Triple &T)
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
bool isOSBinFormatELF() const
Tests whether the OS uses the ELF binary format.
Definition Triple.h:866
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:300
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:299
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool isSized() const
Return true if it makes sense to take the size of this type.
Definition Type.h:321
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:296
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI bool isSwiftError() const
Return true if this value is a swifterror value.
Definition Value.cpp:1164
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.
@ 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:720
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:679
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:577
@ Length
Definition DWP.cpp:577
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)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
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:204
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:3898
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:791
LLVM_ABI SmallString< 32 > digest() const
Definition MD5.cpp:280
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)