2016-10-23 70 views
0

我想要得到嵌套結構/數組數據類型的確切字節表示。例如,以下C結構:嵌套結構/數組的LLVM對齊

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任意嵌套的數據類型爲我的目標架構的準確佈局傳遞?

回答

1

這是ABI特定的,所以它取決於目標。 Clang將通常將C/C++計算爲各個成員對齊的最大值。 這裏整數是最大的字段,並且具有4的默認對齊約束,這就是你所得到的。

鐺具有-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 
+0

你知道我怎麼能在我的通行證裏面得到這些信息嗎? – user2600312

+0

用LLVM API更新了答案。 – Joky