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

Meh*_*dad 6 c++ llvm 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*, ...)
Run Code Online (Sandbox Code Playgroud)

我找到了预先存在的通行证ExternalFunctionsPassedConstants,这似乎是相关的:

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;

        ...
Run Code Online (Sandbox Code Playgroud)

所以我添加了代码:

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

到目前为止,这么好 - 我看到类型ID是14,这意味着它是一个PointerTyID.

但是现在,我如何得到作为参数传递的字符串文字的内容,所以我可以根据实际给出的数字验证预期参数的数量?

Cha*_*ang 7

CS.getArgument(0)  
Run Code Online (Sandbox Code Playgroud)

表示GetElementPtrConstantExpr

i8* getelementptr inbounds ([7 x i8]* @.str, i32 0, i32 0)
Run Code Online (Sandbox Code Playgroud)

,它是一个User对象.你想要的字符串(即@ .str)是这个GetElementPtrConstantExpr的第一个操作数.

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

CS.getArgument(0).getOperand(0)
Run Code Online (Sandbox Code Playgroud)

但是,我还没有测试过这段代码.如果有任何错误,请告诉我.

  • 太棒了!`getOperand`指出我正确的方向!看来我需要`cast <ConstantDataArray>(cast <GlobalVariable>(cast <ConstantExpr>(CS.getArgument(0)) - > getOperand(0)) - > getInitializer()) - > getAsCString()`,这给了我字符串.:) 非常感谢! (2认同)