CGRecordLayoutBuilder.cpp revision a860e755f1f9f071b6a6a2f96128a6a258f5c331
1//===--- CGRecordLayoutBuilder.cpp - Record builder helper ------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This is a helper class used to build CGRecordLayout objects and LLVM types.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGRecordLayoutBuilder.h"
15
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/Attr.h"
18#include "clang/AST/DeclCXX.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/RecordLayout.h"
21#include "CodeGenTypes.h"
22#include "llvm/DerivedTypes.h"
23#include "llvm/Target/TargetData.h"
24
25
26using namespace clang;
27using namespace CodeGen;
28
29void CGRecordLayoutBuilder::Layout(const RecordDecl *D) {
30  if (D->isUnion()) {
31    LayoutUnion(D);
32    return;
33  }
34
35  Packed = D->hasAttr<PackedAttr>();
36
37  if (LayoutFields(D))
38    return;
39
40  // We weren't able to layout the struct. Try again with a packed struct
41  Packed = true;
42  AlignmentAsLLVMStruct = 1;
43  NextFieldOffsetInBytes = 0;
44  FieldTypes.clear();
45  LLVMFields.clear();
46  LLVMBitFields.clear();
47
48  LayoutFields(D);
49}
50
51void CGRecordLayoutBuilder::LayoutBitField(const FieldDecl *D,
52                                           uint64_t FieldOffset) {
53  uint64_t FieldSize =
54    D->getBitWidth()->EvaluateAsInt(Types.getContext()).getZExtValue();
55
56  if (FieldSize == 0)
57    return;
58
59  uint64_t NextFieldOffset = NextFieldOffsetInBytes * 8;
60  unsigned NumBytesToAppend;
61
62  if (FieldOffset < NextFieldOffset) {
63    assert(BitsAvailableInLastField && "Bitfield size mismatch!");
64    assert(NextFieldOffsetInBytes && "Must have laid out at least one byte!");
65
66    // The bitfield begins in the previous bit-field.
67    NumBytesToAppend =
68      llvm::RoundUpToAlignment(FieldSize - BitsAvailableInLastField, 8) / 8;
69  } else {
70    assert(FieldOffset % 8 == 0 && "Field offset not aligned correctly");
71
72    // Append padding if necessary.
73    AppendBytes((FieldOffset - NextFieldOffset) / 8);
74
75    NumBytesToAppend =
76      llvm::RoundUpToAlignment(FieldSize, 8) / 8;
77
78    assert(NumBytesToAppend && "No bytes to append!");
79  }
80
81  const llvm::Type *Ty = Types.ConvertTypeForMemRecursive(D->getType());
82  uint64_t TypeSizeInBits = getTypeSizeInBytes(Ty) * 8;
83
84  LLVMBitFields.push_back(LLVMBitFieldInfo(D, FieldOffset / TypeSizeInBits,
85                                           FieldOffset % TypeSizeInBits,
86                                           FieldSize));
87
88  AppendBytes(NumBytesToAppend);
89
90  AlignmentAsLLVMStruct = std::max(AlignmentAsLLVMStruct, getTypeAlignment(Ty));
91
92  BitsAvailableInLastField =
93    NextFieldOffsetInBytes * 8 - (FieldOffset + FieldSize);
94}
95
96bool CGRecordLayoutBuilder::LayoutField(const FieldDecl *D,
97                                        uint64_t FieldOffset) {
98  // If the field is packed, then we need a packed struct.
99  if (!Packed && D->hasAttr<PackedAttr>())
100    return false;
101
102  if (D->isBitField()) {
103    // We must use packed structs for unnamed bit fields since they
104    // don't affect the struct alignment.
105    if (!Packed && !D->getDeclName())
106      return false;
107
108    LayoutBitField(D, FieldOffset);
109    return true;
110  }
111
112  assert(FieldOffset % 8 == 0 && "FieldOffset is not on a byte boundary!");
113  uint64_t FieldOffsetInBytes = FieldOffset / 8;
114
115  const llvm::Type *Ty = Types.ConvertTypeForMemRecursive(D->getType());
116  unsigned TypeAlignment = getTypeAlignment(Ty);
117
118  // Round up the field offset to the alignment of the field type.
119  uint64_t AlignedNextFieldOffsetInBytes =
120    llvm::RoundUpToAlignment(NextFieldOffsetInBytes, TypeAlignment);
121
122  if (FieldOffsetInBytes < AlignedNextFieldOffsetInBytes) {
123    assert(!Packed && "Could not place field even with packed struct!");
124    return false;
125  }
126
127  if (AlignedNextFieldOffsetInBytes < FieldOffsetInBytes) {
128    // Even with alignment, the field offset is not at the right place,
129    // insert padding.
130    uint64_t PaddingInBytes = FieldOffsetInBytes - NextFieldOffsetInBytes;
131
132    AppendBytes(PaddingInBytes);
133  }
134
135  // Now append the field.
136  LLVMFields.push_back(LLVMFieldInfo(D, FieldTypes.size()));
137  AppendField(FieldOffsetInBytes, Ty);
138
139  return true;
140}
141
142void CGRecordLayoutBuilder::LayoutUnion(const RecordDecl *D) {
143  assert(D->isUnion() && "Can't call LayoutUnion on a non-union record!");
144
145  const ASTRecordLayout &Layout = Types.getContext().getASTRecordLayout(D);
146
147  const llvm::Type *Ty = 0;
148  uint64_t Size = 0;
149  unsigned Align = 0;
150
151  unsigned FieldNo = 0;
152  for (RecordDecl::field_iterator Field = D->field_begin(),
153       FieldEnd = D->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
154    assert(Layout.getFieldOffset(FieldNo) == 0 &&
155          "Union field offset did not start at the beginning of record!");
156
157    if (Field->isBitField()) {
158      uint64_t FieldSize =
159        Field->getBitWidth()->EvaluateAsInt(Types.getContext()).getZExtValue();
160
161      // Ignore zero sized bit fields.
162      if (FieldSize == 0)
163        continue;
164
165      // Add the bit field info.
166      Types.addBitFieldInfo(*Field, 0, 0, FieldSize);
167    } else
168      Types.addFieldInfo(*Field, 0);
169
170    const llvm::Type *FieldTy =
171      Types.ConvertTypeForMemRecursive(Field->getType());
172    unsigned FieldAlign = Types.getTargetData().getABITypeAlignment(FieldTy);
173    uint64_t FieldSize = Types.getTargetData().getTypeAllocSize(FieldTy);
174
175    if (FieldAlign < Align)
176      continue;
177
178    if (FieldAlign > Align || FieldSize > Size) {
179      Ty = FieldTy;
180      Align = FieldAlign;
181      Size = FieldSize;
182    }
183  }
184
185  // Now add our field.
186  if (Ty)
187    AppendField(0, Ty);
188
189  // Append tail padding.
190  if (Layout.getSize() / 8 > Size)
191    AppendPadding(Layout.getSize() / 8, Align);
192}
193
194bool CGRecordLayoutBuilder::LayoutFields(const RecordDecl *D) {
195  assert(!D->isUnion() && "Can't call LayoutFields on a union!");
196
197  const ASTRecordLayout &Layout = Types.getContext().getASTRecordLayout(D);
198
199  unsigned FieldNo = 0;
200
201  for (RecordDecl::field_iterator Field = D->field_begin(),
202       FieldEnd = D->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
203    if (!LayoutField(*Field, Layout.getFieldOffset(FieldNo))) {
204      assert(!Packed &&
205             "Could not layout fields even with a packed LLVM struct!");
206      return false;
207    }
208  }
209
210  // Append tail padding if necessary.
211  AppendTailPadding(Layout.getSize());
212
213  return true;
214}
215
216void CGRecordLayoutBuilder::AppendTailPadding(uint64_t RecordSize) {
217  assert(RecordSize % 8 == 0 && "Invalid record size!");
218
219  uint64_t RecordSizeInBytes = RecordSize / 8;
220  assert(NextFieldOffsetInBytes <= RecordSizeInBytes && "Size mismatch!");
221
222  unsigned NumPadBytes = RecordSizeInBytes - NextFieldOffsetInBytes;
223  AppendBytes(NumPadBytes);
224}
225
226void CGRecordLayoutBuilder::AppendField(uint64_t FieldOffsetInBytes,
227                                        const llvm::Type *FieldTy) {
228  AlignmentAsLLVMStruct = std::max(AlignmentAsLLVMStruct,
229                                   getTypeAlignment(FieldTy));
230
231  uint64_t FieldSizeInBytes = getTypeSizeInBytes(FieldTy);
232
233  FieldTypes.push_back(FieldTy);
234
235  NextFieldOffsetInBytes = FieldOffsetInBytes + FieldSizeInBytes;
236  BitsAvailableInLastField = 0;
237}
238
239void
240CGRecordLayoutBuilder::AppendPadding(uint64_t FieldOffsetInBytes,
241                                     const llvm::Type *FieldTy) {
242  AppendPadding(FieldOffsetInBytes, getTypeAlignment(FieldTy));
243}
244
245void CGRecordLayoutBuilder::AppendPadding(uint64_t FieldOffsetInBytes,
246                                          unsigned FieldAlignment) {
247  assert(NextFieldOffsetInBytes <= FieldOffsetInBytes &&
248         "Incorrect field layout!");
249
250  // Round up the field offset to the alignment of the field type.
251  uint64_t AlignedNextFieldOffsetInBytes =
252    llvm::RoundUpToAlignment(NextFieldOffsetInBytes, FieldAlignment);
253
254  if (AlignedNextFieldOffsetInBytes < FieldOffsetInBytes) {
255    // Even with alignment, the field offset is not at the right place,
256    // insert padding.
257    uint64_t PaddingInBytes = FieldOffsetInBytes - NextFieldOffsetInBytes;
258
259    AppendBytes(PaddingInBytes);
260  }
261}
262
263void CGRecordLayoutBuilder::AppendBytes(uint64_t NumBytes) {
264  if (NumBytes == 0)
265    return;
266
267  const llvm::Type *Ty = llvm::Type::Int8Ty;
268  if (NumBytes > 1)
269    Ty = llvm::ArrayType::get(Ty, NumBytes);
270
271  // Append the padding field
272  AppendField(NextFieldOffsetInBytes, Ty);
273}
274
275unsigned CGRecordLayoutBuilder::getTypeAlignment(const llvm::Type *Ty) const {
276  if (Packed)
277    return 1;
278
279  return Types.getTargetData().getABITypeAlignment(Ty);
280}
281
282uint64_t CGRecordLayoutBuilder::getTypeSizeInBytes(const llvm::Type *Ty) const {
283  return Types.getTargetData().getTypeAllocSize(Ty);
284}
285
286CGRecordLayout *
287CGRecordLayoutBuilder::ComputeLayout(CodeGenTypes &Types,
288                                     const RecordDecl *D) {
289  CGRecordLayoutBuilder Builder(Types);
290
291  Builder.Layout(D);
292
293  const llvm::Type *Ty = llvm::StructType::get(Types.getLLVMContext(),
294                                               Builder.FieldTypes,
295                                               Builder.Packed);
296  assert(Types.getContext().getASTRecordLayout(D).getSize() / 8 ==
297         Types.getTargetData().getTypeAllocSize(Ty) &&
298         "Type size mismatch!");
299
300  // Add all the field numbers.
301  for (unsigned i = 0, e = Builder.LLVMFields.size(); i != e; ++i) {
302    const FieldDecl *FD = Builder.LLVMFields[i].first;
303    unsigned FieldNo = Builder.LLVMFields[i].second;
304
305    Types.addFieldInfo(FD, FieldNo);
306  }
307
308  // Add bitfield info.
309  for (unsigned i = 0, e = Builder.LLVMBitFields.size(); i != e; ++i) {
310    const LLVMBitFieldInfo &Info = Builder.LLVMBitFields[i];
311
312    Types.addBitFieldInfo(Info.FD, Info.FieldNo, Info.Start, Info.Size);
313  }
314
315  return new CGRecordLayout(Ty, llvm::SmallSet<unsigned, 8>());
316}
317