RecordLayoutBuilder.cpp 124 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229
  1. //=== RecordLayoutBuilder.cpp - Helper class for building record layouts ---==//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. #include "clang/AST/RecordLayout.h"
  10. #include "clang/AST/ASTContext.h"
  11. #include "clang/AST/Attr.h"
  12. #include "clang/AST/CXXInheritance.h"
  13. #include "clang/AST/Decl.h"
  14. #include "clang/AST/DeclCXX.h"
  15. #include "clang/AST/DeclObjC.h"
  16. #include "clang/AST/Expr.h"
  17. #include "clang/Basic/TargetInfo.h"
  18. #include "clang/Sema/SemaDiagnostic.h"
  19. #include "llvm/ADT/SmallSet.h"
  20. #include "llvm/Support/CrashRecoveryContext.h"
  21. #include "llvm/Support/Format.h"
  22. #include "llvm/Support/MathExtras.h"
  23. using namespace clang;
  24. namespace {
  25. /// BaseSubobjectInfo - Represents a single base subobject in a complete class.
  26. /// For a class hierarchy like
  27. ///
  28. /// class A { };
  29. /// class B : A { };
  30. /// class C : A, B { };
  31. ///
  32. /// The BaseSubobjectInfo graph for C will have three BaseSubobjectInfo
  33. /// instances, one for B and two for A.
  34. ///
  35. /// If a base is virtual, it will only have one BaseSubobjectInfo allocated.
  36. struct BaseSubobjectInfo {
  37. /// Class - The class for this base info.
  38. const CXXRecordDecl *Class;
  39. /// IsVirtual - Whether the BaseInfo represents a virtual base or not.
  40. bool IsVirtual;
  41. /// Bases - Information about the base subobjects.
  42. SmallVector<BaseSubobjectInfo*, 4> Bases;
  43. /// PrimaryVirtualBaseInfo - Holds the base info for the primary virtual base
  44. /// of this base info (if one exists).
  45. BaseSubobjectInfo *PrimaryVirtualBaseInfo;
  46. // FIXME: Document.
  47. const BaseSubobjectInfo *Derived;
  48. };
  49. /// \brief Externally provided layout. Typically used when the AST source, such
  50. /// as DWARF, lacks all the information that was available at compile time, such
  51. /// as alignment attributes on fields and pragmas in effect.
  52. struct ExternalLayout {
  53. ExternalLayout() : Size(0), Align(0) {}
  54. /// \brief Overall record size in bits.
  55. uint64_t Size;
  56. /// \brief Overall record alignment in bits.
  57. uint64_t Align;
  58. /// \brief Record field offsets in bits.
  59. llvm::DenseMap<const FieldDecl *, uint64_t> FieldOffsets;
  60. /// \brief Direct, non-virtual base offsets.
  61. llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsets;
  62. /// \brief Virtual base offsets.
  63. llvm::DenseMap<const CXXRecordDecl *, CharUnits> VirtualBaseOffsets;
  64. /// Get the offset of the given field. The external source must provide
  65. /// entries for all fields in the record.
  66. uint64_t getExternalFieldOffset(const FieldDecl *FD) {
  67. assert(FieldOffsets.count(FD) &&
  68. "Field does not have an external offset");
  69. return FieldOffsets[FD];
  70. }
  71. bool getExternalNVBaseOffset(const CXXRecordDecl *RD, CharUnits &BaseOffset) {
  72. auto Known = BaseOffsets.find(RD);
  73. if (Known == BaseOffsets.end())
  74. return false;
  75. BaseOffset = Known->second;
  76. return true;
  77. }
  78. bool getExternalVBaseOffset(const CXXRecordDecl *RD, CharUnits &BaseOffset) {
  79. auto Known = VirtualBaseOffsets.find(RD);
  80. if (Known == VirtualBaseOffsets.end())
  81. return false;
  82. BaseOffset = Known->second;
  83. return true;
  84. }
  85. };
  86. /// EmptySubobjectMap - Keeps track of which empty subobjects exist at different
  87. /// offsets while laying out a C++ class.
  88. class EmptySubobjectMap {
  89. const ASTContext &Context;
  90. uint64_t CharWidth;
  91. /// Class - The class whose empty entries we're keeping track of.
  92. const CXXRecordDecl *Class;
  93. /// EmptyClassOffsets - A map from offsets to empty record decls.
  94. typedef llvm::TinyPtrVector<const CXXRecordDecl *> ClassVectorTy;
  95. typedef llvm::DenseMap<CharUnits, ClassVectorTy> EmptyClassOffsetsMapTy;
  96. EmptyClassOffsetsMapTy EmptyClassOffsets;
  97. /// MaxEmptyClassOffset - The highest offset known to contain an empty
  98. /// base subobject.
  99. CharUnits MaxEmptyClassOffset;
  100. /// ComputeEmptySubobjectSizes - Compute the size of the largest base or
  101. /// member subobject that is empty.
  102. void ComputeEmptySubobjectSizes();
  103. void AddSubobjectAtOffset(const CXXRecordDecl *RD, CharUnits Offset);
  104. void UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info,
  105. CharUnits Offset, bool PlacingEmptyBase);
  106. void UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD,
  107. const CXXRecordDecl *Class,
  108. CharUnits Offset);
  109. void UpdateEmptyFieldSubobjects(const FieldDecl *FD, CharUnits Offset);
  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 (std::find(Classes.begin(), Classes.end(), RD) == Classes.end())
  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 (std::find(Classes.begin(), Classes.end(), RD) != Classes.end())
  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);
  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 base subobject map.
  384. UpdateEmptyFieldSubobjects(FD, Offset);
  385. return true;
  386. }
  387. void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD,
  388. const CXXRecordDecl *Class,
  389. CharUnits Offset) {
  390. // We know that the only empty subobjects that can conflict with empty
  391. // field subobjects are subobjects of empty bases that can be placed at offset
  392. // zero. Because of this, we only need to keep track of empty field
  393. // subobjects with offsets less than the size of the largest empty
  394. // subobject for our class.
  395. if (Offset >= SizeOfLargestEmptySubobject)
  396. return;
  397. AddSubobjectAtOffset(RD, Offset);
  398. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  399. // Traverse all non-virtual bases.
  400. for (const CXXBaseSpecifier &Base : RD->bases()) {
  401. if (Base.isVirtual())
  402. continue;
  403. const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
  404. CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl);
  405. UpdateEmptyFieldSubobjects(BaseDecl, Class, BaseOffset);
  406. }
  407. if (RD == Class) {
  408. // This is the most derived class, traverse virtual bases as well.
  409. for (const CXXBaseSpecifier &Base : RD->vbases()) {
  410. const CXXRecordDecl *VBaseDecl = Base.getType()->getAsCXXRecordDecl();
  411. CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl);
  412. UpdateEmptyFieldSubobjects(VBaseDecl, Class, VBaseOffset);
  413. }
  414. }
  415. // Traverse all member variables.
  416. unsigned FieldNo = 0;
  417. for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
  418. I != E; ++I, ++FieldNo) {
  419. if (I->isBitField())
  420. continue;
  421. CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
  422. UpdateEmptyFieldSubobjects(*I, FieldOffset);
  423. }
  424. }
  425. void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const FieldDecl *FD,
  426. CharUnits Offset) {
  427. QualType T = FD->getType();
  428. if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
  429. UpdateEmptyFieldSubobjects(RD, RD, Offset);
  430. return;
  431. }
  432. // If we have an array type we need to update every element.
  433. if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) {
  434. QualType ElemTy = Context.getBaseElementType(AT);
  435. const RecordType *RT = ElemTy->getAs<RecordType>();
  436. if (!RT)
  437. return;
  438. const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
  439. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  440. uint64_t NumElements = Context.getConstantArrayElementCount(AT);
  441. CharUnits ElementOffset = Offset;
  442. for (uint64_t I = 0; I != NumElements; ++I) {
  443. // We know that the only empty subobjects that can conflict with empty
  444. // field subobjects are subobjects of empty bases that can be placed at
  445. // offset zero. Because of this, we only need to keep track of empty field
  446. // subobjects with offsets less than the size of the largest empty
  447. // subobject for our class.
  448. if (ElementOffset >= SizeOfLargestEmptySubobject)
  449. return;
  450. UpdateEmptyFieldSubobjects(RD, RD, ElementOffset);
  451. ElementOffset += Layout.getSize();
  452. }
  453. }
  454. }
  455. typedef llvm::SmallPtrSet<const CXXRecordDecl*, 4> ClassSetTy;
  456. class RecordLayoutBuilder {
  457. protected:
  458. // FIXME: Remove this and make the appropriate fields public.
  459. friend class clang::ASTContext;
  460. const ASTContext &Context;
  461. EmptySubobjectMap *EmptySubobjects;
  462. /// Size - The current size of the record layout.
  463. uint64_t Size;
  464. /// Alignment - The current alignment of the record layout.
  465. CharUnits Alignment;
  466. /// \brief The alignment if attribute packed is not used.
  467. CharUnits UnpackedAlignment;
  468. SmallVector<uint64_t, 16> FieldOffsets;
  469. /// \brief Whether the external AST source has provided a layout for this
  470. /// record.
  471. unsigned UseExternalLayout : 1;
  472. /// \brief Whether we need to infer alignment, even when we have an
  473. /// externally-provided layout.
  474. unsigned InferAlignment : 1;
  475. /// Packed - Whether the record is packed or not.
  476. unsigned Packed : 1;
  477. unsigned IsUnion : 1;
  478. unsigned IsMac68kAlign : 1;
  479. unsigned IsMsStruct : 1;
  480. /// UnfilledBitsInLastUnit - If the last field laid out was a bitfield,
  481. /// this contains the number of bits in the last unit that can be used for
  482. /// an adjacent bitfield if necessary. The unit in question is usually
  483. /// a byte, but larger units are used if IsMsStruct.
  484. unsigned char UnfilledBitsInLastUnit;
  485. /// LastBitfieldTypeSize - If IsMsStruct, represents the size of the type
  486. /// of the previous field if it was a bitfield.
  487. unsigned char LastBitfieldTypeSize;
  488. /// MaxFieldAlignment - The maximum allowed field alignment. This is set by
  489. /// #pragma pack.
  490. CharUnits MaxFieldAlignment;
  491. /// DataSize - The data size of the record being laid out.
  492. uint64_t DataSize;
  493. CharUnits NonVirtualSize;
  494. CharUnits NonVirtualAlignment;
  495. /// PrimaryBase - the primary base class (if one exists) of the class
  496. /// we're laying out.
  497. const CXXRecordDecl *PrimaryBase;
  498. /// PrimaryBaseIsVirtual - Whether the primary base of the class we're laying
  499. /// out is virtual.
  500. bool PrimaryBaseIsVirtual;
  501. /// HasOwnVFPtr - Whether the class provides its own vtable/vftbl
  502. /// pointer, as opposed to inheriting one from a primary base class.
  503. bool HasOwnVFPtr;
  504. typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy;
  505. /// Bases - base classes and their offsets in the record.
  506. BaseOffsetsMapTy Bases;
  507. // VBases - virtual base classes and their offsets in the record.
  508. ASTRecordLayout::VBaseOffsetsMapTy VBases;
  509. /// IndirectPrimaryBases - Virtual base classes, direct or indirect, that are
  510. /// primary base classes for some other direct or indirect base class.
  511. CXXIndirectPrimaryBaseSet IndirectPrimaryBases;
  512. /// FirstNearlyEmptyVBase - The first nearly empty virtual base class in
  513. /// inheritance graph order. Used for determining the primary base class.
  514. const CXXRecordDecl *FirstNearlyEmptyVBase;
  515. /// VisitedVirtualBases - A set of all the visited virtual bases, used to
  516. /// avoid visiting virtual bases more than once.
  517. llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
  518. /// Valid if UseExternalLayout is true.
  519. ExternalLayout External;
  520. RecordLayoutBuilder(const ASTContext &Context,
  521. EmptySubobjectMap *EmptySubobjects)
  522. : Context(Context), EmptySubobjects(EmptySubobjects), Size(0),
  523. Alignment(CharUnits::One()), UnpackedAlignment(CharUnits::One()),
  524. UseExternalLayout(false), InferAlignment(false),
  525. Packed(false), IsUnion(false), IsMac68kAlign(false), IsMsStruct(false),
  526. UnfilledBitsInLastUnit(0), LastBitfieldTypeSize(0),
  527. MaxFieldAlignment(CharUnits::Zero()),
  528. DataSize(0), NonVirtualSize(CharUnits::Zero()),
  529. NonVirtualAlignment(CharUnits::One()),
  530. PrimaryBase(nullptr), PrimaryBaseIsVirtual(false),
  531. HasOwnVFPtr(false),
  532. FirstNearlyEmptyVBase(nullptr) {}
  533. void Layout(const RecordDecl *D);
  534. void Layout(const CXXRecordDecl *D);
  535. void Layout(const ObjCInterfaceDecl *D);
  536. void LayoutFields(const RecordDecl *D);
  537. void LayoutField(const FieldDecl *D, bool InsertExtraPadding);
  538. void LayoutWideBitField(uint64_t FieldSize, uint64_t TypeSize,
  539. bool FieldPacked, const FieldDecl *D);
  540. void LayoutBitField(const FieldDecl *D);
  541. TargetCXXABI getCXXABI() const {
  542. return Context.getTargetInfo().getCXXABI();
  543. }
  544. /// BaseSubobjectInfoAllocator - Allocator for BaseSubobjectInfo objects.
  545. llvm::SpecificBumpPtrAllocator<BaseSubobjectInfo> BaseSubobjectInfoAllocator;
  546. typedef llvm::DenseMap<const CXXRecordDecl *, BaseSubobjectInfo *>
  547. BaseSubobjectInfoMapTy;
  548. /// VirtualBaseInfo - Map from all the (direct or indirect) virtual bases
  549. /// of the class we're laying out to their base subobject info.
  550. BaseSubobjectInfoMapTy VirtualBaseInfo;
  551. /// NonVirtualBaseInfo - Map from all the direct non-virtual bases of the
  552. /// class we're laying out to their base subobject info.
  553. BaseSubobjectInfoMapTy NonVirtualBaseInfo;
  554. /// ComputeBaseSubobjectInfo - Compute the base subobject information for the
  555. /// bases of the given class.
  556. void ComputeBaseSubobjectInfo(const CXXRecordDecl *RD);
  557. /// ComputeBaseSubobjectInfo - Compute the base subobject information for a
  558. /// single class and all of its base classes.
  559. BaseSubobjectInfo *ComputeBaseSubobjectInfo(const CXXRecordDecl *RD,
  560. bool IsVirtual,
  561. BaseSubobjectInfo *Derived);
  562. /// DeterminePrimaryBase - Determine the primary base of the given class.
  563. void DeterminePrimaryBase(const CXXRecordDecl *RD);
  564. void SelectPrimaryVBase(const CXXRecordDecl *RD);
  565. void EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign);
  566. /// LayoutNonVirtualBases - Determines the primary base class (if any) and
  567. /// lays it out. Will then proceed to lay out all non-virtual base clasess.
  568. void LayoutNonVirtualBases(const CXXRecordDecl *RD);
  569. /// LayoutNonVirtualBase - Lays out a single non-virtual base.
  570. void LayoutNonVirtualBase(const BaseSubobjectInfo *Base);
  571. void AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info,
  572. CharUnits Offset);
  573. /// LayoutVirtualBases - Lays out all the virtual bases.
  574. void LayoutVirtualBases(const CXXRecordDecl *RD,
  575. const CXXRecordDecl *MostDerivedClass);
  576. /// LayoutVirtualBase - Lays out a single virtual base.
  577. void LayoutVirtualBase(const BaseSubobjectInfo *Base);
  578. /// LayoutBase - Will lay out a base and return the offset where it was
  579. /// placed, in chars.
  580. CharUnits LayoutBase(const BaseSubobjectInfo *Base);
  581. /// InitializeLayout - Initialize record layout for the given record decl.
  582. void InitializeLayout(const Decl *D);
  583. /// FinishLayout - Finalize record layout. Adjust record size based on the
  584. /// alignment.
  585. void FinishLayout(const NamedDecl *D);
  586. void UpdateAlignment(CharUnits NewAlignment, CharUnits UnpackedNewAlignment);
  587. void UpdateAlignment(CharUnits NewAlignment) {
  588. UpdateAlignment(NewAlignment, NewAlignment);
  589. }
  590. /// \brief Retrieve the externally-supplied field offset for the given
  591. /// field.
  592. ///
  593. /// \param Field The field whose offset is being queried.
  594. /// \param ComputedOffset The offset that we've computed for this field.
  595. uint64_t updateExternalFieldOffset(const FieldDecl *Field,
  596. uint64_t ComputedOffset);
  597. void CheckFieldPadding(uint64_t Offset, uint64_t UnpaddedOffset,
  598. uint64_t UnpackedOffset, unsigned UnpackedAlign,
  599. bool isPacked, const FieldDecl *D);
  600. DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
  601. CharUnits getSize() const {
  602. assert(Size % Context.getCharWidth() == 0);
  603. return Context.toCharUnitsFromBits(Size);
  604. }
  605. uint64_t getSizeInBits() const { return Size; }
  606. void setSize(CharUnits NewSize) { Size = Context.toBits(NewSize); }
  607. void setSize(uint64_t NewSize) { Size = NewSize; }
  608. CharUnits getAligment() const { return Alignment; }
  609. CharUnits getDataSize() const {
  610. assert(DataSize % Context.getCharWidth() == 0);
  611. return Context.toCharUnitsFromBits(DataSize);
  612. }
  613. uint64_t getDataSizeInBits() const { return DataSize; }
  614. void setDataSize(CharUnits NewSize) { DataSize = Context.toBits(NewSize); }
  615. void setDataSize(uint64_t NewSize) { DataSize = NewSize; }
  616. RecordLayoutBuilder(const RecordLayoutBuilder &) = delete;
  617. void operator=(const RecordLayoutBuilder &) = delete;
  618. };
  619. } // end anonymous namespace
  620. void
  621. RecordLayoutBuilder::SelectPrimaryVBase(const CXXRecordDecl *RD) {
  622. for (const auto &I : RD->bases()) {
  623. assert(!I.getType()->isDependentType() &&
  624. "Cannot layout class with dependent bases.");
  625. const CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
  626. // Check if this is a nearly empty virtual base.
  627. if (I.isVirtual() && Context.isNearlyEmpty(Base)) {
  628. // If it's not an indirect primary base, then we've found our primary
  629. // base.
  630. if (!IndirectPrimaryBases.count(Base)) {
  631. PrimaryBase = Base;
  632. PrimaryBaseIsVirtual = true;
  633. return;
  634. }
  635. // Is this the first nearly empty virtual base?
  636. if (!FirstNearlyEmptyVBase)
  637. FirstNearlyEmptyVBase = Base;
  638. }
  639. SelectPrimaryVBase(Base);
  640. if (PrimaryBase)
  641. return;
  642. }
  643. }
  644. /// DeterminePrimaryBase - Determine the primary base of the given class.
  645. void RecordLayoutBuilder::DeterminePrimaryBase(const CXXRecordDecl *RD) {
  646. // If the class isn't dynamic, it won't have a primary base.
  647. if (!RD->isDynamicClass())
  648. return;
  649. // Compute all the primary virtual bases for all of our direct and
  650. // indirect bases, and record all their primary virtual base classes.
  651. RD->getIndirectPrimaryBases(IndirectPrimaryBases);
  652. // If the record has a dynamic base class, attempt to choose a primary base
  653. // class. It is the first (in direct base class order) non-virtual dynamic
  654. // base class, if one exists.
  655. for (const auto &I : RD->bases()) {
  656. // Ignore virtual bases.
  657. if (I.isVirtual())
  658. continue;
  659. const CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
  660. if (Base->isDynamicClass()) {
  661. // We found it.
  662. PrimaryBase = Base;
  663. PrimaryBaseIsVirtual = false;
  664. return;
  665. }
  666. }
  667. // Under the Itanium ABI, if there is no non-virtual primary base class,
  668. // try to compute the primary virtual base. The primary virtual base is
  669. // the first nearly empty virtual base that is not an indirect primary
  670. // virtual base class, if one exists.
  671. if (RD->getNumVBases() != 0) {
  672. SelectPrimaryVBase(RD);
  673. if (PrimaryBase)
  674. return;
  675. }
  676. // Otherwise, it is the first indirect primary base class, if one exists.
  677. if (FirstNearlyEmptyVBase) {
  678. PrimaryBase = FirstNearlyEmptyVBase;
  679. PrimaryBaseIsVirtual = true;
  680. return;
  681. }
  682. assert(!PrimaryBase && "Should not get here with a primary base!");
  683. }
  684. BaseSubobjectInfo *
  685. RecordLayoutBuilder::ComputeBaseSubobjectInfo(const CXXRecordDecl *RD,
  686. bool IsVirtual,
  687. BaseSubobjectInfo *Derived) {
  688. BaseSubobjectInfo *Info;
  689. if (IsVirtual) {
  690. // Check if we already have info about this virtual base.
  691. BaseSubobjectInfo *&InfoSlot = VirtualBaseInfo[RD];
  692. if (InfoSlot) {
  693. assert(InfoSlot->Class == RD && "Wrong class for virtual base info!");
  694. return InfoSlot;
  695. }
  696. // We don't, create it.
  697. InfoSlot = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
  698. Info = InfoSlot;
  699. } else {
  700. Info = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
  701. }
  702. Info->Class = RD;
  703. Info->IsVirtual = IsVirtual;
  704. Info->Derived = nullptr;
  705. Info->PrimaryVirtualBaseInfo = nullptr;
  706. const CXXRecordDecl *PrimaryVirtualBase = nullptr;
  707. BaseSubobjectInfo *PrimaryVirtualBaseInfo = nullptr;
  708. // Check if this base has a primary virtual base.
  709. if (RD->getNumVBases()) {
  710. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  711. if (Layout.isPrimaryBaseVirtual()) {
  712. // This base does have a primary virtual base.
  713. PrimaryVirtualBase = Layout.getPrimaryBase();
  714. assert(PrimaryVirtualBase && "Didn't have a primary virtual base!");
  715. // Now check if we have base subobject info about this primary base.
  716. PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
  717. if (PrimaryVirtualBaseInfo) {
  718. if (PrimaryVirtualBaseInfo->Derived) {
  719. // We did have info about this primary base, and it turns out that it
  720. // has already been claimed as a primary virtual base for another
  721. // base.
  722. PrimaryVirtualBase = nullptr;
  723. } else {
  724. // We can claim this base as our primary base.
  725. Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
  726. PrimaryVirtualBaseInfo->Derived = Info;
  727. }
  728. }
  729. }
  730. }
  731. // Now go through all direct bases.
  732. for (const auto &I : RD->bases()) {
  733. bool IsVirtual = I.isVirtual();
  734. const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
  735. Info->Bases.push_back(ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, Info));
  736. }
  737. if (PrimaryVirtualBase && !PrimaryVirtualBaseInfo) {
  738. // Traversing the bases must have created the base info for our primary
  739. // virtual base.
  740. PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
  741. assert(PrimaryVirtualBaseInfo &&
  742. "Did not create a primary virtual base!");
  743. // Claim the primary virtual base as our primary virtual base.
  744. Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
  745. PrimaryVirtualBaseInfo->Derived = Info;
  746. }
  747. return Info;
  748. }
  749. void RecordLayoutBuilder::ComputeBaseSubobjectInfo(const CXXRecordDecl *RD) {
  750. for (const auto &I : RD->bases()) {
  751. bool IsVirtual = I.isVirtual();
  752. const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
  753. // Compute the base subobject info for this base.
  754. BaseSubobjectInfo *Info = ComputeBaseSubobjectInfo(BaseDecl, IsVirtual,
  755. nullptr);
  756. if (IsVirtual) {
  757. // ComputeBaseInfo has already added this base for us.
  758. assert(VirtualBaseInfo.count(BaseDecl) &&
  759. "Did not add virtual base!");
  760. } else {
  761. // Add the base info to the map of non-virtual bases.
  762. assert(!NonVirtualBaseInfo.count(BaseDecl) &&
  763. "Non-virtual base already exists!");
  764. NonVirtualBaseInfo.insert(std::make_pair(BaseDecl, Info));
  765. }
  766. }
  767. }
  768. void
  769. RecordLayoutBuilder::EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign) {
  770. CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign;
  771. // The maximum field alignment overrides base align.
  772. if (!MaxFieldAlignment.isZero()) {
  773. BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
  774. UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment);
  775. }
  776. // Round up the current record size to pointer alignment.
  777. setSize(getSize().RoundUpToAlignment(BaseAlign));
  778. setDataSize(getSize());
  779. // Update the alignment.
  780. UpdateAlignment(BaseAlign, UnpackedBaseAlign);
  781. }
  782. void
  783. RecordLayoutBuilder::LayoutNonVirtualBases(const CXXRecordDecl *RD) {
  784. // Then, determine the primary base class.
  785. DeterminePrimaryBase(RD);
  786. // Compute base subobject info.
  787. ComputeBaseSubobjectInfo(RD);
  788. // If we have a primary base class, lay it out.
  789. if (PrimaryBase) {
  790. if (PrimaryBaseIsVirtual) {
  791. // If the primary virtual base was a primary virtual base of some other
  792. // base class we'll have to steal it.
  793. BaseSubobjectInfo *PrimaryBaseInfo = VirtualBaseInfo.lookup(PrimaryBase);
  794. PrimaryBaseInfo->Derived = nullptr;
  795. // We have a virtual primary base, insert it as an indirect primary base.
  796. IndirectPrimaryBases.insert(PrimaryBase);
  797. assert(!VisitedVirtualBases.count(PrimaryBase) &&
  798. "vbase already visited!");
  799. VisitedVirtualBases.insert(PrimaryBase);
  800. LayoutVirtualBase(PrimaryBaseInfo);
  801. } else {
  802. BaseSubobjectInfo *PrimaryBaseInfo =
  803. NonVirtualBaseInfo.lookup(PrimaryBase);
  804. assert(PrimaryBaseInfo &&
  805. "Did not find base info for non-virtual primary base!");
  806. LayoutNonVirtualBase(PrimaryBaseInfo);
  807. }
  808. // If this class needs a vtable/vf-table and didn't get one from a
  809. // primary base, add it in now.
  810. } else if (RD->isDynamicClass()) {
  811. assert(DataSize == 0 && "Vtable pointer must be at offset zero!");
  812. CharUnits PtrWidth =
  813. Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
  814. CharUnits PtrAlign =
  815. Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(0));
  816. EnsureVTablePointerAlignment(PtrAlign);
  817. HasOwnVFPtr = true;
  818. setSize(getSize() + PtrWidth);
  819. setDataSize(getSize());
  820. }
  821. // Now lay out the non-virtual bases.
  822. for (const auto &I : RD->bases()) {
  823. // Ignore virtual bases.
  824. if (I.isVirtual())
  825. continue;
  826. const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
  827. // Skip the primary base, because we've already laid it out. The
  828. // !PrimaryBaseIsVirtual check is required because we might have a
  829. // non-virtual base of the same type as a primary virtual base.
  830. if (BaseDecl == PrimaryBase && !PrimaryBaseIsVirtual)
  831. continue;
  832. // Lay out the base.
  833. BaseSubobjectInfo *BaseInfo = NonVirtualBaseInfo.lookup(BaseDecl);
  834. assert(BaseInfo && "Did not find base info for non-virtual base!");
  835. LayoutNonVirtualBase(BaseInfo);
  836. }
  837. }
  838. void RecordLayoutBuilder::LayoutNonVirtualBase(const BaseSubobjectInfo *Base) {
  839. // Layout the base.
  840. CharUnits Offset = LayoutBase(Base);
  841. // Add its base class offset.
  842. assert(!Bases.count(Base->Class) && "base offset already exists!");
  843. Bases.insert(std::make_pair(Base->Class, Offset));
  844. AddPrimaryVirtualBaseOffsets(Base, Offset);
  845. }
  846. void
  847. RecordLayoutBuilder::AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info,
  848. CharUnits Offset) {
  849. // This base isn't interesting, it has no virtual bases.
  850. if (!Info->Class->getNumVBases())
  851. return;
  852. // First, check if we have a virtual primary base to add offsets for.
  853. if (Info->PrimaryVirtualBaseInfo) {
  854. assert(Info->PrimaryVirtualBaseInfo->IsVirtual &&
  855. "Primary virtual base is not virtual!");
  856. if (Info->PrimaryVirtualBaseInfo->Derived == Info) {
  857. // Add the offset.
  858. assert(!VBases.count(Info->PrimaryVirtualBaseInfo->Class) &&
  859. "primary vbase offset already exists!");
  860. VBases.insert(std::make_pair(Info->PrimaryVirtualBaseInfo->Class,
  861. ASTRecordLayout::VBaseInfo(Offset, false)));
  862. // Traverse the primary virtual base.
  863. AddPrimaryVirtualBaseOffsets(Info->PrimaryVirtualBaseInfo, Offset);
  864. }
  865. }
  866. // Now go through all direct non-virtual bases.
  867. const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
  868. for (const BaseSubobjectInfo *Base : Info->Bases) {
  869. if (Base->IsVirtual)
  870. continue;
  871. CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
  872. AddPrimaryVirtualBaseOffsets(Base, BaseOffset);
  873. }
  874. }
  875. void
  876. RecordLayoutBuilder::LayoutVirtualBases(const CXXRecordDecl *RD,
  877. const CXXRecordDecl *MostDerivedClass) {
  878. const CXXRecordDecl *PrimaryBase;
  879. bool PrimaryBaseIsVirtual;
  880. if (MostDerivedClass == RD) {
  881. PrimaryBase = this->PrimaryBase;
  882. PrimaryBaseIsVirtual = this->PrimaryBaseIsVirtual;
  883. } else {
  884. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  885. PrimaryBase = Layout.getPrimaryBase();
  886. PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
  887. }
  888. for (const CXXBaseSpecifier &Base : RD->bases()) {
  889. assert(!Base.getType()->isDependentType() &&
  890. "Cannot layout class with dependent bases.");
  891. const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
  892. if (Base.isVirtual()) {
  893. if (PrimaryBase != BaseDecl || !PrimaryBaseIsVirtual) {
  894. bool IndirectPrimaryBase = IndirectPrimaryBases.count(BaseDecl);
  895. // Only lay out the virtual base if it's not an indirect primary base.
  896. if (!IndirectPrimaryBase) {
  897. // Only visit virtual bases once.
  898. if (!VisitedVirtualBases.insert(BaseDecl).second)
  899. continue;
  900. const BaseSubobjectInfo *BaseInfo = VirtualBaseInfo.lookup(BaseDecl);
  901. assert(BaseInfo && "Did not find virtual base info!");
  902. LayoutVirtualBase(BaseInfo);
  903. }
  904. }
  905. }
  906. if (!BaseDecl->getNumVBases()) {
  907. // This base isn't interesting since it doesn't have any virtual bases.
  908. continue;
  909. }
  910. LayoutVirtualBases(BaseDecl, MostDerivedClass);
  911. }
  912. }
  913. void RecordLayoutBuilder::LayoutVirtualBase(const BaseSubobjectInfo *Base) {
  914. assert(!Base->Derived && "Trying to lay out a primary virtual base!");
  915. // Layout the base.
  916. CharUnits Offset = LayoutBase(Base);
  917. // Add its base class offset.
  918. assert(!VBases.count(Base->Class) && "vbase offset already exists!");
  919. VBases.insert(std::make_pair(Base->Class,
  920. ASTRecordLayout::VBaseInfo(Offset, false)));
  921. AddPrimaryVirtualBaseOffsets(Base, Offset);
  922. }
  923. CharUnits RecordLayoutBuilder::LayoutBase(const BaseSubobjectInfo *Base) {
  924. const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base->Class);
  925. CharUnits Offset;
  926. // Query the external layout to see if it provides an offset.
  927. bool HasExternalLayout = false;
  928. if (UseExternalLayout) {
  929. llvm::DenseMap<const CXXRecordDecl *, CharUnits>::iterator Known;
  930. if (Base->IsVirtual)
  931. HasExternalLayout = External.getExternalNVBaseOffset(Base->Class, Offset);
  932. else
  933. HasExternalLayout = External.getExternalVBaseOffset(Base->Class, Offset);
  934. }
  935. CharUnits UnpackedBaseAlign = Layout.getNonVirtualAlignment();
  936. CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign;
  937. // If we have an empty base class, try to place it at offset 0.
  938. if (Base->Class->isEmpty() &&
  939. (!HasExternalLayout || Offset == CharUnits::Zero()) &&
  940. EmptySubobjects->CanPlaceBaseAtOffset(Base, CharUnits::Zero())) {
  941. setSize(std::max(getSize(), Layout.getSize()));
  942. UpdateAlignment(BaseAlign, UnpackedBaseAlign);
  943. return CharUnits::Zero();
  944. }
  945. // The maximum field alignment overrides base align.
  946. if (!MaxFieldAlignment.isZero()) {
  947. BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
  948. UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment);
  949. }
  950. if (!HasExternalLayout) {
  951. // Round up the current record size to the base's alignment boundary.
  952. Offset = getDataSize().RoundUpToAlignment(BaseAlign);
  953. // Try to place the base.
  954. while (!EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset))
  955. Offset += BaseAlign;
  956. } else {
  957. bool Allowed = EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset);
  958. (void)Allowed;
  959. assert(Allowed && "Base subobject externally placed at overlapping offset");
  960. if (InferAlignment && Offset < getDataSize().RoundUpToAlignment(BaseAlign)){
  961. // The externally-supplied base offset is before the base offset we
  962. // computed. Assume that the structure is packed.
  963. Alignment = CharUnits::One();
  964. InferAlignment = false;
  965. }
  966. }
  967. if (!Base->Class->isEmpty()) {
  968. // Update the data size.
  969. setDataSize(Offset + Layout.getNonVirtualSize());
  970. setSize(std::max(getSize(), getDataSize()));
  971. } else
  972. setSize(std::max(getSize(), Offset + Layout.getSize()));
  973. // Remember max struct/class alignment.
  974. UpdateAlignment(BaseAlign, UnpackedBaseAlign);
  975. return Offset;
  976. }
  977. void RecordLayoutBuilder::InitializeLayout(const Decl *D) {
  978. if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
  979. IsUnion = RD->isUnion();
  980. IsMsStruct = RD->isMsStruct(Context);
  981. }
  982. Packed = D->hasAttr<PackedAttr>();
  983. // Honor the default struct packing maximum alignment flag.
  984. if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct) {
  985. MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment);
  986. }
  987. // mac68k alignment supersedes maximum field alignment and attribute aligned,
  988. // and forces all structures to have 2-byte alignment. The IBM docs on it
  989. // allude to additional (more complicated) semantics, especially with regard
  990. // to bit-fields, but gcc appears not to follow that.
  991. if (D->hasAttr<AlignMac68kAttr>()) {
  992. IsMac68kAlign = true;
  993. MaxFieldAlignment = CharUnits::fromQuantity(2);
  994. Alignment = CharUnits::fromQuantity(2);
  995. } else {
  996. if (const MaxFieldAlignmentAttr *MFAA = D->getAttr<MaxFieldAlignmentAttr>())
  997. MaxFieldAlignment = Context.toCharUnitsFromBits(MFAA->getAlignment());
  998. if (unsigned MaxAlign = D->getMaxAlignment())
  999. UpdateAlignment(Context.toCharUnitsFromBits(MaxAlign));
  1000. }
  1001. // If there is an external AST source, ask it for the various offsets.
  1002. if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
  1003. if (ExternalASTSource *Source = Context.getExternalSource()) {
  1004. UseExternalLayout = Source->layoutRecordType(
  1005. RD, External.Size, External.Align, External.FieldOffsets,
  1006. External.BaseOffsets, External.VirtualBaseOffsets);
  1007. // Update based on external alignment.
  1008. if (UseExternalLayout) {
  1009. if (External.Align > 0) {
  1010. Alignment = Context.toCharUnitsFromBits(External.Align);
  1011. } else {
  1012. // The external source didn't have alignment information; infer it.
  1013. InferAlignment = true;
  1014. }
  1015. }
  1016. }
  1017. }
  1018. void RecordLayoutBuilder::Layout(const RecordDecl *D) {
  1019. InitializeLayout(D);
  1020. LayoutFields(D);
  1021. // Finally, round the size of the total struct up to the alignment of the
  1022. // struct itself.
  1023. FinishLayout(D);
  1024. }
  1025. void RecordLayoutBuilder::Layout(const CXXRecordDecl *RD) {
  1026. InitializeLayout(RD);
  1027. // Lay out the vtable and the non-virtual bases.
  1028. LayoutNonVirtualBases(RD);
  1029. LayoutFields(RD);
  1030. NonVirtualSize = Context.toCharUnitsFromBits(
  1031. llvm::RoundUpToAlignment(getSizeInBits(),
  1032. Context.getTargetInfo().getCharAlign()));
  1033. NonVirtualAlignment = Alignment;
  1034. // Lay out the virtual bases and add the primary virtual base offsets.
  1035. LayoutVirtualBases(RD, RD);
  1036. // Finally, round the size of the total struct up to the alignment
  1037. // of the struct itself.
  1038. FinishLayout(RD);
  1039. #ifndef NDEBUG
  1040. // Check that we have base offsets for all bases.
  1041. for (const CXXBaseSpecifier &Base : RD->bases()) {
  1042. if (Base.isVirtual())
  1043. continue;
  1044. const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
  1045. assert(Bases.count(BaseDecl) && "Did not find base offset!");
  1046. }
  1047. // And all virtual bases.
  1048. for (const CXXBaseSpecifier &Base : RD->vbases()) {
  1049. const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
  1050. assert(VBases.count(BaseDecl) && "Did not find base offset!");
  1051. }
  1052. #endif
  1053. }
  1054. void RecordLayoutBuilder::Layout(const ObjCInterfaceDecl *D) {
  1055. if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
  1056. const ASTRecordLayout &SL = Context.getASTObjCInterfaceLayout(SD);
  1057. UpdateAlignment(SL.getAlignment());
  1058. // We start laying out ivars not at the end of the superclass
  1059. // structure, but at the next byte following the last field.
  1060. setSize(SL.getDataSize());
  1061. setDataSize(getSize());
  1062. }
  1063. InitializeLayout(D);
  1064. // Layout each ivar sequentially.
  1065. for (const ObjCIvarDecl *IVD = D->all_declared_ivar_begin(); IVD;
  1066. IVD = IVD->getNextIvar())
  1067. LayoutField(IVD, false);
  1068. // Finally, round the size of the total struct up to the alignment of the
  1069. // struct itself.
  1070. FinishLayout(D);
  1071. }
  1072. void RecordLayoutBuilder::LayoutFields(const RecordDecl *D) {
  1073. // Layout each field, for now, just sequentially, respecting alignment. In
  1074. // the future, this will need to be tweakable by targets.
  1075. bool InsertExtraPadding = D->mayInsertExtraPadding(/*EmitRemark=*/true);
  1076. bool HasFlexibleArrayMember = D->hasFlexibleArrayMember();
  1077. for (auto I = D->field_begin(), End = D->field_end(); I != End; ++I) {
  1078. auto Next(I);
  1079. ++Next;
  1080. LayoutField(*I,
  1081. InsertExtraPadding && (Next != End || !HasFlexibleArrayMember));
  1082. }
  1083. }
  1084. // Rounds the specified size to have it a multiple of the char size.
  1085. static uint64_t
  1086. roundUpSizeToCharAlignment(uint64_t Size,
  1087. const ASTContext &Context) {
  1088. uint64_t CharAlignment = Context.getTargetInfo().getCharAlign();
  1089. return llvm::RoundUpToAlignment(Size, CharAlignment);
  1090. }
  1091. void RecordLayoutBuilder::LayoutWideBitField(uint64_t FieldSize,
  1092. uint64_t TypeSize,
  1093. bool FieldPacked,
  1094. const FieldDecl *D) {
  1095. assert(Context.getLangOpts().CPlusPlus &&
  1096. "Can only have wide bit-fields in C++!");
  1097. // Itanium C++ ABI 2.4:
  1098. // If sizeof(T)*8 < n, let T' be the largest integral POD type with
  1099. // sizeof(T')*8 <= n.
  1100. QualType IntegralPODTypes[] = {
  1101. Context.UnsignedCharTy, Context.UnsignedShortTy, Context.UnsignedIntTy,
  1102. Context.UnsignedLongTy, Context.UnsignedLongLongTy
  1103. };
  1104. QualType Type;
  1105. for (const QualType &QT : IntegralPODTypes) {
  1106. uint64_t Size = Context.getTypeSize(QT);
  1107. if (Size > FieldSize)
  1108. break;
  1109. Type = QT;
  1110. }
  1111. assert(!Type.isNull() && "Did not find a type!");
  1112. CharUnits TypeAlign = Context.getTypeAlignInChars(Type);
  1113. // We're not going to use any of the unfilled bits in the last byte.
  1114. UnfilledBitsInLastUnit = 0;
  1115. LastBitfieldTypeSize = 0;
  1116. uint64_t FieldOffset;
  1117. uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastUnit;
  1118. if (IsUnion) {
  1119. uint64_t RoundedFieldSize = roundUpSizeToCharAlignment(FieldSize,
  1120. Context);
  1121. setDataSize(std::max(getDataSizeInBits(), RoundedFieldSize));
  1122. FieldOffset = 0;
  1123. } else {
  1124. // The bitfield is allocated starting at the next offset aligned
  1125. // appropriately for T', with length n bits.
  1126. FieldOffset = llvm::RoundUpToAlignment(getDataSizeInBits(),
  1127. Context.toBits(TypeAlign));
  1128. uint64_t NewSizeInBits = FieldOffset + FieldSize;
  1129. setDataSize(llvm::RoundUpToAlignment(NewSizeInBits,
  1130. Context.getTargetInfo().getCharAlign()));
  1131. UnfilledBitsInLastUnit = getDataSizeInBits() - NewSizeInBits;
  1132. }
  1133. // Place this field at the current location.
  1134. FieldOffsets.push_back(FieldOffset);
  1135. CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, FieldOffset,
  1136. Context.toBits(TypeAlign), FieldPacked, D);
  1137. // Update the size.
  1138. setSize(std::max(getSizeInBits(), getDataSizeInBits()));
  1139. // Remember max struct/class alignment.
  1140. UpdateAlignment(TypeAlign);
  1141. }
  1142. void RecordLayoutBuilder::LayoutBitField(const FieldDecl *D) {
  1143. bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
  1144. uint64_t FieldSize = D->getBitWidthValue(Context);
  1145. TypeInfo FieldInfo = Context.getTypeInfo(D->getType());
  1146. uint64_t TypeSize = FieldInfo.Width;
  1147. unsigned FieldAlign = FieldInfo.Align;
  1148. // UnfilledBitsInLastUnit is the difference between the end of the
  1149. // last allocated bitfield (i.e. the first bit offset available for
  1150. // bitfields) and the end of the current data size in bits (i.e. the
  1151. // first bit offset available for non-bitfields). The current data
  1152. // size in bits is always a multiple of the char size; additionally,
  1153. // for ms_struct records it's also a multiple of the
  1154. // LastBitfieldTypeSize (if set).
  1155. // The struct-layout algorithm is dictated by the platform ABI,
  1156. // which in principle could use almost any rules it likes. In
  1157. // practice, UNIXy targets tend to inherit the algorithm described
  1158. // in the System V generic ABI. The basic bitfield layout rule in
  1159. // System V is to place bitfields at the next available bit offset
  1160. // where the entire bitfield would fit in an aligned storage unit of
  1161. // the declared type; it's okay if an earlier or later non-bitfield
  1162. // is allocated in the same storage unit. However, some targets
  1163. // (those that !useBitFieldTypeAlignment(), e.g. ARM APCS) don't
  1164. // require this storage unit to be aligned, and therefore always put
  1165. // the bitfield at the next available bit offset.
  1166. // ms_struct basically requests a complete replacement of the
  1167. // platform ABI's struct-layout algorithm, with the high-level goal
  1168. // of duplicating MSVC's layout. For non-bitfields, this follows
  1169. // the standard algorithm. The basic bitfield layout rule is to
  1170. // allocate an entire unit of the bitfield's declared type
  1171. // (e.g. 'unsigned long'), then parcel it up among successive
  1172. // bitfields whose declared types have the same size, making a new
  1173. // unit as soon as the last can no longer store the whole value.
  1174. // Since it completely replaces the platform ABI's algorithm,
  1175. // settings like !useBitFieldTypeAlignment() do not apply.
  1176. // A zero-width bitfield forces the use of a new storage unit for
  1177. // later bitfields. In general, this occurs by rounding up the
  1178. // current size of the struct as if the algorithm were about to
  1179. // place a non-bitfield of the field's formal type. Usually this
  1180. // does not change the alignment of the struct itself, but it does
  1181. // on some targets (those that useZeroLengthBitfieldAlignment(),
  1182. // e.g. ARM). In ms_struct layout, zero-width bitfields are
  1183. // ignored unless they follow a non-zero-width bitfield.
  1184. // A field alignment restriction (e.g. from #pragma pack) or
  1185. // specification (e.g. from __attribute__((aligned))) changes the
  1186. // formal alignment of the field. For System V, this alters the
  1187. // required alignment of the notional storage unit that must contain
  1188. // the bitfield. For ms_struct, this only affects the placement of
  1189. // new storage units. In both cases, the effect of #pragma pack is
  1190. // ignored on zero-width bitfields.
  1191. // On System V, a packed field (e.g. from #pragma pack or
  1192. // __attribute__((packed))) always uses the next available bit
  1193. // offset.
  1194. // In an ms_struct struct, the alignment of a fundamental type is
  1195. // always equal to its size. This is necessary in order to mimic
  1196. // the i386 alignment rules on targets which might not fully align
  1197. // all types (e.g. Darwin PPC32, where alignof(long long) == 4).
  1198. // First, some simple bookkeeping to perform for ms_struct structs.
  1199. if (IsMsStruct) {
  1200. // The field alignment for integer types is always the size.
  1201. FieldAlign = TypeSize;
  1202. // If the previous field was not a bitfield, or was a bitfield
  1203. // with a different storage unit size, we're done with that
  1204. // storage unit.
  1205. if (LastBitfieldTypeSize != TypeSize) {
  1206. // Also, ignore zero-length bitfields after non-bitfields.
  1207. if (!LastBitfieldTypeSize && !FieldSize)
  1208. FieldAlign = 1;
  1209. UnfilledBitsInLastUnit = 0;
  1210. LastBitfieldTypeSize = 0;
  1211. }
  1212. }
  1213. // If the field is wider than its declared type, it follows
  1214. // different rules in all cases.
  1215. if (FieldSize > TypeSize) {
  1216. LayoutWideBitField(FieldSize, TypeSize, FieldPacked, D);
  1217. return;
  1218. }
  1219. // Compute the next available bit offset.
  1220. uint64_t FieldOffset =
  1221. IsUnion ? 0 : (getDataSizeInBits() - UnfilledBitsInLastUnit);
  1222. // Handle targets that don't honor bitfield type alignment.
  1223. if (!IsMsStruct && !Context.getTargetInfo().useBitFieldTypeAlignment()) {
  1224. // Some such targets do honor it on zero-width bitfields.
  1225. if (FieldSize == 0 &&
  1226. Context.getTargetInfo().useZeroLengthBitfieldAlignment()) {
  1227. // The alignment to round up to is the max of the field's natural
  1228. // alignment and a target-specific fixed value (sometimes zero).
  1229. unsigned ZeroLengthBitfieldBoundary =
  1230. Context.getTargetInfo().getZeroLengthBitfieldBoundary();
  1231. FieldAlign = std::max(FieldAlign, ZeroLengthBitfieldBoundary);
  1232. // If that doesn't apply, just ignore the field alignment.
  1233. } else {
  1234. FieldAlign = 1;
  1235. }
  1236. }
  1237. // Remember the alignment we would have used if the field were not packed.
  1238. unsigned UnpackedFieldAlign = FieldAlign;
  1239. // Ignore the field alignment if the field is packed unless it has zero-size.
  1240. if (!IsMsStruct && FieldPacked && FieldSize != 0)
  1241. FieldAlign = 1;
  1242. // But, if there's an 'aligned' attribute on the field, honor that.
  1243. if (unsigned ExplicitFieldAlign = D->getMaxAlignment()) {
  1244. FieldAlign = std::max(FieldAlign, ExplicitFieldAlign);
  1245. UnpackedFieldAlign = std::max(UnpackedFieldAlign, ExplicitFieldAlign);
  1246. }
  1247. // But, if there's a #pragma pack in play, that takes precedent over
  1248. // even the 'aligned' attribute, for non-zero-width bitfields.
  1249. if (!MaxFieldAlignment.isZero() && FieldSize) {
  1250. unsigned MaxFieldAlignmentInBits = Context.toBits(MaxFieldAlignment);
  1251. FieldAlign = std::min(FieldAlign, MaxFieldAlignmentInBits);
  1252. UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignmentInBits);
  1253. }
  1254. // For purposes of diagnostics, we're going to simultaneously
  1255. // compute the field offsets that we would have used if we weren't
  1256. // adding any alignment padding or if the field weren't packed.
  1257. uint64_t UnpaddedFieldOffset = FieldOffset;
  1258. uint64_t UnpackedFieldOffset = FieldOffset;
  1259. // Check if we need to add padding to fit the bitfield within an
  1260. // allocation unit with the right size and alignment. The rules are
  1261. // somewhat different here for ms_struct structs.
  1262. if (IsMsStruct) {
  1263. // If it's not a zero-width bitfield, and we can fit the bitfield
  1264. // into the active storage unit (and we haven't already decided to
  1265. // start a new storage unit), just do so, regardless of any other
  1266. // other consideration. Otherwise, round up to the right alignment.
  1267. if (FieldSize == 0 || FieldSize > UnfilledBitsInLastUnit) {
  1268. FieldOffset = llvm::RoundUpToAlignment(FieldOffset, FieldAlign);
  1269. UnpackedFieldOffset = llvm::RoundUpToAlignment(UnpackedFieldOffset,
  1270. UnpackedFieldAlign);
  1271. UnfilledBitsInLastUnit = 0;
  1272. }
  1273. } else {
  1274. // #pragma pack, with any value, suppresses the insertion of padding.
  1275. bool AllowPadding = MaxFieldAlignment.isZero();
  1276. // Compute the real offset.
  1277. if (FieldSize == 0 ||
  1278. (AllowPadding &&
  1279. (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize)) {
  1280. FieldOffset = llvm::RoundUpToAlignment(FieldOffset, FieldAlign);
  1281. }
  1282. // Repeat the computation for diagnostic purposes.
  1283. if (FieldSize == 0 ||
  1284. (AllowPadding &&
  1285. (UnpackedFieldOffset & (UnpackedFieldAlign-1)) + FieldSize > TypeSize))
  1286. UnpackedFieldOffset = llvm::RoundUpToAlignment(UnpackedFieldOffset,
  1287. UnpackedFieldAlign);
  1288. }
  1289. // If we're using external layout, give the external layout a chance
  1290. // to override this information.
  1291. if (UseExternalLayout)
  1292. FieldOffset = updateExternalFieldOffset(D, FieldOffset);
  1293. // Okay, place the bitfield at the calculated offset.
  1294. FieldOffsets.push_back(FieldOffset);
  1295. // Bookkeeping:
  1296. // Anonymous members don't affect the overall record alignment,
  1297. // except on targets where they do.
  1298. if (!IsMsStruct &&
  1299. !Context.getTargetInfo().useZeroLengthBitfieldAlignment() &&
  1300. !D->getIdentifier())
  1301. FieldAlign = UnpackedFieldAlign = 1;
  1302. // Diagnose differences in layout due to padding or packing.
  1303. if (!UseExternalLayout)
  1304. CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, UnpackedFieldOffset,
  1305. UnpackedFieldAlign, FieldPacked, D);
  1306. // Update DataSize to include the last byte containing (part of) the bitfield.
  1307. // For unions, this is just a max operation, as usual.
  1308. if (IsUnion) {
  1309. uint64_t RoundedFieldSize = roundUpSizeToCharAlignment(FieldSize,
  1310. Context);
  1311. setDataSize(std::max(getDataSizeInBits(), RoundedFieldSize));
  1312. // For non-zero-width bitfields in ms_struct structs, allocate a new
  1313. // storage unit if necessary.
  1314. } else if (IsMsStruct && FieldSize) {
  1315. // We should have cleared UnfilledBitsInLastUnit in every case
  1316. // where we changed storage units.
  1317. if (!UnfilledBitsInLastUnit) {
  1318. setDataSize(FieldOffset + TypeSize);
  1319. UnfilledBitsInLastUnit = TypeSize;
  1320. }
  1321. UnfilledBitsInLastUnit -= FieldSize;
  1322. LastBitfieldTypeSize = TypeSize;
  1323. // Otherwise, bump the data size up to include the bitfield,
  1324. // including padding up to char alignment, and then remember how
  1325. // bits we didn't use.
  1326. } else {
  1327. uint64_t NewSizeInBits = FieldOffset + FieldSize;
  1328. uint64_t CharAlignment = Context.getTargetInfo().getCharAlign();
  1329. setDataSize(llvm::RoundUpToAlignment(NewSizeInBits, CharAlignment));
  1330. UnfilledBitsInLastUnit = getDataSizeInBits() - NewSizeInBits;
  1331. // The only time we can get here for an ms_struct is if this is a
  1332. // zero-width bitfield, which doesn't count as anything for the
  1333. // purposes of unfilled bits.
  1334. LastBitfieldTypeSize = 0;
  1335. }
  1336. // Update the size.
  1337. setSize(std::max(getSizeInBits(), getDataSizeInBits()));
  1338. // Remember max struct/class alignment.
  1339. UpdateAlignment(Context.toCharUnitsFromBits(FieldAlign),
  1340. Context.toCharUnitsFromBits(UnpackedFieldAlign));
  1341. }
  1342. void RecordLayoutBuilder::LayoutField(const FieldDecl *D,
  1343. bool InsertExtraPadding) {
  1344. if (D->isBitField()) {
  1345. LayoutBitField(D);
  1346. return;
  1347. }
  1348. uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastUnit;
  1349. // Reset the unfilled bits.
  1350. UnfilledBitsInLastUnit = 0;
  1351. LastBitfieldTypeSize = 0;
  1352. bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
  1353. CharUnits FieldOffset =
  1354. IsUnion ? CharUnits::Zero() : getDataSize();
  1355. CharUnits FieldSize;
  1356. CharUnits FieldAlign;
  1357. if (D->getType()->isIncompleteArrayType()) {
  1358. // This is a flexible array member; we can't directly
  1359. // query getTypeInfo about these, so we figure it out here.
  1360. // Flexible array members don't have any size, but they
  1361. // have to be aligned appropriately for their element type.
  1362. FieldSize = CharUnits::Zero();
  1363. const ArrayType* ATy = Context.getAsArrayType(D->getType());
  1364. FieldAlign = Context.getTypeAlignInChars(ATy->getElementType());
  1365. } else if (const ReferenceType *RT = D->getType()->getAs<ReferenceType>()) {
  1366. unsigned AS = RT->getPointeeType().getAddressSpace();
  1367. FieldSize =
  1368. Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(AS));
  1369. FieldAlign =
  1370. Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(AS));
  1371. } else {
  1372. std::pair<CharUnits, CharUnits> FieldInfo =
  1373. Context.getTypeInfoInChars(D->getType());
  1374. FieldSize = FieldInfo.first;
  1375. FieldAlign = FieldInfo.second;
  1376. if (IsMsStruct) {
  1377. // If MS bitfield layout is required, figure out what type is being
  1378. // laid out and align the field to the width of that type.
  1379. // Resolve all typedefs down to their base type and round up the field
  1380. // alignment if necessary.
  1381. QualType T = Context.getBaseElementType(D->getType());
  1382. if (const BuiltinType *BTy = T->getAs<BuiltinType>()) {
  1383. CharUnits TypeSize = Context.getTypeSizeInChars(BTy);
  1384. if (TypeSize > FieldAlign)
  1385. FieldAlign = TypeSize;
  1386. }
  1387. }
  1388. }
  1389. // The align if the field is not packed. This is to check if the attribute
  1390. // was unnecessary (-Wpacked).
  1391. CharUnits UnpackedFieldAlign = FieldAlign;
  1392. CharUnits UnpackedFieldOffset = FieldOffset;
  1393. if (FieldPacked)
  1394. FieldAlign = CharUnits::One();
  1395. CharUnits MaxAlignmentInChars =
  1396. Context.toCharUnitsFromBits(D->getMaxAlignment());
  1397. FieldAlign = std::max(FieldAlign, MaxAlignmentInChars);
  1398. UnpackedFieldAlign = std::max(UnpackedFieldAlign, MaxAlignmentInChars);
  1399. // The maximum field alignment overrides the aligned attribute.
  1400. if (!MaxFieldAlignment.isZero()) {
  1401. FieldAlign = std::min(FieldAlign, MaxFieldAlignment);
  1402. UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignment);
  1403. }
  1404. // Round up the current record size to the field's alignment boundary.
  1405. FieldOffset = FieldOffset.RoundUpToAlignment(FieldAlign);
  1406. UnpackedFieldOffset =
  1407. UnpackedFieldOffset.RoundUpToAlignment(UnpackedFieldAlign);
  1408. if (UseExternalLayout) {
  1409. FieldOffset = Context.toCharUnitsFromBits(
  1410. updateExternalFieldOffset(D, Context.toBits(FieldOffset)));
  1411. if (!IsUnion && EmptySubobjects) {
  1412. // Record the fact that we're placing a field at this offset.
  1413. bool Allowed = EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset);
  1414. (void)Allowed;
  1415. assert(Allowed && "Externally-placed field cannot be placed here");
  1416. }
  1417. } else {
  1418. if (!IsUnion && EmptySubobjects) {
  1419. // Check if we can place the field at this offset.
  1420. while (!EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset)) {
  1421. // We couldn't place the field at the offset. Try again at a new offset.
  1422. FieldOffset += FieldAlign;
  1423. }
  1424. }
  1425. }
  1426. // Place this field at the current location.
  1427. FieldOffsets.push_back(Context.toBits(FieldOffset));
  1428. if (!UseExternalLayout)
  1429. CheckFieldPadding(Context.toBits(FieldOffset), UnpaddedFieldOffset,
  1430. Context.toBits(UnpackedFieldOffset),
  1431. Context.toBits(UnpackedFieldAlign), FieldPacked, D);
  1432. if (InsertExtraPadding) {
  1433. CharUnits ASanAlignment = CharUnits::fromQuantity(8);
  1434. CharUnits ExtraSizeForAsan = ASanAlignment;
  1435. if (FieldSize % ASanAlignment)
  1436. ExtraSizeForAsan +=
  1437. ASanAlignment - CharUnits::fromQuantity(FieldSize % ASanAlignment);
  1438. FieldSize += ExtraSizeForAsan;
  1439. }
  1440. // Reserve space for this field.
  1441. uint64_t FieldSizeInBits = Context.toBits(FieldSize);
  1442. if (IsUnion)
  1443. setDataSize(std::max(getDataSizeInBits(), FieldSizeInBits));
  1444. else
  1445. setDataSize(FieldOffset + FieldSize);
  1446. // Update the size.
  1447. setSize(std::max(getSizeInBits(), getDataSizeInBits()));
  1448. // Remember max struct/class alignment.
  1449. UpdateAlignment(FieldAlign, UnpackedFieldAlign);
  1450. }
  1451. void RecordLayoutBuilder::FinishLayout(const NamedDecl *D) {
  1452. // In C++, records cannot be of size 0.
  1453. if (Context.getLangOpts().CPlusPlus && getSizeInBits() == 0) {
  1454. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
  1455. // Compatibility with gcc requires a class (pod or non-pod)
  1456. // which is not empty but of size 0; such as having fields of
  1457. // array of zero-length, remains of Size 0
  1458. if (RD->isEmpty())
  1459. setSize(CharUnits::One());
  1460. }
  1461. else
  1462. setSize(CharUnits::One());
  1463. }
  1464. // Finally, round the size of the record up to the alignment of the
  1465. // record itself.
  1466. uint64_t UnpaddedSize = getSizeInBits() - UnfilledBitsInLastUnit;
  1467. uint64_t UnpackedSizeInBits =
  1468. llvm::RoundUpToAlignment(getSizeInBits(),
  1469. Context.toBits(UnpackedAlignment));
  1470. CharUnits UnpackedSize = Context.toCharUnitsFromBits(UnpackedSizeInBits);
  1471. uint64_t RoundedSize
  1472. = llvm::RoundUpToAlignment(getSizeInBits(), Context.toBits(Alignment));
  1473. if (UseExternalLayout) {
  1474. // If we're inferring alignment, and the external size is smaller than
  1475. // our size after we've rounded up to alignment, conservatively set the
  1476. // alignment to 1.
  1477. if (InferAlignment && External.Size < RoundedSize) {
  1478. Alignment = CharUnits::One();
  1479. InferAlignment = false;
  1480. }
  1481. setSize(External.Size);
  1482. return;
  1483. }
  1484. // Set the size to the final size.
  1485. setSize(RoundedSize);
  1486. unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
  1487. if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
  1488. // Warn if padding was introduced to the struct/class/union.
  1489. if (getSizeInBits() > UnpaddedSize) {
  1490. unsigned PadSize = getSizeInBits() - UnpaddedSize;
  1491. bool InBits = true;
  1492. if (PadSize % CharBitNum == 0) {
  1493. PadSize = PadSize / CharBitNum;
  1494. InBits = false;
  1495. }
  1496. Diag(RD->getLocation(), diag::warn_padded_struct_size)
  1497. << Context.getTypeDeclType(RD)
  1498. << PadSize
  1499. << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1); // plural or not
  1500. }
  1501. // Warn if we packed it unnecessarily. If the alignment is 1 byte don't
  1502. // bother since there won't be alignment issues.
  1503. if (Packed && UnpackedAlignment > CharUnits::One() &&
  1504. getSize() == UnpackedSize)
  1505. Diag(D->getLocation(), diag::warn_unnecessary_packed)
  1506. << Context.getTypeDeclType(RD);
  1507. }
  1508. }
  1509. void RecordLayoutBuilder::UpdateAlignment(CharUnits NewAlignment,
  1510. CharUnits UnpackedNewAlignment) {
  1511. // The alignment is not modified when using 'mac68k' alignment or when
  1512. // we have an externally-supplied layout that also provides overall alignment.
  1513. if (IsMac68kAlign || (UseExternalLayout && !InferAlignment))
  1514. return;
  1515. if (NewAlignment > Alignment) {
  1516. assert(llvm::isPowerOf2_64(NewAlignment.getQuantity()) &&
  1517. "Alignment not a power of 2");
  1518. Alignment = NewAlignment;
  1519. }
  1520. if (UnpackedNewAlignment > UnpackedAlignment) {
  1521. assert(llvm::isPowerOf2_64(UnpackedNewAlignment.getQuantity()) &&
  1522. "Alignment not a power of 2");
  1523. UnpackedAlignment = UnpackedNewAlignment;
  1524. }
  1525. }
  1526. uint64_t
  1527. RecordLayoutBuilder::updateExternalFieldOffset(const FieldDecl *Field,
  1528. uint64_t ComputedOffset) {
  1529. uint64_t ExternalFieldOffset = External.getExternalFieldOffset(Field);
  1530. if (InferAlignment && ExternalFieldOffset < ComputedOffset) {
  1531. // The externally-supplied field offset is before the field offset we
  1532. // computed. Assume that the structure is packed.
  1533. Alignment = CharUnits::One();
  1534. InferAlignment = false;
  1535. }
  1536. // Use the externally-supplied field offset.
  1537. return ExternalFieldOffset;
  1538. }
  1539. /// \brief Get diagnostic %select index for tag kind for
  1540. /// field padding diagnostic message.
  1541. /// WARNING: Indexes apply to particular diagnostics only!
  1542. ///
  1543. /// \returns diagnostic %select index.
  1544. static unsigned getPaddingDiagFromTagKind(TagTypeKind Tag) {
  1545. switch (Tag) {
  1546. case TTK_Struct: return 0;
  1547. case TTK_Interface: return 1;
  1548. case TTK_Class: return 2;
  1549. default: llvm_unreachable("Invalid tag kind for field padding diagnostic!");
  1550. }
  1551. }
  1552. void RecordLayoutBuilder::CheckFieldPadding(uint64_t Offset,
  1553. uint64_t UnpaddedOffset,
  1554. uint64_t UnpackedOffset,
  1555. unsigned UnpackedAlign,
  1556. bool isPacked,
  1557. const FieldDecl *D) {
  1558. // We let objc ivars without warning, objc interfaces generally are not used
  1559. // for padding tricks.
  1560. if (isa<ObjCIvarDecl>(D))
  1561. return;
  1562. // Don't warn about structs created without a SourceLocation. This can
  1563. // be done by clients of the AST, such as codegen.
  1564. if (D->getLocation().isInvalid())
  1565. return;
  1566. unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
  1567. // Warn if padding was introduced to the struct/class.
  1568. if (!IsUnion && Offset > UnpaddedOffset) {
  1569. unsigned PadSize = Offset - UnpaddedOffset;
  1570. bool InBits = true;
  1571. if (PadSize % CharBitNum == 0) {
  1572. PadSize = PadSize / CharBitNum;
  1573. InBits = false;
  1574. }
  1575. if (D->getIdentifier())
  1576. Diag(D->getLocation(), diag::warn_padded_struct_field)
  1577. << getPaddingDiagFromTagKind(D->getParent()->getTagKind())
  1578. << Context.getTypeDeclType(D->getParent())
  1579. << PadSize
  1580. << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1) // plural or not
  1581. << D->getIdentifier();
  1582. else
  1583. Diag(D->getLocation(), diag::warn_padded_struct_anon_field)
  1584. << getPaddingDiagFromTagKind(D->getParent()->getTagKind())
  1585. << Context.getTypeDeclType(D->getParent())
  1586. << PadSize
  1587. << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1); // plural or not
  1588. }
  1589. // Warn if we packed it unnecessarily. If the alignment is 1 byte don't
  1590. // bother since there won't be alignment issues.
  1591. if (isPacked && UnpackedAlign > CharBitNum && Offset == UnpackedOffset)
  1592. Diag(D->getLocation(), diag::warn_unnecessary_packed)
  1593. << D->getIdentifier();
  1594. }
  1595. static const CXXMethodDecl *computeKeyFunction(ASTContext &Context,
  1596. const CXXRecordDecl *RD) {
  1597. // If a class isn't polymorphic it doesn't have a key function.
  1598. if (!RD->isPolymorphic())
  1599. return nullptr;
  1600. // A class that is not externally visible doesn't have a key function. (Or
  1601. // at least, there's no point to assigning a key function to such a class;
  1602. // this doesn't affect the ABI.)
  1603. if (!RD->isExternallyVisible())
  1604. return nullptr;
  1605. // Template instantiations don't have key functions per Itanium C++ ABI 5.2.6.
  1606. // Same behavior as GCC.
  1607. TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
  1608. if (TSK == TSK_ImplicitInstantiation ||
  1609. TSK == TSK_ExplicitInstantiationDeclaration ||
  1610. TSK == TSK_ExplicitInstantiationDefinition)
  1611. return nullptr;
  1612. bool allowInlineFunctions =
  1613. Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline();
  1614. for (const CXXMethodDecl *MD : RD->methods()) {
  1615. if (!MD->isVirtual())
  1616. continue;
  1617. if (MD->isPure())
  1618. continue;
  1619. // Ignore implicit member functions, they are always marked as inline, but
  1620. // they don't have a body until they're defined.
  1621. if (MD->isImplicit())
  1622. continue;
  1623. if (MD->isInlineSpecified())
  1624. continue;
  1625. if (MD->hasInlineBody())
  1626. continue;
  1627. // Ignore inline deleted or defaulted functions.
  1628. if (!MD->isUserProvided())
  1629. continue;
  1630. // In certain ABIs, ignore functions with out-of-line inline definitions.
  1631. if (!allowInlineFunctions) {
  1632. const FunctionDecl *Def;
  1633. if (MD->hasBody(Def) && Def->isInlineSpecified())
  1634. continue;
  1635. }
  1636. // If the key function is dllimport but the class isn't, then the class has
  1637. // no key function. The DLL that exports the key function won't export the
  1638. // vtable in this case.
  1639. if (MD->hasAttr<DLLImportAttr>() && !RD->hasAttr<DLLImportAttr>())
  1640. return nullptr;
  1641. // We found it.
  1642. return MD;
  1643. }
  1644. return nullptr;
  1645. }
  1646. DiagnosticBuilder
  1647. RecordLayoutBuilder::Diag(SourceLocation Loc, unsigned DiagID) {
  1648. return Context.getDiagnostics().Report(Loc, DiagID);
  1649. }
  1650. /// Does the target C++ ABI require us to skip over the tail-padding
  1651. /// of the given class (considering it as a base class) when allocating
  1652. /// objects?
  1653. static bool mustSkipTailPadding(TargetCXXABI ABI, const CXXRecordDecl *RD) {
  1654. switch (ABI.getTailPaddingUseRules()) {
  1655. case TargetCXXABI::AlwaysUseTailPadding:
  1656. return false;
  1657. case TargetCXXABI::UseTailPaddingUnlessPOD03:
  1658. // FIXME: To the extent that this is meant to cover the Itanium ABI
  1659. // rules, we should implement the restrictions about over-sized
  1660. // bitfields:
  1661. //
  1662. // http://mentorembedded.github.com/cxx-abi/abi.html#POD :
  1663. // In general, a type is considered a POD for the purposes of
  1664. // layout if it is a POD type (in the sense of ISO C++
  1665. // [basic.types]). However, a POD-struct or POD-union (in the
  1666. // sense of ISO C++ [class]) with a bitfield member whose
  1667. // declared width is wider than the declared type of the
  1668. // bitfield is not a POD for the purpose of layout. Similarly,
  1669. // an array type is not a POD for the purpose of layout if the
  1670. // element type of the array is not a POD for the purpose of
  1671. // layout.
  1672. //
  1673. // Where references to the ISO C++ are made in this paragraph,
  1674. // the Technical Corrigendum 1 version of the standard is
  1675. // intended.
  1676. return RD->isPOD();
  1677. case TargetCXXABI::UseTailPaddingUnlessPOD11:
  1678. // This is equivalent to RD->getTypeForDecl().isCXX11PODType(),
  1679. // but with a lot of abstraction penalty stripped off. This does
  1680. // assume that these properties are set correctly even in C++98
  1681. // mode; fortunately, that is true because we want to assign
  1682. // consistently semantics to the type-traits intrinsics (or at
  1683. // least as many of them as possible).
  1684. return RD->isTrivial() && RD->isStandardLayout();
  1685. }
  1686. llvm_unreachable("bad tail-padding use kind");
  1687. }
  1688. static bool isMsLayout(const RecordDecl* D) {
  1689. return D->getASTContext().getTargetInfo().getCXXABI().isMicrosoft();
  1690. }
  1691. // This section contains an implementation of struct layout that is, up to the
  1692. // included tests, compatible with cl.exe (2013). The layout produced is
  1693. // significantly different than those produced by the Itanium ABI. Here we note
  1694. // the most important differences.
  1695. //
  1696. // * The alignment of bitfields in unions is ignored when computing the
  1697. // alignment of the union.
  1698. // * The existence of zero-width bitfield that occurs after anything other than
  1699. // a non-zero length bitfield is ignored.
  1700. // * There is no explicit primary base for the purposes of layout. All bases
  1701. // with vfptrs are laid out first, followed by all bases without vfptrs.
  1702. // * The Itanium equivalent vtable pointers are split into a vfptr (virtual
  1703. // function pointer) and a vbptr (virtual base pointer). They can each be
  1704. // shared with a, non-virtual bases. These bases need not be the same. vfptrs
  1705. // always occur at offset 0. vbptrs can occur at an arbitrary offset and are
  1706. // placed after the lexiographically last non-virtual base. This placement
  1707. // is always before fields but can be in the middle of the non-virtual bases
  1708. // due to the two-pass layout scheme for non-virtual-bases.
  1709. // * Virtual bases sometimes require a 'vtordisp' field that is laid out before
  1710. // the virtual base and is used in conjunction with virtual overrides during
  1711. // construction and destruction. This is always a 4 byte value and is used as
  1712. // an alternative to constructor vtables.
  1713. // * vtordisps are allocated in a block of memory with size and alignment equal
  1714. // to the alignment of the completed structure (before applying __declspec(
  1715. // align())). The vtordisp always occur at the end of the allocation block,
  1716. // immediately prior to the virtual base.
  1717. // * vfptrs are injected after all bases and fields have been laid out. In
  1718. // order to guarantee proper alignment of all fields, the vfptr injection
  1719. // pushes all bases and fields back by the alignment imposed by those bases
  1720. // and fields. This can potentially add a significant amount of padding.
  1721. // vfptrs are always injected at offset 0.
  1722. // * vbptrs are injected after all bases and fields have been laid out. In
  1723. // order to guarantee proper alignment of all fields, the vfptr injection
  1724. // pushes all bases and fields back by the alignment imposed by those bases
  1725. // and fields. This can potentially add a significant amount of padding.
  1726. // vbptrs are injected immediately after the last non-virtual base as
  1727. // lexiographically ordered in the code. If this site isn't pointer aligned
  1728. // the vbptr is placed at the next properly aligned location. Enough padding
  1729. // is added to guarantee a fit.
  1730. // * The last zero sized non-virtual base can be placed at the end of the
  1731. // struct (potentially aliasing another object), or may alias with the first
  1732. // field, even if they are of the same type.
  1733. // * The last zero size virtual base may be placed at the end of the struct
  1734. // potentially aliasing another object.
  1735. // * The ABI attempts to avoid aliasing of zero sized bases by adding padding
  1736. // between bases or vbases with specific properties. The criteria for
  1737. // additional padding between two bases is that the first base is zero sized
  1738. // or ends with a zero sized subobject and the second base is zero sized or
  1739. // trails with a zero sized base or field (sharing of vfptrs can reorder the
  1740. // layout of the so the leading base is not always the first one declared).
  1741. // This rule does take into account fields that are not records, so padding
  1742. // will occur even if the last field is, e.g. an int. The padding added for
  1743. // bases is 1 byte. The padding added between vbases depends on the alignment
  1744. // of the object but is at least 4 bytes (in both 32 and 64 bit modes).
  1745. // * There is no concept of non-virtual alignment, non-virtual alignment and
  1746. // alignment are always identical.
  1747. // * There is a distinction between alignment and required alignment.
  1748. // __declspec(align) changes the required alignment of a struct. This
  1749. // alignment is _always_ obeyed, even in the presence of #pragma pack. A
  1750. // record inherits required alignment from all of its fields and bases.
  1751. // * __declspec(align) on bitfields has the effect of changing the bitfield's
  1752. // alignment instead of its required alignment. This is the only known way
  1753. // to make the alignment of a struct bigger than 8. Interestingly enough
  1754. // this alignment is also immune to the effects of #pragma pack and can be
  1755. // used to create structures with large alignment under #pragma pack.
  1756. // However, because it does not impact required alignment, such a structure,
  1757. // when used as a field or base, will not be aligned if #pragma pack is
  1758. // still active at the time of use.
  1759. //
  1760. // Known incompatibilities:
  1761. // * all: #pragma pack between fields in a record
  1762. // * 2010 and back: If the last field in a record is a bitfield, every object
  1763. // laid out after the record will have extra padding inserted before it. The
  1764. // extra padding will have size equal to the size of the storage class of the
  1765. // bitfield. 0 sized bitfields don't exhibit this behavior and the extra
  1766. // padding can be avoided by adding a 0 sized bitfield after the non-zero-
  1767. // sized bitfield.
  1768. // * 2012 and back: In 64-bit mode, if the alignment of a record is 16 or
  1769. // greater due to __declspec(align()) then a second layout phase occurs after
  1770. // The locations of the vf and vb pointers are known. This layout phase
  1771. // suffers from the "last field is a bitfield" bug in 2010 and results in
  1772. // _every_ field getting padding put in front of it, potentially including the
  1773. // vfptr, leaving the vfprt at a non-zero location which results in a fault if
  1774. // anything tries to read the vftbl. The second layout phase also treats
  1775. // bitfields as separate entities and gives them each storage rather than
  1776. // packing them. Additionally, because this phase appears to perform a
  1777. // (an unstable) sort on the members before laying them out and because merged
  1778. // bitfields have the same address, the bitfields end up in whatever order
  1779. // the sort left them in, a behavior we could never hope to replicate.
  1780. namespace {
  1781. struct MicrosoftRecordLayoutBuilder {
  1782. struct ElementInfo {
  1783. CharUnits Size;
  1784. CharUnits Alignment;
  1785. };
  1786. typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy;
  1787. MicrosoftRecordLayoutBuilder(const ASTContext &Context) : Context(Context) {}
  1788. private:
  1789. MicrosoftRecordLayoutBuilder(const MicrosoftRecordLayoutBuilder &) = delete;
  1790. void operator=(const MicrosoftRecordLayoutBuilder &) = delete;
  1791. public:
  1792. void layout(const RecordDecl *RD);
  1793. void cxxLayout(const CXXRecordDecl *RD);
  1794. /// \brief Initializes size and alignment and honors some flags.
  1795. void initializeLayout(const RecordDecl *RD);
  1796. /// \brief Initialized C++ layout, compute alignment and virtual alignment and
  1797. /// existence of vfptrs and vbptrs. Alignment is needed before the vfptr is
  1798. /// laid out.
  1799. void initializeCXXLayout(const CXXRecordDecl *RD);
  1800. void layoutNonVirtualBases(const CXXRecordDecl *RD);
  1801. void layoutNonVirtualBase(const CXXRecordDecl *BaseDecl,
  1802. const ASTRecordLayout &BaseLayout,
  1803. const ASTRecordLayout *&PreviousBaseLayout);
  1804. void injectVFPtr(const CXXRecordDecl *RD);
  1805. void injectVBPtr(const CXXRecordDecl *RD);
  1806. /// \brief Lays out the fields of the record. Also rounds size up to
  1807. /// alignment.
  1808. void layoutFields(const RecordDecl *RD);
  1809. void layoutField(const FieldDecl *FD);
  1810. void layoutBitField(const FieldDecl *FD);
  1811. /// \brief Lays out a single zero-width bit-field in the record and handles
  1812. /// special cases associated with zero-width bit-fields.
  1813. void layoutZeroWidthBitField(const FieldDecl *FD);
  1814. void layoutVirtualBases(const CXXRecordDecl *RD);
  1815. void finalizeLayout(const RecordDecl *RD);
  1816. /// \brief Gets the size and alignment of a base taking pragma pack and
  1817. /// __declspec(align) into account.
  1818. ElementInfo getAdjustedElementInfo(const ASTRecordLayout &Layout);
  1819. /// \brief Gets the size and alignment of a field taking pragma pack and
  1820. /// __declspec(align) into account. It also updates RequiredAlignment as a
  1821. /// side effect because it is most convenient to do so here.
  1822. ElementInfo getAdjustedElementInfo(const FieldDecl *FD);
  1823. /// \brief Places a field at an offset in CharUnits.
  1824. void placeFieldAtOffset(CharUnits FieldOffset) {
  1825. FieldOffsets.push_back(Context.toBits(FieldOffset));
  1826. }
  1827. /// \brief Places a bitfield at a bit offset.
  1828. void placeFieldAtBitOffset(uint64_t FieldOffset) {
  1829. FieldOffsets.push_back(FieldOffset);
  1830. }
  1831. /// \brief Compute the set of virtual bases for which vtordisps are required.
  1832. void computeVtorDispSet(
  1833. llvm::SmallPtrSetImpl<const CXXRecordDecl *> &HasVtorDispSet,
  1834. const CXXRecordDecl *RD) const;
  1835. const ASTContext &Context;
  1836. /// \brief The size of the record being laid out.
  1837. CharUnits Size;
  1838. /// \brief The non-virtual size of the record layout.
  1839. CharUnits NonVirtualSize;
  1840. /// \brief The data size of the record layout.
  1841. CharUnits DataSize;
  1842. /// \brief The current alignment of the record layout.
  1843. CharUnits Alignment;
  1844. /// \brief The maximum allowed field alignment. This is set by #pragma pack.
  1845. CharUnits MaxFieldAlignment;
  1846. /// \brief The alignment that this record must obey. This is imposed by
  1847. /// __declspec(align()) on the record itself or one of its fields or bases.
  1848. CharUnits RequiredAlignment;
  1849. /// \brief The size of the allocation of the currently active bitfield.
  1850. /// This value isn't meaningful unless LastFieldIsNonZeroWidthBitfield
  1851. /// is true.
  1852. CharUnits CurrentBitfieldSize;
  1853. /// \brief Offset to the virtual base table pointer (if one exists).
  1854. CharUnits VBPtrOffset;
  1855. /// \brief Minimum record size possible.
  1856. CharUnits MinEmptyStructSize;
  1857. /// \brief The size and alignment info of a pointer.
  1858. ElementInfo PointerInfo;
  1859. /// \brief The primary base class (if one exists).
  1860. const CXXRecordDecl *PrimaryBase;
  1861. /// \brief The class we share our vb-pointer with.
  1862. const CXXRecordDecl *SharedVBPtrBase;
  1863. /// \brief The collection of field offsets.
  1864. SmallVector<uint64_t, 16> FieldOffsets;
  1865. /// \brief Base classes and their offsets in the record.
  1866. BaseOffsetsMapTy Bases;
  1867. /// \brief virtual base classes and their offsets in the record.
  1868. ASTRecordLayout::VBaseOffsetsMapTy VBases;
  1869. /// \brief The number of remaining bits in our last bitfield allocation.
  1870. /// This value isn't meaningful unless LastFieldIsNonZeroWidthBitfield is
  1871. /// true.
  1872. unsigned RemainingBitsInField;
  1873. bool IsUnion : 1;
  1874. /// \brief True if the last field laid out was a bitfield and was not 0
  1875. /// width.
  1876. bool LastFieldIsNonZeroWidthBitfield : 1;
  1877. /// \brief True if the class has its own vftable pointer.
  1878. bool HasOwnVFPtr : 1;
  1879. /// \brief True if the class has a vbtable pointer.
  1880. bool HasVBPtr : 1;
  1881. /// \brief True if the last sub-object within the type is zero sized or the
  1882. /// object itself is zero sized. This *does not* count members that are not
  1883. /// records. Only used for MS-ABI.
  1884. bool EndsWithZeroSizedObject : 1;
  1885. /// \brief True if this class is zero sized or first base is zero sized or
  1886. /// has this property. Only used for MS-ABI.
  1887. bool LeadsWithZeroSizedBase : 1;
  1888. /// \brief True if the external AST source provided a layout for this record.
  1889. bool UseExternalLayout : 1;
  1890. /// \brief The layout provided by the external AST source. Only active if
  1891. /// UseExternalLayout is true.
  1892. ExternalLayout External;
  1893. };
  1894. } // namespace
  1895. MicrosoftRecordLayoutBuilder::ElementInfo
  1896. MicrosoftRecordLayoutBuilder::getAdjustedElementInfo(
  1897. const ASTRecordLayout &Layout) {
  1898. ElementInfo Info;
  1899. Info.Alignment = Layout.getAlignment();
  1900. // Respect pragma pack.
  1901. if (!MaxFieldAlignment.isZero())
  1902. Info.Alignment = std::min(Info.Alignment, MaxFieldAlignment);
  1903. // Track zero-sized subobjects here where it's already available.
  1904. EndsWithZeroSizedObject = Layout.hasZeroSizedSubObject();
  1905. // Respect required alignment, this is necessary because we may have adjusted
  1906. // the alignment in the case of pragam pack. Note that the required alignment
  1907. // doesn't actually apply to the struct alignment at this point.
  1908. Alignment = std::max(Alignment, Info.Alignment);
  1909. RequiredAlignment = std::max(RequiredAlignment, Layout.getRequiredAlignment());
  1910. Info.Alignment = std::max(Info.Alignment, Layout.getRequiredAlignment());
  1911. Info.Size = Layout.getNonVirtualSize();
  1912. return Info;
  1913. }
  1914. MicrosoftRecordLayoutBuilder::ElementInfo
  1915. MicrosoftRecordLayoutBuilder::getAdjustedElementInfo(
  1916. const FieldDecl *FD) {
  1917. // Get the alignment of the field type's natural alignment, ignore any
  1918. // alignment attributes.
  1919. ElementInfo Info;
  1920. std::tie(Info.Size, Info.Alignment) =
  1921. Context.getTypeInfoInChars(FD->getType()->getUnqualifiedDesugaredType());
  1922. // Respect align attributes on the field.
  1923. CharUnits FieldRequiredAlignment =
  1924. Context.toCharUnitsFromBits(FD->getMaxAlignment());
  1925. // Respect align attributes on the type.
  1926. if (Context.isAlignmentRequired(FD->getType()))
  1927. FieldRequiredAlignment = std::max(
  1928. Context.getTypeAlignInChars(FD->getType()), FieldRequiredAlignment);
  1929. // Respect attributes applied to subobjects of the field.
  1930. if (FD->isBitField())
  1931. // For some reason __declspec align impacts alignment rather than required
  1932. // alignment when it is applied to bitfields.
  1933. Info.Alignment = std::max(Info.Alignment, FieldRequiredAlignment);
  1934. else {
  1935. if (auto RT =
  1936. FD->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
  1937. auto const &Layout = Context.getASTRecordLayout(RT->getDecl());
  1938. EndsWithZeroSizedObject = Layout.hasZeroSizedSubObject();
  1939. FieldRequiredAlignment = std::max(FieldRequiredAlignment,
  1940. Layout.getRequiredAlignment());
  1941. }
  1942. // Capture required alignment as a side-effect.
  1943. RequiredAlignment = std::max(RequiredAlignment, FieldRequiredAlignment);
  1944. }
  1945. // Respect pragma pack, attribute pack and declspec align
  1946. if (!MaxFieldAlignment.isZero())
  1947. Info.Alignment = std::min(Info.Alignment, MaxFieldAlignment);
  1948. if (FD->hasAttr<PackedAttr>())
  1949. Info.Alignment = CharUnits::One();
  1950. Info.Alignment = std::max(Info.Alignment, FieldRequiredAlignment);
  1951. return Info;
  1952. }
  1953. void MicrosoftRecordLayoutBuilder::layout(const RecordDecl *RD) {
  1954. // For C record layout, zero-sized records always have size 4.
  1955. MinEmptyStructSize = CharUnits::fromQuantity(4);
  1956. initializeLayout(RD);
  1957. layoutFields(RD);
  1958. DataSize = Size = Size.RoundUpToAlignment(Alignment);
  1959. RequiredAlignment = std::max(
  1960. RequiredAlignment, Context.toCharUnitsFromBits(RD->getMaxAlignment()));
  1961. finalizeLayout(RD);
  1962. }
  1963. void MicrosoftRecordLayoutBuilder::cxxLayout(const CXXRecordDecl *RD) {
  1964. // HLSL Change Begins
  1965. if (Context.getLangOpts().HLSL) {
  1966. MinEmptyStructSize = CharUnits::fromQuantity(0);
  1967. }
  1968. else { // HLSL Change Ends
  1969. // The C++ standard says that empty structs have size 1.
  1970. MinEmptyStructSize = CharUnits::One();
  1971. } // HLSL Change
  1972. initializeLayout(RD);
  1973. initializeCXXLayout(RD);
  1974. layoutNonVirtualBases(RD);
  1975. layoutFields(RD);
  1976. injectVBPtr(RD);
  1977. injectVFPtr(RD);
  1978. if (HasOwnVFPtr || (HasVBPtr && !SharedVBPtrBase))
  1979. Alignment = std::max(Alignment, PointerInfo.Alignment);
  1980. auto RoundingAlignment = Alignment;
  1981. if (!MaxFieldAlignment.isZero())
  1982. RoundingAlignment = std::min(RoundingAlignment, MaxFieldAlignment);
  1983. NonVirtualSize = Size = Size.RoundUpToAlignment(RoundingAlignment);
  1984. RequiredAlignment = std::max(
  1985. RequiredAlignment, Context.toCharUnitsFromBits(RD->getMaxAlignment()));
  1986. layoutVirtualBases(RD);
  1987. finalizeLayout(RD);
  1988. }
  1989. void MicrosoftRecordLayoutBuilder::initializeLayout(const RecordDecl *RD) {
  1990. IsUnion = RD->isUnion();
  1991. Size = CharUnits::Zero();
  1992. Alignment = CharUnits::One();
  1993. // In 64-bit mode we always perform an alignment step after laying out vbases.
  1994. // In 32-bit mode we do not. The check to see if we need to perform alignment
  1995. // checks the RequiredAlignment field and performs alignment if it isn't 0.
  1996. RequiredAlignment = Context.getTargetInfo().getTriple().isArch64Bit()
  1997. ? CharUnits::One()
  1998. : CharUnits::Zero();
  1999. // Compute the maximum field alignment.
  2000. MaxFieldAlignment = CharUnits::Zero();
  2001. // Honor the default struct packing maximum alignment flag.
  2002. if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct)
  2003. MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment);
  2004. // Honor the packing attribute. The MS-ABI ignores pragma pack if its larger
  2005. // than the pointer size.
  2006. if (const MaxFieldAlignmentAttr *MFAA = RD->getAttr<MaxFieldAlignmentAttr>()){
  2007. unsigned PackedAlignment = MFAA->getAlignment();
  2008. if (PackedAlignment <= Context.getTargetInfo().getPointerWidth(0))
  2009. MaxFieldAlignment = Context.toCharUnitsFromBits(PackedAlignment);
  2010. }
  2011. // Packed attribute forces max field alignment to be 1.
  2012. if (RD->hasAttr<PackedAttr>())
  2013. MaxFieldAlignment = CharUnits::One();
  2014. // Try to respect the external layout if present.
  2015. UseExternalLayout = false;
  2016. if (ExternalASTSource *Source = Context.getExternalSource())
  2017. UseExternalLayout = Source->layoutRecordType(
  2018. RD, External.Size, External.Align, External.FieldOffsets,
  2019. External.BaseOffsets, External.VirtualBaseOffsets);
  2020. }
  2021. void
  2022. MicrosoftRecordLayoutBuilder::initializeCXXLayout(const CXXRecordDecl *RD) {
  2023. EndsWithZeroSizedObject = false;
  2024. LeadsWithZeroSizedBase = false;
  2025. HasOwnVFPtr = false;
  2026. HasVBPtr = false;
  2027. PrimaryBase = nullptr;
  2028. SharedVBPtrBase = nullptr;
  2029. // Calculate pointer size and alignment. These are used for vfptr and vbprt
  2030. // injection.
  2031. PointerInfo.Size =
  2032. Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
  2033. PointerInfo.Alignment =
  2034. Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(0));
  2035. // Respect pragma pack.
  2036. if (!MaxFieldAlignment.isZero())
  2037. PointerInfo.Alignment = std::min(PointerInfo.Alignment, MaxFieldAlignment);
  2038. }
  2039. void
  2040. MicrosoftRecordLayoutBuilder::layoutNonVirtualBases(const CXXRecordDecl *RD) {
  2041. // The MS-ABI lays out all bases that contain leading vfptrs before it lays
  2042. // out any bases that do not contain vfptrs. We implement this as two passes
  2043. // over the bases. This approach guarantees that the primary base is laid out
  2044. // first. We use these passes to calculate some additional aggregated
  2045. // information about the bases, such as reqruied alignment and the presence of
  2046. // zero sized members.
  2047. const ASTRecordLayout *PreviousBaseLayout = nullptr;
  2048. // Iterate through the bases and lay out the non-virtual ones.
  2049. for (const CXXBaseSpecifier &Base : RD->bases()) {
  2050. const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
  2051. const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
  2052. // Mark and skip virtual bases.
  2053. if (Base.isVirtual()) {
  2054. HasVBPtr = true;
  2055. continue;
  2056. }
  2057. // Check fo a base to share a VBPtr with.
  2058. if (!SharedVBPtrBase && BaseLayout.hasVBPtr()) {
  2059. SharedVBPtrBase = BaseDecl;
  2060. HasVBPtr = true;
  2061. }
  2062. // Only lay out bases with extendable VFPtrs on the first pass.
  2063. if (!BaseLayout.hasExtendableVFPtr())
  2064. continue;
  2065. // If we don't have a primary base, this one qualifies.
  2066. if (!PrimaryBase) {
  2067. PrimaryBase = BaseDecl;
  2068. LeadsWithZeroSizedBase = BaseLayout.leadsWithZeroSizedBase();
  2069. }
  2070. // Lay out the base.
  2071. layoutNonVirtualBase(BaseDecl, BaseLayout, PreviousBaseLayout);
  2072. }
  2073. // Figure out if we need a fresh VFPtr for this class.
  2074. if (!PrimaryBase && RD->isDynamicClass())
  2075. for (CXXRecordDecl::method_iterator i = RD->method_begin(),
  2076. e = RD->method_end();
  2077. !HasOwnVFPtr && i != e; ++i)
  2078. HasOwnVFPtr = i->isVirtual() && i->size_overridden_methods() == 0;
  2079. // If we don't have a primary base then we have a leading object that could
  2080. // itself lead with a zero-sized object, something we track.
  2081. bool CheckLeadingLayout = !PrimaryBase;
  2082. // Iterate through the bases and lay out the non-virtual ones.
  2083. for (const CXXBaseSpecifier &Base : RD->bases()) {
  2084. if (Base.isVirtual())
  2085. continue;
  2086. const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
  2087. const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
  2088. // Only lay out bases without extendable VFPtrs on the second pass.
  2089. if (BaseLayout.hasExtendableVFPtr()) {
  2090. VBPtrOffset = Bases[BaseDecl] + BaseLayout.getNonVirtualSize();
  2091. continue;
  2092. }
  2093. // If this is the first layout, check to see if it leads with a zero sized
  2094. // object. If it does, so do we.
  2095. if (CheckLeadingLayout) {
  2096. CheckLeadingLayout = false;
  2097. LeadsWithZeroSizedBase = BaseLayout.leadsWithZeroSizedBase();
  2098. }
  2099. // Lay out the base.
  2100. layoutNonVirtualBase(BaseDecl, BaseLayout, PreviousBaseLayout);
  2101. VBPtrOffset = Bases[BaseDecl] + BaseLayout.getNonVirtualSize();
  2102. }
  2103. // Set our VBPtroffset if we know it at this point.
  2104. if (!HasVBPtr)
  2105. VBPtrOffset = CharUnits::fromQuantity(-1);
  2106. else if (SharedVBPtrBase) {
  2107. const ASTRecordLayout &Layout = Context.getASTRecordLayout(SharedVBPtrBase);
  2108. VBPtrOffset = Bases[SharedVBPtrBase] + Layout.getVBPtrOffset();
  2109. }
  2110. }
  2111. void MicrosoftRecordLayoutBuilder::layoutNonVirtualBase(
  2112. const CXXRecordDecl *BaseDecl,
  2113. const ASTRecordLayout &BaseLayout,
  2114. const ASTRecordLayout *&PreviousBaseLayout) {
  2115. // Insert padding between two bases if the left first one is zero sized or
  2116. // contains a zero sized subobject and the right is zero sized or one leads
  2117. // with a zero sized base.
  2118. if (PreviousBaseLayout && PreviousBaseLayout->hasZeroSizedSubObject() &&
  2119. BaseLayout.leadsWithZeroSizedBase())
  2120. Size++;
  2121. ElementInfo Info = getAdjustedElementInfo(BaseLayout);
  2122. CharUnits BaseOffset;
  2123. // Respect the external AST source base offset, if present.
  2124. bool FoundBase = false;
  2125. if (UseExternalLayout) {
  2126. FoundBase = External.getExternalNVBaseOffset(BaseDecl, BaseOffset);
  2127. if (FoundBase)
  2128. assert(BaseOffset >= Size && "base offset already allocated");
  2129. }
  2130. if (!FoundBase)
  2131. BaseOffset = Size.RoundUpToAlignment(Info.Alignment);
  2132. Bases.insert(std::make_pair(BaseDecl, BaseOffset));
  2133. Size = BaseOffset + BaseLayout.getNonVirtualSize();
  2134. PreviousBaseLayout = &BaseLayout;
  2135. }
  2136. void MicrosoftRecordLayoutBuilder::layoutFields(const RecordDecl *RD) {
  2137. LastFieldIsNonZeroWidthBitfield = false;
  2138. for (const FieldDecl *Field : RD->fields())
  2139. layoutField(Field);
  2140. }
  2141. void MicrosoftRecordLayoutBuilder::layoutField(const FieldDecl *FD) {
  2142. if (FD->isBitField()) {
  2143. layoutBitField(FD);
  2144. return;
  2145. }
  2146. LastFieldIsNonZeroWidthBitfield = false;
  2147. ElementInfo Info = getAdjustedElementInfo(FD);
  2148. Alignment = std::max(Alignment, Info.Alignment);
  2149. if (IsUnion) {
  2150. placeFieldAtOffset(CharUnits::Zero());
  2151. Size = std::max(Size, Info.Size);
  2152. } else {
  2153. CharUnits FieldOffset;
  2154. if (UseExternalLayout) {
  2155. FieldOffset =
  2156. Context.toCharUnitsFromBits(External.getExternalFieldOffset(FD));
  2157. assert(FieldOffset >= Size && "field offset already allocated");
  2158. } else {
  2159. FieldOffset = Size.RoundUpToAlignment(Info.Alignment);
  2160. }
  2161. placeFieldAtOffset(FieldOffset);
  2162. Size = FieldOffset + Info.Size;
  2163. }
  2164. }
  2165. void MicrosoftRecordLayoutBuilder::layoutBitField(const FieldDecl *FD) {
  2166. unsigned Width = FD->getBitWidthValue(Context);
  2167. if (Width == 0) {
  2168. layoutZeroWidthBitField(FD);
  2169. return;
  2170. }
  2171. ElementInfo Info = getAdjustedElementInfo(FD);
  2172. // Clamp the bitfield to a containable size for the sake of being able
  2173. // to lay them out. Sema will throw an error.
  2174. if (Width > Context.toBits(Info.Size))
  2175. Width = Context.toBits(Info.Size);
  2176. // Check to see if this bitfield fits into an existing allocation. Note:
  2177. // MSVC refuses to pack bitfields of formal types with different sizes
  2178. // into the same allocation.
  2179. if (!IsUnion && LastFieldIsNonZeroWidthBitfield &&
  2180. CurrentBitfieldSize == Info.Size && Width <= RemainingBitsInField) {
  2181. placeFieldAtBitOffset(Context.toBits(Size) - RemainingBitsInField);
  2182. RemainingBitsInField -= Width;
  2183. return;
  2184. }
  2185. LastFieldIsNonZeroWidthBitfield = true;
  2186. CurrentBitfieldSize = Info.Size;
  2187. if (IsUnion) {
  2188. placeFieldAtOffset(CharUnits::Zero());
  2189. Size = std::max(Size, Info.Size);
  2190. // TODO: Add a Sema warning that MS ignores bitfield alignment in unions.
  2191. } else {
  2192. // Allocate a new block of memory and place the bitfield in it.
  2193. CharUnits FieldOffset = Size.RoundUpToAlignment(Info.Alignment);
  2194. placeFieldAtOffset(FieldOffset);
  2195. Size = FieldOffset + Info.Size;
  2196. Alignment = std::max(Alignment, Info.Alignment);
  2197. RemainingBitsInField = Context.toBits(Info.Size) - Width;
  2198. }
  2199. }
  2200. void
  2201. MicrosoftRecordLayoutBuilder::layoutZeroWidthBitField(const FieldDecl *FD) {
  2202. // Zero-width bitfields are ignored unless they follow a non-zero-width
  2203. // bitfield.
  2204. if (!LastFieldIsNonZeroWidthBitfield) {
  2205. placeFieldAtOffset(IsUnion ? CharUnits::Zero() : Size);
  2206. // TODO: Add a Sema warning that MS ignores alignment for zero
  2207. // sized bitfields that occur after zero-size bitfields or non-bitfields.
  2208. return;
  2209. }
  2210. LastFieldIsNonZeroWidthBitfield = false;
  2211. ElementInfo Info = getAdjustedElementInfo(FD);
  2212. if (IsUnion) {
  2213. placeFieldAtOffset(CharUnits::Zero());
  2214. Size = std::max(Size, Info.Size);
  2215. // TODO: Add a Sema warning that MS ignores bitfield alignment in unions.
  2216. } else {
  2217. // Round up the current record size to the field's alignment boundary.
  2218. CharUnits FieldOffset = Size.RoundUpToAlignment(Info.Alignment);
  2219. placeFieldAtOffset(FieldOffset);
  2220. Size = FieldOffset;
  2221. Alignment = std::max(Alignment, Info.Alignment);
  2222. }
  2223. }
  2224. void MicrosoftRecordLayoutBuilder::injectVBPtr(const CXXRecordDecl *RD) {
  2225. if (!HasVBPtr || SharedVBPtrBase)
  2226. return;
  2227. // Inject the VBPointer at the injection site.
  2228. CharUnits InjectionSite = VBPtrOffset;
  2229. // But before we do, make sure it's properly aligned.
  2230. VBPtrOffset = VBPtrOffset.RoundUpToAlignment(PointerInfo.Alignment);
  2231. // Shift everything after the vbptr down, unless we're using an external
  2232. // layout.
  2233. if (UseExternalLayout)
  2234. return;
  2235. // Determine where the first field should be laid out after the vbptr.
  2236. CharUnits FieldStart = VBPtrOffset + PointerInfo.Size;
  2237. // Make sure that the amount we push the fields back by is a multiple of the
  2238. // alignment.
  2239. CharUnits Offset = (FieldStart - InjectionSite).RoundUpToAlignment(
  2240. std::max(RequiredAlignment, Alignment));
  2241. Size += Offset;
  2242. for (uint64_t &FieldOffset : FieldOffsets)
  2243. FieldOffset += Context.toBits(Offset);
  2244. for (BaseOffsetsMapTy::value_type &Base : Bases)
  2245. if (Base.second >= InjectionSite)
  2246. Base.second += Offset;
  2247. }
  2248. void MicrosoftRecordLayoutBuilder::injectVFPtr(const CXXRecordDecl *RD) {
  2249. if (!HasOwnVFPtr)
  2250. return;
  2251. // Make sure that the amount we push the struct back by is a multiple of the
  2252. // alignment.
  2253. CharUnits Offset = PointerInfo.Size.RoundUpToAlignment(
  2254. std::max(RequiredAlignment, Alignment));
  2255. // Increase the size of the object and push back all fields, the vbptr and all
  2256. // bases by the offset amount.
  2257. Size += Offset;
  2258. for (uint64_t &FieldOffset : FieldOffsets)
  2259. FieldOffset += Context.toBits(Offset);
  2260. if (HasVBPtr)
  2261. VBPtrOffset += Offset;
  2262. for (BaseOffsetsMapTy::value_type &Base : Bases)
  2263. Base.second += Offset;
  2264. }
  2265. void MicrosoftRecordLayoutBuilder::layoutVirtualBases(const CXXRecordDecl *RD) {
  2266. if (!HasVBPtr)
  2267. return;
  2268. // Vtordisps are always 4 bytes (even in 64-bit mode)
  2269. CharUnits VtorDispSize = CharUnits::fromQuantity(4);
  2270. CharUnits VtorDispAlignment = VtorDispSize;
  2271. // vtordisps respect pragma pack.
  2272. if (!MaxFieldAlignment.isZero())
  2273. VtorDispAlignment = std::min(VtorDispAlignment, MaxFieldAlignment);
  2274. // The alignment of the vtordisp is at least the required alignment of the
  2275. // entire record. This requirement may be present to support vtordisp
  2276. // injection.
  2277. for (const CXXBaseSpecifier &VBase : RD->vbases()) {
  2278. const CXXRecordDecl *BaseDecl = VBase.getType()->getAsCXXRecordDecl();
  2279. const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
  2280. RequiredAlignment =
  2281. std::max(RequiredAlignment, BaseLayout.getRequiredAlignment());
  2282. }
  2283. VtorDispAlignment = std::max(VtorDispAlignment, RequiredAlignment);
  2284. // Compute the vtordisp set.
  2285. llvm::SmallPtrSet<const CXXRecordDecl *, 2> HasVtorDispSet;
  2286. computeVtorDispSet(HasVtorDispSet, RD);
  2287. // Iterate through the virtual bases and lay them out.
  2288. const ASTRecordLayout *PreviousBaseLayout = nullptr;
  2289. for (const CXXBaseSpecifier &VBase : RD->vbases()) {
  2290. const CXXRecordDecl *BaseDecl = VBase.getType()->getAsCXXRecordDecl();
  2291. const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
  2292. bool HasVtordisp = HasVtorDispSet.count(BaseDecl) > 0;
  2293. // Insert padding between two bases if the left first one is zero sized or
  2294. // contains a zero sized subobject and the right is zero sized or one leads
  2295. // with a zero sized base. The padding between virtual bases is 4
  2296. // bytes (in both 32 and 64 bits modes) and always involves rounding up to
  2297. // the required alignment, we don't know why.
  2298. if ((PreviousBaseLayout && PreviousBaseLayout->hasZeroSizedSubObject() &&
  2299. BaseLayout.leadsWithZeroSizedBase()) || HasVtordisp) {
  2300. Size = Size.RoundUpToAlignment(VtorDispAlignment) + VtorDispSize;
  2301. Alignment = std::max(VtorDispAlignment, Alignment);
  2302. }
  2303. // Insert the virtual base.
  2304. ElementInfo Info = getAdjustedElementInfo(BaseLayout);
  2305. CharUnits BaseOffset;
  2306. // Respect the external AST source base offset, if present.
  2307. bool FoundBase = false;
  2308. if (UseExternalLayout) {
  2309. FoundBase = External.getExternalVBaseOffset(BaseDecl, BaseOffset);
  2310. if (FoundBase)
  2311. assert(BaseOffset >= Size && "base offset already allocated");
  2312. }
  2313. if (!FoundBase)
  2314. BaseOffset = Size.RoundUpToAlignment(Info.Alignment);
  2315. VBases.insert(std::make_pair(BaseDecl,
  2316. ASTRecordLayout::VBaseInfo(BaseOffset, HasVtordisp)));
  2317. Size = BaseOffset + BaseLayout.getNonVirtualSize();
  2318. PreviousBaseLayout = &BaseLayout;
  2319. }
  2320. }
  2321. void MicrosoftRecordLayoutBuilder::finalizeLayout(const RecordDecl *RD) {
  2322. // Respect required alignment. Note that in 32-bit mode Required alignment
  2323. // may be 0 and cause size not to be updated.
  2324. DataSize = Size;
  2325. if (!RequiredAlignment.isZero()) {
  2326. Alignment = std::max(Alignment, RequiredAlignment);
  2327. auto RoundingAlignment = Alignment;
  2328. if (!MaxFieldAlignment.isZero())
  2329. RoundingAlignment = std::min(RoundingAlignment, MaxFieldAlignment);
  2330. RoundingAlignment = std::max(RoundingAlignment, RequiredAlignment);
  2331. Size = Size.RoundUpToAlignment(RoundingAlignment);
  2332. }
  2333. if (Size.isZero()) {
  2334. EndsWithZeroSizedObject = true;
  2335. LeadsWithZeroSizedBase = true;
  2336. if (!Context.getLangOpts().HLSL) { // HLSL Change - allow empty structs to be zero sized
  2337. // Zero-sized structures have size equal to their alignment if a
  2338. // __declspec(align) came into play.
  2339. if (RequiredAlignment >= MinEmptyStructSize)
  2340. Size = Alignment;
  2341. else
  2342. Size = MinEmptyStructSize;
  2343. } // HLSL Change
  2344. }
  2345. if (UseExternalLayout) {
  2346. Size = Context.toCharUnitsFromBits(External.Size);
  2347. if (External.Align)
  2348. Alignment = Context.toCharUnitsFromBits(External.Align);
  2349. }
  2350. }
  2351. // Recursively walks the non-virtual bases of a class and determines if any of
  2352. // them are in the bases with overridden methods set.
  2353. static bool
  2354. RequiresVtordisp(const llvm::SmallPtrSetImpl<const CXXRecordDecl *> &
  2355. BasesWithOverriddenMethods,
  2356. const CXXRecordDecl *RD) {
  2357. if (BasesWithOverriddenMethods.count(RD))
  2358. return true;
  2359. // If any of a virtual bases non-virtual bases (recursively) requires a
  2360. // vtordisp than so does this virtual base.
  2361. for (const CXXBaseSpecifier &Base : RD->bases())
  2362. if (!Base.isVirtual() &&
  2363. RequiresVtordisp(BasesWithOverriddenMethods,
  2364. Base.getType()->getAsCXXRecordDecl()))
  2365. return true;
  2366. return false;
  2367. }
  2368. void MicrosoftRecordLayoutBuilder::computeVtorDispSet(
  2369. llvm::SmallPtrSetImpl<const CXXRecordDecl *> &HasVtordispSet,
  2370. const CXXRecordDecl *RD) const {
  2371. // /vd2 or #pragma vtordisp(2): Always use vtordisps for virtual bases with
  2372. // vftables.
  2373. if (RD->getMSVtorDispMode() == MSVtorDispAttr::ForVFTable) {
  2374. for (const CXXBaseSpecifier &Base : RD->vbases()) {
  2375. const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
  2376. const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
  2377. if (Layout.hasExtendableVFPtr())
  2378. HasVtordispSet.insert(BaseDecl);
  2379. }
  2380. return;
  2381. }
  2382. // If any of our bases need a vtordisp for this type, so do we. Check our
  2383. // direct bases for vtordisp requirements.
  2384. for (const CXXBaseSpecifier &Base : RD->bases()) {
  2385. const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
  2386. const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
  2387. for (const auto &bi : Layout.getVBaseOffsetsMap())
  2388. if (bi.second.hasVtorDisp())
  2389. HasVtordispSet.insert(bi.first);
  2390. }
  2391. // We don't introduce any additional vtordisps if either:
  2392. // * A user declared constructor or destructor aren't declared.
  2393. // * #pragma vtordisp(0) or the /vd0 flag are in use.
  2394. if ((!RD->hasUserDeclaredConstructor() && !RD->hasUserDeclaredDestructor()) ||
  2395. RD->getMSVtorDispMode() == MSVtorDispAttr::Never)
  2396. return;
  2397. // /vd1 or #pragma vtordisp(1): Try to guess based on whether we think it's
  2398. // possible for a partially constructed object with virtual base overrides to
  2399. // escape a non-trivial constructor.
  2400. assert(RD->getMSVtorDispMode() == MSVtorDispAttr::ForVBaseOverride);
  2401. // Compute a set of base classes which define methods we override. A virtual
  2402. // base in this set will require a vtordisp. A virtual base that transitively
  2403. // contains one of these bases as a non-virtual base will also require a
  2404. // vtordisp.
  2405. llvm::SmallPtrSet<const CXXMethodDecl *, 8> Work;
  2406. llvm::SmallPtrSet<const CXXRecordDecl *, 2> BasesWithOverriddenMethods;
  2407. // Seed the working set with our non-destructor, non-pure virtual methods.
  2408. for (const CXXMethodDecl *MD : RD->methods())
  2409. if (MD->isVirtual() && !isa<CXXDestructorDecl>(MD) && !MD->isPure())
  2410. Work.insert(MD);
  2411. while (!Work.empty()) {
  2412. const CXXMethodDecl *MD = *Work.begin();
  2413. CXXMethodDecl::method_iterator i = MD->begin_overridden_methods(),
  2414. e = MD->end_overridden_methods();
  2415. // If a virtual method has no-overrides it lives in its parent's vtable.
  2416. if (i == e)
  2417. BasesWithOverriddenMethods.insert(MD->getParent());
  2418. else
  2419. Work.insert(i, e);
  2420. // We've finished processing this element, remove it from the working set.
  2421. Work.erase(MD);
  2422. }
  2423. // For each of our virtual bases, check if it is in the set of overridden
  2424. // bases or if it transitively contains a non-virtual base that is.
  2425. for (const CXXBaseSpecifier &Base : RD->vbases()) {
  2426. const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
  2427. if (!HasVtordispSet.count(BaseDecl) &&
  2428. RequiresVtordisp(BasesWithOverriddenMethods, BaseDecl))
  2429. HasVtordispSet.insert(BaseDecl);
  2430. }
  2431. }
  2432. /// \brief Get or compute information about the layout of the specified record
  2433. /// (struct/union/class), which indicates its size and field position
  2434. /// information.
  2435. const ASTRecordLayout *
  2436. ASTContext::BuildMicrosoftASTRecordLayout(const RecordDecl *D) const {
  2437. MicrosoftRecordLayoutBuilder Builder(*this);
  2438. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
  2439. Builder.cxxLayout(RD);
  2440. return new (*this) ASTRecordLayout(
  2441. *this, Builder.Size, Builder.Alignment, Builder.RequiredAlignment,
  2442. Builder.HasOwnVFPtr,
  2443. Builder.HasOwnVFPtr || Builder.PrimaryBase,
  2444. Builder.VBPtrOffset, Builder.NonVirtualSize, Builder.FieldOffsets.data(),
  2445. Builder.FieldOffsets.size(), Builder.NonVirtualSize,
  2446. Builder.Alignment, CharUnits::Zero(), Builder.PrimaryBase,
  2447. false, Builder.SharedVBPtrBase,
  2448. Builder.EndsWithZeroSizedObject, Builder.LeadsWithZeroSizedBase,
  2449. Builder.Bases, Builder.VBases);
  2450. } else {
  2451. Builder.layout(D);
  2452. return new (*this) ASTRecordLayout(
  2453. *this, Builder.Size, Builder.Alignment, Builder.RequiredAlignment,
  2454. Builder.Size, Builder.FieldOffsets.data(), Builder.FieldOffsets.size());
  2455. }
  2456. }
  2457. /// getASTRecordLayout - Get or compute information about the layout of the
  2458. /// specified record (struct/union/class), which indicates its size and field
  2459. /// position information.
  2460. const ASTRecordLayout &
  2461. ASTContext::getASTRecordLayout(const RecordDecl *D) const {
  2462. // These asserts test different things. A record has a definition
  2463. // as soon as we begin to parse the definition. That definition is
  2464. // not a complete definition (which is what isDefinition() tests)
  2465. // until we *finish* parsing the definition.
  2466. if (D->hasExternalLexicalStorage() && !D->getDefinition())
  2467. getExternalSource()->CompleteType(const_cast<RecordDecl*>(D));
  2468. D = D->getDefinition();
  2469. assert(D && "Cannot get layout of forward declarations!");
  2470. assert(!D->isInvalidDecl() && "Cannot get layout of invalid decl!");
  2471. assert(D->isCompleteDefinition() && "Cannot layout type before complete!");
  2472. // Look up this layout, if already laid out, return what we have.
  2473. // Note that we can't save a reference to the entry because this function
  2474. // is recursive.
  2475. const ASTRecordLayout *Entry = ASTRecordLayouts[D];
  2476. if (Entry) return *Entry;
  2477. const ASTRecordLayout *NewEntry = nullptr;
  2478. if (isMsLayout(D)) {
  2479. NewEntry = BuildMicrosoftASTRecordLayout(D);
  2480. } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
  2481. EmptySubobjectMap EmptySubobjects(*this, RD);
  2482. RecordLayoutBuilder Builder(*this, &EmptySubobjects);
  2483. Builder.Layout(RD);
  2484. // In certain situations, we are allowed to lay out objects in the
  2485. // tail-padding of base classes. This is ABI-dependent.
  2486. // FIXME: this should be stored in the record layout.
  2487. bool skipTailPadding =
  2488. mustSkipTailPadding(getTargetInfo().getCXXABI(), cast<CXXRecordDecl>(D));
  2489. // FIXME: This should be done in FinalizeLayout.
  2490. CharUnits DataSize =
  2491. skipTailPadding ? Builder.getSize() : Builder.getDataSize();
  2492. CharUnits NonVirtualSize =
  2493. skipTailPadding ? DataSize : Builder.NonVirtualSize;
  2494. NewEntry =
  2495. new (*this) ASTRecordLayout(*this, Builder.getSize(),
  2496. Builder.Alignment,
  2497. /*RequiredAlignment : used by MS-ABI)*/
  2498. Builder.Alignment,
  2499. Builder.HasOwnVFPtr,
  2500. RD->isDynamicClass(),
  2501. CharUnits::fromQuantity(-1),
  2502. DataSize,
  2503. Builder.FieldOffsets.data(),
  2504. Builder.FieldOffsets.size(),
  2505. NonVirtualSize,
  2506. Builder.NonVirtualAlignment,
  2507. EmptySubobjects.SizeOfLargestEmptySubobject,
  2508. Builder.PrimaryBase,
  2509. Builder.PrimaryBaseIsVirtual,
  2510. nullptr, false, false,
  2511. Builder.Bases, Builder.VBases);
  2512. } else {
  2513. RecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/nullptr);
  2514. Builder.Layout(D);
  2515. NewEntry =
  2516. new (*this) ASTRecordLayout(*this, Builder.getSize(),
  2517. Builder.Alignment,
  2518. /*RequiredAlignment : used by MS-ABI)*/
  2519. Builder.Alignment,
  2520. Builder.getSize(),
  2521. Builder.FieldOffsets.data(),
  2522. Builder.FieldOffsets.size());
  2523. }
  2524. ASTRecordLayouts[D] = NewEntry;
  2525. if (getLangOpts().DumpRecordLayouts) {
  2526. llvm::outs() << "\n*** Dumping AST Record Layout\n";
  2527. DumpRecordLayout(D, llvm::outs(), getLangOpts().DumpRecordLayoutsSimple);
  2528. }
  2529. return *NewEntry;
  2530. }
  2531. const CXXMethodDecl *ASTContext::getCurrentKeyFunction(const CXXRecordDecl *RD) {
  2532. if (!getTargetInfo().getCXXABI().hasKeyFunctions())
  2533. return nullptr;
  2534. assert(RD->getDefinition() && "Cannot get key function for forward decl!");
  2535. RD = cast<CXXRecordDecl>(RD->getDefinition());
  2536. // Beware:
  2537. // 1) computing the key function might trigger deserialization, which might
  2538. // invalidate iterators into KeyFunctions
  2539. // 2) 'get' on the LazyDeclPtr might also trigger deserialization and
  2540. // invalidate the LazyDeclPtr within the map itself
  2541. LazyDeclPtr Entry = KeyFunctions[RD];
  2542. const Decl *Result =
  2543. Entry ? Entry.get(getExternalSource()) : computeKeyFunction(*this, RD);
  2544. // Store it back if it changed.
  2545. if (Entry.isOffset() || Entry.isValid() != bool(Result))
  2546. KeyFunctions[RD] = const_cast<Decl*>(Result);
  2547. return cast_or_null<CXXMethodDecl>(Result);
  2548. }
  2549. void ASTContext::setNonKeyFunction(const CXXMethodDecl *Method) {
  2550. assert(Method == Method->getFirstDecl() &&
  2551. "not working with method declaration from class definition");
  2552. // Look up the cache entry. Since we're working with the first
  2553. // declaration, its parent must be the class definition, which is
  2554. // the correct key for the KeyFunctions hash.
  2555. const auto &Map = KeyFunctions;
  2556. auto I = Map.find(Method->getParent());
  2557. // If it's not cached, there's nothing to do.
  2558. if (I == Map.end()) return;
  2559. // If it is cached, check whether it's the target method, and if so,
  2560. // remove it from the cache. Note, the call to 'get' might invalidate
  2561. // the iterator and the LazyDeclPtr object within the map.
  2562. LazyDeclPtr Ptr = I->second;
  2563. if (Ptr.get(getExternalSource()) == Method) {
  2564. // FIXME: remember that we did this for module / chained PCH state?
  2565. KeyFunctions.erase(Method->getParent());
  2566. }
  2567. }
  2568. static uint64_t getFieldOffset(const ASTContext &C, const FieldDecl *FD) {
  2569. const ASTRecordLayout &Layout = C.getASTRecordLayout(FD->getParent());
  2570. return Layout.getFieldOffset(FD->getFieldIndex());
  2571. }
  2572. uint64_t ASTContext::getFieldOffset(const ValueDecl *VD) const {
  2573. uint64_t OffsetInBits;
  2574. if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
  2575. OffsetInBits = ::getFieldOffset(*this, FD);
  2576. } else {
  2577. const IndirectFieldDecl *IFD = cast<IndirectFieldDecl>(VD);
  2578. OffsetInBits = 0;
  2579. for (const NamedDecl *ND : IFD->chain())
  2580. OffsetInBits += ::getFieldOffset(*this, cast<FieldDecl>(ND));
  2581. }
  2582. return OffsetInBits;
  2583. }
  2584. /// getObjCLayout - Get or compute information about the layout of the
  2585. /// given interface.
  2586. ///
  2587. /// \param Impl - If given, also include the layout of the interface's
  2588. /// implementation. This may differ by including synthesized ivars.
  2589. const ASTRecordLayout &
  2590. ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
  2591. const ObjCImplementationDecl *Impl) const {
  2592. // Retrieve the definition
  2593. if (D->hasExternalLexicalStorage() && !D->getDefinition())
  2594. getExternalSource()->CompleteType(const_cast<ObjCInterfaceDecl*>(D));
  2595. D = D->getDefinition();
  2596. assert(D && D->isThisDeclarationADefinition() && "Invalid interface decl!");
  2597. // Look up this layout, if already laid out, return what we have.
  2598. const ObjCContainerDecl *Key =
  2599. Impl ? (const ObjCContainerDecl*) Impl : (const ObjCContainerDecl*) D;
  2600. if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
  2601. return *Entry;
  2602. // Add in synthesized ivar count if laying out an implementation.
  2603. if (Impl) {
  2604. unsigned SynthCount = CountNonClassIvars(D);
  2605. // If there aren't any sythesized ivars then reuse the interface
  2606. // entry. Note we can't cache this because we simply free all
  2607. // entries later; however we shouldn't look up implementations
  2608. // frequently.
  2609. if (SynthCount == 0)
  2610. return getObjCLayout(D, nullptr);
  2611. }
  2612. RecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/nullptr);
  2613. Builder.Layout(D);
  2614. const ASTRecordLayout *NewEntry =
  2615. new (*this) ASTRecordLayout(*this, Builder.getSize(),
  2616. Builder.Alignment,
  2617. /*RequiredAlignment : used by MS-ABI)*/
  2618. Builder.Alignment,
  2619. Builder.getDataSize(),
  2620. Builder.FieldOffsets.data(),
  2621. Builder.FieldOffsets.size());
  2622. ObjCLayouts[Key] = NewEntry;
  2623. return *NewEntry;
  2624. }
  2625. static void PrintOffset(raw_ostream &OS,
  2626. CharUnits Offset, unsigned IndentLevel) {
  2627. OS << llvm::format("%4" PRId64 " | ", (int64_t)Offset.getQuantity());
  2628. OS.indent(IndentLevel * 2);
  2629. }
  2630. static void PrintIndentNoOffset(raw_ostream &OS, unsigned IndentLevel) {
  2631. OS << " | ";
  2632. OS.indent(IndentLevel * 2);
  2633. }
  2634. static void DumpCXXRecordLayout(raw_ostream &OS,
  2635. const CXXRecordDecl *RD, const ASTContext &C,
  2636. CharUnits Offset,
  2637. unsigned IndentLevel,
  2638. const char* Description,
  2639. bool IncludeVirtualBases) {
  2640. const ASTRecordLayout &Layout = C.getASTRecordLayout(RD);
  2641. PrintOffset(OS, Offset, IndentLevel);
  2642. OS << C.getTypeDeclType(const_cast<CXXRecordDecl *>(RD)).getAsString();
  2643. if (Description)
  2644. OS << ' ' << Description;
  2645. if (RD->isEmpty())
  2646. OS << " (empty)";
  2647. OS << '\n';
  2648. IndentLevel++;
  2649. const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
  2650. bool HasOwnVFPtr = Layout.hasOwnVFPtr();
  2651. bool HasOwnVBPtr = Layout.hasOwnVBPtr();
  2652. // Vtable pointer.
  2653. if (RD->isDynamicClass() && !PrimaryBase && !isMsLayout(RD)) {
  2654. PrintOffset(OS, Offset, IndentLevel);
  2655. OS << '(' << *RD << " vtable pointer)\n";
  2656. } else if (HasOwnVFPtr) {
  2657. PrintOffset(OS, Offset, IndentLevel);
  2658. // vfptr (for Microsoft C++ ABI)
  2659. OS << '(' << *RD << " vftable pointer)\n";
  2660. }
  2661. // Collect nvbases.
  2662. SmallVector<const CXXRecordDecl *, 4> Bases;
  2663. for (const CXXBaseSpecifier &Base : RD->bases()) {
  2664. assert(!Base.getType()->isDependentType() &&
  2665. "Cannot layout class with dependent bases.");
  2666. if (!Base.isVirtual())
  2667. Bases.push_back(Base.getType()->getAsCXXRecordDecl());
  2668. }
  2669. // Sort nvbases by offset.
  2670. std::stable_sort(Bases.begin(), Bases.end(),
  2671. [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
  2672. return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
  2673. });
  2674. // Dump (non-virtual) bases
  2675. for (const CXXRecordDecl *Base : Bases) {
  2676. CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base);
  2677. DumpCXXRecordLayout(OS, Base, C, BaseOffset, IndentLevel,
  2678. Base == PrimaryBase ? "(primary base)" : "(base)",
  2679. /*IncludeVirtualBases=*/false);
  2680. }
  2681. // vbptr (for Microsoft C++ ABI)
  2682. if (HasOwnVBPtr) {
  2683. PrintOffset(OS, Offset + Layout.getVBPtrOffset(), IndentLevel);
  2684. OS << '(' << *RD << " vbtable pointer)\n";
  2685. }
  2686. // Dump fields.
  2687. uint64_t FieldNo = 0;
  2688. for (CXXRecordDecl::field_iterator I = RD->field_begin(),
  2689. E = RD->field_end(); I != E; ++I, ++FieldNo) {
  2690. const FieldDecl &Field = **I;
  2691. CharUnits FieldOffset = Offset +
  2692. C.toCharUnitsFromBits(Layout.getFieldOffset(FieldNo));
  2693. if (const CXXRecordDecl *D = Field.getType()->getAsCXXRecordDecl()) {
  2694. DumpCXXRecordLayout(OS, D, C, FieldOffset, IndentLevel,
  2695. Field.getName().data(),
  2696. /*IncludeVirtualBases=*/true);
  2697. continue;
  2698. }
  2699. PrintOffset(OS, FieldOffset, IndentLevel);
  2700. OS << Field.getType().getAsString() << ' ' << Field << '\n';
  2701. }
  2702. if (!IncludeVirtualBases)
  2703. return;
  2704. // Dump virtual bases.
  2705. const ASTRecordLayout::VBaseOffsetsMapTy &vtordisps =
  2706. Layout.getVBaseOffsetsMap();
  2707. for (const CXXBaseSpecifier &Base : RD->vbases()) {
  2708. assert(Base.isVirtual() && "Found non-virtual class!");
  2709. const CXXRecordDecl *VBase = Base.getType()->getAsCXXRecordDecl();
  2710. CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBase);
  2711. if (vtordisps.find(VBase)->second.hasVtorDisp()) {
  2712. PrintOffset(OS, VBaseOffset - CharUnits::fromQuantity(4), IndentLevel);
  2713. OS << "(vtordisp for vbase " << *VBase << ")\n";
  2714. }
  2715. DumpCXXRecordLayout(OS, VBase, C, VBaseOffset, IndentLevel,
  2716. VBase == PrimaryBase ?
  2717. "(primary virtual base)" : "(virtual base)",
  2718. /*IncludeVirtualBases=*/false);
  2719. }
  2720. PrintIndentNoOffset(OS, IndentLevel - 1);
  2721. OS << "[sizeof=" << Layout.getSize().getQuantity();
  2722. if (!isMsLayout(RD))
  2723. OS << ", dsize=" << Layout.getDataSize().getQuantity();
  2724. OS << ", align=" << Layout.getAlignment().getQuantity() << '\n';
  2725. PrintIndentNoOffset(OS, IndentLevel - 1);
  2726. OS << " nvsize=" << Layout.getNonVirtualSize().getQuantity();
  2727. OS << ", nvalign=" << Layout.getNonVirtualAlignment().getQuantity() << "]\n";
  2728. }
  2729. void ASTContext::DumpRecordLayout(const RecordDecl *RD,
  2730. raw_ostream &OS,
  2731. bool Simple) const {
  2732. const ASTRecordLayout &Info = getASTRecordLayout(RD);
  2733. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
  2734. if (!Simple)
  2735. return DumpCXXRecordLayout(OS, CXXRD, *this, CharUnits(), 0, nullptr,
  2736. /*IncludeVirtualBases=*/true);
  2737. OS << "Type: " << getTypeDeclType(RD).getAsString() << "\n";
  2738. if (!Simple) {
  2739. OS << "Record: ";
  2740. RD->dump();
  2741. }
  2742. OS << "\nLayout: ";
  2743. OS << "<ASTRecordLayout\n";
  2744. OS << " Size:" << toBits(Info.getSize()) << "\n";
  2745. if (!isMsLayout(RD))
  2746. OS << " DataSize:" << toBits(Info.getDataSize()) << "\n";
  2747. OS << " Alignment:" << toBits(Info.getAlignment()) << "\n";
  2748. OS << " FieldOffsets: [";
  2749. for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i) {
  2750. if (i) OS << ", ";
  2751. OS << Info.getFieldOffset(i);
  2752. }
  2753. OS << "]>\n";
  2754. }