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