DeclCXX.cpp 134 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492
  1. //===- DeclCXX.cpp - C++ Declaration AST Node Implementation --------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the C++ related Decl classes.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/AST/DeclCXX.h"
  13. #include "clang/AST/ASTContext.h"
  14. #include "clang/AST/ASTLambda.h"
  15. #include "clang/AST/ASTMutationListener.h"
  16. #include "clang/AST/ASTUnresolvedSet.h"
  17. #include "clang/AST/Attr.h"
  18. #include "clang/AST/CXXInheritance.h"
  19. #include "clang/AST/DeclBase.h"
  20. #include "clang/AST/DeclTemplate.h"
  21. #include "clang/AST/DeclarationName.h"
  22. #include "clang/AST/Expr.h"
  23. #include "clang/AST/ExprCXX.h"
  24. #include "clang/AST/LambdaCapture.h"
  25. #include "clang/AST/NestedNameSpecifier.h"
  26. #include "clang/AST/ODRHash.h"
  27. #include "clang/AST/Type.h"
  28. #include "clang/AST/TypeLoc.h"
  29. #include "clang/AST/UnresolvedSet.h"
  30. #include "clang/Basic/Diagnostic.h"
  31. #include "clang/Basic/IdentifierTable.h"
  32. #include "clang/Basic/LLVM.h"
  33. #include "clang/Basic/LangOptions.h"
  34. #include "clang/Basic/OperatorKinds.h"
  35. #include "clang/Basic/PartialDiagnostic.h"
  36. #include "clang/Basic/SourceLocation.h"
  37. #include "clang/Basic/Specifiers.h"
  38. #include "clang/Basic/TargetInfo.h"
  39. #include "llvm/ADT/SmallPtrSet.h"
  40. #include "llvm/ADT/SmallVector.h"
  41. #include "llvm/ADT/iterator_range.h"
  42. #include "llvm/Support/Casting.h"
  43. #include "llvm/Support/ErrorHandling.h"
  44. #include "llvm/Support/Format.h"
  45. #include "llvm/Support/raw_ostream.h"
  46. #include <algorithm>
  47. #include <cassert>
  48. #include <cstddef>
  49. #include <cstdint>
  50. using namespace clang;
  51. //===----------------------------------------------------------------------===//
  52. // Decl Allocation/Deallocation Method Implementations
  53. //===----------------------------------------------------------------------===//
  54. void AccessSpecDecl::anchor() {}
  55. AccessSpecDecl *AccessSpecDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  56. return new (C, ID) AccessSpecDecl(EmptyShell());
  57. }
  58. void LazyASTUnresolvedSet::getFromExternalSource(ASTContext &C) const {
  59. ExternalASTSource *Source = C.getExternalSource();
  60. assert(Impl.Decls.isLazy() && "getFromExternalSource for non-lazy set");
  61. assert(Source && "getFromExternalSource with no external source");
  62. for (ASTUnresolvedSet::iterator I = Impl.begin(); I != Impl.end(); ++I)
  63. I.setDecl(cast<NamedDecl>(Source->GetExternalDecl(
  64. reinterpret_cast<uintptr_t>(I.getDecl()) >> 2)));
  65. Impl.Decls.setLazy(false);
  66. }
  67. CXXRecordDecl::DefinitionData::DefinitionData(CXXRecordDecl *D)
  68. : UserDeclaredConstructor(false), UserDeclaredSpecialMembers(0),
  69. Aggregate(true), PlainOldData(true), Empty(true), Polymorphic(false),
  70. Abstract(false), IsStandardLayout(true), IsCXX11StandardLayout(true),
  71. HasBasesWithFields(false), HasBasesWithNonStaticDataMembers(false),
  72. HasPrivateFields(false), HasProtectedFields(false),
  73. HasPublicFields(false), HasMutableFields(false), HasVariantMembers(false),
  74. HasOnlyCMembers(true), HasInitMethod(false), HasInClassInitializer(false),
  75. HasUninitializedReferenceMember(false), HasUninitializedFields(false),
  76. HasInheritedConstructor(false), HasInheritedDefaultConstructor(false),
  77. HasInheritedAssignment(false),
  78. NeedOverloadResolutionForCopyConstructor(false),
  79. NeedOverloadResolutionForMoveConstructor(false),
  80. NeedOverloadResolutionForCopyAssignment(false),
  81. NeedOverloadResolutionForMoveAssignment(false),
  82. NeedOverloadResolutionForDestructor(false),
  83. DefaultedCopyConstructorIsDeleted(false),
  84. DefaultedMoveConstructorIsDeleted(false),
  85. DefaultedCopyAssignmentIsDeleted(false),
  86. DefaultedMoveAssignmentIsDeleted(false),
  87. DefaultedDestructorIsDeleted(false), HasTrivialSpecialMembers(SMF_All),
  88. HasTrivialSpecialMembersForCall(SMF_All),
  89. DeclaredNonTrivialSpecialMembers(0),
  90. DeclaredNonTrivialSpecialMembersForCall(0), HasIrrelevantDestructor(true),
  91. HasConstexprNonCopyMoveConstructor(false),
  92. HasDefaultedDefaultConstructor(false),
  93. DefaultedDefaultConstructorIsConstexpr(true),
  94. HasConstexprDefaultConstructor(false),
  95. DefaultedDestructorIsConstexpr(true),
  96. HasNonLiteralTypeFieldsOrBases(false), StructuralIfLiteral(true),
  97. UserProvidedDefaultConstructor(false), DeclaredSpecialMembers(0),
  98. ImplicitCopyConstructorCanHaveConstParamForVBase(true),
  99. ImplicitCopyConstructorCanHaveConstParamForNonVBase(true),
  100. ImplicitCopyAssignmentHasConstParam(true),
  101. HasDeclaredCopyConstructorWithConstParam(false),
  102. HasDeclaredCopyAssignmentWithConstParam(false),
  103. IsAnyDestructorNoReturn(false), IsLambda(false),
  104. IsParsingBaseSpecifiers(false), ComputedVisibleConversions(false),
  105. HasODRHash(false), Definition(D) {}
  106. CXXBaseSpecifier *CXXRecordDecl::DefinitionData::getBasesSlowCase() const {
  107. return Bases.get(Definition->getASTContext().getExternalSource());
  108. }
  109. CXXBaseSpecifier *CXXRecordDecl::DefinitionData::getVBasesSlowCase() const {
  110. return VBases.get(Definition->getASTContext().getExternalSource());
  111. }
  112. CXXRecordDecl::CXXRecordDecl(Kind K, TagKind TK, const ASTContext &C,
  113. DeclContext *DC, SourceLocation StartLoc,
  114. SourceLocation IdLoc, IdentifierInfo *Id,
  115. CXXRecordDecl *PrevDecl)
  116. : RecordDecl(K, TK, C, DC, StartLoc, IdLoc, Id, PrevDecl),
  117. DefinitionData(PrevDecl ? PrevDecl->DefinitionData
  118. : nullptr) {}
  119. CXXRecordDecl *CXXRecordDecl::Create(const ASTContext &C, TagKind TK,
  120. DeclContext *DC, SourceLocation StartLoc,
  121. SourceLocation IdLoc, IdentifierInfo *Id,
  122. CXXRecordDecl *PrevDecl,
  123. bool DelayTypeCreation) {
  124. auto *R = new (C, DC) CXXRecordDecl(CXXRecord, TK, C, DC, StartLoc, IdLoc, Id,
  125. PrevDecl);
  126. R->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
  127. // FIXME: DelayTypeCreation seems like such a hack
  128. if (!DelayTypeCreation)
  129. C.getTypeDeclType(R, PrevDecl);
  130. return R;
  131. }
  132. CXXRecordDecl *
  133. CXXRecordDecl::CreateLambda(const ASTContext &C, DeclContext *DC,
  134. TypeSourceInfo *Info, SourceLocation Loc,
  135. unsigned DependencyKind, bool IsGeneric,
  136. LambdaCaptureDefault CaptureDefault) {
  137. auto *R = new (C, DC) CXXRecordDecl(CXXRecord, TTK_Class, C, DC, Loc, Loc,
  138. nullptr, nullptr);
  139. R->setBeingDefined(true);
  140. R->DefinitionData = new (C) struct LambdaDefinitionData(
  141. R, Info, DependencyKind, IsGeneric, CaptureDefault);
  142. R->setMayHaveOutOfDateDef(false);
  143. R->setImplicit(true);
  144. C.getTypeDeclType(R, /*PrevDecl=*/nullptr);
  145. return R;
  146. }
  147. CXXRecordDecl *
  148. CXXRecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
  149. auto *R = new (C, ID) CXXRecordDecl(
  150. CXXRecord, TTK_Struct, C, nullptr, SourceLocation(), SourceLocation(),
  151. nullptr, nullptr);
  152. R->setMayHaveOutOfDateDef(false);
  153. return R;
  154. }
  155. /// Determine whether a class has a repeated base class. This is intended for
  156. /// use when determining if a class is standard-layout, so makes no attempt to
  157. /// handle virtual bases.
  158. static bool hasRepeatedBaseClass(const CXXRecordDecl *StartRD) {
  159. llvm::SmallPtrSet<const CXXRecordDecl*, 8> SeenBaseTypes;
  160. SmallVector<const CXXRecordDecl*, 8> WorkList = {StartRD};
  161. while (!WorkList.empty()) {
  162. const CXXRecordDecl *RD = WorkList.pop_back_val();
  163. if (RD->getTypeForDecl()->isDependentType())
  164. continue;
  165. for (const CXXBaseSpecifier &BaseSpec : RD->bases()) {
  166. if (const CXXRecordDecl *B = BaseSpec.getType()->getAsCXXRecordDecl()) {
  167. if (!SeenBaseTypes.insert(B).second)
  168. return true;
  169. WorkList.push_back(B);
  170. }
  171. }
  172. }
  173. return false;
  174. }
  175. void
  176. CXXRecordDecl::setBases(CXXBaseSpecifier const * const *Bases,
  177. unsigned NumBases) {
  178. ASTContext &C = getASTContext();
  179. if (!data().Bases.isOffset() && data().NumBases > 0)
  180. C.Deallocate(data().getBases());
  181. if (NumBases) {
  182. if (!C.getLangOpts().CPlusPlus17) {
  183. // C++ [dcl.init.aggr]p1:
  184. // An aggregate is [...] a class with [...] no base classes [...].
  185. data().Aggregate = false;
  186. }
  187. // C++ [class]p4:
  188. // A POD-struct is an aggregate class...
  189. data().PlainOldData = false;
  190. }
  191. // The set of seen virtual base types.
  192. llvm::SmallPtrSet<CanQualType, 8> SeenVBaseTypes;
  193. // The virtual bases of this class.
  194. SmallVector<const CXXBaseSpecifier *, 8> VBases;
  195. data().Bases = new(C) CXXBaseSpecifier [NumBases];
  196. data().NumBases = NumBases;
  197. for (unsigned i = 0; i < NumBases; ++i) {
  198. data().getBases()[i] = *Bases[i];
  199. // Keep track of inherited vbases for this base class.
  200. const CXXBaseSpecifier *Base = Bases[i];
  201. QualType BaseType = Base->getType();
  202. // Skip dependent types; we can't do any checking on them now.
  203. if (BaseType->isDependentType())
  204. continue;
  205. auto *BaseClassDecl =
  206. cast<CXXRecordDecl>(BaseType->castAs<RecordType>()->getDecl());
  207. // C++2a [class]p7:
  208. // A standard-layout class is a class that:
  209. // [...]
  210. // -- has all non-static data members and bit-fields in the class and
  211. // its base classes first declared in the same class
  212. if (BaseClassDecl->data().HasBasesWithFields ||
  213. !BaseClassDecl->field_empty()) {
  214. if (data().HasBasesWithFields)
  215. // Two bases have members or bit-fields: not standard-layout.
  216. data().IsStandardLayout = false;
  217. data().HasBasesWithFields = true;
  218. }
  219. // C++11 [class]p7:
  220. // A standard-layout class is a class that:
  221. // -- [...] has [...] at most one base class with non-static data
  222. // members
  223. if (BaseClassDecl->data().HasBasesWithNonStaticDataMembers ||
  224. BaseClassDecl->hasDirectFields()) {
  225. if (data().HasBasesWithNonStaticDataMembers)
  226. data().IsCXX11StandardLayout = false;
  227. data().HasBasesWithNonStaticDataMembers = true;
  228. }
  229. if (!BaseClassDecl->isEmpty()) {
  230. // C++14 [meta.unary.prop]p4:
  231. // T is a class type [...] with [...] no base class B for which
  232. // is_empty<B>::value is false.
  233. data().Empty = false;
  234. }
  235. // C++1z [dcl.init.agg]p1:
  236. // An aggregate is a class with [...] no private or protected base classes
  237. if (Base->getAccessSpecifier() != AS_public) {
  238. data().Aggregate = false;
  239. // C++20 [temp.param]p7:
  240. // A structural type is [...] a literal class type with [...] all base
  241. // classes [...] public
  242. data().StructuralIfLiteral = false;
  243. }
  244. // C++ [class.virtual]p1:
  245. // A class that declares or inherits a virtual function is called a
  246. // polymorphic class.
  247. if (BaseClassDecl->isPolymorphic()) {
  248. data().Polymorphic = true;
  249. // An aggregate is a class with [...] no virtual functions.
  250. data().Aggregate = false;
  251. }
  252. // C++0x [class]p7:
  253. // A standard-layout class is a class that: [...]
  254. // -- has no non-standard-layout base classes
  255. if (!BaseClassDecl->isStandardLayout())
  256. data().IsStandardLayout = false;
  257. if (!BaseClassDecl->isCXX11StandardLayout())
  258. data().IsCXX11StandardLayout = false;
  259. // Record if this base is the first non-literal field or base.
  260. if (!hasNonLiteralTypeFieldsOrBases() && !BaseType->isLiteralType(C))
  261. data().HasNonLiteralTypeFieldsOrBases = true;
  262. // Now go through all virtual bases of this base and add them.
  263. for (const auto &VBase : BaseClassDecl->vbases()) {
  264. // Add this base if it's not already in the list.
  265. if (SeenVBaseTypes.insert(C.getCanonicalType(VBase.getType())).second) {
  266. VBases.push_back(&VBase);
  267. // C++11 [class.copy]p8:
  268. // The implicitly-declared copy constructor for a class X will have
  269. // the form 'X::X(const X&)' if each [...] virtual base class B of X
  270. // has a copy constructor whose first parameter is of type
  271. // 'const B&' or 'const volatile B&' [...]
  272. if (CXXRecordDecl *VBaseDecl = VBase.getType()->getAsCXXRecordDecl())
  273. if (!VBaseDecl->hasCopyConstructorWithConstParam())
  274. data().ImplicitCopyConstructorCanHaveConstParamForVBase = false;
  275. // C++1z [dcl.init.agg]p1:
  276. // An aggregate is a class with [...] no virtual base classes
  277. data().Aggregate = false;
  278. }
  279. }
  280. if (Base->isVirtual()) {
  281. // Add this base if it's not already in the list.
  282. if (SeenVBaseTypes.insert(C.getCanonicalType(BaseType)).second)
  283. VBases.push_back(Base);
  284. // C++14 [meta.unary.prop] is_empty:
  285. // T is a class type, but not a union type, with ... no virtual base
  286. // classes
  287. data().Empty = false;
  288. // C++1z [dcl.init.agg]p1:
  289. // An aggregate is a class with [...] no virtual base classes
  290. data().Aggregate = false;
  291. // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
  292. // A [default constructor, copy/move constructor, or copy/move assignment
  293. // operator for a class X] is trivial [...] if:
  294. // -- class X has [...] no virtual base classes
  295. data().HasTrivialSpecialMembers &= SMF_Destructor;
  296. data().HasTrivialSpecialMembersForCall &= SMF_Destructor;
  297. // C++0x [class]p7:
  298. // A standard-layout class is a class that: [...]
  299. // -- has [...] no virtual base classes
  300. data().IsStandardLayout = false;
  301. data().IsCXX11StandardLayout = false;
  302. // C++20 [dcl.constexpr]p3:
  303. // In the definition of a constexpr function [...]
  304. // -- if the function is a constructor or destructor,
  305. // its class shall not have any virtual base classes
  306. data().DefaultedDefaultConstructorIsConstexpr = false;
  307. data().DefaultedDestructorIsConstexpr = false;
  308. // C++1z [class.copy]p8:
  309. // The implicitly-declared copy constructor for a class X will have
  310. // the form 'X::X(const X&)' if each potentially constructed subobject
  311. // has a copy constructor whose first parameter is of type
  312. // 'const B&' or 'const volatile B&' [...]
  313. if (!BaseClassDecl->hasCopyConstructorWithConstParam())
  314. data().ImplicitCopyConstructorCanHaveConstParamForVBase = false;
  315. } else {
  316. // C++ [class.ctor]p5:
  317. // A default constructor is trivial [...] if:
  318. // -- all the direct base classes of its class have trivial default
  319. // constructors.
  320. if (!BaseClassDecl->hasTrivialDefaultConstructor())
  321. data().HasTrivialSpecialMembers &= ~SMF_DefaultConstructor;
  322. // C++0x [class.copy]p13:
  323. // A copy/move constructor for class X is trivial if [...]
  324. // [...]
  325. // -- the constructor selected to copy/move each direct base class
  326. // subobject is trivial, and
  327. if (!BaseClassDecl->hasTrivialCopyConstructor())
  328. data().HasTrivialSpecialMembers &= ~SMF_CopyConstructor;
  329. if (!BaseClassDecl->hasTrivialCopyConstructorForCall())
  330. data().HasTrivialSpecialMembersForCall &= ~SMF_CopyConstructor;
  331. // If the base class doesn't have a simple move constructor, we'll eagerly
  332. // declare it and perform overload resolution to determine which function
  333. // it actually calls. If it does have a simple move constructor, this
  334. // check is correct.
  335. if (!BaseClassDecl->hasTrivialMoveConstructor())
  336. data().HasTrivialSpecialMembers &= ~SMF_MoveConstructor;
  337. if (!BaseClassDecl->hasTrivialMoveConstructorForCall())
  338. data().HasTrivialSpecialMembersForCall &= ~SMF_MoveConstructor;
  339. // C++0x [class.copy]p27:
  340. // A copy/move assignment operator for class X is trivial if [...]
  341. // [...]
  342. // -- the assignment operator selected to copy/move each direct base
  343. // class subobject is trivial, and
  344. if (!BaseClassDecl->hasTrivialCopyAssignment())
  345. data().HasTrivialSpecialMembers &= ~SMF_CopyAssignment;
  346. // If the base class doesn't have a simple move assignment, we'll eagerly
  347. // declare it and perform overload resolution to determine which function
  348. // it actually calls. If it does have a simple move assignment, this
  349. // check is correct.
  350. if (!BaseClassDecl->hasTrivialMoveAssignment())
  351. data().HasTrivialSpecialMembers &= ~SMF_MoveAssignment;
  352. // C++11 [class.ctor]p6:
  353. // If that user-written default constructor would satisfy the
  354. // requirements of a constexpr constructor, the implicitly-defined
  355. // default constructor is constexpr.
  356. if (!BaseClassDecl->hasConstexprDefaultConstructor())
  357. data().DefaultedDefaultConstructorIsConstexpr = false;
  358. // C++1z [class.copy]p8:
  359. // The implicitly-declared copy constructor for a class X will have
  360. // the form 'X::X(const X&)' if each potentially constructed subobject
  361. // has a copy constructor whose first parameter is of type
  362. // 'const B&' or 'const volatile B&' [...]
  363. if (!BaseClassDecl->hasCopyConstructorWithConstParam())
  364. data().ImplicitCopyConstructorCanHaveConstParamForNonVBase = false;
  365. }
  366. // C++ [class.ctor]p3:
  367. // A destructor is trivial if all the direct base classes of its class
  368. // have trivial destructors.
  369. if (!BaseClassDecl->hasTrivialDestructor())
  370. data().HasTrivialSpecialMembers &= ~SMF_Destructor;
  371. if (!BaseClassDecl->hasTrivialDestructorForCall())
  372. data().HasTrivialSpecialMembersForCall &= ~SMF_Destructor;
  373. if (!BaseClassDecl->hasIrrelevantDestructor())
  374. data().HasIrrelevantDestructor = false;
  375. if (BaseClassDecl->isAnyDestructorNoReturn())
  376. data().IsAnyDestructorNoReturn = true;
  377. // C++11 [class.copy]p18:
  378. // The implicitly-declared copy assignment operator for a class X will
  379. // have the form 'X& X::operator=(const X&)' if each direct base class B
  380. // of X has a copy assignment operator whose parameter is of type 'const
  381. // B&', 'const volatile B&', or 'B' [...]
  382. if (!BaseClassDecl->hasCopyAssignmentWithConstParam())
  383. data().ImplicitCopyAssignmentHasConstParam = false;
  384. // A class has an Objective-C object member if... or any of its bases
  385. // has an Objective-C object member.
  386. if (BaseClassDecl->hasObjectMember())
  387. setHasObjectMember(true);
  388. if (BaseClassDecl->hasVolatileMember())
  389. setHasVolatileMember(true);
  390. if (BaseClassDecl->getArgPassingRestrictions() ==
  391. RecordDecl::APK_CanNeverPassInRegs)
  392. setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
  393. // Keep track of the presence of mutable fields.
  394. if (BaseClassDecl->hasMutableFields())
  395. data().HasMutableFields = true;
  396. if (BaseClassDecl->hasUninitializedReferenceMember())
  397. data().HasUninitializedReferenceMember = true;
  398. if (!BaseClassDecl->allowConstDefaultInit())
  399. data().HasUninitializedFields = true;
  400. addedClassSubobject(BaseClassDecl);
  401. }
  402. // C++2a [class]p7:
  403. // A class S is a standard-layout class if it:
  404. // -- has at most one base class subobject of any given type
  405. //
  406. // Note that we only need to check this for classes with more than one base
  407. // class. If there's only one base class, and it's standard layout, then
  408. // we know there are no repeated base classes.
  409. if (data().IsStandardLayout && NumBases > 1 && hasRepeatedBaseClass(this))
  410. data().IsStandardLayout = false;
  411. if (VBases.empty()) {
  412. data().IsParsingBaseSpecifiers = false;
  413. return;
  414. }
  415. // Create base specifier for any direct or indirect virtual bases.
  416. data().VBases = new (C) CXXBaseSpecifier[VBases.size()];
  417. data().NumVBases = VBases.size();
  418. for (int I = 0, E = VBases.size(); I != E; ++I) {
  419. QualType Type = VBases[I]->getType();
  420. if (!Type->isDependentType())
  421. addedClassSubobject(Type->getAsCXXRecordDecl());
  422. data().getVBases()[I] = *VBases[I];
  423. }
  424. data().IsParsingBaseSpecifiers = false;
  425. }
  426. unsigned CXXRecordDecl::getODRHash() const {
  427. assert(hasDefinition() && "ODRHash only for records with definitions");
  428. // Previously calculated hash is stored in DefinitionData.
  429. if (DefinitionData->HasODRHash)
  430. return DefinitionData->ODRHash;
  431. // Only calculate hash on first call of getODRHash per record.
  432. ODRHash Hash;
  433. Hash.AddCXXRecordDecl(getDefinition());
  434. DefinitionData->HasODRHash = true;
  435. DefinitionData->ODRHash = Hash.CalculateHash();
  436. return DefinitionData->ODRHash;
  437. }
  438. void CXXRecordDecl::addedClassSubobject(CXXRecordDecl *Subobj) {
  439. // C++11 [class.copy]p11:
  440. // A defaulted copy/move constructor for a class X is defined as
  441. // deleted if X has:
  442. // -- a direct or virtual base class B that cannot be copied/moved [...]
  443. // -- a non-static data member of class type M (or array thereof)
  444. // that cannot be copied or moved [...]
  445. if (!Subobj->hasSimpleCopyConstructor())
  446. data().NeedOverloadResolutionForCopyConstructor = true;
  447. if (!Subobj->hasSimpleMoveConstructor())
  448. data().NeedOverloadResolutionForMoveConstructor = true;
  449. // C++11 [class.copy]p23:
  450. // A defaulted copy/move assignment operator for a class X is defined as
  451. // deleted if X has:
  452. // -- a direct or virtual base class B that cannot be copied/moved [...]
  453. // -- a non-static data member of class type M (or array thereof)
  454. // that cannot be copied or moved [...]
  455. if (!Subobj->hasSimpleCopyAssignment())
  456. data().NeedOverloadResolutionForCopyAssignment = true;
  457. if (!Subobj->hasSimpleMoveAssignment())
  458. data().NeedOverloadResolutionForMoveAssignment = true;
  459. // C++11 [class.ctor]p5, C++11 [class.copy]p11, C++11 [class.dtor]p5:
  460. // A defaulted [ctor or dtor] for a class X is defined as
  461. // deleted if X has:
  462. // -- any direct or virtual base class [...] has a type with a destructor
  463. // that is deleted or inaccessible from the defaulted [ctor or dtor].
  464. // -- any non-static data member has a type with a destructor
  465. // that is deleted or inaccessible from the defaulted [ctor or dtor].
  466. if (!Subobj->hasSimpleDestructor()) {
  467. data().NeedOverloadResolutionForCopyConstructor = true;
  468. data().NeedOverloadResolutionForMoveConstructor = true;
  469. data().NeedOverloadResolutionForDestructor = true;
  470. }
  471. // C++2a [dcl.constexpr]p4:
  472. // The definition of a constexpr destructor [shall] satisfy the
  473. // following requirement:
  474. // -- for every subobject of class type or (possibly multi-dimensional)
  475. // array thereof, that class type shall have a constexpr destructor
  476. if (!Subobj->hasConstexprDestructor())
  477. data().DefaultedDestructorIsConstexpr = false;
  478. // C++20 [temp.param]p7:
  479. // A structural type is [...] a literal class type [for which] the types
  480. // of all base classes and non-static data members are structural types or
  481. // (possibly multi-dimensional) array thereof
  482. if (!Subobj->data().StructuralIfLiteral)
  483. data().StructuralIfLiteral = false;
  484. }
  485. bool CXXRecordDecl::hasConstexprDestructor() const {
  486. auto *Dtor = getDestructor();
  487. return Dtor ? Dtor->isConstexpr() : defaultedDestructorIsConstexpr();
  488. }
  489. bool CXXRecordDecl::hasAnyDependentBases() const {
  490. if (!isDependentContext())
  491. return false;
  492. return !forallBases([](const CXXRecordDecl *) { return true; });
  493. }
  494. bool CXXRecordDecl::isTriviallyCopyable() const {
  495. // C++0x [class]p5:
  496. // A trivially copyable class is a class that:
  497. // -- has no non-trivial copy constructors,
  498. if (hasNonTrivialCopyConstructor()) return false;
  499. // -- has no non-trivial move constructors,
  500. if (hasNonTrivialMoveConstructor()) return false;
  501. // -- has no non-trivial copy assignment operators,
  502. if (hasNonTrivialCopyAssignment()) return false;
  503. // -- has no non-trivial move assignment operators, and
  504. if (hasNonTrivialMoveAssignment()) return false;
  505. // -- has a trivial destructor.
  506. if (!hasTrivialDestructor()) return false;
  507. return true;
  508. }
  509. void CXXRecordDecl::markedVirtualFunctionPure() {
  510. // C++ [class.abstract]p2:
  511. // A class is abstract if it has at least one pure virtual function.
  512. data().Abstract = true;
  513. }
  514. bool CXXRecordDecl::hasSubobjectAtOffsetZeroOfEmptyBaseType(
  515. ASTContext &Ctx, const CXXRecordDecl *XFirst) {
  516. if (!getNumBases())
  517. return false;
  518. llvm::SmallPtrSet<const CXXRecordDecl*, 8> Bases;
  519. llvm::SmallPtrSet<const CXXRecordDecl*, 8> M;
  520. SmallVector<const CXXRecordDecl*, 8> WorkList;
  521. // Visit a type that we have determined is an element of M(S).
  522. auto Visit = [&](const CXXRecordDecl *RD) -> bool {
  523. RD = RD->getCanonicalDecl();
  524. // C++2a [class]p8:
  525. // A class S is a standard-layout class if it [...] has no element of the
  526. // set M(S) of types as a base class.
  527. //
  528. // If we find a subobject of an empty type, it might also be a base class,
  529. // so we'll need to walk the base classes to check.
  530. if (!RD->data().HasBasesWithFields) {
  531. // Walk the bases the first time, stopping if we find the type. Build a
  532. // set of them so we don't need to walk them again.
  533. if (Bases.empty()) {
  534. bool RDIsBase = !forallBases([&](const CXXRecordDecl *Base) -> bool {
  535. Base = Base->getCanonicalDecl();
  536. if (RD == Base)
  537. return false;
  538. Bases.insert(Base);
  539. return true;
  540. });
  541. if (RDIsBase)
  542. return true;
  543. } else {
  544. if (Bases.count(RD))
  545. return true;
  546. }
  547. }
  548. if (M.insert(RD).second)
  549. WorkList.push_back(RD);
  550. return false;
  551. };
  552. if (Visit(XFirst))
  553. return true;
  554. while (!WorkList.empty()) {
  555. const CXXRecordDecl *X = WorkList.pop_back_val();
  556. // FIXME: We don't check the bases of X. That matches the standard, but
  557. // that sure looks like a wording bug.
  558. // -- If X is a non-union class type with a non-static data member
  559. // [recurse to each field] that is either of zero size or is the
  560. // first non-static data member of X
  561. // -- If X is a union type, [recurse to union members]
  562. bool IsFirstField = true;
  563. for (auto *FD : X->fields()) {
  564. // FIXME: Should we really care about the type of the first non-static
  565. // data member of a non-union if there are preceding unnamed bit-fields?
  566. if (FD->isUnnamedBitfield())
  567. continue;
  568. if (!IsFirstField && !FD->isZeroSize(Ctx))
  569. continue;
  570. // -- If X is n array type, [visit the element type]
  571. QualType T = Ctx.getBaseElementType(FD->getType());
  572. if (auto *RD = T->getAsCXXRecordDecl())
  573. if (Visit(RD))
  574. return true;
  575. if (!X->isUnion())
  576. IsFirstField = false;
  577. }
  578. }
  579. return false;
  580. }
  581. bool CXXRecordDecl::lambdaIsDefaultConstructibleAndAssignable() const {
  582. assert(isLambda() && "not a lambda");
  583. // C++2a [expr.prim.lambda.capture]p11:
  584. // The closure type associated with a lambda-expression has no default
  585. // constructor if the lambda-expression has a lambda-capture and a
  586. // defaulted default constructor otherwise. It has a deleted copy
  587. // assignment operator if the lambda-expression has a lambda-capture and
  588. // defaulted copy and move assignment operators otherwise.
  589. //
  590. // C++17 [expr.prim.lambda]p21:
  591. // The closure type associated with a lambda-expression has no default
  592. // constructor and a deleted copy assignment operator.
  593. if (getLambdaCaptureDefault() != LCD_None || capture_size() != 0)
  594. return false;
  595. return getASTContext().getLangOpts().CPlusPlus20;
  596. }
  597. void CXXRecordDecl::addedMember(Decl *D) {
  598. if (!D->isImplicit() &&
  599. !isa<FieldDecl>(D) &&
  600. !isa<IndirectFieldDecl>(D) &&
  601. (!isa<TagDecl>(D) || cast<TagDecl>(D)->getTagKind() == TTK_Class ||
  602. cast<TagDecl>(D)->getTagKind() == TTK_Interface))
  603. data().HasOnlyCMembers = false;
  604. // Ignore friends and invalid declarations.
  605. if (D->getFriendObjectKind() || D->isInvalidDecl())
  606. return;
  607. auto *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
  608. if (FunTmpl)
  609. D = FunTmpl->getTemplatedDecl();
  610. // FIXME: Pass NamedDecl* to addedMember?
  611. Decl *DUnderlying = D;
  612. if (auto *ND = dyn_cast<NamedDecl>(DUnderlying)) {
  613. DUnderlying = ND->getUnderlyingDecl();
  614. if (auto *UnderlyingFunTmpl = dyn_cast<FunctionTemplateDecl>(DUnderlying))
  615. DUnderlying = UnderlyingFunTmpl->getTemplatedDecl();
  616. }
  617. if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
  618. if (Method->isVirtual()) {
  619. // C++ [dcl.init.aggr]p1:
  620. // An aggregate is an array or a class with [...] no virtual functions.
  621. data().Aggregate = false;
  622. // C++ [class]p4:
  623. // A POD-struct is an aggregate class...
  624. data().PlainOldData = false;
  625. // C++14 [meta.unary.prop]p4:
  626. // T is a class type [...] with [...] no virtual member functions...
  627. data().Empty = false;
  628. // C++ [class.virtual]p1:
  629. // A class that declares or inherits a virtual function is called a
  630. // polymorphic class.
  631. data().Polymorphic = true;
  632. // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
  633. // A [default constructor, copy/move constructor, or copy/move
  634. // assignment operator for a class X] is trivial [...] if:
  635. // -- class X has no virtual functions [...]
  636. data().HasTrivialSpecialMembers &= SMF_Destructor;
  637. data().HasTrivialSpecialMembersForCall &= SMF_Destructor;
  638. // C++0x [class]p7:
  639. // A standard-layout class is a class that: [...]
  640. // -- has no virtual functions
  641. data().IsStandardLayout = false;
  642. data().IsCXX11StandardLayout = false;
  643. }
  644. }
  645. // Notify the listener if an implicit member was added after the definition
  646. // was completed.
  647. if (!isBeingDefined() && D->isImplicit())
  648. if (ASTMutationListener *L = getASTMutationListener())
  649. L->AddedCXXImplicitMember(data().Definition, D);
  650. // The kind of special member this declaration is, if any.
  651. unsigned SMKind = 0;
  652. // Handle constructors.
  653. if (const auto *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
  654. if (Constructor->isInheritingConstructor()) {
  655. // Ignore constructor shadow declarations. They are lazily created and
  656. // so shouldn't affect any properties of the class.
  657. } else {
  658. if (!Constructor->isImplicit()) {
  659. // Note that we have a user-declared constructor.
  660. data().UserDeclaredConstructor = true;
  661. const TargetInfo &TI = getASTContext().getTargetInfo();
  662. if ((!Constructor->isDeleted() && !Constructor->isDefaulted()) ||
  663. !TI.areDefaultedSMFStillPOD(getLangOpts())) {
  664. // C++ [class]p4:
  665. // A POD-struct is an aggregate class [...]
  666. // Since the POD bit is meant to be C++03 POD-ness, clear it even if
  667. // the type is technically an aggregate in C++0x since it wouldn't be
  668. // in 03.
  669. data().PlainOldData = false;
  670. }
  671. }
  672. if (Constructor->isDefaultConstructor()) {
  673. SMKind |= SMF_DefaultConstructor;
  674. if (Constructor->isUserProvided())
  675. data().UserProvidedDefaultConstructor = true;
  676. if (Constructor->isConstexpr())
  677. data().HasConstexprDefaultConstructor = true;
  678. if (Constructor->isDefaulted())
  679. data().HasDefaultedDefaultConstructor = true;
  680. }
  681. if (!FunTmpl) {
  682. unsigned Quals;
  683. if (Constructor->isCopyConstructor(Quals)) {
  684. SMKind |= SMF_CopyConstructor;
  685. if (Quals & Qualifiers::Const)
  686. data().HasDeclaredCopyConstructorWithConstParam = true;
  687. } else if (Constructor->isMoveConstructor())
  688. SMKind |= SMF_MoveConstructor;
  689. }
  690. // C++11 [dcl.init.aggr]p1: DR1518
  691. // An aggregate is an array or a class with no user-provided [or]
  692. // explicit [...] constructors
  693. // C++20 [dcl.init.aggr]p1:
  694. // An aggregate is an array or a class with no user-declared [...]
  695. // constructors
  696. if (getASTContext().getLangOpts().CPlusPlus20
  697. ? !Constructor->isImplicit()
  698. : (Constructor->isUserProvided() || Constructor->isExplicit()))
  699. data().Aggregate = false;
  700. }
  701. }
  702. // Handle constructors, including those inherited from base classes.
  703. if (const auto *Constructor = dyn_cast<CXXConstructorDecl>(DUnderlying)) {
  704. // Record if we see any constexpr constructors which are neither copy
  705. // nor move constructors.
  706. // C++1z [basic.types]p10:
  707. // [...] has at least one constexpr constructor or constructor template
  708. // (possibly inherited from a base class) that is not a copy or move
  709. // constructor [...]
  710. if (Constructor->isConstexpr() && !Constructor->isCopyOrMoveConstructor())
  711. data().HasConstexprNonCopyMoveConstructor = true;
  712. if (!isa<CXXConstructorDecl>(D) && Constructor->isDefaultConstructor())
  713. data().HasInheritedDefaultConstructor = true;
  714. }
  715. // Handle member functions.
  716. if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
  717. if (isa<CXXDestructorDecl>(D))
  718. SMKind |= SMF_Destructor;
  719. if (Method->isCopyAssignmentOperator()) {
  720. SMKind |= SMF_CopyAssignment;
  721. const auto *ParamTy =
  722. Method->getParamDecl(0)->getType()->getAs<ReferenceType>();
  723. if (!ParamTy || ParamTy->getPointeeType().isConstQualified())
  724. data().HasDeclaredCopyAssignmentWithConstParam = true;
  725. }
  726. if (Method->isMoveAssignmentOperator())
  727. SMKind |= SMF_MoveAssignment;
  728. // Keep the list of conversion functions up-to-date.
  729. if (auto *Conversion = dyn_cast<CXXConversionDecl>(D)) {
  730. // FIXME: We use the 'unsafe' accessor for the access specifier here,
  731. // because Sema may not have set it yet. That's really just a misdesign
  732. // in Sema. However, LLDB *will* have set the access specifier correctly,
  733. // and adds declarations after the class is technically completed,
  734. // so completeDefinition()'s overriding of the access specifiers doesn't
  735. // work.
  736. AccessSpecifier AS = Conversion->getAccessUnsafe();
  737. if (Conversion->getPrimaryTemplate()) {
  738. // We don't record specializations.
  739. } else {
  740. ASTContext &Ctx = getASTContext();
  741. ASTUnresolvedSet &Conversions = data().Conversions.get(Ctx);
  742. NamedDecl *Primary =
  743. FunTmpl ? cast<NamedDecl>(FunTmpl) : cast<NamedDecl>(Conversion);
  744. if (Primary->getPreviousDecl())
  745. Conversions.replace(cast<NamedDecl>(Primary->getPreviousDecl()),
  746. Primary, AS);
  747. else
  748. Conversions.addDecl(Ctx, Primary, AS);
  749. }
  750. }
  751. if (SMKind) {
  752. // If this is the first declaration of a special member, we no longer have
  753. // an implicit trivial special member.
  754. data().HasTrivialSpecialMembers &=
  755. data().DeclaredSpecialMembers | ~SMKind;
  756. data().HasTrivialSpecialMembersForCall &=
  757. data().DeclaredSpecialMembers | ~SMKind;
  758. // Note when we have declared a declared special member, and suppress the
  759. // implicit declaration of this special member.
  760. data().DeclaredSpecialMembers |= SMKind;
  761. if (!Method->isImplicit()) {
  762. data().UserDeclaredSpecialMembers |= SMKind;
  763. const TargetInfo &TI = getASTContext().getTargetInfo();
  764. if ((!Method->isDeleted() && !Method->isDefaulted() &&
  765. SMKind != SMF_MoveAssignment) ||
  766. !TI.areDefaultedSMFStillPOD(getLangOpts())) {
  767. // C++03 [class]p4:
  768. // A POD-struct is an aggregate class that has [...] no user-defined
  769. // copy assignment operator and no user-defined destructor.
  770. //
  771. // Since the POD bit is meant to be C++03 POD-ness, and in C++03,
  772. // aggregates could not have any constructors, clear it even for an
  773. // explicitly defaulted or deleted constructor.
  774. // type is technically an aggregate in C++0x since it wouldn't be in
  775. // 03.
  776. //
  777. // Also, a user-declared move assignment operator makes a class
  778. // non-POD. This is an extension in C++03.
  779. data().PlainOldData = false;
  780. }
  781. }
  782. // When instantiating a class, we delay updating the destructor and
  783. // triviality properties of the class until selecting a destructor and
  784. // computing the eligibility of its special member functions. This is
  785. // because there might be function constraints that we need to evaluate
  786. // and compare later in the instantiation.
  787. if (!Method->isIneligibleOrNotSelected()) {
  788. addedEligibleSpecialMemberFunction(Method, SMKind);
  789. }
  790. }
  791. return;
  792. }
  793. // Handle non-static data members.
  794. if (const auto *Field = dyn_cast<FieldDecl>(D)) {
  795. ASTContext &Context = getASTContext();
  796. // C++2a [class]p7:
  797. // A standard-layout class is a class that:
  798. // [...]
  799. // -- has all non-static data members and bit-fields in the class and
  800. // its base classes first declared in the same class
  801. if (data().HasBasesWithFields)
  802. data().IsStandardLayout = false;
  803. // C++ [class.bit]p2:
  804. // A declaration for a bit-field that omits the identifier declares an
  805. // unnamed bit-field. Unnamed bit-fields are not members and cannot be
  806. // initialized.
  807. if (Field->isUnnamedBitfield()) {
  808. // C++ [meta.unary.prop]p4: [LWG2358]
  809. // T is a class type [...] with [...] no unnamed bit-fields of non-zero
  810. // length
  811. if (data().Empty && !Field->isZeroLengthBitField(Context) &&
  812. Context.getLangOpts().getClangABICompat() >
  813. LangOptions::ClangABI::Ver6)
  814. data().Empty = false;
  815. return;
  816. }
  817. // C++11 [class]p7:
  818. // A standard-layout class is a class that:
  819. // -- either has no non-static data members in the most derived class
  820. // [...] or has no base classes with non-static data members
  821. if (data().HasBasesWithNonStaticDataMembers)
  822. data().IsCXX11StandardLayout = false;
  823. // C++ [dcl.init.aggr]p1:
  824. // An aggregate is an array or a class (clause 9) with [...] no
  825. // private or protected non-static data members (clause 11).
  826. //
  827. // A POD must be an aggregate.
  828. if (D->getAccess() == AS_private || D->getAccess() == AS_protected) {
  829. data().Aggregate = false;
  830. data().PlainOldData = false;
  831. // C++20 [temp.param]p7:
  832. // A structural type is [...] a literal class type [for which] all
  833. // non-static data members are public
  834. data().StructuralIfLiteral = false;
  835. }
  836. // Track whether this is the first field. We use this when checking
  837. // whether the class is standard-layout below.
  838. bool IsFirstField = !data().HasPrivateFields &&
  839. !data().HasProtectedFields && !data().HasPublicFields;
  840. // C++0x [class]p7:
  841. // A standard-layout class is a class that:
  842. // [...]
  843. // -- has the same access control for all non-static data members,
  844. switch (D->getAccess()) {
  845. case AS_private: data().HasPrivateFields = true; break;
  846. case AS_protected: data().HasProtectedFields = true; break;
  847. case AS_public: data().HasPublicFields = true; break;
  848. case AS_none: llvm_unreachable("Invalid access specifier");
  849. };
  850. if ((data().HasPrivateFields + data().HasProtectedFields +
  851. data().HasPublicFields) > 1) {
  852. data().IsStandardLayout = false;
  853. data().IsCXX11StandardLayout = false;
  854. }
  855. // Keep track of the presence of mutable fields.
  856. if (Field->isMutable()) {
  857. data().HasMutableFields = true;
  858. // C++20 [temp.param]p7:
  859. // A structural type is [...] a literal class type [for which] all
  860. // non-static data members are public
  861. data().StructuralIfLiteral = false;
  862. }
  863. // C++11 [class.union]p8, DR1460:
  864. // If X is a union, a non-static data member of X that is not an anonymous
  865. // union is a variant member of X.
  866. if (isUnion() && !Field->isAnonymousStructOrUnion())
  867. data().HasVariantMembers = true;
  868. // C++0x [class]p9:
  869. // A POD struct is a class that is both a trivial class and a
  870. // standard-layout class, and has no non-static data members of type
  871. // non-POD struct, non-POD union (or array of such types).
  872. //
  873. // Automatic Reference Counting: the presence of a member of Objective-C pointer type
  874. // that does not explicitly have no lifetime makes the class a non-POD.
  875. QualType T = Context.getBaseElementType(Field->getType());
  876. if (T->isObjCRetainableType() || T.isObjCGCStrong()) {
  877. if (T.hasNonTrivialObjCLifetime()) {
  878. // Objective-C Automatic Reference Counting:
  879. // If a class has a non-static data member of Objective-C pointer
  880. // type (or array thereof), it is a non-POD type and its
  881. // default constructor (if any), copy constructor, move constructor,
  882. // copy assignment operator, move assignment operator, and destructor are
  883. // non-trivial.
  884. setHasObjectMember(true);
  885. struct DefinitionData &Data = data();
  886. Data.PlainOldData = false;
  887. Data.HasTrivialSpecialMembers = 0;
  888. // __strong or __weak fields do not make special functions non-trivial
  889. // for the purpose of calls.
  890. Qualifiers::ObjCLifetime LT = T.getQualifiers().getObjCLifetime();
  891. if (LT != Qualifiers::OCL_Strong && LT != Qualifiers::OCL_Weak)
  892. data().HasTrivialSpecialMembersForCall = 0;
  893. // Structs with __weak fields should never be passed directly.
  894. if (LT == Qualifiers::OCL_Weak)
  895. setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
  896. Data.HasIrrelevantDestructor = false;
  897. if (isUnion()) {
  898. data().DefaultedCopyConstructorIsDeleted = true;
  899. data().DefaultedMoveConstructorIsDeleted = true;
  900. data().DefaultedCopyAssignmentIsDeleted = true;
  901. data().DefaultedMoveAssignmentIsDeleted = true;
  902. data().DefaultedDestructorIsDeleted = true;
  903. data().NeedOverloadResolutionForCopyConstructor = true;
  904. data().NeedOverloadResolutionForMoveConstructor = true;
  905. data().NeedOverloadResolutionForCopyAssignment = true;
  906. data().NeedOverloadResolutionForMoveAssignment = true;
  907. data().NeedOverloadResolutionForDestructor = true;
  908. }
  909. } else if (!Context.getLangOpts().ObjCAutoRefCount) {
  910. setHasObjectMember(true);
  911. }
  912. } else if (!T.isCXX98PODType(Context))
  913. data().PlainOldData = false;
  914. if (T->isReferenceType()) {
  915. if (!Field->hasInClassInitializer())
  916. data().HasUninitializedReferenceMember = true;
  917. // C++0x [class]p7:
  918. // A standard-layout class is a class that:
  919. // -- has no non-static data members of type [...] reference,
  920. data().IsStandardLayout = false;
  921. data().IsCXX11StandardLayout = false;
  922. // C++1z [class.copy.ctor]p10:
  923. // A defaulted copy constructor for a class X is defined as deleted if X has:
  924. // -- a non-static data member of rvalue reference type
  925. if (T->isRValueReferenceType())
  926. data().DefaultedCopyConstructorIsDeleted = true;
  927. }
  928. if (!Field->hasInClassInitializer() && !Field->isMutable()) {
  929. if (CXXRecordDecl *FieldType = T->getAsCXXRecordDecl()) {
  930. if (FieldType->hasDefinition() && !FieldType->allowConstDefaultInit())
  931. data().HasUninitializedFields = true;
  932. } else {
  933. data().HasUninitializedFields = true;
  934. }
  935. }
  936. // Record if this field is the first non-literal or volatile field or base.
  937. if (!T->isLiteralType(Context) || T.isVolatileQualified())
  938. data().HasNonLiteralTypeFieldsOrBases = true;
  939. if (Field->hasInClassInitializer() ||
  940. (Field->isAnonymousStructOrUnion() &&
  941. Field->getType()->getAsCXXRecordDecl()->hasInClassInitializer())) {
  942. data().HasInClassInitializer = true;
  943. // C++11 [class]p5:
  944. // A default constructor is trivial if [...] no non-static data member
  945. // of its class has a brace-or-equal-initializer.
  946. data().HasTrivialSpecialMembers &= ~SMF_DefaultConstructor;
  947. // C++11 [dcl.init.aggr]p1:
  948. // An aggregate is a [...] class with [...] no
  949. // brace-or-equal-initializers for non-static data members.
  950. //
  951. // This rule was removed in C++14.
  952. if (!getASTContext().getLangOpts().CPlusPlus14)
  953. data().Aggregate = false;
  954. // C++11 [class]p10:
  955. // A POD struct is [...] a trivial class.
  956. data().PlainOldData = false;
  957. }
  958. // C++11 [class.copy]p23:
  959. // A defaulted copy/move assignment operator for a class X is defined
  960. // as deleted if X has:
  961. // -- a non-static data member of reference type
  962. if (T->isReferenceType()) {
  963. data().DefaultedCopyAssignmentIsDeleted = true;
  964. data().DefaultedMoveAssignmentIsDeleted = true;
  965. }
  966. // Bitfields of length 0 are also zero-sized, but we already bailed out for
  967. // those because they are always unnamed.
  968. bool IsZeroSize = Field->isZeroSize(Context);
  969. if (const auto *RecordTy = T->getAs<RecordType>()) {
  970. auto *FieldRec = cast<CXXRecordDecl>(RecordTy->getDecl());
  971. if (FieldRec->getDefinition()) {
  972. addedClassSubobject(FieldRec);
  973. // We may need to perform overload resolution to determine whether a
  974. // field can be moved if it's const or volatile qualified.
  975. if (T.getCVRQualifiers() & (Qualifiers::Const | Qualifiers::Volatile)) {
  976. // We need to care about 'const' for the copy constructor because an
  977. // implicit copy constructor might be declared with a non-const
  978. // parameter.
  979. data().NeedOverloadResolutionForCopyConstructor = true;
  980. data().NeedOverloadResolutionForMoveConstructor = true;
  981. data().NeedOverloadResolutionForCopyAssignment = true;
  982. data().NeedOverloadResolutionForMoveAssignment = true;
  983. }
  984. // C++11 [class.ctor]p5, C++11 [class.copy]p11:
  985. // A defaulted [special member] for a class X is defined as
  986. // deleted if:
  987. // -- X is a union-like class that has a variant member with a
  988. // non-trivial [corresponding special member]
  989. if (isUnion()) {
  990. if (FieldRec->hasNonTrivialCopyConstructor())
  991. data().DefaultedCopyConstructorIsDeleted = true;
  992. if (FieldRec->hasNonTrivialMoveConstructor())
  993. data().DefaultedMoveConstructorIsDeleted = true;
  994. if (FieldRec->hasNonTrivialCopyAssignment())
  995. data().DefaultedCopyAssignmentIsDeleted = true;
  996. if (FieldRec->hasNonTrivialMoveAssignment())
  997. data().DefaultedMoveAssignmentIsDeleted = true;
  998. if (FieldRec->hasNonTrivialDestructor())
  999. data().DefaultedDestructorIsDeleted = true;
  1000. }
  1001. // For an anonymous union member, our overload resolution will perform
  1002. // overload resolution for its members.
  1003. if (Field->isAnonymousStructOrUnion()) {
  1004. data().NeedOverloadResolutionForCopyConstructor |=
  1005. FieldRec->data().NeedOverloadResolutionForCopyConstructor;
  1006. data().NeedOverloadResolutionForMoveConstructor |=
  1007. FieldRec->data().NeedOverloadResolutionForMoveConstructor;
  1008. data().NeedOverloadResolutionForCopyAssignment |=
  1009. FieldRec->data().NeedOverloadResolutionForCopyAssignment;
  1010. data().NeedOverloadResolutionForMoveAssignment |=
  1011. FieldRec->data().NeedOverloadResolutionForMoveAssignment;
  1012. data().NeedOverloadResolutionForDestructor |=
  1013. FieldRec->data().NeedOverloadResolutionForDestructor;
  1014. }
  1015. // C++0x [class.ctor]p5:
  1016. // A default constructor is trivial [...] if:
  1017. // -- for all the non-static data members of its class that are of
  1018. // class type (or array thereof), each such class has a trivial
  1019. // default constructor.
  1020. if (!FieldRec->hasTrivialDefaultConstructor())
  1021. data().HasTrivialSpecialMembers &= ~SMF_DefaultConstructor;
  1022. // C++0x [class.copy]p13:
  1023. // A copy/move constructor for class X is trivial if [...]
  1024. // [...]
  1025. // -- for each non-static data member of X that is of class type (or
  1026. // an array thereof), the constructor selected to copy/move that
  1027. // member is trivial;
  1028. if (!FieldRec->hasTrivialCopyConstructor())
  1029. data().HasTrivialSpecialMembers &= ~SMF_CopyConstructor;
  1030. if (!FieldRec->hasTrivialCopyConstructorForCall())
  1031. data().HasTrivialSpecialMembersForCall &= ~SMF_CopyConstructor;
  1032. // If the field doesn't have a simple move constructor, we'll eagerly
  1033. // declare the move constructor for this class and we'll decide whether
  1034. // it's trivial then.
  1035. if (!FieldRec->hasTrivialMoveConstructor())
  1036. data().HasTrivialSpecialMembers &= ~SMF_MoveConstructor;
  1037. if (!FieldRec->hasTrivialMoveConstructorForCall())
  1038. data().HasTrivialSpecialMembersForCall &= ~SMF_MoveConstructor;
  1039. // C++0x [class.copy]p27:
  1040. // A copy/move assignment operator for class X is trivial if [...]
  1041. // [...]
  1042. // -- for each non-static data member of X that is of class type (or
  1043. // an array thereof), the assignment operator selected to
  1044. // copy/move that member is trivial;
  1045. if (!FieldRec->hasTrivialCopyAssignment())
  1046. data().HasTrivialSpecialMembers &= ~SMF_CopyAssignment;
  1047. // If the field doesn't have a simple move assignment, we'll eagerly
  1048. // declare the move assignment for this class and we'll decide whether
  1049. // it's trivial then.
  1050. if (!FieldRec->hasTrivialMoveAssignment())
  1051. data().HasTrivialSpecialMembers &= ~SMF_MoveAssignment;
  1052. if (!FieldRec->hasTrivialDestructor())
  1053. data().HasTrivialSpecialMembers &= ~SMF_Destructor;
  1054. if (!FieldRec->hasTrivialDestructorForCall())
  1055. data().HasTrivialSpecialMembersForCall &= ~SMF_Destructor;
  1056. if (!FieldRec->hasIrrelevantDestructor())
  1057. data().HasIrrelevantDestructor = false;
  1058. if (FieldRec->isAnyDestructorNoReturn())
  1059. data().IsAnyDestructorNoReturn = true;
  1060. if (FieldRec->hasObjectMember())
  1061. setHasObjectMember(true);
  1062. if (FieldRec->hasVolatileMember())
  1063. setHasVolatileMember(true);
  1064. if (FieldRec->getArgPassingRestrictions() ==
  1065. RecordDecl::APK_CanNeverPassInRegs)
  1066. setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
  1067. // C++0x [class]p7:
  1068. // A standard-layout class is a class that:
  1069. // -- has no non-static data members of type non-standard-layout
  1070. // class (or array of such types) [...]
  1071. if (!FieldRec->isStandardLayout())
  1072. data().IsStandardLayout = false;
  1073. if (!FieldRec->isCXX11StandardLayout())
  1074. data().IsCXX11StandardLayout = false;
  1075. // C++2a [class]p7:
  1076. // A standard-layout class is a class that:
  1077. // [...]
  1078. // -- has no element of the set M(S) of types as a base class.
  1079. if (data().IsStandardLayout &&
  1080. (isUnion() || IsFirstField || IsZeroSize) &&
  1081. hasSubobjectAtOffsetZeroOfEmptyBaseType(Context, FieldRec))
  1082. data().IsStandardLayout = false;
  1083. // C++11 [class]p7:
  1084. // A standard-layout class is a class that:
  1085. // -- has no base classes of the same type as the first non-static
  1086. // data member
  1087. if (data().IsCXX11StandardLayout && IsFirstField) {
  1088. // FIXME: We should check all base classes here, not just direct
  1089. // base classes.
  1090. for (const auto &BI : bases()) {
  1091. if (Context.hasSameUnqualifiedType(BI.getType(), T)) {
  1092. data().IsCXX11StandardLayout = false;
  1093. break;
  1094. }
  1095. }
  1096. }
  1097. // Keep track of the presence of mutable fields.
  1098. if (FieldRec->hasMutableFields())
  1099. data().HasMutableFields = true;
  1100. if (Field->isMutable()) {
  1101. // Our copy constructor/assignment might call something other than
  1102. // the subobject's copy constructor/assignment if it's mutable and of
  1103. // class type.
  1104. data().NeedOverloadResolutionForCopyConstructor = true;
  1105. data().NeedOverloadResolutionForCopyAssignment = true;
  1106. }
  1107. // C++11 [class.copy]p13:
  1108. // If the implicitly-defined constructor would satisfy the
  1109. // requirements of a constexpr constructor, the implicitly-defined
  1110. // constructor is constexpr.
  1111. // C++11 [dcl.constexpr]p4:
  1112. // -- every constructor involved in initializing non-static data
  1113. // members [...] shall be a constexpr constructor
  1114. if (!Field->hasInClassInitializer() &&
  1115. !FieldRec->hasConstexprDefaultConstructor() && !isUnion())
  1116. // The standard requires any in-class initializer to be a constant
  1117. // expression. We consider this to be a defect.
  1118. data().DefaultedDefaultConstructorIsConstexpr = false;
  1119. // C++11 [class.copy]p8:
  1120. // The implicitly-declared copy constructor for a class X will have
  1121. // the form 'X::X(const X&)' if each potentially constructed subobject
  1122. // of a class type M (or array thereof) has a copy constructor whose
  1123. // first parameter is of type 'const M&' or 'const volatile M&'.
  1124. if (!FieldRec->hasCopyConstructorWithConstParam())
  1125. data().ImplicitCopyConstructorCanHaveConstParamForNonVBase = false;
  1126. // C++11 [class.copy]p18:
  1127. // The implicitly-declared copy assignment oeprator for a class X will
  1128. // have the form 'X& X::operator=(const X&)' if [...] for all the
  1129. // non-static data members of X that are of a class type M (or array
  1130. // thereof), each such class type has a copy assignment operator whose
  1131. // parameter is of type 'const M&', 'const volatile M&' or 'M'.
  1132. if (!FieldRec->hasCopyAssignmentWithConstParam())
  1133. data().ImplicitCopyAssignmentHasConstParam = false;
  1134. if (FieldRec->hasUninitializedReferenceMember() &&
  1135. !Field->hasInClassInitializer())
  1136. data().HasUninitializedReferenceMember = true;
  1137. // C++11 [class.union]p8, DR1460:
  1138. // a non-static data member of an anonymous union that is a member of
  1139. // X is also a variant member of X.
  1140. if (FieldRec->hasVariantMembers() &&
  1141. Field->isAnonymousStructOrUnion())
  1142. data().HasVariantMembers = true;
  1143. }
  1144. } else {
  1145. // Base element type of field is a non-class type.
  1146. if (!T->isLiteralType(Context) ||
  1147. (!Field->hasInClassInitializer() && !isUnion() &&
  1148. !Context.getLangOpts().CPlusPlus20))
  1149. data().DefaultedDefaultConstructorIsConstexpr = false;
  1150. // C++11 [class.copy]p23:
  1151. // A defaulted copy/move assignment operator for a class X is defined
  1152. // as deleted if X has:
  1153. // -- a non-static data member of const non-class type (or array
  1154. // thereof)
  1155. if (T.isConstQualified()) {
  1156. data().DefaultedCopyAssignmentIsDeleted = true;
  1157. data().DefaultedMoveAssignmentIsDeleted = true;
  1158. }
  1159. // C++20 [temp.param]p7:
  1160. // A structural type is [...] a literal class type [for which] the
  1161. // types of all non-static data members are structural types or
  1162. // (possibly multidimensional) array thereof
  1163. // We deal with class types elsewhere.
  1164. if (!T->isStructuralType())
  1165. data().StructuralIfLiteral = false;
  1166. }
  1167. // C++14 [meta.unary.prop]p4:
  1168. // T is a class type [...] with [...] no non-static data members other
  1169. // than subobjects of zero size
  1170. if (data().Empty && !IsZeroSize)
  1171. data().Empty = false;
  1172. }
  1173. // Handle using declarations of conversion functions.
  1174. if (auto *Shadow = dyn_cast<UsingShadowDecl>(D)) {
  1175. if (Shadow->getDeclName().getNameKind()
  1176. == DeclarationName::CXXConversionFunctionName) {
  1177. ASTContext &Ctx = getASTContext();
  1178. data().Conversions.get(Ctx).addDecl(Ctx, Shadow, Shadow->getAccess());
  1179. }
  1180. }
  1181. if (const auto *Using = dyn_cast<UsingDecl>(D)) {
  1182. if (Using->getDeclName().getNameKind() ==
  1183. DeclarationName::CXXConstructorName) {
  1184. data().HasInheritedConstructor = true;
  1185. // C++1z [dcl.init.aggr]p1:
  1186. // An aggregate is [...] a class [...] with no inherited constructors
  1187. data().Aggregate = false;
  1188. }
  1189. if (Using->getDeclName().getCXXOverloadedOperator() == OO_Equal)
  1190. data().HasInheritedAssignment = true;
  1191. }
  1192. }
  1193. void CXXRecordDecl::addedSelectedDestructor(CXXDestructorDecl *DD) {
  1194. DD->setIneligibleOrNotSelected(false);
  1195. addedEligibleSpecialMemberFunction(DD, SMF_Destructor);
  1196. }
  1197. void CXXRecordDecl::addedEligibleSpecialMemberFunction(const CXXMethodDecl *MD,
  1198. unsigned SMKind) {
  1199. // FIXME: We shouldn't change DeclaredNonTrivialSpecialMembers if `MD` is
  1200. // a function template, but this needs CWG attention before we break ABI.
  1201. // See https://github.com/llvm/llvm-project/issues/59206
  1202. if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
  1203. if (DD->isUserProvided())
  1204. data().HasIrrelevantDestructor = false;
  1205. // If the destructor is explicitly defaulted and not trivial or not public
  1206. // or if the destructor is deleted, we clear HasIrrelevantDestructor in
  1207. // finishedDefaultedOrDeletedMember.
  1208. // C++11 [class.dtor]p5:
  1209. // A destructor is trivial if [...] the destructor is not virtual.
  1210. if (DD->isVirtual()) {
  1211. data().HasTrivialSpecialMembers &= ~SMF_Destructor;
  1212. data().HasTrivialSpecialMembersForCall &= ~SMF_Destructor;
  1213. }
  1214. if (DD->isNoReturn())
  1215. data().IsAnyDestructorNoReturn = true;
  1216. }
  1217. if (!MD->isImplicit() && !MD->isUserProvided()) {
  1218. // This method is user-declared but not user-provided. We can't work
  1219. // out whether it's trivial yet (not until we get to the end of the
  1220. // class). We'll handle this method in
  1221. // finishedDefaultedOrDeletedMember.
  1222. } else if (MD->isTrivial()) {
  1223. data().HasTrivialSpecialMembers |= SMKind;
  1224. data().HasTrivialSpecialMembersForCall |= SMKind;
  1225. } else if (MD->isTrivialForCall()) {
  1226. data().HasTrivialSpecialMembersForCall |= SMKind;
  1227. data().DeclaredNonTrivialSpecialMembers |= SMKind;
  1228. } else {
  1229. data().DeclaredNonTrivialSpecialMembers |= SMKind;
  1230. // If this is a user-provided function, do not set
  1231. // DeclaredNonTrivialSpecialMembersForCall here since we don't know
  1232. // yet whether the method would be considered non-trivial for the
  1233. // purpose of calls (attribute "trivial_abi" can be dropped from the
  1234. // class later, which can change the special method's triviality).
  1235. if (!MD->isUserProvided())
  1236. data().DeclaredNonTrivialSpecialMembersForCall |= SMKind;
  1237. }
  1238. }
  1239. void CXXRecordDecl::finishedDefaultedOrDeletedMember(CXXMethodDecl *D) {
  1240. assert(!D->isImplicit() && !D->isUserProvided());
  1241. // The kind of special member this declaration is, if any.
  1242. unsigned SMKind = 0;
  1243. if (const auto *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
  1244. if (Constructor->isDefaultConstructor()) {
  1245. SMKind |= SMF_DefaultConstructor;
  1246. if (Constructor->isConstexpr())
  1247. data().HasConstexprDefaultConstructor = true;
  1248. }
  1249. if (Constructor->isCopyConstructor())
  1250. SMKind |= SMF_CopyConstructor;
  1251. else if (Constructor->isMoveConstructor())
  1252. SMKind |= SMF_MoveConstructor;
  1253. else if (Constructor->isConstexpr())
  1254. // We may now know that the constructor is constexpr.
  1255. data().HasConstexprNonCopyMoveConstructor = true;
  1256. } else if (isa<CXXDestructorDecl>(D)) {
  1257. SMKind |= SMF_Destructor;
  1258. if (!D->isTrivial() || D->getAccess() != AS_public || D->isDeleted())
  1259. data().HasIrrelevantDestructor = false;
  1260. } else if (D->isCopyAssignmentOperator())
  1261. SMKind |= SMF_CopyAssignment;
  1262. else if (D->isMoveAssignmentOperator())
  1263. SMKind |= SMF_MoveAssignment;
  1264. // Update which trivial / non-trivial special members we have.
  1265. // addedMember will have skipped this step for this member.
  1266. if (!D->isIneligibleOrNotSelected()) {
  1267. if (D->isTrivial())
  1268. data().HasTrivialSpecialMembers |= SMKind;
  1269. else
  1270. data().DeclaredNonTrivialSpecialMembers |= SMKind;
  1271. }
  1272. }
  1273. void CXXRecordDecl::LambdaDefinitionData::AddCaptureList(ASTContext &Ctx,
  1274. Capture *CaptureList) {
  1275. Captures.push_back(CaptureList);
  1276. if (Captures.size() == 2) {
  1277. // The TinyPtrVector member now needs destruction.
  1278. Ctx.addDestruction(&Captures);
  1279. }
  1280. }
  1281. void CXXRecordDecl::setCaptures(ASTContext &Context,
  1282. ArrayRef<LambdaCapture> Captures) {
  1283. CXXRecordDecl::LambdaDefinitionData &Data = getLambdaData();
  1284. // Copy captures.
  1285. Data.NumCaptures = Captures.size();
  1286. Data.NumExplicitCaptures = 0;
  1287. auto *ToCapture = (LambdaCapture *)Context.Allocate(sizeof(LambdaCapture) *
  1288. Captures.size());
  1289. Data.AddCaptureList(Context, ToCapture);
  1290. for (unsigned I = 0, N = Captures.size(); I != N; ++I) {
  1291. if (Captures[I].isExplicit())
  1292. ++Data.NumExplicitCaptures;
  1293. *ToCapture++ = Captures[I];
  1294. }
  1295. if (!lambdaIsDefaultConstructibleAndAssignable())
  1296. Data.DefaultedCopyAssignmentIsDeleted = true;
  1297. }
  1298. void CXXRecordDecl::setTrivialForCallFlags(CXXMethodDecl *D) {
  1299. unsigned SMKind = 0;
  1300. if (const auto *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
  1301. if (Constructor->isCopyConstructor())
  1302. SMKind = SMF_CopyConstructor;
  1303. else if (Constructor->isMoveConstructor())
  1304. SMKind = SMF_MoveConstructor;
  1305. } else if (isa<CXXDestructorDecl>(D))
  1306. SMKind = SMF_Destructor;
  1307. if (D->isTrivialForCall())
  1308. data().HasTrivialSpecialMembersForCall |= SMKind;
  1309. else
  1310. data().DeclaredNonTrivialSpecialMembersForCall |= SMKind;
  1311. }
  1312. bool CXXRecordDecl::isCLike() const {
  1313. if (getTagKind() == TTK_Class || getTagKind() == TTK_Interface ||
  1314. !TemplateOrInstantiation.isNull())
  1315. return false;
  1316. if (!hasDefinition())
  1317. return true;
  1318. return isPOD() && data().HasOnlyCMembers;
  1319. }
  1320. bool CXXRecordDecl::isGenericLambda() const {
  1321. if (!isLambda()) return false;
  1322. return getLambdaData().IsGenericLambda;
  1323. }
  1324. #ifndef NDEBUG
  1325. static bool allLookupResultsAreTheSame(const DeclContext::lookup_result &R) {
  1326. for (auto *D : R)
  1327. if (!declaresSameEntity(D, R.front()))
  1328. return false;
  1329. return true;
  1330. }
  1331. #endif
  1332. static NamedDecl* getLambdaCallOperatorHelper(const CXXRecordDecl &RD) {
  1333. if (!RD.isLambda()) return nullptr;
  1334. DeclarationName Name =
  1335. RD.getASTContext().DeclarationNames.getCXXOperatorName(OO_Call);
  1336. DeclContext::lookup_result Calls = RD.lookup(Name);
  1337. assert(!Calls.empty() && "Missing lambda call operator!");
  1338. assert(allLookupResultsAreTheSame(Calls) &&
  1339. "More than one lambda call operator!");
  1340. return Calls.front();
  1341. }
  1342. FunctionTemplateDecl* CXXRecordDecl::getDependentLambdaCallOperator() const {
  1343. NamedDecl *CallOp = getLambdaCallOperatorHelper(*this);
  1344. return dyn_cast_or_null<FunctionTemplateDecl>(CallOp);
  1345. }
  1346. CXXMethodDecl *CXXRecordDecl::getLambdaCallOperator() const {
  1347. NamedDecl *CallOp = getLambdaCallOperatorHelper(*this);
  1348. if (CallOp == nullptr)
  1349. return nullptr;
  1350. if (const auto *CallOpTmpl = dyn_cast<FunctionTemplateDecl>(CallOp))
  1351. return cast<CXXMethodDecl>(CallOpTmpl->getTemplatedDecl());
  1352. return cast<CXXMethodDecl>(CallOp);
  1353. }
  1354. CXXMethodDecl* CXXRecordDecl::getLambdaStaticInvoker() const {
  1355. CXXMethodDecl *CallOp = getLambdaCallOperator();
  1356. CallingConv CC = CallOp->getType()->castAs<FunctionType>()->getCallConv();
  1357. return getLambdaStaticInvoker(CC);
  1358. }
  1359. static DeclContext::lookup_result
  1360. getLambdaStaticInvokers(const CXXRecordDecl &RD) {
  1361. assert(RD.isLambda() && "Must be a lambda");
  1362. DeclarationName Name =
  1363. &RD.getASTContext().Idents.get(getLambdaStaticInvokerName());
  1364. return RD.lookup(Name);
  1365. }
  1366. static CXXMethodDecl *getInvokerAsMethod(NamedDecl *ND) {
  1367. if (const auto *InvokerTemplate = dyn_cast<FunctionTemplateDecl>(ND))
  1368. return cast<CXXMethodDecl>(InvokerTemplate->getTemplatedDecl());
  1369. return cast<CXXMethodDecl>(ND);
  1370. }
  1371. CXXMethodDecl *CXXRecordDecl::getLambdaStaticInvoker(CallingConv CC) const {
  1372. if (!isLambda())
  1373. return nullptr;
  1374. DeclContext::lookup_result Invoker = getLambdaStaticInvokers(*this);
  1375. for (NamedDecl *ND : Invoker) {
  1376. const auto *FTy =
  1377. cast<ValueDecl>(ND->getAsFunction())->getType()->castAs<FunctionType>();
  1378. if (FTy->getCallConv() == CC)
  1379. return getInvokerAsMethod(ND);
  1380. }
  1381. return nullptr;
  1382. }
  1383. void CXXRecordDecl::getCaptureFields(
  1384. llvm::DenseMap<const ValueDecl *, FieldDecl *> &Captures,
  1385. FieldDecl *&ThisCapture) const {
  1386. Captures.clear();
  1387. ThisCapture = nullptr;
  1388. LambdaDefinitionData &Lambda = getLambdaData();
  1389. for (const LambdaCapture *List : Lambda.Captures) {
  1390. RecordDecl::field_iterator Field = field_begin();
  1391. for (const LambdaCapture *C = List, *CEnd = C + Lambda.NumCaptures;
  1392. C != CEnd; ++C, ++Field) {
  1393. if (C->capturesThis())
  1394. ThisCapture = *Field;
  1395. else if (C->capturesVariable())
  1396. Captures[C->getCapturedVar()] = *Field;
  1397. }
  1398. assert(Field == field_end());
  1399. }
  1400. }
  1401. TemplateParameterList *
  1402. CXXRecordDecl::getGenericLambdaTemplateParameterList() const {
  1403. if (!isGenericLambda()) return nullptr;
  1404. CXXMethodDecl *CallOp = getLambdaCallOperator();
  1405. if (FunctionTemplateDecl *Tmpl = CallOp->getDescribedFunctionTemplate())
  1406. return Tmpl->getTemplateParameters();
  1407. return nullptr;
  1408. }
  1409. ArrayRef<NamedDecl *>
  1410. CXXRecordDecl::getLambdaExplicitTemplateParameters() const {
  1411. TemplateParameterList *List = getGenericLambdaTemplateParameterList();
  1412. if (!List)
  1413. return {};
  1414. assert(std::is_partitioned(List->begin(), List->end(),
  1415. [](const NamedDecl *D) { return !D->isImplicit(); })
  1416. && "Explicit template params should be ordered before implicit ones");
  1417. const auto ExplicitEnd = llvm::partition_point(
  1418. *List, [](const NamedDecl *D) { return !D->isImplicit(); });
  1419. return llvm::ArrayRef(List->begin(), ExplicitEnd);
  1420. }
  1421. Decl *CXXRecordDecl::getLambdaContextDecl() const {
  1422. assert(isLambda() && "Not a lambda closure type!");
  1423. ExternalASTSource *Source = getParentASTContext().getExternalSource();
  1424. return getLambdaData().ContextDecl.get(Source);
  1425. }
  1426. void CXXRecordDecl::setDeviceLambdaManglingNumber(unsigned Num) const {
  1427. assert(isLambda() && "Not a lambda closure type!");
  1428. if (Num)
  1429. getASTContext().DeviceLambdaManglingNumbers[this] = Num;
  1430. }
  1431. unsigned CXXRecordDecl::getDeviceLambdaManglingNumber() const {
  1432. assert(isLambda() && "Not a lambda closure type!");
  1433. auto I = getASTContext().DeviceLambdaManglingNumbers.find(this);
  1434. if (I != getASTContext().DeviceLambdaManglingNumbers.end())
  1435. return I->second;
  1436. return 0;
  1437. }
  1438. static CanQualType GetConversionType(ASTContext &Context, NamedDecl *Conv) {
  1439. QualType T =
  1440. cast<CXXConversionDecl>(Conv->getUnderlyingDecl()->getAsFunction())
  1441. ->getConversionType();
  1442. return Context.getCanonicalType(T);
  1443. }
  1444. /// Collect the visible conversions of a base class.
  1445. ///
  1446. /// \param Record a base class of the class we're considering
  1447. /// \param InVirtual whether this base class is a virtual base (or a base
  1448. /// of a virtual base)
  1449. /// \param Access the access along the inheritance path to this base
  1450. /// \param ParentHiddenTypes the conversions provided by the inheritors
  1451. /// of this base
  1452. /// \param Output the set to which to add conversions from non-virtual bases
  1453. /// \param VOutput the set to which to add conversions from virtual bases
  1454. /// \param HiddenVBaseCs the set of conversions which were hidden in a
  1455. /// virtual base along some inheritance path
  1456. static void CollectVisibleConversions(
  1457. ASTContext &Context, const CXXRecordDecl *Record, bool InVirtual,
  1458. AccessSpecifier Access,
  1459. const llvm::SmallPtrSet<CanQualType, 8> &ParentHiddenTypes,
  1460. ASTUnresolvedSet &Output, UnresolvedSetImpl &VOutput,
  1461. llvm::SmallPtrSet<NamedDecl *, 8> &HiddenVBaseCs) {
  1462. // The set of types which have conversions in this class or its
  1463. // subclasses. As an optimization, we don't copy the derived set
  1464. // unless it might change.
  1465. const llvm::SmallPtrSet<CanQualType, 8> *HiddenTypes = &ParentHiddenTypes;
  1466. llvm::SmallPtrSet<CanQualType, 8> HiddenTypesBuffer;
  1467. // Collect the direct conversions and figure out which conversions
  1468. // will be hidden in the subclasses.
  1469. CXXRecordDecl::conversion_iterator ConvI = Record->conversion_begin();
  1470. CXXRecordDecl::conversion_iterator ConvE = Record->conversion_end();
  1471. if (ConvI != ConvE) {
  1472. HiddenTypesBuffer = ParentHiddenTypes;
  1473. HiddenTypes = &HiddenTypesBuffer;
  1474. for (CXXRecordDecl::conversion_iterator I = ConvI; I != ConvE; ++I) {
  1475. CanQualType ConvType(GetConversionType(Context, I.getDecl()));
  1476. bool Hidden = ParentHiddenTypes.count(ConvType);
  1477. if (!Hidden)
  1478. HiddenTypesBuffer.insert(ConvType);
  1479. // If this conversion is hidden and we're in a virtual base,
  1480. // remember that it's hidden along some inheritance path.
  1481. if (Hidden && InVirtual)
  1482. HiddenVBaseCs.insert(cast<NamedDecl>(I.getDecl()->getCanonicalDecl()));
  1483. // If this conversion isn't hidden, add it to the appropriate output.
  1484. else if (!Hidden) {
  1485. AccessSpecifier IAccess
  1486. = CXXRecordDecl::MergeAccess(Access, I.getAccess());
  1487. if (InVirtual)
  1488. VOutput.addDecl(I.getDecl(), IAccess);
  1489. else
  1490. Output.addDecl(Context, I.getDecl(), IAccess);
  1491. }
  1492. }
  1493. }
  1494. // Collect information recursively from any base classes.
  1495. for (const auto &I : Record->bases()) {
  1496. const auto *RT = I.getType()->getAs<RecordType>();
  1497. if (!RT) continue;
  1498. AccessSpecifier BaseAccess
  1499. = CXXRecordDecl::MergeAccess(Access, I.getAccessSpecifier());
  1500. bool BaseInVirtual = InVirtual || I.isVirtual();
  1501. auto *Base = cast<CXXRecordDecl>(RT->getDecl());
  1502. CollectVisibleConversions(Context, Base, BaseInVirtual, BaseAccess,
  1503. *HiddenTypes, Output, VOutput, HiddenVBaseCs);
  1504. }
  1505. }
  1506. /// Collect the visible conversions of a class.
  1507. ///
  1508. /// This would be extremely straightforward if it weren't for virtual
  1509. /// bases. It might be worth special-casing that, really.
  1510. static void CollectVisibleConversions(ASTContext &Context,
  1511. const CXXRecordDecl *Record,
  1512. ASTUnresolvedSet &Output) {
  1513. // The collection of all conversions in virtual bases that we've
  1514. // found. These will be added to the output as long as they don't
  1515. // appear in the hidden-conversions set.
  1516. UnresolvedSet<8> VBaseCs;
  1517. // The set of conversions in virtual bases that we've determined to
  1518. // be hidden.
  1519. llvm::SmallPtrSet<NamedDecl*, 8> HiddenVBaseCs;
  1520. // The set of types hidden by classes derived from this one.
  1521. llvm::SmallPtrSet<CanQualType, 8> HiddenTypes;
  1522. // Go ahead and collect the direct conversions and add them to the
  1523. // hidden-types set.
  1524. CXXRecordDecl::conversion_iterator ConvI = Record->conversion_begin();
  1525. CXXRecordDecl::conversion_iterator ConvE = Record->conversion_end();
  1526. Output.append(Context, ConvI, ConvE);
  1527. for (; ConvI != ConvE; ++ConvI)
  1528. HiddenTypes.insert(GetConversionType(Context, ConvI.getDecl()));
  1529. // Recursively collect conversions from base classes.
  1530. for (const auto &I : Record->bases()) {
  1531. const auto *RT = I.getType()->getAs<RecordType>();
  1532. if (!RT) continue;
  1533. CollectVisibleConversions(Context, cast<CXXRecordDecl>(RT->getDecl()),
  1534. I.isVirtual(), I.getAccessSpecifier(),
  1535. HiddenTypes, Output, VBaseCs, HiddenVBaseCs);
  1536. }
  1537. // Add any unhidden conversions provided by virtual bases.
  1538. for (UnresolvedSetIterator I = VBaseCs.begin(), E = VBaseCs.end();
  1539. I != E; ++I) {
  1540. if (!HiddenVBaseCs.count(cast<NamedDecl>(I.getDecl()->getCanonicalDecl())))
  1541. Output.addDecl(Context, I.getDecl(), I.getAccess());
  1542. }
  1543. }
  1544. /// getVisibleConversionFunctions - get all conversion functions visible
  1545. /// in current class; including conversion function templates.
  1546. llvm::iterator_range<CXXRecordDecl::conversion_iterator>
  1547. CXXRecordDecl::getVisibleConversionFunctions() const {
  1548. ASTContext &Ctx = getASTContext();
  1549. ASTUnresolvedSet *Set;
  1550. if (bases_begin() == bases_end()) {
  1551. // If root class, all conversions are visible.
  1552. Set = &data().Conversions.get(Ctx);
  1553. } else {
  1554. Set = &data().VisibleConversions.get(Ctx);
  1555. // If visible conversion list is not evaluated, evaluate it.
  1556. if (!data().ComputedVisibleConversions) {
  1557. CollectVisibleConversions(Ctx, this, *Set);
  1558. data().ComputedVisibleConversions = true;
  1559. }
  1560. }
  1561. return llvm::make_range(Set->begin(), Set->end());
  1562. }
  1563. void CXXRecordDecl::removeConversion(const NamedDecl *ConvDecl) {
  1564. // This operation is O(N) but extremely rare. Sema only uses it to
  1565. // remove UsingShadowDecls in a class that were followed by a direct
  1566. // declaration, e.g.:
  1567. // class A : B {
  1568. // using B::operator int;
  1569. // operator int();
  1570. // };
  1571. // This is uncommon by itself and even more uncommon in conjunction
  1572. // with sufficiently large numbers of directly-declared conversions
  1573. // that asymptotic behavior matters.
  1574. ASTUnresolvedSet &Convs = data().Conversions.get(getASTContext());
  1575. for (unsigned I = 0, E = Convs.size(); I != E; ++I) {
  1576. if (Convs[I].getDecl() == ConvDecl) {
  1577. Convs.erase(I);
  1578. assert(!llvm::is_contained(Convs, ConvDecl) &&
  1579. "conversion was found multiple times in unresolved set");
  1580. return;
  1581. }
  1582. }
  1583. llvm_unreachable("conversion not found in set!");
  1584. }
  1585. CXXRecordDecl *CXXRecordDecl::getInstantiatedFromMemberClass() const {
  1586. if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo())
  1587. return cast<CXXRecordDecl>(MSInfo->getInstantiatedFrom());
  1588. return nullptr;
  1589. }
  1590. MemberSpecializationInfo *CXXRecordDecl::getMemberSpecializationInfo() const {
  1591. return TemplateOrInstantiation.dyn_cast<MemberSpecializationInfo *>();
  1592. }
  1593. void
  1594. CXXRecordDecl::setInstantiationOfMemberClass(CXXRecordDecl *RD,
  1595. TemplateSpecializationKind TSK) {
  1596. assert(TemplateOrInstantiation.isNull() &&
  1597. "Previous template or instantiation?");
  1598. assert(!isa<ClassTemplatePartialSpecializationDecl>(this));
  1599. TemplateOrInstantiation
  1600. = new (getASTContext()) MemberSpecializationInfo(RD, TSK);
  1601. }
  1602. ClassTemplateDecl *CXXRecordDecl::getDescribedClassTemplate() const {
  1603. return TemplateOrInstantiation.dyn_cast<ClassTemplateDecl *>();
  1604. }
  1605. void CXXRecordDecl::setDescribedClassTemplate(ClassTemplateDecl *Template) {
  1606. TemplateOrInstantiation = Template;
  1607. }
  1608. TemplateSpecializationKind CXXRecordDecl::getTemplateSpecializationKind() const{
  1609. if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(this))
  1610. return Spec->getSpecializationKind();
  1611. if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo())
  1612. return MSInfo->getTemplateSpecializationKind();
  1613. return TSK_Undeclared;
  1614. }
  1615. void
  1616. CXXRecordDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK) {
  1617. if (auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(this)) {
  1618. Spec->setSpecializationKind(TSK);
  1619. return;
  1620. }
  1621. if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
  1622. MSInfo->setTemplateSpecializationKind(TSK);
  1623. return;
  1624. }
  1625. llvm_unreachable("Not a class template or member class specialization");
  1626. }
  1627. const CXXRecordDecl *CXXRecordDecl::getTemplateInstantiationPattern() const {
  1628. auto GetDefinitionOrSelf =
  1629. [](const CXXRecordDecl *D) -> const CXXRecordDecl * {
  1630. if (auto *Def = D->getDefinition())
  1631. return Def;
  1632. return D;
  1633. };
  1634. // If it's a class template specialization, find the template or partial
  1635. // specialization from which it was instantiated.
  1636. if (auto *TD = dyn_cast<ClassTemplateSpecializationDecl>(this)) {
  1637. auto From = TD->getInstantiatedFrom();
  1638. if (auto *CTD = From.dyn_cast<ClassTemplateDecl *>()) {
  1639. while (auto *NewCTD = CTD->getInstantiatedFromMemberTemplate()) {
  1640. if (NewCTD->isMemberSpecialization())
  1641. break;
  1642. CTD = NewCTD;
  1643. }
  1644. return GetDefinitionOrSelf(CTD->getTemplatedDecl());
  1645. }
  1646. if (auto *CTPSD =
  1647. From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
  1648. while (auto *NewCTPSD = CTPSD->getInstantiatedFromMember()) {
  1649. if (NewCTPSD->isMemberSpecialization())
  1650. break;
  1651. CTPSD = NewCTPSD;
  1652. }
  1653. return GetDefinitionOrSelf(CTPSD);
  1654. }
  1655. }
  1656. if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
  1657. if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
  1658. const CXXRecordDecl *RD = this;
  1659. while (auto *NewRD = RD->getInstantiatedFromMemberClass())
  1660. RD = NewRD;
  1661. return GetDefinitionOrSelf(RD);
  1662. }
  1663. }
  1664. assert(!isTemplateInstantiation(this->getTemplateSpecializationKind()) &&
  1665. "couldn't find pattern for class template instantiation");
  1666. return nullptr;
  1667. }
  1668. CXXDestructorDecl *CXXRecordDecl::getDestructor() const {
  1669. ASTContext &Context = getASTContext();
  1670. QualType ClassType = Context.getTypeDeclType(this);
  1671. DeclarationName Name
  1672. = Context.DeclarationNames.getCXXDestructorName(
  1673. Context.getCanonicalType(ClassType));
  1674. DeclContext::lookup_result R = lookup(Name);
  1675. // If a destructor was marked as not selected, we skip it. We don't always
  1676. // have a selected destructor: dependent types, unnamed structs.
  1677. for (auto *Decl : R) {
  1678. auto* DD = dyn_cast<CXXDestructorDecl>(Decl);
  1679. if (DD && !DD->isIneligibleOrNotSelected())
  1680. return DD;
  1681. }
  1682. return nullptr;
  1683. }
  1684. static bool isDeclContextInNamespace(const DeclContext *DC) {
  1685. while (!DC->isTranslationUnit()) {
  1686. if (DC->isNamespace())
  1687. return true;
  1688. DC = DC->getParent();
  1689. }
  1690. return false;
  1691. }
  1692. bool CXXRecordDecl::isInterfaceLike() const {
  1693. assert(hasDefinition() && "checking for interface-like without a definition");
  1694. // All __interfaces are inheritently interface-like.
  1695. if (isInterface())
  1696. return true;
  1697. // Interface-like types cannot have a user declared constructor, destructor,
  1698. // friends, VBases, conversion functions, or fields. Additionally, lambdas
  1699. // cannot be interface types.
  1700. if (isLambda() || hasUserDeclaredConstructor() ||
  1701. hasUserDeclaredDestructor() || !field_empty() || hasFriends() ||
  1702. getNumVBases() > 0 || conversion_end() - conversion_begin() > 0)
  1703. return false;
  1704. // No interface-like type can have a method with a definition.
  1705. for (const auto *const Method : methods())
  1706. if (Method->isDefined() && !Method->isImplicit())
  1707. return false;
  1708. // Check "Special" types.
  1709. const auto *Uuid = getAttr<UuidAttr>();
  1710. // MS SDK declares IUnknown/IDispatch both in the root of a TU, or in an
  1711. // extern C++ block directly in the TU. These are only valid if in one
  1712. // of these two situations.
  1713. if (Uuid && isStruct() && !getDeclContext()->isExternCContext() &&
  1714. !isDeclContextInNamespace(getDeclContext()) &&
  1715. ((getName() == "IUnknown" &&
  1716. Uuid->getGuid() == "00000000-0000-0000-C000-000000000046") ||
  1717. (getName() == "IDispatch" &&
  1718. Uuid->getGuid() == "00020400-0000-0000-C000-000000000046"))) {
  1719. if (getNumBases() > 0)
  1720. return false;
  1721. return true;
  1722. }
  1723. // FIXME: Any access specifiers is supposed to make this no longer interface
  1724. // like.
  1725. // If this isn't a 'special' type, it must have a single interface-like base.
  1726. if (getNumBases() != 1)
  1727. return false;
  1728. const auto BaseSpec = *bases_begin();
  1729. if (BaseSpec.isVirtual() || BaseSpec.getAccessSpecifier() != AS_public)
  1730. return false;
  1731. const auto *Base = BaseSpec.getType()->getAsCXXRecordDecl();
  1732. if (Base->isInterface() || !Base->isInterfaceLike())
  1733. return false;
  1734. return true;
  1735. }
  1736. void CXXRecordDecl::completeDefinition() {
  1737. completeDefinition(nullptr);
  1738. }
  1739. void CXXRecordDecl::completeDefinition(CXXFinalOverriderMap *FinalOverriders) {
  1740. RecordDecl::completeDefinition();
  1741. // If the class may be abstract (but hasn't been marked as such), check for
  1742. // any pure final overriders.
  1743. if (mayBeAbstract()) {
  1744. CXXFinalOverriderMap MyFinalOverriders;
  1745. if (!FinalOverriders) {
  1746. getFinalOverriders(MyFinalOverriders);
  1747. FinalOverriders = &MyFinalOverriders;
  1748. }
  1749. bool Done = false;
  1750. for (CXXFinalOverriderMap::iterator M = FinalOverriders->begin(),
  1751. MEnd = FinalOverriders->end();
  1752. M != MEnd && !Done; ++M) {
  1753. for (OverridingMethods::iterator SO = M->second.begin(),
  1754. SOEnd = M->second.end();
  1755. SO != SOEnd && !Done; ++SO) {
  1756. assert(SO->second.size() > 0 &&
  1757. "All virtual functions have overriding virtual functions");
  1758. // C++ [class.abstract]p4:
  1759. // A class is abstract if it contains or inherits at least one
  1760. // pure virtual function for which the final overrider is pure
  1761. // virtual.
  1762. if (SO->second.front().Method->isPure()) {
  1763. data().Abstract = true;
  1764. Done = true;
  1765. break;
  1766. }
  1767. }
  1768. }
  1769. }
  1770. // Set access bits correctly on the directly-declared conversions.
  1771. for (conversion_iterator I = conversion_begin(), E = conversion_end();
  1772. I != E; ++I)
  1773. I.setAccess((*I)->getAccess());
  1774. }
  1775. bool CXXRecordDecl::mayBeAbstract() const {
  1776. if (data().Abstract || isInvalidDecl() || !data().Polymorphic ||
  1777. isDependentContext())
  1778. return false;
  1779. for (const auto &B : bases()) {
  1780. const auto *BaseDecl =
  1781. cast<CXXRecordDecl>(B.getType()->castAs<RecordType>()->getDecl());
  1782. if (BaseDecl->isAbstract())
  1783. return true;
  1784. }
  1785. return false;
  1786. }
  1787. bool CXXRecordDecl::isEffectivelyFinal() const {
  1788. auto *Def = getDefinition();
  1789. if (!Def)
  1790. return false;
  1791. if (Def->hasAttr<FinalAttr>())
  1792. return true;
  1793. if (const auto *Dtor = Def->getDestructor())
  1794. if (Dtor->hasAttr<FinalAttr>())
  1795. return true;
  1796. return false;
  1797. }
  1798. void CXXDeductionGuideDecl::anchor() {}
  1799. bool ExplicitSpecifier::isEquivalent(const ExplicitSpecifier Other) const {
  1800. if ((getKind() != Other.getKind() ||
  1801. getKind() == ExplicitSpecKind::Unresolved)) {
  1802. if (getKind() == ExplicitSpecKind::Unresolved &&
  1803. Other.getKind() == ExplicitSpecKind::Unresolved) {
  1804. ODRHash SelfHash, OtherHash;
  1805. SelfHash.AddStmt(getExpr());
  1806. OtherHash.AddStmt(Other.getExpr());
  1807. return SelfHash.CalculateHash() == OtherHash.CalculateHash();
  1808. } else
  1809. return false;
  1810. }
  1811. return true;
  1812. }
  1813. ExplicitSpecifier ExplicitSpecifier::getFromDecl(FunctionDecl *Function) {
  1814. switch (Function->getDeclKind()) {
  1815. case Decl::Kind::CXXConstructor:
  1816. return cast<CXXConstructorDecl>(Function)->getExplicitSpecifier();
  1817. case Decl::Kind::CXXConversion:
  1818. return cast<CXXConversionDecl>(Function)->getExplicitSpecifier();
  1819. case Decl::Kind::CXXDeductionGuide:
  1820. return cast<CXXDeductionGuideDecl>(Function)->getExplicitSpecifier();
  1821. default:
  1822. return {};
  1823. }
  1824. }
  1825. CXXDeductionGuideDecl *
  1826. CXXDeductionGuideDecl::Create(ASTContext &C, DeclContext *DC,
  1827. SourceLocation StartLoc, ExplicitSpecifier ES,
  1828. const DeclarationNameInfo &NameInfo, QualType T,
  1829. TypeSourceInfo *TInfo, SourceLocation EndLocation,
  1830. CXXConstructorDecl *Ctor) {
  1831. return new (C, DC) CXXDeductionGuideDecl(C, DC, StartLoc, ES, NameInfo, T,
  1832. TInfo, EndLocation, Ctor);
  1833. }
  1834. CXXDeductionGuideDecl *CXXDeductionGuideDecl::CreateDeserialized(ASTContext &C,
  1835. unsigned ID) {
  1836. return new (C, ID) CXXDeductionGuideDecl(
  1837. C, nullptr, SourceLocation(), ExplicitSpecifier(), DeclarationNameInfo(),
  1838. QualType(), nullptr, SourceLocation(), nullptr);
  1839. }
  1840. RequiresExprBodyDecl *RequiresExprBodyDecl::Create(
  1841. ASTContext &C, DeclContext *DC, SourceLocation StartLoc) {
  1842. return new (C, DC) RequiresExprBodyDecl(C, DC, StartLoc);
  1843. }
  1844. RequiresExprBodyDecl *RequiresExprBodyDecl::CreateDeserialized(ASTContext &C,
  1845. unsigned ID) {
  1846. return new (C, ID) RequiresExprBodyDecl(C, nullptr, SourceLocation());
  1847. }
  1848. void CXXMethodDecl::anchor() {}
  1849. bool CXXMethodDecl::isStatic() const {
  1850. const CXXMethodDecl *MD = getCanonicalDecl();
  1851. if (MD->getStorageClass() == SC_Static)
  1852. return true;
  1853. OverloadedOperatorKind OOK = getDeclName().getCXXOverloadedOperator();
  1854. return isStaticOverloadedOperator(OOK);
  1855. }
  1856. static bool recursivelyOverrides(const CXXMethodDecl *DerivedMD,
  1857. const CXXMethodDecl *BaseMD) {
  1858. for (const CXXMethodDecl *MD : DerivedMD->overridden_methods()) {
  1859. if (MD->getCanonicalDecl() == BaseMD->getCanonicalDecl())
  1860. return true;
  1861. if (recursivelyOverrides(MD, BaseMD))
  1862. return true;
  1863. }
  1864. return false;
  1865. }
  1866. CXXMethodDecl *
  1867. CXXMethodDecl::getCorrespondingMethodDeclaredInClass(const CXXRecordDecl *RD,
  1868. bool MayBeBase) {
  1869. if (this->getParent()->getCanonicalDecl() == RD->getCanonicalDecl())
  1870. return this;
  1871. // Lookup doesn't work for destructors, so handle them separately.
  1872. if (isa<CXXDestructorDecl>(this)) {
  1873. CXXMethodDecl *MD = RD->getDestructor();
  1874. if (MD) {
  1875. if (recursivelyOverrides(MD, this))
  1876. return MD;
  1877. if (MayBeBase && recursivelyOverrides(this, MD))
  1878. return MD;
  1879. }
  1880. return nullptr;
  1881. }
  1882. for (auto *ND : RD->lookup(getDeclName())) {
  1883. auto *MD = dyn_cast<CXXMethodDecl>(ND);
  1884. if (!MD)
  1885. continue;
  1886. if (recursivelyOverrides(MD, this))
  1887. return MD;
  1888. if (MayBeBase && recursivelyOverrides(this, MD))
  1889. return MD;
  1890. }
  1891. return nullptr;
  1892. }
  1893. CXXMethodDecl *
  1894. CXXMethodDecl::getCorrespondingMethodInClass(const CXXRecordDecl *RD,
  1895. bool MayBeBase) {
  1896. if (auto *MD = getCorrespondingMethodDeclaredInClass(RD, MayBeBase))
  1897. return MD;
  1898. llvm::SmallVector<CXXMethodDecl*, 4> FinalOverriders;
  1899. auto AddFinalOverrider = [&](CXXMethodDecl *D) {
  1900. // If this function is overridden by a candidate final overrider, it is not
  1901. // a final overrider.
  1902. for (CXXMethodDecl *OtherD : FinalOverriders) {
  1903. if (declaresSameEntity(D, OtherD) || recursivelyOverrides(OtherD, D))
  1904. return;
  1905. }
  1906. // Other candidate final overriders might be overridden by this function.
  1907. llvm::erase_if(FinalOverriders, [&](CXXMethodDecl *OtherD) {
  1908. return recursivelyOverrides(D, OtherD);
  1909. });
  1910. FinalOverriders.push_back(D);
  1911. };
  1912. for (const auto &I : RD->bases()) {
  1913. const RecordType *RT = I.getType()->getAs<RecordType>();
  1914. if (!RT)
  1915. continue;
  1916. const auto *Base = cast<CXXRecordDecl>(RT->getDecl());
  1917. if (CXXMethodDecl *D = this->getCorrespondingMethodInClass(Base))
  1918. AddFinalOverrider(D);
  1919. }
  1920. return FinalOverriders.size() == 1 ? FinalOverriders.front() : nullptr;
  1921. }
  1922. CXXMethodDecl *
  1923. CXXMethodDecl::Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
  1924. const DeclarationNameInfo &NameInfo, QualType T,
  1925. TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin,
  1926. bool isInline, ConstexprSpecKind ConstexprKind,
  1927. SourceLocation EndLocation,
  1928. Expr *TrailingRequiresClause) {
  1929. return new (C, RD) CXXMethodDecl(
  1930. CXXMethod, C, RD, StartLoc, NameInfo, T, TInfo, SC, UsesFPIntrin,
  1931. isInline, ConstexprKind, EndLocation, TrailingRequiresClause);
  1932. }
  1933. CXXMethodDecl *CXXMethodDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  1934. return new (C, ID) CXXMethodDecl(
  1935. CXXMethod, C, nullptr, SourceLocation(), DeclarationNameInfo(),
  1936. QualType(), nullptr, SC_None, false, false,
  1937. ConstexprSpecKind::Unspecified, SourceLocation(), nullptr);
  1938. }
  1939. CXXMethodDecl *CXXMethodDecl::getDevirtualizedMethod(const Expr *Base,
  1940. bool IsAppleKext) {
  1941. assert(isVirtual() && "this method is expected to be virtual");
  1942. // When building with -fapple-kext, all calls must go through the vtable since
  1943. // the kernel linker can do runtime patching of vtables.
  1944. if (IsAppleKext)
  1945. return nullptr;
  1946. // If the member function is marked 'final', we know that it can't be
  1947. // overridden and can therefore devirtualize it unless it's pure virtual.
  1948. if (hasAttr<FinalAttr>())
  1949. return isPure() ? nullptr : this;
  1950. // If Base is unknown, we cannot devirtualize.
  1951. if (!Base)
  1952. return nullptr;
  1953. // If the base expression (after skipping derived-to-base conversions) is a
  1954. // class prvalue, then we can devirtualize.
  1955. Base = Base->getBestDynamicClassTypeExpr();
  1956. if (Base->isPRValue() && Base->getType()->isRecordType())
  1957. return this;
  1958. // If we don't even know what we would call, we can't devirtualize.
  1959. const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
  1960. if (!BestDynamicDecl)
  1961. return nullptr;
  1962. // There may be a method corresponding to MD in a derived class.
  1963. CXXMethodDecl *DevirtualizedMethod =
  1964. getCorrespondingMethodInClass(BestDynamicDecl);
  1965. // If there final overrider in the dynamic type is ambiguous, we can't
  1966. // devirtualize this call.
  1967. if (!DevirtualizedMethod)
  1968. return nullptr;
  1969. // If that method is pure virtual, we can't devirtualize. If this code is
  1970. // reached, the result would be UB, not a direct call to the derived class
  1971. // function, and we can't assume the derived class function is defined.
  1972. if (DevirtualizedMethod->isPure())
  1973. return nullptr;
  1974. // If that method is marked final, we can devirtualize it.
  1975. if (DevirtualizedMethod->hasAttr<FinalAttr>())
  1976. return DevirtualizedMethod;
  1977. // Similarly, if the class itself or its destructor is marked 'final',
  1978. // the class can't be derived from and we can therefore devirtualize the
  1979. // member function call.
  1980. if (BestDynamicDecl->isEffectivelyFinal())
  1981. return DevirtualizedMethod;
  1982. if (const auto *DRE = dyn_cast<DeclRefExpr>(Base)) {
  1983. if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
  1984. if (VD->getType()->isRecordType())
  1985. // This is a record decl. We know the type and can devirtualize it.
  1986. return DevirtualizedMethod;
  1987. return nullptr;
  1988. }
  1989. // We can devirtualize calls on an object accessed by a class member access
  1990. // expression, since by C++11 [basic.life]p6 we know that it can't refer to
  1991. // a derived class object constructed in the same location.
  1992. if (const auto *ME = dyn_cast<MemberExpr>(Base)) {
  1993. const ValueDecl *VD = ME->getMemberDecl();
  1994. return VD->getType()->isRecordType() ? DevirtualizedMethod : nullptr;
  1995. }
  1996. // Likewise for calls on an object accessed by a (non-reference) pointer to
  1997. // member access.
  1998. if (auto *BO = dyn_cast<BinaryOperator>(Base)) {
  1999. if (BO->isPtrMemOp()) {
  2000. auto *MPT = BO->getRHS()->getType()->castAs<MemberPointerType>();
  2001. if (MPT->getPointeeType()->isRecordType())
  2002. return DevirtualizedMethod;
  2003. }
  2004. }
  2005. // We can't devirtualize the call.
  2006. return nullptr;
  2007. }
  2008. bool CXXMethodDecl::isUsualDeallocationFunction(
  2009. SmallVectorImpl<const FunctionDecl *> &PreventedBy) const {
  2010. assert(PreventedBy.empty() && "PreventedBy is expected to be empty");
  2011. if (getOverloadedOperator() != OO_Delete &&
  2012. getOverloadedOperator() != OO_Array_Delete)
  2013. return false;
  2014. // C++ [basic.stc.dynamic.deallocation]p2:
  2015. // A template instance is never a usual deallocation function,
  2016. // regardless of its signature.
  2017. if (getPrimaryTemplate())
  2018. return false;
  2019. // C++ [basic.stc.dynamic.deallocation]p2:
  2020. // If a class T has a member deallocation function named operator delete
  2021. // with exactly one parameter, then that function is a usual (non-placement)
  2022. // deallocation function. [...]
  2023. if (getNumParams() == 1)
  2024. return true;
  2025. unsigned UsualParams = 1;
  2026. // C++ P0722:
  2027. // A destroying operator delete is a usual deallocation function if
  2028. // removing the std::destroying_delete_t parameter and changing the
  2029. // first parameter type from T* to void* results in the signature of
  2030. // a usual deallocation function.
  2031. if (isDestroyingOperatorDelete())
  2032. ++UsualParams;
  2033. // C++ <=14 [basic.stc.dynamic.deallocation]p2:
  2034. // [...] If class T does not declare such an operator delete but does
  2035. // declare a member deallocation function named operator delete with
  2036. // exactly two parameters, the second of which has type std::size_t (18.1),
  2037. // then this function is a usual deallocation function.
  2038. //
  2039. // C++17 says a usual deallocation function is one with the signature
  2040. // (void* [, size_t] [, std::align_val_t] [, ...])
  2041. // and all such functions are usual deallocation functions. It's not clear
  2042. // that allowing varargs functions was intentional.
  2043. ASTContext &Context = getASTContext();
  2044. if (UsualParams < getNumParams() &&
  2045. Context.hasSameUnqualifiedType(getParamDecl(UsualParams)->getType(),
  2046. Context.getSizeType()))
  2047. ++UsualParams;
  2048. if (UsualParams < getNumParams() &&
  2049. getParamDecl(UsualParams)->getType()->isAlignValT())
  2050. ++UsualParams;
  2051. if (UsualParams != getNumParams())
  2052. return false;
  2053. // In C++17 onwards, all potential usual deallocation functions are actual
  2054. // usual deallocation functions. Honor this behavior when post-C++14
  2055. // deallocation functions are offered as extensions too.
  2056. // FIXME(EricWF): Destroying Delete should be a language option. How do we
  2057. // handle when destroying delete is used prior to C++17?
  2058. if (Context.getLangOpts().CPlusPlus17 ||
  2059. Context.getLangOpts().AlignedAllocation ||
  2060. isDestroyingOperatorDelete())
  2061. return true;
  2062. // This function is a usual deallocation function if there are no
  2063. // single-parameter deallocation functions of the same kind.
  2064. DeclContext::lookup_result R = getDeclContext()->lookup(getDeclName());
  2065. bool Result = true;
  2066. for (const auto *D : R) {
  2067. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  2068. if (FD->getNumParams() == 1) {
  2069. PreventedBy.push_back(FD);
  2070. Result = false;
  2071. }
  2072. }
  2073. }
  2074. return Result;
  2075. }
  2076. bool CXXMethodDecl::isCopyAssignmentOperator() const {
  2077. // C++0x [class.copy]p17:
  2078. // A user-declared copy assignment operator X::operator= is a non-static
  2079. // non-template member function of class X with exactly one parameter of
  2080. // type X, X&, const X&, volatile X& or const volatile X&.
  2081. if (/*operator=*/getOverloadedOperator() != OO_Equal ||
  2082. /*non-static*/ isStatic() ||
  2083. /*non-template*/getPrimaryTemplate() || getDescribedFunctionTemplate() ||
  2084. getNumParams() != 1)
  2085. return false;
  2086. QualType ParamType = getParamDecl(0)->getType();
  2087. if (const auto *Ref = ParamType->getAs<LValueReferenceType>())
  2088. ParamType = Ref->getPointeeType();
  2089. ASTContext &Context = getASTContext();
  2090. QualType ClassType
  2091. = Context.getCanonicalType(Context.getTypeDeclType(getParent()));
  2092. return Context.hasSameUnqualifiedType(ClassType, ParamType);
  2093. }
  2094. bool CXXMethodDecl::isMoveAssignmentOperator() const {
  2095. // C++0x [class.copy]p19:
  2096. // A user-declared move assignment operator X::operator= is a non-static
  2097. // non-template member function of class X with exactly one parameter of type
  2098. // X&&, const X&&, volatile X&&, or const volatile X&&.
  2099. if (getOverloadedOperator() != OO_Equal || isStatic() ||
  2100. getPrimaryTemplate() || getDescribedFunctionTemplate() ||
  2101. getNumParams() != 1)
  2102. return false;
  2103. QualType ParamType = getParamDecl(0)->getType();
  2104. if (!ParamType->isRValueReferenceType())
  2105. return false;
  2106. ParamType = ParamType->getPointeeType();
  2107. ASTContext &Context = getASTContext();
  2108. QualType ClassType
  2109. = Context.getCanonicalType(Context.getTypeDeclType(getParent()));
  2110. return Context.hasSameUnqualifiedType(ClassType, ParamType);
  2111. }
  2112. void CXXMethodDecl::addOverriddenMethod(const CXXMethodDecl *MD) {
  2113. assert(MD->isCanonicalDecl() && "Method is not canonical!");
  2114. assert(!MD->getParent()->isDependentContext() &&
  2115. "Can't add an overridden method to a class template!");
  2116. assert(MD->isVirtual() && "Method is not virtual!");
  2117. getASTContext().addOverriddenMethod(this, MD);
  2118. }
  2119. CXXMethodDecl::method_iterator CXXMethodDecl::begin_overridden_methods() const {
  2120. if (isa<CXXConstructorDecl>(this)) return nullptr;
  2121. return getASTContext().overridden_methods_begin(this);
  2122. }
  2123. CXXMethodDecl::method_iterator CXXMethodDecl::end_overridden_methods() const {
  2124. if (isa<CXXConstructorDecl>(this)) return nullptr;
  2125. return getASTContext().overridden_methods_end(this);
  2126. }
  2127. unsigned CXXMethodDecl::size_overridden_methods() const {
  2128. if (isa<CXXConstructorDecl>(this)) return 0;
  2129. return getASTContext().overridden_methods_size(this);
  2130. }
  2131. CXXMethodDecl::overridden_method_range
  2132. CXXMethodDecl::overridden_methods() const {
  2133. if (isa<CXXConstructorDecl>(this))
  2134. return overridden_method_range(nullptr, nullptr);
  2135. return getASTContext().overridden_methods(this);
  2136. }
  2137. static QualType getThisObjectType(ASTContext &C, const FunctionProtoType *FPT,
  2138. const CXXRecordDecl *Decl) {
  2139. QualType ClassTy = C.getTypeDeclType(Decl);
  2140. return C.getQualifiedType(ClassTy, FPT->getMethodQuals());
  2141. }
  2142. QualType CXXMethodDecl::getThisType(const FunctionProtoType *FPT,
  2143. const CXXRecordDecl *Decl) {
  2144. ASTContext &C = Decl->getASTContext();
  2145. QualType ObjectTy = ::getThisObjectType(C, FPT, Decl);
  2146. return C.getPointerType(ObjectTy);
  2147. }
  2148. QualType CXXMethodDecl::getThisObjectType(const FunctionProtoType *FPT,
  2149. const CXXRecordDecl *Decl) {
  2150. ASTContext &C = Decl->getASTContext();
  2151. return ::getThisObjectType(C, FPT, Decl);
  2152. }
  2153. QualType CXXMethodDecl::getThisType() const {
  2154. // C++ 9.3.2p1: The type of this in a member function of a class X is X*.
  2155. // If the member function is declared const, the type of this is const X*,
  2156. // if the member function is declared volatile, the type of this is
  2157. // volatile X*, and if the member function is declared const volatile,
  2158. // the type of this is const volatile X*.
  2159. assert(isInstance() && "No 'this' for static methods!");
  2160. return CXXMethodDecl::getThisType(getType()->castAs<FunctionProtoType>(),
  2161. getParent());
  2162. }
  2163. QualType CXXMethodDecl::getThisObjectType() const {
  2164. // Ditto getThisType.
  2165. assert(isInstance() && "No 'this' for static methods!");
  2166. return CXXMethodDecl::getThisObjectType(
  2167. getType()->castAs<FunctionProtoType>(), getParent());
  2168. }
  2169. bool CXXMethodDecl::hasInlineBody() const {
  2170. // If this function is a template instantiation, look at the template from
  2171. // which it was instantiated.
  2172. const FunctionDecl *CheckFn = getTemplateInstantiationPattern();
  2173. if (!CheckFn)
  2174. CheckFn = this;
  2175. const FunctionDecl *fn;
  2176. return CheckFn->isDefined(fn) && !fn->isOutOfLine() &&
  2177. (fn->doesThisDeclarationHaveABody() || fn->willHaveBody());
  2178. }
  2179. bool CXXMethodDecl::isLambdaStaticInvoker() const {
  2180. const CXXRecordDecl *P = getParent();
  2181. return P->isLambda() && getDeclName().isIdentifier() &&
  2182. getName() == getLambdaStaticInvokerName();
  2183. }
  2184. CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
  2185. TypeSourceInfo *TInfo, bool IsVirtual,
  2186. SourceLocation L, Expr *Init,
  2187. SourceLocation R,
  2188. SourceLocation EllipsisLoc)
  2189. : Initializee(TInfo), Init(Init), MemberOrEllipsisLocation(EllipsisLoc),
  2190. LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(IsVirtual),
  2191. IsWritten(false), SourceOrder(0) {}
  2192. CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context, FieldDecl *Member,
  2193. SourceLocation MemberLoc,
  2194. SourceLocation L, Expr *Init,
  2195. SourceLocation R)
  2196. : Initializee(Member), Init(Init), MemberOrEllipsisLocation(MemberLoc),
  2197. LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(false),
  2198. IsWritten(false), SourceOrder(0) {}
  2199. CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
  2200. IndirectFieldDecl *Member,
  2201. SourceLocation MemberLoc,
  2202. SourceLocation L, Expr *Init,
  2203. SourceLocation R)
  2204. : Initializee(Member), Init(Init), MemberOrEllipsisLocation(MemberLoc),
  2205. LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(false),
  2206. IsWritten(false), SourceOrder(0) {}
  2207. CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
  2208. TypeSourceInfo *TInfo,
  2209. SourceLocation L, Expr *Init,
  2210. SourceLocation R)
  2211. : Initializee(TInfo), Init(Init), LParenLoc(L), RParenLoc(R),
  2212. IsDelegating(true), IsVirtual(false), IsWritten(false), SourceOrder(0) {}
  2213. int64_t CXXCtorInitializer::getID(const ASTContext &Context) const {
  2214. return Context.getAllocator()
  2215. .identifyKnownAlignedObject<CXXCtorInitializer>(this);
  2216. }
  2217. TypeLoc CXXCtorInitializer::getBaseClassLoc() const {
  2218. if (isBaseInitializer())
  2219. return Initializee.get<TypeSourceInfo*>()->getTypeLoc();
  2220. else
  2221. return {};
  2222. }
  2223. const Type *CXXCtorInitializer::getBaseClass() const {
  2224. if (isBaseInitializer())
  2225. return Initializee.get<TypeSourceInfo*>()->getType().getTypePtr();
  2226. else
  2227. return nullptr;
  2228. }
  2229. SourceLocation CXXCtorInitializer::getSourceLocation() const {
  2230. if (isInClassMemberInitializer())
  2231. return getAnyMember()->getLocation();
  2232. if (isAnyMemberInitializer())
  2233. return getMemberLocation();
  2234. if (const auto *TSInfo = Initializee.get<TypeSourceInfo *>())
  2235. return TSInfo->getTypeLoc().getBeginLoc();
  2236. return {};
  2237. }
  2238. SourceRange CXXCtorInitializer::getSourceRange() const {
  2239. if (isInClassMemberInitializer()) {
  2240. FieldDecl *D = getAnyMember();
  2241. if (Expr *I = D->getInClassInitializer())
  2242. return I->getSourceRange();
  2243. return {};
  2244. }
  2245. return SourceRange(getSourceLocation(), getRParenLoc());
  2246. }
  2247. CXXConstructorDecl::CXXConstructorDecl(
  2248. ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
  2249. const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
  2250. ExplicitSpecifier ES, bool UsesFPIntrin, bool isInline,
  2251. bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind,
  2252. InheritedConstructor Inherited, Expr *TrailingRequiresClause)
  2253. : CXXMethodDecl(CXXConstructor, C, RD, StartLoc, NameInfo, T, TInfo,
  2254. SC_None, UsesFPIntrin, isInline, ConstexprKind,
  2255. SourceLocation(), TrailingRequiresClause) {
  2256. setNumCtorInitializers(0);
  2257. setInheritingConstructor(static_cast<bool>(Inherited));
  2258. setImplicit(isImplicitlyDeclared);
  2259. CXXConstructorDeclBits.HasTrailingExplicitSpecifier = ES.getExpr() ? 1 : 0;
  2260. if (Inherited)
  2261. *getTrailingObjects<InheritedConstructor>() = Inherited;
  2262. setExplicitSpecifier(ES);
  2263. }
  2264. void CXXConstructorDecl::anchor() {}
  2265. CXXConstructorDecl *CXXConstructorDecl::CreateDeserialized(ASTContext &C,
  2266. unsigned ID,
  2267. uint64_t AllocKind) {
  2268. bool hasTrailingExplicit = static_cast<bool>(AllocKind & TAKHasTailExplicit);
  2269. bool isInheritingConstructor =
  2270. static_cast<bool>(AllocKind & TAKInheritsConstructor);
  2271. unsigned Extra =
  2272. additionalSizeToAlloc<InheritedConstructor, ExplicitSpecifier>(
  2273. isInheritingConstructor, hasTrailingExplicit);
  2274. auto *Result = new (C, ID, Extra) CXXConstructorDecl(
  2275. C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(), nullptr,
  2276. ExplicitSpecifier(), false, false, false, ConstexprSpecKind::Unspecified,
  2277. InheritedConstructor(), nullptr);
  2278. Result->setInheritingConstructor(isInheritingConstructor);
  2279. Result->CXXConstructorDeclBits.HasTrailingExplicitSpecifier =
  2280. hasTrailingExplicit;
  2281. Result->setExplicitSpecifier(ExplicitSpecifier());
  2282. return Result;
  2283. }
  2284. CXXConstructorDecl *CXXConstructorDecl::Create(
  2285. ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
  2286. const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
  2287. ExplicitSpecifier ES, bool UsesFPIntrin, bool isInline,
  2288. bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind,
  2289. InheritedConstructor Inherited, Expr *TrailingRequiresClause) {
  2290. assert(NameInfo.getName().getNameKind()
  2291. == DeclarationName::CXXConstructorName &&
  2292. "Name must refer to a constructor");
  2293. unsigned Extra =
  2294. additionalSizeToAlloc<InheritedConstructor, ExplicitSpecifier>(
  2295. Inherited ? 1 : 0, ES.getExpr() ? 1 : 0);
  2296. return new (C, RD, Extra) CXXConstructorDecl(
  2297. C, RD, StartLoc, NameInfo, T, TInfo, ES, UsesFPIntrin, isInline,
  2298. isImplicitlyDeclared, ConstexprKind, Inherited, TrailingRequiresClause);
  2299. }
  2300. CXXConstructorDecl::init_const_iterator CXXConstructorDecl::init_begin() const {
  2301. return CtorInitializers.get(getASTContext().getExternalSource());
  2302. }
  2303. CXXConstructorDecl *CXXConstructorDecl::getTargetConstructor() const {
  2304. assert(isDelegatingConstructor() && "Not a delegating constructor!");
  2305. Expr *E = (*init_begin())->getInit()->IgnoreImplicit();
  2306. if (const auto *Construct = dyn_cast<CXXConstructExpr>(E))
  2307. return Construct->getConstructor();
  2308. return nullptr;
  2309. }
  2310. bool CXXConstructorDecl::isDefaultConstructor() const {
  2311. // C++ [class.default.ctor]p1:
  2312. // A default constructor for a class X is a constructor of class X for
  2313. // which each parameter that is not a function parameter pack has a default
  2314. // argument (including the case of a constructor with no parameters)
  2315. return getMinRequiredArguments() == 0;
  2316. }
  2317. bool
  2318. CXXConstructorDecl::isCopyConstructor(unsigned &TypeQuals) const {
  2319. return isCopyOrMoveConstructor(TypeQuals) &&
  2320. getParamDecl(0)->getType()->isLValueReferenceType();
  2321. }
  2322. bool CXXConstructorDecl::isMoveConstructor(unsigned &TypeQuals) const {
  2323. return isCopyOrMoveConstructor(TypeQuals) &&
  2324. getParamDecl(0)->getType()->isRValueReferenceType();
  2325. }
  2326. /// Determine whether this is a copy or move constructor.
  2327. bool CXXConstructorDecl::isCopyOrMoveConstructor(unsigned &TypeQuals) const {
  2328. // C++ [class.copy]p2:
  2329. // A non-template constructor for class X is a copy constructor
  2330. // if its first parameter is of type X&, const X&, volatile X& or
  2331. // const volatile X&, and either there are no other parameters
  2332. // or else all other parameters have default arguments (8.3.6).
  2333. // C++0x [class.copy]p3:
  2334. // A non-template constructor for class X is a move constructor if its
  2335. // first parameter is of type X&&, const X&&, volatile X&&, or
  2336. // const volatile X&&, and either there are no other parameters or else
  2337. // all other parameters have default arguments.
  2338. if (!hasOneParamOrDefaultArgs() || getPrimaryTemplate() != nullptr ||
  2339. getDescribedFunctionTemplate() != nullptr)
  2340. return false;
  2341. const ParmVarDecl *Param = getParamDecl(0);
  2342. // Do we have a reference type?
  2343. const auto *ParamRefType = Param->getType()->getAs<ReferenceType>();
  2344. if (!ParamRefType)
  2345. return false;
  2346. // Is it a reference to our class type?
  2347. ASTContext &Context = getASTContext();
  2348. CanQualType PointeeType
  2349. = Context.getCanonicalType(ParamRefType->getPointeeType());
  2350. CanQualType ClassTy
  2351. = Context.getCanonicalType(Context.getTagDeclType(getParent()));
  2352. if (PointeeType.getUnqualifiedType() != ClassTy)
  2353. return false;
  2354. // FIXME: other qualifiers?
  2355. // We have a copy or move constructor.
  2356. TypeQuals = PointeeType.getCVRQualifiers();
  2357. return true;
  2358. }
  2359. bool CXXConstructorDecl::isConvertingConstructor(bool AllowExplicit) const {
  2360. // C++ [class.conv.ctor]p1:
  2361. // A constructor declared without the function-specifier explicit
  2362. // that can be called with a single parameter specifies a
  2363. // conversion from the type of its first parameter to the type of
  2364. // its class. Such a constructor is called a converting
  2365. // constructor.
  2366. if (isExplicit() && !AllowExplicit)
  2367. return false;
  2368. // FIXME: This has nothing to do with the definition of converting
  2369. // constructor, but is convenient for how we use this function in overload
  2370. // resolution.
  2371. return getNumParams() == 0
  2372. ? getType()->castAs<FunctionProtoType>()->isVariadic()
  2373. : getMinRequiredArguments() <= 1;
  2374. }
  2375. bool CXXConstructorDecl::isSpecializationCopyingObject() const {
  2376. if (!hasOneParamOrDefaultArgs() || getDescribedFunctionTemplate() != nullptr)
  2377. return false;
  2378. const ParmVarDecl *Param = getParamDecl(0);
  2379. ASTContext &Context = getASTContext();
  2380. CanQualType ParamType = Context.getCanonicalType(Param->getType());
  2381. // Is it the same as our class type?
  2382. CanQualType ClassTy
  2383. = Context.getCanonicalType(Context.getTagDeclType(getParent()));
  2384. if (ParamType.getUnqualifiedType() != ClassTy)
  2385. return false;
  2386. return true;
  2387. }
  2388. void CXXDestructorDecl::anchor() {}
  2389. CXXDestructorDecl *
  2390. CXXDestructorDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  2391. return new (C, ID) CXXDestructorDecl(
  2392. C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(), nullptr,
  2393. false, false, false, ConstexprSpecKind::Unspecified, nullptr);
  2394. }
  2395. CXXDestructorDecl *CXXDestructorDecl::Create(
  2396. ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
  2397. const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
  2398. bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared,
  2399. ConstexprSpecKind ConstexprKind, Expr *TrailingRequiresClause) {
  2400. assert(NameInfo.getName().getNameKind()
  2401. == DeclarationName::CXXDestructorName &&
  2402. "Name must refer to a destructor");
  2403. return new (C, RD) CXXDestructorDecl(
  2404. C, RD, StartLoc, NameInfo, T, TInfo, UsesFPIntrin, isInline,
  2405. isImplicitlyDeclared, ConstexprKind, TrailingRequiresClause);
  2406. }
  2407. void CXXDestructorDecl::setOperatorDelete(FunctionDecl *OD, Expr *ThisArg) {
  2408. auto *First = cast<CXXDestructorDecl>(getFirstDecl());
  2409. if (OD && !First->OperatorDelete) {
  2410. First->OperatorDelete = OD;
  2411. First->OperatorDeleteThisArg = ThisArg;
  2412. if (auto *L = getASTMutationListener())
  2413. L->ResolvedOperatorDelete(First, OD, ThisArg);
  2414. }
  2415. }
  2416. void CXXConversionDecl::anchor() {}
  2417. CXXConversionDecl *
  2418. CXXConversionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  2419. return new (C, ID) CXXConversionDecl(
  2420. C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(), nullptr,
  2421. false, false, ExplicitSpecifier(), ConstexprSpecKind::Unspecified,
  2422. SourceLocation(), nullptr);
  2423. }
  2424. CXXConversionDecl *CXXConversionDecl::Create(
  2425. ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
  2426. const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
  2427. bool UsesFPIntrin, bool isInline, ExplicitSpecifier ES,
  2428. ConstexprSpecKind ConstexprKind, SourceLocation EndLocation,
  2429. Expr *TrailingRequiresClause) {
  2430. assert(NameInfo.getName().getNameKind()
  2431. == DeclarationName::CXXConversionFunctionName &&
  2432. "Name must refer to a conversion function");
  2433. return new (C, RD) CXXConversionDecl(
  2434. C, RD, StartLoc, NameInfo, T, TInfo, UsesFPIntrin, isInline, ES,
  2435. ConstexprKind, EndLocation, TrailingRequiresClause);
  2436. }
  2437. bool CXXConversionDecl::isLambdaToBlockPointerConversion() const {
  2438. return isImplicit() && getParent()->isLambda() &&
  2439. getConversionType()->isBlockPointerType();
  2440. }
  2441. LinkageSpecDecl::LinkageSpecDecl(DeclContext *DC, SourceLocation ExternLoc,
  2442. SourceLocation LangLoc, LanguageIDs lang,
  2443. bool HasBraces)
  2444. : Decl(LinkageSpec, DC, LangLoc), DeclContext(LinkageSpec),
  2445. ExternLoc(ExternLoc), RBraceLoc(SourceLocation()) {
  2446. setLanguage(lang);
  2447. LinkageSpecDeclBits.HasBraces = HasBraces;
  2448. }
  2449. void LinkageSpecDecl::anchor() {}
  2450. LinkageSpecDecl *LinkageSpecDecl::Create(ASTContext &C,
  2451. DeclContext *DC,
  2452. SourceLocation ExternLoc,
  2453. SourceLocation LangLoc,
  2454. LanguageIDs Lang,
  2455. bool HasBraces) {
  2456. return new (C, DC) LinkageSpecDecl(DC, ExternLoc, LangLoc, Lang, HasBraces);
  2457. }
  2458. LinkageSpecDecl *LinkageSpecDecl::CreateDeserialized(ASTContext &C,
  2459. unsigned ID) {
  2460. return new (C, ID) LinkageSpecDecl(nullptr, SourceLocation(),
  2461. SourceLocation(), lang_c, false);
  2462. }
  2463. void UsingDirectiveDecl::anchor() {}
  2464. UsingDirectiveDecl *UsingDirectiveDecl::Create(ASTContext &C, DeclContext *DC,
  2465. SourceLocation L,
  2466. SourceLocation NamespaceLoc,
  2467. NestedNameSpecifierLoc QualifierLoc,
  2468. SourceLocation IdentLoc,
  2469. NamedDecl *Used,
  2470. DeclContext *CommonAncestor) {
  2471. if (auto *NS = dyn_cast_or_null<NamespaceDecl>(Used))
  2472. Used = NS->getOriginalNamespace();
  2473. return new (C, DC) UsingDirectiveDecl(DC, L, NamespaceLoc, QualifierLoc,
  2474. IdentLoc, Used, CommonAncestor);
  2475. }
  2476. UsingDirectiveDecl *UsingDirectiveDecl::CreateDeserialized(ASTContext &C,
  2477. unsigned ID) {
  2478. return new (C, ID) UsingDirectiveDecl(nullptr, SourceLocation(),
  2479. SourceLocation(),
  2480. NestedNameSpecifierLoc(),
  2481. SourceLocation(), nullptr, nullptr);
  2482. }
  2483. NamespaceDecl *UsingDirectiveDecl::getNominatedNamespace() {
  2484. if (auto *NA = dyn_cast_or_null<NamespaceAliasDecl>(NominatedNamespace))
  2485. return NA->getNamespace();
  2486. return cast_or_null<NamespaceDecl>(NominatedNamespace);
  2487. }
  2488. NamespaceDecl::NamespaceDecl(ASTContext &C, DeclContext *DC, bool Inline,
  2489. SourceLocation StartLoc, SourceLocation IdLoc,
  2490. IdentifierInfo *Id, NamespaceDecl *PrevDecl,
  2491. bool Nested)
  2492. : NamedDecl(Namespace, DC, IdLoc, Id), DeclContext(Namespace),
  2493. redeclarable_base(C), LocStart(StartLoc) {
  2494. unsigned Flags = 0;
  2495. if (Inline)
  2496. Flags |= F_Inline;
  2497. if (Nested)
  2498. Flags |= F_Nested;
  2499. AnonOrFirstNamespaceAndFlags = {nullptr, Flags};
  2500. setPreviousDecl(PrevDecl);
  2501. if (PrevDecl)
  2502. AnonOrFirstNamespaceAndFlags.setPointer(PrevDecl->getOriginalNamespace());
  2503. }
  2504. NamespaceDecl *NamespaceDecl::Create(ASTContext &C, DeclContext *DC,
  2505. bool Inline, SourceLocation StartLoc,
  2506. SourceLocation IdLoc, IdentifierInfo *Id,
  2507. NamespaceDecl *PrevDecl, bool Nested) {
  2508. return new (C, DC)
  2509. NamespaceDecl(C, DC, Inline, StartLoc, IdLoc, Id, PrevDecl, Nested);
  2510. }
  2511. NamespaceDecl *NamespaceDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  2512. return new (C, ID) NamespaceDecl(C, nullptr, false, SourceLocation(),
  2513. SourceLocation(), nullptr, nullptr, false);
  2514. }
  2515. NamespaceDecl *NamespaceDecl::getOriginalNamespace() {
  2516. if (isFirstDecl())
  2517. return this;
  2518. return AnonOrFirstNamespaceAndFlags.getPointer();
  2519. }
  2520. const NamespaceDecl *NamespaceDecl::getOriginalNamespace() const {
  2521. if (isFirstDecl())
  2522. return this;
  2523. return AnonOrFirstNamespaceAndFlags.getPointer();
  2524. }
  2525. bool NamespaceDecl::isOriginalNamespace() const { return isFirstDecl(); }
  2526. NamespaceDecl *NamespaceDecl::getNextRedeclarationImpl() {
  2527. return getNextRedeclaration();
  2528. }
  2529. NamespaceDecl *NamespaceDecl::getPreviousDeclImpl() {
  2530. return getPreviousDecl();
  2531. }
  2532. NamespaceDecl *NamespaceDecl::getMostRecentDeclImpl() {
  2533. return getMostRecentDecl();
  2534. }
  2535. void NamespaceAliasDecl::anchor() {}
  2536. NamespaceAliasDecl *NamespaceAliasDecl::getNextRedeclarationImpl() {
  2537. return getNextRedeclaration();
  2538. }
  2539. NamespaceAliasDecl *NamespaceAliasDecl::getPreviousDeclImpl() {
  2540. return getPreviousDecl();
  2541. }
  2542. NamespaceAliasDecl *NamespaceAliasDecl::getMostRecentDeclImpl() {
  2543. return getMostRecentDecl();
  2544. }
  2545. NamespaceAliasDecl *NamespaceAliasDecl::Create(ASTContext &C, DeclContext *DC,
  2546. SourceLocation UsingLoc,
  2547. SourceLocation AliasLoc,
  2548. IdentifierInfo *Alias,
  2549. NestedNameSpecifierLoc QualifierLoc,
  2550. SourceLocation IdentLoc,
  2551. NamedDecl *Namespace) {
  2552. // FIXME: Preserve the aliased namespace as written.
  2553. if (auto *NS = dyn_cast_or_null<NamespaceDecl>(Namespace))
  2554. Namespace = NS->getOriginalNamespace();
  2555. return new (C, DC) NamespaceAliasDecl(C, DC, UsingLoc, AliasLoc, Alias,
  2556. QualifierLoc, IdentLoc, Namespace);
  2557. }
  2558. NamespaceAliasDecl *
  2559. NamespaceAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  2560. return new (C, ID) NamespaceAliasDecl(C, nullptr, SourceLocation(),
  2561. SourceLocation(), nullptr,
  2562. NestedNameSpecifierLoc(),
  2563. SourceLocation(), nullptr);
  2564. }
  2565. void LifetimeExtendedTemporaryDecl::anchor() {}
  2566. /// Retrieve the storage duration for the materialized temporary.
  2567. StorageDuration LifetimeExtendedTemporaryDecl::getStorageDuration() const {
  2568. const ValueDecl *ExtendingDecl = getExtendingDecl();
  2569. if (!ExtendingDecl)
  2570. return SD_FullExpression;
  2571. // FIXME: This is not necessarily correct for a temporary materialized
  2572. // within a default initializer.
  2573. if (isa<FieldDecl>(ExtendingDecl))
  2574. return SD_Automatic;
  2575. // FIXME: This only works because storage class specifiers are not allowed
  2576. // on decomposition declarations.
  2577. if (isa<BindingDecl>(ExtendingDecl))
  2578. return ExtendingDecl->getDeclContext()->isFunctionOrMethod() ? SD_Automatic
  2579. : SD_Static;
  2580. return cast<VarDecl>(ExtendingDecl)->getStorageDuration();
  2581. }
  2582. APValue *LifetimeExtendedTemporaryDecl::getOrCreateValue(bool MayCreate) const {
  2583. assert(getStorageDuration() == SD_Static &&
  2584. "don't need to cache the computed value for this temporary");
  2585. if (MayCreate && !Value) {
  2586. Value = (new (getASTContext()) APValue);
  2587. getASTContext().addDestruction(Value);
  2588. }
  2589. assert(Value && "may not be null");
  2590. return Value;
  2591. }
  2592. void UsingShadowDecl::anchor() {}
  2593. UsingShadowDecl::UsingShadowDecl(Kind K, ASTContext &C, DeclContext *DC,
  2594. SourceLocation Loc, DeclarationName Name,
  2595. BaseUsingDecl *Introducer, NamedDecl *Target)
  2596. : NamedDecl(K, DC, Loc, Name), redeclarable_base(C),
  2597. UsingOrNextShadow(Introducer) {
  2598. if (Target) {
  2599. assert(!isa<UsingShadowDecl>(Target));
  2600. setTargetDecl(Target);
  2601. }
  2602. setImplicit();
  2603. }
  2604. UsingShadowDecl::UsingShadowDecl(Kind K, ASTContext &C, EmptyShell Empty)
  2605. : NamedDecl(K, nullptr, SourceLocation(), DeclarationName()),
  2606. redeclarable_base(C) {}
  2607. UsingShadowDecl *
  2608. UsingShadowDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  2609. return new (C, ID) UsingShadowDecl(UsingShadow, C, EmptyShell());
  2610. }
  2611. BaseUsingDecl *UsingShadowDecl::getIntroducer() const {
  2612. const UsingShadowDecl *Shadow = this;
  2613. while (const auto *NextShadow =
  2614. dyn_cast<UsingShadowDecl>(Shadow->UsingOrNextShadow))
  2615. Shadow = NextShadow;
  2616. return cast<BaseUsingDecl>(Shadow->UsingOrNextShadow);
  2617. }
  2618. void ConstructorUsingShadowDecl::anchor() {}
  2619. ConstructorUsingShadowDecl *
  2620. ConstructorUsingShadowDecl::Create(ASTContext &C, DeclContext *DC,
  2621. SourceLocation Loc, UsingDecl *Using,
  2622. NamedDecl *Target, bool IsVirtual) {
  2623. return new (C, DC) ConstructorUsingShadowDecl(C, DC, Loc, Using, Target,
  2624. IsVirtual);
  2625. }
  2626. ConstructorUsingShadowDecl *
  2627. ConstructorUsingShadowDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  2628. return new (C, ID) ConstructorUsingShadowDecl(C, EmptyShell());
  2629. }
  2630. CXXRecordDecl *ConstructorUsingShadowDecl::getNominatedBaseClass() const {
  2631. return getIntroducer()->getQualifier()->getAsRecordDecl();
  2632. }
  2633. void BaseUsingDecl::anchor() {}
  2634. void BaseUsingDecl::addShadowDecl(UsingShadowDecl *S) {
  2635. assert(!llvm::is_contained(shadows(), S) && "declaration already in set");
  2636. assert(S->getIntroducer() == this);
  2637. if (FirstUsingShadow.getPointer())
  2638. S->UsingOrNextShadow = FirstUsingShadow.getPointer();
  2639. FirstUsingShadow.setPointer(S);
  2640. }
  2641. void BaseUsingDecl::removeShadowDecl(UsingShadowDecl *S) {
  2642. assert(llvm::is_contained(shadows(), S) && "declaration not in set");
  2643. assert(S->getIntroducer() == this);
  2644. // Remove S from the shadow decl chain. This is O(n) but hopefully rare.
  2645. if (FirstUsingShadow.getPointer() == S) {
  2646. FirstUsingShadow.setPointer(
  2647. dyn_cast<UsingShadowDecl>(S->UsingOrNextShadow));
  2648. S->UsingOrNextShadow = this;
  2649. return;
  2650. }
  2651. UsingShadowDecl *Prev = FirstUsingShadow.getPointer();
  2652. while (Prev->UsingOrNextShadow != S)
  2653. Prev = cast<UsingShadowDecl>(Prev->UsingOrNextShadow);
  2654. Prev->UsingOrNextShadow = S->UsingOrNextShadow;
  2655. S->UsingOrNextShadow = this;
  2656. }
  2657. void UsingDecl::anchor() {}
  2658. UsingDecl *UsingDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation UL,
  2659. NestedNameSpecifierLoc QualifierLoc,
  2660. const DeclarationNameInfo &NameInfo,
  2661. bool HasTypename) {
  2662. return new (C, DC) UsingDecl(DC, UL, QualifierLoc, NameInfo, HasTypename);
  2663. }
  2664. UsingDecl *UsingDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  2665. return new (C, ID) UsingDecl(nullptr, SourceLocation(),
  2666. NestedNameSpecifierLoc(), DeclarationNameInfo(),
  2667. false);
  2668. }
  2669. SourceRange UsingDecl::getSourceRange() const {
  2670. SourceLocation Begin = isAccessDeclaration()
  2671. ? getQualifierLoc().getBeginLoc() : UsingLocation;
  2672. return SourceRange(Begin, getNameInfo().getEndLoc());
  2673. }
  2674. void UsingEnumDecl::anchor() {}
  2675. UsingEnumDecl *UsingEnumDecl::Create(ASTContext &C, DeclContext *DC,
  2676. SourceLocation UL,
  2677. SourceLocation EL,
  2678. SourceLocation NL,
  2679. TypeSourceInfo *EnumType) {
  2680. assert(isa<EnumDecl>(EnumType->getType()->getAsTagDecl()));
  2681. return new (C, DC)
  2682. UsingEnumDecl(DC, EnumType->getType()->getAsTagDecl()->getDeclName(), UL, EL, NL, EnumType);
  2683. }
  2684. UsingEnumDecl *UsingEnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  2685. return new (C, ID)
  2686. UsingEnumDecl(nullptr, DeclarationName(), SourceLocation(),
  2687. SourceLocation(), SourceLocation(), nullptr);
  2688. }
  2689. SourceRange UsingEnumDecl::getSourceRange() const {
  2690. return SourceRange(UsingLocation, EnumType->getTypeLoc().getEndLoc());
  2691. }
  2692. void UsingPackDecl::anchor() {}
  2693. UsingPackDecl *UsingPackDecl::Create(ASTContext &C, DeclContext *DC,
  2694. NamedDecl *InstantiatedFrom,
  2695. ArrayRef<NamedDecl *> UsingDecls) {
  2696. size_t Extra = additionalSizeToAlloc<NamedDecl *>(UsingDecls.size());
  2697. return new (C, DC, Extra) UsingPackDecl(DC, InstantiatedFrom, UsingDecls);
  2698. }
  2699. UsingPackDecl *UsingPackDecl::CreateDeserialized(ASTContext &C, unsigned ID,
  2700. unsigned NumExpansions) {
  2701. size_t Extra = additionalSizeToAlloc<NamedDecl *>(NumExpansions);
  2702. auto *Result =
  2703. new (C, ID, Extra) UsingPackDecl(nullptr, nullptr, std::nullopt);
  2704. Result->NumExpansions = NumExpansions;
  2705. auto *Trail = Result->getTrailingObjects<NamedDecl *>();
  2706. for (unsigned I = 0; I != NumExpansions; ++I)
  2707. new (Trail + I) NamedDecl*(nullptr);
  2708. return Result;
  2709. }
  2710. void UnresolvedUsingValueDecl::anchor() {}
  2711. UnresolvedUsingValueDecl *
  2712. UnresolvedUsingValueDecl::Create(ASTContext &C, DeclContext *DC,
  2713. SourceLocation UsingLoc,
  2714. NestedNameSpecifierLoc QualifierLoc,
  2715. const DeclarationNameInfo &NameInfo,
  2716. SourceLocation EllipsisLoc) {
  2717. return new (C, DC) UnresolvedUsingValueDecl(DC, C.DependentTy, UsingLoc,
  2718. QualifierLoc, NameInfo,
  2719. EllipsisLoc);
  2720. }
  2721. UnresolvedUsingValueDecl *
  2722. UnresolvedUsingValueDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  2723. return new (C, ID) UnresolvedUsingValueDecl(nullptr, QualType(),
  2724. SourceLocation(),
  2725. NestedNameSpecifierLoc(),
  2726. DeclarationNameInfo(),
  2727. SourceLocation());
  2728. }
  2729. SourceRange UnresolvedUsingValueDecl::getSourceRange() const {
  2730. SourceLocation Begin = isAccessDeclaration()
  2731. ? getQualifierLoc().getBeginLoc() : UsingLocation;
  2732. return SourceRange(Begin, getNameInfo().getEndLoc());
  2733. }
  2734. void UnresolvedUsingTypenameDecl::anchor() {}
  2735. UnresolvedUsingTypenameDecl *
  2736. UnresolvedUsingTypenameDecl::Create(ASTContext &C, DeclContext *DC,
  2737. SourceLocation UsingLoc,
  2738. SourceLocation TypenameLoc,
  2739. NestedNameSpecifierLoc QualifierLoc,
  2740. SourceLocation TargetNameLoc,
  2741. DeclarationName TargetName,
  2742. SourceLocation EllipsisLoc) {
  2743. return new (C, DC) UnresolvedUsingTypenameDecl(
  2744. DC, UsingLoc, TypenameLoc, QualifierLoc, TargetNameLoc,
  2745. TargetName.getAsIdentifierInfo(), EllipsisLoc);
  2746. }
  2747. UnresolvedUsingTypenameDecl *
  2748. UnresolvedUsingTypenameDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  2749. return new (C, ID) UnresolvedUsingTypenameDecl(
  2750. nullptr, SourceLocation(), SourceLocation(), NestedNameSpecifierLoc(),
  2751. SourceLocation(), nullptr, SourceLocation());
  2752. }
  2753. UnresolvedUsingIfExistsDecl *
  2754. UnresolvedUsingIfExistsDecl::Create(ASTContext &Ctx, DeclContext *DC,
  2755. SourceLocation Loc, DeclarationName Name) {
  2756. return new (Ctx, DC) UnresolvedUsingIfExistsDecl(DC, Loc, Name);
  2757. }
  2758. UnresolvedUsingIfExistsDecl *
  2759. UnresolvedUsingIfExistsDecl::CreateDeserialized(ASTContext &Ctx, unsigned ID) {
  2760. return new (Ctx, ID)
  2761. UnresolvedUsingIfExistsDecl(nullptr, SourceLocation(), DeclarationName());
  2762. }
  2763. UnresolvedUsingIfExistsDecl::UnresolvedUsingIfExistsDecl(DeclContext *DC,
  2764. SourceLocation Loc,
  2765. DeclarationName Name)
  2766. : NamedDecl(Decl::UnresolvedUsingIfExists, DC, Loc, Name) {}
  2767. void UnresolvedUsingIfExistsDecl::anchor() {}
  2768. void StaticAssertDecl::anchor() {}
  2769. StaticAssertDecl *StaticAssertDecl::Create(ASTContext &C, DeclContext *DC,
  2770. SourceLocation StaticAssertLoc,
  2771. Expr *AssertExpr,
  2772. StringLiteral *Message,
  2773. SourceLocation RParenLoc,
  2774. bool Failed) {
  2775. return new (C, DC) StaticAssertDecl(DC, StaticAssertLoc, AssertExpr, Message,
  2776. RParenLoc, Failed);
  2777. }
  2778. StaticAssertDecl *StaticAssertDecl::CreateDeserialized(ASTContext &C,
  2779. unsigned ID) {
  2780. return new (C, ID) StaticAssertDecl(nullptr, SourceLocation(), nullptr,
  2781. nullptr, SourceLocation(), false);
  2782. }
  2783. VarDecl *ValueDecl::getPotentiallyDecomposedVarDecl() {
  2784. assert((isa<VarDecl, BindingDecl>(this)) &&
  2785. "expected a VarDecl or a BindingDecl");
  2786. if (auto *Var = llvm::dyn_cast<VarDecl>(this))
  2787. return Var;
  2788. if (auto *BD = llvm::dyn_cast<BindingDecl>(this))
  2789. return llvm::dyn_cast<VarDecl>(BD->getDecomposedDecl());
  2790. return nullptr;
  2791. }
  2792. void BindingDecl::anchor() {}
  2793. BindingDecl *BindingDecl::Create(ASTContext &C, DeclContext *DC,
  2794. SourceLocation IdLoc, IdentifierInfo *Id) {
  2795. return new (C, DC) BindingDecl(DC, IdLoc, Id);
  2796. }
  2797. BindingDecl *BindingDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  2798. return new (C, ID) BindingDecl(nullptr, SourceLocation(), nullptr);
  2799. }
  2800. VarDecl *BindingDecl::getHoldingVar() const {
  2801. Expr *B = getBinding();
  2802. if (!B)
  2803. return nullptr;
  2804. auto *DRE = dyn_cast<DeclRefExpr>(B->IgnoreImplicit());
  2805. if (!DRE)
  2806. return nullptr;
  2807. auto *VD = cast<VarDecl>(DRE->getDecl());
  2808. assert(VD->isImplicit() && "holding var for binding decl not implicit");
  2809. return VD;
  2810. }
  2811. void DecompositionDecl::anchor() {}
  2812. DecompositionDecl *DecompositionDecl::Create(ASTContext &C, DeclContext *DC,
  2813. SourceLocation StartLoc,
  2814. SourceLocation LSquareLoc,
  2815. QualType T, TypeSourceInfo *TInfo,
  2816. StorageClass SC,
  2817. ArrayRef<BindingDecl *> Bindings) {
  2818. size_t Extra = additionalSizeToAlloc<BindingDecl *>(Bindings.size());
  2819. return new (C, DC, Extra)
  2820. DecompositionDecl(C, DC, StartLoc, LSquareLoc, T, TInfo, SC, Bindings);
  2821. }
  2822. DecompositionDecl *DecompositionDecl::CreateDeserialized(ASTContext &C,
  2823. unsigned ID,
  2824. unsigned NumBindings) {
  2825. size_t Extra = additionalSizeToAlloc<BindingDecl *>(NumBindings);
  2826. auto *Result = new (C, ID, Extra)
  2827. DecompositionDecl(C, nullptr, SourceLocation(), SourceLocation(),
  2828. QualType(), nullptr, StorageClass(), std::nullopt);
  2829. // Set up and clean out the bindings array.
  2830. Result->NumBindings = NumBindings;
  2831. auto *Trail = Result->getTrailingObjects<BindingDecl *>();
  2832. for (unsigned I = 0; I != NumBindings; ++I)
  2833. new (Trail + I) BindingDecl*(nullptr);
  2834. return Result;
  2835. }
  2836. void DecompositionDecl::printName(llvm::raw_ostream &OS,
  2837. const PrintingPolicy &Policy) const {
  2838. OS << '[';
  2839. bool Comma = false;
  2840. for (const auto *B : bindings()) {
  2841. if (Comma)
  2842. OS << ", ";
  2843. B->printName(OS, Policy);
  2844. Comma = true;
  2845. }
  2846. OS << ']';
  2847. }
  2848. void MSPropertyDecl::anchor() {}
  2849. MSPropertyDecl *MSPropertyDecl::Create(ASTContext &C, DeclContext *DC,
  2850. SourceLocation L, DeclarationName N,
  2851. QualType T, TypeSourceInfo *TInfo,
  2852. SourceLocation StartL,
  2853. IdentifierInfo *Getter,
  2854. IdentifierInfo *Setter) {
  2855. return new (C, DC) MSPropertyDecl(DC, L, N, T, TInfo, StartL, Getter, Setter);
  2856. }
  2857. MSPropertyDecl *MSPropertyDecl::CreateDeserialized(ASTContext &C,
  2858. unsigned ID) {
  2859. return new (C, ID) MSPropertyDecl(nullptr, SourceLocation(),
  2860. DeclarationName(), QualType(), nullptr,
  2861. SourceLocation(), nullptr, nullptr);
  2862. }
  2863. void MSGuidDecl::anchor() {}
  2864. MSGuidDecl::MSGuidDecl(DeclContext *DC, QualType T, Parts P)
  2865. : ValueDecl(Decl::MSGuid, DC, SourceLocation(), DeclarationName(), T),
  2866. PartVal(P) {}
  2867. MSGuidDecl *MSGuidDecl::Create(const ASTContext &C, QualType T, Parts P) {
  2868. DeclContext *DC = C.getTranslationUnitDecl();
  2869. return new (C, DC) MSGuidDecl(DC, T, P);
  2870. }
  2871. MSGuidDecl *MSGuidDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  2872. return new (C, ID) MSGuidDecl(nullptr, QualType(), Parts());
  2873. }
  2874. void MSGuidDecl::printName(llvm::raw_ostream &OS,
  2875. const PrintingPolicy &) const {
  2876. OS << llvm::format("GUID{%08" PRIx32 "-%04" PRIx16 "-%04" PRIx16 "-",
  2877. PartVal.Part1, PartVal.Part2, PartVal.Part3);
  2878. unsigned I = 0;
  2879. for (uint8_t Byte : PartVal.Part4And5) {
  2880. OS << llvm::format("%02" PRIx8, Byte);
  2881. if (++I == 2)
  2882. OS << '-';
  2883. }
  2884. OS << '}';
  2885. }
  2886. /// Determine if T is a valid 'struct _GUID' of the shape that we expect.
  2887. static bool isValidStructGUID(ASTContext &Ctx, QualType T) {
  2888. // FIXME: We only need to check this once, not once each time we compute a
  2889. // GUID APValue.
  2890. using MatcherRef = llvm::function_ref<bool(QualType)>;
  2891. auto IsInt = [&Ctx](unsigned N) {
  2892. return [&Ctx, N](QualType T) {
  2893. return T->isUnsignedIntegerOrEnumerationType() &&
  2894. Ctx.getIntWidth(T) == N;
  2895. };
  2896. };
  2897. auto IsArray = [&Ctx](MatcherRef Elem, unsigned N) {
  2898. return [&Ctx, Elem, N](QualType T) {
  2899. const ConstantArrayType *CAT = Ctx.getAsConstantArrayType(T);
  2900. return CAT && CAT->getSize() == N && Elem(CAT->getElementType());
  2901. };
  2902. };
  2903. auto IsStruct = [](std::initializer_list<MatcherRef> Fields) {
  2904. return [Fields](QualType T) {
  2905. const RecordDecl *RD = T->getAsRecordDecl();
  2906. if (!RD || RD->isUnion())
  2907. return false;
  2908. RD = RD->getDefinition();
  2909. if (!RD)
  2910. return false;
  2911. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
  2912. if (CXXRD->getNumBases())
  2913. return false;
  2914. auto MatcherIt = Fields.begin();
  2915. for (const FieldDecl *FD : RD->fields()) {
  2916. if (FD->isUnnamedBitfield()) continue;
  2917. if (FD->isBitField() || MatcherIt == Fields.end() ||
  2918. !(*MatcherIt)(FD->getType()))
  2919. return false;
  2920. ++MatcherIt;
  2921. }
  2922. return MatcherIt == Fields.end();
  2923. };
  2924. };
  2925. // We expect an {i32, i16, i16, [8 x i8]}.
  2926. return IsStruct({IsInt(32), IsInt(16), IsInt(16), IsArray(IsInt(8), 8)})(T);
  2927. }
  2928. APValue &MSGuidDecl::getAsAPValue() const {
  2929. if (APVal.isAbsent() && isValidStructGUID(getASTContext(), getType())) {
  2930. using llvm::APInt;
  2931. using llvm::APSInt;
  2932. APVal = APValue(APValue::UninitStruct(), 0, 4);
  2933. APVal.getStructField(0) = APValue(APSInt(APInt(32, PartVal.Part1), true));
  2934. APVal.getStructField(1) = APValue(APSInt(APInt(16, PartVal.Part2), true));
  2935. APVal.getStructField(2) = APValue(APSInt(APInt(16, PartVal.Part3), true));
  2936. APValue &Arr = APVal.getStructField(3) =
  2937. APValue(APValue::UninitArray(), 8, 8);
  2938. for (unsigned I = 0; I != 8; ++I) {
  2939. Arr.getArrayInitializedElt(I) =
  2940. APValue(APSInt(APInt(8, PartVal.Part4And5[I]), true));
  2941. }
  2942. // Register this APValue to be destroyed if necessary. (Note that the
  2943. // MSGuidDecl destructor is never run.)
  2944. getASTContext().addDestruction(&APVal);
  2945. }
  2946. return APVal;
  2947. }
  2948. void UnnamedGlobalConstantDecl::anchor() {}
  2949. UnnamedGlobalConstantDecl::UnnamedGlobalConstantDecl(const ASTContext &C,
  2950. DeclContext *DC,
  2951. QualType Ty,
  2952. const APValue &Val)
  2953. : ValueDecl(Decl::UnnamedGlobalConstant, DC, SourceLocation(),
  2954. DeclarationName(), Ty),
  2955. Value(Val) {
  2956. // Cleanup the embedded APValue if required (note that our destructor is never
  2957. // run)
  2958. if (Value.needsCleanup())
  2959. C.addDestruction(&Value);
  2960. }
  2961. UnnamedGlobalConstantDecl *
  2962. UnnamedGlobalConstantDecl::Create(const ASTContext &C, QualType T,
  2963. const APValue &Value) {
  2964. DeclContext *DC = C.getTranslationUnitDecl();
  2965. return new (C, DC) UnnamedGlobalConstantDecl(C, DC, T, Value);
  2966. }
  2967. UnnamedGlobalConstantDecl *
  2968. UnnamedGlobalConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  2969. return new (C, ID)
  2970. UnnamedGlobalConstantDecl(C, nullptr, QualType(), APValue());
  2971. }
  2972. void UnnamedGlobalConstantDecl::printName(llvm::raw_ostream &OS,
  2973. const PrintingPolicy &) const {
  2974. OS << "unnamed-global-constant";
  2975. }
  2976. static const char *getAccessName(AccessSpecifier AS) {
  2977. switch (AS) {
  2978. case AS_none:
  2979. llvm_unreachable("Invalid access specifier!");
  2980. case AS_public:
  2981. return "public";
  2982. case AS_private:
  2983. return "private";
  2984. case AS_protected:
  2985. return "protected";
  2986. }
  2987. llvm_unreachable("Invalid access specifier!");
  2988. }
  2989. const StreamingDiagnostic &clang::operator<<(const StreamingDiagnostic &DB,
  2990. AccessSpecifier AS) {
  2991. return DB << getAccessName(AS);
  2992. }