1 //===-- ThreadSanitizer.cpp - race detector -------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file is a part of ThreadSanitizer, a race detector.
12 // The tool is under development, for the details about previous versions see
13 // http://code.google.com/p/data-race-test
15 // The instrumentation phase is quite simple:
16 // - Insert calls to run-time library before every memory access.
17 // - Optimizations may apply to avoid instrumenting some of the accesses.
18 // - Insert calls at function entry/exit.
19 // The rest is handled by the run-time library.
20 //===----------------------------------------------------------------------===//
22 #define DEBUG_TYPE "tsan"
24 #include "llvm/Transforms/Instrumentation.h"
25 #include "llvm/ADT/SmallSet.h"
26 #include "llvm/ADT/SmallString.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/IRBuilder.h"
33 #include "llvm/IR/Intrinsics.h"
34 #include "llvm/IR/LLVMContext.h"
35 #include "llvm/IR/Metadata.h"
36 #include "llvm/IR/Module.h"
37 #include "llvm/IR/Type.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/MathExtras.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
43 #include "llvm/Transforms/Utils/BlackList.h"
44 #include "llvm/Transforms/Utils/ModuleUtils.h"
48 static cl::opt<std::string> ClBlacklistFile("tsan-blacklist",
49 cl::desc("Blacklist file"), cl::Hidden);
50 static cl::opt<bool> ClInstrumentMemoryAccesses(
51 "tsan-instrument-memory-accesses", cl::init(true),
52 cl::desc("Instrument memory accesses"), cl::Hidden);
53 static cl::opt<bool> ClInstrumentFuncEntryExit(
54 "tsan-instrument-func-entry-exit", cl::init(true),
55 cl::desc("Instrument function entry and exit"), cl::Hidden);
56 static cl::opt<bool> ClInstrumentAtomics(
57 "tsan-instrument-atomics", cl::init(true),
58 cl::desc("Instrument atomics"), cl::Hidden);
60 STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
61 STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
62 STATISTIC(NumOmittedReadsBeforeWrite,
63 "Number of reads ignored due to following writes");
64 STATISTIC(NumAccessesWithBadSize, "Number of accesses with bad size");
65 STATISTIC(NumInstrumentedVtableWrites, "Number of vtable ptr writes");
66 STATISTIC(NumInstrumentedVtableReads, "Number of vtable ptr reads");
67 STATISTIC(NumOmittedReadsFromConstantGlobals,
68 "Number of reads from constant globals");
69 STATISTIC(NumOmittedReadsFromVtable, "Number of vtable reads");
73 /// ThreadSanitizer: instrument the code in module to find races.
74 struct ThreadSanitizer : public FunctionPass {
75 ThreadSanitizer(StringRef BlacklistFile = StringRef())
78 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
80 const char *getPassName() const;
81 bool runOnFunction(Function &F);
82 bool doInitialization(Module &M);
83 static char ID; // Pass identification, replacement for typeid.
86 void initializeCallbacks(Module &M);
87 bool instrumentLoadOrStore(Instruction *I);
88 bool instrumentAtomic(Instruction *I);
89 void chooseInstructionsToInstrument(SmallVectorImpl<Instruction*> &Local,
90 SmallVectorImpl<Instruction*> &All);
91 bool addrPointsToConstantData(Value *Addr);
92 int getMemoryAccessFuncIndex(Value *Addr);
95 SmallString<64> BlacklistFile;
96 OwningPtr<BlackList> BL;
98 // Callbacks to run-time library are computed in doInitialization.
99 Function *TsanFuncEntry;
100 Function *TsanFuncExit;
101 // Accesses sizes are powers of two: 1, 2, 4, 8, 16.
102 static const size_t kNumberOfAccessSizes = 5;
103 Function *TsanRead[kNumberOfAccessSizes];
104 Function *TsanWrite[kNumberOfAccessSizes];
105 Function *TsanAtomicLoad[kNumberOfAccessSizes];
106 Function *TsanAtomicStore[kNumberOfAccessSizes];
107 Function *TsanAtomicRMW[AtomicRMWInst::LAST_BINOP + 1][kNumberOfAccessSizes];
108 Function *TsanAtomicCAS[kNumberOfAccessSizes];
109 Function *TsanAtomicThreadFence;
110 Function *TsanAtomicSignalFence;
111 Function *TsanVptrUpdate;
112 Function *TsanVptrLoad;
116 char ThreadSanitizer::ID = 0;
117 INITIALIZE_PASS(ThreadSanitizer, "tsan",
118 "ThreadSanitizer: detects data races.",
121 const char *ThreadSanitizer::getPassName() const {
122 return "ThreadSanitizer";
125 FunctionPass *llvm::createThreadSanitizerPass(StringRef BlacklistFile) {
126 return new ThreadSanitizer(BlacklistFile);
129 static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
130 if (Function *F = dyn_cast<Function>(FuncOrBitcast))
132 FuncOrBitcast->dump();
133 report_fatal_error("ThreadSanitizer interface function redefined");
136 void ThreadSanitizer::initializeCallbacks(Module &M) {
137 IRBuilder<> IRB(M.getContext());
138 // Initialize the callbacks.
139 TsanFuncEntry = checkInterfaceFunction(M.getOrInsertFunction(
140 "__tsan_func_entry", IRB.getVoidTy(), IRB.getInt8PtrTy(), NULL));
141 TsanFuncExit = checkInterfaceFunction(M.getOrInsertFunction(
142 "__tsan_func_exit", IRB.getVoidTy(), NULL));
143 OrdTy = IRB.getInt32Ty();
144 for (size_t i = 0; i < kNumberOfAccessSizes; ++i) {
145 const size_t ByteSize = 1 << i;
146 const size_t BitSize = ByteSize * 8;
147 SmallString<32> ReadName("__tsan_read" + itostr(ByteSize));
148 TsanRead[i] = checkInterfaceFunction(M.getOrInsertFunction(
149 ReadName, IRB.getVoidTy(), IRB.getInt8PtrTy(), NULL));
151 SmallString<32> WriteName("__tsan_write" + itostr(ByteSize));
152 TsanWrite[i] = checkInterfaceFunction(M.getOrInsertFunction(
153 WriteName, IRB.getVoidTy(), IRB.getInt8PtrTy(), NULL));
155 Type *Ty = Type::getIntNTy(M.getContext(), BitSize);
156 Type *PtrTy = Ty->getPointerTo();
157 SmallString<32> AtomicLoadName("__tsan_atomic" + itostr(BitSize) +
159 TsanAtomicLoad[i] = checkInterfaceFunction(M.getOrInsertFunction(
160 AtomicLoadName, Ty, PtrTy, OrdTy, NULL));
162 SmallString<32> AtomicStoreName("__tsan_atomic" + itostr(BitSize) +
164 TsanAtomicStore[i] = checkInterfaceFunction(M.getOrInsertFunction(
165 AtomicStoreName, IRB.getVoidTy(), PtrTy, Ty, OrdTy,
168 for (int op = AtomicRMWInst::FIRST_BINOP;
169 op <= AtomicRMWInst::LAST_BINOP; ++op) {
170 TsanAtomicRMW[op][i] = NULL;
171 const char *NamePart = NULL;
172 if (op == AtomicRMWInst::Xchg)
173 NamePart = "_exchange";
174 else if (op == AtomicRMWInst::Add)
175 NamePart = "_fetch_add";
176 else if (op == AtomicRMWInst::Sub)
177 NamePart = "_fetch_sub";
178 else if (op == AtomicRMWInst::And)
179 NamePart = "_fetch_and";
180 else if (op == AtomicRMWInst::Or)
181 NamePart = "_fetch_or";
182 else if (op == AtomicRMWInst::Xor)
183 NamePart = "_fetch_xor";
184 else if (op == AtomicRMWInst::Nand)
185 NamePart = "_fetch_nand";
188 SmallString<32> RMWName("__tsan_atomic" + itostr(BitSize) + NamePart);
189 TsanAtomicRMW[op][i] = checkInterfaceFunction(M.getOrInsertFunction(
190 RMWName, Ty, PtrTy, Ty, OrdTy, NULL));
193 SmallString<32> AtomicCASName("__tsan_atomic" + itostr(BitSize) +
194 "_compare_exchange_val");
195 TsanAtomicCAS[i] = checkInterfaceFunction(M.getOrInsertFunction(
196 AtomicCASName, Ty, PtrTy, Ty, Ty, OrdTy, OrdTy, NULL));
198 TsanVptrUpdate = checkInterfaceFunction(M.getOrInsertFunction(
199 "__tsan_vptr_update", IRB.getVoidTy(), IRB.getInt8PtrTy(),
200 IRB.getInt8PtrTy(), NULL));
201 TsanVptrLoad = checkInterfaceFunction(M.getOrInsertFunction(
202 "__tsan_vptr_read", IRB.getVoidTy(), IRB.getInt8PtrTy(), NULL));
203 TsanAtomicThreadFence = checkInterfaceFunction(M.getOrInsertFunction(
204 "__tsan_atomic_thread_fence", IRB.getVoidTy(), OrdTy, NULL));
205 TsanAtomicSignalFence = checkInterfaceFunction(M.getOrInsertFunction(
206 "__tsan_atomic_signal_fence", IRB.getVoidTy(), OrdTy, NULL));
209 bool ThreadSanitizer::doInitialization(Module &M) {
210 TD = getAnalysisIfAvailable<DataLayout>();
213 BL.reset(new BlackList(BlacklistFile));
215 // Always insert a call to __tsan_init into the module's CTORs.
216 IRBuilder<> IRB(M.getContext());
217 Value *TsanInit = M.getOrInsertFunction("__tsan_init",
218 IRB.getVoidTy(), NULL);
219 appendToGlobalCtors(M, cast<Function>(TsanInit), 0);
224 static bool isVtableAccess(Instruction *I) {
225 if (MDNode *Tag = I->getMetadata(LLVMContext::MD_tbaa)) {
226 if (Tag->getNumOperands() < 1) return false;
227 if (MDString *Tag1 = dyn_cast<MDString>(Tag->getOperand(0))) {
228 if (Tag1->getString() == "vtable pointer") return true;
234 bool ThreadSanitizer::addrPointsToConstantData(Value *Addr) {
235 // If this is a GEP, just analyze its pointer operand.
236 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Addr))
237 Addr = GEP->getPointerOperand();
239 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
240 if (GV->isConstant()) {
241 // Reads from constant globals can not race with any writes.
242 NumOmittedReadsFromConstantGlobals++;
245 } else if (LoadInst *L = dyn_cast<LoadInst>(Addr)) {
246 if (isVtableAccess(L)) {
247 // Reads from a vtable pointer can not race with any writes.
248 NumOmittedReadsFromVtable++;
255 // Instrumenting some of the accesses may be proven redundant.
256 // Currently handled:
257 // - read-before-write (within same BB, no calls between)
259 // We do not handle some of the patterns that should not survive
260 // after the classic compiler optimizations.
261 // E.g. two reads from the same temp should be eliminated by CSE,
262 // two writes should be eliminated by DSE, etc.
264 // 'Local' is a vector of insns within the same BB (no calls between).
265 // 'All' is a vector of insns that will be instrumented.
266 void ThreadSanitizer::chooseInstructionsToInstrument(
267 SmallVectorImpl<Instruction*> &Local,
268 SmallVectorImpl<Instruction*> &All) {
269 SmallSet<Value*, 8> WriteTargets;
270 // Iterate from the end.
271 for (SmallVectorImpl<Instruction*>::reverse_iterator It = Local.rbegin(),
272 E = Local.rend(); It != E; ++It) {
273 Instruction *I = *It;
274 if (StoreInst *Store = dyn_cast<StoreInst>(I)) {
275 WriteTargets.insert(Store->getPointerOperand());
277 LoadInst *Load = cast<LoadInst>(I);
278 Value *Addr = Load->getPointerOperand();
279 if (WriteTargets.count(Addr)) {
280 // We will write to this temp, so no reason to analyze the read.
281 NumOmittedReadsBeforeWrite++;
284 if (addrPointsToConstantData(Addr)) {
285 // Addr points to some constant data -- it can not race with any writes.
294 static bool isAtomic(Instruction *I) {
295 if (LoadInst *LI = dyn_cast<LoadInst>(I))
296 return LI->isAtomic() && LI->getSynchScope() == CrossThread;
297 if (StoreInst *SI = dyn_cast<StoreInst>(I))
298 return SI->isAtomic() && SI->getSynchScope() == CrossThread;
299 if (isa<AtomicRMWInst>(I))
301 if (isa<AtomicCmpXchgInst>(I))
303 if (isa<FenceInst>(I))
308 bool ThreadSanitizer::runOnFunction(Function &F) {
309 if (!TD) return false;
310 if (BL->isIn(F)) return false;
311 initializeCallbacks(*F.getParent());
312 SmallVector<Instruction*, 8> RetVec;
313 SmallVector<Instruction*, 8> AllLoadsAndStores;
314 SmallVector<Instruction*, 8> LocalLoadsAndStores;
315 SmallVector<Instruction*, 8> AtomicAccesses;
317 bool HasCalls = false;
319 // Traverse all instructions, collect loads/stores/returns, check for calls.
320 for (Function::iterator FI = F.begin(), FE = F.end();
322 BasicBlock &BB = *FI;
323 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end();
326 AtomicAccesses.push_back(BI);
327 else if (isa<LoadInst>(BI) || isa<StoreInst>(BI))
328 LocalLoadsAndStores.push_back(BI);
329 else if (isa<ReturnInst>(BI))
330 RetVec.push_back(BI);
331 else if (isa<CallInst>(BI) || isa<InvokeInst>(BI)) {
333 chooseInstructionsToInstrument(LocalLoadsAndStores, AllLoadsAndStores);
336 chooseInstructionsToInstrument(LocalLoadsAndStores, AllLoadsAndStores);
339 // We have collected all loads and stores.
340 // FIXME: many of these accesses do not need to be checked for races
341 // (e.g. variables that do not escape, etc).
343 // Instrument memory accesses.
344 if (ClInstrumentMemoryAccesses)
345 for (size_t i = 0, n = AllLoadsAndStores.size(); i < n; ++i) {
346 Res |= instrumentLoadOrStore(AllLoadsAndStores[i]);
349 // Instrument atomic memory accesses.
350 if (ClInstrumentAtomics)
351 for (size_t i = 0, n = AtomicAccesses.size(); i < n; ++i) {
352 Res |= instrumentAtomic(AtomicAccesses[i]);
355 // Instrument function entry/exit points if there were instrumented accesses.
356 if ((Res || HasCalls) && ClInstrumentFuncEntryExit) {
357 IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
358 Value *ReturnAddress = IRB.CreateCall(
359 Intrinsic::getDeclaration(F.getParent(), Intrinsic::returnaddress),
361 IRB.CreateCall(TsanFuncEntry, ReturnAddress);
362 for (size_t i = 0, n = RetVec.size(); i < n; ++i) {
363 IRBuilder<> IRBRet(RetVec[i]);
364 IRBRet.CreateCall(TsanFuncExit);
371 bool ThreadSanitizer::instrumentLoadOrStore(Instruction *I) {
373 bool IsWrite = isa<StoreInst>(*I);
374 Value *Addr = IsWrite
375 ? cast<StoreInst>(I)->getPointerOperand()
376 : cast<LoadInst>(I)->getPointerOperand();
377 int Idx = getMemoryAccessFuncIndex(Addr);
380 if (IsWrite && isVtableAccess(I)) {
381 DEBUG(dbgs() << " VPTR : " << *I << "\n");
382 Value *StoredValue = cast<StoreInst>(I)->getValueOperand();
383 // StoredValue does not necessary have a pointer type.
384 if (isa<IntegerType>(StoredValue->getType()))
385 StoredValue = IRB.CreateIntToPtr(StoredValue, IRB.getInt8PtrTy());
386 // Call TsanVptrUpdate.
387 IRB.CreateCall2(TsanVptrUpdate,
388 IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()),
389 IRB.CreatePointerCast(StoredValue, IRB.getInt8PtrTy()));
390 NumInstrumentedVtableWrites++;
393 if (!IsWrite && isVtableAccess(I)) {
394 IRB.CreateCall(TsanVptrLoad,
395 IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()));
396 NumInstrumentedVtableReads++;
399 Value *OnAccessFunc = IsWrite ? TsanWrite[Idx] : TsanRead[Idx];
400 IRB.CreateCall(OnAccessFunc, IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()));
401 if (IsWrite) NumInstrumentedWrites++;
402 else NumInstrumentedReads++;
406 static ConstantInt *createOrdering(IRBuilder<> *IRB, AtomicOrdering ord) {
409 case NotAtomic: assert(false);
410 case Unordered: // Fall-through.
411 case Monotonic: v = 0; break;
412 // case Consume: v = 1; break; // Not specified yet.
413 case Acquire: v = 2; break;
414 case Release: v = 3; break;
415 case AcquireRelease: v = 4; break;
416 case SequentiallyConsistent: v = 5; break;
418 return IRB->getInt32(v);
421 static ConstantInt *createFailOrdering(IRBuilder<> *IRB, AtomicOrdering ord) {
424 case NotAtomic: assert(false);
425 case Unordered: // Fall-through.
426 case Monotonic: v = 0; break;
427 // case Consume: v = 1; break; // Not specified yet.
428 case Acquire: v = 2; break;
429 case Release: v = 0; break;
430 case AcquireRelease: v = 2; break;
431 case SequentiallyConsistent: v = 5; break;
433 return IRB->getInt32(v);
436 // Both llvm and ThreadSanitizer atomic operations are based on C++11/C1x
437 // standards. For background see C++11 standard. A slightly older, publically
438 // available draft of the standard (not entirely up-to-date, but close enough
439 // for casual browsing) is available here:
440 // http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2011/n3242.pdf
441 // The following page contains more background information:
442 // http://www.hpl.hp.com/personal/Hans_Boehm/c++mm/
444 bool ThreadSanitizer::instrumentAtomic(Instruction *I) {
446 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
447 Value *Addr = LI->getPointerOperand();
448 int Idx = getMemoryAccessFuncIndex(Addr);
451 const size_t ByteSize = 1 << Idx;
452 const size_t BitSize = ByteSize * 8;
453 Type *Ty = Type::getIntNTy(IRB.getContext(), BitSize);
454 Type *PtrTy = Ty->getPointerTo();
455 Value *Args[] = {IRB.CreatePointerCast(Addr, PtrTy),
456 createOrdering(&IRB, LI->getOrdering())};
457 CallInst *C = CallInst::Create(TsanAtomicLoad[Idx],
458 ArrayRef<Value*>(Args));
459 ReplaceInstWithInst(I, C);
461 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
462 Value *Addr = SI->getPointerOperand();
463 int Idx = getMemoryAccessFuncIndex(Addr);
466 const size_t ByteSize = 1 << Idx;
467 const size_t BitSize = ByteSize * 8;
468 Type *Ty = Type::getIntNTy(IRB.getContext(), BitSize);
469 Type *PtrTy = Ty->getPointerTo();
470 Value *Args[] = {IRB.CreatePointerCast(Addr, PtrTy),
471 IRB.CreateIntCast(SI->getValueOperand(), Ty, false),
472 createOrdering(&IRB, SI->getOrdering())};
473 CallInst *C = CallInst::Create(TsanAtomicStore[Idx],
474 ArrayRef<Value*>(Args));
475 ReplaceInstWithInst(I, C);
476 } else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I)) {
477 Value *Addr = RMWI->getPointerOperand();
478 int Idx = getMemoryAccessFuncIndex(Addr);
481 Function *F = TsanAtomicRMW[RMWI->getOperation()][Idx];
484 const size_t ByteSize = 1 << Idx;
485 const size_t BitSize = ByteSize * 8;
486 Type *Ty = Type::getIntNTy(IRB.getContext(), BitSize);
487 Type *PtrTy = Ty->getPointerTo();
488 Value *Args[] = {IRB.CreatePointerCast(Addr, PtrTy),
489 IRB.CreateIntCast(RMWI->getValOperand(), Ty, false),
490 createOrdering(&IRB, RMWI->getOrdering())};
491 CallInst *C = CallInst::Create(F, ArrayRef<Value*>(Args));
492 ReplaceInstWithInst(I, C);
493 } else if (AtomicCmpXchgInst *CASI = dyn_cast<AtomicCmpXchgInst>(I)) {
494 Value *Addr = CASI->getPointerOperand();
495 int Idx = getMemoryAccessFuncIndex(Addr);
498 const size_t ByteSize = 1 << Idx;
499 const size_t BitSize = ByteSize * 8;
500 Type *Ty = Type::getIntNTy(IRB.getContext(), BitSize);
501 Type *PtrTy = Ty->getPointerTo();
502 Value *Args[] = {IRB.CreatePointerCast(Addr, PtrTy),
503 IRB.CreateIntCast(CASI->getCompareOperand(), Ty, false),
504 IRB.CreateIntCast(CASI->getNewValOperand(), Ty, false),
505 createOrdering(&IRB, CASI->getOrdering()),
506 createFailOrdering(&IRB, CASI->getOrdering())};
507 CallInst *C = CallInst::Create(TsanAtomicCAS[Idx], ArrayRef<Value*>(Args));
508 ReplaceInstWithInst(I, C);
509 } else if (FenceInst *FI = dyn_cast<FenceInst>(I)) {
510 Value *Args[] = {createOrdering(&IRB, FI->getOrdering())};
511 Function *F = FI->getSynchScope() == SingleThread ?
512 TsanAtomicSignalFence : TsanAtomicThreadFence;
513 CallInst *C = CallInst::Create(F, ArrayRef<Value*>(Args));
514 ReplaceInstWithInst(I, C);
519 int ThreadSanitizer::getMemoryAccessFuncIndex(Value *Addr) {
520 Type *OrigPtrTy = Addr->getType();
521 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
522 assert(OrigTy->isSized());
523 uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
524 if (TypeSize != 8 && TypeSize != 16 &&
525 TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
526 NumAccessesWithBadSize++;
527 // Ignore all unusual sizes.
530 size_t Idx = CountTrailingZeros_32(TypeSize / 8);
531 assert(Idx < kNumberOfAccessSizes);