在 LLVM IR 中找到合适的数组大小
Finding the right size of array in LLVM IR
我需要在 GetElementPtr 指令中计算数组的大小(以字节为单位)I
。我之前一直在做使用下面的逻辑推导:
/* Get the bitWidth of the item */
int bitWidth = cast<IntegerType>(I->getOperand(2)->getType())->getBitWidth();
/* Find total number of elements in array */
Type *T = cast<PointerType>(cast<GetElementPtrInst>(I)->getPointerOperandType())->getElementType();
int no_of_elements = cast<ArrayType>(T)->getNumElements();
/* Compute total and return bytes */
return (no_of_elements * bitWidth) / 8
但也有像下面这样的棘手情况。答案是 1024 字节,但我的上述逻辑将给出 2048 因为它完全不知道 i32
%arrayidx932 = getelementptr inbounds [256 x i32], [256 x i32]* @array5, i64 0, i64 %idxprom931, !dbg !168
谁能帮我纠正我的逻辑?
当您编写 I->getOperand(2)
时,您将获得与数组类型无关的索引之一。如果您的代码在任何情况下都能正常工作,那纯属巧合。
您得到了 T
,在本例中代表 [256 x i32]
。您已经使用 getNumElements()
获得了 256
,您可以使用 getElementType()
获得 i32
,然后从那里算出尺寸。
可能更好的方法是 get the DataLayout
off your Module
, and then call getTypeAllocSize(T)
。
我需要在 GetElementPtr 指令中计算数组的大小(以字节为单位)I
。我之前一直在做使用下面的逻辑推导:
/* Get the bitWidth of the item */
int bitWidth = cast<IntegerType>(I->getOperand(2)->getType())->getBitWidth();
/* Find total number of elements in array */
Type *T = cast<PointerType>(cast<GetElementPtrInst>(I)->getPointerOperandType())->getElementType();
int no_of_elements = cast<ArrayType>(T)->getNumElements();
/* Compute total and return bytes */
return (no_of_elements * bitWidth) / 8
但也有像下面这样的棘手情况。答案是 1024 字节,但我的上述逻辑将给出 2048 因为它完全不知道 i32
%arrayidx932 = getelementptr inbounds [256 x i32], [256 x i32]* @array5, i64 0, i64 %idxprom931, !dbg !168
谁能帮我纠正我的逻辑?
当您编写 I->getOperand(2)
时,您将获得与数组类型无关的索引之一。如果您的代码在任何情况下都能正常工作,那纯属巧合。
您得到了 T
,在本例中代表 [256 x i32]
。您已经使用 getNumElements()
获得了 256
,您可以使用 getElementType()
获得 i32
,然后从那里算出尺寸。
可能更好的方法是 get the DataLayout
off your Module
, and then call getTypeAllocSize(T)
。