Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I declare a global variable in LLVM?

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.

like image 418
dalibocai Avatar asked Oct 16 '11 21:10

dalibocai


People also ask

How do you declare a global variable?

Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function. To create a global variable inside a function, you can use the global keyword.

How do you declare global variables in pho?

Using global keyword. Using array GLOBALS[var_name]: It stores all global variables in an array called $GLOBALS[var_name]. Var_name is the name of the variable.

Where should I declare global variables?

Hence, the natural place to put global variable declaration statements is before any function definitions: i.e., right at the beginning of the program. Global variables declarations can be used to initialize such variables, in the regular manner.


1 Answers

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);
like image 111
SK-logic Avatar answered Sep 20 '22 21:09

SK-logic