DeclTemplate.h 129 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- DeclTemplate.h - Classes for representing C++ templates --*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. /// \file
  15. /// Defines the C++ template declaration subclasses.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #ifndef LLVM_CLANG_AST_DECLTEMPLATE_H
  19. #define LLVM_CLANG_AST_DECLTEMPLATE_H
  20. #include "clang/AST/ASTConcept.h"
  21. #include "clang/AST/ASTContext.h"
  22. #include "clang/AST/Decl.h"
  23. #include "clang/AST/DeclBase.h"
  24. #include "clang/AST/DeclCXX.h"
  25. #include "clang/AST/DeclarationName.h"
  26. #include "clang/AST/Redeclarable.h"
  27. #include "clang/AST/TemplateBase.h"
  28. #include "clang/AST/Type.h"
  29. #include "clang/Basic/LLVM.h"
  30. #include "clang/Basic/SourceLocation.h"
  31. #include "clang/Basic/Specifiers.h"
  32. #include "llvm/ADT/ArrayRef.h"
  33. #include "llvm/ADT/FoldingSet.h"
  34. #include "llvm/ADT/PointerIntPair.h"
  35. #include "llvm/ADT/PointerUnion.h"
  36. #include "llvm/ADT/iterator.h"
  37. #include "llvm/ADT/iterator_range.h"
  38. #include "llvm/Support/Casting.h"
  39. #include "llvm/Support/Compiler.h"
  40. #include "llvm/Support/TrailingObjects.h"
  41. #include <cassert>
  42. #include <cstddef>
  43. #include <cstdint>
  44. #include <iterator>
  45. #include <optional>
  46. #include <utility>
  47. namespace clang {
  48. enum BuiltinTemplateKind : int;
  49. class ClassTemplateDecl;
  50. class ClassTemplatePartialSpecializationDecl;
  51. class Expr;
  52. class FunctionTemplateDecl;
  53. class IdentifierInfo;
  54. class NonTypeTemplateParmDecl;
  55. class TemplateDecl;
  56. class TemplateTemplateParmDecl;
  57. class TemplateTypeParmDecl;
  58. class ConceptDecl;
  59. class UnresolvedSetImpl;
  60. class VarTemplateDecl;
  61. class VarTemplatePartialSpecializationDecl;
  62. /// Stores a template parameter of any kind.
  63. using TemplateParameter =
  64. llvm::PointerUnion<TemplateTypeParmDecl *, NonTypeTemplateParmDecl *,
  65. TemplateTemplateParmDecl *>;
  66. NamedDecl *getAsNamedDecl(TemplateParameter P);
  67. /// Stores a list of template parameters for a TemplateDecl and its
  68. /// derived classes.
  69. class TemplateParameterList final
  70. : private llvm::TrailingObjects<TemplateParameterList, NamedDecl *,
  71. Expr *> {
  72. /// The location of the 'template' keyword.
  73. SourceLocation TemplateLoc;
  74. /// The locations of the '<' and '>' angle brackets.
  75. SourceLocation LAngleLoc, RAngleLoc;
  76. /// The number of template parameters in this template
  77. /// parameter list.
  78. unsigned NumParams : 29;
  79. /// Whether this template parameter list contains an unexpanded parameter
  80. /// pack.
  81. unsigned ContainsUnexpandedParameterPack : 1;
  82. /// Whether this template parameter list has a requires clause.
  83. unsigned HasRequiresClause : 1;
  84. /// Whether any of the template parameters has constrained-parameter
  85. /// constraint-expression.
  86. unsigned HasConstrainedParameters : 1;
  87. protected:
  88. TemplateParameterList(const ASTContext& C, SourceLocation TemplateLoc,
  89. SourceLocation LAngleLoc, ArrayRef<NamedDecl *> Params,
  90. SourceLocation RAngleLoc, Expr *RequiresClause);
  91. size_t numTrailingObjects(OverloadToken<NamedDecl *>) const {
  92. return NumParams;
  93. }
  94. size_t numTrailingObjects(OverloadToken<Expr *>) const {
  95. return HasRequiresClause ? 1 : 0;
  96. }
  97. public:
  98. template <size_t N, bool HasRequiresClause>
  99. friend class FixedSizeTemplateParameterListStorage;
  100. friend TrailingObjects;
  101. static TemplateParameterList *Create(const ASTContext &C,
  102. SourceLocation TemplateLoc,
  103. SourceLocation LAngleLoc,
  104. ArrayRef<NamedDecl *> Params,
  105. SourceLocation RAngleLoc,
  106. Expr *RequiresClause);
  107. /// Iterates through the template parameters in this list.
  108. using iterator = NamedDecl **;
  109. /// Iterates through the template parameters in this list.
  110. using const_iterator = NamedDecl * const *;
  111. iterator begin() { return getTrailingObjects<NamedDecl *>(); }
  112. const_iterator begin() const { return getTrailingObjects<NamedDecl *>(); }
  113. iterator end() { return begin() + NumParams; }
  114. const_iterator end() const { return begin() + NumParams; }
  115. unsigned size() const { return NumParams; }
  116. ArrayRef<NamedDecl *> asArray() { return llvm::ArrayRef(begin(), end()); }
  117. ArrayRef<const NamedDecl*> asArray() const {
  118. return llvm::ArrayRef(begin(), size());
  119. }
  120. NamedDecl* getParam(unsigned Idx) {
  121. assert(Idx < size() && "Template parameter index out-of-range");
  122. return begin()[Idx];
  123. }
  124. const NamedDecl* getParam(unsigned Idx) const {
  125. assert(Idx < size() && "Template parameter index out-of-range");
  126. return begin()[Idx];
  127. }
  128. /// Returns the minimum number of arguments needed to form a
  129. /// template specialization.
  130. ///
  131. /// This may be fewer than the number of template parameters, if some of
  132. /// the parameters have default arguments or if there is a parameter pack.
  133. unsigned getMinRequiredArguments() const;
  134. /// Get the depth of this template parameter list in the set of
  135. /// template parameter lists.
  136. ///
  137. /// The first template parameter list in a declaration will have depth 0,
  138. /// the second template parameter list will have depth 1, etc.
  139. unsigned getDepth() const;
  140. /// Determine whether this template parameter list contains an
  141. /// unexpanded parameter pack.
  142. bool containsUnexpandedParameterPack() const;
  143. /// Determine whether this template parameter list contains a parameter pack.
  144. bool hasParameterPack() const {
  145. for (const NamedDecl *P : asArray())
  146. if (P->isParameterPack())
  147. return true;
  148. return false;
  149. }
  150. /// The constraint-expression of the associated requires-clause.
  151. Expr *getRequiresClause() {
  152. return HasRequiresClause ? getTrailingObjects<Expr *>()[0] : nullptr;
  153. }
  154. /// The constraint-expression of the associated requires-clause.
  155. const Expr *getRequiresClause() const {
  156. return HasRequiresClause ? getTrailingObjects<Expr *>()[0] : nullptr;
  157. }
  158. /// \brief All associated constraints derived from this template parameter
  159. /// list, including the requires clause and any constraints derived from
  160. /// constrained-parameters.
  161. ///
  162. /// The constraints in the resulting list are to be treated as if in a
  163. /// conjunction ("and").
  164. void getAssociatedConstraints(llvm::SmallVectorImpl<const Expr *> &AC) const;
  165. bool hasAssociatedConstraints() const;
  166. SourceLocation getTemplateLoc() const { return TemplateLoc; }
  167. SourceLocation getLAngleLoc() const { return LAngleLoc; }
  168. SourceLocation getRAngleLoc() const { return RAngleLoc; }
  169. SourceRange getSourceRange() const LLVM_READONLY {
  170. return SourceRange(TemplateLoc, RAngleLoc);
  171. }
  172. void print(raw_ostream &Out, const ASTContext &Context,
  173. bool OmitTemplateKW = false) const;
  174. void print(raw_ostream &Out, const ASTContext &Context,
  175. const PrintingPolicy &Policy, bool OmitTemplateKW = false) const;
  176. static bool shouldIncludeTypeForArgument(const PrintingPolicy &Policy,
  177. const TemplateParameterList *TPL,
  178. unsigned Idx);
  179. };
  180. /// Stores a list of template parameters and the associated
  181. /// requires-clause (if any) for a TemplateDecl and its derived classes.
  182. /// Suitable for creating on the stack.
  183. template <size_t N, bool HasRequiresClause>
  184. class FixedSizeTemplateParameterListStorage
  185. : public TemplateParameterList::FixedSizeStorageOwner {
  186. typename TemplateParameterList::FixedSizeStorage<
  187. NamedDecl *, Expr *>::with_counts<
  188. N, HasRequiresClause ? 1u : 0u
  189. >::type storage;
  190. public:
  191. FixedSizeTemplateParameterListStorage(const ASTContext &C,
  192. SourceLocation TemplateLoc,
  193. SourceLocation LAngleLoc,
  194. ArrayRef<NamedDecl *> Params,
  195. SourceLocation RAngleLoc,
  196. Expr *RequiresClause)
  197. : FixedSizeStorageOwner(
  198. (assert(N == Params.size()),
  199. assert(HasRequiresClause == (RequiresClause != nullptr)),
  200. new (static_cast<void *>(&storage)) TemplateParameterList(C,
  201. TemplateLoc, LAngleLoc, Params, RAngleLoc, RequiresClause))) {}
  202. };
  203. /// A template argument list.
  204. class TemplateArgumentList final
  205. : private llvm::TrailingObjects<TemplateArgumentList, TemplateArgument> {
  206. /// The template argument list.
  207. const TemplateArgument *Arguments;
  208. /// The number of template arguments in this template
  209. /// argument list.
  210. unsigned NumArguments;
  211. // Constructs an instance with an internal Argument list, containing
  212. // a copy of the Args array. (Called by CreateCopy)
  213. TemplateArgumentList(ArrayRef<TemplateArgument> Args);
  214. public:
  215. friend TrailingObjects;
  216. TemplateArgumentList(const TemplateArgumentList &) = delete;
  217. TemplateArgumentList &operator=(const TemplateArgumentList &) = delete;
  218. /// Type used to indicate that the template argument list itself is a
  219. /// stack object. It does not own its template arguments.
  220. enum OnStackType { OnStack };
  221. /// Create a new template argument list that copies the given set of
  222. /// template arguments.
  223. static TemplateArgumentList *CreateCopy(ASTContext &Context,
  224. ArrayRef<TemplateArgument> Args);
  225. /// Construct a new, temporary template argument list on the stack.
  226. ///
  227. /// The template argument list does not own the template arguments
  228. /// provided.
  229. explicit TemplateArgumentList(OnStackType, ArrayRef<TemplateArgument> Args)
  230. : Arguments(Args.data()), NumArguments(Args.size()) {}
  231. /// Produces a shallow copy of the given template argument list.
  232. ///
  233. /// This operation assumes that the input argument list outlives it.
  234. /// This takes the list as a pointer to avoid looking like a copy
  235. /// constructor, since this really isn't safe to use that way.
  236. explicit TemplateArgumentList(const TemplateArgumentList *Other)
  237. : Arguments(Other->data()), NumArguments(Other->size()) {}
  238. /// Retrieve the template argument at a given index.
  239. const TemplateArgument &get(unsigned Idx) const {
  240. assert(Idx < NumArguments && "Invalid template argument index");
  241. return data()[Idx];
  242. }
  243. /// Retrieve the template argument at a given index.
  244. const TemplateArgument &operator[](unsigned Idx) const { return get(Idx); }
  245. /// Produce this as an array ref.
  246. ArrayRef<TemplateArgument> asArray() const {
  247. return llvm::ArrayRef(data(), size());
  248. }
  249. /// Retrieve the number of template arguments in this
  250. /// template argument list.
  251. unsigned size() const { return NumArguments; }
  252. /// Retrieve a pointer to the template argument list.
  253. const TemplateArgument *data() const { return Arguments; }
  254. };
  255. void *allocateDefaultArgStorageChain(const ASTContext &C);
  256. /// Storage for a default argument. This is conceptually either empty, or an
  257. /// argument value, or a pointer to a previous declaration that had a default
  258. /// argument.
  259. ///
  260. /// However, this is complicated by modules: while we require all the default
  261. /// arguments for a template to be equivalent, there may be more than one, and
  262. /// we need to track all the originating parameters to determine if the default
  263. /// argument is visible.
  264. template<typename ParmDecl, typename ArgType>
  265. class DefaultArgStorage {
  266. /// Storage for both the value *and* another parameter from which we inherit
  267. /// the default argument. This is used when multiple default arguments for a
  268. /// parameter are merged together from different modules.
  269. struct Chain {
  270. ParmDecl *PrevDeclWithDefaultArg;
  271. ArgType Value;
  272. };
  273. static_assert(sizeof(Chain) == sizeof(void *) * 2,
  274. "non-pointer argument type?");
  275. llvm::PointerUnion<ArgType, ParmDecl*, Chain*> ValueOrInherited;
  276. static ParmDecl *getParmOwningDefaultArg(ParmDecl *Parm) {
  277. const DefaultArgStorage &Storage = Parm->getDefaultArgStorage();
  278. if (auto *Prev = Storage.ValueOrInherited.template dyn_cast<ParmDecl *>())
  279. Parm = Prev;
  280. assert(!Parm->getDefaultArgStorage()
  281. .ValueOrInherited.template is<ParmDecl *>() &&
  282. "should only be one level of indirection");
  283. return Parm;
  284. }
  285. public:
  286. DefaultArgStorage() : ValueOrInherited(ArgType()) {}
  287. /// Determine whether there is a default argument for this parameter.
  288. bool isSet() const { return !ValueOrInherited.isNull(); }
  289. /// Determine whether the default argument for this parameter was inherited
  290. /// from a previous declaration of the same entity.
  291. bool isInherited() const { return ValueOrInherited.template is<ParmDecl*>(); }
  292. /// Get the default argument's value. This does not consider whether the
  293. /// default argument is visible.
  294. ArgType get() const {
  295. const DefaultArgStorage *Storage = this;
  296. if (const auto *Prev = ValueOrInherited.template dyn_cast<ParmDecl *>())
  297. Storage = &Prev->getDefaultArgStorage();
  298. if (const auto *C = Storage->ValueOrInherited.template dyn_cast<Chain *>())
  299. return C->Value;
  300. return Storage->ValueOrInherited.template get<ArgType>();
  301. }
  302. /// Get the parameter from which we inherit the default argument, if any.
  303. /// This is the parameter on which the default argument was actually written.
  304. const ParmDecl *getInheritedFrom() const {
  305. if (const auto *D = ValueOrInherited.template dyn_cast<ParmDecl *>())
  306. return D;
  307. if (const auto *C = ValueOrInherited.template dyn_cast<Chain *>())
  308. return C->PrevDeclWithDefaultArg;
  309. return nullptr;
  310. }
  311. /// Set the default argument.
  312. void set(ArgType Arg) {
  313. assert(!isSet() && "default argument already set");
  314. ValueOrInherited = Arg;
  315. }
  316. /// Set that the default argument was inherited from another parameter.
  317. void setInherited(const ASTContext &C, ParmDecl *InheritedFrom) {
  318. InheritedFrom = getParmOwningDefaultArg(InheritedFrom);
  319. if (!isSet())
  320. ValueOrInherited = InheritedFrom;
  321. else if (auto *D = ValueOrInherited.template dyn_cast<ParmDecl *>()) {
  322. assert(C.isSameDefaultTemplateArgument(D, InheritedFrom));
  323. ValueOrInherited =
  324. new (allocateDefaultArgStorageChain(C)) Chain{InheritedFrom, get()};
  325. } else if (auto *Inherited =
  326. ValueOrInherited.template dyn_cast<Chain *>()) {
  327. assert(C.isSameDefaultTemplateArgument(Inherited->PrevDeclWithDefaultArg,
  328. InheritedFrom));
  329. Inherited->PrevDeclWithDefaultArg = InheritedFrom;
  330. } else
  331. ValueOrInherited = new (allocateDefaultArgStorageChain(C))
  332. Chain{InheritedFrom, ValueOrInherited.template get<ArgType>()};
  333. }
  334. /// Remove the default argument, even if it was inherited.
  335. void clear() {
  336. ValueOrInherited = ArgType();
  337. }
  338. };
  339. //===----------------------------------------------------------------------===//
  340. // Kinds of Templates
  341. //===----------------------------------------------------------------------===//
  342. /// \brief The base class of all kinds of template declarations (e.g.,
  343. /// class, function, etc.).
  344. ///
  345. /// The TemplateDecl class stores the list of template parameters and a
  346. /// reference to the templated scoped declaration: the underlying AST node.
  347. class TemplateDecl : public NamedDecl {
  348. void anchor() override;
  349. protected:
  350. // Construct a template decl with name, parameters, and templated element.
  351. TemplateDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName Name,
  352. TemplateParameterList *Params, NamedDecl *Decl);
  353. // Construct a template decl with the given name and parameters.
  354. // Used when there is no templated element (e.g., for tt-params).
  355. TemplateDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName Name,
  356. TemplateParameterList *Params)
  357. : TemplateDecl(DK, DC, L, Name, Params, nullptr) {}
  358. public:
  359. friend class ASTDeclReader;
  360. friend class ASTDeclWriter;
  361. /// Get the list of template parameters
  362. TemplateParameterList *getTemplateParameters() const {
  363. return TemplateParams;
  364. }
  365. /// \brief Get the total constraint-expression associated with this template,
  366. /// including constraint-expressions derived from the requires-clause,
  367. /// trailing requires-clause (for functions and methods) and constrained
  368. /// template parameters.
  369. void getAssociatedConstraints(llvm::SmallVectorImpl<const Expr *> &AC) const;
  370. bool hasAssociatedConstraints() const;
  371. /// Get the underlying, templated declaration.
  372. NamedDecl *getTemplatedDecl() const { return TemplatedDecl; }
  373. // Should a specialization behave like an alias for another type.
  374. bool isTypeAlias() const;
  375. // Implement isa/cast/dyncast/etc.
  376. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  377. static bool classofKind(Kind K) {
  378. return K >= firstTemplate && K <= lastTemplate;
  379. }
  380. SourceRange getSourceRange() const override LLVM_READONLY {
  381. return SourceRange(getTemplateParameters()->getTemplateLoc(),
  382. TemplatedDecl->getSourceRange().getEnd());
  383. }
  384. protected:
  385. NamedDecl *TemplatedDecl;
  386. TemplateParameterList *TemplateParams;
  387. public:
  388. void setTemplateParameters(TemplateParameterList *TParams) {
  389. TemplateParams = TParams;
  390. }
  391. /// Initialize the underlying templated declaration.
  392. void init(NamedDecl *NewTemplatedDecl) {
  393. if (TemplatedDecl)
  394. assert(TemplatedDecl == NewTemplatedDecl && "Inconsistent TemplatedDecl");
  395. else
  396. TemplatedDecl = NewTemplatedDecl;
  397. }
  398. };
  399. /// Provides information about a function template specialization,
  400. /// which is a FunctionDecl that has been explicitly specialization or
  401. /// instantiated from a function template.
  402. class FunctionTemplateSpecializationInfo final
  403. : public llvm::FoldingSetNode,
  404. private llvm::TrailingObjects<FunctionTemplateSpecializationInfo,
  405. MemberSpecializationInfo *> {
  406. /// The function template specialization that this structure describes and a
  407. /// flag indicating if the function is a member specialization.
  408. llvm::PointerIntPair<FunctionDecl *, 1, bool> Function;
  409. /// The function template from which this function template
  410. /// specialization was generated.
  411. ///
  412. /// The two bits contain the top 4 values of TemplateSpecializationKind.
  413. llvm::PointerIntPair<FunctionTemplateDecl *, 2> Template;
  414. public:
  415. /// The template arguments used to produce the function template
  416. /// specialization from the function template.
  417. const TemplateArgumentList *TemplateArguments;
  418. /// The template arguments as written in the sources, if provided.
  419. /// FIXME: Normally null; tail-allocate this.
  420. const ASTTemplateArgumentListInfo *TemplateArgumentsAsWritten;
  421. /// The point at which this function template specialization was
  422. /// first instantiated.
  423. SourceLocation PointOfInstantiation;
  424. private:
  425. FunctionTemplateSpecializationInfo(
  426. FunctionDecl *FD, FunctionTemplateDecl *Template,
  427. TemplateSpecializationKind TSK, const TemplateArgumentList *TemplateArgs,
  428. const ASTTemplateArgumentListInfo *TemplateArgsAsWritten,
  429. SourceLocation POI, MemberSpecializationInfo *MSInfo)
  430. : Function(FD, MSInfo ? true : false), Template(Template, TSK - 1),
  431. TemplateArguments(TemplateArgs),
  432. TemplateArgumentsAsWritten(TemplateArgsAsWritten),
  433. PointOfInstantiation(POI) {
  434. if (MSInfo)
  435. getTrailingObjects<MemberSpecializationInfo *>()[0] = MSInfo;
  436. }
  437. size_t numTrailingObjects(OverloadToken<MemberSpecializationInfo*>) const {
  438. return Function.getInt();
  439. }
  440. public:
  441. friend TrailingObjects;
  442. static FunctionTemplateSpecializationInfo *
  443. Create(ASTContext &C, FunctionDecl *FD, FunctionTemplateDecl *Template,
  444. TemplateSpecializationKind TSK,
  445. const TemplateArgumentList *TemplateArgs,
  446. const TemplateArgumentListInfo *TemplateArgsAsWritten,
  447. SourceLocation POI, MemberSpecializationInfo *MSInfo);
  448. /// Retrieve the declaration of the function template specialization.
  449. FunctionDecl *getFunction() const { return Function.getPointer(); }
  450. /// Retrieve the template from which this function was specialized.
  451. FunctionTemplateDecl *getTemplate() const { return Template.getPointer(); }
  452. /// Determine what kind of template specialization this is.
  453. TemplateSpecializationKind getTemplateSpecializationKind() const {
  454. return (TemplateSpecializationKind)(Template.getInt() + 1);
  455. }
  456. bool isExplicitSpecialization() const {
  457. return getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
  458. }
  459. /// True if this declaration is an explicit specialization,
  460. /// explicit instantiation declaration, or explicit instantiation
  461. /// definition.
  462. bool isExplicitInstantiationOrSpecialization() const {
  463. return isTemplateExplicitInstantiationOrSpecialization(
  464. getTemplateSpecializationKind());
  465. }
  466. /// Set the template specialization kind.
  467. void setTemplateSpecializationKind(TemplateSpecializationKind TSK) {
  468. assert(TSK != TSK_Undeclared &&
  469. "Cannot encode TSK_Undeclared for a function template specialization");
  470. Template.setInt(TSK - 1);
  471. }
  472. /// Retrieve the first point of instantiation of this function
  473. /// template specialization.
  474. ///
  475. /// The point of instantiation may be an invalid source location if this
  476. /// function has yet to be instantiated.
  477. SourceLocation getPointOfInstantiation() const {
  478. return PointOfInstantiation;
  479. }
  480. /// Set the (first) point of instantiation of this function template
  481. /// specialization.
  482. void setPointOfInstantiation(SourceLocation POI) {
  483. PointOfInstantiation = POI;
  484. }
  485. /// Get the specialization info if this function template specialization is
  486. /// also a member specialization:
  487. ///
  488. /// \code
  489. /// template<typename> struct A {
  490. /// template<typename> void f();
  491. /// template<> void f<int>(); // ClassScopeFunctionSpecializationDecl
  492. /// };
  493. /// \endcode
  494. ///
  495. /// Here, A<int>::f<int> is a function template specialization that is
  496. /// an explicit specialization of A<int>::f, but it's also a member
  497. /// specialization (an implicit instantiation in this case) of A::f<int>.
  498. /// Further:
  499. ///
  500. /// \code
  501. /// template<> template<> void A<int>::f<int>() {}
  502. /// \endcode
  503. ///
  504. /// ... declares a function template specialization that is an explicit
  505. /// specialization of A<int>::f, and is also an explicit member
  506. /// specialization of A::f<int>.
  507. ///
  508. /// Note that the TemplateSpecializationKind of the MemberSpecializationInfo
  509. /// need not be the same as that returned by getTemplateSpecializationKind(),
  510. /// and represents the relationship between the function and the class-scope
  511. /// explicit specialization in the original templated class -- whereas our
  512. /// TemplateSpecializationKind represents the relationship between the
  513. /// function and the function template, and should always be
  514. /// TSK_ExplicitSpecialization whenever we have MemberSpecializationInfo.
  515. MemberSpecializationInfo *getMemberSpecializationInfo() const {
  516. return numTrailingObjects(OverloadToken<MemberSpecializationInfo *>())
  517. ? getTrailingObjects<MemberSpecializationInfo *>()[0]
  518. : nullptr;
  519. }
  520. void Profile(llvm::FoldingSetNodeID &ID) {
  521. Profile(ID, TemplateArguments->asArray(), getFunction()->getASTContext());
  522. }
  523. static void
  524. Profile(llvm::FoldingSetNodeID &ID, ArrayRef<TemplateArgument> TemplateArgs,
  525. ASTContext &Context) {
  526. ID.AddInteger(TemplateArgs.size());
  527. for (const TemplateArgument &TemplateArg : TemplateArgs)
  528. TemplateArg.Profile(ID, Context);
  529. }
  530. };
  531. /// Provides information a specialization of a member of a class
  532. /// template, which may be a member function, static data member,
  533. /// member class or member enumeration.
  534. class MemberSpecializationInfo {
  535. // The member declaration from which this member was instantiated, and the
  536. // manner in which the instantiation occurred (in the lower two bits).
  537. llvm::PointerIntPair<NamedDecl *, 2> MemberAndTSK;
  538. // The point at which this member was first instantiated.
  539. SourceLocation PointOfInstantiation;
  540. public:
  541. explicit
  542. MemberSpecializationInfo(NamedDecl *IF, TemplateSpecializationKind TSK,
  543. SourceLocation POI = SourceLocation())
  544. : MemberAndTSK(IF, TSK - 1), PointOfInstantiation(POI) {
  545. assert(TSK != TSK_Undeclared &&
  546. "Cannot encode undeclared template specializations for members");
  547. }
  548. /// Retrieve the member declaration from which this member was
  549. /// instantiated.
  550. NamedDecl *getInstantiatedFrom() const { return MemberAndTSK.getPointer(); }
  551. /// Determine what kind of template specialization this is.
  552. TemplateSpecializationKind getTemplateSpecializationKind() const {
  553. return (TemplateSpecializationKind)(MemberAndTSK.getInt() + 1);
  554. }
  555. bool isExplicitSpecialization() const {
  556. return getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
  557. }
  558. /// Set the template specialization kind.
  559. void setTemplateSpecializationKind(TemplateSpecializationKind TSK) {
  560. assert(TSK != TSK_Undeclared &&
  561. "Cannot encode undeclared template specializations for members");
  562. MemberAndTSK.setInt(TSK - 1);
  563. }
  564. /// Retrieve the first point of instantiation of this member.
  565. /// If the point of instantiation is an invalid location, then this member
  566. /// has not yet been instantiated.
  567. SourceLocation getPointOfInstantiation() const {
  568. return PointOfInstantiation;
  569. }
  570. /// Set the first point of instantiation.
  571. void setPointOfInstantiation(SourceLocation POI) {
  572. PointOfInstantiation = POI;
  573. }
  574. };
  575. /// Provides information about a dependent function-template
  576. /// specialization declaration.
  577. ///
  578. /// Since explicit function template specialization and instantiation
  579. /// declarations can only appear in namespace scope, and you can only
  580. /// specialize a member of a fully-specialized class, the only way to
  581. /// get one of these is in a friend declaration like the following:
  582. ///
  583. /// \code
  584. /// template \<class T> void foo(T);
  585. /// template \<class T> class A {
  586. /// friend void foo<>(T);
  587. /// };
  588. /// \endcode
  589. class DependentFunctionTemplateSpecializationInfo final
  590. : private llvm::TrailingObjects<DependentFunctionTemplateSpecializationInfo,
  591. TemplateArgumentLoc,
  592. FunctionTemplateDecl *> {
  593. /// The number of potential template candidates.
  594. unsigned NumTemplates;
  595. /// The number of template arguments.
  596. unsigned NumArgs;
  597. /// The locations of the left and right angle brackets.
  598. SourceRange AngleLocs;
  599. size_t numTrailingObjects(OverloadToken<TemplateArgumentLoc>) const {
  600. return NumArgs;
  601. }
  602. size_t numTrailingObjects(OverloadToken<FunctionTemplateDecl *>) const {
  603. return NumTemplates;
  604. }
  605. DependentFunctionTemplateSpecializationInfo(
  606. const UnresolvedSetImpl &Templates,
  607. const TemplateArgumentListInfo &TemplateArgs);
  608. public:
  609. friend TrailingObjects;
  610. static DependentFunctionTemplateSpecializationInfo *
  611. Create(ASTContext &Context, const UnresolvedSetImpl &Templates,
  612. const TemplateArgumentListInfo &TemplateArgs);
  613. /// Returns the number of function templates that this might
  614. /// be a specialization of.
  615. unsigned getNumTemplates() const { return NumTemplates; }
  616. /// Returns the i'th template candidate.
  617. FunctionTemplateDecl *getTemplate(unsigned I) const {
  618. assert(I < getNumTemplates() && "template index out of range");
  619. return getTrailingObjects<FunctionTemplateDecl *>()[I];
  620. }
  621. /// Returns the explicit template arguments that were given.
  622. const TemplateArgumentLoc *getTemplateArgs() const {
  623. return getTrailingObjects<TemplateArgumentLoc>();
  624. }
  625. /// Returns the number of explicit template arguments that were given.
  626. unsigned getNumTemplateArgs() const { return NumArgs; }
  627. llvm::ArrayRef<TemplateArgumentLoc> arguments() const {
  628. return llvm::ArrayRef(getTemplateArgs(), getNumTemplateArgs());
  629. }
  630. /// Returns the nth template argument.
  631. const TemplateArgumentLoc &getTemplateArg(unsigned I) const {
  632. assert(I < getNumTemplateArgs() && "template arg index out of range");
  633. return getTemplateArgs()[I];
  634. }
  635. SourceLocation getLAngleLoc() const {
  636. return AngleLocs.getBegin();
  637. }
  638. SourceLocation getRAngleLoc() const {
  639. return AngleLocs.getEnd();
  640. }
  641. };
  642. /// Declaration of a redeclarable template.
  643. class RedeclarableTemplateDecl : public TemplateDecl,
  644. public Redeclarable<RedeclarableTemplateDecl>
  645. {
  646. using redeclarable_base = Redeclarable<RedeclarableTemplateDecl>;
  647. RedeclarableTemplateDecl *getNextRedeclarationImpl() override {
  648. return getNextRedeclaration();
  649. }
  650. RedeclarableTemplateDecl *getPreviousDeclImpl() override {
  651. return getPreviousDecl();
  652. }
  653. RedeclarableTemplateDecl *getMostRecentDeclImpl() override {
  654. return getMostRecentDecl();
  655. }
  656. void anchor() override;
  657. protected:
  658. template <typename EntryType> struct SpecEntryTraits {
  659. using DeclType = EntryType;
  660. static DeclType *getDecl(EntryType *D) {
  661. return D;
  662. }
  663. static ArrayRef<TemplateArgument> getTemplateArgs(EntryType *D) {
  664. return D->getTemplateArgs().asArray();
  665. }
  666. };
  667. template <typename EntryType, typename SETraits = SpecEntryTraits<EntryType>,
  668. typename DeclType = typename SETraits::DeclType>
  669. struct SpecIterator
  670. : llvm::iterator_adaptor_base<
  671. SpecIterator<EntryType, SETraits, DeclType>,
  672. typename llvm::FoldingSetVector<EntryType>::iterator,
  673. typename std::iterator_traits<typename llvm::FoldingSetVector<
  674. EntryType>::iterator>::iterator_category,
  675. DeclType *, ptrdiff_t, DeclType *, DeclType *> {
  676. SpecIterator() = default;
  677. explicit SpecIterator(
  678. typename llvm::FoldingSetVector<EntryType>::iterator SetIter)
  679. : SpecIterator::iterator_adaptor_base(std::move(SetIter)) {}
  680. DeclType *operator*() const {
  681. return SETraits::getDecl(&*this->I)->getMostRecentDecl();
  682. }
  683. DeclType *operator->() const { return **this; }
  684. };
  685. template <typename EntryType>
  686. static SpecIterator<EntryType>
  687. makeSpecIterator(llvm::FoldingSetVector<EntryType> &Specs, bool isEnd) {
  688. return SpecIterator<EntryType>(isEnd ? Specs.end() : Specs.begin());
  689. }
  690. void loadLazySpecializationsImpl() const;
  691. template <class EntryType, typename ...ProfileArguments>
  692. typename SpecEntryTraits<EntryType>::DeclType*
  693. findSpecializationImpl(llvm::FoldingSetVector<EntryType> &Specs,
  694. void *&InsertPos, ProfileArguments &&...ProfileArgs);
  695. template <class Derived, class EntryType>
  696. void addSpecializationImpl(llvm::FoldingSetVector<EntryType> &Specs,
  697. EntryType *Entry, void *InsertPos);
  698. struct CommonBase {
  699. CommonBase() : InstantiatedFromMember(nullptr, false) {}
  700. /// The template from which this was most
  701. /// directly instantiated (or null).
  702. ///
  703. /// The boolean value indicates whether this template
  704. /// was explicitly specialized.
  705. llvm::PointerIntPair<RedeclarableTemplateDecl*, 1, bool>
  706. InstantiatedFromMember;
  707. /// If non-null, points to an array of specializations (including
  708. /// partial specializations) known only by their external declaration IDs.
  709. ///
  710. /// The first value in the array is the number of specializations/partial
  711. /// specializations that follow.
  712. uint32_t *LazySpecializations = nullptr;
  713. /// The set of "injected" template arguments used within this
  714. /// template.
  715. ///
  716. /// This pointer refers to the template arguments (there are as
  717. /// many template arguments as template parameaters) for the
  718. /// template, and is allocated lazily, since most templates do not
  719. /// require the use of this information.
  720. TemplateArgument *InjectedArgs = nullptr;
  721. };
  722. /// Pointer to the common data shared by all declarations of this
  723. /// template.
  724. mutable CommonBase *Common = nullptr;
  725. /// Retrieves the "common" pointer shared by all (re-)declarations of
  726. /// the same template. Calling this routine may implicitly allocate memory
  727. /// for the common pointer.
  728. CommonBase *getCommonPtr() const;
  729. virtual CommonBase *newCommon(ASTContext &C) const = 0;
  730. // Construct a template decl with name, parameters, and templated element.
  731. RedeclarableTemplateDecl(Kind DK, ASTContext &C, DeclContext *DC,
  732. SourceLocation L, DeclarationName Name,
  733. TemplateParameterList *Params, NamedDecl *Decl)
  734. : TemplateDecl(DK, DC, L, Name, Params, Decl), redeclarable_base(C) {}
  735. public:
  736. friend class ASTDeclReader;
  737. friend class ASTDeclWriter;
  738. friend class ASTReader;
  739. template <class decl_type> friend class RedeclarableTemplate;
  740. /// Retrieves the canonical declaration of this template.
  741. RedeclarableTemplateDecl *getCanonicalDecl() override {
  742. return getFirstDecl();
  743. }
  744. const RedeclarableTemplateDecl *getCanonicalDecl() const {
  745. return getFirstDecl();
  746. }
  747. /// Determines whether this template was a specialization of a
  748. /// member template.
  749. ///
  750. /// In the following example, the function template \c X<int>::f and the
  751. /// member template \c X<int>::Inner are member specializations.
  752. ///
  753. /// \code
  754. /// template<typename T>
  755. /// struct X {
  756. /// template<typename U> void f(T, U);
  757. /// template<typename U> struct Inner;
  758. /// };
  759. ///
  760. /// template<> template<typename T>
  761. /// void X<int>::f(int, T);
  762. /// template<> template<typename T>
  763. /// struct X<int>::Inner { /* ... */ };
  764. /// \endcode
  765. bool isMemberSpecialization() const {
  766. return getCommonPtr()->InstantiatedFromMember.getInt();
  767. }
  768. /// Note that this member template is a specialization.
  769. void setMemberSpecialization() {
  770. assert(getCommonPtr()->InstantiatedFromMember.getPointer() &&
  771. "Only member templates can be member template specializations");
  772. getCommonPtr()->InstantiatedFromMember.setInt(true);
  773. }
  774. /// Retrieve the member template from which this template was
  775. /// instantiated, or nullptr if this template was not instantiated from a
  776. /// member template.
  777. ///
  778. /// A template is instantiated from a member template when the member
  779. /// template itself is part of a class template (or member thereof). For
  780. /// example, given
  781. ///
  782. /// \code
  783. /// template<typename T>
  784. /// struct X {
  785. /// template<typename U> void f(T, U);
  786. /// };
  787. ///
  788. /// void test(X<int> x) {
  789. /// x.f(1, 'a');
  790. /// };
  791. /// \endcode
  792. ///
  793. /// \c X<int>::f is a FunctionTemplateDecl that describes the function
  794. /// template
  795. ///
  796. /// \code
  797. /// template<typename U> void X<int>::f(int, U);
  798. /// \endcode
  799. ///
  800. /// which was itself created during the instantiation of \c X<int>. Calling
  801. /// getInstantiatedFromMemberTemplate() on this FunctionTemplateDecl will
  802. /// retrieve the FunctionTemplateDecl for the original template \c f within
  803. /// the class template \c X<T>, i.e.,
  804. ///
  805. /// \code
  806. /// template<typename T>
  807. /// template<typename U>
  808. /// void X<T>::f(T, U);
  809. /// \endcode
  810. RedeclarableTemplateDecl *getInstantiatedFromMemberTemplate() const {
  811. return getCommonPtr()->InstantiatedFromMember.getPointer();
  812. }
  813. void setInstantiatedFromMemberTemplate(RedeclarableTemplateDecl *TD) {
  814. assert(!getCommonPtr()->InstantiatedFromMember.getPointer());
  815. getCommonPtr()->InstantiatedFromMember.setPointer(TD);
  816. }
  817. /// Retrieve the "injected" template arguments that correspond to the
  818. /// template parameters of this template.
  819. ///
  820. /// Although the C++ standard has no notion of the "injected" template
  821. /// arguments for a template, the notion is convenient when
  822. /// we need to perform substitutions inside the definition of a template.
  823. ArrayRef<TemplateArgument> getInjectedTemplateArgs();
  824. using redecl_range = redeclarable_base::redecl_range;
  825. using redecl_iterator = redeclarable_base::redecl_iterator;
  826. using redeclarable_base::redecls_begin;
  827. using redeclarable_base::redecls_end;
  828. using redeclarable_base::redecls;
  829. using redeclarable_base::getPreviousDecl;
  830. using redeclarable_base::getMostRecentDecl;
  831. using redeclarable_base::isFirstDecl;
  832. // Implement isa/cast/dyncast/etc.
  833. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  834. static bool classofKind(Kind K) {
  835. return K >= firstRedeclarableTemplate && K <= lastRedeclarableTemplate;
  836. }
  837. };
  838. template <> struct RedeclarableTemplateDecl::
  839. SpecEntryTraits<FunctionTemplateSpecializationInfo> {
  840. using DeclType = FunctionDecl;
  841. static DeclType *getDecl(FunctionTemplateSpecializationInfo *I) {
  842. return I->getFunction();
  843. }
  844. static ArrayRef<TemplateArgument>
  845. getTemplateArgs(FunctionTemplateSpecializationInfo *I) {
  846. return I->TemplateArguments->asArray();
  847. }
  848. };
  849. /// Declaration of a template function.
  850. class FunctionTemplateDecl : public RedeclarableTemplateDecl {
  851. protected:
  852. friend class FunctionDecl;
  853. /// Data that is common to all of the declarations of a given
  854. /// function template.
  855. struct Common : CommonBase {
  856. /// The function template specializations for this function
  857. /// template, including explicit specializations and instantiations.
  858. llvm::FoldingSetVector<FunctionTemplateSpecializationInfo> Specializations;
  859. Common() = default;
  860. };
  861. FunctionTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
  862. DeclarationName Name, TemplateParameterList *Params,
  863. NamedDecl *Decl)
  864. : RedeclarableTemplateDecl(FunctionTemplate, C, DC, L, Name, Params,
  865. Decl) {}
  866. CommonBase *newCommon(ASTContext &C) const override;
  867. Common *getCommonPtr() const {
  868. return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
  869. }
  870. /// Retrieve the set of function template specializations of this
  871. /// function template.
  872. llvm::FoldingSetVector<FunctionTemplateSpecializationInfo> &
  873. getSpecializations() const;
  874. /// Add a specialization of this function template.
  875. ///
  876. /// \param InsertPos Insert position in the FoldingSetVector, must have been
  877. /// retrieved by an earlier call to findSpecialization().
  878. void addSpecialization(FunctionTemplateSpecializationInfo* Info,
  879. void *InsertPos);
  880. public:
  881. friend class ASTDeclReader;
  882. friend class ASTDeclWriter;
  883. /// Load any lazily-loaded specializations from the external source.
  884. void LoadLazySpecializations() const;
  885. /// Get the underlying function declaration of the template.
  886. FunctionDecl *getTemplatedDecl() const {
  887. return static_cast<FunctionDecl *>(TemplatedDecl);
  888. }
  889. /// Returns whether this template declaration defines the primary
  890. /// pattern.
  891. bool isThisDeclarationADefinition() const {
  892. return getTemplatedDecl()->isThisDeclarationADefinition();
  893. }
  894. /// Return the specialization with the provided arguments if it exists,
  895. /// otherwise return the insertion point.
  896. FunctionDecl *findSpecialization(ArrayRef<TemplateArgument> Args,
  897. void *&InsertPos);
  898. FunctionTemplateDecl *getCanonicalDecl() override {
  899. return cast<FunctionTemplateDecl>(
  900. RedeclarableTemplateDecl::getCanonicalDecl());
  901. }
  902. const FunctionTemplateDecl *getCanonicalDecl() const {
  903. return cast<FunctionTemplateDecl>(
  904. RedeclarableTemplateDecl::getCanonicalDecl());
  905. }
  906. /// Retrieve the previous declaration of this function template, or
  907. /// nullptr if no such declaration exists.
  908. FunctionTemplateDecl *getPreviousDecl() {
  909. return cast_or_null<FunctionTemplateDecl>(
  910. static_cast<RedeclarableTemplateDecl *>(this)->getPreviousDecl());
  911. }
  912. const FunctionTemplateDecl *getPreviousDecl() const {
  913. return cast_or_null<FunctionTemplateDecl>(
  914. static_cast<const RedeclarableTemplateDecl *>(this)->getPreviousDecl());
  915. }
  916. FunctionTemplateDecl *getMostRecentDecl() {
  917. return cast<FunctionTemplateDecl>(
  918. static_cast<RedeclarableTemplateDecl *>(this)
  919. ->getMostRecentDecl());
  920. }
  921. const FunctionTemplateDecl *getMostRecentDecl() const {
  922. return const_cast<FunctionTemplateDecl*>(this)->getMostRecentDecl();
  923. }
  924. FunctionTemplateDecl *getInstantiatedFromMemberTemplate() const {
  925. return cast_or_null<FunctionTemplateDecl>(
  926. RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
  927. }
  928. using spec_iterator = SpecIterator<FunctionTemplateSpecializationInfo>;
  929. using spec_range = llvm::iterator_range<spec_iterator>;
  930. spec_range specializations() const {
  931. return spec_range(spec_begin(), spec_end());
  932. }
  933. spec_iterator spec_begin() const {
  934. return makeSpecIterator(getSpecializations(), false);
  935. }
  936. spec_iterator spec_end() const {
  937. return makeSpecIterator(getSpecializations(), true);
  938. }
  939. /// Return whether this function template is an abbreviated function template,
  940. /// e.g. `void foo(auto x)` or `template<typename T> void foo(auto x)`
  941. bool isAbbreviated() const {
  942. // Since the invented template parameters generated from 'auto' parameters
  943. // are either appended to the end of the explicit template parameter list or
  944. // form a new template parameter list, we can simply observe the last
  945. // parameter to determine if such a thing happened.
  946. const TemplateParameterList *TPL = getTemplateParameters();
  947. return TPL->getParam(TPL->size() - 1)->isImplicit();
  948. }
  949. /// Merge \p Prev with our RedeclarableTemplateDecl::Common.
  950. void mergePrevDecl(FunctionTemplateDecl *Prev);
  951. /// Create a function template node.
  952. static FunctionTemplateDecl *Create(ASTContext &C, DeclContext *DC,
  953. SourceLocation L,
  954. DeclarationName Name,
  955. TemplateParameterList *Params,
  956. NamedDecl *Decl);
  957. /// Create an empty function template node.
  958. static FunctionTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
  959. // Implement isa/cast/dyncast support
  960. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  961. static bool classofKind(Kind K) { return K == FunctionTemplate; }
  962. };
  963. //===----------------------------------------------------------------------===//
  964. // Kinds of Template Parameters
  965. //===----------------------------------------------------------------------===//
  966. /// Defines the position of a template parameter within a template
  967. /// parameter list.
  968. ///
  969. /// Because template parameter can be listed
  970. /// sequentially for out-of-line template members, each template parameter is
  971. /// given a Depth - the nesting of template parameter scopes - and a Position -
  972. /// the occurrence within the parameter list.
  973. /// This class is inheritedly privately by different kinds of template
  974. /// parameters and is not part of the Decl hierarchy. Just a facility.
  975. class TemplateParmPosition {
  976. protected:
  977. enum { DepthWidth = 20, PositionWidth = 12 };
  978. unsigned Depth : DepthWidth;
  979. unsigned Position : PositionWidth;
  980. static constexpr unsigned MaxDepth = (1U << DepthWidth) - 1;
  981. static constexpr unsigned MaxPosition = (1U << PositionWidth) - 1;
  982. TemplateParmPosition(unsigned D, unsigned P) : Depth(D), Position(P) {
  983. // The input may fill maximum values to show that it is invalid.
  984. // Add one here to convert it to zero.
  985. assert((D + 1) <= MaxDepth &&
  986. "The depth of template parmeter position is more than 2^20!");
  987. assert((P + 1) <= MaxPosition &&
  988. "The position of template parmeter position is more than 2^12!");
  989. }
  990. public:
  991. TemplateParmPosition() = delete;
  992. /// Get the nesting depth of the template parameter.
  993. unsigned getDepth() const { return Depth; }
  994. void setDepth(unsigned D) {
  995. assert((D + 1) <= MaxDepth &&
  996. "The depth of template parmeter position is more than 2^20!");
  997. Depth = D;
  998. }
  999. /// Get the position of the template parameter within its parameter list.
  1000. unsigned getPosition() const { return Position; }
  1001. void setPosition(unsigned P) {
  1002. assert((P + 1) <= MaxPosition &&
  1003. "The position of template parmeter position is more than 2^12!");
  1004. Position = P;
  1005. }
  1006. /// Get the index of the template parameter within its parameter list.
  1007. unsigned getIndex() const { return Position; }
  1008. };
  1009. /// Declaration of a template type parameter.
  1010. ///
  1011. /// For example, "T" in
  1012. /// \code
  1013. /// template<typename T> class vector;
  1014. /// \endcode
  1015. class TemplateTypeParmDecl final : public TypeDecl,
  1016. private llvm::TrailingObjects<TemplateTypeParmDecl, TypeConstraint> {
  1017. /// Sema creates these on the stack during auto type deduction.
  1018. friend class Sema;
  1019. friend TrailingObjects;
  1020. friend class ASTDeclReader;
  1021. /// Whether this template type parameter was declaration with
  1022. /// the 'typename' keyword.
  1023. ///
  1024. /// If false, it was declared with the 'class' keyword.
  1025. bool Typename : 1;
  1026. /// Whether this template type parameter has a type-constraint construct.
  1027. bool HasTypeConstraint : 1;
  1028. /// Whether the type constraint has been initialized. This can be false if the
  1029. /// constraint was not initialized yet or if there was an error forming the
  1030. /// type constraint.
  1031. bool TypeConstraintInitialized : 1;
  1032. /// Whether this type template parameter is an "expanded"
  1033. /// parameter pack, meaning that its type is a pack expansion and we
  1034. /// already know the set of types that expansion expands to.
  1035. bool ExpandedParameterPack : 1;
  1036. /// The number of type parameters in an expanded parameter pack.
  1037. unsigned NumExpanded = 0;
  1038. /// The default template argument, if any.
  1039. using DefArgStorage =
  1040. DefaultArgStorage<TemplateTypeParmDecl, TypeSourceInfo *>;
  1041. DefArgStorage DefaultArgument;
  1042. TemplateTypeParmDecl(DeclContext *DC, SourceLocation KeyLoc,
  1043. SourceLocation IdLoc, IdentifierInfo *Id, bool Typename,
  1044. bool HasTypeConstraint,
  1045. std::optional<unsigned> NumExpanded)
  1046. : TypeDecl(TemplateTypeParm, DC, IdLoc, Id, KeyLoc), Typename(Typename),
  1047. HasTypeConstraint(HasTypeConstraint), TypeConstraintInitialized(false),
  1048. ExpandedParameterPack(NumExpanded),
  1049. NumExpanded(NumExpanded.value_or(0)) {}
  1050. public:
  1051. static TemplateTypeParmDecl *
  1052. Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc,
  1053. SourceLocation NameLoc, unsigned D, unsigned P, IdentifierInfo *Id,
  1054. bool Typename, bool ParameterPack, bool HasTypeConstraint = false,
  1055. std::optional<unsigned> NumExpanded = std::nullopt);
  1056. static TemplateTypeParmDecl *CreateDeserialized(const ASTContext &C,
  1057. unsigned ID);
  1058. static TemplateTypeParmDecl *CreateDeserialized(const ASTContext &C,
  1059. unsigned ID,
  1060. bool HasTypeConstraint);
  1061. /// Whether this template type parameter was declared with
  1062. /// the 'typename' keyword.
  1063. ///
  1064. /// If not, it was either declared with the 'class' keyword or with a
  1065. /// type-constraint (see hasTypeConstraint()).
  1066. bool wasDeclaredWithTypename() const {
  1067. return Typename && !HasTypeConstraint;
  1068. }
  1069. const DefArgStorage &getDefaultArgStorage() const { return DefaultArgument; }
  1070. /// Determine whether this template parameter has a default
  1071. /// argument.
  1072. bool hasDefaultArgument() const { return DefaultArgument.isSet(); }
  1073. /// Retrieve the default argument, if any.
  1074. QualType getDefaultArgument() const {
  1075. return DefaultArgument.get()->getType();
  1076. }
  1077. /// Retrieves the default argument's source information, if any.
  1078. TypeSourceInfo *getDefaultArgumentInfo() const {
  1079. return DefaultArgument.get();
  1080. }
  1081. /// Retrieves the location of the default argument declaration.
  1082. SourceLocation getDefaultArgumentLoc() const;
  1083. /// Determines whether the default argument was inherited
  1084. /// from a previous declaration of this template.
  1085. bool defaultArgumentWasInherited() const {
  1086. return DefaultArgument.isInherited();
  1087. }
  1088. /// Set the default argument for this template parameter.
  1089. void setDefaultArgument(TypeSourceInfo *DefArg) {
  1090. DefaultArgument.set(DefArg);
  1091. }
  1092. /// Set that this default argument was inherited from another
  1093. /// parameter.
  1094. void setInheritedDefaultArgument(const ASTContext &C,
  1095. TemplateTypeParmDecl *Prev) {
  1096. DefaultArgument.setInherited(C, Prev);
  1097. }
  1098. /// Removes the default argument of this template parameter.
  1099. void removeDefaultArgument() {
  1100. DefaultArgument.clear();
  1101. }
  1102. /// Set whether this template type parameter was declared with
  1103. /// the 'typename' or 'class' keyword.
  1104. void setDeclaredWithTypename(bool withTypename) { Typename = withTypename; }
  1105. /// Retrieve the depth of the template parameter.
  1106. unsigned getDepth() const;
  1107. /// Retrieve the index of the template parameter.
  1108. unsigned getIndex() const;
  1109. /// Returns whether this is a parameter pack.
  1110. bool isParameterPack() const;
  1111. /// Whether this parameter pack is a pack expansion.
  1112. ///
  1113. /// A template type template parameter pack can be a pack expansion if its
  1114. /// type-constraint contains an unexpanded parameter pack.
  1115. bool isPackExpansion() const {
  1116. if (!isParameterPack())
  1117. return false;
  1118. if (const TypeConstraint *TC = getTypeConstraint())
  1119. if (TC->hasExplicitTemplateArgs())
  1120. for (const auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
  1121. if (ArgLoc.getArgument().containsUnexpandedParameterPack())
  1122. return true;
  1123. return false;
  1124. }
  1125. /// Whether this parameter is a template type parameter pack that has a known
  1126. /// list of different type-constraints at different positions.
  1127. ///
  1128. /// A parameter pack is an expanded parameter pack when the original
  1129. /// parameter pack's type-constraint was itself a pack expansion, and that
  1130. /// expansion has already been expanded. For example, given:
  1131. ///
  1132. /// \code
  1133. /// template<typename ...Types>
  1134. /// struct X {
  1135. /// template<convertible_to<Types> ...Convertibles>
  1136. /// struct Y { /* ... */ };
  1137. /// };
  1138. /// \endcode
  1139. ///
  1140. /// The parameter pack \c Convertibles has (convertible_to<Types> && ...) as
  1141. /// its type-constraint. When \c Types is supplied with template arguments by
  1142. /// instantiating \c X, the instantiation of \c Convertibles becomes an
  1143. /// expanded parameter pack. For example, instantiating
  1144. /// \c X<int, unsigned int> results in \c Convertibles being an expanded
  1145. /// parameter pack of size 2 (use getNumExpansionTypes() to get this number).
  1146. bool isExpandedParameterPack() const { return ExpandedParameterPack; }
  1147. /// Retrieves the number of parameters in an expanded parameter pack.
  1148. unsigned getNumExpansionParameters() const {
  1149. assert(ExpandedParameterPack && "Not an expansion parameter pack");
  1150. return NumExpanded;
  1151. }
  1152. /// Returns the type constraint associated with this template parameter (if
  1153. /// any).
  1154. const TypeConstraint *getTypeConstraint() const {
  1155. return TypeConstraintInitialized ? getTrailingObjects<TypeConstraint>() :
  1156. nullptr;
  1157. }
  1158. void setTypeConstraint(NestedNameSpecifierLoc NNS,
  1159. DeclarationNameInfo NameInfo, NamedDecl *FoundDecl,
  1160. ConceptDecl *CD,
  1161. const ASTTemplateArgumentListInfo *ArgsAsWritten,
  1162. Expr *ImmediatelyDeclaredConstraint);
  1163. /// Determine whether this template parameter has a type-constraint.
  1164. bool hasTypeConstraint() const {
  1165. return HasTypeConstraint;
  1166. }
  1167. /// \brief Get the associated-constraints of this template parameter.
  1168. /// This will either be the immediately-introduced constraint or empty.
  1169. ///
  1170. /// Use this instead of getTypeConstraint for concepts APIs that
  1171. /// accept an ArrayRef of constraint expressions.
  1172. void getAssociatedConstraints(llvm::SmallVectorImpl<const Expr *> &AC) const {
  1173. if (HasTypeConstraint)
  1174. AC.push_back(getTypeConstraint()->getImmediatelyDeclaredConstraint());
  1175. }
  1176. SourceRange getSourceRange() const override LLVM_READONLY;
  1177. // Implement isa/cast/dyncast/etc.
  1178. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  1179. static bool classofKind(Kind K) { return K == TemplateTypeParm; }
  1180. };
  1181. /// NonTypeTemplateParmDecl - Declares a non-type template parameter,
  1182. /// e.g., "Size" in
  1183. /// @code
  1184. /// template<int Size> class array { };
  1185. /// @endcode
  1186. class NonTypeTemplateParmDecl final
  1187. : public DeclaratorDecl,
  1188. protected TemplateParmPosition,
  1189. private llvm::TrailingObjects<NonTypeTemplateParmDecl,
  1190. std::pair<QualType, TypeSourceInfo *>,
  1191. Expr *> {
  1192. friend class ASTDeclReader;
  1193. friend TrailingObjects;
  1194. /// The default template argument, if any, and whether or not
  1195. /// it was inherited.
  1196. using DefArgStorage = DefaultArgStorage<NonTypeTemplateParmDecl, Expr *>;
  1197. DefArgStorage DefaultArgument;
  1198. // FIXME: Collapse this into TemplateParamPosition; or, just move depth/index
  1199. // down here to save memory.
  1200. /// Whether this non-type template parameter is a parameter pack.
  1201. bool ParameterPack;
  1202. /// Whether this non-type template parameter is an "expanded"
  1203. /// parameter pack, meaning that its type is a pack expansion and we
  1204. /// already know the set of types that expansion expands to.
  1205. bool ExpandedParameterPack = false;
  1206. /// The number of types in an expanded parameter pack.
  1207. unsigned NumExpandedTypes = 0;
  1208. size_t numTrailingObjects(
  1209. OverloadToken<std::pair<QualType, TypeSourceInfo *>>) const {
  1210. return NumExpandedTypes;
  1211. }
  1212. NonTypeTemplateParmDecl(DeclContext *DC, SourceLocation StartLoc,
  1213. SourceLocation IdLoc, unsigned D, unsigned P,
  1214. IdentifierInfo *Id, QualType T,
  1215. bool ParameterPack, TypeSourceInfo *TInfo)
  1216. : DeclaratorDecl(NonTypeTemplateParm, DC, IdLoc, Id, T, TInfo, StartLoc),
  1217. TemplateParmPosition(D, P), ParameterPack(ParameterPack) {}
  1218. NonTypeTemplateParmDecl(DeclContext *DC, SourceLocation StartLoc,
  1219. SourceLocation IdLoc, unsigned D, unsigned P,
  1220. IdentifierInfo *Id, QualType T,
  1221. TypeSourceInfo *TInfo,
  1222. ArrayRef<QualType> ExpandedTypes,
  1223. ArrayRef<TypeSourceInfo *> ExpandedTInfos);
  1224. public:
  1225. static NonTypeTemplateParmDecl *
  1226. Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
  1227. SourceLocation IdLoc, unsigned D, unsigned P, IdentifierInfo *Id,
  1228. QualType T, bool ParameterPack, TypeSourceInfo *TInfo);
  1229. static NonTypeTemplateParmDecl *
  1230. Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
  1231. SourceLocation IdLoc, unsigned D, unsigned P, IdentifierInfo *Id,
  1232. QualType T, TypeSourceInfo *TInfo, ArrayRef<QualType> ExpandedTypes,
  1233. ArrayRef<TypeSourceInfo *> ExpandedTInfos);
  1234. static NonTypeTemplateParmDecl *CreateDeserialized(ASTContext &C,
  1235. unsigned ID,
  1236. bool HasTypeConstraint);
  1237. static NonTypeTemplateParmDecl *CreateDeserialized(ASTContext &C,
  1238. unsigned ID,
  1239. unsigned NumExpandedTypes,
  1240. bool HasTypeConstraint);
  1241. using TemplateParmPosition::getDepth;
  1242. using TemplateParmPosition::setDepth;
  1243. using TemplateParmPosition::getPosition;
  1244. using TemplateParmPosition::setPosition;
  1245. using TemplateParmPosition::getIndex;
  1246. SourceRange getSourceRange() const override LLVM_READONLY;
  1247. const DefArgStorage &getDefaultArgStorage() const { return DefaultArgument; }
  1248. /// Determine whether this template parameter has a default
  1249. /// argument.
  1250. bool hasDefaultArgument() const { return DefaultArgument.isSet(); }
  1251. /// Retrieve the default argument, if any.
  1252. Expr *getDefaultArgument() const { return DefaultArgument.get(); }
  1253. /// Retrieve the location of the default argument, if any.
  1254. SourceLocation getDefaultArgumentLoc() const;
  1255. /// Determines whether the default argument was inherited
  1256. /// from a previous declaration of this template.
  1257. bool defaultArgumentWasInherited() const {
  1258. return DefaultArgument.isInherited();
  1259. }
  1260. /// Set the default argument for this template parameter, and
  1261. /// whether that default argument was inherited from another
  1262. /// declaration.
  1263. void setDefaultArgument(Expr *DefArg) { DefaultArgument.set(DefArg); }
  1264. void setInheritedDefaultArgument(const ASTContext &C,
  1265. NonTypeTemplateParmDecl *Parm) {
  1266. DefaultArgument.setInherited(C, Parm);
  1267. }
  1268. /// Removes the default argument of this template parameter.
  1269. void removeDefaultArgument() { DefaultArgument.clear(); }
  1270. /// Whether this parameter is a non-type template parameter pack.
  1271. ///
  1272. /// If the parameter is a parameter pack, the type may be a
  1273. /// \c PackExpansionType. In the following example, the \c Dims parameter
  1274. /// is a parameter pack (whose type is 'unsigned').
  1275. ///
  1276. /// \code
  1277. /// template<typename T, unsigned ...Dims> struct multi_array;
  1278. /// \endcode
  1279. bool isParameterPack() const { return ParameterPack; }
  1280. /// Whether this parameter pack is a pack expansion.
  1281. ///
  1282. /// A non-type template parameter pack is a pack expansion if its type
  1283. /// contains an unexpanded parameter pack. In this case, we will have
  1284. /// built a PackExpansionType wrapping the type.
  1285. bool isPackExpansion() const {
  1286. return ParameterPack && getType()->getAs<PackExpansionType>();
  1287. }
  1288. /// Whether this parameter is a non-type template parameter pack
  1289. /// that has a known list of different types at different positions.
  1290. ///
  1291. /// A parameter pack is an expanded parameter pack when the original
  1292. /// parameter pack's type was itself a pack expansion, and that expansion
  1293. /// has already been expanded. For example, given:
  1294. ///
  1295. /// \code
  1296. /// template<typename ...Types>
  1297. /// struct X {
  1298. /// template<Types ...Values>
  1299. /// struct Y { /* ... */ };
  1300. /// };
  1301. /// \endcode
  1302. ///
  1303. /// The parameter pack \c Values has a \c PackExpansionType as its type,
  1304. /// which expands \c Types. When \c Types is supplied with template arguments
  1305. /// by instantiating \c X, the instantiation of \c Values becomes an
  1306. /// expanded parameter pack. For example, instantiating
  1307. /// \c X<int, unsigned int> results in \c Values being an expanded parameter
  1308. /// pack with expansion types \c int and \c unsigned int.
  1309. ///
  1310. /// The \c getExpansionType() and \c getExpansionTypeSourceInfo() functions
  1311. /// return the expansion types.
  1312. bool isExpandedParameterPack() const { return ExpandedParameterPack; }
  1313. /// Retrieves the number of expansion types in an expanded parameter
  1314. /// pack.
  1315. unsigned getNumExpansionTypes() const {
  1316. assert(ExpandedParameterPack && "Not an expansion parameter pack");
  1317. return NumExpandedTypes;
  1318. }
  1319. /// Retrieve a particular expansion type within an expanded parameter
  1320. /// pack.
  1321. QualType getExpansionType(unsigned I) const {
  1322. assert(I < NumExpandedTypes && "Out-of-range expansion type index");
  1323. auto TypesAndInfos =
  1324. getTrailingObjects<std::pair<QualType, TypeSourceInfo *>>();
  1325. return TypesAndInfos[I].first;
  1326. }
  1327. /// Retrieve a particular expansion type source info within an
  1328. /// expanded parameter pack.
  1329. TypeSourceInfo *getExpansionTypeSourceInfo(unsigned I) const {
  1330. assert(I < NumExpandedTypes && "Out-of-range expansion type index");
  1331. auto TypesAndInfos =
  1332. getTrailingObjects<std::pair<QualType, TypeSourceInfo *>>();
  1333. return TypesAndInfos[I].second;
  1334. }
  1335. /// Return the constraint introduced by the placeholder type of this non-type
  1336. /// template parameter (if any).
  1337. Expr *getPlaceholderTypeConstraint() const {
  1338. return hasPlaceholderTypeConstraint() ? *getTrailingObjects<Expr *>() :
  1339. nullptr;
  1340. }
  1341. void setPlaceholderTypeConstraint(Expr *E) {
  1342. *getTrailingObjects<Expr *>() = E;
  1343. }
  1344. /// Determine whether this non-type template parameter's type has a
  1345. /// placeholder with a type-constraint.
  1346. bool hasPlaceholderTypeConstraint() const {
  1347. auto *AT = getType()->getContainedAutoType();
  1348. return AT && AT->isConstrained();
  1349. }
  1350. /// \brief Get the associated-constraints of this template parameter.
  1351. /// This will either be a vector of size 1 containing the immediately-declared
  1352. /// constraint introduced by the placeholder type, or an empty vector.
  1353. ///
  1354. /// Use this instead of getPlaceholderImmediatelyDeclaredConstraint for
  1355. /// concepts APIs that accept an ArrayRef of constraint expressions.
  1356. void getAssociatedConstraints(llvm::SmallVectorImpl<const Expr *> &AC) const {
  1357. if (Expr *E = getPlaceholderTypeConstraint())
  1358. AC.push_back(E);
  1359. }
  1360. // Implement isa/cast/dyncast/etc.
  1361. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  1362. static bool classofKind(Kind K) { return K == NonTypeTemplateParm; }
  1363. };
  1364. /// TemplateTemplateParmDecl - Declares a template template parameter,
  1365. /// e.g., "T" in
  1366. /// @code
  1367. /// template <template <typename> class T> class container { };
  1368. /// @endcode
  1369. /// A template template parameter is a TemplateDecl because it defines the
  1370. /// name of a template and the template parameters allowable for substitution.
  1371. class TemplateTemplateParmDecl final
  1372. : public TemplateDecl,
  1373. protected TemplateParmPosition,
  1374. private llvm::TrailingObjects<TemplateTemplateParmDecl,
  1375. TemplateParameterList *> {
  1376. /// The default template argument, if any.
  1377. using DefArgStorage =
  1378. DefaultArgStorage<TemplateTemplateParmDecl, TemplateArgumentLoc *>;
  1379. DefArgStorage DefaultArgument;
  1380. /// Whether this parameter is a parameter pack.
  1381. bool ParameterPack;
  1382. /// Whether this template template parameter is an "expanded"
  1383. /// parameter pack, meaning that it is a pack expansion and we
  1384. /// already know the set of template parameters that expansion expands to.
  1385. bool ExpandedParameterPack = false;
  1386. /// The number of parameters in an expanded parameter pack.
  1387. unsigned NumExpandedParams = 0;
  1388. TemplateTemplateParmDecl(DeclContext *DC, SourceLocation L,
  1389. unsigned D, unsigned P, bool ParameterPack,
  1390. IdentifierInfo *Id, TemplateParameterList *Params)
  1391. : TemplateDecl(TemplateTemplateParm, DC, L, Id, Params),
  1392. TemplateParmPosition(D, P), ParameterPack(ParameterPack) {}
  1393. TemplateTemplateParmDecl(DeclContext *DC, SourceLocation L,
  1394. unsigned D, unsigned P,
  1395. IdentifierInfo *Id, TemplateParameterList *Params,
  1396. ArrayRef<TemplateParameterList *> Expansions);
  1397. void anchor() override;
  1398. public:
  1399. friend class ASTDeclReader;
  1400. friend class ASTDeclWriter;
  1401. friend TrailingObjects;
  1402. static TemplateTemplateParmDecl *Create(const ASTContext &C, DeclContext *DC,
  1403. SourceLocation L, unsigned D,
  1404. unsigned P, bool ParameterPack,
  1405. IdentifierInfo *Id,
  1406. TemplateParameterList *Params);
  1407. static TemplateTemplateParmDecl *Create(const ASTContext &C, DeclContext *DC,
  1408. SourceLocation L, unsigned D,
  1409. unsigned P,
  1410. IdentifierInfo *Id,
  1411. TemplateParameterList *Params,
  1412. ArrayRef<TemplateParameterList *> Expansions);
  1413. static TemplateTemplateParmDecl *CreateDeserialized(ASTContext &C,
  1414. unsigned ID);
  1415. static TemplateTemplateParmDecl *CreateDeserialized(ASTContext &C,
  1416. unsigned ID,
  1417. unsigned NumExpansions);
  1418. using TemplateParmPosition::getDepth;
  1419. using TemplateParmPosition::setDepth;
  1420. using TemplateParmPosition::getPosition;
  1421. using TemplateParmPosition::setPosition;
  1422. using TemplateParmPosition::getIndex;
  1423. /// Whether this template template parameter is a template
  1424. /// parameter pack.
  1425. ///
  1426. /// \code
  1427. /// template<template <class T> ...MetaFunctions> struct Apply;
  1428. /// \endcode
  1429. bool isParameterPack() const { return ParameterPack; }
  1430. /// Whether this parameter pack is a pack expansion.
  1431. ///
  1432. /// A template template parameter pack is a pack expansion if its template
  1433. /// parameter list contains an unexpanded parameter pack.
  1434. bool isPackExpansion() const {
  1435. return ParameterPack &&
  1436. getTemplateParameters()->containsUnexpandedParameterPack();
  1437. }
  1438. /// Whether this parameter is a template template parameter pack that
  1439. /// has a known list of different template parameter lists at different
  1440. /// positions.
  1441. ///
  1442. /// A parameter pack is an expanded parameter pack when the original parameter
  1443. /// pack's template parameter list was itself a pack expansion, and that
  1444. /// expansion has already been expanded. For exampe, given:
  1445. ///
  1446. /// \code
  1447. /// template<typename...Types> struct Outer {
  1448. /// template<template<Types> class...Templates> struct Inner;
  1449. /// };
  1450. /// \endcode
  1451. ///
  1452. /// The parameter pack \c Templates is a pack expansion, which expands the
  1453. /// pack \c Types. When \c Types is supplied with template arguments by
  1454. /// instantiating \c Outer, the instantiation of \c Templates is an expanded
  1455. /// parameter pack.
  1456. bool isExpandedParameterPack() const { return ExpandedParameterPack; }
  1457. /// Retrieves the number of expansion template parameters in
  1458. /// an expanded parameter pack.
  1459. unsigned getNumExpansionTemplateParameters() const {
  1460. assert(ExpandedParameterPack && "Not an expansion parameter pack");
  1461. return NumExpandedParams;
  1462. }
  1463. /// Retrieve a particular expansion type within an expanded parameter
  1464. /// pack.
  1465. TemplateParameterList *getExpansionTemplateParameters(unsigned I) const {
  1466. assert(I < NumExpandedParams && "Out-of-range expansion type index");
  1467. return getTrailingObjects<TemplateParameterList *>()[I];
  1468. }
  1469. const DefArgStorage &getDefaultArgStorage() const { return DefaultArgument; }
  1470. /// Determine whether this template parameter has a default
  1471. /// argument.
  1472. bool hasDefaultArgument() const { return DefaultArgument.isSet(); }
  1473. /// Retrieve the default argument, if any.
  1474. const TemplateArgumentLoc &getDefaultArgument() const {
  1475. static const TemplateArgumentLoc NoneLoc;
  1476. return DefaultArgument.isSet() ? *DefaultArgument.get() : NoneLoc;
  1477. }
  1478. /// Retrieve the location of the default argument, if any.
  1479. SourceLocation getDefaultArgumentLoc() const;
  1480. /// Determines whether the default argument was inherited
  1481. /// from a previous declaration of this template.
  1482. bool defaultArgumentWasInherited() const {
  1483. return DefaultArgument.isInherited();
  1484. }
  1485. /// Set the default argument for this template parameter, and
  1486. /// whether that default argument was inherited from another
  1487. /// declaration.
  1488. void setDefaultArgument(const ASTContext &C,
  1489. const TemplateArgumentLoc &DefArg);
  1490. void setInheritedDefaultArgument(const ASTContext &C,
  1491. TemplateTemplateParmDecl *Prev) {
  1492. DefaultArgument.setInherited(C, Prev);
  1493. }
  1494. /// Removes the default argument of this template parameter.
  1495. void removeDefaultArgument() { DefaultArgument.clear(); }
  1496. SourceRange getSourceRange() const override LLVM_READONLY {
  1497. SourceLocation End = getLocation();
  1498. if (hasDefaultArgument() && !defaultArgumentWasInherited())
  1499. End = getDefaultArgument().getSourceRange().getEnd();
  1500. return SourceRange(getTemplateParameters()->getTemplateLoc(), End);
  1501. }
  1502. // Implement isa/cast/dyncast/etc.
  1503. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  1504. static bool classofKind(Kind K) { return K == TemplateTemplateParm; }
  1505. };
  1506. /// Represents the builtin template declaration which is used to
  1507. /// implement __make_integer_seq and other builtin templates. It serves
  1508. /// no real purpose beyond existing as a place to hold template parameters.
  1509. class BuiltinTemplateDecl : public TemplateDecl {
  1510. BuiltinTemplateKind BTK;
  1511. BuiltinTemplateDecl(const ASTContext &C, DeclContext *DC,
  1512. DeclarationName Name, BuiltinTemplateKind BTK);
  1513. void anchor() override;
  1514. public:
  1515. // Implement isa/cast/dyncast support
  1516. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  1517. static bool classofKind(Kind K) { return K == BuiltinTemplate; }
  1518. static BuiltinTemplateDecl *Create(const ASTContext &C, DeclContext *DC,
  1519. DeclarationName Name,
  1520. BuiltinTemplateKind BTK) {
  1521. return new (C, DC) BuiltinTemplateDecl(C, DC, Name, BTK);
  1522. }
  1523. SourceRange getSourceRange() const override LLVM_READONLY {
  1524. return {};
  1525. }
  1526. BuiltinTemplateKind getBuiltinTemplateKind() const { return BTK; }
  1527. };
  1528. /// Represents a class template specialization, which refers to
  1529. /// a class template with a given set of template arguments.
  1530. ///
  1531. /// Class template specializations represent both explicit
  1532. /// specialization of class templates, as in the example below, and
  1533. /// implicit instantiations of class templates.
  1534. ///
  1535. /// \code
  1536. /// template<typename T> class array;
  1537. ///
  1538. /// template<>
  1539. /// class array<bool> { }; // class template specialization array<bool>
  1540. /// \endcode
  1541. class ClassTemplateSpecializationDecl
  1542. : public CXXRecordDecl, public llvm::FoldingSetNode {
  1543. /// Structure that stores information about a class template
  1544. /// specialization that was instantiated from a class template partial
  1545. /// specialization.
  1546. struct SpecializedPartialSpecialization {
  1547. /// The class template partial specialization from which this
  1548. /// class template specialization was instantiated.
  1549. ClassTemplatePartialSpecializationDecl *PartialSpecialization;
  1550. /// The template argument list deduced for the class template
  1551. /// partial specialization itself.
  1552. const TemplateArgumentList *TemplateArgs;
  1553. };
  1554. /// The template that this specialization specializes
  1555. llvm::PointerUnion<ClassTemplateDecl *, SpecializedPartialSpecialization *>
  1556. SpecializedTemplate;
  1557. /// Further info for explicit template specialization/instantiation.
  1558. struct ExplicitSpecializationInfo {
  1559. /// The type-as-written.
  1560. TypeSourceInfo *TypeAsWritten = nullptr;
  1561. /// The location of the extern keyword.
  1562. SourceLocation ExternLoc;
  1563. /// The location of the template keyword.
  1564. SourceLocation TemplateKeywordLoc;
  1565. ExplicitSpecializationInfo() = default;
  1566. };
  1567. /// Further info for explicit template specialization/instantiation.
  1568. /// Does not apply to implicit specializations.
  1569. ExplicitSpecializationInfo *ExplicitInfo = nullptr;
  1570. /// The template arguments used to describe this specialization.
  1571. const TemplateArgumentList *TemplateArgs;
  1572. /// The point where this template was instantiated (if any)
  1573. SourceLocation PointOfInstantiation;
  1574. /// The kind of specialization this declaration refers to.
  1575. /// Really a value of type TemplateSpecializationKind.
  1576. unsigned SpecializationKind : 3;
  1577. protected:
  1578. ClassTemplateSpecializationDecl(ASTContext &Context, Kind DK, TagKind TK,
  1579. DeclContext *DC, SourceLocation StartLoc,
  1580. SourceLocation IdLoc,
  1581. ClassTemplateDecl *SpecializedTemplate,
  1582. ArrayRef<TemplateArgument> Args,
  1583. ClassTemplateSpecializationDecl *PrevDecl);
  1584. explicit ClassTemplateSpecializationDecl(ASTContext &C, Kind DK);
  1585. public:
  1586. friend class ASTDeclReader;
  1587. friend class ASTDeclWriter;
  1588. static ClassTemplateSpecializationDecl *
  1589. Create(ASTContext &Context, TagKind TK, DeclContext *DC,
  1590. SourceLocation StartLoc, SourceLocation IdLoc,
  1591. ClassTemplateDecl *SpecializedTemplate,
  1592. ArrayRef<TemplateArgument> Args,
  1593. ClassTemplateSpecializationDecl *PrevDecl);
  1594. static ClassTemplateSpecializationDecl *
  1595. CreateDeserialized(ASTContext &C, unsigned ID);
  1596. void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
  1597. bool Qualified) const override;
  1598. // FIXME: This is broken. CXXRecordDecl::getMostRecentDecl() returns a
  1599. // different "most recent" declaration from this function for the same
  1600. // declaration, because we don't override getMostRecentDeclImpl(). But
  1601. // it's not clear that we should override that, because the most recent
  1602. // declaration as a CXXRecordDecl sometimes is the injected-class-name.
  1603. ClassTemplateSpecializationDecl *getMostRecentDecl() {
  1604. return cast<ClassTemplateSpecializationDecl>(
  1605. getMostRecentNonInjectedDecl());
  1606. }
  1607. /// Retrieve the template that this specialization specializes.
  1608. ClassTemplateDecl *getSpecializedTemplate() const;
  1609. /// Retrieve the template arguments of the class template
  1610. /// specialization.
  1611. const TemplateArgumentList &getTemplateArgs() const {
  1612. return *TemplateArgs;
  1613. }
  1614. void setTemplateArgs(TemplateArgumentList *Args) {
  1615. TemplateArgs = Args;
  1616. }
  1617. /// Determine the kind of specialization that this
  1618. /// declaration represents.
  1619. TemplateSpecializationKind getSpecializationKind() const {
  1620. return static_cast<TemplateSpecializationKind>(SpecializationKind);
  1621. }
  1622. bool isExplicitSpecialization() const {
  1623. return getSpecializationKind() == TSK_ExplicitSpecialization;
  1624. }
  1625. /// Is this an explicit specialization at class scope (within the class that
  1626. /// owns the primary template)? For example:
  1627. ///
  1628. /// \code
  1629. /// template<typename T> struct Outer {
  1630. /// template<typename U> struct Inner;
  1631. /// template<> struct Inner; // class-scope explicit specialization
  1632. /// };
  1633. /// \endcode
  1634. bool isClassScopeExplicitSpecialization() const {
  1635. return isExplicitSpecialization() &&
  1636. isa<CXXRecordDecl>(getLexicalDeclContext());
  1637. }
  1638. /// True if this declaration is an explicit specialization,
  1639. /// explicit instantiation declaration, or explicit instantiation
  1640. /// definition.
  1641. bool isExplicitInstantiationOrSpecialization() const {
  1642. return isTemplateExplicitInstantiationOrSpecialization(
  1643. getTemplateSpecializationKind());
  1644. }
  1645. void setSpecializedTemplate(ClassTemplateDecl *Specialized) {
  1646. SpecializedTemplate = Specialized;
  1647. }
  1648. void setSpecializationKind(TemplateSpecializationKind TSK) {
  1649. SpecializationKind = TSK;
  1650. }
  1651. /// Get the point of instantiation (if any), or null if none.
  1652. SourceLocation getPointOfInstantiation() const {
  1653. return PointOfInstantiation;
  1654. }
  1655. void setPointOfInstantiation(SourceLocation Loc) {
  1656. assert(Loc.isValid() && "point of instantiation must be valid!");
  1657. PointOfInstantiation = Loc;
  1658. }
  1659. /// If this class template specialization is an instantiation of
  1660. /// a template (rather than an explicit specialization), return the
  1661. /// class template or class template partial specialization from which it
  1662. /// was instantiated.
  1663. llvm::PointerUnion<ClassTemplateDecl *,
  1664. ClassTemplatePartialSpecializationDecl *>
  1665. getInstantiatedFrom() const {
  1666. if (!isTemplateInstantiation(getSpecializationKind()))
  1667. return llvm::PointerUnion<ClassTemplateDecl *,
  1668. ClassTemplatePartialSpecializationDecl *>();
  1669. return getSpecializedTemplateOrPartial();
  1670. }
  1671. /// Retrieve the class template or class template partial
  1672. /// specialization which was specialized by this.
  1673. llvm::PointerUnion<ClassTemplateDecl *,
  1674. ClassTemplatePartialSpecializationDecl *>
  1675. getSpecializedTemplateOrPartial() const {
  1676. if (const auto *PartialSpec =
  1677. SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization *>())
  1678. return PartialSpec->PartialSpecialization;
  1679. return SpecializedTemplate.get<ClassTemplateDecl*>();
  1680. }
  1681. /// Retrieve the set of template arguments that should be used
  1682. /// to instantiate members of the class template or class template partial
  1683. /// specialization from which this class template specialization was
  1684. /// instantiated.
  1685. ///
  1686. /// \returns For a class template specialization instantiated from the primary
  1687. /// template, this function will return the same template arguments as
  1688. /// getTemplateArgs(). For a class template specialization instantiated from
  1689. /// a class template partial specialization, this function will return the
  1690. /// deduced template arguments for the class template partial specialization
  1691. /// itself.
  1692. const TemplateArgumentList &getTemplateInstantiationArgs() const {
  1693. if (const auto *PartialSpec =
  1694. SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization *>())
  1695. return *PartialSpec->TemplateArgs;
  1696. return getTemplateArgs();
  1697. }
  1698. /// Note that this class template specialization is actually an
  1699. /// instantiation of the given class template partial specialization whose
  1700. /// template arguments have been deduced.
  1701. void setInstantiationOf(ClassTemplatePartialSpecializationDecl *PartialSpec,
  1702. const TemplateArgumentList *TemplateArgs) {
  1703. assert(!SpecializedTemplate.is<SpecializedPartialSpecialization*>() &&
  1704. "Already set to a class template partial specialization!");
  1705. auto *PS = new (getASTContext()) SpecializedPartialSpecialization();
  1706. PS->PartialSpecialization = PartialSpec;
  1707. PS->TemplateArgs = TemplateArgs;
  1708. SpecializedTemplate = PS;
  1709. }
  1710. /// Note that this class template specialization is an instantiation
  1711. /// of the given class template.
  1712. void setInstantiationOf(ClassTemplateDecl *TemplDecl) {
  1713. assert(!SpecializedTemplate.is<SpecializedPartialSpecialization*>() &&
  1714. "Previously set to a class template partial specialization!");
  1715. SpecializedTemplate = TemplDecl;
  1716. }
  1717. /// Sets the type of this specialization as it was written by
  1718. /// the user. This will be a class template specialization type.
  1719. void setTypeAsWritten(TypeSourceInfo *T) {
  1720. if (!ExplicitInfo)
  1721. ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
  1722. ExplicitInfo->TypeAsWritten = T;
  1723. }
  1724. /// Gets the type of this specialization as it was written by
  1725. /// the user, if it was so written.
  1726. TypeSourceInfo *getTypeAsWritten() const {
  1727. return ExplicitInfo ? ExplicitInfo->TypeAsWritten : nullptr;
  1728. }
  1729. /// Gets the location of the extern keyword, if present.
  1730. SourceLocation getExternLoc() const {
  1731. return ExplicitInfo ? ExplicitInfo->ExternLoc : SourceLocation();
  1732. }
  1733. /// Sets the location of the extern keyword.
  1734. void setExternLoc(SourceLocation Loc) {
  1735. if (!ExplicitInfo)
  1736. ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
  1737. ExplicitInfo->ExternLoc = Loc;
  1738. }
  1739. /// Sets the location of the template keyword.
  1740. void setTemplateKeywordLoc(SourceLocation Loc) {
  1741. if (!ExplicitInfo)
  1742. ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
  1743. ExplicitInfo->TemplateKeywordLoc = Loc;
  1744. }
  1745. /// Gets the location of the template keyword, if present.
  1746. SourceLocation getTemplateKeywordLoc() const {
  1747. return ExplicitInfo ? ExplicitInfo->TemplateKeywordLoc : SourceLocation();
  1748. }
  1749. SourceRange getSourceRange() const override LLVM_READONLY;
  1750. void Profile(llvm::FoldingSetNodeID &ID) const {
  1751. Profile(ID, TemplateArgs->asArray(), getASTContext());
  1752. }
  1753. static void
  1754. Profile(llvm::FoldingSetNodeID &ID, ArrayRef<TemplateArgument> TemplateArgs,
  1755. ASTContext &Context) {
  1756. ID.AddInteger(TemplateArgs.size());
  1757. for (const TemplateArgument &TemplateArg : TemplateArgs)
  1758. TemplateArg.Profile(ID, Context);
  1759. }
  1760. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  1761. static bool classofKind(Kind K) {
  1762. return K >= firstClassTemplateSpecialization &&
  1763. K <= lastClassTemplateSpecialization;
  1764. }
  1765. };
  1766. class ClassTemplatePartialSpecializationDecl
  1767. : public ClassTemplateSpecializationDecl {
  1768. /// The list of template parameters
  1769. TemplateParameterList* TemplateParams = nullptr;
  1770. /// The source info for the template arguments as written.
  1771. /// FIXME: redundant with TypeAsWritten?
  1772. const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
  1773. /// The class template partial specialization from which this
  1774. /// class template partial specialization was instantiated.
  1775. ///
  1776. /// The boolean value will be true to indicate that this class template
  1777. /// partial specialization was specialized at this level.
  1778. llvm::PointerIntPair<ClassTemplatePartialSpecializationDecl *, 1, bool>
  1779. InstantiatedFromMember;
  1780. ClassTemplatePartialSpecializationDecl(ASTContext &Context, TagKind TK,
  1781. DeclContext *DC,
  1782. SourceLocation StartLoc,
  1783. SourceLocation IdLoc,
  1784. TemplateParameterList *Params,
  1785. ClassTemplateDecl *SpecializedTemplate,
  1786. ArrayRef<TemplateArgument> Args,
  1787. const ASTTemplateArgumentListInfo *ArgsAsWritten,
  1788. ClassTemplatePartialSpecializationDecl *PrevDecl);
  1789. ClassTemplatePartialSpecializationDecl(ASTContext &C)
  1790. : ClassTemplateSpecializationDecl(C, ClassTemplatePartialSpecialization),
  1791. InstantiatedFromMember(nullptr, false) {}
  1792. void anchor() override;
  1793. public:
  1794. friend class ASTDeclReader;
  1795. friend class ASTDeclWriter;
  1796. static ClassTemplatePartialSpecializationDecl *
  1797. Create(ASTContext &Context, TagKind TK, DeclContext *DC,
  1798. SourceLocation StartLoc, SourceLocation IdLoc,
  1799. TemplateParameterList *Params,
  1800. ClassTemplateDecl *SpecializedTemplate,
  1801. ArrayRef<TemplateArgument> Args,
  1802. const TemplateArgumentListInfo &ArgInfos,
  1803. QualType CanonInjectedType,
  1804. ClassTemplatePartialSpecializationDecl *PrevDecl);
  1805. static ClassTemplatePartialSpecializationDecl *
  1806. CreateDeserialized(ASTContext &C, unsigned ID);
  1807. ClassTemplatePartialSpecializationDecl *getMostRecentDecl() {
  1808. return cast<ClassTemplatePartialSpecializationDecl>(
  1809. static_cast<ClassTemplateSpecializationDecl *>(
  1810. this)->getMostRecentDecl());
  1811. }
  1812. /// Get the list of template parameters
  1813. TemplateParameterList *getTemplateParameters() const {
  1814. return TemplateParams;
  1815. }
  1816. /// \brief All associated constraints of this partial specialization,
  1817. /// including the requires clause and any constraints derived from
  1818. /// constrained-parameters.
  1819. ///
  1820. /// The constraints in the resulting list are to be treated as if in a
  1821. /// conjunction ("and").
  1822. void getAssociatedConstraints(llvm::SmallVectorImpl<const Expr *> &AC) const {
  1823. TemplateParams->getAssociatedConstraints(AC);
  1824. }
  1825. bool hasAssociatedConstraints() const {
  1826. return TemplateParams->hasAssociatedConstraints();
  1827. }
  1828. /// Get the template arguments as written.
  1829. const ASTTemplateArgumentListInfo *getTemplateArgsAsWritten() const {
  1830. return ArgsAsWritten;
  1831. }
  1832. /// Retrieve the member class template partial specialization from
  1833. /// which this particular class template partial specialization was
  1834. /// instantiated.
  1835. ///
  1836. /// \code
  1837. /// template<typename T>
  1838. /// struct Outer {
  1839. /// template<typename U> struct Inner;
  1840. /// template<typename U> struct Inner<U*> { }; // #1
  1841. /// };
  1842. ///
  1843. /// Outer<float>::Inner<int*> ii;
  1844. /// \endcode
  1845. ///
  1846. /// In this example, the instantiation of \c Outer<float>::Inner<int*> will
  1847. /// end up instantiating the partial specialization
  1848. /// \c Outer<float>::Inner<U*>, which itself was instantiated from the class
  1849. /// template partial specialization \c Outer<T>::Inner<U*>. Given
  1850. /// \c Outer<float>::Inner<U*>, this function would return
  1851. /// \c Outer<T>::Inner<U*>.
  1852. ClassTemplatePartialSpecializationDecl *getInstantiatedFromMember() const {
  1853. const auto *First =
  1854. cast<ClassTemplatePartialSpecializationDecl>(getFirstDecl());
  1855. return First->InstantiatedFromMember.getPointer();
  1856. }
  1857. ClassTemplatePartialSpecializationDecl *
  1858. getInstantiatedFromMemberTemplate() const {
  1859. return getInstantiatedFromMember();
  1860. }
  1861. void setInstantiatedFromMember(
  1862. ClassTemplatePartialSpecializationDecl *PartialSpec) {
  1863. auto *First = cast<ClassTemplatePartialSpecializationDecl>(getFirstDecl());
  1864. First->InstantiatedFromMember.setPointer(PartialSpec);
  1865. }
  1866. /// Determines whether this class template partial specialization
  1867. /// template was a specialization of a member partial specialization.
  1868. ///
  1869. /// In the following example, the member template partial specialization
  1870. /// \c X<int>::Inner<T*> is a member specialization.
  1871. ///
  1872. /// \code
  1873. /// template<typename T>
  1874. /// struct X {
  1875. /// template<typename U> struct Inner;
  1876. /// template<typename U> struct Inner<U*>;
  1877. /// };
  1878. ///
  1879. /// template<> template<typename T>
  1880. /// struct X<int>::Inner<T*> { /* ... */ };
  1881. /// \endcode
  1882. bool isMemberSpecialization() {
  1883. const auto *First =
  1884. cast<ClassTemplatePartialSpecializationDecl>(getFirstDecl());
  1885. return First->InstantiatedFromMember.getInt();
  1886. }
  1887. /// Note that this member template is a specialization.
  1888. void setMemberSpecialization() {
  1889. auto *First = cast<ClassTemplatePartialSpecializationDecl>(getFirstDecl());
  1890. assert(First->InstantiatedFromMember.getPointer() &&
  1891. "Only member templates can be member template specializations");
  1892. return First->InstantiatedFromMember.setInt(true);
  1893. }
  1894. /// Retrieves the injected specialization type for this partial
  1895. /// specialization. This is not the same as the type-decl-type for
  1896. /// this partial specialization, which is an InjectedClassNameType.
  1897. QualType getInjectedSpecializationType() const {
  1898. assert(getTypeForDecl() && "partial specialization has no type set!");
  1899. return cast<InjectedClassNameType>(getTypeForDecl())
  1900. ->getInjectedSpecializationType();
  1901. }
  1902. void Profile(llvm::FoldingSetNodeID &ID) const {
  1903. Profile(ID, getTemplateArgs().asArray(), getTemplateParameters(),
  1904. getASTContext());
  1905. }
  1906. static void
  1907. Profile(llvm::FoldingSetNodeID &ID, ArrayRef<TemplateArgument> TemplateArgs,
  1908. TemplateParameterList *TPL, ASTContext &Context);
  1909. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  1910. static bool classofKind(Kind K) {
  1911. return K == ClassTemplatePartialSpecialization;
  1912. }
  1913. };
  1914. /// Declaration of a class template.
  1915. class ClassTemplateDecl : public RedeclarableTemplateDecl {
  1916. protected:
  1917. /// Data that is common to all of the declarations of a given
  1918. /// class template.
  1919. struct Common : CommonBase {
  1920. /// The class template specializations for this class
  1921. /// template, including explicit specializations and instantiations.
  1922. llvm::FoldingSetVector<ClassTemplateSpecializationDecl> Specializations;
  1923. /// The class template partial specializations for this class
  1924. /// template.
  1925. llvm::FoldingSetVector<ClassTemplatePartialSpecializationDecl>
  1926. PartialSpecializations;
  1927. /// The injected-class-name type for this class template.
  1928. QualType InjectedClassNameType;
  1929. Common() = default;
  1930. };
  1931. /// Retrieve the set of specializations of this class template.
  1932. llvm::FoldingSetVector<ClassTemplateSpecializationDecl> &
  1933. getSpecializations() const;
  1934. /// Retrieve the set of partial specializations of this class
  1935. /// template.
  1936. llvm::FoldingSetVector<ClassTemplatePartialSpecializationDecl> &
  1937. getPartialSpecializations() const;
  1938. ClassTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
  1939. DeclarationName Name, TemplateParameterList *Params,
  1940. NamedDecl *Decl)
  1941. : RedeclarableTemplateDecl(ClassTemplate, C, DC, L, Name, Params, Decl) {}
  1942. CommonBase *newCommon(ASTContext &C) const override;
  1943. Common *getCommonPtr() const {
  1944. return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
  1945. }
  1946. public:
  1947. friend class ASTDeclReader;
  1948. friend class ASTDeclWriter;
  1949. /// Load any lazily-loaded specializations from the external source.
  1950. void LoadLazySpecializations() const;
  1951. /// Get the underlying class declarations of the template.
  1952. CXXRecordDecl *getTemplatedDecl() const {
  1953. return static_cast<CXXRecordDecl *>(TemplatedDecl);
  1954. }
  1955. /// Returns whether this template declaration defines the primary
  1956. /// class pattern.
  1957. bool isThisDeclarationADefinition() const {
  1958. return getTemplatedDecl()->isThisDeclarationADefinition();
  1959. }
  1960. /// \brief Create a class template node.
  1961. static ClassTemplateDecl *Create(ASTContext &C, DeclContext *DC,
  1962. SourceLocation L,
  1963. DeclarationName Name,
  1964. TemplateParameterList *Params,
  1965. NamedDecl *Decl);
  1966. /// Create an empty class template node.
  1967. static ClassTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
  1968. /// Return the specialization with the provided arguments if it exists,
  1969. /// otherwise return the insertion point.
  1970. ClassTemplateSpecializationDecl *
  1971. findSpecialization(ArrayRef<TemplateArgument> Args, void *&InsertPos);
  1972. /// Insert the specified specialization knowing that it is not already
  1973. /// in. InsertPos must be obtained from findSpecialization.
  1974. void AddSpecialization(ClassTemplateSpecializationDecl *D, void *InsertPos);
  1975. ClassTemplateDecl *getCanonicalDecl() override {
  1976. return cast<ClassTemplateDecl>(
  1977. RedeclarableTemplateDecl::getCanonicalDecl());
  1978. }
  1979. const ClassTemplateDecl *getCanonicalDecl() const {
  1980. return cast<ClassTemplateDecl>(
  1981. RedeclarableTemplateDecl::getCanonicalDecl());
  1982. }
  1983. /// Retrieve the previous declaration of this class template, or
  1984. /// nullptr if no such declaration exists.
  1985. ClassTemplateDecl *getPreviousDecl() {
  1986. return cast_or_null<ClassTemplateDecl>(
  1987. static_cast<RedeclarableTemplateDecl *>(this)->getPreviousDecl());
  1988. }
  1989. const ClassTemplateDecl *getPreviousDecl() const {
  1990. return cast_or_null<ClassTemplateDecl>(
  1991. static_cast<const RedeclarableTemplateDecl *>(
  1992. this)->getPreviousDecl());
  1993. }
  1994. ClassTemplateDecl *getMostRecentDecl() {
  1995. return cast<ClassTemplateDecl>(
  1996. static_cast<RedeclarableTemplateDecl *>(this)->getMostRecentDecl());
  1997. }
  1998. const ClassTemplateDecl *getMostRecentDecl() const {
  1999. return const_cast<ClassTemplateDecl*>(this)->getMostRecentDecl();
  2000. }
  2001. ClassTemplateDecl *getInstantiatedFromMemberTemplate() const {
  2002. return cast_or_null<ClassTemplateDecl>(
  2003. RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
  2004. }
  2005. /// Return the partial specialization with the provided arguments if it
  2006. /// exists, otherwise return the insertion point.
  2007. ClassTemplatePartialSpecializationDecl *
  2008. findPartialSpecialization(ArrayRef<TemplateArgument> Args,
  2009. TemplateParameterList *TPL, void *&InsertPos);
  2010. /// Insert the specified partial specialization knowing that it is not
  2011. /// already in. InsertPos must be obtained from findPartialSpecialization.
  2012. void AddPartialSpecialization(ClassTemplatePartialSpecializationDecl *D,
  2013. void *InsertPos);
  2014. /// Retrieve the partial specializations as an ordered list.
  2015. void getPartialSpecializations(
  2016. SmallVectorImpl<ClassTemplatePartialSpecializationDecl *> &PS) const;
  2017. /// Find a class template partial specialization with the given
  2018. /// type T.
  2019. ///
  2020. /// \param T a dependent type that names a specialization of this class
  2021. /// template.
  2022. ///
  2023. /// \returns the class template partial specialization that exactly matches
  2024. /// the type \p T, or nullptr if no such partial specialization exists.
  2025. ClassTemplatePartialSpecializationDecl *findPartialSpecialization(QualType T);
  2026. /// Find a class template partial specialization which was instantiated
  2027. /// from the given member partial specialization.
  2028. ///
  2029. /// \param D a member class template partial specialization.
  2030. ///
  2031. /// \returns the class template partial specialization which was instantiated
  2032. /// from the given member partial specialization, or nullptr if no such
  2033. /// partial specialization exists.
  2034. ClassTemplatePartialSpecializationDecl *
  2035. findPartialSpecInstantiatedFromMember(
  2036. ClassTemplatePartialSpecializationDecl *D);
  2037. /// Retrieve the template specialization type of the
  2038. /// injected-class-name for this class template.
  2039. ///
  2040. /// The injected-class-name for a class template \c X is \c
  2041. /// X<template-args>, where \c template-args is formed from the
  2042. /// template arguments that correspond to the template parameters of
  2043. /// \c X. For example:
  2044. ///
  2045. /// \code
  2046. /// template<typename T, int N>
  2047. /// struct array {
  2048. /// typedef array this_type; // "array" is equivalent to "array<T, N>"
  2049. /// };
  2050. /// \endcode
  2051. QualType getInjectedClassNameSpecialization();
  2052. using spec_iterator = SpecIterator<ClassTemplateSpecializationDecl>;
  2053. using spec_range = llvm::iterator_range<spec_iterator>;
  2054. spec_range specializations() const {
  2055. return spec_range(spec_begin(), spec_end());
  2056. }
  2057. spec_iterator spec_begin() const {
  2058. return makeSpecIterator(getSpecializations(), false);
  2059. }
  2060. spec_iterator spec_end() const {
  2061. return makeSpecIterator(getSpecializations(), true);
  2062. }
  2063. // Implement isa/cast/dyncast support
  2064. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  2065. static bool classofKind(Kind K) { return K == ClassTemplate; }
  2066. };
  2067. /// Declaration of a friend template.
  2068. ///
  2069. /// For example:
  2070. /// \code
  2071. /// template \<typename T> class A {
  2072. /// friend class MyVector<T>; // not a friend template
  2073. /// template \<typename U> friend class B; // not a friend template
  2074. /// template \<typename U> friend class Foo<T>::Nested; // friend template
  2075. /// };
  2076. /// \endcode
  2077. ///
  2078. /// \note This class is not currently in use. All of the above
  2079. /// will yield a FriendDecl, not a FriendTemplateDecl.
  2080. class FriendTemplateDecl : public Decl {
  2081. virtual void anchor();
  2082. public:
  2083. using FriendUnion = llvm::PointerUnion<NamedDecl *,TypeSourceInfo *>;
  2084. private:
  2085. // The number of template parameters; always non-zero.
  2086. unsigned NumParams = 0;
  2087. // The parameter list.
  2088. TemplateParameterList **Params = nullptr;
  2089. // The declaration that's a friend of this class.
  2090. FriendUnion Friend;
  2091. // Location of the 'friend' specifier.
  2092. SourceLocation FriendLoc;
  2093. FriendTemplateDecl(DeclContext *DC, SourceLocation Loc,
  2094. TemplateParameterList **Params, unsigned NumParams,
  2095. FriendUnion Friend, SourceLocation FriendLoc)
  2096. : Decl(Decl::FriendTemplate, DC, Loc), NumParams(NumParams),
  2097. Params(Params), Friend(Friend), FriendLoc(FriendLoc) {}
  2098. FriendTemplateDecl(EmptyShell Empty) : Decl(Decl::FriendTemplate, Empty) {}
  2099. public:
  2100. friend class ASTDeclReader;
  2101. static FriendTemplateDecl *
  2102. Create(ASTContext &Context, DeclContext *DC, SourceLocation Loc,
  2103. MutableArrayRef<TemplateParameterList *> Params, FriendUnion Friend,
  2104. SourceLocation FriendLoc);
  2105. static FriendTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
  2106. /// If this friend declaration names a templated type (or
  2107. /// a dependent member type of a templated type), return that
  2108. /// type; otherwise return null.
  2109. TypeSourceInfo *getFriendType() const {
  2110. return Friend.dyn_cast<TypeSourceInfo*>();
  2111. }
  2112. /// If this friend declaration names a templated function (or
  2113. /// a member function of a templated type), return that type;
  2114. /// otherwise return null.
  2115. NamedDecl *getFriendDecl() const {
  2116. return Friend.dyn_cast<NamedDecl*>();
  2117. }
  2118. /// Retrieves the location of the 'friend' keyword.
  2119. SourceLocation getFriendLoc() const {
  2120. return FriendLoc;
  2121. }
  2122. TemplateParameterList *getTemplateParameterList(unsigned i) const {
  2123. assert(i <= NumParams);
  2124. return Params[i];
  2125. }
  2126. unsigned getNumTemplateParameters() const {
  2127. return NumParams;
  2128. }
  2129. // Implement isa/cast/dyncast/etc.
  2130. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  2131. static bool classofKind(Kind K) { return K == Decl::FriendTemplate; }
  2132. };
  2133. /// Declaration of an alias template.
  2134. ///
  2135. /// For example:
  2136. /// \code
  2137. /// template \<typename T> using V = std::map<T*, int, MyCompare<T>>;
  2138. /// \endcode
  2139. class TypeAliasTemplateDecl : public RedeclarableTemplateDecl {
  2140. protected:
  2141. using Common = CommonBase;
  2142. TypeAliasTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
  2143. DeclarationName Name, TemplateParameterList *Params,
  2144. NamedDecl *Decl)
  2145. : RedeclarableTemplateDecl(TypeAliasTemplate, C, DC, L, Name, Params,
  2146. Decl) {}
  2147. CommonBase *newCommon(ASTContext &C) const override;
  2148. Common *getCommonPtr() {
  2149. return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
  2150. }
  2151. public:
  2152. friend class ASTDeclReader;
  2153. friend class ASTDeclWriter;
  2154. /// Get the underlying function declaration of the template.
  2155. TypeAliasDecl *getTemplatedDecl() const {
  2156. return static_cast<TypeAliasDecl *>(TemplatedDecl);
  2157. }
  2158. TypeAliasTemplateDecl *getCanonicalDecl() override {
  2159. return cast<TypeAliasTemplateDecl>(
  2160. RedeclarableTemplateDecl::getCanonicalDecl());
  2161. }
  2162. const TypeAliasTemplateDecl *getCanonicalDecl() const {
  2163. return cast<TypeAliasTemplateDecl>(
  2164. RedeclarableTemplateDecl::getCanonicalDecl());
  2165. }
  2166. /// Retrieve the previous declaration of this function template, or
  2167. /// nullptr if no such declaration exists.
  2168. TypeAliasTemplateDecl *getPreviousDecl() {
  2169. return cast_or_null<TypeAliasTemplateDecl>(
  2170. static_cast<RedeclarableTemplateDecl *>(this)->getPreviousDecl());
  2171. }
  2172. const TypeAliasTemplateDecl *getPreviousDecl() const {
  2173. return cast_or_null<TypeAliasTemplateDecl>(
  2174. static_cast<const RedeclarableTemplateDecl *>(
  2175. this)->getPreviousDecl());
  2176. }
  2177. TypeAliasTemplateDecl *getInstantiatedFromMemberTemplate() const {
  2178. return cast_or_null<TypeAliasTemplateDecl>(
  2179. RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
  2180. }
  2181. /// Create a function template node.
  2182. static TypeAliasTemplateDecl *Create(ASTContext &C, DeclContext *DC,
  2183. SourceLocation L,
  2184. DeclarationName Name,
  2185. TemplateParameterList *Params,
  2186. NamedDecl *Decl);
  2187. /// Create an empty alias template node.
  2188. static TypeAliasTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
  2189. // Implement isa/cast/dyncast support
  2190. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  2191. static bool classofKind(Kind K) { return K == TypeAliasTemplate; }
  2192. };
  2193. /// Declaration of a function specialization at template class scope.
  2194. ///
  2195. /// For example:
  2196. /// \code
  2197. /// template <class T>
  2198. /// class A {
  2199. /// template <class U> void foo(U a) { }
  2200. /// template<> void foo(int a) { }
  2201. /// }
  2202. /// \endcode
  2203. ///
  2204. /// "template<> foo(int a)" will be saved in Specialization as a normal
  2205. /// CXXMethodDecl. Then during an instantiation of class A, it will be
  2206. /// transformed into an actual function specialization.
  2207. ///
  2208. /// FIXME: This is redundant; we could store the same information directly on
  2209. /// the CXXMethodDecl as a DependentFunctionTemplateSpecializationInfo.
  2210. class ClassScopeFunctionSpecializationDecl : public Decl {
  2211. CXXMethodDecl *Specialization;
  2212. const ASTTemplateArgumentListInfo *TemplateArgs;
  2213. ClassScopeFunctionSpecializationDecl(
  2214. DeclContext *DC, SourceLocation Loc, CXXMethodDecl *FD,
  2215. const ASTTemplateArgumentListInfo *TemplArgs)
  2216. : Decl(Decl::ClassScopeFunctionSpecialization, DC, Loc),
  2217. Specialization(FD), TemplateArgs(TemplArgs) {}
  2218. ClassScopeFunctionSpecializationDecl(EmptyShell Empty)
  2219. : Decl(Decl::ClassScopeFunctionSpecialization, Empty) {}
  2220. virtual void anchor();
  2221. public:
  2222. friend class ASTDeclReader;
  2223. friend class ASTDeclWriter;
  2224. CXXMethodDecl *getSpecialization() const { return Specialization; }
  2225. bool hasExplicitTemplateArgs() const { return TemplateArgs; }
  2226. const ASTTemplateArgumentListInfo *getTemplateArgsAsWritten() const {
  2227. return TemplateArgs;
  2228. }
  2229. static ClassScopeFunctionSpecializationDecl *
  2230. Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, CXXMethodDecl *FD,
  2231. bool HasExplicitTemplateArgs,
  2232. const TemplateArgumentListInfo &TemplateArgs) {
  2233. return new (C, DC) ClassScopeFunctionSpecializationDecl(
  2234. DC, Loc, FD,
  2235. HasExplicitTemplateArgs
  2236. ? ASTTemplateArgumentListInfo::Create(C, TemplateArgs)
  2237. : nullptr);
  2238. }
  2239. static ClassScopeFunctionSpecializationDecl *
  2240. CreateDeserialized(ASTContext &Context, unsigned ID);
  2241. // Implement isa/cast/dyncast/etc.
  2242. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  2243. static bool classofKind(Kind K) {
  2244. return K == Decl::ClassScopeFunctionSpecialization;
  2245. }
  2246. };
  2247. /// Represents a variable template specialization, which refers to
  2248. /// a variable template with a given set of template arguments.
  2249. ///
  2250. /// Variable template specializations represent both explicit
  2251. /// specializations of variable templates, as in the example below, and
  2252. /// implicit instantiations of variable templates.
  2253. ///
  2254. /// \code
  2255. /// template<typename T> constexpr T pi = T(3.1415926535897932385);
  2256. ///
  2257. /// template<>
  2258. /// constexpr float pi<float>; // variable template specialization pi<float>
  2259. /// \endcode
  2260. class VarTemplateSpecializationDecl : public VarDecl,
  2261. public llvm::FoldingSetNode {
  2262. /// Structure that stores information about a variable template
  2263. /// specialization that was instantiated from a variable template partial
  2264. /// specialization.
  2265. struct SpecializedPartialSpecialization {
  2266. /// The variable template partial specialization from which this
  2267. /// variable template specialization was instantiated.
  2268. VarTemplatePartialSpecializationDecl *PartialSpecialization;
  2269. /// The template argument list deduced for the variable template
  2270. /// partial specialization itself.
  2271. const TemplateArgumentList *TemplateArgs;
  2272. };
  2273. /// The template that this specialization specializes.
  2274. llvm::PointerUnion<VarTemplateDecl *, SpecializedPartialSpecialization *>
  2275. SpecializedTemplate;
  2276. /// Further info for explicit template specialization/instantiation.
  2277. struct ExplicitSpecializationInfo {
  2278. /// The type-as-written.
  2279. TypeSourceInfo *TypeAsWritten = nullptr;
  2280. /// The location of the extern keyword.
  2281. SourceLocation ExternLoc;
  2282. /// The location of the template keyword.
  2283. SourceLocation TemplateKeywordLoc;
  2284. ExplicitSpecializationInfo() = default;
  2285. };
  2286. /// Further info for explicit template specialization/instantiation.
  2287. /// Does not apply to implicit specializations.
  2288. ExplicitSpecializationInfo *ExplicitInfo = nullptr;
  2289. /// The template arguments used to describe this specialization.
  2290. const TemplateArgumentList *TemplateArgs;
  2291. const ASTTemplateArgumentListInfo *TemplateArgsInfo = nullptr;
  2292. /// The point where this template was instantiated (if any).
  2293. SourceLocation PointOfInstantiation;
  2294. /// The kind of specialization this declaration refers to.
  2295. /// Really a value of type TemplateSpecializationKind.
  2296. unsigned SpecializationKind : 3;
  2297. /// Whether this declaration is a complete definition of the
  2298. /// variable template specialization. We can't otherwise tell apart
  2299. /// an instantiated declaration from an instantiated definition with
  2300. /// no initializer.
  2301. unsigned IsCompleteDefinition : 1;
  2302. protected:
  2303. VarTemplateSpecializationDecl(Kind DK, ASTContext &Context, DeclContext *DC,
  2304. SourceLocation StartLoc, SourceLocation IdLoc,
  2305. VarTemplateDecl *SpecializedTemplate,
  2306. QualType T, TypeSourceInfo *TInfo,
  2307. StorageClass S,
  2308. ArrayRef<TemplateArgument> Args);
  2309. explicit VarTemplateSpecializationDecl(Kind DK, ASTContext &Context);
  2310. public:
  2311. friend class ASTDeclReader;
  2312. friend class ASTDeclWriter;
  2313. friend class VarDecl;
  2314. static VarTemplateSpecializationDecl *
  2315. Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc,
  2316. SourceLocation IdLoc, VarTemplateDecl *SpecializedTemplate, QualType T,
  2317. TypeSourceInfo *TInfo, StorageClass S,
  2318. ArrayRef<TemplateArgument> Args);
  2319. static VarTemplateSpecializationDecl *CreateDeserialized(ASTContext &C,
  2320. unsigned ID);
  2321. void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
  2322. bool Qualified) const override;
  2323. VarTemplateSpecializationDecl *getMostRecentDecl() {
  2324. VarDecl *Recent = static_cast<VarDecl *>(this)->getMostRecentDecl();
  2325. return cast<VarTemplateSpecializationDecl>(Recent);
  2326. }
  2327. /// Retrieve the template that this specialization specializes.
  2328. VarTemplateDecl *getSpecializedTemplate() const;
  2329. /// Retrieve the template arguments of the variable template
  2330. /// specialization.
  2331. const TemplateArgumentList &getTemplateArgs() const { return *TemplateArgs; }
  2332. // TODO: Always set this when creating the new specialization?
  2333. void setTemplateArgsInfo(const TemplateArgumentListInfo &ArgsInfo);
  2334. void setTemplateArgsInfo(const ASTTemplateArgumentListInfo *ArgsInfo);
  2335. const ASTTemplateArgumentListInfo *getTemplateArgsInfo() const {
  2336. return TemplateArgsInfo;
  2337. }
  2338. /// Determine the kind of specialization that this
  2339. /// declaration represents.
  2340. TemplateSpecializationKind getSpecializationKind() const {
  2341. return static_cast<TemplateSpecializationKind>(SpecializationKind);
  2342. }
  2343. bool isExplicitSpecialization() const {
  2344. return getSpecializationKind() == TSK_ExplicitSpecialization;
  2345. }
  2346. bool isClassScopeExplicitSpecialization() const {
  2347. return isExplicitSpecialization() &&
  2348. isa<CXXRecordDecl>(getLexicalDeclContext());
  2349. }
  2350. /// True if this declaration is an explicit specialization,
  2351. /// explicit instantiation declaration, or explicit instantiation
  2352. /// definition.
  2353. bool isExplicitInstantiationOrSpecialization() const {
  2354. return isTemplateExplicitInstantiationOrSpecialization(
  2355. getTemplateSpecializationKind());
  2356. }
  2357. void setSpecializationKind(TemplateSpecializationKind TSK) {
  2358. SpecializationKind = TSK;
  2359. }
  2360. /// Get the point of instantiation (if any), or null if none.
  2361. SourceLocation getPointOfInstantiation() const {
  2362. return PointOfInstantiation;
  2363. }
  2364. void setPointOfInstantiation(SourceLocation Loc) {
  2365. assert(Loc.isValid() && "point of instantiation must be valid!");
  2366. PointOfInstantiation = Loc;
  2367. }
  2368. void setCompleteDefinition() { IsCompleteDefinition = true; }
  2369. /// If this variable template specialization is an instantiation of
  2370. /// a template (rather than an explicit specialization), return the
  2371. /// variable template or variable template partial specialization from which
  2372. /// it was instantiated.
  2373. llvm::PointerUnion<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *>
  2374. getInstantiatedFrom() const {
  2375. if (!isTemplateInstantiation(getSpecializationKind()))
  2376. return llvm::PointerUnion<VarTemplateDecl *,
  2377. VarTemplatePartialSpecializationDecl *>();
  2378. return getSpecializedTemplateOrPartial();
  2379. }
  2380. /// Retrieve the variable template or variable template partial
  2381. /// specialization which was specialized by this.
  2382. llvm::PointerUnion<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *>
  2383. getSpecializedTemplateOrPartial() const {
  2384. if (const auto *PartialSpec =
  2385. SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization *>())
  2386. return PartialSpec->PartialSpecialization;
  2387. return SpecializedTemplate.get<VarTemplateDecl *>();
  2388. }
  2389. /// Retrieve the set of template arguments that should be used
  2390. /// to instantiate the initializer of the variable template or variable
  2391. /// template partial specialization from which this variable template
  2392. /// specialization was instantiated.
  2393. ///
  2394. /// \returns For a variable template specialization instantiated from the
  2395. /// primary template, this function will return the same template arguments
  2396. /// as getTemplateArgs(). For a variable template specialization instantiated
  2397. /// from a variable template partial specialization, this function will the
  2398. /// return deduced template arguments for the variable template partial
  2399. /// specialization itself.
  2400. const TemplateArgumentList &getTemplateInstantiationArgs() const {
  2401. if (const auto *PartialSpec =
  2402. SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization *>())
  2403. return *PartialSpec->TemplateArgs;
  2404. return getTemplateArgs();
  2405. }
  2406. /// Note that this variable template specialization is actually an
  2407. /// instantiation of the given variable template partial specialization whose
  2408. /// template arguments have been deduced.
  2409. void setInstantiationOf(VarTemplatePartialSpecializationDecl *PartialSpec,
  2410. const TemplateArgumentList *TemplateArgs) {
  2411. assert(!SpecializedTemplate.is<SpecializedPartialSpecialization *>() &&
  2412. "Already set to a variable template partial specialization!");
  2413. auto *PS = new (getASTContext()) SpecializedPartialSpecialization();
  2414. PS->PartialSpecialization = PartialSpec;
  2415. PS->TemplateArgs = TemplateArgs;
  2416. SpecializedTemplate = PS;
  2417. }
  2418. /// Note that this variable template specialization is an instantiation
  2419. /// of the given variable template.
  2420. void setInstantiationOf(VarTemplateDecl *TemplDecl) {
  2421. assert(!SpecializedTemplate.is<SpecializedPartialSpecialization *>() &&
  2422. "Previously set to a variable template partial specialization!");
  2423. SpecializedTemplate = TemplDecl;
  2424. }
  2425. /// Sets the type of this specialization as it was written by
  2426. /// the user.
  2427. void setTypeAsWritten(TypeSourceInfo *T) {
  2428. if (!ExplicitInfo)
  2429. ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
  2430. ExplicitInfo->TypeAsWritten = T;
  2431. }
  2432. /// Gets the type of this specialization as it was written by
  2433. /// the user, if it was so written.
  2434. TypeSourceInfo *getTypeAsWritten() const {
  2435. return ExplicitInfo ? ExplicitInfo->TypeAsWritten : nullptr;
  2436. }
  2437. /// Gets the location of the extern keyword, if present.
  2438. SourceLocation getExternLoc() const {
  2439. return ExplicitInfo ? ExplicitInfo->ExternLoc : SourceLocation();
  2440. }
  2441. /// Sets the location of the extern keyword.
  2442. void setExternLoc(SourceLocation Loc) {
  2443. if (!ExplicitInfo)
  2444. ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
  2445. ExplicitInfo->ExternLoc = Loc;
  2446. }
  2447. /// Sets the location of the template keyword.
  2448. void setTemplateKeywordLoc(SourceLocation Loc) {
  2449. if (!ExplicitInfo)
  2450. ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
  2451. ExplicitInfo->TemplateKeywordLoc = Loc;
  2452. }
  2453. /// Gets the location of the template keyword, if present.
  2454. SourceLocation getTemplateKeywordLoc() const {
  2455. return ExplicitInfo ? ExplicitInfo->TemplateKeywordLoc : SourceLocation();
  2456. }
  2457. SourceRange getSourceRange() const override LLVM_READONLY {
  2458. if (isExplicitSpecialization()) {
  2459. if (const ASTTemplateArgumentListInfo *Info = getTemplateArgsInfo())
  2460. return SourceRange(getOuterLocStart(), Info->getRAngleLoc());
  2461. }
  2462. return VarDecl::getSourceRange();
  2463. }
  2464. void Profile(llvm::FoldingSetNodeID &ID) const {
  2465. Profile(ID, TemplateArgs->asArray(), getASTContext());
  2466. }
  2467. static void Profile(llvm::FoldingSetNodeID &ID,
  2468. ArrayRef<TemplateArgument> TemplateArgs,
  2469. ASTContext &Context) {
  2470. ID.AddInteger(TemplateArgs.size());
  2471. for (const TemplateArgument &TemplateArg : TemplateArgs)
  2472. TemplateArg.Profile(ID, Context);
  2473. }
  2474. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  2475. static bool classofKind(Kind K) {
  2476. return K >= firstVarTemplateSpecialization &&
  2477. K <= lastVarTemplateSpecialization;
  2478. }
  2479. };
  2480. class VarTemplatePartialSpecializationDecl
  2481. : public VarTemplateSpecializationDecl {
  2482. /// The list of template parameters
  2483. TemplateParameterList *TemplateParams = nullptr;
  2484. /// The source info for the template arguments as written.
  2485. /// FIXME: redundant with TypeAsWritten?
  2486. const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
  2487. /// The variable template partial specialization from which this
  2488. /// variable template partial specialization was instantiated.
  2489. ///
  2490. /// The boolean value will be true to indicate that this variable template
  2491. /// partial specialization was specialized at this level.
  2492. llvm::PointerIntPair<VarTemplatePartialSpecializationDecl *, 1, bool>
  2493. InstantiatedFromMember;
  2494. VarTemplatePartialSpecializationDecl(
  2495. ASTContext &Context, DeclContext *DC, SourceLocation StartLoc,
  2496. SourceLocation IdLoc, TemplateParameterList *Params,
  2497. VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo,
  2498. StorageClass S, ArrayRef<TemplateArgument> Args,
  2499. const ASTTemplateArgumentListInfo *ArgInfos);
  2500. VarTemplatePartialSpecializationDecl(ASTContext &Context)
  2501. : VarTemplateSpecializationDecl(VarTemplatePartialSpecialization,
  2502. Context),
  2503. InstantiatedFromMember(nullptr, false) {}
  2504. void anchor() override;
  2505. public:
  2506. friend class ASTDeclReader;
  2507. friend class ASTDeclWriter;
  2508. static VarTemplatePartialSpecializationDecl *
  2509. Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc,
  2510. SourceLocation IdLoc, TemplateParameterList *Params,
  2511. VarTemplateDecl *SpecializedTemplate, QualType T,
  2512. TypeSourceInfo *TInfo, StorageClass S, ArrayRef<TemplateArgument> Args,
  2513. const TemplateArgumentListInfo &ArgInfos);
  2514. static VarTemplatePartialSpecializationDecl *CreateDeserialized(ASTContext &C,
  2515. unsigned ID);
  2516. VarTemplatePartialSpecializationDecl *getMostRecentDecl() {
  2517. return cast<VarTemplatePartialSpecializationDecl>(
  2518. static_cast<VarTemplateSpecializationDecl *>(
  2519. this)->getMostRecentDecl());
  2520. }
  2521. /// Get the list of template parameters
  2522. TemplateParameterList *getTemplateParameters() const {
  2523. return TemplateParams;
  2524. }
  2525. /// Get the template arguments as written.
  2526. const ASTTemplateArgumentListInfo *getTemplateArgsAsWritten() const {
  2527. return ArgsAsWritten;
  2528. }
  2529. /// \brief All associated constraints of this partial specialization,
  2530. /// including the requires clause and any constraints derived from
  2531. /// constrained-parameters.
  2532. ///
  2533. /// The constraints in the resulting list are to be treated as if in a
  2534. /// conjunction ("and").
  2535. void getAssociatedConstraints(llvm::SmallVectorImpl<const Expr *> &AC) const {
  2536. TemplateParams->getAssociatedConstraints(AC);
  2537. }
  2538. bool hasAssociatedConstraints() const {
  2539. return TemplateParams->hasAssociatedConstraints();
  2540. }
  2541. /// \brief Retrieve the member variable template partial specialization from
  2542. /// which this particular variable template partial specialization was
  2543. /// instantiated.
  2544. ///
  2545. /// \code
  2546. /// template<typename T>
  2547. /// struct Outer {
  2548. /// template<typename U> U Inner;
  2549. /// template<typename U> U* Inner<U*> = (U*)(0); // #1
  2550. /// };
  2551. ///
  2552. /// template int* Outer<float>::Inner<int*>;
  2553. /// \endcode
  2554. ///
  2555. /// In this example, the instantiation of \c Outer<float>::Inner<int*> will
  2556. /// end up instantiating the partial specialization
  2557. /// \c Outer<float>::Inner<U*>, which itself was instantiated from the
  2558. /// variable template partial specialization \c Outer<T>::Inner<U*>. Given
  2559. /// \c Outer<float>::Inner<U*>, this function would return
  2560. /// \c Outer<T>::Inner<U*>.
  2561. VarTemplatePartialSpecializationDecl *getInstantiatedFromMember() const {
  2562. const auto *First =
  2563. cast<VarTemplatePartialSpecializationDecl>(getFirstDecl());
  2564. return First->InstantiatedFromMember.getPointer();
  2565. }
  2566. void
  2567. setInstantiatedFromMember(VarTemplatePartialSpecializationDecl *PartialSpec) {
  2568. auto *First = cast<VarTemplatePartialSpecializationDecl>(getFirstDecl());
  2569. First->InstantiatedFromMember.setPointer(PartialSpec);
  2570. }
  2571. /// Determines whether this variable template partial specialization
  2572. /// was a specialization of a member partial specialization.
  2573. ///
  2574. /// In the following example, the member template partial specialization
  2575. /// \c X<int>::Inner<T*> is a member specialization.
  2576. ///
  2577. /// \code
  2578. /// template<typename T>
  2579. /// struct X {
  2580. /// template<typename U> U Inner;
  2581. /// template<typename U> U* Inner<U*> = (U*)(0);
  2582. /// };
  2583. ///
  2584. /// template<> template<typename T>
  2585. /// U* X<int>::Inner<T*> = (T*)(0) + 1;
  2586. /// \endcode
  2587. bool isMemberSpecialization() {
  2588. const auto *First =
  2589. cast<VarTemplatePartialSpecializationDecl>(getFirstDecl());
  2590. return First->InstantiatedFromMember.getInt();
  2591. }
  2592. /// Note that this member template is a specialization.
  2593. void setMemberSpecialization() {
  2594. auto *First = cast<VarTemplatePartialSpecializationDecl>(getFirstDecl());
  2595. assert(First->InstantiatedFromMember.getPointer() &&
  2596. "Only member templates can be member template specializations");
  2597. return First->InstantiatedFromMember.setInt(true);
  2598. }
  2599. SourceRange getSourceRange() const override LLVM_READONLY {
  2600. if (isExplicitSpecialization()) {
  2601. if (const ASTTemplateArgumentListInfo *Info = getTemplateArgsAsWritten())
  2602. return SourceRange(getOuterLocStart(), Info->getRAngleLoc());
  2603. }
  2604. return VarDecl::getSourceRange();
  2605. }
  2606. void Profile(llvm::FoldingSetNodeID &ID) const {
  2607. Profile(ID, getTemplateArgs().asArray(), getTemplateParameters(),
  2608. getASTContext());
  2609. }
  2610. static void
  2611. Profile(llvm::FoldingSetNodeID &ID, ArrayRef<TemplateArgument> TemplateArgs,
  2612. TemplateParameterList *TPL, ASTContext &Context);
  2613. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  2614. static bool classofKind(Kind K) {
  2615. return K == VarTemplatePartialSpecialization;
  2616. }
  2617. };
  2618. /// Declaration of a variable template.
  2619. class VarTemplateDecl : public RedeclarableTemplateDecl {
  2620. protected:
  2621. /// Data that is common to all of the declarations of a given
  2622. /// variable template.
  2623. struct Common : CommonBase {
  2624. /// The variable template specializations for this variable
  2625. /// template, including explicit specializations and instantiations.
  2626. llvm::FoldingSetVector<VarTemplateSpecializationDecl> Specializations;
  2627. /// The variable template partial specializations for this variable
  2628. /// template.
  2629. llvm::FoldingSetVector<VarTemplatePartialSpecializationDecl>
  2630. PartialSpecializations;
  2631. Common() = default;
  2632. };
  2633. /// Retrieve the set of specializations of this variable template.
  2634. llvm::FoldingSetVector<VarTemplateSpecializationDecl> &
  2635. getSpecializations() const;
  2636. /// Retrieve the set of partial specializations of this class
  2637. /// template.
  2638. llvm::FoldingSetVector<VarTemplatePartialSpecializationDecl> &
  2639. getPartialSpecializations() const;
  2640. VarTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
  2641. DeclarationName Name, TemplateParameterList *Params,
  2642. NamedDecl *Decl)
  2643. : RedeclarableTemplateDecl(VarTemplate, C, DC, L, Name, Params, Decl) {}
  2644. CommonBase *newCommon(ASTContext &C) const override;
  2645. Common *getCommonPtr() const {
  2646. return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
  2647. }
  2648. public:
  2649. friend class ASTDeclReader;
  2650. friend class ASTDeclWriter;
  2651. /// Load any lazily-loaded specializations from the external source.
  2652. void LoadLazySpecializations() const;
  2653. /// Get the underlying variable declarations of the template.
  2654. VarDecl *getTemplatedDecl() const {
  2655. return static_cast<VarDecl *>(TemplatedDecl);
  2656. }
  2657. /// Returns whether this template declaration defines the primary
  2658. /// variable pattern.
  2659. bool isThisDeclarationADefinition() const {
  2660. return getTemplatedDecl()->isThisDeclarationADefinition();
  2661. }
  2662. VarTemplateDecl *getDefinition();
  2663. /// Create a variable template node.
  2664. static VarTemplateDecl *Create(ASTContext &C, DeclContext *DC,
  2665. SourceLocation L, DeclarationName Name,
  2666. TemplateParameterList *Params,
  2667. VarDecl *Decl);
  2668. /// Create an empty variable template node.
  2669. static VarTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
  2670. /// Return the specialization with the provided arguments if it exists,
  2671. /// otherwise return the insertion point.
  2672. VarTemplateSpecializationDecl *
  2673. findSpecialization(ArrayRef<TemplateArgument> Args, void *&InsertPos);
  2674. /// Insert the specified specialization knowing that it is not already
  2675. /// in. InsertPos must be obtained from findSpecialization.
  2676. void AddSpecialization(VarTemplateSpecializationDecl *D, void *InsertPos);
  2677. VarTemplateDecl *getCanonicalDecl() override {
  2678. return cast<VarTemplateDecl>(RedeclarableTemplateDecl::getCanonicalDecl());
  2679. }
  2680. const VarTemplateDecl *getCanonicalDecl() const {
  2681. return cast<VarTemplateDecl>(RedeclarableTemplateDecl::getCanonicalDecl());
  2682. }
  2683. /// Retrieve the previous declaration of this variable template, or
  2684. /// nullptr if no such declaration exists.
  2685. VarTemplateDecl *getPreviousDecl() {
  2686. return cast_or_null<VarTemplateDecl>(
  2687. static_cast<RedeclarableTemplateDecl *>(this)->getPreviousDecl());
  2688. }
  2689. const VarTemplateDecl *getPreviousDecl() const {
  2690. return cast_or_null<VarTemplateDecl>(
  2691. static_cast<const RedeclarableTemplateDecl *>(
  2692. this)->getPreviousDecl());
  2693. }
  2694. VarTemplateDecl *getMostRecentDecl() {
  2695. return cast<VarTemplateDecl>(
  2696. static_cast<RedeclarableTemplateDecl *>(this)->getMostRecentDecl());
  2697. }
  2698. const VarTemplateDecl *getMostRecentDecl() const {
  2699. return const_cast<VarTemplateDecl *>(this)->getMostRecentDecl();
  2700. }
  2701. VarTemplateDecl *getInstantiatedFromMemberTemplate() const {
  2702. return cast_or_null<VarTemplateDecl>(
  2703. RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
  2704. }
  2705. /// Return the partial specialization with the provided arguments if it
  2706. /// exists, otherwise return the insertion point.
  2707. VarTemplatePartialSpecializationDecl *
  2708. findPartialSpecialization(ArrayRef<TemplateArgument> Args,
  2709. TemplateParameterList *TPL, void *&InsertPos);
  2710. /// Insert the specified partial specialization knowing that it is not
  2711. /// already in. InsertPos must be obtained from findPartialSpecialization.
  2712. void AddPartialSpecialization(VarTemplatePartialSpecializationDecl *D,
  2713. void *InsertPos);
  2714. /// Retrieve the partial specializations as an ordered list.
  2715. void getPartialSpecializations(
  2716. SmallVectorImpl<VarTemplatePartialSpecializationDecl *> &PS) const;
  2717. /// Find a variable template partial specialization which was
  2718. /// instantiated
  2719. /// from the given member partial specialization.
  2720. ///
  2721. /// \param D a member variable template partial specialization.
  2722. ///
  2723. /// \returns the variable template partial specialization which was
  2724. /// instantiated
  2725. /// from the given member partial specialization, or nullptr if no such
  2726. /// partial specialization exists.
  2727. VarTemplatePartialSpecializationDecl *findPartialSpecInstantiatedFromMember(
  2728. VarTemplatePartialSpecializationDecl *D);
  2729. using spec_iterator = SpecIterator<VarTemplateSpecializationDecl>;
  2730. using spec_range = llvm::iterator_range<spec_iterator>;
  2731. spec_range specializations() const {
  2732. return spec_range(spec_begin(), spec_end());
  2733. }
  2734. spec_iterator spec_begin() const {
  2735. return makeSpecIterator(getSpecializations(), false);
  2736. }
  2737. spec_iterator spec_end() const {
  2738. return makeSpecIterator(getSpecializations(), true);
  2739. }
  2740. // Implement isa/cast/dyncast support
  2741. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  2742. static bool classofKind(Kind K) { return K == VarTemplate; }
  2743. };
  2744. /// Declaration of a C++20 concept.
  2745. class ConceptDecl : public TemplateDecl, public Mergeable<ConceptDecl> {
  2746. protected:
  2747. Expr *ConstraintExpr;
  2748. ConceptDecl(DeclContext *DC, SourceLocation L, DeclarationName Name,
  2749. TemplateParameterList *Params, Expr *ConstraintExpr)
  2750. : TemplateDecl(Concept, DC, L, Name, Params),
  2751. ConstraintExpr(ConstraintExpr) {};
  2752. public:
  2753. static ConceptDecl *Create(ASTContext &C, DeclContext *DC,
  2754. SourceLocation L, DeclarationName Name,
  2755. TemplateParameterList *Params,
  2756. Expr *ConstraintExpr);
  2757. static ConceptDecl *CreateDeserialized(ASTContext &C, unsigned ID);
  2758. Expr *getConstraintExpr() const {
  2759. return ConstraintExpr;
  2760. }
  2761. SourceRange getSourceRange() const override LLVM_READONLY {
  2762. return SourceRange(getTemplateParameters()->getTemplateLoc(),
  2763. ConstraintExpr->getEndLoc());
  2764. }
  2765. bool isTypeConcept() const {
  2766. return isa<TemplateTypeParmDecl>(getTemplateParameters()->getParam(0));
  2767. }
  2768. ConceptDecl *getCanonicalDecl() override {
  2769. return cast<ConceptDecl>(getPrimaryMergedDecl(this));
  2770. }
  2771. const ConceptDecl *getCanonicalDecl() const {
  2772. return const_cast<ConceptDecl *>(this)->getCanonicalDecl();
  2773. }
  2774. // Implement isa/cast/dyncast/etc.
  2775. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  2776. static bool classofKind(Kind K) { return K == Concept; }
  2777. friend class ASTReader;
  2778. friend class ASTDeclReader;
  2779. friend class ASTDeclWriter;
  2780. };
  2781. // An implementation detail of ConceptSpecialicationExpr that holds the template
  2782. // arguments, so we can later use this to reconstitute the template arguments
  2783. // during constraint checking.
  2784. class ImplicitConceptSpecializationDecl final
  2785. : public Decl,
  2786. private llvm::TrailingObjects<ImplicitConceptSpecializationDecl,
  2787. TemplateArgument> {
  2788. unsigned NumTemplateArgs;
  2789. ImplicitConceptSpecializationDecl(DeclContext *DC, SourceLocation SL,
  2790. ArrayRef<TemplateArgument> ConvertedArgs);
  2791. ImplicitConceptSpecializationDecl(EmptyShell Empty, unsigned NumTemplateArgs);
  2792. public:
  2793. static ImplicitConceptSpecializationDecl *
  2794. Create(const ASTContext &C, DeclContext *DC, SourceLocation SL,
  2795. ArrayRef<TemplateArgument> ConvertedArgs);
  2796. static ImplicitConceptSpecializationDecl *
  2797. CreateDeserialized(const ASTContext &C, unsigned ID,
  2798. unsigned NumTemplateArgs);
  2799. ArrayRef<TemplateArgument> getTemplateArguments() const {
  2800. return ArrayRef<TemplateArgument>(getTrailingObjects<TemplateArgument>(),
  2801. NumTemplateArgs);
  2802. }
  2803. void setTemplateArguments(ArrayRef<TemplateArgument> Converted);
  2804. static bool classofKind(Kind K) { return K == ImplicitConceptSpecialization; }
  2805. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  2806. friend TrailingObjects;
  2807. friend class ASTDeclReader;
  2808. };
  2809. /// A template parameter object.
  2810. ///
  2811. /// Template parameter objects represent values of class type used as template
  2812. /// arguments. There is one template parameter object for each such distinct
  2813. /// value used as a template argument across the program.
  2814. ///
  2815. /// \code
  2816. /// struct A { int x, y; };
  2817. /// template<A> struct S;
  2818. /// S<A{1, 2}> s1;
  2819. /// S<A{1, 2}> s2; // same type, argument is same TemplateParamObjectDecl.
  2820. /// \endcode
  2821. class TemplateParamObjectDecl : public ValueDecl,
  2822. public Mergeable<TemplateParamObjectDecl>,
  2823. public llvm::FoldingSetNode {
  2824. private:
  2825. /// The value of this template parameter object.
  2826. APValue Value;
  2827. TemplateParamObjectDecl(DeclContext *DC, QualType T, const APValue &V)
  2828. : ValueDecl(TemplateParamObject, DC, SourceLocation(), DeclarationName(),
  2829. T),
  2830. Value(V) {}
  2831. static TemplateParamObjectDecl *Create(const ASTContext &C, QualType T,
  2832. const APValue &V);
  2833. static TemplateParamObjectDecl *CreateDeserialized(ASTContext &C,
  2834. unsigned ID);
  2835. /// Only ASTContext::getTemplateParamObjectDecl and deserialization
  2836. /// create these.
  2837. friend class ASTContext;
  2838. friend class ASTReader;
  2839. friend class ASTDeclReader;
  2840. public:
  2841. /// Print this template parameter object in a human-readable format.
  2842. void printName(llvm::raw_ostream &OS,
  2843. const PrintingPolicy &Policy) const override;
  2844. /// Print this object as an equivalent expression.
  2845. void printAsExpr(llvm::raw_ostream &OS) const;
  2846. void printAsExpr(llvm::raw_ostream &OS, const PrintingPolicy &Policy) const;
  2847. /// Print this object as an initializer suitable for a variable of the
  2848. /// object's type.
  2849. void printAsInit(llvm::raw_ostream &OS) const;
  2850. void printAsInit(llvm::raw_ostream &OS, const PrintingPolicy &Policy) const;
  2851. const APValue &getValue() const { return Value; }
  2852. static void Profile(llvm::FoldingSetNodeID &ID, QualType T,
  2853. const APValue &V) {
  2854. ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
  2855. V.Profile(ID);
  2856. }
  2857. void Profile(llvm::FoldingSetNodeID &ID) {
  2858. Profile(ID, getType(), getValue());
  2859. }
  2860. TemplateParamObjectDecl *getCanonicalDecl() override {
  2861. return getFirstDecl();
  2862. }
  2863. const TemplateParamObjectDecl *getCanonicalDecl() const {
  2864. return getFirstDecl();
  2865. }
  2866. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  2867. static bool classofKind(Kind K) { return K == TemplateParamObject; }
  2868. };
  2869. inline NamedDecl *getAsNamedDecl(TemplateParameter P) {
  2870. if (auto *PD = P.dyn_cast<TemplateTypeParmDecl *>())
  2871. return PD;
  2872. if (auto *PD = P.dyn_cast<NonTypeTemplateParmDecl *>())
  2873. return PD;
  2874. return P.get<TemplateTemplateParmDecl *>();
  2875. }
  2876. inline TemplateDecl *getAsTypeTemplateDecl(Decl *D) {
  2877. auto *TD = dyn_cast<TemplateDecl>(D);
  2878. return TD && (isa<ClassTemplateDecl>(TD) ||
  2879. isa<ClassTemplatePartialSpecializationDecl>(TD) ||
  2880. isa<TypeAliasTemplateDecl>(TD) ||
  2881. isa<TemplateTemplateParmDecl>(TD))
  2882. ? TD
  2883. : nullptr;
  2884. }
  2885. /// Check whether the template parameter is a pack expansion, and if so,
  2886. /// determine the number of parameters produced by that expansion. For instance:
  2887. ///
  2888. /// \code
  2889. /// template<typename ...Ts> struct A {
  2890. /// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
  2891. /// };
  2892. /// \endcode
  2893. ///
  2894. /// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
  2895. /// is not a pack expansion, so returns an empty Optional.
  2896. inline std::optional<unsigned> getExpandedPackSize(const NamedDecl *Param) {
  2897. if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
  2898. if (TTP->isExpandedParameterPack())
  2899. return TTP->getNumExpansionParameters();
  2900. }
  2901. if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
  2902. if (NTTP->isExpandedParameterPack())
  2903. return NTTP->getNumExpansionTypes();
  2904. }
  2905. if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
  2906. if (TTP->isExpandedParameterPack())
  2907. return TTP->getNumExpansionTemplateParameters();
  2908. }
  2909. return std::nullopt;
  2910. }
  2911. /// Internal helper used by Subst* nodes to retrieve the parameter list
  2912. /// for their AssociatedDecl.
  2913. TemplateParameterList *getReplacedTemplateParameterList(Decl *D);
  2914. } // namespace clang
  2915. #endif // LLVM_CLANG_AST_DECLTEMPLATE_H
  2916. #ifdef __GNUC__
  2917. #pragma GCC diagnostic pop
  2918. #endif