How can I declare a global variable in LLVM?

空扰寡人 提交于 2019-12-04 09:17:36

问题


I'd like to record some dynamic behaviors into some global variables. So I wrote a pass to instrument the code and insert some instructions to update the global variable. I tried to use the GlobalVariable constructor to define a global variable, but there are two problems. First, how can I DEFINE the global variables in the module containing main function? Second, how can I DECLARE those global variables in other modules? It's like "extern double someThing;".

The target programs are written in C.


回答1:


There is a tool which can answer this and many other questions about LLVM API: llc -march=cpp. You can generate a bitcode file using Clang or llvm-gcc, and then build a C++ code which should reconstruct the same module using the cpp backend.

A sample output, showing how to define a global int * variable:

// Global Variable Declarations

GlobalVariable* gvar_ptr_abc = new GlobalVariable(/*Module=*/*mod, 
        /*Type=*/PointerTy_0,
        /*isConstant=*/false,
        /*Linkage=*/GlobalValue::CommonLinkage,
        /*Initializer=*/0, // has initializer, specified below
        /*Name=*/"abc");
gvar_ptr_abc->setAlignment(4);

// Constant Definitions
ConstantPointerNull* const_ptr_2 = ConstantPointerNull::get(PointerTy_0);

// Global Variable Definitions
gvar_ptr_abc->setInitializer(const_ptr_2);


来源:https://stackoverflow.com/questions/7787308/how-can-i-declare-a-global-variable-in-llvm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!