Instruction not in sequence

This code:

int main(int argc, char **argv) {
puts(“abc”);
return 0;
}

compiles to this:

@"\01??_C@_03FIKCJHKP@abc?$AA@" = linkonce_odr unnamed_addr constant [4 x i8] c"abc\00", comdat, align 1

; Function Attrs: nounwind uwtable
define i32 @main(i32 %argc, i8** nocapture readnone %argv) #0 {
%1 = tail call i32 @puts(i8* getelementptr inbounds ([4 x i8], [4 x i8]* @"\01??_C@_03FIKCJHKP@abc?$AA@", i64 0, i64 0)) #2, !dbg !15
ret i32 0, !dbg !16
}

The part I don’t understand is where the call instruction refers to the result of getelementptr without the latter appearing in the sequence of instructions. I thought all instructions appeared in sequence in basic blocks, so I was expecting %1 = getelementptr …, %2 = call(%1 …)

Is there something I’m missing about the rules for the intermediate code representation?

From: "Russell Wallace via llvm-dev" <llvm-dev@lists.llvm.org>
To: "llvm-dev" <llvm-dev@lists.llvm.org>
Sent: Sunday, November 8, 2015 4:03:27 AM
Subject: [llvm-dev] Instruction not in sequence

This code:

int main(int argc, char **argv) {
puts("abc");
return 0;
}

compiles to this:

@"\01??_C@_03FIKCJHKP@abc?$AA@" = linkonce_odr unnamed_addr constant
[4 x i8] c"abc\00", comdat, align 1

; Function Attrs: nounwind uwtable
define i32 @main(i32 %argc, i8** nocapture readnone %argv) #0 {
%1 = tail call i32 @puts(i8* getelementptr inbounds ([4 x i8], [4 x
i8]* @"\01??_C@_03FIKCJHKP@abc?$AA@", i64 0, i64 0)) #2, !dbg !15
ret i32 0, !dbg !16
}

The part I don't understand is where the call instruction refers to
the result of getelementptr without the latter appearing in the
sequence of instructions. I thought all instructions appeared in
sequence in basic blocks, so I was expecting %1 = getelementptr ...,
%2 = call(%1 ...)

Is there something I'm missing about the rules for the intermediate
code representation?

The getelementptr here is not an instruction at all, but rather a constant expression. Constant expressions in LLVM can be complicated, and have expression nodes that mirror the usual IR instructions.

A quick way to see this is to run your IR through llc -march=cpp.

-Hal

Ah! Okay, that makes sense except for one thing.

The getelementptr successfully dyn_cast’ed. At first glance that figures since it is a constant expression. But from the inheritance diagram of Value, getelementptr is not a subclass of Constant but of Instruction; from that perspective I would expect that the fact that this particular one is a constant expression would be as far as the compiler is concerned just a dynamic fact based on the fact that its operands happen to be constants, so I wouldn’t have expected the dynamic cast to succeed. What am I missing here?

Oh! Now I see, the thing that printed as getelementptr is as far as the inheritance hierarchy is concerned quite a different thing, it’s a gep ConstantExpr rather than a gep Instruction. That makes sense, thanks!