DeclCXX.cpp 120 KB

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