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 
26 using namespace clang;
27 using namespace CodeGen;
28 
29 void CGRecordLayoutBuilder::Layout(const RecordDecl *D) {
30   Alignment = Types.getContext().getASTRecordLayout(D).getAlignment() / 8;
31   Packed = D->hasAttr<PackedAttr>();
32 
33   if (D->isUnion()) {
34     LayoutUnion(D);
35     return;
36   }
37 
38   if (LayoutFields(D))
39     return;
40 
41   // We weren't able to layout the struct. Try again with a packed struct
42   Packed = true;
43   AlignmentAsLLVMStruct = 1;
44   NextFieldOffsetInBytes = 0;
45   FieldTypes.clear();
46   LLVMFields.clear();
47   LLVMBitFields.clear();
48 
49   LayoutFields(D);
50 }
51 
52 void CGRecordLayoutBuilder::LayoutBitField(const FieldDecl *D,
53                                            uint64_t FieldOffset) {
54   uint64_t FieldSize =
55     D->getBitWidth()->EvaluateAsInt(Types.getContext()).getZExtValue();
56 
57   if (FieldSize == 0)
58     return;
59 
60   uint64_t NextFieldOffset = NextFieldOffsetInBytes * 8;
61   unsigned NumBytesToAppend;
62 
63   if (FieldOffset < NextFieldOffset) {
64     assert(BitsAvailableInLastField && "Bitfield size mismatch!");
65     assert(NextFieldOffsetInBytes && "Must have laid out at least one byte!");
66 
67     // The bitfield begins in the previous bit-field.
68     NumBytesToAppend =
69       llvm::RoundUpToAlignment(FieldSize - BitsAvailableInLastField, 8) / 8;
70   } else {
71     assert(FieldOffset % 8 == 0 && "Field offset not aligned correctly");
72 
73     // Append padding if necessary.
74     AppendBytes((FieldOffset - NextFieldOffset) / 8);
75 
76     NumBytesToAppend =
77       llvm::RoundUpToAlignment(FieldSize, 8) / 8;
78 
79     assert(NumBytesToAppend && "No bytes to append!");
80   }
81 
82   const llvm::Type *Ty = Types.ConvertTypeForMemRecursive(D->getType());
83   uint64_t TypeSizeInBits = getTypeSizeInBytes(Ty) * 8;
84 
85   LLVMBitFields.push_back(LLVMBitFieldInfo(D, FieldOffset / TypeSizeInBits,
86                                            FieldOffset % TypeSizeInBits,
87                                            FieldSize));
88 
89   AppendBytes(NumBytesToAppend);
90 
91   BitsAvailableInLastField =
92     NextFieldOffsetInBytes * 8 - (FieldOffset + FieldSize);
93 }
94 
95 bool CGRecordLayoutBuilder::LayoutField(const FieldDecl *D,
96                                         uint64_t FieldOffset) {
97   // If the field is packed, then we need a packed struct.
98   if (!Packed && D->hasAttr<PackedAttr>())
99     return false;
100 
101   if (D->isBitField()) {
102     // We must use packed structs for unnamed bit fields since they
103     // don't affect the struct alignment.
104     if (!Packed && !D->getDeclName())
105       return false;
106 
107     LayoutBitField(D, FieldOffset);
108     return true;
109   }
110 
111   assert(FieldOffset % 8 == 0 && "FieldOffset is not on a byte boundary!");
112   uint64_t FieldOffsetInBytes = FieldOffset / 8;
113 
114   const llvm::Type *Ty = Types.ConvertTypeForMemRecursive(D->getType());
115   unsigned TypeAlignment = getTypeAlignment(Ty);
116 
117   // If the type alignment is larger then the struct alignment, we must use
118   // a packed struct.
119   if (TypeAlignment > Alignment) {
120     assert(!Packed && "Alignment is wrong even with packed struct!");
121     return false;
122   }
123 
124   if (const RecordType *RT = D->getType()->getAs<RecordType>()) {
125     const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
126     if (const PragmaPackAttr *PPA = RD->getAttr<PragmaPackAttr>()) {
127       if (PPA->getAlignment() != TypeAlignment * 8 && !Packed)
128         return false;
129     }
130   }
131 
132   // Round up the field offset to the alignment of the field type.
133   uint64_t AlignedNextFieldOffsetInBytes =
134     llvm::RoundUpToAlignment(NextFieldOffsetInBytes, TypeAlignment);
135 
136   if (FieldOffsetInBytes < AlignedNextFieldOffsetInBytes) {
137     assert(!Packed && "Could not place field even with packed struct!");
138     return false;
139   }
140 
141   if (AlignedNextFieldOffsetInBytes < FieldOffsetInBytes) {
142     // Even with alignment, the field offset is not at the right place,
143     // insert padding.
144     uint64_t PaddingInBytes = FieldOffsetInBytes - NextFieldOffsetInBytes;
145 
146     AppendBytes(PaddingInBytes);
147   }
148 
149   // Now append the field.
150   LLVMFields.push_back(LLVMFieldInfo(D, FieldTypes.size()));
151   AppendField(FieldOffsetInBytes, Ty);
152 
153   return true;
154 }
155 
156 void CGRecordLayoutBuilder::LayoutUnion(const RecordDecl *D) {
157   assert(D->isUnion() && "Can't call LayoutUnion on a non-union record!");
158 
159   const ASTRecordLayout &Layout = Types.getContext().getASTRecordLayout(D);
160 
161   const llvm::Type *Ty = 0;
162   uint64_t Size = 0;
163   unsigned Align = 0;
164 
165   bool HasOnlyZeroSizedBitFields = true;
166 
167   unsigned FieldNo = 0;
168   for (RecordDecl::field_iterator Field = D->field_begin(),
169        FieldEnd = D->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
170     assert(Layout.getFieldOffset(FieldNo) == 0 &&
171           "Union field offset did not start at the beginning of record!");
172 
173     if (Field->isBitField()) {
174       uint64_t FieldSize =
175         Field->getBitWidth()->EvaluateAsInt(Types.getContext()).getZExtValue();
176 
177       // Ignore zero sized bit fields.
178       if (FieldSize == 0)
179         continue;
180 
181       // Add the bit field info.
182       Types.addBitFieldInfo(*Field, 0, 0, FieldSize);
183     } else
184       Types.addFieldInfo(*Field, 0);
185 
186     HasOnlyZeroSizedBitFields = false;
187 
188     const llvm::Type *FieldTy =
189       Types.ConvertTypeForMemRecursive(Field->getType());
190     unsigned FieldAlign = Types.getTargetData().getABITypeAlignment(FieldTy);
191     uint64_t FieldSize = Types.getTargetData().getTypeAllocSize(FieldTy);
192 
193     if (FieldAlign < Align)
194       continue;
195 
196     if (FieldAlign > Align || FieldSize > Size) {
197       Ty = FieldTy;
198       Align = FieldAlign;
199       Size = FieldSize;
200     }
201   }
202 
203   // Now add our field.
204   if (Ty) {
205     AppendField(0, Ty);
206 
207     if (getTypeAlignment(Ty) > Layout.getAlignment() / 8) {
208       // We need a packed struct.
209       Packed = true;
210       Align = 1;
211     }
212   }
213   if (!Align) {
214     assert(HasOnlyZeroSizedBitFields &&
215            "0-align record did not have all zero-sized bit-fields!");
216     Align = 1;
217   }
218 
219   // Append tail padding.
220   if (Layout.getSize() / 8 > Size)
221     AppendPadding(Layout.getSize() / 8, Align);
222 }
223 
224 void CGRecordLayoutBuilder::LayoutBases(const CXXRecordDecl *RD,
225                                         const ASTRecordLayout &Layout) {
226   // Check if we need to add a vtable pointer.
227   if (RD->isDynamicClass() && !Layout.getPrimaryBase()) {
228     const llvm::Type *Int8PtrTy =
229       llvm::Type::getInt8PtrTy(Types.getLLVMContext());
230 
231     assert(NextFieldOffsetInBytes == 0 &&
232            "Vtable pointer must come first!");
233     AppendField(NextFieldOffsetInBytes, Int8PtrTy->getPointerTo());
234   }
235 }
236 
237 bool CGRecordLayoutBuilder::LayoutFields(const RecordDecl *D) {
238   assert(!D->isUnion() && "Can't call LayoutFields on a union!");
239   assert(Alignment && "Did not set alignment!");
240 
241   const ASTRecordLayout &Layout = Types.getContext().getASTRecordLayout(D);
242 
243   if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
244     LayoutBases(RD, Layout);
245 
246   unsigned FieldNo = 0;
247 
248   for (RecordDecl::field_iterator Field = D->field_begin(),
249        FieldEnd = D->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
250     if (!LayoutField(*Field, Layout.getFieldOffset(FieldNo))) {
251       assert(!Packed &&
252              "Could not layout fields even with a packed LLVM struct!");
253       return false;
254     }
255   }
256 
257   // Append tail padding if necessary.
258   AppendTailPadding(Layout.getSize());
259 
260   return true;
261 }
262 
263 void CGRecordLayoutBuilder::AppendTailPadding(uint64_t RecordSize) {
264   assert(RecordSize % 8 == 0 && "Invalid record size!");
265 
266   uint64_t RecordSizeInBytes = RecordSize / 8;
267   assert(NextFieldOffsetInBytes <= RecordSizeInBytes && "Size mismatch!");
268 
269   uint64_t AlignedNextFieldOffset =
270     llvm::RoundUpToAlignment(NextFieldOffsetInBytes, AlignmentAsLLVMStruct);
271 
272   if (AlignedNextFieldOffset == RecordSizeInBytes) {
273     // We don't need any padding.
274     return;
275   }
276 
277   unsigned NumPadBytes = RecordSizeInBytes - NextFieldOffsetInBytes;
278   AppendBytes(NumPadBytes);
279 }
280 
281 void CGRecordLayoutBuilder::AppendField(uint64_t FieldOffsetInBytes,
282                                         const llvm::Type *FieldTy) {
283   AlignmentAsLLVMStruct = std::max(AlignmentAsLLVMStruct,
284                                    getTypeAlignment(FieldTy));
285 
286   uint64_t FieldSizeInBytes = getTypeSizeInBytes(FieldTy);
287 
288   FieldTypes.push_back(FieldTy);
289 
290   NextFieldOffsetInBytes = FieldOffsetInBytes + FieldSizeInBytes;
291   BitsAvailableInLastField = 0;
292 }
293 
294 void
295 CGRecordLayoutBuilder::AppendPadding(uint64_t FieldOffsetInBytes,
296                                      const llvm::Type *FieldTy) {
297   AppendPadding(FieldOffsetInBytes, getTypeAlignment(FieldTy));
298 }
299 
300 void CGRecordLayoutBuilder::AppendPadding(uint64_t FieldOffsetInBytes,
301                                           unsigned FieldAlignment) {
302   assert(NextFieldOffsetInBytes <= FieldOffsetInBytes &&
303          "Incorrect field layout!");
304 
305   // Round up the field offset to the alignment of the field type.
306   uint64_t AlignedNextFieldOffsetInBytes =
307     llvm::RoundUpToAlignment(NextFieldOffsetInBytes, FieldAlignment);
308 
309   if (AlignedNextFieldOffsetInBytes < FieldOffsetInBytes) {
310     // Even with alignment, the field offset is not at the right place,
311     // insert padding.
312     uint64_t PaddingInBytes = FieldOffsetInBytes - NextFieldOffsetInBytes;
313 
314     AppendBytes(PaddingInBytes);
315   }
316 }
317 
318 void CGRecordLayoutBuilder::AppendBytes(uint64_t NumBytes) {
319   if (NumBytes == 0)
320     return;
321 
322   const llvm::Type *Ty = llvm::Type::getInt8Ty(Types.getLLVMContext());
323   if (NumBytes > 1)
324     Ty = llvm::ArrayType::get(Ty, NumBytes);
325 
326   // Append the padding field
327   AppendField(NextFieldOffsetInBytes, Ty);
328 }
329 
330 unsigned CGRecordLayoutBuilder::getTypeAlignment(const llvm::Type *Ty) const {
331   if (Packed)
332     return 1;
333 
334   return Types.getTargetData().getABITypeAlignment(Ty);
335 }
336 
337 uint64_t CGRecordLayoutBuilder::getTypeSizeInBytes(const llvm::Type *Ty) const {
338   return Types.getTargetData().getTypeAllocSize(Ty);
339 }
340 
341 void CGRecordLayoutBuilder::CheckForMemberPointer(const FieldDecl *FD) {
342   // This record already contains a member pointer.
343   if (ContainsMemberPointer)
344     return;
345 
346   // Can only have member pointers if we're compiling C++.
347   if (!Types.getContext().getLangOptions().CPlusPlus)
348     return;
349 
350   QualType Ty = FD->getType();
351 
352   if (Ty->isMemberPointerType()) {
353     // We have a member pointer!
354     ContainsMemberPointer = true;
355     return;
356   }
357 
358 }
359 
360 CGRecordLayout *
361 CGRecordLayoutBuilder::ComputeLayout(CodeGenTypes &Types,
362                                      const RecordDecl *D) {
363   CGRecordLayoutBuilder Builder(Types);
364 
365   Builder.Layout(D);
366 
367   const llvm::Type *Ty = llvm::StructType::get(Types.getLLVMContext(),
368                                                Builder.FieldTypes,
369                                                Builder.Packed);
370   assert(Types.getContext().getASTRecordLayout(D).getSize() / 8 ==
371          Types.getTargetData().getTypeAllocSize(Ty) &&
372          "Type size mismatch!");
373 
374   // Add all the field numbers.
375   for (unsigned i = 0, e = Builder.LLVMFields.size(); i != e; ++i) {
376     const FieldDecl *FD = Builder.LLVMFields[i].first;
377     unsigned FieldNo = Builder.LLVMFields[i].second;
378 
379     Types.addFieldInfo(FD, FieldNo);
380   }
381 
382   // Add bitfield info.
383   for (unsigned i = 0, e = Builder.LLVMBitFields.size(); i != e; ++i) {
384     const LLVMBitFieldInfo &Info = Builder.LLVMBitFields[i];
385 
386     Types.addBitFieldInfo(Info.FD, Info.FieldNo, Info.Start, Info.Size);
387   }
388 
389   return new CGRecordLayout(Ty, Builder.ContainsMemberPointer);
390 }
391