SemaTemplateInstantiateDecl.cpp 217 KB

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