Search code examples
c++cclangllvmpragma

How to customise pragma in C?


I want to ask what is the simplest way to build a parser to recognise my customised pragmas in C/C++ code. Yes, a simple bash script can do but I am wondering if there is any formal way to do through Clang or LLVM? I tried to check Clang AST but I cannot find any pragmas.

For instance:

int foo1(){
#pragma hi k=1
...
}

int foo2(){
#pragma hello k=7
...
}

I want the pass returns the following:

function foo1 has hi and k=1
function foo2 has hello and k=7

Thanks.


Solution

  • Pragma handling needs to be done in the following parts:

    1. Add a handler in ParsePragma.cpp file (there are examples how to do that). In this step you can parse the pragma token by token and store corresponding information in the AST (possibly the best way to transfer data from this stage to the later stages).
    2. If you need to handle this information in the passes working on LLVM IR, then you need to attach the information previously stored into AST into an IR related classes, in your case it seems the llvm::Function is the place where to keep that. During this process it is needed to update 'lib/AsmParser/LLParser.cpp', 'lib/AsmParser/LLLexer.cpp' and 'lib/IR/AsmWriter.cpp' files. This will allow to read and write the information stored in IR.

    Finally if you need to write extra information kept in IR into the assembler file then you will need to update 'lib/CodeGen/AsmPrinter/AsmPrinter.cpp' file correspondingly.