clang 22.0.0git
RecordLayoutBuilder.cpp
Go to the documentation of this file.
1//=== RecordLayoutBuilder.cpp - Helper class for building record layouts ---==//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
11#include "clang/AST/Attr.h"
13#include "clang/AST/Decl.h"
14#include "clang/AST/DeclCXX.h"
15#include "clang/AST/DeclObjC.h"
16#include "clang/AST/Expr.h"
20#include "llvm/Support/Format.h"
21#include "llvm/Support/MathExtras.h"
22
23using namespace clang;
24
25namespace {
26
27/// BaseSubobjectInfo - Represents a single base subobject in a complete class.
28/// For a class hierarchy like
29///
30/// class A { };
31/// class B : A { };
32/// class C : A, B { };
33///
34/// The BaseSubobjectInfo graph for C will have three BaseSubobjectInfo
35/// instances, one for B and two for A.
36///
37/// If a base is virtual, it will only have one BaseSubobjectInfo allocated.
38struct BaseSubobjectInfo {
39 /// Class - The class for this base info.
40 const CXXRecordDecl *Class;
41
42 /// IsVirtual - Whether the BaseInfo represents a virtual base or not.
43 bool IsVirtual;
44
45 /// Bases - Information about the base subobjects.
47
48 /// PrimaryVirtualBaseInfo - Holds the base info for the primary virtual base
49 /// of this base info (if one exists).
50 BaseSubobjectInfo *PrimaryVirtualBaseInfo;
51
52 // FIXME: Document.
53 const BaseSubobjectInfo *Derived;
54};
55
56/// Externally provided layout. Typically used when the AST source, such
57/// as DWARF, lacks all the information that was available at compile time, such
58/// as alignment attributes on fields and pragmas in effect.
59struct ExternalLayout {
60 ExternalLayout() = default;
61
62 /// Overall record size in bits.
63 uint64_t Size = 0;
64
65 /// Overall record alignment in bits.
66 uint64_t Align = 0;
67
68 /// Record field offsets in bits.
69 llvm::DenseMap<const FieldDecl *, uint64_t> FieldOffsets;
70
71 /// Direct, non-virtual base offsets.
72 llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsets;
73
74 /// Virtual base offsets.
75 llvm::DenseMap<const CXXRecordDecl *, CharUnits> VirtualBaseOffsets;
76
77 /// Get the offset of the given field. The external source must provide
78 /// entries for all fields in the record.
79 uint64_t getExternalFieldOffset(const FieldDecl *FD) {
80 assert(FieldOffsets.count(FD) &&
81 "Field does not have an external offset");
82 return FieldOffsets[FD];
83 }
84
85 bool getExternalNVBaseOffset(const CXXRecordDecl *RD, CharUnits &BaseOffset) {
86 auto Known = BaseOffsets.find(RD);
87 if (Known == BaseOffsets.end())
88 return false;
89 BaseOffset = Known->second;
90 return true;
91 }
92
93 bool getExternalVBaseOffset(const CXXRecordDecl *RD, CharUnits &BaseOffset) {
94 auto Known = VirtualBaseOffsets.find(RD);
95 if (Known == VirtualBaseOffsets.end())
96 return false;
97 BaseOffset = Known->second;
98 return true;
99 }
100};
101
102/// EmptySubobjectMap - Keeps track of which empty subobjects exist at different
103/// offsets while laying out a C++ class.
104class EmptySubobjectMap {
105 const ASTContext &Context;
106 uint64_t CharWidth;
107
108 /// Class - The class whose empty entries we're keeping track of.
109 const CXXRecordDecl *Class;
110
111 /// EmptyClassOffsets - A map from offsets to empty record decls.
112 typedef llvm::TinyPtrVector<const CXXRecordDecl *> ClassVectorTy;
113 typedef llvm::DenseMap<CharUnits, ClassVectorTy> EmptyClassOffsetsMapTy;
114 EmptyClassOffsetsMapTy EmptyClassOffsets;
115
116 /// MaxEmptyClassOffset - The highest offset known to contain an empty
117 /// base subobject.
118 CharUnits MaxEmptyClassOffset;
119
120 /// ComputeEmptySubobjectSizes - Compute the size of the largest base or
121 /// member subobject that is empty.
122 void ComputeEmptySubobjectSizes();
123
124 void AddSubobjectAtOffset(const CXXRecordDecl *RD, CharUnits Offset);
125
126 void UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info,
127 CharUnits Offset, bool PlacingEmptyBase);
128
129 void UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD,
130 const CXXRecordDecl *Class, CharUnits Offset,
131 bool PlacingOverlappingField);
132 void UpdateEmptyFieldSubobjects(const FieldDecl *FD, CharUnits Offset,
133 bool PlacingOverlappingField);
134
135 /// AnyEmptySubobjectsBeyondOffset - Returns whether there are any empty
136 /// subobjects beyond the given offset.
137 bool AnyEmptySubobjectsBeyondOffset(CharUnits Offset) const {
138 return Offset <= MaxEmptyClassOffset;
139 }
140
142 const FieldDecl *Field) const {
143 uint64_t FieldOffset = Layout.getFieldOffset(Field->getFieldIndex());
144 assert(FieldOffset % CharWidth == 0 &&
145 "Field offset not at char boundary!");
146
147 return Context.toCharUnitsFromBits(FieldOffset);
148 }
149
150protected:
151 bool CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD,
152 CharUnits Offset) const;
153
154 bool CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info,
155 CharUnits Offset);
156
157 bool CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD,
158 const CXXRecordDecl *Class,
159 CharUnits Offset) const;
160 bool CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD,
161 CharUnits Offset) const;
162
163public:
164 /// This holds the size of the largest empty subobject (either a base
165 /// or a member). Will be zero if the record being built doesn't contain
166 /// any empty classes.
167 CharUnits SizeOfLargestEmptySubobject;
168
169 EmptySubobjectMap(const ASTContext &Context, const CXXRecordDecl *Class)
170 : Context(Context), CharWidth(Context.getCharWidth()), Class(Class) {
171 ComputeEmptySubobjectSizes();
172 }
173
174 /// CanPlaceBaseAtOffset - Return whether the given base class can be placed
175 /// at the given offset.
176 /// Returns false if placing the record will result in two components
177 /// (direct or indirect) of the same type having the same offset.
178 bool CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info,
179 CharUnits Offset);
180
181 /// CanPlaceFieldAtOffset - Return whether a field can be placed at the given
182 /// offset.
183 bool CanPlaceFieldAtOffset(const FieldDecl *FD, CharUnits Offset);
184};
185
186void EmptySubobjectMap::ComputeEmptySubobjectSizes() {
187 // Check the bases.
188 for (const CXXBaseSpecifier &Base : Class->bases()) {
189 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
190
191 CharUnits EmptySize;
192 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
193 if (BaseDecl->isEmpty()) {
194 // If the class decl is empty, get its size.
195 EmptySize = Layout.getSize();
196 } else {
197 // Otherwise, we get the largest empty subobject for the decl.
198 EmptySize = Layout.getSizeOfLargestEmptySubobject();
199 }
200
201 if (EmptySize > SizeOfLargestEmptySubobject)
202 SizeOfLargestEmptySubobject = EmptySize;
203 }
204
205 // Check the fields.
206 for (const FieldDecl *FD : Class->fields()) {
207 // We only care about records.
208 const auto *MemberDecl =
209 Context.getBaseElementType(FD->getType())->getAsCXXRecordDecl();
210 if (!MemberDecl)
211 continue;
212
213 CharUnits EmptySize;
214 const ASTRecordLayout &Layout = Context.getASTRecordLayout(MemberDecl);
215 if (MemberDecl->isEmpty()) {
216 // If the class decl is empty, get its size.
217 EmptySize = Layout.getSize();
218 } else {
219 // Otherwise, we get the largest empty subobject for the decl.
220 EmptySize = Layout.getSizeOfLargestEmptySubobject();
221 }
222
223 if (EmptySize > SizeOfLargestEmptySubobject)
224 SizeOfLargestEmptySubobject = EmptySize;
225 }
226}
227
228bool
229EmptySubobjectMap::CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD,
230 CharUnits Offset) const {
231 // We only need to check empty bases.
232 if (!RD->isEmpty())
233 return true;
234
235 EmptyClassOffsetsMapTy::const_iterator I = EmptyClassOffsets.find(Offset);
236 if (I == EmptyClassOffsets.end())
237 return true;
238
239 const ClassVectorTy &Classes = I->second;
240 if (!llvm::is_contained(Classes, RD))
241 return true;
242
243 // There is already an empty class of the same type at this offset.
244 return false;
245}
246
247void EmptySubobjectMap::AddSubobjectAtOffset(const CXXRecordDecl *RD,
248 CharUnits Offset) {
249 // We only care about empty bases.
250 if (!RD->isEmpty())
251 return;
252
253 // If we have empty structures inside a union, we can assign both
254 // the same offset. Just avoid pushing them twice in the list.
255 ClassVectorTy &Classes = EmptyClassOffsets[Offset];
256 if (llvm::is_contained(Classes, RD))
257 return;
258
259 Classes.push_back(RD);
260
261 // Update the empty class offset.
262 if (Offset > MaxEmptyClassOffset)
263 MaxEmptyClassOffset = Offset;
264}
265
266bool
267EmptySubobjectMap::CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info,
268 CharUnits Offset) {
269 // We don't have to keep looking past the maximum offset that's known to
270 // contain an empty class.
271 if (!AnyEmptySubobjectsBeyondOffset(Offset))
272 return true;
273
274 if (!CanPlaceSubobjectAtOffset(Info->Class, Offset))
275 return false;
276
277 // Traverse all non-virtual bases.
278 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
279 for (const BaseSubobjectInfo *Base : Info->Bases) {
280 if (Base->IsVirtual)
281 continue;
282
283 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
284
285 if (!CanPlaceBaseSubobjectAtOffset(Base, BaseOffset))
286 return false;
287 }
288
289 if (Info->PrimaryVirtualBaseInfo) {
290 BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo;
291
292 if (Info == PrimaryVirtualBaseInfo->Derived) {
293 if (!CanPlaceBaseSubobjectAtOffset(PrimaryVirtualBaseInfo, Offset))
294 return false;
295 }
296 }
297
298 // Traverse all member variables.
299 for (const FieldDecl *Field : Info->Class->fields()) {
300 if (Field->isBitField())
301 continue;
302
303 CharUnits FieldOffset = Offset + getFieldOffset(Layout, Field);
304 if (!CanPlaceFieldSubobjectAtOffset(Field, FieldOffset))
305 return false;
306 }
307
308 return true;
309}
310
311void EmptySubobjectMap::UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info,
312 CharUnits Offset,
313 bool PlacingEmptyBase) {
314 if (!PlacingEmptyBase && Offset >= SizeOfLargestEmptySubobject) {
315 // We know that the only empty subobjects that can conflict with empty
316 // subobject of non-empty bases, are empty bases that can be placed at
317 // offset zero. Because of this, we only need to keep track of empty base
318 // subobjects with offsets less than the size of the largest empty
319 // subobject for our class.
320 return;
321 }
322
323 AddSubobjectAtOffset(Info->Class, Offset);
324
325 // Traverse all non-virtual bases.
326 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
327 for (const BaseSubobjectInfo *Base : Info->Bases) {
328 if (Base->IsVirtual)
329 continue;
330
331 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
332 UpdateEmptyBaseSubobjects(Base, BaseOffset, PlacingEmptyBase);
333 }
334
335 if (Info->PrimaryVirtualBaseInfo) {
336 BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo;
337
338 if (Info == PrimaryVirtualBaseInfo->Derived)
339 UpdateEmptyBaseSubobjects(PrimaryVirtualBaseInfo, Offset,
340 PlacingEmptyBase);
341 }
342
343 // Traverse all member variables.
344 for (const FieldDecl *Field : Info->Class->fields()) {
345 if (Field->isBitField())
346 continue;
347
348 CharUnits FieldOffset = Offset + getFieldOffset(Layout, Field);
349 UpdateEmptyFieldSubobjects(Field, FieldOffset, PlacingEmptyBase);
350 }
351}
352
353bool EmptySubobjectMap::CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info,
354 CharUnits Offset) {
355 // If we know this class doesn't have any empty subobjects we don't need to
356 // bother checking.
357 if (SizeOfLargestEmptySubobject.isZero())
358 return true;
359
360 if (!CanPlaceBaseSubobjectAtOffset(Info, Offset))
361 return false;
362
363 // We are able to place the base at this offset. Make sure to update the
364 // empty base subobject map.
365 UpdateEmptyBaseSubobjects(Info, Offset, Info->Class->isEmpty());
366 return true;
367}
368
369bool
370EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD,
371 const CXXRecordDecl *Class,
372 CharUnits Offset) const {
373 // We don't have to keep looking past the maximum offset that's known to
374 // contain an empty class.
375 if (!AnyEmptySubobjectsBeyondOffset(Offset))
376 return true;
377
378 if (!CanPlaceSubobjectAtOffset(RD, Offset))
379 return false;
380
381 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
382
383 // Traverse all non-virtual bases.
384 for (const CXXBaseSpecifier &Base : RD->bases()) {
385 if (Base.isVirtual())
386 continue;
387
388 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
389
390 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl);
391 if (!CanPlaceFieldSubobjectAtOffset(BaseDecl, Class, BaseOffset))
392 return false;
393 }
394
395 if (RD == Class) {
396 // This is the most derived class, traverse virtual bases as well.
397 for (const CXXBaseSpecifier &Base : RD->vbases()) {
398 const CXXRecordDecl *VBaseDecl = Base.getType()->getAsCXXRecordDecl();
399
400 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl);
401 if (!CanPlaceFieldSubobjectAtOffset(VBaseDecl, Class, VBaseOffset))
402 return false;
403 }
404 }
405
406 // Traverse all member variables.
407 for (const FieldDecl *Field : RD->fields()) {
408 if (Field->isBitField())
409 continue;
410
411 CharUnits FieldOffset = Offset + getFieldOffset(Layout, Field);
412 if (!CanPlaceFieldSubobjectAtOffset(Field, FieldOffset))
413 return false;
414 }
415
416 return true;
417}
418
419bool
420EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD,
421 CharUnits Offset) const {
422 // We don't have to keep looking past the maximum offset that's known to
423 // contain an empty class.
424 if (!AnyEmptySubobjectsBeyondOffset(Offset))
425 return true;
426
427 QualType T = FD->getType();
428 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
429 return CanPlaceFieldSubobjectAtOffset(RD, RD, Offset);
430
431 // If we have an array type we need to look at every element.
432 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) {
433 QualType ElemTy = Context.getBaseElementType(AT);
434 const auto *RD = ElemTy->getAsCXXRecordDecl();
435 if (!RD)
436 return true;
437
438 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
439
440 uint64_t NumElements = Context.getConstantArrayElementCount(AT);
441 CharUnits ElementOffset = Offset;
442 for (uint64_t I = 0; I != NumElements; ++I) {
443 // We don't have to keep looking past the maximum offset that's known to
444 // contain an empty class.
445 if (!AnyEmptySubobjectsBeyondOffset(ElementOffset))
446 return true;
447
448 if (!CanPlaceFieldSubobjectAtOffset(RD, RD, ElementOffset))
449 return false;
450
451 ElementOffset += Layout.getSize();
452 }
453 }
454
455 return true;
456}
457
458bool EmptySubobjectMap::CanPlaceFieldAtOffset(const FieldDecl *FD,
459 CharUnits Offset) {
460 if (!CanPlaceFieldSubobjectAtOffset(FD, Offset))
461 return false;
462
463 // We are able to place the member variable at this offset.
464 // Make sure to update the empty field subobject map.
465 UpdateEmptyFieldSubobjects(FD, Offset, FD->hasAttr<NoUniqueAddressAttr>());
466 return true;
467}
468
469void EmptySubobjectMap::UpdateEmptyFieldSubobjects(
470 const CXXRecordDecl *RD, const CXXRecordDecl *Class, CharUnits Offset,
471 bool PlacingOverlappingField) {
472 // We know that the only empty subobjects that can conflict with empty
473 // field subobjects are subobjects of empty bases and potentially-overlapping
474 // fields that can be placed at offset zero. Because of this, we only need to
475 // keep track of empty field subobjects with offsets less than the size of
476 // the largest empty subobject for our class.
477 //
478 // (Proof: we will only consider placing a subobject at offset zero or at
479 // >= the current dsize. The only cases where the earlier subobject can be
480 // placed beyond the end of dsize is if it's an empty base or a
481 // potentially-overlapping field.)
482 if (!PlacingOverlappingField && Offset >= SizeOfLargestEmptySubobject)
483 return;
484
485 AddSubobjectAtOffset(RD, Offset);
486
487 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
488
489 // Traverse all non-virtual bases.
490 for (const CXXBaseSpecifier &Base : RD->bases()) {
491 if (Base.isVirtual())
492 continue;
493
494 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
495
496 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl);
497 UpdateEmptyFieldSubobjects(BaseDecl, Class, BaseOffset,
498 PlacingOverlappingField);
499 }
500
501 if (RD == Class) {
502 // This is the most derived class, traverse virtual bases as well.
503 for (const CXXBaseSpecifier &Base : RD->vbases()) {
504 const CXXRecordDecl *VBaseDecl = Base.getType()->getAsCXXRecordDecl();
505
506 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl);
507 UpdateEmptyFieldSubobjects(VBaseDecl, Class, VBaseOffset,
508 PlacingOverlappingField);
509 }
510 }
511
512 // Traverse all member variables.
513 for (const FieldDecl *Field : RD->fields()) {
514 if (Field->isBitField())
515 continue;
516
517 CharUnits FieldOffset = Offset + getFieldOffset(Layout, Field);
518 UpdateEmptyFieldSubobjects(Field, FieldOffset, PlacingOverlappingField);
519 }
520}
521
522void EmptySubobjectMap::UpdateEmptyFieldSubobjects(
523 const FieldDecl *FD, CharUnits Offset, bool PlacingOverlappingField) {
524 QualType T = FD->getType();
525 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
526 UpdateEmptyFieldSubobjects(RD, RD, Offset, PlacingOverlappingField);
527 return;
528 }
529
530 // If we have an array type we need to update every element.
531 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) {
532 QualType ElemTy = Context.getBaseElementType(AT);
533 const auto *RD = ElemTy->getAsCXXRecordDecl();
534 if (!RD)
535 return;
536
537 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
538
539 uint64_t NumElements = Context.getConstantArrayElementCount(AT);
540 CharUnits ElementOffset = Offset;
541
542 for (uint64_t I = 0; I != NumElements; ++I) {
543 // We know that the only empty subobjects that can conflict with empty
544 // field subobjects are subobjects of empty bases that can be placed at
545 // offset zero. Because of this, we only need to keep track of empty field
546 // subobjects with offsets less than the size of the largest empty
547 // subobject for our class.
548 if (!PlacingOverlappingField &&
549 ElementOffset >= SizeOfLargestEmptySubobject)
550 return;
551
552 UpdateEmptyFieldSubobjects(RD, RD, ElementOffset,
553 PlacingOverlappingField);
554 ElementOffset += Layout.getSize();
555 }
556 }
557}
558
560
561class ItaniumRecordLayoutBuilder {
562protected:
563 // FIXME: Remove this and make the appropriate fields public.
564 friend class clang::ASTContext;
565
566 const ASTContext &Context;
567
568 EmptySubobjectMap *EmptySubobjects;
569
570 /// Size - The current size of the record layout.
572
573 /// Alignment - The current alignment of the record layout.
574 CharUnits Alignment;
575
576 /// PreferredAlignment - The preferred alignment of the record layout.
577 CharUnits PreferredAlignment;
578
579 /// The alignment if attribute packed is not used.
580 CharUnits UnpackedAlignment;
581
582 /// \brief The maximum of the alignments of top-level members.
583 CharUnits UnadjustedAlignment;
584
585 SmallVector<uint64_t, 16> FieldOffsets;
586
587 /// Whether the external AST source has provided a layout for this
588 /// record.
589 LLVM_PREFERRED_TYPE(bool)
590 unsigned UseExternalLayout : 1;
591
592 /// Whether we need to infer alignment, even when we have an
593 /// externally-provided layout.
594 LLVM_PREFERRED_TYPE(bool)
595 unsigned InferAlignment : 1;
596
597 /// Packed - Whether the record is packed or not.
598 LLVM_PREFERRED_TYPE(bool)
599 unsigned Packed : 1;
600
601 LLVM_PREFERRED_TYPE(bool)
602 unsigned IsUnion : 1;
603
604 LLVM_PREFERRED_TYPE(bool)
605 unsigned IsMac68kAlign : 1;
606
607 LLVM_PREFERRED_TYPE(bool)
608 unsigned IsNaturalAlign : 1;
609
610 LLVM_PREFERRED_TYPE(bool)
611 unsigned IsMsStruct : 1;
612
613 /// UnfilledBitsInLastUnit - If the last field laid out was a bitfield,
614 /// this contains the number of bits in the last unit that can be used for
615 /// an adjacent bitfield if necessary. The unit in question is usually
616 /// a byte, but larger units are used if IsMsStruct.
617 unsigned char UnfilledBitsInLastUnit;
618
619 /// LastBitfieldStorageUnitSize - If IsMsStruct, represents the size of the
620 /// storage unit of the previous field if it was a bitfield.
621 unsigned char LastBitfieldStorageUnitSize;
622
623 /// MaxFieldAlignment - The maximum allowed field alignment. This is set by
624 /// #pragma pack.
625 CharUnits MaxFieldAlignment;
626
627 /// DataSize - The data size of the record being laid out.
628 uint64_t DataSize;
629
630 CharUnits NonVirtualSize;
631 CharUnits NonVirtualAlignment;
632 CharUnits PreferredNVAlignment;
633
634 /// If we've laid out a field but not included its tail padding in Size yet,
635 /// this is the size up to the end of that field.
636 CharUnits PaddedFieldSize;
637
638 /// PrimaryBase - the primary base class (if one exists) of the class
639 /// we're laying out.
640 const CXXRecordDecl *PrimaryBase;
641
642 /// PrimaryBaseIsVirtual - Whether the primary base of the class we're laying
643 /// out is virtual.
644 bool PrimaryBaseIsVirtual;
645
646 /// HasOwnVFPtr - Whether the class provides its own vtable/vftbl
647 /// pointer, as opposed to inheriting one from a primary base class.
648 bool HasOwnVFPtr;
649
650 /// the flag of field offset changing due to packed attribute.
651 bool HasPackedField;
652
653 /// HandledFirstNonOverlappingEmptyField - An auxiliary field used for AIX.
654 /// When there are OverlappingEmptyFields existing in the aggregate, the
655 /// flag shows if the following first non-empty or empty-but-non-overlapping
656 /// field has been handled, if any.
657 bool HandledFirstNonOverlappingEmptyField;
658
659 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy;
660
661 /// Bases - base classes and their offsets in the record.
662 BaseOffsetsMapTy Bases;
663
664 // VBases - virtual base classes and their offsets in the record.
666
667 /// IndirectPrimaryBases - Virtual base classes, direct or indirect, that are
668 /// primary base classes for some other direct or indirect base class.
669 CXXIndirectPrimaryBaseSet IndirectPrimaryBases;
670
671 /// FirstNearlyEmptyVBase - The first nearly empty virtual base class in
672 /// inheritance graph order. Used for determining the primary base class.
673 const CXXRecordDecl *FirstNearlyEmptyVBase;
674
675 /// VisitedVirtualBases - A set of all the visited virtual bases, used to
676 /// avoid visiting virtual bases more than once.
678
679 /// Valid if UseExternalLayout is true.
680 ExternalLayout External;
681
682 ItaniumRecordLayoutBuilder(const ASTContext &Context,
683 EmptySubobjectMap *EmptySubobjects)
684 : Context(Context), EmptySubobjects(EmptySubobjects), Size(0),
685 Alignment(CharUnits::One()), PreferredAlignment(CharUnits::One()),
686 UnpackedAlignment(CharUnits::One()),
687 UnadjustedAlignment(CharUnits::One()), UseExternalLayout(false),
688 InferAlignment(false), Packed(false), IsUnion(false),
689 IsMac68kAlign(false),
690 IsNaturalAlign(!Context.getTargetInfo().getTriple().isOSAIX()),
691 IsMsStruct(false), UnfilledBitsInLastUnit(0),
692 LastBitfieldStorageUnitSize(0), MaxFieldAlignment(CharUnits::Zero()),
693 DataSize(0), NonVirtualSize(CharUnits::Zero()),
694 NonVirtualAlignment(CharUnits::One()),
695 PreferredNVAlignment(CharUnits::One()),
696 PaddedFieldSize(CharUnits::Zero()), PrimaryBase(nullptr),
697 PrimaryBaseIsVirtual(false), HasOwnVFPtr(false), HasPackedField(false),
698 HandledFirstNonOverlappingEmptyField(false),
699 FirstNearlyEmptyVBase(nullptr) {}
700
701 void Layout(const RecordDecl *D);
702 void Layout(const CXXRecordDecl *D);
703 void Layout(const ObjCInterfaceDecl *D);
704
705 void LayoutFields(const RecordDecl *D);
706 void LayoutField(const FieldDecl *D, bool InsertExtraPadding);
707 void LayoutWideBitField(uint64_t FieldSize, uint64_t StorageUnitSize,
708 bool FieldPacked, const FieldDecl *D);
709 void LayoutBitField(const FieldDecl *D);
710
711 TargetCXXABI getCXXABI() const {
712 return Context.getTargetInfo().getCXXABI();
713 }
714
715 /// BaseSubobjectInfoAllocator - Allocator for BaseSubobjectInfo objects.
716 llvm::SpecificBumpPtrAllocator<BaseSubobjectInfo> BaseSubobjectInfoAllocator;
717
718 typedef llvm::DenseMap<const CXXRecordDecl *, BaseSubobjectInfo *>
719 BaseSubobjectInfoMapTy;
720
721 /// VirtualBaseInfo - Map from all the (direct or indirect) virtual bases
722 /// of the class we're laying out to their base subobject info.
723 BaseSubobjectInfoMapTy VirtualBaseInfo;
724
725 /// NonVirtualBaseInfo - Map from all the direct non-virtual bases of the
726 /// class we're laying out to their base subobject info.
727 BaseSubobjectInfoMapTy NonVirtualBaseInfo;
728
729 /// ComputeBaseSubobjectInfo - Compute the base subobject information for the
730 /// bases of the given class.
731 void ComputeBaseSubobjectInfo(const CXXRecordDecl *RD);
732
733 /// ComputeBaseSubobjectInfo - Compute the base subobject information for a
734 /// single class and all of its base classes.
735 BaseSubobjectInfo *ComputeBaseSubobjectInfo(const CXXRecordDecl *RD,
736 bool IsVirtual,
737 BaseSubobjectInfo *Derived);
738
739 /// DeterminePrimaryBase - Determine the primary base of the given class.
740 void DeterminePrimaryBase(const CXXRecordDecl *RD);
741
742 void SelectPrimaryVBase(const CXXRecordDecl *RD);
743
744 void EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign);
745
746 /// LayoutNonVirtualBases - Determines the primary base class (if any) and
747 /// lays it out. Will then proceed to lay out all non-virtual base clasess.
748 void LayoutNonVirtualBases(const CXXRecordDecl *RD);
749
750 /// LayoutNonVirtualBase - Lays out a single non-virtual base.
751 void LayoutNonVirtualBase(const BaseSubobjectInfo *Base);
752
753 void AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info,
754 CharUnits Offset);
755
756 /// LayoutVirtualBases - Lays out all the virtual bases.
757 void LayoutVirtualBases(const CXXRecordDecl *RD,
758 const CXXRecordDecl *MostDerivedClass);
759
760 /// LayoutVirtualBase - Lays out a single virtual base.
761 void LayoutVirtualBase(const BaseSubobjectInfo *Base);
762
763 /// LayoutBase - Will lay out a base and return the offset where it was
764 /// placed, in chars.
765 CharUnits LayoutBase(const BaseSubobjectInfo *Base);
766
767 /// InitializeLayout - Initialize record layout for the given record decl.
768 void InitializeLayout(const Decl *D);
769
770 /// FinishLayout - Finalize record layout. Adjust record size based on the
771 /// alignment.
772 void FinishLayout(const NamedDecl *D);
773
774 void UpdateAlignment(CharUnits NewAlignment, CharUnits UnpackedNewAlignment,
775 CharUnits PreferredAlignment);
776 void UpdateAlignment(CharUnits NewAlignment, CharUnits UnpackedNewAlignment) {
777 UpdateAlignment(NewAlignment, UnpackedNewAlignment, NewAlignment);
778 }
779 void UpdateAlignment(CharUnits NewAlignment) {
780 UpdateAlignment(NewAlignment, NewAlignment, NewAlignment);
781 }
782
783 /// Retrieve the externally-supplied field offset for the given
784 /// field.
785 ///
786 /// \param Field The field whose offset is being queried.
787 /// \param ComputedOffset The offset that we've computed for this field.
788 uint64_t updateExternalFieldOffset(const FieldDecl *Field,
789 uint64_t ComputedOffset);
790
791 void CheckFieldPadding(uint64_t Offset, uint64_t UnpaddedOffset,
792 uint64_t UnpackedOffset, unsigned UnpackedAlign,
793 bool isPacked, const FieldDecl *D);
794
795 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
796
797 CharUnits getSize() const {
798 assert(Size % Context.getCharWidth() == 0);
799 return Context.toCharUnitsFromBits(Size);
800 }
801 uint64_t getSizeInBits() const { return Size; }
802
803 void setSize(CharUnits NewSize) { Size = Context.toBits(NewSize); }
804 void setSize(uint64_t NewSize) { Size = NewSize; }
805
806 CharUnits getAlignment() const { return Alignment; }
807
808 CharUnits getDataSize() const {
809 assert(DataSize % Context.getCharWidth() == 0);
810 return Context.toCharUnitsFromBits(DataSize);
811 }
812 uint64_t getDataSizeInBits() const { return DataSize; }
813
814 void setDataSize(CharUnits NewSize) { DataSize = Context.toBits(NewSize); }
815 void setDataSize(uint64_t NewSize) { DataSize = NewSize; }
816
817 ItaniumRecordLayoutBuilder(const ItaniumRecordLayoutBuilder &) = delete;
818 void operator=(const ItaniumRecordLayoutBuilder &) = delete;
819};
820} // end anonymous namespace
821
822void ItaniumRecordLayoutBuilder::SelectPrimaryVBase(const CXXRecordDecl *RD) {
823 for (const auto &I : RD->bases()) {
824 assert(!I.getType()->isDependentType() &&
825 "Cannot layout class with dependent bases.");
826
827 const CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
828
829 // Check if this is a nearly empty virtual base.
830 if (I.isVirtual() && Context.isNearlyEmpty(Base)) {
831 // If it's not an indirect primary base, then we've found our primary
832 // base.
833 if (!IndirectPrimaryBases.count(Base)) {
834 PrimaryBase = Base;
835 PrimaryBaseIsVirtual = true;
836 return;
837 }
838
839 // Is this the first nearly empty virtual base?
840 if (!FirstNearlyEmptyVBase)
841 FirstNearlyEmptyVBase = Base;
842 }
843
844 SelectPrimaryVBase(Base);
845 if (PrimaryBase)
846 return;
847 }
848}
849
850/// DeterminePrimaryBase - Determine the primary base of the given class.
851void ItaniumRecordLayoutBuilder::DeterminePrimaryBase(const CXXRecordDecl *RD) {
852 // If the class isn't dynamic, it won't have a primary base.
853 if (!RD->isDynamicClass())
854 return;
855
856 // Compute all the primary virtual bases for all of our direct and
857 // indirect bases, and record all their primary virtual base classes.
858 RD->getIndirectPrimaryBases(IndirectPrimaryBases);
859
860 // If the record has a dynamic base class, attempt to choose a primary base
861 // class. It is the first (in direct base class order) non-virtual dynamic
862 // base class, if one exists.
863 for (const auto &I : RD->bases()) {
864 // Ignore virtual bases.
865 if (I.isVirtual())
866 continue;
867
868 const CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
869
870 if (Base->isDynamicClass()) {
871 // We found it.
872 PrimaryBase = Base;
873 PrimaryBaseIsVirtual = false;
874 return;
875 }
876 }
877
878 // Under the Itanium ABI, if there is no non-virtual primary base class,
879 // try to compute the primary virtual base. The primary virtual base is
880 // the first nearly empty virtual base that is not an indirect primary
881 // virtual base class, if one exists.
882 if (RD->getNumVBases() != 0) {
883 SelectPrimaryVBase(RD);
884 if (PrimaryBase)
885 return;
886 }
887
888 // Otherwise, it is the first indirect primary base class, if one exists.
889 if (FirstNearlyEmptyVBase) {
890 PrimaryBase = FirstNearlyEmptyVBase;
891 PrimaryBaseIsVirtual = true;
892 return;
893 }
894
895 assert(!PrimaryBase && "Should not get here with a primary base!");
896}
897
898BaseSubobjectInfo *ItaniumRecordLayoutBuilder::ComputeBaseSubobjectInfo(
899 const CXXRecordDecl *RD, bool IsVirtual, BaseSubobjectInfo *Derived) {
900 BaseSubobjectInfo *Info;
901
902 if (IsVirtual) {
903 // Check if we already have info about this virtual base.
904 BaseSubobjectInfo *&InfoSlot = VirtualBaseInfo[RD];
905 if (InfoSlot) {
906 assert(InfoSlot->Class == RD && "Wrong class for virtual base info!");
907 return InfoSlot;
908 }
909
910 // We don't, create it.
911 InfoSlot = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
912 Info = InfoSlot;
913 } else {
914 Info = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
915 }
916
917 Info->Class = RD;
918 Info->IsVirtual = IsVirtual;
919 Info->Derived = nullptr;
920 Info->PrimaryVirtualBaseInfo = nullptr;
921
922 const CXXRecordDecl *PrimaryVirtualBase = nullptr;
923 BaseSubobjectInfo *PrimaryVirtualBaseInfo = nullptr;
924
925 // Check if this base has a primary virtual base.
926 if (RD->getNumVBases()) {
927 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
928 if (Layout.isPrimaryBaseVirtual()) {
929 // This base does have a primary virtual base.
930 PrimaryVirtualBase = Layout.getPrimaryBase();
931 assert(PrimaryVirtualBase && "Didn't have a primary virtual base!");
932
933 // Now check if we have base subobject info about this primary base.
934 PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
935
936 if (PrimaryVirtualBaseInfo) {
937 if (PrimaryVirtualBaseInfo->Derived) {
938 // We did have info about this primary base, and it turns out that it
939 // has already been claimed as a primary virtual base for another
940 // base.
941 PrimaryVirtualBase = nullptr;
942 } else {
943 // We can claim this base as our primary base.
944 Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
945 PrimaryVirtualBaseInfo->Derived = Info;
946 }
947 }
948 }
949 }
950
951 // Now go through all direct bases.
952 for (const auto &I : RD->bases()) {
953 bool IsVirtual = I.isVirtual();
954
955 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
956
957 Info->Bases.push_back(ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, Info));
958 }
959
960 if (PrimaryVirtualBase && !PrimaryVirtualBaseInfo) {
961 // Traversing the bases must have created the base info for our primary
962 // virtual base.
963 PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
964 assert(PrimaryVirtualBaseInfo &&
965 "Did not create a primary virtual base!");
966
967 // Claim the primary virtual base as our primary virtual base.
968 Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
969 PrimaryVirtualBaseInfo->Derived = Info;
970 }
971
972 return Info;
973}
974
975void ItaniumRecordLayoutBuilder::ComputeBaseSubobjectInfo(
976 const CXXRecordDecl *RD) {
977 for (const auto &I : RD->bases()) {
978 bool IsVirtual = I.isVirtual();
979
980 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
981
982 // Compute the base subobject info for this base.
983 BaseSubobjectInfo *Info = ComputeBaseSubobjectInfo(BaseDecl, IsVirtual,
984 nullptr);
985
986 if (IsVirtual) {
987 // ComputeBaseInfo has already added this base for us.
988 assert(VirtualBaseInfo.count(BaseDecl) &&
989 "Did not add virtual base!");
990 } else {
991 // Add the base info to the map of non-virtual bases.
992 assert(!NonVirtualBaseInfo.count(BaseDecl) &&
993 "Non-virtual base already exists!");
994 NonVirtualBaseInfo.insert(std::make_pair(BaseDecl, Info));
995 }
996 }
997}
998
999void ItaniumRecordLayoutBuilder::EnsureVTablePointerAlignment(
1000 CharUnits UnpackedBaseAlign) {
1001 CharUnits BaseAlign = Packed ? CharUnits::One() : UnpackedBaseAlign;
1002
1003 // The maximum field alignment overrides base align.
1004 if (!MaxFieldAlignment.isZero()) {
1005 BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
1006 UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment);
1007 }
1008
1009 // Round up the current record size to pointer alignment.
1010 setSize(getSize().alignTo(BaseAlign));
1011
1012 // Update the alignment.
1013 UpdateAlignment(BaseAlign, UnpackedBaseAlign, BaseAlign);
1014}
1015
1016void ItaniumRecordLayoutBuilder::LayoutNonVirtualBases(
1017 const CXXRecordDecl *RD) {
1018 // Then, determine the primary base class.
1019 DeterminePrimaryBase(RD);
1020
1021 // Compute base subobject info.
1022 ComputeBaseSubobjectInfo(RD);
1023
1024 // If we have a primary base class, lay it out.
1025 if (PrimaryBase) {
1026 if (PrimaryBaseIsVirtual) {
1027 // If the primary virtual base was a primary virtual base of some other
1028 // base class we'll have to steal it.
1029 BaseSubobjectInfo *PrimaryBaseInfo = VirtualBaseInfo.lookup(PrimaryBase);
1030 PrimaryBaseInfo->Derived = nullptr;
1031
1032 // We have a virtual primary base, insert it as an indirect primary base.
1033 IndirectPrimaryBases.insert(PrimaryBase);
1034
1035 assert(!VisitedVirtualBases.count(PrimaryBase) &&
1036 "vbase already visited!");
1037 VisitedVirtualBases.insert(PrimaryBase);
1038
1039 LayoutVirtualBase(PrimaryBaseInfo);
1040 } else {
1041 BaseSubobjectInfo *PrimaryBaseInfo =
1042 NonVirtualBaseInfo.lookup(PrimaryBase);
1043 assert(PrimaryBaseInfo &&
1044 "Did not find base info for non-virtual primary base!");
1045
1046 LayoutNonVirtualBase(PrimaryBaseInfo);
1047 }
1048
1049 // If this class needs a vtable/vf-table and didn't get one from a
1050 // primary base, add it in now.
1051 } else if (RD->isDynamicClass()) {
1052 assert(DataSize == 0 && "Vtable pointer must be at offset zero!");
1053 CharUnits PtrWidth = Context.toCharUnitsFromBits(
1055 CharUnits PtrAlign = Context.toCharUnitsFromBits(
1057 EnsureVTablePointerAlignment(PtrAlign);
1058 HasOwnVFPtr = true;
1059
1060 assert(!IsUnion && "Unions cannot be dynamic classes.");
1061 HandledFirstNonOverlappingEmptyField = true;
1062
1063 setSize(getSize() + PtrWidth);
1064 setDataSize(getSize());
1065 }
1066
1067 // Now lay out the non-virtual bases.
1068 for (const auto &I : RD->bases()) {
1069
1070 // Ignore virtual bases.
1071 if (I.isVirtual())
1072 continue;
1073
1074 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
1075
1076 // Skip the primary base, because we've already laid it out. The
1077 // !PrimaryBaseIsVirtual check is required because we might have a
1078 // non-virtual base of the same type as a primary virtual base.
1079 if (BaseDecl == PrimaryBase && !PrimaryBaseIsVirtual)
1080 continue;
1081
1082 // Lay out the base.
1083 BaseSubobjectInfo *BaseInfo = NonVirtualBaseInfo.lookup(BaseDecl);
1084 assert(BaseInfo && "Did not find base info for non-virtual base!");
1085
1086 LayoutNonVirtualBase(BaseInfo);
1087 }
1088}
1089
1090void ItaniumRecordLayoutBuilder::LayoutNonVirtualBase(
1091 const BaseSubobjectInfo *Base) {
1092 // Layout the base.
1093 CharUnits Offset = LayoutBase(Base);
1094
1095 // Add its base class offset.
1096 assert(!Bases.count(Base->Class) && "base offset already exists!");
1097 Bases.insert(std::make_pair(Base->Class, Offset));
1098
1099 AddPrimaryVirtualBaseOffsets(Base, Offset);
1100}
1101
1102void ItaniumRecordLayoutBuilder::AddPrimaryVirtualBaseOffsets(
1103 const BaseSubobjectInfo *Info, CharUnits Offset) {
1104 // This base isn't interesting, it has no virtual bases.
1105 if (!Info->Class->getNumVBases())
1106 return;
1107
1108 // First, check if we have a virtual primary base to add offsets for.
1109 if (Info->PrimaryVirtualBaseInfo) {
1110 assert(Info->PrimaryVirtualBaseInfo->IsVirtual &&
1111 "Primary virtual base is not virtual!");
1112 if (Info->PrimaryVirtualBaseInfo->Derived == Info) {
1113 // Add the offset.
1114 assert(!VBases.count(Info->PrimaryVirtualBaseInfo->Class) &&
1115 "primary vbase offset already exists!");
1116 VBases.insert(std::make_pair(Info->PrimaryVirtualBaseInfo->Class,
1117 ASTRecordLayout::VBaseInfo(Offset, false)));
1118
1119 // Traverse the primary virtual base.
1120 AddPrimaryVirtualBaseOffsets(Info->PrimaryVirtualBaseInfo, Offset);
1121 }
1122 }
1123
1124 // Now go through all direct non-virtual bases.
1125 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
1126 for (const BaseSubobjectInfo *Base : Info->Bases) {
1127 if (Base->IsVirtual)
1128 continue;
1129
1130 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
1131 AddPrimaryVirtualBaseOffsets(Base, BaseOffset);
1132 }
1133}
1134
1135void ItaniumRecordLayoutBuilder::LayoutVirtualBases(
1136 const CXXRecordDecl *RD, const CXXRecordDecl *MostDerivedClass) {
1137 const CXXRecordDecl *PrimaryBase;
1138 bool PrimaryBaseIsVirtual;
1139
1140 if (MostDerivedClass == RD) {
1141 PrimaryBase = this->PrimaryBase;
1142 PrimaryBaseIsVirtual = this->PrimaryBaseIsVirtual;
1143 } else {
1144 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1145 PrimaryBase = Layout.getPrimaryBase();
1146 PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
1147 }
1148
1149 for (const CXXBaseSpecifier &Base : RD->bases()) {
1150 assert(!Base.getType()->isDependentType() &&
1151 "Cannot layout class with dependent bases.");
1152
1153 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
1154
1155 if (Base.isVirtual()) {
1156 if (PrimaryBase != BaseDecl || !PrimaryBaseIsVirtual) {
1157 bool IndirectPrimaryBase = IndirectPrimaryBases.count(BaseDecl);
1158
1159 // Only lay out the virtual base if it's not an indirect primary base.
1160 if (!IndirectPrimaryBase) {
1161 // Only visit virtual bases once.
1162 if (!VisitedVirtualBases.insert(BaseDecl).second)
1163 continue;
1164
1165 const BaseSubobjectInfo *BaseInfo = VirtualBaseInfo.lookup(BaseDecl);
1166 assert(BaseInfo && "Did not find virtual base info!");
1167 LayoutVirtualBase(BaseInfo);
1168 }
1169 }
1170 }
1171
1172 if (!BaseDecl->getNumVBases()) {
1173 // This base isn't interesting since it doesn't have any virtual bases.
1174 continue;
1175 }
1176
1177 LayoutVirtualBases(BaseDecl, MostDerivedClass);
1178 }
1179}
1180
1181void ItaniumRecordLayoutBuilder::LayoutVirtualBase(
1182 const BaseSubobjectInfo *Base) {
1183 assert(!Base->Derived && "Trying to lay out a primary virtual base!");
1184
1185 // Layout the base.
1186 CharUnits Offset = LayoutBase(Base);
1187
1188 // Add its base class offset.
1189 assert(!VBases.count(Base->Class) && "vbase offset already exists!");
1190 VBases.insert(std::make_pair(Base->Class,
1191 ASTRecordLayout::VBaseInfo(Offset, false)));
1192
1193 AddPrimaryVirtualBaseOffsets(Base, Offset);
1194}
1195
1197ItaniumRecordLayoutBuilder::LayoutBase(const BaseSubobjectInfo *Base) {
1198 assert(!IsUnion && "Unions cannot have base classes.");
1199
1200 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base->Class);
1201 CharUnits Offset;
1202
1203 // Query the external layout to see if it provides an offset.
1204 bool HasExternalLayout = false;
1205 if (UseExternalLayout) {
1206 if (Base->IsVirtual)
1207 HasExternalLayout = External.getExternalVBaseOffset(Base->Class, Offset);
1208 else
1209 HasExternalLayout = External.getExternalNVBaseOffset(Base->Class, Offset);
1210 }
1211
1212 auto getBaseOrPreferredBaseAlignFromUnpacked = [&](CharUnits UnpackedAlign) {
1213 // Clang <= 6 incorrectly applied the 'packed' attribute to base classes.
1214 // Per GCC's documentation, it only applies to non-static data members.
1215 return (Packed && ((Context.getLangOpts().getClangABICompat() <=
1216 LangOptions::ClangABI::Ver6) ||
1217 Context.getTargetInfo().getTriple().isPS() ||
1218 Context.getTargetInfo().getTriple().isOSAIX()))
1219 ? CharUnits::One()
1220 : UnpackedAlign;
1221 };
1222
1223 CharUnits UnpackedBaseAlign = Layout.getNonVirtualAlignment();
1224 CharUnits UnpackedPreferredBaseAlign = Layout.getPreferredNVAlignment();
1225 CharUnits BaseAlign =
1226 getBaseOrPreferredBaseAlignFromUnpacked(UnpackedBaseAlign);
1227 CharUnits PreferredBaseAlign =
1228 getBaseOrPreferredBaseAlignFromUnpacked(UnpackedPreferredBaseAlign);
1229
1230 const bool DefaultsToAIXPowerAlignment =
1232 if (DefaultsToAIXPowerAlignment) {
1233 // AIX `power` alignment does not apply the preferred alignment for
1234 // non-union classes if the source of the alignment (the current base in
1235 // this context) follows introduction of the first subobject with
1236 // exclusively allocated space or zero-extent array.
1237 if (!Base->Class->isEmpty() && !HandledFirstNonOverlappingEmptyField) {
1238 // By handling a base class that is not empty, we're handling the
1239 // "first (inherited) member".
1240 HandledFirstNonOverlappingEmptyField = true;
1241 } else if (!IsNaturalAlign) {
1242 UnpackedPreferredBaseAlign = UnpackedBaseAlign;
1243 PreferredBaseAlign = BaseAlign;
1244 }
1245 }
1246
1247 CharUnits UnpackedAlignTo = !DefaultsToAIXPowerAlignment
1248 ? UnpackedBaseAlign
1249 : UnpackedPreferredBaseAlign;
1250 // If we have an empty base class, try to place it at offset 0.
1251 if (Base->Class->isEmpty() &&
1252 (!HasExternalLayout || Offset == CharUnits::Zero()) &&
1253 EmptySubobjects->CanPlaceBaseAtOffset(Base, CharUnits::Zero())) {
1254 setSize(std::max(getSize(), Layout.getSize()));
1255 // On PS4/PS5, don't update the alignment, to preserve compatibility.
1256 if (!Context.getTargetInfo().getTriple().isPS())
1257 UpdateAlignment(BaseAlign, UnpackedAlignTo, PreferredBaseAlign);
1258
1259 return CharUnits::Zero();
1260 }
1261
1262 // The maximum field alignment overrides the base align/(AIX-only) preferred
1263 // base align.
1264 if (!MaxFieldAlignment.isZero()) {
1265 BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
1266 PreferredBaseAlign = std::min(PreferredBaseAlign, MaxFieldAlignment);
1267 UnpackedAlignTo = std::min(UnpackedAlignTo, MaxFieldAlignment);
1268 }
1269
1270 CharUnits AlignTo =
1271 !DefaultsToAIXPowerAlignment ? BaseAlign : PreferredBaseAlign;
1272 if (!HasExternalLayout) {
1273 // Round up the current record size to the base's alignment boundary.
1274 Offset = getDataSize().alignTo(AlignTo);
1275
1276 // Try to place the base.
1277 while (!EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset))
1278 Offset += AlignTo;
1279 } else {
1280 bool Allowed = EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset);
1281 (void)Allowed;
1282 assert(Allowed && "Base subobject externally placed at overlapping offset");
1283
1284 if (InferAlignment && Offset < getDataSize().alignTo(AlignTo)) {
1285 // The externally-supplied base offset is before the base offset we
1286 // computed. Assume that the structure is packed.
1287 Alignment = CharUnits::One();
1288 InferAlignment = false;
1289 }
1290 }
1291
1292 if (!Base->Class->isEmpty()) {
1293 // Update the data size.
1294 setDataSize(Offset + Layout.getNonVirtualSize());
1295
1296 setSize(std::max(getSize(), getDataSize()));
1297 } else
1298 setSize(std::max(getSize(), Offset + Layout.getSize()));
1299
1300 // Remember max struct/class alignment.
1301 UnadjustedAlignment = std::max(UnadjustedAlignment, BaseAlign);
1302 UpdateAlignment(BaseAlign, UnpackedAlignTo, PreferredBaseAlign);
1303
1304 return Offset;
1305}
1306
1307void ItaniumRecordLayoutBuilder::InitializeLayout(const Decl *D) {
1308 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
1309 IsUnion = RD->isUnion();
1310 IsMsStruct = RD->isMsStruct(Context);
1311 }
1312
1313 Packed = D->hasAttr<PackedAttr>();
1314
1315 // Honor the default struct packing maximum alignment flag.
1316 if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct) {
1317 MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment);
1318 }
1319
1320 // mac68k alignment supersedes maximum field alignment and attribute aligned,
1321 // and forces all structures to have 2-byte alignment. The IBM docs on it
1322 // allude to additional (more complicated) semantics, especially with regard
1323 // to bit-fields, but gcc appears not to follow that.
1324 if (D->hasAttr<AlignMac68kAttr>()) {
1325 assert(
1326 !D->hasAttr<AlignNaturalAttr>() &&
1327 "Having both mac68k and natural alignment on a decl is not allowed.");
1328 IsMac68kAlign = true;
1329 MaxFieldAlignment = CharUnits::fromQuantity(2);
1330 Alignment = CharUnits::fromQuantity(2);
1331 PreferredAlignment = CharUnits::fromQuantity(2);
1332 } else {
1333 if (D->hasAttr<AlignNaturalAttr>())
1334 IsNaturalAlign = true;
1335
1336 if (const MaxFieldAlignmentAttr *MFAA = D->getAttr<MaxFieldAlignmentAttr>())
1337 MaxFieldAlignment = Context.toCharUnitsFromBits(MFAA->getAlignment());
1338
1339 if (unsigned MaxAlign = D->getMaxAlignment())
1340 UpdateAlignment(Context.toCharUnitsFromBits(MaxAlign));
1341 }
1342
1343 HandledFirstNonOverlappingEmptyField =
1344 !Context.getTargetInfo().defaultsToAIXPowerAlignment() || IsNaturalAlign;
1345
1346 // If there is an external AST source, ask it for the various offsets.
1347 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
1348 if (ExternalASTSource *Source = Context.getExternalSource()) {
1349 UseExternalLayout = Source->layoutRecordType(
1350 RD, External.Size, External.Align, External.FieldOffsets,
1351 External.BaseOffsets, External.VirtualBaseOffsets);
1352
1353 // Update based on external alignment.
1354 if (UseExternalLayout) {
1355 if (External.Align > 0) {
1356 Alignment = Context.toCharUnitsFromBits(External.Align);
1357 PreferredAlignment = Context.toCharUnitsFromBits(External.Align);
1358 } else {
1359 // The external source didn't have alignment information; infer it.
1360 InferAlignment = true;
1361 }
1362 }
1363 }
1364}
1365
1366void ItaniumRecordLayoutBuilder::Layout(const RecordDecl *D) {
1367 InitializeLayout(D);
1368 LayoutFields(D);
1369
1370 // Finally, round the size of the total struct up to the alignment of the
1371 // struct itself.
1372 FinishLayout(D);
1373}
1374
1375void ItaniumRecordLayoutBuilder::Layout(const CXXRecordDecl *RD) {
1376 InitializeLayout(RD);
1377
1378 // Lay out the vtable and the non-virtual bases.
1379 LayoutNonVirtualBases(RD);
1380
1381 LayoutFields(RD);
1382
1383 NonVirtualSize = Context.toCharUnitsFromBits(
1384 llvm::alignTo(getSizeInBits(), Context.getTargetInfo().getCharAlign()));
1385 NonVirtualAlignment = Alignment;
1386 PreferredNVAlignment = PreferredAlignment;
1387
1388 // Lay out the virtual bases and add the primary virtual base offsets.
1389 LayoutVirtualBases(RD, RD);
1390
1391 // Finally, round the size of the total struct up to the alignment
1392 // of the struct itself.
1393 FinishLayout(RD);
1394
1395#ifndef NDEBUG
1396 // Check that we have base offsets for all bases.
1397 for (const CXXBaseSpecifier &Base : RD->bases()) {
1398 if (Base.isVirtual())
1399 continue;
1400
1401 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
1402
1403 assert(Bases.count(BaseDecl) && "Did not find base offset!");
1404 }
1405
1406 // And all virtual bases.
1407 for (const CXXBaseSpecifier &Base : RD->vbases()) {
1408 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
1409
1410 assert(VBases.count(BaseDecl) && "Did not find base offset!");
1411 }
1412#endif
1413}
1414
1415void ItaniumRecordLayoutBuilder::Layout(const ObjCInterfaceDecl *D) {
1416 if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
1417 const ASTRecordLayout &SL = Context.getASTObjCInterfaceLayout(SD);
1418
1419 UpdateAlignment(SL.getAlignment());
1420
1421 // We start laying out ivars not at the end of the superclass
1422 // structure, but at the next byte following the last field.
1423 setDataSize(SL.getDataSize());
1424 setSize(getDataSize());
1425 }
1426
1427 InitializeLayout(D);
1428 // Layout each ivar sequentially.
1429 for (const ObjCIvarDecl *IVD = D->all_declared_ivar_begin(); IVD;
1430 IVD = IVD->getNextIvar())
1431 LayoutField(IVD, false);
1432
1433 // Finally, round the size of the total struct up to the alignment of the
1434 // struct itself.
1435 FinishLayout(D);
1436}
1437
1438void ItaniumRecordLayoutBuilder::LayoutFields(const RecordDecl *D) {
1439 // Layout each field, for now, just sequentially, respecting alignment. In
1440 // the future, this will need to be tweakable by targets.
1441 bool InsertExtraPadding = D->mayInsertExtraPadding(/*EmitRemark=*/true);
1442 bool HasFlexibleArrayMember = D->hasFlexibleArrayMember();
1443 for (auto I = D->field_begin(), End = D->field_end(); I != End; ++I) {
1444 LayoutField(*I, InsertExtraPadding &&
1445 (std::next(I) != End || !HasFlexibleArrayMember));
1446 }
1447}
1448
1449// Rounds the specified size to have it a multiple of the char size.
1450static uint64_t
1452 const ASTContext &Context) {
1453 uint64_t CharAlignment = Context.getTargetInfo().getCharAlign();
1454 return llvm::alignTo(Size, CharAlignment);
1455}
1456
1457void ItaniumRecordLayoutBuilder::LayoutWideBitField(uint64_t FieldSize,
1458 uint64_t StorageUnitSize,
1459 bool FieldPacked,
1460 const FieldDecl *D) {
1461 assert(Context.getLangOpts().CPlusPlus &&
1462 "Can only have wide bit-fields in C++!");
1463
1464 // Itanium C++ ABI 2.4:
1465 // If sizeof(T)*8 < n, let T' be the largest integral POD type with
1466 // sizeof(T')*8 <= n.
1467
1468 QualType IntegralPODTypes[] = {
1469 Context.UnsignedCharTy, Context.UnsignedShortTy,
1470 Context.UnsignedIntTy, Context.UnsignedLongTy,
1471 Context.UnsignedLongLongTy, Context.UnsignedInt128Ty,
1472 };
1473
1474 QualType Type;
1475 uint64_t MaxSize =
1477 for (const QualType &QT : IntegralPODTypes) {
1478 uint64_t Size = Context.getTypeSize(QT);
1479
1480 if (Size > FieldSize || Size > MaxSize)
1481 break;
1482
1483 Type = QT;
1484 }
1485 assert(!Type.isNull() && "Did not find a type!");
1486
1487 CharUnits TypeAlign = Context.getTypeAlignInChars(Type);
1488
1489 // We're not going to use any of the unfilled bits in the last byte.
1490 UnfilledBitsInLastUnit = 0;
1491 LastBitfieldStorageUnitSize = 0;
1492
1493 uint64_t FieldOffset;
1494 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastUnit;
1495
1496 if (IsUnion) {
1497 uint64_t RoundedFieldSize = roundUpSizeToCharAlignment(FieldSize,
1498 Context);
1499 setDataSize(std::max(getDataSizeInBits(), RoundedFieldSize));
1500 FieldOffset = 0;
1501 } else {
1502 // The bitfield is allocated starting at the next offset aligned
1503 // appropriately for T', with length n bits.
1504 FieldOffset = llvm::alignTo(getDataSizeInBits(), Context.toBits(TypeAlign));
1505
1506 uint64_t NewSizeInBits = FieldOffset + FieldSize;
1507
1508 setDataSize(
1509 llvm::alignTo(NewSizeInBits, Context.getTargetInfo().getCharAlign()));
1510 UnfilledBitsInLastUnit = getDataSizeInBits() - NewSizeInBits;
1511 }
1512
1513 // Place this field at the current location.
1514 FieldOffsets.push_back(FieldOffset);
1515
1516 CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, FieldOffset,
1517 Context.toBits(TypeAlign), FieldPacked, D);
1518
1519 // Update the size.
1520 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
1521
1522 // Remember max struct/class alignment.
1523 UnadjustedAlignment = std::max(UnadjustedAlignment, TypeAlign);
1524 UpdateAlignment(TypeAlign);
1525}
1526
1527static bool isAIXLayout(const ASTContext &Context) {
1528 return Context.getTargetInfo().getTriple().getOS() == llvm::Triple::AIX;
1529}
1530
1531void ItaniumRecordLayoutBuilder::LayoutBitField(const FieldDecl *D) {
1532 bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
1533 uint64_t FieldSize = D->getBitWidthValue();
1534 TypeInfo FieldInfo = Context.getTypeInfo(D->getType());
1535 uint64_t StorageUnitSize = FieldInfo.Width;
1536 unsigned FieldAlign = FieldInfo.Align;
1537 bool AlignIsRequired = FieldInfo.isAlignRequired();
1538 unsigned char PaddingInLastUnit = 0;
1539
1540 // UnfilledBitsInLastUnit is the difference between the end of the
1541 // last allocated bitfield (i.e. the first bit offset available for
1542 // bitfields) and the end of the current data size in bits (i.e. the
1543 // first bit offset available for non-bitfields). The current data
1544 // size in bits is always a multiple of the char size; additionally,
1545 // for ms_struct records it's also a multiple of the
1546 // LastBitfieldStorageUnitSize (if set).
1547
1548 // The struct-layout algorithm is dictated by the platform ABI,
1549 // which in principle could use almost any rules it likes. In
1550 // practice, UNIXy targets tend to inherit the algorithm described
1551 // in the System V generic ABI. The basic bitfield layout rule in
1552 // System V is to place bitfields at the next available bit offset
1553 // where the entire bitfield would fit in an aligned storage unit of
1554 // the declared type; it's okay if an earlier or later non-bitfield
1555 // is allocated in the same storage unit. However, some targets
1556 // (those that !useBitFieldTypeAlignment(), e.g. ARM APCS) don't
1557 // require this storage unit to be aligned, and therefore always put
1558 // the bitfield at the next available bit offset.
1559
1560 // ms_struct basically requests a complete replacement of the
1561 // platform ABI's struct-layout algorithm, with the high-level goal
1562 // of duplicating MSVC's layout. For non-bitfields, this follows
1563 // the standard algorithm. The basic bitfield layout rule is to
1564 // allocate an entire unit of the bitfield's declared type
1565 // (e.g. 'unsigned long'), then parcel it up among successive
1566 // bitfields whose declared types have the same size, making a new
1567 // unit as soon as the last can no longer store the whole value.
1568 // Since it completely replaces the platform ABI's algorithm,
1569 // settings like !useBitFieldTypeAlignment() do not apply.
1570
1571 // A zero-width bitfield forces the use of a new storage unit for
1572 // later bitfields. In general, this occurs by rounding up the
1573 // current size of the struct as if the algorithm were about to
1574 // place a non-bitfield of the field's formal type. Usually this
1575 // does not change the alignment of the struct itself, but it does
1576 // on some targets (those that useZeroLengthBitfieldAlignment(),
1577 // e.g. ARM). In ms_struct layout, zero-width bitfields are
1578 // ignored unless they follow a non-zero-width bitfield.
1579
1580 // A field alignment restriction (e.g. from #pragma pack) or
1581 // specification (e.g. from __attribute__((aligned))) changes the
1582 // formal alignment of the field. For System V, this alters the
1583 // required alignment of the notional storage unit that must contain
1584 // the bitfield. For ms_struct, this only affects the placement of
1585 // new storage units. In both cases, the effect of #pragma pack is
1586 // ignored on zero-width bitfields.
1587
1588 // On System V, a packed field (e.g. from #pragma pack or
1589 // __attribute__((packed))) always uses the next available bit
1590 // offset.
1591
1592 // In an ms_struct struct, the alignment of a fundamental type is
1593 // always equal to its size. This is necessary in order to mimic
1594 // the i386 alignment rules on targets which might not fully align
1595 // all types (e.g. Darwin PPC32, where alignof(long long) == 4).
1596
1597 // First, some simple bookkeeping to perform for ms_struct structs.
1598 if (IsMsStruct) {
1599 // The field alignment for integer types is always the size.
1600 FieldAlign = StorageUnitSize;
1601
1602 // If the previous field was not a bitfield, or was a bitfield
1603 // with a different storage unit size, or if this field doesn't fit into
1604 // the current storage unit, we're done with that storage unit.
1605 if (LastBitfieldStorageUnitSize != StorageUnitSize ||
1606 UnfilledBitsInLastUnit < FieldSize) {
1607 // Also, ignore zero-length bitfields after non-bitfields.
1608 if (!LastBitfieldStorageUnitSize && !FieldSize)
1609 FieldAlign = 1;
1610
1611 PaddingInLastUnit = UnfilledBitsInLastUnit;
1612 UnfilledBitsInLastUnit = 0;
1613 LastBitfieldStorageUnitSize = 0;
1614 }
1615 }
1616
1617 if (isAIXLayout(Context)) {
1618 if (StorageUnitSize < Context.getTypeSize(Context.UnsignedIntTy)) {
1619 // On AIX, [bool, char, short] bitfields have the same alignment
1620 // as [unsigned].
1621 StorageUnitSize = Context.getTypeSize(Context.UnsignedIntTy);
1622 } else if (StorageUnitSize > Context.getTypeSize(Context.UnsignedIntTy) &&
1623 Context.getTargetInfo().getTriple().isArch32Bit() &&
1624 FieldSize <= 32) {
1625 // Under 32-bit compile mode, the bitcontainer is 32 bits if a single
1626 // long long bitfield has length no greater than 32 bits.
1627 StorageUnitSize = 32;
1628
1629 if (!AlignIsRequired)
1630 FieldAlign = 32;
1631 }
1632
1633 if (FieldAlign < StorageUnitSize) {
1634 // The bitfield alignment should always be greater than or equal to
1635 // bitcontainer size.
1636 FieldAlign = StorageUnitSize;
1637 }
1638 }
1639
1640 // If the field is wider than its declared type, it follows
1641 // different rules in all cases, except on AIX.
1642 // On AIX, wide bitfield follows the same rules as normal bitfield.
1643 if (FieldSize > StorageUnitSize && !isAIXLayout(Context)) {
1644 LayoutWideBitField(FieldSize, StorageUnitSize, FieldPacked, D);
1645 return;
1646 }
1647
1648 // Compute the next available bit offset.
1649 uint64_t FieldOffset =
1650 IsUnion ? 0 : (getDataSizeInBits() - UnfilledBitsInLastUnit);
1651
1652 // Handle targets that don't honor bitfield type alignment.
1653 if (!IsMsStruct && !Context.getTargetInfo().useBitFieldTypeAlignment()) {
1654 // Some such targets do honor it on zero-width bitfields.
1655 if (FieldSize == 0 &&
1657 // Some targets don't honor leading zero-width bitfield.
1658 if (!IsUnion && FieldOffset == 0 &&
1660 FieldAlign = 1;
1661 else {
1662 // The alignment to round up to is the max of the field's natural
1663 // alignment and a target-specific fixed value (sometimes zero).
1664 unsigned ZeroLengthBitfieldBoundary =
1666 FieldAlign = std::max(FieldAlign, ZeroLengthBitfieldBoundary);
1667 }
1668 // If that doesn't apply, just ignore the field alignment.
1669 } else {
1670 FieldAlign = 1;
1671 }
1672 }
1673
1674 // Remember the alignment we would have used if the field were not packed.
1675 unsigned UnpackedFieldAlign = FieldAlign;
1676
1677 // Ignore the field alignment if the field is packed unless it has zero-size.
1678 if (!IsMsStruct && FieldPacked && FieldSize != 0)
1679 FieldAlign = 1;
1680
1681 // But, if there's an 'aligned' attribute on the field, honor that.
1682 unsigned ExplicitFieldAlign = D->getMaxAlignment();
1683 if (ExplicitFieldAlign) {
1684 FieldAlign = std::max(FieldAlign, ExplicitFieldAlign);
1685 UnpackedFieldAlign = std::max(UnpackedFieldAlign, ExplicitFieldAlign);
1686 }
1687
1688 // But, if there's a #pragma pack in play, that takes precedent over
1689 // even the 'aligned' attribute, for non-zero-width bitfields.
1690 unsigned MaxFieldAlignmentInBits = Context.toBits(MaxFieldAlignment);
1691 if (!MaxFieldAlignment.isZero() && FieldSize) {
1692 UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignmentInBits);
1693 if (FieldPacked)
1694 FieldAlign = UnpackedFieldAlign;
1695 else
1696 FieldAlign = std::min(FieldAlign, MaxFieldAlignmentInBits);
1697 }
1698
1699 // But, ms_struct just ignores all of that in unions, even explicit
1700 // alignment attributes.
1701 if (IsMsStruct && IsUnion) {
1702 FieldAlign = UnpackedFieldAlign = 1;
1703 }
1704
1705 // For purposes of diagnostics, we're going to simultaneously
1706 // compute the field offsets that we would have used if we weren't
1707 // adding any alignment padding or if the field weren't packed.
1708 uint64_t UnpaddedFieldOffset = FieldOffset - PaddingInLastUnit;
1709 uint64_t UnpackedFieldOffset = FieldOffset;
1710
1711 // Check if we need to add padding to fit the bitfield within an
1712 // allocation unit with the right size and alignment. The rules are
1713 // somewhat different here for ms_struct structs.
1714 if (IsMsStruct) {
1715 // If it's not a zero-width bitfield, and we can fit the bitfield
1716 // into the active storage unit (and we haven't already decided to
1717 // start a new storage unit), just do so, regardless of any other
1718 // other consideration. Otherwise, round up to the right alignment.
1719 if (FieldSize == 0 || FieldSize > UnfilledBitsInLastUnit) {
1720 FieldOffset = llvm::alignTo(FieldOffset, FieldAlign);
1721 UnpackedFieldOffset =
1722 llvm::alignTo(UnpackedFieldOffset, UnpackedFieldAlign);
1723 UnfilledBitsInLastUnit = 0;
1724 }
1725
1726 } else {
1727 // #pragma pack, with any value, suppresses the insertion of padding.
1728 bool AllowPadding = MaxFieldAlignment.isZero();
1729
1730 // Compute the real offset.
1731 if (FieldSize == 0 ||
1732 (AllowPadding &&
1733 (FieldOffset & (FieldAlign - 1)) + FieldSize > StorageUnitSize)) {
1734 FieldOffset = llvm::alignTo(FieldOffset, FieldAlign);
1735 } else if (ExplicitFieldAlign &&
1736 (MaxFieldAlignmentInBits == 0 ||
1737 ExplicitFieldAlign <= MaxFieldAlignmentInBits) &&
1739 // TODO: figure it out what needs to be done on targets that don't honor
1740 // bit-field type alignment like ARM APCS ABI.
1741 FieldOffset = llvm::alignTo(FieldOffset, ExplicitFieldAlign);
1742 }
1743
1744 // Repeat the computation for diagnostic purposes.
1745 if (FieldSize == 0 ||
1746 (AllowPadding &&
1747 (UnpackedFieldOffset & (UnpackedFieldAlign - 1)) + FieldSize >
1748 StorageUnitSize))
1749 UnpackedFieldOffset =
1750 llvm::alignTo(UnpackedFieldOffset, UnpackedFieldAlign);
1751 else if (ExplicitFieldAlign &&
1752 (MaxFieldAlignmentInBits == 0 ||
1753 ExplicitFieldAlign <= MaxFieldAlignmentInBits) &&
1755 UnpackedFieldOffset =
1756 llvm::alignTo(UnpackedFieldOffset, ExplicitFieldAlign);
1757 }
1758
1759 // If we're using external layout, give the external layout a chance
1760 // to override this information.
1761 if (UseExternalLayout)
1762 FieldOffset = updateExternalFieldOffset(D, FieldOffset);
1763
1764 // Okay, place the bitfield at the calculated offset.
1765 FieldOffsets.push_back(FieldOffset);
1766
1767 // Bookkeeping:
1768
1769 // Anonymous members don't affect the overall record alignment,
1770 // except on targets where they do.
1771 if (!IsMsStruct &&
1773 !D->getIdentifier())
1774 FieldAlign = UnpackedFieldAlign = 1;
1775
1776 // On AIX, zero-width bitfields pad out to the natural alignment boundary,
1777 // but do not increase the alignment greater than the MaxFieldAlignment, or 1
1778 // if packed.
1779 if (isAIXLayout(Context) && !FieldSize) {
1780 if (FieldPacked)
1781 FieldAlign = 1;
1782 if (!MaxFieldAlignment.isZero()) {
1783 UnpackedFieldAlign =
1784 std::min(UnpackedFieldAlign, MaxFieldAlignmentInBits);
1785 FieldAlign = std::min(FieldAlign, MaxFieldAlignmentInBits);
1786 }
1787 }
1788
1789 // Diagnose differences in layout due to padding or packing.
1790 if (!UseExternalLayout)
1791 CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, UnpackedFieldOffset,
1792 UnpackedFieldAlign, FieldPacked, D);
1793
1794 // Update DataSize to include the last byte containing (part of) the bitfield.
1795
1796 // For unions, this is just a max operation, as usual.
1797 if (IsUnion) {
1798 // For ms_struct, allocate the entire storage unit --- unless this
1799 // is a zero-width bitfield, in which case just use a size of 1.
1800 uint64_t RoundedFieldSize;
1801 if (IsMsStruct) {
1802 RoundedFieldSize = (FieldSize ? StorageUnitSize
1803 : Context.getTargetInfo().getCharWidth());
1804
1805 // Otherwise, allocate just the number of bytes required to store
1806 // the bitfield.
1807 } else {
1808 RoundedFieldSize = roundUpSizeToCharAlignment(FieldSize, Context);
1809 }
1810 setDataSize(std::max(getDataSizeInBits(), RoundedFieldSize));
1811
1812 // For non-zero-width bitfields in ms_struct structs, allocate a new
1813 // storage unit if necessary.
1814 } else if (IsMsStruct && FieldSize) {
1815 // We should have cleared UnfilledBitsInLastUnit in every case
1816 // where we changed storage units.
1817 if (!UnfilledBitsInLastUnit) {
1818 setDataSize(FieldOffset + StorageUnitSize);
1819 UnfilledBitsInLastUnit = StorageUnitSize;
1820 }
1821 UnfilledBitsInLastUnit -= FieldSize;
1822 LastBitfieldStorageUnitSize = StorageUnitSize;
1823
1824 // Otherwise, bump the data size up to include the bitfield,
1825 // including padding up to char alignment, and then remember how
1826 // bits we didn't use.
1827 } else {
1828 uint64_t NewSizeInBits = FieldOffset + FieldSize;
1829 uint64_t CharAlignment = Context.getTargetInfo().getCharAlign();
1830 setDataSize(llvm::alignTo(NewSizeInBits, CharAlignment));
1831 UnfilledBitsInLastUnit = getDataSizeInBits() - NewSizeInBits;
1832
1833 // The only time we can get here for an ms_struct is if this is a
1834 // zero-width bitfield, which doesn't count as anything for the
1835 // purposes of unfilled bits.
1836 LastBitfieldStorageUnitSize = 0;
1837 }
1838
1839 // Update the size.
1840 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
1841
1842 // Remember max struct/class alignment.
1843 UnadjustedAlignment =
1844 std::max(UnadjustedAlignment, Context.toCharUnitsFromBits(FieldAlign));
1845 UpdateAlignment(Context.toCharUnitsFromBits(FieldAlign),
1846 Context.toCharUnitsFromBits(UnpackedFieldAlign));
1847}
1848
1849void ItaniumRecordLayoutBuilder::LayoutField(const FieldDecl *D,
1850 bool InsertExtraPadding) {
1851 auto *FieldClass = D->getType()->getAsCXXRecordDecl();
1852 bool IsOverlappingEmptyField =
1853 D->isPotentiallyOverlapping() && FieldClass->isEmpty();
1854
1855 CharUnits FieldOffset =
1856 (IsUnion || IsOverlappingEmptyField) ? CharUnits::Zero() : getDataSize();
1857
1858 const bool DefaultsToAIXPowerAlignment =
1860 bool FoundFirstNonOverlappingEmptyFieldForAIX = false;
1861 if (DefaultsToAIXPowerAlignment && !HandledFirstNonOverlappingEmptyField) {
1862 assert(FieldOffset == CharUnits::Zero() &&
1863 "The first non-overlapping empty field should have been handled.");
1864
1865 if (!IsOverlappingEmptyField) {
1866 FoundFirstNonOverlappingEmptyFieldForAIX = true;
1867
1868 // We're going to handle the "first member" based on
1869 // `FoundFirstNonOverlappingEmptyFieldForAIX` during the current
1870 // invocation of this function; record it as handled for future
1871 // invocations (except for unions, because the current field does not
1872 // represent all "firsts").
1873 HandledFirstNonOverlappingEmptyField = !IsUnion;
1874 }
1875 }
1876
1877 if (D->isBitField()) {
1878 LayoutBitField(D);
1879 return;
1880 }
1881
1882 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastUnit;
1883 // Reset the unfilled bits.
1884 UnfilledBitsInLastUnit = 0;
1885 LastBitfieldStorageUnitSize = 0;
1886
1887 llvm::Triple Target = Context.getTargetInfo().getTriple();
1888
1890 CharUnits FieldSize;
1891 CharUnits FieldAlign;
1892 // The amount of this class's dsize occupied by the field.
1893 // This is equal to FieldSize unless we're permitted to pack
1894 // into the field's tail padding.
1895 CharUnits EffectiveFieldSize;
1896
1897 auto setDeclInfo = [&](bool IsIncompleteArrayType) {
1898 auto TI = Context.getTypeInfoInChars(D->getType());
1899 FieldAlign = TI.Align;
1900 // Flexible array members don't have any size, but they have to be
1901 // aligned appropriately for their element type.
1902 EffectiveFieldSize = FieldSize =
1903 IsIncompleteArrayType ? CharUnits::Zero() : TI.Width;
1904 AlignRequirement = TI.AlignRequirement;
1905 };
1906
1907 if (D->getType()->isIncompleteArrayType()) {
1908 setDeclInfo(true /* IsIncompleteArrayType */);
1909 } else {
1910 setDeclInfo(false /* IsIncompleteArrayType */);
1911
1912 // A potentially-overlapping field occupies its dsize or nvsize, whichever
1913 // is larger.
1914 if (D->isPotentiallyOverlapping()) {
1915 const ASTRecordLayout &Layout = Context.getASTRecordLayout(FieldClass);
1916 EffectiveFieldSize =
1917 std::max(Layout.getNonVirtualSize(), Layout.getDataSize());
1918 }
1919
1920 if (IsMsStruct) {
1921 // If MS bitfield layout is required, figure out what type is being
1922 // laid out and align the field to the width of that type.
1923
1924 // Resolve all typedefs down to their base type and round up the field
1925 // alignment if necessary.
1926 QualType T = Context.getBaseElementType(D->getType());
1927 if (const BuiltinType *BTy = T->getAs<BuiltinType>()) {
1928 CharUnits TypeSize = Context.getTypeSizeInChars(BTy);
1929
1930 if (!llvm::isPowerOf2_64(TypeSize.getQuantity())) {
1931 assert(
1932 !Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment() &&
1933 "Non PowerOf2 size in MSVC mode");
1934 // Base types with sizes that aren't a power of two don't work
1935 // with the layout rules for MS structs. This isn't an issue in
1936 // MSVC itself since there are no such base data types there.
1937 // On e.g. x86_32 mingw and linux, long double is 12 bytes though.
1938 // Any structs involving that data type obviously can't be ABI
1939 // compatible with MSVC regardless of how it is laid out.
1940
1941 // Since ms_struct can be mass enabled (via a pragma or via the
1942 // -mms-bitfields command line parameter), this can trigger for
1943 // structs that don't actually need MSVC compatibility, so we
1944 // need to be able to sidestep the ms_struct layout for these types.
1945
1946 // Since the combination of -mms-bitfields together with structs
1947 // like max_align_t (which contains a long double) for mingw is
1948 // quite common (and GCC handles it silently), just handle it
1949 // silently there. For other targets that have ms_struct enabled
1950 // (most probably via a pragma or attribute), trigger a diagnostic
1951 // that defaults to an error.
1952 if (!Context.getTargetInfo().getTriple().isOSCygMing())
1953 Diag(D->getLocation(), diag::warn_npot_ms_struct);
1954 }
1955 if (TypeSize > FieldAlign &&
1956 llvm::isPowerOf2_64(TypeSize.getQuantity()))
1957 FieldAlign = TypeSize;
1958 }
1959 }
1960 }
1961
1962 bool FieldPacked = (Packed && (!FieldClass || FieldClass->isPOD() ||
1963 FieldClass->hasAttr<PackedAttr>() ||
1964 Context.getLangOpts().getClangABICompat() <=
1965 LangOptions::ClangABI::Ver15 ||
1966 Target.isPS() || Target.isOSDarwin() ||
1967 Target.isOSAIX())) ||
1968 D->hasAttr<PackedAttr>();
1969
1970 // When used as part of a typedef, or together with a 'packed' attribute, the
1971 // 'aligned' attribute can be used to decrease alignment. In that case, it
1972 // overrides any computed alignment we have, and there is no need to upgrade
1973 // the alignment.
1974 auto alignedAttrCanDecreaseAIXAlignment = [AlignRequirement, FieldPacked] {
1975 // Enum alignment sources can be safely ignored here, because this only
1976 // helps decide whether we need the AIX alignment upgrade, which only
1977 // applies to floating-point types.
1978 return AlignRequirement == AlignRequirementKind::RequiredByTypedef ||
1979 (AlignRequirement == AlignRequirementKind::RequiredByRecord &&
1980 FieldPacked);
1981 };
1982
1983 // The AIX `power` alignment rules apply the natural alignment of the
1984 // "first member" if it is of a floating-point data type (or is an aggregate
1985 // whose recursively "first" member or element is such a type). The alignment
1986 // associated with these types for subsequent members use an alignment value
1987 // where the floating-point data type is considered to have 4-byte alignment.
1988 //
1989 // For the purposes of the foregoing: vtable pointers, non-empty base classes,
1990 // and zero-width bit-fields count as prior members; members of empty class
1991 // types marked `no_unique_address` are not considered to be prior members.
1992 CharUnits PreferredAlign = FieldAlign;
1993 if (DefaultsToAIXPowerAlignment && !alignedAttrCanDecreaseAIXAlignment() &&
1994 (FoundFirstNonOverlappingEmptyFieldForAIX || IsNaturalAlign)) {
1995 auto performBuiltinTypeAlignmentUpgrade = [&](const BuiltinType *BTy) {
1996 if (BTy->getKind() == BuiltinType::Double ||
1997 BTy->getKind() == BuiltinType::LongDouble) {
1998 assert(PreferredAlign == CharUnits::fromQuantity(4) &&
1999 "No need to upgrade the alignment value.");
2000 PreferredAlign = CharUnits::fromQuantity(8);
2001 }
2002 };
2003
2004 const Type *BaseTy = D->getType()->getBaseElementTypeUnsafe();
2005 if (const ComplexType *CTy = BaseTy->getAs<ComplexType>()) {
2006 performBuiltinTypeAlignmentUpgrade(
2007 CTy->getElementType()->castAs<BuiltinType>());
2008 } else if (const BuiltinType *BTy = BaseTy->getAs<BuiltinType>()) {
2009 performBuiltinTypeAlignmentUpgrade(BTy);
2010 } else if (const RecordType *RT = BaseTy->getAsCanonical<RecordType>()) {
2011 const RecordDecl *RD = RT->getOriginalDecl();
2012 const ASTRecordLayout &FieldRecord = Context.getASTRecordLayout(RD);
2013 PreferredAlign = FieldRecord.getPreferredAlignment();
2014 }
2015 }
2016
2017 // The align if the field is not packed. This is to check if the attribute
2018 // was unnecessary (-Wpacked).
2019 CharUnits UnpackedFieldAlign = FieldAlign;
2020 CharUnits PackedFieldAlign = CharUnits::One();
2021 CharUnits UnpackedFieldOffset = FieldOffset;
2022 CharUnits OriginalFieldAlign = UnpackedFieldAlign;
2023
2024 CharUnits MaxAlignmentInChars =
2026 PackedFieldAlign = std::max(PackedFieldAlign, MaxAlignmentInChars);
2027 PreferredAlign = std::max(PreferredAlign, MaxAlignmentInChars);
2028 UnpackedFieldAlign = std::max(UnpackedFieldAlign, MaxAlignmentInChars);
2029
2030 // The maximum field alignment overrides the aligned attribute.
2031 if (!MaxFieldAlignment.isZero()) {
2032 PackedFieldAlign = std::min(PackedFieldAlign, MaxFieldAlignment);
2033 PreferredAlign = std::min(PreferredAlign, MaxFieldAlignment);
2034 UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignment);
2035 }
2036
2037
2038 if (!FieldPacked)
2039 FieldAlign = UnpackedFieldAlign;
2040 if (DefaultsToAIXPowerAlignment)
2041 UnpackedFieldAlign = PreferredAlign;
2042 if (FieldPacked) {
2043 PreferredAlign = PackedFieldAlign;
2044 FieldAlign = PackedFieldAlign;
2045 }
2046
2047 CharUnits AlignTo =
2048 !DefaultsToAIXPowerAlignment ? FieldAlign : PreferredAlign;
2049 // Round up the current record size to the field's alignment boundary.
2050 FieldOffset = FieldOffset.alignTo(AlignTo);
2051 UnpackedFieldOffset = UnpackedFieldOffset.alignTo(UnpackedFieldAlign);
2052
2053 if (UseExternalLayout) {
2054 FieldOffset = Context.toCharUnitsFromBits(
2055 updateExternalFieldOffset(D, Context.toBits(FieldOffset)));
2056
2057 if (!IsUnion && EmptySubobjects) {
2058 // Record the fact that we're placing a field at this offset.
2059 bool Allowed = EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset);
2060 (void)Allowed;
2061 assert(Allowed && "Externally-placed field cannot be placed here");
2062 }
2063 } else {
2064 if (!IsUnion && EmptySubobjects) {
2065 // Check if we can place the field at this offset.
2066 while (!EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset)) {
2067 // We couldn't place the field at the offset. Try again at a new offset.
2068 // We try offset 0 (for an empty field) and then dsize(C) onwards.
2069 if (FieldOffset == CharUnits::Zero() &&
2070 getDataSize() != CharUnits::Zero())
2071 FieldOffset = getDataSize().alignTo(AlignTo);
2072 else
2073 FieldOffset += AlignTo;
2074 }
2075 }
2076 }
2077
2078 // Place this field at the current location.
2079 FieldOffsets.push_back(Context.toBits(FieldOffset));
2080
2081 if (!UseExternalLayout)
2082 CheckFieldPadding(Context.toBits(FieldOffset), UnpaddedFieldOffset,
2083 Context.toBits(UnpackedFieldOffset),
2084 Context.toBits(UnpackedFieldAlign), FieldPacked, D);
2085
2086 if (InsertExtraPadding) {
2087 CharUnits ASanAlignment = CharUnits::fromQuantity(8);
2088 CharUnits ExtraSizeForAsan = ASanAlignment;
2089 if (FieldSize % ASanAlignment)
2090 ExtraSizeForAsan +=
2091 ASanAlignment - CharUnits::fromQuantity(FieldSize % ASanAlignment);
2092 EffectiveFieldSize = FieldSize = FieldSize + ExtraSizeForAsan;
2093 }
2094
2095 // Reserve space for this field.
2096 if (!IsOverlappingEmptyField) {
2097 uint64_t EffectiveFieldSizeInBits = Context.toBits(EffectiveFieldSize);
2098 if (IsUnion)
2099 setDataSize(std::max(getDataSizeInBits(), EffectiveFieldSizeInBits));
2100 else
2101 setDataSize(FieldOffset + EffectiveFieldSize);
2102
2103 PaddedFieldSize = std::max(PaddedFieldSize, FieldOffset + FieldSize);
2104 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
2105 } else {
2106 setSize(std::max(getSizeInBits(),
2107 (uint64_t)Context.toBits(FieldOffset + FieldSize)));
2108 }
2109
2110 // Remember max struct/class ABI-specified alignment.
2111 UnadjustedAlignment = std::max(UnadjustedAlignment, FieldAlign);
2112 UpdateAlignment(FieldAlign, UnpackedFieldAlign, PreferredAlign);
2113
2114 // For checking the alignment of inner fields against
2115 // the alignment of its parent record.
2116 if (const RecordDecl *RD = D->getParent()) {
2117 // Check if packed attribute or pragma pack is present.
2118 if (RD->hasAttr<PackedAttr>() || !MaxFieldAlignment.isZero())
2119 if (FieldAlign < OriginalFieldAlign)
2120 if (D->getType()->isRecordType()) {
2121 // If the offset is a multiple of the alignment of
2122 // the type, raise the warning.
2123 // TODO: Takes no account the alignment of the outer struct
2124 if (FieldOffset % OriginalFieldAlign != 0)
2125 Diag(D->getLocation(), diag::warn_unaligned_access)
2126 << Context.getCanonicalTagType(RD) << D->getName()
2127 << D->getType();
2128 }
2129 }
2130
2131 if (Packed && !FieldPacked && PackedFieldAlign < FieldAlign)
2132 Diag(D->getLocation(), diag::warn_unpacked_field) << D;
2133}
2134
2135void ItaniumRecordLayoutBuilder::FinishLayout(const NamedDecl *D) {
2136 // In C++, records cannot be of size 0.
2137 if (Context.getLangOpts().CPlusPlus && getSizeInBits() == 0) {
2138 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
2139 // Compatibility with gcc requires a class (pod or non-pod)
2140 // which is not empty but of size 0; such as having fields of
2141 // array of zero-length, remains of Size 0
2142 if (RD->isEmpty())
2143 setSize(CharUnits::One());
2144 }
2145 else
2146 setSize(CharUnits::One());
2147 }
2148
2149 // If we have any remaining field tail padding, include that in the overall
2150 // size.
2151 setSize(std::max(getSizeInBits(), (uint64_t)Context.toBits(PaddedFieldSize)));
2152
2153 // Finally, round the size of the record up to the alignment of the
2154 // record itself.
2155 uint64_t UnpaddedSize = getSizeInBits() - UnfilledBitsInLastUnit;
2156 uint64_t UnpackedSizeInBits =
2157 llvm::alignTo(getSizeInBits(), Context.toBits(UnpackedAlignment));
2158
2159 uint64_t RoundedSize = llvm::alignTo(
2160 getSizeInBits(),
2162 ? Alignment
2163 : PreferredAlignment));
2164
2165 if (UseExternalLayout) {
2166 // If we're inferring alignment, and the external size is smaller than
2167 // our size after we've rounded up to alignment, conservatively set the
2168 // alignment to 1.
2169 if (InferAlignment && External.Size < RoundedSize) {
2170 Alignment = CharUnits::One();
2171 PreferredAlignment = CharUnits::One();
2172 InferAlignment = false;
2173 }
2174 setSize(External.Size);
2175 return;
2176 }
2177
2178 // Set the size to the final size.
2179 setSize(RoundedSize);
2180
2181 unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
2182 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
2183 // Warn if padding was introduced to the struct/class/union.
2184 if (getSizeInBits() > UnpaddedSize) {
2185 unsigned PadSize = getSizeInBits() - UnpaddedSize;
2186 bool InBits = true;
2187 if (PadSize % CharBitNum == 0) {
2188 PadSize = PadSize / CharBitNum;
2189 InBits = false;
2190 }
2191 Diag(RD->getLocation(), diag::warn_padded_struct_size)
2192 << Context.getCanonicalTagType(RD) << PadSize
2193 << (InBits ? 1 : 0); // (byte|bit)
2194 }
2195
2196 const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
2197
2198 // Warn if we packed it unnecessarily, when the unpacked alignment is not
2199 // greater than the one after packing, the size in bits doesn't change and
2200 // the offset of each field is identical.
2201 // Unless the type is non-POD (for Clang ABI > 15), where the packed
2202 // attribute on such a type does allow the type to be packed into other
2203 // structures that use the packed attribute.
2204 if (Packed && UnpackedAlignment <= Alignment &&
2205 UnpackedSizeInBits == getSizeInBits() && !HasPackedField &&
2206 (!CXXRD || CXXRD->isPOD() ||
2207 Context.getLangOpts().getClangABICompat() <=
2208 LangOptions::ClangABI::Ver15))
2209 Diag(D->getLocation(), diag::warn_unnecessary_packed)
2210 << Context.getCanonicalTagType(RD);
2211 }
2212}
2213
2214void ItaniumRecordLayoutBuilder::UpdateAlignment(
2215 CharUnits NewAlignment, CharUnits UnpackedNewAlignment,
2216 CharUnits PreferredNewAlignment) {
2217 // The alignment is not modified when using 'mac68k' alignment or when
2218 // we have an externally-supplied layout that also provides overall alignment.
2219 if (IsMac68kAlign || (UseExternalLayout && !InferAlignment))
2220 return;
2221
2222 if (NewAlignment > Alignment) {
2223 assert(llvm::isPowerOf2_64(NewAlignment.getQuantity()) &&
2224 "Alignment not a power of 2");
2225 Alignment = NewAlignment;
2226 }
2227
2228 if (UnpackedNewAlignment > UnpackedAlignment) {
2229 assert(llvm::isPowerOf2_64(UnpackedNewAlignment.getQuantity()) &&
2230 "Alignment not a power of 2");
2231 UnpackedAlignment = UnpackedNewAlignment;
2232 }
2233
2234 if (PreferredNewAlignment > PreferredAlignment) {
2235 assert(llvm::isPowerOf2_64(PreferredNewAlignment.getQuantity()) &&
2236 "Alignment not a power of 2");
2237 PreferredAlignment = PreferredNewAlignment;
2238 }
2239}
2240
2242ItaniumRecordLayoutBuilder::updateExternalFieldOffset(const FieldDecl *Field,
2243 uint64_t ComputedOffset) {
2244 uint64_t ExternalFieldOffset = External.getExternalFieldOffset(Field);
2245
2246 if (InferAlignment && ExternalFieldOffset < ComputedOffset) {
2247 // The externally-supplied field offset is before the field offset we
2248 // computed. Assume that the structure is packed.
2249 Alignment = CharUnits::One();
2250 PreferredAlignment = CharUnits::One();
2251 InferAlignment = false;
2252 }
2253
2254 // Use the externally-supplied field offset.
2255 return ExternalFieldOffset;
2256}
2257
2258/// Get diagnostic %select index for tag kind for
2259/// field padding diagnostic message.
2260/// WARNING: Indexes apply to particular diagnostics only!
2261///
2262/// \returns diagnostic %select index.
2264 switch (Tag) {
2266 return 0;
2268 return 1;
2269 case TagTypeKind::Class:
2270 return 2;
2271 default: llvm_unreachable("Invalid tag kind for field padding diagnostic!");
2272 }
2273}
2274
2275static void CheckFieldPadding(const ASTContext &Context, bool IsUnion,
2276 uint64_t Offset, uint64_t UnpaddedOffset,
2277 const FieldDecl *D) {
2278 // We let objc ivars without warning, objc interfaces generally are not used
2279 // for padding tricks.
2280 if (isa<ObjCIvarDecl>(D))
2281 return;
2282
2283 // Don't warn about structs created without a SourceLocation. This can
2284 // be done by clients of the AST, such as codegen.
2285 if (D->getLocation().isInvalid())
2286 return;
2287
2288 unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
2289
2290 // Warn if padding was introduced to the struct/class.
2291 if (!IsUnion && Offset > UnpaddedOffset) {
2292 unsigned PadSize = Offset - UnpaddedOffset;
2293 bool InBits = true;
2294 if (PadSize % CharBitNum == 0) {
2295 PadSize = PadSize / CharBitNum;
2296 InBits = false;
2297 }
2298 if (D->getIdentifier()) {
2299 auto Diagnostic = D->isBitField() ? diag::warn_padded_struct_bitfield
2300 : diag::warn_padded_struct_field;
2301 Context.getDiagnostics().Report(D->getLocation(),
2302 Diagnostic)
2303 << getPaddingDiagFromTagKind(D->getParent()->getTagKind())
2304 << Context.getCanonicalTagType(D->getParent()) << PadSize
2305 << (InBits ? 1 : 0) // (byte|bit)
2306 << D->getIdentifier();
2307 } else {
2308 auto Diagnostic = D->isBitField() ? diag::warn_padded_struct_anon_bitfield
2309 : diag::warn_padded_struct_anon_field;
2310 Context.getDiagnostics().Report(D->getLocation(),
2311 Diagnostic)
2312 << getPaddingDiagFromTagKind(D->getParent()->getTagKind())
2313 << Context.getCanonicalTagType(D->getParent()) << PadSize
2314 << (InBits ? 1 : 0); // (byte|bit)
2315 }
2316 }
2317}
2318
2319void ItaniumRecordLayoutBuilder::CheckFieldPadding(
2320 uint64_t Offset, uint64_t UnpaddedOffset, uint64_t UnpackedOffset,
2321 unsigned UnpackedAlign, bool isPacked, const FieldDecl *D) {
2322 ::CheckFieldPadding(Context, IsUnion, Offset, UnpaddedOffset, D);
2323 if (isPacked && Offset != UnpackedOffset) {
2324 HasPackedField = true;
2325 }
2326}
2327
2329 const CXXRecordDecl *RD) {
2330 // If a class isn't polymorphic it doesn't have a key function.
2331 if (!RD->isPolymorphic())
2332 return nullptr;
2333
2334 // A class that is not externally visible doesn't have a key function. (Or
2335 // at least, there's no point to assigning a key function to such a class;
2336 // this doesn't affect the ABI.)
2337 if (!RD->isExternallyVisible())
2338 return nullptr;
2339
2340 // Template instantiations don't have key functions per Itanium C++ ABI 5.2.6.
2341 // Same behavior as GCC.
2343 if (TSK == TSK_ImplicitInstantiation ||
2346 return nullptr;
2347
2348 bool allowInlineFunctions =
2350
2351 for (const CXXMethodDecl *MD : RD->methods()) {
2352 if (!MD->isVirtual())
2353 continue;
2354
2355 if (MD->isPureVirtual())
2356 continue;
2357
2358 // Ignore implicit member functions, they are always marked as inline, but
2359 // they don't have a body until they're defined.
2360 if (MD->isImplicit())
2361 continue;
2362
2363 if (MD->isInlineSpecified() || MD->isConstexpr())
2364 continue;
2365
2366 if (MD->hasInlineBody())
2367 continue;
2368
2369 // Ignore inline deleted or defaulted functions.
2370 if (!MD->isUserProvided())
2371 continue;
2372
2373 // In certain ABIs, ignore functions with out-of-line inline definitions.
2374 if (!allowInlineFunctions) {
2375 const FunctionDecl *Def;
2376 if (MD->hasBody(Def) && Def->isInlineSpecified())
2377 continue;
2378 }
2379
2380 if (Context.getLangOpts().CUDA) {
2381 // While compiler may see key method in this TU, during CUDA
2382 // compilation we should ignore methods that are not accessible
2383 // on this side of compilation.
2384 if (Context.getLangOpts().CUDAIsDevice) {
2385 // In device mode ignore methods without __device__ attribute.
2386 if (!MD->hasAttr<CUDADeviceAttr>())
2387 continue;
2388 } else {
2389 // In host mode ignore __device__-only methods.
2390 if (!MD->hasAttr<CUDAHostAttr>() && MD->hasAttr<CUDADeviceAttr>())
2391 continue;
2392 }
2393 }
2394
2395 // If the key function is dllimport but the class isn't, then the class has
2396 // no key function. The DLL that exports the key function won't export the
2397 // vtable in this case.
2398 if (MD->hasAttr<DLLImportAttr>() && !RD->hasAttr<DLLImportAttr>() &&
2400 return nullptr;
2401
2402 // We found it.
2403 return MD;
2404 }
2405
2406 return nullptr;
2407}
2408
2409DiagnosticBuilder ItaniumRecordLayoutBuilder::Diag(SourceLocation Loc,
2410 unsigned DiagID) {
2411 return Context.getDiagnostics().Report(Loc, DiagID);
2412}
2413
2414/// Does the target C++ ABI require us to skip over the tail-padding
2415/// of the given class (considering it as a base class) when allocating
2416/// objects?
2418 switch (ABI.getTailPaddingUseRules()) {
2420 return false;
2421
2423 // FIXME: To the extent that this is meant to cover the Itanium ABI
2424 // rules, we should implement the restrictions about over-sized
2425 // bitfields:
2426 //
2427 // http://itanium-cxx-abi.github.io/cxx-abi/abi.html#POD :
2428 // In general, a type is considered a POD for the purposes of
2429 // layout if it is a POD type (in the sense of ISO C++
2430 // [basic.types]). However, a POD-struct or POD-union (in the
2431 // sense of ISO C++ [class]) with a bitfield member whose
2432 // declared width is wider than the declared type of the
2433 // bitfield is not a POD for the purpose of layout. Similarly,
2434 // an array type is not a POD for the purpose of layout if the
2435 // element type of the array is not a POD for the purpose of
2436 // layout.
2437 //
2438 // Where references to the ISO C++ are made in this paragraph,
2439 // the Technical Corrigendum 1 version of the standard is
2440 // intended.
2441 return RD->isPOD();
2442
2444 // This is equivalent to RD->getTypeForDecl().isCXX11PODType(),
2445 // but with a lot of abstraction penalty stripped off. This does
2446 // assume that these properties are set correctly even in C++98
2447 // mode; fortunately, that is true because we want to assign
2448 // consistently semantics to the type-traits intrinsics (or at
2449 // least as many of them as possible).
2450 return RD->isTrivial() && RD->isCXX11StandardLayout();
2451 }
2452
2453 llvm_unreachable("bad tail-padding use kind");
2454}
2455
2456// This section contains an implementation of struct layout that is, up to the
2457// included tests, compatible with cl.exe (2013). The layout produced is
2458// significantly different than those produced by the Itanium ABI. Here we note
2459// the most important differences.
2460//
2461// * The alignment of bitfields in unions is ignored when computing the
2462// alignment of the union.
2463// * The existence of zero-width bitfield that occurs after anything other than
2464// a non-zero length bitfield is ignored.
2465// * There is no explicit primary base for the purposes of layout. All bases
2466// with vfptrs are laid out first, followed by all bases without vfptrs.
2467// * The Itanium equivalent vtable pointers are split into a vfptr (virtual
2468// function pointer) and a vbptr (virtual base pointer). They can each be
2469// shared with a, non-virtual bases. These bases need not be the same. vfptrs
2470// always occur at offset 0. vbptrs can occur at an arbitrary offset and are
2471// placed after the lexicographically last non-virtual base. This placement
2472// is always before fields but can be in the middle of the non-virtual bases
2473// due to the two-pass layout scheme for non-virtual-bases.
2474// * Virtual bases sometimes require a 'vtordisp' field that is laid out before
2475// the virtual base and is used in conjunction with virtual overrides during
2476// construction and destruction. This is always a 4 byte value and is used as
2477// an alternative to constructor vtables.
2478// * vtordisps are allocated in a block of memory with size and alignment equal
2479// to the alignment of the completed structure (before applying __declspec(
2480// align())). The vtordisp always occur at the end of the allocation block,
2481// immediately prior to the virtual base.
2482// * vfptrs are injected after all bases and fields have been laid out. In
2483// order to guarantee proper alignment of all fields, the vfptr injection
2484// pushes all bases and fields back by the alignment imposed by those bases
2485// and fields. This can potentially add a significant amount of padding.
2486// vfptrs are always injected at offset 0.
2487// * vbptrs are injected after all bases and fields have been laid out. In
2488// order to guarantee proper alignment of all fields, the vfptr injection
2489// pushes all bases and fields back by the alignment imposed by those bases
2490// and fields. This can potentially add a significant amount of padding.
2491// vbptrs are injected immediately after the last non-virtual base as
2492// lexicographically ordered in the code. If this site isn't pointer aligned
2493// the vbptr is placed at the next properly aligned location. Enough padding
2494// is added to guarantee a fit.
2495// * The last zero sized non-virtual base can be placed at the end of the
2496// struct (potentially aliasing another object), or may alias with the first
2497// field, even if they are of the same type.
2498// * The last zero size virtual base may be placed at the end of the struct
2499// potentially aliasing another object.
2500// * The ABI attempts to avoid aliasing of zero sized bases by adding padding
2501// between bases or vbases with specific properties. The criteria for
2502// additional padding between two bases is that the first base is zero sized
2503// or ends with a zero sized subobject and the second base is zero sized or
2504// trails with a zero sized base or field (sharing of vfptrs can reorder the
2505// layout of the so the leading base is not always the first one declared).
2506// This rule does take into account fields that are not records, so padding
2507// will occur even if the last field is, e.g. an int. The padding added for
2508// bases is 1 byte. The padding added between vbases depends on the alignment
2509// of the object but is at least 4 bytes (in both 32 and 64 bit modes).
2510// * There is no concept of non-virtual alignment, non-virtual alignment and
2511// alignment are always identical.
2512// * There is a distinction between alignment and required alignment.
2513// __declspec(align) changes the required alignment of a struct. This
2514// alignment is _always_ obeyed, even in the presence of #pragma pack. A
2515// record inherits required alignment from all of its fields and bases.
2516// * __declspec(align) on bitfields has the effect of changing the bitfield's
2517// alignment instead of its required alignment. This is the only known way
2518// to make the alignment of a struct bigger than 8. Interestingly enough
2519// this alignment is also immune to the effects of #pragma pack and can be
2520// used to create structures with large alignment under #pragma pack.
2521// However, because it does not impact required alignment, such a structure,
2522// when used as a field or base, will not be aligned if #pragma pack is
2523// still active at the time of use.
2524//
2525// Known incompatibilities:
2526// * all: #pragma pack between fields in a record
2527// * 2010 and back: If the last field in a record is a bitfield, every object
2528// laid out after the record will have extra padding inserted before it. The
2529// extra padding will have size equal to the size of the storage class of the
2530// bitfield. 0 sized bitfields don't exhibit this behavior and the extra
2531// padding can be avoided by adding a 0 sized bitfield after the non-zero-
2532// sized bitfield.
2533// * 2012 and back: In 64-bit mode, if the alignment of a record is 16 or
2534// greater due to __declspec(align()) then a second layout phase occurs after
2535// The locations of the vf and vb pointers are known. This layout phase
2536// suffers from the "last field is a bitfield" bug in 2010 and results in
2537// _every_ field getting padding put in front of it, potentially including the
2538// vfptr, leaving the vfprt at a non-zero location which results in a fault if
2539// anything tries to read the vftbl. The second layout phase also treats
2540// bitfields as separate entities and gives them each storage rather than
2541// packing them. Additionally, because this phase appears to perform a
2542// (an unstable) sort on the members before laying them out and because merged
2543// bitfields have the same address, the bitfields end up in whatever order
2544// the sort left them in, a behavior we could never hope to replicate.
2545
2546namespace {
2547struct MicrosoftRecordLayoutBuilder {
2548 struct ElementInfo {
2550 CharUnits Alignment;
2551 };
2552 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy;
2553 MicrosoftRecordLayoutBuilder(const ASTContext &Context,
2554 EmptySubobjectMap *EmptySubobjects)
2555 : Context(Context), EmptySubobjects(EmptySubobjects),
2556 RemainingBitsInField(0) {}
2557
2558private:
2559 MicrosoftRecordLayoutBuilder(const MicrosoftRecordLayoutBuilder &) = delete;
2560 void operator=(const MicrosoftRecordLayoutBuilder &) = delete;
2561public:
2562 void layout(const RecordDecl *RD);
2563 void cxxLayout(const CXXRecordDecl *RD);
2564 /// Initializes size and alignment and honors some flags.
2565 void initializeLayout(const RecordDecl *RD);
2566 /// Initialized C++ layout, compute alignment and virtual alignment and
2567 /// existence of vfptrs and vbptrs. Alignment is needed before the vfptr is
2568 /// laid out.
2569 void initializeCXXLayout(const CXXRecordDecl *RD);
2570 void layoutNonVirtualBases(const CXXRecordDecl *RD);
2571 void layoutNonVirtualBase(const CXXRecordDecl *RD,
2572 const CXXRecordDecl *BaseDecl,
2573 const ASTRecordLayout &BaseLayout,
2574 const ASTRecordLayout *&PreviousBaseLayout);
2575 void injectVFPtr(const CXXRecordDecl *RD);
2576 void injectVBPtr(const CXXRecordDecl *RD);
2577 /// Lays out the fields of the record. Also rounds size up to
2578 /// alignment.
2579 void layoutFields(const RecordDecl *RD);
2580 void layoutField(const FieldDecl *FD);
2581 void layoutBitField(const FieldDecl *FD);
2582 /// Lays out a single zero-width bit-field in the record and handles
2583 /// special cases associated with zero-width bit-fields.
2584 void layoutZeroWidthBitField(const FieldDecl *FD);
2585 void layoutVirtualBases(const CXXRecordDecl *RD);
2586 void finalizeLayout(const RecordDecl *RD);
2587 /// Gets the size and alignment of a base taking pragma pack and
2588 /// __declspec(align) into account.
2589 ElementInfo getAdjustedElementInfo(const ASTRecordLayout &Layout);
2590 /// Gets the size and alignment of a field taking pragma pack and
2591 /// __declspec(align) into account. It also updates RequiredAlignment as a
2592 /// side effect because it is most convenient to do so here.
2593 ElementInfo getAdjustedElementInfo(const FieldDecl *FD);
2594 /// Places a field at an offset in CharUnits.
2595 void placeFieldAtOffset(CharUnits FieldOffset) {
2596 FieldOffsets.push_back(Context.toBits(FieldOffset));
2597 }
2598 /// Places a bitfield at a bit offset.
2599 void placeFieldAtBitOffset(uint64_t FieldOffset) {
2600 FieldOffsets.push_back(FieldOffset);
2601 }
2602 /// Compute the set of virtual bases for which vtordisps are required.
2603 void computeVtorDispSet(
2604 llvm::SmallPtrSetImpl<const CXXRecordDecl *> &HasVtorDispSet,
2605 const CXXRecordDecl *RD) const;
2606 const ASTContext &Context;
2607 EmptySubobjectMap *EmptySubobjects;
2608
2609 /// The size of the record being laid out.
2611 /// The non-virtual size of the record layout.
2612 CharUnits NonVirtualSize;
2613 /// The data size of the record layout.
2614 CharUnits DataSize;
2615 /// The current alignment of the record layout.
2616 CharUnits Alignment;
2617 /// The maximum allowed field alignment. This is set by #pragma pack.
2618 CharUnits MaxFieldAlignment;
2619 /// The alignment that this record must obey. This is imposed by
2620 /// __declspec(align()) on the record itself or one of its fields or bases.
2621 CharUnits RequiredAlignment;
2622 /// The size of the allocation of the currently active bitfield.
2623 /// This value isn't meaningful unless LastFieldIsNonZeroWidthBitfield
2624 /// is true.
2625 CharUnits CurrentBitfieldSize;
2626 /// Offset to the virtual base table pointer (if one exists).
2627 CharUnits VBPtrOffset;
2628 /// Minimum record size possible.
2629 CharUnits MinEmptyStructSize;
2630 /// The size and alignment info of a pointer.
2631 ElementInfo PointerInfo;
2632 /// The primary base class (if one exists).
2633 const CXXRecordDecl *PrimaryBase;
2634 /// The class we share our vb-pointer with.
2635 const CXXRecordDecl *SharedVBPtrBase;
2636 /// The collection of field offsets.
2637 SmallVector<uint64_t, 16> FieldOffsets;
2638 /// Base classes and their offsets in the record.
2639 BaseOffsetsMapTy Bases;
2640 /// virtual base classes and their offsets in the record.
2642 /// The number of remaining bits in our last bitfield allocation.
2643 unsigned RemainingBitsInField;
2644 bool IsUnion : 1;
2645 /// True if the last field laid out was a bitfield and was not 0
2646 /// width.
2647 bool LastFieldIsNonZeroWidthBitfield : 1;
2648 /// True if the class has its own vftable pointer.
2649 bool HasOwnVFPtr : 1;
2650 /// True if the class has a vbtable pointer.
2651 bool HasVBPtr : 1;
2652 /// True if the last sub-object within the type is zero sized or the
2653 /// object itself is zero sized. This *does not* count members that are not
2654 /// records. Only used for MS-ABI.
2655 bool EndsWithZeroSizedObject : 1;
2656 /// True if this class is zero sized or first base is zero sized or
2657 /// has this property. Only used for MS-ABI.
2658 bool LeadsWithZeroSizedBase : 1;
2659
2660 /// True if the external AST source provided a layout for this record.
2661 bool UseExternalLayout : 1;
2662
2663 /// The layout provided by the external AST source. Only active if
2664 /// UseExternalLayout is true.
2665 ExternalLayout External;
2666};
2667} // namespace
2668
2669MicrosoftRecordLayoutBuilder::ElementInfo
2670MicrosoftRecordLayoutBuilder::getAdjustedElementInfo(
2671 const ASTRecordLayout &Layout) {
2672 ElementInfo Info;
2673 Info.Alignment = Layout.getAlignment();
2674 // Respect pragma pack.
2675 if (!MaxFieldAlignment.isZero())
2676 Info.Alignment = std::min(Info.Alignment, MaxFieldAlignment);
2677 // Track zero-sized subobjects here where it's already available.
2678 EndsWithZeroSizedObject = Layout.endsWithZeroSizedObject();
2679 // Respect required alignment, this is necessary because we may have adjusted
2680 // the alignment in the case of pragma pack. Note that the required alignment
2681 // doesn't actually apply to the struct alignment at this point.
2682 Alignment = std::max(Alignment, Info.Alignment);
2683 RequiredAlignment = std::max(RequiredAlignment, Layout.getRequiredAlignment());
2684 Info.Alignment = std::max(Info.Alignment, Layout.getRequiredAlignment());
2685 Info.Size = Layout.getNonVirtualSize();
2686 return Info;
2687}
2688
2689MicrosoftRecordLayoutBuilder::ElementInfo
2690MicrosoftRecordLayoutBuilder::getAdjustedElementInfo(
2691 const FieldDecl *FD) {
2692 // Get the alignment of the field type's natural alignment, ignore any
2693 // alignment attributes.
2694 auto TInfo =
2696 ElementInfo Info{TInfo.Width, TInfo.Align};
2697 // Respect align attributes on the field.
2698 CharUnits FieldRequiredAlignment =
2699 Context.toCharUnitsFromBits(FD->getMaxAlignment());
2700 // Respect align attributes on the type.
2701 if (Context.isAlignmentRequired(FD->getType()))
2702 FieldRequiredAlignment = std::max(
2703 Context.getTypeAlignInChars(FD->getType()), FieldRequiredAlignment);
2704 // Respect attributes applied to subobjects of the field.
2705 if (FD->isBitField())
2706 // For some reason __declspec align impacts alignment rather than required
2707 // alignment when it is applied to bitfields.
2708 Info.Alignment = std::max(Info.Alignment, FieldRequiredAlignment);
2709 else {
2710 if (const auto *RT = FD->getType()
2713 auto const &Layout = Context.getASTRecordLayout(RT->getOriginalDecl());
2714 EndsWithZeroSizedObject = Layout.endsWithZeroSizedObject();
2715 FieldRequiredAlignment = std::max(FieldRequiredAlignment,
2716 Layout.getRequiredAlignment());
2717 }
2718 // Capture required alignment as a side-effect.
2719 RequiredAlignment = std::max(RequiredAlignment, FieldRequiredAlignment);
2720 }
2721 // Respect pragma pack, attribute pack and declspec align
2722 if (!MaxFieldAlignment.isZero())
2723 Info.Alignment = std::min(Info.Alignment, MaxFieldAlignment);
2724 if (FD->hasAttr<PackedAttr>())
2725 Info.Alignment = CharUnits::One();
2726 Info.Alignment = std::max(Info.Alignment, FieldRequiredAlignment);
2727 return Info;
2728}
2729
2730void MicrosoftRecordLayoutBuilder::layout(const RecordDecl *RD) {
2731 // For C record layout, zero-sized records always have size 4.
2732 MinEmptyStructSize = CharUnits::fromQuantity(4);
2733 initializeLayout(RD);
2734 layoutFields(RD);
2735 DataSize = Size = Size.alignTo(Alignment);
2736 RequiredAlignment = std::max(
2737 RequiredAlignment, Context.toCharUnitsFromBits(RD->getMaxAlignment()));
2738 finalizeLayout(RD);
2739}
2740
2741void MicrosoftRecordLayoutBuilder::cxxLayout(const CXXRecordDecl *RD) {
2742 // The C++ standard says that empty structs have size 1.
2743 MinEmptyStructSize = CharUnits::One();
2744 initializeLayout(RD);
2745 initializeCXXLayout(RD);
2746 layoutNonVirtualBases(RD);
2747 layoutFields(RD);
2748 injectVBPtr(RD);
2749 injectVFPtr(RD);
2750 if (HasOwnVFPtr || (HasVBPtr && !SharedVBPtrBase))
2751 Alignment = std::max(Alignment, PointerInfo.Alignment);
2752 auto RoundingAlignment = Alignment;
2753 if (!MaxFieldAlignment.isZero())
2754 RoundingAlignment = std::min(RoundingAlignment, MaxFieldAlignment);
2755 if (!UseExternalLayout)
2756 Size = Size.alignTo(RoundingAlignment);
2757 NonVirtualSize = Size;
2758 RequiredAlignment = std::max(
2759 RequiredAlignment, Context.toCharUnitsFromBits(RD->getMaxAlignment()));
2760 layoutVirtualBases(RD);
2761 finalizeLayout(RD);
2762}
2763
2764void MicrosoftRecordLayoutBuilder::initializeLayout(const RecordDecl *RD) {
2765 IsUnion = RD->isUnion();
2767 Alignment = CharUnits::One();
2768 // In 64-bit mode we always perform an alignment step after laying out vbases.
2769 // In 32-bit mode we do not. The check to see if we need to perform alignment
2770 // checks the RequiredAlignment field and performs alignment if it isn't 0.
2771 RequiredAlignment = Context.getTargetInfo().getTriple().isArch64Bit()
2772 ? CharUnits::One()
2773 : CharUnits::Zero();
2774 // Compute the maximum field alignment.
2775 MaxFieldAlignment = CharUnits::Zero();
2776 // Honor the default struct packing maximum alignment flag.
2777 if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct)
2778 MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment);
2779 // Honor the packing attribute. The MS-ABI ignores pragma pack if its larger
2780 // than the pointer size.
2781 if (const MaxFieldAlignmentAttr *MFAA = RD->getAttr<MaxFieldAlignmentAttr>()){
2782 unsigned PackedAlignment = MFAA->getAlignment();
2783 if (PackedAlignment <=
2784 Context.getTargetInfo().getPointerWidth(LangAS::Default))
2785 MaxFieldAlignment = Context.toCharUnitsFromBits(PackedAlignment);
2786 }
2787 // Packed attribute forces max field alignment to be 1.
2788 if (RD->hasAttr<PackedAttr>())
2789 MaxFieldAlignment = CharUnits::One();
2790
2791 // Try to respect the external layout if present.
2792 UseExternalLayout = false;
2793 if (ExternalASTSource *Source = Context.getExternalSource())
2794 UseExternalLayout = Source->layoutRecordType(
2795 RD, External.Size, External.Align, External.FieldOffsets,
2796 External.BaseOffsets, External.VirtualBaseOffsets);
2797}
2798
2799void
2800MicrosoftRecordLayoutBuilder::initializeCXXLayout(const CXXRecordDecl *RD) {
2801 EndsWithZeroSizedObject = false;
2802 LeadsWithZeroSizedBase = false;
2803 HasOwnVFPtr = false;
2804 HasVBPtr = false;
2805 PrimaryBase = nullptr;
2806 SharedVBPtrBase = nullptr;
2807 // Calculate pointer size and alignment. These are used for vfptr and vbprt
2808 // injection.
2809 PointerInfo.Size = Context.toCharUnitsFromBits(
2810 Context.getTargetInfo().getPointerWidth(LangAS::Default));
2811 PointerInfo.Alignment = Context.toCharUnitsFromBits(
2812 Context.getTargetInfo().getPointerAlign(LangAS::Default));
2813 // Respect pragma pack.
2814 if (!MaxFieldAlignment.isZero())
2815 PointerInfo.Alignment = std::min(PointerInfo.Alignment, MaxFieldAlignment);
2816}
2817
2818void
2819MicrosoftRecordLayoutBuilder::layoutNonVirtualBases(const CXXRecordDecl *RD) {
2820 // The MS-ABI lays out all bases that contain leading vfptrs before it lays
2821 // out any bases that do not contain vfptrs. We implement this as two passes
2822 // over the bases. This approach guarantees that the primary base is laid out
2823 // first. We use these passes to calculate some additional aggregated
2824 // information about the bases, such as required alignment and the presence of
2825 // zero sized members.
2826 const ASTRecordLayout *PreviousBaseLayout = nullptr;
2827 bool HasPolymorphicBaseClass = false;
2828 // Iterate through the bases and lay out the non-virtual ones.
2829 for (const CXXBaseSpecifier &Base : RD->bases()) {
2830 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
2831 HasPolymorphicBaseClass |= BaseDecl->isPolymorphic();
2832 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
2833 // Mark and skip virtual bases.
2834 if (Base.isVirtual()) {
2835 HasVBPtr = true;
2836 continue;
2837 }
2838 // Check for a base to share a VBPtr with.
2839 if (!SharedVBPtrBase && BaseLayout.hasVBPtr()) {
2840 SharedVBPtrBase = BaseDecl;
2841 HasVBPtr = true;
2842 }
2843 // Only lay out bases with extendable VFPtrs on the first pass.
2844 if (!BaseLayout.hasExtendableVFPtr())
2845 continue;
2846 // If we don't have a primary base, this one qualifies.
2847 if (!PrimaryBase) {
2848 PrimaryBase = BaseDecl;
2849 LeadsWithZeroSizedBase = BaseLayout.leadsWithZeroSizedBase();
2850 }
2851 // Lay out the base.
2852 layoutNonVirtualBase(RD, BaseDecl, BaseLayout, PreviousBaseLayout);
2853 }
2854 // Figure out if we need a fresh VFPtr for this class.
2855 if (RD->isPolymorphic()) {
2856 if (!HasPolymorphicBaseClass)
2857 // This class introduces polymorphism, so we need a vftable to store the
2858 // RTTI information.
2859 HasOwnVFPtr = true;
2860 else if (!PrimaryBase) {
2861 // We have a polymorphic base class but can't extend its vftable. Add a
2862 // new vfptr if we would use any vftable slots.
2863 for (CXXMethodDecl *M : RD->methods()) {
2864 if (MicrosoftVTableContext::hasVtableSlot(M) &&
2865 M->size_overridden_methods() == 0) {
2866 HasOwnVFPtr = true;
2867 break;
2868 }
2869 }
2870 }
2871 }
2872 // If we don't have a primary base then we have a leading object that could
2873 // itself lead with a zero-sized object, something we track.
2874 bool CheckLeadingLayout = !PrimaryBase;
2875 // Iterate through the bases and lay out the non-virtual ones.
2876 for (const CXXBaseSpecifier &Base : RD->bases()) {
2877 if (Base.isVirtual())
2878 continue;
2879 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
2880 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
2881 // Only lay out bases without extendable VFPtrs on the second pass.
2882 if (BaseLayout.hasExtendableVFPtr()) {
2883 VBPtrOffset = Bases[BaseDecl] + BaseLayout.getNonVirtualSize();
2884 continue;
2885 }
2886 // If this is the first layout, check to see if it leads with a zero sized
2887 // object. If it does, so do we.
2888 if (CheckLeadingLayout) {
2889 CheckLeadingLayout = false;
2890 LeadsWithZeroSizedBase = BaseLayout.leadsWithZeroSizedBase();
2891 }
2892 // Lay out the base.
2893 layoutNonVirtualBase(RD, BaseDecl, BaseLayout, PreviousBaseLayout);
2894 VBPtrOffset = Bases[BaseDecl] + BaseLayout.getNonVirtualSize();
2895 }
2896 // Set our VBPtroffset if we know it at this point.
2897 if (!HasVBPtr)
2898 VBPtrOffset = CharUnits::fromQuantity(-1);
2899 else if (SharedVBPtrBase) {
2900 const ASTRecordLayout &Layout = Context.getASTRecordLayout(SharedVBPtrBase);
2901 VBPtrOffset = Bases[SharedVBPtrBase] + Layout.getVBPtrOffset();
2902 }
2903}
2904
2905static bool recordUsesEBO(const RecordDecl *RD) {
2906 if (!isa<CXXRecordDecl>(RD))
2907 return false;
2908 if (RD->hasAttr<EmptyBasesAttr>())
2909 return true;
2910 if (auto *LVA = RD->getAttr<LayoutVersionAttr>())
2911 // TODO: Double check with the next version of MSVC.
2912 if (LVA->getVersion() <= LangOptions::MSVC2015)
2913 return false;
2914 // TODO: Some later version of MSVC will change the default behavior of the
2915 // compiler to enable EBO by default. When this happens, we will need an
2916 // additional isCompatibleWithMSVC check.
2917 return false;
2918}
2919
2920void MicrosoftRecordLayoutBuilder::layoutNonVirtualBase(
2921 const CXXRecordDecl *RD, const CXXRecordDecl *BaseDecl,
2922 const ASTRecordLayout &BaseLayout,
2923 const ASTRecordLayout *&PreviousBaseLayout) {
2924 // Insert padding between two bases if the left first one is zero sized or
2925 // contains a zero sized subobject and the right is zero sized or one leads
2926 // with a zero sized base.
2927 bool MDCUsesEBO = recordUsesEBO(RD);
2928 if (PreviousBaseLayout && PreviousBaseLayout->endsWithZeroSizedObject() &&
2929 BaseLayout.leadsWithZeroSizedBase() && !MDCUsesEBO)
2930 Size++;
2931 ElementInfo Info = getAdjustedElementInfo(BaseLayout);
2932 CharUnits BaseOffset;
2933
2934 // Respect the external AST source base offset, if present.
2935 bool FoundBase = false;
2936 if (UseExternalLayout) {
2937 FoundBase = External.getExternalNVBaseOffset(BaseDecl, BaseOffset);
2938 if (BaseOffset > Size) {
2939 Size = BaseOffset;
2940 }
2941 }
2942
2943 if (!FoundBase) {
2944 if (MDCUsesEBO && BaseDecl->isEmpty() &&
2945 (BaseLayout.getNonVirtualSize() == CharUnits::Zero())) {
2946 BaseOffset = CharUnits::Zero();
2947 } else {
2948 // Otherwise, lay the base out at the end of the MDC.
2949 BaseOffset = Size = Size.alignTo(Info.Alignment);
2950 }
2951 }
2952 Bases.insert(std::make_pair(BaseDecl, BaseOffset));
2953 Size += BaseLayout.getNonVirtualSize();
2954 DataSize = Size;
2955 PreviousBaseLayout = &BaseLayout;
2956}
2957
2958void MicrosoftRecordLayoutBuilder::layoutFields(const RecordDecl *RD) {
2959 LastFieldIsNonZeroWidthBitfield = false;
2960 for (const FieldDecl *Field : RD->fields())
2961 layoutField(Field);
2962}
2963
2964void MicrosoftRecordLayoutBuilder::layoutField(const FieldDecl *FD) {
2965 if (FD->isBitField()) {
2966 layoutBitField(FD);
2967 return;
2968 }
2969 LastFieldIsNonZeroWidthBitfield = false;
2970 ElementInfo Info = getAdjustedElementInfo(FD);
2971 Alignment = std::max(Alignment, Info.Alignment);
2972
2973 const CXXRecordDecl *FieldClass = FD->getType()->getAsCXXRecordDecl();
2974 bool IsOverlappingEmptyField = FD->isPotentiallyOverlapping() &&
2975 FieldClass->isEmpty() &&
2976 FieldClass->fields().empty();
2977 CharUnits FieldOffset = CharUnits::Zero();
2978
2979 if (UseExternalLayout) {
2980 FieldOffset =
2981 Context.toCharUnitsFromBits(External.getExternalFieldOffset(FD));
2982 } else if (IsUnion) {
2983 FieldOffset = CharUnits::Zero();
2984 } else if (EmptySubobjects) {
2985 if (!IsOverlappingEmptyField)
2986 FieldOffset = DataSize.alignTo(Info.Alignment);
2987
2988 while (!EmptySubobjects->CanPlaceFieldAtOffset(FD, FieldOffset)) {
2989 const CXXRecordDecl *ParentClass = cast<CXXRecordDecl>(FD->getParent());
2990 bool HasBases = ParentClass && (!ParentClass->bases().empty() ||
2991 !ParentClass->vbases().empty());
2992 if (FieldOffset == CharUnits::Zero() && DataSize != CharUnits::Zero() &&
2993 HasBases) {
2994 // MSVC appears to only do this when there are base classes;
2995 // otherwise it overlaps no_unique_address fields in non-zero offsets.
2996 FieldOffset = DataSize.alignTo(Info.Alignment);
2997 } else {
2998 FieldOffset += Info.Alignment;
2999 }
3000 }
3001 } else {
3002 FieldOffset = Size.alignTo(Info.Alignment);
3003 }
3004
3005 uint64_t UnpaddedFielddOffsetInBits =
3006 Context.toBits(DataSize) - RemainingBitsInField;
3007
3008 ::CheckFieldPadding(Context, IsUnion, Context.toBits(FieldOffset),
3009 UnpaddedFielddOffsetInBits, FD);
3010
3011 RemainingBitsInField = 0;
3012
3013 placeFieldAtOffset(FieldOffset);
3014
3015 if (!IsOverlappingEmptyField)
3016 DataSize = std::max(DataSize, FieldOffset + Info.Size);
3017
3018 Size = std::max(Size, FieldOffset + Info.Size);
3019}
3020
3021void MicrosoftRecordLayoutBuilder::layoutBitField(const FieldDecl *FD) {
3022 unsigned Width = FD->getBitWidthValue();
3023 if (Width == 0) {
3024 layoutZeroWidthBitField(FD);
3025 return;
3026 }
3027 ElementInfo Info = getAdjustedElementInfo(FD);
3028 // Clamp the bitfield to a containable size for the sake of being able
3029 // to lay them out. Sema will throw an error.
3030 if (Width > Context.toBits(Info.Size))
3031 Width = Context.toBits(Info.Size);
3032 // Check to see if this bitfield fits into an existing allocation. Note:
3033 // MSVC refuses to pack bitfields of formal types with different sizes
3034 // into the same allocation.
3035 if (!UseExternalLayout && !IsUnion && LastFieldIsNonZeroWidthBitfield &&
3036 CurrentBitfieldSize == Info.Size && Width <= RemainingBitsInField) {
3037 placeFieldAtBitOffset(Context.toBits(Size) - RemainingBitsInField);
3038 RemainingBitsInField -= Width;
3039 return;
3040 }
3041 LastFieldIsNonZeroWidthBitfield = true;
3042 CurrentBitfieldSize = Info.Size;
3043 if (UseExternalLayout) {
3044 auto FieldBitOffset = External.getExternalFieldOffset(FD);
3045 placeFieldAtBitOffset(FieldBitOffset);
3046 auto NewSize = Context.toCharUnitsFromBits(
3047 llvm::alignDown(FieldBitOffset, Context.toBits(Info.Alignment)) +
3048 Context.toBits(Info.Size));
3049 Size = std::max(Size, NewSize);
3050 Alignment = std::max(Alignment, Info.Alignment);
3051 } else if (IsUnion) {
3052 placeFieldAtOffset(CharUnits::Zero());
3053 Size = std::max(Size, Info.Size);
3054 // TODO: Add a Sema warning that MS ignores bitfield alignment in unions.
3055 } else {
3056 // Allocate a new block of memory and place the bitfield in it.
3057 CharUnits FieldOffset = Size.alignTo(Info.Alignment);
3058 uint64_t UnpaddedFieldOffsetInBits =
3059 Context.toBits(DataSize) - RemainingBitsInField;
3060 placeFieldAtOffset(FieldOffset);
3061 Size = FieldOffset + Info.Size;
3062 Alignment = std::max(Alignment, Info.Alignment);
3063 RemainingBitsInField = Context.toBits(Info.Size) - Width;
3064 ::CheckFieldPadding(Context, IsUnion, Context.toBits(FieldOffset),
3065 UnpaddedFieldOffsetInBits, FD);
3066 }
3067 DataSize = Size;
3068}
3069
3070void
3071MicrosoftRecordLayoutBuilder::layoutZeroWidthBitField(const FieldDecl *FD) {
3072 // Zero-width bitfields are ignored unless they follow a non-zero-width
3073 // bitfield.
3074 if (!LastFieldIsNonZeroWidthBitfield) {
3075 placeFieldAtOffset(IsUnion ? CharUnits::Zero() : Size);
3076 // TODO: Add a Sema warning that MS ignores alignment for zero
3077 // sized bitfields that occur after zero-size bitfields or non-bitfields.
3078 return;
3079 }
3080 LastFieldIsNonZeroWidthBitfield = false;
3081 ElementInfo Info = getAdjustedElementInfo(FD);
3082 if (IsUnion) {
3083 placeFieldAtOffset(CharUnits::Zero());
3084 Size = std::max(Size, Info.Size);
3085 // TODO: Add a Sema warning that MS ignores bitfield alignment in unions.
3086 } else {
3087 // Round up the current record size to the field's alignment boundary.
3088 CharUnits FieldOffset = Size.alignTo(Info.Alignment);
3089 uint64_t UnpaddedFieldOffsetInBits =
3090 Context.toBits(DataSize) - RemainingBitsInField;
3091 placeFieldAtOffset(FieldOffset);
3092 RemainingBitsInField = 0;
3093 Size = FieldOffset;
3094 Alignment = std::max(Alignment, Info.Alignment);
3095 ::CheckFieldPadding(Context, IsUnion, Context.toBits(FieldOffset),
3096 UnpaddedFieldOffsetInBits, FD);
3097 }
3098 DataSize = Size;
3099}
3100
3101void MicrosoftRecordLayoutBuilder::injectVBPtr(const CXXRecordDecl *RD) {
3102 if (!HasVBPtr || SharedVBPtrBase)
3103 return;
3104 // Inject the VBPointer at the injection site.
3105 CharUnits InjectionSite = VBPtrOffset;
3106 // But before we do, make sure it's properly aligned.
3107 VBPtrOffset = VBPtrOffset.alignTo(PointerInfo.Alignment);
3108 // Determine where the first field should be laid out after the vbptr.
3109 CharUnits FieldStart = VBPtrOffset + PointerInfo.Size;
3110 // Shift everything after the vbptr down, unless we're using an external
3111 // layout.
3112 if (UseExternalLayout) {
3113 // It is possible that there were no fields or bases located after vbptr,
3114 // so the size was not adjusted before.
3115 if (Size < FieldStart)
3116 Size = FieldStart;
3117 return;
3118 }
3119 // Make sure that the amount we push the fields back by is a multiple of the
3120 // alignment.
3121 CharUnits Offset = (FieldStart - InjectionSite)
3122 .alignTo(std::max(RequiredAlignment, Alignment));
3123 Size += Offset;
3124 for (uint64_t &FieldOffset : FieldOffsets)
3125 FieldOffset += Context.toBits(Offset);
3126 for (BaseOffsetsMapTy::value_type &Base : Bases)
3127 if (Base.second >= InjectionSite)
3128 Base.second += Offset;
3129}
3130
3131void MicrosoftRecordLayoutBuilder::injectVFPtr(const CXXRecordDecl *RD) {
3132 if (!HasOwnVFPtr)
3133 return;
3134 // Make sure that the amount we push the struct back by is a multiple of the
3135 // alignment.
3136 CharUnits Offset =
3137 PointerInfo.Size.alignTo(std::max(RequiredAlignment, Alignment));
3138 // Push back the vbptr, but increase the size of the object and push back
3139 // regular fields by the offset only if not using external record layout.
3140 if (HasVBPtr)
3141 VBPtrOffset += Offset;
3142
3143 if (UseExternalLayout) {
3144 // The class may have size 0 and a vfptr (e.g. it's an interface class). The
3145 // size was not correctly set before in this case.
3146 if (Size.isZero())
3147 Size += Offset;
3148 return;
3149 }
3150
3151 Size += Offset;
3152
3153 // If we're using an external layout, the fields offsets have already
3154 // accounted for this adjustment.
3155 for (uint64_t &FieldOffset : FieldOffsets)
3156 FieldOffset += Context.toBits(Offset);
3157 for (BaseOffsetsMapTy::value_type &Base : Bases)
3158 Base.second += Offset;
3159}
3160
3161void MicrosoftRecordLayoutBuilder::layoutVirtualBases(const CXXRecordDecl *RD) {
3162 if (!HasVBPtr)
3163 return;
3164 // Vtordisps are always 4 bytes (even in 64-bit mode)
3165 CharUnits VtorDispSize = CharUnits::fromQuantity(4);
3166 CharUnits VtorDispAlignment = VtorDispSize;
3167 // vtordisps respect pragma pack.
3168 if (!MaxFieldAlignment.isZero())
3169 VtorDispAlignment = std::min(VtorDispAlignment, MaxFieldAlignment);
3170 // The alignment of the vtordisp is at least the required alignment of the
3171 // entire record. This requirement may be present to support vtordisp
3172 // injection.
3173 for (const CXXBaseSpecifier &VBase : RD->vbases()) {
3174 const CXXRecordDecl *BaseDecl = VBase.getType()->getAsCXXRecordDecl();
3175 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
3176 RequiredAlignment =
3177 std::max(RequiredAlignment, BaseLayout.getRequiredAlignment());
3178 }
3179 VtorDispAlignment = std::max(VtorDispAlignment, RequiredAlignment);
3180 // Compute the vtordisp set.
3182 computeVtorDispSet(HasVtorDispSet, RD);
3183 // Iterate through the virtual bases and lay them out.
3184 const ASTRecordLayout *PreviousBaseLayout = nullptr;
3185 for (const CXXBaseSpecifier &VBase : RD->vbases()) {
3186 const CXXRecordDecl *BaseDecl = VBase.getType()->getAsCXXRecordDecl();
3187 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
3188 bool HasVtordisp = HasVtorDispSet.contains(BaseDecl);
3189 // Insert padding between two bases if the left first one is zero sized or
3190 // contains a zero sized subobject and the right is zero sized or one leads
3191 // with a zero sized base. The padding between virtual bases is 4
3192 // bytes (in both 32 and 64 bits modes) and always involves rounding up to
3193 // the required alignment, we don't know why.
3194 if ((PreviousBaseLayout && PreviousBaseLayout->endsWithZeroSizedObject() &&
3195 BaseLayout.leadsWithZeroSizedBase() && !recordUsesEBO(RD)) ||
3196 HasVtordisp) {
3197 Size = Size.alignTo(VtorDispAlignment) + VtorDispSize;
3198 Alignment = std::max(VtorDispAlignment, Alignment);
3199 }
3200 // Insert the virtual base.
3201 ElementInfo Info = getAdjustedElementInfo(BaseLayout);
3202 CharUnits BaseOffset;
3203
3204 // Respect the external AST source base offset, if present.
3205 if (UseExternalLayout) {
3206 if (!External.getExternalVBaseOffset(BaseDecl, BaseOffset))
3207 BaseOffset = Size;
3208 } else
3209 BaseOffset = Size.alignTo(Info.Alignment);
3210
3211 assert(BaseOffset >= Size && "base offset already allocated");
3212
3213 VBases.insert(std::make_pair(BaseDecl,
3214 ASTRecordLayout::VBaseInfo(BaseOffset, HasVtordisp)));
3215 Size = BaseOffset + BaseLayout.getNonVirtualSize();
3216 PreviousBaseLayout = &BaseLayout;
3217 }
3218}
3219
3220void MicrosoftRecordLayoutBuilder::finalizeLayout(const RecordDecl *RD) {
3221 uint64_t UnpaddedSizeInBits = Context.toBits(DataSize);
3222 UnpaddedSizeInBits -= RemainingBitsInField;
3223
3224 // MS ABI allocates 1 byte for empty class
3225 // (not padding)
3226 if (Size.isZero())
3227 UnpaddedSizeInBits += 8;
3228
3229 // Respect required alignment. Note that in 32-bit mode Required alignment
3230 // may be 0 and cause size not to be updated.
3231 DataSize = Size;
3232 if (!RequiredAlignment.isZero()) {
3233 Alignment = std::max(Alignment, RequiredAlignment);
3234 auto RoundingAlignment = Alignment;
3235 if (!MaxFieldAlignment.isZero())
3236 RoundingAlignment = std::min(RoundingAlignment, MaxFieldAlignment);
3237 RoundingAlignment = std::max(RoundingAlignment, RequiredAlignment);
3238 Size = Size.alignTo(RoundingAlignment);
3239 }
3240 if (Size.isZero()) {
3241 if (!recordUsesEBO(RD) || !cast<CXXRecordDecl>(RD)->isEmpty()) {
3242 EndsWithZeroSizedObject = true;
3243 LeadsWithZeroSizedBase = true;
3244 }
3245 // Zero-sized structures have size equal to their alignment if a
3246 // __declspec(align) came into play.
3247 if (RequiredAlignment >= MinEmptyStructSize)
3248 Size = Alignment;
3249 else
3250 Size = MinEmptyStructSize;
3251 }
3252
3253 if (UseExternalLayout) {
3254 Size = Context.toCharUnitsFromBits(External.Size);
3255 if (External.Align)
3256 Alignment = Context.toCharUnitsFromBits(External.Align);
3257 return;
3258 }
3259 unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
3260 uint64_t SizeInBits = Context.toBits(Size);
3261
3262 if (SizeInBits > UnpaddedSizeInBits) {
3263 unsigned int PadSize = SizeInBits - UnpaddedSizeInBits;
3264 bool InBits = true;
3265 if (PadSize % CharBitNum == 0) {
3266 PadSize = PadSize / CharBitNum;
3267 InBits = false;
3268 }
3269
3270 Context.getDiagnostics().Report(RD->getLocation(),
3271 diag::warn_padded_struct_size)
3272 << Context.getCanonicalTagType(RD) << PadSize
3273 << (InBits ? 1 : 0); // (byte|bit)
3274 }
3275}
3276
3277// Recursively walks the non-virtual bases of a class and determines if any of
3278// them are in the bases with overridden methods set.
3279static bool
3280RequiresVtordisp(const llvm::SmallPtrSetImpl<const CXXRecordDecl *> &
3281 BasesWithOverriddenMethods,
3282 const CXXRecordDecl *RD) {
3283 if (BasesWithOverriddenMethods.count(RD))
3284 return true;
3285 // If any of a virtual bases non-virtual bases (recursively) requires a
3286 // vtordisp than so does this virtual base.
3287 for (const CXXBaseSpecifier &Base : RD->bases())
3288 if (!Base.isVirtual() &&
3289 RequiresVtordisp(BasesWithOverriddenMethods,
3290 Base.getType()->getAsCXXRecordDecl()))
3291 return true;
3292 return false;
3293}
3294
3295void MicrosoftRecordLayoutBuilder::computeVtorDispSet(
3296 llvm::SmallPtrSetImpl<const CXXRecordDecl *> &HasVtordispSet,
3297 const CXXRecordDecl *RD) const {
3298 // /vd2 or #pragma vtordisp(2): Always use vtordisps for virtual bases with
3299 // vftables.
3300 if (RD->getMSVtorDispMode() == MSVtorDispMode::ForVFTable) {
3301 for (const CXXBaseSpecifier &Base : RD->vbases()) {
3302 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
3303 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
3304 if (Layout.hasExtendableVFPtr())
3305 HasVtordispSet.insert(BaseDecl);
3306 }
3307 return;
3308 }
3309
3310 // If any of our bases need a vtordisp for this type, so do we. Check our
3311 // direct bases for vtordisp requirements.
3312 for (const CXXBaseSpecifier &Base : RD->bases()) {
3313 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
3314 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
3315 for (const auto &bi : Layout.getVBaseOffsetsMap())
3316 if (bi.second.hasVtorDisp())
3317 HasVtordispSet.insert(bi.first);
3318 }
3319 // We don't introduce any additional vtordisps if either:
3320 // * A user declared constructor or destructor aren't declared.
3321 // * #pragma vtordisp(0) or the /vd0 flag are in use.
3323 RD->getMSVtorDispMode() == MSVtorDispMode::Never)
3324 return;
3325 // /vd1 or #pragma vtordisp(1): Try to guess based on whether we think it's
3326 // possible for a partially constructed object with virtual base overrides to
3327 // escape a non-trivial constructor.
3328 assert(RD->getMSVtorDispMode() == MSVtorDispMode::ForVBaseOverride);
3329 // Compute a set of base classes which define methods we override. A virtual
3330 // base in this set will require a vtordisp. A virtual base that transitively
3331 // contains one of these bases as a non-virtual base will also require a
3332 // vtordisp.
3334 llvm::SmallPtrSet<const CXXRecordDecl *, 2> BasesWithOverriddenMethods;
3335 // Seed the working set with our non-destructor, non-pure virtual methods.
3336 for (const CXXMethodDecl *MD : RD->methods())
3337 if (MicrosoftVTableContext::hasVtableSlot(MD) &&
3338 !isa<CXXDestructorDecl>(MD) && !MD->isPureVirtual())
3339 Work.insert(MD);
3340 while (!Work.empty()) {
3341 const CXXMethodDecl *MD = *Work.begin();
3342 auto MethodRange = MD->overridden_methods();
3343 // If a virtual method has no-overrides it lives in its parent's vtable.
3344 if (MethodRange.begin() == MethodRange.end())
3345 BasesWithOverriddenMethods.insert(MD->getParent());
3346 else
3347 Work.insert_range(MethodRange);
3348 // We've finished processing this element, remove it from the working set.
3349 Work.erase(MD);
3350 }
3351 // For each of our virtual bases, check if it is in the set of overridden
3352 // bases or if it transitively contains a non-virtual base that is.
3353 for (const CXXBaseSpecifier &Base : RD->vbases()) {
3354 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
3355 if (!HasVtordispSet.count(BaseDecl) &&
3356 RequiresVtordisp(BasesWithOverriddenMethods, BaseDecl))
3357 HasVtordispSet.insert(BaseDecl);
3358 }
3359}
3360
3361/// getASTRecordLayout - Get or compute information about the layout of the
3362/// specified record (struct/union/class), which indicates its size and field
3363/// position information.
3364const ASTRecordLayout &
3366 // These asserts test different things. A record has a definition
3367 // as soon as we begin to parse the definition. That definition is
3368 // not a complete definition (which is what isDefinition() tests)
3369 // until we *finish* parsing the definition.
3370
3371 if (D->hasExternalLexicalStorage() && !D->getDefinition())
3372 getExternalSource()->CompleteType(const_cast<RecordDecl*>(D));
3373 // Complete the redecl chain (if necessary).
3374 (void)D->getMostRecentDecl();
3375
3376 D = D->getDefinition();
3377 assert(D && "Cannot get layout of forward declarations!");
3378 assert(!D->isInvalidDecl() && "Cannot get layout of invalid decl!");
3379 assert(D->isCompleteDefinition() && "Cannot layout type before complete!");
3380
3381 // Look up this layout, if already laid out, return what we have.
3382 // Note that we can't save a reference to the entry because this function
3383 // is recursive.
3384 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
3385 if (Entry) return *Entry;
3386
3387 const ASTRecordLayout *NewEntry = nullptr;
3388
3389 if (getTargetInfo().hasMicrosoftRecordLayout()) {
3390 if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
3391 EmptySubobjectMap EmptySubobjects(*this, RD);
3392 MicrosoftRecordLayoutBuilder Builder(*this, &EmptySubobjects);
3393 Builder.cxxLayout(RD);
3394 NewEntry = new (*this) ASTRecordLayout(
3395 *this, Builder.Size, Builder.Alignment, Builder.Alignment,
3396 Builder.Alignment, Builder.RequiredAlignment, Builder.HasOwnVFPtr,
3397 Builder.HasOwnVFPtr || Builder.PrimaryBase, Builder.VBPtrOffset,
3398 Builder.DataSize, Builder.FieldOffsets, Builder.NonVirtualSize,
3399 Builder.Alignment, Builder.Alignment, CharUnits::Zero(),
3400 Builder.PrimaryBase, false, Builder.SharedVBPtrBase,
3401 Builder.EndsWithZeroSizedObject, Builder.LeadsWithZeroSizedBase,
3402 Builder.Bases, Builder.VBases);
3403 } else {
3404 MicrosoftRecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/nullptr);
3405 Builder.layout(D);
3406 NewEntry = new (*this) ASTRecordLayout(
3407 *this, Builder.Size, Builder.Alignment, Builder.Alignment,
3408 Builder.Alignment, Builder.RequiredAlignment, Builder.Size,
3409 Builder.FieldOffsets);
3410 }
3411 } else {
3412 if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
3413 EmptySubobjectMap EmptySubobjects(*this, RD);
3414 ItaniumRecordLayoutBuilder Builder(*this, &EmptySubobjects);
3415 Builder.Layout(RD);
3416
3417 // In certain situations, we are allowed to lay out objects in the
3418 // tail-padding of base classes. This is ABI-dependent.
3419 // FIXME: this should be stored in the record layout.
3420 bool skipTailPadding =
3421 mustSkipTailPadding(getTargetInfo().getCXXABI(), RD);
3422
3423 // FIXME: This should be done in FinalizeLayout.
3424 CharUnits DataSize =
3425 skipTailPadding ? Builder.getSize() : Builder.getDataSize();
3426 CharUnits NonVirtualSize =
3427 skipTailPadding ? DataSize : Builder.NonVirtualSize;
3428 NewEntry = new (*this) ASTRecordLayout(
3429 *this, Builder.getSize(), Builder.Alignment,
3430 Builder.PreferredAlignment, Builder.UnadjustedAlignment,
3431 /*RequiredAlignment : used by MS-ABI)*/
3432 Builder.Alignment, Builder.HasOwnVFPtr, RD->isDynamicClass(),
3433 CharUnits::fromQuantity(-1), DataSize, Builder.FieldOffsets,
3434 NonVirtualSize, Builder.NonVirtualAlignment,
3435 Builder.PreferredNVAlignment,
3436 EmptySubobjects.SizeOfLargestEmptySubobject, Builder.PrimaryBase,
3437 Builder.PrimaryBaseIsVirtual, nullptr, false, false, Builder.Bases,
3438 Builder.VBases);
3439 } else {
3440 ItaniumRecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/nullptr);
3441 Builder.Layout(D);
3442
3443 NewEntry = new (*this) ASTRecordLayout(
3444 *this, Builder.getSize(), Builder.Alignment,
3445 Builder.PreferredAlignment, Builder.UnadjustedAlignment,
3446 /*RequiredAlignment : used by MS-ABI)*/
3447 Builder.Alignment, Builder.getSize(), Builder.FieldOffsets);
3448 }
3449 }
3450
3451 ASTRecordLayouts[D] = NewEntry;
3452
3453 constexpr uint64_t MaxStructSizeInBytes = 1ULL << 60;
3454 CharUnits StructSize = NewEntry->getSize();
3455 if (static_cast<uint64_t>(StructSize.getQuantity()) >= MaxStructSizeInBytes) {
3456 getDiagnostics().Report(D->getLocation(), diag::err_struct_too_large)
3457 << D->getName() << MaxStructSizeInBytes;
3458 }
3459
3460 if (getLangOpts().DumpRecordLayouts) {
3461 llvm::outs() << "\n*** Dumping AST Record Layout\n";
3462 DumpRecordLayout(D, llvm::outs(), getLangOpts().DumpRecordLayoutsSimple);
3463 }
3464
3465 return *NewEntry;
3466}
3467
3469 if (!getTargetInfo().getCXXABI().hasKeyFunctions())
3470 return nullptr;
3471
3472 assert(RD->getDefinition() && "Cannot get key function for forward decl!");
3473 RD = RD->getDefinition();
3474
3475 // Beware:
3476 // 1) computing the key function might trigger deserialization, which might
3477 // invalidate iterators into KeyFunctions
3478 // 2) 'get' on the LazyDeclPtr might also trigger deserialization and
3479 // invalidate the LazyDeclPtr within the map itself
3480 LazyDeclPtr Entry = KeyFunctions[RD];
3481 const Decl *Result =
3482 Entry ? Entry.get(getExternalSource()) : computeKeyFunction(*this, RD);
3483
3484 // Store it back if it changed.
3485 if (Entry.isOffset() || Entry.isValid() != bool(Result))
3486 KeyFunctions[RD] = const_cast<Decl*>(Result);
3487
3488 return cast_or_null<CXXMethodDecl>(Result);
3489}
3490
3492 assert(Method == Method->getFirstDecl() &&
3493 "not working with method declaration from class definition");
3494
3495 // Look up the cache entry. Since we're working with the first
3496 // declaration, its parent must be the class definition, which is
3497 // the correct key for the KeyFunctions hash.
3498 const auto &Map = KeyFunctions;
3499 auto I = Map.find(Method->getParent());
3500
3501 // If it's not cached, there's nothing to do.
3502 if (I == Map.end()) return;
3503
3504 // If it is cached, check whether it's the target method, and if so,
3505 // remove it from the cache. Note, the call to 'get' might invalidate
3506 // the iterator and the LazyDeclPtr object within the map.
3507 LazyDeclPtr Ptr = I->second;
3508 if (Ptr.get(getExternalSource()) == Method) {
3509 // FIXME: remember that we did this for module / chained PCH state?
3510 KeyFunctions.erase(Method->getParent());
3511 }
3512}
3513
3514static uint64_t getFieldOffset(const ASTContext &C, const FieldDecl *FD) {
3515 const ASTRecordLayout &Layout = C.getASTRecordLayout(FD->getParent());
3516 return Layout.getFieldOffset(FD->getFieldIndex());
3517}
3518
3519uint64_t ASTContext::getFieldOffset(const ValueDecl *VD) const {
3520 uint64_t OffsetInBits;
3521 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
3522 OffsetInBits = ::getFieldOffset(*this, FD);
3523 } else {
3524 const IndirectFieldDecl *IFD = cast<IndirectFieldDecl>(VD);
3525
3526 OffsetInBits = 0;
3527 for (const NamedDecl *ND : IFD->chain())
3528 OffsetInBits += ::getFieldOffset(*this, cast<FieldDecl>(ND));
3529 }
3530
3531 return OffsetInBits;
3532}
3533
3535 const ObjCIvarDecl *Ivar) const {
3536 Ivar = Ivar->getCanonicalDecl();
3537 const ObjCInterfaceDecl *Container = Ivar->getContainingInterface();
3538 const ASTRecordLayout *RL = &getASTObjCInterfaceLayout(Container);
3539
3540 // Compute field index.
3541 //
3542 // FIXME: The index here is closely tied to how ASTContext::getObjCLayout is
3543 // implemented. This should be fixed to get the information from the layout
3544 // directly.
3545 unsigned Index = 0;
3546
3547 for (const ObjCIvarDecl *IVD = Container->all_declared_ivar_begin();
3548 IVD; IVD = IVD->getNextIvar()) {
3549 if (Ivar == IVD)
3550 break;
3551 ++Index;
3552 }
3553 assert(Index < RL->getFieldCount() && "Ivar is not inside record layout!");
3554
3555 return RL->getFieldOffset(Index);
3556}
3557
3558/// getObjCLayout - Get or compute information about the layout of the
3559/// given interface.
3560///
3561/// \param Impl - If given, also include the layout of the interface's
3562/// implementation. This may differ by including synthesized ivars.
3563const ASTRecordLayout &
3564ASTContext::getObjCLayout(const ObjCInterfaceDecl *D) const {
3565 // Retrieve the definition
3566 if (D->hasExternalLexicalStorage() && !D->getDefinition())
3568 D = D->getDefinition();
3569 assert(D && !D->isInvalidDecl() && D->isThisDeclarationADefinition() &&
3570 "Invalid interface decl!");
3571
3572 // Look up this layout, if already laid out, return what we have.
3573 if (const ASTRecordLayout *Entry = ObjCLayouts[D])
3574 return *Entry;
3575
3576 ItaniumRecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/nullptr);
3577 Builder.Layout(D);
3578
3579 const ASTRecordLayout *NewEntry = new (*this) ASTRecordLayout(
3580 *this, Builder.getSize(), Builder.Alignment, Builder.PreferredAlignment,
3581 Builder.UnadjustedAlignment,
3582 /*RequiredAlignment : used by MS-ABI)*/
3583 Builder.Alignment, Builder.getDataSize(), Builder.FieldOffsets);
3584
3585 ObjCLayouts[D] = NewEntry;
3586
3587 return *NewEntry;
3588}
3589
3590static void PrintOffset(raw_ostream &OS,
3591 CharUnits Offset, unsigned IndentLevel) {
3592 OS << llvm::format("%10" PRId64 " | ", (int64_t)Offset.getQuantity());
3593 OS.indent(IndentLevel * 2);
3594}
3595
3596static void PrintBitFieldOffset(raw_ostream &OS, CharUnits Offset,
3597 unsigned Begin, unsigned Width,
3598 unsigned IndentLevel) {
3599 llvm::SmallString<10> Buffer;
3600 {
3601 llvm::raw_svector_ostream BufferOS(Buffer);
3602 BufferOS << Offset.getQuantity() << ':';
3603 if (Width == 0) {
3604 BufferOS << '-';
3605 } else {
3606 BufferOS << Begin << '-' << (Begin + Width - 1);
3607 }
3608 }
3609
3610 OS << llvm::right_justify(Buffer, 10) << " | ";
3611 OS.indent(IndentLevel * 2);
3612}
3613
3614static void PrintIndentNoOffset(raw_ostream &OS, unsigned IndentLevel) {
3615 OS << " | ";
3616 OS.indent(IndentLevel * 2);
3617}
3618
3619static void DumpRecordLayout(raw_ostream &OS, const RecordDecl *RD,
3620 const ASTContext &C,
3621 CharUnits Offset,
3622 unsigned IndentLevel,
3623 const char* Description,
3624 bool PrintSizeInfo,
3625 bool IncludeVirtualBases) {
3626 const ASTRecordLayout &Layout = C.getASTRecordLayout(RD);
3627 auto CXXRD = dyn_cast<CXXRecordDecl>(RD);
3628
3629 PrintOffset(OS, Offset, IndentLevel);
3630 OS << C.getCanonicalTagType(const_cast<RecordDecl *>(RD));
3631 if (Description)
3632 OS << ' ' << Description;
3633 if (CXXRD && CXXRD->isEmpty())
3634 OS << " (empty)";
3635 OS << '\n';
3636
3637 IndentLevel++;
3638
3639 // Dump bases.
3640 if (CXXRD) {
3641 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
3642 bool HasOwnVFPtr = Layout.hasOwnVFPtr();
3643 bool HasOwnVBPtr = Layout.hasOwnVBPtr();
3644
3645 // Vtable pointer.
3646 if (CXXRD->isDynamicClass() && !PrimaryBase &&
3647 !C.getTargetInfo().hasMicrosoftRecordLayout()) {
3648 PrintOffset(OS, Offset, IndentLevel);
3649 OS << '(' << *RD << " vtable pointer)\n";
3650 } else if (HasOwnVFPtr) {
3651 PrintOffset(OS, Offset, IndentLevel);
3652 // vfptr (for Microsoft C++ ABI)
3653 OS << '(' << *RD << " vftable pointer)\n";
3654 }
3655
3656 // Collect nvbases.
3658 for (const CXXBaseSpecifier &Base : CXXRD->bases()) {
3659 assert(!Base.getType()->isDependentType() &&
3660 "Cannot layout class with dependent bases.");
3661 if (!Base.isVirtual())
3662 Bases.push_back(Base.getType()->getAsCXXRecordDecl());
3663 }
3664
3665 // Sort nvbases by offset.
3666 llvm::stable_sort(
3667 Bases, [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
3668 return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
3669 });
3670
3671 // Dump (non-virtual) bases
3672 for (const CXXRecordDecl *Base : Bases) {
3673 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base);
3674 DumpRecordLayout(OS, Base, C, BaseOffset, IndentLevel,
3675 Base == PrimaryBase ? "(primary base)" : "(base)",
3676 /*PrintSizeInfo=*/false,
3677 /*IncludeVirtualBases=*/false);
3678 }
3679
3680 // vbptr (for Microsoft C++ ABI)
3681 if (HasOwnVBPtr) {
3682 PrintOffset(OS, Offset + Layout.getVBPtrOffset(), IndentLevel);
3683 OS << '(' << *RD << " vbtable pointer)\n";
3684 }
3685 }
3686
3687 // Dump fields.
3688 for (const FieldDecl *Field : RD->fields()) {
3689 uint64_t LocalFieldOffsetInBits =
3690 Layout.getFieldOffset(Field->getFieldIndex());
3691 CharUnits FieldOffset =
3692 Offset + C.toCharUnitsFromBits(LocalFieldOffsetInBits);
3693
3694 // Recursively dump fields of record type.
3695 if (const auto *RD = Field->getType()->getAsRecordDecl()) {
3696 DumpRecordLayout(OS, RD, C, FieldOffset, IndentLevel,
3697 Field->getName().data(),
3698 /*PrintSizeInfo=*/false,
3699 /*IncludeVirtualBases=*/true);
3700 continue;
3701 }
3702
3703 if (Field->isBitField()) {
3704 uint64_t LocalFieldByteOffsetInBits = C.toBits(FieldOffset - Offset);
3705 unsigned Begin = LocalFieldOffsetInBits - LocalFieldByteOffsetInBits;
3706 unsigned Width = Field->getBitWidthValue();
3707 PrintBitFieldOffset(OS, FieldOffset, Begin, Width, IndentLevel);
3708 } else {
3709 PrintOffset(OS, FieldOffset, IndentLevel);
3710 }
3711 const QualType &FieldType = C.getLangOpts().DumpRecordLayoutsCanonical
3712 ? Field->getType().getCanonicalType()
3713 : Field->getType();
3714 OS << FieldType << ' ' << *Field << '\n';
3715 }
3716
3717 // Dump virtual bases.
3718 if (CXXRD && IncludeVirtualBases) {
3719 const ASTRecordLayout::VBaseOffsetsMapTy &VtorDisps =
3720 Layout.getVBaseOffsetsMap();
3721
3722 for (const CXXBaseSpecifier &Base : CXXRD->vbases()) {
3723 assert(Base.isVirtual() && "Found non-virtual class!");
3724 const CXXRecordDecl *VBase = Base.getType()->getAsCXXRecordDecl();
3725
3726 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBase);
3727
3728 if (VtorDisps.find(VBase)->second.hasVtorDisp()) {
3729 PrintOffset(OS, VBaseOffset - CharUnits::fromQuantity(4), IndentLevel);
3730 OS << "(vtordisp for vbase " << *VBase << ")\n";
3731 }
3732
3733 DumpRecordLayout(OS, VBase, C, VBaseOffset, IndentLevel,
3734 VBase == Layout.getPrimaryBase() ?
3735 "(primary virtual base)" : "(virtual base)",
3736 /*PrintSizeInfo=*/false,
3737 /*IncludeVirtualBases=*/false);
3738 }
3739 }
3740
3741 if (!PrintSizeInfo) return;
3742
3743 PrintIndentNoOffset(OS, IndentLevel - 1);
3744 OS << "[sizeof=" << Layout.getSize().getQuantity();
3745 if (CXXRD && !C.getTargetInfo().hasMicrosoftRecordLayout())
3746 OS << ", dsize=" << Layout.getDataSize().getQuantity();
3747 OS << ", align=" << Layout.getAlignment().getQuantity();
3748 if (C.getTargetInfo().defaultsToAIXPowerAlignment())
3749 OS << ", preferredalign=" << Layout.getPreferredAlignment().getQuantity();
3750
3751 if (CXXRD) {
3752 OS << ",\n";
3753 PrintIndentNoOffset(OS, IndentLevel - 1);
3754 OS << " nvsize=" << Layout.getNonVirtualSize().getQuantity();
3755 OS << ", nvalign=" << Layout.getNonVirtualAlignment().getQuantity();
3756 if (C.getTargetInfo().defaultsToAIXPowerAlignment())
3757 OS << ", preferrednvalign="
3759 }
3760 OS << "]\n";
3761}
3762
3763void ASTContext::DumpRecordLayout(const RecordDecl *RD, raw_ostream &OS,
3764 bool Simple) const {
3765 if (!Simple) {
3766 ::DumpRecordLayout(OS, RD, *this, CharUnits(), 0, nullptr,
3767 /*PrintSizeInfo*/ true,
3768 /*IncludeVirtualBases=*/true);
3769 return;
3770 }
3771
3772 // The "simple" format is designed to be parsed by the
3773 // layout-override testing code. There shouldn't be any external
3774 // uses of this format --- when LLDB overrides a layout, it sets up
3775 // the data structures directly --- so feel free to adjust this as
3776 // you like as long as you also update the rudimentary parser for it
3777 // in libFrontend.
3778
3779 const ASTRecordLayout &Info = getASTRecordLayout(RD);
3780 OS << "Type: " << getCanonicalTagType(RD) << "\n";
3781 OS << "\nLayout: ";
3782 OS << "<ASTRecordLayout\n";
3783 OS << " Size:" << toBits(Info.getSize()) << "\n";
3784 if (!getTargetInfo().hasMicrosoftRecordLayout())
3785 OS << " DataSize:" << toBits(Info.getDataSize()) << "\n";
3786 OS << " Alignment:" << toBits(Info.getAlignment()) << "\n";
3787 if (Target->defaultsToAIXPowerAlignment())
3788 OS << " PreferredAlignment:" << toBits(Info.getPreferredAlignment())
3789 << "\n";
3790 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3791 OS << " BaseOffsets: [";
3792 const CXXRecordDecl *Base = nullptr;
3793 for (auto I : CXXRD->bases()) {
3794 if (I.isVirtual())
3795 continue;
3796 if (Base)
3797 OS << ", ";
3798 Base = I.getType()->getAsCXXRecordDecl();
3799 OS << Info.CXXInfo->BaseOffsets[Base].getQuantity();
3800 }
3801 OS << "]>\n";
3802 OS << " VBaseOffsets: [";
3803 const CXXRecordDecl *VBase = nullptr;
3804 for (auto I : CXXRD->vbases()) {
3805 if (VBase)
3806 OS << ", ";
3807 VBase = I.getType()->getAsCXXRecordDecl();
3808 OS << Info.CXXInfo->VBaseOffsets[VBase].VBaseOffset.getQuantity();
3809 }
3810 OS << "]>\n";
3811 }
3812 OS << " FieldOffsets: [";
3813 for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i) {
3814 if (i)
3815 OS << ", ";
3816 OS << Info.getFieldOffset(i);
3817 }
3818 OS << "]>\n";
3819}
Defines the clang::ASTContext interface.
const Decl * D
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
static unsigned getCharWidth(tok::TokenKind kind, const TargetInfo &Target)
llvm::MachO::Target Target
Definition: MachO.h:51
static const CXXMethodDecl * computeKeyFunction(ASTContext &Context, const CXXRecordDecl *RD)
static bool mustSkipTailPadding(TargetCXXABI ABI, const CXXRecordDecl *RD)
Does the target C++ ABI require us to skip over the tail-padding of the given class (considering it a...
static bool isAIXLayout(const ASTContext &Context)
static void PrintIndentNoOffset(raw_ostream &OS, unsigned IndentLevel)
static uint64_t roundUpSizeToCharAlignment(uint64_t Size, const ASTContext &Context)
static void PrintOffset(raw_ostream &OS, CharUnits Offset, unsigned IndentLevel)
static unsigned getPaddingDiagFromTagKind(TagTypeKind Tag)
Get diagnostic select index for tag kind for field padding diagnostic message.
static void DumpRecordLayout(raw_ostream &OS, const RecordDecl *RD, const ASTContext &C, CharUnits Offset, unsigned IndentLevel, const char *Description, bool PrintSizeInfo, bool IncludeVirtualBases)
static void CheckFieldPadding(const ASTContext &Context, bool IsUnion, uint64_t Offset, uint64_t UnpaddedOffset, const FieldDecl *D)
static uint64_t getFieldOffset(const ASTContext &C, const FieldDecl *FD)
static bool RequiresVtordisp(const llvm::SmallPtrSetImpl< const CXXRecordDecl * > &BasesWithOverriddenMethods, const CXXRecordDecl *RD)
static void PrintBitFieldOffset(raw_ostream &OS, CharUnits Offset, unsigned Begin, unsigned Width, unsigned IndentLevel)
static bool recordUsesEBO(const RecordDecl *RD)
SourceLocation Loc
Definition: SemaObjC.cpp:754
SourceLocation Begin
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:3056
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
uint64_t getFieldOffset(const ValueDecl *FD) const
Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
void DumpRecordLayout(const RecordDecl *RD, raw_ostream &OS, bool Simple=false) const
const CXXMethodDecl * getCurrentKeyFunction(const CXXRecordDecl *RD)
Get our current best idea for the key function of the given record decl, or nullptr if there isn't on...
const LangOptions & getLangOpts() const
Definition: ASTContext.h:894
uint64_t lookupFieldBitOffset(const ObjCInterfaceDecl *OID, const ObjCIvarDecl *Ivar) const
Get the offset of an ObjCIvarDecl in bits.
const ASTRecordLayout & getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const
Get or compute information about the layout of the specified Objective-C interface.
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
bool isNearlyEmpty(const CXXRecordDecl *RD) const
CanQualType UnsignedLongTy
Definition: ASTContext.h:1232
TypeInfo getTypeInfo(const Type *T) const
Get the size and alignment of the specified complete type in bits.
bool isAlignmentRequired(const Type *T) const
Determine if the alignment the type has was required using an alignment attribute.
void setNonKeyFunction(const CXXMethodDecl *method)
Observe that the given method cannot be a key function.
TypeInfoChars getTypeInfoInChars(const Type *T) const
int64_t toBits(CharUnits CharSize) const
Convert a size in characters to a size in bits.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2625
CanQualType UnsignedInt128Ty
Definition: ASTContext.h:1233
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType UnsignedCharTy
Definition: ASTContext.h:1232
CanQualType UnsignedIntTy
Definition: ASTContext.h:1232
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1233
CanQualType UnsignedShortTy
Definition: ASTContext.h:1232
DiagnosticsEngine & getDiagnostics() const
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:859
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
Definition: ASTContext.h:1339
uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const
Return number of constant array elements.
CanQualType getCanonicalTagType(const TagDecl *TD) const
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2629
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
Definition: RecordLayout.h:38
bool endsWithZeroSizedObject() const
Definition: RecordLayout.h:314
bool hasOwnVFPtr() const
hasOwnVFPtr - Does this class provide its own virtual-function table pointer, rather than inheriting ...
Definition: RecordLayout.h:281
CharUnits getAlignment() const
getAlignment - Get the record alignment in characters.
Definition: RecordLayout.h:183
CharUnits getPreferredAlignment() const
getPreferredFieldAlignment - Get the record preferred alignment in characters.
Definition: RecordLayout.h:187
bool hasOwnVBPtr() const
hasOwnVBPtr - Does this class provide its own virtual-base table pointer, rather than inheriting one ...
Definition: RecordLayout.h:301
llvm::DenseMap< const CXXRecordDecl *, VBaseInfo > VBaseOffsetsMapTy
Definition: RecordLayout.h:59
CharUnits getSize() const
getSize - Get the record size in characters.
Definition: RecordLayout.h:194
unsigned getFieldCount() const
getFieldCount - Get the number of fields in the layout.
Definition: RecordLayout.h:197
bool hasVBPtr() const
hasVBPtr - Does this class have a virtual function table pointer.
Definition: RecordLayout.h:307
bool leadsWithZeroSizedBase() const
Definition: RecordLayout.h:318
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
Definition: RecordLayout.h:201
CharUnits getNonVirtualAlignment() const
getNonVirtualAlignment - Get the non-virtual alignment (in chars) of an object, which is the alignmen...
Definition: RecordLayout.h:219
CharUnits getVBPtrOffset() const
getVBPtrOffset - Get the offset for virtual base table pointer.
Definition: RecordLayout.h:325
CharUnits getDataSize() const
getDataSize() - Get the record data size, which is the record size without tail padding,...
Definition: RecordLayout.h:207
CharUnits getRequiredAlignment() const
Definition: RecordLayout.h:312
CharUnits getSizeOfLargestEmptySubobject() const
Definition: RecordLayout.h:269
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:250
CharUnits getPreferredNVAlignment() const
getPreferredNVAlignment - Get the preferred non-virtual alignment (in chars) of an object,...
Definition: RecordLayout.h:228
CharUnits getVBaseClassOffset(const CXXRecordDecl *VBase) const
getVBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:260
const VBaseOffsetsMapTy & getVBaseOffsetsMap() const
Definition: RecordLayout.h:335
const CXXRecordDecl * getPrimaryBase() const
getPrimaryBase - Get the primary base for this record.
Definition: RecordLayout.h:235
bool hasExtendableVFPtr() const
hasVFPtr - Does this class have a virtual function table pointer that can be extended by a derived cl...
Definition: RecordLayout.h:289
bool isPrimaryBaseVirtual() const
isPrimaryBaseVirtual - Get whether the primary base for this record is virtual or not.
Definition: RecordLayout.h:243
CharUnits getNonVirtualSize() const
getNonVirtualSize - Get the non-virtual size (in chars) of an object, which is the size of the object...
Definition: RecordLayout.h:211
This class is used for builtin types like 'int'.
Definition: TypeBase.h:3182
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
A set of all the primary bases for a class.
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2129
overridden_method_range overridden_methods() const
Definition: DeclCXX.cpp:2778
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2255
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
void getIndirectPrimaryBases(CXXIndirectPrimaryBaseSet &Bases) const
Get the indirect primary bases for this class.
bool hasUserDeclaredDestructor() const
Determine whether this class has a user-declared destructor.
Definition: DeclCXX.h:1001
base_class_range bases()
Definition: DeclCXX.h:608
method_range methods() const
Definition: DeclCXX.h:650
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:548
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition: DeclCXX.h:1214
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition: DeclCXX.cpp:2050
base_class_range vbases()
Definition: DeclCXX.h:625
bool isDynamicClass() const
Definition: DeclCXX.h:574
bool isCXX11StandardLayout() const
Determine whether this class was standard-layout per C++11 [class]p7, specifically using the C++11 ru...
Definition: DeclCXX.h:1229
bool hasUserDeclaredConstructor() const
Determine whether this class has any user-declared constructors.
Definition: DeclCXX.h:780
bool isPOD() const
Whether this class is a POD-type (C++ [class]p4)
Definition: DeclCXX.h:1171
MSVtorDispMode getMSVtorDispMode() const
Controls when vtordisps will be emitted if this record is used as a virtual base.
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition: DeclCXX.h:1186
bool isTrivial() const
Determine whether this class is considered trivial.
Definition: DeclCXX.h:1436
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition: DeclCXX.h:623
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:122
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
static CharUnits One()
One - Construct a CharUnits quantity of one.
Definition: CharUnits.h:58
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition: CharUnits.h:63
CharUnits alignTo(const CharUnits &Align) const
alignTo - Returns the next integer (mod 2**64) that is greater than or equal to this quantity and is ...
Definition: CharUnits.h:201
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition: CharUnits.h:53
Complex values, per C99 6.2.5p11.
Definition: TypeBase.h:3293
Represents the canonical version of C arrays with a specified constant size.
Definition: TypeBase.h:3776
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1879
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
Decl * getMostRecentDecl()
Retrieve the most recent declaration that declares the same entity as this declaration (which may be ...
Definition: DeclBase.h:1076
T * getAttr() const
Definition: DeclBase.h:573
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
Definition: DeclBase.cpp:538
bool isInvalidDecl() const
Definition: DeclBase.h:588
SourceLocation getLocation() const
Definition: DeclBase.h:439
bool hasAttr() const
Definition: DeclBase.h:577
A little helper class used to produce diagnostics.
Definition: Diagnostic.h:1233
A little helper class (which is basically a smart pointer that forwards info from DiagnosticsEngine a...
Definition: Diagnostic.h:1548
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1529
Abstract interface for external sources of AST nodes.
virtual void CompleteType(TagDecl *Tag)
Gives the external AST source an opportunity to complete an incomplete type.
Represents a member of a struct/union/class.
Definition: Decl.h:3153
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3256
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition: Decl.cpp:4689
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition: Decl.h:3238
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3389
bool isPotentiallyOverlapping() const
Determine if this field is of potentially-overlapping class type, that is, subobject with the [[no_un...
Definition: Decl.cpp:4741
Represents a function declaration or definition.
Definition: Decl.h:1999
bool isInlineSpecified() const
Determine whether the "inline" keyword was specified for this function.
Definition: Decl.h:2892
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3460
ArrayRef< NamedDecl * > chain() const
Definition: Decl.h:3481
This represents a decl that may have a name.
Definition: Decl.h:273
bool isExternallyVisible() const
Definition: Decl.h:432
Represents an ObjC class declaration.
Definition: DeclObjC.h:1154
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1952
ObjCInterfaceDecl * getContainingInterface()
Return the class interface that this ivar is logically contained in; this is either the interface whe...
Definition: DeclObjC.cpp:1872
ObjCIvarDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition: DeclObjC.h:1991
A (possibly-)qualified type.
Definition: TypeBase.h:937
Represents a struct/union/class.
Definition: Decl.h:4305
bool isMsStruct(const ASTContext &C) const
Get whether or not this is an ms_struct which can be turned on with an attribute, pragma,...
Definition: Decl.cpp:5183
field_range fields() const
Definition: Decl.h:4508
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: TypeBase.h:6502
Encodes a location in the source.
bool isUnion() const
Definition: Decl.h:3915
The basic abstraction for the target C++ ABI.
Definition: TargetCXXABI.h:28
TailPaddingUseRules getTailPaddingUseRules() const
Definition: TargetCXXABI.h:280
bool canKeyFunctionBeInline() const
Can an out-of-line inline function serve as a key function?
Definition: TargetCXXABI.h:238
@ AlwaysUseTailPadding
The tail-padding of a base class is always theoretically available, even if it's POD.
Definition: TargetCXXABI.h:270
@ UseTailPaddingUnlessPOD11
Only allocate objects in the tail padding of a base class if the base class is not POD according to t...
Definition: TargetCXXABI.h:278
@ UseTailPaddingUnlessPOD03
Only allocate objects in the tail padding of a base class if the base class is not POD according to t...
Definition: TargetCXXABI.h:274
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1288
bool useLeadingZeroLengthBitfield() const
Check whether zero length bitfield alignment is respected if they are leading members.
Definition: TargetInfo.h:954
uint64_t getPointerWidth(LangAS AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition: TargetInfo.h:486
virtual bool hasPS4DLLImportExport() const
Definition: TargetInfo.h:1332
unsigned getLargestOverSizedBitfieldContainer() const
Definition: TargetInfo.h:964
virtual bool defaultsToAIXPowerAlignment() const
Whether target defaults to the power alignment rules of AIX.
Definition: TargetInfo.h:1790
unsigned getCharAlign() const
Definition: TargetInfo.h:518
unsigned getZeroLengthBitfieldBoundary() const
Get the fixed alignment value in bits for a member that follows a zero length bitfield.
Definition: TargetInfo.h:960
bool useExplicitBitFieldAlignment() const
Check whether explicit bitfield alignment attributes should be.
Definition: TargetInfo.h:974
uint64_t getPointerAlign(LangAS AddrSpace) const
Definition: TargetInfo.h:490
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1360
unsigned getCharWidth() const
Definition: TargetInfo.h:517
bool useZeroLengthBitfieldAlignment() const
Check whether zero length bitfields should force alignment of the next member.
Definition: TargetInfo.h:948
bool useBitFieldTypeAlignment() const
Check whether the alignment of bit-field types is respected when laying out structures.
Definition: TargetInfo.h:942
The base class of the type hierarchy.
Definition: TypeBase.h:1833
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.h:26
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: TypeBase.h:9109
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition: TypeBase.h:2939
const T * getAs() const
Member-template getAs<specific type>'.
Definition: TypeBase.h:9159
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition: Type.cpp:653
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:711
QualType getType() const
Definition: Decl.h:722
Defines the clang::TargetInfo interface.
The JSON file list parser is used to communicate input to InstallAPI.
@ External
External linkage, which indicates that the entity can be referred to from other translation units.
@ Result
The result type of a method or function.
TagTypeKind
The kind of a tag type.
Definition: TypeBase.h:5906
@ Interface
The "__interface" keyword.
@ Struct
The "struct" keyword.
@ Class
The "class" keyword.
const FunctionProtoType * T
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:188
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition: Specifiers.h:206
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:202
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:194
AlignRequirementKind
Definition: ASTContext.h:144
@ None
The alignment was not explicit in code.
@ RequiredByTypedef
The alignment comes from an alignment attribute on a typedef.
@ RequiredByRecord
The alignment comes from an alignment attribute on a record type.
@ Class
The "class" keyword introduces the elaborated-type-specifier.
unsigned long uint64_t
#define false
Definition: stdbool.h:26
bool isValid() const
Whether this pointer is non-NULL.
bool isOffset() const
Whether this pointer is currently stored as an offset.
T * get(ExternalASTSource *Source) const
Retrieve the pointer to the AST node that this lazy pointer points to.
bool isAlignRequired()
Definition: ASTContext.h:167
uint64_t Width
Definition: ASTContext.h:159
unsigned Align
Definition: ASTContext.h:160
All virtual base related information about a given record decl.