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/ADT/SmallString.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/Intrinsics.h"
28 #include "llvm/Function.h"
29 #include "llvm/Module.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/IRBuilder.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Target/TargetData.h"
34 #include "llvm/Transforms/Instrumentation.h"
35 #include "llvm/Transforms/Utils/ModuleUtils.h"
36 #include "llvm/Type.h"
41 /// ThreadSanitizer: instrument the code in module to find races.
42 struct ThreadSanitizer : public FunctionPass {
44 bool runOnFunction(Function &F);
45 bool doInitialization(Module &M);
46 bool instrumentLoadOrStore(Instruction *I);
47 static char ID; // Pass identification, replacement for typeid.
51 // Callbacks to run-time library are computed in doInitialization.
54 // Accesses sizes are powers of two: 1, 2, 4, 8, 16.
55 static const size_t kNumberOfAccessSizes = 5;
56 Value *TsanRead[kNumberOfAccessSizes];
57 Value *TsanWrite[kNumberOfAccessSizes];
61 char ThreadSanitizer::ID = 0;
62 INITIALIZE_PASS(ThreadSanitizer, "tsan",
63 "ThreadSanitizer: detects data races.",
66 ThreadSanitizer::ThreadSanitizer()
71 FunctionPass *llvm::createThreadSanitizerPass() {
72 return new ThreadSanitizer();
75 bool ThreadSanitizer::doInitialization(Module &M) {
76 TD = getAnalysisIfAvailable<TargetData>();
79 // Always insert a call to __tsan_init into the module's CTORs.
80 IRBuilder<> IRB(M.getContext());
81 Value *TsanInit = M.getOrInsertFunction("__tsan_init",
82 IRB.getVoidTy(), NULL);
83 appendToGlobalCtors(M, cast<Function>(TsanInit), 0);
85 // Initialize the callbacks.
86 TsanFuncEntry = M.getOrInsertFunction("__tsan_func_entry", IRB.getVoidTy(),
87 IRB.getInt8PtrTy(), NULL);
88 TsanFuncExit = M.getOrInsertFunction("__tsan_func_exit", IRB.getVoidTy(),
90 for (size_t i = 0; i < kNumberOfAccessSizes; ++i) {
91 SmallString<32> ReadName("__tsan_read");
92 ReadName += itostr(1 << i);
93 TsanRead[i] = M.getOrInsertFunction(ReadName, IRB.getVoidTy(),
94 IRB.getInt8PtrTy(), NULL);
95 SmallString<32> WriteName("__tsan_write");
96 WriteName += itostr(1 << i);
97 TsanWrite[i] = M.getOrInsertFunction(WriteName, IRB.getVoidTy(),
98 IRB.getInt8PtrTy(), NULL);
103 bool ThreadSanitizer::runOnFunction(Function &F) {
104 if (!TD) return false;
105 SmallVector<Instruction*, 8> RetVec;
106 SmallVector<Instruction*, 8> LoadsAndStores;
108 bool HasCalls = false;
110 // Traverse all instructions, collect loads/stores/returns, check for calls.
111 for (Function::iterator FI = F.begin(), FE = F.end();
113 BasicBlock &BB = *FI;
114 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end();
116 if (isa<LoadInst>(BI) || isa<StoreInst>(BI))
117 LoadsAndStores.push_back(BI);
118 else if (isa<ReturnInst>(BI))
119 RetVec.push_back(BI);
120 else if (isa<CallInst>(BI) || isa<InvokeInst>(BI))
125 // We have collected all loads and stores.
126 // FIXME: many of these accesses do not need to be checked for races
127 // (e.g. variables that do not escape, etc).
129 // Instrument memory accesses.
130 for (size_t i = 0, n = LoadsAndStores.size(); i < n; ++i) {
131 Res |= instrumentLoadOrStore(LoadsAndStores[i]);
134 // Instrument function entry/exit points if there were instrumented accesses.
135 if (Res || HasCalls) {
136 IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
137 Value *ReturnAddress = IRB.CreateCall(
138 Intrinsic::getDeclaration(F.getParent(), Intrinsic::returnaddress),
140 IRB.CreateCall(TsanFuncEntry, ReturnAddress);
141 for (size_t i = 0, n = RetVec.size(); i < n; ++i) {
142 IRBuilder<> IRBRet(RetVec[i]);
143 IRBRet.CreateCall(TsanFuncExit);
149 bool ThreadSanitizer::instrumentLoadOrStore(Instruction *I) {
151 bool IsWrite = isa<StoreInst>(*I);
152 Value *Addr = IsWrite
153 ? cast<StoreInst>(I)->getPointerOperand()
154 : cast<LoadInst>(I)->getPointerOperand();
155 Type *OrigPtrTy = Addr->getType();
156 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
157 assert(OrigTy->isSized());
158 uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
159 if (TypeSize != 8 && TypeSize != 16 &&
160 TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
161 // Ignore all unusual sizes.
164 size_t Idx = CountTrailingZeros_32(TypeSize / 8);
165 assert(Idx < kNumberOfAccessSizes);
166 Value *OnAccessFunc = IsWrite ? TsanWrite[Idx] : TsanRead[Idx];
167 IRB.CreateCall(OnAccessFunc, IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()));