1 //===-- CDSPass.cpp - xxx -------------------------------===//
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 modified version of ThreadSanitizer.cpp, a part of 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 #include "llvm/ADT/Statistic.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/Analysis/ValueTracking.h"
26 #include "llvm/Analysis/CaptureTracking.h"
27 #include "llvm/IR/BasicBlock.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/IRBuilder.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/LLVMContext.h"
32 #include "llvm/IR/LegacyPassManager.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/PassManager.h"
35 #include "llvm/Pass.h"
36 #include "llvm/ProfileData/InstrProf.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Support/AtomicOrdering.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Transforms/Scalar.h"
41 #include "llvm/Transforms/Utils/Local.h"
42 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
43 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
46 #define DEBUG_TYPE "CDS"
49 #include "getPosition.hpp"
51 #define FUNCARRAYSIZE 4
53 STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
54 STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
55 // STATISTIC(NumInstrumentedVtableWrites, "Number of vtable ptr writes");
56 // STATISTIC(NumInstrumentedVtableReads, "Number of vtable ptr reads");
58 STATISTIC(NumOmittedReadsBeforeWrite,
59 "Number of reads ignored due to following writes");
60 STATISTIC(NumOmittedReadsFromConstantGlobals,
61 "Number of reads from constant globals");
62 STATISTIC(NumOmittedReadsFromVtable, "Number of vtable reads");
63 STATISTIC(NumOmittedNonCaptured, "Number of accesses ignored due to capturing");
78 Constant * CDSLoad[FUNCARRAYSIZE];
79 Constant * CDSStore[FUNCARRAYSIZE];
80 Constant * CDSAtomicInit[FUNCARRAYSIZE];
81 Constant * CDSAtomicLoad[FUNCARRAYSIZE];
82 Constant * CDSAtomicStore[FUNCARRAYSIZE];
83 Constant * CDSAtomicRMW[AtomicRMWInst::LAST_BINOP + 1][FUNCARRAYSIZE];
84 Constant * CDSAtomicCAS_V1[FUNCARRAYSIZE];
85 Constant * CDSAtomicCAS_V2[FUNCARRAYSIZE];
86 Constant * CDSAtomicThreadFence;
90 int getAtomicOrderIndex(AtomicOrdering order){
92 case AtomicOrdering::Monotonic:
93 return (int)AtomicOrderingCABI::relaxed;
94 // case AtomicOrdering::Consume: // not specified yet
95 // return AtomicOrderingCABI::consume;
96 case AtomicOrdering::Acquire:
97 return (int)AtomicOrderingCABI::acquire;
98 case AtomicOrdering::Release:
99 return (int)AtomicOrderingCABI::release;
100 case AtomicOrdering::AcquireRelease:
101 return (int)AtomicOrderingCABI::acq_rel;
102 case AtomicOrdering::SequentiallyConsistent:
103 return (int)AtomicOrderingCABI::seq_cst;
105 // unordered or Not Atomic
110 int getTypeSize(Type* type) {
111 if (type == Int8PtrTy) {
112 return sizeof(char)*8;
113 } else if (type == Int16PtrTy) {
114 return sizeof(short)*8;
115 } else if (type == Int32PtrTy) {
116 return sizeof(int)*8;
117 } else if (type == Int64PtrTy) {
118 return sizeof(long long int)*8;
120 return sizeof(void*)*8;
126 static int sizetoindex(int size) {
137 struct CDSPass : public FunctionPass {
139 CDSPass() : FunctionPass(ID) {}
140 bool runOnFunction(Function &F) override;
143 void initializeCallbacks(Module &M);
144 bool instrumentLoadOrStore(Instruction *I, const DataLayout &DL);
145 bool instrumentAtomic(Instruction *I, const DataLayout &DL);
146 bool instrumentAtomicCall(CallInst *CI, const DataLayout &DL);
147 void chooseInstructionsToInstrument(SmallVectorImpl<Instruction *> &Local,
148 SmallVectorImpl<Instruction *> &All,
149 const DataLayout &DL);
150 bool addrPointsToConstantData(Value *Addr);
151 int getMemoryAccessFuncIndex(Value *Addr, const DataLayout &DL);
155 static bool isVtableAccess(Instruction *I) {
156 if (MDNode *Tag = I->getMetadata(LLVMContext::MD_tbaa))
157 return Tag->isTBAAVtableAccess();
161 #include "initializeCallbacks.hpp"
162 #include "isAtomicCall.hpp"
163 #include "instrumentAtomicCall.hpp"
165 static bool shouldInstrumentReadWriteFromAddress(const Module *M, Value *Addr) {
166 // Peel off GEPs and BitCasts.
167 Addr = Addr->stripInBoundsOffsets();
169 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
170 if (GV->hasSection()) {
171 StringRef SectionName = GV->getSection();
172 // Check if the global is in the PGO counters section.
173 auto OF = Triple(M->getTargetTriple()).getObjectFormat();
174 if (SectionName.endswith(
175 getInstrProfSectionName(IPSK_cnts, OF, /*AddSegmentInfo=*/false)))
179 // Check if the global is private gcov data.
180 if (GV->getName().startswith("__llvm_gcov") ||
181 GV->getName().startswith("__llvm_gcda"))
185 // Do not instrument acesses from different address spaces; we cannot deal
188 Type *PtrTy = cast<PointerType>(Addr->getType()->getScalarType());
189 if (PtrTy->getPointerAddressSpace() != 0)
196 bool CDSPass::addrPointsToConstantData(Value *Addr) {
197 // If this is a GEP, just analyze its pointer operand.
198 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Addr))
199 Addr = GEP->getPointerOperand();
201 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
202 if (GV->isConstant()) {
203 // Reads from constant globals can not race with any writes.
204 NumOmittedReadsFromConstantGlobals++;
207 } else if (LoadInst *L = dyn_cast<LoadInst>(Addr)) {
208 if (isVtableAccess(L)) {
209 // Reads from a vtable pointer can not race with any writes.
210 NumOmittedReadsFromVtable++;
217 bool CDSPass::runOnFunction(Function &F) {
218 if (F.getName() == "main") {
219 F.setName("user_main");
220 errs() << "main replaced by user_main\n";
224 initializeCallbacks( *F.getParent() );
226 SmallVector<Instruction*, 8> AllLoadsAndStores;
227 SmallVector<Instruction*, 8> LocalLoadsAndStores;
228 SmallVector<Instruction*, 8> AtomicAccesses;
230 std::vector<Instruction *> worklist;
233 const DataLayout &DL = F.getParent()->getDataLayout();
235 errs() << "--- " << F.getName() << "---\n";
239 if ( (&I)->isAtomic() || isAtomicCall(&I) ) {
240 AtomicAccesses.push_back(&I);
241 } else if (isa<LoadInst>(I) || isa<StoreInst>(I)) {
242 LocalLoadsAndStores.push_back(&I);
243 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
244 // not implemented yet
248 chooseInstructionsToInstrument(LocalLoadsAndStores, AllLoadsAndStores, DL);
251 for (auto Inst : AllLoadsAndStores) {
252 // Res |= instrumentLoadOrStore(Inst, DL);
253 // errs() << "load and store are replaced\n";
256 for (auto Inst : AtomicAccesses) {
257 Res |= instrumentAtomic(Inst, DL);
260 if (F.getName() == "user_main") {
269 void CDSPass::chooseInstructionsToInstrument(
270 SmallVectorImpl<Instruction *> &Local, SmallVectorImpl<Instruction *> &All,
271 const DataLayout &DL) {
272 SmallPtrSet<Value*, 8> WriteTargets;
273 // Iterate from the end.
274 for (Instruction *I : reverse(Local)) {
275 if (StoreInst *Store = dyn_cast<StoreInst>(I)) {
276 Value *Addr = Store->getPointerOperand();
277 if (!shouldInstrumentReadWriteFromAddress(I->getModule(), Addr))
279 WriteTargets.insert(Addr);
281 LoadInst *Load = cast<LoadInst>(I);
282 Value *Addr = Load->getPointerOperand();
283 if (!shouldInstrumentReadWriteFromAddress(I->getModule(), Addr))
285 if (WriteTargets.count(Addr)) {
286 // We will write to this temp, so no reason to analyze the read.
287 NumOmittedReadsBeforeWrite++;
290 if (addrPointsToConstantData(Addr)) {
291 // Addr points to some constant data -- it can not race with any writes.
295 Value *Addr = isa<StoreInst>(*I)
296 ? cast<StoreInst>(I)->getPointerOperand()
297 : cast<LoadInst>(I)->getPointerOperand();
298 if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
299 !PointerMayBeCaptured(Addr, true, true)) {
300 // The variable is addressable but not captured, so it cannot be
301 // referenced from a different thread and participate in a data race
302 // (see llvm/Analysis/CaptureTracking.h for details).
303 NumOmittedNonCaptured++;
312 bool CDSPass::instrumentLoadOrStore(Instruction *I,
313 const DataLayout &DL) {
315 bool IsWrite = isa<StoreInst>(*I);
316 Value *Addr = IsWrite
317 ? cast<StoreInst>(I)->getPointerOperand()
318 : cast<LoadInst>(I)->getPointerOperand();
320 // swifterror memory addresses are mem2reg promoted by instruction selection.
321 // As such they cannot have regular uses like an instrumentation function and
322 // it makes no sense to track them as memory.
323 if (Addr->isSwiftError())
326 int size = getTypeSize(Addr->getType());
327 int index = sizetoindex(size);
329 // not supported by CDS yet
330 /* if (IsWrite && isVtableAccess(I)) {
331 LLVM_DEBUG(dbgs() << " VPTR : " << *I << "\n");
332 Value *StoredValue = cast<StoreInst>(I)->getValueOperand();
333 // StoredValue may be a vector type if we are storing several vptrs at once.
334 // In this case, just take the first element of the vector since this is
335 // enough to find vptr races.
336 if (isa<VectorType>(StoredValue->getType()))
337 StoredValue = IRB.CreateExtractElement(
338 StoredValue, ConstantInt::get(IRB.getInt32Ty(), 0));
339 if (StoredValue->getType()->isIntegerTy())
340 StoredValue = IRB.CreateIntToPtr(StoredValue, IRB.getInt8PtrTy());
341 // Call TsanVptrUpdate.
342 IRB.CreateCall(TsanVptrUpdate,
343 {IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()),
344 IRB.CreatePointerCast(StoredValue, IRB.getInt8PtrTy())});
345 NumInstrumentedVtableWrites++;
349 if (!IsWrite && isVtableAccess(I)) {
350 IRB.CreateCall(TsanVptrLoad,
351 IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()));
352 NumInstrumentedVtableReads++;
357 Value *OnAccessFunc = nullptr;
358 OnAccessFunc = IsWrite ? CDSStore[index] : CDSLoad[index];
360 Type *ArgType = IRB.CreatePointerCast(Addr, Addr->getType())->getType();
362 if ( ArgType != Int8PtrTy && ArgType != Int16PtrTy &&
363 ArgType != Int32PtrTy && ArgType != Int64PtrTy ) {
364 //errs() << "A load or store of type ";
365 //errs() << *ArgType;
366 //errs() << " is passed in\n";
367 return false; // if other types of load or stores are passed in
369 IRB.CreateCall(OnAccessFunc, IRB.CreatePointerCast(Addr, Addr->getType()));
370 if (IsWrite) NumInstrumentedWrites++;
371 else NumInstrumentedReads++;
375 // todo: replace getTypeSize with the getMemoryAccessFuncIndex
376 bool CDSPass::instrumentAtomic(Instruction * I, const DataLayout &DL) {
378 // LLVMContext &Ctx = IRB.getContext();
380 if (auto *CI = dyn_cast<CallInst>(I)) {
381 return instrumentAtomicCall(CI, DL);
384 Value *position = getPosition(I, IRB);
386 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
387 int atomic_order_index = getAtomicOrderIndex(SI->getOrdering());
389 Value *val = SI->getValueOperand();
390 Value *ptr = SI->getPointerOperand();
391 Value *order = ConstantInt::get(OrdTy, atomic_order_index);
392 Value *args[] = {ptr, val, order, position};
394 int size=getTypeSize(ptr->getType());
395 int index=sizetoindex(size);
397 Instruction* funcInst=CallInst::Create(CDSAtomicStore[index], args);
398 ReplaceInstWithInst(SI, funcInst);
399 // errs() << "Store replaced\n";
400 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
401 int atomic_order_index = getAtomicOrderIndex(LI->getOrdering());
403 Value *ptr = LI->getPointerOperand();
404 Value *order = ConstantInt::get(OrdTy, atomic_order_index);
405 Value *args[] = {ptr, order, position};
407 int size=getTypeSize(ptr->getType());
408 int index=sizetoindex(size);
410 Instruction* funcInst=CallInst::Create(CDSAtomicLoad[index], args);
411 ReplaceInstWithInst(LI, funcInst);
412 // errs() << "Load Replaced\n";
413 } else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I)) {
414 int atomic_order_index = getAtomicOrderIndex(RMWI->getOrdering());
416 Value *val = RMWI->getValOperand();
417 Value *ptr = RMWI->getPointerOperand();
418 Value *order = ConstantInt::get(OrdTy, atomic_order_index);
419 Value *args[] = {ptr, val, order, position};
421 int size = getTypeSize(ptr->getType());
422 int index = sizetoindex(size);
424 Instruction* funcInst = CallInst::Create(CDSAtomicRMW[RMWI->getOperation()][index], args);
425 ReplaceInstWithInst(RMWI, funcInst);
426 // errs() << RMWI->getOperationName(RMWI->getOperation());
427 // errs() << " replaced\n";
428 } else if (AtomicCmpXchgInst *CASI = dyn_cast<AtomicCmpXchgInst>(I)) {
429 IRBuilder<> IRB(CASI);
431 Value *Addr = CASI->getPointerOperand();
433 int size = getTypeSize(Addr->getType());
434 int index = sizetoindex(size);
435 const unsigned ByteSize = 1U << index;
436 const unsigned BitSize = ByteSize * 8;
437 Type *Ty = Type::getIntNTy(IRB.getContext(), BitSize);
438 Type *PtrTy = Ty->getPointerTo();
440 Value *CmpOperand = IRB.CreateBitOrPointerCast(CASI->getCompareOperand(), Ty);
441 Value *NewOperand = IRB.CreateBitOrPointerCast(CASI->getNewValOperand(), Ty);
443 int atomic_order_index_succ = getAtomicOrderIndex(CASI->getSuccessOrdering());
444 int atomic_order_index_fail = getAtomicOrderIndex(CASI->getFailureOrdering());
445 Value *order_succ = ConstantInt::get(OrdTy, atomic_order_index_succ);
446 Value *order_fail = ConstantInt::get(OrdTy, atomic_order_index_fail);
448 Value *Args[] = {IRB.CreatePointerCast(Addr, PtrTy),
449 CmpOperand, NewOperand,
450 order_succ, order_fail, position};
452 CallInst *funcInst = IRB.CreateCall(CDSAtomicCAS_V1[index], Args);
453 Value *Success = IRB.CreateICmpEQ(funcInst, CmpOperand);
455 Value *OldVal = funcInst;
456 Type *OrigOldValTy = CASI->getNewValOperand()->getType();
457 if (Ty != OrigOldValTy) {
458 // The value is a pointer, so we need to cast the return value.
459 OldVal = IRB.CreateIntToPtr(funcInst, OrigOldValTy);
463 IRB.CreateInsertValue(UndefValue::get(CASI->getType()), OldVal, 0);
464 Res = IRB.CreateInsertValue(Res, Success, 1);
466 I->replaceAllUsesWith(Res);
467 I->eraseFromParent();
468 } else if (FenceInst *FI = dyn_cast<FenceInst>(I)) {
469 int atomic_order_index = getAtomicOrderIndex(FI->getOrdering());
470 Value *order = ConstantInt::get(OrdTy, atomic_order_index);
471 Value *Args[] = {order, position};
473 CallInst *funcInst = CallInst::Create(CDSAtomicThreadFence, Args);
474 ReplaceInstWithInst(FI, funcInst);
475 // errs() << "Thread Fences replaced\n";
480 int CDSPass::getMemoryAccessFuncIndex(Value *Addr,
481 const DataLayout &DL) {
482 Type *OrigPtrTy = Addr->getType();
483 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
484 assert(OrigTy->isSized());
485 uint32_t TypeSize = DL.getTypeStoreSizeInBits(OrigTy);
486 if (TypeSize != 8 && TypeSize != 16 &&
487 TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
488 // NumAccessesWithBadSize++;
489 // Ignore all unusual sizes.
492 size_t Idx = countTrailingZeros(TypeSize / 8);
493 // assert(Idx < FUNCARRAYSIZE);
498 char CDSPass::ID = 0;
500 // Automatically enable the pass.
501 static void registerCDSPass(const PassManagerBuilder &,
502 legacy::PassManagerBase &PM) {
503 PM.add(new CDSPass());
505 static RegisterStandardPasses
506 RegisterMyPass(PassManagerBuilder::EP_OptimizerLast,