LLVM 检索 AllocaInst 的名称

LLVM retrieve name of AllocaInst

我正在尝试检索传递给 cudaMalloc 调用的指针的名称。

CallInst *CUMallocCI = ... ; // CI of cudaMalloc call
Value *Ptr = CUMallocCI->getOperand(0);
if (AllocaInst *AI = dyn_cast<AllocaInst>(Ptr) != nullptr) {
  errs() << AI->getName() << "\n";
}

然而,上面只是打印了一个空行。是否可以从此分配中获取指针名称?

这是相关的 IR:

%28 = alloca i8*, align 8
...
...
call void @llvm.dbg.declare(metadata i8** %28, metadata !926, metadata !DIExpression()), !dbg !927
%257 = call i32 @cudaMalloc(i8** %28, i64 1), !dbg !928
...
...
!926 = !DILocalVariable(name: "d_over", scope: !677, file: !3, line: 191, type: !22)
!927 = !DILocation(line: 191, column: 10, scope: !677)

回答我自己的问题。事实证明,有一个 llvm.dbg.declare 调用(DbgDeclareInst)对应于 alloca 但它可能出现在调用函数的基本块中的任何位置。可能是在第一次使用这个 Alloca 值之后?不确定。无论如何,我的解决方案是搜索 DbgDeclareInst 指令,检查它是否用于 AllocaInst ,如果是,则将该 alloca 与感兴趣的 alloca 进行比较,如果相等,则获取变量名称。像这样:

CallInst *CUMallocCI = ... ; // CI of cudaMalloc call
Value *Ptr = CUMallocCI->getOperand(0);
if (AllocaInst *AI = dyn_cast<AllocaInst>(Ptr) != nullptr) {
  if ( !AI->hasName() ) {
    // Function this AllocaInst belongs
    Function *Caller = AI->getParent()->getParent();
    // Search for llvm.dbg.declare
    for ( BasicBlock& BB : *Caller) 
      for (Instruction &I : BB) {
        if ( DbgDeclareInst *dbg = dyn_cast<DbgDeclareInst>(&I))
          // found. is it for an AllocaInst?
          if ( AllocaInst *dbgAI = dyn_cast<AllocaInst>(dbg->getAddress()))
            // is it for our AllocaInst?
            if (dbgAI == AI)
              if (DILocalVariable *varMD = dbg->getVariable()) // probably not needed?
                errs() << varMD->getName() << "\n";
  } else {
    errs() << AI->getName() << "\n";
  }
}