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   if (D->isUnion()) {
31     LayoutUnion(D);
32     return;
33   }
34 
35   if (const PackedAttr* PA = D->getAttr<PackedAttr>())
36     Packed = PA->getAlignment();
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   bool FieldPacked = Packed;
100 
101   // FIXME: Should this override struct packing? Probably we want to
102   // take the minimum?
103   if (const PackedAttr *PA = D->getAttr<PackedAttr>())
104     FieldPacked = PA->getAlignment();
105 
106   // If the field is packed, then we need a packed struct.
107   if (!Packed && FieldPacked)
108     return false;
109 
110   if (D->isBitField()) {
111     // We must use packed structs for unnamed bit fields since they
112     // don't affect the struct alignment.
113     if (!Packed && !D->getDeclName())
114       return false;
115 
116     LayoutBitField(D, FieldOffset);
117     return true;
118   }
119 
120   const llvm::Type *Ty = Types.ConvertTypeForMemRecursive(D->getType());
121 
122   // Check if the field is aligned.
123   if (const AlignedAttr *PA = D->getAttr<AlignedAttr>()) {
124     unsigned FieldAlign = PA->getAlignment();
125 
126     if (!Packed && getTypeAlignment(Ty) > FieldAlign)
127       return false;
128   }
129 
130   assert(FieldOffset % 8 == 0 && "FieldOffset is not on a byte boundary!");
131 
132   uint64_t FieldOffsetInBytes = FieldOffset / 8;
133 
134   // Append padding if necessary.
135   AppendPadding(FieldOffsetInBytes, Ty);
136 
137   // Now append the field.
138   LLVMFields.push_back(LLVMFieldInfo(D, FieldTypes.size()));
139   AppendField(FieldOffsetInBytes, Ty);
140 
141   return true;
142 }
143 
144 void CGRecordLayoutBuilder::LayoutUnion(const RecordDecl *D) {
145   assert(D->isUnion() && "Can't call LayoutUnion on a non-union record!");
146 
147   const ASTRecordLayout &Layout = Types.getContext().getASTRecordLayout(D);
148 
149   const llvm::Type *Ty = 0;
150   uint64_t Size = 0;
151   unsigned Align = 0;
152 
153   unsigned FieldNo = 0;
154   for (RecordDecl::field_iterator Field = D->field_begin(),
155        FieldEnd = D->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
156     assert(Layout.getFieldOffset(FieldNo) == 0 &&
157           "Union field offset did not start at the beginning of record!");
158 
159     if (Field->isBitField()) {
160       uint64_t FieldSize =
161         Field->getBitWidth()->EvaluateAsInt(Types.getContext()).getZExtValue();
162 
163       // Ignore zero sized bit fields.
164       if (FieldSize == 0)
165         continue;
166 
167       // Add the bit field info.
168       Types.addBitFieldInfo(*Field, 0, 0, FieldSize);
169     } else
170       Types.addFieldInfo(*Field, 0);
171 
172     const llvm::Type *FieldTy =
173       Types.ConvertTypeForMemRecursive(Field->getType());
174     unsigned FieldAlign = Types.getTargetData().getABITypeAlignment(FieldTy);
175     uint64_t FieldSize = Types.getTargetData().getTypeAllocSize(FieldTy);
176 
177     if (FieldAlign < Align)
178       continue;
179 
180     if (FieldAlign > Align || FieldSize > Size) {
181       Ty = FieldTy;
182       Align = FieldAlign;
183       Size = FieldSize;
184     }
185   }
186 
187   // Now add our field.
188   if (Ty)
189     AppendField(0, Ty);
190 
191   // Append tail padding.
192   if (Layout.getSize() / 8 > Size)
193     AppendPadding(Layout.getSize() / 8, Align);
194 }
195 
196 bool CGRecordLayoutBuilder::LayoutFields(const RecordDecl *D) {
197   assert(!D->isUnion() && "Can't call LayoutFields on a union!");
198 
199   const ASTRecordLayout &Layout = Types.getContext().getASTRecordLayout(D);
200 
201   unsigned FieldNo = 0;
202 
203   for (RecordDecl::field_iterator Field = D->field_begin(),
204        FieldEnd = D->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
205     if (!LayoutField(*Field, Layout.getFieldOffset(FieldNo))) {
206       assert(!Packed &&
207              "Could not layout fields even with a packed LLVM struct!");
208       return false;
209     }
210   }
211 
212   // Append tail padding if necessary.
213   AppendTailPadding(Layout.getSize());
214 
215   return true;
216 }
217 
218 void CGRecordLayoutBuilder::AppendTailPadding(uint64_t RecordSize) {
219   assert(RecordSize % 8 == 0 && "Invalid record size!");
220 
221   uint64_t RecordSizeInBytes = RecordSize / 8;
222   assert(NextFieldOffsetInBytes <= RecordSizeInBytes && "Size mismatch!");
223 
224   unsigned NumPadBytes = RecordSizeInBytes - NextFieldOffsetInBytes;
225   AppendBytes(NumPadBytes);
226 }
227 
228 void CGRecordLayoutBuilder::AppendField(uint64_t FieldOffsetInBytes,
229                                         const llvm::Type *FieldTy) {
230   AlignmentAsLLVMStruct = std::max(AlignmentAsLLVMStruct,
231                                    getTypeAlignment(FieldTy));
232 
233   uint64_t FieldSizeInBytes = getTypeSizeInBytes(FieldTy);
234 
235   FieldTypes.push_back(FieldTy);
236 
237   NextFieldOffsetInBytes = FieldOffsetInBytes + FieldSizeInBytes;
238   BitsAvailableInLastField = 0;
239 }
240 
241 void
242 CGRecordLayoutBuilder::AppendPadding(uint64_t FieldOffsetInBytes,
243                                      const llvm::Type *FieldTy) {
244   AppendPadding(FieldOffsetInBytes, getTypeAlignment(FieldTy));
245 }
246 
247 void CGRecordLayoutBuilder::AppendPadding(uint64_t FieldOffsetInBytes,
248                                           unsigned FieldAlignment) {
249   assert(NextFieldOffsetInBytes <= FieldOffsetInBytes &&
250          "Incorrect field layout!");
251 
252   // Round up the field offset to the alignment of the field type.
253   uint64_t AlignedNextFieldOffsetInBytes =
254     llvm::RoundUpToAlignment(NextFieldOffsetInBytes, FieldAlignment);
255 
256   if (AlignedNextFieldOffsetInBytes < FieldOffsetInBytes) {
257     // Even with alignment, the field offset is not at the right place,
258     // insert padding.
259     uint64_t PaddingInBytes = FieldOffsetInBytes - NextFieldOffsetInBytes;
260 
261     AppendBytes(PaddingInBytes);
262   }
263 }
264 
265 void CGRecordLayoutBuilder::AppendBytes(uint64_t NumBytes) {
266   if (NumBytes == 0)
267     return;
268 
269   const llvm::Type *Ty = llvm::Type::Int8Ty;
270   if (NumBytes > 1)
271     Ty = llvm::ArrayType::get(Ty, NumBytes);
272 
273   // Append the padding field
274   AppendField(NextFieldOffsetInBytes, Ty);
275 }
276 
277 unsigned CGRecordLayoutBuilder::getTypeAlignment(const llvm::Type *Ty) const {
278   if (Packed)
279     return 1;
280 
281   return Types.getTargetData().getABITypeAlignment(Ty);
282 }
283 
284 uint64_t CGRecordLayoutBuilder::getTypeSizeInBytes(const llvm::Type *Ty) const {
285   return Types.getTargetData().getTypeAllocSize(Ty);
286 }
287 
288 CGRecordLayout *
289 CGRecordLayoutBuilder::ComputeLayout(CodeGenTypes &Types,
290                                      const RecordDecl *D) {
291   CGRecordLayoutBuilder Builder(Types);
292 
293   Builder.Layout(D);
294 
295   const llvm::Type *Ty = llvm::StructType::get(Builder.FieldTypes,
296                                                Builder.Packed);
297 
298   // Add all the field numbers.
299   for (unsigned i = 0, e = Builder.LLVMFields.size(); i != e; ++i) {
300     const FieldDecl *FD = Builder.LLVMFields[i].first;
301     unsigned FieldNo = Builder.LLVMFields[i].second;
302 
303     Types.addFieldInfo(FD, FieldNo);
304   }
305 
306   // Add bitfield info.
307   for (unsigned i = 0, e = Builder.LLVMBitFields.size(); i != e; ++i) {
308     const LLVMBitFieldInfo &Info = Builder.LLVMBitFields[i];
309 
310     Types.addBitFieldInfo(Info.FD, Info.FieldNo, Info.Start, Info.Size);
311   }
312 
313   return new CGRecordLayout(Ty, llvm::SmallSet<unsigned, 8>());
314 }
315