SemaTemplateInstantiateDecl.cpp 185 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728
  1. //===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl Instantiation ===/
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //===----------------------------------------------------------------------===/
  8. //
  9. // This file implements C++ template instantiation for declarations.
  10. //
  11. //===----------------------------------------------------------------------===/
  12. #include "clang/Sema/SemaInternal.h"
  13. #include "clang/AST/ASTConsumer.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/ASTMutationListener.h"
  16. #include "clang/AST/DeclTemplate.h"
  17. #include "clang/AST/DeclVisitor.h"
  18. #include "clang/AST/DependentDiagnostic.h"
  19. #include "clang/AST/Expr.h"
  20. #include "clang/AST/ExprCXX.h"
  21. #include "clang/AST/TypeLoc.h"
  22. #include "clang/Sema/Lookup.h"
  23. #include "clang/Sema/PrettyDeclStackTrace.h"
  24. #include "clang/Sema/Template.h"
  25. using namespace clang;
  26. static bool isDeclWithinFunction(const Decl *D) {
  27. const DeclContext *DC = D->getDeclContext();
  28. if (DC->isFunctionOrMethod())
  29. return true;
  30. if (DC->isRecord())
  31. return cast<CXXRecordDecl>(DC)->isLocalClass();
  32. return false;
  33. }
  34. template<typename DeclT>
  35. static bool SubstQualifier(Sema &SemaRef, const DeclT *OldDecl, DeclT *NewDecl,
  36. const MultiLevelTemplateArgumentList &TemplateArgs) {
  37. if (!OldDecl->getQualifierLoc())
  38. return false;
  39. assert((NewDecl->getFriendObjectKind() ||
  40. !OldDecl->getLexicalDeclContext()->isDependentContext()) &&
  41. "non-friend with qualified name defined in dependent context");
  42. Sema::ContextRAII SavedContext(
  43. SemaRef,
  44. const_cast<DeclContext *>(NewDecl->getFriendObjectKind()
  45. ? NewDecl->getLexicalDeclContext()
  46. : OldDecl->getLexicalDeclContext()));
  47. NestedNameSpecifierLoc NewQualifierLoc
  48. = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
  49. TemplateArgs);
  50. if (!NewQualifierLoc)
  51. return true;
  52. NewDecl->setQualifierInfo(NewQualifierLoc);
  53. return false;
  54. }
  55. bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
  56. DeclaratorDecl *NewDecl) {
  57. return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
  58. }
  59. bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
  60. TagDecl *NewDecl) {
  61. return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
  62. }
  63. // Include attribute instantiation code.
  64. #include "clang/Sema/AttrTemplateInstantiate.inc"
  65. static void instantiateDependentAlignedAttr(
  66. Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
  67. const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
  68. if (Aligned->isAlignmentExpr()) {
  69. // The alignment expression is a constant expression.
  70. EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated);
  71. ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
  72. if (!Result.isInvalid())
  73. S.AddAlignedAttr(Aligned->getLocation(), New, Result.getAs<Expr>(),
  74. Aligned->getSpellingListIndex(), IsPackExpansion);
  75. } else {
  76. TypeSourceInfo *Result = S.SubstType(Aligned->getAlignmentType(),
  77. TemplateArgs, Aligned->getLocation(),
  78. DeclarationName());
  79. if (Result)
  80. S.AddAlignedAttr(Aligned->getLocation(), New, Result,
  81. Aligned->getSpellingListIndex(), IsPackExpansion);
  82. }
  83. }
  84. static void instantiateDependentAlignedAttr(
  85. Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
  86. const AlignedAttr *Aligned, Decl *New) {
  87. if (!Aligned->isPackExpansion()) {
  88. instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
  89. return;
  90. }
  91. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  92. if (Aligned->isAlignmentExpr())
  93. S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
  94. Unexpanded);
  95. else
  96. S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
  97. Unexpanded);
  98. assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
  99. // Determine whether we can expand this attribute pack yet.
  100. bool Expand = true, RetainExpansion = false;
  101. Optional<unsigned> NumExpansions;
  102. // FIXME: Use the actual location of the ellipsis.
  103. SourceLocation EllipsisLoc = Aligned->getLocation();
  104. if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
  105. Unexpanded, TemplateArgs, Expand,
  106. RetainExpansion, NumExpansions))
  107. return;
  108. if (!Expand) {
  109. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1);
  110. instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
  111. } else {
  112. for (unsigned I = 0; I != *NumExpansions; ++I) {
  113. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I);
  114. instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
  115. }
  116. }
  117. }
  118. static void instantiateDependentAssumeAlignedAttr(
  119. Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
  120. const AssumeAlignedAttr *Aligned, Decl *New) {
  121. // The alignment expression is a constant expression.
  122. EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated);
  123. Expr *E, *OE = nullptr;
  124. ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
  125. if (Result.isInvalid())
  126. return;
  127. E = Result.getAs<Expr>();
  128. if (Aligned->getOffset()) {
  129. Result = S.SubstExpr(Aligned->getOffset(), TemplateArgs);
  130. if (Result.isInvalid())
  131. return;
  132. OE = Result.getAs<Expr>();
  133. }
  134. S.AddAssumeAlignedAttr(Aligned->getLocation(), New, E, OE,
  135. Aligned->getSpellingListIndex());
  136. }
  137. static void instantiateDependentAlignValueAttr(
  138. Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
  139. const AlignValueAttr *Aligned, Decl *New) {
  140. // The alignment expression is a constant expression.
  141. EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated);
  142. ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
  143. if (!Result.isInvalid())
  144. S.AddAlignValueAttr(Aligned->getLocation(), New, Result.getAs<Expr>(),
  145. Aligned->getSpellingListIndex());
  146. }
  147. static void instantiateDependentEnableIfAttr(
  148. Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
  149. const EnableIfAttr *A, const Decl *Tmpl, Decl *New) {
  150. Expr *Cond = nullptr;
  151. {
  152. EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
  153. ExprResult Result = S.SubstExpr(A->getCond(), TemplateArgs);
  154. if (Result.isInvalid())
  155. return;
  156. Cond = Result.getAs<Expr>();
  157. }
  158. if (A->getCond()->isTypeDependent() && !Cond->isTypeDependent()) {
  159. ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
  160. if (Converted.isInvalid())
  161. return;
  162. Cond = Converted.get();
  163. }
  164. SmallVector<PartialDiagnosticAt, 8> Diags;
  165. if (A->getCond()->isValueDependent() && !Cond->isValueDependent() &&
  166. !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(Tmpl),
  167. Diags)) {
  168. S.Diag(A->getLocation(), diag::err_enable_if_never_constant_expr);
  169. for (int I = 0, N = Diags.size(); I != N; ++I)
  170. S.Diag(Diags[I].first, Diags[I].second);
  171. return;
  172. }
  173. EnableIfAttr *EIA = new (S.getASTContext())
  174. EnableIfAttr(A->getLocation(), S.getASTContext(), Cond,
  175. A->getMessage(),
  176. A->getSpellingListIndex());
  177. New->addAttr(EIA);
  178. }
  179. // Constructs and adds to New a new instance of CUDALaunchBoundsAttr using
  180. // template A as the base and arguments from TemplateArgs.
  181. static void instantiateDependentCUDALaunchBoundsAttr(
  182. Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
  183. const CUDALaunchBoundsAttr &Attr, Decl *New) {
  184. // The alignment expression is a constant expression.
  185. EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated);
  186. ExprResult Result = S.SubstExpr(Attr.getMaxThreads(), TemplateArgs);
  187. if (Result.isInvalid())
  188. return;
  189. Expr *MaxThreads = Result.getAs<Expr>();
  190. Expr *MinBlocks = nullptr;
  191. if (Attr.getMinBlocks()) {
  192. Result = S.SubstExpr(Attr.getMinBlocks(), TemplateArgs);
  193. if (Result.isInvalid())
  194. return;
  195. MinBlocks = Result.getAs<Expr>();
  196. }
  197. S.AddLaunchBoundsAttr(Attr.getLocation(), New, MaxThreads, MinBlocks,
  198. Attr.getSpellingListIndex());
  199. }
  200. void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
  201. const Decl *Tmpl, Decl *New,
  202. LateInstantiatedAttrVec *LateAttrs,
  203. LocalInstantiationScope *OuterMostScope) {
  204. for (const auto *TmplAttr : Tmpl->attrs()) {
  205. // FIXME: This should be generalized to more than just the AlignedAttr.
  206. const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
  207. if (Aligned && Aligned->isAlignmentDependent()) {
  208. instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
  209. continue;
  210. }
  211. const AssumeAlignedAttr *AssumeAligned = dyn_cast<AssumeAlignedAttr>(TmplAttr);
  212. if (AssumeAligned) {
  213. instantiateDependentAssumeAlignedAttr(*this, TemplateArgs, AssumeAligned, New);
  214. continue;
  215. }
  216. const AlignValueAttr *AlignValue = dyn_cast<AlignValueAttr>(TmplAttr);
  217. if (AlignValue) {
  218. instantiateDependentAlignValueAttr(*this, TemplateArgs, AlignValue, New);
  219. continue;
  220. }
  221. const EnableIfAttr *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr);
  222. if (EnableIf && EnableIf->getCond()->isValueDependent()) {
  223. instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl,
  224. New);
  225. continue;
  226. }
  227. if (const CUDALaunchBoundsAttr *CUDALaunchBounds =
  228. dyn_cast<CUDALaunchBoundsAttr>(TmplAttr)) {
  229. instantiateDependentCUDALaunchBoundsAttr(*this, TemplateArgs,
  230. *CUDALaunchBounds, New);
  231. continue;
  232. }
  233. // Existing DLL attribute on the instantiation takes precedence.
  234. if (TmplAttr->getKind() == attr::DLLExport ||
  235. TmplAttr->getKind() == attr::DLLImport) {
  236. if (New->hasAttr<DLLExportAttr>() || New->hasAttr<DLLImportAttr>()) {
  237. continue;
  238. }
  239. }
  240. assert(!TmplAttr->isPackExpansion());
  241. if (TmplAttr->isLateParsed() && LateAttrs) {
  242. // Late parsed attributes must be instantiated and attached after the
  243. // enclosing class has been instantiated. See Sema::InstantiateClass.
  244. LocalInstantiationScope *Saved = nullptr;
  245. if (CurrentInstantiationScope)
  246. Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
  247. LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
  248. } else {
  249. // Allow 'this' within late-parsed attributes.
  250. NamedDecl *ND = dyn_cast<NamedDecl>(New);
  251. CXXRecordDecl *ThisContext =
  252. dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
  253. CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
  254. ND && ND->isCXXInstanceMember());
  255. Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
  256. *this, TemplateArgs);
  257. if (NewAttr)
  258. New->addAttr(NewAttr);
  259. }
  260. }
  261. }
  262. /// Get the previous declaration of a declaration for the purposes of template
  263. /// instantiation. If this finds a previous declaration, then the previous
  264. /// declaration of the instantiation of D should be an instantiation of the
  265. /// result of this function.
  266. template<typename DeclT>
  267. static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
  268. DeclT *Result = D->getPreviousDecl();
  269. // If the declaration is within a class, and the previous declaration was
  270. // merged from a different definition of that class, then we don't have a
  271. // previous declaration for the purpose of template instantiation.
  272. if (Result && isa<CXXRecordDecl>(D->getDeclContext()) &&
  273. D->getLexicalDeclContext() != Result->getLexicalDeclContext())
  274. return nullptr;
  275. return Result;
  276. }
  277. Decl *
  278. TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
  279. llvm_unreachable("Translation units cannot be instantiated");
  280. }
  281. // HLSL Change Starts
  282. Decl *
  283. TemplateDeclInstantiator::VisitHLSLBufferDecl(HLSLBufferDecl *Decl) {
  284. llvm_unreachable("HLSL buffer declarations cannot be instantiated");
  285. }
  286. // HLSL Change Ends
  287. Decl *
  288. TemplateDeclInstantiator::VisitExternCContextDecl(ExternCContextDecl *D) {
  289. llvm_unreachable("extern \"C\" context cannot be instantiated");
  290. }
  291. Decl *
  292. TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
  293. LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
  294. D->getIdentifier());
  295. Owner->addDecl(Inst);
  296. return Inst;
  297. }
  298. Decl *
  299. TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
  300. llvm_unreachable("Namespaces cannot be instantiated");
  301. }
  302. Decl *
  303. TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
  304. NamespaceAliasDecl *Inst
  305. = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
  306. D->getNamespaceLoc(),
  307. D->getAliasLoc(),
  308. D->getIdentifier(),
  309. D->getQualifierLoc(),
  310. D->getTargetNameLoc(),
  311. D->getNamespace());
  312. Owner->addDecl(Inst);
  313. return Inst;
  314. }
  315. Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
  316. bool IsTypeAlias) {
  317. bool Invalid = false;
  318. TypeSourceInfo *DI = D->getTypeSourceInfo();
  319. if (DI->getType()->isInstantiationDependentType() ||
  320. DI->getType()->isVariablyModifiedType()) {
  321. DI = SemaRef.SubstType(DI, TemplateArgs,
  322. D->getLocation(), D->getDeclName());
  323. if (!DI) {
  324. Invalid = true;
  325. DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
  326. }
  327. } else {
  328. SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
  329. }
  330. // HACK: g++ has a bug where it gets the value kind of ?: wrong.
  331. // libstdc++ relies upon this bug in its implementation of common_type.
  332. // If we happen to be processing that implementation, fake up the g++ ?:
  333. // semantics. See LWG issue 2141 for more information on the bug.
  334. const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
  335. CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
  336. if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
  337. DT->isReferenceType() &&
  338. RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
  339. RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
  340. D->getIdentifier() && D->getIdentifier()->isStr("type") &&
  341. SemaRef.getSourceManager().isInSystemHeader(D->getLocStart()))
  342. // Fold it to the (non-reference) type which g++ would have produced.
  343. DI = SemaRef.Context.getTrivialTypeSourceInfo(
  344. DI->getType().getNonReferenceType());
  345. // Create the new typedef
  346. TypedefNameDecl *Typedef;
  347. if (IsTypeAlias)
  348. Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
  349. D->getLocation(), D->getIdentifier(), DI);
  350. else
  351. Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
  352. D->getLocation(), D->getIdentifier(), DI);
  353. if (Invalid)
  354. Typedef->setInvalidDecl();
  355. // If the old typedef was the name for linkage purposes of an anonymous
  356. // tag decl, re-establish that relationship for the new typedef.
  357. if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
  358. TagDecl *oldTag = oldTagType->getDecl();
  359. if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
  360. TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
  361. assert(!newTag->hasNameForLinkage());
  362. newTag->setTypedefNameForAnonDecl(Typedef);
  363. }
  364. }
  365. if (TypedefNameDecl *Prev = getPreviousDeclForInstantiation(D)) {
  366. NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
  367. TemplateArgs);
  368. if (!InstPrev)
  369. return nullptr;
  370. TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
  371. // If the typedef types are not identical, reject them.
  372. SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
  373. Typedef->setPreviousDecl(InstPrevTypedef);
  374. }
  375. SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
  376. Typedef->setAccess(D->getAccess());
  377. return Typedef;
  378. }
  379. Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
  380. Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
  381. if (Typedef)
  382. Owner->addDecl(Typedef);
  383. return Typedef;
  384. }
  385. Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
  386. Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
  387. if (Typedef)
  388. Owner->addDecl(Typedef);
  389. return Typedef;
  390. }
  391. Decl *
  392. TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
  393. // Create a local instantiation scope for this type alias template, which
  394. // will contain the instantiations of the template parameters.
  395. LocalInstantiationScope Scope(SemaRef);
  396. TemplateParameterList *TempParams = D->getTemplateParameters();
  397. TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
  398. if (!InstParams)
  399. return nullptr;
  400. TypeAliasDecl *Pattern = D->getTemplatedDecl();
  401. TypeAliasTemplateDecl *PrevAliasTemplate = nullptr;
  402. if (getPreviousDeclForInstantiation<TypedefNameDecl>(Pattern)) {
  403. DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
  404. if (!Found.empty()) {
  405. PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
  406. }
  407. }
  408. TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
  409. InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
  410. if (!AliasInst)
  411. return nullptr;
  412. TypeAliasTemplateDecl *Inst
  413. = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
  414. D->getDeclName(), InstParams, AliasInst);
  415. AliasInst->setDescribedAliasTemplate(Inst);
  416. if (PrevAliasTemplate)
  417. Inst->setPreviousDecl(PrevAliasTemplate);
  418. Inst->setAccess(D->getAccess());
  419. if (!PrevAliasTemplate)
  420. Inst->setInstantiatedFromMemberTemplate(D);
  421. Owner->addDecl(Inst);
  422. return Inst;
  423. }
  424. Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
  425. return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
  426. }
  427. Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D,
  428. bool InstantiatingVarTemplate) {
  429. // If this is the variable for an anonymous struct or union,
  430. // instantiate the anonymous struct/union type first.
  431. if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
  432. if (RecordTy->getDecl()->isAnonymousStructOrUnion())
  433. if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
  434. return nullptr;
  435. // Do substitution on the type of the declaration
  436. TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
  437. TemplateArgs,
  438. D->getTypeSpecStartLoc(),
  439. D->getDeclName());
  440. if (!DI)
  441. return nullptr;
  442. if (DI->getType()->isFunctionType()) {
  443. SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
  444. << D->isStaticDataMember() << DI->getType();
  445. return nullptr;
  446. }
  447. DeclContext *DC = Owner;
  448. if (D->isLocalExternDecl())
  449. SemaRef.adjustContextForLocalExternDecl(DC);
  450. // Build the instantiated declaration.
  451. VarDecl *Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
  452. D->getLocation(), D->getIdentifier(),
  453. DI->getType(), DI, D->getStorageClass());
  454. // In ARC, infer 'retaining' for variables of retainable type.
  455. if (SemaRef.getLangOpts().ObjCAutoRefCount &&
  456. SemaRef.inferObjCARCLifetime(Var))
  457. Var->setInvalidDecl();
  458. // Substitute the nested name specifier, if any.
  459. if (SubstQualifier(D, Var))
  460. return nullptr;
  461. SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
  462. StartingScope, InstantiatingVarTemplate);
  463. if (D->isNRVOVariable()) {
  464. QualType ReturnType = cast<FunctionDecl>(DC)->getReturnType();
  465. if (SemaRef.isCopyElisionCandidate(ReturnType, Var, false))
  466. Var->setNRVOVariable(true);
  467. }
  468. Var->setImplicit(D->isImplicit());
  469. return Var;
  470. }
  471. Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
  472. AccessSpecDecl* AD
  473. = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
  474. D->getAccessSpecifierLoc(), D->getColonLoc());
  475. Owner->addHiddenDecl(AD);
  476. return AD;
  477. }
  478. Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
  479. bool Invalid = false;
  480. TypeSourceInfo *DI = D->getTypeSourceInfo();
  481. if (DI->getType()->isInstantiationDependentType() ||
  482. DI->getType()->isVariablyModifiedType()) {
  483. DI = SemaRef.SubstType(DI, TemplateArgs,
  484. D->getLocation(), D->getDeclName());
  485. if (!DI) {
  486. DI = D->getTypeSourceInfo();
  487. Invalid = true;
  488. } else if (DI->getType()->isFunctionType()) {
  489. // C++ [temp.arg.type]p3:
  490. // If a declaration acquires a function type through a type
  491. // dependent on a template-parameter and this causes a
  492. // declaration that does not use the syntactic form of a
  493. // function declarator to have function type, the program is
  494. // ill-formed.
  495. SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
  496. << DI->getType();
  497. Invalid = true;
  498. }
  499. } else {
  500. SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
  501. }
  502. Expr *BitWidth = D->getBitWidth();
  503. if (Invalid)
  504. BitWidth = nullptr;
  505. else if (BitWidth) {
  506. // The bit-width expression is a constant expression.
  507. EnterExpressionEvaluationContext Unevaluated(SemaRef,
  508. Sema::ConstantEvaluated);
  509. ExprResult InstantiatedBitWidth
  510. = SemaRef.SubstExpr(BitWidth, TemplateArgs);
  511. if (InstantiatedBitWidth.isInvalid()) {
  512. Invalid = true;
  513. BitWidth = nullptr;
  514. } else
  515. BitWidth = InstantiatedBitWidth.getAs<Expr>();
  516. }
  517. FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
  518. DI->getType(), DI,
  519. cast<RecordDecl>(Owner),
  520. D->getLocation(),
  521. D->isMutable(),
  522. BitWidth,
  523. D->getInClassInitStyle(),
  524. D->getInnerLocStart(),
  525. D->getAccess(),
  526. nullptr);
  527. if (!Field) {
  528. cast<Decl>(Owner)->setInvalidDecl();
  529. return nullptr;
  530. }
  531. SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
  532. if (Field->hasAttrs())
  533. SemaRef.CheckAlignasUnderalignment(Field);
  534. if (Invalid)
  535. Field->setInvalidDecl();
  536. if (!Field->getDeclName()) {
  537. // Keep track of where this decl came from.
  538. SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
  539. }
  540. if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
  541. if (Parent->isAnonymousStructOrUnion() &&
  542. Parent->getRedeclContext()->isFunctionOrMethod())
  543. SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
  544. }
  545. Field->setImplicit(D->isImplicit());
  546. Field->setAccess(D->getAccess());
  547. Owner->addDecl(Field);
  548. return Field;
  549. }
  550. Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
  551. bool Invalid = false;
  552. TypeSourceInfo *DI = D->getTypeSourceInfo();
  553. if (DI->getType()->isVariablyModifiedType()) {
  554. SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
  555. << D;
  556. Invalid = true;
  557. } else if (DI->getType()->isInstantiationDependentType()) {
  558. DI = SemaRef.SubstType(DI, TemplateArgs,
  559. D->getLocation(), D->getDeclName());
  560. if (!DI) {
  561. DI = D->getTypeSourceInfo();
  562. Invalid = true;
  563. } else if (DI->getType()->isFunctionType()) {
  564. // C++ [temp.arg.type]p3:
  565. // If a declaration acquires a function type through a type
  566. // dependent on a template-parameter and this causes a
  567. // declaration that does not use the syntactic form of a
  568. // function declarator to have function type, the program is
  569. // ill-formed.
  570. SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
  571. << DI->getType();
  572. Invalid = true;
  573. }
  574. } else {
  575. SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
  576. }
  577. MSPropertyDecl *Property = MSPropertyDecl::Create(
  578. SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(),
  579. DI, D->getLocStart(), D->getGetterId(), D->getSetterId());
  580. SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
  581. StartingScope);
  582. if (Invalid)
  583. Property->setInvalidDecl();
  584. Property->setAccess(D->getAccess());
  585. Owner->addDecl(Property);
  586. return Property;
  587. }
  588. Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
  589. NamedDecl **NamedChain =
  590. new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
  591. int i = 0;
  592. for (auto *PI : D->chain()) {
  593. NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI,
  594. TemplateArgs);
  595. if (!Next)
  596. return nullptr;
  597. NamedChain[i++] = Next;
  598. }
  599. QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
  600. IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
  601. SemaRef.Context, Owner, D->getLocation(), D->getIdentifier(), T,
  602. NamedChain, D->getChainingSize());
  603. for (const auto *Attr : D->attrs())
  604. IndirectField->addAttr(Attr->clone(SemaRef.Context));
  605. IndirectField->setImplicit(D->isImplicit());
  606. IndirectField->setAccess(D->getAccess());
  607. Owner->addDecl(IndirectField);
  608. return IndirectField;
  609. }
  610. Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
  611. // Handle friend type expressions by simply substituting template
  612. // parameters into the pattern type and checking the result.
  613. if (TypeSourceInfo *Ty = D->getFriendType()) {
  614. TypeSourceInfo *InstTy;
  615. // If this is an unsupported friend, don't bother substituting template
  616. // arguments into it. The actual type referred to won't be used by any
  617. // parts of Clang, and may not be valid for instantiating. Just use the
  618. // same info for the instantiated friend.
  619. if (D->isUnsupportedFriend()) {
  620. InstTy = Ty;
  621. } else {
  622. InstTy = SemaRef.SubstType(Ty, TemplateArgs,
  623. D->getLocation(), DeclarationName());
  624. }
  625. if (!InstTy)
  626. return nullptr;
  627. FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getLocStart(),
  628. D->getFriendLoc(), InstTy);
  629. if (!FD)
  630. return nullptr;
  631. FD->setAccess(AS_public);
  632. FD->setUnsupportedFriend(D->isUnsupportedFriend());
  633. Owner->addDecl(FD);
  634. return FD;
  635. }
  636. NamedDecl *ND = D->getFriendDecl();
  637. assert(ND && "friend decl must be a decl or a type!");
  638. // All of the Visit implementations for the various potential friend
  639. // declarations have to be carefully written to work for friend
  640. // objects, with the most important detail being that the target
  641. // decl should almost certainly not be placed in Owner.
  642. Decl *NewND = Visit(ND);
  643. if (!NewND) return nullptr;
  644. FriendDecl *FD =
  645. FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
  646. cast<NamedDecl>(NewND), D->getFriendLoc());
  647. FD->setAccess(AS_public);
  648. FD->setUnsupportedFriend(D->isUnsupportedFriend());
  649. Owner->addDecl(FD);
  650. return FD;
  651. }
  652. Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
  653. Expr *AssertExpr = D->getAssertExpr();
  654. // The expression in a static assertion is a constant expression.
  655. EnterExpressionEvaluationContext Unevaluated(SemaRef,
  656. Sema::ConstantEvaluated);
  657. ExprResult InstantiatedAssertExpr
  658. = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
  659. if (InstantiatedAssertExpr.isInvalid())
  660. return nullptr;
  661. return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
  662. InstantiatedAssertExpr.get(),
  663. D->getMessage(),
  664. D->getRParenLoc(),
  665. D->isFailed());
  666. }
  667. Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
  668. EnumDecl *PrevDecl = nullptr;
  669. if (EnumDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
  670. NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
  671. PatternPrev,
  672. TemplateArgs);
  673. if (!Prev) return nullptr;
  674. PrevDecl = cast<EnumDecl>(Prev);
  675. }
  676. EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
  677. D->getLocation(), D->getIdentifier(),
  678. PrevDecl, D->isScoped(),
  679. D->isScopedUsingClassTag(), D->isFixed());
  680. if (D->isFixed()) {
  681. if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
  682. // If we have type source information for the underlying type, it means it
  683. // has been explicitly set by the user. Perform substitution on it before
  684. // moving on.
  685. SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
  686. TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
  687. DeclarationName());
  688. if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
  689. Enum->setIntegerType(SemaRef.Context.IntTy);
  690. else
  691. Enum->setIntegerTypeSourceInfo(NewTI);
  692. } else {
  693. assert(!D->getIntegerType()->isDependentType()
  694. && "Dependent type without type source info");
  695. Enum->setIntegerType(D->getIntegerType());
  696. }
  697. }
  698. SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
  699. Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
  700. Enum->setAccess(D->getAccess());
  701. // Forward the mangling number from the template to the instantiated decl.
  702. SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D));
  703. if (SubstQualifier(D, Enum)) return nullptr;
  704. Owner->addDecl(Enum);
  705. EnumDecl *Def = D->getDefinition();
  706. if (Def && Def != D) {
  707. // If this is an out-of-line definition of an enum member template, check
  708. // that the underlying types match in the instantiation of both
  709. // declarations.
  710. if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
  711. SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
  712. QualType DefnUnderlying =
  713. SemaRef.SubstType(TI->getType(), TemplateArgs,
  714. UnderlyingLoc, DeclarationName());
  715. SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
  716. DefnUnderlying, Enum);
  717. }
  718. }
  719. // C++11 [temp.inst]p1: The implicit instantiation of a class template
  720. // specialization causes the implicit instantiation of the declarations, but
  721. // not the definitions of scoped member enumerations.
  722. //
  723. // DR1484 clarifies that enumeration definitions inside of a template
  724. // declaration aren't considered entities that can be separately instantiated
  725. // from the rest of the entity they are declared inside of.
  726. if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
  727. SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
  728. InstantiateEnumDefinition(Enum, Def);
  729. }
  730. return Enum;
  731. }
  732. void TemplateDeclInstantiator::InstantiateEnumDefinition(
  733. EnumDecl *Enum, EnumDecl *Pattern) {
  734. Enum->startDefinition();
  735. // Update the location to refer to the definition.
  736. Enum->setLocation(Pattern->getLocation());
  737. SmallVector<Decl*, 4> Enumerators;
  738. EnumConstantDecl *LastEnumConst = nullptr;
  739. for (auto *EC : Pattern->enumerators()) {
  740. // The specified value for the enumerator.
  741. ExprResult Value((Expr *)nullptr);
  742. if (Expr *UninstValue = EC->getInitExpr()) {
  743. // The enumerator's value expression is a constant expression.
  744. EnterExpressionEvaluationContext Unevaluated(SemaRef,
  745. Sema::ConstantEvaluated);
  746. Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
  747. }
  748. // Drop the initial value and continue.
  749. bool isInvalid = false;
  750. if (Value.isInvalid()) {
  751. Value = nullptr;
  752. isInvalid = true;
  753. }
  754. EnumConstantDecl *EnumConst
  755. = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
  756. EC->getLocation(), EC->getIdentifier(),
  757. Value.get());
  758. if (isInvalid) {
  759. if (EnumConst)
  760. EnumConst->setInvalidDecl();
  761. Enum->setInvalidDecl();
  762. }
  763. if (EnumConst) {
  764. SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst);
  765. EnumConst->setAccess(Enum->getAccess());
  766. Enum->addDecl(EnumConst);
  767. Enumerators.push_back(EnumConst);
  768. LastEnumConst = EnumConst;
  769. if (Pattern->getDeclContext()->isFunctionOrMethod() &&
  770. !Enum->isScoped()) {
  771. // If the enumeration is within a function or method, record the enum
  772. // constant as a local.
  773. SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst);
  774. }
  775. }
  776. }
  777. // FIXME: Fixup LBraceLoc
  778. SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(),
  779. Enum->getRBraceLoc(), Enum,
  780. Enumerators,
  781. nullptr, nullptr);
  782. }
  783. Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
  784. llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
  785. }
  786. Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
  787. bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
  788. // Create a local instantiation scope for this class template, which
  789. // will contain the instantiations of the template parameters.
  790. LocalInstantiationScope Scope(SemaRef);
  791. TemplateParameterList *TempParams = D->getTemplateParameters();
  792. TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
  793. if (!InstParams)
  794. return nullptr;
  795. CXXRecordDecl *Pattern = D->getTemplatedDecl();
  796. // Instantiate the qualifier. We have to do this first in case
  797. // we're a friend declaration, because if we are then we need to put
  798. // the new declaration in the appropriate context.
  799. NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
  800. if (QualifierLoc) {
  801. QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
  802. TemplateArgs);
  803. if (!QualifierLoc)
  804. return nullptr;
  805. }
  806. CXXRecordDecl *PrevDecl = nullptr;
  807. ClassTemplateDecl *PrevClassTemplate = nullptr;
  808. if (!isFriend && getPreviousDeclForInstantiation(Pattern)) {
  809. DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
  810. if (!Found.empty()) {
  811. PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
  812. if (PrevClassTemplate)
  813. PrevDecl = PrevClassTemplate->getTemplatedDecl();
  814. }
  815. }
  816. // If this isn't a friend, then it's a member template, in which
  817. // case we just want to build the instantiation in the
  818. // specialization. If it is a friend, we want to build it in
  819. // the appropriate context.
  820. DeclContext *DC = Owner;
  821. if (isFriend) {
  822. if (QualifierLoc) {
  823. CXXScopeSpec SS;
  824. SS.Adopt(QualifierLoc);
  825. DC = SemaRef.computeDeclContext(SS);
  826. if (!DC) return nullptr;
  827. } else {
  828. DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
  829. Pattern->getDeclContext(),
  830. TemplateArgs);
  831. }
  832. // Look for a previous declaration of the template in the owning
  833. // context.
  834. LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
  835. Sema::LookupOrdinaryName, Sema::ForRedeclaration);
  836. SemaRef.LookupQualifiedName(R, DC);
  837. if (R.isSingleResult()) {
  838. PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
  839. if (PrevClassTemplate)
  840. PrevDecl = PrevClassTemplate->getTemplatedDecl();
  841. }
  842. if (!PrevClassTemplate && QualifierLoc) {
  843. SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
  844. << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
  845. << QualifierLoc.getSourceRange();
  846. return nullptr;
  847. }
  848. bool AdoptedPreviousTemplateParams = false;
  849. if (PrevClassTemplate) {
  850. bool Complain = true;
  851. // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
  852. // template for struct std::tr1::__detail::_Map_base, where the
  853. // template parameters of the friend declaration don't match the
  854. // template parameters of the original declaration. In this one
  855. // case, we don't complain about the ill-formed friend
  856. // declaration.
  857. if (isFriend && Pattern->getIdentifier() &&
  858. Pattern->getIdentifier()->isStr("_Map_base") &&
  859. DC->isNamespace() &&
  860. cast<NamespaceDecl>(DC)->getIdentifier() &&
  861. cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
  862. DeclContext *DCParent = DC->getParent();
  863. if (DCParent->isNamespace() &&
  864. cast<NamespaceDecl>(DCParent)->getIdentifier() &&
  865. cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
  866. if (cast<Decl>(DCParent)->isInStdNamespace())
  867. Complain = false;
  868. }
  869. }
  870. TemplateParameterList *PrevParams
  871. = PrevClassTemplate->getTemplateParameters();
  872. // Make sure the parameter lists match.
  873. if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
  874. Complain,
  875. Sema::TPL_TemplateMatch)) {
  876. if (Complain)
  877. return nullptr;
  878. AdoptedPreviousTemplateParams = true;
  879. InstParams = PrevParams;
  880. }
  881. // Do some additional validation, then merge default arguments
  882. // from the existing declarations.
  883. if (!AdoptedPreviousTemplateParams &&
  884. SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
  885. Sema::TPC_ClassTemplate))
  886. return nullptr;
  887. }
  888. }
  889. CXXRecordDecl *RecordInst
  890. = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
  891. Pattern->getLocStart(), Pattern->getLocation(),
  892. Pattern->getIdentifier(), PrevDecl,
  893. /*DelayTypeCreation=*/true);
  894. if (QualifierLoc)
  895. RecordInst->setQualifierInfo(QualifierLoc);
  896. ClassTemplateDecl *Inst
  897. = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
  898. D->getIdentifier(), InstParams, RecordInst,
  899. PrevClassTemplate);
  900. RecordInst->setDescribedClassTemplate(Inst);
  901. if (isFriend) {
  902. if (PrevClassTemplate)
  903. Inst->setAccess(PrevClassTemplate->getAccess());
  904. else
  905. Inst->setAccess(D->getAccess());
  906. Inst->setObjectOfFriendDecl();
  907. // TODO: do we want to track the instantiation progeny of this
  908. // friend target decl?
  909. } else {
  910. Inst->setAccess(D->getAccess());
  911. if (!PrevClassTemplate)
  912. Inst->setInstantiatedFromMemberTemplate(D);
  913. }
  914. // Trigger creation of the type for the instantiation.
  915. SemaRef.Context.getInjectedClassNameType(RecordInst,
  916. Inst->getInjectedClassNameSpecialization());
  917. // Finish handling of friends.
  918. if (isFriend) {
  919. DC->makeDeclVisibleInContext(Inst);
  920. Inst->setLexicalDeclContext(Owner);
  921. RecordInst->setLexicalDeclContext(Owner);
  922. return Inst;
  923. }
  924. if (D->isOutOfLine()) {
  925. Inst->setLexicalDeclContext(D->getLexicalDeclContext());
  926. RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
  927. }
  928. Owner->addDecl(Inst);
  929. if (!PrevClassTemplate) {
  930. // Queue up any out-of-line partial specializations of this member
  931. // class template; the client will force their instantiation once
  932. // the enclosing class has been instantiated.
  933. SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
  934. D->getPartialSpecializations(PartialSpecs);
  935. for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
  936. if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
  937. OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
  938. }
  939. return Inst;
  940. }
  941. Decl *
  942. TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
  943. ClassTemplatePartialSpecializationDecl *D) {
  944. ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
  945. // Lookup the already-instantiated declaration in the instantiation
  946. // of the class template and return that.
  947. DeclContext::lookup_result Found
  948. = Owner->lookup(ClassTemplate->getDeclName());
  949. if (Found.empty())
  950. return nullptr;
  951. ClassTemplateDecl *InstClassTemplate
  952. = dyn_cast<ClassTemplateDecl>(Found.front());
  953. if (!InstClassTemplate)
  954. return nullptr;
  955. if (ClassTemplatePartialSpecializationDecl *Result
  956. = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
  957. return Result;
  958. return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
  959. }
  960. Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
  961. assert(D->getTemplatedDecl()->isStaticDataMember() &&
  962. "Only static data member templates are allowed.");
  963. // Create a local instantiation scope for this variable template, which
  964. // will contain the instantiations of the template parameters.
  965. LocalInstantiationScope Scope(SemaRef);
  966. TemplateParameterList *TempParams = D->getTemplateParameters();
  967. TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
  968. if (!InstParams)
  969. return nullptr;
  970. VarDecl *Pattern = D->getTemplatedDecl();
  971. VarTemplateDecl *PrevVarTemplate = nullptr;
  972. if (getPreviousDeclForInstantiation(Pattern)) {
  973. DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
  974. if (!Found.empty())
  975. PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
  976. }
  977. VarDecl *VarInst =
  978. cast_or_null<VarDecl>(VisitVarDecl(Pattern,
  979. /*InstantiatingVarTemplate=*/true));
  980. DeclContext *DC = Owner;
  981. VarTemplateDecl *Inst = VarTemplateDecl::Create(
  982. SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
  983. VarInst);
  984. VarInst->setDescribedVarTemplate(Inst);
  985. Inst->setPreviousDecl(PrevVarTemplate);
  986. Inst->setAccess(D->getAccess());
  987. if (!PrevVarTemplate)
  988. Inst->setInstantiatedFromMemberTemplate(D);
  989. if (D->isOutOfLine()) {
  990. Inst->setLexicalDeclContext(D->getLexicalDeclContext());
  991. VarInst->setLexicalDeclContext(D->getLexicalDeclContext());
  992. }
  993. Owner->addDecl(Inst);
  994. if (!PrevVarTemplate) {
  995. // Queue up any out-of-line partial specializations of this member
  996. // variable template; the client will force their instantiation once
  997. // the enclosing class has been instantiated.
  998. SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
  999. D->getPartialSpecializations(PartialSpecs);
  1000. for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
  1001. if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
  1002. OutOfLineVarPartialSpecs.push_back(
  1003. std::make_pair(Inst, PartialSpecs[I]));
  1004. }
  1005. return Inst;
  1006. }
  1007. Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
  1008. VarTemplatePartialSpecializationDecl *D) {
  1009. assert(D->isStaticDataMember() &&
  1010. "Only static data member templates are allowed.");
  1011. VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
  1012. // Lookup the already-instantiated declaration and return that.
  1013. DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
  1014. assert(!Found.empty() && "Instantiation found nothing?");
  1015. VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
  1016. assert(InstVarTemplate && "Instantiation did not find a variable template?");
  1017. if (VarTemplatePartialSpecializationDecl *Result =
  1018. InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
  1019. return Result;
  1020. return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
  1021. }
  1022. Decl *
  1023. TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
  1024. // Create a local instantiation scope for this function template, which
  1025. // will contain the instantiations of the template parameters and then get
  1026. // merged with the local instantiation scope for the function template
  1027. // itself.
  1028. LocalInstantiationScope Scope(SemaRef);
  1029. TemplateParameterList *TempParams = D->getTemplateParameters();
  1030. TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
  1031. if (!InstParams)
  1032. return nullptr;
  1033. FunctionDecl *Instantiated = nullptr;
  1034. if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
  1035. Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
  1036. InstParams));
  1037. else
  1038. Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
  1039. D->getTemplatedDecl(),
  1040. InstParams));
  1041. if (!Instantiated)
  1042. return nullptr;
  1043. // Link the instantiated function template declaration to the function
  1044. // template from which it was instantiated.
  1045. FunctionTemplateDecl *InstTemplate
  1046. = Instantiated->getDescribedFunctionTemplate();
  1047. InstTemplate->setAccess(D->getAccess());
  1048. assert(InstTemplate &&
  1049. "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
  1050. bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
  1051. // Link the instantiation back to the pattern *unless* this is a
  1052. // non-definition friend declaration.
  1053. if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
  1054. !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
  1055. InstTemplate->setInstantiatedFromMemberTemplate(D);
  1056. // Make declarations visible in the appropriate context.
  1057. if (!isFriend) {
  1058. Owner->addDecl(InstTemplate);
  1059. } else if (InstTemplate->getDeclContext()->isRecord() &&
  1060. !getPreviousDeclForInstantiation(D)) {
  1061. SemaRef.CheckFriendAccess(InstTemplate);
  1062. }
  1063. return InstTemplate;
  1064. }
  1065. Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
  1066. CXXRecordDecl *PrevDecl = nullptr;
  1067. if (D->isInjectedClassName())
  1068. PrevDecl = cast<CXXRecordDecl>(Owner);
  1069. else if (CXXRecordDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
  1070. NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
  1071. PatternPrev,
  1072. TemplateArgs);
  1073. if (!Prev) return nullptr;
  1074. PrevDecl = cast<CXXRecordDecl>(Prev);
  1075. }
  1076. CXXRecordDecl *Record
  1077. = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
  1078. D->getLocStart(), D->getLocation(),
  1079. D->getIdentifier(), PrevDecl);
  1080. // Substitute the nested name specifier, if any.
  1081. if (SubstQualifier(D, Record))
  1082. return nullptr;
  1083. Record->setImplicit(D->isImplicit());
  1084. // FIXME: Check against AS_none is an ugly hack to work around the issue that
  1085. // the tag decls introduced by friend class declarations don't have an access
  1086. // specifier. Remove once this area of the code gets sorted out.
  1087. if (D->getAccess() != AS_none)
  1088. Record->setAccess(D->getAccess());
  1089. if (!D->isInjectedClassName())
  1090. Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
  1091. // If the original function was part of a friend declaration,
  1092. // inherit its namespace state.
  1093. if (D->getFriendObjectKind())
  1094. Record->setObjectOfFriendDecl();
  1095. // Make sure that anonymous structs and unions are recorded.
  1096. if (D->isAnonymousStructOrUnion())
  1097. Record->setAnonymousStructOrUnion(true);
  1098. if (D->isLocalClass())
  1099. SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
  1100. // Forward the mangling number from the template to the instantiated decl.
  1101. SemaRef.Context.setManglingNumber(Record,
  1102. SemaRef.Context.getManglingNumber(D));
  1103. Owner->addDecl(Record);
  1104. // DR1484 clarifies that the members of a local class are instantiated as part
  1105. // of the instantiation of their enclosing entity.
  1106. if (D->isCompleteDefinition() && D->isLocalClass()) {
  1107. Sema::SavePendingLocalImplicitInstantiationsRAII
  1108. SavedPendingLocalImplicitInstantiations(SemaRef);
  1109. SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
  1110. TSK_ImplicitInstantiation,
  1111. /*Complain=*/true);
  1112. SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
  1113. TSK_ImplicitInstantiation);
  1114. // This class may have local implicit instantiations that need to be
  1115. // performed within this scope.
  1116. SemaRef.PerformPendingInstantiations(/*LocalOnly=*/true);
  1117. }
  1118. SemaRef.DiagnoseUnusedNestedTypedefs(Record);
  1119. return Record;
  1120. }
  1121. /// \brief Adjust the given function type for an instantiation of the
  1122. /// given declaration, to cope with modifications to the function's type that
  1123. /// aren't reflected in the type-source information.
  1124. ///
  1125. /// \param D The declaration we're instantiating.
  1126. /// \param TInfo The already-instantiated type.
  1127. static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
  1128. FunctionDecl *D,
  1129. TypeSourceInfo *TInfo) {
  1130. const FunctionProtoType *OrigFunc
  1131. = D->getType()->castAs<FunctionProtoType>();
  1132. const FunctionProtoType *NewFunc
  1133. = TInfo->getType()->castAs<FunctionProtoType>();
  1134. if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
  1135. return TInfo->getType();
  1136. FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
  1137. NewEPI.ExtInfo = OrigFunc->getExtInfo();
  1138. return Context.getFunctionType(NewFunc->getReturnType(),
  1139. NewFunc->getParamTypes(), NewEPI, NewFunc->getParamMods()); // HLSL Change
  1140. }
  1141. /// Normal class members are of more specific types and therefore
  1142. /// don't make it here. This function serves two purposes:
  1143. /// 1) instantiating function templates
  1144. /// 2) substituting friend declarations
  1145. Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
  1146. TemplateParameterList *TemplateParams) {
  1147. // Check whether there is already a function template specialization for
  1148. // this declaration.
  1149. FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
  1150. if (FunctionTemplate && !TemplateParams) {
  1151. ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
  1152. void *InsertPos = nullptr;
  1153. FunctionDecl *SpecFunc
  1154. = FunctionTemplate->findSpecialization(Innermost, InsertPos);
  1155. // If we already have a function template specialization, return it.
  1156. if (SpecFunc)
  1157. return SpecFunc;
  1158. }
  1159. bool isFriend;
  1160. if (FunctionTemplate)
  1161. isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
  1162. else
  1163. isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
  1164. bool MergeWithParentScope = (TemplateParams != nullptr) ||
  1165. Owner->isFunctionOrMethod() ||
  1166. !(isa<Decl>(Owner) &&
  1167. cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
  1168. LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
  1169. SmallVector<ParmVarDecl *, 4> Params;
  1170. TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
  1171. if (!TInfo)
  1172. return nullptr;
  1173. QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
  1174. NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
  1175. if (QualifierLoc) {
  1176. QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
  1177. TemplateArgs);
  1178. if (!QualifierLoc)
  1179. return nullptr;
  1180. }
  1181. // If we're instantiating a local function declaration, put the result
  1182. // in the enclosing namespace; otherwise we need to find the instantiated
  1183. // context.
  1184. DeclContext *DC;
  1185. if (D->isLocalExternDecl()) {
  1186. DC = Owner;
  1187. SemaRef.adjustContextForLocalExternDecl(DC);
  1188. } else if (isFriend && QualifierLoc) {
  1189. CXXScopeSpec SS;
  1190. SS.Adopt(QualifierLoc);
  1191. DC = SemaRef.computeDeclContext(SS);
  1192. if (!DC) return nullptr;
  1193. } else {
  1194. DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
  1195. TemplateArgs);
  1196. }
  1197. FunctionDecl *Function =
  1198. FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
  1199. D->getNameInfo(), T, TInfo,
  1200. D->getCanonicalDecl()->getStorageClass(),
  1201. D->isInlineSpecified(), D->hasWrittenPrototype(),
  1202. D->isConstexpr());
  1203. Function->setRangeEnd(D->getSourceRange().getEnd());
  1204. if (D->isInlined())
  1205. Function->setImplicitlyInline();
  1206. if (QualifierLoc)
  1207. Function->setQualifierInfo(QualifierLoc);
  1208. if (D->isLocalExternDecl())
  1209. Function->setLocalExternDecl();
  1210. DeclContext *LexicalDC = Owner;
  1211. if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
  1212. assert(D->getDeclContext()->isFileContext());
  1213. LexicalDC = D->getDeclContext();
  1214. }
  1215. Function->setLexicalDeclContext(LexicalDC);
  1216. // Attach the parameters
  1217. for (unsigned P = 0; P < Params.size(); ++P)
  1218. if (Params[P])
  1219. Params[P]->setOwningFunction(Function);
  1220. Function->setParams(Params);
  1221. SourceLocation InstantiateAtPOI;
  1222. if (TemplateParams) {
  1223. // Our resulting instantiation is actually a function template, since we
  1224. // are substituting only the outer template parameters. For example, given
  1225. //
  1226. // template<typename T>
  1227. // struct X {
  1228. // template<typename U> friend void f(T, U);
  1229. // };
  1230. //
  1231. // X<int> x;
  1232. //
  1233. // We are instantiating the friend function template "f" within X<int>,
  1234. // which means substituting int for T, but leaving "f" as a friend function
  1235. // template.
  1236. // Build the function template itself.
  1237. FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
  1238. Function->getLocation(),
  1239. Function->getDeclName(),
  1240. TemplateParams, Function);
  1241. Function->setDescribedFunctionTemplate(FunctionTemplate);
  1242. FunctionTemplate->setLexicalDeclContext(LexicalDC);
  1243. if (isFriend && D->isThisDeclarationADefinition()) {
  1244. // TODO: should we remember this connection regardless of whether
  1245. // the friend declaration provided a body?
  1246. FunctionTemplate->setInstantiatedFromMemberTemplate(
  1247. D->getDescribedFunctionTemplate());
  1248. }
  1249. } else if (FunctionTemplate) {
  1250. // Record this function template specialization.
  1251. ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
  1252. Function->setFunctionTemplateSpecialization(FunctionTemplate,
  1253. TemplateArgumentList::CreateCopy(SemaRef.Context,
  1254. Innermost.begin(),
  1255. Innermost.size()),
  1256. /*InsertPos=*/nullptr);
  1257. } else if (isFriend) {
  1258. // Note, we need this connection even if the friend doesn't have a body.
  1259. // Its body may exist but not have been attached yet due to deferred
  1260. // parsing.
  1261. // FIXME: It might be cleaner to set this when attaching the body to the
  1262. // friend function declaration, however that would require finding all the
  1263. // instantiations and modifying them.
  1264. Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
  1265. }
  1266. if (InitFunctionInstantiation(Function, D))
  1267. Function->setInvalidDecl();
  1268. bool isExplicitSpecialization = false;
  1269. LookupResult Previous(
  1270. SemaRef, Function->getDeclName(), SourceLocation(),
  1271. D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
  1272. : Sema::LookupOrdinaryName,
  1273. Sema::ForRedeclaration);
  1274. if (DependentFunctionTemplateSpecializationInfo *Info
  1275. = D->getDependentSpecializationInfo()) {
  1276. assert(isFriend && "non-friend has dependent specialization info?");
  1277. // This needs to be set now for future sanity.
  1278. Function->setObjectOfFriendDecl();
  1279. // Instantiate the explicit template arguments.
  1280. TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
  1281. Info->getRAngleLoc());
  1282. if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
  1283. ExplicitArgs, TemplateArgs))
  1284. return nullptr;
  1285. // Map the candidate templates to their instantiations.
  1286. for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
  1287. Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
  1288. Info->getTemplate(I),
  1289. TemplateArgs);
  1290. if (!Temp) return nullptr;
  1291. Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
  1292. }
  1293. if (SemaRef.CheckFunctionTemplateSpecialization(Function,
  1294. &ExplicitArgs,
  1295. Previous))
  1296. Function->setInvalidDecl();
  1297. isExplicitSpecialization = true;
  1298. } else if (TemplateParams || !FunctionTemplate) {
  1299. // Look only into the namespace where the friend would be declared to
  1300. // find a previous declaration. This is the innermost enclosing namespace,
  1301. // as described in ActOnFriendFunctionDecl.
  1302. SemaRef.LookupQualifiedName(Previous, DC);
  1303. // In C++, the previous declaration we find might be a tag type
  1304. // (class or enum). In this case, the new declaration will hide the
  1305. // tag type. Note that this does does not apply if we're declaring a
  1306. // typedef (C++ [dcl.typedef]p4).
  1307. if (Previous.isSingleTagDecl())
  1308. Previous.clear();
  1309. }
  1310. SemaRef.CheckFunctionDeclaration(/*Scope*/ nullptr, Function, Previous,
  1311. isExplicitSpecialization);
  1312. NamedDecl *PrincipalDecl = (TemplateParams
  1313. ? cast<NamedDecl>(FunctionTemplate)
  1314. : Function);
  1315. // If the original function was part of a friend declaration,
  1316. // inherit its namespace state and add it to the owner.
  1317. if (isFriend) {
  1318. PrincipalDecl->setObjectOfFriendDecl();
  1319. DC->makeDeclVisibleInContext(PrincipalDecl);
  1320. bool QueuedInstantiation = false;
  1321. // C++11 [temp.friend]p4 (DR329):
  1322. // When a function is defined in a friend function declaration in a class
  1323. // template, the function is instantiated when the function is odr-used.
  1324. // The same restrictions on multiple declarations and definitions that
  1325. // apply to non-template function declarations and definitions also apply
  1326. // to these implicit definitions.
  1327. if (D->isThisDeclarationADefinition()) {
  1328. // Check for a function body.
  1329. const FunctionDecl *Definition = nullptr;
  1330. if (Function->isDefined(Definition) &&
  1331. Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
  1332. SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
  1333. << Function->getDeclName();
  1334. SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
  1335. }
  1336. // Check for redefinitions due to other instantiations of this or
  1337. // a similar friend function.
  1338. else for (auto R : Function->redecls()) {
  1339. if (R == Function)
  1340. continue;
  1341. // If some prior declaration of this function has been used, we need
  1342. // to instantiate its definition.
  1343. if (!QueuedInstantiation && R->isUsed(false)) {
  1344. if (MemberSpecializationInfo *MSInfo =
  1345. Function->getMemberSpecializationInfo()) {
  1346. if (MSInfo->getPointOfInstantiation().isInvalid()) {
  1347. SourceLocation Loc = R->getLocation(); // FIXME
  1348. MSInfo->setPointOfInstantiation(Loc);
  1349. SemaRef.PendingLocalImplicitInstantiations.push_back(
  1350. std::make_pair(Function, Loc));
  1351. QueuedInstantiation = true;
  1352. }
  1353. }
  1354. }
  1355. // If some prior declaration of this function was a friend with an
  1356. // uninstantiated definition, reject it.
  1357. if (R->getFriendObjectKind()) {
  1358. if (const FunctionDecl *RPattern =
  1359. R->getTemplateInstantiationPattern()) {
  1360. if (RPattern->isDefined(RPattern)) {
  1361. SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
  1362. << Function->getDeclName();
  1363. SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
  1364. break;
  1365. }
  1366. }
  1367. }
  1368. }
  1369. }
  1370. }
  1371. if (Function->isLocalExternDecl() && !Function->getPreviousDecl())
  1372. DC->makeDeclVisibleInContext(PrincipalDecl);
  1373. if (Function->isOverloadedOperator() && !DC->isRecord() &&
  1374. PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
  1375. PrincipalDecl->setNonMemberOperator();
  1376. assert(!D->isDefaulted() && "only methods should be defaulted");
  1377. return Function;
  1378. }
  1379. Decl *
  1380. TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
  1381. TemplateParameterList *TemplateParams,
  1382. bool IsClassScopeSpecialization) {
  1383. FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
  1384. if (FunctionTemplate && !TemplateParams) {
  1385. // We are creating a function template specialization from a function
  1386. // template. Check whether there is already a function template
  1387. // specialization for this particular set of template arguments.
  1388. ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
  1389. void *InsertPos = nullptr;
  1390. FunctionDecl *SpecFunc
  1391. = FunctionTemplate->findSpecialization(Innermost, InsertPos);
  1392. // If we already have a function template specialization, return it.
  1393. if (SpecFunc)
  1394. return SpecFunc;
  1395. }
  1396. bool isFriend;
  1397. if (FunctionTemplate)
  1398. isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
  1399. else
  1400. isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
  1401. bool MergeWithParentScope = (TemplateParams != nullptr) ||
  1402. !(isa<Decl>(Owner) &&
  1403. cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
  1404. LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
  1405. // Instantiate enclosing template arguments for friends.
  1406. SmallVector<TemplateParameterList *, 4> TempParamLists;
  1407. unsigned NumTempParamLists = 0;
  1408. if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
  1409. TempParamLists.set_size(NumTempParamLists);
  1410. for (unsigned I = 0; I != NumTempParamLists; ++I) {
  1411. TemplateParameterList *TempParams = D->getTemplateParameterList(I);
  1412. TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
  1413. if (!InstParams)
  1414. return nullptr;
  1415. TempParamLists[I] = InstParams;
  1416. }
  1417. }
  1418. SmallVector<ParmVarDecl *, 4> Params;
  1419. TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
  1420. if (!TInfo)
  1421. return nullptr;
  1422. QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
  1423. NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
  1424. if (QualifierLoc) {
  1425. QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
  1426. TemplateArgs);
  1427. if (!QualifierLoc)
  1428. return nullptr;
  1429. }
  1430. DeclContext *DC = Owner;
  1431. if (isFriend) {
  1432. if (QualifierLoc) {
  1433. CXXScopeSpec SS;
  1434. SS.Adopt(QualifierLoc);
  1435. DC = SemaRef.computeDeclContext(SS);
  1436. if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
  1437. return nullptr;
  1438. } else {
  1439. DC = SemaRef.FindInstantiatedContext(D->getLocation(),
  1440. D->getDeclContext(),
  1441. TemplateArgs);
  1442. }
  1443. if (!DC) return nullptr;
  1444. }
  1445. // Build the instantiated method declaration.
  1446. CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
  1447. CXXMethodDecl *Method = nullptr;
  1448. SourceLocation StartLoc = D->getInnerLocStart();
  1449. DeclarationNameInfo NameInfo
  1450. = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
  1451. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
  1452. Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
  1453. StartLoc, NameInfo, T, TInfo,
  1454. Constructor->isExplicit(),
  1455. Constructor->isInlineSpecified(),
  1456. false, Constructor->isConstexpr());
  1457. // Claim that the instantiation of a constructor or constructor template
  1458. // inherits the same constructor that the template does.
  1459. if (CXXConstructorDecl *Inh = const_cast<CXXConstructorDecl *>(
  1460. Constructor->getInheritedConstructor())) {
  1461. // If we're instantiating a specialization of a function template, our
  1462. // "inherited constructor" will actually itself be a function template.
  1463. // Instantiate a declaration of it, too.
  1464. if (FunctionTemplate) {
  1465. assert(!TemplateParams && Inh->getDescribedFunctionTemplate() &&
  1466. !Inh->getParent()->isDependentContext() &&
  1467. "inheriting constructor template in dependent context?");
  1468. Sema::InstantiatingTemplate Inst(SemaRef, Constructor->getLocation(),
  1469. Inh);
  1470. if (Inst.isInvalid())
  1471. return nullptr;
  1472. Sema::ContextRAII SavedContext(SemaRef, Inh->getDeclContext());
  1473. LocalInstantiationScope LocalScope(SemaRef);
  1474. // Use the same template arguments that we deduced for the inheriting
  1475. // constructor. There's no way they could be deduced differently.
  1476. MultiLevelTemplateArgumentList InheritedArgs;
  1477. InheritedArgs.addOuterTemplateArguments(TemplateArgs.getInnermost());
  1478. Inh = cast_or_null<CXXConstructorDecl>(
  1479. SemaRef.SubstDecl(Inh, Inh->getDeclContext(), InheritedArgs));
  1480. if (!Inh)
  1481. return nullptr;
  1482. }
  1483. cast<CXXConstructorDecl>(Method)->setInheritedConstructor(Inh);
  1484. }
  1485. } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
  1486. Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
  1487. StartLoc, NameInfo, T, TInfo,
  1488. Destructor->isInlineSpecified(),
  1489. false);
  1490. } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
  1491. Method = CXXConversionDecl::Create(SemaRef.Context, Record,
  1492. StartLoc, NameInfo, T, TInfo,
  1493. Conversion->isInlineSpecified(),
  1494. Conversion->isExplicit(),
  1495. Conversion->isConstexpr(),
  1496. Conversion->getLocEnd());
  1497. } else {
  1498. StorageClass SC = D->isStatic() ? SC_Static : SC_None;
  1499. Method = CXXMethodDecl::Create(SemaRef.Context, Record,
  1500. StartLoc, NameInfo, T, TInfo,
  1501. SC, D->isInlineSpecified(),
  1502. D->isConstexpr(), D->getLocEnd());
  1503. }
  1504. if (D->isInlined())
  1505. Method->setImplicitlyInline();
  1506. if (QualifierLoc)
  1507. Method->setQualifierInfo(QualifierLoc);
  1508. if (TemplateParams) {
  1509. // Our resulting instantiation is actually a function template, since we
  1510. // are substituting only the outer template parameters. For example, given
  1511. //
  1512. // template<typename T>
  1513. // struct X {
  1514. // template<typename U> void f(T, U);
  1515. // };
  1516. //
  1517. // X<int> x;
  1518. //
  1519. // We are instantiating the member template "f" within X<int>, which means
  1520. // substituting int for T, but leaving "f" as a member function template.
  1521. // Build the function template itself.
  1522. FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
  1523. Method->getLocation(),
  1524. Method->getDeclName(),
  1525. TemplateParams, Method);
  1526. if (isFriend) {
  1527. FunctionTemplate->setLexicalDeclContext(Owner);
  1528. FunctionTemplate->setObjectOfFriendDecl();
  1529. } else if (D->isOutOfLine())
  1530. FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
  1531. Method->setDescribedFunctionTemplate(FunctionTemplate);
  1532. } else if (FunctionTemplate) {
  1533. // Record this function template specialization.
  1534. ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
  1535. Method->setFunctionTemplateSpecialization(FunctionTemplate,
  1536. TemplateArgumentList::CreateCopy(SemaRef.Context,
  1537. Innermost.begin(),
  1538. Innermost.size()),
  1539. /*InsertPos=*/nullptr);
  1540. } else if (!isFriend) {
  1541. // Record that this is an instantiation of a member function.
  1542. Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
  1543. }
  1544. // If we are instantiating a member function defined
  1545. // out-of-line, the instantiation will have the same lexical
  1546. // context (which will be a namespace scope) as the template.
  1547. if (isFriend) {
  1548. if (NumTempParamLists)
  1549. Method->setTemplateParameterListsInfo(SemaRef.Context,
  1550. NumTempParamLists,
  1551. TempParamLists.data());
  1552. Method->setLexicalDeclContext(Owner);
  1553. Method->setObjectOfFriendDecl();
  1554. } else if (D->isOutOfLine())
  1555. Method->setLexicalDeclContext(D->getLexicalDeclContext());
  1556. // Attach the parameters
  1557. for (unsigned P = 0; P < Params.size(); ++P)
  1558. Params[P]->setOwningFunction(Method);
  1559. Method->setParams(Params);
  1560. if (InitMethodInstantiation(Method, D))
  1561. Method->setInvalidDecl();
  1562. LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
  1563. Sema::ForRedeclaration);
  1564. if (!FunctionTemplate || TemplateParams || isFriend) {
  1565. SemaRef.LookupQualifiedName(Previous, Record);
  1566. // In C++, the previous declaration we find might be a tag type
  1567. // (class or enum). In this case, the new declaration will hide the
  1568. // tag type. Note that this does does not apply if we're declaring a
  1569. // typedef (C++ [dcl.typedef]p4).
  1570. if (Previous.isSingleTagDecl())
  1571. Previous.clear();
  1572. }
  1573. if (!IsClassScopeSpecialization)
  1574. SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous, false);
  1575. if (D->isPure())
  1576. SemaRef.CheckPureMethod(Method, SourceRange());
  1577. // Propagate access. For a non-friend declaration, the access is
  1578. // whatever we're propagating from. For a friend, it should be the
  1579. // previous declaration we just found.
  1580. if (isFriend && Method->getPreviousDecl())
  1581. Method->setAccess(Method->getPreviousDecl()->getAccess());
  1582. else
  1583. Method->setAccess(D->getAccess());
  1584. if (FunctionTemplate)
  1585. FunctionTemplate->setAccess(Method->getAccess());
  1586. SemaRef.CheckOverrideControl(Method);
  1587. // If a function is defined as defaulted or deleted, mark it as such now.
  1588. if (D->isExplicitlyDefaulted())
  1589. SemaRef.SetDeclDefaulted(Method, Method->getLocation());
  1590. if (D->isDeletedAsWritten())
  1591. SemaRef.SetDeclDeleted(Method, Method->getLocation());
  1592. // If there's a function template, let our caller handle it.
  1593. if (FunctionTemplate) {
  1594. // do nothing
  1595. // Don't hide a (potentially) valid declaration with an invalid one.
  1596. } else if (Method->isInvalidDecl() && !Previous.empty()) {
  1597. // do nothing
  1598. // Otherwise, check access to friends and make them visible.
  1599. } else if (isFriend) {
  1600. // We only need to re-check access for methods which we didn't
  1601. // manage to match during parsing.
  1602. if (!D->getPreviousDecl())
  1603. SemaRef.CheckFriendAccess(Method);
  1604. Record->makeDeclVisibleInContext(Method);
  1605. // Otherwise, add the declaration. We don't need to do this for
  1606. // class-scope specializations because we'll have matched them with
  1607. // the appropriate template.
  1608. } else if (!IsClassScopeSpecialization) {
  1609. Owner->addDecl(Method);
  1610. }
  1611. return Method;
  1612. }
  1613. Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
  1614. return VisitCXXMethodDecl(D);
  1615. }
  1616. Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
  1617. return VisitCXXMethodDecl(D);
  1618. }
  1619. Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
  1620. return VisitCXXMethodDecl(D);
  1621. }
  1622. Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
  1623. return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None,
  1624. /*ExpectParameterPack=*/ false);
  1625. }
  1626. Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
  1627. TemplateTypeParmDecl *D) {
  1628. // TODO: don't always clone when decls are refcounted.
  1629. assert(D->getTypeForDecl()->isTemplateTypeParmType());
  1630. TemplateTypeParmDecl *Inst =
  1631. TemplateTypeParmDecl::Create(SemaRef.Context, Owner,
  1632. D->getLocStart(), D->getLocation(),
  1633. D->getDepth() - TemplateArgs.getNumLevels(),
  1634. D->getIndex(), D->getIdentifier(),
  1635. D->wasDeclaredWithTypename(),
  1636. D->isParameterPack());
  1637. Inst->setAccess(AS_public);
  1638. if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
  1639. TypeSourceInfo *InstantiatedDefaultArg =
  1640. SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs,
  1641. D->getDefaultArgumentLoc(), D->getDeclName());
  1642. if (InstantiatedDefaultArg)
  1643. Inst->setDefaultArgument(InstantiatedDefaultArg);
  1644. }
  1645. // Introduce this template parameter's instantiation into the instantiation
  1646. // scope.
  1647. SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
  1648. return Inst;
  1649. }
  1650. Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
  1651. NonTypeTemplateParmDecl *D) {
  1652. // Substitute into the type of the non-type template parameter.
  1653. TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
  1654. SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
  1655. SmallVector<QualType, 4> ExpandedParameterPackTypes;
  1656. bool IsExpandedParameterPack = false;
  1657. TypeSourceInfo *DI;
  1658. QualType T;
  1659. bool Invalid = false;
  1660. if (D->isExpandedParameterPack()) {
  1661. // The non-type template parameter pack is an already-expanded pack
  1662. // expansion of types. Substitute into each of the expanded types.
  1663. ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
  1664. ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
  1665. for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
  1666. TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I),
  1667. TemplateArgs,
  1668. D->getLocation(),
  1669. D->getDeclName());
  1670. if (!NewDI)
  1671. return nullptr;
  1672. ExpandedParameterPackTypesAsWritten.push_back(NewDI);
  1673. QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
  1674. D->getLocation());
  1675. if (NewT.isNull())
  1676. return nullptr;
  1677. ExpandedParameterPackTypes.push_back(NewT);
  1678. }
  1679. IsExpandedParameterPack = true;
  1680. DI = D->getTypeSourceInfo();
  1681. T = DI->getType();
  1682. } else if (D->isPackExpansion()) {
  1683. // The non-type template parameter pack's type is a pack expansion of types.
  1684. // Determine whether we need to expand this parameter pack into separate
  1685. // types.
  1686. PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
  1687. TypeLoc Pattern = Expansion.getPatternLoc();
  1688. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  1689. SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
  1690. // Determine whether the set of unexpanded parameter packs can and should
  1691. // be expanded.
  1692. bool Expand = true;
  1693. bool RetainExpansion = false;
  1694. Optional<unsigned> OrigNumExpansions
  1695. = Expansion.getTypePtr()->getNumExpansions();
  1696. Optional<unsigned> NumExpansions = OrigNumExpansions;
  1697. if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
  1698. Pattern.getSourceRange(),
  1699. Unexpanded,
  1700. TemplateArgs,
  1701. Expand, RetainExpansion,
  1702. NumExpansions))
  1703. return nullptr;
  1704. if (Expand) {
  1705. for (unsigned I = 0; I != *NumExpansions; ++I) {
  1706. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
  1707. TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
  1708. D->getLocation(),
  1709. D->getDeclName());
  1710. if (!NewDI)
  1711. return nullptr;
  1712. ExpandedParameterPackTypesAsWritten.push_back(NewDI);
  1713. QualType NewT = SemaRef.CheckNonTypeTemplateParameterType(
  1714. NewDI->getType(),
  1715. D->getLocation());
  1716. if (NewT.isNull())
  1717. return nullptr;
  1718. ExpandedParameterPackTypes.push_back(NewT);
  1719. }
  1720. // Note that we have an expanded parameter pack. The "type" of this
  1721. // expanded parameter pack is the original expansion type, but callers
  1722. // will end up using the expanded parameter pack types for type-checking.
  1723. IsExpandedParameterPack = true;
  1724. DI = D->getTypeSourceInfo();
  1725. T = DI->getType();
  1726. } else {
  1727. // We cannot fully expand the pack expansion now, so substitute into the
  1728. // pattern and create a new pack expansion type.
  1729. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
  1730. TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
  1731. D->getLocation(),
  1732. D->getDeclName());
  1733. if (!NewPattern)
  1734. return nullptr;
  1735. DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
  1736. NumExpansions);
  1737. if (!DI)
  1738. return nullptr;
  1739. T = DI->getType();
  1740. }
  1741. } else {
  1742. // Simple case: substitution into a parameter that is not a parameter pack.
  1743. DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
  1744. D->getLocation(), D->getDeclName());
  1745. if (!DI)
  1746. return nullptr;
  1747. // Check that this type is acceptable for a non-type template parameter.
  1748. T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
  1749. D->getLocation());
  1750. if (T.isNull()) {
  1751. T = SemaRef.Context.IntTy;
  1752. Invalid = true;
  1753. }
  1754. }
  1755. NonTypeTemplateParmDecl *Param;
  1756. if (IsExpandedParameterPack)
  1757. Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
  1758. D->getInnerLocStart(),
  1759. D->getLocation(),
  1760. D->getDepth() - TemplateArgs.getNumLevels(),
  1761. D->getPosition(),
  1762. D->getIdentifier(), T,
  1763. DI,
  1764. ExpandedParameterPackTypes.data(),
  1765. ExpandedParameterPackTypes.size(),
  1766. ExpandedParameterPackTypesAsWritten.data());
  1767. else
  1768. Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
  1769. D->getInnerLocStart(),
  1770. D->getLocation(),
  1771. D->getDepth() - TemplateArgs.getNumLevels(),
  1772. D->getPosition(),
  1773. D->getIdentifier(), T,
  1774. D->isParameterPack(), DI);
  1775. Param->setAccess(AS_public);
  1776. if (Invalid)
  1777. Param->setInvalidDecl();
  1778. if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
  1779. ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs);
  1780. if (!Value.isInvalid())
  1781. Param->setDefaultArgument(Value.get());
  1782. }
  1783. // Introduce this template parameter's instantiation into the instantiation
  1784. // scope.
  1785. SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
  1786. return Param;
  1787. }
  1788. static void collectUnexpandedParameterPacks(
  1789. Sema &S,
  1790. TemplateParameterList *Params,
  1791. SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
  1792. for (const auto &P : *Params) {
  1793. if (P->isTemplateParameterPack())
  1794. continue;
  1795. if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P))
  1796. S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
  1797. Unexpanded);
  1798. if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(P))
  1799. collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
  1800. Unexpanded);
  1801. }
  1802. }
  1803. Decl *
  1804. TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
  1805. TemplateTemplateParmDecl *D) {
  1806. // Instantiate the template parameter list of the template template parameter.
  1807. TemplateParameterList *TempParams = D->getTemplateParameters();
  1808. TemplateParameterList *InstParams;
  1809. SmallVector<TemplateParameterList*, 8> ExpandedParams;
  1810. bool IsExpandedParameterPack = false;
  1811. if (D->isExpandedParameterPack()) {
  1812. // The template template parameter pack is an already-expanded pack
  1813. // expansion of template parameters. Substitute into each of the expanded
  1814. // parameters.
  1815. ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
  1816. for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
  1817. I != N; ++I) {
  1818. LocalInstantiationScope Scope(SemaRef);
  1819. TemplateParameterList *Expansion =
  1820. SubstTemplateParams(D->getExpansionTemplateParameters(I));
  1821. if (!Expansion)
  1822. return nullptr;
  1823. ExpandedParams.push_back(Expansion);
  1824. }
  1825. IsExpandedParameterPack = true;
  1826. InstParams = TempParams;
  1827. } else if (D->isPackExpansion()) {
  1828. // The template template parameter pack expands to a pack of template
  1829. // template parameters. Determine whether we need to expand this parameter
  1830. // pack into separate parameters.
  1831. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  1832. collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
  1833. Unexpanded);
  1834. // Determine whether the set of unexpanded parameter packs can and should
  1835. // be expanded.
  1836. bool Expand = true;
  1837. bool RetainExpansion = false;
  1838. Optional<unsigned> NumExpansions;
  1839. if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
  1840. TempParams->getSourceRange(),
  1841. Unexpanded,
  1842. TemplateArgs,
  1843. Expand, RetainExpansion,
  1844. NumExpansions))
  1845. return nullptr;
  1846. if (Expand) {
  1847. for (unsigned I = 0; I != *NumExpansions; ++I) {
  1848. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
  1849. LocalInstantiationScope Scope(SemaRef);
  1850. TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
  1851. if (!Expansion)
  1852. return nullptr;
  1853. ExpandedParams.push_back(Expansion);
  1854. }
  1855. // Note that we have an expanded parameter pack. The "type" of this
  1856. // expanded parameter pack is the original expansion type, but callers
  1857. // will end up using the expanded parameter pack types for type-checking.
  1858. IsExpandedParameterPack = true;
  1859. InstParams = TempParams;
  1860. } else {
  1861. // We cannot fully expand the pack expansion now, so just substitute
  1862. // into the pattern.
  1863. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
  1864. LocalInstantiationScope Scope(SemaRef);
  1865. InstParams = SubstTemplateParams(TempParams);
  1866. if (!InstParams)
  1867. return nullptr;
  1868. }
  1869. } else {
  1870. // Perform the actual substitution of template parameters within a new,
  1871. // local instantiation scope.
  1872. LocalInstantiationScope Scope(SemaRef);
  1873. InstParams = SubstTemplateParams(TempParams);
  1874. if (!InstParams)
  1875. return nullptr;
  1876. }
  1877. // Build the template template parameter.
  1878. TemplateTemplateParmDecl *Param;
  1879. if (IsExpandedParameterPack)
  1880. Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
  1881. D->getLocation(),
  1882. D->getDepth() - TemplateArgs.getNumLevels(),
  1883. D->getPosition(),
  1884. D->getIdentifier(), InstParams,
  1885. ExpandedParams);
  1886. else
  1887. Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
  1888. D->getLocation(),
  1889. D->getDepth() - TemplateArgs.getNumLevels(),
  1890. D->getPosition(),
  1891. D->isParameterPack(),
  1892. D->getIdentifier(), InstParams);
  1893. if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
  1894. NestedNameSpecifierLoc QualifierLoc =
  1895. D->getDefaultArgument().getTemplateQualifierLoc();
  1896. QualifierLoc =
  1897. SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
  1898. TemplateName TName = SemaRef.SubstTemplateName(
  1899. QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
  1900. D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
  1901. if (!TName.isNull())
  1902. Param->setDefaultArgument(
  1903. SemaRef.Context,
  1904. TemplateArgumentLoc(TemplateArgument(TName),
  1905. D->getDefaultArgument().getTemplateQualifierLoc(),
  1906. D->getDefaultArgument().getTemplateNameLoc()));
  1907. }
  1908. Param->setAccess(AS_public);
  1909. // Introduce this template parameter's instantiation into the instantiation
  1910. // scope.
  1911. SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
  1912. return Param;
  1913. }
  1914. Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
  1915. // Using directives are never dependent (and never contain any types or
  1916. // expressions), so they require no explicit instantiation work.
  1917. UsingDirectiveDecl *Inst
  1918. = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
  1919. D->getNamespaceKeyLocation(),
  1920. D->getQualifierLoc(),
  1921. D->getIdentLocation(),
  1922. D->getNominatedNamespace(),
  1923. D->getCommonAncestor());
  1924. // Add the using directive to its declaration context
  1925. // only if this is not a function or method.
  1926. if (!Owner->isFunctionOrMethod())
  1927. Owner->addDecl(Inst);
  1928. return Inst;
  1929. }
  1930. Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
  1931. // The nested name specifier may be dependent, for example
  1932. // template <typename T> struct t {
  1933. // struct s1 { T f1(); };
  1934. // struct s2 : s1 { using s1::f1; };
  1935. // };
  1936. // template struct t<int>;
  1937. // Here, in using s1::f1, s1 refers to t<T>::s1;
  1938. // we need to substitute for t<int>::s1.
  1939. NestedNameSpecifierLoc QualifierLoc
  1940. = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
  1941. TemplateArgs);
  1942. if (!QualifierLoc)
  1943. return nullptr;
  1944. // The name info is non-dependent, so no transformation
  1945. // is required.
  1946. DeclarationNameInfo NameInfo = D->getNameInfo();
  1947. // We only need to do redeclaration lookups if we're in a class
  1948. // scope (in fact, it's not really even possible in non-class
  1949. // scopes).
  1950. bool CheckRedeclaration = Owner->isRecord();
  1951. LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
  1952. Sema::ForRedeclaration);
  1953. UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
  1954. D->getUsingLoc(),
  1955. QualifierLoc,
  1956. NameInfo,
  1957. D->hasTypename());
  1958. CXXScopeSpec SS;
  1959. SS.Adopt(QualifierLoc);
  1960. if (CheckRedeclaration) {
  1961. Prev.setHideTags(false);
  1962. SemaRef.LookupQualifiedName(Prev, Owner);
  1963. // Check for invalid redeclarations.
  1964. if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
  1965. D->hasTypename(), SS,
  1966. D->getLocation(), Prev))
  1967. NewUD->setInvalidDecl();
  1968. }
  1969. if (!NewUD->isInvalidDecl() &&
  1970. SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), SS, NameInfo,
  1971. D->getLocation()))
  1972. NewUD->setInvalidDecl();
  1973. SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
  1974. NewUD->setAccess(D->getAccess());
  1975. Owner->addDecl(NewUD);
  1976. // Don't process the shadow decls for an invalid decl.
  1977. if (NewUD->isInvalidDecl())
  1978. return NewUD;
  1979. if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
  1980. SemaRef.CheckInheritingConstructorUsingDecl(NewUD);
  1981. return NewUD;
  1982. }
  1983. bool isFunctionScope = Owner->isFunctionOrMethod();
  1984. // Process the shadow decls.
  1985. for (auto *Shadow : D->shadows()) {
  1986. NamedDecl *InstTarget =
  1987. cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
  1988. Shadow->getLocation(), Shadow->getTargetDecl(), TemplateArgs));
  1989. if (!InstTarget)
  1990. return nullptr;
  1991. UsingShadowDecl *PrevDecl = nullptr;
  1992. if (CheckRedeclaration) {
  1993. if (SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev, PrevDecl))
  1994. continue;
  1995. } else if (UsingShadowDecl *OldPrev =
  1996. getPreviousDeclForInstantiation(Shadow)) {
  1997. PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
  1998. Shadow->getLocation(), OldPrev, TemplateArgs));
  1999. }
  2000. UsingShadowDecl *InstShadow =
  2001. SemaRef.BuildUsingShadowDecl(/*Scope*/nullptr, NewUD, InstTarget,
  2002. PrevDecl);
  2003. SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
  2004. if (isFunctionScope)
  2005. SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
  2006. }
  2007. return NewUD;
  2008. }
  2009. Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
  2010. // Ignore these; we handle them in bulk when processing the UsingDecl.
  2011. return nullptr;
  2012. }
  2013. Decl * TemplateDeclInstantiator
  2014. ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
  2015. NestedNameSpecifierLoc QualifierLoc
  2016. = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
  2017. TemplateArgs);
  2018. if (!QualifierLoc)
  2019. return nullptr;
  2020. CXXScopeSpec SS;
  2021. SS.Adopt(QualifierLoc);
  2022. // Since NameInfo refers to a typename, it cannot be a C++ special name.
  2023. // Hence, no transformation is required for it.
  2024. DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
  2025. NamedDecl *UD =
  2026. SemaRef.BuildUsingDeclaration(/*Scope*/ nullptr, D->getAccess(),
  2027. D->getUsingLoc(), SS, NameInfo, nullptr,
  2028. /*instantiation*/ true,
  2029. /*typename*/ true, D->getTypenameLoc());
  2030. if (UD)
  2031. SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
  2032. return UD;
  2033. }
  2034. Decl * TemplateDeclInstantiator
  2035. ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
  2036. NestedNameSpecifierLoc QualifierLoc
  2037. = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs);
  2038. if (!QualifierLoc)
  2039. return nullptr;
  2040. CXXScopeSpec SS;
  2041. SS.Adopt(QualifierLoc);
  2042. DeclarationNameInfo NameInfo
  2043. = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
  2044. NamedDecl *UD =
  2045. SemaRef.BuildUsingDeclaration(/*Scope*/ nullptr, D->getAccess(),
  2046. D->getUsingLoc(), SS, NameInfo, nullptr,
  2047. /*instantiation*/ true,
  2048. /*typename*/ false, SourceLocation());
  2049. if (UD)
  2050. SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
  2051. return UD;
  2052. }
  2053. Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
  2054. ClassScopeFunctionSpecializationDecl *Decl) {
  2055. CXXMethodDecl *OldFD = Decl->getSpecialization();
  2056. CXXMethodDecl *NewFD =
  2057. cast_or_null<CXXMethodDecl>(VisitCXXMethodDecl(OldFD, nullptr, true));
  2058. if (!NewFD)
  2059. return nullptr;
  2060. LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName,
  2061. Sema::ForRedeclaration);
  2062. TemplateArgumentListInfo TemplateArgs;
  2063. TemplateArgumentListInfo *TemplateArgsPtr = nullptr;
  2064. if (Decl->hasExplicitTemplateArgs()) {
  2065. TemplateArgs = Decl->templateArgs();
  2066. TemplateArgsPtr = &TemplateArgs;
  2067. }
  2068. SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext);
  2069. if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, TemplateArgsPtr,
  2070. Previous)) {
  2071. NewFD->setInvalidDecl();
  2072. return NewFD;
  2073. }
  2074. // Associate the specialization with the pattern.
  2075. FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl());
  2076. assert(Specialization && "Class scope Specialization is null");
  2077. SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD);
  2078. return NewFD;
  2079. }
  2080. Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
  2081. OMPThreadPrivateDecl *D) {
  2082. SmallVector<Expr *, 5> Vars;
  2083. for (auto *I : D->varlists()) {
  2084. Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
  2085. assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
  2086. Vars.push_back(Var);
  2087. }
  2088. OMPThreadPrivateDecl *TD =
  2089. SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
  2090. TD->setAccess(AS_public);
  2091. Owner->addDecl(TD);
  2092. return TD;
  2093. }
  2094. Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
  2095. return VisitFunctionDecl(D, nullptr);
  2096. }
  2097. Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
  2098. return VisitCXXMethodDecl(D, nullptr);
  2099. }
  2100. Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
  2101. llvm_unreachable("There are only CXXRecordDecls in C++");
  2102. }
  2103. Decl *
  2104. TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
  2105. ClassTemplateSpecializationDecl *D) {
  2106. // As a MS extension, we permit class-scope explicit specialization
  2107. // of member class templates.
  2108. ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
  2109. assert(ClassTemplate->getDeclContext()->isRecord() &&
  2110. D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
  2111. "can only instantiate an explicit specialization "
  2112. "for a member class template");
  2113. // Lookup the already-instantiated declaration in the instantiation
  2114. // of the class template. FIXME: Diagnose or assert if this fails?
  2115. DeclContext::lookup_result Found
  2116. = Owner->lookup(ClassTemplate->getDeclName());
  2117. if (Found.empty())
  2118. return nullptr;
  2119. ClassTemplateDecl *InstClassTemplate
  2120. = dyn_cast<ClassTemplateDecl>(Found.front());
  2121. if (!InstClassTemplate)
  2122. return nullptr;
  2123. // Substitute into the template arguments of the class template explicit
  2124. // specialization.
  2125. TemplateSpecializationTypeLoc Loc = D->getTypeAsWritten()->getTypeLoc().
  2126. castAs<TemplateSpecializationTypeLoc>();
  2127. TemplateArgumentListInfo InstTemplateArgs(Loc.getLAngleLoc(),
  2128. Loc.getRAngleLoc());
  2129. SmallVector<TemplateArgumentLoc, 4> ArgLocs;
  2130. for (unsigned I = 0; I != Loc.getNumArgs(); ++I)
  2131. ArgLocs.push_back(Loc.getArgLoc(I));
  2132. if (SemaRef.Subst(ArgLocs.data(), ArgLocs.size(),
  2133. InstTemplateArgs, TemplateArgs))
  2134. return nullptr;
  2135. // Check that the template argument list is well-formed for this
  2136. // class template.
  2137. SmallVector<TemplateArgument, 4> Converted;
  2138. if (SemaRef.CheckTemplateArgumentList(InstClassTemplate,
  2139. D->getLocation(),
  2140. InstTemplateArgs,
  2141. false,
  2142. Converted))
  2143. return nullptr;
  2144. // Figure out where to insert this class template explicit specialization
  2145. // in the member template's set of class template explicit specializations.
  2146. void *InsertPos = nullptr;
  2147. ClassTemplateSpecializationDecl *PrevDecl =
  2148. InstClassTemplate->findSpecialization(Converted, InsertPos);
  2149. // Check whether we've already seen a conflicting instantiation of this
  2150. // declaration (for instance, if there was a prior implicit instantiation).
  2151. bool Ignored;
  2152. if (PrevDecl &&
  2153. SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(),
  2154. D->getSpecializationKind(),
  2155. PrevDecl,
  2156. PrevDecl->getSpecializationKind(),
  2157. PrevDecl->getPointOfInstantiation(),
  2158. Ignored))
  2159. return nullptr;
  2160. // If PrevDecl was a definition and D is also a definition, diagnose.
  2161. // This happens in cases like:
  2162. //
  2163. // template<typename T, typename U>
  2164. // struct Outer {
  2165. // template<typename X> struct Inner;
  2166. // template<> struct Inner<T> {};
  2167. // template<> struct Inner<U> {};
  2168. // };
  2169. //
  2170. // Outer<int, int> outer; // error: the explicit specializations of Inner
  2171. // // have the same signature.
  2172. if (PrevDecl && PrevDecl->getDefinition() &&
  2173. D->isThisDeclarationADefinition()) {
  2174. SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
  2175. SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
  2176. diag::note_previous_definition);
  2177. return nullptr;
  2178. }
  2179. // Create the class template partial specialization declaration.
  2180. ClassTemplateSpecializationDecl *InstD
  2181. = ClassTemplateSpecializationDecl::Create(SemaRef.Context,
  2182. D->getTagKind(),
  2183. Owner,
  2184. D->getLocStart(),
  2185. D->getLocation(),
  2186. InstClassTemplate,
  2187. Converted.data(),
  2188. Converted.size(),
  2189. PrevDecl);
  2190. // Add this partial specialization to the set of class template partial
  2191. // specializations.
  2192. if (!PrevDecl)
  2193. InstClassTemplate->AddSpecialization(InstD, InsertPos);
  2194. // Substitute the nested name specifier, if any.
  2195. if (SubstQualifier(D, InstD))
  2196. return nullptr;
  2197. // Build the canonical type that describes the converted template
  2198. // arguments of the class template explicit specialization.
  2199. QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
  2200. TemplateName(InstClassTemplate), Converted.data(), Converted.size(),
  2201. SemaRef.Context.getRecordType(InstD));
  2202. // Build the fully-sugared type for this class template
  2203. // specialization as the user wrote in the specialization
  2204. // itself. This means that we'll pretty-print the type retrieved
  2205. // from the specialization's declaration the way that the user
  2206. // actually wrote the specialization, rather than formatting the
  2207. // name based on the "canonical" representation used to store the
  2208. // template arguments in the specialization.
  2209. TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
  2210. TemplateName(InstClassTemplate), D->getLocation(), InstTemplateArgs,
  2211. CanonType);
  2212. InstD->setAccess(D->getAccess());
  2213. InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
  2214. InstD->setSpecializationKind(D->getSpecializationKind());
  2215. InstD->setTypeAsWritten(WrittenTy);
  2216. InstD->setExternLoc(D->getExternLoc());
  2217. InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc());
  2218. Owner->addDecl(InstD);
  2219. // Instantiate the members of the class-scope explicit specialization eagerly.
  2220. // We don't have support for lazy instantiation of an explicit specialization
  2221. // yet, and MSVC eagerly instantiates in this case.
  2222. if (D->isThisDeclarationADefinition() &&
  2223. SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
  2224. TSK_ImplicitInstantiation,
  2225. /*Complain=*/true))
  2226. return nullptr;
  2227. return InstD;
  2228. }
  2229. Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
  2230. VarTemplateSpecializationDecl *D) {
  2231. TemplateArgumentListInfo VarTemplateArgsInfo;
  2232. VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
  2233. assert(VarTemplate &&
  2234. "A template specialization without specialized template?");
  2235. // Substitute the current template arguments.
  2236. const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo();
  2237. VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc());
  2238. VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc());
  2239. if (SemaRef.Subst(TemplateArgsInfo.getArgumentArray(),
  2240. TemplateArgsInfo.size(), VarTemplateArgsInfo, TemplateArgs))
  2241. return nullptr;
  2242. // Check that the template argument list is well-formed for this template.
  2243. SmallVector<TemplateArgument, 4> Converted;
  2244. if (SemaRef.CheckTemplateArgumentList(
  2245. VarTemplate, VarTemplate->getLocStart(),
  2246. const_cast<TemplateArgumentListInfo &>(VarTemplateArgsInfo), false,
  2247. Converted))
  2248. return nullptr;
  2249. // Find the variable template specialization declaration that
  2250. // corresponds to these arguments.
  2251. void *InsertPos = nullptr;
  2252. if (VarTemplateSpecializationDecl *VarSpec = VarTemplate->findSpecialization(
  2253. Converted, InsertPos))
  2254. // If we already have a variable template specialization, return it.
  2255. return VarSpec;
  2256. return VisitVarTemplateSpecializationDecl(VarTemplate, D, InsertPos,
  2257. VarTemplateArgsInfo, Converted);
  2258. }
  2259. Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
  2260. VarTemplateDecl *VarTemplate, VarDecl *D, void *InsertPos,
  2261. const TemplateArgumentListInfo &TemplateArgsInfo,
  2262. ArrayRef<TemplateArgument> Converted) {
  2263. // If this is the variable for an anonymous struct or union,
  2264. // instantiate the anonymous struct/union type first.
  2265. if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
  2266. if (RecordTy->getDecl()->isAnonymousStructOrUnion())
  2267. if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
  2268. return nullptr;
  2269. // Do substitution on the type of the declaration
  2270. TypeSourceInfo *DI =
  2271. SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
  2272. D->getTypeSpecStartLoc(), D->getDeclName());
  2273. if (!DI)
  2274. return nullptr;
  2275. if (DI->getType()->isFunctionType()) {
  2276. SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
  2277. << D->isStaticDataMember() << DI->getType();
  2278. return nullptr;
  2279. }
  2280. // Build the instantiated declaration
  2281. VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create(
  2282. SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
  2283. VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted.data(),
  2284. Converted.size());
  2285. Var->setTemplateArgsInfo(TemplateArgsInfo);
  2286. if (InsertPos)
  2287. VarTemplate->AddSpecialization(Var, InsertPos);
  2288. // Substitute the nested name specifier, if any.
  2289. if (SubstQualifier(D, Var))
  2290. return nullptr;
  2291. SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs,
  2292. Owner, StartingScope);
  2293. return Var;
  2294. }
  2295. Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
  2296. llvm_unreachable("@defs is not supported in Objective-C++");
  2297. }
  2298. Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
  2299. // FIXME: We need to be able to instantiate FriendTemplateDecls.
  2300. unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
  2301. DiagnosticsEngine::Error,
  2302. "cannot instantiate %0 yet");
  2303. SemaRef.Diag(D->getLocation(), DiagID)
  2304. << D->getDeclKindName();
  2305. return nullptr;
  2306. }
  2307. Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
  2308. llvm_unreachable("Unexpected decl");
  2309. }
  2310. Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
  2311. const MultiLevelTemplateArgumentList &TemplateArgs) {
  2312. TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
  2313. if (D->isInvalidDecl())
  2314. return nullptr;
  2315. return Instantiator.Visit(D);
  2316. }
  2317. /// \brief Instantiates a nested template parameter list in the current
  2318. /// instantiation context.
  2319. ///
  2320. /// \param L The parameter list to instantiate
  2321. ///
  2322. /// \returns NULL if there was an error
  2323. TemplateParameterList *
  2324. TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
  2325. // Get errors for all the parameters before bailing out.
  2326. bool Invalid = false;
  2327. unsigned N = L->size();
  2328. typedef SmallVector<NamedDecl *, 8> ParamVector;
  2329. ParamVector Params;
  2330. Params.reserve(N);
  2331. for (auto &P : *L) {
  2332. NamedDecl *D = cast_or_null<NamedDecl>(Visit(P));
  2333. Params.push_back(D);
  2334. Invalid = Invalid || !D || D->isInvalidDecl();
  2335. }
  2336. // Clean up if we had an error.
  2337. if (Invalid)
  2338. return nullptr;
  2339. TemplateParameterList *InstL
  2340. = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
  2341. L->getLAngleLoc(), &Params.front(), N,
  2342. L->getRAngleLoc());
  2343. return InstL;
  2344. }
  2345. /// \brief Instantiate the declaration of a class template partial
  2346. /// specialization.
  2347. ///
  2348. /// \param ClassTemplate the (instantiated) class template that is partially
  2349. // specialized by the instantiation of \p PartialSpec.
  2350. ///
  2351. /// \param PartialSpec the (uninstantiated) class template partial
  2352. /// specialization that we are instantiating.
  2353. ///
  2354. /// \returns The instantiated partial specialization, if successful; otherwise,
  2355. /// NULL to indicate an error.
  2356. ClassTemplatePartialSpecializationDecl *
  2357. TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
  2358. ClassTemplateDecl *ClassTemplate,
  2359. ClassTemplatePartialSpecializationDecl *PartialSpec) {
  2360. // Create a local instantiation scope for this class template partial
  2361. // specialization, which will contain the instantiations of the template
  2362. // parameters.
  2363. LocalInstantiationScope Scope(SemaRef);
  2364. // Substitute into the template parameters of the class template partial
  2365. // specialization.
  2366. TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
  2367. TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
  2368. if (!InstParams)
  2369. return nullptr;
  2370. // Substitute into the template arguments of the class template partial
  2371. // specialization.
  2372. const ASTTemplateArgumentListInfo *TemplArgInfo
  2373. = PartialSpec->getTemplateArgsAsWritten();
  2374. TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
  2375. TemplArgInfo->RAngleLoc);
  2376. if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
  2377. TemplArgInfo->NumTemplateArgs,
  2378. InstTemplateArgs, TemplateArgs))
  2379. return nullptr;
  2380. // Check that the template argument list is well-formed for this
  2381. // class template.
  2382. SmallVector<TemplateArgument, 4> Converted;
  2383. if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
  2384. PartialSpec->getLocation(),
  2385. InstTemplateArgs,
  2386. false,
  2387. Converted))
  2388. return nullptr;
  2389. // Figure out where to insert this class template partial specialization
  2390. // in the member template's set of class template partial specializations.
  2391. void *InsertPos = nullptr;
  2392. ClassTemplateSpecializationDecl *PrevDecl
  2393. = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
  2394. // Build the canonical type that describes the converted template
  2395. // arguments of the class template partial specialization.
  2396. QualType CanonType
  2397. = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
  2398. Converted.data(),
  2399. Converted.size());
  2400. // Build the fully-sugared type for this class template
  2401. // specialization as the user wrote in the specialization
  2402. // itself. This means that we'll pretty-print the type retrieved
  2403. // from the specialization's declaration the way that the user
  2404. // actually wrote the specialization, rather than formatting the
  2405. // name based on the "canonical" representation used to store the
  2406. // template arguments in the specialization.
  2407. TypeSourceInfo *WrittenTy
  2408. = SemaRef.Context.getTemplateSpecializationTypeInfo(
  2409. TemplateName(ClassTemplate),
  2410. PartialSpec->getLocation(),
  2411. InstTemplateArgs,
  2412. CanonType);
  2413. if (PrevDecl) {
  2414. // We've already seen a partial specialization with the same template
  2415. // parameters and template arguments. This can happen, for example, when
  2416. // substituting the outer template arguments ends up causing two
  2417. // class template partial specializations of a member class template
  2418. // to have identical forms, e.g.,
  2419. //
  2420. // template<typename T, typename U>
  2421. // struct Outer {
  2422. // template<typename X, typename Y> struct Inner;
  2423. // template<typename Y> struct Inner<T, Y>;
  2424. // template<typename Y> struct Inner<U, Y>;
  2425. // };
  2426. //
  2427. // Outer<int, int> outer; // error: the partial specializations of Inner
  2428. // // have the same signature.
  2429. SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
  2430. << WrittenTy->getType();
  2431. SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
  2432. << SemaRef.Context.getTypeDeclType(PrevDecl);
  2433. return nullptr;
  2434. }
  2435. // Create the class template partial specialization declaration.
  2436. ClassTemplatePartialSpecializationDecl *InstPartialSpec
  2437. = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
  2438. PartialSpec->getTagKind(),
  2439. Owner,
  2440. PartialSpec->getLocStart(),
  2441. PartialSpec->getLocation(),
  2442. InstParams,
  2443. ClassTemplate,
  2444. Converted.data(),
  2445. Converted.size(),
  2446. InstTemplateArgs,
  2447. CanonType,
  2448. nullptr);
  2449. // Substitute the nested name specifier, if any.
  2450. if (SubstQualifier(PartialSpec, InstPartialSpec))
  2451. return nullptr;
  2452. InstPartialSpec->setInstantiatedFromMember(PartialSpec);
  2453. InstPartialSpec->setTypeAsWritten(WrittenTy);
  2454. // Add this partial specialization to the set of class template partial
  2455. // specializations.
  2456. ClassTemplate->AddPartialSpecialization(InstPartialSpec,
  2457. /*InsertPos=*/nullptr);
  2458. return InstPartialSpec;
  2459. }
  2460. /// \brief Instantiate the declaration of a variable template partial
  2461. /// specialization.
  2462. ///
  2463. /// \param VarTemplate the (instantiated) variable template that is partially
  2464. /// specialized by the instantiation of \p PartialSpec.
  2465. ///
  2466. /// \param PartialSpec the (uninstantiated) variable template partial
  2467. /// specialization that we are instantiating.
  2468. ///
  2469. /// \returns The instantiated partial specialization, if successful; otherwise,
  2470. /// NULL to indicate an error.
  2471. VarTemplatePartialSpecializationDecl *
  2472. TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
  2473. VarTemplateDecl *VarTemplate,
  2474. VarTemplatePartialSpecializationDecl *PartialSpec) {
  2475. // Create a local instantiation scope for this variable template partial
  2476. // specialization, which will contain the instantiations of the template
  2477. // parameters.
  2478. LocalInstantiationScope Scope(SemaRef);
  2479. // Substitute into the template parameters of the variable template partial
  2480. // specialization.
  2481. TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
  2482. TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
  2483. if (!InstParams)
  2484. return nullptr;
  2485. // Substitute into the template arguments of the variable template partial
  2486. // specialization.
  2487. const ASTTemplateArgumentListInfo *TemplArgInfo
  2488. = PartialSpec->getTemplateArgsAsWritten();
  2489. TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
  2490. TemplArgInfo->RAngleLoc);
  2491. if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
  2492. TemplArgInfo->NumTemplateArgs,
  2493. InstTemplateArgs, TemplateArgs))
  2494. return nullptr;
  2495. // Check that the template argument list is well-formed for this
  2496. // class template.
  2497. SmallVector<TemplateArgument, 4> Converted;
  2498. if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
  2499. InstTemplateArgs, false, Converted))
  2500. return nullptr;
  2501. // Figure out where to insert this variable template partial specialization
  2502. // in the member template's set of variable template partial specializations.
  2503. void *InsertPos = nullptr;
  2504. VarTemplateSpecializationDecl *PrevDecl =
  2505. VarTemplate->findPartialSpecialization(Converted, InsertPos);
  2506. // Build the canonical type that describes the converted template
  2507. // arguments of the variable template partial specialization.
  2508. QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
  2509. TemplateName(VarTemplate), Converted.data(), Converted.size());
  2510. // Build the fully-sugared type for this variable template
  2511. // specialization as the user wrote in the specialization
  2512. // itself. This means that we'll pretty-print the type retrieved
  2513. // from the specialization's declaration the way that the user
  2514. // actually wrote the specialization, rather than formatting the
  2515. // name based on the "canonical" representation used to store the
  2516. // template arguments in the specialization.
  2517. TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
  2518. TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs,
  2519. CanonType);
  2520. if (PrevDecl) {
  2521. // We've already seen a partial specialization with the same template
  2522. // parameters and template arguments. This can happen, for example, when
  2523. // substituting the outer template arguments ends up causing two
  2524. // variable template partial specializations of a member variable template
  2525. // to have identical forms, e.g.,
  2526. //
  2527. // template<typename T, typename U>
  2528. // struct Outer {
  2529. // template<typename X, typename Y> pair<X,Y> p;
  2530. // template<typename Y> pair<T, Y> p;
  2531. // template<typename Y> pair<U, Y> p;
  2532. // };
  2533. //
  2534. // Outer<int, int> outer; // error: the partial specializations of Inner
  2535. // // have the same signature.
  2536. SemaRef.Diag(PartialSpec->getLocation(),
  2537. diag::err_var_partial_spec_redeclared)
  2538. << WrittenTy->getType();
  2539. SemaRef.Diag(PrevDecl->getLocation(),
  2540. diag::note_var_prev_partial_spec_here);
  2541. return nullptr;
  2542. }
  2543. // Do substitution on the type of the declaration
  2544. TypeSourceInfo *DI = SemaRef.SubstType(
  2545. PartialSpec->getTypeSourceInfo(), TemplateArgs,
  2546. PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
  2547. if (!DI)
  2548. return nullptr;
  2549. if (DI->getType()->isFunctionType()) {
  2550. SemaRef.Diag(PartialSpec->getLocation(),
  2551. diag::err_variable_instantiates_to_function)
  2552. << PartialSpec->isStaticDataMember() << DI->getType();
  2553. return nullptr;
  2554. }
  2555. // Create the variable template partial specialization declaration.
  2556. VarTemplatePartialSpecializationDecl *InstPartialSpec =
  2557. VarTemplatePartialSpecializationDecl::Create(
  2558. SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
  2559. PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
  2560. DI, PartialSpec->getStorageClass(), Converted.data(),
  2561. Converted.size(), InstTemplateArgs);
  2562. // Substitute the nested name specifier, if any.
  2563. if (SubstQualifier(PartialSpec, InstPartialSpec))
  2564. return nullptr;
  2565. InstPartialSpec->setInstantiatedFromMember(PartialSpec);
  2566. InstPartialSpec->setTypeAsWritten(WrittenTy);
  2567. // Add this partial specialization to the set of variable template partial
  2568. // specializations. The instantiation of the initializer is not necessary.
  2569. VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr);
  2570. SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
  2571. LateAttrs, Owner, StartingScope);
  2572. return InstPartialSpec;
  2573. }
  2574. TypeSourceInfo*
  2575. TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
  2576. SmallVectorImpl<ParmVarDecl *> &Params) {
  2577. TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
  2578. assert(OldTInfo && "substituting function without type source info");
  2579. assert(Params.empty() && "parameter vector is non-empty at start");
  2580. CXXRecordDecl *ThisContext = nullptr;
  2581. unsigned ThisTypeQuals = 0;
  2582. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
  2583. ThisContext = cast<CXXRecordDecl>(Owner);
  2584. ThisTypeQuals = Method->getTypeQualifiers();
  2585. }
  2586. TypeSourceInfo *NewTInfo
  2587. = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
  2588. D->getTypeSpecStartLoc(),
  2589. D->getDeclName(),
  2590. ThisContext, ThisTypeQuals);
  2591. if (!NewTInfo)
  2592. return nullptr;
  2593. TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
  2594. if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
  2595. if (NewTInfo != OldTInfo) {
  2596. // Get parameters from the new type info.
  2597. TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
  2598. FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
  2599. unsigned NewIdx = 0;
  2600. for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
  2601. OldIdx != NumOldParams; ++OldIdx) {
  2602. ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
  2603. LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
  2604. Optional<unsigned> NumArgumentsInExpansion;
  2605. if (OldParam->isParameterPack())
  2606. NumArgumentsInExpansion =
  2607. SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
  2608. TemplateArgs);
  2609. if (!NumArgumentsInExpansion) {
  2610. // Simple case: normal parameter, or a parameter pack that's
  2611. // instantiated to a (still-dependent) parameter pack.
  2612. ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
  2613. Params.push_back(NewParam);
  2614. Scope->InstantiatedLocal(OldParam, NewParam);
  2615. } else {
  2616. // Parameter pack expansion: make the instantiation an argument pack.
  2617. Scope->MakeInstantiatedLocalArgPack(OldParam);
  2618. for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
  2619. ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
  2620. Params.push_back(NewParam);
  2621. Scope->InstantiatedLocalPackArg(OldParam, NewParam);
  2622. }
  2623. }
  2624. }
  2625. } else {
  2626. // The function type itself was not dependent and therefore no
  2627. // substitution occurred. However, we still need to instantiate
  2628. // the function parameters themselves.
  2629. const FunctionProtoType *OldProto =
  2630. cast<FunctionProtoType>(OldProtoLoc.getType());
  2631. for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
  2632. ++i) {
  2633. ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
  2634. if (!OldParam) {
  2635. Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
  2636. D, D->getLocation(), OldProto->getParamType(i)));
  2637. continue;
  2638. }
  2639. ParmVarDecl *Parm =
  2640. cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
  2641. if (!Parm)
  2642. return nullptr;
  2643. Params.push_back(Parm);
  2644. }
  2645. }
  2646. } else {
  2647. // If the type of this function, after ignoring parentheses, is not
  2648. // *directly* a function type, then we're instantiating a function that
  2649. // was declared via a typedef or with attributes, e.g.,
  2650. //
  2651. // typedef int functype(int, int);
  2652. // functype func;
  2653. // int __cdecl meth(int, int);
  2654. //
  2655. // In this case, we'll just go instantiate the ParmVarDecls that we
  2656. // synthesized in the method declaration.
  2657. SmallVector<QualType, 4> ParamTypes;
  2658. if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(),
  2659. D->getNumParams(), TemplateArgs, ParamTypes,
  2660. &Params))
  2661. return nullptr;
  2662. }
  2663. return NewTInfo;
  2664. }
  2665. /// Introduce the instantiated function parameters into the local
  2666. /// instantiation scope, and set the parameter names to those used
  2667. /// in the template.
  2668. static bool addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
  2669. const FunctionDecl *PatternDecl,
  2670. LocalInstantiationScope &Scope,
  2671. const MultiLevelTemplateArgumentList &TemplateArgs) {
  2672. unsigned FParamIdx = 0;
  2673. for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
  2674. const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
  2675. if (!PatternParam->isParameterPack()) {
  2676. // Simple case: not a parameter pack.
  2677. assert(FParamIdx < Function->getNumParams());
  2678. ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
  2679. FunctionParam->setDeclName(PatternParam->getDeclName());
  2680. // If the parameter's type is not dependent, update it to match the type
  2681. // in the pattern. They can differ in top-level cv-qualifiers, and we want
  2682. // the pattern's type here. If the type is dependent, they can't differ,
  2683. // per core issue 1668. Substitute into the type from the pattern, in case
  2684. // it's instantiation-dependent.
  2685. // FIXME: Updating the type to work around this is at best fragile.
  2686. if (!PatternDecl->getType()->isDependentType()) {
  2687. QualType T = S.SubstType(PatternParam->getType(), TemplateArgs,
  2688. FunctionParam->getLocation(),
  2689. FunctionParam->getDeclName());
  2690. if (T.isNull())
  2691. return true;
  2692. FunctionParam->setType(T);
  2693. }
  2694. Scope.InstantiatedLocal(PatternParam, FunctionParam);
  2695. ++FParamIdx;
  2696. continue;
  2697. }
  2698. // Expand the parameter pack.
  2699. Scope.MakeInstantiatedLocalArgPack(PatternParam);
  2700. Optional<unsigned> NumArgumentsInExpansion
  2701. = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
  2702. assert(NumArgumentsInExpansion &&
  2703. "should only be called when all template arguments are known");
  2704. QualType PatternType =
  2705. PatternParam->getType()->castAs<PackExpansionType>()->getPattern();
  2706. for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
  2707. ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
  2708. FunctionParam->setDeclName(PatternParam->getDeclName());
  2709. if (!PatternDecl->getType()->isDependentType()) {
  2710. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, Arg);
  2711. QualType T = S.SubstType(PatternType, TemplateArgs,
  2712. FunctionParam->getLocation(),
  2713. FunctionParam->getDeclName());
  2714. if (T.isNull())
  2715. return true;
  2716. FunctionParam->setType(T);
  2717. }
  2718. Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
  2719. ++FParamIdx;
  2720. }
  2721. }
  2722. return false;
  2723. }
  2724. void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
  2725. FunctionDecl *Decl) {
  2726. const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
  2727. if (Proto->getExceptionSpecType() != EST_Uninstantiated)
  2728. return;
  2729. InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
  2730. InstantiatingTemplate::ExceptionSpecification());
  2731. if (Inst.isInvalid()) {
  2732. // We hit the instantiation depth limit. Clear the exception specification
  2733. // so that our callers don't have to cope with EST_Uninstantiated.
  2734. UpdateExceptionSpec(Decl, EST_None);
  2735. return;
  2736. }
  2737. // Enter the scope of this instantiation. We don't use
  2738. // PushDeclContext because we don't have a scope.
  2739. Sema::ContextRAII savedContext(*this, Decl);
  2740. LocalInstantiationScope Scope(*this);
  2741. MultiLevelTemplateArgumentList TemplateArgs =
  2742. getTemplateInstantiationArgs(Decl, nullptr, /*RelativeToPrimary*/true);
  2743. FunctionDecl *Template = Proto->getExceptionSpecTemplate();
  2744. if (addInstantiatedParametersToScope(*this, Decl, Template, Scope,
  2745. TemplateArgs)) {
  2746. UpdateExceptionSpec(Decl, EST_None);
  2747. return;
  2748. }
  2749. SubstExceptionSpec(Decl, Template->getType()->castAs<FunctionProtoType>(),
  2750. TemplateArgs);
  2751. }
  2752. /// \brief Initializes the common fields of an instantiation function
  2753. /// declaration (New) from the corresponding fields of its template (Tmpl).
  2754. ///
  2755. /// \returns true if there was an error
  2756. bool
  2757. TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
  2758. FunctionDecl *Tmpl) {
  2759. if (Tmpl->isDeleted())
  2760. New->setDeletedAsWritten();
  2761. // Forward the mangling number from the template to the instantiated decl.
  2762. SemaRef.Context.setManglingNumber(New,
  2763. SemaRef.Context.getManglingNumber(Tmpl));
  2764. // If we are performing substituting explicitly-specified template arguments
  2765. // or deduced template arguments into a function template and we reach this
  2766. // point, we are now past the point where SFINAE applies and have committed
  2767. // to keeping the new function template specialization. We therefore
  2768. // convert the active template instantiation for the function template
  2769. // into a template instantiation for this specific function template
  2770. // specialization, which is not a SFINAE context, so that we diagnose any
  2771. // further errors in the declaration itself.
  2772. typedef Sema::ActiveTemplateInstantiation ActiveInstType;
  2773. ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
  2774. if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
  2775. ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
  2776. if (FunctionTemplateDecl *FunTmpl
  2777. = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
  2778. assert(FunTmpl->getTemplatedDecl() == Tmpl &&
  2779. "Deduction from the wrong function template?");
  2780. (void) FunTmpl;
  2781. ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
  2782. ActiveInst.Entity = New;
  2783. }
  2784. }
  2785. const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
  2786. assert(Proto && "Function template without prototype?");
  2787. if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
  2788. FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
  2789. // DR1330: In C++11, defer instantiation of a non-trivial
  2790. // exception specification.
  2791. // DR1484: Local classes and their members are instantiated along with the
  2792. // containing function.
  2793. bool RequireInstantiation = false;
  2794. if (CXXRecordDecl *Cls = dyn_cast<CXXRecordDecl>(Tmpl->getDeclContext())) {
  2795. if (Cls->isLocalClass())
  2796. RequireInstantiation = true;
  2797. }
  2798. if (SemaRef.getLangOpts().CPlusPlus11 &&
  2799. EPI.ExceptionSpec.Type != EST_None &&
  2800. EPI.ExceptionSpec.Type != EST_DynamicNone &&
  2801. EPI.ExceptionSpec.Type != EST_BasicNoexcept &&
  2802. !RequireInstantiation) {
  2803. FunctionDecl *ExceptionSpecTemplate = Tmpl;
  2804. if (EPI.ExceptionSpec.Type == EST_Uninstantiated)
  2805. ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate;
  2806. ExceptionSpecificationType NewEST = EST_Uninstantiated;
  2807. if (EPI.ExceptionSpec.Type == EST_Unevaluated)
  2808. NewEST = EST_Unevaluated;
  2809. // Mark the function has having an uninstantiated exception specification.
  2810. const FunctionProtoType *NewProto
  2811. = New->getType()->getAs<FunctionProtoType>();
  2812. assert(NewProto && "Template instantiation without function prototype?");
  2813. EPI = NewProto->getExtProtoInfo();
  2814. EPI.ExceptionSpec.Type = NewEST;
  2815. EPI.ExceptionSpec.SourceDecl = New;
  2816. EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate;
  2817. New->setType(SemaRef.Context.getFunctionType(
  2818. NewProto->getReturnType(), NewProto->getParamTypes(), EPI, NewProto->getParamMods())); // HLSL Change
  2819. } else {
  2820. SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs);
  2821. }
  2822. }
  2823. // Get the definition. Leaves the variable unchanged if undefined.
  2824. const FunctionDecl *Definition = Tmpl;
  2825. Tmpl->isDefined(Definition);
  2826. SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
  2827. LateAttrs, StartingScope);
  2828. return false;
  2829. }
  2830. /// \brief Initializes common fields of an instantiated method
  2831. /// declaration (New) from the corresponding fields of its template
  2832. /// (Tmpl).
  2833. ///
  2834. /// \returns true if there was an error
  2835. bool
  2836. TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
  2837. CXXMethodDecl *Tmpl) {
  2838. if (InitFunctionInstantiation(New, Tmpl))
  2839. return true;
  2840. New->setAccess(Tmpl->getAccess());
  2841. if (Tmpl->isVirtualAsWritten())
  2842. New->setVirtualAsWritten(true);
  2843. // FIXME: New needs a pointer to Tmpl
  2844. return false;
  2845. }
  2846. /// \brief Instantiate the definition of the given function from its
  2847. /// template.
  2848. ///
  2849. /// \param PointOfInstantiation the point at which the instantiation was
  2850. /// required. Note that this is not precisely a "point of instantiation"
  2851. /// for the function, but it's close.
  2852. ///
  2853. /// \param Function the already-instantiated declaration of a
  2854. /// function template specialization or member function of a class template
  2855. /// specialization.
  2856. ///
  2857. /// \param Recursive if true, recursively instantiates any functions that
  2858. /// are required by this instantiation.
  2859. ///
  2860. /// \param DefinitionRequired if true, then we are performing an explicit
  2861. /// instantiation where the body of the function is required. Complain if
  2862. /// there is no such body.
  2863. void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
  2864. FunctionDecl *Function,
  2865. bool Recursive,
  2866. bool DefinitionRequired) {
  2867. if (Function->isInvalidDecl() || Function->isDefined())
  2868. return;
  2869. // Never instantiate an explicit specialization except if it is a class scope
  2870. // explicit specialization.
  2871. if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
  2872. !Function->getClassScopeSpecializationPattern())
  2873. return;
  2874. // Find the function body that we'll be substituting.
  2875. const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
  2876. assert(PatternDecl && "instantiating a non-template");
  2877. Stmt *Pattern = PatternDecl->getBody(PatternDecl);
  2878. assert(PatternDecl && "template definition is not a template");
  2879. if (!Pattern) {
  2880. // Try to find a defaulted definition
  2881. PatternDecl->isDefined(PatternDecl);
  2882. }
  2883. assert(PatternDecl && "template definition is not a template");
  2884. // Postpone late parsed template instantiations.
  2885. if (PatternDecl->isLateTemplateParsed() &&
  2886. !LateTemplateParser) {
  2887. PendingInstantiations.push_back(
  2888. std::make_pair(Function, PointOfInstantiation));
  2889. return;
  2890. }
  2891. // If we're performing recursive template instantiation, create our own
  2892. // queue of pending implicit instantiations that we will instantiate later,
  2893. // while we're still within our own instantiation context.
  2894. // This has to happen before LateTemplateParser below is called, so that
  2895. // it marks vtables used in late parsed templates as used.
  2896. SavePendingLocalImplicitInstantiationsRAII
  2897. SavedPendingLocalImplicitInstantiations(*this);
  2898. SavePendingInstantiationsAndVTableUsesRAII
  2899. SavePendingInstantiationsAndVTableUses(*this, /*Enabled=*/Recursive);
  2900. // Call the LateTemplateParser callback if there is a need to late parse
  2901. // a templated function definition.
  2902. if (!Pattern && PatternDecl->isLateTemplateParsed() &&
  2903. LateTemplateParser) {
  2904. // FIXME: Optimize to allow individual templates to be deserialized.
  2905. if (PatternDecl->isFromASTFile())
  2906. ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
  2907. LateParsedTemplate *LPT = LateParsedTemplateMap.lookup(PatternDecl);
  2908. assert(LPT && "missing LateParsedTemplate");
  2909. LateTemplateParser(OpaqueParser, *LPT);
  2910. Pattern = PatternDecl->getBody(PatternDecl);
  2911. }
  2912. if (!Pattern && !PatternDecl->isDefaulted()) {
  2913. if (DefinitionRequired) {
  2914. if (Function->getPrimaryTemplate())
  2915. Diag(PointOfInstantiation,
  2916. diag::err_explicit_instantiation_undefined_func_template)
  2917. << Function->getPrimaryTemplate();
  2918. else
  2919. Diag(PointOfInstantiation,
  2920. diag::err_explicit_instantiation_undefined_member)
  2921. << 1 << Function->getDeclName() << Function->getDeclContext();
  2922. if (PatternDecl)
  2923. Diag(PatternDecl->getLocation(),
  2924. diag::note_explicit_instantiation_here);
  2925. Function->setInvalidDecl();
  2926. } else if (Function->getTemplateSpecializationKind()
  2927. == TSK_ExplicitInstantiationDefinition) {
  2928. assert(!Recursive);
  2929. PendingInstantiations.push_back(
  2930. std::make_pair(Function, PointOfInstantiation));
  2931. }
  2932. return;
  2933. }
  2934. // C++1y [temp.explicit]p10:
  2935. // Except for inline functions, declarations with types deduced from their
  2936. // initializer or return value, and class template specializations, other
  2937. // explicit instantiation declarations have the effect of suppressing the
  2938. // implicit instantiation of the entity to which they refer.
  2939. if (Function->getTemplateSpecializationKind() ==
  2940. TSK_ExplicitInstantiationDeclaration &&
  2941. !PatternDecl->isInlined() &&
  2942. !PatternDecl->getReturnType()->getContainedAutoType())
  2943. return;
  2944. if (PatternDecl->isInlined()) {
  2945. // Function, and all later redeclarations of it (from imported modules,
  2946. // for instance), are now implicitly inline.
  2947. for (auto *D = Function->getMostRecentDecl(); /**/;
  2948. D = D->getPreviousDecl()) {
  2949. D->setImplicitlyInline();
  2950. if (D == Function)
  2951. break;
  2952. }
  2953. }
  2954. InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
  2955. if (Inst.isInvalid())
  2956. return;
  2957. // Copy the inner loc start from the pattern.
  2958. Function->setInnerLocStart(PatternDecl->getInnerLocStart());
  2959. EnterExpressionEvaluationContext EvalContext(*this,
  2960. Sema::PotentiallyEvaluated);
  2961. // Introduce a new scope where local variable instantiations will be
  2962. // recorded, unless we're actually a member function within a local
  2963. // class, in which case we need to merge our results with the parent
  2964. // scope (of the enclosing function).
  2965. bool MergeWithParentScope = false;
  2966. if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
  2967. MergeWithParentScope = Rec->isLocalClass();
  2968. LocalInstantiationScope Scope(*this, MergeWithParentScope);
  2969. if (PatternDecl->isDefaulted())
  2970. SetDeclDefaulted(Function, PatternDecl->getLocation());
  2971. else {
  2972. MultiLevelTemplateArgumentList TemplateArgs =
  2973. getTemplateInstantiationArgs(Function, nullptr, false, PatternDecl);
  2974. // Substitute into the qualifier; we can get a substitution failure here
  2975. // through evil use of alias templates.
  2976. // FIXME: Is CurContext correct for this? Should we go to the (instantiation
  2977. // of the) lexical context of the pattern?
  2978. SubstQualifier(*this, PatternDecl, Function, TemplateArgs);
  2979. ActOnStartOfFunctionDef(nullptr, Function);
  2980. // Enter the scope of this instantiation. We don't use
  2981. // PushDeclContext because we don't have a scope.
  2982. Sema::ContextRAII savedContext(*this, Function);
  2983. if (addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
  2984. TemplateArgs))
  2985. return;
  2986. // If this is a constructor, instantiate the member initializers.
  2987. if (const CXXConstructorDecl *Ctor =
  2988. dyn_cast<CXXConstructorDecl>(PatternDecl)) {
  2989. InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
  2990. TemplateArgs);
  2991. }
  2992. // Instantiate the function body.
  2993. StmtResult Body = SubstStmt(Pattern, TemplateArgs);
  2994. if (Body.isInvalid())
  2995. Function->setInvalidDecl();
  2996. ActOnFinishFunctionBody(Function, Body.get(),
  2997. /*IsInstantiation=*/true);
  2998. PerformDependentDiagnostics(PatternDecl, TemplateArgs);
  2999. if (auto *Listener = getASTMutationListener())
  3000. Listener->FunctionDefinitionInstantiated(Function);
  3001. savedContext.pop();
  3002. }
  3003. DeclGroupRef DG(Function);
  3004. Consumer.HandleTopLevelDecl(DG);
  3005. // This class may have local implicit instantiations that need to be
  3006. // instantiation within this scope.
  3007. PerformPendingInstantiations(/*LocalOnly=*/true);
  3008. Scope.Exit();
  3009. if (Recursive) {
  3010. // Define any pending vtables.
  3011. DefineUsedVTables();
  3012. // Instantiate any pending implicit instantiations found during the
  3013. // instantiation of this template.
  3014. PerformPendingInstantiations();
  3015. // PendingInstantiations and VTableUses are restored through
  3016. // SavePendingInstantiationsAndVTableUses's destructor.
  3017. }
  3018. }
  3019. VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation(
  3020. VarTemplateDecl *VarTemplate, VarDecl *FromVar,
  3021. const TemplateArgumentList &TemplateArgList,
  3022. const TemplateArgumentListInfo &TemplateArgsInfo,
  3023. SmallVectorImpl<TemplateArgument> &Converted,
  3024. SourceLocation PointOfInstantiation, void *InsertPos,
  3025. LateInstantiatedAttrVec *LateAttrs,
  3026. LocalInstantiationScope *StartingScope) {
  3027. if (FromVar->isInvalidDecl())
  3028. return nullptr;
  3029. InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
  3030. if (Inst.isInvalid())
  3031. return nullptr;
  3032. MultiLevelTemplateArgumentList TemplateArgLists;
  3033. TemplateArgLists.addOuterTemplateArguments(&TemplateArgList);
  3034. // Instantiate the first declaration of the variable template: for a partial
  3035. // specialization of a static data member template, the first declaration may
  3036. // or may not be the declaration in the class; if it's in the class, we want
  3037. // to instantiate a member in the class (a declaration), and if it's outside,
  3038. // we want to instantiate a definition.
  3039. //
  3040. // If we're instantiating an explicitly-specialized member template or member
  3041. // partial specialization, don't do this. The member specialization completely
  3042. // replaces the original declaration in this case.
  3043. bool IsMemberSpec = false;
  3044. if (VarTemplatePartialSpecializationDecl *PartialSpec =
  3045. dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar))
  3046. IsMemberSpec = PartialSpec->isMemberSpecialization();
  3047. else if (VarTemplateDecl *FromTemplate = FromVar->getDescribedVarTemplate())
  3048. IsMemberSpec = FromTemplate->isMemberSpecialization();
  3049. if (!IsMemberSpec)
  3050. FromVar = FromVar->getFirstDecl();
  3051. MultiLevelTemplateArgumentList MultiLevelList(TemplateArgList);
  3052. TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
  3053. MultiLevelList);
  3054. // TODO: Set LateAttrs and StartingScope ...
  3055. return cast_or_null<VarTemplateSpecializationDecl>(
  3056. Instantiator.VisitVarTemplateSpecializationDecl(
  3057. VarTemplate, FromVar, InsertPos, TemplateArgsInfo, Converted));
  3058. }
  3059. /// \brief Instantiates a variable template specialization by completing it
  3060. /// with appropriate type information and initializer.
  3061. VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl(
  3062. VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
  3063. const MultiLevelTemplateArgumentList &TemplateArgs) {
  3064. // Do substitution on the type of the declaration
  3065. TypeSourceInfo *DI =
  3066. SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
  3067. PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
  3068. if (!DI)
  3069. return nullptr;
  3070. // Update the type of this variable template specialization.
  3071. VarSpec->setType(DI->getType());
  3072. // Instantiate the initializer.
  3073. InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
  3074. return VarSpec;
  3075. }
  3076. /// BuildVariableInstantiation - Used after a new variable has been created.
  3077. /// Sets basic variable data and decides whether to postpone the
  3078. /// variable instantiation.
  3079. void Sema::BuildVariableInstantiation(
  3080. VarDecl *NewVar, VarDecl *OldVar,
  3081. const MultiLevelTemplateArgumentList &TemplateArgs,
  3082. LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
  3083. LocalInstantiationScope *StartingScope,
  3084. bool InstantiatingVarTemplate) {
  3085. // If we are instantiating a local extern declaration, the
  3086. // instantiation belongs lexically to the containing function.
  3087. // If we are instantiating a static data member defined
  3088. // out-of-line, the instantiation will have the same lexical
  3089. // context (which will be a namespace scope) as the template.
  3090. if (OldVar->isLocalExternDecl()) {
  3091. NewVar->setLocalExternDecl();
  3092. NewVar->setLexicalDeclContext(Owner);
  3093. } else if (OldVar->isOutOfLine())
  3094. NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
  3095. NewVar->setTSCSpec(OldVar->getTSCSpec());
  3096. NewVar->setInitStyle(OldVar->getInitStyle());
  3097. NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
  3098. NewVar->setConstexpr(OldVar->isConstexpr());
  3099. NewVar->setInitCapture(OldVar->isInitCapture());
  3100. NewVar->setPreviousDeclInSameBlockScope(
  3101. OldVar->isPreviousDeclInSameBlockScope());
  3102. NewVar->setAccess(OldVar->getAccess());
  3103. if (!OldVar->isStaticDataMember()) {
  3104. if (OldVar->isUsed(false))
  3105. NewVar->setIsUsed();
  3106. NewVar->setReferenced(OldVar->isReferenced());
  3107. }
  3108. // See if the old variable had a type-specifier that defined an anonymous tag.
  3109. // If it did, mark the new variable as being the declarator for the new
  3110. // anonymous tag.
  3111. if (const TagType *OldTagType = OldVar->getType()->getAs<TagType>()) {
  3112. TagDecl *OldTag = OldTagType->getDecl();
  3113. if (OldTag->getDeclaratorForAnonDecl() == OldVar) {
  3114. TagDecl *NewTag = NewVar->getType()->castAs<TagType>()->getDecl();
  3115. assert(!NewTag->hasNameForLinkage() &&
  3116. !NewTag->hasDeclaratorForAnonDecl());
  3117. NewTag->setDeclaratorForAnonDecl(NewVar);
  3118. }
  3119. }
  3120. InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
  3121. LookupResult Previous(
  3122. *this, NewVar->getDeclName(), NewVar->getLocation(),
  3123. NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
  3124. : Sema::LookupOrdinaryName,
  3125. Sema::ForRedeclaration);
  3126. if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
  3127. (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() ||
  3128. OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
  3129. // We have a previous declaration. Use that one, so we merge with the
  3130. // right type.
  3131. if (NamedDecl *NewPrev = FindInstantiatedDecl(
  3132. NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
  3133. Previous.addDecl(NewPrev);
  3134. } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
  3135. OldVar->hasLinkage())
  3136. LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
  3137. CheckVariableDeclaration(NewVar, Previous);
  3138. if (!InstantiatingVarTemplate) {
  3139. NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
  3140. if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
  3141. NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
  3142. }
  3143. if (!OldVar->isOutOfLine()) {
  3144. if (NewVar->getDeclContext()->isFunctionOrMethod())
  3145. CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
  3146. }
  3147. // Link instantiations of static data members back to the template from
  3148. // which they were instantiated.
  3149. if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate)
  3150. NewVar->setInstantiationOfStaticDataMember(OldVar,
  3151. TSK_ImplicitInstantiation);
  3152. // Forward the mangling number from the template to the instantiated decl.
  3153. Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar));
  3154. Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar));
  3155. // Delay instantiation of the initializer for variable templates until a
  3156. // definition of the variable is needed. We need it right away if the type
  3157. // contains 'auto'.
  3158. if ((!isa<VarTemplateSpecializationDecl>(NewVar) &&
  3159. !InstantiatingVarTemplate) ||
  3160. NewVar->getType()->isUndeducedType())
  3161. InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
  3162. // Diagnose unused local variables with dependent types, where the diagnostic
  3163. // will have been deferred.
  3164. if (!NewVar->isInvalidDecl() &&
  3165. NewVar->getDeclContext()->isFunctionOrMethod() &&
  3166. OldVar->getType()->isDependentType())
  3167. DiagnoseUnusedDecl(NewVar);
  3168. }
  3169. /// \brief Instantiate the initializer of a variable.
  3170. void Sema::InstantiateVariableInitializer(
  3171. VarDecl *Var, VarDecl *OldVar,
  3172. const MultiLevelTemplateArgumentList &TemplateArgs) {
  3173. if (Var->getAnyInitializer())
  3174. // We already have an initializer in the class.
  3175. return;
  3176. if (OldVar->getInit()) {
  3177. if (Var->isStaticDataMember() && !OldVar->isOutOfLine())
  3178. PushExpressionEvaluationContext(Sema::ConstantEvaluated, OldVar);
  3179. else
  3180. PushExpressionEvaluationContext(Sema::PotentiallyEvaluated, OldVar);
  3181. // Instantiate the initializer.
  3182. ExprResult Init =
  3183. SubstInitializer(OldVar->getInit(), TemplateArgs,
  3184. OldVar->getInitStyle() == VarDecl::CallInit);
  3185. if (!Init.isInvalid()) {
  3186. bool TypeMayContainAuto = true;
  3187. Expr *InitExpr = Init.get();
  3188. if (Var->hasAttr<DLLImportAttr>() &&
  3189. (!InitExpr ||
  3190. !InitExpr->isConstantInitializer(getASTContext(), false))) {
  3191. // Do not dynamically initialize dllimport variables.
  3192. } else if (InitExpr) {
  3193. bool DirectInit = OldVar->isDirectInit();
  3194. AddInitializerToDecl(Var, InitExpr, DirectInit, TypeMayContainAuto);
  3195. } else
  3196. ActOnUninitializedDecl(Var, TypeMayContainAuto);
  3197. } else {
  3198. // FIXME: Not too happy about invalidating the declaration
  3199. // because of a bogus initializer.
  3200. Var->setInvalidDecl();
  3201. }
  3202. PopExpressionEvaluationContext();
  3203. } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) &&
  3204. !Var->isCXXForRangeDecl())
  3205. ActOnUninitializedDecl(Var, false);
  3206. }
  3207. /// \brief Instantiate the definition of the given variable from its
  3208. /// template.
  3209. ///
  3210. /// \param PointOfInstantiation the point at which the instantiation was
  3211. /// required. Note that this is not precisely a "point of instantiation"
  3212. /// for the function, but it's close.
  3213. ///
  3214. /// \param Var the already-instantiated declaration of a static member
  3215. /// variable of a class template specialization.
  3216. ///
  3217. /// \param Recursive if true, recursively instantiates any functions that
  3218. /// are required by this instantiation.
  3219. ///
  3220. /// \param DefinitionRequired if true, then we are performing an explicit
  3221. /// instantiation where an out-of-line definition of the member variable
  3222. /// is required. Complain if there is no such definition.
  3223. void Sema::InstantiateStaticDataMemberDefinition(
  3224. SourceLocation PointOfInstantiation,
  3225. VarDecl *Var,
  3226. bool Recursive,
  3227. bool DefinitionRequired) {
  3228. InstantiateVariableDefinition(PointOfInstantiation, Var, Recursive,
  3229. DefinitionRequired);
  3230. }
  3231. void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
  3232. VarDecl *Var, bool Recursive,
  3233. bool DefinitionRequired) {
  3234. if (Var->isInvalidDecl())
  3235. return;
  3236. VarTemplateSpecializationDecl *VarSpec =
  3237. dyn_cast<VarTemplateSpecializationDecl>(Var);
  3238. VarDecl *PatternDecl = nullptr, *Def = nullptr;
  3239. MultiLevelTemplateArgumentList TemplateArgs =
  3240. getTemplateInstantiationArgs(Var);
  3241. if (VarSpec) {
  3242. // If this is a variable template specialization, make sure that it is
  3243. // non-dependent, then find its instantiation pattern.
  3244. bool InstantiationDependent = false;
  3245. assert(!TemplateSpecializationType::anyDependentTemplateArguments(
  3246. VarSpec->getTemplateArgsInfo(), InstantiationDependent) &&
  3247. "Only instantiate variable template specializations that are "
  3248. "not type-dependent");
  3249. (void)InstantiationDependent;
  3250. // Find the variable initialization that we'll be substituting. If the
  3251. // pattern was instantiated from a member template, look back further to
  3252. // find the real pattern.
  3253. assert(VarSpec->getSpecializedTemplate() &&
  3254. "Specialization without specialized template?");
  3255. llvm::PointerUnion<VarTemplateDecl *,
  3256. VarTemplatePartialSpecializationDecl *> PatternPtr =
  3257. VarSpec->getSpecializedTemplateOrPartial();
  3258. if (PatternPtr.is<VarTemplatePartialSpecializationDecl *>()) {
  3259. VarTemplatePartialSpecializationDecl *Tmpl =
  3260. PatternPtr.get<VarTemplatePartialSpecializationDecl *>();
  3261. while (VarTemplatePartialSpecializationDecl *From =
  3262. Tmpl->getInstantiatedFromMember()) {
  3263. if (Tmpl->isMemberSpecialization())
  3264. break;
  3265. Tmpl = From;
  3266. }
  3267. PatternDecl = Tmpl;
  3268. } else {
  3269. VarTemplateDecl *Tmpl = PatternPtr.get<VarTemplateDecl *>();
  3270. while (VarTemplateDecl *From =
  3271. Tmpl->getInstantiatedFromMemberTemplate()) {
  3272. if (Tmpl->isMemberSpecialization())
  3273. break;
  3274. Tmpl = From;
  3275. }
  3276. PatternDecl = Tmpl->getTemplatedDecl();
  3277. }
  3278. // If this is a static data member template, there might be an
  3279. // uninstantiated initializer on the declaration. If so, instantiate
  3280. // it now.
  3281. if (PatternDecl->isStaticDataMember() &&
  3282. (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
  3283. !Var->hasInit()) {
  3284. // FIXME: Factor out the duplicated instantiation context setup/tear down
  3285. // code here.
  3286. InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
  3287. if (Inst.isInvalid())
  3288. return;
  3289. // If we're performing recursive template instantiation, create our own
  3290. // queue of pending implicit instantiations that we will instantiate
  3291. // later, while we're still within our own instantiation context.
  3292. SavePendingInstantiationsAndVTableUsesRAII
  3293. SavePendingInstantiationsAndVTableUses(*this, /*Enabled=*/Recursive);
  3294. LocalInstantiationScope Local(*this);
  3295. // Enter the scope of this instantiation. We don't use
  3296. // PushDeclContext because we don't have a scope.
  3297. ContextRAII PreviousContext(*this, Var->getDeclContext());
  3298. InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
  3299. PreviousContext.pop();
  3300. // FIXME: Need to inform the ASTConsumer that we instantiated the
  3301. // initializer?
  3302. // This variable may have local implicit instantiations that need to be
  3303. // instantiated within this scope.
  3304. PerformPendingInstantiations(/*LocalOnly=*/true);
  3305. Local.Exit();
  3306. if (Recursive) {
  3307. // Define any newly required vtables.
  3308. DefineUsedVTables();
  3309. // Instantiate any pending implicit instantiations found during the
  3310. // instantiation of this template.
  3311. PerformPendingInstantiations();
  3312. // PendingInstantiations and VTableUses are restored through
  3313. // SavePendingInstantiationsAndVTableUses's destructor.
  3314. }
  3315. }
  3316. // Find actual definition
  3317. Def = PatternDecl->getDefinition(getASTContext());
  3318. } else {
  3319. // If this is a static data member, find its out-of-line definition.
  3320. assert(Var->isStaticDataMember() && "not a static data member?");
  3321. PatternDecl = Var->getInstantiatedFromStaticDataMember();
  3322. assert(PatternDecl && "data member was not instantiated from a template?");
  3323. assert(PatternDecl->isStaticDataMember() && "not a static data member?");
  3324. Def = PatternDecl->getOutOfLineDefinition();
  3325. }
  3326. // If we don't have a definition of the variable template, we won't perform
  3327. // any instantiation. Rather, we rely on the user to instantiate this
  3328. // definition (or provide a specialization for it) in another translation
  3329. // unit.
  3330. if (!Def) {
  3331. if (DefinitionRequired) {
  3332. if (VarSpec)
  3333. Diag(PointOfInstantiation,
  3334. diag::err_explicit_instantiation_undefined_var_template) << Var;
  3335. else
  3336. Diag(PointOfInstantiation,
  3337. diag::err_explicit_instantiation_undefined_member)
  3338. << 2 << Var->getDeclName() << Var->getDeclContext();
  3339. Diag(PatternDecl->getLocation(),
  3340. diag::note_explicit_instantiation_here);
  3341. if (VarSpec)
  3342. Var->setInvalidDecl();
  3343. } else if (Var->getTemplateSpecializationKind()
  3344. == TSK_ExplicitInstantiationDefinition) {
  3345. PendingInstantiations.push_back(
  3346. std::make_pair(Var, PointOfInstantiation));
  3347. }
  3348. return;
  3349. }
  3350. TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
  3351. // Never instantiate an explicit specialization.
  3352. if (TSK == TSK_ExplicitSpecialization)
  3353. return;
  3354. // C++11 [temp.explicit]p10:
  3355. // Except for inline functions, [...] explicit instantiation declarations
  3356. // have the effect of suppressing the implicit instantiation of the entity
  3357. // to which they refer.
  3358. if (TSK == TSK_ExplicitInstantiationDeclaration)
  3359. return;
  3360. // Make sure to pass the instantiated variable to the consumer at the end.
  3361. struct PassToConsumerRAII {
  3362. ASTConsumer &Consumer;
  3363. VarDecl *Var;
  3364. PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
  3365. : Consumer(Consumer), Var(Var) { }
  3366. ~PassToConsumerRAII() {
  3367. Consumer.HandleCXXStaticMemberVarInstantiation(Var);
  3368. }
  3369. } PassToConsumerRAII(Consumer, Var);
  3370. // If we already have a definition, we're done.
  3371. if (VarDecl *Def = Var->getDefinition()) {
  3372. // We may be explicitly instantiating something we've already implicitly
  3373. // instantiated.
  3374. Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
  3375. PointOfInstantiation);
  3376. return;
  3377. }
  3378. InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
  3379. if (Inst.isInvalid())
  3380. return;
  3381. // If we're performing recursive template instantiation, create our own
  3382. // queue of pending implicit instantiations that we will instantiate later,
  3383. // while we're still within our own instantiation context.
  3384. SavePendingLocalImplicitInstantiationsRAII
  3385. SavedPendingLocalImplicitInstantiations(*this);
  3386. SavePendingInstantiationsAndVTableUsesRAII
  3387. SavePendingInstantiationsAndVTableUses(*this, /*Enabled=*/Recursive);
  3388. // Enter the scope of this instantiation. We don't use
  3389. // PushDeclContext because we don't have a scope.
  3390. ContextRAII PreviousContext(*this, Var->getDeclContext());
  3391. LocalInstantiationScope Local(*this);
  3392. VarDecl *OldVar = Var;
  3393. if (!VarSpec)
  3394. Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
  3395. TemplateArgs));
  3396. else if (Var->isStaticDataMember() &&
  3397. Var->getLexicalDeclContext()->isRecord()) {
  3398. // We need to instantiate the definition of a static data member template,
  3399. // and all we have is the in-class declaration of it. Instantiate a separate
  3400. // declaration of the definition.
  3401. TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
  3402. TemplateArgs);
  3403. Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl(
  3404. VarSpec->getSpecializedTemplate(), Def, nullptr,
  3405. VarSpec->getTemplateArgsInfo(), VarSpec->getTemplateArgs().asArray()));
  3406. if (Var) {
  3407. llvm::PointerUnion<VarTemplateDecl *,
  3408. VarTemplatePartialSpecializationDecl *> PatternPtr =
  3409. VarSpec->getSpecializedTemplateOrPartial();
  3410. if (VarTemplatePartialSpecializationDecl *Partial =
  3411. PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
  3412. cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
  3413. Partial, &VarSpec->getTemplateInstantiationArgs());
  3414. // Merge the definition with the declaration.
  3415. LookupResult R(*this, Var->getDeclName(), Var->getLocation(),
  3416. LookupOrdinaryName, ForRedeclaration);
  3417. R.addDecl(OldVar);
  3418. ShadowMergeState MergeState = ShadowMergeState_Disallowed; // HLSL Change - add merge state
  3419. MergeVarDecl(Var, R, MergeState); // HLSL Change - add merge state
  3420. // Attach the initializer.
  3421. InstantiateVariableInitializer(Var, Def, TemplateArgs);
  3422. }
  3423. } else
  3424. // Complete the existing variable's definition with an appropriately
  3425. // substituted type and initializer.
  3426. Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
  3427. PreviousContext.pop();
  3428. if (Var) {
  3429. PassToConsumerRAII.Var = Var;
  3430. Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(),
  3431. OldVar->getPointOfInstantiation());
  3432. }
  3433. // This variable may have local implicit instantiations that need to be
  3434. // instantiated within this scope.
  3435. PerformPendingInstantiations(/*LocalOnly=*/true);
  3436. Local.Exit();
  3437. if (Recursive) {
  3438. // Define any newly required vtables.
  3439. DefineUsedVTables();
  3440. // Instantiate any pending implicit instantiations found during the
  3441. // instantiation of this template.
  3442. PerformPendingInstantiations();
  3443. // PendingInstantiations and VTableUses are restored through
  3444. // SavePendingInstantiationsAndVTableUses's destructor.
  3445. }
  3446. }
  3447. void
  3448. Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
  3449. const CXXConstructorDecl *Tmpl,
  3450. const MultiLevelTemplateArgumentList &TemplateArgs) {
  3451. SmallVector<CXXCtorInitializer*, 4> NewInits;
  3452. bool AnyErrors = Tmpl->isInvalidDecl();
  3453. // Instantiate all the initializers.
  3454. for (const auto *Init : Tmpl->inits()) {
  3455. // Only instantiate written initializers, let Sema re-construct implicit
  3456. // ones.
  3457. if (!Init->isWritten())
  3458. continue;
  3459. SourceLocation EllipsisLoc;
  3460. if (Init->isPackExpansion()) {
  3461. // This is a pack expansion. We should expand it now.
  3462. TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
  3463. SmallVector<UnexpandedParameterPack, 4> Unexpanded;
  3464. collectUnexpandedParameterPacks(BaseTL, Unexpanded);
  3465. collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
  3466. bool ShouldExpand = false;
  3467. bool RetainExpansion = false;
  3468. Optional<unsigned> NumExpansions;
  3469. if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
  3470. BaseTL.getSourceRange(),
  3471. Unexpanded,
  3472. TemplateArgs, ShouldExpand,
  3473. RetainExpansion,
  3474. NumExpansions)) {
  3475. AnyErrors = true;
  3476. New->setInvalidDecl();
  3477. continue;
  3478. }
  3479. assert(ShouldExpand && "Partial instantiation of base initializer?");
  3480. // Loop over all of the arguments in the argument pack(s),
  3481. for (unsigned I = 0; I != *NumExpansions; ++I) {
  3482. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
  3483. // Instantiate the initializer.
  3484. ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
  3485. /*CXXDirectInit=*/true);
  3486. if (TempInit.isInvalid()) {
  3487. AnyErrors = true;
  3488. break;
  3489. }
  3490. // Instantiate the base type.
  3491. TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
  3492. TemplateArgs,
  3493. Init->getSourceLocation(),
  3494. New->getDeclName());
  3495. if (!BaseTInfo) {
  3496. AnyErrors = true;
  3497. break;
  3498. }
  3499. // Build the initializer.
  3500. MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
  3501. BaseTInfo, TempInit.get(),
  3502. New->getParent(),
  3503. SourceLocation());
  3504. if (NewInit.isInvalid()) {
  3505. AnyErrors = true;
  3506. break;
  3507. }
  3508. NewInits.push_back(NewInit.get());
  3509. }
  3510. continue;
  3511. }
  3512. // Instantiate the initializer.
  3513. ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
  3514. /*CXXDirectInit=*/true);
  3515. if (TempInit.isInvalid()) {
  3516. AnyErrors = true;
  3517. continue;
  3518. }
  3519. MemInitResult NewInit;
  3520. if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
  3521. TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
  3522. TemplateArgs,
  3523. Init->getSourceLocation(),
  3524. New->getDeclName());
  3525. if (!TInfo) {
  3526. AnyErrors = true;
  3527. New->setInvalidDecl();
  3528. continue;
  3529. }
  3530. if (Init->isBaseInitializer())
  3531. NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.get(),
  3532. New->getParent(), EllipsisLoc);
  3533. else
  3534. NewInit = BuildDelegatingInitializer(TInfo, TempInit.get(),
  3535. cast<CXXRecordDecl>(CurContext->getParent()));
  3536. } else if (Init->isMemberInitializer()) {
  3537. FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
  3538. Init->getMemberLocation(),
  3539. Init->getMember(),
  3540. TemplateArgs));
  3541. if (!Member) {
  3542. AnyErrors = true;
  3543. New->setInvalidDecl();
  3544. continue;
  3545. }
  3546. NewInit = BuildMemberInitializer(Member, TempInit.get(),
  3547. Init->getSourceLocation());
  3548. } else if (Init->isIndirectMemberInitializer()) {
  3549. IndirectFieldDecl *IndirectMember =
  3550. cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
  3551. Init->getMemberLocation(),
  3552. Init->getIndirectMember(), TemplateArgs));
  3553. if (!IndirectMember) {
  3554. AnyErrors = true;
  3555. New->setInvalidDecl();
  3556. continue;
  3557. }
  3558. NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(),
  3559. Init->getSourceLocation());
  3560. }
  3561. if (NewInit.isInvalid()) {
  3562. AnyErrors = true;
  3563. New->setInvalidDecl();
  3564. } else {
  3565. NewInits.push_back(NewInit.get());
  3566. }
  3567. }
  3568. // Assign all the initializers to the new constructor.
  3569. ActOnMemInitializers(New,
  3570. /*FIXME: ColonLoc */
  3571. SourceLocation(),
  3572. NewInits,
  3573. AnyErrors);
  3574. }
  3575. // TODO: this could be templated if the various decl types used the
  3576. // same method name.
  3577. static bool isInstantiationOf(ClassTemplateDecl *Pattern,
  3578. ClassTemplateDecl *Instance) {
  3579. Pattern = Pattern->getCanonicalDecl();
  3580. do {
  3581. Instance = Instance->getCanonicalDecl();
  3582. if (Pattern == Instance) return true;
  3583. Instance = Instance->getInstantiatedFromMemberTemplate();
  3584. } while (Instance);
  3585. return false;
  3586. }
  3587. static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
  3588. FunctionTemplateDecl *Instance) {
  3589. Pattern = Pattern->getCanonicalDecl();
  3590. do {
  3591. Instance = Instance->getCanonicalDecl();
  3592. if (Pattern == Instance) return true;
  3593. Instance = Instance->getInstantiatedFromMemberTemplate();
  3594. } while (Instance);
  3595. return false;
  3596. }
  3597. static bool
  3598. isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
  3599. ClassTemplatePartialSpecializationDecl *Instance) {
  3600. Pattern
  3601. = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
  3602. do {
  3603. Instance = cast<ClassTemplatePartialSpecializationDecl>(
  3604. Instance->getCanonicalDecl());
  3605. if (Pattern == Instance)
  3606. return true;
  3607. Instance = Instance->getInstantiatedFromMember();
  3608. } while (Instance);
  3609. return false;
  3610. }
  3611. static bool isInstantiationOf(CXXRecordDecl *Pattern,
  3612. CXXRecordDecl *Instance) {
  3613. Pattern = Pattern->getCanonicalDecl();
  3614. do {
  3615. Instance = Instance->getCanonicalDecl();
  3616. if (Pattern == Instance) return true;
  3617. Instance = Instance->getInstantiatedFromMemberClass();
  3618. } while (Instance);
  3619. return false;
  3620. }
  3621. static bool isInstantiationOf(FunctionDecl *Pattern,
  3622. FunctionDecl *Instance) {
  3623. Pattern = Pattern->getCanonicalDecl();
  3624. do {
  3625. Instance = Instance->getCanonicalDecl();
  3626. if (Pattern == Instance) return true;
  3627. Instance = Instance->getInstantiatedFromMemberFunction();
  3628. } while (Instance);
  3629. return false;
  3630. }
  3631. static bool isInstantiationOf(EnumDecl *Pattern,
  3632. EnumDecl *Instance) {
  3633. Pattern = Pattern->getCanonicalDecl();
  3634. do {
  3635. Instance = Instance->getCanonicalDecl();
  3636. if (Pattern == Instance) return true;
  3637. Instance = Instance->getInstantiatedFromMemberEnum();
  3638. } while (Instance);
  3639. return false;
  3640. }
  3641. static bool isInstantiationOf(UsingShadowDecl *Pattern,
  3642. UsingShadowDecl *Instance,
  3643. ASTContext &C) {
  3644. return declaresSameEntity(C.getInstantiatedFromUsingShadowDecl(Instance),
  3645. Pattern);
  3646. }
  3647. static bool isInstantiationOf(UsingDecl *Pattern,
  3648. UsingDecl *Instance,
  3649. ASTContext &C) {
  3650. return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
  3651. }
  3652. static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
  3653. UsingDecl *Instance,
  3654. ASTContext &C) {
  3655. return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
  3656. }
  3657. static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
  3658. UsingDecl *Instance,
  3659. ASTContext &C) {
  3660. return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
  3661. }
  3662. static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
  3663. VarDecl *Instance) {
  3664. assert(Instance->isStaticDataMember());
  3665. Pattern = Pattern->getCanonicalDecl();
  3666. do {
  3667. Instance = Instance->getCanonicalDecl();
  3668. if (Pattern == Instance) return true;
  3669. Instance = Instance->getInstantiatedFromStaticDataMember();
  3670. } while (Instance);
  3671. return false;
  3672. }
  3673. // Other is the prospective instantiation
  3674. // D is the prospective pattern
  3675. static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
  3676. if (D->getKind() != Other->getKind()) {
  3677. if (UnresolvedUsingTypenameDecl *UUD
  3678. = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
  3679. if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
  3680. return isInstantiationOf(UUD, UD, Ctx);
  3681. }
  3682. }
  3683. if (UnresolvedUsingValueDecl *UUD
  3684. = dyn_cast<UnresolvedUsingValueDecl>(D)) {
  3685. if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
  3686. return isInstantiationOf(UUD, UD, Ctx);
  3687. }
  3688. }
  3689. return false;
  3690. }
  3691. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
  3692. return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
  3693. if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
  3694. return isInstantiationOf(cast<FunctionDecl>(D), Function);
  3695. if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
  3696. return isInstantiationOf(cast<EnumDecl>(D), Enum);
  3697. if (VarDecl *Var = dyn_cast<VarDecl>(Other))
  3698. if (Var->isStaticDataMember())
  3699. return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
  3700. if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
  3701. return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
  3702. if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
  3703. return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
  3704. if (ClassTemplatePartialSpecializationDecl *PartialSpec
  3705. = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
  3706. return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
  3707. PartialSpec);
  3708. if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
  3709. if (!Field->getDeclName()) {
  3710. // This is an unnamed field.
  3711. return declaresSameEntity(Ctx.getInstantiatedFromUnnamedFieldDecl(Field),
  3712. cast<FieldDecl>(D));
  3713. }
  3714. }
  3715. if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
  3716. return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
  3717. if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
  3718. return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
  3719. return D->getDeclName() && isa<NamedDecl>(Other) &&
  3720. D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
  3721. }
  3722. template<typename ForwardIterator>
  3723. static NamedDecl *findInstantiationOf(ASTContext &Ctx,
  3724. NamedDecl *D,
  3725. ForwardIterator first,
  3726. ForwardIterator last) {
  3727. for (; first != last; ++first)
  3728. if (isInstantiationOf(Ctx, D, *first))
  3729. return cast<NamedDecl>(*first);
  3730. return nullptr;
  3731. }
  3732. /// \brief Finds the instantiation of the given declaration context
  3733. /// within the current instantiation.
  3734. ///
  3735. /// \returns NULL if there was an error
  3736. DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
  3737. const MultiLevelTemplateArgumentList &TemplateArgs) {
  3738. if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
  3739. Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
  3740. return cast_or_null<DeclContext>(ID);
  3741. } else return DC;
  3742. }
  3743. /// \brief Find the instantiation of the given declaration within the
  3744. /// current instantiation.
  3745. ///
  3746. /// This routine is intended to be used when \p D is a declaration
  3747. /// referenced from within a template, that needs to mapped into the
  3748. /// corresponding declaration within an instantiation. For example,
  3749. /// given:
  3750. ///
  3751. /// \code
  3752. /// template<typename T>
  3753. /// struct X {
  3754. /// enum Kind {
  3755. /// KnownValue = sizeof(T)
  3756. /// };
  3757. ///
  3758. /// bool getKind() const { return KnownValue; }
  3759. /// };
  3760. ///
  3761. /// template struct X<int>;
  3762. /// \endcode
  3763. ///
  3764. /// In the instantiation of <tt>X<int>::getKind()</tt>, we need to map the
  3765. /// \p EnumConstantDecl for \p KnownValue (which refers to
  3766. /// <tt>X<T>::<Kind>::KnownValue</tt>) to its instantiation
  3767. /// (<tt>X<int>::<Kind>::KnownValue</tt>). \p FindInstantiatedDecl performs
  3768. /// this mapping from within the instantiation of <tt>X<int></tt>.
  3769. NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
  3770. const MultiLevelTemplateArgumentList &TemplateArgs) {
  3771. DeclContext *ParentDC = D->getDeclContext();
  3772. // FIXME: Parmeters of pointer to functions (y below) that are themselves
  3773. // parameters (p below) can have their ParentDC set to the translation-unit
  3774. // - thus we can not consistently check if the ParentDC of such a parameter
  3775. // is Dependent or/and a FunctionOrMethod.
  3776. // For e.g. this code, during Template argument deduction tries to
  3777. // find an instantiated decl for (T y) when the ParentDC for y is
  3778. // the translation unit.
  3779. // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
  3780. // float baz(float(*)()) { return 0.0; }
  3781. // Foo(baz);
  3782. // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
  3783. // it gets here, always has a FunctionOrMethod as its ParentDC??
  3784. // For now:
  3785. // - as long as we have a ParmVarDecl whose parent is non-dependent and
  3786. // whose type is not instantiation dependent, do nothing to the decl
  3787. // - otherwise find its instantiated decl.
  3788. if (isa<ParmVarDecl>(D) && !ParentDC->isDependentContext() &&
  3789. !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
  3790. return D;
  3791. if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
  3792. isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
  3793. (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) ||
  3794. (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
  3795. // D is a local of some kind. Look into the map of local
  3796. // declarations to their instantiations.
  3797. if (CurrentInstantiationScope) {
  3798. if (auto Found = CurrentInstantiationScope->findInstantiationOf(D)) {
  3799. if (Decl *FD = Found->dyn_cast<Decl *>())
  3800. return cast<NamedDecl>(FD);
  3801. int PackIdx = ArgumentPackSubstitutionIndex;
  3802. assert(PackIdx != -1 &&
  3803. "found declaration pack but not pack expanding");
  3804. typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
  3805. return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
  3806. }
  3807. }
  3808. // If we're performing a partial substitution during template argument
  3809. // deduction, we may not have values for template parameters yet. They
  3810. // just map to themselves.
  3811. if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
  3812. isa<TemplateTemplateParmDecl>(D))
  3813. return D;
  3814. if (D->isInvalidDecl())
  3815. return nullptr;
  3816. // Normally this function only searches for already instantiated declaration
  3817. // however we have to make an exclusion for local types used before
  3818. // definition as in the code:
  3819. //
  3820. // template<typename T> void f1() {
  3821. // void g1(struct x1);
  3822. // struct x1 {};
  3823. // }
  3824. //
  3825. // In this case instantiation of the type of 'g1' requires definition of
  3826. // 'x1', which is defined later. Error recovery may produce an enum used
  3827. // before definition. In these cases we need to instantiate relevant
  3828. // declarations here.
  3829. bool NeedInstantiate = false;
  3830. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
  3831. NeedInstantiate = RD->isLocalClass();
  3832. else
  3833. NeedInstantiate = isa<EnumDecl>(D);
  3834. if (NeedInstantiate) {
  3835. Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
  3836. CurrentInstantiationScope->InstantiatedLocal(D, Inst);
  3837. return cast<TypeDecl>(Inst);
  3838. }
  3839. // If we didn't find the decl, then we must have a label decl that hasn't
  3840. // been found yet. Lazily instantiate it and return it now.
  3841. assert(isa<LabelDecl>(D));
  3842. Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
  3843. assert(Inst && "Failed to instantiate label??");
  3844. CurrentInstantiationScope->InstantiatedLocal(D, Inst);
  3845. return cast<LabelDecl>(Inst);
  3846. }
  3847. // For variable template specializations, update those that are still
  3848. // type-dependent.
  3849. if (VarTemplateSpecializationDecl *VarSpec =
  3850. dyn_cast<VarTemplateSpecializationDecl>(D)) {
  3851. bool InstantiationDependent = false;
  3852. const TemplateArgumentListInfo &VarTemplateArgs =
  3853. VarSpec->getTemplateArgsInfo();
  3854. if (TemplateSpecializationType::anyDependentTemplateArguments(
  3855. VarTemplateArgs, InstantiationDependent))
  3856. D = cast<NamedDecl>(
  3857. SubstDecl(D, VarSpec->getDeclContext(), TemplateArgs));
  3858. return D;
  3859. }
  3860. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
  3861. if (!Record->isDependentContext())
  3862. return D;
  3863. // Determine whether this record is the "templated" declaration describing
  3864. // a class template or class template partial specialization.
  3865. ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
  3866. if (ClassTemplate)
  3867. ClassTemplate = ClassTemplate->getCanonicalDecl();
  3868. else if (ClassTemplatePartialSpecializationDecl *PartialSpec
  3869. = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
  3870. ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
  3871. // Walk the current context to find either the record or an instantiation of
  3872. // it.
  3873. DeclContext *DC = CurContext;
  3874. while (!DC->isFileContext()) {
  3875. // If we're performing substitution while we're inside the template
  3876. // definition, we'll find our own context. We're done.
  3877. if (DC->Equals(Record))
  3878. return Record;
  3879. if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
  3880. // Check whether we're in the process of instantiating a class template
  3881. // specialization of the template we're mapping.
  3882. if (ClassTemplateSpecializationDecl *InstSpec
  3883. = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
  3884. ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
  3885. if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
  3886. return InstRecord;
  3887. }
  3888. // Check whether we're in the process of instantiating a member class.
  3889. if (isInstantiationOf(Record, InstRecord))
  3890. return InstRecord;
  3891. }
  3892. // Move to the outer template scope.
  3893. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
  3894. if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
  3895. DC = FD->getLexicalDeclContext();
  3896. continue;
  3897. }
  3898. }
  3899. DC = DC->getParent();
  3900. }
  3901. // Fall through to deal with other dependent record types (e.g.,
  3902. // anonymous unions in class templates).
  3903. }
  3904. if (!ParentDC->isDependentContext())
  3905. return D;
  3906. ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
  3907. if (!ParentDC)
  3908. return nullptr;
  3909. if (ParentDC != D->getDeclContext()) {
  3910. // We performed some kind of instantiation in the parent context,
  3911. // so now we need to look into the instantiated parent context to
  3912. // find the instantiation of the declaration D.
  3913. // If our context used to be dependent, we may need to instantiate
  3914. // it before performing lookup into that context.
  3915. bool IsBeingInstantiated = false;
  3916. if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
  3917. if (!Spec->isDependentContext()) {
  3918. QualType T = Context.getTypeDeclType(Spec);
  3919. const RecordType *Tag = T->getAs<RecordType>();
  3920. assert(Tag && "type of non-dependent record is not a RecordType");
  3921. if (Tag->isBeingDefined())
  3922. IsBeingInstantiated = true;
  3923. if (!Tag->isBeingDefined() &&
  3924. RequireCompleteType(Loc, T, diag::err_incomplete_type))
  3925. return nullptr;
  3926. ParentDC = Tag->getDecl();
  3927. }
  3928. }
  3929. NamedDecl *Result = nullptr;
  3930. if (D->getDeclName()) {
  3931. DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
  3932. Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
  3933. } else {
  3934. // Since we don't have a name for the entity we're looking for,
  3935. // our only option is to walk through all of the declarations to
  3936. // find that name. This will occur in a few cases:
  3937. //
  3938. // - anonymous struct/union within a template
  3939. // - unnamed class/struct/union/enum within a template
  3940. //
  3941. // FIXME: Find a better way to find these instantiations!
  3942. Result = findInstantiationOf(Context, D,
  3943. ParentDC->decls_begin(),
  3944. ParentDC->decls_end());
  3945. }
  3946. if (!Result) {
  3947. if (isa<UsingShadowDecl>(D)) {
  3948. // UsingShadowDecls can instantiate to nothing because of using hiding.
  3949. } else if (Diags.hasErrorOccurred()) {
  3950. // We've already complained about something, so most likely this
  3951. // declaration failed to instantiate. There's no point in complaining
  3952. // further, since this is normal in invalid code.
  3953. } else if (IsBeingInstantiated) {
  3954. // The class in which this member exists is currently being
  3955. // instantiated, and we haven't gotten around to instantiating this
  3956. // member yet. This can happen when the code uses forward declarations
  3957. // of member classes, and introduces ordering dependencies via
  3958. // template instantiation.
  3959. Diag(Loc, diag::err_member_not_yet_instantiated)
  3960. << D->getDeclName()
  3961. << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
  3962. Diag(D->getLocation(), diag::note_non_instantiated_member_here);
  3963. } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
  3964. // This enumeration constant was found when the template was defined,
  3965. // but can't be found in the instantiation. This can happen if an
  3966. // unscoped enumeration member is explicitly specialized.
  3967. EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
  3968. EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
  3969. TemplateArgs));
  3970. assert(Spec->getTemplateSpecializationKind() ==
  3971. TSK_ExplicitSpecialization);
  3972. Diag(Loc, diag::err_enumerator_does_not_exist)
  3973. << D->getDeclName()
  3974. << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
  3975. Diag(Spec->getLocation(), diag::note_enum_specialized_here)
  3976. << Context.getTypeDeclType(Spec);
  3977. } else {
  3978. // We should have found something, but didn't.
  3979. llvm_unreachable("Unable to find instantiation of declaration!");
  3980. }
  3981. }
  3982. D = Result;
  3983. }
  3984. return D;
  3985. }
  3986. /// \brief Performs template instantiation for all implicit template
  3987. /// instantiations we have seen until this point.
  3988. void Sema::PerformPendingInstantiations(bool LocalOnly) {
  3989. while (!PendingLocalImplicitInstantiations.empty() ||
  3990. (!LocalOnly && !PendingInstantiations.empty())) {
  3991. PendingImplicitInstantiation Inst;
  3992. if (PendingLocalImplicitInstantiations.empty()) {
  3993. Inst = PendingInstantiations.front();
  3994. PendingInstantiations.pop_front();
  3995. } else {
  3996. Inst = PendingLocalImplicitInstantiations.front();
  3997. PendingLocalImplicitInstantiations.pop_front();
  3998. }
  3999. // Instantiate function definitions
  4000. if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
  4001. PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
  4002. "instantiating function definition");
  4003. bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
  4004. TSK_ExplicitInstantiationDefinition;
  4005. InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
  4006. DefinitionRequired);
  4007. continue;
  4008. }
  4009. // Instantiate variable definitions
  4010. VarDecl *Var = cast<VarDecl>(Inst.first);
  4011. assert((Var->isStaticDataMember() ||
  4012. isa<VarTemplateSpecializationDecl>(Var)) &&
  4013. "Not a static data member, nor a variable template"
  4014. " specialization?");
  4015. // Don't try to instantiate declarations if the most recent redeclaration
  4016. // is invalid.
  4017. if (Var->getMostRecentDecl()->isInvalidDecl())
  4018. continue;
  4019. // Check if the most recent declaration has changed the specialization kind
  4020. // and removed the need for implicit instantiation.
  4021. switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) {
  4022. case TSK_Undeclared:
  4023. llvm_unreachable("Cannot instantitiate an undeclared specialization.");
  4024. case TSK_ExplicitInstantiationDeclaration:
  4025. case TSK_ExplicitSpecialization:
  4026. continue; // No longer need to instantiate this type.
  4027. case TSK_ExplicitInstantiationDefinition:
  4028. // We only need an instantiation if the pending instantiation *is* the
  4029. // explicit instantiation.
  4030. if (Var != Var->getMostRecentDecl()) continue;
  4031. case TSK_ImplicitInstantiation:
  4032. break;
  4033. }
  4034. PrettyDeclStackTraceEntry CrashInfo(*this, Var, SourceLocation(),
  4035. "instantiating variable definition");
  4036. bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
  4037. TSK_ExplicitInstantiationDefinition;
  4038. // Instantiate static data member definitions or variable template
  4039. // specializations.
  4040. InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
  4041. DefinitionRequired);
  4042. }
  4043. }
  4044. void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
  4045. const MultiLevelTemplateArgumentList &TemplateArgs) {
  4046. for (auto DD : Pattern->ddiags()) {
  4047. switch (DD->getKind()) {
  4048. case DependentDiagnostic::Access:
  4049. HandleDependentAccessCheck(*DD, TemplateArgs);
  4050. break;
  4051. }
  4052. }
  4053. }