Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is "__builtin_va_list" implemented?

Tags:

c

gcc

clang

I want to delve into the implementation of function "printf" in C on macOS. "printf" uses the <stdarg.h> header file. I open the <stdarg.h> file and find that va_list is just a macro.

So, I am really curious about how the __builtin_va_list is implemented? I know it is compiler-specific. Where can I find the definition of the __builtin_va_list? Should I download the source code of clang compiler?

like image 377
linyuwang Avatar asked Apr 09 '18 12:04

linyuwang


2 Answers

In Clang 9, this is implemented in

clang\lib\AST\ASTContext.cpp

call graph:

getVaListTagDecl
=>getBuiltinVaListDecl
=>CreateVaListDecl
=>Create***BuiltinVaListDecl
for example:
=>CreateCharPtrBuiltinVaListDecl
=>CreateCharPtrNamedVaListDecl
=>buildImplicitTypedef

When there is __builtin_va_list in the preprocessed source, the compiler calls getVaListTagDecl to build a TypedefDecl AST node and insert it into the AST, the typedef doesn't exist in any source code, it is generated dynamically during build, as if there is such in the source:

typedef *** __builtin_va_list;
//for example
typedef char* __builtin_va_list;
like image 165
jw_ Avatar answered Oct 14 '22 15:10

jw_


So, I am really curious about how the __builtin_va_list is implemented?

__builtin_va_list is implemented inside the GCC compiler (or the Clang/LLVM one). So you should study the GCC compiler source code to understand details.

Look into gcc/builtins.def & gcc/builtins.c for more.

I am less familiar with Clang, which implements the same builtin.

But both GCC & Clang are open source or free software. They are complex beasts (several millions lines of code each), so you could need years of work to understand them.

Be aware that the ABI of your compiler matters. Look for example into X86 psABI for more details.

BTW, Grady Player commented:

Pops the correct number of bytes off of the stack for each of those tokens...

Unfortunately, today it is much more complex than that. On current processors and ABIs the calling conventions do use processor registers to pass some arguments (and the evil is in the details).

Should I download the source code of clang compiler?

Yes, and you also need to allocate several years of work to understand the details.

A few years ago, I did write some tutorial slides and links to external documentation regarding GCC implementation, see my GCC MELT documentation page (a bit rotten).

like image 28
Basile Starynkevitch Avatar answered Oct 14 '22 16:10

Basile Starynkevitch