从c++ API中检索常量函数参数的值

LLVM: Retrieving the value of constant function parameters from the C++ API

本文关键字:函数 参数 常量 检索 c++ API      更新时间:2023-10-16

我正在使用LLVM API编写一些代码。我正在使用llvm::CallGraph对象来循环通过父函数调用的所有子函数:

CallGraph cg( *mod );
for( auto i = cg.begin(); i != cg.end(); ++i )
{
    const Function *parent = i->first;
    if( !parent )
        continue;
    for( auto j = i->second->begin(); j != i->second->end(); ++j )
    {
        Function *child = j->second->getFunction();
        if( !child )
            continue;
        for( auto iarg = child->arg_begin(); iarg != child->arg_end(); ++iarg )
        {
            // Print values here!
        }
    }
    o.flush();

我感兴趣的IR中的实际函数调用看起来像这样:

call void @_ZN3abc3FooC1Ejjj(%"struct.abc::Foo"* %5, i32 4, i32 2, i32 0)

,我想做的是检索最后三个常量整数值:4,2,0。如果我也能检索%5,那就加分了,但这并不那么重要。我花了大约两个小时盯着http://llvm.org/docs/doxygen/,但我就是不知道我应该如何得到这三个值

在第二个循环中,当您遍历CallGraphNode时,您将返回std::pair<WeakVH, CallGraphNode*>的实例。WeakVH表示调用指令,CallGraphNode*表示被调用函数。代码的问题在于,您正在查看被调用的函数,并在其定义中的形式参数上迭代,而不是查看调用位置。你想要这样的东西(注意,我还没有测试过这个,只是根据签名):

CallGraph cg( *mod );
for( auto i = cg.begin(); i != cg.end(); ++i )
{
    for( auto j = i->second->begin(); j != i->second->end(); ++j )
    {
        CallSite CS(*j->first);
        for (auto arg = CS.arg_begin(); arg != CS.arg_end(); ++arg) {
            // Print values here!
        }
    }
    o.flush();

从那里你可以得到代表参数的Value*指针,检查它们是否为ConstantInt,等等。