1 //===-- CDSPass.cpp - xxx -------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 // This file is distributed under the University of Illinois Open Source
7 // License. See LICENSE.TXT for details.
9 //===----------------------------------------------------------------------===//
11 // This file is a modified version of ThreadSanitizer.cpp, a part of a race detector.
13 // The tool is under development, for the details about previous versions see
14 // http://code.google.com/p/data-race-test
16 // The instrumentation phase is quite simple:
17 // - Insert calls to run-time library before every memory access.
18 // - Optimizations may apply to avoid instrumenting some of the accesses.
19 // - Insert calls at function entry/exit.
20 // The rest is handled by the run-time library.
21 //===----------------------------------------------------------------------===//
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/SmallString.h"
26 #include "llvm/Analysis/ValueTracking.h"
27 #include "llvm/Analysis/CaptureTracking.h"
28 #include "llvm/IR/BasicBlock.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/IRBuilder.h"
31 #include "llvm/IR/Instructions.h"
32 #include "llvm/IR/IntrinsicInst.h"
33 #include "llvm/IR/LLVMContext.h"
34 #include "llvm/IR/LegacyPassManager.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/IR/PassManager.h"
37 #include "llvm/Pass.h"
38 #include "llvm/ProfileData/InstrProf.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Support/AtomicOrdering.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Transforms/Scalar.h"
43 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
44 #include "llvm/Transforms/Utils/EscapeEnumerator.h"
45 // #include "llvm/Transforms/Utils/ModuleUtils.h"
46 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
51 #define DEBUG_TYPE "CDS"
52 #include <llvm/IR/DebugLoc.h>
54 Value *getPosition( Instruction * I, IRBuilder <> IRB, bool print = false)
56 const DebugLoc & debug_location = I->getDebugLoc ();
57 std::string position_string;
59 llvm::raw_string_ostream position_stream (position_string);
60 debug_location . print (position_stream);
64 errs() << position_string << "\n";
67 return IRB.CreateGlobalStringPtr (position_string);
70 STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
71 STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
72 STATISTIC(NumOmittedReadsBeforeWrite,
73 "Number of reads ignored due to following writes");
74 STATISTIC(NumAccessesWithBadSize, "Number of accesses with bad size");
75 // STATISTIC(NumInstrumentedVtableWrites, "Number of vtable ptr writes");
76 // STATISTIC(NumInstrumentedVtableReads, "Number of vtable ptr reads");
77 STATISTIC(NumOmittedReadsFromConstantGlobals,
78 "Number of reads from constant globals");
79 STATISTIC(NumOmittedReadsFromVtable, "Number of vtable reads");
80 STATISTIC(NumOmittedNonCaptured, "Number of accesses ignored due to capturing");
82 // static const char *const kCDSModuleCtorName = "cds.module_ctor";
83 // static const char *const kCDSInitName = "cds_init";
94 static const size_t kNumberOfAccessSizes = 4;
96 int getAtomicOrderIndex(AtomicOrdering order) {
98 case AtomicOrdering::Monotonic:
99 return (int)AtomicOrderingCABI::relaxed;
100 // case AtomicOrdering::Consume: // not specified yet
101 // return AtomicOrderingCABI::consume;
102 case AtomicOrdering::Acquire:
103 return (int)AtomicOrderingCABI::acquire;
104 case AtomicOrdering::Release:
105 return (int)AtomicOrderingCABI::release;
106 case AtomicOrdering::AcquireRelease:
107 return (int)AtomicOrderingCABI::acq_rel;
108 case AtomicOrdering::SequentiallyConsistent:
109 return (int)AtomicOrderingCABI::seq_cst;
111 // unordered or Not Atomic
116 AtomicOrderingCABI indexToAtomicOrder(int index) {
119 return AtomicOrderingCABI::relaxed;
121 return AtomicOrderingCABI::consume;
123 return AtomicOrderingCABI::acquire;
125 return AtomicOrderingCABI::release;
127 return AtomicOrderingCABI::acq_rel;
129 return AtomicOrderingCABI::seq_cst;
131 errs() << "Bad Atomic index\n";
132 return AtomicOrderingCABI::seq_cst;
136 /* According to atomic_base.h: __cmpexch_failure_order */
137 int AtomicCasFailureOrderIndex(int index) {
138 AtomicOrderingCABI succ_order = indexToAtomicOrder(index);
139 AtomicOrderingCABI fail_order;
140 if (succ_order == AtomicOrderingCABI::acq_rel)
141 fail_order = AtomicOrderingCABI::acquire;
142 else if (succ_order == AtomicOrderingCABI::release)
143 fail_order = AtomicOrderingCABI::relaxed;
145 fail_order = succ_order;
147 return (int) fail_order;
150 /* The original function checkSanitizerInterfaceFunction was defined
151 * in llvm/Transforms/Utils/ModuleUtils.h
153 static Function * checkCDSPassInterfaceFunction(Constant *FuncOrBitcast) {
154 if (isa<Function>(FuncOrBitcast))
155 return cast<Function>(FuncOrBitcast);
156 FuncOrBitcast->print(errs());
159 raw_string_ostream Stream(Err);
160 Stream << "CDSPass interface function redefined: " << *FuncOrBitcast;
161 report_fatal_error(Err);
165 struct CDSPass : public FunctionPass {
166 CDSPass() : FunctionPass(ID) {}
167 StringRef getPassName() const override;
168 bool runOnFunction(Function &F) override;
169 bool doInitialization(Module &M) override;
173 void initializeCallbacks(Module &M);
174 bool instrumentLoadOrStore(Instruction *I, const DataLayout &DL);
175 bool instrumentVolatile(Instruction *I, const DataLayout &DL);
176 bool instrumentMemIntrinsic(Instruction *I);
177 bool isAtomicCall(Instruction *I);
178 bool instrumentAtomic(Instruction *I, const DataLayout &DL);
179 bool instrumentAtomicCall(CallInst *CI, const DataLayout &DL);
180 void chooseInstructionsToInstrument(SmallVectorImpl<Instruction *> &Local,
181 SmallVectorImpl<Instruction *> &All,
182 const DataLayout &DL);
183 bool addrPointsToConstantData(Value *Addr);
184 int getMemoryAccessFuncIndex(Value *Addr, const DataLayout &DL);
186 Function * CDSFuncEntry;
187 Function * CDSFuncExit;
189 Function * CDSLoad[kNumberOfAccessSizes];
190 Function * CDSStore[kNumberOfAccessSizes];
191 Function * CDSVolatileLoad[kNumberOfAccessSizes];
192 Function * CDSVolatileStore[kNumberOfAccessSizes];
193 Function * CDSAtomicInit[kNumberOfAccessSizes];
194 Function * CDSAtomicLoad[kNumberOfAccessSizes];
195 Function * CDSAtomicStore[kNumberOfAccessSizes];
196 Function * CDSAtomicRMW[AtomicRMWInst::LAST_BINOP + 1][kNumberOfAccessSizes];
197 Function * CDSAtomicCAS_V1[kNumberOfAccessSizes];
198 Function * CDSAtomicCAS_V2[kNumberOfAccessSizes];
199 Function * CDSAtomicThreadFence;
200 Function * MemmoveFn, * MemcpyFn, * MemsetFn;
201 // Function * CDSCtorFunction;
203 std::vector<StringRef> AtomicFuncNames;
204 std::vector<StringRef> PartialAtomicFuncNames;
208 StringRef CDSPass::getPassName() const {
212 void CDSPass::initializeCallbacks(Module &M) {
213 LLVMContext &Ctx = M.getContext();
215 Attr = Attr.addAttribute(Ctx, AttributeList::FunctionIndex,
216 Attribute::NoUnwind);
218 Type * Int1Ty = Type::getInt1Ty(Ctx);
219 Type * Int32Ty = Type::getInt32Ty(Ctx);
220 OrdTy = Type::getInt32Ty(Ctx);
222 Int8PtrTy = Type::getInt8PtrTy(Ctx);
223 Int16PtrTy = Type::getInt16PtrTy(Ctx);
224 Int32PtrTy = Type::getInt32PtrTy(Ctx);
225 Int64PtrTy = Type::getInt64PtrTy(Ctx);
227 VoidTy = Type::getVoidTy(Ctx);
229 CDSFuncEntry = checkCDSPassInterfaceFunction(
230 M.getOrInsertFunction("cds_func_entry",
231 Attr, VoidTy, Int8PtrTy));
232 CDSFuncExit = checkCDSPassInterfaceFunction(
233 M.getOrInsertFunction("cds_func_exit",
234 Attr, VoidTy, Int8PtrTy));
236 // Get the function to call from our untime library.
237 for (unsigned i = 0; i < kNumberOfAccessSizes; i++) {
238 const unsigned ByteSize = 1U << i;
239 const unsigned BitSize = ByteSize * 8;
241 std::string ByteSizeStr = utostr(ByteSize);
242 std::string BitSizeStr = utostr(BitSize);
244 Type *Ty = Type::getIntNTy(Ctx, BitSize);
245 Type *PtrTy = Ty->getPointerTo();
247 // uint8_t cds_atomic_load8 (void * obj, int atomic_index)
248 // void cds_atomic_store8 (void * obj, int atomic_index, uint8_t val)
249 SmallString<32> LoadName("cds_load" + BitSizeStr);
250 SmallString<32> StoreName("cds_store" + BitSizeStr);
251 SmallString<32> VolatileLoadName("cds_volatile_load" + BitSizeStr);
252 SmallString<32> VolatileStoreName("cds_volatile_store" + BitSizeStr);
253 SmallString<32> AtomicInitName("cds_atomic_init" + BitSizeStr);
254 SmallString<32> AtomicLoadName("cds_atomic_load" + BitSizeStr);
255 SmallString<32> AtomicStoreName("cds_atomic_store" + BitSizeStr);
257 CDSLoad[i] = checkCDSPassInterfaceFunction(
258 M.getOrInsertFunction(LoadName, Attr, VoidTy, PtrTy));
259 CDSStore[i] = checkCDSPassInterfaceFunction(
260 M.getOrInsertFunction(StoreName, Attr, VoidTy, PtrTy));
261 CDSVolatileLoad[i] = checkCDSPassInterfaceFunction(
262 M.getOrInsertFunction(VolatileLoadName,
263 Attr, Ty, PtrTy, Int8PtrTy));
264 CDSVolatileStore[i] = checkCDSPassInterfaceFunction(
265 M.getOrInsertFunction(VolatileStoreName,
266 Attr, VoidTy, PtrTy, Ty, Int8PtrTy));
267 CDSAtomicInit[i] = checkCDSPassInterfaceFunction(
268 M.getOrInsertFunction(AtomicInitName,
269 Attr, VoidTy, PtrTy, Ty, Int8PtrTy));
270 CDSAtomicLoad[i] = checkCDSPassInterfaceFunction(
271 M.getOrInsertFunction(AtomicLoadName,
272 Attr, Ty, PtrTy, OrdTy, Int8PtrTy));
273 CDSAtomicStore[i] = checkCDSPassInterfaceFunction(
274 M.getOrInsertFunction(AtomicStoreName,
275 Attr, VoidTy, PtrTy, Ty, OrdTy, Int8PtrTy));
277 for (int op = AtomicRMWInst::FIRST_BINOP;
278 op <= AtomicRMWInst::LAST_BINOP; ++op) {
279 CDSAtomicRMW[op][i] = nullptr;
280 std::string NamePart;
282 if (op == AtomicRMWInst::Xchg)
283 NamePart = "_exchange";
284 else if (op == AtomicRMWInst::Add)
285 NamePart = "_fetch_add";
286 else if (op == AtomicRMWInst::Sub)
287 NamePart = "_fetch_sub";
288 else if (op == AtomicRMWInst::And)
289 NamePart = "_fetch_and";
290 else if (op == AtomicRMWInst::Or)
291 NamePart = "_fetch_or";
292 else if (op == AtomicRMWInst::Xor)
293 NamePart = "_fetch_xor";
297 SmallString<32> AtomicRMWName("cds_atomic" + NamePart + BitSizeStr);
298 CDSAtomicRMW[op][i] = checkCDSPassInterfaceFunction(
299 M.getOrInsertFunction(AtomicRMWName,
300 Attr, Ty, PtrTy, Ty, OrdTy, Int8PtrTy));
303 // only supportes strong version
304 SmallString<32> AtomicCASName_V1("cds_atomic_compare_exchange" + BitSizeStr + "_v1");
305 SmallString<32> AtomicCASName_V2("cds_atomic_compare_exchange" + BitSizeStr + "_v2");
306 CDSAtomicCAS_V1[i] = checkCDSPassInterfaceFunction(
307 M.getOrInsertFunction(AtomicCASName_V1,
308 Attr, Ty, PtrTy, Ty, Ty, OrdTy, OrdTy, Int8PtrTy));
309 CDSAtomicCAS_V2[i] = checkCDSPassInterfaceFunction(
310 M.getOrInsertFunction(AtomicCASName_V2,
311 Attr, Int1Ty, PtrTy, PtrTy, Ty, OrdTy, OrdTy, Int8PtrTy));
314 CDSAtomicThreadFence = checkCDSPassInterfaceFunction(
315 M.getOrInsertFunction("cds_atomic_thread_fence", Attr, VoidTy, OrdTy, Int8PtrTy));
317 MemmoveFn = checkCDSPassInterfaceFunction(
318 M.getOrInsertFunction("memmove", Attr, Int8PtrTy, Int8PtrTy,
319 Int8PtrTy, IntPtrTy));
320 MemcpyFn = checkCDSPassInterfaceFunction(
321 M.getOrInsertFunction("memcpy", Attr, Int8PtrTy, Int8PtrTy,
322 Int8PtrTy, IntPtrTy));
323 MemsetFn = checkCDSPassInterfaceFunction(
324 M.getOrInsertFunction("memset", Attr, Int8PtrTy, Int8PtrTy,
328 bool CDSPass::doInitialization(Module &M) {
329 const DataLayout &DL = M.getDataLayout();
330 IntPtrTy = DL.getIntPtrType(M.getContext());
332 // createSanitizerCtorAndInitFunctions is defined in "llvm/Transforms/Utils/ModuleUtils.h"
333 // We do not support it yet
335 std::tie(CDSCtorFunction, std::ignore) = createSanitizerCtorAndInitFunctions(
336 M, kCDSModuleCtorName, kCDSInitName, {}, {});
338 appendToGlobalCtors(M, CDSCtorFunction, 0);
343 "atomic_init", "atomic_load", "atomic_store",
344 "atomic_fetch_", "atomic_exchange", "atomic_compare_exchange_"
347 PartialAtomicFuncNames =
349 "load", "store", "fetch", "exchange", "compare_exchange_"
355 static bool isVtableAccess(Instruction *I) {
356 if (MDNode *Tag = I->getMetadata(LLVMContext::MD_tbaa))
357 return Tag->isTBAAVtableAccess();
361 // Do not instrument known races/"benign races" that come from compiler
362 // instrumentatin. The user has no way of suppressing them.
363 static bool shouldInstrumentReadWriteFromAddress(const Module *M, Value *Addr) {
364 // Peel off GEPs and BitCasts.
365 Addr = Addr->stripInBoundsOffsets();
367 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
368 if (GV->hasSection()) {
369 StringRef SectionName = GV->getSection();
370 // Check if the global is in the PGO counters section.
371 auto OF = Triple(M->getTargetTriple()).getObjectFormat();
372 if (SectionName.endswith(
373 getInstrProfSectionName(IPSK_cnts, OF, /*AddSegmentInfo=*/false)))
377 // Check if the global is private gcov data.
378 if (GV->getName().startswith("__llvm_gcov") ||
379 GV->getName().startswith("__llvm_gcda"))
383 // Do not instrument acesses from different address spaces; we cannot deal
386 Type *PtrTy = cast<PointerType>(Addr->getType()->getScalarType());
387 if (PtrTy->getPointerAddressSpace() != 0)
394 bool CDSPass::addrPointsToConstantData(Value *Addr) {
395 // If this is a GEP, just analyze its pointer operand.
396 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Addr))
397 Addr = GEP->getPointerOperand();
399 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
400 if (GV->isConstant()) {
401 // Reads from constant globals can not race with any writes.
402 NumOmittedReadsFromConstantGlobals++;
405 } else if (LoadInst *L = dyn_cast<LoadInst>(Addr)) {
406 if (isVtableAccess(L)) {
407 // Reads from a vtable pointer can not race with any writes.
408 NumOmittedReadsFromVtable++;
415 void CDSPass::chooseInstructionsToInstrument(
416 SmallVectorImpl<Instruction *> &Local, SmallVectorImpl<Instruction *> &All,
417 const DataLayout &DL) {
418 SmallPtrSet<Value*, 8> WriteTargets;
419 // Iterate from the end.
420 for (Instruction *I : reverse(Local)) {
421 if (StoreInst *Store = dyn_cast<StoreInst>(I)) {
422 Value *Addr = Store->getPointerOperand();
423 if (!shouldInstrumentReadWriteFromAddress(I->getModule(), Addr))
425 WriteTargets.insert(Addr);
427 LoadInst *Load = cast<LoadInst>(I);
428 Value *Addr = Load->getPointerOperand();
429 if (!shouldInstrumentReadWriteFromAddress(I->getModule(), Addr))
431 if (WriteTargets.count(Addr)) {
432 // We will write to this temp, so no reason to analyze the read.
433 NumOmittedReadsBeforeWrite++;
436 if (addrPointsToConstantData(Addr)) {
437 // Addr points to some constant data -- it can not race with any writes.
441 Value *Addr = isa<StoreInst>(*I)
442 ? cast<StoreInst>(I)->getPointerOperand()
443 : cast<LoadInst>(I)->getPointerOperand();
444 if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
445 !PointerMayBeCaptured(Addr, true, true)) {
446 // The variable is addressable but not captured, so it cannot be
447 // referenced from a different thread and participate in a data race
448 // (see llvm/Analysis/CaptureTracking.h for details).
449 NumOmittedNonCaptured++;
458 void CDSPass::InsertRuntimeIgnores(Function &F) {
459 IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
460 IRB.CreateCall(CDSIgnoreBegin);
461 EscapeEnumerator EE(F, "cds_ignore_cleanup", ClHandleCxxExceptions);
462 while (IRBuilder<> *AtExit = EE.Next()) {
463 AtExit->CreateCall(CDSIgnoreEnd);
467 bool CDSPass::runOnFunction(Function &F) {
468 if (F.getName() == "main") {
469 F.setName("user_main");
470 errs() << "main replaced by user_main\n";
473 initializeCallbacks( *F.getParent() );
474 SmallVector<Instruction*, 8> AllLoadsAndStores;
475 SmallVector<Instruction*, 8> LocalLoadsAndStores;
476 SmallVector<Instruction*, 8> VolatileLoadsAndStores;
477 SmallVector<Instruction*, 8> AtomicAccesses;
478 SmallVector<Instruction*, 8> MemIntrinCalls;
481 bool HasAtomic = false;
482 bool HasVolatile = false;
483 const DataLayout &DL = F.getParent()->getDataLayout();
486 for (auto &Inst : BB) {
487 if ( (&Inst)->isAtomic() || isAtomicCall(&Inst) ) {
488 AtomicAccesses.push_back(&Inst);
490 } else if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst)) {
491 LoadInst *LI = dyn_cast<LoadInst>(&Inst);
492 StoreInst *SI = dyn_cast<StoreInst>(&Inst);
493 bool isVolatile = ( LI ? LI->isVolatile() : SI->isVolatile() );
496 VolatileLoadsAndStores.push_back(&Inst);
499 LocalLoadsAndStores.push_back(&Inst);
500 } else if (isa<CallInst>(Inst) || isa<InvokeInst>(Inst)) {
501 if (isa<MemIntrinsic>(Inst))
502 MemIntrinCalls.push_back(&Inst);
504 /*if (CallInst *CI = dyn_cast<CallInst>(&Inst))
505 maybeMarkSanitizerLibraryCallNoBuiltin(CI, TLI);
508 chooseInstructionsToInstrument(LocalLoadsAndStores, AllLoadsAndStores,
513 chooseInstructionsToInstrument(LocalLoadsAndStores, AllLoadsAndStores, DL);
516 for (auto Inst : AllLoadsAndStores) {
517 Res |= instrumentLoadOrStore(Inst, DL);
520 for (auto Inst : VolatileLoadsAndStores) {
521 Res |= instrumentVolatile(Inst, DL);
524 for (auto Inst : AtomicAccesses) {
525 Res |= instrumentAtomic(Inst, DL);
528 for (auto Inst : MemIntrinCalls) {
529 Res |= instrumentMemIntrinsic(Inst);
532 // Only instrument functions that contain atomics or volatiles
533 if (Res && ( HasAtomic || HasVolatile) ) {
534 IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
536 Value *ReturnAddress = IRB.CreateCall(
537 Intrinsic::getDeclaration(F.getParent(), Intrinsic::returnaddress),
541 Value * FuncName = IRB.CreateGlobalStringPtr(F.getName());
542 IRB.CreateCall(CDSFuncEntry, FuncName);
544 EscapeEnumerator EE(F, "cds_cleanup", true);
545 while (IRBuilder<> *AtExit = EE.Next()) {
546 AtExit->CreateCall(CDSFuncExit, FuncName);
555 bool CDSPass::instrumentLoadOrStore(Instruction *I,
556 const DataLayout &DL) {
558 bool IsWrite = isa<StoreInst>(*I);
559 Value *Addr = IsWrite
560 ? cast<StoreInst>(I)->getPointerOperand()
561 : cast<LoadInst>(I)->getPointerOperand();
563 // swifterror memory addresses are mem2reg promoted by instruction selection.
564 // As such they cannot have regular uses like an instrumentation function and
565 // it makes no sense to track them as memory.
566 if (Addr->isSwiftError())
569 int Idx = getMemoryAccessFuncIndex(Addr, DL);
573 // not supported by CDS yet
574 /* if (IsWrite && isVtableAccess(I)) {
575 LLVM_DEBUG(dbgs() << " VPTR : " << *I << "\n");
576 Value *StoredValue = cast<StoreInst>(I)->getValueOperand();
577 // StoredValue may be a vector type if we are storing several vptrs at once.
578 // In this case, just take the first element of the vector since this is
579 // enough to find vptr races.
580 if (isa<VectorType>(StoredValue->getType()))
581 StoredValue = IRB.CreateExtractElement(
582 StoredValue, ConstantInt::get(IRB.getInt32Ty(), 0));
583 if (StoredValue->getType()->isIntegerTy())
584 StoredValue = IRB.CreateIntToPtr(StoredValue, IRB.getInt8PtrTy());
585 // Call TsanVptrUpdate.
586 IRB.CreateCall(TsanVptrUpdate,
587 {IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()),
588 IRB.CreatePointerCast(StoredValue, IRB.getInt8PtrTy())});
589 NumInstrumentedVtableWrites++;
593 if (!IsWrite && isVtableAccess(I)) {
594 IRB.CreateCall(TsanVptrLoad,
595 IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()));
596 NumInstrumentedVtableReads++;
601 Value *OnAccessFunc = nullptr;
602 OnAccessFunc = IsWrite ? CDSStore[Idx] : CDSLoad[Idx];
604 Type *ArgType = IRB.CreatePointerCast(Addr, Addr->getType())->getType();
606 if ( ArgType != Int8PtrTy && ArgType != Int16PtrTy &&
607 ArgType != Int32PtrTy && ArgType != Int64PtrTy ) {
608 // if other types of load or stores are passed in
612 IRB.CreateCall(OnAccessFunc, IRB.CreatePointerCast(Addr, Addr->getType()));
613 if (IsWrite) NumInstrumentedWrites++;
614 else NumInstrumentedReads++;
618 bool CDSPass::instrumentVolatile(Instruction * I, const DataLayout &DL) {
620 Value *position = getPosition(I, IRB);
622 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
623 assert( LI->isVolatile() );
624 Value *Addr = LI->getPointerOperand();
625 int Idx=getMemoryAccessFuncIndex(Addr, DL);
629 Value *args[] = {Addr, position};
630 Instruction* funcInst = CallInst::Create(CDSVolatileLoad[Idx], args);
631 ReplaceInstWithInst(LI, funcInst);
632 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
633 assert( SI->isVolatile() );
634 Value *Addr = SI->getPointerOperand();
635 int Idx=getMemoryAccessFuncIndex(Addr, DL);
639 Value *val = SI->getValueOperand();
640 Value *args[] = {Addr, val, position};
641 Instruction* funcInst = CallInst::Create(CDSVolatileStore[Idx], args);
642 ReplaceInstWithInst(SI, funcInst);
650 bool CDSPass::instrumentMemIntrinsic(Instruction *I) {
652 if (MemSetInst *M = dyn_cast<MemSetInst>(I)) {
655 {IRB.CreatePointerCast(M->getArgOperand(0), IRB.getInt8PtrTy()),
656 IRB.CreateIntCast(M->getArgOperand(1), IRB.getInt32Ty(), false),
657 IRB.CreateIntCast(M->getArgOperand(2), IntPtrTy, false)});
658 I->eraseFromParent();
659 } else if (MemTransferInst *M = dyn_cast<MemTransferInst>(I)) {
661 isa<MemCpyInst>(M) ? MemcpyFn : MemmoveFn,
662 {IRB.CreatePointerCast(M->getArgOperand(0), IRB.getInt8PtrTy()),
663 IRB.CreatePointerCast(M->getArgOperand(1), IRB.getInt8PtrTy()),
664 IRB.CreateIntCast(M->getArgOperand(2), IntPtrTy, false)});
665 I->eraseFromParent();
670 bool CDSPass::instrumentAtomic(Instruction * I, const DataLayout &DL) {
673 if (auto *CI = dyn_cast<CallInst>(I)) {
674 return instrumentAtomicCall(CI, DL);
677 Value *position = getPosition(I, IRB);
679 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
680 Value *Addr = LI->getPointerOperand();
681 int Idx=getMemoryAccessFuncIndex(Addr, DL);
685 int atomic_order_index = getAtomicOrderIndex(LI->getOrdering());
686 Value *order = ConstantInt::get(OrdTy, atomic_order_index);
687 Value *args[] = {Addr, order, position};
688 Instruction* funcInst = CallInst::Create(CDSAtomicLoad[Idx], args);
689 ReplaceInstWithInst(LI, funcInst);
690 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
691 Value *Addr = SI->getPointerOperand();
692 int Idx=getMemoryAccessFuncIndex(Addr, DL);
696 int atomic_order_index = getAtomicOrderIndex(SI->getOrdering());
697 Value *val = SI->getValueOperand();
698 Value *order = ConstantInt::get(OrdTy, atomic_order_index);
699 Value *args[] = {Addr, val, order, position};
700 Instruction* funcInst = CallInst::Create(CDSAtomicStore[Idx], args);
701 ReplaceInstWithInst(SI, funcInst);
702 } else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I)) {
703 Value *Addr = RMWI->getPointerOperand();
704 int Idx=getMemoryAccessFuncIndex(Addr, DL);
708 int atomic_order_index = getAtomicOrderIndex(RMWI->getOrdering());
709 Value *val = RMWI->getValOperand();
710 Value *order = ConstantInt::get(OrdTy, atomic_order_index);
711 Value *args[] = {Addr, val, order, position};
712 Instruction* funcInst = CallInst::Create(CDSAtomicRMW[RMWI->getOperation()][Idx], args);
713 ReplaceInstWithInst(RMWI, funcInst);
714 } else if (AtomicCmpXchgInst *CASI = dyn_cast<AtomicCmpXchgInst>(I)) {
715 IRBuilder<> IRB(CASI);
717 Value *Addr = CASI->getPointerOperand();
718 int Idx=getMemoryAccessFuncIndex(Addr, DL);
722 const unsigned ByteSize = 1U << Idx;
723 const unsigned BitSize = ByteSize * 8;
724 Type *Ty = Type::getIntNTy(IRB.getContext(), BitSize);
725 Type *PtrTy = Ty->getPointerTo();
727 Value *CmpOperand = IRB.CreateBitOrPointerCast(CASI->getCompareOperand(), Ty);
728 Value *NewOperand = IRB.CreateBitOrPointerCast(CASI->getNewValOperand(), Ty);
730 int atomic_order_index_succ = getAtomicOrderIndex(CASI->getSuccessOrdering());
731 int atomic_order_index_fail = getAtomicOrderIndex(CASI->getFailureOrdering());
732 Value *order_succ = ConstantInt::get(OrdTy, atomic_order_index_succ);
733 Value *order_fail = ConstantInt::get(OrdTy, atomic_order_index_fail);
735 Value *Args[] = {IRB.CreatePointerCast(Addr, PtrTy),
736 CmpOperand, NewOperand,
737 order_succ, order_fail, position};
739 CallInst *funcInst = IRB.CreateCall(CDSAtomicCAS_V1[Idx], Args);
740 Value *Success = IRB.CreateICmpEQ(funcInst, CmpOperand);
742 Value *OldVal = funcInst;
743 Type *OrigOldValTy = CASI->getNewValOperand()->getType();
744 if (Ty != OrigOldValTy) {
745 // The value is a pointer, so we need to cast the return value.
746 OldVal = IRB.CreateIntToPtr(funcInst, OrigOldValTy);
750 IRB.CreateInsertValue(UndefValue::get(CASI->getType()), OldVal, 0);
751 Res = IRB.CreateInsertValue(Res, Success, 1);
753 I->replaceAllUsesWith(Res);
754 I->eraseFromParent();
755 } else if (FenceInst *FI = dyn_cast<FenceInst>(I)) {
756 int atomic_order_index = getAtomicOrderIndex(FI->getOrdering());
757 Value *order = ConstantInt::get(OrdTy, atomic_order_index);
758 Value *Args[] = {order, position};
760 CallInst *funcInst = CallInst::Create(CDSAtomicThreadFence, Args);
761 ReplaceInstWithInst(FI, funcInst);
762 // errs() << "Thread Fences replaced\n";
767 bool CDSPass::isAtomicCall(Instruction *I) {
768 if ( auto *CI = dyn_cast<CallInst>(I) ) {
769 Function *fun = CI->getCalledFunction();
773 StringRef funName = fun->getName();
775 // TODO: come up with better rules for function name checking
776 for (StringRef name : AtomicFuncNames) {
777 if ( funName.contains(name) )
781 for (StringRef PartialName : PartialAtomicFuncNames) {
782 if (funName.contains(PartialName) &&
783 funName.contains("atomic") )
791 bool CDSPass::instrumentAtomicCall(CallInst *CI, const DataLayout &DL) {
793 Function *fun = CI->getCalledFunction();
794 StringRef funName = fun->getName();
795 std::vector<Value *> parameters;
797 User::op_iterator begin = CI->arg_begin();
798 User::op_iterator end = CI->arg_end();
799 for (User::op_iterator it = begin; it != end; ++it) {
801 parameters.push_back(param);
804 // obtain source line number of the CallInst
805 Value *position = getPosition(CI, IRB);
807 // the pointer to the address is always the first argument
808 Value *OrigPtr = parameters[0];
810 int Idx = getMemoryAccessFuncIndex(OrigPtr, DL);
814 const unsigned ByteSize = 1U << Idx;
815 const unsigned BitSize = ByteSize * 8;
816 Type *Ty = Type::getIntNTy(IRB.getContext(), BitSize);
817 Type *PtrTy = Ty->getPointerTo();
819 // atomic_init; args = {obj, order}
820 if (funName.contains("atomic_init")) {
821 Value *OrigVal = parameters[1];
823 Value *ptr = IRB.CreatePointerCast(OrigPtr, PtrTy);
825 if (OrigVal->getType()->isPtrOrPtrVectorTy())
826 val = IRB.CreatePointerCast(OrigVal, Ty);
828 val = IRB.CreateIntCast(OrigVal, Ty, true);
830 Value *args[] = {ptr, val, position};
832 Instruction* funcInst = CallInst::Create(CDSAtomicInit[Idx], args);
833 ReplaceInstWithInst(CI, funcInst);
838 // atomic_load; args = {obj, order}
839 if (funName.contains("atomic_load")) {
840 bool isExplicit = funName.contains("atomic_load_explicit");
842 Value *ptr = IRB.CreatePointerCast(OrigPtr, PtrTy);
845 order = IRB.CreateBitOrPointerCast(parameters[1], OrdTy);
847 order = ConstantInt::get(OrdTy,
848 (int) AtomicOrderingCABI::seq_cst);
849 Value *args[] = {ptr, order, position};
851 Instruction* funcInst = CallInst::Create(CDSAtomicLoad[Idx], args);
852 ReplaceInstWithInst(CI, funcInst);
855 } else if (funName.contains("atomic") &&
856 funName.contains("load") ) {
857 // does this version of call always have an atomic order as an argument?
858 Value *ptr = IRB.CreatePointerCast(OrigPtr, PtrTy);
859 Value *order = IRB.CreateBitOrPointerCast(parameters[1], OrdTy);
860 Value *args[] = {ptr, order, position};
862 if (!CI->getType()->isPointerTy()) {
866 CallInst *funcInst = IRB.CreateCall(CDSAtomicLoad[Idx], args);
867 Value *RetVal = IRB.CreateIntToPtr(funcInst, CI->getType());
869 CI->replaceAllUsesWith(RetVal);
870 CI->eraseFromParent();
875 // atomic_store; args = {obj, val, order}
876 if (funName.contains("atomic_store")) {
877 bool isExplicit = funName.contains("atomic_store_explicit");
878 Value *OrigVal = parameters[1];
880 Value *ptr = IRB.CreatePointerCast(OrigPtr, PtrTy);
881 Value *val = IRB.CreatePointerCast(OrigVal, Ty);
884 order = IRB.CreateBitOrPointerCast(parameters[2], OrdTy);
886 order = ConstantInt::get(OrdTy,
887 (int) AtomicOrderingCABI::seq_cst);
888 Value *args[] = {ptr, val, order, position};
890 Instruction* funcInst = CallInst::Create(CDSAtomicStore[Idx], args);
891 ReplaceInstWithInst(CI, funcInst);
894 } else if (funName.contains("atomic") &&
895 funName.contains("store") ) {
896 // does this version of call always have an atomic order as an argument?
897 Value *OrigVal = parameters[1];
899 Value *ptr = IRB.CreatePointerCast(OrigPtr, PtrTy);
901 if (OrigVal->getType()->isPtrOrPtrVectorTy())
902 val = IRB.CreatePointerCast(OrigVal, Ty);
904 val = IRB.CreateIntCast(OrigVal, Ty, true);
906 Value *order = IRB.CreateBitOrPointerCast(parameters[2], OrdTy);
907 Value *args[] = {ptr, val, order, position};
909 Instruction* funcInst = CallInst::Create(CDSAtomicStore[Idx], args);
910 ReplaceInstWithInst(CI, funcInst);
915 // atomic_fetch_*; args = {obj, val, order}
916 if (funName.contains("atomic_fetch_") ||
917 funName.contains("atomic_exchange")) {
919 /* TODO: implement stricter function name checking */
920 if (funName.contains("non"))
923 bool isExplicit = funName.contains("_explicit");
924 Value *OrigVal = parameters[1];
927 if ( funName.contains("_fetch_add") )
928 op = AtomicRMWInst::Add;
929 else if ( funName.contains("_fetch_sub") )
930 op = AtomicRMWInst::Sub;
931 else if ( funName.contains("_fetch_and") )
932 op = AtomicRMWInst::And;
933 else if ( funName.contains("_fetch_or") )
934 op = AtomicRMWInst::Or;
935 else if ( funName.contains("_fetch_xor") )
936 op = AtomicRMWInst::Xor;
937 else if ( funName.contains("atomic_exchange") )
938 op = AtomicRMWInst::Xchg;
940 errs() << "Unknown atomic read-modify-write operation\n";
944 Value *ptr = IRB.CreatePointerCast(OrigPtr, PtrTy);
946 if (OrigVal->getType()->isPtrOrPtrVectorTy())
947 val = IRB.CreatePointerCast(OrigVal, Ty);
949 val = IRB.CreateIntCast(OrigVal, Ty, true);
953 order = IRB.CreateBitOrPointerCast(parameters[2], OrdTy);
955 order = ConstantInt::get(OrdTy,
956 (int) AtomicOrderingCABI::seq_cst);
957 Value *args[] = {ptr, val, order, position};
959 Instruction* funcInst = CallInst::Create(CDSAtomicRMW[op][Idx], args);
960 ReplaceInstWithInst(CI, funcInst);
963 } else if (funName.contains("fetch")) {
964 errs() << "atomic fetch captured. Not implemented yet. ";
965 errs() << "See source file :";
966 getPosition(CI, IRB, true);
968 } else if (funName.contains("exchange") &&
969 !funName.contains("compare_exchange") ) {
970 if (CI->getType()->isPointerTy()) {
971 // Can not deal with this now
972 errs() << "atomic exchange captured. Not implemented yet. ";
973 errs() << "See source file :";
974 getPosition(CI, IRB, true);
979 Value *OrigVal = parameters[1];
981 Value *ptr = IRB.CreatePointerCast(OrigPtr, PtrTy);
983 if (OrigVal->getType()->isPtrOrPtrVectorTy())
984 val = IRB.CreatePointerCast(OrigVal, Ty);
986 val = IRB.CreateIntCast(OrigVal, Ty, true);
988 Value *order = IRB.CreateBitOrPointerCast(parameters[2], OrdTy);
989 Value *args[] = {ptr, val, order, position};
990 int op = AtomicRMWInst::Xchg;
992 Instruction* funcInst = CallInst::Create(CDSAtomicRMW[op][Idx], args);
993 ReplaceInstWithInst(CI, funcInst);
996 /* atomic_compare_exchange_*;
997 args = {obj, expected, new value, order1, order2}
999 if ( funName.contains("atomic_compare_exchange_") ) {
1000 bool isExplicit = funName.contains("_explicit");
1002 Value *Addr = IRB.CreatePointerCast(OrigPtr, PtrTy);
1003 Value *CmpOperand = IRB.CreatePointerCast(parameters[1], PtrTy);
1004 Value *NewOperand = IRB.CreateBitOrPointerCast(parameters[2], Ty);
1006 Value *order_succ, *order_fail;
1008 order_succ = IRB.CreateBitOrPointerCast(parameters[3], OrdTy);
1010 if (parameters.size() > 4) {
1011 order_fail = IRB.CreateBitOrPointerCast(parameters[4], OrdTy);
1013 /* The failure order is not provided */
1014 order_fail = order_succ;
1015 ConstantInt * order_succ_cast = dyn_cast<ConstantInt>(order_succ);
1016 int index = order_succ_cast->getSExtValue();
1018 order_fail = ConstantInt::get(OrdTy,
1019 AtomicCasFailureOrderIndex(index));
1022 order_succ = ConstantInt::get(OrdTy,
1023 (int) AtomicOrderingCABI::seq_cst);
1024 order_fail = ConstantInt::get(OrdTy,
1025 (int) AtomicOrderingCABI::seq_cst);
1028 Value *args[] = {Addr, CmpOperand, NewOperand,
1029 order_succ, order_fail, position};
1031 Instruction* funcInst = CallInst::Create(CDSAtomicCAS_V2[Idx], args);
1032 ReplaceInstWithInst(CI, funcInst);
1035 } else if ( funName.contains("compare_exchange_strong") ||
1036 funName.contains("compare_exchange_weak") ) {
1037 Value *Addr = IRB.CreatePointerCast(OrigPtr, PtrTy);
1038 Value *CmpOperand = IRB.CreatePointerCast(parameters[1], PtrTy);
1039 Value *NewOperand = IRB.CreateBitOrPointerCast(parameters[2], Ty);
1041 Value *order_succ, *order_fail;
1042 order_succ = IRB.CreateBitOrPointerCast(parameters[3], OrdTy);
1044 if (parameters.size() > 4) {
1045 order_fail = IRB.CreateBitOrPointerCast(parameters[4], OrdTy);
1047 /* The failure order is not provided */
1048 order_fail = order_succ;
1049 ConstantInt * order_succ_cast = dyn_cast<ConstantInt>(order_succ);
1050 int index = order_succ_cast->getSExtValue();
1052 order_fail = ConstantInt::get(OrdTy,
1053 AtomicCasFailureOrderIndex(index));
1056 Value *args[] = {Addr, CmpOperand, NewOperand,
1057 order_succ, order_fail, position};
1058 Instruction* funcInst = CallInst::Create(CDSAtomicCAS_V2[Idx], args);
1059 ReplaceInstWithInst(CI, funcInst);
1067 int CDSPass::getMemoryAccessFuncIndex(Value *Addr,
1068 const DataLayout &DL) {
1069 Type *OrigPtrTy = Addr->getType();
1070 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
1071 assert(OrigTy->isSized());
1072 uint32_t TypeSize = DL.getTypeStoreSizeInBits(OrigTy);
1073 if (TypeSize != 8 && TypeSize != 16 &&
1074 TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
1075 NumAccessesWithBadSize++;
1076 // Ignore all unusual sizes.
1079 size_t Idx = countTrailingZeros(TypeSize / 8);
1080 //assert(Idx < kNumberOfAccessSizes);
1081 if (Idx >= kNumberOfAccessSizes) {
1088 char CDSPass::ID = 0;
1090 // Automatically enable the pass.
1091 static void registerCDSPass(const PassManagerBuilder &,
1092 legacy::PassManagerBase &PM) {
1093 PM.add(new CDSPass());
1096 /* Enable the pass when opt level is greater than 0 */
1097 static RegisterStandardPasses
1098 RegisterMyPass1(PassManagerBuilder::EP_OptimizerLast,
1101 /* Enable the pass when opt level is 0 */
1102 static RegisterStandardPasses
1103 RegisterMyPass2(PassManagerBuilder::EP_EnabledOnOptLevel0,