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