RecordLayoutBuilder.cpp 143 KB

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