簡體   English   中英

如何在LLVM IR中獲取字符串文字的值?

[英]How to get the value of a string literal in LLVM IR?

我是LLVM的新手。 我正在嘗試編寫一個基本的Pass,它將檢查printf調用的參數,當它被賦予中間表示時。
如果格式字符串不是字符串文字,那么我當然無法檢查它。 但通常情況確實如此。

我試圖檢查的樣本IR是:

@.str = private unnamed_addr constant [7 x i8] c"Hi %u\0A\00", align 1

define i32 @main() nounwind {
entry:
  %retval = alloca i32, align 4
  store i32 0, i32* %retval
  %call = call i32 (i8*, ...)* @printf(i8* getelementptr inbounds ([7 x i8]* @.str, i32 0, i32 0), i32 1)
  ret i32 0
}

declare i32 @printf(i8*, ...)

我找到了一個名為ExternalFunctionsPassedConstants的預先存在的Pass,它看似相關:

struct ExternalFunctionsPassedConstants : public ModulePass {
  static char ID; // Pass ID, replacement for typeid
  ExternalFunctionsPassedConstants() : ModulePass(ID) {}
  virtual bool runOnModule(Module &M) {
    for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
      if (!I->isDeclaration()) continue;

      bool PrintedFn = false;
      for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
           UI != E; ++UI) {
        Instruction *User = dyn_cast<Instruction>(*UI);
        if (!User) continue;

        CallSite CS(cast<Value>(User));
        if (!CS) continue;

        ...

所以我添加了代碼:

        if (I->getName() == "printf") {
          errs() << "printf() arg0 type: "
                 << CS.getArgument(0)->getType()->getTypeID() << "\n";
        }

到目前為止,這么好 - 我看到類型ID是14,這意味着它是一個PointerTyID

但是現在,我如何得到作為參數傳遞的字符串文字的內容 ,所以我可以根據實際給出的數字驗證預期參數的數量?

CS.getArgument(0)  

表示GetElementPtrConstantExpr

i8* getelementptr inbounds ([7 x i8]* @.str, i32 0, i32 0)

,它是一個User對象。 你想要的字符串(即@ .str)是這個GetElementPtrConstantExpr的第一個操作數。

所以,你可以得到字符串文字

CS.getArgument(0).getOperand(0)

但是,我還沒有測試過這段代碼。 如果有任何錯誤,請告訴我。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM