[PATCH] Make LLVM profiling thread-safe

Matthew Dempsky matthew at dempsky.org
Mon Jun 24 12:17:17 PDT 2013


Instead of emitting separate read-modify-write instructions to
increment the profiling counters, an monotonically ordered atomic add
instruction should be emitted.

Index: llvm/lib/Transforms/Instrumentation/ProfilingUtils.cpp
===================================================================
--- llvm/lib/Transforms/Instrumentation/ProfilingUtils.cpp	(revision 184494)
+++ llvm/lib/Transforms/Instrumentation/ProfilingUtils.cpp	(working copy)
@@ -121,12 +121,10 @@
   Constant *ElementPtr =
     ConstantExpr::getGetElementPtr(CounterArray, Indices);
 
-  // Load, increment and store the value back.
-  Value *OldVal = new LoadInst(ElementPtr, "OldFuncCounter", InsertPos);
-  Value *NewVal = BinaryOperator::Create(Instruction::Add, OldVal,
-                                 ConstantInt::get(Type::getInt32Ty(Context), 1),
-                                         "NewFuncCounter", InsertPos);
-  new StoreInst(NewVal, ElementPtr, InsertPos);
+  // Atomically increment the counter by one.
+  Constant *One = ConstantInt::get(Type::getInt32Ty(Context), 1);
+  new AtomicRMWInst(AtomicRMWInst::Add, ElementPtr, One, Monotonic,
+                    CrossThread, InsertPos);
 }
 
 void llvm::InsertProfilingShutdownCall(Function *Callee, Module *Mod) {



More information about the llvm-commits mailing list