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