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