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/Attr.h" 11 #include "clang/AST/CXXInheritance.h" 12 #include "clang/AST/Decl.h" 13 #include "clang/AST/DeclCXX.h" 14 #include "clang/AST/DeclObjC.h" 15 #include "clang/AST/Expr.h" 16 #include "clang/AST/RecordLayout.h" 17 #include "clang/Basic/TargetInfo.h" 18 #include "clang/Sema/SemaDiagnostic.h" 19 #include "llvm/Support/Format.h" 20 #include "llvm/ADT/SmallSet.h" 21 #include "llvm/Support/MathExtras.h" 22 #include "llvm/Support/CrashRecoveryContext.h" 23 24 using namespace clang; 25 26 namespace { 27 28 /// BaseSubobjectInfo - Represents a single base subobject in a complete class. 29 /// For a class hierarchy like 30 /// 31 /// class A { }; 32 /// class B : A { }; 33 /// class C : A, B { }; 34 /// 35 /// The BaseSubobjectInfo graph for C will have three BaseSubobjectInfo 36 /// instances, one for B and two for A. 37 /// 38 /// If a base is virtual, it will only have one BaseSubobjectInfo allocated. 39 struct BaseSubobjectInfo { 40 /// Class - The class for this base info. 41 const CXXRecordDecl *Class; 42 43 /// IsVirtual - Whether the BaseInfo represents a virtual base or not. 44 bool IsVirtual; 45 46 /// Bases - Information about the base subobjects. 47 SmallVector<BaseSubobjectInfo*, 4> Bases; 48 49 /// PrimaryVirtualBaseInfo - Holds the base info for the primary virtual base 50 /// of this base info (if one exists). 51 BaseSubobjectInfo *PrimaryVirtualBaseInfo; 52 53 // FIXME: Document. 54 const BaseSubobjectInfo *Derived; 55 }; 56 57 /// EmptySubobjectMap - Keeps track of which empty subobjects exist at different 58 /// offsets while laying out a C++ class. 59 class EmptySubobjectMap { 60 const ASTContext &Context; 61 uint64_t CharWidth; 62 63 /// Class - The class whose empty entries we're keeping track of. 64 const CXXRecordDecl *Class; 65 66 /// EmptyClassOffsets - A map from offsets to empty record decls. 67 typedef SmallVector<const CXXRecordDecl *, 1> ClassVectorTy; 68 typedef llvm::DenseMap<CharUnits, ClassVectorTy> EmptyClassOffsetsMapTy; 69 EmptyClassOffsetsMapTy EmptyClassOffsets; 70 71 /// MaxEmptyClassOffset - The highest offset known to contain an empty 72 /// base subobject. 73 CharUnits MaxEmptyClassOffset; 74 75 /// ComputeEmptySubobjectSizes - Compute the size of the largest base or 76 /// member subobject that is empty. 77 void ComputeEmptySubobjectSizes(); 78 79 void AddSubobjectAtOffset(const CXXRecordDecl *RD, CharUnits Offset); 80 81 void UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info, 82 CharUnits Offset, bool PlacingEmptyBase); 83 84 void UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD, 85 const CXXRecordDecl *Class, 86 CharUnits Offset); 87 void UpdateEmptyFieldSubobjects(const FieldDecl *FD, CharUnits Offset); 88 89 /// AnyEmptySubobjectsBeyondOffset - Returns whether there are any empty 90 /// subobjects beyond the given offset. 91 bool AnyEmptySubobjectsBeyondOffset(CharUnits Offset) const { 92 return Offset <= MaxEmptyClassOffset; 93 } 94 95 CharUnits 96 getFieldOffset(const ASTRecordLayout &Layout, unsigned FieldNo) const { 97 uint64_t FieldOffset = Layout.getFieldOffset(FieldNo); 98 assert(FieldOffset % CharWidth == 0 && 99 "Field offset not at char boundary!"); 100 101 return Context.toCharUnitsFromBits(FieldOffset); 102 } 103 104 protected: 105 bool CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD, 106 CharUnits Offset) const; 107 108 bool CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info, 109 CharUnits Offset); 110 111 bool CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD, 112 const CXXRecordDecl *Class, 113 CharUnits Offset) const; 114 bool CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD, 115 CharUnits Offset) const; 116 117 public: 118 /// This holds the size of the largest empty subobject (either a base 119 /// or a member). Will be zero if the record being built doesn't contain 120 /// any empty classes. 121 CharUnits SizeOfLargestEmptySubobject; 122 123 EmptySubobjectMap(const ASTContext &Context, const CXXRecordDecl *Class) 124 : Context(Context), CharWidth(Context.getCharWidth()), Class(Class) { 125 ComputeEmptySubobjectSizes(); 126 } 127 128 /// CanPlaceBaseAtOffset - Return whether the given base class can be placed 129 /// at the given offset. 130 /// Returns false if placing the record will result in two components 131 /// (direct or indirect) of the same type having the same offset. 132 bool CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info, 133 CharUnits Offset); 134 135 /// CanPlaceFieldAtOffset - Return whether a field can be placed at the given 136 /// offset. 137 bool CanPlaceFieldAtOffset(const FieldDecl *FD, CharUnits Offset); 138 }; 139 140 void EmptySubobjectMap::ComputeEmptySubobjectSizes() { 141 // Check the bases. 142 for (CXXRecordDecl::base_class_const_iterator I = Class->bases_begin(), 143 E = Class->bases_end(); I != E; ++I) { 144 const CXXRecordDecl *BaseDecl = 145 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl()); 146 147 CharUnits EmptySize; 148 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl); 149 if (BaseDecl->isEmpty()) { 150 // If the class decl is empty, get its size. 151 EmptySize = Layout.getSize(); 152 } else { 153 // Otherwise, we get the largest empty subobject for the decl. 154 EmptySize = Layout.getSizeOfLargestEmptySubobject(); 155 } 156 157 if (EmptySize > SizeOfLargestEmptySubobject) 158 SizeOfLargestEmptySubobject = EmptySize; 159 } 160 161 // Check the fields. 162 for (CXXRecordDecl::field_iterator I = Class->field_begin(), 163 E = Class->field_end(); I != E; ++I) { 164 const FieldDecl &FD = *I; 165 166 const RecordType *RT = 167 Context.getBaseElementType(FD.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 189 bool 190 EmptySubobjectMap::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 208 void 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 an 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 227 bool 228 EmptySubobjectMap::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 const FieldDecl *FD = &*I; 265 if (FD->isBitField()) 266 continue; 267 268 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo); 269 if (!CanPlaceFieldSubobjectAtOffset(FD, FieldOffset)) 270 return false; 271 } 272 273 return true; 274 } 275 276 void EmptySubobjectMap::UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info, 277 CharUnits Offset, 278 bool PlacingEmptyBase) { 279 if (!PlacingEmptyBase && Offset >= SizeOfLargestEmptySubobject) { 280 // We know that the only empty subobjects that can conflict with empty 281 // subobject of non-empty bases, are empty bases that can be placed at 282 // offset zero. Because of this, we only need to keep track of empty base 283 // subobjects with offsets less than the size of the largest empty 284 // subobject for our class. 285 return; 286 } 287 288 AddSubobjectAtOffset(Info->Class, Offset); 289 290 // Traverse all non-virtual bases. 291 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class); 292 for (unsigned I = 0, E = Info->Bases.size(); I != E; ++I) { 293 BaseSubobjectInfo* Base = Info->Bases[I]; 294 if (Base->IsVirtual) 295 continue; 296 297 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class); 298 UpdateEmptyBaseSubobjects(Base, BaseOffset, PlacingEmptyBase); 299 } 300 301 if (Info->PrimaryVirtualBaseInfo) { 302 BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo; 303 304 if (Info == PrimaryVirtualBaseInfo->Derived) 305 UpdateEmptyBaseSubobjects(PrimaryVirtualBaseInfo, Offset, 306 PlacingEmptyBase); 307 } 308 309 // Traverse all member variables. 310 unsigned FieldNo = 0; 311 for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(), 312 E = Info->Class->field_end(); I != E; ++I, ++FieldNo) { 313 const FieldDecl *FD = &*I; 314 if (FD->isBitField()) 315 continue; 316 317 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo); 318 UpdateEmptyFieldSubobjects(FD, FieldOffset); 319 } 320 } 321 322 bool EmptySubobjectMap::CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info, 323 CharUnits Offset) { 324 // If we know this class doesn't have any empty subobjects we don't need to 325 // bother checking. 326 if (SizeOfLargestEmptySubobject.isZero()) 327 return true; 328 329 if (!CanPlaceBaseSubobjectAtOffset(Info, Offset)) 330 return false; 331 332 // We are able to place the base at this offset. Make sure to update the 333 // empty base subobject map. 334 UpdateEmptyBaseSubobjects(Info, Offset, Info->Class->isEmpty()); 335 return true; 336 } 337 338 bool 339 EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD, 340 const CXXRecordDecl *Class, 341 CharUnits Offset) const { 342 // We don't have to keep looking past the maximum offset that's known to 343 // contain an empty class. 344 if (!AnyEmptySubobjectsBeyondOffset(Offset)) 345 return true; 346 347 if (!CanPlaceSubobjectAtOffset(RD, Offset)) 348 return false; 349 350 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 351 352 // Traverse all non-virtual bases. 353 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 354 E = RD->bases_end(); I != E; ++I) { 355 if (I->isVirtual()) 356 continue; 357 358 const CXXRecordDecl *BaseDecl = 359 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl()); 360 361 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl); 362 if (!CanPlaceFieldSubobjectAtOffset(BaseDecl, Class, BaseOffset)) 363 return false; 364 } 365 366 if (RD == Class) { 367 // This is the most derived class, traverse virtual bases as well. 368 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(), 369 E = RD->vbases_end(); I != E; ++I) { 370 const CXXRecordDecl *VBaseDecl = 371 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl()); 372 373 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl); 374 if (!CanPlaceFieldSubobjectAtOffset(VBaseDecl, Class, VBaseOffset)) 375 return false; 376 } 377 } 378 379 // Traverse all member variables. 380 unsigned FieldNo = 0; 381 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end(); 382 I != E; ++I, ++FieldNo) { 383 const FieldDecl *FD = &*I; 384 if (FD->isBitField()) 385 continue; 386 387 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo); 388 389 if (!CanPlaceFieldSubobjectAtOffset(FD, FieldOffset)) 390 return false; 391 } 392 393 return true; 394 } 395 396 bool 397 EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD, 398 CharUnits Offset) const { 399 // We don't have to keep looking past the maximum offset that's known to 400 // contain an empty class. 401 if (!AnyEmptySubobjectsBeyondOffset(Offset)) 402 return true; 403 404 QualType T = FD->getType(); 405 if (const RecordType *RT = T->getAs<RecordType>()) { 406 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 407 return CanPlaceFieldSubobjectAtOffset(RD, RD, Offset); 408 } 409 410 // If we have an array type we need to look at every element. 411 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) { 412 QualType ElemTy = Context.getBaseElementType(AT); 413 const RecordType *RT = ElemTy->getAs<RecordType>(); 414 if (!RT) 415 return true; 416 417 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 418 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 419 420 uint64_t NumElements = Context.getConstantArrayElementCount(AT); 421 CharUnits ElementOffset = Offset; 422 for (uint64_t I = 0; I != NumElements; ++I) { 423 // We don't have to keep looking past the maximum offset that's known to 424 // contain an empty class. 425 if (!AnyEmptySubobjectsBeyondOffset(ElementOffset)) 426 return true; 427 428 if (!CanPlaceFieldSubobjectAtOffset(RD, RD, ElementOffset)) 429 return false; 430 431 ElementOffset += Layout.getSize(); 432 } 433 } 434 435 return true; 436 } 437 438 bool 439 EmptySubobjectMap::CanPlaceFieldAtOffset(const FieldDecl *FD, 440 CharUnits Offset) { 441 if (!CanPlaceFieldSubobjectAtOffset(FD, Offset)) 442 return false; 443 444 // We are able to place the member variable at this offset. 445 // Make sure to update the empty base subobject map. 446 UpdateEmptyFieldSubobjects(FD, Offset); 447 return true; 448 } 449 450 void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD, 451 const CXXRecordDecl *Class, 452 CharUnits Offset) { 453 // We know that the only empty subobjects that can conflict with empty 454 // field subobjects are subobjects of empty bases that can be placed at offset 455 // zero. Because of this, we only need to keep track of empty field 456 // subobjects with offsets less than the size of the largest empty 457 // subobject for our class. 458 if (Offset >= SizeOfLargestEmptySubobject) 459 return; 460 461 AddSubobjectAtOffset(RD, Offset); 462 463 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 464 465 // Traverse all non-virtual bases. 466 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 467 E = RD->bases_end(); I != E; ++I) { 468 if (I->isVirtual()) 469 continue; 470 471 const CXXRecordDecl *BaseDecl = 472 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl()); 473 474 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl); 475 UpdateEmptyFieldSubobjects(BaseDecl, Class, BaseOffset); 476 } 477 478 if (RD == Class) { 479 // This is the most derived class, traverse virtual bases as well. 480 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(), 481 E = RD->vbases_end(); I != E; ++I) { 482 const CXXRecordDecl *VBaseDecl = 483 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl()); 484 485 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl); 486 UpdateEmptyFieldSubobjects(VBaseDecl, Class, VBaseOffset); 487 } 488 } 489 490 // Traverse all member variables. 491 unsigned FieldNo = 0; 492 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end(); 493 I != E; ++I, ++FieldNo) { 494 const FieldDecl *FD = &*I; 495 if (FD->isBitField()) 496 continue; 497 498 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo); 499 500 UpdateEmptyFieldSubobjects(FD, FieldOffset); 501 } 502 } 503 504 void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const FieldDecl *FD, 505 CharUnits Offset) { 506 QualType T = FD->getType(); 507 if (const RecordType *RT = T->getAs<RecordType>()) { 508 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 509 UpdateEmptyFieldSubobjects(RD, RD, Offset); 510 return; 511 } 512 513 // If we have an array type we need to update every element. 514 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) { 515 QualType ElemTy = Context.getBaseElementType(AT); 516 const RecordType *RT = ElemTy->getAs<RecordType>(); 517 if (!RT) 518 return; 519 520 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 521 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 522 523 uint64_t NumElements = Context.getConstantArrayElementCount(AT); 524 CharUnits ElementOffset = Offset; 525 526 for (uint64_t I = 0; I != NumElements; ++I) { 527 // We know that the only empty subobjects that can conflict with empty 528 // field subobjects are subobjects of empty bases that can be placed at 529 // offset zero. Because of this, we only need to keep track of empty field 530 // subobjects with offsets less than the size of the largest empty 531 // subobject for our class. 532 if (ElementOffset >= SizeOfLargestEmptySubobject) 533 return; 534 535 UpdateEmptyFieldSubobjects(RD, RD, ElementOffset); 536 ElementOffset += Layout.getSize(); 537 } 538 } 539 } 540 541 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 4> ClassSetTy; 542 543 class RecordLayoutBuilder { 544 protected: 545 // FIXME: Remove this and make the appropriate fields public. 546 friend class clang::ASTContext; 547 548 const ASTContext &Context; 549 550 EmptySubobjectMap *EmptySubobjects; 551 552 /// Size - The current size of the record layout. 553 uint64_t Size; 554 555 /// Alignment - The current alignment of the record layout. 556 CharUnits Alignment; 557 558 /// \brief The alignment if attribute packed is not used. 559 CharUnits UnpackedAlignment; 560 561 SmallVector<uint64_t, 16> FieldOffsets; 562 563 /// \brief Whether the external AST source has provided a layout for this 564 /// record. 565 unsigned ExternalLayout : 1; 566 567 /// \brief Whether we need to infer alignment, even when we have an 568 /// externally-provided layout. 569 unsigned InferAlignment : 1; 570 571 /// Packed - Whether the record is packed or not. 572 unsigned Packed : 1; 573 574 unsigned IsUnion : 1; 575 576 unsigned IsMac68kAlign : 1; 577 578 unsigned IsMsStruct : 1; 579 580 /// UnfilledBitsInLastByte - If the last field laid out was a bitfield, 581 /// this contains the number of bits in the last byte that can be used for 582 /// an adjacent bitfield if necessary. 583 unsigned char UnfilledBitsInLastByte; 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 FieldDecl *ZeroLengthBitfield; 596 597 /// PrimaryBase - the primary base class (if one exists) of the class 598 /// we're laying out. 599 const CXXRecordDecl *PrimaryBase; 600 601 /// PrimaryBaseIsVirtual - Whether the primary base of the class we're laying 602 /// out is virtual. 603 bool PrimaryBaseIsVirtual; 604 605 /// HasOwnVFPtr - Whether the class provides its own vtable/vftbl 606 /// pointer, as opposed to inheriting one from a primary base class. 607 bool HasOwnVFPtr; 608 609 /// VBPtrOffset - Virtual base table offset. Only for MS layout. 610 CharUnits VBPtrOffset; 611 612 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy; 613 614 /// Bases - base classes and their offsets in the record. 615 BaseOffsetsMapTy Bases; 616 617 // VBases - virtual base classes and their offsets in the record. 618 ASTRecordLayout::VBaseOffsetsMapTy VBases; 619 620 /// IndirectPrimaryBases - Virtual base classes, direct or indirect, that are 621 /// primary base classes for some other direct or indirect base class. 622 CXXIndirectPrimaryBaseSet IndirectPrimaryBases; 623 624 /// FirstNearlyEmptyVBase - The first nearly empty virtual base class in 625 /// inheritance graph order. Used for determining the primary base class. 626 const CXXRecordDecl *FirstNearlyEmptyVBase; 627 628 /// VisitedVirtualBases - A set of all the visited virtual bases, used to 629 /// avoid visiting virtual bases more than once. 630 llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases; 631 632 /// \brief Externally-provided size. 633 uint64_t ExternalSize; 634 635 /// \brief Externally-provided alignment. 636 uint64_t ExternalAlign; 637 638 /// \brief Externally-provided field offsets. 639 llvm::DenseMap<const FieldDecl *, uint64_t> ExternalFieldOffsets; 640 641 /// \brief Externally-provided direct, non-virtual base offsets. 642 llvm::DenseMap<const CXXRecordDecl *, CharUnits> ExternalBaseOffsets; 643 644 /// \brief Externally-provided virtual base offsets. 645 llvm::DenseMap<const CXXRecordDecl *, CharUnits> ExternalVirtualBaseOffsets; 646 647 RecordLayoutBuilder(const ASTContext &Context, 648 EmptySubobjectMap *EmptySubobjects) 649 : Context(Context), EmptySubobjects(EmptySubobjects), Size(0), 650 Alignment(CharUnits::One()), UnpackedAlignment(CharUnits::One()), 651 ExternalLayout(false), InferAlignment(false), 652 Packed(false), IsUnion(false), IsMac68kAlign(false), IsMsStruct(false), 653 UnfilledBitsInLastByte(0), MaxFieldAlignment(CharUnits::Zero()), 654 DataSize(0), NonVirtualSize(CharUnits::Zero()), 655 NonVirtualAlignment(CharUnits::One()), 656 ZeroLengthBitfield(0), PrimaryBase(0), 657 PrimaryBaseIsVirtual(false), 658 HasOwnVFPtr(false), 659 VBPtrOffset(CharUnits::fromQuantity(-1)), 660 FirstNearlyEmptyVBase(0) { } 661 662 /// Reset this RecordLayoutBuilder to a fresh state, using the given 663 /// alignment as the initial alignment. This is used for the 664 /// correct layout of vb-table pointers in MSVC. 665 void resetWithTargetAlignment(CharUnits TargetAlignment) { 666 const ASTContext &Context = this->Context; 667 EmptySubobjectMap *EmptySubobjects = this->EmptySubobjects; 668 this->~RecordLayoutBuilder(); 669 new (this) RecordLayoutBuilder(Context, EmptySubobjects); 670 Alignment = UnpackedAlignment = TargetAlignment; 671 } 672 673 void Layout(const RecordDecl *D); 674 void Layout(const CXXRecordDecl *D); 675 void Layout(const ObjCInterfaceDecl *D); 676 677 void LayoutFields(const RecordDecl *D); 678 void LayoutField(const FieldDecl *D); 679 void LayoutWideBitField(uint64_t FieldSize, uint64_t TypeSize, 680 bool FieldPacked, const FieldDecl *D); 681 void LayoutBitField(const FieldDecl *D); 682 683 bool isMicrosoftCXXABI() const { 684 return Context.getTargetInfo().getCXXABI() == CXXABI_Microsoft; 685 } 686 687 void MSLayoutVirtualBases(const CXXRecordDecl *RD); 688 689 /// BaseSubobjectInfoAllocator - Allocator for BaseSubobjectInfo objects. 690 llvm::SpecificBumpPtrAllocator<BaseSubobjectInfo> BaseSubobjectInfoAllocator; 691 692 typedef llvm::DenseMap<const CXXRecordDecl *, BaseSubobjectInfo *> 693 BaseSubobjectInfoMapTy; 694 695 /// VirtualBaseInfo - Map from all the (direct or indirect) virtual bases 696 /// of the class we're laying out to their base subobject info. 697 BaseSubobjectInfoMapTy VirtualBaseInfo; 698 699 /// NonVirtualBaseInfo - Map from all the direct non-virtual bases of the 700 /// class we're laying out to their base subobject info. 701 BaseSubobjectInfoMapTy NonVirtualBaseInfo; 702 703 /// ComputeBaseSubobjectInfo - Compute the base subobject information for the 704 /// bases of the given class. 705 void ComputeBaseSubobjectInfo(const CXXRecordDecl *RD); 706 707 /// ComputeBaseSubobjectInfo - Compute the base subobject information for a 708 /// single class and all of its base classes. 709 BaseSubobjectInfo *ComputeBaseSubobjectInfo(const CXXRecordDecl *RD, 710 bool IsVirtual, 711 BaseSubobjectInfo *Derived); 712 713 /// DeterminePrimaryBase - Determine the primary base of the given class. 714 void DeterminePrimaryBase(const CXXRecordDecl *RD); 715 716 void SelectPrimaryVBase(const CXXRecordDecl *RD); 717 718 void EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign); 719 720 /// LayoutNonVirtualBases - Determines the primary base class (if any) and 721 /// lays it out. Will then proceed to lay out all non-virtual base clasess. 722 void LayoutNonVirtualBases(const CXXRecordDecl *RD); 723 724 /// LayoutNonVirtualBase - Lays out a single non-virtual base. 725 void LayoutNonVirtualBase(const BaseSubobjectInfo *Base); 726 727 void AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info, 728 CharUnits Offset); 729 730 bool needsVFTable(const CXXRecordDecl *RD) const; 731 bool hasNewVirtualFunction(const CXXRecordDecl *RD, 732 bool IgnoreDestructor = false) const; 733 bool isPossiblePrimaryBase(const CXXRecordDecl *Base) const; 734 735 void computeVtordisps(const CXXRecordDecl *RD, 736 ClassSetTy &VtordispVBases); 737 738 /// LayoutVirtualBases - Lays out all the virtual bases. 739 void LayoutVirtualBases(const CXXRecordDecl *RD, 740 const CXXRecordDecl *MostDerivedClass); 741 742 /// LayoutVirtualBase - Lays out a single virtual base. 743 void LayoutVirtualBase(const BaseSubobjectInfo *Base, 744 bool IsVtordispNeed = false); 745 746 /// LayoutBase - Will lay out a base and return the offset where it was 747 /// placed, in chars. 748 CharUnits LayoutBase(const BaseSubobjectInfo *Base); 749 750 /// InitializeLayout - Initialize record layout for the given record decl. 751 void InitializeLayout(const Decl *D); 752 753 /// FinishLayout - Finalize record layout. Adjust record size based on the 754 /// alignment. 755 void FinishLayout(const NamedDecl *D); 756 757 void UpdateAlignment(CharUnits NewAlignment, CharUnits UnpackedNewAlignment); 758 void UpdateAlignment(CharUnits NewAlignment) { 759 UpdateAlignment(NewAlignment, NewAlignment); 760 } 761 762 /// \brief Retrieve the externally-supplied field offset for the given 763 /// field. 764 /// 765 /// \param Field The field whose offset is being queried. 766 /// \param ComputedOffset The offset that we've computed for this field. 767 uint64_t updateExternalFieldOffset(const FieldDecl *Field, 768 uint64_t ComputedOffset); 769 770 void CheckFieldPadding(uint64_t Offset, uint64_t UnpaddedOffset, 771 uint64_t UnpackedOffset, unsigned UnpackedAlign, 772 bool isPacked, const FieldDecl *D); 773 774 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID); 775 776 CharUnits getSize() const { 777 assert(Size % Context.getCharWidth() == 0); 778 return Context.toCharUnitsFromBits(Size); 779 } 780 uint64_t getSizeInBits() const { return Size; } 781 782 void setSize(CharUnits NewSize) { Size = Context.toBits(NewSize); } 783 void setSize(uint64_t NewSize) { Size = NewSize; } 784 785 CharUnits getAligment() const { return Alignment; } 786 787 CharUnits getDataSize() const { 788 assert(DataSize % Context.getCharWidth() == 0); 789 return Context.toCharUnitsFromBits(DataSize); 790 } 791 uint64_t getDataSizeInBits() const { return DataSize; } 792 793 void setDataSize(CharUnits NewSize) { DataSize = Context.toBits(NewSize); } 794 void setDataSize(uint64_t NewSize) { DataSize = NewSize; } 795 796 RecordLayoutBuilder(const RecordLayoutBuilder&); // DO NOT IMPLEMENT 797 void operator=(const RecordLayoutBuilder&); // DO NOT IMPLEMENT 798 public: 799 static const CXXMethodDecl *ComputeKeyFunction(const CXXRecordDecl *RD); 800 }; 801 } // end anonymous namespace 802 803 void 804 RecordLayoutBuilder::SelectPrimaryVBase(const CXXRecordDecl *RD) { 805 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 806 E = RD->bases_end(); I != E; ++I) { 807 assert(!I->getType()->isDependentType() && 808 "Cannot layout class with dependent bases."); 809 810 const CXXRecordDecl *Base = 811 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl()); 812 813 // Check if this is a nearly empty virtual base. 814 if (I->isVirtual() && Context.isNearlyEmpty(Base)) { 815 // If it's not an indirect primary base, then we've found our primary 816 // base. 817 if (!IndirectPrimaryBases.count(Base)) { 818 PrimaryBase = Base; 819 PrimaryBaseIsVirtual = true; 820 return; 821 } 822 823 // Is this the first nearly empty virtual base? 824 if (!FirstNearlyEmptyVBase) 825 FirstNearlyEmptyVBase = Base; 826 } 827 828 SelectPrimaryVBase(Base); 829 if (PrimaryBase) 830 return; 831 } 832 } 833 834 /// DeterminePrimaryBase - Determine the primary base of the given class. 835 void RecordLayoutBuilder::DeterminePrimaryBase(const CXXRecordDecl *RD) { 836 // If the class isn't dynamic, it won't have a primary base. 837 if (!RD->isDynamicClass()) 838 return; 839 840 // Compute all the primary virtual bases for all of our direct and 841 // indirect bases, and record all their primary virtual base classes. 842 RD->getIndirectPrimaryBases(IndirectPrimaryBases); 843 844 // If the record has a dynamic base class, attempt to choose a primary base 845 // class. It is the first (in direct base class order) non-virtual dynamic 846 // base class, if one exists. 847 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(), 848 e = RD->bases_end(); i != e; ++i) { 849 // Ignore virtual bases. 850 if (i->isVirtual()) 851 continue; 852 853 const CXXRecordDecl *Base = 854 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl()); 855 856 if (isPossiblePrimaryBase(Base)) { 857 // We found it. 858 PrimaryBase = Base; 859 PrimaryBaseIsVirtual = false; 860 return; 861 } 862 } 863 864 // The Microsoft ABI doesn't have primary virtual bases. 865 if (isMicrosoftCXXABI()) { 866 assert(!PrimaryBase && "Should not get here with a primary base!"); 867 return; 868 } 869 870 // Under the Itanium ABI, if there is no non-virtual primary base class, 871 // try to compute the primary virtual base. The primary virtual base is 872 // the first nearly empty virtual base that is not an indirect primary 873 // virtual base class, if one exists. 874 if (RD->getNumVBases() != 0) { 875 SelectPrimaryVBase(RD); 876 if (PrimaryBase) 877 return; 878 } 879 880 // Otherwise, it is the first indirect primary base class, if one exists. 881 if (FirstNearlyEmptyVBase) { 882 PrimaryBase = FirstNearlyEmptyVBase; 883 PrimaryBaseIsVirtual = true; 884 return; 885 } 886 887 assert(!PrimaryBase && "Should not get here with a primary base!"); 888 } 889 890 BaseSubobjectInfo * 891 RecordLayoutBuilder::ComputeBaseSubobjectInfo(const CXXRecordDecl *RD, 892 bool IsVirtual, 893 BaseSubobjectInfo *Derived) { 894 BaseSubobjectInfo *Info; 895 896 if (IsVirtual) { 897 // Check if we already have info about this virtual base. 898 BaseSubobjectInfo *&InfoSlot = VirtualBaseInfo[RD]; 899 if (InfoSlot) { 900 assert(InfoSlot->Class == RD && "Wrong class for virtual base info!"); 901 return InfoSlot; 902 } 903 904 // We don't, create it. 905 InfoSlot = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo; 906 Info = InfoSlot; 907 } else { 908 Info = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo; 909 } 910 911 Info->Class = RD; 912 Info->IsVirtual = IsVirtual; 913 Info->Derived = 0; 914 Info->PrimaryVirtualBaseInfo = 0; 915 916 const CXXRecordDecl *PrimaryVirtualBase = 0; 917 BaseSubobjectInfo *PrimaryVirtualBaseInfo = 0; 918 919 // Check if this base has a primary virtual base. 920 if (RD->getNumVBases()) { 921 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 922 if (Layout.isPrimaryBaseVirtual()) { 923 // This base does have a primary virtual base. 924 PrimaryVirtualBase = Layout.getPrimaryBase(); 925 assert(PrimaryVirtualBase && "Didn't have a primary virtual base!"); 926 927 // Now check if we have base subobject info about this primary base. 928 PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase); 929 930 if (PrimaryVirtualBaseInfo) { 931 if (PrimaryVirtualBaseInfo->Derived) { 932 // We did have info about this primary base, and it turns out that it 933 // has already been claimed as a primary virtual base for another 934 // base. 935 PrimaryVirtualBase = 0; 936 } else { 937 // We can claim this base as our primary base. 938 Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo; 939 PrimaryVirtualBaseInfo->Derived = Info; 940 } 941 } 942 } 943 } 944 945 // Now go through all direct bases. 946 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 947 E = RD->bases_end(); I != E; ++I) { 948 bool IsVirtual = I->isVirtual(); 949 950 const CXXRecordDecl *BaseDecl = 951 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl()); 952 953 Info->Bases.push_back(ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, Info)); 954 } 955 956 if (PrimaryVirtualBase && !PrimaryVirtualBaseInfo) { 957 // Traversing the bases must have created the base info for our primary 958 // virtual base. 959 PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase); 960 assert(PrimaryVirtualBaseInfo && 961 "Did not create a primary virtual base!"); 962 963 // Claim the primary virtual base as our primary virtual base. 964 Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo; 965 PrimaryVirtualBaseInfo->Derived = Info; 966 } 967 968 return Info; 969 } 970 971 void RecordLayoutBuilder::ComputeBaseSubobjectInfo(const CXXRecordDecl *RD) { 972 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 973 E = RD->bases_end(); I != E; ++I) { 974 bool IsVirtual = I->isVirtual(); 975 976 const CXXRecordDecl *BaseDecl = 977 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl()); 978 979 // Compute the base subobject info for this base. 980 BaseSubobjectInfo *Info = ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, 0); 981 982 if (IsVirtual) { 983 // ComputeBaseInfo has already added this base for us. 984 assert(VirtualBaseInfo.count(BaseDecl) && 985 "Did not add virtual base!"); 986 } else { 987 // Add the base info to the map of non-virtual bases. 988 assert(!NonVirtualBaseInfo.count(BaseDecl) && 989 "Non-virtual base already exists!"); 990 NonVirtualBaseInfo.insert(std::make_pair(BaseDecl, Info)); 991 } 992 } 993 } 994 995 void 996 RecordLayoutBuilder::EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign) { 997 CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign; 998 999 // The maximum field alignment overrides base align. 1000 if (!MaxFieldAlignment.isZero()) { 1001 BaseAlign = std::min(BaseAlign, MaxFieldAlignment); 1002 UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment); 1003 } 1004 1005 // Round up the current record size to pointer alignment. 1006 setSize(getSize().RoundUpToAlignment(BaseAlign)); 1007 setDataSize(getSize()); 1008 1009 // Update the alignment. 1010 UpdateAlignment(BaseAlign, UnpackedBaseAlign); 1011 } 1012 1013 void 1014 RecordLayoutBuilder::LayoutNonVirtualBases(const CXXRecordDecl *RD) { 1015 // Then, determine the primary base class. 1016 DeterminePrimaryBase(RD); 1017 1018 // Compute base subobject info. 1019 ComputeBaseSubobjectInfo(RD); 1020 1021 // If we have a primary base class, lay it out. 1022 if (PrimaryBase) { 1023 if (PrimaryBaseIsVirtual) { 1024 // If the primary virtual base was a primary virtual base of some other 1025 // base class we'll have to steal it. 1026 BaseSubobjectInfo *PrimaryBaseInfo = VirtualBaseInfo.lookup(PrimaryBase); 1027 PrimaryBaseInfo->Derived = 0; 1028 1029 // We have a virtual primary base, insert it as an indirect primary base. 1030 IndirectPrimaryBases.insert(PrimaryBase); 1031 1032 assert(!VisitedVirtualBases.count(PrimaryBase) && 1033 "vbase already visited!"); 1034 VisitedVirtualBases.insert(PrimaryBase); 1035 1036 LayoutVirtualBase(PrimaryBaseInfo); 1037 } else { 1038 BaseSubobjectInfo *PrimaryBaseInfo = 1039 NonVirtualBaseInfo.lookup(PrimaryBase); 1040 assert(PrimaryBaseInfo && 1041 "Did not find base info for non-virtual primary base!"); 1042 1043 LayoutNonVirtualBase(PrimaryBaseInfo); 1044 } 1045 1046 // If this class needs a vtable/vf-table and didn't get one from a 1047 // primary base, add it in now. 1048 } else if (needsVFTable(RD)) { 1049 assert(DataSize == 0 && "Vtable pointer must be at offset zero!"); 1050 CharUnits PtrWidth = 1051 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0)); 1052 CharUnits PtrAlign = 1053 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(0)); 1054 EnsureVTablePointerAlignment(PtrAlign); 1055 HasOwnVFPtr = true; 1056 setSize(getSize() + PtrWidth); 1057 setDataSize(getSize()); 1058 } 1059 1060 bool HasDirectVirtualBases = false; 1061 bool HasNonVirtualBaseWithVBTable = false; 1062 1063 // Now lay out the non-virtual bases. 1064 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 1065 E = RD->bases_end(); I != E; ++I) { 1066 1067 // Ignore virtual bases, but remember that we saw one. 1068 if (I->isVirtual()) { 1069 HasDirectVirtualBases = true; 1070 continue; 1071 } 1072 1073 const CXXRecordDecl *BaseDecl = 1074 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl()); 1075 1076 // Remember if this base has virtual bases itself. 1077 if (BaseDecl->getNumVBases()) 1078 HasNonVirtualBaseWithVBTable = true; 1079 1080 // Skip the primary base, because we've already laid it out. The 1081 // !PrimaryBaseIsVirtual check is required because we might have a 1082 // non-virtual base of the same type as a primary virtual base. 1083 if (BaseDecl == PrimaryBase && !PrimaryBaseIsVirtual) 1084 continue; 1085 1086 // Lay out the base. 1087 BaseSubobjectInfo *BaseInfo = NonVirtualBaseInfo.lookup(BaseDecl); 1088 assert(BaseInfo && "Did not find base info for non-virtual base!"); 1089 1090 LayoutNonVirtualBase(BaseInfo); 1091 } 1092 1093 // In the MS ABI, add the vb-table pointer if we need one, which is 1094 // whenever we have a virtual base and we can't re-use a vb-table 1095 // pointer from a non-virtual base. 1096 if (isMicrosoftCXXABI() && 1097 HasDirectVirtualBases && !HasNonVirtualBaseWithVBTable) { 1098 CharUnits PtrWidth = 1099 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0)); 1100 CharUnits PtrAlign = 1101 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(0)); 1102 1103 // MSVC potentially over-aligns the vb-table pointer by giving it 1104 // the max alignment of all the non-virtual objects in the class. 1105 // This is completely unnecessary, but we're not here to pass 1106 // judgment. 1107 // 1108 // Note that we've only laid out the non-virtual bases, so on the 1109 // first pass Alignment won't be set correctly here, but if the 1110 // vb-table doesn't end up aligned correctly we'll come through 1111 // and redo the layout from scratch with the right alignment. 1112 // 1113 // TODO: Instead of doing this, just lay out the fields as if the 1114 // vb-table were at offset zero, then retroactively bump the field 1115 // offsets up. 1116 PtrAlign = std::max(PtrAlign, Alignment); 1117 1118 EnsureVTablePointerAlignment(PtrAlign); 1119 VBPtrOffset = getSize(); 1120 setSize(getSize() + PtrWidth); 1121 setDataSize(getSize()); 1122 } 1123 } 1124 1125 void RecordLayoutBuilder::LayoutNonVirtualBase(const BaseSubobjectInfo *Base) { 1126 // Layout the base. 1127 CharUnits Offset = LayoutBase(Base); 1128 1129 // Add its base class offset. 1130 assert(!Bases.count(Base->Class) && "base offset already exists!"); 1131 Bases.insert(std::make_pair(Base->Class, Offset)); 1132 1133 AddPrimaryVirtualBaseOffsets(Base, Offset); 1134 } 1135 1136 void 1137 RecordLayoutBuilder::AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info, 1138 CharUnits Offset) { 1139 // This base isn't interesting, it has no virtual bases. 1140 if (!Info->Class->getNumVBases()) 1141 return; 1142 1143 // First, check if we have a virtual primary base to add offsets for. 1144 if (Info->PrimaryVirtualBaseInfo) { 1145 assert(Info->PrimaryVirtualBaseInfo->IsVirtual && 1146 "Primary virtual base is not virtual!"); 1147 if (Info->PrimaryVirtualBaseInfo->Derived == Info) { 1148 // Add the offset. 1149 assert(!VBases.count(Info->PrimaryVirtualBaseInfo->Class) && 1150 "primary vbase offset already exists!"); 1151 VBases.insert(std::make_pair(Info->PrimaryVirtualBaseInfo->Class, 1152 ASTRecordLayout::VBaseInfo(Offset, false))); 1153 1154 // Traverse the primary virtual base. 1155 AddPrimaryVirtualBaseOffsets(Info->PrimaryVirtualBaseInfo, Offset); 1156 } 1157 } 1158 1159 // Now go through all direct non-virtual bases. 1160 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class); 1161 for (unsigned I = 0, E = Info->Bases.size(); I != E; ++I) { 1162 const BaseSubobjectInfo *Base = Info->Bases[I]; 1163 if (Base->IsVirtual) 1164 continue; 1165 1166 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class); 1167 AddPrimaryVirtualBaseOffsets(Base, BaseOffset); 1168 } 1169 } 1170 1171 /// needsVFTable - Return true if this class needs a vtable or vf-table 1172 /// when laid out as a base class. These are treated the same because 1173 /// they're both always laid out at offset zero. 1174 /// 1175 /// This function assumes that the class has no primary base. 1176 bool RecordLayoutBuilder::needsVFTable(const CXXRecordDecl *RD) const { 1177 assert(!PrimaryBase); 1178 1179 // In the Itanium ABI, every dynamic class needs a vtable: even if 1180 // this class has no virtual functions as a base class (i.e. it's 1181 // non-polymorphic or only has virtual functions from virtual 1182 // bases),x it still needs a vtable to locate its virtual bases. 1183 if (!isMicrosoftCXXABI()) 1184 return RD->isDynamicClass(); 1185 1186 // In the MS ABI, we need a vfptr if the class has virtual functions 1187 // other than those declared by its virtual bases. The AST doesn't 1188 // tell us that directly, and checking manually for virtual 1189 // functions that aren't overrides is expensive, but there are 1190 // some important shortcuts: 1191 1192 // - Non-polymorphic classes have no virtual functions at all. 1193 if (!RD->isPolymorphic()) return false; 1194 1195 // - Polymorphic classes with no virtual bases must either declare 1196 // virtual functions directly or inherit them, but in the latter 1197 // case we would have a primary base. 1198 if (RD->getNumVBases() == 0) return true; 1199 1200 return hasNewVirtualFunction(RD); 1201 } 1202 1203 /// Does the given class inherit non-virtually from any of the classes 1204 /// in the given set? 1205 static bool hasNonVirtualBaseInSet(const CXXRecordDecl *RD, 1206 const ClassSetTy &set) { 1207 for (CXXRecordDecl::base_class_const_iterator 1208 I = RD->bases_begin(), E = RD->bases_end(); I != E; ++I) { 1209 // Ignore virtual links. 1210 if (I->isVirtual()) continue; 1211 1212 // Check whether the set contains the base. 1213 const CXXRecordDecl *base = I->getType()->getAsCXXRecordDecl(); 1214 if (set.count(base)) 1215 return true; 1216 1217 // Otherwise, recurse and propagate. 1218 if (hasNonVirtualBaseInSet(base, set)) 1219 return true; 1220 } 1221 1222 return false; 1223 } 1224 1225 /// Does the given method (B::foo()) already override a method (A::foo()) 1226 /// such that A requires a vtordisp in B? If so, we don't need to add a 1227 /// new vtordisp for B in a yet-more-derived class C providing C::foo(). 1228 static bool overridesMethodRequiringVtorDisp(const ASTContext &Context, 1229 const CXXMethodDecl *M) { 1230 CXXMethodDecl::method_iterator 1231 I = M->begin_overridden_methods(), E = M->end_overridden_methods(); 1232 if (I == E) return false; 1233 1234 const ASTRecordLayout::VBaseOffsetsMapTy &offsets = 1235 Context.getASTRecordLayout(M->getParent()).getVBaseOffsetsMap(); 1236 do { 1237 const CXXMethodDecl *overridden = *I; 1238 1239 // If the overridden method's class isn't recognized as a virtual 1240 // base in the derived class, ignore it. 1241 ASTRecordLayout::VBaseOffsetsMapTy::const_iterator 1242 it = offsets.find(overridden->getParent()); 1243 if (it == offsets.end()) continue; 1244 1245 // Otherwise, check if the overridden method's class needs a vtordisp. 1246 if (it->second.hasVtorDisp()) return true; 1247 1248 } while (++I != E); 1249 return false; 1250 } 1251 1252 /// In the Microsoft ABI, decide which of the virtual bases require a 1253 /// vtordisp field. 1254 void RecordLayoutBuilder::computeVtordisps(const CXXRecordDecl *RD, 1255 ClassSetTy &vtordispVBases) { 1256 // Bail out if we have no virtual bases. 1257 assert(RD->getNumVBases()); 1258 1259 // Build up the set of virtual bases that we haven't decided yet. 1260 ClassSetTy undecidedVBases; 1261 for (CXXRecordDecl::base_class_const_iterator 1262 I = RD->vbases_begin(), E = RD->vbases_end(); I != E; ++I) { 1263 const CXXRecordDecl *vbase = I->getType()->getAsCXXRecordDecl(); 1264 undecidedVBases.insert(vbase); 1265 } 1266 assert(!undecidedVBases.empty()); 1267 1268 // A virtual base requires a vtordisp field in a derived class if it 1269 // requires a vtordisp field in a base class. Walk all the direct 1270 // bases and collect this information. 1271 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 1272 E = RD->bases_end(); I != E; ++I) { 1273 const CXXRecordDecl *base = I->getType()->getAsCXXRecordDecl(); 1274 const ASTRecordLayout &baseLayout = Context.getASTRecordLayout(base); 1275 1276 // Iterate over the set of virtual bases provided by this class. 1277 for (ASTRecordLayout::VBaseOffsetsMapTy::const_iterator 1278 VI = baseLayout.getVBaseOffsetsMap().begin(), 1279 VE = baseLayout.getVBaseOffsetsMap().end(); VI != VE; ++VI) { 1280 // If it doesn't need a vtordisp in this base, ignore it. 1281 if (!VI->second.hasVtorDisp()) continue; 1282 1283 // If we've already seen it and decided it needs a vtordisp, ignore it. 1284 if (!undecidedVBases.erase(VI->first)) 1285 continue; 1286 1287 // Add it. 1288 vtordispVBases.insert(VI->first); 1289 1290 // Quit as soon as we've decided everything. 1291 if (undecidedVBases.empty()) 1292 return; 1293 } 1294 } 1295 1296 // Okay, we have virtual bases that we haven't yet decided about. A 1297 // virtual base requires a vtordisp if any the non-destructor 1298 // virtual methods declared in this class directly override a method 1299 // provided by that virtual base. (If so, we need to emit a thunk 1300 // for that method, to be used in the construction vftable, which 1301 // applies an additional 'vtordisp' this-adjustment.) 1302 1303 // Collect the set of bases directly overridden by any method in this class. 1304 // It's possible that some of these classes won't be virtual bases, or won't be 1305 // provided by virtual bases, or won't be virtual bases in the overridden 1306 // instance but are virtual bases elsewhere. Only the last matters for what 1307 // we're doing, and we can ignore those: if we don't directly override 1308 // a method provided by a virtual copy of a base class, but we do directly 1309 // override a method provided by a non-virtual copy of that base class, 1310 // then we must indirectly override the method provided by the virtual base, 1311 // and so we should already have collected it in the loop above. 1312 ClassSetTy overriddenBases; 1313 for (CXXRecordDecl::method_iterator 1314 M = RD->method_begin(), E = RD->method_end(); M != E; ++M) { 1315 // Ignore non-virtual methods and destructors. 1316 if (isa<CXXDestructorDecl>(*M) || !M->isVirtual()) 1317 continue; 1318 1319 for (CXXMethodDecl::method_iterator I = M->begin_overridden_methods(), 1320 E = M->end_overridden_methods(); I != E; ++I) { 1321 const CXXMethodDecl *overriddenMethod = (*I); 1322 1323 // Ignore methods that override methods from vbases that require 1324 // require vtordisps. 1325 if (overridesMethodRequiringVtorDisp(Context, overriddenMethod)) 1326 continue; 1327 1328 // As an optimization, check immediately whether we're overriding 1329 // something from the undecided set. 1330 const CXXRecordDecl *overriddenBase = overriddenMethod->getParent(); 1331 if (undecidedVBases.erase(overriddenBase)) { 1332 vtordispVBases.insert(overriddenBase); 1333 if (undecidedVBases.empty()) return; 1334 1335 // We can't 'continue;' here because one of our undecided 1336 // vbases might non-virtually inherit from this base. 1337 // Consider: 1338 // struct A { virtual void foo(); }; 1339 // struct B : A {}; 1340 // struct C : virtual A, virtual B { virtual void foo(); }; 1341 // We need a vtordisp for B here. 1342 } 1343 1344 // Otherwise, just collect it. 1345 overriddenBases.insert(overriddenBase); 1346 } 1347 } 1348 1349 // Walk the undecided v-bases and check whether they (non-virtually) 1350 // provide any of the overridden bases. We don't need to consider 1351 // virtual links because the vtordisp inheres to the layout 1352 // subobject containing the base. 1353 for (ClassSetTy::const_iterator 1354 I = undecidedVBases.begin(), E = undecidedVBases.end(); I != E; ++I) { 1355 if (hasNonVirtualBaseInSet(*I, overriddenBases)) 1356 vtordispVBases.insert(*I); 1357 } 1358 } 1359 1360 /// hasNewVirtualFunction - Does the given polymorphic class declare a 1361 /// virtual function that does not override a method from any of its 1362 /// base classes? 1363 bool 1364 RecordLayoutBuilder::hasNewVirtualFunction(const CXXRecordDecl *RD, 1365 bool IgnoreDestructor) const { 1366 if (!RD->getNumBases()) 1367 return true; 1368 1369 for (CXXRecordDecl::method_iterator method = RD->method_begin(); 1370 method != RD->method_end(); 1371 ++method) { 1372 if (method->isVirtual() && !method->size_overridden_methods() && 1373 !(IgnoreDestructor && method->getKind() == Decl::CXXDestructor)) { 1374 return true; 1375 } 1376 } 1377 return false; 1378 } 1379 1380 /// isPossiblePrimaryBase - Is the given base class an acceptable 1381 /// primary base class? 1382 bool 1383 RecordLayoutBuilder::isPossiblePrimaryBase(const CXXRecordDecl *base) const { 1384 // In the Itanium ABI, a class can be a primary base class if it has 1385 // a vtable for any reason. 1386 if (!isMicrosoftCXXABI()) 1387 return base->isDynamicClass(); 1388 1389 // In the MS ABI, a class can only be a primary base class if it 1390 // provides a vf-table at a static offset. That means it has to be 1391 // non-virtual base. The existence of a separate vb-table means 1392 // that it's possible to get virtual functions only from a virtual 1393 // base, which we have to guard against. 1394 1395 // First off, it has to have virtual functions. 1396 if (!base->isPolymorphic()) return false; 1397 1398 // If it has no virtual bases, then the vfptr must be at a static offset. 1399 if (!base->getNumVBases()) return true; 1400 1401 // Otherwise, the necessary information is cached in the layout. 1402 const ASTRecordLayout &layout = Context.getASTRecordLayout(base); 1403 1404 // If the base has its own vfptr, it can be a primary base. 1405 if (layout.hasOwnVFPtr()) return true; 1406 1407 // If the base has a primary base class, then it can be a primary base. 1408 if (layout.getPrimaryBase()) return true; 1409 1410 // Otherwise it can't. 1411 return false; 1412 } 1413 1414 void 1415 RecordLayoutBuilder::LayoutVirtualBases(const CXXRecordDecl *RD, 1416 const CXXRecordDecl *MostDerivedClass) { 1417 const CXXRecordDecl *PrimaryBase; 1418 bool PrimaryBaseIsVirtual; 1419 1420 if (MostDerivedClass == RD) { 1421 PrimaryBase = this->PrimaryBase; 1422 PrimaryBaseIsVirtual = this->PrimaryBaseIsVirtual; 1423 } else { 1424 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 1425 PrimaryBase = Layout.getPrimaryBase(); 1426 PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual(); 1427 } 1428 1429 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 1430 E = RD->bases_end(); I != E; ++I) { 1431 assert(!I->getType()->isDependentType() && 1432 "Cannot layout class with dependent bases."); 1433 1434 const CXXRecordDecl *BaseDecl = 1435 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl()); 1436 1437 if (I->isVirtual()) { 1438 if (PrimaryBase != BaseDecl || !PrimaryBaseIsVirtual) { 1439 bool IndirectPrimaryBase = IndirectPrimaryBases.count(BaseDecl); 1440 1441 // Only lay out the virtual base if it's not an indirect primary base. 1442 if (!IndirectPrimaryBase) { 1443 // Only visit virtual bases once. 1444 if (!VisitedVirtualBases.insert(BaseDecl)) 1445 continue; 1446 1447 const BaseSubobjectInfo *BaseInfo = VirtualBaseInfo.lookup(BaseDecl); 1448 assert(BaseInfo && "Did not find virtual base info!"); 1449 LayoutVirtualBase(BaseInfo); 1450 } 1451 } 1452 } 1453 1454 if (!BaseDecl->getNumVBases()) { 1455 // This base isn't interesting since it doesn't have any virtual bases. 1456 continue; 1457 } 1458 1459 LayoutVirtualBases(BaseDecl, MostDerivedClass); 1460 } 1461 } 1462 1463 void RecordLayoutBuilder::MSLayoutVirtualBases(const CXXRecordDecl *RD) { 1464 if (!RD->getNumVBases()) 1465 return; 1466 1467 ClassSetTy VtordispVBases; 1468 computeVtordisps(RD, VtordispVBases); 1469 1470 // This is substantially simplified because there are no virtual 1471 // primary bases. 1472 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(), 1473 E = RD->vbases_end(); I != E; ++I) { 1474 const CXXRecordDecl *BaseDecl = I->getType()->getAsCXXRecordDecl(); 1475 const BaseSubobjectInfo *BaseInfo = VirtualBaseInfo.lookup(BaseDecl); 1476 assert(BaseInfo && "Did not find virtual base info!"); 1477 1478 // If this base requires a vtordisp, add enough space for an int field. 1479 // This is apparently always 32-bits, even on x64. 1480 bool vtordispNeeded = false; 1481 if (VtordispVBases.count(BaseDecl)) { 1482 CharUnits IntSize = 1483 CharUnits::fromQuantity(Context.getTargetInfo().getIntWidth() / 8); 1484 1485 setSize(getSize() + IntSize); 1486 setDataSize(getSize()); 1487 vtordispNeeded = true; 1488 } 1489 1490 LayoutVirtualBase(BaseInfo, vtordispNeeded); 1491 } 1492 } 1493 1494 void RecordLayoutBuilder::LayoutVirtualBase(const BaseSubobjectInfo *Base, 1495 bool IsVtordispNeed) { 1496 assert(!Base->Derived && "Trying to lay out a primary virtual base!"); 1497 1498 // Layout the base. 1499 CharUnits Offset = LayoutBase(Base); 1500 1501 // Add its base class offset. 1502 assert(!VBases.count(Base->Class) && "vbase offset already exists!"); 1503 VBases.insert(std::make_pair(Base->Class, 1504 ASTRecordLayout::VBaseInfo(Offset, IsVtordispNeed))); 1505 1506 if (!isMicrosoftCXXABI()) 1507 AddPrimaryVirtualBaseOffsets(Base, Offset); 1508 } 1509 1510 CharUnits RecordLayoutBuilder::LayoutBase(const BaseSubobjectInfo *Base) { 1511 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base->Class); 1512 1513 1514 CharUnits Offset; 1515 1516 // Query the external layout to see if it provides an offset. 1517 bool HasExternalLayout = false; 1518 if (ExternalLayout) { 1519 llvm::DenseMap<const CXXRecordDecl *, CharUnits>::iterator Known; 1520 if (Base->IsVirtual) { 1521 Known = ExternalVirtualBaseOffsets.find(Base->Class); 1522 if (Known != ExternalVirtualBaseOffsets.end()) { 1523 Offset = Known->second; 1524 HasExternalLayout = true; 1525 } 1526 } else { 1527 Known = ExternalBaseOffsets.find(Base->Class); 1528 if (Known != ExternalBaseOffsets.end()) { 1529 Offset = Known->second; 1530 HasExternalLayout = true; 1531 } 1532 } 1533 } 1534 1535 // If we have an empty base class, try to place it at offset 0. 1536 if (Base->Class->isEmpty() && 1537 (!HasExternalLayout || Offset == CharUnits::Zero()) && 1538 EmptySubobjects->CanPlaceBaseAtOffset(Base, CharUnits::Zero())) { 1539 setSize(std::max(getSize(), Layout.getSize())); 1540 1541 return CharUnits::Zero(); 1542 } 1543 1544 CharUnits UnpackedBaseAlign = Layout.getNonVirtualAlign(); 1545 CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign; 1546 1547 // The maximum field alignment overrides base align. 1548 if (!MaxFieldAlignment.isZero()) { 1549 BaseAlign = std::min(BaseAlign, MaxFieldAlignment); 1550 UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment); 1551 } 1552 1553 if (!HasExternalLayout) { 1554 // Round up the current record size to the base's alignment boundary. 1555 Offset = getDataSize().RoundUpToAlignment(BaseAlign); 1556 1557 // Try to place the base. 1558 while (!EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset)) 1559 Offset += BaseAlign; 1560 } else { 1561 bool Allowed = EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset); 1562 (void)Allowed; 1563 assert(Allowed && "Base subobject externally placed at overlapping offset"); 1564 } 1565 1566 if (!Base->Class->isEmpty()) { 1567 // Update the data size. 1568 setDataSize(Offset + Layout.getNonVirtualSize()); 1569 1570 setSize(std::max(getSize(), getDataSize())); 1571 } else 1572 setSize(std::max(getSize(), Offset + Layout.getSize())); 1573 1574 // Remember max struct/class alignment. 1575 UpdateAlignment(BaseAlign, UnpackedBaseAlign); 1576 1577 return Offset; 1578 } 1579 1580 void RecordLayoutBuilder::InitializeLayout(const Decl *D) { 1581 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) 1582 IsUnion = RD->isUnion(); 1583 1584 Packed = D->hasAttr<PackedAttr>(); 1585 1586 IsMsStruct = D->hasAttr<MsStructAttr>(); 1587 1588 // Honor the default struct packing maximum alignment flag. 1589 if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct) { 1590 MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment); 1591 } 1592 1593 // mac68k alignment supersedes maximum field alignment and attribute aligned, 1594 // and forces all structures to have 2-byte alignment. The IBM docs on it 1595 // allude to additional (more complicated) semantics, especially with regard 1596 // to bit-fields, but gcc appears not to follow that. 1597 if (D->hasAttr<AlignMac68kAttr>()) { 1598 IsMac68kAlign = true; 1599 MaxFieldAlignment = CharUnits::fromQuantity(2); 1600 Alignment = CharUnits::fromQuantity(2); 1601 } else { 1602 if (const MaxFieldAlignmentAttr *MFAA = D->getAttr<MaxFieldAlignmentAttr>()) 1603 MaxFieldAlignment = Context.toCharUnitsFromBits(MFAA->getAlignment()); 1604 1605 if (unsigned MaxAlign = D->getMaxAlignment()) 1606 UpdateAlignment(Context.toCharUnitsFromBits(MaxAlign)); 1607 } 1608 1609 // If there is an external AST source, ask it for the various offsets. 1610 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) 1611 if (ExternalASTSource *External = Context.getExternalSource()) { 1612 ExternalLayout = External->layoutRecordType(RD, 1613 ExternalSize, 1614 ExternalAlign, 1615 ExternalFieldOffsets, 1616 ExternalBaseOffsets, 1617 ExternalVirtualBaseOffsets); 1618 1619 // Update based on external alignment. 1620 if (ExternalLayout) { 1621 if (ExternalAlign > 0) { 1622 Alignment = Context.toCharUnitsFromBits(ExternalAlign); 1623 UnpackedAlignment = Alignment; 1624 } else { 1625 // The external source didn't have alignment information; infer it. 1626 InferAlignment = true; 1627 } 1628 } 1629 } 1630 } 1631 1632 void RecordLayoutBuilder::Layout(const RecordDecl *D) { 1633 InitializeLayout(D); 1634 LayoutFields(D); 1635 1636 // Finally, round the size of the total struct up to the alignment of the 1637 // struct itself. 1638 FinishLayout(D); 1639 } 1640 1641 void RecordLayoutBuilder::Layout(const CXXRecordDecl *RD) { 1642 InitializeLayout(RD); 1643 1644 // Lay out the vtable and the non-virtual bases. 1645 LayoutNonVirtualBases(RD); 1646 1647 LayoutFields(RD); 1648 1649 NonVirtualSize = Context.toCharUnitsFromBits( 1650 llvm::RoundUpToAlignment(getSizeInBits(), 1651 Context.getTargetInfo().getCharAlign())); 1652 NonVirtualAlignment = Alignment; 1653 1654 if (isMicrosoftCXXABI()) { 1655 if (NonVirtualSize != NonVirtualSize.RoundUpToAlignment(Alignment)) { 1656 CharUnits AlignMember = 1657 NonVirtualSize.RoundUpToAlignment(Alignment) - NonVirtualSize; 1658 1659 setSize(getSize() + AlignMember); 1660 setDataSize(getSize()); 1661 1662 NonVirtualSize = Context.toCharUnitsFromBits( 1663 llvm::RoundUpToAlignment(getSizeInBits(), 1664 Context.getTargetInfo().getCharAlign())); 1665 } 1666 1667 MSLayoutVirtualBases(RD); 1668 } else { 1669 // Lay out the virtual bases and add the primary virtual base offsets. 1670 LayoutVirtualBases(RD, RD); 1671 } 1672 1673 // Finally, round the size of the total struct up to the alignment 1674 // of the struct itself. 1675 FinishLayout(RD); 1676 1677 #ifndef NDEBUG 1678 // Check that we have base offsets for all bases. 1679 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 1680 E = RD->bases_end(); I != E; ++I) { 1681 if (I->isVirtual()) 1682 continue; 1683 1684 const CXXRecordDecl *BaseDecl = 1685 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl()); 1686 1687 assert(Bases.count(BaseDecl) && "Did not find base offset!"); 1688 } 1689 1690 // And all virtual bases. 1691 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(), 1692 E = RD->vbases_end(); I != E; ++I) { 1693 const CXXRecordDecl *BaseDecl = 1694 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl()); 1695 1696 assert(VBases.count(BaseDecl) && "Did not find base offset!"); 1697 } 1698 #endif 1699 } 1700 1701 void RecordLayoutBuilder::Layout(const ObjCInterfaceDecl *D) { 1702 if (ObjCInterfaceDecl *SD = D->getSuperClass()) { 1703 const ASTRecordLayout &SL = Context.getASTObjCInterfaceLayout(SD); 1704 1705 UpdateAlignment(SL.getAlignment()); 1706 1707 // We start laying out ivars not at the end of the superclass 1708 // structure, but at the next byte following the last field. 1709 setSize(SL.getDataSize()); 1710 setDataSize(getSize()); 1711 } 1712 1713 InitializeLayout(D); 1714 // Layout each ivar sequentially. 1715 for (const ObjCIvarDecl *IVD = D->all_declared_ivar_begin(); IVD; 1716 IVD = IVD->getNextIvar()) 1717 LayoutField(IVD); 1718 1719 // Finally, round the size of the total struct up to the alignment of the 1720 // struct itself. 1721 FinishLayout(D); 1722 } 1723 1724 void RecordLayoutBuilder::LayoutFields(const RecordDecl *D) { 1725 // Layout each field, for now, just sequentially, respecting alignment. In 1726 // the future, this will need to be tweakable by targets. 1727 const FieldDecl *LastFD = 0; 1728 ZeroLengthBitfield = 0; 1729 unsigned RemainingInAlignment = 0; 1730 for (RecordDecl::field_iterator Field = D->field_begin(), 1731 FieldEnd = D->field_end(); Field != FieldEnd; ++Field) { 1732 if (IsMsStruct) { 1733 FieldDecl *FD = &*Field; 1734 if (Context.ZeroBitfieldFollowsBitfield(FD, LastFD)) 1735 ZeroLengthBitfield = FD; 1736 // Zero-length bitfields following non-bitfield members are 1737 // ignored: 1738 else if (Context.ZeroBitfieldFollowsNonBitfield(FD, LastFD)) 1739 continue; 1740 // FIXME. streamline these conditions into a simple one. 1741 else if (Context.BitfieldFollowsBitfield(FD, LastFD) || 1742 Context.BitfieldFollowsNonBitfield(FD, LastFD) || 1743 Context.NonBitfieldFollowsBitfield(FD, LastFD)) { 1744 // 1) Adjacent bit fields are packed into the same 1-, 2-, or 1745 // 4-byte allocation unit if the integral types are the same 1746 // size and if the next bit field fits into the current 1747 // allocation unit without crossing the boundary imposed by the 1748 // common alignment requirements of the bit fields. 1749 // 2) Establish a new alignment for a bitfield following 1750 // a non-bitfield if size of their types differ. 1751 // 3) Establish a new alignment for a non-bitfield following 1752 // a bitfield if size of their types differ. 1753 std::pair<uint64_t, unsigned> FieldInfo = 1754 Context.getTypeInfo(FD->getType()); 1755 uint64_t TypeSize = FieldInfo.first; 1756 unsigned FieldAlign = FieldInfo.second; 1757 // This check is needed for 'long long' in -m32 mode. 1758 if (TypeSize > FieldAlign && 1759 (Context.hasSameType(FD->getType(), 1760 Context.UnsignedLongLongTy) 1761 ||Context.hasSameType(FD->getType(), 1762 Context.LongLongTy))) 1763 FieldAlign = TypeSize; 1764 FieldInfo = Context.getTypeInfo(LastFD->getType()); 1765 uint64_t TypeSizeLastFD = FieldInfo.first; 1766 unsigned FieldAlignLastFD = FieldInfo.second; 1767 // This check is needed for 'long long' in -m32 mode. 1768 if (TypeSizeLastFD > FieldAlignLastFD && 1769 (Context.hasSameType(LastFD->getType(), 1770 Context.UnsignedLongLongTy) 1771 || Context.hasSameType(LastFD->getType(), 1772 Context.LongLongTy))) 1773 FieldAlignLastFD = TypeSizeLastFD; 1774 1775 if (TypeSizeLastFD != TypeSize) { 1776 if (RemainingInAlignment && 1777 LastFD && LastFD->isBitField() && 1778 LastFD->getBitWidthValue(Context)) { 1779 // If previous field was a bitfield with some remaining unfilled 1780 // bits, pad the field so current field starts on its type boundary. 1781 uint64_t FieldOffset = 1782 getDataSizeInBits() - UnfilledBitsInLastByte; 1783 uint64_t NewSizeInBits = RemainingInAlignment + FieldOffset; 1784 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits, 1785 Context.getTargetInfo().getCharAlign())); 1786 setSize(std::max(getSizeInBits(), getDataSizeInBits())); 1787 RemainingInAlignment = 0; 1788 } 1789 1790 uint64_t UnpaddedFieldOffset = 1791 getDataSizeInBits() - UnfilledBitsInLastByte; 1792 FieldAlign = std::max(FieldAlign, FieldAlignLastFD); 1793 1794 // The maximum field alignment overrides the aligned attribute. 1795 if (!MaxFieldAlignment.isZero()) { 1796 unsigned MaxFieldAlignmentInBits = 1797 Context.toBits(MaxFieldAlignment); 1798 FieldAlign = std::min(FieldAlign, MaxFieldAlignmentInBits); 1799 } 1800 1801 uint64_t NewSizeInBits = 1802 llvm::RoundUpToAlignment(UnpaddedFieldOffset, FieldAlign); 1803 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits, 1804 Context.getTargetInfo().getCharAlign())); 1805 UnfilledBitsInLastByte = getDataSizeInBits() - NewSizeInBits; 1806 setSize(std::max(getSizeInBits(), getDataSizeInBits())); 1807 } 1808 if (FD->isBitField()) { 1809 uint64_t FieldSize = FD->getBitWidthValue(Context); 1810 assert (FieldSize > 0 && "LayoutFields - ms_struct layout"); 1811 if (RemainingInAlignment < FieldSize) 1812 RemainingInAlignment = TypeSize - FieldSize; 1813 else 1814 RemainingInAlignment -= FieldSize; 1815 } 1816 } 1817 else if (FD->isBitField()) { 1818 uint64_t FieldSize = FD->getBitWidthValue(Context); 1819 std::pair<uint64_t, unsigned> FieldInfo = 1820 Context.getTypeInfo(FD->getType()); 1821 uint64_t TypeSize = FieldInfo.first; 1822 RemainingInAlignment = TypeSize - FieldSize; 1823 } 1824 LastFD = FD; 1825 } 1826 else if (!Context.getTargetInfo().useBitFieldTypeAlignment() && 1827 Context.getTargetInfo().useZeroLengthBitfieldAlignment()) { 1828 FieldDecl *FD = &*Field; 1829 if (FD->isBitField() && FD->getBitWidthValue(Context) == 0) 1830 ZeroLengthBitfield = FD; 1831 } 1832 LayoutField(&*Field); 1833 } 1834 if (IsMsStruct && RemainingInAlignment && 1835 LastFD && LastFD->isBitField() && LastFD->getBitWidthValue(Context)) { 1836 // If we ended a bitfield before the full length of the type then 1837 // pad the struct out to the full length of the last type. 1838 uint64_t FieldOffset = 1839 getDataSizeInBits() - UnfilledBitsInLastByte; 1840 uint64_t NewSizeInBits = RemainingInAlignment + FieldOffset; 1841 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits, 1842 Context.getTargetInfo().getCharAlign())); 1843 setSize(std::max(getSizeInBits(), getDataSizeInBits())); 1844 } 1845 } 1846 1847 void RecordLayoutBuilder::LayoutWideBitField(uint64_t FieldSize, 1848 uint64_t TypeSize, 1849 bool FieldPacked, 1850 const FieldDecl *D) { 1851 assert(Context.getLangOpts().CPlusPlus && 1852 "Can only have wide bit-fields in C++!"); 1853 1854 // Itanium C++ ABI 2.4: 1855 // If sizeof(T)*8 < n, let T' be the largest integral POD type with 1856 // sizeof(T')*8 <= n. 1857 1858 QualType IntegralPODTypes[] = { 1859 Context.UnsignedCharTy, Context.UnsignedShortTy, Context.UnsignedIntTy, 1860 Context.UnsignedLongTy, Context.UnsignedLongLongTy 1861 }; 1862 1863 QualType Type; 1864 for (unsigned I = 0, E = llvm::array_lengthof(IntegralPODTypes); 1865 I != E; ++I) { 1866 uint64_t Size = Context.getTypeSize(IntegralPODTypes[I]); 1867 1868 if (Size > FieldSize) 1869 break; 1870 1871 Type = IntegralPODTypes[I]; 1872 } 1873 assert(!Type.isNull() && "Did not find a type!"); 1874 1875 CharUnits TypeAlign = Context.getTypeAlignInChars(Type); 1876 1877 // We're not going to use any of the unfilled bits in the last byte. 1878 UnfilledBitsInLastByte = 0; 1879 1880 uint64_t FieldOffset; 1881 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastByte; 1882 1883 if (IsUnion) { 1884 setDataSize(std::max(getDataSizeInBits(), FieldSize)); 1885 FieldOffset = 0; 1886 } else { 1887 // The bitfield is allocated starting at the next offset aligned 1888 // appropriately for T', with length n bits. 1889 FieldOffset = llvm::RoundUpToAlignment(getDataSizeInBits(), 1890 Context.toBits(TypeAlign)); 1891 1892 uint64_t NewSizeInBits = FieldOffset + FieldSize; 1893 1894 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits, 1895 Context.getTargetInfo().getCharAlign())); 1896 UnfilledBitsInLastByte = getDataSizeInBits() - NewSizeInBits; 1897 } 1898 1899 // Place this field at the current location. 1900 FieldOffsets.push_back(FieldOffset); 1901 1902 CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, FieldOffset, 1903 Context.toBits(TypeAlign), FieldPacked, D); 1904 1905 // Update the size. 1906 setSize(std::max(getSizeInBits(), getDataSizeInBits())); 1907 1908 // Remember max struct/class alignment. 1909 UpdateAlignment(TypeAlign); 1910 } 1911 1912 void RecordLayoutBuilder::LayoutBitField(const FieldDecl *D) { 1913 bool FieldPacked = Packed || D->hasAttr<PackedAttr>(); 1914 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastByte; 1915 uint64_t FieldOffset = IsUnion ? 0 : UnpaddedFieldOffset; 1916 uint64_t FieldSize = D->getBitWidthValue(Context); 1917 1918 std::pair<uint64_t, unsigned> FieldInfo = Context.getTypeInfo(D->getType()); 1919 uint64_t TypeSize = FieldInfo.first; 1920 unsigned FieldAlign = FieldInfo.second; 1921 1922 // This check is needed for 'long long' in -m32 mode. 1923 if (IsMsStruct && (TypeSize > FieldAlign) && 1924 (Context.hasSameType(D->getType(), 1925 Context.UnsignedLongLongTy) 1926 || Context.hasSameType(D->getType(), Context.LongLongTy))) 1927 FieldAlign = TypeSize; 1928 1929 if (ZeroLengthBitfield) { 1930 std::pair<uint64_t, unsigned> FieldInfo; 1931 unsigned ZeroLengthBitfieldAlignment; 1932 if (IsMsStruct) { 1933 // If a zero-length bitfield is inserted after a bitfield, 1934 // and the alignment of the zero-length bitfield is 1935 // greater than the member that follows it, `bar', `bar' 1936 // will be aligned as the type of the zero-length bitfield. 1937 if (ZeroLengthBitfield != D) { 1938 FieldInfo = Context.getTypeInfo(ZeroLengthBitfield->getType()); 1939 ZeroLengthBitfieldAlignment = FieldInfo.second; 1940 // Ignore alignment of subsequent zero-length bitfields. 1941 if ((ZeroLengthBitfieldAlignment > FieldAlign) || (FieldSize == 0)) 1942 FieldAlign = ZeroLengthBitfieldAlignment; 1943 if (FieldSize) 1944 ZeroLengthBitfield = 0; 1945 } 1946 } else { 1947 // The alignment of a zero-length bitfield affects the alignment 1948 // of the next member. The alignment is the max of the zero 1949 // length bitfield's alignment and a target specific fixed value. 1950 unsigned ZeroLengthBitfieldBoundary = 1951 Context.getTargetInfo().getZeroLengthBitfieldBoundary(); 1952 if (ZeroLengthBitfieldBoundary > FieldAlign) 1953 FieldAlign = ZeroLengthBitfieldBoundary; 1954 } 1955 } 1956 1957 if (FieldSize > TypeSize) { 1958 LayoutWideBitField(FieldSize, TypeSize, FieldPacked, D); 1959 return; 1960 } 1961 1962 // The align if the field is not packed. This is to check if the attribute 1963 // was unnecessary (-Wpacked). 1964 unsigned UnpackedFieldAlign = FieldAlign; 1965 uint64_t UnpackedFieldOffset = FieldOffset; 1966 if (!Context.getTargetInfo().useBitFieldTypeAlignment() && !ZeroLengthBitfield) 1967 UnpackedFieldAlign = 1; 1968 1969 if (FieldPacked || 1970 (!Context.getTargetInfo().useBitFieldTypeAlignment() && !ZeroLengthBitfield)) 1971 FieldAlign = 1; 1972 FieldAlign = std::max(FieldAlign, D->getMaxAlignment()); 1973 UnpackedFieldAlign = std::max(UnpackedFieldAlign, D->getMaxAlignment()); 1974 1975 // The maximum field alignment overrides the aligned attribute. 1976 if (!MaxFieldAlignment.isZero() && FieldSize != 0) { 1977 unsigned MaxFieldAlignmentInBits = Context.toBits(MaxFieldAlignment); 1978 FieldAlign = std::min(FieldAlign, MaxFieldAlignmentInBits); 1979 UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignmentInBits); 1980 } 1981 1982 // Check if we need to add padding to give the field the correct alignment. 1983 if (FieldSize == 0 || 1984 (MaxFieldAlignment.isZero() && 1985 (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize)) 1986 FieldOffset = llvm::RoundUpToAlignment(FieldOffset, FieldAlign); 1987 1988 if (FieldSize == 0 || 1989 (MaxFieldAlignment.isZero() && 1990 (UnpackedFieldOffset & (UnpackedFieldAlign-1)) + FieldSize > TypeSize)) 1991 UnpackedFieldOffset = llvm::RoundUpToAlignment(UnpackedFieldOffset, 1992 UnpackedFieldAlign); 1993 1994 // Padding members don't affect overall alignment, unless zero length bitfield 1995 // alignment is enabled. 1996 if (!D->getIdentifier() && !Context.getTargetInfo().useZeroLengthBitfieldAlignment()) 1997 FieldAlign = UnpackedFieldAlign = 1; 1998 1999 if (!IsMsStruct) 2000 ZeroLengthBitfield = 0; 2001 2002 if (ExternalLayout) 2003 FieldOffset = updateExternalFieldOffset(D, FieldOffset); 2004 2005 // Place this field at the current location. 2006 FieldOffsets.push_back(FieldOffset); 2007 2008 if (!ExternalLayout) 2009 CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, UnpackedFieldOffset, 2010 UnpackedFieldAlign, FieldPacked, D); 2011 2012 // Update DataSize to include the last byte containing (part of) the bitfield. 2013 if (IsUnion) { 2014 // FIXME: I think FieldSize should be TypeSize here. 2015 setDataSize(std::max(getDataSizeInBits(), FieldSize)); 2016 } else { 2017 uint64_t NewSizeInBits = FieldOffset + FieldSize; 2018 2019 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits, 2020 Context.getTargetInfo().getCharAlign())); 2021 UnfilledBitsInLastByte = getDataSizeInBits() - NewSizeInBits; 2022 } 2023 2024 // Update the size. 2025 setSize(std::max(getSizeInBits(), getDataSizeInBits())); 2026 2027 // Remember max struct/class alignment. 2028 UpdateAlignment(Context.toCharUnitsFromBits(FieldAlign), 2029 Context.toCharUnitsFromBits(UnpackedFieldAlign)); 2030 } 2031 2032 void RecordLayoutBuilder::LayoutField(const FieldDecl *D) { 2033 if (D->isBitField()) { 2034 LayoutBitField(D); 2035 return; 2036 } 2037 2038 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastByte; 2039 2040 // Reset the unfilled bits. 2041 UnfilledBitsInLastByte = 0; 2042 2043 bool FieldPacked = Packed || D->hasAttr<PackedAttr>(); 2044 CharUnits FieldOffset = 2045 IsUnion ? CharUnits::Zero() : getDataSize(); 2046 CharUnits FieldSize; 2047 CharUnits FieldAlign; 2048 2049 if (D->getType()->isIncompleteArrayType()) { 2050 // This is a flexible array member; we can't directly 2051 // query getTypeInfo about these, so we figure it out here. 2052 // Flexible array members don't have any size, but they 2053 // have to be aligned appropriately for their element type. 2054 FieldSize = CharUnits::Zero(); 2055 const ArrayType* ATy = Context.getAsArrayType(D->getType()); 2056 FieldAlign = Context.getTypeAlignInChars(ATy->getElementType()); 2057 } else if (const ReferenceType *RT = D->getType()->getAs<ReferenceType>()) { 2058 unsigned AS = RT->getPointeeType().getAddressSpace(); 2059 FieldSize = 2060 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(AS)); 2061 FieldAlign = 2062 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(AS)); 2063 } else { 2064 std::pair<CharUnits, CharUnits> FieldInfo = 2065 Context.getTypeInfoInChars(D->getType()); 2066 FieldSize = FieldInfo.first; 2067 FieldAlign = FieldInfo.second; 2068 2069 if (ZeroLengthBitfield) { 2070 CharUnits ZeroLengthBitfieldBoundary = 2071 Context.toCharUnitsFromBits( 2072 Context.getTargetInfo().getZeroLengthBitfieldBoundary()); 2073 if (ZeroLengthBitfieldBoundary == CharUnits::Zero()) { 2074 // If a zero-length bitfield is inserted after a bitfield, 2075 // and the alignment of the zero-length bitfield is 2076 // greater than the member that follows it, `bar', `bar' 2077 // will be aligned as the type of the zero-length bitfield. 2078 std::pair<CharUnits, CharUnits> FieldInfo = 2079 Context.getTypeInfoInChars(ZeroLengthBitfield->getType()); 2080 CharUnits ZeroLengthBitfieldAlignment = FieldInfo.second; 2081 if (ZeroLengthBitfieldAlignment > FieldAlign) 2082 FieldAlign = ZeroLengthBitfieldAlignment; 2083 } else if (ZeroLengthBitfieldBoundary > FieldAlign) { 2084 // Align 'bar' based on a fixed alignment specified by the target. 2085 assert(Context.getTargetInfo().useZeroLengthBitfieldAlignment() && 2086 "ZeroLengthBitfieldBoundary should only be used in conjunction" 2087 " with useZeroLengthBitfieldAlignment."); 2088 FieldAlign = ZeroLengthBitfieldBoundary; 2089 } 2090 ZeroLengthBitfield = 0; 2091 } 2092 2093 if (Context.getLangOpts().MSBitfields || IsMsStruct) { 2094 // If MS bitfield layout is required, figure out what type is being 2095 // laid out and align the field to the width of that type. 2096 2097 // Resolve all typedefs down to their base type and round up the field 2098 // alignment if necessary. 2099 QualType T = Context.getBaseElementType(D->getType()); 2100 if (const BuiltinType *BTy = T->getAs<BuiltinType>()) { 2101 CharUnits TypeSize = Context.getTypeSizeInChars(BTy); 2102 if (TypeSize > FieldAlign) 2103 FieldAlign = TypeSize; 2104 } 2105 } 2106 } 2107 2108 // The align if the field is not packed. This is to check if the attribute 2109 // was unnecessary (-Wpacked). 2110 CharUnits UnpackedFieldAlign = FieldAlign; 2111 CharUnits UnpackedFieldOffset = FieldOffset; 2112 2113 if (FieldPacked) 2114 FieldAlign = CharUnits::One(); 2115 CharUnits MaxAlignmentInChars = 2116 Context.toCharUnitsFromBits(D->getMaxAlignment()); 2117 FieldAlign = std::max(FieldAlign, MaxAlignmentInChars); 2118 UnpackedFieldAlign = std::max(UnpackedFieldAlign, MaxAlignmentInChars); 2119 2120 // The maximum field alignment overrides the aligned attribute. 2121 if (!MaxFieldAlignment.isZero()) { 2122 FieldAlign = std::min(FieldAlign, MaxFieldAlignment); 2123 UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignment); 2124 } 2125 2126 // Round up the current record size to the field's alignment boundary. 2127 FieldOffset = FieldOffset.RoundUpToAlignment(FieldAlign); 2128 UnpackedFieldOffset = 2129 UnpackedFieldOffset.RoundUpToAlignment(UnpackedFieldAlign); 2130 2131 if (ExternalLayout) { 2132 FieldOffset = Context.toCharUnitsFromBits( 2133 updateExternalFieldOffset(D, Context.toBits(FieldOffset))); 2134 2135 if (!IsUnion && EmptySubobjects) { 2136 // Record the fact that we're placing a field at this offset. 2137 bool Allowed = EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset); 2138 (void)Allowed; 2139 assert(Allowed && "Externally-placed field cannot be placed here"); 2140 } 2141 } else { 2142 if (!IsUnion && EmptySubobjects) { 2143 // Check if we can place the field at this offset. 2144 while (!EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset)) { 2145 // We couldn't place the field at the offset. Try again at a new offset. 2146 FieldOffset += FieldAlign; 2147 } 2148 } 2149 } 2150 2151 // Place this field at the current location. 2152 FieldOffsets.push_back(Context.toBits(FieldOffset)); 2153 2154 if (!ExternalLayout) 2155 CheckFieldPadding(Context.toBits(FieldOffset), UnpaddedFieldOffset, 2156 Context.toBits(UnpackedFieldOffset), 2157 Context.toBits(UnpackedFieldAlign), FieldPacked, D); 2158 2159 // Reserve space for this field. 2160 uint64_t FieldSizeInBits = Context.toBits(FieldSize); 2161 if (IsUnion) 2162 setDataSize(std::max(getDataSizeInBits(), FieldSizeInBits)); 2163 else 2164 setDataSize(FieldOffset + FieldSize); 2165 2166 // Update the size. 2167 setSize(std::max(getSizeInBits(), getDataSizeInBits())); 2168 2169 // Remember max struct/class alignment. 2170 UpdateAlignment(FieldAlign, UnpackedFieldAlign); 2171 } 2172 2173 void RecordLayoutBuilder::FinishLayout(const NamedDecl *D) { 2174 if (ExternalLayout) { 2175 setSize(ExternalSize); 2176 return; 2177 } 2178 2179 // In C++, records cannot be of size 0. 2180 if (Context.getLangOpts().CPlusPlus && getSizeInBits() == 0) { 2181 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) { 2182 // Compatibility with gcc requires a class (pod or non-pod) 2183 // which is not empty but of size 0; such as having fields of 2184 // array of zero-length, remains of Size 0 2185 if (RD->isEmpty()) 2186 setSize(CharUnits::One()); 2187 } 2188 else 2189 setSize(CharUnits::One()); 2190 } 2191 2192 // MSVC doesn't round up to the alignment of the record with virtual bases. 2193 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) { 2194 if (isMicrosoftCXXABI() && RD->getNumVBases()) 2195 return; 2196 } 2197 2198 // Finally, round the size of the record up to the alignment of the 2199 // record itself. 2200 uint64_t UnpaddedSize = getSizeInBits() - UnfilledBitsInLastByte; 2201 uint64_t UnpackedSizeInBits = 2202 llvm::RoundUpToAlignment(getSizeInBits(), 2203 Context.toBits(UnpackedAlignment)); 2204 CharUnits UnpackedSize = Context.toCharUnitsFromBits(UnpackedSizeInBits); 2205 setSize(llvm::RoundUpToAlignment(getSizeInBits(), Context.toBits(Alignment))); 2206 2207 unsigned CharBitNum = Context.getTargetInfo().getCharWidth(); 2208 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) { 2209 // Warn if padding was introduced to the struct/class/union. 2210 if (getSizeInBits() > UnpaddedSize) { 2211 unsigned PadSize = getSizeInBits() - UnpaddedSize; 2212 bool InBits = true; 2213 if (PadSize % CharBitNum == 0) { 2214 PadSize = PadSize / CharBitNum; 2215 InBits = false; 2216 } 2217 Diag(RD->getLocation(), diag::warn_padded_struct_size) 2218 << Context.getTypeDeclType(RD) 2219 << PadSize 2220 << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1); // plural or not 2221 } 2222 2223 // Warn if we packed it unnecessarily. If the alignment is 1 byte don't 2224 // bother since there won't be alignment issues. 2225 if (Packed && UnpackedAlignment > CharUnits::One() && 2226 getSize() == UnpackedSize) 2227 Diag(D->getLocation(), diag::warn_unnecessary_packed) 2228 << Context.getTypeDeclType(RD); 2229 } 2230 } 2231 2232 void RecordLayoutBuilder::UpdateAlignment(CharUnits NewAlignment, 2233 CharUnits UnpackedNewAlignment) { 2234 // The alignment is not modified when using 'mac68k' alignment or when 2235 // we have an externally-supplied layout that also provides overall alignment. 2236 if (IsMac68kAlign || (ExternalLayout && !InferAlignment)) 2237 return; 2238 2239 if (NewAlignment > Alignment) { 2240 assert(llvm::isPowerOf2_32(NewAlignment.getQuantity() && 2241 "Alignment not a power of 2")); 2242 Alignment = NewAlignment; 2243 } 2244 2245 if (UnpackedNewAlignment > UnpackedAlignment) { 2246 assert(llvm::isPowerOf2_32(UnpackedNewAlignment.getQuantity() && 2247 "Alignment not a power of 2")); 2248 UnpackedAlignment = UnpackedNewAlignment; 2249 } 2250 } 2251 2252 uint64_t 2253 RecordLayoutBuilder::updateExternalFieldOffset(const FieldDecl *Field, 2254 uint64_t ComputedOffset) { 2255 assert(ExternalFieldOffsets.find(Field) != ExternalFieldOffsets.end() && 2256 "Field does not have an external offset"); 2257 2258 uint64_t ExternalFieldOffset = ExternalFieldOffsets[Field]; 2259 2260 if (InferAlignment && ExternalFieldOffset < ComputedOffset) { 2261 // The externally-supplied field offset is before the field offset we 2262 // computed. Assume that the structure is packed. 2263 Alignment = CharUnits::fromQuantity(1); 2264 InferAlignment = false; 2265 } 2266 2267 // Use the externally-supplied field offset. 2268 return ExternalFieldOffset; 2269 } 2270 2271 void RecordLayoutBuilder::CheckFieldPadding(uint64_t Offset, 2272 uint64_t UnpaddedOffset, 2273 uint64_t UnpackedOffset, 2274 unsigned UnpackedAlign, 2275 bool isPacked, 2276 const FieldDecl *D) { 2277 // We let objc ivars without warning, objc interfaces generally are not used 2278 // for padding tricks. 2279 if (isa<ObjCIvarDecl>(D)) 2280 return; 2281 2282 // Don't warn about structs created without a SourceLocation. This can 2283 // be done by clients of the AST, such as codegen. 2284 if (D->getLocation().isInvalid()) 2285 return; 2286 2287 unsigned CharBitNum = Context.getTargetInfo().getCharWidth(); 2288 2289 // Warn if padding was introduced to the struct/class. 2290 if (!IsUnion && Offset > UnpaddedOffset) { 2291 unsigned PadSize = Offset - UnpaddedOffset; 2292 bool InBits = true; 2293 if (PadSize % CharBitNum == 0) { 2294 PadSize = PadSize / CharBitNum; 2295 InBits = false; 2296 } 2297 if (D->getIdentifier()) 2298 Diag(D->getLocation(), diag::warn_padded_struct_field) 2299 << (D->getParent()->isStruct() ? 0 : 1) // struct|class 2300 << Context.getTypeDeclType(D->getParent()) 2301 << PadSize 2302 << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1) // plural or not 2303 << D->getIdentifier(); 2304 else 2305 Diag(D->getLocation(), diag::warn_padded_struct_anon_field) 2306 << (D->getParent()->isStruct() ? 0 : 1) // struct|class 2307 << Context.getTypeDeclType(D->getParent()) 2308 << PadSize 2309 << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1); // plural or not 2310 } 2311 2312 // Warn if we packed it unnecessarily. If the alignment is 1 byte don't 2313 // bother since there won't be alignment issues. 2314 if (isPacked && UnpackedAlign > CharBitNum && Offset == UnpackedOffset) 2315 Diag(D->getLocation(), diag::warn_unnecessary_packed) 2316 << D->getIdentifier(); 2317 } 2318 2319 const CXXMethodDecl * 2320 RecordLayoutBuilder::ComputeKeyFunction(const CXXRecordDecl *RD) { 2321 // If a class isn't polymorphic it doesn't have a key function. 2322 if (!RD->isPolymorphic()) 2323 return 0; 2324 2325 // A class that is not externally visible doesn't have a key function. (Or 2326 // at least, there's no point to assigning a key function to such a class; 2327 // this doesn't affect the ABI.) 2328 if (RD->getLinkage() != ExternalLinkage) 2329 return 0; 2330 2331 // Template instantiations don't have key functions,see Itanium C++ ABI 5.2.6. 2332 // Same behavior as GCC. 2333 TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind(); 2334 if (TSK == TSK_ImplicitInstantiation || 2335 TSK == TSK_ExplicitInstantiationDefinition) 2336 return 0; 2337 2338 for (CXXRecordDecl::method_iterator I = RD->method_begin(), 2339 E = RD->method_end(); I != E; ++I) { 2340 const CXXMethodDecl *MD = &*I; 2341 2342 if (!MD->isVirtual()) 2343 continue; 2344 2345 if (MD->isPure()) 2346 continue; 2347 2348 // Ignore implicit member functions, they are always marked as inline, but 2349 // they don't have a body until they're defined. 2350 if (MD->isImplicit()) 2351 continue; 2352 2353 if (MD->isInlineSpecified()) 2354 continue; 2355 2356 if (MD->hasInlineBody()) 2357 continue; 2358 2359 // We found it. 2360 return MD; 2361 } 2362 2363 return 0; 2364 } 2365 2366 DiagnosticBuilder 2367 RecordLayoutBuilder::Diag(SourceLocation Loc, unsigned DiagID) { 2368 return Context.getDiagnostics().Report(Loc, DiagID); 2369 } 2370 2371 /// getASTRecordLayout - Get or compute information about the layout of the 2372 /// specified record (struct/union/class), which indicates its size and field 2373 /// position information. 2374 const ASTRecordLayout & 2375 ASTContext::getASTRecordLayout(const RecordDecl *D) const { 2376 // These asserts test different things. A record has a definition 2377 // as soon as we begin to parse the definition. That definition is 2378 // not a complete definition (which is what isDefinition() tests) 2379 // until we *finish* parsing the definition. 2380 2381 if (D->hasExternalLexicalStorage() && !D->getDefinition()) 2382 getExternalSource()->CompleteType(const_cast<RecordDecl*>(D)); 2383 2384 D = D->getDefinition(); 2385 assert(D && "Cannot get layout of forward declarations!"); 2386 assert(D->isCompleteDefinition() && "Cannot layout type before complete!"); 2387 2388 // Look up this layout, if already laid out, return what we have. 2389 // Note that we can't save a reference to the entry because this function 2390 // is recursive. 2391 const ASTRecordLayout *Entry = ASTRecordLayouts[D]; 2392 if (Entry) return *Entry; 2393 2394 const ASTRecordLayout *NewEntry; 2395 2396 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) { 2397 EmptySubobjectMap EmptySubobjects(*this, RD); 2398 RecordLayoutBuilder Builder(*this, &EmptySubobjects); 2399 Builder.Layout(RD); 2400 2401 // MSVC gives the vb-table pointer an alignment equal to that of 2402 // the non-virtual part of the structure. That's an inherently 2403 // multi-pass operation. If our first pass doesn't give us 2404 // adequate alignment, try again with the specified minimum 2405 // alignment. This is *much* more maintainable than computing the 2406 // alignment in advance in a separately-coded pass; it's also 2407 // significantly more efficient in the common case where the 2408 // vb-table doesn't need extra padding. 2409 if (Builder.VBPtrOffset != CharUnits::fromQuantity(-1) && 2410 (Builder.VBPtrOffset % Builder.NonVirtualAlignment) != 0) { 2411 Builder.resetWithTargetAlignment(Builder.NonVirtualAlignment); 2412 Builder.Layout(RD); 2413 } 2414 2415 // FIXME: This is not always correct. See the part about bitfields at 2416 // http://www.codesourcery.com/public/cxx-abi/abi.html#POD for more info. 2417 // FIXME: IsPODForThePurposeOfLayout should be stored in the record layout. 2418 // This does not affect the calculations of MSVC layouts 2419 bool IsPODForThePurposeOfLayout = 2420 (!Builder.isMicrosoftCXXABI() && cast<CXXRecordDecl>(D)->isPOD()); 2421 2422 // FIXME: This should be done in FinalizeLayout. 2423 CharUnits DataSize = 2424 IsPODForThePurposeOfLayout ? Builder.getSize() : Builder.getDataSize(); 2425 CharUnits NonVirtualSize = 2426 IsPODForThePurposeOfLayout ? DataSize : Builder.NonVirtualSize; 2427 2428 NewEntry = 2429 new (*this) ASTRecordLayout(*this, Builder.getSize(), 2430 Builder.Alignment, 2431 Builder.HasOwnVFPtr, 2432 Builder.VBPtrOffset, 2433 DataSize, 2434 Builder.FieldOffsets.data(), 2435 Builder.FieldOffsets.size(), 2436 NonVirtualSize, 2437 Builder.NonVirtualAlignment, 2438 EmptySubobjects.SizeOfLargestEmptySubobject, 2439 Builder.PrimaryBase, 2440 Builder.PrimaryBaseIsVirtual, 2441 Builder.Bases, Builder.VBases); 2442 } else { 2443 RecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/0); 2444 Builder.Layout(D); 2445 2446 NewEntry = 2447 new (*this) ASTRecordLayout(*this, Builder.getSize(), 2448 Builder.Alignment, 2449 Builder.getSize(), 2450 Builder.FieldOffsets.data(), 2451 Builder.FieldOffsets.size()); 2452 } 2453 2454 ASTRecordLayouts[D] = NewEntry; 2455 2456 if (getLangOpts().DumpRecordLayouts) { 2457 llvm::errs() << "\n*** Dumping AST Record Layout\n"; 2458 DumpRecordLayout(D, llvm::errs(), getLangOpts().DumpRecordLayoutsSimple); 2459 } 2460 2461 return *NewEntry; 2462 } 2463 2464 const CXXMethodDecl *ASTContext::getKeyFunction(const CXXRecordDecl *RD) { 2465 RD = cast<CXXRecordDecl>(RD->getDefinition()); 2466 assert(RD && "Cannot get key function for forward declarations!"); 2467 2468 const CXXMethodDecl *&Entry = KeyFunctions[RD]; 2469 if (!Entry) 2470 Entry = RecordLayoutBuilder::ComputeKeyFunction(RD); 2471 2472 return Entry; 2473 } 2474 2475 static uint64_t getFieldOffset(const ASTContext &C, const FieldDecl *FD) { 2476 const ASTRecordLayout &Layout = C.getASTRecordLayout(FD->getParent()); 2477 return Layout.getFieldOffset(FD->getFieldIndex()); 2478 } 2479 2480 uint64_t ASTContext::getFieldOffset(const ValueDecl *VD) const { 2481 uint64_t OffsetInBits; 2482 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) { 2483 OffsetInBits = ::getFieldOffset(*this, FD); 2484 } else { 2485 const IndirectFieldDecl *IFD = cast<IndirectFieldDecl>(VD); 2486 2487 OffsetInBits = 0; 2488 for (IndirectFieldDecl::chain_iterator CI = IFD->chain_begin(), 2489 CE = IFD->chain_end(); 2490 CI != CE; ++CI) 2491 OffsetInBits += ::getFieldOffset(*this, cast<FieldDecl>(*CI)); 2492 } 2493 2494 return OffsetInBits; 2495 } 2496 2497 /// getObjCLayout - Get or compute information about the layout of the 2498 /// given interface. 2499 /// 2500 /// \param Impl - If given, also include the layout of the interface's 2501 /// implementation. This may differ by including synthesized ivars. 2502 const ASTRecordLayout & 2503 ASTContext::getObjCLayout(const ObjCInterfaceDecl *D, 2504 const ObjCImplementationDecl *Impl) const { 2505 // Retrieve the definition 2506 if (D->hasExternalLexicalStorage() && !D->getDefinition()) 2507 getExternalSource()->CompleteType(const_cast<ObjCInterfaceDecl*>(D)); 2508 D = D->getDefinition(); 2509 assert(D && D->isThisDeclarationADefinition() && "Invalid interface decl!"); 2510 2511 // Look up this layout, if already laid out, return what we have. 2512 ObjCContainerDecl *Key = 2513 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D; 2514 if (const ASTRecordLayout *Entry = ObjCLayouts[Key]) 2515 return *Entry; 2516 2517 // Add in synthesized ivar count if laying out an implementation. 2518 if (Impl) { 2519 unsigned SynthCount = CountNonClassIvars(D); 2520 // If there aren't any sythesized ivars then reuse the interface 2521 // entry. Note we can't cache this because we simply free all 2522 // entries later; however we shouldn't look up implementations 2523 // frequently. 2524 if (SynthCount == 0) 2525 return getObjCLayout(D, 0); 2526 } 2527 2528 RecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/0); 2529 Builder.Layout(D); 2530 2531 const ASTRecordLayout *NewEntry = 2532 new (*this) ASTRecordLayout(*this, Builder.getSize(), 2533 Builder.Alignment, 2534 Builder.getDataSize(), 2535 Builder.FieldOffsets.data(), 2536 Builder.FieldOffsets.size()); 2537 2538 ObjCLayouts[Key] = NewEntry; 2539 2540 return *NewEntry; 2541 } 2542 2543 static void PrintOffset(raw_ostream &OS, 2544 CharUnits Offset, unsigned IndentLevel) { 2545 OS << llvm::format("%4" PRId64 " | ", (int64_t)Offset.getQuantity()); 2546 OS.indent(IndentLevel * 2); 2547 } 2548 2549 static void DumpCXXRecordLayout(raw_ostream &OS, 2550 const CXXRecordDecl *RD, const ASTContext &C, 2551 CharUnits Offset, 2552 unsigned IndentLevel, 2553 const char* Description, 2554 bool IncludeVirtualBases) { 2555 const ASTRecordLayout &Layout = C.getASTRecordLayout(RD); 2556 2557 PrintOffset(OS, Offset, IndentLevel); 2558 OS << C.getTypeDeclType(const_cast<CXXRecordDecl *>(RD)).getAsString(); 2559 if (Description) 2560 OS << ' ' << Description; 2561 if (RD->isEmpty()) 2562 OS << " (empty)"; 2563 OS << '\n'; 2564 2565 IndentLevel++; 2566 2567 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase(); 2568 bool HasVfptr = Layout.hasOwnVFPtr(); 2569 bool HasVbptr = Layout.getVBPtrOffset() != CharUnits::fromQuantity(-1); 2570 2571 // Vtable pointer. 2572 if (RD->isDynamicClass() && !PrimaryBase && 2573 C.getTargetInfo().getCXXABI() != CXXABI_Microsoft) { 2574 PrintOffset(OS, Offset, IndentLevel); 2575 OS << '(' << *RD << " vtable pointer)\n"; 2576 } 2577 2578 // Dump (non-virtual) bases 2579 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 2580 E = RD->bases_end(); I != E; ++I) { 2581 assert(!I->getType()->isDependentType() && 2582 "Cannot layout class with dependent bases."); 2583 if (I->isVirtual()) 2584 continue; 2585 2586 const CXXRecordDecl *Base = 2587 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl()); 2588 2589 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base); 2590 2591 DumpCXXRecordLayout(OS, Base, C, BaseOffset, IndentLevel, 2592 Base == PrimaryBase ? "(primary base)" : "(base)", 2593 /*IncludeVirtualBases=*/false); 2594 } 2595 2596 // vfptr and vbptr (for Microsoft C++ ABI) 2597 if (HasVfptr) { 2598 PrintOffset(OS, Offset, IndentLevel); 2599 OS << '(' << *RD << " vftable pointer)\n"; 2600 } 2601 if (HasVbptr) { 2602 PrintOffset(OS, Offset + Layout.getVBPtrOffset(), IndentLevel); 2603 OS << '(' << *RD << " vbtable pointer)\n"; 2604 } 2605 2606 // Dump fields. 2607 uint64_t FieldNo = 0; 2608 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 2609 E = RD->field_end(); I != E; ++I, ++FieldNo) { 2610 const FieldDecl &Field = *I; 2611 CharUnits FieldOffset = Offset + 2612 C.toCharUnitsFromBits(Layout.getFieldOffset(FieldNo)); 2613 2614 if (const RecordType *RT = Field.getType()->getAs<RecordType>()) { 2615 if (const CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 2616 DumpCXXRecordLayout(OS, D, C, FieldOffset, IndentLevel, 2617 Field.getName().data(), 2618 /*IncludeVirtualBases=*/true); 2619 continue; 2620 } 2621 } 2622 2623 PrintOffset(OS, FieldOffset, IndentLevel); 2624 OS << Field.getType().getAsString() << ' ' << Field << '\n'; 2625 } 2626 2627 if (!IncludeVirtualBases) 2628 return; 2629 2630 // Dump virtual bases. 2631 const ASTRecordLayout::VBaseOffsetsMapTy &vtordisps = 2632 Layout.getVBaseOffsetsMap(); 2633 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(), 2634 E = RD->vbases_end(); I != E; ++I) { 2635 assert(I->isVirtual() && "Found non-virtual class!"); 2636 const CXXRecordDecl *VBase = 2637 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl()); 2638 2639 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBase); 2640 2641 if (vtordisps.find(VBase)->second.hasVtorDisp()) { 2642 PrintOffset(OS, VBaseOffset - CharUnits::fromQuantity(4), IndentLevel); 2643 OS << "(vtordisp for vbase " << *VBase << ")\n"; 2644 } 2645 2646 DumpCXXRecordLayout(OS, VBase, C, VBaseOffset, IndentLevel, 2647 VBase == PrimaryBase ? 2648 "(primary virtual base)" : "(virtual base)", 2649 /*IncludeVirtualBases=*/false); 2650 } 2651 2652 OS << " sizeof=" << Layout.getSize().getQuantity(); 2653 OS << ", dsize=" << Layout.getDataSize().getQuantity(); 2654 OS << ", align=" << Layout.getAlignment().getQuantity() << '\n'; 2655 OS << " nvsize=" << Layout.getNonVirtualSize().getQuantity(); 2656 OS << ", nvalign=" << Layout.getNonVirtualAlign().getQuantity() << '\n'; 2657 OS << '\n'; 2658 } 2659 2660 void ASTContext::DumpRecordLayout(const RecordDecl *RD, 2661 raw_ostream &OS, 2662 bool Simple) const { 2663 const ASTRecordLayout &Info = getASTRecordLayout(RD); 2664 2665 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 2666 if (!Simple) 2667 return DumpCXXRecordLayout(OS, CXXRD, *this, CharUnits(), 0, 0, 2668 /*IncludeVirtualBases=*/true); 2669 2670 OS << "Type: " << getTypeDeclType(RD).getAsString() << "\n"; 2671 if (!Simple) { 2672 OS << "Record: "; 2673 RD->dump(); 2674 } 2675 OS << "\nLayout: "; 2676 OS << "<ASTRecordLayout\n"; 2677 OS << " Size:" << toBits(Info.getSize()) << "\n"; 2678 OS << " DataSize:" << toBits(Info.getDataSize()) << "\n"; 2679 OS << " Alignment:" << toBits(Info.getAlignment()) << "\n"; 2680 OS << " FieldOffsets: ["; 2681 for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i) { 2682 if (i) OS << ", "; 2683 OS << Info.getFieldOffset(i); 2684 } 2685 OS << "]>\n"; 2686 } 2687