2016-03-06 25 views
1

我是新來LLVM,並試圖找到鎖聲明語句,然後做一些instrumention工作中,這樣的代碼:如何在llvm中發現鎖定聲明指令?

#include <iostream> 
#include <thread> 
#include <mutex> 
using namespace std; 

int share = 42; 
mutex m; 

void f() 
{ 
    m.lock(); 
    --share; 
    cout << "function f -> share: " << share << '\n'; 
    m.unlock(); 
} 



int main() 
{ 
    thread thf{f}; 

    thf.join(); 

    return 0; 
} 

我想找到鎖聲明指令如: mutex m; 的llvm instrumention通過這樣的:

struct SkeletonPass : public FunctionPass { 
static char ID; 
SkeletonPass() : FunctionPass(ID) {} 

virtual bool runOnFunction(Function &F) { 
    // Get the function to call from our runtime library. 
    LLVMContext &Ctx = F.getContext(); 
    Constant *logFunc = F.getParent()->getOrInsertFunction(
    "logop", Type::getVoidTy(Ctx), Type::getInt32Ty(Ctx), NULL 
); 

    for (auto &B : F) { 
    for (auto &I : B) { 
     ***if ((&I) is lock declaration instruction)*** { 

     // Insert something *after* `op`. 
     IRBuilder<> builder(op); 
     builder.SetInsertPoint(&B, ++builder.GetInsertPoint()); 

     // Insert a call to function. 

     builder.CreateCall(logFunc, ConstantInt::get(Type::getInt32Ty(Ctx), 2)); 

     return true; 
     } 
    } 
    } 

總之,請你告訴我如何發現鎖定聲明指令,謝謝!

回答

0

該聲明將顯示爲全局,因此您應該編寫一個模塊傳遞來查找它,而不是函數傳遞。它應該會出現像:

@m = global %mutex zeroinitializer 

事實上,使用演示在http://ellcc.org/demo/index.cgi試試這個,你確實可以看到:

...  
%"class.std::__1::mutex" = type { %struct.pthread_mutex_t } 
%struct.pthread_mutex_t = type { %union.anon } 
%union.anon = type { [5 x i8*] } 
... 
@m = global %"class.std::__1::mutex" zeroinitializer, align 8 
+0

非常感謝!在你的幫助下,我解決了這個問題。演示非常方便! –

+0

我有[鏈接]另一個問題(http://stackoverflow.com/questions/35893006/how-to-define-string-type-in​​-getorinsertfunction-llvm)。我認爲你必須知道如何解決它。如果你知道,請告訴我該怎麼做。謝謝 ! –

0

您可以使用LLVM的CppBackend編譯您的代碼。這將產生構成源代碼的C++代碼。然後,您可以輕鬆瞭解如何通過LLVM API構造mutex m;定義。

運行clang -march=cpp foo.cpp使用CppBackend。或者,您可以使用this demo page在線編譯您的代碼。

+0

感謝您的幫助,我已經解決了我的問題。 –