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