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 "FunctionBlackList.h"
25 #include "llvm/ADT/SmallString.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/Intrinsics.h"
29 #include "llvm/Function.h"
30 #include "llvm/Module.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/IRBuilder.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Target/TargetData.h"
36 #include "llvm/Transforms/Instrumentation.h"
37 #include "llvm/Transforms/Utils/ModuleUtils.h"
38 #include "llvm/Type.h"
42 static cl::opt<std::string> ClBlackListFile("tsan-blacklist",
43 cl::desc("Blacklist file"), cl::Hidden);
46 /// ThreadSanitizer: instrument the code in module to find races.
47 struct ThreadSanitizer : public FunctionPass {
49 bool runOnFunction(Function &F);
50 bool doInitialization(Module &M);
51 bool instrumentLoadOrStore(Instruction *I);
52 static char ID; // Pass identification, replacement for typeid.
56 OwningPtr<FunctionBlackList> BL;
57 // Callbacks to run-time library are computed in doInitialization.
60 // Accesses sizes are powers of two: 1, 2, 4, 8, 16.
61 static const size_t kNumberOfAccessSizes = 5;
62 Value *TsanRead[kNumberOfAccessSizes];
63 Value *TsanWrite[kNumberOfAccessSizes];
67 char ThreadSanitizer::ID = 0;
68 INITIALIZE_PASS(ThreadSanitizer, "tsan",
69 "ThreadSanitizer: detects data races.",
72 ThreadSanitizer::ThreadSanitizer()
77 FunctionPass *llvm::createThreadSanitizerPass() {
78 return new ThreadSanitizer();
81 bool ThreadSanitizer::doInitialization(Module &M) {
82 TD = getAnalysisIfAvailable<TargetData>();
85 BL.reset(new FunctionBlackList(ClBlackListFile));
87 // Always insert a call to __tsan_init into the module's CTORs.
88 IRBuilder<> IRB(M.getContext());
89 Value *TsanInit = M.getOrInsertFunction("__tsan_init",
90 IRB.getVoidTy(), NULL);
91 appendToGlobalCtors(M, cast<Function>(TsanInit), 0);
93 // Initialize the callbacks.
94 TsanFuncEntry = M.getOrInsertFunction("__tsan_func_entry", IRB.getVoidTy(),
95 IRB.getInt8PtrTy(), NULL);
96 TsanFuncExit = M.getOrInsertFunction("__tsan_func_exit", IRB.getVoidTy(),
98 for (size_t i = 0; i < kNumberOfAccessSizes; ++i) {
99 SmallString<32> ReadName("__tsan_read");
100 ReadName += itostr(1 << i);
101 TsanRead[i] = M.getOrInsertFunction(ReadName, IRB.getVoidTy(),
102 IRB.getInt8PtrTy(), NULL);
103 SmallString<32> WriteName("__tsan_write");
104 WriteName += itostr(1 << i);
105 TsanWrite[i] = M.getOrInsertFunction(WriteName, IRB.getVoidTy(),
106 IRB.getInt8PtrTy(), NULL);
111 bool ThreadSanitizer::runOnFunction(Function &F) {
112 if (!TD) return false;
113 if (BL->isIn(F)) return false;
114 SmallVector<Instruction*, 8> RetVec;
115 SmallVector<Instruction*, 8> LoadsAndStores;
117 bool HasCalls = false;
119 // Traverse all instructions, collect loads/stores/returns, check for calls.
120 for (Function::iterator FI = F.begin(), FE = F.end();
122 BasicBlock &BB = *FI;
123 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end();
125 if (isa<LoadInst>(BI) || isa<StoreInst>(BI))
126 LoadsAndStores.push_back(BI);
127 else if (isa<ReturnInst>(BI))
128 RetVec.push_back(BI);
129 else if (isa<CallInst>(BI) || isa<InvokeInst>(BI))
134 // We have collected all loads and stores.
135 // FIXME: many of these accesses do not need to be checked for races
136 // (e.g. variables that do not escape, etc).
138 // Instrument memory accesses.
139 for (size_t i = 0, n = LoadsAndStores.size(); i < n; ++i) {
140 Res |= instrumentLoadOrStore(LoadsAndStores[i]);
143 // Instrument function entry/exit points if there were instrumented accesses.
144 if (Res || HasCalls) {
145 IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
146 Value *ReturnAddress = IRB.CreateCall(
147 Intrinsic::getDeclaration(F.getParent(), Intrinsic::returnaddress),
149 IRB.CreateCall(TsanFuncEntry, ReturnAddress);
150 for (size_t i = 0, n = RetVec.size(); i < n; ++i) {
151 IRBuilder<> IRBRet(RetVec[i]);
152 IRBRet.CreateCall(TsanFuncExit);
158 bool ThreadSanitizer::instrumentLoadOrStore(Instruction *I) {
160 bool IsWrite = isa<StoreInst>(*I);
161 Value *Addr = IsWrite
162 ? cast<StoreInst>(I)->getPointerOperand()
163 : cast<LoadInst>(I)->getPointerOperand();
164 Type *OrigPtrTy = Addr->getType();
165 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
166 assert(OrigTy->isSized());
167 uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
168 if (TypeSize != 8 && TypeSize != 16 &&
169 TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
170 // Ignore all unusual sizes.
173 size_t Idx = CountTrailingZeros_32(TypeSize / 8);
174 assert(Idx < kNumberOfAccessSizes);
175 Value *OnAccessFunc = IsWrite ? TsanWrite[Idx] : TsanRead[Idx];
176 IRB.CreateCall(OnAccessFunc, IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()));