Pavan Yalamanchili
Pavan Yalamanchili

Reputation: 12099

Setting a variable to 0 in LLVM IR

Is it possible to set a variable to 0 (or any other number) in LLVM-IR ? My searches have found me the following 3 line snippet, but is there anything simpler than the following solution ?

%ptr = alloca i32                               ; yields i32*:ptr
store i32 3, i32* %ptr                          ; yields void
%val = load i32, i32* %ptr                      ; yields i32:val = i32 3

Upvotes: 0

Views: 974

Answers (2)

hadi sadeghi
hadi sadeghi

Reputation: 537

To set a value to zero (or null in general) you can use

Constant::getNullValue(Type)

and to set a value with an arbitrary constant number you can use ConstantInt::get(), but you need to identify the context first, like this:

LLVMContext &context = function->getContext();
/* or BB->getContext(), BB can be any basic block in the function */
Value* constVal = ConstantInt::get(Type::getInt32Ty(context), 3);

Upvotes: 3

box
box

Reputation: 3246

LLVM-IR is in static single assignment (SSA) form, so each variable is only assigned once. If you want to assign a value to a memory region you can simply use a store operation as you showed in your example:

store i32 3, i32* %ptr     

The type of the second argument is i32* which means that it is a pointer to an integer that is 32 bit long.

Upvotes: 1

Related Questions