如何在Clang LLVM AST中获取UnaryOperator的DevlRefExpr操作数

How to get the DevlRefExpr operand out of UnaryOperator in the Clang LLVM AST?

本文关键字:UnaryOperator 获取 DevlRefExpr 操作数 AST Clang LLVM      更新时间:2023-10-16

我这里有这段代码:

class MemcpyMatcher : public MatchFinder::MatchCallback
{
  public:
    MemcpyMatcher(map<string, Replacements> * replacements)
        : replacements(replacements) {}
    /* Callback method for the MatchFinder.
     * @param result - Found matching results.
     */
    virtual void run(const MatchFinder::MatchResult& result)
    {
        const CallExpr* call_expr = result.Nodes.getNodeAs<CallExpr>("memcpy_call");
        if (call_expr != NULL) {
            const Expr* voidp_dest = call_expr->getArg(0)->IgnoreImplicit();
            const Expr* voidp_src  = call_expr->getArg(1)->IgnoreImplicit();
            const Expr* size_t_n   = call_expr->getArg(2)->IgnoreImplicit();
            voidp_dest->dump();
    }
  private:
    map<string, Replacements>* replacements;
    // Add other variables here as needed.
};

这是 voidp_dest->dump(); 语句的输出:

UnaryOperator 0x2148d48 'int *' prefix '&'
`-DeclRefExpr 0x2148cf8 'int' lvalue Var 0x21480c0 'number' 'int'

在源代码中,我抓取的表达式如下所示:&number .

我想从UnaryOperator中获取DeclRefExpr,以便将其转换为字符串并获取变量的名称。我不知道该怎么做。

对于仍在寻找答案的任何人:

  const DeclRefExpr* decl_ref = nullptr;
  if (auto unary = dyn_cast<UnaryOperator>(expr)) {
    if (unary->getOpcode() == UnaryOperator::Opcode::UO_AddrOf) {
      unsigned count = 0;
      // there will be only one child
      for (auto child : unary->children()) {
        decl_ref = dyn_cast<DeclRefExpr>(child);
      }
    }
  }

另一种用更少的LOC完成相同任务的方法,

DeclRefExpr* ref = nullptr;
if(auto UnOp = dyn_cast<UnaryOperator>(expr)) {
  ref = dyn_cast<DeclRefExpr>(UnOp->getSubExp());
}