【问题标题】:LLVM alignment of nested structs/arrays嵌套结构/数组的 LLVM 对齐
【发布时间】:2016-10-30 02:02:18
【问题描述】:

我想获得嵌套结构/数组数据类型的确切字节表示。例如下面的 C 结构体:

typedef struct zTy {
    int x;
    char c[2];
    struct  { char d; } v;
} z;

它被转换为以下 LLVM IR:

%struct.zTy = type { i32, [2 x i8], %struct.anon }
%struct.anon = type { i8 }

%a = alloca %struct.zTy, align 4

从 alloca 指令可以看到对齐(4 字节)。但我不知道在哪里插入对齐或如何计算嵌套结构的对齐。 我使用 getTypeAllocSize() 获得目标三元组的结构的总大小:

AllocaInst* AI;
Module &M;
Type* T = AI->getAllocatedType();
int size = M.getDataLayout()->getTypeAllocSize(T) // 8 Byte

有没有办法通过 LLVM 通道确定目标架构的任意嵌套数据类型的确切布局?

【问题讨论】:

    标签: struct alignment llvm llvm-c++-api


    【解决方案1】:

    这是特定于 ABI 的,因此取决于目标。对于 C/C++,Clang 通常会将其计算为单个成员对齐的最大值。 这里整数是最大的字段,并且有一个默认的对齐约束 4,这就是你得到的。

    Clang 有 -fdump-record-layouts 作为 cc1 选项来帮助确定结构/类的布局,例如这里:

    $ echo "struct zTy {
        int x;
        char c[2];
        struct  { char d; } v;
    } z;" | clang -x c  -w - -Xclang -fdump-record-layouts  -c
    
    *** Dumping AST Record Layout
             0 | struct zTy::(anonymous at <stdin>:4:5)
             0 |   char d
               | [sizeof=1, align=1]
    
    *** Dumping AST Record Layout
             0 | struct zTy
             0 |   int x
             4 |   char [2] c
             6 |   struct zTy::(anonymous at <stdin>:4:5) v
             6 |     char d
               | [sizeof=8, align=4]
    

    在 LLVM 内部,您会丢失“C”类型,但如果您想检查一个结构,您需要使用:

    const StructLayout *getStructLayout(StructType *Ty) const;
    

    然后使用返回的StructLayout,您可以使用以下方法获取每个元素的偏移量:

    uint64_t StructLayout::getElementOffsetInBits(unsigned Idx) const
    

    【讨论】:

    • 您知道我如何在通行证中获取这些信息吗?
    • 使用 LLVM API 更新了答案。
    猜你喜欢
    • 2023-03-27
    • 1970-01-01
    • 2015-08-14
    • 2017-06-14
    • 2011-12-18
    • 1970-01-01
    • 1970-01-01
    • 2020-08-23
    • 1970-01-01
    相关资源
    最近更新 更多