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   unsigned FieldNo = 0;
166   for (RecordDecl::field_iterator Field = D->field_begin(),
167        FieldEnd = D->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
168     assert(Layout.getFieldOffset(FieldNo) == 0 &&
169           "Union field offset did not start at the beginning of record!");
170 
171     if (Field->isBitField()) {
172       uint64_t FieldSize =
173         Field->getBitWidth()->EvaluateAsInt(Types.getContext()).getZExtValue();
174 
175       // Ignore zero sized bit fields.
176       if (FieldSize == 0)
177         continue;
178 
179       // Add the bit field info.
180       Types.addBitFieldInfo(*Field, 0, 0, FieldSize);
181     } else
182       Types.addFieldInfo(*Field, 0);
183 
184     const llvm::Type *FieldTy =
185       Types.ConvertTypeForMemRecursive(Field->getType());
186     unsigned FieldAlign = Types.getTargetData().getABITypeAlignment(FieldTy);
187     uint64_t FieldSize = Types.getTargetData().getTypeAllocSize(FieldTy);
188 
189     if (FieldAlign < Align)
190       continue;
191 
192     if (FieldAlign > Align || FieldSize > Size) {
193       Ty = FieldTy;
194       Align = FieldAlign;
195       Size = FieldSize;
196     }
197   }
198 
199   // Now add our field.
200   if (Ty) {
201     AppendField(0, Ty);
202 
203     if (getTypeAlignment(Ty) > Layout.getAlignment() / 8) {
204       // We need a packed struct.
205       Packed = true;
206       Align = 1;
207     }
208   }
209   if (!Align) {
210     assert((D->field_begin() == D->field_end()) && "LayoutUnion - Align 0");
211     Align = 1;
212   }
213 
214   // Append tail padding.
215   if (Layout.getSize() / 8 > Size)
216     AppendPadding(Layout.getSize() / 8, Align);
217 }
218 
219 void CGRecordLayoutBuilder::LayoutBases(const CXXRecordDecl *RD,
220                                         const ASTRecordLayout &Layout) {
221   // Check if we need to add a vtable pointer.
222   if (RD->isDynamicClass() && !Layout.getPrimaryBase()) {
223     const llvm::Type *Int8PtrTy =
224       llvm::Type::getInt8PtrTy(Types.getLLVMContext());
225 
226     assert(NextFieldOffsetInBytes == 0 &&
227            "Vtable pointer must come first!");
228     AppendField(NextFieldOffsetInBytes, Int8PtrTy->getPointerTo());
229   }
230 }
231 
232 bool CGRecordLayoutBuilder::LayoutFields(const RecordDecl *D) {
233   assert(!D->isUnion() && "Can't call LayoutFields on a union!");
234   assert(Alignment && "Did not set alignment!");
235 
236   const ASTRecordLayout &Layout = Types.getContext().getASTRecordLayout(D);
237 
238   if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
239     LayoutBases(RD, Layout);
240 
241   unsigned FieldNo = 0;
242 
243   for (RecordDecl::field_iterator Field = D->field_begin(),
244        FieldEnd = D->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
245     if (!LayoutField(*Field, Layout.getFieldOffset(FieldNo))) {
246       assert(!Packed &&
247              "Could not layout fields even with a packed LLVM struct!");
248       return false;
249     }
250   }
251 
252   // Append tail padding if necessary.
253   AppendTailPadding(Layout.getSize());
254 
255   return true;
256 }
257 
258 void CGRecordLayoutBuilder::AppendTailPadding(uint64_t RecordSize) {
259   assert(RecordSize % 8 == 0 && "Invalid record size!");
260 
261   uint64_t RecordSizeInBytes = RecordSize / 8;
262   assert(NextFieldOffsetInBytes <= RecordSizeInBytes && "Size mismatch!");
263 
264   uint64_t AlignedNextFieldOffset =
265     llvm::RoundUpToAlignment(NextFieldOffsetInBytes, AlignmentAsLLVMStruct);
266 
267   if (AlignedNextFieldOffset == RecordSizeInBytes) {
268     // We don't need any padding.
269     return;
270   }
271 
272   unsigned NumPadBytes = RecordSizeInBytes - NextFieldOffsetInBytes;
273   AppendBytes(NumPadBytes);
274 }
275 
276 void CGRecordLayoutBuilder::AppendField(uint64_t FieldOffsetInBytes,
277                                         const llvm::Type *FieldTy) {
278   AlignmentAsLLVMStruct = std::max(AlignmentAsLLVMStruct,
279                                    getTypeAlignment(FieldTy));
280 
281   uint64_t FieldSizeInBytes = getTypeSizeInBytes(FieldTy);
282 
283   FieldTypes.push_back(FieldTy);
284 
285   NextFieldOffsetInBytes = FieldOffsetInBytes + FieldSizeInBytes;
286   BitsAvailableInLastField = 0;
287 }
288 
289 void
290 CGRecordLayoutBuilder::AppendPadding(uint64_t FieldOffsetInBytes,
291                                      const llvm::Type *FieldTy) {
292   AppendPadding(FieldOffsetInBytes, getTypeAlignment(FieldTy));
293 }
294 
295 void CGRecordLayoutBuilder::AppendPadding(uint64_t FieldOffsetInBytes,
296                                           unsigned FieldAlignment) {
297   assert(NextFieldOffsetInBytes <= FieldOffsetInBytes &&
298          "Incorrect field layout!");
299 
300   // Round up the field offset to the alignment of the field type.
301   uint64_t AlignedNextFieldOffsetInBytes =
302     llvm::RoundUpToAlignment(NextFieldOffsetInBytes, FieldAlignment);
303 
304   if (AlignedNextFieldOffsetInBytes < FieldOffsetInBytes) {
305     // Even with alignment, the field offset is not at the right place,
306     // insert padding.
307     uint64_t PaddingInBytes = FieldOffsetInBytes - NextFieldOffsetInBytes;
308 
309     AppendBytes(PaddingInBytes);
310   }
311 }
312 
313 void CGRecordLayoutBuilder::AppendBytes(uint64_t NumBytes) {
314   if (NumBytes == 0)
315     return;
316 
317   const llvm::Type *Ty = llvm::Type::getInt8Ty(Types.getLLVMContext());
318   if (NumBytes > 1)
319     Ty = llvm::ArrayType::get(Ty, NumBytes);
320 
321   // Append the padding field
322   AppendField(NextFieldOffsetInBytes, Ty);
323 }
324 
325 unsigned CGRecordLayoutBuilder::getTypeAlignment(const llvm::Type *Ty) const {
326   if (Packed)
327     return 1;
328 
329   return Types.getTargetData().getABITypeAlignment(Ty);
330 }
331 
332 uint64_t CGRecordLayoutBuilder::getTypeSizeInBytes(const llvm::Type *Ty) const {
333   return Types.getTargetData().getTypeAllocSize(Ty);
334 }
335 
336 void CGRecordLayoutBuilder::CheckForMemberPointer(const FieldDecl *FD) {
337   // This record already contains a member pointer.
338   if (ContainsMemberPointer)
339     return;
340 
341   // Can only have member pointers if we're compiling C++.
342   if (!Types.getContext().getLangOptions().CPlusPlus)
343     return;
344 
345   QualType Ty = FD->getType();
346 
347   if (Ty->isMemberPointerType()) {
348     // We have a member pointer!
349     ContainsMemberPointer = true;
350     return;
351   }
352 
353 }
354 
355 CGRecordLayout *
356 CGRecordLayoutBuilder::ComputeLayout(CodeGenTypes &Types,
357                                      const RecordDecl *D) {
358   CGRecordLayoutBuilder Builder(Types);
359 
360   Builder.Layout(D);
361 
362   const llvm::Type *Ty = llvm::StructType::get(Types.getLLVMContext(),
363                                                Builder.FieldTypes,
364                                                Builder.Packed);
365   assert(Types.getContext().getASTRecordLayout(D).getSize() / 8 ==
366          Types.getTargetData().getTypeAllocSize(Ty) &&
367          "Type size mismatch!");
368 
369   // Add all the field numbers.
370   for (unsigned i = 0, e = Builder.LLVMFields.size(); i != e; ++i) {
371     const FieldDecl *FD = Builder.LLVMFields[i].first;
372     unsigned FieldNo = Builder.LLVMFields[i].second;
373 
374     Types.addFieldInfo(FD, FieldNo);
375   }
376 
377   // Add bitfield info.
378   for (unsigned i = 0, e = Builder.LLVMBitFields.size(); i != e; ++i) {
379     const LLVMBitFieldInfo &Info = Builder.LLVMBitFields[i];
380 
381     Types.addBitFieldInfo(Info.FD, Info.FieldNo, Info.Start, Info.Size);
382   }
383 
384   return new CGRecordLayout(Ty, Builder.ContainsMemberPointer);
385 }
386