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
16#include "llvm/ADT/SetVector.h"
18#include "llvm/ADT/Statistic.h"
22#include "llvm/IR/DataLayout.h"
23#include "llvm/IR/Function.h"
24#include "llvm/IR/IRBuilder.h"
28#include "llvm/IR/Intrinsics.h"
29#include "llvm/IR/LLVMContext.h"
30#include "llvm/IR/MDBuilder.h"
31#include "llvm/IR/Metadata.h"
32#include "llvm/IR/Module.h"
33#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
56STATISTIC(NumInstrumentedAccesses, "Number of instrumented accesses");
57
58namespace {
59
60/// TypeSanitizer: instrument the code in module to find type-based aliasing
61/// violations.
62struct TypeSanitizer {
63 TypeSanitizer(const InstrumentationOptions &Opts, Module &M);
64 bool sanitizeFunction(Function &F, const TargetLibraryInfo &TLI);
65 void instrumentGlobals(Module &M);
66
67 const InstrumentationOptions &Opts;
68 bool OutlineInstrumentation;
69
70private:
72 TypeDescriptorsMapTy;
74
75 void initializeCallbacks(Module &M);
76
77 Instruction *getShadowBase(Function &F);
78 Instruction *getAppMemMask(Function &F);
79
80 bool instrumentWithShadowUpdate(IRBuilder<> &IRB, const MDNode *TBAAMD,
81 Value *Ptr, uint64_t AccessSize, bool IsRead,
82 bool IsWrite, Value *ShadowBase,
83 Value *AppMemMask, bool ForceSetType,
84 bool SanitizeFunction,
85 TypeDescriptorsMapTy &TypeDescriptors,
86 const DataLayout &DL);
87
88 /// Memory-related intrinsics/instructions reset the type of the destination
89 /// memory (including allocas and byval arguments).
90 bool instrumentMemInst(Value *I, Instruction *ShadowBase,
91 Instruction *AppMemMask, const DataLayout &DL);
92
93 std::string getAnonymousStructIdentifier(const MDNode *MD,
94 TypeNameMapTy &TypeNames);
95 bool generateTypeDescriptor(const MDNode *MD,
96 TypeDescriptorsMapTy &TypeDescriptors,
97 TypeNameMapTy &TypeNames, Module &M);
98 bool generateBaseTypeDescriptor(const MDNode *MD,
99 TypeDescriptorsMapTy &TypeDescriptors,
100 TypeNameMapTy &TypeNames, Module &M);
101
102 const Triple TargetTriple;
103 Regex AnonNameRegex;
104 Type *IntptrTy;
105 uint64_t PtrShift;
106 IntegerType *OrdTy, *U64Ty;
107
108 /// Callbacks to run-time library are computed in initializeCallbacks.
109 FunctionCallee TysanCheck;
110 FunctionCallee TysanCtorFunction;
111
112 FunctionCallee TysanIntrumentMemInst;
113 FunctionCallee TysanInstrumentWithShadowUpdate;
114 FunctionCallee TysanSetShadowType;
115
116 /// Callback to set types for gloabls.
117 Function *TysanGlobalsSetTypeFunction;
118};
119} // namespace
120
121TypeSanitizer::TypeSanitizer(const InstrumentationOptions &Opts, Module &M)
122 : Opts(Opts), OutlineInstrumentation(Opts.tysan_outline_instrumentation),
123 TargetTriple(M.getTargetTriple()),
124 AnonNameRegex("^_ZTS.*N[1-9][0-9]*_GLOBAL__N") {
125 const DataLayout &DL = M.getDataLayout();
126 IntptrTy = DL.getIntPtrType(M.getContext());
127 PtrShift = countr_zero(IntptrTy->getPrimitiveSizeInBits() / 8);
128
129 TysanGlobalsSetTypeFunction = M.getFunction("__tysan_set_globals_types");
130 initializeCallbacks(M);
131}
132
133void TypeSanitizer::initializeCallbacks(Module &M) {
134 LLVMContext &C = M.getContext();
135 IRBuilder<> IRB(M);
136 OrdTy = IRB.getInt32Ty();
137 U64Ty = IRB.getInt64Ty();
138 Type *BoolType = IRB.getInt1Ty();
139
140 AttributeList Attr;
141 Attr = Attr.addFnAttribute(C, Attribute::NoUnwind);
142 Attribute::AttrKind SExtAttr =
143 TargetLibraryInfo::getExtAttrForI32Param(TargetTriple, /*Signed=*/true);
144 Attribute::AttrKind BoolExtAttr =
146
147 // Initialize the callbacks. TODO: use TLI/emitLibFunc() for these functions.
148 TysanCheck =
149 M.getOrInsertFunction(kTysanCheckName,
150 Attr.maybeAddParamAttribute(C, 1, SExtAttr)
151 .maybeAddParamAttribute(C, 3, SExtAttr),
152 IRB.getVoidTy(),
153 IRB.getPtrTy(), // Pointer to data to be read.
154 OrdTy, // Size of the data in bytes.
155 IRB.getPtrTy(), // Pointer to type descriptor.
156 OrdTy // Flags.
157 );
158
159 TysanCtorFunction =
160 M.getOrInsertFunction(kTysanModuleCtorName, Attr, IRB.getVoidTy());
161
162 TysanIntrumentMemInst = M.getOrInsertFunction(
163 "__tysan_instrument_mem_inst",
164 Attr.maybeAddParamAttribute(C, 3, BoolExtAttr), IRB.getVoidTy(),
165 IRB.getPtrTy(), // Pointer of data to be written to
166 IRB.getPtrTy(), // Pointer of data to write
167 U64Ty, // Size of the data in bytes
168 BoolType // Do we need to call memmove
169 );
170
171 TysanInstrumentWithShadowUpdate =
172 M.getOrInsertFunction("__tysan_instrument_with_shadow_update",
173 Attr.maybeAddParamAttribute(C, 2, BoolExtAttr)
174 .maybeAddParamAttribute(C, 4, SExtAttr),
175 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
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
349 if ((unsigned)i + 1 < MD->getNumOperands()) {
350 Offset =
351 mdconst::extract<ConstantInt>(MD->getOperand(i + 1))->getZExtValue();
352 } else {
353 assert(i == 1 && MD->getNumOperands() == 2 && "Malformed TBAA MD.");
354 // The third operand for a scalar tag is actually optional, its absence
355 // indicating an offset of zero.
356 Offset = 0;
357 }
358
359 Members.push_back(std::make_pair(Member, Offset));
360 }
361
362 // The descriptor for a scalar is:
363 // [2, member count, [type pointer, offset]..., name]
364
365 LLVMContext &C = MD->getContext();
366 Constant *NameData = ConstantDataArray::getString(C, NameNode->getString());
367 SmallVector<Type *> TDSubTys;
368 SmallVector<Constant *> TDSubData;
369
370 auto PushTDSub = [&](Constant *C) {
371 TDSubTys.push_back(C->getType());
372 TDSubData.push_back(C);
373 };
374
375 PushTDSub(ConstantInt::get(IntptrTy, 2));
376 PushTDSub(ConstantInt::get(IntptrTy, Members.size()));
377
378 // Types that are in an anonymous namespace are local to this module.
379 // FIXME: This should really be marked by the frontend in the metadata
380 // instead of having us guess this from the mangled name. Moreover, the regex
381 // here can pick up (unlikely) names in the non-reserved namespace (because
382 // it needs to search into the type to pick up cases where the type in the
383 // anonymous namespace is a template parameter, etc.).
384 bool ShouldBeComdat = !AnonNameRegex.match(NameNode->getString());
385 for (auto &Member : Members) {
386 PushTDSub(Member.first);
387 PushTDSub(ConstantInt::get(IntptrTy, Member.second));
388 }
389
390 PushTDSub(NameData);
391
392 StructType *TDTy = StructType::get(C, TDSubTys);
393 Constant *TD = ConstantStruct::get(TDTy, TDSubData);
394
395 GlobalVariable *TDGV =
396 new GlobalVariable(TDTy, true,
397 !ShouldBeComdat ? GlobalValue::InternalLinkage
399 TD, EncodedName);
400 M.insertGlobalVariable(TDGV);
401
402 if (ShouldBeComdat) {
403 if (TargetTriple.isOSBinFormatELF()) {
404 Comdat *TDComdat = M.getOrInsertComdat(EncodedName);
405 TDGV->setComdat(TDComdat);
406 }
407 appendToUsed(M, TDGV);
408 }
409
410 TypeDescriptors[MD] = TDGV;
411 return true;
412}
413
414bool TypeSanitizer::generateTypeDescriptor(
415 const MDNode *MD, TypeDescriptorsMapTy &TypeDescriptors,
416 TypeNameMapTy &TypeNames, Module &M) {
417 // Here we need to generate a type descriptor corresponding to this TBAA
418 // metadata node. Under the current scheme there are three kinds of TBAA
419 // metadata nodes: scalar nodes, struct nodes, and struct tag nodes.
420
421 if (MD->getNumOperands() < 3)
422 return false;
423
424 const MDNode *BaseNode = dyn_cast<MDNode>(MD->getOperand(0));
425 if (!BaseNode)
426 return false;
427
428 // This is a struct tag (element-access) node.
429
430 const MDNode *AccessNode = dyn_cast<MDNode>(MD->getOperand(1));
431 if (!AccessNode)
432 return false;
433
434 Constant *Base;
435 auto TDI = TypeDescriptors.find(BaseNode);
436 if (TDI != TypeDescriptors.end()) {
437 Base = TDI->second;
438 } else {
439 if (!generateBaseTypeDescriptor(BaseNode, TypeDescriptors, TypeNames, M))
440 return false;
441
442 Base = TypeDescriptors[BaseNode];
443 }
444
446 TDI = TypeDescriptors.find(AccessNode);
447 if (TDI != TypeDescriptors.end()) {
448 Access = TDI->second;
449 } else {
450 if (!generateBaseTypeDescriptor(AccessNode, TypeDescriptors, TypeNames, M))
451 return false;
452
453 Access = TypeDescriptors[AccessNode];
454 }
455
457 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue();
458 std::string EncodedName =
459 std::string(Base->getName()) + "_o_" + utostr(Offset);
460
461 GlobalVariable *GV =
462 dyn_cast_or_null<GlobalVariable>(M.getNamedValue(EncodedName));
463 if (GV) {
464 TypeDescriptors[MD] = GV;
465 return true;
466 }
467
468 // The descriptor for a scalar is:
469 // [1, base-type pointer, access-type pointer, offset]
470
471 StructType *TDTy =
472 StructType::get(IntptrTy, Base->getType(), Access->getType(), IntptrTy);
473 Constant *TD =
474 ConstantStruct::get(TDTy, ConstantInt::get(IntptrTy, 1), Base, Access,
475 ConstantInt::get(IntptrTy, Offset));
476
477 bool ShouldBeComdat = cast<GlobalVariable>(Base)->getLinkage() ==
479
480 GlobalVariable *TDGV =
481 new GlobalVariable(TDTy, true,
482 !ShouldBeComdat ? GlobalValue::InternalLinkage
484 TD, EncodedName);
485 M.insertGlobalVariable(TDGV);
486
487 if (ShouldBeComdat) {
488 if (TargetTriple.isOSBinFormatELF()) {
489 Comdat *TDComdat = M.getOrInsertComdat(EncodedName);
490 TDGV->setComdat(TDComdat);
491 }
492 appendToUsed(M, TDGV);
493 }
494
495 TypeDescriptors[MD] = TDGV;
496 return true;
497}
498
499Instruction *TypeSanitizer::getShadowBase(Function &F) {
500 IRBuilder<> IRB(&F.front().front());
501 Constant *GlobalShadowAddress =
502 F.getParent()->getOrInsertGlobal(kTysanShadowMemoryAddress, IntptrTy);
503 return IRB.CreateLoad(IntptrTy, GlobalShadowAddress, "shadow.base");
504}
505
506Instruction *TypeSanitizer::getAppMemMask(Function &F) {
507 IRBuilder<> IRB(&F.front().front());
508 Value *GlobalAppMemMask =
509 F.getParent()->getOrInsertGlobal(kTysanAppMemMask, IntptrTy);
510 return IRB.CreateLoad(IntptrTy, GlobalAppMemMask, "app.mem.mask");
511}
512
513/// Collect all loads and stores, and for what TBAA nodes we need to generate
514/// type descriptors.
516 Function &F, const TargetLibraryInfo &TLI,
517 SmallVectorImpl<std::pair<Instruction *, MemoryLocation>> &MemoryAccesses,
519 SmallVectorImpl<Value *> &MemTypeResetInsts) {
520 // Traverse all instructions, collect loads/stores/returns, check for calls.
521 for (Instruction &Inst : instructions(F)) {
522 // Skip memory accesses inserted by another instrumentation.
523 if (Inst.getMetadata(LLVMContext::MD_nosanitize))
524 continue;
525
526 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst) ||
529
530 // Swift errors are special (we can't introduce extra uses on them).
531 if (MLoc.Ptr->isSwiftError())
532 continue;
533
534 // Skip non-address-space-0 pointers; we don't know how to handle them.
535 Type *PtrTy = cast<PointerType>(MLoc.Ptr->getType());
536 if (PtrTy->getPointerAddressSpace() != 0)
537 continue;
538
539 if (MLoc.AATags.TBAA)
540 TBAAMetadata.insert(MLoc.AATags.TBAA);
541 MemoryAccesses.push_back(std::make_pair(&Inst, MLoc));
542 } else if (isa<CallInst>(Inst) || isa<InvokeInst>(Inst)) {
543 if (CallInst *CI = dyn_cast<CallInst>(&Inst))
545
547 MemTypeResetInsts.push_back(&Inst);
548 } else if (isa<AllocaInst>(Inst)) {
549 MemTypeResetInsts.push_back(&Inst);
550 }
551 }
552}
553
554bool TypeSanitizer::sanitizeFunction(Function &F,
555 const TargetLibraryInfo &TLI) {
556 if (F.isDeclaration())
557 return false;
558 // This is required to prevent instrumenting call to __tysan_init from within
559 // the module constructor.
560 if (&F == TysanCtorFunction.getCallee() || &F == TysanGlobalsSetTypeFunction)
561 return false;
562 initializeCallbacks(*F.getParent());
563
564 // We need to collect all loads and stores, and know for what TBAA nodes we
565 // need to generate type descriptors.
567 SmallSetVector<const MDNode *, 8> TBAAMetadata;
568 SmallVector<Value *> MemTypeResetInsts;
569 collectMemAccessInfo(F, TLI, MemoryAccesses, TBAAMetadata, MemTypeResetInsts);
570
571 // byval arguments also need their types reset (they're new stack memory,
572 // just like allocas).
573 for (auto &A : F.args())
574 if (A.hasByValAttr())
575 MemTypeResetInsts.push_back(&A);
576
577 Module &M = *F.getParent();
578 TypeDescriptorsMapTy TypeDescriptors;
579 TypeNameMapTy TypeNames;
580 bool Res = false;
581 for (const MDNode *MD : TBAAMetadata) {
582 if (TypeDescriptors.count(MD))
583 continue;
584
585 if (!generateTypeDescriptor(MD, TypeDescriptors, TypeNames, M))
586 return Res; // Giving up.
587
588 Res = true;
589 }
590
591 const DataLayout &DL = F.getDataLayout();
592 bool SanitizeFunction = F.hasFnAttribute(Attribute::SanitizeType);
593 bool NeedsInstrumentation =
594 MemTypeResetInsts.empty() && MemoryAccesses.empty();
595 Instruction *ShadowBase = NeedsInstrumentation ? nullptr : getShadowBase(F);
596 Instruction *AppMemMask = NeedsInstrumentation ? nullptr : getAppMemMask(F);
597 for (const auto &[I, MLoc] : MemoryAccesses) {
598 IRBuilder<> IRB(I);
599 assert(MLoc.Size.isPrecise());
600 if (instrumentWithShadowUpdate(
601 IRB, MLoc.AATags.TBAA, const_cast<Value *>(MLoc.Ptr),
602 MLoc.Size.getValue(), I->mayReadFromMemory(), I->mayWriteToMemory(),
603 ShadowBase, AppMemMask, false, SanitizeFunction, TypeDescriptors,
604 DL)) {
605 ++NumInstrumentedAccesses;
606 Res = true;
607 }
608 }
609
610 for (auto Inst : MemTypeResetInsts)
611 Res |= instrumentMemInst(Inst, ShadowBase, AppMemMask, DL);
612
613 return Res;
614}
615
617 Type *IntptrTy, uint64_t PtrShift,
618 Value *ShadowBase, Value *AppMemMask) {
619 return IRB.CreateAdd(
620 IRB.CreateShl(
621 IRB.CreateAnd(IRB.CreatePtrToInt(Ptr, IntptrTy, "app.ptr.int"),
622 AppMemMask, "app.ptr.masked"),
623 PtrShift, "app.ptr.shifted"),
624 ShadowBase, "shadow.ptr.int");
625}
626
627bool TypeSanitizer::instrumentWithShadowUpdate(
628 IRBuilder<> &IRB, const MDNode *TBAAMD, Value *Ptr, uint64_t AccessSize,
629 bool IsRead, bool IsWrite, Value *ShadowBase, Value *AppMemMask,
630 bool ForceSetType, bool SanitizeFunction,
631 TypeDescriptorsMapTy &TypeDescriptors, const DataLayout &DL) {
632 Constant *TDGV;
633 if (TBAAMD)
634 TDGV = TypeDescriptors[TBAAMD];
635 else
636 TDGV = Constant::getNullValue(IRB.getPtrTy());
637
638 Value *TD = IRB.CreateBitCast(TDGV, IRB.getPtrTy());
639
640 if (OutlineInstrumentation) {
641 if (!ForceSetType && (!Opts.tysan_writes_always_set_type || IsRead)) {
642 // We need to check the type here. If the type is unknown, then the read
643 // sets the type. If the type is known, then it is checked. If the type
644 // doesn't match, then we call the runtime type check (which may yet
645 // determine that the mismatch is okay).
646
647 Constant *Flags =
648 ConstantInt::get(OrdTy, (int)IsRead | (((int)IsWrite) << 1));
649
650 IRB.CreateCall(TysanInstrumentWithShadowUpdate,
651 {Ptr, TD,
652 SanitizeFunction ? IRB.getTrue() : IRB.getFalse(),
653 IRB.getInt64(AccessSize), Flags});
654 } else if (ForceSetType || IsWrite) {
655 // In the mode where writes always set the type, for a write (which does
656 // not also read), we just set the type.
657 IRB.CreateCall(TysanSetShadowType, {Ptr, TD, IRB.getInt64(AccessSize)});
658 }
659
660 return true;
661 }
662
663 Value *ShadowDataInt = convertToShadowDataInt(IRB, Ptr, IntptrTy, PtrShift,
664 ShadowBase, AppMemMask);
665 Type *Int8PtrPtrTy = PointerType::get(IRB.getContext(), 0);
666 Value *ShadowData =
667 IRB.CreateIntToPtr(ShadowDataInt, Int8PtrPtrTy, "shadow.ptr");
668
669 auto SetType = [&]() {
670 IRB.CreateStore(TD, ShadowData);
671
672 // Now fill the remainder of the shadow memory corresponding to the
673 // remainder of the the bytes of the type with a bad type descriptor.
674 for (uint64_t i = 1; i < AccessSize; ++i) {
675 Value *BadShadowData = IRB.CreateIntToPtr(
676 IRB.CreateAdd(ShadowDataInt,
677 ConstantInt::get(IntptrTy, i << PtrShift),
678 "shadow.byte." + Twine(i) + ".offset"),
679 Int8PtrPtrTy, "shadow.byte." + Twine(i) + ".ptr");
680
681 // This is the TD value, -i, which is used to indicate that the byte is
682 // i bytes after the first byte of the type.
683 Value *BadTD =
684 IRB.CreateIntToPtr(ConstantInt::getSigned(IntptrTy, -i),
685 IRB.getPtrTy(), "bad.descriptor" + Twine(i));
686 IRB.CreateStore(BadTD, BadShadowData);
687 }
688 };
689
690 if (ForceSetType || (Opts.tysan_writes_always_set_type && IsWrite)) {
691 // In the mode where writes always set the type, for a write (which does
692 // not also read), we just set the type.
693 SetType();
694 return true;
695 }
696
697 assert((!Opts.tysan_writes_always_set_type || IsRead) &&
698 "should have handled case above");
699 LLVMContext &C = IRB.getContext();
700 MDNode *UnlikelyBW = MDBuilder(C).createBranchWeights(1, 100000);
701
702 if (!SanitizeFunction) {
703 // If we're not sanitizing this function, then we only care whether we
704 // need to *set* the type.
705 Value *LoadedTD = IRB.CreateLoad(IRB.getPtrTy(), ShadowData, "shadow.desc");
706 Value *NullTDCmp = IRB.CreateIsNull(LoadedTD, "desc.set");
708 NullTDCmp, &*IRB.GetInsertPoint(), false, UnlikelyBW);
709 IRB.SetInsertPoint(NullTDTerm);
710 NullTDTerm->getParent()->setName("set.type");
711 SetType();
712 return true;
713 }
714 // We need to check the type here. If the type is unknown, then the read
715 // sets the type. If the type is known, then it is checked. If the type
716 // doesn't match, then we call the runtime (which may yet determine that
717 // the mismatch is okay).
718 //
719 // The checks generated below have the following structure.
720 //
721 // ; First we load the descriptor for the load from shadow memory and
722 // ; compare it against the type descriptor for the current access type.
723 // %shadow.desc = load ptr %shadow.data
724 // %bad.desc = icmp ne %shadow.desc, %td
725 // br %bad.desc, %bad.bb, %good.bb
726 //
727 // bad.bb:
728 // %shadow.desc.null = icmp eq %shadow.desc, null
729 // br %shadow.desc.null, %null.td.bb, %good.td.bb
730 //
731 // null.td.bb:
732 // ; The typ is unknown, set it if all bytes in the value are also unknown.
733 // ; To check, we load the shadow data for all bytes of the access. For the
734 // ; pseudo code below, assume an access of size 1.
735 // %shadow.data.int = add %shadow.data.int, 0
736 // %l = load (inttoptr %shadow.data.int)
737 // %is.not.null = icmp ne %l, null
738 // %not.all.unknown = %is.not.null
739 // br %no.all.unknown, before.set.type.bb
740 //
741 // before.set.type.bb:
742 // ; Call runtime to check mismatch.
743 // call void @__tysan_check()
744 // br %set.type.bb
745 //
746 // set.type.bb:
747 // ; Now fill the remainder of the shadow memory corresponding to the
748 // ; remainder of the the bytes of the type with a bad type descriptor.
749 // store %TD, %shadow.data
750 // br %continue.bb
751 //
752 // good.td.bb::
753 // ; We have a non-trivial mismatch. Call the runtime.
754 // call void @__tysan_check()
755 // br %continue.bb
756 //
757 // good.bb:
758 // ; We appear to have the right type. Make sure that all other bytes in
759 // ; the type are still marked as interior bytes. If not, call the runtime.
760 // %shadow.data.int = add %shadow.data.int, 0
761 // %l = load (inttoptr %shadow.data.int)
762 // %not.all.interior = icmp sge %l, 0
763 // br %not.all.interior, label %check.rt.bb, label %continue.bb
764 //
765 // check.rt.bb:
766 // call void @__tysan_check()
767 // br %continue.bb
768
769 Constant *Flags = ConstantInt::get(OrdTy, int(IsRead) | (int(IsWrite) << 1));
770
771 Value *LoadedTD = IRB.CreateLoad(IRB.getPtrTy(), ShadowData, "shadow.desc");
772 Value *BadTDCmp = IRB.CreateICmpNE(LoadedTD, TD, "bad.desc");
773 Instruction *BadTDTerm, *GoodTDTerm;
774 SplitBlockAndInsertIfThenElse(BadTDCmp, &*IRB.GetInsertPoint(), &BadTDTerm,
775 &GoodTDTerm, UnlikelyBW);
776 IRB.SetInsertPoint(BadTDTerm);
777
778 // We now know that the types did not match (we're on the slow path). If
779 // the type is unknown, then set it.
780 Value *NullTDCmp = IRB.CreateIsNull(LoadedTD);
781 Instruction *NullTDTerm, *MismatchTerm;
782 SplitBlockAndInsertIfThenElse(NullTDCmp, &*IRB.GetInsertPoint(), &NullTDTerm,
783 &MismatchTerm);
784
785 // If the type is unknown, then set the type.
786 IRB.SetInsertPoint(NullTDTerm);
787
788 // We're about to set the type. Make sure that all bytes in the value are
789 // also of unknown type.
790 Value *Size = ConstantInt::get(OrdTy, AccessSize);
791 Value *NotAllUnkTD = IRB.getFalse();
792 for (uint64_t i = 1; i < AccessSize; ++i) {
793 Value *UnkShadowData = IRB.CreateIntToPtr(
794 IRB.CreateAdd(ShadowDataInt, ConstantInt::get(IntptrTy, i << PtrShift)),
795 Int8PtrPtrTy);
796 Value *ILdTD = IRB.CreateLoad(IRB.getPtrTy(), UnkShadowData);
797 NotAllUnkTD = IRB.CreateOr(NotAllUnkTD, IRB.CreateIsNotNull(ILdTD));
798 }
799
800 Instruction *BeforeSetType = &*IRB.GetInsertPoint();
801 Instruction *BadUTDTerm =
802 SplitBlockAndInsertIfThen(NotAllUnkTD, BeforeSetType, false, UnlikelyBW);
803 IRB.SetInsertPoint(BadUTDTerm);
804 IRB.CreateCall(TysanCheck, {IRB.CreateBitCast(Ptr, IRB.getPtrTy()), Size,
805 (Value *)TD, (Value *)Flags});
806
807 IRB.SetInsertPoint(BeforeSetType);
808 SetType();
809
810 // We have a non-trivial mismatch. Call the runtime.
811 IRB.SetInsertPoint(MismatchTerm);
812 IRB.CreateCall(TysanCheck, {IRB.CreateBitCast(Ptr, IRB.getPtrTy()), Size,
813 (Value *)TD, (Value *)Flags});
814
815 // We appear to have the right type. Make sure that all other bytes in
816 // the type are still marked as interior bytes. If not, call the runtime.
817 IRB.SetInsertPoint(GoodTDTerm);
818 Value *NotAllBadTD = IRB.getFalse();
819 for (uint64_t i = 1; i < AccessSize; ++i) {
820 Value *BadShadowData = IRB.CreateIntToPtr(
821 IRB.CreateAdd(ShadowDataInt, ConstantInt::get(IntptrTy, i << PtrShift)),
822 Int8PtrPtrTy);
823 Value *ILdTD = IRB.CreatePtrToInt(
824 IRB.CreateLoad(IRB.getPtrTy(), BadShadowData), IntptrTy);
825 NotAllBadTD = IRB.CreateOr(
826 NotAllBadTD, IRB.CreateICmpSGE(ILdTD, ConstantInt::get(IntptrTy, 0)));
827 }
828
830 NotAllBadTD, &*IRB.GetInsertPoint(), false, UnlikelyBW);
831 IRB.SetInsertPoint(BadITDTerm);
832 IRB.CreateCall(TysanCheck, {IRB.CreateBitCast(Ptr, IRB.getPtrTy()), Size,
833 (Value *)TD, (Value *)Flags});
834 return true;
835}
836
837bool TypeSanitizer::instrumentMemInst(Value *V, Instruction *ShadowBase,
838 Instruction *AppMemMask,
839 const DataLayout &DL) {
841 BasicBlock *BB;
842 Function *F;
843
844 if (auto *I = dyn_cast<Instruction>(V)) {
846 BB = I->getParent();
847 F = BB->getParent();
848 } else {
849 auto *A = cast<Argument>(V);
850 F = A->getParent();
851 BB = &F->getEntryBlock();
852 IP = BB->getFirstInsertionPt();
853
854 // Find the next insert point after both ShadowBase and AppMemMask.
855 if (IP->comesBefore(ShadowBase))
856 IP = ShadowBase->getNextNode()->getIterator();
857 if (IP->comesBefore(AppMemMask))
858 IP = AppMemMask->getNextNode()->getIterator();
859 }
860
861 Value *Dest, *Size, *Src = nullptr;
862 bool NeedsMemMove = false;
863 IRBuilder<> IRB(IP);
864
865 if (auto *A = dyn_cast<Argument>(V)) {
866 assert(A->hasByValAttr() && "Type reset for non-byval argument?");
867
868 Dest = A;
869 Size =
870 ConstantInt::get(IntptrTy, DL.getTypeAllocSize(A->getParamByValType()));
871 } else {
872 auto *I = cast<Instruction>(V);
873 if (auto *MI = dyn_cast<MemIntrinsic>(I)) {
874 if (MI->getDestAddressSpace() != 0)
875 return false;
876
877 Dest = MI->getDest();
878 Size = MI->getLength();
879
880 if (auto *MTI = dyn_cast<MemTransferInst>(MI)) {
881 if (MTI->getSourceAddressSpace() == 0) {
882 Src = MTI->getSource();
883 NeedsMemMove = isa<MemMoveInst>(MTI);
884 }
885 }
886 } else if (auto *II = dyn_cast<LifetimeIntrinsic>(I)) {
887 auto *AI = dyn_cast<AllocaInst>(II->getArgOperand(0));
888 if (!AI)
889 return false;
890
891 Size = IRB.CreateAllocationSize(IntptrTy, AI);
892 Dest = II->getArgOperand(0);
893 } else if (auto *AI = dyn_cast<AllocaInst>(I)) {
894 // We need to clear the types for new stack allocations (or else we might
895 // read stale type information from a previous function execution).
896
897 IRB.SetInsertPoint(&*std::next(BasicBlock::iterator(I)));
899
900 Size = IRB.CreateAllocationSize(IntptrTy, AI);
901 Dest = I;
902 } else {
903 return false;
904 }
905 }
906
907 if (OutlineInstrumentation) {
908 if (!Src)
910
911 // The runtime function expects a uint64_t size parameter. On 32-bit
912 // targets, Size may be IntptrTy (i32), so extend it to match.
913 Value *Size64 = IRB.CreateZExtOrTrunc(Size, U64Ty);
914 IRB.CreateCall(
915 TysanIntrumentMemInst,
916 {Dest, Src, Size64, NeedsMemMove ? IRB.getTrue() : IRB.getFalse()});
917 return true;
918 } else {
919 if (!ShadowBase)
920 ShadowBase = getShadowBase(*F);
921 if (!AppMemMask)
922 AppMemMask = getAppMemMask(*F);
923
924 Value *ShadowDataInt = IRB.CreateAdd(
925 IRB.CreateShl(
926 IRB.CreateAnd(IRB.CreatePtrToInt(Dest, IntptrTy), AppMemMask),
927 PtrShift),
928 ShadowBase);
929 Value *ShadowData = IRB.CreateIntToPtr(ShadowDataInt, IRB.getPtrTy());
930
931 if (!Src) {
932 IRB.CreateMemSet(ShadowData, IRB.getInt8(0),
933 IRB.CreateShl(Size, PtrShift),
934 Align::fromLog2(PtrShift));
935 return true;
936 }
937
938 Value *SrcShadowDataInt = IRB.CreateAdd(
939 IRB.CreateShl(
940 IRB.CreateAnd(IRB.CreatePtrToInt(Src, IntptrTy), AppMemMask),
941 PtrShift),
942 ShadowBase);
943 Value *SrcShadowData = IRB.CreateIntToPtr(SrcShadowDataInt, IRB.getPtrTy());
944
945 if (NeedsMemMove) {
946 IRB.CreateMemMove(ShadowData, Align::fromLog2(PtrShift), SrcShadowData,
947 Align::fromLog2(PtrShift),
948 IRB.CreateShl(Size, PtrShift));
949 } else {
950 IRB.CreateMemCpy(ShadowData, Align::fromLog2(PtrShift), SrcShadowData,
951 Align::fromLog2(PtrShift),
952 IRB.CreateShl(Size, PtrShift));
953 }
954 }
955
956 return true;
957}
958
961 Function *TysanCtorFunction;
962 std::tie(TysanCtorFunction, std::ignore) =
964 kTysanInitName, /*InitArgTypes=*/{},
965 /*InitArgs=*/{});
966
967 const InstrumentationOptions &Opts = InstrumentationOptions::Global;
968 TypeSanitizer TySan(Opts, M);
969 TySan.instrumentGlobals(M);
970 appendToGlobalCtors(M, TysanCtorFunction, 0);
971
972 auto &FAM = MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
973 for (Function &F : M) {
974 const TargetLibraryInfo &TLI = FAM.getResult<TargetLibraryAnalysis>(F);
975 TySan.sanitizeFunction(F, TLI);
976 if (Opts.tysan_verify_outlined_instrumentation &&
977 Opts.tysan_outline_instrumentation) {
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.
983 TySan.OutlineInstrumentation = false;
984 TySan.sanitizeFunction(F, TLI);
985 TySan.OutlineInstrumentation = true;
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 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 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:2148
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:660
ConstantInt * getTrue()
Get the constant value for i1 true.
Definition IRBuilder.h:454
Value * CreateICmpSGE(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2419
BasicBlock::iterator GetInsertPoint() const
Definition IRBuilder.h:180
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2247
ConstantInt * getInt8(uint8_t C)
Get a constant 8-bit value.
Definition IRBuilder.h:464
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2395
ConstantInt * getInt64(uint64_t C)
Get a constant 64-bit value.
Definition IRBuilder.h:479
CallInst * CreateMemMove(Value *Dst, MaybeAlign DstAlign, Value *Src, MaybeAlign SrcAlign, uint64_t Size, bool isVolatile=false, const AAMDNodes &AAInfo=AAMDNodes())
Definition IRBuilder.h:702
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2252
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:1916
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1516
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:605
LLVMContext & getContext() const
Definition IRBuilder.h:181
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:1575
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition IRBuilder.h:1934
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1427
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2242
ConstantInt * getFalse()
Get the constant value for i1 false.
Definition IRBuilder.h:459
Value * CreateIsNotNull(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg != 0.
Definition IRBuilder.h:2772
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args={}, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2570
PointerType * getPtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer.
Definition IRBuilder.h:574
Value * CreateIsNull(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg == 0.
Definition IRBuilder.h:2767
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:199
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:1597
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2918
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
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:1893
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:867
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
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
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...
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
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
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:3902
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
static constexpr Align fromLog2(unsigned Log2Value)
Returns an alignment of 1 << Log2Value bytes.
Definition Alignment.h:73
LLVM_ABI SmallString< 32 > digest() const
Definition MD5.cpp:280
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)