Bug Summary

File:clang/lib/AST/RecordLayoutBuilder.cpp
Warning:line 1181, column 10
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name RecordLayoutBuilder.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/build-llvm/tools/clang/lib/AST -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D CLANG_ROUND_TRIP_CC1_ARGS=ON -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/build-llvm/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/build-llvm/include -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/include -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/build-llvm/tools/clang/lib/AST -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-08-28-193554-24367-1 -x c++ /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp
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
9#include "clang/AST/ASTContext.h"
10#include "clang/AST/ASTDiagnostic.h"
11#include "clang/AST/Attr.h"
12#include "clang/AST/CXXInheritance.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"
17#include "clang/AST/VTableBuilder.h"
18#include "clang/AST/RecordLayout.h"
19#include "clang/Basic/TargetInfo.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.
47 SmallVector<BaseSubobjectInfo*, 4> Bases;
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() : Size(0), Align(0) {}
62
63 /// Overall record size in bits.
64 uint64_t Size;
65
66 /// Overall record alignment in bits.
67 uint64_t Align;
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) &&(static_cast <bool> (FieldOffsets.count(FD) && "Field does not have an external offset"
) ? void (0) : __assert_fail ("FieldOffsets.count(FD) && \"Field does not have an external offset\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 82, __extension__ __PRETTY_FUNCTION__))
82 "Field does not have an external offset")(static_cast <bool> (FieldOffsets.count(FD) && "Field does not have an external offset"
) ? void (0) : __assert_fail ("FieldOffsets.count(FD) && \"Field does not have an external offset\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 82, __extension__ __PRETTY_FUNCTION__))
;
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
142 CharUnits
143 getFieldOffset(const ASTRecordLayout &Layout, unsigned FieldNo) const {
144 uint64_t FieldOffset = Layout.getFieldOffset(FieldNo);
145 assert(FieldOffset % CharWidth == 0 &&(static_cast <bool> (FieldOffset % CharWidth == 0 &&
"Field offset not at char boundary!") ? void (0) : __assert_fail
("FieldOffset % CharWidth == 0 && \"Field offset not at char boundary!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 146, __extension__ __PRETTY_FUNCTION__))
146 "Field offset not at char boundary!")(static_cast <bool> (FieldOffset % CharWidth == 0 &&
"Field offset not at char boundary!") ? void (0) : __assert_fail
("FieldOffset % CharWidth == 0 && \"Field offset not at char boundary!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 146, __extension__ __PRETTY_FUNCTION__))
;
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::find(Classes, RD) == Classes.end())
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
575typedef llvm::SmallPtrSet<const CXXRecordDecl*, 4> ClassSetTy;
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.
587 uint64_t Size;
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 unsigned UseExternalLayout : 1;
606
607 /// Whether we need to infer alignment, even when we have an
608 /// externally-provided layout.
609 unsigned InferAlignment : 1;
610
611 /// Packed - Whether the record is packed or not.
612 unsigned Packed : 1;
613
614 unsigned IsUnion : 1;
615
616 unsigned IsMac68kAlign : 1;
617
618 unsigned IsNaturalAlign : 1;
619
620 unsigned IsMsStruct : 1;
621
622 /// UnfilledBitsInLastUnit - If the last field laid out was a bitfield,
623 /// this contains the number of bits in the last unit that can be used for
624 /// an adjacent bitfield if necessary. The unit in question is usually
625 /// a byte, but larger units are used if IsMsStruct.
626 unsigned char UnfilledBitsInLastUnit;
627
628 /// LastBitfieldStorageUnitSize - If IsMsStruct, represents the size of the
629 /// storage unit of the previous field if it was a bitfield.
630 unsigned char LastBitfieldStorageUnitSize;
631
632 /// MaxFieldAlignment - The maximum allowed field alignment. This is set by
633 /// #pragma pack.
634 CharUnits MaxFieldAlignment;
635
636 /// DataSize - The data size of the record being laid out.
637 uint64_t DataSize;
638
639 CharUnits NonVirtualSize;
640 CharUnits NonVirtualAlignment;
641 CharUnits PreferredNVAlignment;
642
643 /// If we've laid out a field but not included its tail padding in Size yet,
644 /// this is the size up to the end of that field.
645 CharUnits PaddedFieldSize;
646
647 /// PrimaryBase - the primary base class (if one exists) of the class
648 /// we're laying out.
649 const CXXRecordDecl *PrimaryBase;
650
651 /// PrimaryBaseIsVirtual - Whether the primary base of the class we're laying
652 /// out is virtual.
653 bool PrimaryBaseIsVirtual;
654
655 /// HasOwnVFPtr - Whether the class provides its own vtable/vftbl
656 /// pointer, as opposed to inheriting one from a primary base class.
657 bool HasOwnVFPtr;
658
659 /// the flag of field offset changing due to packed attribute.
660 bool HasPackedField;
661
662 /// HandledFirstNonOverlappingEmptyField - An auxiliary field used for AIX.
663 /// When there are OverlappingEmptyFields existing in the aggregate, the
664 /// flag shows if the following first non-empty or empty-but-non-overlapping
665 /// field has been handled, if any.
666 bool HandledFirstNonOverlappingEmptyField;
667
668 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy;
669
670 /// Bases - base classes and their offsets in the record.
671 BaseOffsetsMapTy Bases;
672
673 // VBases - virtual base classes and their offsets in the record.
674 ASTRecordLayout::VBaseOffsetsMapTy VBases;
675
676 /// IndirectPrimaryBases - Virtual base classes, direct or indirect, that are
677 /// primary base classes for some other direct or indirect base class.
678 CXXIndirectPrimaryBaseSet IndirectPrimaryBases;
679
680 /// FirstNearlyEmptyVBase - The first nearly empty virtual base class in
681 /// inheritance graph order. Used for determining the primary base class.
682 const CXXRecordDecl *FirstNearlyEmptyVBase;
683
684 /// VisitedVirtualBases - A set of all the visited virtual bases, used to
685 /// avoid visiting virtual bases more than once.
686 llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
687
688 /// Valid if UseExternalLayout is true.
689 ExternalLayout External;
690
691 ItaniumRecordLayoutBuilder(const ASTContext &Context,
692 EmptySubobjectMap *EmptySubobjects)
693 : Context(Context), EmptySubobjects(EmptySubobjects), Size(0),
694 Alignment(CharUnits::One()), PreferredAlignment(CharUnits::One()),
695 UnpackedAlignment(CharUnits::One()),
696 UnadjustedAlignment(CharUnits::One()), UseExternalLayout(false),
697 InferAlignment(false), Packed(false), IsUnion(false),
698 IsMac68kAlign(false),
699 IsNaturalAlign(!Context.getTargetInfo().getTriple().isOSAIX()),
700 IsMsStruct(false), UnfilledBitsInLastUnit(0),
701 LastBitfieldStorageUnitSize(0), MaxFieldAlignment(CharUnits::Zero()),
702 DataSize(0), NonVirtualSize(CharUnits::Zero()),
703 NonVirtualAlignment(CharUnits::One()),
704 PreferredNVAlignment(CharUnits::One()),
705 PaddedFieldSize(CharUnits::Zero()), PrimaryBase(nullptr),
706 PrimaryBaseIsVirtual(false), HasOwnVFPtr(false), HasPackedField(false),
707 HandledFirstNonOverlappingEmptyField(false),
708 FirstNearlyEmptyVBase(nullptr) {}
709
710 void Layout(const RecordDecl *D);
711 void Layout(const CXXRecordDecl *D);
712 void Layout(const ObjCInterfaceDecl *D);
713
714 void LayoutFields(const RecordDecl *D);
715 void LayoutField(const FieldDecl *D, bool InsertExtraPadding);
716 void LayoutWideBitField(uint64_t FieldSize, uint64_t StorageUnitSize,
717 bool FieldPacked, const FieldDecl *D);
718 void LayoutBitField(const FieldDecl *D);
719
720 TargetCXXABI getCXXABI() const {
721 return Context.getTargetInfo().getCXXABI();
722 }
723
724 /// BaseSubobjectInfoAllocator - Allocator for BaseSubobjectInfo objects.
725 llvm::SpecificBumpPtrAllocator<BaseSubobjectInfo> BaseSubobjectInfoAllocator;
726
727 typedef llvm::DenseMap<const CXXRecordDecl *, BaseSubobjectInfo *>
728 BaseSubobjectInfoMapTy;
729
730 /// VirtualBaseInfo - Map from all the (direct or indirect) virtual bases
731 /// of the class we're laying out to their base subobject info.
732 BaseSubobjectInfoMapTy VirtualBaseInfo;
733
734 /// NonVirtualBaseInfo - Map from all the direct non-virtual bases of the
735 /// class we're laying out to their base subobject info.
736 BaseSubobjectInfoMapTy NonVirtualBaseInfo;
737
738 /// ComputeBaseSubobjectInfo - Compute the base subobject information for the
739 /// bases of the given class.
740 void ComputeBaseSubobjectInfo(const CXXRecordDecl *RD);
741
742 /// ComputeBaseSubobjectInfo - Compute the base subobject information for a
743 /// single class and all of its base classes.
744 BaseSubobjectInfo *ComputeBaseSubobjectInfo(const CXXRecordDecl *RD,
745 bool IsVirtual,
746 BaseSubobjectInfo *Derived);
747
748 /// DeterminePrimaryBase - Determine the primary base of the given class.
749 void DeterminePrimaryBase(const CXXRecordDecl *RD);
750
751 void SelectPrimaryVBase(const CXXRecordDecl *RD);
752
753 void EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign);
754
755 /// LayoutNonVirtualBases - Determines the primary base class (if any) and
756 /// lays it out. Will then proceed to lay out all non-virtual base clasess.
757 void LayoutNonVirtualBases(const CXXRecordDecl *RD);
758
759 /// LayoutNonVirtualBase - Lays out a single non-virtual base.
760 void LayoutNonVirtualBase(const BaseSubobjectInfo *Base);
761
762 void AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info,
763 CharUnits Offset);
764
765 /// LayoutVirtualBases - Lays out all the virtual bases.
766 void LayoutVirtualBases(const CXXRecordDecl *RD,
767 const CXXRecordDecl *MostDerivedClass);
768
769 /// LayoutVirtualBase - Lays out a single virtual base.
770 void LayoutVirtualBase(const BaseSubobjectInfo *Base);
771
772 /// LayoutBase - Will lay out a base and return the offset where it was
773 /// placed, in chars.
774 CharUnits LayoutBase(const BaseSubobjectInfo *Base);
775
776 /// InitializeLayout - Initialize record layout for the given record decl.
777 void InitializeLayout(const Decl *D);
778
779 /// FinishLayout - Finalize record layout. Adjust record size based on the
780 /// alignment.
781 void FinishLayout(const NamedDecl *D);
782
783 void UpdateAlignment(CharUnits NewAlignment, CharUnits UnpackedNewAlignment,
784 CharUnits PreferredAlignment);
785 void UpdateAlignment(CharUnits NewAlignment, CharUnits UnpackedNewAlignment) {
786 UpdateAlignment(NewAlignment, UnpackedNewAlignment, NewAlignment);
787 }
788 void UpdateAlignment(CharUnits NewAlignment) {
789 UpdateAlignment(NewAlignment, NewAlignment, NewAlignment);
790 }
791
792 /// Retrieve the externally-supplied field offset for the given
793 /// field.
794 ///
795 /// \param Field The field whose offset is being queried.
796 /// \param ComputedOffset The offset that we've computed for this field.
797 uint64_t updateExternalFieldOffset(const FieldDecl *Field,
798 uint64_t ComputedOffset);
799
800 void CheckFieldPadding(uint64_t Offset, uint64_t UnpaddedOffset,
801 uint64_t UnpackedOffset, unsigned UnpackedAlign,
802 bool isPacked, const FieldDecl *D);
803
804 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
805
806 CharUnits getSize() const {
807 assert(Size % Context.getCharWidth() == 0)(static_cast <bool> (Size % Context.getCharWidth() == 0
) ? void (0) : __assert_fail ("Size % Context.getCharWidth() == 0"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 807, __extension__ __PRETTY_FUNCTION__))
;
808 return Context.toCharUnitsFromBits(Size);
809 }
810 uint64_t getSizeInBits() const { return Size; }
811
812 void setSize(CharUnits NewSize) { Size = Context.toBits(NewSize); }
813 void setSize(uint64_t NewSize) { Size = NewSize; }
814
815 CharUnits getAligment() const { return Alignment; }
816
817 CharUnits getDataSize() const {
818 assert(DataSize % Context.getCharWidth() == 0)(static_cast <bool> (DataSize % Context.getCharWidth() ==
0) ? void (0) : __assert_fail ("DataSize % Context.getCharWidth() == 0"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 818, __extension__ __PRETTY_FUNCTION__))
;
819 return Context.toCharUnitsFromBits(DataSize);
820 }
821 uint64_t getDataSizeInBits() const { return DataSize; }
822
823 void setDataSize(CharUnits NewSize) { DataSize = Context.toBits(NewSize); }
824 void setDataSize(uint64_t NewSize) { DataSize = NewSize; }
825
826 ItaniumRecordLayoutBuilder(const ItaniumRecordLayoutBuilder &) = delete;
827 void operator=(const ItaniumRecordLayoutBuilder &) = delete;
828};
829} // end anonymous namespace
830
831void ItaniumRecordLayoutBuilder::SelectPrimaryVBase(const CXXRecordDecl *RD) {
832 for (const auto &I : RD->bases()) {
833 assert(!I.getType()->isDependentType() &&(static_cast <bool> (!I.getType()->isDependentType()
&& "Cannot layout class with dependent bases.") ? void
(0) : __assert_fail ("!I.getType()->isDependentType() && \"Cannot layout class with dependent bases.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 834, __extension__ __PRETTY_FUNCTION__))
834 "Cannot layout class with dependent bases.")(static_cast <bool> (!I.getType()->isDependentType()
&& "Cannot layout class with dependent bases.") ? void
(0) : __assert_fail ("!I.getType()->isDependentType() && \"Cannot layout class with dependent bases.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 834, __extension__ __PRETTY_FUNCTION__))
;
835
836 const CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
837
838 // Check if this is a nearly empty virtual base.
839 if (I.isVirtual() && Context.isNearlyEmpty(Base)) {
840 // If it's not an indirect primary base, then we've found our primary
841 // base.
842 if (!IndirectPrimaryBases.count(Base)) {
843 PrimaryBase = Base;
844 PrimaryBaseIsVirtual = true;
845 return;
846 }
847
848 // Is this the first nearly empty virtual base?
849 if (!FirstNearlyEmptyVBase)
850 FirstNearlyEmptyVBase = Base;
851 }
852
853 SelectPrimaryVBase(Base);
854 if (PrimaryBase)
855 return;
856 }
857}
858
859/// DeterminePrimaryBase - Determine the primary base of the given class.
860void ItaniumRecordLayoutBuilder::DeterminePrimaryBase(const CXXRecordDecl *RD) {
861 // If the class isn't dynamic, it won't have a primary base.
862 if (!RD->isDynamicClass())
863 return;
864
865 // Compute all the primary virtual bases for all of our direct and
866 // indirect bases, and record all their primary virtual base classes.
867 RD->getIndirectPrimaryBases(IndirectPrimaryBases);
868
869 // If the record has a dynamic base class, attempt to choose a primary base
870 // class. It is the first (in direct base class order) non-virtual dynamic
871 // base class, if one exists.
872 for (const auto &I : RD->bases()) {
873 // Ignore virtual bases.
874 if (I.isVirtual())
875 continue;
876
877 const CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
878
879 if (Base->isDynamicClass()) {
880 // We found it.
881 PrimaryBase = Base;
882 PrimaryBaseIsVirtual = false;
883 return;
884 }
885 }
886
887 // Under the Itanium ABI, if there is no non-virtual primary base class,
888 // try to compute the primary virtual base. The primary virtual base is
889 // the first nearly empty virtual base that is not an indirect primary
890 // virtual base class, if one exists.
891 if (RD->getNumVBases() != 0) {
892 SelectPrimaryVBase(RD);
893 if (PrimaryBase)
894 return;
895 }
896
897 // Otherwise, it is the first indirect primary base class, if one exists.
898 if (FirstNearlyEmptyVBase) {
899 PrimaryBase = FirstNearlyEmptyVBase;
900 PrimaryBaseIsVirtual = true;
901 return;
902 }
903
904 assert(!PrimaryBase && "Should not get here with a primary base!")(static_cast <bool> (!PrimaryBase && "Should not get here with a primary base!"
) ? void (0) : __assert_fail ("!PrimaryBase && \"Should not get here with a primary base!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 904, __extension__ __PRETTY_FUNCTION__))
;
905}
906
907BaseSubobjectInfo *ItaniumRecordLayoutBuilder::ComputeBaseSubobjectInfo(
908 const CXXRecordDecl *RD, bool IsVirtual, BaseSubobjectInfo *Derived) {
909 BaseSubobjectInfo *Info;
910
911 if (IsVirtual) {
912 // Check if we already have info about this virtual base.
913 BaseSubobjectInfo *&InfoSlot = VirtualBaseInfo[RD];
914 if (InfoSlot) {
915 assert(InfoSlot->Class == RD && "Wrong class for virtual base info!")(static_cast <bool> (InfoSlot->Class == RD &&
"Wrong class for virtual base info!") ? void (0) : __assert_fail
("InfoSlot->Class == RD && \"Wrong class for virtual base info!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 915, __extension__ __PRETTY_FUNCTION__))
;
916 return InfoSlot;
917 }
918
919 // We don't, create it.
920 InfoSlot = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
921 Info = InfoSlot;
922 } else {
923 Info = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
924 }
925
926 Info->Class = RD;
927 Info->IsVirtual = IsVirtual;
928 Info->Derived = nullptr;
929 Info->PrimaryVirtualBaseInfo = nullptr;
930
931 const CXXRecordDecl *PrimaryVirtualBase = nullptr;
932 BaseSubobjectInfo *PrimaryVirtualBaseInfo = nullptr;
933
934 // Check if this base has a primary virtual base.
935 if (RD->getNumVBases()) {
936 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
937 if (Layout.isPrimaryBaseVirtual()) {
938 // This base does have a primary virtual base.
939 PrimaryVirtualBase = Layout.getPrimaryBase();
940 assert(PrimaryVirtualBase && "Didn't have a primary virtual base!")(static_cast <bool> (PrimaryVirtualBase && "Didn't have a primary virtual base!"
) ? void (0) : __assert_fail ("PrimaryVirtualBase && \"Didn't have a primary virtual base!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 940, __extension__ __PRETTY_FUNCTION__))
;
941
942 // Now check if we have base subobject info about this primary base.
943 PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
944
945 if (PrimaryVirtualBaseInfo) {
946 if (PrimaryVirtualBaseInfo->Derived) {
947 // We did have info about this primary base, and it turns out that it
948 // has already been claimed as a primary virtual base for another
949 // base.
950 PrimaryVirtualBase = nullptr;
951 } else {
952 // We can claim this base as our primary base.
953 Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
954 PrimaryVirtualBaseInfo->Derived = Info;
955 }
956 }
957 }
958 }
959
960 // Now go through all direct bases.
961 for (const auto &I : RD->bases()) {
962 bool IsVirtual = I.isVirtual();
963
964 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
965
966 Info->Bases.push_back(ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, Info));
967 }
968
969 if (PrimaryVirtualBase && !PrimaryVirtualBaseInfo) {
970 // Traversing the bases must have created the base info for our primary
971 // virtual base.
972 PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
973 assert(PrimaryVirtualBaseInfo &&(static_cast <bool> (PrimaryVirtualBaseInfo && "Did not create a primary virtual base!"
) ? void (0) : __assert_fail ("PrimaryVirtualBaseInfo && \"Did not create a primary virtual base!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 974, __extension__ __PRETTY_FUNCTION__))
974 "Did not create a primary virtual base!")(static_cast <bool> (PrimaryVirtualBaseInfo && "Did not create a primary virtual base!"
) ? void (0) : __assert_fail ("PrimaryVirtualBaseInfo && \"Did not create a primary virtual base!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 974, __extension__ __PRETTY_FUNCTION__))
;
975
976 // Claim the primary virtual base as our primary virtual base.
977 Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
978 PrimaryVirtualBaseInfo->Derived = Info;
979 }
980
981 return Info;
982}
983
984void ItaniumRecordLayoutBuilder::ComputeBaseSubobjectInfo(
985 const CXXRecordDecl *RD) {
986 for (const auto &I : RD->bases()) {
987 bool IsVirtual = I.isVirtual();
988
989 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
990
991 // Compute the base subobject info for this base.
992 BaseSubobjectInfo *Info = ComputeBaseSubobjectInfo(BaseDecl, IsVirtual,
993 nullptr);
994
995 if (IsVirtual) {
996 // ComputeBaseInfo has already added this base for us.
997 assert(VirtualBaseInfo.count(BaseDecl) &&(static_cast <bool> (VirtualBaseInfo.count(BaseDecl) &&
"Did not add virtual base!") ? void (0) : __assert_fail ("VirtualBaseInfo.count(BaseDecl) && \"Did not add virtual base!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 998, __extension__ __PRETTY_FUNCTION__))
998 "Did not add virtual base!")(static_cast <bool> (VirtualBaseInfo.count(BaseDecl) &&
"Did not add virtual base!") ? void (0) : __assert_fail ("VirtualBaseInfo.count(BaseDecl) && \"Did not add virtual base!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 998, __extension__ __PRETTY_FUNCTION__))
;
999 } else {
1000 // Add the base info to the map of non-virtual bases.
1001 assert(!NonVirtualBaseInfo.count(BaseDecl) &&(static_cast <bool> (!NonVirtualBaseInfo.count(BaseDecl
) && "Non-virtual base already exists!") ? void (0) :
__assert_fail ("!NonVirtualBaseInfo.count(BaseDecl) && \"Non-virtual base already exists!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1002, __extension__ __PRETTY_FUNCTION__))
1002 "Non-virtual base already exists!")(static_cast <bool> (!NonVirtualBaseInfo.count(BaseDecl
) && "Non-virtual base already exists!") ? void (0) :
__assert_fail ("!NonVirtualBaseInfo.count(BaseDecl) && \"Non-virtual base already exists!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1002, __extension__ __PRETTY_FUNCTION__))
;
1003 NonVirtualBaseInfo.insert(std::make_pair(BaseDecl, Info));
1004 }
1005 }
1006}
1007
1008void ItaniumRecordLayoutBuilder::EnsureVTablePointerAlignment(
1009 CharUnits UnpackedBaseAlign) {
1010 CharUnits BaseAlign = Packed ? CharUnits::One() : UnpackedBaseAlign;
1011
1012 // The maximum field alignment overrides base align.
1013 if (!MaxFieldAlignment.isZero()) {
1014 BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
1015 UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment);
1016 }
1017
1018 // Round up the current record size to pointer alignment.
1019 setSize(getSize().alignTo(BaseAlign));
1020
1021 // Update the alignment.
1022 UpdateAlignment(BaseAlign, UnpackedBaseAlign, BaseAlign);
1023}
1024
1025void ItaniumRecordLayoutBuilder::LayoutNonVirtualBases(
1026 const CXXRecordDecl *RD) {
1027 // Then, determine the primary base class.
1028 DeterminePrimaryBase(RD);
1029
1030 // Compute base subobject info.
1031 ComputeBaseSubobjectInfo(RD);
1032
1033 // If we have a primary base class, lay it out.
1034 if (PrimaryBase) {
1035 if (PrimaryBaseIsVirtual) {
1036 // If the primary virtual base was a primary virtual base of some other
1037 // base class we'll have to steal it.
1038 BaseSubobjectInfo *PrimaryBaseInfo = VirtualBaseInfo.lookup(PrimaryBase);
1039 PrimaryBaseInfo->Derived = nullptr;
1040
1041 // We have a virtual primary base, insert it as an indirect primary base.
1042 IndirectPrimaryBases.insert(PrimaryBase);
1043
1044 assert(!VisitedVirtualBases.count(PrimaryBase) &&(static_cast <bool> (!VisitedVirtualBases.count(PrimaryBase
) && "vbase already visited!") ? void (0) : __assert_fail
("!VisitedVirtualBases.count(PrimaryBase) && \"vbase already visited!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1045, __extension__ __PRETTY_FUNCTION__))
1045 "vbase already visited!")(static_cast <bool> (!VisitedVirtualBases.count(PrimaryBase
) && "vbase already visited!") ? void (0) : __assert_fail
("!VisitedVirtualBases.count(PrimaryBase) && \"vbase already visited!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1045, __extension__ __PRETTY_FUNCTION__))
;
1046 VisitedVirtualBases.insert(PrimaryBase);
1047
1048 LayoutVirtualBase(PrimaryBaseInfo);
1049 } else {
1050 BaseSubobjectInfo *PrimaryBaseInfo =
1051 NonVirtualBaseInfo.lookup(PrimaryBase);
1052 assert(PrimaryBaseInfo &&(static_cast <bool> (PrimaryBaseInfo && "Did not find base info for non-virtual primary base!"
) ? void (0) : __assert_fail ("PrimaryBaseInfo && \"Did not find base info for non-virtual primary base!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1053, __extension__ __PRETTY_FUNCTION__))
1053 "Did not find base info for non-virtual primary base!")(static_cast <bool> (PrimaryBaseInfo && "Did not find base info for non-virtual primary base!"
) ? void (0) : __assert_fail ("PrimaryBaseInfo && \"Did not find base info for non-virtual primary base!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1053, __extension__ __PRETTY_FUNCTION__))
;
1054
1055 LayoutNonVirtualBase(PrimaryBaseInfo);
1056 }
1057
1058 // If this class needs a vtable/vf-table and didn't get one from a
1059 // primary base, add it in now.
1060 } else if (RD->isDynamicClass()) {
1061 assert(DataSize == 0 && "Vtable pointer must be at offset zero!")(static_cast <bool> (DataSize == 0 && "Vtable pointer must be at offset zero!"
) ? void (0) : __assert_fail ("DataSize == 0 && \"Vtable pointer must be at offset zero!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1061, __extension__ __PRETTY_FUNCTION__))
;
1062 CharUnits PtrWidth =
1063 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
1064 CharUnits PtrAlign =
1065 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(0));
1066 EnsureVTablePointerAlignment(PtrAlign);
1067 HasOwnVFPtr = true;
1068
1069 assert(!IsUnion && "Unions cannot be dynamic classes.")(static_cast <bool> (!IsUnion && "Unions cannot be dynamic classes."
) ? void (0) : __assert_fail ("!IsUnion && \"Unions cannot be dynamic classes.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1069, __extension__ __PRETTY_FUNCTION__))
;
1070 HandledFirstNonOverlappingEmptyField = true;
1071
1072 setSize(getSize() + PtrWidth);
1073 setDataSize(getSize());
1074 }
1075
1076 // Now lay out the non-virtual bases.
1077 for (const auto &I : RD->bases()) {
1078
1079 // Ignore virtual bases.
1080 if (I.isVirtual())
1081 continue;
1082
1083 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
1084
1085 // Skip the primary base, because we've already laid it out. The
1086 // !PrimaryBaseIsVirtual check is required because we might have a
1087 // non-virtual base of the same type as a primary virtual base.
1088 if (BaseDecl == PrimaryBase && !PrimaryBaseIsVirtual)
1089 continue;
1090
1091 // Lay out the base.
1092 BaseSubobjectInfo *BaseInfo = NonVirtualBaseInfo.lookup(BaseDecl);
1093 assert(BaseInfo && "Did not find base info for non-virtual base!")(static_cast <bool> (BaseInfo && "Did not find base info for non-virtual base!"
) ? void (0) : __assert_fail ("BaseInfo && \"Did not find base info for non-virtual base!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1093, __extension__ __PRETTY_FUNCTION__))
;
1094
1095 LayoutNonVirtualBase(BaseInfo);
1096 }
1097}
1098
1099void ItaniumRecordLayoutBuilder::LayoutNonVirtualBase(
1100 const BaseSubobjectInfo *Base) {
1101 // Layout the base.
1102 CharUnits Offset = LayoutBase(Base);
1103
1104 // Add its base class offset.
1105 assert(!Bases.count(Base->Class) && "base offset already exists!")(static_cast <bool> (!Bases.count(Base->Class) &&
"base offset already exists!") ? void (0) : __assert_fail ("!Bases.count(Base->Class) && \"base offset already exists!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1105, __extension__ __PRETTY_FUNCTION__))
;
1106 Bases.insert(std::make_pair(Base->Class, Offset));
1107
1108 AddPrimaryVirtualBaseOffsets(Base, Offset);
1109}
1110
1111void ItaniumRecordLayoutBuilder::AddPrimaryVirtualBaseOffsets(
1112 const BaseSubobjectInfo *Info, CharUnits Offset) {
1113 // This base isn't interesting, it has no virtual bases.
1114 if (!Info->Class->getNumVBases())
1115 return;
1116
1117 // First, check if we have a virtual primary base to add offsets for.
1118 if (Info->PrimaryVirtualBaseInfo) {
1119 assert(Info->PrimaryVirtualBaseInfo->IsVirtual &&(static_cast <bool> (Info->PrimaryVirtualBaseInfo->
IsVirtual && "Primary virtual base is not virtual!") ?
void (0) : __assert_fail ("Info->PrimaryVirtualBaseInfo->IsVirtual && \"Primary virtual base is not virtual!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1120, __extension__ __PRETTY_FUNCTION__))
1120 "Primary virtual base is not virtual!")(static_cast <bool> (Info->PrimaryVirtualBaseInfo->
IsVirtual && "Primary virtual base is not virtual!") ?
void (0) : __assert_fail ("Info->PrimaryVirtualBaseInfo->IsVirtual && \"Primary virtual base is not virtual!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1120, __extension__ __PRETTY_FUNCTION__))
;
1121 if (Info->PrimaryVirtualBaseInfo->Derived == Info) {
1122 // Add the offset.
1123 assert(!VBases.count(Info->PrimaryVirtualBaseInfo->Class) &&(static_cast <bool> (!VBases.count(Info->PrimaryVirtualBaseInfo
->Class) && "primary vbase offset already exists!"
) ? void (0) : __assert_fail ("!VBases.count(Info->PrimaryVirtualBaseInfo->Class) && \"primary vbase offset already exists!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1124, __extension__ __PRETTY_FUNCTION__))
1124 "primary vbase offset already exists!")(static_cast <bool> (!VBases.count(Info->PrimaryVirtualBaseInfo
->Class) && "primary vbase offset already exists!"
) ? void (0) : __assert_fail ("!VBases.count(Info->PrimaryVirtualBaseInfo->Class) && \"primary vbase offset already exists!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1124, __extension__ __PRETTY_FUNCTION__))
;
1125 VBases.insert(std::make_pair(Info->PrimaryVirtualBaseInfo->Class,
1126 ASTRecordLayout::VBaseInfo(Offset, false)));
1127
1128 // Traverse the primary virtual base.
1129 AddPrimaryVirtualBaseOffsets(Info->PrimaryVirtualBaseInfo, Offset);
1130 }
1131 }
1132
1133 // Now go through all direct non-virtual bases.
1134 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
1135 for (const BaseSubobjectInfo *Base : Info->Bases) {
1136 if (Base->IsVirtual)
1137 continue;
1138
1139 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
1140 AddPrimaryVirtualBaseOffsets(Base, BaseOffset);
1141 }
1142}
1143
1144void ItaniumRecordLayoutBuilder::LayoutVirtualBases(
1145 const CXXRecordDecl *RD, const CXXRecordDecl *MostDerivedClass) {
1146 const CXXRecordDecl *PrimaryBase;
1147 bool PrimaryBaseIsVirtual;
1148
1149 if (MostDerivedClass
17.1
'MostDerivedClass' is equal to 'RD'
== RD) {
18
Taking true branch
1150 PrimaryBase = this->PrimaryBase;
1151 PrimaryBaseIsVirtual = this->PrimaryBaseIsVirtual;
1152 } else {
1153 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1154 PrimaryBase = Layout.getPrimaryBase();
1155 PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
1156 }
1157
1158 for (const CXXBaseSpecifier &Base : RD->bases()) {
19
Assuming '__begin1' is not equal to '__end1'
1159 assert(!Base.getType()->isDependentType() &&(static_cast <bool> (!Base.getType()->isDependentType
() && "Cannot layout class with dependent bases.") ? void
(0) : __assert_fail ("!Base.getType()->isDependentType() && \"Cannot layout class with dependent bases.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1160, __extension__ __PRETTY_FUNCTION__))
20
Assuming the condition is true
21
'?' condition is true
1160 "Cannot layout class with dependent bases.")(static_cast <bool> (!Base.getType()->isDependentType
() && "Cannot layout class with dependent bases.") ? void
(0) : __assert_fail ("!Base.getType()->isDependentType() && \"Cannot layout class with dependent bases.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1160, __extension__ __PRETTY_FUNCTION__))
;
1161
1162 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
22
'BaseDecl' initialized here
1163
1164 if (Base.isVirtual()) {
23
Assuming the condition is true
1165 if (PrimaryBase != BaseDecl || !PrimaryBaseIsVirtual) {
24
Assuming 'PrimaryBase' is equal to 'BaseDecl'
25
Assuming 'PrimaryBaseIsVirtual' is true
26
Taking false branch
1166 bool IndirectPrimaryBase = IndirectPrimaryBases.count(BaseDecl);
1167
1168 // Only lay out the virtual base if it's not an indirect primary base.
1169 if (!IndirectPrimaryBase) {
1170 // Only visit virtual bases once.
1171 if (!VisitedVirtualBases.insert(BaseDecl).second)
1172 continue;
1173
1174 const BaseSubobjectInfo *BaseInfo = VirtualBaseInfo.lookup(BaseDecl);
1175 assert(BaseInfo && "Did not find virtual base info!")(static_cast <bool> (BaseInfo && "Did not find virtual base info!"
) ? void (0) : __assert_fail ("BaseInfo && \"Did not find virtual base info!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1175, __extension__ __PRETTY_FUNCTION__))
;
1176 LayoutVirtualBase(BaseInfo);
1177 }
1178 }
1179 }
1180
1181 if (!BaseDecl->getNumVBases()) {
27
Called C++ object pointer is null
1182 // This base isn't interesting since it doesn't have any virtual bases.
1183 continue;
1184 }
1185
1186 LayoutVirtualBases(BaseDecl, MostDerivedClass);
1187 }
1188}
1189
1190void ItaniumRecordLayoutBuilder::LayoutVirtualBase(
1191 const BaseSubobjectInfo *Base) {
1192 assert(!Base->Derived && "Trying to lay out a primary virtual base!")(static_cast <bool> (!Base->Derived && "Trying to lay out a primary virtual base!"
) ? void (0) : __assert_fail ("!Base->Derived && \"Trying to lay out a primary virtual base!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1192, __extension__ __PRETTY_FUNCTION__))
;
1193
1194 // Layout the base.
1195 CharUnits Offset = LayoutBase(Base);
1196
1197 // Add its base class offset.
1198 assert(!VBases.count(Base->Class) && "vbase offset already exists!")(static_cast <bool> (!VBases.count(Base->Class) &&
"vbase offset already exists!") ? void (0) : __assert_fail (
"!VBases.count(Base->Class) && \"vbase offset already exists!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1198, __extension__ __PRETTY_FUNCTION__))
;
1199 VBases.insert(std::make_pair(Base->Class,
1200 ASTRecordLayout::VBaseInfo(Offset, false)));
1201
1202 AddPrimaryVirtualBaseOffsets(Base, Offset);
1203}
1204
1205CharUnits
1206ItaniumRecordLayoutBuilder::LayoutBase(const BaseSubobjectInfo *Base) {
1207 assert(!IsUnion && "Unions cannot have base classes.")(static_cast <bool> (!IsUnion && "Unions cannot have base classes."
) ? void (0) : __assert_fail ("!IsUnion && \"Unions cannot have base classes.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1207, __extension__ __PRETTY_FUNCTION__))
;
1208
1209 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base->Class);
1210 CharUnits Offset;
1211
1212 // Query the external layout to see if it provides an offset.
1213 bool HasExternalLayout = false;
1214 if (UseExternalLayout) {
1215 if (Base->IsVirtual)
1216 HasExternalLayout = External.getExternalVBaseOffset(Base->Class, Offset);
1217 else
1218 HasExternalLayout = External.getExternalNVBaseOffset(Base->Class, Offset);
1219 }
1220
1221 auto getBaseOrPreferredBaseAlignFromUnpacked = [&](CharUnits UnpackedAlign) {
1222 // Clang <= 6 incorrectly applied the 'packed' attribute to base classes.
1223 // Per GCC's documentation, it only applies to non-static data members.
1224 return (Packed && ((Context.getLangOpts().getClangABICompat() <=
1225 LangOptions::ClangABI::Ver6) ||
1226 Context.getTargetInfo().getTriple().isPS4() ||
1227 Context.getTargetInfo().getTriple().isOSAIX()))
1228 ? CharUnits::One()
1229 : UnpackedAlign;
1230 };
1231
1232 CharUnits UnpackedBaseAlign = Layout.getNonVirtualAlignment();
1233 CharUnits UnpackedPreferredBaseAlign = Layout.getPreferredNVAlignment();
1234 CharUnits BaseAlign =
1235 getBaseOrPreferredBaseAlignFromUnpacked(UnpackedBaseAlign);
1236 CharUnits PreferredBaseAlign =
1237 getBaseOrPreferredBaseAlignFromUnpacked(UnpackedPreferredBaseAlign);
1238
1239 const bool DefaultsToAIXPowerAlignment =
1240 Context.getTargetInfo().defaultsToAIXPowerAlignment();
1241 if (DefaultsToAIXPowerAlignment) {
1242 // AIX `power` alignment does not apply the preferred alignment for
1243 // non-union classes if the source of the alignment (the current base in
1244 // this context) follows introduction of the first subobject with
1245 // exclusively allocated space or zero-extent array.
1246 if (!Base->Class->isEmpty() && !HandledFirstNonOverlappingEmptyField) {
1247 // By handling a base class that is not empty, we're handling the
1248 // "first (inherited) member".
1249 HandledFirstNonOverlappingEmptyField = true;
1250 } else if (!IsNaturalAlign) {
1251 UnpackedPreferredBaseAlign = UnpackedBaseAlign;
1252 PreferredBaseAlign = BaseAlign;
1253 }
1254 }
1255
1256 CharUnits UnpackedAlignTo = !DefaultsToAIXPowerAlignment
1257 ? UnpackedBaseAlign
1258 : UnpackedPreferredBaseAlign;
1259 // If we have an empty base class, try to place it at offset 0.
1260 if (Base->Class->isEmpty() &&
1261 (!HasExternalLayout || Offset == CharUnits::Zero()) &&
1262 EmptySubobjects->CanPlaceBaseAtOffset(Base, CharUnits::Zero())) {
1263 setSize(std::max(getSize(), Layout.getSize()));
1264 UpdateAlignment(BaseAlign, UnpackedAlignTo, PreferredBaseAlign);
1265
1266 return CharUnits::Zero();
1267 }
1268
1269 // The maximum field alignment overrides the base align/(AIX-only) preferred
1270 // base align.
1271 if (!MaxFieldAlignment.isZero()) {
1272 BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
1273 PreferredBaseAlign = std::min(PreferredBaseAlign, MaxFieldAlignment);
1274 UnpackedAlignTo = std::min(UnpackedAlignTo, MaxFieldAlignment);
1275 }
1276
1277 CharUnits AlignTo =
1278 !DefaultsToAIXPowerAlignment ? BaseAlign : PreferredBaseAlign;
1279 if (!HasExternalLayout) {
1280 // Round up the current record size to the base's alignment boundary.
1281 Offset = getDataSize().alignTo(AlignTo);
1282
1283 // Try to place the base.
1284 while (!EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset))
1285 Offset += AlignTo;
1286 } else {
1287 bool Allowed = EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset);
1288 (void)Allowed;
1289 assert(Allowed && "Base subobject externally placed at overlapping offset")(static_cast <bool> (Allowed && "Base subobject externally placed at overlapping offset"
) ? void (0) : __assert_fail ("Allowed && \"Base subobject externally placed at overlapping offset\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1289, __extension__ __PRETTY_FUNCTION__))
;
1290
1291 if (InferAlignment && Offset < getDataSize().alignTo(AlignTo)) {
1292 // The externally-supplied base offset is before the base offset we
1293 // computed. Assume that the structure is packed.
1294 Alignment = CharUnits::One();
1295 InferAlignment = false;
1296 }
1297 }
1298
1299 if (!Base->Class->isEmpty()) {
1300 // Update the data size.
1301 setDataSize(Offset + Layout.getNonVirtualSize());
1302
1303 setSize(std::max(getSize(), getDataSize()));
1304 } else
1305 setSize(std::max(getSize(), Offset + Layout.getSize()));
1306
1307 // Remember max struct/class alignment.
1308 UpdateAlignment(BaseAlign, UnpackedAlignTo, PreferredBaseAlign);
1309
1310 return Offset;
1311}
1312
1313void ItaniumRecordLayoutBuilder::InitializeLayout(const Decl *D) {
1314 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
1315 IsUnion = RD->isUnion();
1316 IsMsStruct = RD->isMsStruct(Context);
1317 }
1318
1319 Packed = D->hasAttr<PackedAttr>();
1320
1321 // Honor the default struct packing maximum alignment flag.
1322 if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct) {
1323 MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment);
1324 }
1325
1326 // mac68k alignment supersedes maximum field alignment and attribute aligned,
1327 // and forces all structures to have 2-byte alignment. The IBM docs on it
1328 // allude to additional (more complicated) semantics, especially with regard
1329 // to bit-fields, but gcc appears not to follow that.
1330 if (D->hasAttr<AlignMac68kAttr>()) {
1331 assert((static_cast <bool> (!D->hasAttr<AlignNaturalAttr
>() && "Having both mac68k and natural alignment on a decl is not allowed."
) ? void (0) : __assert_fail ("!D->hasAttr<AlignNaturalAttr>() && \"Having both mac68k and natural alignment on a decl is not allowed.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1333, __extension__ __PRETTY_FUNCTION__))
1332 !D->hasAttr<AlignNaturalAttr>() &&(static_cast <bool> (!D->hasAttr<AlignNaturalAttr
>() && "Having both mac68k and natural alignment on a decl is not allowed."
) ? void (0) : __assert_fail ("!D->hasAttr<AlignNaturalAttr>() && \"Having both mac68k and natural alignment on a decl is not allowed.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1333, __extension__ __PRETTY_FUNCTION__))
1333 "Having both mac68k and natural alignment on a decl is not allowed.")(static_cast <bool> (!D->hasAttr<AlignNaturalAttr
>() && "Having both mac68k and natural alignment on a decl is not allowed."
) ? void (0) : __assert_fail ("!D->hasAttr<AlignNaturalAttr>() && \"Having both mac68k and natural alignment on a decl is not allowed.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1333, __extension__ __PRETTY_FUNCTION__))
;
1334 IsMac68kAlign = true;
1335 MaxFieldAlignment = CharUnits::fromQuantity(2);
1336 Alignment = CharUnits::fromQuantity(2);
1337 PreferredAlignment = CharUnits::fromQuantity(2);
1338 } else {
1339 if (D->hasAttr<AlignNaturalAttr>())
1340 IsNaturalAlign = true;
1341
1342 if (const MaxFieldAlignmentAttr *MFAA = D->getAttr<MaxFieldAlignmentAttr>())
1343 MaxFieldAlignment = Context.toCharUnitsFromBits(MFAA->getAlignment());
1344
1345 if (unsigned MaxAlign = D->getMaxAlignment())
1346 UpdateAlignment(Context.toCharUnitsFromBits(MaxAlign));
1347 }
1348
1349 HandledFirstNonOverlappingEmptyField =
1350 !Context.getTargetInfo().defaultsToAIXPowerAlignment() || IsNaturalAlign;
1351
1352 // If there is an external AST source, ask it for the various offsets.
1353 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
1354 if (ExternalASTSource *Source = Context.getExternalSource()) {
1355 UseExternalLayout = Source->layoutRecordType(
1356 RD, External.Size, External.Align, External.FieldOffsets,
1357 External.BaseOffsets, External.VirtualBaseOffsets);
1358
1359 // Update based on external alignment.
1360 if (UseExternalLayout) {
1361 if (External.Align > 0) {
1362 Alignment = Context.toCharUnitsFromBits(External.Align);
1363 PreferredAlignment = Context.toCharUnitsFromBits(External.Align);
1364 } else {
1365 // The external source didn't have alignment information; infer it.
1366 InferAlignment = true;
1367 }
1368 }
1369 }
1370}
1371
1372void ItaniumRecordLayoutBuilder::Layout(const RecordDecl *D) {
1373 InitializeLayout(D);
1374 LayoutFields(D);
1375
1376 // Finally, round the size of the total struct up to the alignment of the
1377 // struct itself.
1378 FinishLayout(D);
1379}
1380
1381void ItaniumRecordLayoutBuilder::Layout(const CXXRecordDecl *RD) {
1382 InitializeLayout(RD);
1383
1384 // Lay out the vtable and the non-virtual bases.
1385 LayoutNonVirtualBases(RD);
1386
1387 LayoutFields(RD);
1388
1389 NonVirtualSize = Context.toCharUnitsFromBits(
1390 llvm::alignTo(getSizeInBits(), Context.getTargetInfo().getCharAlign()));
1391 NonVirtualAlignment = Alignment;
1392 PreferredNVAlignment = PreferredAlignment;
1393
1394 // Lay out the virtual bases and add the primary virtual base offsets.
1395 LayoutVirtualBases(RD, RD);
17
Calling 'ItaniumRecordLayoutBuilder::LayoutVirtualBases'
1396
1397 // Finally, round the size of the total struct up to the alignment
1398 // of the struct itself.
1399 FinishLayout(RD);
1400
1401#ifndef NDEBUG
1402 // Check that we have base offsets for all bases.
1403 for (const CXXBaseSpecifier &Base : RD->bases()) {
1404 if (Base.isVirtual())
1405 continue;
1406
1407 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
1408
1409 assert(Bases.count(BaseDecl) && "Did not find base offset!")(static_cast <bool> (Bases.count(BaseDecl) && "Did not find base offset!"
) ? void (0) : __assert_fail ("Bases.count(BaseDecl) && \"Did not find base offset!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1409, __extension__ __PRETTY_FUNCTION__))
;
1410 }
1411
1412 // And all virtual bases.
1413 for (const CXXBaseSpecifier &Base : RD->vbases()) {
1414 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
1415
1416 assert(VBases.count(BaseDecl) && "Did not find base offset!")(static_cast <bool> (VBases.count(BaseDecl) && "Did not find base offset!"
) ? void (0) : __assert_fail ("VBases.count(BaseDecl) && \"Did not find base offset!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1416, __extension__ __PRETTY_FUNCTION__))
;
1417 }
1418#endif
1419}
1420
1421void ItaniumRecordLayoutBuilder::Layout(const ObjCInterfaceDecl *D) {
1422 if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
1423 const ASTRecordLayout &SL = Context.getASTObjCInterfaceLayout(SD);
1424
1425 UpdateAlignment(SL.getAlignment());
1426
1427 // We start laying out ivars not at the end of the superclass
1428 // structure, but at the next byte following the last field.
1429 setDataSize(SL.getDataSize());
1430 setSize(getDataSize());
1431 }
1432
1433 InitializeLayout(D);
1434 // Layout each ivar sequentially.
1435 for (const ObjCIvarDecl *IVD = D->all_declared_ivar_begin(); IVD;
1436 IVD = IVD->getNextIvar())
1437 LayoutField(IVD, false);
1438
1439 // Finally, round the size of the total struct up to the alignment of the
1440 // struct itself.
1441 FinishLayout(D);
1442}
1443
1444void ItaniumRecordLayoutBuilder::LayoutFields(const RecordDecl *D) {
1445 // Layout each field, for now, just sequentially, respecting alignment. In
1446 // the future, this will need to be tweakable by targets.
1447 bool InsertExtraPadding = D->mayInsertExtraPadding(/*EmitRemark=*/true);
1448 bool HasFlexibleArrayMember = D->hasFlexibleArrayMember();
1449 for (auto I = D->field_begin(), End = D->field_end(); I != End; ++I) {
1450 auto Next(I);
1451 ++Next;
1452 LayoutField(*I,
1453 InsertExtraPadding && (Next != End || !HasFlexibleArrayMember));
1454 }
1455}
1456
1457// Rounds the specified size to have it a multiple of the char size.
1458static uint64_t
1459roundUpSizeToCharAlignment(uint64_t Size,
1460 const ASTContext &Context) {
1461 uint64_t CharAlignment = Context.getTargetInfo().getCharAlign();
1462 return llvm::alignTo(Size, CharAlignment);
1463}
1464
1465void ItaniumRecordLayoutBuilder::LayoutWideBitField(uint64_t FieldSize,
1466 uint64_t StorageUnitSize,
1467 bool FieldPacked,
1468 const FieldDecl *D) {
1469 assert(Context.getLangOpts().CPlusPlus &&(static_cast <bool> (Context.getLangOpts().CPlusPlus &&
"Can only have wide bit-fields in C++!") ? void (0) : __assert_fail
("Context.getLangOpts().CPlusPlus && \"Can only have wide bit-fields in C++!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1470, __extension__ __PRETTY_FUNCTION__))
1470 "Can only have wide bit-fields in C++!")(static_cast <bool> (Context.getLangOpts().CPlusPlus &&
"Can only have wide bit-fields in C++!") ? void (0) : __assert_fail
("Context.getLangOpts().CPlusPlus && \"Can only have wide bit-fields in C++!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1470, __extension__ __PRETTY_FUNCTION__))
;
1471
1472 // Itanium C++ ABI 2.4:
1473 // If sizeof(T)*8 < n, let T' be the largest integral POD type with
1474 // sizeof(T')*8 <= n.
1475
1476 QualType IntegralPODTypes[] = {
1477 Context.UnsignedCharTy, Context.UnsignedShortTy, Context.UnsignedIntTy,
1478 Context.UnsignedLongTy, Context.UnsignedLongLongTy
1479 };
1480
1481 QualType Type;
1482 for (const QualType &QT : IntegralPODTypes) {
1483 uint64_t Size = Context.getTypeSize(QT);
1484
1485 if (Size > FieldSize)
1486 break;
1487
1488 Type = QT;
1489 }
1490 assert(!Type.isNull() && "Did not find a type!")(static_cast <bool> (!Type.isNull() && "Did not find a type!"
) ? void (0) : __assert_fail ("!Type.isNull() && \"Did not find a type!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1490, __extension__ __PRETTY_FUNCTION__))
;
1491
1492 CharUnits TypeAlign = Context.getTypeAlignInChars(Type);
1493
1494 // We're not going to use any of the unfilled bits in the last byte.
1495 UnfilledBitsInLastUnit = 0;
1496 LastBitfieldStorageUnitSize = 0;
1497
1498 uint64_t FieldOffset;
1499 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastUnit;
1500
1501 if (IsUnion) {
1502 uint64_t RoundedFieldSize = roundUpSizeToCharAlignment(FieldSize,
1503 Context);
1504 setDataSize(std::max(getDataSizeInBits(), RoundedFieldSize));
1505 FieldOffset = 0;
1506 } else {
1507 // The bitfield is allocated starting at the next offset aligned
1508 // appropriately for T', with length n bits.
1509 FieldOffset = llvm::alignTo(getDataSizeInBits(), Context.toBits(TypeAlign));
1510
1511 uint64_t NewSizeInBits = FieldOffset + FieldSize;
1512
1513 setDataSize(
1514 llvm::alignTo(NewSizeInBits, Context.getTargetInfo().getCharAlign()));
1515 UnfilledBitsInLastUnit = getDataSizeInBits() - NewSizeInBits;
1516 }
1517
1518 // Place this field at the current location.
1519 FieldOffsets.push_back(FieldOffset);
1520
1521 CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, FieldOffset,
1522 Context.toBits(TypeAlign), FieldPacked, D);
1523
1524 // Update the size.
1525 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
1526
1527 // Remember max struct/class alignment.
1528 UpdateAlignment(TypeAlign);
1529}
1530
1531static bool isAIXLayout(const ASTContext &Context) {
1532 return Context.getTargetInfo().getTriple().getOS() == llvm::Triple::AIX;
1533}
1534
1535void ItaniumRecordLayoutBuilder::LayoutBitField(const FieldDecl *D) {
1536 bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
1537 uint64_t FieldSize = D->getBitWidthValue(Context);
1538 TypeInfo FieldInfo = Context.getTypeInfo(D->getType());
1539 uint64_t StorageUnitSize = FieldInfo.Width;
1540 unsigned FieldAlign = FieldInfo.Align;
1541 bool AlignIsRequired = FieldInfo.AlignIsRequired;
1542
1543 // UnfilledBitsInLastUnit is the difference between the end of the
1544 // last allocated bitfield (i.e. the first bit offset available for
1545 // bitfields) and the end of the current data size in bits (i.e. the
1546 // first bit offset available for non-bitfields). The current data
1547 // size in bits is always a multiple of the char size; additionally,
1548 // for ms_struct records it's also a multiple of the
1549 // LastBitfieldStorageUnitSize (if set).
1550
1551 // The struct-layout algorithm is dictated by the platform ABI,
1552 // which in principle could use almost any rules it likes. In
1553 // practice, UNIXy targets tend to inherit the algorithm described
1554 // in the System V generic ABI. The basic bitfield layout rule in
1555 // System V is to place bitfields at the next available bit offset
1556 // where the entire bitfield would fit in an aligned storage unit of
1557 // the declared type; it's okay if an earlier or later non-bitfield
1558 // is allocated in the same storage unit. However, some targets
1559 // (those that !useBitFieldTypeAlignment(), e.g. ARM APCS) don't
1560 // require this storage unit to be aligned, and therefore always put
1561 // the bitfield at the next available bit offset.
1562
1563 // ms_struct basically requests a complete replacement of the
1564 // platform ABI's struct-layout algorithm, with the high-level goal
1565 // of duplicating MSVC's layout. For non-bitfields, this follows
1566 // the standard algorithm. The basic bitfield layout rule is to
1567 // allocate an entire unit of the bitfield's declared type
1568 // (e.g. 'unsigned long'), then parcel it up among successive
1569 // bitfields whose declared types have the same size, making a new
1570 // unit as soon as the last can no longer store the whole value.
1571 // Since it completely replaces the platform ABI's algorithm,
1572 // settings like !useBitFieldTypeAlignment() do not apply.
1573
1574 // A zero-width bitfield forces the use of a new storage unit for
1575 // later bitfields. In general, this occurs by rounding up the
1576 // current size of the struct as if the algorithm were about to
1577 // place a non-bitfield of the field's formal type. Usually this
1578 // does not change the alignment of the struct itself, but it does
1579 // on some targets (those that useZeroLengthBitfieldAlignment(),
1580 // e.g. ARM). In ms_struct layout, zero-width bitfields are
1581 // ignored unless they follow a non-zero-width bitfield.
1582
1583 // A field alignment restriction (e.g. from #pragma pack) or
1584 // specification (e.g. from __attribute__((aligned))) changes the
1585 // formal alignment of the field. For System V, this alters the
1586 // required alignment of the notional storage unit that must contain
1587 // the bitfield. For ms_struct, this only affects the placement of
1588 // new storage units. In both cases, the effect of #pragma pack is
1589 // ignored on zero-width bitfields.
1590
1591 // On System V, a packed field (e.g. from #pragma pack or
1592 // __attribute__((packed))) always uses the next available bit
1593 // offset.
1594
1595 // In an ms_struct struct, the alignment of a fundamental type is
1596 // always equal to its size. This is necessary in order to mimic
1597 // the i386 alignment rules on targets which might not fully align
1598 // all types (e.g. Darwin PPC32, where alignof(long long) == 4).
1599
1600 // First, some simple bookkeeping to perform for ms_struct structs.
1601 if (IsMsStruct) {
1602 // The field alignment for integer types is always the size.
1603 FieldAlign = StorageUnitSize;
1604
1605 // If the previous field was not a bitfield, or was a bitfield
1606 // with a different storage unit size, or if this field doesn't fit into
1607 // the current storage unit, we're done with that storage unit.
1608 if (LastBitfieldStorageUnitSize != StorageUnitSize ||
1609 UnfilledBitsInLastUnit < FieldSize) {
1610 // Also, ignore zero-length bitfields after non-bitfields.
1611 if (!LastBitfieldStorageUnitSize && !FieldSize)
1612 FieldAlign = 1;
1613
1614 UnfilledBitsInLastUnit = 0;
1615 LastBitfieldStorageUnitSize = 0;
1616 }
1617 }
1618
1619 if (isAIXLayout(Context)) {
1620 if (StorageUnitSize < Context.getTypeSize(Context.UnsignedIntTy)) {
1621 // On AIX, [bool, char, short] bitfields have the same alignment
1622 // as [unsigned].
1623 StorageUnitSize = Context.getTypeSize(Context.UnsignedIntTy);
1624 } else if (StorageUnitSize > Context.getTypeSize(Context.UnsignedIntTy) &&
1625 Context.getTargetInfo().getTriple().isArch32Bit() &&
1626 FieldSize <= 32) {
1627 // Under 32-bit compile mode, the bitcontainer is 32 bits if a single
1628 // long long bitfield has length no greater than 32 bits.
1629 StorageUnitSize = 32;
1630
1631 if (!AlignIsRequired)
1632 FieldAlign = 32;
1633 }
1634
1635 if (FieldAlign < StorageUnitSize) {
1636 // The bitfield alignment should always be greater than or equal to
1637 // bitcontainer size.
1638 FieldAlign = StorageUnitSize;
1639 }
1640 }
1641
1642 // If the field is wider than its declared type, it follows
1643 // different rules in all cases, except on AIX.
1644 // On AIX, wide bitfield follows the same rules as normal bitfield.
1645 if (FieldSize > StorageUnitSize && !isAIXLayout(Context)) {
1646 LayoutWideBitField(FieldSize, StorageUnitSize, FieldPacked, D);
1647 return;
1648 }
1649
1650 // Compute the next available bit offset.
1651 uint64_t FieldOffset =
1652 IsUnion ? 0 : (getDataSizeInBits() - UnfilledBitsInLastUnit);
1653
1654 // Handle targets that don't honor bitfield type alignment.
1655 if (!IsMsStruct && !Context.getTargetInfo().useBitFieldTypeAlignment()) {
1656 // Some such targets do honor it on zero-width bitfields.
1657 if (FieldSize == 0 &&
1658 Context.getTargetInfo().useZeroLengthBitfieldAlignment()) {
1659 // Some targets don't honor leading zero-width bitfield.
1660 if (!IsUnion && FieldOffset == 0 &&
1661 !Context.getTargetInfo().useLeadingZeroLengthBitfield())
1662 FieldAlign = 1;
1663 else {
1664 // The alignment to round up to is the max of the field's natural
1665 // alignment and a target-specific fixed value (sometimes zero).
1666 unsigned ZeroLengthBitfieldBoundary =
1667 Context.getTargetInfo().getZeroLengthBitfieldBoundary();
1668 FieldAlign = std::max(FieldAlign, ZeroLengthBitfieldBoundary);
1669 }
1670 // If that doesn't apply, just ignore the field alignment.
1671 } else {
1672 FieldAlign = 1;
1673 }
1674 }
1675
1676 // Remember the alignment we would have used if the field were not packed.
1677 unsigned UnpackedFieldAlign = FieldAlign;
1678
1679 // Ignore the field alignment if the field is packed unless it has zero-size.
1680 if (!IsMsStruct && FieldPacked && FieldSize != 0)
1681 FieldAlign = 1;
1682
1683 // But, if there's an 'aligned' attribute on the field, honor that.
1684 unsigned ExplicitFieldAlign = D->getMaxAlignment();
1685 if (ExplicitFieldAlign) {
1686 FieldAlign = std::max(FieldAlign, ExplicitFieldAlign);
1687 UnpackedFieldAlign = std::max(UnpackedFieldAlign, ExplicitFieldAlign);
1688 }
1689
1690 // But, if there's a #pragma pack in play, that takes precedent over
1691 // even the 'aligned' attribute, for non-zero-width bitfields.
1692 unsigned MaxFieldAlignmentInBits = Context.toBits(MaxFieldAlignment);
1693 if (!MaxFieldAlignment.isZero() && FieldSize) {
1694 UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignmentInBits);
1695 if (FieldPacked)
1696 FieldAlign = UnpackedFieldAlign;
1697 else
1698 FieldAlign = std::min(FieldAlign, MaxFieldAlignmentInBits);
1699 }
1700
1701 // But, ms_struct just ignores all of that in unions, even explicit
1702 // alignment attributes.
1703 if (IsMsStruct && IsUnion) {
1704 FieldAlign = UnpackedFieldAlign = 1;
1705 }
1706
1707 // For purposes of diagnostics, we're going to simultaneously
1708 // compute the field offsets that we would have used if we weren't
1709 // adding any alignment padding or if the field weren't packed.
1710 uint64_t UnpaddedFieldOffset = FieldOffset;
1711 uint64_t UnpackedFieldOffset = FieldOffset;
1712
1713 // Check if we need to add padding to fit the bitfield within an
1714 // allocation unit with the right size and alignment. The rules are
1715 // somewhat different here for ms_struct structs.
1716 if (IsMsStruct) {
1717 // If it's not a zero-width bitfield, and we can fit the bitfield
1718 // into the active storage unit (and we haven't already decided to
1719 // start a new storage unit), just do so, regardless of any other
1720 // other consideration. Otherwise, round up to the right alignment.
1721 if (FieldSize == 0 || FieldSize > UnfilledBitsInLastUnit) {
1722 FieldOffset = llvm::alignTo(FieldOffset, FieldAlign);
1723 UnpackedFieldOffset =
1724 llvm::alignTo(UnpackedFieldOffset, UnpackedFieldAlign);
1725 UnfilledBitsInLastUnit = 0;
1726 }
1727
1728 } else {
1729 // #pragma pack, with any value, suppresses the insertion of padding.
1730 bool AllowPadding = MaxFieldAlignment.isZero();
1731
1732 // Compute the real offset.
1733 if (FieldSize == 0 ||
1734 (AllowPadding &&
1735 (FieldOffset & (FieldAlign - 1)) + FieldSize > StorageUnitSize)) {
1736 FieldOffset = llvm::alignTo(FieldOffset, FieldAlign);
1737 } else if (ExplicitFieldAlign &&
1738 (MaxFieldAlignmentInBits == 0 ||
1739 ExplicitFieldAlign <= MaxFieldAlignmentInBits) &&
1740 Context.getTargetInfo().useExplicitBitFieldAlignment()) {
1741 // TODO: figure it out what needs to be done on targets that don't honor
1742 // bit-field type alignment like ARM APCS ABI.
1743 FieldOffset = llvm::alignTo(FieldOffset, ExplicitFieldAlign);
1744 }
1745
1746 // Repeat the computation for diagnostic purposes.
1747 if (FieldSize == 0 ||
1748 (AllowPadding &&
1749 (UnpackedFieldOffset & (UnpackedFieldAlign - 1)) + FieldSize >
1750 StorageUnitSize))
1751 UnpackedFieldOffset =
1752 llvm::alignTo(UnpackedFieldOffset, UnpackedFieldAlign);
1753 else if (ExplicitFieldAlign &&
1754 (MaxFieldAlignmentInBits == 0 ||
1755 ExplicitFieldAlign <= MaxFieldAlignmentInBits) &&
1756 Context.getTargetInfo().useExplicitBitFieldAlignment())
1757 UnpackedFieldOffset =
1758 llvm::alignTo(UnpackedFieldOffset, ExplicitFieldAlign);
1759 }
1760
1761 // If we're using external layout, give the external layout a chance
1762 // to override this information.
1763 if (UseExternalLayout)
1764 FieldOffset = updateExternalFieldOffset(D, FieldOffset);
1765
1766 // Okay, place the bitfield at the calculated offset.
1767 FieldOffsets.push_back(FieldOffset);
1768
1769 // Bookkeeping:
1770
1771 // Anonymous members don't affect the overall record alignment,
1772 // except on targets where they do.
1773 if (!IsMsStruct &&
1774 !Context.getTargetInfo().useZeroLengthBitfieldAlignment() &&
1775 !D->getIdentifier())
1776 FieldAlign = UnpackedFieldAlign = 1;
1777
1778 // On AIX, zero-width bitfields pad out to the natural alignment boundary,
1779 // but do not increase the alignment greater than the MaxFieldAlignment, or 1
1780 // if packed.
1781 if (isAIXLayout(Context) && !FieldSize) {
1782 if (FieldPacked)
1783 FieldAlign = 1;
1784 if (!MaxFieldAlignment.isZero()) {
1785 UnpackedFieldAlign =
1786 std::min(UnpackedFieldAlign, MaxFieldAlignmentInBits);
1787 FieldAlign = std::min(FieldAlign, MaxFieldAlignmentInBits);
1788 }
1789 }
1790
1791 // Diagnose differences in layout due to padding or packing.
1792 if (!UseExternalLayout)
1793 CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, UnpackedFieldOffset,
1794 UnpackedFieldAlign, FieldPacked, D);
1795
1796 // Update DataSize to include the last byte containing (part of) the bitfield.
1797
1798 // For unions, this is just a max operation, as usual.
1799 if (IsUnion) {
1800 // For ms_struct, allocate the entire storage unit --- unless this
1801 // is a zero-width bitfield, in which case just use a size of 1.
1802 uint64_t RoundedFieldSize;
1803 if (IsMsStruct) {
1804 RoundedFieldSize = (FieldSize ? StorageUnitSize
1805 : Context.getTargetInfo().getCharWidth());
1806
1807 // Otherwise, allocate just the number of bytes required to store
1808 // the bitfield.
1809 } else {
1810 RoundedFieldSize = roundUpSizeToCharAlignment(FieldSize, Context);
1811 }
1812 setDataSize(std::max(getDataSizeInBits(), RoundedFieldSize));
1813
1814 // For non-zero-width bitfields in ms_struct structs, allocate a new
1815 // storage unit if necessary.
1816 } else if (IsMsStruct && FieldSize) {
1817 // We should have cleared UnfilledBitsInLastUnit in every case
1818 // where we changed storage units.
1819 if (!UnfilledBitsInLastUnit) {
1820 setDataSize(FieldOffset + StorageUnitSize);
1821 UnfilledBitsInLastUnit = StorageUnitSize;
1822 }
1823 UnfilledBitsInLastUnit -= FieldSize;
1824 LastBitfieldStorageUnitSize = StorageUnitSize;
1825
1826 // Otherwise, bump the data size up to include the bitfield,
1827 // including padding up to char alignment, and then remember how
1828 // bits we didn't use.
1829 } else {
1830 uint64_t NewSizeInBits = FieldOffset + FieldSize;
1831 uint64_t CharAlignment = Context.getTargetInfo().getCharAlign();
1832 setDataSize(llvm::alignTo(NewSizeInBits, CharAlignment));
1833 UnfilledBitsInLastUnit = getDataSizeInBits() - NewSizeInBits;
1834
1835 // The only time we can get here for an ms_struct is if this is a
1836 // zero-width bitfield, which doesn't count as anything for the
1837 // purposes of unfilled bits.
1838 LastBitfieldStorageUnitSize = 0;
1839 }
1840
1841 // Update the size.
1842 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
1843
1844 // Remember max struct/class alignment.
1845 UnadjustedAlignment =
1846 std::max(UnadjustedAlignment, Context.toCharUnitsFromBits(FieldAlign));
1847 UpdateAlignment(Context.toCharUnitsFromBits(FieldAlign),
1848 Context.toCharUnitsFromBits(UnpackedFieldAlign));
1849}
1850
1851void ItaniumRecordLayoutBuilder::LayoutField(const FieldDecl *D,
1852 bool InsertExtraPadding) {
1853 auto *FieldClass = D->getType()->getAsCXXRecordDecl();
1854 bool PotentiallyOverlapping = D->hasAttr<NoUniqueAddressAttr>() && FieldClass;
1855 bool IsOverlappingEmptyField =
1856 PotentiallyOverlapping && FieldClass->isEmpty();
1857
1858 CharUnits FieldOffset =
1859 (IsUnion || IsOverlappingEmptyField) ? CharUnits::Zero() : getDataSize();
1860
1861 const bool DefaultsToAIXPowerAlignment =
1862 Context.getTargetInfo().defaultsToAIXPowerAlignment();
1863 bool FoundFirstNonOverlappingEmptyFieldForAIX = false;
1864 if (DefaultsToAIXPowerAlignment && !HandledFirstNonOverlappingEmptyField) {
1865 assert(FieldOffset == CharUnits::Zero() &&(static_cast <bool> (FieldOffset == CharUnits::Zero() &&
"The first non-overlapping empty field should have been handled."
) ? void (0) : __assert_fail ("FieldOffset == CharUnits::Zero() && \"The first non-overlapping empty field should have been handled.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1866, __extension__ __PRETTY_FUNCTION__))
1866 "The first non-overlapping empty field should have been handled.")(static_cast <bool> (FieldOffset == CharUnits::Zero() &&
"The first non-overlapping empty field should have been handled."
) ? void (0) : __assert_fail ("FieldOffset == CharUnits::Zero() && \"The first non-overlapping empty field should have been handled.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1866, __extension__ __PRETTY_FUNCTION__))
;
1867
1868 if (!IsOverlappingEmptyField) {
1869 FoundFirstNonOverlappingEmptyFieldForAIX = true;
1870
1871 // We're going to handle the "first member" based on
1872 // `FoundFirstNonOverlappingEmptyFieldForAIX` during the current
1873 // invocation of this function; record it as handled for future
1874 // invocations (except for unions, because the current field does not
1875 // represent all "firsts").
1876 HandledFirstNonOverlappingEmptyField = !IsUnion;
1877 }
1878 }
1879
1880 if (D->isBitField()) {
1881 LayoutBitField(D);
1882 return;
1883 }
1884
1885 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastUnit;
1886 // Reset the unfilled bits.
1887 UnfilledBitsInLastUnit = 0;
1888 LastBitfieldStorageUnitSize = 0;
1889
1890 bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
1891
1892 bool AlignIsRequired = false;
1893 CharUnits FieldSize;
1894 CharUnits FieldAlign;
1895 // The amount of this class's dsize occupied by the field.
1896 // This is equal to FieldSize unless we're permitted to pack
1897 // into the field's tail padding.
1898 CharUnits EffectiveFieldSize;
1899
1900 auto setDeclInfo = [&](bool IsIncompleteArrayType) {
1901 auto TI = Context.getTypeInfoInChars(D->getType());
1902 FieldAlign = TI.Align;
1903 // Flexible array members don't have any size, but they have to be
1904 // aligned appropriately for their element type.
1905 EffectiveFieldSize = FieldSize =
1906 IsIncompleteArrayType ? CharUnits::Zero() : TI.Width;
1907 AlignIsRequired = TI.AlignIsRequired;
1908 };
1909
1910 if (D->getType()->isIncompleteArrayType()) {
1911 setDeclInfo(true /* IsIncompleteArrayType */);
1912 } else if (const ReferenceType *RT = D->getType()->getAs<ReferenceType>()) {
1913 unsigned AS = Context.getTargetAddressSpace(RT->getPointeeType());
1914 EffectiveFieldSize = FieldSize = Context.toCharUnitsFromBits(
1915 Context.getTargetInfo().getPointerWidth(AS));
1916 FieldAlign = Context.toCharUnitsFromBits(
1917 Context.getTargetInfo().getPointerAlign(AS));
1918 } else {
1919 setDeclInfo(false /* IsIncompleteArrayType */);
1920
1921 // A potentially-overlapping field occupies its dsize or nvsize, whichever
1922 // is larger.
1923 if (PotentiallyOverlapping) {
1924 const ASTRecordLayout &Layout = Context.getASTRecordLayout(FieldClass);
1925 EffectiveFieldSize =
1926 std::max(Layout.getNonVirtualSize(), Layout.getDataSize());
1927 }
1928
1929 if (IsMsStruct) {
1930 // If MS bitfield layout is required, figure out what type is being
1931 // laid out and align the field to the width of that type.
1932
1933 // Resolve all typedefs down to their base type and round up the field
1934 // alignment if necessary.
1935 QualType T = Context.getBaseElementType(D->getType());
1936 if (const BuiltinType *BTy = T->getAs<BuiltinType>()) {
1937 CharUnits TypeSize = Context.getTypeSizeInChars(BTy);
1938
1939 if (!llvm::isPowerOf2_64(TypeSize.getQuantity())) {
1940 assert((static_cast <bool> (!Context.getTargetInfo().getTriple
().isWindowsMSVCEnvironment() && "Non PowerOf2 size in MSVC mode"
) ? void (0) : __assert_fail ("!Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment() && \"Non PowerOf2 size in MSVC mode\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1942, __extension__ __PRETTY_FUNCTION__))
1941 !Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment() &&(static_cast <bool> (!Context.getTargetInfo().getTriple
().isWindowsMSVCEnvironment() && "Non PowerOf2 size in MSVC mode"
) ? void (0) : __assert_fail ("!Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment() && \"Non PowerOf2 size in MSVC mode\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1942, __extension__ __PRETTY_FUNCTION__))
1942 "Non PowerOf2 size in MSVC mode")(static_cast <bool> (!Context.getTargetInfo().getTriple
().isWindowsMSVCEnvironment() && "Non PowerOf2 size in MSVC mode"
) ? void (0) : __assert_fail ("!Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment() && \"Non PowerOf2 size in MSVC mode\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1942, __extension__ __PRETTY_FUNCTION__))
;
1943 // Base types with sizes that aren't a power of two don't work
1944 // with the layout rules for MS structs. This isn't an issue in
1945 // MSVC itself since there are no such base data types there.
1946 // On e.g. x86_32 mingw and linux, long double is 12 bytes though.
1947 // Any structs involving that data type obviously can't be ABI
1948 // compatible with MSVC regardless of how it is laid out.
1949
1950 // Since ms_struct can be mass enabled (via a pragma or via the
1951 // -mms-bitfields command line parameter), this can trigger for
1952 // structs that don't actually need MSVC compatibility, so we
1953 // need to be able to sidestep the ms_struct layout for these types.
1954
1955 // Since the combination of -mms-bitfields together with structs
1956 // like max_align_t (which contains a long double) for mingw is
1957 // quite comon (and GCC handles it silently), just handle it
1958 // silently there. For other targets that have ms_struct enabled
1959 // (most probably via a pragma or attribute), trigger a diagnostic
1960 // that defaults to an error.
1961 if (!Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
1962 Diag(D->getLocation(), diag::warn_npot_ms_struct);
1963 }
1964 if (TypeSize > FieldAlign &&
1965 llvm::isPowerOf2_64(TypeSize.getQuantity()))
1966 FieldAlign = TypeSize;
1967 }
1968 }
1969 }
1970
1971 // The AIX `power` alignment rules apply the natural alignment of the
1972 // "first member" if it is of a floating-point data type (or is an aggregate
1973 // whose recursively "first" member or element is such a type). The alignment
1974 // associated with these types for subsequent members use an alignment value
1975 // where the floating-point data type is considered to have 4-byte alignment.
1976 //
1977 // For the purposes of the foregoing: vtable pointers, non-empty base classes,
1978 // and zero-width bit-fields count as prior members; members of empty class
1979 // types marked `no_unique_address` are not considered to be prior members.
1980 CharUnits PreferredAlign = FieldAlign;
1981 if (DefaultsToAIXPowerAlignment && !AlignIsRequired &&
1982 (FoundFirstNonOverlappingEmptyFieldForAIX || IsNaturalAlign)) {
1983 auto performBuiltinTypeAlignmentUpgrade = [&](const BuiltinType *BTy) {
1984 if (BTy->getKind() == BuiltinType::Double ||
1985 BTy->getKind() == BuiltinType::LongDouble) {
1986 assert(PreferredAlign == CharUnits::fromQuantity(4) &&(static_cast <bool> (PreferredAlign == CharUnits::fromQuantity
(4) && "No need to upgrade the alignment value.") ? void
(0) : __assert_fail ("PreferredAlign == CharUnits::fromQuantity(4) && \"No need to upgrade the alignment value.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1987, __extension__ __PRETTY_FUNCTION__))
1987 "No need to upgrade the alignment value.")(static_cast <bool> (PreferredAlign == CharUnits::fromQuantity
(4) && "No need to upgrade the alignment value.") ? void
(0) : __assert_fail ("PreferredAlign == CharUnits::fromQuantity(4) && \"No need to upgrade the alignment value.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1987, __extension__ __PRETTY_FUNCTION__))
;
1988 PreferredAlign = CharUnits::fromQuantity(8);
1989 }
1990 };
1991
1992 const Type *Ty = D->getType()->getBaseElementTypeUnsafe();
1993 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
1994 performBuiltinTypeAlignmentUpgrade(CTy->getElementType()->castAs<BuiltinType>());
1995 } else if (const BuiltinType *BTy = Ty->getAs<BuiltinType>()) {
1996 performBuiltinTypeAlignmentUpgrade(BTy);
1997 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
1998 const RecordDecl *RD = RT->getDecl();
1999 assert(RD && "Expected non-null RecordDecl.")(static_cast <bool> (RD && "Expected non-null RecordDecl."
) ? void (0) : __assert_fail ("RD && \"Expected non-null RecordDecl.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 1999, __extension__ __PRETTY_FUNCTION__))
;
2000 const ASTRecordLayout &FieldRecord = Context.getASTRecordLayout(RD);
2001 PreferredAlign = FieldRecord.getPreferredAlignment();
2002 }
2003 }
2004
2005 // The align if the field is not packed. This is to check if the attribute
2006 // was unnecessary (-Wpacked).
2007 CharUnits UnpackedFieldAlign =
2008 !DefaultsToAIXPowerAlignment ? FieldAlign : PreferredAlign;
2009 CharUnits UnpackedFieldOffset = FieldOffset;
2010
2011 if (FieldPacked) {
2012 FieldAlign = CharUnits::One();
2013 PreferredAlign = CharUnits::One();
2014 }
2015 CharUnits MaxAlignmentInChars =
2016 Context.toCharUnitsFromBits(D->getMaxAlignment());
2017 FieldAlign = std::max(FieldAlign, MaxAlignmentInChars);
2018 PreferredAlign = std::max(PreferredAlign, MaxAlignmentInChars);
2019 UnpackedFieldAlign = std::max(UnpackedFieldAlign, MaxAlignmentInChars);
2020
2021 // The maximum field alignment overrides the aligned attribute.
2022 if (!MaxFieldAlignment.isZero()) {
2023 FieldAlign = std::min(FieldAlign, MaxFieldAlignment);
2024 PreferredAlign = std::min(PreferredAlign, MaxFieldAlignment);
2025 UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignment);
2026 }
2027
2028 CharUnits AlignTo =
2029 !DefaultsToAIXPowerAlignment ? FieldAlign : PreferredAlign;
2030 // Round up the current record size to the field's alignment boundary.
2031 FieldOffset = FieldOffset.alignTo(AlignTo);
2032 UnpackedFieldOffset = UnpackedFieldOffset.alignTo(UnpackedFieldAlign);
2033
2034 if (UseExternalLayout) {
2035 FieldOffset = Context.toCharUnitsFromBits(
2036 updateExternalFieldOffset(D, Context.toBits(FieldOffset)));
2037
2038 if (!IsUnion && EmptySubobjects) {
2039 // Record the fact that we're placing a field at this offset.
2040 bool Allowed = EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset);
2041 (void)Allowed;
2042 assert(Allowed && "Externally-placed field cannot be placed here")(static_cast <bool> (Allowed && "Externally-placed field cannot be placed here"
) ? void (0) : __assert_fail ("Allowed && \"Externally-placed field cannot be placed here\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 2042, __extension__ __PRETTY_FUNCTION__))
;
2043 }
2044 } else {
2045 if (!IsUnion && EmptySubobjects) {
2046 // Check if we can place the field at this offset.
2047 while (!EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset)) {
2048 // We couldn't place the field at the offset. Try again at a new offset.
2049 // We try offset 0 (for an empty field) and then dsize(C) onwards.
2050 if (FieldOffset == CharUnits::Zero() &&
2051 getDataSize() != CharUnits::Zero())
2052 FieldOffset = getDataSize().alignTo(AlignTo);
2053 else
2054 FieldOffset += AlignTo;
2055 }
2056 }
2057 }
2058
2059 // Place this field at the current location.
2060 FieldOffsets.push_back(Context.toBits(FieldOffset));
2061
2062 if (!UseExternalLayout)
2063 CheckFieldPadding(Context.toBits(FieldOffset), UnpaddedFieldOffset,
2064 Context.toBits(UnpackedFieldOffset),
2065 Context.toBits(UnpackedFieldAlign), FieldPacked, D);
2066
2067 if (InsertExtraPadding) {
2068 CharUnits ASanAlignment = CharUnits::fromQuantity(8);
2069 CharUnits ExtraSizeForAsan = ASanAlignment;
2070 if (FieldSize % ASanAlignment)
2071 ExtraSizeForAsan +=
2072 ASanAlignment - CharUnits::fromQuantity(FieldSize % ASanAlignment);
2073 EffectiveFieldSize = FieldSize = FieldSize + ExtraSizeForAsan;
2074 }
2075
2076 // Reserve space for this field.
2077 if (!IsOverlappingEmptyField) {
2078 uint64_t EffectiveFieldSizeInBits = Context.toBits(EffectiveFieldSize);
2079 if (IsUnion)
2080 setDataSize(std::max(getDataSizeInBits(), EffectiveFieldSizeInBits));
2081 else
2082 setDataSize(FieldOffset + EffectiveFieldSize);
2083
2084 PaddedFieldSize = std::max(PaddedFieldSize, FieldOffset + FieldSize);
2085 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
2086 } else {
2087 setSize(std::max(getSizeInBits(),
2088 (uint64_t)Context.toBits(FieldOffset + FieldSize)));
2089 }
2090
2091 // Remember max struct/class ABI-specified alignment.
2092 UnadjustedAlignment = std::max(UnadjustedAlignment, FieldAlign);
2093 UpdateAlignment(FieldAlign, UnpackedFieldAlign, PreferredAlign);
2094}
2095
2096void ItaniumRecordLayoutBuilder::FinishLayout(const NamedDecl *D) {
2097 // In C++, records cannot be of size 0.
2098 if (Context.getLangOpts().CPlusPlus && getSizeInBits() == 0) {
2099 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
2100 // Compatibility with gcc requires a class (pod or non-pod)
2101 // which is not empty but of size 0; such as having fields of
2102 // array of zero-length, remains of Size 0
2103 if (RD->isEmpty())
2104 setSize(CharUnits::One());
2105 }
2106 else
2107 setSize(CharUnits::One());
2108 }
2109
2110 // If we have any remaining field tail padding, include that in the overall
2111 // size.
2112 setSize(std::max(getSizeInBits(), (uint64_t)Context.toBits(PaddedFieldSize)));
2113
2114 // Finally, round the size of the record up to the alignment of the
2115 // record itself.
2116 uint64_t UnpaddedSize = getSizeInBits() - UnfilledBitsInLastUnit;
2117 uint64_t UnpackedSizeInBits =
2118 llvm::alignTo(getSizeInBits(), Context.toBits(UnpackedAlignment));
2119
2120 uint64_t RoundedSize = llvm::alignTo(
2121 getSizeInBits(),
2122 Context.toBits(!Context.getTargetInfo().defaultsToAIXPowerAlignment()
2123 ? Alignment
2124 : PreferredAlignment));
2125
2126 if (UseExternalLayout) {
2127 // If we're inferring alignment, and the external size is smaller than
2128 // our size after we've rounded up to alignment, conservatively set the
2129 // alignment to 1.
2130 if (InferAlignment && External.Size < RoundedSize) {
2131 Alignment = CharUnits::One();
2132 PreferredAlignment = CharUnits::One();
2133 InferAlignment = false;
2134 }
2135 setSize(External.Size);
2136 return;
2137 }
2138
2139 // Set the size to the final size.
2140 setSize(RoundedSize);
2141
2142 unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
2143 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
2144 // Warn if padding was introduced to the struct/class/union.
2145 if (getSizeInBits() > UnpaddedSize) {
2146 unsigned PadSize = getSizeInBits() - UnpaddedSize;
2147 bool InBits = true;
2148 if (PadSize % CharBitNum == 0) {
2149 PadSize = PadSize / CharBitNum;
2150 InBits = false;
2151 }
2152 Diag(RD->getLocation(), diag::warn_padded_struct_size)
2153 << Context.getTypeDeclType(RD)
2154 << PadSize
2155 << (InBits ? 1 : 0); // (byte|bit)
2156 }
2157
2158 // Warn if we packed it unnecessarily, when the unpacked alignment is not
2159 // greater than the one after packing, the size in bits doesn't change and
2160 // the offset of each field is identical.
2161 if (Packed && UnpackedAlignment <= Alignment &&
2162 UnpackedSizeInBits == getSizeInBits() && !HasPackedField)
2163 Diag(D->getLocation(), diag::warn_unnecessary_packed)
2164 << Context.getTypeDeclType(RD);
2165 }
2166}
2167
2168void ItaniumRecordLayoutBuilder::UpdateAlignment(
2169 CharUnits NewAlignment, CharUnits UnpackedNewAlignment,
2170 CharUnits PreferredNewAlignment) {
2171 // The alignment is not modified when using 'mac68k' alignment or when
2172 // we have an externally-supplied layout that also provides overall alignment.
2173 if (IsMac68kAlign || (UseExternalLayout && !InferAlignment))
2174 return;
2175
2176 if (NewAlignment > Alignment) {
2177 assert(llvm::isPowerOf2_64(NewAlignment.getQuantity()) &&(static_cast <bool> (llvm::isPowerOf2_64(NewAlignment.getQuantity
()) && "Alignment not a power of 2") ? void (0) : __assert_fail
("llvm::isPowerOf2_64(NewAlignment.getQuantity()) && \"Alignment not a power of 2\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 2178, __extension__ __PRETTY_FUNCTION__))
2178 "Alignment not a power of 2")(static_cast <bool> (llvm::isPowerOf2_64(NewAlignment.getQuantity
()) && "Alignment not a power of 2") ? void (0) : __assert_fail
("llvm::isPowerOf2_64(NewAlignment.getQuantity()) && \"Alignment not a power of 2\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 2178, __extension__ __PRETTY_FUNCTION__))
;
2179 Alignment = NewAlignment;
2180 }
2181
2182 if (UnpackedNewAlignment > UnpackedAlignment) {
2183 assert(llvm::isPowerOf2_64(UnpackedNewAlignment.getQuantity()) &&(static_cast <bool> (llvm::isPowerOf2_64(UnpackedNewAlignment
.getQuantity()) && "Alignment not a power of 2") ? void
(0) : __assert_fail ("llvm::isPowerOf2_64(UnpackedNewAlignment.getQuantity()) && \"Alignment not a power of 2\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 2184, __extension__ __PRETTY_FUNCTION__))
2184 "Alignment not a power of 2")(static_cast <bool> (llvm::isPowerOf2_64(UnpackedNewAlignment
.getQuantity()) && "Alignment not a power of 2") ? void
(0) : __assert_fail ("llvm::isPowerOf2_64(UnpackedNewAlignment.getQuantity()) && \"Alignment not a power of 2\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 2184, __extension__ __PRETTY_FUNCTION__))
;
2185 UnpackedAlignment = UnpackedNewAlignment;
2186 }
2187
2188 if (PreferredNewAlignment > PreferredAlignment) {
2189 assert(llvm::isPowerOf2_64(PreferredNewAlignment.getQuantity()) &&(static_cast <bool> (llvm::isPowerOf2_64(PreferredNewAlignment
.getQuantity()) && "Alignment not a power of 2") ? void
(0) : __assert_fail ("llvm::isPowerOf2_64(PreferredNewAlignment.getQuantity()) && \"Alignment not a power of 2\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 2190, __extension__ __PRETTY_FUNCTION__))
2190 "Alignment not a power of 2")(static_cast <bool> (llvm::isPowerOf2_64(PreferredNewAlignment
.getQuantity()) && "Alignment not a power of 2") ? void
(0) : __assert_fail ("llvm::isPowerOf2_64(PreferredNewAlignment.getQuantity()) && \"Alignment not a power of 2\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 2190, __extension__ __PRETTY_FUNCTION__))
;
2191 PreferredAlignment = PreferredNewAlignment;
2192 }
2193}
2194
2195uint64_t
2196ItaniumRecordLayoutBuilder::updateExternalFieldOffset(const FieldDecl *Field,
2197 uint64_t ComputedOffset) {
2198 uint64_t ExternalFieldOffset = External.getExternalFieldOffset(Field);
2199
2200 if (InferAlignment && ExternalFieldOffset < ComputedOffset) {
2201 // The externally-supplied field offset is before the field offset we
2202 // computed. Assume that the structure is packed.
2203 Alignment = CharUnits::One();
2204 PreferredAlignment = CharUnits::One();
2205 InferAlignment = false;
2206 }
2207
2208 // Use the externally-supplied field offset.
2209 return ExternalFieldOffset;
2210}
2211
2212/// Get diagnostic %select index for tag kind for
2213/// field padding diagnostic message.
2214/// WARNING: Indexes apply to particular diagnostics only!
2215///
2216/// \returns diagnostic %select index.
2217static unsigned getPaddingDiagFromTagKind(TagTypeKind Tag) {
2218 switch (Tag) {
2219 case TTK_Struct: return 0;
2220 case TTK_Interface: return 1;
2221 case TTK_Class: return 2;
2222 default: llvm_unreachable("Invalid tag kind for field padding diagnostic!")::llvm::llvm_unreachable_internal("Invalid tag kind for field padding diagnostic!"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 2222)
;
2223 }
2224}
2225
2226void ItaniumRecordLayoutBuilder::CheckFieldPadding(
2227 uint64_t Offset, uint64_t UnpaddedOffset, uint64_t UnpackedOffset,
2228 unsigned UnpackedAlign, bool isPacked, const FieldDecl *D) {
2229 // We let objc ivars without warning, objc interfaces generally are not used
2230 // for padding tricks.
2231 if (isa<ObjCIvarDecl>(D))
2232 return;
2233
2234 // Don't warn about structs created without a SourceLocation. This can
2235 // be done by clients of the AST, such as codegen.
2236 if (D->getLocation().isInvalid())
2237 return;
2238
2239 unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
2240
2241 // Warn if padding was introduced to the struct/class.
2242 if (!IsUnion && Offset > UnpaddedOffset) {
2243 unsigned PadSize = Offset - UnpaddedOffset;
2244 bool InBits = true;
2245 if (PadSize % CharBitNum == 0) {
2246 PadSize = PadSize / CharBitNum;
2247 InBits = false;
2248 }
2249 if (D->getIdentifier())
2250 Diag(D->getLocation(), diag::warn_padded_struct_field)
2251 << getPaddingDiagFromTagKind(D->getParent()->getTagKind())
2252 << Context.getTypeDeclType(D->getParent())
2253 << PadSize
2254 << (InBits ? 1 : 0) // (byte|bit)
2255 << D->getIdentifier();
2256 else
2257 Diag(D->getLocation(), diag::warn_padded_struct_anon_field)
2258 << getPaddingDiagFromTagKind(D->getParent()->getTagKind())
2259 << Context.getTypeDeclType(D->getParent())
2260 << PadSize
2261 << (InBits ? 1 : 0); // (byte|bit)
2262 }
2263 if (isPacked && Offset != UnpackedOffset) {
2264 HasPackedField = true;
2265 }
2266}
2267
2268static const CXXMethodDecl *computeKeyFunction(ASTContext &Context,
2269 const CXXRecordDecl *RD) {
2270 // If a class isn't polymorphic it doesn't have a key function.
2271 if (!RD->isPolymorphic())
2272 return nullptr;
2273
2274 // A class that is not externally visible doesn't have a key function. (Or
2275 // at least, there's no point to assigning a key function to such a class;
2276 // this doesn't affect the ABI.)
2277 if (!RD->isExternallyVisible())
2278 return nullptr;
2279
2280 // Template instantiations don't have key functions per Itanium C++ ABI 5.2.6.
2281 // Same behavior as GCC.
2282 TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
2283 if (TSK == TSK_ImplicitInstantiation ||
2284 TSK == TSK_ExplicitInstantiationDeclaration ||
2285 TSK == TSK_ExplicitInstantiationDefinition)
2286 return nullptr;
2287
2288 bool allowInlineFunctions =
2289 Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline();
2290
2291 for (const CXXMethodDecl *MD : RD->methods()) {
2292 if (!MD->isVirtual())
2293 continue;
2294
2295 if (MD->isPure())
2296 continue;
2297
2298 // Ignore implicit member functions, they are always marked as inline, but
2299 // they don't have a body until they're defined.
2300 if (MD->isImplicit())
2301 continue;
2302
2303 if (MD->isInlineSpecified() || MD->isConstexpr())
2304 continue;
2305
2306 if (MD->hasInlineBody())
2307 continue;
2308
2309 // Ignore inline deleted or defaulted functions.
2310 if (!MD->isUserProvided())
2311 continue;
2312
2313 // In certain ABIs, ignore functions with out-of-line inline definitions.
2314 if (!allowInlineFunctions) {
2315 const FunctionDecl *Def;
2316 if (MD->hasBody(Def) && Def->isInlineSpecified())
2317 continue;
2318 }
2319
2320 if (Context.getLangOpts().CUDA) {
2321 // While compiler may see key method in this TU, during CUDA
2322 // compilation we should ignore methods that are not accessible
2323 // on this side of compilation.
2324 if (Context.getLangOpts().CUDAIsDevice) {
2325 // In device mode ignore methods without __device__ attribute.
2326 if (!MD->hasAttr<CUDADeviceAttr>())
2327 continue;
2328 } else {
2329 // In host mode ignore __device__-only methods.
2330 if (!MD->hasAttr<CUDAHostAttr>() && MD->hasAttr<CUDADeviceAttr>())
2331 continue;
2332 }
2333 }
2334
2335 // If the key function is dllimport but the class isn't, then the class has
2336 // no key function. The DLL that exports the key function won't export the
2337 // vtable in this case.
2338 if (MD->hasAttr<DLLImportAttr>() && !RD->hasAttr<DLLImportAttr>() &&
2339 !Context.getTargetInfo().hasPS4DLLImportExport())
2340 return nullptr;
2341
2342 // We found it.
2343 return MD;
2344 }
2345
2346 return nullptr;
2347}
2348
2349DiagnosticBuilder ItaniumRecordLayoutBuilder::Diag(SourceLocation Loc,
2350 unsigned DiagID) {
2351 return Context.getDiagnostics().Report(Loc, DiagID);
2352}
2353
2354/// Does the target C++ ABI require us to skip over the tail-padding
2355/// of the given class (considering it as a base class) when allocating
2356/// objects?
2357static bool mustSkipTailPadding(TargetCXXABI ABI, const CXXRecordDecl *RD) {
2358 switch (ABI.getTailPaddingUseRules()) {
2359 case TargetCXXABI::AlwaysUseTailPadding:
2360 return false;
2361
2362 case TargetCXXABI::UseTailPaddingUnlessPOD03:
2363 // FIXME: To the extent that this is meant to cover the Itanium ABI
2364 // rules, we should implement the restrictions about over-sized
2365 // bitfields:
2366 //
2367 // http://itanium-cxx-abi.github.io/cxx-abi/abi.html#POD :
2368 // In general, a type is considered a POD for the purposes of
2369 // layout if it is a POD type (in the sense of ISO C++
2370 // [basic.types]). However, a POD-struct or POD-union (in the
2371 // sense of ISO C++ [class]) with a bitfield member whose
2372 // declared width is wider than the declared type of the
2373 // bitfield is not a POD for the purpose of layout. Similarly,
2374 // an array type is not a POD for the purpose of layout if the
2375 // element type of the array is not a POD for the purpose of
2376 // layout.
2377 //
2378 // Where references to the ISO C++ are made in this paragraph,
2379 // the Technical Corrigendum 1 version of the standard is
2380 // intended.
2381 return RD->isPOD();
2382
2383 case TargetCXXABI::UseTailPaddingUnlessPOD11:
2384 // This is equivalent to RD->getTypeForDecl().isCXX11PODType(),
2385 // but with a lot of abstraction penalty stripped off. This does
2386 // assume that these properties are set correctly even in C++98
2387 // mode; fortunately, that is true because we want to assign
2388 // consistently semantics to the type-traits intrinsics (or at
2389 // least as many of them as possible).
2390 return RD->isTrivial() && RD->isCXX11StandardLayout();
2391 }
2392
2393 llvm_unreachable("bad tail-padding use kind")::llvm::llvm_unreachable_internal("bad tail-padding use kind"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 2393)
;
2394}
2395
2396static bool isMsLayout(const ASTContext &Context) {
2397 return Context.getTargetInfo().getCXXABI().isMicrosoft();
2398}
2399
2400// This section contains an implementation of struct layout that is, up to the
2401// included tests, compatible with cl.exe (2013). The layout produced is
2402// significantly different than those produced by the Itanium ABI. Here we note
2403// the most important differences.
2404//
2405// * The alignment of bitfields in unions is ignored when computing the
2406// alignment of the union.
2407// * The existence of zero-width bitfield that occurs after anything other than
2408// a non-zero length bitfield is ignored.
2409// * There is no explicit primary base for the purposes of layout. All bases
2410// with vfptrs are laid out first, followed by all bases without vfptrs.
2411// * The Itanium equivalent vtable pointers are split into a vfptr (virtual
2412// function pointer) and a vbptr (virtual base pointer). They can each be
2413// shared with a, non-virtual bases. These bases need not be the same. vfptrs
2414// always occur at offset 0. vbptrs can occur at an arbitrary offset and are
2415// placed after the lexicographically last non-virtual base. This placement
2416// is always before fields but can be in the middle of the non-virtual bases
2417// due to the two-pass layout scheme for non-virtual-bases.
2418// * Virtual bases sometimes require a 'vtordisp' field that is laid out before
2419// the virtual base and is used in conjunction with virtual overrides during
2420// construction and destruction. This is always a 4 byte value and is used as
2421// an alternative to constructor vtables.
2422// * vtordisps are allocated in a block of memory with size and alignment equal
2423// to the alignment of the completed structure (before applying __declspec(
2424// align())). The vtordisp always occur at the end of the allocation block,
2425// immediately prior to the virtual base.
2426// * vfptrs are injected after all bases and fields have been laid out. In
2427// order to guarantee proper alignment of all fields, the vfptr injection
2428// pushes all bases and fields back by the alignment imposed by those bases
2429// and fields. This can potentially add a significant amount of padding.
2430// vfptrs are always injected at offset 0.
2431// * vbptrs are injected after all bases and fields have been laid out. In
2432// order to guarantee proper alignment of all fields, the vfptr injection
2433// pushes all bases and fields back by the alignment imposed by those bases
2434// and fields. This can potentially add a significant amount of padding.
2435// vbptrs are injected immediately after the last non-virtual base as
2436// lexicographically ordered in the code. If this site isn't pointer aligned
2437// the vbptr is placed at the next properly aligned location. Enough padding
2438// is added to guarantee a fit.
2439// * The last zero sized non-virtual base can be placed at the end of the
2440// struct (potentially aliasing another object), or may alias with the first
2441// field, even if they are of the same type.
2442// * The last zero size virtual base may be placed at the end of the struct
2443// potentially aliasing another object.
2444// * The ABI attempts to avoid aliasing of zero sized bases by adding padding
2445// between bases or vbases with specific properties. The criteria for
2446// additional padding between two bases is that the first base is zero sized
2447// or ends with a zero sized subobject and the second base is zero sized or
2448// trails with a zero sized base or field (sharing of vfptrs can reorder the
2449// layout of the so the leading base is not always the first one declared).
2450// This rule does take into account fields that are not records, so padding
2451// will occur even if the last field is, e.g. an int. The padding added for
2452// bases is 1 byte. The padding added between vbases depends on the alignment
2453// of the object but is at least 4 bytes (in both 32 and 64 bit modes).
2454// * There is no concept of non-virtual alignment, non-virtual alignment and
2455// alignment are always identical.
2456// * There is a distinction between alignment and required alignment.
2457// __declspec(align) changes the required alignment of a struct. This
2458// alignment is _always_ obeyed, even in the presence of #pragma pack. A
2459// record inherits required alignment from all of its fields and bases.
2460// * __declspec(align) on bitfields has the effect of changing the bitfield's
2461// alignment instead of its required alignment. This is the only known way
2462// to make the alignment of a struct bigger than 8. Interestingly enough
2463// this alignment is also immune to the effects of #pragma pack and can be
2464// used to create structures with large alignment under #pragma pack.
2465// However, because it does not impact required alignment, such a structure,
2466// when used as a field or base, will not be aligned if #pragma pack is
2467// still active at the time of use.
2468//
2469// Known incompatibilities:
2470// * all: #pragma pack between fields in a record
2471// * 2010 and back: If the last field in a record is a bitfield, every object
2472// laid out after the record will have extra padding inserted before it. The
2473// extra padding will have size equal to the size of the storage class of the
2474// bitfield. 0 sized bitfields don't exhibit this behavior and the extra
2475// padding can be avoided by adding a 0 sized bitfield after the non-zero-
2476// sized bitfield.
2477// * 2012 and back: In 64-bit mode, if the alignment of a record is 16 or
2478// greater due to __declspec(align()) then a second layout phase occurs after
2479// The locations of the vf and vb pointers are known. This layout phase
2480// suffers from the "last field is a bitfield" bug in 2010 and results in
2481// _every_ field getting padding put in front of it, potentially including the
2482// vfptr, leaving the vfprt at a non-zero location which results in a fault if
2483// anything tries to read the vftbl. The second layout phase also treats
2484// bitfields as separate entities and gives them each storage rather than
2485// packing them. Additionally, because this phase appears to perform a
2486// (an unstable) sort on the members before laying them out and because merged
2487// bitfields have the same address, the bitfields end up in whatever order
2488// the sort left them in, a behavior we could never hope to replicate.
2489
2490namespace {
2491struct MicrosoftRecordLayoutBuilder {
2492 struct ElementInfo {
2493 CharUnits Size;
2494 CharUnits Alignment;
2495 };
2496 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy;
2497 MicrosoftRecordLayoutBuilder(const ASTContext &Context) : Context(Context) {}
2498private:
2499 MicrosoftRecordLayoutBuilder(const MicrosoftRecordLayoutBuilder &) = delete;
2500 void operator=(const MicrosoftRecordLayoutBuilder &) = delete;
2501public:
2502 void layout(const RecordDecl *RD);
2503 void cxxLayout(const CXXRecordDecl *RD);
2504 /// Initializes size and alignment and honors some flags.
2505 void initializeLayout(const RecordDecl *RD);
2506 /// Initialized C++ layout, compute alignment and virtual alignment and
2507 /// existence of vfptrs and vbptrs. Alignment is needed before the vfptr is
2508 /// laid out.
2509 void initializeCXXLayout(const CXXRecordDecl *RD);
2510 void layoutNonVirtualBases(const CXXRecordDecl *RD);
2511 void layoutNonVirtualBase(const CXXRecordDecl *RD,
2512 const CXXRecordDecl *BaseDecl,
2513 const ASTRecordLayout &BaseLayout,
2514 const ASTRecordLayout *&PreviousBaseLayout);
2515 void injectVFPtr(const CXXRecordDecl *RD);
2516 void injectVBPtr(const CXXRecordDecl *RD);
2517 /// Lays out the fields of the record. Also rounds size up to
2518 /// alignment.
2519 void layoutFields(const RecordDecl *RD);
2520 void layoutField(const FieldDecl *FD);
2521 void layoutBitField(const FieldDecl *FD);
2522 /// Lays out a single zero-width bit-field in the record and handles
2523 /// special cases associated with zero-width bit-fields.
2524 void layoutZeroWidthBitField(const FieldDecl *FD);
2525 void layoutVirtualBases(const CXXRecordDecl *RD);
2526 void finalizeLayout(const RecordDecl *RD);
2527 /// Gets the size and alignment of a base taking pragma pack and
2528 /// __declspec(align) into account.
2529 ElementInfo getAdjustedElementInfo(const ASTRecordLayout &Layout);
2530 /// Gets the size and alignment of a field taking pragma pack and
2531 /// __declspec(align) into account. It also updates RequiredAlignment as a
2532 /// side effect because it is most convenient to do so here.
2533 ElementInfo getAdjustedElementInfo(const FieldDecl *FD);
2534 /// Places a field at an offset in CharUnits.
2535 void placeFieldAtOffset(CharUnits FieldOffset) {
2536 FieldOffsets.push_back(Context.toBits(FieldOffset));
2537 }
2538 /// Places a bitfield at a bit offset.
2539 void placeFieldAtBitOffset(uint64_t FieldOffset) {
2540 FieldOffsets.push_back(FieldOffset);
2541 }
2542 /// Compute the set of virtual bases for which vtordisps are required.
2543 void computeVtorDispSet(
2544 llvm::SmallPtrSetImpl<const CXXRecordDecl *> &HasVtorDispSet,
2545 const CXXRecordDecl *RD) const;
2546 const ASTContext &Context;
2547 /// The size of the record being laid out.
2548 CharUnits Size;
2549 /// The non-virtual size of the record layout.
2550 CharUnits NonVirtualSize;
2551 /// The data size of the record layout.
2552 CharUnits DataSize;
2553 /// The current alignment of the record layout.
2554 CharUnits Alignment;
2555 /// The maximum allowed field alignment. This is set by #pragma pack.
2556 CharUnits MaxFieldAlignment;
2557 /// The alignment that this record must obey. This is imposed by
2558 /// __declspec(align()) on the record itself or one of its fields or bases.
2559 CharUnits RequiredAlignment;
2560 /// The size of the allocation of the currently active bitfield.
2561 /// This value isn't meaningful unless LastFieldIsNonZeroWidthBitfield
2562 /// is true.
2563 CharUnits CurrentBitfieldSize;
2564 /// Offset to the virtual base table pointer (if one exists).
2565 CharUnits VBPtrOffset;
2566 /// Minimum record size possible.
2567 CharUnits MinEmptyStructSize;
2568 /// The size and alignment info of a pointer.
2569 ElementInfo PointerInfo;
2570 /// The primary base class (if one exists).
2571 const CXXRecordDecl *PrimaryBase;
2572 /// The class we share our vb-pointer with.
2573 const CXXRecordDecl *SharedVBPtrBase;
2574 /// The collection of field offsets.
2575 SmallVector<uint64_t, 16> FieldOffsets;
2576 /// Base classes and their offsets in the record.
2577 BaseOffsetsMapTy Bases;
2578 /// virtual base classes and their offsets in the record.
2579 ASTRecordLayout::VBaseOffsetsMapTy VBases;
2580 /// The number of remaining bits in our last bitfield allocation.
2581 /// This value isn't meaningful unless LastFieldIsNonZeroWidthBitfield is
2582 /// true.
2583 unsigned RemainingBitsInField;
2584 bool IsUnion : 1;
2585 /// True if the last field laid out was a bitfield and was not 0
2586 /// width.
2587 bool LastFieldIsNonZeroWidthBitfield : 1;
2588 /// True if the class has its own vftable pointer.
2589 bool HasOwnVFPtr : 1;
2590 /// True if the class has a vbtable pointer.
2591 bool HasVBPtr : 1;
2592 /// True if the last sub-object within the type is zero sized or the
2593 /// object itself is zero sized. This *does not* count members that are not
2594 /// records. Only used for MS-ABI.
2595 bool EndsWithZeroSizedObject : 1;
2596 /// True if this class is zero sized or first base is zero sized or
2597 /// has this property. Only used for MS-ABI.
2598 bool LeadsWithZeroSizedBase : 1;
2599
2600 /// True if the external AST source provided a layout for this record.
2601 bool UseExternalLayout : 1;
2602
2603 /// The layout provided by the external AST source. Only active if
2604 /// UseExternalLayout is true.
2605 ExternalLayout External;
2606};
2607} // namespace
2608
2609MicrosoftRecordLayoutBuilder::ElementInfo
2610MicrosoftRecordLayoutBuilder::getAdjustedElementInfo(
2611 const ASTRecordLayout &Layout) {
2612 ElementInfo Info;
2613 Info.Alignment = Layout.getAlignment();
2614 // Respect pragma pack.
2615 if (!MaxFieldAlignment.isZero())
2616 Info.Alignment = std::min(Info.Alignment, MaxFieldAlignment);
2617 // Track zero-sized subobjects here where it's already available.
2618 EndsWithZeroSizedObject = Layout.endsWithZeroSizedObject();
2619 // Respect required alignment, this is necessary because we may have adjusted
2620 // the alignment in the case of pragam pack. Note that the required alignment
2621 // doesn't actually apply to the struct alignment at this point.
2622 Alignment = std::max(Alignment, Info.Alignment);
2623 RequiredAlignment = std::max(RequiredAlignment, Layout.getRequiredAlignment());
2624 Info.Alignment = std::max(Info.Alignment, Layout.getRequiredAlignment());
2625 Info.Size = Layout.getNonVirtualSize();
2626 return Info;
2627}
2628
2629MicrosoftRecordLayoutBuilder::ElementInfo
2630MicrosoftRecordLayoutBuilder::getAdjustedElementInfo(
2631 const FieldDecl *FD) {
2632 // Get the alignment of the field type's natural alignment, ignore any
2633 // alignment attributes.
2634 auto TInfo =
2635 Context.getTypeInfoInChars(FD->getType()->getUnqualifiedDesugaredType());
2636 ElementInfo Info{TInfo.Width, TInfo.Align};
2637 // Respect align attributes on the field.
2638 CharUnits FieldRequiredAlignment =
2639 Context.toCharUnitsFromBits(FD->getMaxAlignment());
2640 // Respect align attributes on the type.
2641 if (Context.isAlignmentRequired(FD->getType()))
2642 FieldRequiredAlignment = std::max(
2643 Context.getTypeAlignInChars(FD->getType()), FieldRequiredAlignment);
2644 // Respect attributes applied to subobjects of the field.
2645 if (FD->isBitField())
2646 // For some reason __declspec align impacts alignment rather than required
2647 // alignment when it is applied to bitfields.
2648 Info.Alignment = std::max(Info.Alignment, FieldRequiredAlignment);
2649 else {
2650 if (auto RT =
2651 FD->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
2652 auto const &Layout = Context.getASTRecordLayout(RT->getDecl());
2653 EndsWithZeroSizedObject = Layout.endsWithZeroSizedObject();
2654 FieldRequiredAlignment = std::max(FieldRequiredAlignment,
2655 Layout.getRequiredAlignment());
2656 }
2657 // Capture required alignment as a side-effect.
2658 RequiredAlignment = std::max(RequiredAlignment, FieldRequiredAlignment);
2659 }
2660 // Respect pragma pack, attribute pack and declspec align
2661 if (!MaxFieldAlignment.isZero())
2662 Info.Alignment = std::min(Info.Alignment, MaxFieldAlignment);
2663 if (FD->hasAttr<PackedAttr>())
2664 Info.Alignment = CharUnits::One();
2665 Info.Alignment = std::max(Info.Alignment, FieldRequiredAlignment);
2666 return Info;
2667}
2668
2669void MicrosoftRecordLayoutBuilder::layout(const RecordDecl *RD) {
2670 // For C record layout, zero-sized records always have size 4.
2671 MinEmptyStructSize = CharUnits::fromQuantity(4);
2672 initializeLayout(RD);
2673 layoutFields(RD);
2674 DataSize = Size = Size.alignTo(Alignment);
2675 RequiredAlignment = std::max(
2676 RequiredAlignment, Context.toCharUnitsFromBits(RD->getMaxAlignment()));
2677 finalizeLayout(RD);
2678}
2679
2680void MicrosoftRecordLayoutBuilder::cxxLayout(const CXXRecordDecl *RD) {
2681 // The C++ standard says that empty structs have size 1.
2682 MinEmptyStructSize = CharUnits::One();
2683 initializeLayout(RD);
2684 initializeCXXLayout(RD);
2685 layoutNonVirtualBases(RD);
2686 layoutFields(RD);
2687 injectVBPtr(RD);
2688 injectVFPtr(RD);
2689 if (HasOwnVFPtr || (HasVBPtr && !SharedVBPtrBase))
2690 Alignment = std::max(Alignment, PointerInfo.Alignment);
2691 auto RoundingAlignment = Alignment;
2692 if (!MaxFieldAlignment.isZero())
2693 RoundingAlignment = std::min(RoundingAlignment, MaxFieldAlignment);
2694 if (!UseExternalLayout)
2695 Size = Size.alignTo(RoundingAlignment);
2696 NonVirtualSize = Size;
2697 RequiredAlignment = std::max(
2698 RequiredAlignment, Context.toCharUnitsFromBits(RD->getMaxAlignment()));
2699 layoutVirtualBases(RD);
2700 finalizeLayout(RD);
2701}
2702
2703void MicrosoftRecordLayoutBuilder::initializeLayout(const RecordDecl *RD) {
2704 IsUnion = RD->isUnion();
2705 Size = CharUnits::Zero();
2706 Alignment = CharUnits::One();
2707 // In 64-bit mode we always perform an alignment step after laying out vbases.
2708 // In 32-bit mode we do not. The check to see if we need to perform alignment
2709 // checks the RequiredAlignment field and performs alignment if it isn't 0.
2710 RequiredAlignment = Context.getTargetInfo().getTriple().isArch64Bit()
2711 ? CharUnits::One()
2712 : CharUnits::Zero();
2713 // Compute the maximum field alignment.
2714 MaxFieldAlignment = CharUnits::Zero();
2715 // Honor the default struct packing maximum alignment flag.
2716 if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct)
2717 MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment);
2718 // Honor the packing attribute. The MS-ABI ignores pragma pack if its larger
2719 // than the pointer size.
2720 if (const MaxFieldAlignmentAttr *MFAA = RD->getAttr<MaxFieldAlignmentAttr>()){
2721 unsigned PackedAlignment = MFAA->getAlignment();
2722 if (PackedAlignment <= Context.getTargetInfo().getPointerWidth(0))
2723 MaxFieldAlignment = Context.toCharUnitsFromBits(PackedAlignment);
2724 }
2725 // Packed attribute forces max field alignment to be 1.
2726 if (RD->hasAttr<PackedAttr>())
2727 MaxFieldAlignment = CharUnits::One();
2728
2729 // Try to respect the external layout if present.
2730 UseExternalLayout = false;
2731 if (ExternalASTSource *Source = Context.getExternalSource())
2732 UseExternalLayout = Source->layoutRecordType(
2733 RD, External.Size, External.Align, External.FieldOffsets,
2734 External.BaseOffsets, External.VirtualBaseOffsets);
2735}
2736
2737void
2738MicrosoftRecordLayoutBuilder::initializeCXXLayout(const CXXRecordDecl *RD) {
2739 EndsWithZeroSizedObject = false;
2740 LeadsWithZeroSizedBase = false;
2741 HasOwnVFPtr = false;
2742 HasVBPtr = false;
2743 PrimaryBase = nullptr;
2744 SharedVBPtrBase = nullptr;
2745 // Calculate pointer size and alignment. These are used for vfptr and vbprt
2746 // injection.
2747 PointerInfo.Size =
2748 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
2749 PointerInfo.Alignment =
2750 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(0));
2751 // Respect pragma pack.
2752 if (!MaxFieldAlignment.isZero())
2753 PointerInfo.Alignment = std::min(PointerInfo.Alignment, MaxFieldAlignment);
2754}
2755
2756void
2757MicrosoftRecordLayoutBuilder::layoutNonVirtualBases(const CXXRecordDecl *RD) {
2758 // The MS-ABI lays out all bases that contain leading vfptrs before it lays
2759 // out any bases that do not contain vfptrs. We implement this as two passes
2760 // over the bases. This approach guarantees that the primary base is laid out
2761 // first. We use these passes to calculate some additional aggregated
2762 // information about the bases, such as required alignment and the presence of
2763 // zero sized members.
2764 const ASTRecordLayout *PreviousBaseLayout = nullptr;
2765 bool HasPolymorphicBaseClass = false;
2766 // Iterate through the bases and lay out the non-virtual ones.
2767 for (const CXXBaseSpecifier &Base : RD->bases()) {
2768 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
2769 HasPolymorphicBaseClass |= BaseDecl->isPolymorphic();
2770 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
2771 // Mark and skip virtual bases.
2772 if (Base.isVirtual()) {
2773 HasVBPtr = true;
2774 continue;
2775 }
2776 // Check for a base to share a VBPtr with.
2777 if (!SharedVBPtrBase && BaseLayout.hasVBPtr()) {
2778 SharedVBPtrBase = BaseDecl;
2779 HasVBPtr = true;
2780 }
2781 // Only lay out bases with extendable VFPtrs on the first pass.
2782 if (!BaseLayout.hasExtendableVFPtr())
2783 continue;
2784 // If we don't have a primary base, this one qualifies.
2785 if (!PrimaryBase) {
2786 PrimaryBase = BaseDecl;
2787 LeadsWithZeroSizedBase = BaseLayout.leadsWithZeroSizedBase();
2788 }
2789 // Lay out the base.
2790 layoutNonVirtualBase(RD, BaseDecl, BaseLayout, PreviousBaseLayout);
2791 }
2792 // Figure out if we need a fresh VFPtr for this class.
2793 if (RD->isPolymorphic()) {
2794 if (!HasPolymorphicBaseClass)
2795 // This class introduces polymorphism, so we need a vftable to store the
2796 // RTTI information.
2797 HasOwnVFPtr = true;
2798 else if (!PrimaryBase) {
2799 // We have a polymorphic base class but can't extend its vftable. Add a
2800 // new vfptr if we would use any vftable slots.
2801 for (CXXMethodDecl *M : RD->methods()) {
2802 if (MicrosoftVTableContext::hasVtableSlot(M) &&
2803 M->size_overridden_methods() == 0) {
2804 HasOwnVFPtr = true;
2805 break;
2806 }
2807 }
2808 }
2809 }
2810 // If we don't have a primary base then we have a leading object that could
2811 // itself lead with a zero-sized object, something we track.
2812 bool CheckLeadingLayout = !PrimaryBase;
2813 // Iterate through the bases and lay out the non-virtual ones.
2814 for (const CXXBaseSpecifier &Base : RD->bases()) {
2815 if (Base.isVirtual())
2816 continue;
2817 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
2818 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
2819 // Only lay out bases without extendable VFPtrs on the second pass.
2820 if (BaseLayout.hasExtendableVFPtr()) {
2821 VBPtrOffset = Bases[BaseDecl] + BaseLayout.getNonVirtualSize();
2822 continue;
2823 }
2824 // If this is the first layout, check to see if it leads with a zero sized
2825 // object. If it does, so do we.
2826 if (CheckLeadingLayout) {
2827 CheckLeadingLayout = false;
2828 LeadsWithZeroSizedBase = BaseLayout.leadsWithZeroSizedBase();
2829 }
2830 // Lay out the base.
2831 layoutNonVirtualBase(RD, BaseDecl, BaseLayout, PreviousBaseLayout);
2832 VBPtrOffset = Bases[BaseDecl] + BaseLayout.getNonVirtualSize();
2833 }
2834 // Set our VBPtroffset if we know it at this point.
2835 if (!HasVBPtr)
2836 VBPtrOffset = CharUnits::fromQuantity(-1);
2837 else if (SharedVBPtrBase) {
2838 const ASTRecordLayout &Layout = Context.getASTRecordLayout(SharedVBPtrBase);
2839 VBPtrOffset = Bases[SharedVBPtrBase] + Layout.getVBPtrOffset();
2840 }
2841}
2842
2843static bool recordUsesEBO(const RecordDecl *RD) {
2844 if (!isa<CXXRecordDecl>(RD))
2845 return false;
2846 if (RD->hasAttr<EmptyBasesAttr>())
2847 return true;
2848 if (auto *LVA = RD->getAttr<LayoutVersionAttr>())
2849 // TODO: Double check with the next version of MSVC.
2850 if (LVA->getVersion() <= LangOptions::MSVC2015)
2851 return false;
2852 // TODO: Some later version of MSVC will change the default behavior of the
2853 // compiler to enable EBO by default. When this happens, we will need an
2854 // additional isCompatibleWithMSVC check.
2855 return false;
2856}
2857
2858void MicrosoftRecordLayoutBuilder::layoutNonVirtualBase(
2859 const CXXRecordDecl *RD,
2860 const CXXRecordDecl *BaseDecl,
2861 const ASTRecordLayout &BaseLayout,
2862 const ASTRecordLayout *&PreviousBaseLayout) {
2863 // Insert padding between two bases if the left first one is zero sized or
2864 // contains a zero sized subobject and the right is zero sized or one leads
2865 // with a zero sized base.
2866 bool MDCUsesEBO = recordUsesEBO(RD);
2867 if (PreviousBaseLayout && PreviousBaseLayout->endsWithZeroSizedObject() &&
2868 BaseLayout.leadsWithZeroSizedBase() && !MDCUsesEBO)
2869 Size++;
2870 ElementInfo Info = getAdjustedElementInfo(BaseLayout);
2871 CharUnits BaseOffset;
2872
2873 // Respect the external AST source base offset, if present.
2874 bool FoundBase = false;
2875 if (UseExternalLayout) {
2876 FoundBase = External.getExternalNVBaseOffset(BaseDecl, BaseOffset);
2877 if (FoundBase) {
2878 assert(BaseOffset >= Size && "base offset already allocated")(static_cast <bool> (BaseOffset >= Size && "base offset already allocated"
) ? void (0) : __assert_fail ("BaseOffset >= Size && \"base offset already allocated\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 2878, __extension__ __PRETTY_FUNCTION__))
;
2879 Size = BaseOffset;
2880 }
2881 }
2882
2883 if (!FoundBase) {
2884 if (MDCUsesEBO && BaseDecl->isEmpty()) {
2885 assert(BaseLayout.getNonVirtualSize() == CharUnits::Zero())(static_cast <bool> (BaseLayout.getNonVirtualSize() == CharUnits
::Zero()) ? void (0) : __assert_fail ("BaseLayout.getNonVirtualSize() == CharUnits::Zero()"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 2885, __extension__ __PRETTY_FUNCTION__))
;
2886 BaseOffset = CharUnits::Zero();
2887 } else {
2888 // Otherwise, lay the base out at the end of the MDC.
2889 BaseOffset = Size = Size.alignTo(Info.Alignment);
2890 }
2891 }
2892 Bases.insert(std::make_pair(BaseDecl, BaseOffset));
2893 Size += BaseLayout.getNonVirtualSize();
2894 PreviousBaseLayout = &BaseLayout;
2895}
2896
2897void MicrosoftRecordLayoutBuilder::layoutFields(const RecordDecl *RD) {
2898 LastFieldIsNonZeroWidthBitfield = false;
2899 for (const FieldDecl *Field : RD->fields())
2900 layoutField(Field);
2901}
2902
2903void MicrosoftRecordLayoutBuilder::layoutField(const FieldDecl *FD) {
2904 if (FD->isBitField()) {
2905 layoutBitField(FD);
2906 return;
2907 }
2908 LastFieldIsNonZeroWidthBitfield = false;
2909 ElementInfo Info = getAdjustedElementInfo(FD);
2910 Alignment = std::max(Alignment, Info.Alignment);
2911 CharUnits FieldOffset;
2912 if (UseExternalLayout)
2913 FieldOffset =
2914 Context.toCharUnitsFromBits(External.getExternalFieldOffset(FD));
2915 else if (IsUnion)
2916 FieldOffset = CharUnits::Zero();
2917 else
2918 FieldOffset = Size.alignTo(Info.Alignment);
2919 placeFieldAtOffset(FieldOffset);
2920 Size = std::max(Size, FieldOffset + Info.Size);
2921}
2922
2923void MicrosoftRecordLayoutBuilder::layoutBitField(const FieldDecl *FD) {
2924 unsigned Width = FD->getBitWidthValue(Context);
2925 if (Width == 0) {
2926 layoutZeroWidthBitField(FD);
2927 return;
2928 }
2929 ElementInfo Info = getAdjustedElementInfo(FD);
2930 // Clamp the bitfield to a containable size for the sake of being able
2931 // to lay them out. Sema will throw an error.
2932 if (Width > Context.toBits(Info.Size))
2933 Width = Context.toBits(Info.Size);
2934 // Check to see if this bitfield fits into an existing allocation. Note:
2935 // MSVC refuses to pack bitfields of formal types with different sizes
2936 // into the same allocation.
2937 if (!UseExternalLayout && !IsUnion && LastFieldIsNonZeroWidthBitfield &&
2938 CurrentBitfieldSize == Info.Size && Width <= RemainingBitsInField) {
2939 placeFieldAtBitOffset(Context.toBits(Size) - RemainingBitsInField);
2940 RemainingBitsInField -= Width;
2941 return;
2942 }
2943 LastFieldIsNonZeroWidthBitfield = true;
2944 CurrentBitfieldSize = Info.Size;
2945 if (UseExternalLayout) {
2946 auto FieldBitOffset = External.getExternalFieldOffset(FD);
2947 placeFieldAtBitOffset(FieldBitOffset);
2948 auto NewSize = Context.toCharUnitsFromBits(
2949 llvm::alignDown(FieldBitOffset, Context.toBits(Info.Alignment)) +
2950 Context.toBits(Info.Size));
2951 Size = std::max(Size, NewSize);
2952 Alignment = std::max(Alignment, Info.Alignment);
2953 } else if (IsUnion) {
2954 placeFieldAtOffset(CharUnits::Zero());
2955 Size = std::max(Size, Info.Size);
2956 // TODO: Add a Sema warning that MS ignores bitfield alignment in unions.
2957 } else {
2958 // Allocate a new block of memory and place the bitfield in it.
2959 CharUnits FieldOffset = Size.alignTo(Info.Alignment);
2960 placeFieldAtOffset(FieldOffset);
2961 Size = FieldOffset + Info.Size;
2962 Alignment = std::max(Alignment, Info.Alignment);
2963 RemainingBitsInField = Context.toBits(Info.Size) - Width;
2964 }
2965}
2966
2967void
2968MicrosoftRecordLayoutBuilder::layoutZeroWidthBitField(const FieldDecl *FD) {
2969 // Zero-width bitfields are ignored unless they follow a non-zero-width
2970 // bitfield.
2971 if (!LastFieldIsNonZeroWidthBitfield) {
2972 placeFieldAtOffset(IsUnion ? CharUnits::Zero() : Size);
2973 // TODO: Add a Sema warning that MS ignores alignment for zero
2974 // sized bitfields that occur after zero-size bitfields or non-bitfields.
2975 return;
2976 }
2977 LastFieldIsNonZeroWidthBitfield = false;
2978 ElementInfo Info = getAdjustedElementInfo(FD);
2979 if (IsUnion) {
2980 placeFieldAtOffset(CharUnits::Zero());
2981 Size = std::max(Size, Info.Size);
2982 // TODO: Add a Sema warning that MS ignores bitfield alignment in unions.
2983 } else {
2984 // Round up the current record size to the field's alignment boundary.
2985 CharUnits FieldOffset = Size.alignTo(Info.Alignment);
2986 placeFieldAtOffset(FieldOffset);
2987 Size = FieldOffset;
2988 Alignment = std::max(Alignment, Info.Alignment);
2989 }
2990}
2991
2992void MicrosoftRecordLayoutBuilder::injectVBPtr(const CXXRecordDecl *RD) {
2993 if (!HasVBPtr || SharedVBPtrBase)
2994 return;
2995 // Inject the VBPointer at the injection site.
2996 CharUnits InjectionSite = VBPtrOffset;
2997 // But before we do, make sure it's properly aligned.
2998 VBPtrOffset = VBPtrOffset.alignTo(PointerInfo.Alignment);
2999 // Determine where the first field should be laid out after the vbptr.
3000 CharUnits FieldStart = VBPtrOffset + PointerInfo.Size;
3001 // Shift everything after the vbptr down, unless we're using an external
3002 // layout.
3003 if (UseExternalLayout) {
3004 // It is possible that there were no fields or bases located after vbptr,
3005 // so the size was not adjusted before.
3006 if (Size < FieldStart)
3007 Size = FieldStart;
3008 return;
3009 }
3010 // Make sure that the amount we push the fields back by is a multiple of the
3011 // alignment.
3012 CharUnits Offset = (FieldStart - InjectionSite)
3013 .alignTo(std::max(RequiredAlignment, Alignment));
3014 Size += Offset;
3015 for (uint64_t &FieldOffset : FieldOffsets)
3016 FieldOffset += Context.toBits(Offset);
3017 for (BaseOffsetsMapTy::value_type &Base : Bases)
3018 if (Base.second >= InjectionSite)
3019 Base.second += Offset;
3020}
3021
3022void MicrosoftRecordLayoutBuilder::injectVFPtr(const CXXRecordDecl *RD) {
3023 if (!HasOwnVFPtr)
3024 return;
3025 // Make sure that the amount we push the struct back by is a multiple of the
3026 // alignment.
3027 CharUnits Offset =
3028 PointerInfo.Size.alignTo(std::max(RequiredAlignment, Alignment));
3029 // Push back the vbptr, but increase the size of the object and push back
3030 // regular fields by the offset only if not using external record layout.
3031 if (HasVBPtr)
3032 VBPtrOffset += Offset;
3033
3034 if (UseExternalLayout) {
3035 // The class may have no bases or fields, but still have a vfptr
3036 // (e.g. it's an interface class). The size was not correctly set before
3037 // in this case.
3038 if (FieldOffsets.empty() && Bases.empty())
3039 Size += Offset;
3040 return;
3041 }
3042
3043 Size += Offset;
3044
3045 // If we're using an external layout, the fields offsets have already
3046 // accounted for this adjustment.
3047 for (uint64_t &FieldOffset : FieldOffsets)
3048 FieldOffset += Context.toBits(Offset);
3049 for (BaseOffsetsMapTy::value_type &Base : Bases)
3050 Base.second += Offset;
3051}
3052
3053void MicrosoftRecordLayoutBuilder::layoutVirtualBases(const CXXRecordDecl *RD) {
3054 if (!HasVBPtr)
3055 return;
3056 // Vtordisps are always 4 bytes (even in 64-bit mode)
3057 CharUnits VtorDispSize = CharUnits::fromQuantity(4);
3058 CharUnits VtorDispAlignment = VtorDispSize;
3059 // vtordisps respect pragma pack.
3060 if (!MaxFieldAlignment.isZero())
3061 VtorDispAlignment = std::min(VtorDispAlignment, MaxFieldAlignment);
3062 // The alignment of the vtordisp is at least the required alignment of the
3063 // entire record. This requirement may be present to support vtordisp
3064 // injection.
3065 for (const CXXBaseSpecifier &VBase : RD->vbases()) {
3066 const CXXRecordDecl *BaseDecl = VBase.getType()->getAsCXXRecordDecl();
3067 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
3068 RequiredAlignment =
3069 std::max(RequiredAlignment, BaseLayout.getRequiredAlignment());
3070 }
3071 VtorDispAlignment = std::max(VtorDispAlignment, RequiredAlignment);
3072 // Compute the vtordisp set.
3073 llvm::SmallPtrSet<const CXXRecordDecl *, 2> HasVtorDispSet;
3074 computeVtorDispSet(HasVtorDispSet, RD);
3075 // Iterate through the virtual bases and lay them out.
3076 const ASTRecordLayout *PreviousBaseLayout = nullptr;
3077 for (const CXXBaseSpecifier &VBase : RD->vbases()) {
3078 const CXXRecordDecl *BaseDecl = VBase.getType()->getAsCXXRecordDecl();
3079 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
3080 bool HasVtordisp = HasVtorDispSet.count(BaseDecl) > 0;
3081 // Insert padding between two bases if the left first one is zero sized or
3082 // contains a zero sized subobject and the right is zero sized or one leads
3083 // with a zero sized base. The padding between virtual bases is 4
3084 // bytes (in both 32 and 64 bits modes) and always involves rounding up to
3085 // the required alignment, we don't know why.
3086 if ((PreviousBaseLayout && PreviousBaseLayout->endsWithZeroSizedObject() &&
3087 BaseLayout.leadsWithZeroSizedBase() && !recordUsesEBO(RD)) ||
3088 HasVtordisp) {
3089 Size = Size.alignTo(VtorDispAlignment) + VtorDispSize;
3090 Alignment = std::max(VtorDispAlignment, Alignment);
3091 }
3092 // Insert the virtual base.
3093 ElementInfo Info = getAdjustedElementInfo(BaseLayout);
3094 CharUnits BaseOffset;
3095
3096 // Respect the external AST source base offset, if present.
3097 if (UseExternalLayout) {
3098 if (!External.getExternalVBaseOffset(BaseDecl, BaseOffset))
3099 BaseOffset = Size;
3100 } else
3101 BaseOffset = Size.alignTo(Info.Alignment);
3102
3103 assert(BaseOffset >= Size && "base offset already allocated")(static_cast <bool> (BaseOffset >= Size && "base offset already allocated"
) ? void (0) : __assert_fail ("BaseOffset >= Size && \"base offset already allocated\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 3103, __extension__ __PRETTY_FUNCTION__))
;
3104
3105 VBases.insert(std::make_pair(BaseDecl,
3106 ASTRecordLayout::VBaseInfo(BaseOffset, HasVtordisp)));
3107 Size = BaseOffset + BaseLayout.getNonVirtualSize();
3108 PreviousBaseLayout = &BaseLayout;
3109 }
3110}
3111
3112void MicrosoftRecordLayoutBuilder::finalizeLayout(const RecordDecl *RD) {
3113 // Respect required alignment. Note that in 32-bit mode Required alignment
3114 // may be 0 and cause size not to be updated.
3115 DataSize = Size;
3116 if (!RequiredAlignment.isZero()) {
3117 Alignment = std::max(Alignment, RequiredAlignment);
3118 auto RoundingAlignment = Alignment;
3119 if (!MaxFieldAlignment.isZero())
3120 RoundingAlignment = std::min(RoundingAlignment, MaxFieldAlignment);
3121 RoundingAlignment = std::max(RoundingAlignment, RequiredAlignment);
3122 Size = Size.alignTo(RoundingAlignment);
3123 }
3124 if (Size.isZero()) {
3125 if (!recordUsesEBO(RD) || !cast<CXXRecordDecl>(RD)->isEmpty()) {
3126 EndsWithZeroSizedObject = true;
3127 LeadsWithZeroSizedBase = true;
3128 }
3129 // Zero-sized structures have size equal to their alignment if a
3130 // __declspec(align) came into play.
3131 if (RequiredAlignment >= MinEmptyStructSize)
3132 Size = Alignment;
3133 else
3134 Size = MinEmptyStructSize;
3135 }
3136
3137 if (UseExternalLayout) {
3138 Size = Context.toCharUnitsFromBits(External.Size);
3139 if (External.Align)
3140 Alignment = Context.toCharUnitsFromBits(External.Align);
3141 }
3142}
3143
3144// Recursively walks the non-virtual bases of a class and determines if any of
3145// them are in the bases with overridden methods set.
3146static bool
3147RequiresVtordisp(const llvm::SmallPtrSetImpl<const CXXRecordDecl *> &
3148 BasesWithOverriddenMethods,
3149 const CXXRecordDecl *RD) {
3150 if (BasesWithOverriddenMethods.count(RD))
3151 return true;
3152 // If any of a virtual bases non-virtual bases (recursively) requires a
3153 // vtordisp than so does this virtual base.
3154 for (const CXXBaseSpecifier &Base : RD->bases())
3155 if (!Base.isVirtual() &&
3156 RequiresVtordisp(BasesWithOverriddenMethods,
3157 Base.getType()->getAsCXXRecordDecl()))
3158 return true;
3159 return false;
3160}
3161
3162void MicrosoftRecordLayoutBuilder::computeVtorDispSet(
3163 llvm::SmallPtrSetImpl<const CXXRecordDecl *> &HasVtordispSet,
3164 const CXXRecordDecl *RD) const {
3165 // /vd2 or #pragma vtordisp(2): Always use vtordisps for virtual bases with
3166 // vftables.
3167 if (RD->getMSVtorDispMode() == MSVtorDispMode::ForVFTable) {
3168 for (const CXXBaseSpecifier &Base : RD->vbases()) {
3169 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
3170 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
3171 if (Layout.hasExtendableVFPtr())
3172 HasVtordispSet.insert(BaseDecl);
3173 }
3174 return;
3175 }
3176
3177 // If any of our bases need a vtordisp for this type, so do we. Check our
3178 // direct bases for vtordisp requirements.
3179 for (const CXXBaseSpecifier &Base : RD->bases()) {
3180 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
3181 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
3182 for (const auto &bi : Layout.getVBaseOffsetsMap())
3183 if (bi.second.hasVtorDisp())
3184 HasVtordispSet.insert(bi.first);
3185 }
3186 // We don't introduce any additional vtordisps if either:
3187 // * A user declared constructor or destructor aren't declared.
3188 // * #pragma vtordisp(0) or the /vd0 flag are in use.
3189 if ((!RD->hasUserDeclaredConstructor() && !RD->hasUserDeclaredDestructor()) ||
3190 RD->getMSVtorDispMode() == MSVtorDispMode::Never)
3191 return;
3192 // /vd1 or #pragma vtordisp(1): Try to guess based on whether we think it's
3193 // possible for a partially constructed object with virtual base overrides to
3194 // escape a non-trivial constructor.
3195 assert(RD->getMSVtorDispMode() == MSVtorDispMode::ForVBaseOverride)(static_cast <bool> (RD->getMSVtorDispMode() == MSVtorDispMode
::ForVBaseOverride) ? void (0) : __assert_fail ("RD->getMSVtorDispMode() == MSVtorDispMode::ForVBaseOverride"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 3195, __extension__ __PRETTY_FUNCTION__))
;
3196 // Compute a set of base classes which define methods we override. A virtual
3197 // base in this set will require a vtordisp. A virtual base that transitively
3198 // contains one of these bases as a non-virtual base will also require a
3199 // vtordisp.
3200 llvm::SmallPtrSet<const CXXMethodDecl *, 8> Work;
3201 llvm::SmallPtrSet<const CXXRecordDecl *, 2> BasesWithOverriddenMethods;
3202 // Seed the working set with our non-destructor, non-pure virtual methods.
3203 for (const CXXMethodDecl *MD : RD->methods())
3204 if (MicrosoftVTableContext::hasVtableSlot(MD) &&
3205 !isa<CXXDestructorDecl>(MD) && !MD->isPure())
3206 Work.insert(MD);
3207 while (!Work.empty()) {
3208 const CXXMethodDecl *MD = *Work.begin();
3209 auto MethodRange = MD->overridden_methods();
3210 // If a virtual method has no-overrides it lives in its parent's vtable.
3211 if (MethodRange.begin() == MethodRange.end())
3212 BasesWithOverriddenMethods.insert(MD->getParent());
3213 else
3214 Work.insert(MethodRange.begin(), MethodRange.end());
3215 // We've finished processing this element, remove it from the working set.
3216 Work.erase(MD);
3217 }
3218 // For each of our virtual bases, check if it is in the set of overridden
3219 // bases or if it transitively contains a non-virtual base that is.
3220 for (const CXXBaseSpecifier &Base : RD->vbases()) {
3221 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
3222 if (!HasVtordispSet.count(BaseDecl) &&
3223 RequiresVtordisp(BasesWithOverriddenMethods, BaseDecl))
3224 HasVtordispSet.insert(BaseDecl);
3225 }
3226}
3227
3228/// getASTRecordLayout - Get or compute information about the layout of the
3229/// specified record (struct/union/class), which indicates its size and field
3230/// position information.
3231const ASTRecordLayout &
3232ASTContext::getASTRecordLayout(const RecordDecl *D) const {
3233 // These asserts test different things. A record has a definition
3234 // as soon as we begin to parse the definition. That definition is
3235 // not a complete definition (which is what isDefinition() tests)
3236 // until we *finish* parsing the definition.
3237
3238 if (D->hasExternalLexicalStorage() && !D->getDefinition())
5
Assuming the condition is false
3239 getExternalSource()->CompleteType(const_cast<RecordDecl*>(D));
3240
3241 D = D->getDefinition();
3242 assert(D && "Cannot get layout of forward declarations!")(static_cast <bool> (D && "Cannot get layout of forward declarations!"
) ? void (0) : __assert_fail ("D && \"Cannot get layout of forward declarations!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 3242, __extension__ __PRETTY_FUNCTION__))
;
6
'?' condition is true
3243 assert(!D->isInvalidDecl() && "Cannot get layout of invalid decl!")(static_cast <bool> (!D->isInvalidDecl() && "Cannot get layout of invalid decl!"
) ? void (0) : __assert_fail ("!D->isInvalidDecl() && \"Cannot get layout of invalid decl!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 3243, __extension__ __PRETTY_FUNCTION__))
;
7
Assuming the condition is true
8
'?' condition is true
3244 assert(D->isCompleteDefinition() && "Cannot layout type before complete!")(static_cast <bool> (D->isCompleteDefinition() &&
"Cannot layout type before complete!") ? void (0) : __assert_fail
("D->isCompleteDefinition() && \"Cannot layout type before complete!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 3244, __extension__ __PRETTY_FUNCTION__))
;
9
Assuming the condition is true
10
'?' condition is true
3245
3246 // Look up this layout, if already laid out, return what we have.
3247 // Note that we can't save a reference to the entry because this function
3248 // is recursive.
3249 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
3250 if (Entry) return *Entry;
11
Assuming 'Entry' is null
12
Taking false branch
3251
3252 const ASTRecordLayout *NewEntry = nullptr;
3253
3254 if (isMsLayout(*this)) {
13
Taking false branch
3255 MicrosoftRecordLayoutBuilder Builder(*this);
3256 if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
3257 Builder.cxxLayout(RD);
3258 NewEntry = new (*this) ASTRecordLayout(
3259 *this, Builder.Size, Builder.Alignment, Builder.Alignment,
3260 Builder.Alignment, Builder.RequiredAlignment, Builder.HasOwnVFPtr,
3261 Builder.HasOwnVFPtr || Builder.PrimaryBase, Builder.VBPtrOffset,
3262 Builder.DataSize, Builder.FieldOffsets, Builder.NonVirtualSize,
3263 Builder.Alignment, Builder.Alignment, CharUnits::Zero(),
3264 Builder.PrimaryBase, false, Builder.SharedVBPtrBase,
3265 Builder.EndsWithZeroSizedObject, Builder.LeadsWithZeroSizedBase,
3266 Builder.Bases, Builder.VBases);
3267 } else {
3268 Builder.layout(D);
3269 NewEntry = new (*this) ASTRecordLayout(
3270 *this, Builder.Size, Builder.Alignment, Builder.Alignment,
3271 Builder.Alignment, Builder.RequiredAlignment, Builder.Size,
3272 Builder.FieldOffsets);
3273 }
3274 } else {
3275 if (const auto *RD
14.1
'RD' is non-null
= dyn_cast<CXXRecordDecl>(D)) {
14
Assuming 'D' is a 'CXXRecordDecl'
15
Taking true branch
3276 EmptySubobjectMap EmptySubobjects(*this, RD);
3277 ItaniumRecordLayoutBuilder Builder(*this, &EmptySubobjects);
3278 Builder.Layout(RD);
16
Calling 'ItaniumRecordLayoutBuilder::Layout'
3279
3280 // In certain situations, we are allowed to lay out objects in the
3281 // tail-padding of base classes. This is ABI-dependent.
3282 // FIXME: this should be stored in the record layout.
3283 bool skipTailPadding =
3284 mustSkipTailPadding(getTargetInfo().getCXXABI(), RD);
3285
3286 // FIXME: This should be done in FinalizeLayout.
3287 CharUnits DataSize =
3288 skipTailPadding ? Builder.getSize() : Builder.getDataSize();
3289 CharUnits NonVirtualSize =
3290 skipTailPadding ? DataSize : Builder.NonVirtualSize;
3291 NewEntry = new (*this) ASTRecordLayout(
3292 *this, Builder.getSize(), Builder.Alignment,
3293 Builder.PreferredAlignment, Builder.UnadjustedAlignment,
3294 /*RequiredAlignment : used by MS-ABI)*/
3295 Builder.Alignment, Builder.HasOwnVFPtr, RD->isDynamicClass(),
3296 CharUnits::fromQuantity(-1), DataSize, Builder.FieldOffsets,
3297 NonVirtualSize, Builder.NonVirtualAlignment,
3298 Builder.PreferredNVAlignment,
3299 EmptySubobjects.SizeOfLargestEmptySubobject, Builder.PrimaryBase,
3300 Builder.PrimaryBaseIsVirtual, nullptr, false, false, Builder.Bases,
3301 Builder.VBases);
3302 } else {
3303 ItaniumRecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/nullptr);
3304 Builder.Layout(D);
3305
3306 NewEntry = new (*this) ASTRecordLayout(
3307 *this, Builder.getSize(), Builder.Alignment,
3308 Builder.PreferredAlignment, Builder.UnadjustedAlignment,
3309 /*RequiredAlignment : used by MS-ABI)*/
3310 Builder.Alignment, Builder.getSize(), Builder.FieldOffsets);
3311 }
3312 }
3313
3314 ASTRecordLayouts[D] = NewEntry;
3315
3316 if (getLangOpts().DumpRecordLayouts) {
3317 llvm::outs() << "\n*** Dumping AST Record Layout\n";
3318 DumpRecordLayout(D, llvm::outs(), getLangOpts().DumpRecordLayoutsSimple);
3319 }
3320
3321 return *NewEntry;
3322}
3323
3324const CXXMethodDecl *ASTContext::getCurrentKeyFunction(const CXXRecordDecl *RD) {
3325 if (!getTargetInfo().getCXXABI().hasKeyFunctions())
3326 return nullptr;
3327
3328 assert(RD->getDefinition() && "Cannot get key function for forward decl!")(static_cast <bool> (RD->getDefinition() && "Cannot get key function for forward decl!"
) ? void (0) : __assert_fail ("RD->getDefinition() && \"Cannot get key function for forward decl!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 3328, __extension__ __PRETTY_FUNCTION__))
;
3329 RD = RD->getDefinition();
3330
3331 // Beware:
3332 // 1) computing the key function might trigger deserialization, which might
3333 // invalidate iterators into KeyFunctions
3334 // 2) 'get' on the LazyDeclPtr might also trigger deserialization and
3335 // invalidate the LazyDeclPtr within the map itself
3336 LazyDeclPtr Entry = KeyFunctions[RD];
3337 const Decl *Result =
3338 Entry ? Entry.get(getExternalSource()) : computeKeyFunction(*this, RD);
3339
3340 // Store it back if it changed.
3341 if (Entry.isOffset() || Entry.isValid() != bool(Result))
3342 KeyFunctions[RD] = const_cast<Decl*>(Result);
3343
3344 return cast_or_null<CXXMethodDecl>(Result);
3345}
3346
3347void ASTContext::setNonKeyFunction(const CXXMethodDecl *Method) {
3348 assert(Method == Method->getFirstDecl() &&(static_cast <bool> (Method == Method->getFirstDecl(
) && "not working with method declaration from class definition"
) ? void (0) : __assert_fail ("Method == Method->getFirstDecl() && \"not working with method declaration from class definition\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 3349, __extension__ __PRETTY_FUNCTION__))
3349 "not working with method declaration from class definition")(static_cast <bool> (Method == Method->getFirstDecl(
) && "not working with method declaration from class definition"
) ? void (0) : __assert_fail ("Method == Method->getFirstDecl() && \"not working with method declaration from class definition\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 3349, __extension__ __PRETTY_FUNCTION__))
;
3350
3351 // Look up the cache entry. Since we're working with the first
3352 // declaration, its parent must be the class definition, which is
3353 // the correct key for the KeyFunctions hash.
3354 const auto &Map = KeyFunctions;
3355 auto I = Map.find(Method->getParent());
3356
3357 // If it's not cached, there's nothing to do.
3358 if (I == Map.end()) return;
3359
3360 // If it is cached, check whether it's the target method, and if so,
3361 // remove it from the cache. Note, the call to 'get' might invalidate
3362 // the iterator and the LazyDeclPtr object within the map.
3363 LazyDeclPtr Ptr = I->second;
3364 if (Ptr.get(getExternalSource()) == Method) {
3365 // FIXME: remember that we did this for module / chained PCH state?
3366 KeyFunctions.erase(Method->getParent());
3367 }
3368}
3369
3370static uint64_t getFieldOffset(const ASTContext &C, const FieldDecl *FD) {
3371 const ASTRecordLayout &Layout = C.getASTRecordLayout(FD->getParent());
3372 return Layout.getFieldOffset(FD->getFieldIndex());
3373}
3374
3375uint64_t ASTContext::getFieldOffset(const ValueDecl *VD) const {
3376 uint64_t OffsetInBits;
3377 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
3378 OffsetInBits = ::getFieldOffset(*this, FD);
3379 } else {
3380 const IndirectFieldDecl *IFD = cast<IndirectFieldDecl>(VD);
3381
3382 OffsetInBits = 0;
3383 for (const NamedDecl *ND : IFD->chain())
3384 OffsetInBits += ::getFieldOffset(*this, cast<FieldDecl>(ND));
3385 }
3386
3387 return OffsetInBits;
3388}
3389
3390uint64_t ASTContext::lookupFieldBitOffset(const ObjCInterfaceDecl *OID,
3391 const ObjCImplementationDecl *ID,
3392 const ObjCIvarDecl *Ivar) const {
3393 const ObjCInterfaceDecl *Container = Ivar->getContainingInterface();
3394
3395 // FIXME: We should eliminate the need to have ObjCImplementationDecl passed
3396 // in here; it should never be necessary because that should be the lexical
3397 // decl context for the ivar.
3398
3399 // If we know have an implementation (and the ivar is in it) then
3400 // look up in the implementation layout.
3401 const ASTRecordLayout *RL;
3402 if (ID && declaresSameEntity(ID->getClassInterface(), Container))
3403 RL = &getASTObjCImplementationLayout(ID);
3404 else
3405 RL = &getASTObjCInterfaceLayout(Container);
3406
3407 // Compute field index.
3408 //
3409 // FIXME: The index here is closely tied to how ASTContext::getObjCLayout is
3410 // implemented. This should be fixed to get the information from the layout
3411 // directly.
3412 unsigned Index = 0;
3413
3414 for (const ObjCIvarDecl *IVD = Container->all_declared_ivar_begin();
3415 IVD; IVD = IVD->getNextIvar()) {
3416 if (Ivar == IVD)
3417 break;
3418 ++Index;
3419 }
3420 assert(Index < RL->getFieldCount() && "Ivar is not inside record layout!")(static_cast <bool> (Index < RL->getFieldCount() &&
"Ivar is not inside record layout!") ? void (0) : __assert_fail
("Index < RL->getFieldCount() && \"Ivar is not inside record layout!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 3420, __extension__ __PRETTY_FUNCTION__))
;
3421
3422 return RL->getFieldOffset(Index);
3423}
3424
3425/// getObjCLayout - Get or compute information about the layout of the
3426/// given interface.
3427///
3428/// \param Impl - If given, also include the layout of the interface's
3429/// implementation. This may differ by including synthesized ivars.
3430const ASTRecordLayout &
3431ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
3432 const ObjCImplementationDecl *Impl) const {
3433 // Retrieve the definition
3434 if (D->hasExternalLexicalStorage() && !D->getDefinition())
3435 getExternalSource()->CompleteType(const_cast<ObjCInterfaceDecl*>(D));
3436 D = D->getDefinition();
3437 assert(D && !D->isInvalidDecl() && D->isThisDeclarationADefinition() &&(static_cast <bool> (D && !D->isInvalidDecl(
) && D->isThisDeclarationADefinition() && "Invalid interface decl!"
) ? void (0) : __assert_fail ("D && !D->isInvalidDecl() && D->isThisDeclarationADefinition() && \"Invalid interface decl!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 3438, __extension__ __PRETTY_FUNCTION__))
3438 "Invalid interface decl!")(static_cast <bool> (D && !D->isInvalidDecl(
) && D->isThisDeclarationADefinition() && "Invalid interface decl!"
) ? void (0) : __assert_fail ("D && !D->isInvalidDecl() && D->isThisDeclarationADefinition() && \"Invalid interface decl!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 3438, __extension__ __PRETTY_FUNCTION__))
;
3439
3440 // Look up this layout, if already laid out, return what we have.
3441 const ObjCContainerDecl *Key =
3442 Impl ? (const ObjCContainerDecl*) Impl : (const ObjCContainerDecl*) D;
3443 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
3444 return *Entry;
3445
3446 // Add in synthesized ivar count if laying out an implementation.
3447 if (Impl) {
3448 unsigned SynthCount = CountNonClassIvars(D);
3449 // If there aren't any synthesized ivars then reuse the interface
3450 // entry. Note we can't cache this because we simply free all
3451 // entries later; however we shouldn't look up implementations
3452 // frequently.
3453 if (SynthCount == 0)
3454 return getObjCLayout(D, nullptr);
3455 }
3456
3457 ItaniumRecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/nullptr);
3458 Builder.Layout(D);
3459
3460 const ASTRecordLayout *NewEntry = new (*this) ASTRecordLayout(
3461 *this, Builder.getSize(), Builder.Alignment, Builder.PreferredAlignment,
3462 Builder.UnadjustedAlignment,
3463 /*RequiredAlignment : used by MS-ABI)*/
3464 Builder.Alignment, Builder.getDataSize(), Builder.FieldOffsets);
3465
3466 ObjCLayouts[Key] = NewEntry;
3467
3468 return *NewEntry;
3469}
3470
3471static void PrintOffset(raw_ostream &OS,
3472 CharUnits Offset, unsigned IndentLevel) {
3473 OS << llvm::format("%10" PRId64"l" "d" " | ", (int64_t)Offset.getQuantity());
3474 OS.indent(IndentLevel * 2);
3475}
3476
3477static void PrintBitFieldOffset(raw_ostream &OS, CharUnits Offset,
3478 unsigned Begin, unsigned Width,
3479 unsigned IndentLevel) {
3480 llvm::SmallString<10> Buffer;
3481 {
3482 llvm::raw_svector_ostream BufferOS(Buffer);
3483 BufferOS << Offset.getQuantity() << ':';
3484 if (Width == 0) {
3485 BufferOS << '-';
3486 } else {
3487 BufferOS << Begin << '-' << (Begin + Width - 1);
3488 }
3489 }
3490
3491 OS << llvm::right_justify(Buffer, 10) << " | ";
3492 OS.indent(IndentLevel * 2);
3493}
3494
3495static void PrintIndentNoOffset(raw_ostream &OS, unsigned IndentLevel) {
3496 OS << " | ";
3497 OS.indent(IndentLevel * 2);
3498}
3499
3500static void DumpRecordLayout(raw_ostream &OS, const RecordDecl *RD,
3501 const ASTContext &C,
3502 CharUnits Offset,
3503 unsigned IndentLevel,
3504 const char* Description,
3505 bool PrintSizeInfo,
3506 bool IncludeVirtualBases) {
3507 const ASTRecordLayout &Layout = C.getASTRecordLayout(RD);
4
Calling 'ASTContext::getASTRecordLayout'
3508 auto CXXRD = dyn_cast<CXXRecordDecl>(RD);
3509
3510 PrintOffset(OS, Offset, IndentLevel);
3511 OS << C.getTypeDeclType(const_cast<RecordDecl*>(RD)).getAsString();
3512 if (Description)
3513 OS << ' ' << Description;
3514 if (CXXRD && CXXRD->isEmpty())
3515 OS << " (empty)";
3516 OS << '\n';
3517
3518 IndentLevel++;
3519
3520 // Dump bases.
3521 if (CXXRD) {
3522 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
3523 bool HasOwnVFPtr = Layout.hasOwnVFPtr();
3524 bool HasOwnVBPtr = Layout.hasOwnVBPtr();
3525
3526 // Vtable pointer.
3527 if (CXXRD->isDynamicClass() && !PrimaryBase && !isMsLayout(C)) {
3528 PrintOffset(OS, Offset, IndentLevel);
3529 OS << '(' << *RD << " vtable pointer)\n";
3530 } else if (HasOwnVFPtr) {
3531 PrintOffset(OS, Offset, IndentLevel);
3532 // vfptr (for Microsoft C++ ABI)
3533 OS << '(' << *RD << " vftable pointer)\n";
3534 }
3535
3536 // Collect nvbases.
3537 SmallVector<const CXXRecordDecl *, 4> Bases;
3538 for (const CXXBaseSpecifier &Base : CXXRD->bases()) {
3539 assert(!Base.getType()->isDependentType() &&(static_cast <bool> (!Base.getType()->isDependentType
() && "Cannot layout class with dependent bases.") ? void
(0) : __assert_fail ("!Base.getType()->isDependentType() && \"Cannot layout class with dependent bases.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 3540, __extension__ __PRETTY_FUNCTION__))
3540 "Cannot layout class with dependent bases.")(static_cast <bool> (!Base.getType()->isDependentType
() && "Cannot layout class with dependent bases.") ? void
(0) : __assert_fail ("!Base.getType()->isDependentType() && \"Cannot layout class with dependent bases.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 3540, __extension__ __PRETTY_FUNCTION__))
;
3541 if (!Base.isVirtual())
3542 Bases.push_back(Base.getType()->getAsCXXRecordDecl());
3543 }
3544
3545 // Sort nvbases by offset.
3546 llvm::stable_sort(
3547 Bases, [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
3548 return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
3549 });
3550
3551 // Dump (non-virtual) bases
3552 for (const CXXRecordDecl *Base : Bases) {
3553 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base);
3554 DumpRecordLayout(OS, Base, C, BaseOffset, IndentLevel,
3555 Base == PrimaryBase ? "(primary base)" : "(base)",
3556 /*PrintSizeInfo=*/false,
3557 /*IncludeVirtualBases=*/false);
3558 }
3559
3560 // vbptr (for Microsoft C++ ABI)
3561 if (HasOwnVBPtr) {
3562 PrintOffset(OS, Offset + Layout.getVBPtrOffset(), IndentLevel);
3563 OS << '(' << *RD << " vbtable pointer)\n";
3564 }
3565 }
3566
3567 // Dump fields.
3568 uint64_t FieldNo = 0;
3569 for (RecordDecl::field_iterator I = RD->field_begin(),
3570 E = RD->field_end(); I != E; ++I, ++FieldNo) {
3571 const FieldDecl &Field = **I;
3572 uint64_t LocalFieldOffsetInBits = Layout.getFieldOffset(FieldNo);
3573 CharUnits FieldOffset =
3574 Offset + C.toCharUnitsFromBits(LocalFieldOffsetInBits);
3575
3576 // Recursively dump fields of record type.
3577 if (auto RT = Field.getType()->getAs<RecordType>()) {
3578 DumpRecordLayout(OS, RT->getDecl(), C, FieldOffset, IndentLevel,
3579 Field.getName().data(),
3580 /*PrintSizeInfo=*/false,
3581 /*IncludeVirtualBases=*/true);
3582 continue;
3583 }
3584
3585 if (Field.isBitField()) {
3586 uint64_t LocalFieldByteOffsetInBits = C.toBits(FieldOffset - Offset);
3587 unsigned Begin = LocalFieldOffsetInBits - LocalFieldByteOffsetInBits;
3588 unsigned Width = Field.getBitWidthValue(C);
3589 PrintBitFieldOffset(OS, FieldOffset, Begin, Width, IndentLevel);
3590 } else {
3591 PrintOffset(OS, FieldOffset, IndentLevel);
3592 }
3593 const QualType &FieldType = C.getLangOpts().DumpRecordLayoutsCanonical
3594 ? Field.getType().getCanonicalType()
3595 : Field.getType();
3596 OS << FieldType.getAsString() << ' ' << Field << '\n';
3597 }
3598
3599 // Dump virtual bases.
3600 if (CXXRD && IncludeVirtualBases) {
3601 const ASTRecordLayout::VBaseOffsetsMapTy &VtorDisps =
3602 Layout.getVBaseOffsetsMap();
3603
3604 for (const CXXBaseSpecifier &Base : CXXRD->vbases()) {
3605 assert(Base.isVirtual() && "Found non-virtual class!")(static_cast <bool> (Base.isVirtual() && "Found non-virtual class!"
) ? void (0) : __assert_fail ("Base.isVirtual() && \"Found non-virtual class!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/RecordLayoutBuilder.cpp"
, 3605, __extension__ __PRETTY_FUNCTION__))
;
3606 const CXXRecordDecl *VBase = Base.getType()->getAsCXXRecordDecl();
3607
3608 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBase);
3609
3610 if (VtorDisps.find(VBase)->second.hasVtorDisp()) {
3611 PrintOffset(OS, VBaseOffset - CharUnits::fromQuantity(4), IndentLevel);
3612 OS << "(vtordisp for vbase " << *VBase << ")\n";
3613 }
3614
3615 DumpRecordLayout(OS, VBase, C, VBaseOffset, IndentLevel,
3616 VBase == Layout.getPrimaryBase() ?
3617 "(primary virtual base)" : "(virtual base)",
3618 /*PrintSizeInfo=*/false,
3619 /*IncludeVirtualBases=*/false);
3620 }
3621 }
3622
3623 if (!PrintSizeInfo) return;
3624
3625 PrintIndentNoOffset(OS, IndentLevel - 1);
3626 OS << "[sizeof=" << Layout.getSize().getQuantity();
3627 if (CXXRD && !isMsLayout(C))
3628 OS << ", dsize=" << Layout.getDataSize().getQuantity();
3629 OS << ", align=" << Layout.getAlignment().getQuantity();
3630 if (C.getTargetInfo().defaultsToAIXPowerAlignment())
3631 OS << ", preferredalign=" << Layout.getPreferredAlignment().getQuantity();
3632
3633 if (CXXRD) {
3634 OS << ",\n";
3635 PrintIndentNoOffset(OS, IndentLevel - 1);
3636 OS << " nvsize=" << Layout.getNonVirtualSize().getQuantity();
3637 OS << ", nvalign=" << Layout.getNonVirtualAlignment().getQuantity();
3638 if (C.getTargetInfo().defaultsToAIXPowerAlignment())
3639 OS << ", preferrednvalign="
3640 << Layout.getPreferredNVAlignment().getQuantity();
3641 }
3642 OS << "]\n";
3643}
3644
3645void ASTContext::DumpRecordLayout(const RecordDecl *RD, raw_ostream &OS,
3646 bool Simple) const {
3647 if (!Simple) {
1
Assuming 'Simple' is false
2
Taking true branch
3648 ::DumpRecordLayout(OS, RD, *this, CharUnits(), 0, nullptr,
3
Calling 'DumpRecordLayout'
3649 /*PrintSizeInfo*/ true,
3650 /*IncludeVirtualBases=*/true);
3651 return;
3652 }
3653
3654 // The "simple" format is designed to be parsed by the
3655 // layout-override testing code. There shouldn't be any external
3656 // uses of this format --- when LLDB overrides a layout, it sets up
3657 // the data structures directly --- so feel free to adjust this as
3658 // you like as long as you also update the rudimentary parser for it
3659 // in libFrontend.
3660
3661 const ASTRecordLayout &Info = getASTRecordLayout(RD);
3662 OS << "Type: " << getTypeDeclType(RD).getAsString() << "\n";
3663 OS << "\nLayout: ";
3664 OS << "<ASTRecordLayout\n";
3665 OS << " Size:" << toBits(Info.getSize()) << "\n";
3666 if (!isMsLayout(*this))
3667 OS << " DataSize:" << toBits(Info.getDataSize()) << "\n";
3668 OS << " Alignment:" << toBits(Info.getAlignment()) << "\n";
3669 if (Target->defaultsToAIXPowerAlignment())
3670 OS << " PreferredAlignment:" << toBits(Info.getPreferredAlignment())
3671 << "\n";
3672 OS << " FieldOffsets: [";
3673 for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i) {
3674 if (i)
3675 OS << ", ";
3676 OS << Info.getFieldOffset(i);
3677 }
3678 OS << "]>\n";
3679}