DeclCXX.cpp 130 KB

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