How to distinguish between user defined function in a program and library functions

Say, I have the following program:

int main(){
std::cout << “hello\n”;
return 0;

After generating llvm bitcode using the following command:
$ clang++ -c -emit-llvm -O -Xclang -disable-llvm-passes a.cpp

the bitcode has the following function with define.

In a pass, I want to know what are the functions defined by the user e.g ‘main’ and what are not e.g. other than ‘main’.


Generally, you can’t - and optimizations/the compiler shouldn’t differentiate between them.

Actually I want to run some analysis pass only on the user defined functions but not on the library functions. Is there any boolean method that can tell which is a library function and which is not?

LLVM’s analysis infrastructure is mostly intended for optimizations, which should apply to any code equally - I don’t believe there’s any bit that tracks which functions came from system libraries or not.

In general it isn’t possible I believe, however if you are tolerant to false positives / false negatives you can compile with debug information (-g or -gline-tables-only) and figure it out.
Obviously after inlining this becomes more murky (user code can get inlined into library code, and vice-versa).

Perhaps you can check where a function is defined and treat all functions defined in a file passed to the compiler as user defined and all other as system defined. Not sure if that's good enough for you.

I’d imagine you can tweak clang’s CodeGen to add a Metadata node to all llvm::Functions clang emits that basically says whether or not the code appeared in a system header. SourceManager::isInSystemHeader should help you figure out what’s where. You’ll probably need special handling for generated code, like __cxx_global_var_init

I offer no guarantees about the LLVM community accepting this patch, though :slight_smile:

To Mehdi’s point, inlining can make things materially more difficult.