LLVM load global pointer to i32 type for adding to it

Hi’ I’m trying to add in global i32 to a local i32, but I’m having trouble converting the global ptr to an int which could then be added, and because of this I’m getting the following error when I verify my module:

Both operands to a binary operator are not of the same type!
  %add = add ptr %g, i32 1`

Here is my original code:

i32 g = 0;

i32 main() {
    i32 l = 1;
    l = g + 1;
}

Here is my generated IR:

; ModuleID = 'channel'
source_filename = "channel"

@g = private global i32 0

define i32 @main() {
entry:
  %l = alloca i32, align 4
  store i32 1, ptr %l, align 4
  %g = load ptr, ptr @g, align 8
  %add = add ptr %g, i32 1
  store ptr %add, ptr %l, align 8
  ret i32 0
}

And here is my codegen visit function for this problem:

llvm::Value* codegen_visitor::visit_variable_node(variable_node& node) {
    // local variable
    if(llvm::Value* variable_value = m_named_values[node.get_name()]) {
        // load the value from the memory location
        return m_builder.CreateLoad(variable_value->getType(), variable_value, node.get_name());
    }

    // global variable
    llvm::Value* global_variable_value = m_named_global_values[node.get_name()];
    ASSERT(global_variable_value, "[codegen]: variable not found (" + node.get_name() + ")");
    // doesn't work :/
    return m_builder.CreateLoad(global_variable_value->getType(), global_variable_value, node.get_name());
}

I’m using LLVM 16.0.0
Any advice is very much appreciated

i32 g = 0;

i32 main() {
    i32 l = 1;
    l = g + 1;
}

Assuming g,i and l are an i32.
%g should be a i32, and @g should be a pointer to the location of g in memory.

%g = load ptr, ptr @g, align 8
  %add = add ptr %g, i32 1

“load ptr” is saying that the contents at location @g is a pointer which looks to me to be wrong.
Those instructions should probably be:

%g = load i32, ptr @g, align 8     <- Note the change of the first ptr to i32.
%add = add i32 %g, i32 1
1 Like

Thanks, I solved it by casting to a GlobalValue and using the getValueType function.