如何从llvm的getelementptr指令中提取数组索引值

How to extract the array index value from getelementptr instruction of llvm

array[5] = 20;

等效的 LLVM IR

%arrayidx = getelementptr inbounds i32, i32* %2, i64 5
store i32 20, i32* %arrayidx, align 4

如何从 LLVM IR 中提取 5?

如果你有一个 GetElementPtrInst* GEP,你可以使用 GEP->getOperand(i) 访问索引(操作数 0 是指针,其余操作数是索引)。要获得值 5,您可以检查索引是否为 ConstantInt,如果是,则获取其值,如下所示:

if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(1)) {
    uint64_t Idx = CI->getZExtValue();
}