基于C++识别LLVM代码中用户定义函数与声明函数的技术问询
Hey Daniel, no worries—this is a super common question when getting started with LLVM's analysis APIs, and the solution is simpler than you might think!
Core Check: Use Function::isDeclaration()
LLVM's Function class has a built-in method made exactly for this purpose. It’s designed to clearly separate functions with full implementations (user-defined) from those that only exist as declarations (no body, just name, parameters, and return type).
Here’s the breakdown:
- If
F.isDeclaration()returnstrue: The function is just a declaration—no implementation code exists in the module. - If it returns
false: The function has a complete user-defined body made up of basic blocks.
Example Code Snippet
Here’s a quick C++ example that iterates over all functions in an LLVM Module and classifies them:
#include "llvm/IR/Module.h" #include "llvm/IR/Function.h" #include "llvm/Support/raw_ostream.h" void classifyLLVMFunctions(llvm::Module &Module) { for (auto &Func : Module) { if (Func.isDeclaration()) { llvm::errs() << "Declaration-only function: " << Func.getName() << "\n"; } else { llvm::errs() << "User-defined function (with body): " << Func.getName() << "\n"; } } }
Why This Works
Under the hood, isDeclaration() checks whether the function has no basic blocks (the core building blocks of a function’s executable logic). You could also use Func.empty() to get the same result (since an empty function has no basic blocks), but isDeclaration() is far more semantically clear—it explicitly signals that you’re checking for a declaration vs. a fully defined function.
Edge Cases to Keep in Mind
- External library functions (like
printformalloc) will show up as declaration-only, which makes sense because their implementation lives outside your module. - If you’re working with inline functions or functions linked from other modules,
isDeclaration()will correctly mark them as non-declaration only if their full body is present in the current module.
内容的提问来源于stack exchange,提问作者Daniel

