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