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/LLVMContext.h"
33 #include "llvm/IR/LegacyPassManager.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/IR/PassManager.h"
36 #include "llvm/Pass.h"
37 #include "llvm/ProfileData/InstrProf.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Support/AtomicOrdering.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Transforms/Scalar.h"
42 #include "llvm/Transforms/Utils/Local.h"
43 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
44 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
45 #include "llvm/Transforms/Utils/EscapeEnumerator.h"
50 #define DEBUG_TYPE "CDS"
51 #include <llvm/IR/DebugLoc.h>
53 Value *getPosition( Instruction * I, IRBuilder <> IRB, bool print = false)
55 const DebugLoc & debug_location = I->getDebugLoc ();
56 std::string position_string;
58 llvm::raw_string_ostream position_stream (position_string);
59 debug_location . print (position_stream);
63 errs() << position_string << "\n";
66 return IRB.CreateGlobalStringPtr (position_string);
69 STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
70 STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
71 STATISTIC(NumAccessesWithBadSize, "Number of accesses with bad size");
72 // STATISTIC(NumInstrumentedVtableWrites, "Number of vtable ptr writes");
73 // STATISTIC(NumInstrumentedVtableReads, "Number of vtable ptr reads");
75 STATISTIC(NumOmittedReadsBeforeWrite,
76 "Number of reads ignored due to following writes");
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");
91 static const size_t kNumberOfAccessSizes = 4;
93 int getAtomicOrderIndex(AtomicOrdering order){
95 case AtomicOrdering::Monotonic:
96 return (int)AtomicOrderingCABI::relaxed;
97 // case AtomicOrdering::Consume: // not specified yet
98 // return AtomicOrderingCABI::consume;
99 case AtomicOrdering::Acquire:
100 return (int)AtomicOrderingCABI::acquire;
101 case AtomicOrdering::Release:
102 return (int)AtomicOrderingCABI::release;
103 case AtomicOrdering::AcquireRelease:
104 return (int)AtomicOrderingCABI::acq_rel;
105 case AtomicOrdering::SequentiallyConsistent:
106 return (int)AtomicOrderingCABI::seq_cst;
108 // unordered or Not Atomic
114 struct CDSPass : public FunctionPass {
116 CDSPass() : FunctionPass(ID) {}
117 bool runOnFunction(Function &F) override;
120 void initializeCallbacks(Module &M);
121 bool instrumentLoadOrStore(Instruction *I, const DataLayout &DL);
122 bool isAtomicCall(Instruction *I);
123 bool instrumentAtomic(Instruction *I, const DataLayout &DL);
124 bool instrumentAtomicCall(CallInst *CI, const DataLayout &DL);
125 void chooseInstructionsToInstrument(SmallVectorImpl<Instruction *> &Local,
126 SmallVectorImpl<Instruction *> &All,
127 const DataLayout &DL);
128 bool addrPointsToConstantData(Value *Addr);
129 int getMemoryAccessFuncIndex(Value *Addr, const DataLayout &DL);
131 // Callbacks to run-time library are computed in doInitialization.
132 Constant * CDSFuncEntry;
133 Constant * CDSFuncExit;
135 Constant * CDSLoad[kNumberOfAccessSizes];
136 Constant * CDSStore[kNumberOfAccessSizes];
137 Constant * CDSAtomicInit[kNumberOfAccessSizes];
138 Constant * CDSAtomicLoad[kNumberOfAccessSizes];
139 Constant * CDSAtomicStore[kNumberOfAccessSizes];
140 Constant * CDSAtomicRMW[AtomicRMWInst::LAST_BINOP + 1][kNumberOfAccessSizes];
141 Constant * CDSAtomicCAS_V1[kNumberOfAccessSizes];
142 Constant * CDSAtomicCAS_V2[kNumberOfAccessSizes];
143 Constant * CDSAtomicThreadFence;
145 std::vector<StringRef> AtomicFuncNames;
146 std::vector<StringRef> PartialAtomicFuncNames;
150 static bool isVtableAccess(Instruction *I) {
151 if (MDNode *Tag = I->getMetadata(LLVMContext::MD_tbaa))
152 return Tag->isTBAAVtableAccess();
156 void CDSPass::initializeCallbacks(Module &M) {
157 LLVMContext &Ctx = M.getContext();
159 Type * Int1Ty = Type::getInt1Ty(Ctx);
160 OrdTy = Type::getInt32Ty(Ctx);
162 Int8PtrTy = Type::getInt8PtrTy(Ctx);
163 Int16PtrTy = Type::getInt16PtrTy(Ctx);
164 Int32PtrTy = Type::getInt32PtrTy(Ctx);
165 Int64PtrTy = Type::getInt64PtrTy(Ctx);
167 VoidTy = Type::getVoidTy(Ctx);
169 CDSFuncEntry = M.getOrInsertFunction("cds_func_entry",
171 CDSFuncExit = M.getOrInsertFunction("cds_func_exit",
174 // Get the function to call from our untime library.
175 for (unsigned i = 0; i < kNumberOfAccessSizes; i++) {
176 const unsigned ByteSize = 1U << i;
177 const unsigned BitSize = ByteSize * 8;
179 std::string ByteSizeStr = utostr(ByteSize);
180 std::string BitSizeStr = utostr(BitSize);
182 Type *Ty = Type::getIntNTy(Ctx, BitSize);
183 Type *PtrTy = Ty->getPointerTo();
185 // uint8_t cds_atomic_load8 (void * obj, int atomic_index)
186 // void cds_atomic_store8 (void * obj, int atomic_index, uint8_t val)
187 SmallString<32> LoadName("cds_load" + BitSizeStr);
188 SmallString<32> StoreName("cds_store" + BitSizeStr);
189 SmallString<32> AtomicInitName("cds_atomic_init" + BitSizeStr);
190 SmallString<32> AtomicLoadName("cds_atomic_load" + BitSizeStr);
191 SmallString<32> AtomicStoreName("cds_atomic_store" + BitSizeStr);
193 CDSLoad[i] = M.getOrInsertFunction(LoadName, VoidTy, PtrTy);
194 CDSStore[i] = M.getOrInsertFunction(StoreName, VoidTy, PtrTy);
195 CDSAtomicInit[i] = M.getOrInsertFunction(AtomicInitName,
196 VoidTy, PtrTy, Ty, Int8PtrTy);
197 CDSAtomicLoad[i] = M.getOrInsertFunction(AtomicLoadName,
198 Ty, PtrTy, OrdTy, Int8PtrTy);
199 CDSAtomicStore[i] = M.getOrInsertFunction(AtomicStoreName,
200 VoidTy, PtrTy, Ty, OrdTy, Int8PtrTy);
202 for (int op = AtomicRMWInst::FIRST_BINOP;
203 op <= AtomicRMWInst::LAST_BINOP; ++op) {
204 CDSAtomicRMW[op][i] = nullptr;
205 std::string NamePart;
207 if (op == AtomicRMWInst::Xchg)
208 NamePart = "_exchange";
209 else if (op == AtomicRMWInst::Add)
210 NamePart = "_fetch_add";
211 else if (op == AtomicRMWInst::Sub)
212 NamePart = "_fetch_sub";
213 else if (op == AtomicRMWInst::And)
214 NamePart = "_fetch_and";
215 else if (op == AtomicRMWInst::Or)
216 NamePart = "_fetch_or";
217 else if (op == AtomicRMWInst::Xor)
218 NamePart = "_fetch_xor";
222 SmallString<32> AtomicRMWName("cds_atomic" + NamePart + BitSizeStr);
223 CDSAtomicRMW[op][i] = M.getOrInsertFunction(AtomicRMWName,
224 Ty, PtrTy, Ty, OrdTy, Int8PtrTy);
227 // only supportes strong version
228 SmallString<32> AtomicCASName_V1("cds_atomic_compare_exchange" + BitSizeStr + "_v1");
229 SmallString<32> AtomicCASName_V2("cds_atomic_compare_exchange" + BitSizeStr + "_v2");
230 CDSAtomicCAS_V1[i] = M.getOrInsertFunction(AtomicCASName_V1,
231 Ty, PtrTy, Ty, Ty, OrdTy, OrdTy, Int8PtrTy);
232 CDSAtomicCAS_V2[i] = M.getOrInsertFunction(AtomicCASName_V2,
233 Int1Ty, PtrTy, PtrTy, Ty, OrdTy, OrdTy, Int8PtrTy);
236 CDSAtomicThreadFence = M.getOrInsertFunction("cds_atomic_thread_fence",
237 VoidTy, OrdTy, Int8PtrTy);
240 static bool shouldInstrumentReadWriteFromAddress(const Module *M, Value *Addr) {
241 // Peel off GEPs and BitCasts.
242 Addr = Addr->stripInBoundsOffsets();
244 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
245 if (GV->hasSection()) {
246 StringRef SectionName = GV->getSection();
247 // Check if the global is in the PGO counters section.
248 auto OF = Triple(M->getTargetTriple()).getObjectFormat();
249 if (SectionName.endswith(
250 getInstrProfSectionName(IPSK_cnts, OF, /*AddSegmentInfo=*/false)))
254 // Check if the global is private gcov data.
255 if (GV->getName().startswith("__llvm_gcov") ||
256 GV->getName().startswith("__llvm_gcda"))
260 // Do not instrument acesses from different address spaces; we cannot deal
263 Type *PtrTy = cast<PointerType>(Addr->getType()->getScalarType());
264 if (PtrTy->getPointerAddressSpace() != 0)
271 bool CDSPass::addrPointsToConstantData(Value *Addr) {
272 // If this is a GEP, just analyze its pointer operand.
273 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Addr))
274 Addr = GEP->getPointerOperand();
276 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
277 if (GV->isConstant()) {
278 // Reads from constant globals can not race with any writes.
279 NumOmittedReadsFromConstantGlobals++;
282 } else if (LoadInst *L = dyn_cast<LoadInst>(Addr)) {
283 if (isVtableAccess(L)) {
284 // Reads from a vtable pointer can not race with any writes.
285 NumOmittedReadsFromVtable++;
292 bool CDSPass::runOnFunction(Function &F) {
293 if (F.getName() == "main") {
294 F.setName("user_main");
295 errs() << "main replaced by user_main\n";
299 initializeCallbacks( *F.getParent() );
303 "atomic_init", "atomic_load", "atomic_store",
304 "atomic_fetch_", "atomic_exchange", "atomic_compare_exchange_"
307 PartialAtomicFuncNames =
309 "load", "store", "fetch", "exchange", "compare_exchange_"
312 SmallVector<Instruction*, 8> AllLoadsAndStores;
313 SmallVector<Instruction*, 8> LocalLoadsAndStores;
314 SmallVector<Instruction*, 8> AtomicAccesses;
316 std::vector<Instruction *> worklist;
319 bool HasAtomic = false;
320 const DataLayout &DL = F.getParent()->getDataLayout();
322 // errs() << "--- " << F.getName() << "---\n";
326 if ( (&I)->isAtomic() || isAtomicCall(&I) ) {
327 AtomicAccesses.push_back(&I);
329 } else if (isa<LoadInst>(I) || isa<StoreInst>(I)) {
330 LocalLoadsAndStores.push_back(&I);
331 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
332 // not implemented yet
336 chooseInstructionsToInstrument(LocalLoadsAndStores, AllLoadsAndStores, DL);
339 for (auto Inst : AllLoadsAndStores) {
340 Res |= instrumentLoadOrStore(Inst, DL);
343 for (auto Inst : AtomicAccesses) {
344 Res |= instrumentAtomic(Inst, DL);
347 // only instrument functions that contain atomics
348 if (Res && HasAtomic) {
349 IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
351 Value *ReturnAddress = IRB.CreateCall(
352 Intrinsic::getDeclaration(F.getParent(), Intrinsic::returnaddress),
356 Value * FuncName = IRB.CreateGlobalStringPtr(F.getName());
357 IRB.CreateCall(CDSFuncEntry, FuncName);
359 EscapeEnumerator EE(F, "cds_cleanup", true);
360 while (IRBuilder<> *AtExit = EE.Next()) {
361 AtExit->CreateCall(CDSFuncExit, FuncName);
371 void CDSPass::chooseInstructionsToInstrument(
372 SmallVectorImpl<Instruction *> &Local, SmallVectorImpl<Instruction *> &All,
373 const DataLayout &DL) {
374 SmallPtrSet<Value*, 8> WriteTargets;
375 // Iterate from the end.
376 for (Instruction *I : reverse(Local)) {
377 if (StoreInst *Store = dyn_cast<StoreInst>(I)) {
378 Value *Addr = Store->getPointerOperand();
379 if (!shouldInstrumentReadWriteFromAddress(I->getModule(), Addr))
381 WriteTargets.insert(Addr);
383 LoadInst *Load = cast<LoadInst>(I);
384 Value *Addr = Load->getPointerOperand();
385 if (!shouldInstrumentReadWriteFromAddress(I->getModule(), Addr))
387 if (WriteTargets.count(Addr)) {
388 // We will write to this temp, so no reason to analyze the read.
389 NumOmittedReadsBeforeWrite++;
392 if (addrPointsToConstantData(Addr)) {
393 // Addr points to some constant data -- it can not race with any writes.
397 Value *Addr = isa<StoreInst>(*I)
398 ? cast<StoreInst>(I)->getPointerOperand()
399 : cast<LoadInst>(I)->getPointerOperand();
400 if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
401 !PointerMayBeCaptured(Addr, true, true)) {
402 // The variable is addressable but not captured, so it cannot be
403 // referenced from a different thread and participate in a data race
404 // (see llvm/Analysis/CaptureTracking.h for details).
405 NumOmittedNonCaptured++;
414 bool CDSPass::instrumentLoadOrStore(Instruction *I,
415 const DataLayout &DL) {
417 bool IsWrite = isa<StoreInst>(*I);
418 Value *Addr = IsWrite
419 ? cast<StoreInst>(I)->getPointerOperand()
420 : cast<LoadInst>(I)->getPointerOperand();
422 // swifterror memory addresses are mem2reg promoted by instruction selection.
423 // As such they cannot have regular uses like an instrumentation function and
424 // it makes no sense to track them as memory.
425 if (Addr->isSwiftError())
428 int Idx = getMemoryAccessFuncIndex(Addr, DL);
432 // not supported by CDS yet
433 /* if (IsWrite && isVtableAccess(I)) {
434 LLVM_DEBUG(dbgs() << " VPTR : " << *I << "\n");
435 Value *StoredValue = cast<StoreInst>(I)->getValueOperand();
436 // StoredValue may be a vector type if we are storing several vptrs at once.
437 // In this case, just take the first element of the vector since this is
438 // enough to find vptr races.
439 if (isa<VectorType>(StoredValue->getType()))
440 StoredValue = IRB.CreateExtractElement(
441 StoredValue, ConstantInt::get(IRB.getInt32Ty(), 0));
442 if (StoredValue->getType()->isIntegerTy())
443 StoredValue = IRB.CreateIntToPtr(StoredValue, IRB.getInt8PtrTy());
444 // Call TsanVptrUpdate.
445 IRB.CreateCall(TsanVptrUpdate,
446 {IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()),
447 IRB.CreatePointerCast(StoredValue, IRB.getInt8PtrTy())});
448 NumInstrumentedVtableWrites++;
452 if (!IsWrite && isVtableAccess(I)) {
453 IRB.CreateCall(TsanVptrLoad,
454 IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()));
455 NumInstrumentedVtableReads++;
460 Value *OnAccessFunc = nullptr;
461 OnAccessFunc = IsWrite ? CDSStore[Idx] : CDSLoad[Idx];
463 Type *ArgType = IRB.CreatePointerCast(Addr, Addr->getType())->getType();
465 if ( ArgType != Int8PtrTy && ArgType != Int16PtrTy &&
466 ArgType != Int32PtrTy && ArgType != Int64PtrTy ) {
467 // if other types of load or stores are passed in
470 IRB.CreateCall(OnAccessFunc, IRB.CreatePointerCast(Addr, Addr->getType()));
471 if (IsWrite) NumInstrumentedWrites++;
472 else NumInstrumentedReads++;
476 bool CDSPass::instrumentAtomic(Instruction * I, const DataLayout &DL) {
479 // errs() << "instrumenting: " << *I << "\n";
481 if (auto *CI = dyn_cast<CallInst>(I)) {
482 return instrumentAtomicCall(CI, DL);
485 Value *position = getPosition(I, IRB);
487 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
488 Value *Addr = LI->getPointerOperand();
489 int Idx=getMemoryAccessFuncIndex(Addr, DL);
493 int atomic_order_index = getAtomicOrderIndex(LI->getOrdering());
494 Value *order = ConstantInt::get(OrdTy, atomic_order_index);
495 Value *args[] = {Addr, order, position};
496 Instruction* funcInst=CallInst::Create(CDSAtomicLoad[Idx], args);
497 ReplaceInstWithInst(LI, funcInst);
498 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
499 Value *Addr = SI->getPointerOperand();
500 int Idx=getMemoryAccessFuncIndex(Addr, DL);
504 int atomic_order_index = getAtomicOrderIndex(SI->getOrdering());
505 Value *val = SI->getValueOperand();
506 Value *order = ConstantInt::get(OrdTy, atomic_order_index);
507 Value *args[] = {Addr, val, order, position};
508 Instruction* funcInst=CallInst::Create(CDSAtomicStore[Idx], args);
509 ReplaceInstWithInst(SI, funcInst);
510 } else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I)) {
511 Value *Addr = RMWI->getPointerOperand();
512 int Idx=getMemoryAccessFuncIndex(Addr, DL);
516 int atomic_order_index = getAtomicOrderIndex(RMWI->getOrdering());
517 Value *val = RMWI->getValOperand();
518 Value *order = ConstantInt::get(OrdTy, atomic_order_index);
519 Value *args[] = {Addr, val, order, position};
520 Instruction* funcInst = CallInst::Create(CDSAtomicRMW[RMWI->getOperation()][Idx], args);
521 ReplaceInstWithInst(RMWI, funcInst);
522 } else if (AtomicCmpXchgInst *CASI = dyn_cast<AtomicCmpXchgInst>(I)) {
523 IRBuilder<> IRB(CASI);
525 Value *Addr = CASI->getPointerOperand();
526 int Idx=getMemoryAccessFuncIndex(Addr, DL);
530 const unsigned ByteSize = 1U << Idx;
531 const unsigned BitSize = ByteSize * 8;
532 Type *Ty = Type::getIntNTy(IRB.getContext(), BitSize);
533 Type *PtrTy = Ty->getPointerTo();
535 Value *CmpOperand = IRB.CreateBitOrPointerCast(CASI->getCompareOperand(), Ty);
536 Value *NewOperand = IRB.CreateBitOrPointerCast(CASI->getNewValOperand(), Ty);
538 int atomic_order_index_succ = getAtomicOrderIndex(CASI->getSuccessOrdering());
539 int atomic_order_index_fail = getAtomicOrderIndex(CASI->getFailureOrdering());
540 Value *order_succ = ConstantInt::get(OrdTy, atomic_order_index_succ);
541 Value *order_fail = ConstantInt::get(OrdTy, atomic_order_index_fail);
543 Value *Args[] = {IRB.CreatePointerCast(Addr, PtrTy),
544 CmpOperand, NewOperand,
545 order_succ, order_fail, position};
547 CallInst *funcInst = IRB.CreateCall(CDSAtomicCAS_V1[Idx], Args);
548 Value *Success = IRB.CreateICmpEQ(funcInst, CmpOperand);
550 Value *OldVal = funcInst;
551 Type *OrigOldValTy = CASI->getNewValOperand()->getType();
552 if (Ty != OrigOldValTy) {
553 // The value is a pointer, so we need to cast the return value.
554 OldVal = IRB.CreateIntToPtr(funcInst, OrigOldValTy);
558 IRB.CreateInsertValue(UndefValue::get(CASI->getType()), OldVal, 0);
559 Res = IRB.CreateInsertValue(Res, Success, 1);
561 I->replaceAllUsesWith(Res);
562 I->eraseFromParent();
563 } else if (FenceInst *FI = dyn_cast<FenceInst>(I)) {
564 int atomic_order_index = getAtomicOrderIndex(FI->getOrdering());
565 Value *order = ConstantInt::get(OrdTy, atomic_order_index);
566 Value *Args[] = {order, position};
568 CallInst *funcInst = CallInst::Create(CDSAtomicThreadFence, Args);
569 ReplaceInstWithInst(FI, funcInst);
570 // errs() << "Thread Fences replaced\n";
575 bool CDSPass::isAtomicCall(Instruction *I) {
576 if ( auto *CI = dyn_cast<CallInst>(I) ) {
577 Function *fun = CI->getCalledFunction();
581 StringRef funName = fun->getName();
583 // todo: come up with better rules for function name checking
584 for (StringRef name : AtomicFuncNames) {
585 if ( funName.contains(name) )
589 for (StringRef PartialName : PartialAtomicFuncNames) {
590 if (funName.contains(PartialName) &&
591 funName.contains("atomic") )
599 bool CDSPass::instrumentAtomicCall(CallInst *CI, const DataLayout &DL) {
601 Function *fun = CI->getCalledFunction();
602 StringRef funName = fun->getName();
603 std::vector<Value *> parameters;
605 User::op_iterator begin = CI->arg_begin();
606 User::op_iterator end = CI->arg_end();
607 for (User::op_iterator it = begin; it != end; ++it) {
609 parameters.push_back(param);
612 // obtain source line number of the CallInst
613 Value *position = getPosition(CI, IRB);
615 // the pointer to the address is always the first argument
616 Value *OrigPtr = parameters[0];
618 int Idx = getMemoryAccessFuncIndex(OrigPtr, DL);
622 const unsigned ByteSize = 1U << Idx;
623 const unsigned BitSize = ByteSize * 8;
624 Type *Ty = Type::getIntNTy(IRB.getContext(), BitSize);
625 Type *PtrTy = Ty->getPointerTo();
627 // atomic_init; args = {obj, order}
628 if (funName.contains("atomic_init")) {
629 Value *ptr = IRB.CreatePointerCast(OrigPtr, PtrTy);
630 Value *val = IRB.CreateBitOrPointerCast(parameters[1], Ty);
631 Value *args[] = {ptr, val, position};
633 Instruction* funcInst = CallInst::Create(CDSAtomicInit[Idx], args);
634 ReplaceInstWithInst(CI, funcInst);
639 // atomic_load; args = {obj, order}
640 if (funName.contains("atomic_load")) {
641 bool isExplicit = funName.contains("atomic_load_explicit");
643 Value *ptr = IRB.CreatePointerCast(OrigPtr, PtrTy);
646 order = IRB.CreateBitOrPointerCast(parameters[1], OrdTy);
648 order = ConstantInt::get(OrdTy,
649 (int) AtomicOrderingCABI::seq_cst);
650 Value *args[] = {ptr, order, position};
652 Instruction* funcInst = CallInst::Create(CDSAtomicLoad[Idx], args);
653 ReplaceInstWithInst(CI, funcInst);
656 } else if (funName.contains("atomic") &&
657 funName.contains("load") ) {
658 // does this version of call always have an atomic order as an argument?
659 Value *ptr = IRB.CreatePointerCast(OrigPtr, PtrTy);
660 Value *order = IRB.CreateBitOrPointerCast(parameters[1], OrdTy);
661 Value *args[] = {ptr, order, position};
663 if (!CI->getType()->isPointerTy()) {
667 CallInst *funcInst = IRB.CreateCall(CDSAtomicLoad[Idx], args);
668 Value *RetVal = IRB.CreateIntToPtr(funcInst, CI->getType());
670 CI->replaceAllUsesWith(RetVal);
671 CI->eraseFromParent();
676 // atomic_store; args = {obj, val, order}
677 if (funName.contains("atomic_store")) {
678 bool isExplicit = funName.contains("atomic_store_explicit");
679 Value *OrigVal = parameters[1];
681 Value *ptr = IRB.CreatePointerCast(OrigPtr, PtrTy);
682 Value *val = IRB.CreatePointerCast(OrigVal, Ty);
685 order = IRB.CreateBitOrPointerCast(parameters[2], OrdTy);
687 order = ConstantInt::get(OrdTy,
688 (int) AtomicOrderingCABI::seq_cst);
689 Value *args[] = {ptr, val, order, position};
691 Instruction* funcInst = CallInst::Create(CDSAtomicStore[Idx], args);
692 ReplaceInstWithInst(CI, funcInst);
695 } else if (funName.contains("atomic") &&
696 funName.contains("EEEE5store") ) {
697 // does this version of call always have an atomic order as an argument?
698 Value *OrigVal = parameters[1];
700 Value *ptr = IRB.CreatePointerCast(OrigPtr, PtrTy);
701 Value *val = IRB.CreatePointerCast(OrigVal, Ty);
702 Value *order = IRB.CreateBitOrPointerCast(parameters[2], OrdTy);
703 Value *args[] = {ptr, val, order, position};
705 Instruction* funcInst = CallInst::Create(CDSAtomicStore[Idx], args);
706 ReplaceInstWithInst(CI, funcInst);
711 // atomic_fetch_*; args = {obj, val, order}
712 if (funName.contains("atomic_fetch_") ||
713 funName.contains("atomic_exchange") ) {
714 bool isExplicit = funName.contains("_explicit");
715 Value *OrigVal = parameters[1];
718 if ( funName.contains("_fetch_add") )
719 op = AtomicRMWInst::Add;
720 else if ( funName.contains("_fetch_sub") )
721 op = AtomicRMWInst::Sub;
722 else if ( funName.contains("_fetch_and") )
723 op = AtomicRMWInst::And;
724 else if ( funName.contains("_fetch_or") )
725 op = AtomicRMWInst::Or;
726 else if ( funName.contains("_fetch_xor") )
727 op = AtomicRMWInst::Xor;
728 else if ( funName.contains("atomic_exchange") )
729 op = AtomicRMWInst::Xchg;
731 errs() << "Unknown atomic read-modify-write operation\n";
735 Value *ptr = IRB.CreatePointerCast(OrigPtr, PtrTy);
736 Value *val = IRB.CreatePointerCast(OrigVal, Ty);
739 order = IRB.CreateBitOrPointerCast(parameters[2], OrdTy);
741 order = ConstantInt::get(OrdTy,
742 (int) AtomicOrderingCABI::seq_cst);
743 Value *args[] = {ptr, val, order, position};
745 Instruction* funcInst = CallInst::Create(CDSAtomicRMW[op][Idx], args);
746 ReplaceInstWithInst(CI, funcInst);
749 } else if (funName.contains("fetch")) {
750 errs() << "atomic exchange captured. Not implemented yet. ";
751 errs() << "See source file :";
752 getPosition(CI, IRB, true);
753 } else if (funName.contains("exchange") &&
754 !funName.contains("compare_exchange") ) {
755 errs() << "atomic exchange captured. Not implemented yet. ";
756 errs() << "See source file :";
757 getPosition(CI, IRB, true);
760 /* atomic_compare_exchange_*;
761 args = {obj, expected, new value, order1, order2}
763 if ( funName.contains("atomic_compare_exchange_") ) {
764 bool isExplicit = funName.contains("_explicit");
766 Value *Addr = IRB.CreatePointerCast(OrigPtr, PtrTy);
767 Value *CmpOperand = IRB.CreatePointerCast(parameters[1], PtrTy);
768 Value *NewOperand = IRB.CreateBitOrPointerCast(parameters[2], Ty);
770 Value *order_succ, *order_fail;
772 order_succ = IRB.CreateBitOrPointerCast(parameters[3], OrdTy);
773 order_fail = IRB.CreateBitOrPointerCast(parameters[4], OrdTy);
775 order_succ = ConstantInt::get(OrdTy,
776 (int) AtomicOrderingCABI::seq_cst);
777 order_fail = ConstantInt::get(OrdTy,
778 (int) AtomicOrderingCABI::seq_cst);
781 Value *args[] = {Addr, CmpOperand, NewOperand,
782 order_succ, order_fail, position};
784 Instruction* funcInst = CallInst::Create(CDSAtomicCAS_V2[Idx], args);
785 ReplaceInstWithInst(CI, funcInst);
788 } else if ( funName.contains("compare_exchange_strong") ||
789 funName.contains("compare_exchange_weak") ) {
790 Value *Addr = IRB.CreatePointerCast(OrigPtr, PtrTy);
791 Value *CmpOperand = IRB.CreatePointerCast(parameters[1], PtrTy);
792 Value *NewOperand = IRB.CreateBitOrPointerCast(parameters[2], Ty);
794 Value *order_succ, *order_fail;
795 order_succ = IRB.CreateBitOrPointerCast(parameters[3], OrdTy);
796 order_fail = IRB.CreateBitOrPointerCast(parameters[4], OrdTy);
798 Value *args[] = {Addr, CmpOperand, NewOperand,
799 order_succ, order_fail, position};
800 Instruction* funcInst = CallInst::Create(CDSAtomicCAS_V2[Idx], args);
801 ReplaceInstWithInst(CI, funcInst);
809 int CDSPass::getMemoryAccessFuncIndex(Value *Addr,
810 const DataLayout &DL) {
811 Type *OrigPtrTy = Addr->getType();
812 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
813 assert(OrigTy->isSized());
814 uint32_t TypeSize = DL.getTypeStoreSizeInBits(OrigTy);
815 if (TypeSize != 8 && TypeSize != 16 &&
816 TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
817 NumAccessesWithBadSize++;
818 // Ignore all unusual sizes.
821 size_t Idx = countTrailingZeros(TypeSize / 8);
822 //assert(Idx < kNumberOfAccessSizes);
823 if (Idx >= kNumberOfAccessSizes) {
830 char CDSPass::ID = 0;
832 // Automatically enable the pass.
833 static void registerCDSPass(const PassManagerBuilder &,
834 legacy::PassManagerBase &PM) {
835 PM.add(new CDSPass());
838 /* Enable the pass when opt level is greater than 0 */
839 static RegisterStandardPasses
840 RegisterMyPass1(PassManagerBuilder::EP_OptimizerLast,
843 /* Enable the pass when opt level is 0 */
844 static RegisterStandardPasses
845 RegisterMyPass2(PassManagerBuilder::EP_EnabledOnOptLevel0,