blob: b774211a8541f8348299db48399998681578eed0 [file] [log] [blame]
Kostya Serebryany60ebb1942012-02-13 22:50:51 +00001//===-- ThreadSanitizer.cpp - race detector -------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file is a part of ThreadSanitizer, a race detector.
11//
12// The tool is under development, for the details about previous versions see
13// http://code.google.com/p/data-race-test
14//
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//===----------------------------------------------------------------------===//
21
22#define DEBUG_TYPE "tsan"
23
Kostya Serebryany6e590e32012-03-14 23:33:24 +000024#include "FunctionBlackList.h"
Kostya Serebryany60ebb1942012-02-13 22:50:51 +000025#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"
Kostya Serebryany52eb69922012-03-26 17:35:03 +000030#include "llvm/LLVMContext.h"
31#include "llvm/Metadata.h"
Kostya Serebryany60ebb1942012-02-13 22:50:51 +000032#include "llvm/Module.h"
Kostya Serebryany6e590e32012-03-14 23:33:24 +000033#include "llvm/Support/CommandLine.h"
Kostya Serebryany60ebb1942012-02-13 22:50:51 +000034#include "llvm/Support/Debug.h"
35#include "llvm/Support/IRBuilder.h"
36#include "llvm/Support/MathExtras.h"
Kostya Serebryany52eb69922012-03-26 17:35:03 +000037#include "llvm/Support/raw_ostream.h"
Kostya Serebryany60ebb1942012-02-13 22:50:51 +000038#include "llvm/Target/TargetData.h"
39#include "llvm/Transforms/Instrumentation.h"
40#include "llvm/Transforms/Utils/ModuleUtils.h"
41#include "llvm/Type.h"
42
43using namespace llvm;
44
Kostya Serebryany6e590e32012-03-14 23:33:24 +000045static cl::opt<std::string> ClBlackListFile("tsan-blacklist",
46 cl::desc("Blacklist file"), cl::Hidden);
47
Kostya Serebryany60ebb1942012-02-13 22:50:51 +000048namespace {
49/// ThreadSanitizer: instrument the code in module to find races.
50struct ThreadSanitizer : public FunctionPass {
51 ThreadSanitizer();
52 bool runOnFunction(Function &F);
53 bool doInitialization(Module &M);
54 bool instrumentLoadOrStore(Instruction *I);
55 static char ID; // Pass identification, replacement for typeid.
56
57 private:
58 TargetData *TD;
Kostya Serebryany6e590e32012-03-14 23:33:24 +000059 OwningPtr<FunctionBlackList> BL;
Kostya Serebryany60ebb1942012-02-13 22:50:51 +000060 // Callbacks to run-time library are computed in doInitialization.
61 Value *TsanFuncEntry;
62 Value *TsanFuncExit;
63 // Accesses sizes are powers of two: 1, 2, 4, 8, 16.
Kostya Serebryany3eccaa62012-02-14 00:52:07 +000064 static const size_t kNumberOfAccessSizes = 5;
Kostya Serebryany60ebb1942012-02-13 22:50:51 +000065 Value *TsanRead[kNumberOfAccessSizes];
66 Value *TsanWrite[kNumberOfAccessSizes];
Kostya Serebryany52eb69922012-03-26 17:35:03 +000067 Value *TsanVptrUpdate;
Kostya Serebryany60ebb1942012-02-13 22:50:51 +000068};
69} // namespace
70
71char ThreadSanitizer::ID = 0;
72INITIALIZE_PASS(ThreadSanitizer, "tsan",
73 "ThreadSanitizer: detects data races.",
74 false, false)
75
76ThreadSanitizer::ThreadSanitizer()
77 : FunctionPass(ID),
78 TD(NULL) {
79}
80
81FunctionPass *llvm::createThreadSanitizerPass() {
82 return new ThreadSanitizer();
83}
84
85bool ThreadSanitizer::doInitialization(Module &M) {
86 TD = getAnalysisIfAvailable<TargetData>();
87 if (!TD)
88 return false;
Kostya Serebryany6e590e32012-03-14 23:33:24 +000089 BL.reset(new FunctionBlackList(ClBlackListFile));
90
Kostya Serebryany60ebb1942012-02-13 22:50:51 +000091 // Always insert a call to __tsan_init into the module's CTORs.
92 IRBuilder<> IRB(M.getContext());
93 Value *TsanInit = M.getOrInsertFunction("__tsan_init",
94 IRB.getVoidTy(), NULL);
95 appendToGlobalCtors(M, cast<Function>(TsanInit), 0);
96
97 // Initialize the callbacks.
98 TsanFuncEntry = M.getOrInsertFunction("__tsan_func_entry", IRB.getVoidTy(),
99 IRB.getInt8PtrTy(), NULL);
100 TsanFuncExit = M.getOrInsertFunction("__tsan_func_exit", IRB.getVoidTy(),
101 NULL);
Kostya Serebryany3eccaa62012-02-14 00:52:07 +0000102 for (size_t i = 0; i < kNumberOfAccessSizes; ++i) {
Kostya Serebryany60ebb1942012-02-13 22:50:51 +0000103 SmallString<32> ReadName("__tsan_read");
104 ReadName += itostr(1 << i);
105 TsanRead[i] = M.getOrInsertFunction(ReadName, IRB.getVoidTy(),
106 IRB.getInt8PtrTy(), NULL);
107 SmallString<32> WriteName("__tsan_write");
108 WriteName += itostr(1 << i);
109 TsanWrite[i] = M.getOrInsertFunction(WriteName, IRB.getVoidTy(),
110 IRB.getInt8PtrTy(), NULL);
111 }
Kostya Serebryany52eb69922012-03-26 17:35:03 +0000112 TsanVptrUpdate = M.getOrInsertFunction("__tsan_vptr_update", IRB.getVoidTy(),
113 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
114 NULL);
Kostya Serebryany60ebb1942012-02-13 22:50:51 +0000115 return true;
116}
117
118bool ThreadSanitizer::runOnFunction(Function &F) {
119 if (!TD) return false;
Kostya Serebryany6e590e32012-03-14 23:33:24 +0000120 if (BL->isIn(F)) return false;
Kostya Serebryany60ebb1942012-02-13 22:50:51 +0000121 SmallVector<Instruction*, 8> RetVec;
122 SmallVector<Instruction*, 8> LoadsAndStores;
123 bool Res = false;
124 bool HasCalls = false;
125
126 // Traverse all instructions, collect loads/stores/returns, check for calls.
127 for (Function::iterator FI = F.begin(), FE = F.end();
128 FI != FE; ++FI) {
129 BasicBlock &BB = *FI;
130 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end();
131 BI != BE; ++BI) {
132 if (isa<LoadInst>(BI) || isa<StoreInst>(BI))
133 LoadsAndStores.push_back(BI);
134 else if (isa<ReturnInst>(BI))
135 RetVec.push_back(BI);
136 else if (isa<CallInst>(BI) || isa<InvokeInst>(BI))
137 HasCalls = true;
138 }
139 }
140
141 // We have collected all loads and stores.
142 // FIXME: many of these accesses do not need to be checked for races
143 // (e.g. variables that do not escape, etc).
144
145 // Instrument memory accesses.
146 for (size_t i = 0, n = LoadsAndStores.size(); i < n; ++i) {
147 Res |= instrumentLoadOrStore(LoadsAndStores[i]);
148 }
149
150 // Instrument function entry/exit points if there were instrumented accesses.
151 if (Res || HasCalls) {
152 IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
153 Value *ReturnAddress = IRB.CreateCall(
154 Intrinsic::getDeclaration(F.getParent(), Intrinsic::returnaddress),
155 IRB.getInt32(0));
156 IRB.CreateCall(TsanFuncEntry, ReturnAddress);
157 for (size_t i = 0, n = RetVec.size(); i < n; ++i) {
158 IRBuilder<> IRBRet(RetVec[i]);
159 IRBRet.CreateCall(TsanFuncExit);
160 }
Kostya Serebryany52eb69922012-03-26 17:35:03 +0000161 Res = true;
Kostya Serebryany60ebb1942012-02-13 22:50:51 +0000162 }
163 return Res;
164}
165
Kostya Serebryany52eb69922012-03-26 17:35:03 +0000166static bool isVtableAccess(Instruction *I) {
167 if (MDNode *Tag = I->getMetadata(LLVMContext::MD_tbaa)) {
168 if (Tag->getNumOperands() < 1) return false;
169 if (MDString *Tag1 = dyn_cast<MDString>(Tag->getOperand(0))) {
170 if (Tag1->getString() == "vtable pointer") return true;
171 }
172 }
173 return false;
174}
175
Kostya Serebryany60ebb1942012-02-13 22:50:51 +0000176bool ThreadSanitizer::instrumentLoadOrStore(Instruction *I) {
177 IRBuilder<> IRB(I);
178 bool IsWrite = isa<StoreInst>(*I);
179 Value *Addr = IsWrite
180 ? cast<StoreInst>(I)->getPointerOperand()
181 : cast<LoadInst>(I)->getPointerOperand();
182 Type *OrigPtrTy = Addr->getType();
183 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
184 assert(OrigTy->isSized());
185 uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
186 if (TypeSize != 8 && TypeSize != 16 &&
187 TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
188 // Ignore all unusual sizes.
189 return false;
190 }
Kostya Serebryany52eb69922012-03-26 17:35:03 +0000191 if (IsWrite && isVtableAccess(I)) {
192 Value *StoredValue = cast<StoreInst>(I)->getValueOperand();
193 IRB.CreateCall2(TsanVptrUpdate,
194 IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()),
195 IRB.CreatePointerCast(StoredValue, IRB.getInt8PtrTy()));
196 return true;
197 }
Kostya Serebryany3eccaa62012-02-14 00:52:07 +0000198 size_t Idx = CountTrailingZeros_32(TypeSize / 8);
Kostya Serebryany60ebb1942012-02-13 22:50:51 +0000199 assert(Idx < kNumberOfAccessSizes);
200 Value *OnAccessFunc = IsWrite ? TsanWrite[Idx] : TsanRead[Idx];
201 IRB.CreateCall(OnAccessFunc, IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()));
202 return true;
203}