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   AlignmentAsLLVMStruct = std::max(AlignmentAsLLVMStruct, getTypeAlignment(Ty));
92 
93   BitsAvailableInLastField =
94     NextFieldOffsetInBytes * 8 - (FieldOffset + FieldSize);
95 }
96 
97 bool CGRecordLayoutBuilder::LayoutField(const FieldDecl *D,
98                                         uint64_t FieldOffset) {
99   // If the field is packed, then we need a packed struct.
100   if (!Packed && D->hasAttr<PackedAttr>())
101     return false;
102 
103   if (D->isBitField()) {
104     // We must use packed structs for unnamed bit fields since they
105     // don't affect the struct alignment.
106     if (!Packed && !D->getDeclName())
107       return false;
108 
109     LayoutBitField(D, FieldOffset);
110     return true;
111   }
112 
113   assert(FieldOffset % 8 == 0 && "FieldOffset is not on a byte boundary!");
114   uint64_t FieldOffsetInBytes = FieldOffset / 8;
115 
116   const llvm::Type *Ty = Types.ConvertTypeForMemRecursive(D->getType());
117   unsigned TypeAlignment = getTypeAlignment(Ty);
118 
119   // If the type alignment is larger then the struct alignment, we must use
120   // a packed struct.
121   if (TypeAlignment > Alignment) {
122     assert(!Packed && "Alignment is wrong even with packed struct!");
123     return false;
124   }
125 
126   if (const RecordType *RT = D->getType()->getAs<RecordType>()) {
127     const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
128     if (const PragmaPackAttr *PPA = RD->getAttr<PragmaPackAttr>()) {
129       if (PPA->getAlignment() != TypeAlignment * 8 && !Packed)
130         return false;
131     }
132   }
133 
134   // Round up the field offset to the alignment of the field type.
135   uint64_t AlignedNextFieldOffsetInBytes =
136     llvm::RoundUpToAlignment(NextFieldOffsetInBytes, TypeAlignment);
137 
138   if (FieldOffsetInBytes < AlignedNextFieldOffsetInBytes) {
139     assert(!Packed && "Could not place field even with packed struct!");
140     return false;
141   }
142 
143   if (AlignedNextFieldOffsetInBytes < FieldOffsetInBytes) {
144     // Even with alignment, the field offset is not at the right place,
145     // insert padding.
146     uint64_t PaddingInBytes = FieldOffsetInBytes - NextFieldOffsetInBytes;
147 
148     AppendBytes(PaddingInBytes);
149   }
150 
151   // Now append the field.
152   LLVMFields.push_back(LLVMFieldInfo(D, FieldTypes.size()));
153   AppendField(FieldOffsetInBytes, Ty);
154 
155   return true;
156 }
157 
158 void CGRecordLayoutBuilder::LayoutUnion(const RecordDecl *D) {
159   assert(D->isUnion() && "Can't call LayoutUnion on a non-union record!");
160 
161   const ASTRecordLayout &Layout = Types.getContext().getASTRecordLayout(D);
162 
163   const llvm::Type *Ty = 0;
164   uint64_t Size = 0;
165   unsigned Align = 0;
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     const llvm::Type *FieldTy =
187       Types.ConvertTypeForMemRecursive(Field->getType());
188     unsigned FieldAlign = Types.getTargetData().getABITypeAlignment(FieldTy);
189     uint64_t FieldSize = Types.getTargetData().getTypeAllocSize(FieldTy);
190 
191     if (FieldAlign < Align)
192       continue;
193 
194     if (FieldAlign > Align || FieldSize > Size) {
195       Ty = FieldTy;
196       Align = FieldAlign;
197       Size = FieldSize;
198     }
199   }
200 
201   // Now add our field.
202   if (Ty) {
203     AppendField(0, Ty);
204 
205     if (getTypeAlignment(Ty) > Layout.getAlignment() / 8) {
206       // We need a packed struct.
207       Packed = true;
208       Align = 1;
209     }
210   }
211 
212   // Append tail padding.
213   if (Layout.getSize() / 8 > Size)
214     AppendPadding(Layout.getSize() / 8, Align);
215 }
216 
217 bool CGRecordLayoutBuilder::LayoutFields(const RecordDecl *D) {
218   assert(!D->isUnion() && "Can't call LayoutFields on a union!");
219   assert(Alignment && "Did not set alignment!");
220 
221   const ASTRecordLayout &Layout = Types.getContext().getASTRecordLayout(D);
222 
223   unsigned FieldNo = 0;
224 
225   for (RecordDecl::field_iterator Field = D->field_begin(),
226        FieldEnd = D->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
227     if (!LayoutField(*Field, Layout.getFieldOffset(FieldNo))) {
228       assert(!Packed &&
229              "Could not layout fields even with a packed LLVM struct!");
230       return false;
231     }
232   }
233 
234   // Append tail padding if necessary.
235   AppendTailPadding(Layout.getSize());
236 
237   return true;
238 }
239 
240 void CGRecordLayoutBuilder::AppendTailPadding(uint64_t RecordSize) {
241   assert(RecordSize % 8 == 0 && "Invalid record size!");
242 
243   uint64_t RecordSizeInBytes = RecordSize / 8;
244   assert(NextFieldOffsetInBytes <= RecordSizeInBytes && "Size mismatch!");
245 
246   unsigned NumPadBytes = RecordSizeInBytes - NextFieldOffsetInBytes;
247   AppendBytes(NumPadBytes);
248 }
249 
250 void CGRecordLayoutBuilder::AppendField(uint64_t FieldOffsetInBytes,
251                                         const llvm::Type *FieldTy) {
252   AlignmentAsLLVMStruct = std::max(AlignmentAsLLVMStruct,
253                                    getTypeAlignment(FieldTy));
254 
255   uint64_t FieldSizeInBytes = getTypeSizeInBytes(FieldTy);
256 
257   FieldTypes.push_back(FieldTy);
258 
259   NextFieldOffsetInBytes = FieldOffsetInBytes + FieldSizeInBytes;
260   BitsAvailableInLastField = 0;
261 }
262 
263 void
264 CGRecordLayoutBuilder::AppendPadding(uint64_t FieldOffsetInBytes,
265                                      const llvm::Type *FieldTy) {
266   AppendPadding(FieldOffsetInBytes, getTypeAlignment(FieldTy));
267 }
268 
269 void CGRecordLayoutBuilder::AppendPadding(uint64_t FieldOffsetInBytes,
270                                           unsigned FieldAlignment) {
271   assert(NextFieldOffsetInBytes <= FieldOffsetInBytes &&
272          "Incorrect field layout!");
273 
274   // Round up the field offset to the alignment of the field type.
275   uint64_t AlignedNextFieldOffsetInBytes =
276     llvm::RoundUpToAlignment(NextFieldOffsetInBytes, FieldAlignment);
277 
278   if (AlignedNextFieldOffsetInBytes < FieldOffsetInBytes) {
279     // Even with alignment, the field offset is not at the right place,
280     // insert padding.
281     uint64_t PaddingInBytes = FieldOffsetInBytes - NextFieldOffsetInBytes;
282 
283     AppendBytes(PaddingInBytes);
284   }
285 }
286 
287 void CGRecordLayoutBuilder::AppendBytes(uint64_t NumBytes) {
288   if (NumBytes == 0)
289     return;
290 
291   const llvm::Type *Ty = llvm::Type::getInt8Ty(Types.getLLVMContext());
292   if (NumBytes > 1)
293     Ty = llvm::ArrayType::get(Ty, NumBytes);
294 
295   // Append the padding field
296   AppendField(NextFieldOffsetInBytes, Ty);
297 }
298 
299 unsigned CGRecordLayoutBuilder::getTypeAlignment(const llvm::Type *Ty) const {
300   if (Packed)
301     return 1;
302 
303   return Types.getTargetData().getABITypeAlignment(Ty);
304 }
305 
306 uint64_t CGRecordLayoutBuilder::getTypeSizeInBytes(const llvm::Type *Ty) const {
307   return Types.getTargetData().getTypeAllocSize(Ty);
308 }
309 
310 void CGRecordLayoutBuilder::CheckForMemberPointer(const FieldDecl *FD) {
311   // This record already contains a member pointer.
312   if (ContainsMemberPointer)
313     return;
314 
315   // Can only have member pointers if we're compiling C++.
316   if (!Types.getContext().getLangOptions().CPlusPlus)
317     return;
318 
319   QualType Ty = FD->getType();
320 
321   if (Ty->isMemberPointerType()) {
322     // We have a member pointer!
323     ContainsMemberPointer = true;
324     return;
325   }
326 
327 }
328 
329 CGRecordLayout *
330 CGRecordLayoutBuilder::ComputeLayout(CodeGenTypes &Types,
331                                      const RecordDecl *D) {
332   CGRecordLayoutBuilder Builder(Types);
333 
334   Builder.Layout(D);
335 
336   const llvm::Type *Ty = llvm::StructType::get(Types.getLLVMContext(),
337                                                Builder.FieldTypes,
338                                                Builder.Packed);
339   assert(Types.getContext().getASTRecordLayout(D).getSize() / 8 ==
340          Types.getTargetData().getTypeAllocSize(Ty) &&
341          "Type size mismatch!");
342 
343   // Add all the field numbers.
344   for (unsigned i = 0, e = Builder.LLVMFields.size(); i != e; ++i) {
345     const FieldDecl *FD = Builder.LLVMFields[i].first;
346     unsigned FieldNo = Builder.LLVMFields[i].second;
347 
348     Types.addFieldInfo(FD, FieldNo);
349   }
350 
351   // Add bitfield info.
352   for (unsigned i = 0, e = Builder.LLVMBitFields.size(); i != e; ++i) {
353     const LLVMBitFieldInfo &Info = Builder.LLVMBitFields[i];
354 
355     Types.addBitFieldInfo(Info.FD, Info.FieldNo, Info.Start, Info.Size);
356   }
357 
358   return new CGRecordLayout(Ty, Builder.ContainsMemberPointer);
359 }
360