LLVM IR: C ++ API: Typecast from i1 to i32 and i32 to i1

I am writing a compiler for a makeshift language that can only process int values, i.e. i32. Conditions and expressions are similar to C. Thus, I consider conditional expressions as expressions, that is, they return an int value. They can also be used in expressions, such as (2 > 1) + (3 > 2)returns 2. But LLVM conditions infer the meaning i1.

  • Now I want to i1convert to after each conditional statement i32so that I can perform binary operations
  • In addition, I want to use the variables and results of the expression as a condition, for example. if(variable)or if(a + b). For this I need to convert i32toi1

In the end, I need a way to typecast from i1to i32and from i32to i1. My code gives such errors at the moment:

For an operator like if(variable):

error: branch condition must have 'i1' type
br i32 %0, label %ifb, label %else
   ^

For type operator a = b > 3

error: stored value and pointer type do not match
store i1 %gttmp, i32* @a
      ^

Any suggestion on how to do this?

+4
source share
1 answer

I get it. To convert from i1to i32, as indicated here by Ismail Badawi , I used IRBuilder::CreateIntCast. Therefore, if vis a pointer Value *pointing to an expression expressed in i1, I did the following to convert it to i32:

v = Builder.CreateIntCast(v, Type::getInt32Ty(getGlobalContext()), true);

i32 i1. . , i32 2 i1 0. i1 1 i32. v - Value *, , i32, , i1:

v = Builder.CreateICmpNE(v, ConstantInt::get(Type::getInt32Ty(getGlobalContext()), 0, true))
+1

Source: https://habr.com/ru/post/1689194/


All Articles