Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the size of a variable in Clang

Tags:

c++

c

clang

With the Clang library, is there some available method to get the size of a variable (as if I used sizeof() in a regular C/C++ program ?

I am able (and this is what I want to do) to spot VarDecl, but at the moment I still can't find any method in the Clang namespace to get the size of my var spotted with the current VarDecl

like image 446
Marc-O Avatar asked Mar 19 '23 21:03

Marc-O


1 Answers

Size information for a type is stored in a TypeInfo associated with a given type. You can get a corresponding FieldInfo pair from the ASTContext via the getTypeInfo function. The first element of the pair is the size of the type in bits. The second element is the alignment of the type in bits.

bool VisitVarDecl(VarDecl *VD) {
    std::pair<uint64_t, unsigned> FieldInfo = VD->getASTContext().getTypeInfo(VD->getType());
    uint64_t TypeSize = FieldInfo.first;
    unsigned FieldAlign = FieldInfo.second;
    llvm::outs() << VD->getNameAsString() << " Size: " << TypeSize/8 << " Alignment: " << FieldAlign/8 << '\n';
}
like image 63
Robin Joy Avatar answered Mar 21 '23 11:03

Robin Joy