GEP的第一個操作數(getelementptr
指令)是一個指針,而不是一個數組。該指針可能指向一個數組,或者它可能不是(見下文)。所以你需要看看這個指針指向什麼。
下面是一個示例BasicBlockPass
訪問者:
virtual bool runOnBasicBlock(BasicBlock &BB) {
for (BasicBlock::iterator ii = BB.begin(), ii_e = BB.end(); ii != ii_e; ++ii) {
if (GetElementPtrInst *gep = dyn_cast<GetElementPtrInst>(&*ii)) {
// Dump the GEP instruction
gep->dump();
Value* firstOperand = gep->getOperand(0);
Type* type = firstOperand->getType();
// Figure out whether the first operand points to an array
if (PointerType *pointerType = dyn_cast<PointerType>(type)) {
Type* elementType = pointerType->getElementType();
errs() << "The element type is: " << *elementType << "\n";
if (elementType->isArrayTy()) {
errs() << " .. points to an array!\n";
}
}
}
}
return false;
}
但請注意,許多「陣列」,在C/C++實際上是指針,所以你可能不會得到你所期望的數組類型。
例如,如果您編譯此代碼:
int main(int argc, char **argv) {
return (int)argv[1][8];
}
你獲得IR:
define i32 @main(i32 %argc, i8** %argv) nounwind uwtable {
%1 = alloca i32, align 4
%2 = alloca i32, align 4
%3 = alloca i8**, align 8
store i32 0, i32* %1
store i32 %argc, i32* %2, align 4
store i8** %argv, i8*** %3, align 8
%4 = load i8*** %3, align 8
%5 = getelementptr inbounds i8** %4, i64 1
%6 = load i8** %5
%7 = getelementptr inbounds i8* %6, i64 8
%8 = load i8* %7
%9 = sext i8 %8 to i32
ret i32 %9
}
雖然argv
是處理作爲數組,編譯器認爲它作爲一個指針,所以沒有陣列類型。我上面粘貼的pass在這裏不會識別數組,因爲GEP的第一個操作數是指向的指針。