问题
How can the total number of arrays be counted in a C program ?
The array declarations in LLVM IR correspond to alloca type of operation. So
int a[10];
corresponds to
%a = alloca [10 x i32], align 4
in LLVM IR.
But I also noticed that
int j = 0;
also corresponds to an alloca instruction
%j = alloca i32, align 4
So how to count the number of alloca instructions that correspond only to arrays ?
EDIT:
for (Function::iterator i = F.begin(), e = F.end(); i != e; ++i)
{
for (BasicBlock::iterator ii =(*i).begin(), ii_e = (*i).end(); ii != ii_e; ++ii)
{
Instruction *n = dyn_cast<Instruction>(&*ii);
for( int num = 0; num < n->getNumOperands(); ++num)
if(isa<ArrayType>(n->getOperand(num)->getType()))
{
// doesn't work
errs()<<"yayayayay Array\n";
}
}
}
回答1:
AllocaInst has public method isArrayAllocation(). You can use it to count the number of alloca instructions that correspond only to arrays.
for (Function::iterator BB = F.begin(), BE = F.end(); BB != BE; ++BB)
for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE; ++II)
if (AllocaInst *AI = dyn_cast<AllocaInst>(II))
if (AI->isArrayAllocation())
errs() << "Alloca of array is found!\n";
回答2:
Open the LLVM demo page and compile following code
int main(int argc, char **argv) {
int a[10];
return 0;
}
to the LLVM C++ API calls.
This is how a created:
AllocaInst* ptr_a = new AllocaInst(ArrayTy_6, "a", label_9);
where ArrayTy_6 is:
ArrayType* ArrayTy_6 = ArrayType::get(IntegerType::get(mod->getContext(), 32), 10);
So, to find out if alloca instruction you are looking at is defining array, just do isa<ArrayType>() on it's first argument.
See LLVM docs for more info.
来源:https://stackoverflow.com/questions/12033920/count-number-of-arrays