LLVM 检查数组分配是否具有动态大小或恒定大小

LLVM check if array allocation has dynamic size or constant size

我想检查数组的堆栈分配是否具有恒定大小或动态大小(在运行时计算)。例如

int myInt;
scanf("%d", &myInt);
int buffer[myInt]; //dynamic sized array

动态大小的数组像这样转换为 llvm IR:

%myInt = alloca i32, align 4
%saved_stack = alloca i8*
%call = call i32 (i8*, ...) @__isoc99_scanf(i8* getelementptr inbounds ([3 x i8], [3 x i8]* @.str, i32 0, i32 0), i32* %myInt)
%0 = load i32, i32* %myInt, align 4
%1 = zext i32 %0 to i64
%2 = call i8* @llvm.stacksave()
store i8* %2, i8** %saved_stack
%vla = alloca i32, i64 %1, align 16 //allocation
%3 = load i8*, i8** %saved_stack
call void @llvm.stackrestore(i8* %3)

一个常量大小的数组:

int buffer2[123]; 

LLVM IR:

%buffer2 = alloca [123 x i32], align 16 

如何确定 alloca 指令分配的是动态大小的数组还是常量大小的数组?

查看 "include/llvm/IR/Instructions.h" 中的 class AllocaInst。它包含一个方法 returns 分配数组的大小

  /// Get the number of elements allocated. For a simple allocation of a single
  /// element, this will return a constant 1 value.
  const Value *getArraySize() const { return getOperand(0); }

一旦你有了数组大小的 Value *,你应该能够使用 dyn_cast<ConstantInt> 来分析它是否是一个常量。 (grep for this expression. 它在代码中被广泛使用)。