LLVM 20.0.0git
ThreadSanitizer.cpp
Go to the documentation of this file.
1//===-- ThreadSanitizer.cpp - race 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 ThreadSanitizer, a race detector.
10//
11// The tool is under development, for the details about previous versions see
12// http://code.google.com/p/data-race-test
13//
14// The instrumentation phase is quite simple:
15// - Insert calls to run-time library before every memory access.
16// - Optimizations may apply to avoid instrumenting some of the accesses.
17// - Insert calls at function entry/exit.
18// The rest is handled by the run-time library.
19//===----------------------------------------------------------------------===//
20
22#include "llvm/ADT/DenseMap.h"
25#include "llvm/ADT/Statistic.h"
30#include "llvm/IR/DataLayout.h"
31#include "llvm/IR/Function.h"
32#include "llvm/IR/IRBuilder.h"
35#include "llvm/IR/Intrinsics.h"
36#include "llvm/IR/LLVMContext.h"
37#include "llvm/IR/Metadata.h"
38#include "llvm/IR/Module.h"
39#include "llvm/IR/Type.h"
42#include "llvm/Support/Debug.h"
49
50using namespace llvm;
51
52#define DEBUG_TYPE "tsan"
53
55 "tsan-instrument-memory-accesses", cl::init(true),
56 cl::desc("Instrument memory accesses"), cl::Hidden);
57static cl::opt<bool>
58 ClInstrumentFuncEntryExit("tsan-instrument-func-entry-exit", cl::init(true),
59 cl::desc("Instrument function entry and exit"),
62 "tsan-handle-cxx-exceptions", cl::init(true),
63 cl::desc("Handle C++ exceptions (insert cleanup blocks for unwinding)"),
65static cl::opt<bool> ClInstrumentAtomics("tsan-instrument-atomics",
66 cl::init(true),
67 cl::desc("Instrument atomics"),
70 "tsan-instrument-memintrinsics", cl::init(true),
71 cl::desc("Instrument memintrinsics (memset/memcpy/memmove)"), cl::Hidden);
73 "tsan-distinguish-volatile", cl::init(false),
74 cl::desc("Emit special instrumentation for accesses to volatiles"),
77 "tsan-instrument-read-before-write", cl::init(false),
78 cl::desc("Do not eliminate read instrumentation for read-before-writes"),
81 "tsan-compound-read-before-write", cl::init(false),
82 cl::desc("Emit special compound instrumentation for reads-before-writes"),
84
85STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
86STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
87STATISTIC(NumOmittedReadsBeforeWrite,
88 "Number of reads ignored due to following writes");
89STATISTIC(NumAccessesWithBadSize, "Number of accesses with bad size");
90STATISTIC(NumInstrumentedVtableWrites, "Number of vtable ptr writes");
91STATISTIC(NumInstrumentedVtableReads, "Number of vtable ptr reads");
92STATISTIC(NumOmittedReadsFromConstantGlobals,
93 "Number of reads from constant globals");
94STATISTIC(NumOmittedReadsFromVtable, "Number of vtable reads");
95STATISTIC(NumOmittedNonCaptured, "Number of accesses ignored due to capturing");
96
97const char kTsanModuleCtorName[] = "tsan.module_ctor";
98const char kTsanInitName[] = "__tsan_init";
99
100namespace {
101
102/// ThreadSanitizer: instrument the code in module to find races.
103///
104/// Instantiating ThreadSanitizer inserts the tsan runtime library API function
105/// declarations into the module if they don't exist already. Instantiating
106/// ensures the __tsan_init function is in the list of global constructors for
107/// the module.
108struct ThreadSanitizer {
109 ThreadSanitizer() {
110 // Check options and warn user.
112 errs()
113 << "warning: Option -tsan-compound-read-before-write has no effect "
114 "when -tsan-instrument-read-before-write is set.\n";
115 }
116 }
117
118 bool sanitizeFunction(Function &F, const TargetLibraryInfo &TLI);
119
120private:
121 // Internal Instruction wrapper that contains more information about the
122 // Instruction from prior analysis.
123 struct InstructionInfo {
124 // Instrumentation emitted for this instruction is for a compounded set of
125 // read and write operations in the same basic block.
126 static constexpr unsigned kCompoundRW = (1U << 0);
127
128 explicit InstructionInfo(Instruction *Inst) : Inst(Inst) {}
129
130 Instruction *Inst;
131 unsigned Flags = 0;
132 };
133
134 void initialize(Module &M, const TargetLibraryInfo &TLI);
135 bool instrumentLoadOrStore(const InstructionInfo &II, const DataLayout &DL);
136 bool instrumentAtomic(Instruction *I, const DataLayout &DL);
137 bool instrumentMemIntrinsic(Instruction *I);
138 void chooseInstructionsToInstrument(SmallVectorImpl<Instruction *> &Local,
140 const DataLayout &DL);
141 bool addrPointsToConstantData(Value *Addr);
142 int getMemoryAccessFuncIndex(Type *OrigTy, Value *Addr, const DataLayout &DL);
143 void InsertRuntimeIgnores(Function &F);
144
145 Type *IntptrTy;
146 FunctionCallee TsanFuncEntry;
147 FunctionCallee TsanFuncExit;
148 FunctionCallee TsanIgnoreBegin;
149 FunctionCallee TsanIgnoreEnd;
150 // Accesses sizes are powers of two: 1, 2, 4, 8, 16.
151 static const size_t kNumberOfAccessSizes = 5;
152 FunctionCallee TsanRead[kNumberOfAccessSizes];
153 FunctionCallee TsanWrite[kNumberOfAccessSizes];
154 FunctionCallee TsanUnalignedRead[kNumberOfAccessSizes];
155 FunctionCallee TsanUnalignedWrite[kNumberOfAccessSizes];
156 FunctionCallee TsanVolatileRead[kNumberOfAccessSizes];
157 FunctionCallee TsanVolatileWrite[kNumberOfAccessSizes];
158 FunctionCallee TsanUnalignedVolatileRead[kNumberOfAccessSizes];
159 FunctionCallee TsanUnalignedVolatileWrite[kNumberOfAccessSizes];
160 FunctionCallee TsanCompoundRW[kNumberOfAccessSizes];
161 FunctionCallee TsanUnalignedCompoundRW[kNumberOfAccessSizes];
162 FunctionCallee TsanAtomicLoad[kNumberOfAccessSizes];
163 FunctionCallee TsanAtomicStore[kNumberOfAccessSizes];
165 [kNumberOfAccessSizes];
166 FunctionCallee TsanAtomicCAS[kNumberOfAccessSizes];
167 FunctionCallee TsanAtomicThreadFence;
168 FunctionCallee TsanAtomicSignalFence;
169 FunctionCallee TsanVptrUpdate;
170 FunctionCallee TsanVptrLoad;
171 FunctionCallee MemmoveFn, MemcpyFn, MemsetFn;
172};
173
174void insertModuleCtor(Module &M) {
176 M, kTsanModuleCtorName, kTsanInitName, /*InitArgTypes=*/{},
177 /*InitArgs=*/{},
178 // This callback is invoked when the functions are created the first
179 // time. Hook them into the global ctors list in that case:
180 [&](Function *Ctor, FunctionCallee) { appendToGlobalCtors(M, Ctor, 0); });
181}
182} // namespace
183
186 ThreadSanitizer TSan;
187 if (TSan.sanitizeFunction(F, FAM.getResult<TargetLibraryAnalysis>(F)))
189 return PreservedAnalyses::all();
190}
191
194 // Return early if nosanitize_thread module flag is present for the module.
195 if (checkIfAlreadyInstrumented(M, "nosanitize_thread"))
196 return PreservedAnalyses::all();
197 insertModuleCtor(M);
199}
200void ThreadSanitizer::initialize(Module &M, const TargetLibraryInfo &TLI) {
201 const DataLayout &DL = M.getDataLayout();
202 LLVMContext &Ctx = M.getContext();
203 IntptrTy = DL.getIntPtrType(Ctx);
204
205 IRBuilder<> IRB(Ctx);
206 AttributeList Attr;
207 Attr = Attr.addFnAttribute(Ctx, Attribute::NoUnwind);
208 // Initialize the callbacks.
209 TsanFuncEntry = M.getOrInsertFunction("__tsan_func_entry", Attr,
210 IRB.getVoidTy(), IRB.getPtrTy());
211 TsanFuncExit =
212 M.getOrInsertFunction("__tsan_func_exit", Attr, IRB.getVoidTy());
213 TsanIgnoreBegin = M.getOrInsertFunction("__tsan_ignore_thread_begin", Attr,
214 IRB.getVoidTy());
215 TsanIgnoreEnd =
216 M.getOrInsertFunction("__tsan_ignore_thread_end", Attr, IRB.getVoidTy());
217 IntegerType *OrdTy = IRB.getInt32Ty();
218 for (size_t i = 0; i < kNumberOfAccessSizes; ++i) {
219 const unsigned ByteSize = 1U << i;
220 const unsigned BitSize = ByteSize * 8;
221 std::string ByteSizeStr = utostr(ByteSize);
222 std::string BitSizeStr = utostr(BitSize);
223 SmallString<32> ReadName("__tsan_read" + ByteSizeStr);
224 TsanRead[i] = M.getOrInsertFunction(ReadName, Attr, IRB.getVoidTy(),
225 IRB.getPtrTy());
226
227 SmallString<32> WriteName("__tsan_write" + ByteSizeStr);
228 TsanWrite[i] = M.getOrInsertFunction(WriteName, Attr, IRB.getVoidTy(),
229 IRB.getPtrTy());
230
231 SmallString<64> UnalignedReadName("__tsan_unaligned_read" + ByteSizeStr);
232 TsanUnalignedRead[i] = M.getOrInsertFunction(
233 UnalignedReadName, Attr, IRB.getVoidTy(), IRB.getPtrTy());
234
235 SmallString<64> UnalignedWriteName("__tsan_unaligned_write" + ByteSizeStr);
236 TsanUnalignedWrite[i] = M.getOrInsertFunction(
237 UnalignedWriteName, Attr, IRB.getVoidTy(), IRB.getPtrTy());
238
239 SmallString<64> VolatileReadName("__tsan_volatile_read" + ByteSizeStr);
240 TsanVolatileRead[i] = M.getOrInsertFunction(
241 VolatileReadName, Attr, IRB.getVoidTy(), IRB.getPtrTy());
242
243 SmallString<64> VolatileWriteName("__tsan_volatile_write" + ByteSizeStr);
244 TsanVolatileWrite[i] = M.getOrInsertFunction(
245 VolatileWriteName, Attr, IRB.getVoidTy(), IRB.getPtrTy());
246
247 SmallString<64> UnalignedVolatileReadName("__tsan_unaligned_volatile_read" +
248 ByteSizeStr);
249 TsanUnalignedVolatileRead[i] = M.getOrInsertFunction(
250 UnalignedVolatileReadName, Attr, IRB.getVoidTy(), IRB.getPtrTy());
251
252 SmallString<64> UnalignedVolatileWriteName(
253 "__tsan_unaligned_volatile_write" + ByteSizeStr);
254 TsanUnalignedVolatileWrite[i] = M.getOrInsertFunction(
255 UnalignedVolatileWriteName, Attr, IRB.getVoidTy(), IRB.getPtrTy());
256
257 SmallString<64> CompoundRWName("__tsan_read_write" + ByteSizeStr);
258 TsanCompoundRW[i] = M.getOrInsertFunction(
259 CompoundRWName, Attr, IRB.getVoidTy(), IRB.getPtrTy());
260
261 SmallString<64> UnalignedCompoundRWName("__tsan_unaligned_read_write" +
262 ByteSizeStr);
263 TsanUnalignedCompoundRW[i] = M.getOrInsertFunction(
264 UnalignedCompoundRWName, Attr, IRB.getVoidTy(), IRB.getPtrTy());
265
266 Type *Ty = Type::getIntNTy(Ctx, BitSize);
267 Type *PtrTy = PointerType::get(Ctx, 0);
268 SmallString<32> AtomicLoadName("__tsan_atomic" + BitSizeStr + "_load");
269 TsanAtomicLoad[i] =
270 M.getOrInsertFunction(AtomicLoadName,
271 TLI.getAttrList(&Ctx, {1}, /*Signed=*/true,
272 /*Ret=*/BitSize <= 32, Attr),
273 Ty, PtrTy, OrdTy);
274
275 // Args of type Ty need extension only when BitSize is 32 or less.
276 using Idxs = std::vector<unsigned>;
277 Idxs Idxs2Or12 ((BitSize <= 32) ? Idxs({1, 2}) : Idxs({2}));
278 Idxs Idxs34Or1234((BitSize <= 32) ? Idxs({1, 2, 3, 4}) : Idxs({3, 4}));
279 SmallString<32> AtomicStoreName("__tsan_atomic" + BitSizeStr + "_store");
280 TsanAtomicStore[i] = M.getOrInsertFunction(
281 AtomicStoreName,
282 TLI.getAttrList(&Ctx, Idxs2Or12, /*Signed=*/true, /*Ret=*/false, Attr),
283 IRB.getVoidTy(), PtrTy, Ty, OrdTy);
284
285 for (unsigned Op = AtomicRMWInst::FIRST_BINOP;
287 TsanAtomicRMW[Op][i] = nullptr;
288 const char *NamePart = nullptr;
289 if (Op == AtomicRMWInst::Xchg)
290 NamePart = "_exchange";
291 else if (Op == AtomicRMWInst::Add)
292 NamePart = "_fetch_add";
293 else if (Op == AtomicRMWInst::Sub)
294 NamePart = "_fetch_sub";
295 else if (Op == AtomicRMWInst::And)
296 NamePart = "_fetch_and";
297 else if (Op == AtomicRMWInst::Or)
298 NamePart = "_fetch_or";
299 else if (Op == AtomicRMWInst::Xor)
300 NamePart = "_fetch_xor";
301 else if (Op == AtomicRMWInst::Nand)
302 NamePart = "_fetch_nand";
303 else
304 continue;
305 SmallString<32> RMWName("__tsan_atomic" + itostr(BitSize) + NamePart);
306 TsanAtomicRMW[Op][i] = M.getOrInsertFunction(
307 RMWName,
308 TLI.getAttrList(&Ctx, Idxs2Or12, /*Signed=*/true,
309 /*Ret=*/BitSize <= 32, Attr),
310 Ty, PtrTy, Ty, OrdTy);
311 }
312
313 SmallString<32> AtomicCASName("__tsan_atomic" + BitSizeStr +
314 "_compare_exchange_val");
315 TsanAtomicCAS[i] = M.getOrInsertFunction(
316 AtomicCASName,
317 TLI.getAttrList(&Ctx, Idxs34Or1234, /*Signed=*/true,
318 /*Ret=*/BitSize <= 32, Attr),
319 Ty, PtrTy, Ty, Ty, OrdTy, OrdTy);
320 }
321 TsanVptrUpdate =
322 M.getOrInsertFunction("__tsan_vptr_update", Attr, IRB.getVoidTy(),
323 IRB.getPtrTy(), IRB.getPtrTy());
324 TsanVptrLoad = M.getOrInsertFunction("__tsan_vptr_read", Attr,
325 IRB.getVoidTy(), IRB.getPtrTy());
326 TsanAtomicThreadFence = M.getOrInsertFunction(
327 "__tsan_atomic_thread_fence",
328 TLI.getAttrList(&Ctx, {0}, /*Signed=*/true, /*Ret=*/false, Attr),
329 IRB.getVoidTy(), OrdTy);
330
331 TsanAtomicSignalFence = M.getOrInsertFunction(
332 "__tsan_atomic_signal_fence",
333 TLI.getAttrList(&Ctx, {0}, /*Signed=*/true, /*Ret=*/false, Attr),
334 IRB.getVoidTy(), OrdTy);
335
336 MemmoveFn =
337 M.getOrInsertFunction("__tsan_memmove", Attr, IRB.getPtrTy(),
338 IRB.getPtrTy(), IRB.getPtrTy(), IntptrTy);
339 MemcpyFn =
340 M.getOrInsertFunction("__tsan_memcpy", Attr, IRB.getPtrTy(),
341 IRB.getPtrTy(), IRB.getPtrTy(), IntptrTy);
342 MemsetFn = M.getOrInsertFunction(
343 "__tsan_memset",
344 TLI.getAttrList(&Ctx, {1}, /*Signed=*/true, /*Ret=*/false, Attr),
345 IRB.getPtrTy(), IRB.getPtrTy(), IRB.getInt32Ty(), IntptrTy);
346}
347
349 if (MDNode *Tag = I->getMetadata(LLVMContext::MD_tbaa))
350 return Tag->isTBAAVtableAccess();
351 return false;
352}
353
354// Do not instrument known races/"benign races" that come from compiler
355// instrumentatin. The user has no way of suppressing them.
357 // Peel off GEPs and BitCasts.
358 Addr = Addr->stripInBoundsOffsets();
359
360 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
361 if (GV->hasSection()) {
362 StringRef SectionName = GV->getSection();
363 // Check if the global is in the PGO counters section.
364 auto OF = Triple(M->getTargetTriple()).getObjectFormat();
365 if (SectionName.ends_with(
366 getInstrProfSectionName(IPSK_cnts, OF, /*AddSegmentInfo=*/false)))
367 return false;
368 }
369 }
370
371 // Do not instrument accesses from different address spaces; we cannot deal
372 // with them.
373 if (Addr) {
374 Type *PtrTy = cast<PointerType>(Addr->getType()->getScalarType());
375 if (PtrTy->getPointerAddressSpace() != 0)
376 return false;
377 }
378
379 return true;
380}
381
382bool ThreadSanitizer::addrPointsToConstantData(Value *Addr) {
383 // If this is a GEP, just analyze its pointer operand.
384 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Addr))
385 Addr = GEP->getPointerOperand();
386
387 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
388 if (GV->isConstant()) {
389 // Reads from constant globals can not race with any writes.
390 NumOmittedReadsFromConstantGlobals++;
391 return true;
392 }
393 } else if (LoadInst *L = dyn_cast<LoadInst>(Addr)) {
394 if (isVtableAccess(L)) {
395 // Reads from a vtable pointer can not race with any writes.
396 NumOmittedReadsFromVtable++;
397 return true;
398 }
399 }
400 return false;
401}
402
403// Instrumenting some of the accesses may be proven redundant.
404// Currently handled:
405// - read-before-write (within same BB, no calls between)
406// - not captured variables
407//
408// We do not handle some of the patterns that should not survive
409// after the classic compiler optimizations.
410// E.g. two reads from the same temp should be eliminated by CSE,
411// two writes should be eliminated by DSE, etc.
412//
413// 'Local' is a vector of insns within the same BB (no calls between).
414// 'All' is a vector of insns that will be instrumented.
415void ThreadSanitizer::chooseInstructionsToInstrument(
418 DenseMap<Value *, size_t> WriteTargets; // Map of addresses to index in All
419 // Iterate from the end.
420 for (Instruction *I : reverse(Local)) {
421 const bool IsWrite = isa<StoreInst>(*I);
422 Value *Addr = IsWrite ? cast<StoreInst>(I)->getPointerOperand()
423 : cast<LoadInst>(I)->getPointerOperand();
424
425 if (!shouldInstrumentReadWriteFromAddress(I->getModule(), Addr))
426 continue;
427
428 if (!IsWrite) {
429 const auto WriteEntry = WriteTargets.find(Addr);
430 if (!ClInstrumentReadBeforeWrite && WriteEntry != WriteTargets.end()) {
431 auto &WI = All[WriteEntry->second];
432 // If we distinguish volatile accesses and if either the read or write
433 // is volatile, do not omit any instrumentation.
434 const bool AnyVolatile =
435 ClDistinguishVolatile && (cast<LoadInst>(I)->isVolatile() ||
436 cast<StoreInst>(WI.Inst)->isVolatile());
437 if (!AnyVolatile) {
438 // We will write to this temp, so no reason to analyze the read.
439 // Mark the write instruction as compound.
440 WI.Flags |= InstructionInfo::kCompoundRW;
441 NumOmittedReadsBeforeWrite++;
442 continue;
443 }
444 }
445
446 if (addrPointsToConstantData(Addr)) {
447 // Addr points to some constant data -- it can not race with any writes.
448 continue;
449 }
450 }
451
452 if (isa<AllocaInst>(getUnderlyingObject(Addr)) &&
453 !PointerMayBeCaptured(Addr, true, true)) {
454 // The variable is addressable but not captured, so it cannot be
455 // referenced from a different thread and participate in a data race
456 // (see llvm/Analysis/CaptureTracking.h for details).
457 NumOmittedNonCaptured++;
458 continue;
459 }
460
461 // Instrument this instruction.
462 All.emplace_back(I);
463 if (IsWrite) {
464 // For read-before-write and compound instrumentation we only need one
465 // write target, and we can override any previous entry if it exists.
466 WriteTargets[Addr] = All.size() - 1;
467 }
468 }
469 Local.clear();
470}
471
472static bool isTsanAtomic(const Instruction *I) {
473 // TODO: Ask TTI whether synchronization scope is between threads.
474 auto SSID = getAtomicSyncScopeID(I);
475 if (!SSID)
476 return false;
477 if (isa<LoadInst>(I) || isa<StoreInst>(I))
478 return *SSID != SyncScope::SingleThread;
479 return true;
480}
481
482void ThreadSanitizer::InsertRuntimeIgnores(Function &F) {
483 InstrumentationIRBuilder IRB(F.getEntryBlock().getFirstNonPHI());
484 IRB.CreateCall(TsanIgnoreBegin);
485 EscapeEnumerator EE(F, "tsan_ignore_cleanup", ClHandleCxxExceptions);
486 while (IRBuilder<> *AtExit = EE.Next()) {
488 AtExit->CreateCall(TsanIgnoreEnd);
489 }
490}
491
492bool ThreadSanitizer::sanitizeFunction(Function &F,
493 const TargetLibraryInfo &TLI) {
494 // This is required to prevent instrumenting call to __tsan_init from within
495 // the module constructor.
496 if (F.getName() == kTsanModuleCtorName)
497 return false;
498 // Naked functions can not have prologue/epilogue
499 // (__tsan_func_entry/__tsan_func_exit) generated, so don't instrument them at
500 // all.
501 if (F.hasFnAttribute(Attribute::Naked))
502 return false;
503
504 // __attribute__(disable_sanitizer_instrumentation) prevents all kinds of
505 // instrumentation.
506 if (F.hasFnAttribute(Attribute::DisableSanitizerInstrumentation))
507 return false;
508
509 initialize(*F.getParent(), TLI);
510 SmallVector<InstructionInfo, 8> AllLoadsAndStores;
511 SmallVector<Instruction*, 8> LocalLoadsAndStores;
512 SmallVector<Instruction*, 8> AtomicAccesses;
513 SmallVector<Instruction*, 8> MemIntrinCalls;
514 bool Res = false;
515 bool HasCalls = false;
516 bool SanitizeFunction = F.hasFnAttribute(Attribute::SanitizeThread);
517 const DataLayout &DL = F.getDataLayout();
518
519 // Traverse all instructions, collect loads/stores/returns, check for calls.
520 for (auto &BB : F) {
521 for (auto &Inst : BB) {
522 // Skip instructions inserted by another instrumentation.
523 if (Inst.hasMetadata(LLVMContext::MD_nosanitize))
524 continue;
525 if (isTsanAtomic(&Inst))
526 AtomicAccesses.push_back(&Inst);
527 else if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst))
528 LocalLoadsAndStores.push_back(&Inst);
529 else if ((isa<CallInst>(Inst) && !isa<DbgInfoIntrinsic>(Inst)) ||
530 isa<InvokeInst>(Inst)) {
531 if (CallInst *CI = dyn_cast<CallInst>(&Inst))
533 if (isa<MemIntrinsic>(Inst))
534 MemIntrinCalls.push_back(&Inst);
535 HasCalls = true;
536 chooseInstructionsToInstrument(LocalLoadsAndStores, AllLoadsAndStores,
537 DL);
538 }
539 }
540 chooseInstructionsToInstrument(LocalLoadsAndStores, AllLoadsAndStores, DL);
541 }
542
543 // We have collected all loads and stores.
544 // FIXME: many of these accesses do not need to be checked for races
545 // (e.g. variables that do not escape, etc).
546
547 // Instrument memory accesses only if we want to report bugs in the function.
548 if (ClInstrumentMemoryAccesses && SanitizeFunction)
549 for (const auto &II : AllLoadsAndStores) {
550 Res |= instrumentLoadOrStore(II, DL);
551 }
552
553 // Instrument atomic memory accesses in any case (they can be used to
554 // implement synchronization).
556 for (auto *Inst : AtomicAccesses) {
557 Res |= instrumentAtomic(Inst, DL);
558 }
559
560 if (ClInstrumentMemIntrinsics && SanitizeFunction)
561 for (auto *Inst : MemIntrinCalls) {
562 Res |= instrumentMemIntrinsic(Inst);
563 }
564
565 if (F.hasFnAttribute("sanitize_thread_no_checking_at_run_time")) {
566 assert(!F.hasFnAttribute(Attribute::SanitizeThread));
567 if (HasCalls)
568 InsertRuntimeIgnores(F);
569 }
570
571 // Instrument function entry/exit points if there were instrumented accesses.
572 if ((Res || HasCalls) && ClInstrumentFuncEntryExit) {
573 InstrumentationIRBuilder IRB(F.getEntryBlock().getFirstNonPHI());
574 Value *ReturnAddress = IRB.CreateCall(
575 Intrinsic::getDeclaration(F.getParent(), Intrinsic::returnaddress),
576 IRB.getInt32(0));
577 IRB.CreateCall(TsanFuncEntry, ReturnAddress);
578
579 EscapeEnumerator EE(F, "tsan_cleanup", ClHandleCxxExceptions);
580 while (IRBuilder<> *AtExit = EE.Next()) {
582 AtExit->CreateCall(TsanFuncExit, {});
583 }
584 Res = true;
585 }
586 return Res;
587}
588
589bool ThreadSanitizer::instrumentLoadOrStore(const InstructionInfo &II,
590 const DataLayout &DL) {
592 const bool IsWrite = isa<StoreInst>(*II.Inst);
593 Value *Addr = IsWrite ? cast<StoreInst>(II.Inst)->getPointerOperand()
594 : cast<LoadInst>(II.Inst)->getPointerOperand();
595 Type *OrigTy = getLoadStoreType(II.Inst);
596
597 // swifterror memory addresses are mem2reg promoted by instruction selection.
598 // As such they cannot have regular uses like an instrumentation function and
599 // it makes no sense to track them as memory.
600 if (Addr->isSwiftError())
601 return false;
602
603 int Idx = getMemoryAccessFuncIndex(OrigTy, Addr, DL);
604 if (Idx < 0)
605 return false;
606 if (IsWrite && isVtableAccess(II.Inst)) {
607 LLVM_DEBUG(dbgs() << " VPTR : " << *II.Inst << "\n");
608 Value *StoredValue = cast<StoreInst>(II.Inst)->getValueOperand();
609 // StoredValue may be a vector type if we are storing several vptrs at once.
610 // In this case, just take the first element of the vector since this is
611 // enough to find vptr races.
612 if (isa<VectorType>(StoredValue->getType()))
613 StoredValue = IRB.CreateExtractElement(
614 StoredValue, ConstantInt::get(IRB.getInt32Ty(), 0));
615 if (StoredValue->getType()->isIntegerTy())
616 StoredValue = IRB.CreateIntToPtr(StoredValue, IRB.getPtrTy());
617 // Call TsanVptrUpdate.
618 IRB.CreateCall(TsanVptrUpdate, {Addr, StoredValue});
619 NumInstrumentedVtableWrites++;
620 return true;
621 }
622 if (!IsWrite && isVtableAccess(II.Inst)) {
623 IRB.CreateCall(TsanVptrLoad, Addr);
624 NumInstrumentedVtableReads++;
625 return true;
626 }
627
628 const Align Alignment = IsWrite ? cast<StoreInst>(II.Inst)->getAlign()
629 : cast<LoadInst>(II.Inst)->getAlign();
630 const bool IsCompoundRW =
631 ClCompoundReadBeforeWrite && (II.Flags & InstructionInfo::kCompoundRW);
632 const bool IsVolatile = ClDistinguishVolatile &&
633 (IsWrite ? cast<StoreInst>(II.Inst)->isVolatile()
634 : cast<LoadInst>(II.Inst)->isVolatile());
635 assert((!IsVolatile || !IsCompoundRW) && "Compound volatile invalid!");
636
637 const uint32_t TypeSize = DL.getTypeStoreSizeInBits(OrigTy);
638 FunctionCallee OnAccessFunc = nullptr;
639 if (Alignment >= Align(8) || (Alignment.value() % (TypeSize / 8)) == 0) {
640 if (IsCompoundRW)
641 OnAccessFunc = TsanCompoundRW[Idx];
642 else if (IsVolatile)
643 OnAccessFunc = IsWrite ? TsanVolatileWrite[Idx] : TsanVolatileRead[Idx];
644 else
645 OnAccessFunc = IsWrite ? TsanWrite[Idx] : TsanRead[Idx];
646 } else {
647 if (IsCompoundRW)
648 OnAccessFunc = TsanUnalignedCompoundRW[Idx];
649 else if (IsVolatile)
650 OnAccessFunc = IsWrite ? TsanUnalignedVolatileWrite[Idx]
651 : TsanUnalignedVolatileRead[Idx];
652 else
653 OnAccessFunc = IsWrite ? TsanUnalignedWrite[Idx] : TsanUnalignedRead[Idx];
654 }
655 IRB.CreateCall(OnAccessFunc, Addr);
656 if (IsCompoundRW || IsWrite)
657 NumInstrumentedWrites++;
658 if (IsCompoundRW || !IsWrite)
659 NumInstrumentedReads++;
660 return true;
661}
662
664 uint32_t v = 0;
665 switch (ord) {
667 llvm_unreachable("unexpected atomic ordering!");
668 case AtomicOrdering::Unordered: [[fallthrough]];
669 case AtomicOrdering::Monotonic: v = 0; break;
670 // Not specified yet:
671 // case AtomicOrdering::Consume: v = 1; break;
672 case AtomicOrdering::Acquire: v = 2; break;
673 case AtomicOrdering::Release: v = 3; break;
674 case AtomicOrdering::AcquireRelease: v = 4; break;
676 }
677 return IRB->getInt32(v);
678}
679
680// If a memset intrinsic gets inlined by the code gen, we will miss races on it.
681// So, we either need to ensure the intrinsic is not inlined, or instrument it.
682// We do not instrument memset/memmove/memcpy intrinsics (too complicated),
683// instead we simply replace them with regular function calls, which are then
684// intercepted by the run-time.
685// Since tsan is running after everyone else, the calls should not be
686// replaced back with intrinsics. If that becomes wrong at some point,
687// we will need to call e.g. __tsan_memset to avoid the intrinsics.
688bool ThreadSanitizer::instrumentMemIntrinsic(Instruction *I) {
690 if (MemSetInst *M = dyn_cast<MemSetInst>(I)) {
691 Value *Cast1 = IRB.CreateIntCast(M->getArgOperand(1), IRB.getInt32Ty(), false);
692 Value *Cast2 = IRB.CreateIntCast(M->getArgOperand(2), IntptrTy, false);
693 IRB.CreateCall(
694 MemsetFn,
695 {M->getArgOperand(0),
696 Cast1,
697 Cast2});
698 I->eraseFromParent();
699 } else if (MemTransferInst *M = dyn_cast<MemTransferInst>(I)) {
700 IRB.CreateCall(
701 isa<MemCpyInst>(M) ? MemcpyFn : MemmoveFn,
702 {M->getArgOperand(0),
703 M->getArgOperand(1),
704 IRB.CreateIntCast(M->getArgOperand(2), IntptrTy, false)});
705 I->eraseFromParent();
706 }
707 return false;
708}
709
710// Both llvm and ThreadSanitizer atomic operations are based on C++11/C1x
711// standards. For background see C++11 standard. A slightly older, publicly
712// available draft of the standard (not entirely up-to-date, but close enough
713// for casual browsing) is available here:
714// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2011/n3242.pdf
715// The following page contains more background information:
716// http://www.hpl.hp.com/personal/Hans_Boehm/c++mm/
717
718bool ThreadSanitizer::instrumentAtomic(Instruction *I, const DataLayout &DL) {
720 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
721 Value *Addr = LI->getPointerOperand();
722 Type *OrigTy = LI->getType();
723 int Idx = getMemoryAccessFuncIndex(OrigTy, Addr, DL);
724 if (Idx < 0)
725 return false;
726 Value *Args[] = {Addr,
727 createOrdering(&IRB, LI->getOrdering())};
728 Value *C = IRB.CreateCall(TsanAtomicLoad[Idx], Args);
729 Value *Cast = IRB.CreateBitOrPointerCast(C, OrigTy);
730 I->replaceAllUsesWith(Cast);
731 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
732 Value *Addr = SI->getPointerOperand();
733 int Idx =
734 getMemoryAccessFuncIndex(SI->getValueOperand()->getType(), Addr, DL);
735 if (Idx < 0)
736 return false;
737 const unsigned ByteSize = 1U << Idx;
738 const unsigned BitSize = ByteSize * 8;
739 Type *Ty = Type::getIntNTy(IRB.getContext(), BitSize);
740 Value *Args[] = {Addr,
741 IRB.CreateBitOrPointerCast(SI->getValueOperand(), Ty),
742 createOrdering(&IRB, SI->getOrdering())};
743 IRB.CreateCall(TsanAtomicStore[Idx], Args);
744 SI->eraseFromParent();
745 } else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I)) {
746 Value *Addr = RMWI->getPointerOperand();
747 int Idx =
748 getMemoryAccessFuncIndex(RMWI->getValOperand()->getType(), Addr, DL);
749 if (Idx < 0)
750 return false;
751 FunctionCallee F = TsanAtomicRMW[RMWI->getOperation()][Idx];
752 if (!F)
753 return false;
754 const unsigned ByteSize = 1U << Idx;
755 const unsigned BitSize = ByteSize * 8;
756 Type *Ty = Type::getIntNTy(IRB.getContext(), BitSize);
757 Value *Val = RMWI->getValOperand();
758 Value *Args[] = {Addr, IRB.CreateBitOrPointerCast(Val, Ty),
759 createOrdering(&IRB, RMWI->getOrdering())};
760 Value *C = IRB.CreateCall(F, Args);
761 I->replaceAllUsesWith(IRB.CreateBitOrPointerCast(C, Val->getType()));
762 I->eraseFromParent();
763 } else if (AtomicCmpXchgInst *CASI = dyn_cast<AtomicCmpXchgInst>(I)) {
764 Value *Addr = CASI->getPointerOperand();
765 Type *OrigOldValTy = CASI->getNewValOperand()->getType();
766 int Idx = getMemoryAccessFuncIndex(OrigOldValTy, Addr, DL);
767 if (Idx < 0)
768 return false;
769 const unsigned ByteSize = 1U << Idx;
770 const unsigned BitSize = ByteSize * 8;
771 Type *Ty = Type::getIntNTy(IRB.getContext(), BitSize);
772 Value *CmpOperand =
773 IRB.CreateBitOrPointerCast(CASI->getCompareOperand(), Ty);
774 Value *NewOperand =
775 IRB.CreateBitOrPointerCast(CASI->getNewValOperand(), Ty);
776 Value *Args[] = {Addr,
777 CmpOperand,
778 NewOperand,
779 createOrdering(&IRB, CASI->getSuccessOrdering()),
780 createOrdering(&IRB, CASI->getFailureOrdering())};
781 CallInst *C = IRB.CreateCall(TsanAtomicCAS[Idx], Args);
782 Value *Success = IRB.CreateICmpEQ(C, CmpOperand);
783 Value *OldVal = C;
784 if (Ty != OrigOldValTy) {
785 // The value is a pointer, so we need to cast the return value.
786 OldVal = IRB.CreateIntToPtr(C, OrigOldValTy);
787 }
788
789 Value *Res =
790 IRB.CreateInsertValue(PoisonValue::get(CASI->getType()), OldVal, 0);
791 Res = IRB.CreateInsertValue(Res, Success, 1);
792
793 I->replaceAllUsesWith(Res);
794 I->eraseFromParent();
795 } else if (FenceInst *FI = dyn_cast<FenceInst>(I)) {
796 Value *Args[] = {createOrdering(&IRB, FI->getOrdering())};
797 FunctionCallee F = FI->getSyncScopeID() == SyncScope::SingleThread
798 ? TsanAtomicSignalFence
799 : TsanAtomicThreadFence;
800 IRB.CreateCall(F, Args);
801 FI->eraseFromParent();
802 }
803 return true;
804}
805
806int ThreadSanitizer::getMemoryAccessFuncIndex(Type *OrigTy, Value *Addr,
807 const DataLayout &DL) {
808 assert(OrigTy->isSized());
809 if (OrigTy->isScalableTy()) {
810 // FIXME: support vscale.
811 return -1;
812 }
813 uint32_t TypeSize = DL.getTypeStoreSizeInBits(OrigTy);
814 if (TypeSize != 8 && TypeSize != 16 &&
815 TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
816 NumAccessesWithBadSize++;
817 // Ignore all unusual sizes.
818 return -1;
819 }
820 size_t Idx = llvm::countr_zero(TypeSize / 8);
822 return Idx;
823}
#define Success
@ HasCalls
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static cl::opt< bool > ClInstrumentAtomics("asan-instrument-atomics", cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden, cl::init(true))
static const size_t kNumberOfAccessSizes
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
#define LLVM_DEBUG(X)
Definition: Debug.h:101
This file defines the DenseMap class.
uint64_t Addr
static cl::opt< bool > ClInstrumentMemIntrinsics("hwasan-instrument-mem-intrinsics", cl::desc("instrument memory intrinsics"), cl::Hidden, cl::init(true))
Hexagon Common GEP
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
This file contains the declarations for metadata subclasses.
Module.h This file contains the declarations for the Module class.
uint64_t IntrinsicInst * II
FunctionAnalysisManager FAM
ModuleAnalysisManager MAM
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallString class.
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:166
This file contains some functions that are useful when dealing with strings.
static void initialize(TargetLibraryInfoImpl &TLI, const Triple &T, ArrayRef< StringLiteral > StandardNames)
Initialize the set of available library functions based on the specified target triple.
static bool shouldInstrumentReadWriteFromAddress(const Module *M, Value *Addr)
static bool isVtableAccess(Instruction *I)
static bool isTsanAtomic(const Instruction *I)
const char kTsanModuleCtorName[]
static cl::opt< bool > ClInstrumentFuncEntryExit("tsan-instrument-func-entry-exit", cl::init(true), cl::desc("Instrument function entry and exit"), cl::Hidden)
static ConstantInt * createOrdering(IRBuilder<> *IRB, AtomicOrdering ord)
static cl::opt< bool > ClInstrumentMemIntrinsics("tsan-instrument-memintrinsics", cl::init(true), cl::desc("Instrument memintrinsics (memset/memcpy/memmove)"), cl::Hidden)
const char kTsanInitName[]
static cl::opt< bool > ClDistinguishVolatile("tsan-distinguish-volatile", cl::init(false), cl::desc("Emit special instrumentation for accesses to volatiles"), cl::Hidden)
static cl::opt< bool > ClCompoundReadBeforeWrite("tsan-compound-read-before-write", cl::init(false), cl::desc("Emit special compound instrumentation for reads-before-writes"), cl::Hidden)
static cl::opt< bool > ClInstrumentAtomics("tsan-instrument-atomics", cl::init(true), cl::desc("Instrument atomics"), cl::Hidden)
static cl::opt< bool > ClHandleCxxExceptions("tsan-handle-cxx-exceptions", cl::init(true), cl::desc("Handle C++ exceptions (insert cleanup blocks for unwinding)"), cl::Hidden)
static cl::opt< bool > ClInstrumentReadBeforeWrite("tsan-instrument-read-before-write", cl::init(false), cl::desc("Do not eliminate read instrumentation for read-before-writes"), cl::Hidden)
static cl::opt< bool > ClInstrumentMemoryAccesses("tsan-instrument-memory-accesses", cl::init(true), cl::desc("Instrument memory accesses"), cl::Hidden)
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:253
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:405
An instruction that atomically checks whether a specified value is in a memory location,...
Definition: Instructions.h:495
an instruction that atomically reads a memory location, combines it with another value,...
Definition: Instructions.h:696
@ Add
*p = old + v
Definition: Instructions.h:712
@ Or
*p = old | v
Definition: Instructions.h:720
@ Sub
*p = old - v
Definition: Instructions.h:714
@ And
*p = old & v
Definition: Instructions.h:716
@ Xor
*p = old ^ v
Definition: Instructions.h:722
@ Nand
*p = ~(old & v)
Definition: Instructions.h:718
AttributeList addFnAttribute(LLVMContext &C, Attribute::AttrKind Kind) const
Add a function attribute to the list.
Definition: Attributes.h:555
This class represents a function call, abstracting a target machine's calling convention.
This is the shared class of boolean and integer constants.
Definition: Constants.h:81
This class represents an Operation in the Expression.
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:63
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:155
iterator end()
Definition: DenseMap.h:84
EscapeEnumerator - This is a little algorithm to find all escape points from a function so that "fina...
An instruction for ordering other memory operations.
Definition: Instructions.h:420
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
Definition: DerivedTypes.h:168
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
Definition: Instructions.h:915
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition: IRBuilder.h:483
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2686
Class to represent integer types.
Definition: DerivedTypes.h:40
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
An instruction for reading from memory.
Definition: Instructions.h:174
Metadata node.
Definition: Metadata.h:1069
This class wraps the llvm.memset and llvm.memset.inline intrinsics.
This class wraps the llvm.memcpy/memmove intrinsics.
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
static PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Definition: Constants.cpp:1852
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:111
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: Analysis.h:114
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:117
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:586
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
An instruction for storing to memory.
Definition: Instructions.h:290
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
AttributeList getAttrList(LLVMContext *C, ArrayRef< unsigned > ArgNos, bool Signed, bool Ret=false, AttributeList AL=AttributeList()) const
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
ObjectFormatType getObjectFormat() const
Get the object format for this triple.
Definition: Triple.h:399
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
static IntegerType * getIntNTy(LLVMContext &C, unsigned N)
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition: Type.h:298
bool isScalableTy() const
Return true if this is a type whose size is a known multiple of vscale.
static IntegerType * getInt32Ty(LLVMContext &C)
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:224
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char IsVolatile[]
Key for Kernel::Arg::Metadata::mIsVolatile.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=std::nullopt)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Definition: Function.cpp:1539
@ SingleThread
Synchronized with respect to signal handlers executing in the same thread.
Definition: LLVMContext.h:54
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=6)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
std::string getInstrProfSectionName(InstrProfSectKind IPSK, Triple::ObjectFormatType OF, bool AddSegmentInfo=true)
Return the name of the profile section corresponding to IPSK.
Definition: InstrProf.cpp:236
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:215
auto reverse(ContainerTy &&C)
Definition: STLExtras.h:419
std::pair< Function *, FunctionCallee > getOrCreateSanitizerCtorAndInitFunctions(Module &M, StringRef CtorName, StringRef InitName, ArrayRef< Type * > InitArgTypes, ArrayRef< Value * > InitArgs, function_ref< void(Function *, FunctionCallee)> FunctionsCreatedCallback, StringRef VersionCheckName=StringRef(), bool Weak=false)
Creates sanitizer constructor function lazily.
std::optional< SyncScope::ID > getAtomicSyncScopeID(const Instruction *I)
A helper function that returns an atomic operation's sync scope; returns std::nullopt if it is not an...
bool PointerMayBeCaptured(const Value *V, bool ReturnCaptures, bool StoreCaptures, unsigned MaxUsesToExplore=0)
PointerMayBeCaptured - Return true if this pointer value may be captured by the enclosing function (w...
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
AtomicOrdering
Atomic ordering for LLVM's memory model.
DWARFExpression::Operation Op
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.
Definition: ModuleUtils.cpp:74
Type * getLoadStoreType(const Value *I)
A helper function that returns the type of a load or store instruction.
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:4103
bool checkIfAlreadyInstrumented(Module &M, StringRef Flag)
Check if module has flag attached, if not add the flag.
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
uint64_t value() const
This is a hole in the type system and should not be abused.
Definition: Alignment.h:85
static void ensureDebugInfo(IRBuilder<> &IRB, const Function &F)
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
PreservedAnalyses run(Function &F, FunctionAnalysisManager &FAM)