Search code examples
llvmllvm-irllvm-c++-api

How to determine the size of memory a particular load/store is accessing in LLVM IR?


I want to know if load/store accesses a byte, half word, word, or double word in LLVM IR.

There is a this funtion getAlignment() in llvm::LoadInst and in llvm:StoreInst classes. Its description says it returns the alignment of the access that is being performed. I'm not sure if this gives the memory alignment or no of bytes it accesses?


Solution

  • DataLayout* dataLayout = new DataLayout(&module);
    Value* memoryPointer = loadInstruction->getPointerOperand();
    PointerType* pointerType = cast<PointerType>(memoryPointer->getType());                         
    uint64_t storeSize = dataLayout->getTypeStoreSize(pointerType->getPointerElementType());
    

    I have this code working on llvm-3.7. storeSize would be the size of the operand in bytes. Here module is the module pointer that you get as parameter in a module pass. The function getPointerOperand works for both load and store instructions. Here is the reference for function getTypeStoreSize. There are other functions like getTypeStoreSizeInBits, getTypeAllocSize etc which you can use as per your need.