user3761728
user3761728

Reputation: 97

allow llvm generate code to access a global array

I currently have the following code:

int counter_array[10] = {0};

void increment_address (int*);
void increment_array ();
int main (){
  increment_array();
}

increment_address (int* ptr){
  (*ptr) ++;
}

I am trying use llvm to do instrumentation in order to generate code for the "increment_array()" function so that the function should pass the address of the second element of "counter_array" into the "increment_address(int*)" function.

In other words, the increment_array generated should do something like the following:

void increment_array(){
  int* array_pty = &counter_array[1];
  increment_address(array_ptr);
}

By looking at the IR code It seems like it is done with "getelementptr inbount" instruction. However, I am unable to allocate the array to it.

I was wondering how do I generate the IR code as below in the function generated?

 store i32* getelementptr inbounds ([10 x i32]* @counterarray, i32 0, i64 1), i32** %ptr, align 8

Thank you all for the potential help.

Upvotes: 2

Views: 683

Answers (1)

Cheng Sun
Cheng Sun

Reputation: 1035

First read about how GEP works: http://llvm.org/docs/GetElementPtr.html

Then, to create the actual instruction, use the following APIs:

For instance, to replicate the GEP in your example (without the store):

Value *counterarray = ...

Value *indices[] = {
    ConstantInt::get(Type::getInt32Ty(), 0),
    ConstantInt::get(Type::getInt64Ty(), 1)
};

GetElementPtrInst *Inst = GetElementPtrInst::CreateInBounds(counterarray, indices);

(NB: untested code)

Upvotes: 1

Related Questions