CGRecordLayoutBuilder.cpp revision 206084
1//===--- CGRecordLayoutBuilder.cpp - CGRecordLayout builder  ----*- 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// Builder implementation for CGRecordLayout objects.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGRecordLayout.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/Attr.h"
17#include "clang/AST/DeclCXX.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/RecordLayout.h"
20#include "CodeGenTypes.h"
21#include "llvm/Type.h"
22#include "llvm/DerivedTypes.h"
23#include "llvm/Target/TargetData.h"
24using namespace clang;
25using namespace CodeGen;
26
27namespace clang {
28namespace CodeGen {
29
30class CGRecordLayoutBuilder {
31public:
32  /// FieldTypes - Holds the LLVM types that the struct is created from.
33  std::vector<const llvm::Type *> FieldTypes;
34
35  /// LLVMFieldInfo - Holds a field and its corresponding LLVM field number.
36  typedef std::pair<const FieldDecl *, unsigned> LLVMFieldInfo;
37  llvm::SmallVector<LLVMFieldInfo, 16> LLVMFields;
38
39  /// LLVMBitFieldInfo - Holds location and size information about a bit field.
40  struct LLVMBitFieldInfo {
41    LLVMBitFieldInfo(const FieldDecl *FD, unsigned FieldNo, unsigned Start,
42                     unsigned Size)
43      : FD(FD), FieldNo(FieldNo), Start(Start), Size(Size) { }
44
45    const FieldDecl *FD;
46
47    unsigned FieldNo;
48    unsigned Start;
49    unsigned Size;
50  };
51  llvm::SmallVector<LLVMBitFieldInfo, 16> LLVMBitFields;
52
53  /// ContainsPointerToDataMember - Whether one of the fields in this record
54  /// layout is a pointer to data member, or a struct that contains pointer to
55  /// data member.
56  bool ContainsPointerToDataMember;
57
58  /// Packed - Whether the resulting LLVM struct will be packed or not.
59  bool Packed;
60
61private:
62  CodeGenTypes &Types;
63
64  /// Alignment - Contains the alignment of the RecordDecl.
65  //
66  // FIXME: This is not needed and should be removed.
67  unsigned Alignment;
68
69  /// AlignmentAsLLVMStruct - Will contain the maximum alignment of all the
70  /// LLVM types.
71  unsigned AlignmentAsLLVMStruct;
72
73  /// BitsAvailableInLastField - If a bit field spans only part of a LLVM field,
74  /// this will have the number of bits still available in the field.
75  char BitsAvailableInLastField;
76
77  /// NextFieldOffsetInBytes - Holds the next field offset in bytes.
78  uint64_t NextFieldOffsetInBytes;
79
80  /// LayoutUnion - Will layout a union RecordDecl.
81  void LayoutUnion(const RecordDecl *D);
82
83  /// LayoutField - try to layout all fields in the record decl.
84  /// Returns false if the operation failed because the struct is not packed.
85  bool LayoutFields(const RecordDecl *D);
86
87  /// LayoutBases - layout the bases and vtable pointer of a record decl.
88  void LayoutBases(const CXXRecordDecl *RD, const ASTRecordLayout &Layout);
89
90  /// LayoutField - layout a single field. Returns false if the operation failed
91  /// because the current struct is not packed.
92  bool LayoutField(const FieldDecl *D, uint64_t FieldOffset);
93
94  /// LayoutBitField - layout a single bit field.
95  void LayoutBitField(const FieldDecl *D, uint64_t FieldOffset);
96
97  /// AppendField - Appends a field with the given offset and type.
98  void AppendField(uint64_t FieldOffsetInBytes, const llvm::Type *FieldTy);
99
100  /// AppendPadding - Appends enough padding bytes so that the total struct
101  /// size matches the alignment of the passed in type.
102  void AppendPadding(uint64_t FieldOffsetInBytes, const llvm::Type *FieldTy);
103
104  /// AppendPadding - Appends enough padding bytes so that the total
105  /// struct size is a multiple of the field alignment.
106  void AppendPadding(uint64_t FieldOffsetInBytes, unsigned FieldAlignment);
107
108  /// AppendBytes - Append a given number of bytes to the record.
109  void AppendBytes(uint64_t NumBytes);
110
111  /// AppendTailPadding - Append enough tail padding so that the type will have
112  /// the passed size.
113  void AppendTailPadding(uint64_t RecordSize);
114
115  unsigned getTypeAlignment(const llvm::Type *Ty) const;
116  uint64_t getTypeSizeInBytes(const llvm::Type *Ty) const;
117
118  /// CheckForPointerToDataMember - Check if the given type contains a pointer
119  /// to data member.
120  void CheckForPointerToDataMember(QualType T);
121
122public:
123  CGRecordLayoutBuilder(CodeGenTypes &Types)
124    : ContainsPointerToDataMember(false), Packed(false), Types(Types),
125      Alignment(0), AlignmentAsLLVMStruct(1),
126      BitsAvailableInLastField(0), NextFieldOffsetInBytes(0) { }
127
128  /// Layout - Will layout a RecordDecl.
129  void Layout(const RecordDecl *D);
130};
131
132}
133}
134
135void CGRecordLayoutBuilder::Layout(const RecordDecl *D) {
136  Alignment = Types.getContext().getASTRecordLayout(D).getAlignment() / 8;
137  Packed = D->hasAttr<PackedAttr>();
138
139  if (D->isUnion()) {
140    LayoutUnion(D);
141    return;
142  }
143
144  if (LayoutFields(D))
145    return;
146
147  // We weren't able to layout the struct. Try again with a packed struct
148  Packed = true;
149  AlignmentAsLLVMStruct = 1;
150  NextFieldOffsetInBytes = 0;
151  FieldTypes.clear();
152  LLVMFields.clear();
153  LLVMBitFields.clear();
154
155  LayoutFields(D);
156}
157
158void CGRecordLayoutBuilder::LayoutBitField(const FieldDecl *D,
159                                           uint64_t FieldOffset) {
160  uint64_t FieldSize =
161    D->getBitWidth()->EvaluateAsInt(Types.getContext()).getZExtValue();
162
163  if (FieldSize == 0)
164    return;
165
166  uint64_t NextFieldOffset = NextFieldOffsetInBytes * 8;
167  unsigned NumBytesToAppend;
168
169  if (FieldOffset < NextFieldOffset) {
170    assert(BitsAvailableInLastField && "Bitfield size mismatch!");
171    assert(NextFieldOffsetInBytes && "Must have laid out at least one byte!");
172
173    // The bitfield begins in the previous bit-field.
174    NumBytesToAppend =
175      llvm::RoundUpToAlignment(FieldSize - BitsAvailableInLastField, 8) / 8;
176  } else {
177    assert(FieldOffset % 8 == 0 && "Field offset not aligned correctly");
178
179    // Append padding if necessary.
180    AppendBytes((FieldOffset - NextFieldOffset) / 8);
181
182    NumBytesToAppend =
183      llvm::RoundUpToAlignment(FieldSize, 8) / 8;
184
185    assert(NumBytesToAppend && "No bytes to append!");
186  }
187
188  const llvm::Type *Ty = Types.ConvertTypeForMemRecursive(D->getType());
189  uint64_t TypeSizeInBits = getTypeSizeInBytes(Ty) * 8;
190
191  LLVMBitFields.push_back(LLVMBitFieldInfo(D, FieldOffset / TypeSizeInBits,
192                                           FieldOffset % TypeSizeInBits,
193                                           FieldSize));
194
195  AppendBytes(NumBytesToAppend);
196
197  BitsAvailableInLastField =
198    NextFieldOffsetInBytes * 8 - (FieldOffset + FieldSize);
199}
200
201bool CGRecordLayoutBuilder::LayoutField(const FieldDecl *D,
202                                        uint64_t FieldOffset) {
203  // If the field is packed, then we need a packed struct.
204  if (!Packed && D->hasAttr<PackedAttr>())
205    return false;
206
207  if (D->isBitField()) {
208    // We must use packed structs for unnamed bit fields since they
209    // don't affect the struct alignment.
210    if (!Packed && !D->getDeclName())
211      return false;
212
213    LayoutBitField(D, FieldOffset);
214    return true;
215  }
216
217  // Check if we have a pointer to data member in this field.
218  CheckForPointerToDataMember(D->getType());
219
220  assert(FieldOffset % 8 == 0 && "FieldOffset is not on a byte boundary!");
221  uint64_t FieldOffsetInBytes = FieldOffset / 8;
222
223  const llvm::Type *Ty = Types.ConvertTypeForMemRecursive(D->getType());
224  unsigned TypeAlignment = getTypeAlignment(Ty);
225
226  // If the type alignment is larger then the struct alignment, we must use
227  // a packed struct.
228  if (TypeAlignment > Alignment) {
229    assert(!Packed && "Alignment is wrong even with packed struct!");
230    return false;
231  }
232
233  if (const RecordType *RT = D->getType()->getAs<RecordType>()) {
234    const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
235    if (const PragmaPackAttr *PPA = RD->getAttr<PragmaPackAttr>()) {
236      if (PPA->getAlignment() != TypeAlignment * 8 && !Packed)
237        return false;
238    }
239  }
240
241  // Round up the field offset to the alignment of the field type.
242  uint64_t AlignedNextFieldOffsetInBytes =
243    llvm::RoundUpToAlignment(NextFieldOffsetInBytes, TypeAlignment);
244
245  if (FieldOffsetInBytes < AlignedNextFieldOffsetInBytes) {
246    assert(!Packed && "Could not place field even with packed struct!");
247    return false;
248  }
249
250  if (AlignedNextFieldOffsetInBytes < FieldOffsetInBytes) {
251    // Even with alignment, the field offset is not at the right place,
252    // insert padding.
253    uint64_t PaddingInBytes = FieldOffsetInBytes - NextFieldOffsetInBytes;
254
255    AppendBytes(PaddingInBytes);
256  }
257
258  // Now append the field.
259  LLVMFields.push_back(LLVMFieldInfo(D, FieldTypes.size()));
260  AppendField(FieldOffsetInBytes, Ty);
261
262  return true;
263}
264
265void CGRecordLayoutBuilder::LayoutUnion(const RecordDecl *D) {
266  assert(D->isUnion() && "Can't call LayoutUnion on a non-union record!");
267
268  const ASTRecordLayout &Layout = Types.getContext().getASTRecordLayout(D);
269
270  const llvm::Type *Ty = 0;
271  uint64_t Size = 0;
272  unsigned Align = 0;
273
274  bool HasOnlyZeroSizedBitFields = true;
275
276  unsigned FieldNo = 0;
277  for (RecordDecl::field_iterator Field = D->field_begin(),
278       FieldEnd = D->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
279    assert(Layout.getFieldOffset(FieldNo) == 0 &&
280          "Union field offset did not start at the beginning of record!");
281
282    if (Field->isBitField()) {
283      uint64_t FieldSize =
284        Field->getBitWidth()->EvaluateAsInt(Types.getContext()).getZExtValue();
285
286      // Ignore zero sized bit fields.
287      if (FieldSize == 0)
288        continue;
289
290      // Add the bit field info.
291      LLVMBitFields.push_back(LLVMBitFieldInfo(*Field, 0, 0, FieldSize));
292    } else {
293      LLVMFields.push_back(LLVMFieldInfo(*Field, 0));
294    }
295
296    HasOnlyZeroSizedBitFields = false;
297
298    const llvm::Type *FieldTy =
299      Types.ConvertTypeForMemRecursive(Field->getType());
300    unsigned FieldAlign = Types.getTargetData().getABITypeAlignment(FieldTy);
301    uint64_t FieldSize = Types.getTargetData().getTypeAllocSize(FieldTy);
302
303    if (FieldAlign < Align)
304      continue;
305
306    if (FieldAlign > Align || FieldSize > Size) {
307      Ty = FieldTy;
308      Align = FieldAlign;
309      Size = FieldSize;
310    }
311  }
312
313  // Now add our field.
314  if (Ty) {
315    AppendField(0, Ty);
316
317    if (getTypeAlignment(Ty) > Layout.getAlignment() / 8) {
318      // We need a packed struct.
319      Packed = true;
320      Align = 1;
321    }
322  }
323  if (!Align) {
324    assert(HasOnlyZeroSizedBitFields &&
325           "0-align record did not have all zero-sized bit-fields!");
326    Align = 1;
327  }
328
329  // Append tail padding.
330  if (Layout.getSize() / 8 > Size)
331    AppendPadding(Layout.getSize() / 8, Align);
332}
333
334void CGRecordLayoutBuilder::LayoutBases(const CXXRecordDecl *RD,
335                                        const ASTRecordLayout &Layout) {
336  // Check if we need to add a vtable pointer.
337  if (RD->isDynamicClass() && !Layout.getPrimaryBase()) {
338    const llvm::Type *Int8PtrTy =
339      llvm::Type::getInt8PtrTy(Types.getLLVMContext());
340
341    assert(NextFieldOffsetInBytes == 0 &&
342           "Vtable pointer must come first!");
343    AppendField(NextFieldOffsetInBytes, Int8PtrTy->getPointerTo());
344  }
345}
346
347bool CGRecordLayoutBuilder::LayoutFields(const RecordDecl *D) {
348  assert(!D->isUnion() && "Can't call LayoutFields on a union!");
349  assert(Alignment && "Did not set alignment!");
350
351  const ASTRecordLayout &Layout = Types.getContext().getASTRecordLayout(D);
352
353  if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
354    LayoutBases(RD, Layout);
355
356  unsigned FieldNo = 0;
357
358  for (RecordDecl::field_iterator Field = D->field_begin(),
359       FieldEnd = D->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
360    if (!LayoutField(*Field, Layout.getFieldOffset(FieldNo))) {
361      assert(!Packed &&
362             "Could not layout fields even with a packed LLVM struct!");
363      return false;
364    }
365  }
366
367  // Append tail padding if necessary.
368  AppendTailPadding(Layout.getSize());
369
370  return true;
371}
372
373void CGRecordLayoutBuilder::AppendTailPadding(uint64_t RecordSize) {
374  assert(RecordSize % 8 == 0 && "Invalid record size!");
375
376  uint64_t RecordSizeInBytes = RecordSize / 8;
377  assert(NextFieldOffsetInBytes <= RecordSizeInBytes && "Size mismatch!");
378
379  uint64_t AlignedNextFieldOffset =
380    llvm::RoundUpToAlignment(NextFieldOffsetInBytes, AlignmentAsLLVMStruct);
381
382  if (AlignedNextFieldOffset == RecordSizeInBytes) {
383    // We don't need any padding.
384    return;
385  }
386
387  unsigned NumPadBytes = RecordSizeInBytes - NextFieldOffsetInBytes;
388  AppendBytes(NumPadBytes);
389}
390
391void CGRecordLayoutBuilder::AppendField(uint64_t FieldOffsetInBytes,
392                                        const llvm::Type *FieldTy) {
393  AlignmentAsLLVMStruct = std::max(AlignmentAsLLVMStruct,
394                                   getTypeAlignment(FieldTy));
395
396  uint64_t FieldSizeInBytes = getTypeSizeInBytes(FieldTy);
397
398  FieldTypes.push_back(FieldTy);
399
400  NextFieldOffsetInBytes = FieldOffsetInBytes + FieldSizeInBytes;
401  BitsAvailableInLastField = 0;
402}
403
404void
405CGRecordLayoutBuilder::AppendPadding(uint64_t FieldOffsetInBytes,
406                                     const llvm::Type *FieldTy) {
407  AppendPadding(FieldOffsetInBytes, getTypeAlignment(FieldTy));
408}
409
410void CGRecordLayoutBuilder::AppendPadding(uint64_t FieldOffsetInBytes,
411                                          unsigned FieldAlignment) {
412  assert(NextFieldOffsetInBytes <= FieldOffsetInBytes &&
413         "Incorrect field layout!");
414
415  // Round up the field offset to the alignment of the field type.
416  uint64_t AlignedNextFieldOffsetInBytes =
417    llvm::RoundUpToAlignment(NextFieldOffsetInBytes, FieldAlignment);
418
419  if (AlignedNextFieldOffsetInBytes < FieldOffsetInBytes) {
420    // Even with alignment, the field offset is not at the right place,
421    // insert padding.
422    uint64_t PaddingInBytes = FieldOffsetInBytes - NextFieldOffsetInBytes;
423
424    AppendBytes(PaddingInBytes);
425  }
426}
427
428void CGRecordLayoutBuilder::AppendBytes(uint64_t NumBytes) {
429  if (NumBytes == 0)
430    return;
431
432  const llvm::Type *Ty = llvm::Type::getInt8Ty(Types.getLLVMContext());
433  if (NumBytes > 1)
434    Ty = llvm::ArrayType::get(Ty, NumBytes);
435
436  // Append the padding field
437  AppendField(NextFieldOffsetInBytes, Ty);
438}
439
440unsigned CGRecordLayoutBuilder::getTypeAlignment(const llvm::Type *Ty) const {
441  if (Packed)
442    return 1;
443
444  return Types.getTargetData().getABITypeAlignment(Ty);
445}
446
447uint64_t CGRecordLayoutBuilder::getTypeSizeInBytes(const llvm::Type *Ty) const {
448  return Types.getTargetData().getTypeAllocSize(Ty);
449}
450
451void CGRecordLayoutBuilder::CheckForPointerToDataMember(QualType T) {
452  // This record already contains a member pointer.
453  if (ContainsPointerToDataMember)
454    return;
455
456  // Can only have member pointers if we're compiling C++.
457  if (!Types.getContext().getLangOptions().CPlusPlus)
458    return;
459
460  T = Types.getContext().getBaseElementType(T);
461
462  if (const MemberPointerType *MPT = T->getAs<MemberPointerType>()) {
463    if (!MPT->getPointeeType()->isFunctionType()) {
464      // We have a pointer to data member.
465      ContainsPointerToDataMember = true;
466    }
467  } else if (const RecordType *RT = T->getAs<RecordType>()) {
468    const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
469
470    // FIXME: It would be better if there was a way to explicitly compute the
471    // record layout instead of converting to a type.
472    Types.ConvertTagDeclType(RD);
473
474    const CGRecordLayout &Layout = Types.getCGRecordLayout(RD);
475
476    if (Layout.containsPointerToDataMember())
477      ContainsPointerToDataMember = true;
478  }
479}
480
481CGRecordLayout *CodeGenTypes::ComputeRecordLayout(const RecordDecl *D) {
482  CGRecordLayoutBuilder Builder(*this);
483
484  Builder.Layout(D);
485
486  const llvm::Type *Ty = llvm::StructType::get(getLLVMContext(),
487                                               Builder.FieldTypes,
488                                               Builder.Packed);
489  assert(getContext().getASTRecordLayout(D).getSize() / 8 ==
490         getTargetData().getTypeAllocSize(Ty) &&
491         "Type size mismatch!");
492
493  CGRecordLayout *RL =
494    new CGRecordLayout(Ty, Builder.ContainsPointerToDataMember);
495
496  // Add all the field numbers.
497  for (unsigned i = 0, e = Builder.LLVMFields.size(); i != e; ++i) {
498    const FieldDecl *FD = Builder.LLVMFields[i].first;
499    unsigned FieldNo = Builder.LLVMFields[i].second;
500
501    RL->FieldInfo.insert(std::make_pair(FD, FieldNo));
502  }
503
504  // Add bitfield info.
505  for (unsigned i = 0, e = Builder.LLVMBitFields.size(); i != e; ++i) {
506    const CGRecordLayoutBuilder::LLVMBitFieldInfo &Info =
507      Builder.LLVMBitFields[i];
508
509    CGRecordLayout::BitFieldInfo BFI(Info.FieldNo, Info.Start, Info.Size);
510    RL->BitFields.insert(std::make_pair(Info.FD, BFI));
511  }
512
513  return RL;
514}
515