Reputation: 11
LLVM uses SSA (Static Single Assignment) form for its IR. This results in the introduction of new variables into the code at IR level. However, is there any method, API ... to determine if a variable originally belongs to the program or is inserted by the compiler?
Upvotes: 1
Views: 477
Reputation: 3246
There is no notion of inserting new variables into LLVM IR. The source language and LLVM IR are simply two different languages, and you should rather see the compilation as a translation step.
Conceptually, it would be difficult to come up with a precise definition when a variable belongs to the original program or not.
Consider for example this small C function:
void test() {
int i;
i = 2;
i = 3;
}
Compiling this function to LLVM IR would result in at least two variables (if no constant folding is applied) since of SSA form. Which one would be the original one, and which one inserted?
This also gets complicated, when control flow and phi functions are involved:
int a = 1;
int b = 2;
int c = 3;
int func() {
int result;
if (a) {
result = b;
} else {
result = c;
}
return result;
}
When translating this C function to LLVM IR and applying the -mem2reg pass we get the following:
define i32 @func() #0 {
%1 = load i32* @a, align 4
%2 = icmp ne i32 %1, 0
br i1 %2, label %3, label %5
; <label>:3 ; preds = %0
%4 = load i32* @b, align 4
br label %7
; <label>:5 ; preds = %0
%6 = load i32* @c, align 4
br label %7
; <label>:7 ; preds = %5, %3
%result.0 = phi i32 [ %4, %3 ], [ %6, %5 ]
ret i32 %result.0
}
As you see, the virtual register name of result does not show up at the stage of assignment. It is only visible at the merge point. Here, the original place of the variable assignment was moved towards the end of the function. Again, it is questionable which variables got inserted, and which ones didn't.
What you could do is to compile the original program with debug metadata and then process the debug information to find out variable declarations etc. In Clang you can output the debug information with the -g
flag.
Upvotes: 5