SemaTemplate.cpp 419 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479
  1. //===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===//
  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 semantic analysis for C++ templates.
  9. //===----------------------------------------------------------------------===//
  10. #include "TreeTransform.h"
  11. #include "clang/AST/ASTConsumer.h"
  12. #include "clang/AST/ASTContext.h"
  13. #include "clang/AST/DeclFriend.h"
  14. #include "clang/AST/DeclTemplate.h"
  15. #include "clang/AST/Expr.h"
  16. #include "clang/AST/ExprCXX.h"
  17. #include "clang/AST/RecursiveASTVisitor.h"
  18. #include "clang/AST/TypeVisitor.h"
  19. #include "clang/Basic/Builtins.h"
  20. #include "clang/Basic/LangOptions.h"
  21. #include "clang/Basic/PartialDiagnostic.h"
  22. #include "clang/Basic/Stack.h"
  23. #include "clang/Basic/TargetInfo.h"
  24. #include "clang/Sema/DeclSpec.h"
  25. #include "clang/Sema/Lookup.h"
  26. #include "clang/Sema/ParsedTemplate.h"
  27. #include "clang/Sema/Scope.h"
  28. #include "clang/Sema/SemaInternal.h"
  29. #include "clang/Sema/Template.h"
  30. #include "clang/Sema/TemplateDeduction.h"
  31. #include "llvm/ADT/SmallBitVector.h"
  32. #include "llvm/ADT/SmallString.h"
  33. #include "llvm/ADT/StringExtras.h"
  34. #include <iterator>
  35. using namespace clang;
  36. using namespace sema;
  37. // Exported for use by Parser.
  38. SourceRange
  39. clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
  40. unsigned N) {
  41. if (!N) return SourceRange();
  42. return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
  43. }
  44. namespace clang {
  45. /// [temp.constr.decl]p2: A template's associated constraints are
  46. /// defined as a single constraint-expression derived from the introduced
  47. /// constraint-expressions [ ... ].
  48. ///
  49. /// \param Params The template parameter list and optional requires-clause.
  50. ///
  51. /// \param FD The underlying templated function declaration for a function
  52. /// template.
  53. static Expr *formAssociatedConstraints(TemplateParameterList *Params,
  54. FunctionDecl *FD);
  55. }
  56. static Expr *clang::formAssociatedConstraints(TemplateParameterList *Params,
  57. FunctionDecl *FD) {
  58. // FIXME: Concepts: collect additional introduced constraint-expressions
  59. assert(!FD && "Cannot collect constraints from function declaration yet.");
  60. return Params->getRequiresClause();
  61. }
  62. /// Determine whether the declaration found is acceptable as the name
  63. /// of a template and, if so, return that template declaration. Otherwise,
  64. /// returns null.
  65. ///
  66. /// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
  67. /// is true. In all other cases it will return a TemplateDecl (or null).
  68. NamedDecl *Sema::getAsTemplateNameDecl(NamedDecl *D,
  69. bool AllowFunctionTemplates,
  70. bool AllowDependent) {
  71. D = D->getUnderlyingDecl();
  72. if (isa<TemplateDecl>(D)) {
  73. if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
  74. return nullptr;
  75. return D;
  76. }
  77. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
  78. // C++ [temp.local]p1:
  79. // Like normal (non-template) classes, class templates have an
  80. // injected-class-name (Clause 9). The injected-class-name
  81. // can be used with or without a template-argument-list. When
  82. // it is used without a template-argument-list, it is
  83. // equivalent to the injected-class-name followed by the
  84. // template-parameters of the class template enclosed in
  85. // <>. When it is used with a template-argument-list, it
  86. // refers to the specified class template specialization,
  87. // which could be the current specialization or another
  88. // specialization.
  89. if (Record->isInjectedClassName()) {
  90. Record = cast<CXXRecordDecl>(Record->getDeclContext());
  91. if (Record->getDescribedClassTemplate())
  92. return Record->getDescribedClassTemplate();
  93. if (ClassTemplateSpecializationDecl *Spec
  94. = dyn_cast<ClassTemplateSpecializationDecl>(Record))
  95. return Spec->getSpecializedTemplate();
  96. }
  97. return nullptr;
  98. }
  99. // 'using Dependent::foo;' can resolve to a template name.
  100. // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
  101. // injected-class-name).
  102. if (AllowDependent && isa<UnresolvedUsingValueDecl>(D))
  103. return D;
  104. return nullptr;
  105. }
  106. void Sema::FilterAcceptableTemplateNames(LookupResult &R,
  107. bool AllowFunctionTemplates,
  108. bool AllowDependent) {
  109. LookupResult::Filter filter = R.makeFilter();
  110. while (filter.hasNext()) {
  111. NamedDecl *Orig = filter.next();
  112. if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent))
  113. filter.erase();
  114. }
  115. filter.done();
  116. }
  117. bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
  118. bool AllowFunctionTemplates,
  119. bool AllowDependent,
  120. bool AllowNonTemplateFunctions) {
  121. for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
  122. if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent))
  123. return true;
  124. if (AllowNonTemplateFunctions &&
  125. isa<FunctionDecl>((*I)->getUnderlyingDecl()))
  126. return true;
  127. }
  128. return false;
  129. }
  130. TemplateNameKind Sema::isTemplateName(Scope *S,
  131. CXXScopeSpec &SS,
  132. bool hasTemplateKeyword,
  133. const UnqualifiedId &Name,
  134. ParsedType ObjectTypePtr,
  135. bool EnteringContext,
  136. TemplateTy &TemplateResult,
  137. bool &MemberOfUnknownSpecialization) {
  138. assert(getLangOpts().CPlusPlus && "No template names in C!");
  139. DeclarationName TName;
  140. MemberOfUnknownSpecialization = false;
  141. switch (Name.getKind()) {
  142. case UnqualifiedIdKind::IK_Identifier:
  143. TName = DeclarationName(Name.Identifier);
  144. break;
  145. case UnqualifiedIdKind::IK_OperatorFunctionId:
  146. TName = Context.DeclarationNames.getCXXOperatorName(
  147. Name.OperatorFunctionId.Operator);
  148. break;
  149. case UnqualifiedIdKind::IK_LiteralOperatorId:
  150. TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
  151. break;
  152. default:
  153. return TNK_Non_template;
  154. }
  155. QualType ObjectType = ObjectTypePtr.get();
  156. AssumedTemplateKind AssumedTemplate;
  157. LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
  158. if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
  159. MemberOfUnknownSpecialization, SourceLocation(),
  160. &AssumedTemplate))
  161. return TNK_Non_template;
  162. if (AssumedTemplate != AssumedTemplateKind::None) {
  163. TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName));
  164. // Let the parser know whether we found nothing or found functions; if we
  165. // found nothing, we want to more carefully check whether this is actually
  166. // a function template name versus some other kind of undeclared identifier.
  167. return AssumedTemplate == AssumedTemplateKind::FoundNothing
  168. ? TNK_Undeclared_template
  169. : TNK_Function_template;
  170. }
  171. if (R.empty())
  172. return TNK_Non_template;
  173. NamedDecl *D = nullptr;
  174. if (R.isAmbiguous()) {
  175. // If we got an ambiguity involving a non-function template, treat this
  176. // as a template name, and pick an arbitrary template for error recovery.
  177. bool AnyFunctionTemplates = false;
  178. for (NamedDecl *FoundD : R) {
  179. if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) {
  180. if (isa<FunctionTemplateDecl>(FoundTemplate))
  181. AnyFunctionTemplates = true;
  182. else {
  183. D = FoundTemplate;
  184. break;
  185. }
  186. }
  187. }
  188. // If we didn't find any templates at all, this isn't a template name.
  189. // Leave the ambiguity for a later lookup to diagnose.
  190. if (!D && !AnyFunctionTemplates) {
  191. R.suppressDiagnostics();
  192. return TNK_Non_template;
  193. }
  194. // If the only templates were function templates, filter out the rest.
  195. // We'll diagnose the ambiguity later.
  196. if (!D)
  197. FilterAcceptableTemplateNames(R);
  198. }
  199. // At this point, we have either picked a single template name declaration D
  200. // or we have a non-empty set of results R containing either one template name
  201. // declaration or a set of function templates.
  202. TemplateName Template;
  203. TemplateNameKind TemplateKind;
  204. unsigned ResultCount = R.end() - R.begin();
  205. if (!D && ResultCount > 1) {
  206. // We assume that we'll preserve the qualifier from a function
  207. // template name in other ways.
  208. Template = Context.getOverloadedTemplateName(R.begin(), R.end());
  209. TemplateKind = TNK_Function_template;
  210. // We'll do this lookup again later.
  211. R.suppressDiagnostics();
  212. } else {
  213. if (!D) {
  214. D = getAsTemplateNameDecl(*R.begin());
  215. assert(D && "unambiguous result is not a template name");
  216. }
  217. if (isa<UnresolvedUsingValueDecl>(D)) {
  218. // We don't yet know whether this is a template-name or not.
  219. MemberOfUnknownSpecialization = true;
  220. return TNK_Non_template;
  221. }
  222. TemplateDecl *TD = cast<TemplateDecl>(D);
  223. if (SS.isSet() && !SS.isInvalid()) {
  224. NestedNameSpecifier *Qualifier = SS.getScopeRep();
  225. Template = Context.getQualifiedTemplateName(Qualifier,
  226. hasTemplateKeyword, TD);
  227. } else {
  228. Template = TemplateName(TD);
  229. }
  230. if (isa<FunctionTemplateDecl>(TD)) {
  231. TemplateKind = TNK_Function_template;
  232. // We'll do this lookup again later.
  233. R.suppressDiagnostics();
  234. } else {
  235. assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
  236. isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
  237. isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD));
  238. TemplateKind =
  239. isa<VarTemplateDecl>(TD) ? TNK_Var_template :
  240. isa<ConceptDecl>(TD) ? TNK_Concept_template :
  241. TNK_Type_template;
  242. }
  243. }
  244. TemplateResult = TemplateTy::make(Template);
  245. return TemplateKind;
  246. }
  247. bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
  248. SourceLocation NameLoc,
  249. ParsedTemplateTy *Template) {
  250. CXXScopeSpec SS;
  251. bool MemberOfUnknownSpecialization = false;
  252. // We could use redeclaration lookup here, but we don't need to: the
  253. // syntactic form of a deduction guide is enough to identify it even
  254. // if we can't look up the template name at all.
  255. LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
  256. if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
  257. /*EnteringContext*/ false,
  258. MemberOfUnknownSpecialization))
  259. return false;
  260. if (R.empty()) return false;
  261. if (R.isAmbiguous()) {
  262. // FIXME: Diagnose an ambiguity if we find at least one template.
  263. R.suppressDiagnostics();
  264. return false;
  265. }
  266. // We only treat template-names that name type templates as valid deduction
  267. // guide names.
  268. TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
  269. if (!TD || !getAsTypeTemplateDecl(TD))
  270. return false;
  271. if (Template)
  272. *Template = TemplateTy::make(TemplateName(TD));
  273. return true;
  274. }
  275. bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
  276. SourceLocation IILoc,
  277. Scope *S,
  278. const CXXScopeSpec *SS,
  279. TemplateTy &SuggestedTemplate,
  280. TemplateNameKind &SuggestedKind) {
  281. // We can't recover unless there's a dependent scope specifier preceding the
  282. // template name.
  283. // FIXME: Typo correction?
  284. if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
  285. computeDeclContext(*SS))
  286. return false;
  287. // The code is missing a 'template' keyword prior to the dependent template
  288. // name.
  289. NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
  290. Diag(IILoc, diag::err_template_kw_missing)
  291. << Qualifier << II.getName()
  292. << FixItHint::CreateInsertion(IILoc, "template ");
  293. SuggestedTemplate
  294. = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
  295. SuggestedKind = TNK_Dependent_template_name;
  296. return true;
  297. }
  298. bool Sema::LookupTemplateName(LookupResult &Found,
  299. Scope *S, CXXScopeSpec &SS,
  300. QualType ObjectType,
  301. bool EnteringContext,
  302. bool &MemberOfUnknownSpecialization,
  303. SourceLocation TemplateKWLoc,
  304. AssumedTemplateKind *ATK) {
  305. if (ATK)
  306. *ATK = AssumedTemplateKind::None;
  307. Found.setTemplateNameLookup(true);
  308. // Determine where to perform name lookup
  309. MemberOfUnknownSpecialization = false;
  310. DeclContext *LookupCtx = nullptr;
  311. bool IsDependent = false;
  312. if (!ObjectType.isNull()) {
  313. // This nested-name-specifier occurs in a member access expression, e.g.,
  314. // x->B::f, and we are looking into the type of the object.
  315. assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
  316. LookupCtx = computeDeclContext(ObjectType);
  317. IsDependent = !LookupCtx && ObjectType->isDependentType();
  318. assert((IsDependent || !ObjectType->isIncompleteType() ||
  319. ObjectType->castAs<TagType>()->isBeingDefined()) &&
  320. "Caller should have completed object type");
  321. // Template names cannot appear inside an Objective-C class or object type
  322. // or a vector type.
  323. //
  324. // FIXME: This is wrong. For example:
  325. //
  326. // template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
  327. // Vec<int> vi;
  328. // vi.Vec<int>::~Vec<int>();
  329. //
  330. // ... should be accepted but we will not treat 'Vec' as a template name
  331. // here. The right thing to do would be to check if the name is a valid
  332. // vector component name, and look up a template name if not. And similarly
  333. // for lookups into Objective-C class and object types, where the same
  334. // problem can arise.
  335. if (ObjectType->isObjCObjectOrInterfaceType() ||
  336. ObjectType->isVectorType()) {
  337. Found.clear();
  338. return false;
  339. }
  340. } else if (SS.isSet()) {
  341. // This nested-name-specifier occurs after another nested-name-specifier,
  342. // so long into the context associated with the prior nested-name-specifier.
  343. LookupCtx = computeDeclContext(SS, EnteringContext);
  344. IsDependent = !LookupCtx;
  345. // The declaration context must be complete.
  346. if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
  347. return true;
  348. }
  349. bool ObjectTypeSearchedInScope = false;
  350. bool AllowFunctionTemplatesInLookup = true;
  351. if (LookupCtx) {
  352. // Perform "qualified" name lookup into the declaration context we
  353. // computed, which is either the type of the base of a member access
  354. // expression or the declaration context associated with a prior
  355. // nested-name-specifier.
  356. LookupQualifiedName(Found, LookupCtx);
  357. // FIXME: The C++ standard does not clearly specify what happens in the
  358. // case where the object type is dependent, and implementations vary. In
  359. // Clang, we treat a name after a . or -> as a template-name if lookup
  360. // finds a non-dependent member or member of the current instantiation that
  361. // is a type template, or finds no such members and lookup in the context
  362. // of the postfix-expression finds a type template. In the latter case, the
  363. // name is nonetheless dependent, and we may resolve it to a member of an
  364. // unknown specialization when we come to instantiate the template.
  365. IsDependent |= Found.wasNotFoundInCurrentInstantiation();
  366. }
  367. if (!SS.isSet() && (ObjectType.isNull() || Found.empty())) {
  368. // C++ [basic.lookup.classref]p1:
  369. // In a class member access expression (5.2.5), if the . or -> token is
  370. // immediately followed by an identifier followed by a <, the
  371. // identifier must be looked up to determine whether the < is the
  372. // beginning of a template argument list (14.2) or a less-than operator.
  373. // The identifier is first looked up in the class of the object
  374. // expression. If the identifier is not found, it is then looked up in
  375. // the context of the entire postfix-expression and shall name a class
  376. // template.
  377. if (S)
  378. LookupName(Found, S);
  379. if (!ObjectType.isNull()) {
  380. // FIXME: We should filter out all non-type templates here, particularly
  381. // variable templates and concepts. But the exclusion of alias templates
  382. // and template template parameters is a wording defect.
  383. AllowFunctionTemplatesInLookup = false;
  384. ObjectTypeSearchedInScope = true;
  385. }
  386. IsDependent |= Found.wasNotFoundInCurrentInstantiation();
  387. }
  388. if (Found.isAmbiguous())
  389. return false;
  390. if (ATK && !SS.isSet() && ObjectType.isNull() && TemplateKWLoc.isInvalid()) {
  391. // C++2a [temp.names]p2:
  392. // A name is also considered to refer to a template if it is an
  393. // unqualified-id followed by a < and name lookup finds either one or more
  394. // functions or finds nothing.
  395. //
  396. // To keep our behavior consistent, we apply the "finds nothing" part in
  397. // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
  398. // successfully form a call to an undeclared template-id.
  399. bool AllFunctions =
  400. getLangOpts().CPlusPlus2a &&
  401. std::all_of(Found.begin(), Found.end(), [](NamedDecl *ND) {
  402. return isa<FunctionDecl>(ND->getUnderlyingDecl());
  403. });
  404. if (AllFunctions || (Found.empty() && !IsDependent)) {
  405. // If lookup found any functions, or if this is a name that can only be
  406. // used for a function, then strongly assume this is a function
  407. // template-id.
  408. *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
  409. ? AssumedTemplateKind::FoundNothing
  410. : AssumedTemplateKind::FoundFunctions;
  411. Found.clear();
  412. return false;
  413. }
  414. }
  415. if (Found.empty() && !IsDependent) {
  416. // If we did not find any names, attempt to correct any typos.
  417. DeclarationName Name = Found.getLookupName();
  418. Found.clear();
  419. // Simple filter callback that, for keywords, only accepts the C++ *_cast
  420. DefaultFilterCCC FilterCCC{};
  421. FilterCCC.WantTypeSpecifiers = false;
  422. FilterCCC.WantExpressionKeywords = false;
  423. FilterCCC.WantRemainingKeywords = false;
  424. FilterCCC.WantCXXNamedCasts = true;
  425. if (TypoCorrection Corrected =
  426. CorrectTypo(Found.getLookupNameInfo(), Found.getLookupKind(), S,
  427. &SS, FilterCCC, CTK_ErrorRecovery, LookupCtx)) {
  428. if (auto *ND = Corrected.getFoundDecl())
  429. Found.addDecl(ND);
  430. FilterAcceptableTemplateNames(Found);
  431. if (Found.isAmbiguous()) {
  432. Found.clear();
  433. } else if (!Found.empty()) {
  434. Found.setLookupName(Corrected.getCorrection());
  435. if (LookupCtx) {
  436. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  437. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  438. Name.getAsString() == CorrectedStr;
  439. diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
  440. << Name << LookupCtx << DroppedSpecifier
  441. << SS.getRange());
  442. } else {
  443. diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
  444. }
  445. }
  446. }
  447. }
  448. NamedDecl *ExampleLookupResult =
  449. Found.empty() ? nullptr : Found.getRepresentativeDecl();
  450. FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
  451. if (Found.empty()) {
  452. if (IsDependent) {
  453. MemberOfUnknownSpecialization = true;
  454. return false;
  455. }
  456. // If a 'template' keyword was used, a lookup that finds only non-template
  457. // names is an error.
  458. if (ExampleLookupResult && TemplateKWLoc.isValid()) {
  459. Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
  460. << Found.getLookupName() << SS.getRange();
  461. Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
  462. diag::note_template_kw_refers_to_non_template)
  463. << Found.getLookupName();
  464. return true;
  465. }
  466. return false;
  467. }
  468. if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
  469. !getLangOpts().CPlusPlus11) {
  470. // C++03 [basic.lookup.classref]p1:
  471. // [...] If the lookup in the class of the object expression finds a
  472. // template, the name is also looked up in the context of the entire
  473. // postfix-expression and [...]
  474. //
  475. // Note: C++11 does not perform this second lookup.
  476. LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
  477. LookupOrdinaryName);
  478. FoundOuter.setTemplateNameLookup(true);
  479. LookupName(FoundOuter, S);
  480. // FIXME: We silently accept an ambiguous lookup here, in violation of
  481. // [basic.lookup]/1.
  482. FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
  483. NamedDecl *OuterTemplate;
  484. if (FoundOuter.empty()) {
  485. // - if the name is not found, the name found in the class of the
  486. // object expression is used, otherwise
  487. } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
  488. !(OuterTemplate =
  489. getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) {
  490. // - if the name is found in the context of the entire
  491. // postfix-expression and does not name a class template, the name
  492. // found in the class of the object expression is used, otherwise
  493. FoundOuter.clear();
  494. } else if (!Found.isSuppressingDiagnostics()) {
  495. // - if the name found is a class template, it must refer to the same
  496. // entity as the one found in the class of the object expression,
  497. // otherwise the program is ill-formed.
  498. if (!Found.isSingleResult() ||
  499. getAsTemplateNameDecl(Found.getFoundDecl())->getCanonicalDecl() !=
  500. OuterTemplate->getCanonicalDecl()) {
  501. Diag(Found.getNameLoc(),
  502. diag::ext_nested_name_member_ref_lookup_ambiguous)
  503. << Found.getLookupName()
  504. << ObjectType;
  505. Diag(Found.getRepresentativeDecl()->getLocation(),
  506. diag::note_ambig_member_ref_object_type)
  507. << ObjectType;
  508. Diag(FoundOuter.getFoundDecl()->getLocation(),
  509. diag::note_ambig_member_ref_scope);
  510. // Recover by taking the template that we found in the object
  511. // expression's type.
  512. }
  513. }
  514. }
  515. return false;
  516. }
  517. void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
  518. SourceLocation Less,
  519. SourceLocation Greater) {
  520. if (TemplateName.isInvalid())
  521. return;
  522. DeclarationNameInfo NameInfo;
  523. CXXScopeSpec SS;
  524. LookupNameKind LookupKind;
  525. DeclContext *LookupCtx = nullptr;
  526. NamedDecl *Found = nullptr;
  527. bool MissingTemplateKeyword = false;
  528. // Figure out what name we looked up.
  529. if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {
  530. NameInfo = DRE->getNameInfo();
  531. SS.Adopt(DRE->getQualifierLoc());
  532. LookupKind = LookupOrdinaryName;
  533. Found = DRE->getFoundDecl();
  534. } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
  535. NameInfo = ME->getMemberNameInfo();
  536. SS.Adopt(ME->getQualifierLoc());
  537. LookupKind = LookupMemberName;
  538. LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
  539. Found = ME->getMemberDecl();
  540. } else if (auto *DSDRE =
  541. dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
  542. NameInfo = DSDRE->getNameInfo();
  543. SS.Adopt(DSDRE->getQualifierLoc());
  544. MissingTemplateKeyword = true;
  545. } else if (auto *DSME =
  546. dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
  547. NameInfo = DSME->getMemberNameInfo();
  548. SS.Adopt(DSME->getQualifierLoc());
  549. MissingTemplateKeyword = true;
  550. } else {
  551. llvm_unreachable("unexpected kind of potential template name");
  552. }
  553. // If this is a dependent-scope lookup, diagnose that the 'template' keyword
  554. // was missing.
  555. if (MissingTemplateKeyword) {
  556. Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)
  557. << "" << NameInfo.getName().getAsString() << SourceRange(Less, Greater);
  558. return;
  559. }
  560. // Try to correct the name by looking for templates and C++ named casts.
  561. struct TemplateCandidateFilter : CorrectionCandidateCallback {
  562. Sema &S;
  563. TemplateCandidateFilter(Sema &S) : S(S) {
  564. WantTypeSpecifiers = false;
  565. WantExpressionKeywords = false;
  566. WantRemainingKeywords = false;
  567. WantCXXNamedCasts = true;
  568. };
  569. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  570. if (auto *ND = Candidate.getCorrectionDecl())
  571. return S.getAsTemplateNameDecl(ND);
  572. return Candidate.isKeyword();
  573. }
  574. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  575. return std::make_unique<TemplateCandidateFilter>(*this);
  576. }
  577. };
  578. DeclarationName Name = NameInfo.getName();
  579. TemplateCandidateFilter CCC(*this);
  580. if (TypoCorrection Corrected = CorrectTypo(NameInfo, LookupKind, S, &SS, CCC,
  581. CTK_ErrorRecovery, LookupCtx)) {
  582. auto *ND = Corrected.getFoundDecl();
  583. if (ND)
  584. ND = getAsTemplateNameDecl(ND);
  585. if (ND || Corrected.isKeyword()) {
  586. if (LookupCtx) {
  587. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  588. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  589. Name.getAsString() == CorrectedStr;
  590. diagnoseTypo(Corrected,
  591. PDiag(diag::err_non_template_in_member_template_id_suggest)
  592. << Name << LookupCtx << DroppedSpecifier
  593. << SS.getRange(), false);
  594. } else {
  595. diagnoseTypo(Corrected,
  596. PDiag(diag::err_non_template_in_template_id_suggest)
  597. << Name, false);
  598. }
  599. if (Found)
  600. Diag(Found->getLocation(),
  601. diag::note_non_template_in_template_id_found);
  602. return;
  603. }
  604. }
  605. Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
  606. << Name << SourceRange(Less, Greater);
  607. if (Found)
  608. Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
  609. }
  610. /// ActOnDependentIdExpression - Handle a dependent id-expression that
  611. /// was just parsed. This is only possible with an explicit scope
  612. /// specifier naming a dependent type.
  613. ExprResult
  614. Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
  615. SourceLocation TemplateKWLoc,
  616. const DeclarationNameInfo &NameInfo,
  617. bool isAddressOfOperand,
  618. const TemplateArgumentListInfo *TemplateArgs) {
  619. DeclContext *DC = getFunctionLevelDeclContext();
  620. // C++11 [expr.prim.general]p12:
  621. // An id-expression that denotes a non-static data member or non-static
  622. // member function of a class can only be used:
  623. // (...)
  624. // - if that id-expression denotes a non-static data member and it
  625. // appears in an unevaluated operand.
  626. //
  627. // If this might be the case, form a DependentScopeDeclRefExpr instead of a
  628. // CXXDependentScopeMemberExpr. The former can instantiate to either
  629. // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
  630. // always a MemberExpr.
  631. bool MightBeCxx11UnevalField =
  632. getLangOpts().CPlusPlus11 && isUnevaluatedContext();
  633. // Check if the nested name specifier is an enum type.
  634. bool IsEnum = false;
  635. if (NestedNameSpecifier *NNS = SS.getScopeRep())
  636. IsEnum = dyn_cast_or_null<EnumType>(NNS->getAsType());
  637. if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum &&
  638. isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) {
  639. QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType();
  640. // Since the 'this' expression is synthesized, we don't need to
  641. // perform the double-lookup check.
  642. NamedDecl *FirstQualifierInScope = nullptr;
  643. return CXXDependentScopeMemberExpr::Create(
  644. Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
  645. /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
  646. FirstQualifierInScope, NameInfo, TemplateArgs);
  647. }
  648. return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
  649. }
  650. ExprResult
  651. Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
  652. SourceLocation TemplateKWLoc,
  653. const DeclarationNameInfo &NameInfo,
  654. const TemplateArgumentListInfo *TemplateArgs) {
  655. return DependentScopeDeclRefExpr::Create(
  656. Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
  657. TemplateArgs);
  658. }
  659. /// Determine whether we would be unable to instantiate this template (because
  660. /// it either has no definition, or is in the process of being instantiated).
  661. bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
  662. NamedDecl *Instantiation,
  663. bool InstantiatedFromMember,
  664. const NamedDecl *Pattern,
  665. const NamedDecl *PatternDef,
  666. TemplateSpecializationKind TSK,
  667. bool Complain /*= true*/) {
  668. assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
  669. isa<VarDecl>(Instantiation));
  670. bool IsEntityBeingDefined = false;
  671. if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
  672. IsEntityBeingDefined = TD->isBeingDefined();
  673. if (PatternDef && !IsEntityBeingDefined) {
  674. NamedDecl *SuggestedDef = nullptr;
  675. if (!hasVisibleDefinition(const_cast<NamedDecl*>(PatternDef), &SuggestedDef,
  676. /*OnlyNeedComplete*/false)) {
  677. // If we're allowed to diagnose this and recover, do so.
  678. bool Recover = Complain && !isSFINAEContext();
  679. if (Complain)
  680. diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
  681. Sema::MissingImportKind::Definition, Recover);
  682. return !Recover;
  683. }
  684. return false;
  685. }
  686. if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
  687. return true;
  688. llvm::Optional<unsigned> Note;
  689. QualType InstantiationTy;
  690. if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
  691. InstantiationTy = Context.getTypeDeclType(TD);
  692. if (PatternDef) {
  693. Diag(PointOfInstantiation,
  694. diag::err_template_instantiate_within_definition)
  695. << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
  696. << InstantiationTy;
  697. // Not much point in noting the template declaration here, since
  698. // we're lexically inside it.
  699. Instantiation->setInvalidDecl();
  700. } else if (InstantiatedFromMember) {
  701. if (isa<FunctionDecl>(Instantiation)) {
  702. Diag(PointOfInstantiation,
  703. diag::err_explicit_instantiation_undefined_member)
  704. << /*member function*/ 1 << Instantiation->getDeclName()
  705. << Instantiation->getDeclContext();
  706. Note = diag::note_explicit_instantiation_here;
  707. } else {
  708. assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
  709. Diag(PointOfInstantiation,
  710. diag::err_implicit_instantiate_member_undefined)
  711. << InstantiationTy;
  712. Note = diag::note_member_declared_at;
  713. }
  714. } else {
  715. if (isa<FunctionDecl>(Instantiation)) {
  716. Diag(PointOfInstantiation,
  717. diag::err_explicit_instantiation_undefined_func_template)
  718. << Pattern;
  719. Note = diag::note_explicit_instantiation_here;
  720. } else if (isa<TagDecl>(Instantiation)) {
  721. Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
  722. << (TSK != TSK_ImplicitInstantiation)
  723. << InstantiationTy;
  724. Note = diag::note_template_decl_here;
  725. } else {
  726. assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
  727. if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
  728. Diag(PointOfInstantiation,
  729. diag::err_explicit_instantiation_undefined_var_template)
  730. << Instantiation;
  731. Instantiation->setInvalidDecl();
  732. } else
  733. Diag(PointOfInstantiation,
  734. diag::err_explicit_instantiation_undefined_member)
  735. << /*static data member*/ 2 << Instantiation->getDeclName()
  736. << Instantiation->getDeclContext();
  737. Note = diag::note_explicit_instantiation_here;
  738. }
  739. }
  740. if (Note) // Diagnostics were emitted.
  741. Diag(Pattern->getLocation(), Note.getValue());
  742. // In general, Instantiation isn't marked invalid to get more than one
  743. // error for multiple undefined instantiations. But the code that does
  744. // explicit declaration -> explicit definition conversion can't handle
  745. // invalid declarations, so mark as invalid in that case.
  746. if (TSK == TSK_ExplicitInstantiationDeclaration)
  747. Instantiation->setInvalidDecl();
  748. return true;
  749. }
  750. /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
  751. /// that the template parameter 'PrevDecl' is being shadowed by a new
  752. /// declaration at location Loc. Returns true to indicate that this is
  753. /// an error, and false otherwise.
  754. void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
  755. assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
  756. // Microsoft Visual C++ permits template parameters to be shadowed.
  757. if (getLangOpts().MicrosoftExt)
  758. return;
  759. // C++ [temp.local]p4:
  760. // A template-parameter shall not be redeclared within its
  761. // scope (including nested scopes).
  762. Diag(Loc, diag::err_template_param_shadow)
  763. << cast<NamedDecl>(PrevDecl)->getDeclName();
  764. Diag(PrevDecl->getLocation(), diag::note_template_param_here);
  765. }
  766. /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
  767. /// the parameter D to reference the templated declaration and return a pointer
  768. /// to the template declaration. Otherwise, do nothing to D and return null.
  769. TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
  770. if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
  771. D = Temp->getTemplatedDecl();
  772. return Temp;
  773. }
  774. return nullptr;
  775. }
  776. ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
  777. SourceLocation EllipsisLoc) const {
  778. assert(Kind == Template &&
  779. "Only template template arguments can be pack expansions here");
  780. assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
  781. "Template template argument pack expansion without packs");
  782. ParsedTemplateArgument Result(*this);
  783. Result.EllipsisLoc = EllipsisLoc;
  784. return Result;
  785. }
  786. static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
  787. const ParsedTemplateArgument &Arg) {
  788. switch (Arg.getKind()) {
  789. case ParsedTemplateArgument::Type: {
  790. TypeSourceInfo *DI;
  791. QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
  792. if (!DI)
  793. DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
  794. return TemplateArgumentLoc(TemplateArgument(T), DI);
  795. }
  796. case ParsedTemplateArgument::NonType: {
  797. Expr *E = static_cast<Expr *>(Arg.getAsExpr());
  798. return TemplateArgumentLoc(TemplateArgument(E), E);
  799. }
  800. case ParsedTemplateArgument::Template: {
  801. TemplateName Template = Arg.getAsTemplate().get();
  802. TemplateArgument TArg;
  803. if (Arg.getEllipsisLoc().isValid())
  804. TArg = TemplateArgument(Template, Optional<unsigned int>());
  805. else
  806. TArg = Template;
  807. return TemplateArgumentLoc(TArg,
  808. Arg.getScopeSpec().getWithLocInContext(
  809. SemaRef.Context),
  810. Arg.getLocation(),
  811. Arg.getEllipsisLoc());
  812. }
  813. }
  814. llvm_unreachable("Unhandled parsed template argument");
  815. }
  816. /// Translates template arguments as provided by the parser
  817. /// into template arguments used by semantic analysis.
  818. void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
  819. TemplateArgumentListInfo &TemplateArgs) {
  820. for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
  821. TemplateArgs.addArgument(translateTemplateArgument(*this,
  822. TemplateArgsIn[I]));
  823. }
  824. static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
  825. SourceLocation Loc,
  826. IdentifierInfo *Name) {
  827. NamedDecl *PrevDecl = SemaRef.LookupSingleName(
  828. S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
  829. if (PrevDecl && PrevDecl->isTemplateParameter())
  830. SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
  831. }
  832. /// Convert a parsed type into a parsed template argument. This is mostly
  833. /// trivial, except that we may have parsed a C++17 deduced class template
  834. /// specialization type, in which case we should form a template template
  835. /// argument instead of a type template argument.
  836. ParsedTemplateArgument Sema::ActOnTemplateTypeArgument(TypeResult ParsedType) {
  837. TypeSourceInfo *TInfo;
  838. QualType T = GetTypeFromParser(ParsedType.get(), &TInfo);
  839. if (T.isNull())
  840. return ParsedTemplateArgument();
  841. assert(TInfo && "template argument with no location");
  842. // If we might have formed a deduced template specialization type, convert
  843. // it to a template template argument.
  844. if (getLangOpts().CPlusPlus17) {
  845. TypeLoc TL = TInfo->getTypeLoc();
  846. SourceLocation EllipsisLoc;
  847. if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
  848. EllipsisLoc = PET.getEllipsisLoc();
  849. TL = PET.getPatternLoc();
  850. }
  851. CXXScopeSpec SS;
  852. if (auto ET = TL.getAs<ElaboratedTypeLoc>()) {
  853. SS.Adopt(ET.getQualifierLoc());
  854. TL = ET.getNamedTypeLoc();
  855. }
  856. if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
  857. TemplateName Name = DTST.getTypePtr()->getTemplateName();
  858. if (SS.isSet())
  859. Name = Context.getQualifiedTemplateName(SS.getScopeRep(),
  860. /*HasTemplateKeyword*/ false,
  861. Name.getAsTemplateDecl());
  862. ParsedTemplateArgument Result(SS, TemplateTy::make(Name),
  863. DTST.getTemplateNameLoc());
  864. if (EllipsisLoc.isValid())
  865. Result = Result.getTemplatePackExpansion(EllipsisLoc);
  866. return Result;
  867. }
  868. }
  869. // This is a normal type template argument. Note, if the type template
  870. // argument is an injected-class-name for a template, it has a dual nature
  871. // and can be used as either a type or a template. We handle that in
  872. // convertTypeTemplateArgumentToTemplate.
  873. return ParsedTemplateArgument(ParsedTemplateArgument::Type,
  874. ParsedType.get().getAsOpaquePtr(),
  875. TInfo->getTypeLoc().getBeginLoc());
  876. }
  877. /// ActOnTypeParameter - Called when a C++ template type parameter
  878. /// (e.g., "typename T") has been parsed. Typename specifies whether
  879. /// the keyword "typename" was used to declare the type parameter
  880. /// (otherwise, "class" was used), and KeyLoc is the location of the
  881. /// "class" or "typename" keyword. ParamName is the name of the
  882. /// parameter (NULL indicates an unnamed template parameter) and
  883. /// ParamNameLoc is the location of the parameter name (if any).
  884. /// If the type parameter has a default argument, it will be added
  885. /// later via ActOnTypeParameterDefault.
  886. NamedDecl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
  887. SourceLocation EllipsisLoc,
  888. SourceLocation KeyLoc,
  889. IdentifierInfo *ParamName,
  890. SourceLocation ParamNameLoc,
  891. unsigned Depth, unsigned Position,
  892. SourceLocation EqualLoc,
  893. ParsedType DefaultArg) {
  894. assert(S->isTemplateParamScope() &&
  895. "Template type parameter not in template parameter scope!");
  896. SourceLocation Loc = ParamNameLoc;
  897. if (!ParamName)
  898. Loc = KeyLoc;
  899. bool IsParameterPack = EllipsisLoc.isValid();
  900. TemplateTypeParmDecl *Param
  901. = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
  902. KeyLoc, Loc, Depth, Position, ParamName,
  903. Typename, IsParameterPack);
  904. Param->setAccess(AS_public);
  905. if (ParamName) {
  906. maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
  907. // Add the template parameter into the current scope.
  908. S->AddDecl(Param);
  909. IdResolver.AddDecl(Param);
  910. }
  911. // C++0x [temp.param]p9:
  912. // A default template-argument may be specified for any kind of
  913. // template-parameter that is not a template parameter pack.
  914. if (DefaultArg && IsParameterPack) {
  915. Diag(EqualLoc, diag::err_template_param_pack_default_arg);
  916. DefaultArg = nullptr;
  917. }
  918. // Handle the default argument, if provided.
  919. if (DefaultArg) {
  920. TypeSourceInfo *DefaultTInfo;
  921. GetTypeFromParser(DefaultArg, &DefaultTInfo);
  922. assert(DefaultTInfo && "expected source information for type");
  923. // Check for unexpanded parameter packs.
  924. if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
  925. UPPC_DefaultArgument))
  926. return Param;
  927. // Check the template argument itself.
  928. if (CheckTemplateArgument(Param, DefaultTInfo)) {
  929. Param->setInvalidDecl();
  930. return Param;
  931. }
  932. Param->setDefaultArgument(DefaultTInfo);
  933. }
  934. return Param;
  935. }
  936. /// Check that the type of a non-type template parameter is
  937. /// well-formed.
  938. ///
  939. /// \returns the (possibly-promoted) parameter type if valid;
  940. /// otherwise, produces a diagnostic and returns a NULL type.
  941. QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
  942. SourceLocation Loc) {
  943. if (TSI->getType()->isUndeducedType()) {
  944. // C++17 [temp.dep.expr]p3:
  945. // An id-expression is type-dependent if it contains
  946. // - an identifier associated by name lookup with a non-type
  947. // template-parameter declared with a type that contains a
  948. // placeholder type (7.1.7.4),
  949. TSI = SubstAutoTypeSourceInfo(TSI, Context.DependentTy);
  950. }
  951. return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
  952. }
  953. QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
  954. SourceLocation Loc) {
  955. // We don't allow variably-modified types as the type of non-type template
  956. // parameters.
  957. if (T->isVariablyModifiedType()) {
  958. Diag(Loc, diag::err_variably_modified_nontype_template_param)
  959. << T;
  960. return QualType();
  961. }
  962. // C++ [temp.param]p4:
  963. //
  964. // A non-type template-parameter shall have one of the following
  965. // (optionally cv-qualified) types:
  966. //
  967. // -- integral or enumeration type,
  968. if (T->isIntegralOrEnumerationType() ||
  969. // -- pointer to object or pointer to function,
  970. T->isPointerType() ||
  971. // -- reference to object or reference to function,
  972. T->isReferenceType() ||
  973. // -- pointer to member,
  974. T->isMemberPointerType() ||
  975. // -- std::nullptr_t.
  976. T->isNullPtrType() ||
  977. // If T is a dependent type, we can't do the check now, so we
  978. // assume that it is well-formed.
  979. T->isDependentType() ||
  980. // Allow use of auto in template parameter declarations.
  981. T->isUndeducedType()) {
  982. // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
  983. // are ignored when determining its type.
  984. return T.getUnqualifiedType();
  985. }
  986. // C++ [temp.param]p8:
  987. //
  988. // A non-type template-parameter of type "array of T" or
  989. // "function returning T" is adjusted to be of type "pointer to
  990. // T" or "pointer to function returning T", respectively.
  991. else if (T->isArrayType() || T->isFunctionType())
  992. return Context.getDecayedType(T);
  993. Diag(Loc, diag::err_template_nontype_parm_bad_type)
  994. << T;
  995. return QualType();
  996. }
  997. NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
  998. unsigned Depth,
  999. unsigned Position,
  1000. SourceLocation EqualLoc,
  1001. Expr *Default) {
  1002. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  1003. // Check that we have valid decl-specifiers specified.
  1004. auto CheckValidDeclSpecifiers = [this, &D] {
  1005. // C++ [temp.param]
  1006. // p1
  1007. // template-parameter:
  1008. // ...
  1009. // parameter-declaration
  1010. // p2
  1011. // ... A storage class shall not be specified in a template-parameter
  1012. // declaration.
  1013. // [dcl.typedef]p1:
  1014. // The typedef specifier [...] shall not be used in the decl-specifier-seq
  1015. // of a parameter-declaration
  1016. const DeclSpec &DS = D.getDeclSpec();
  1017. auto EmitDiag = [this](SourceLocation Loc) {
  1018. Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
  1019. << FixItHint::CreateRemoval(Loc);
  1020. };
  1021. if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified)
  1022. EmitDiag(DS.getStorageClassSpecLoc());
  1023. if (DS.getThreadStorageClassSpec() != TSCS_unspecified)
  1024. EmitDiag(DS.getThreadStorageClassSpecLoc());
  1025. // [dcl.inline]p1:
  1026. // The inline specifier can be applied only to the declaration or
  1027. // definition of a variable or function.
  1028. if (DS.isInlineSpecified())
  1029. EmitDiag(DS.getInlineSpecLoc());
  1030. // [dcl.constexpr]p1:
  1031. // The constexpr specifier shall be applied only to the definition of a
  1032. // variable or variable template or the declaration of a function or
  1033. // function template.
  1034. if (DS.hasConstexprSpecifier())
  1035. EmitDiag(DS.getConstexprSpecLoc());
  1036. // [dcl.fct.spec]p1:
  1037. // Function-specifiers can be used only in function declarations.
  1038. if (DS.isVirtualSpecified())
  1039. EmitDiag(DS.getVirtualSpecLoc());
  1040. if (DS.hasExplicitSpecifier())
  1041. EmitDiag(DS.getExplicitSpecLoc());
  1042. if (DS.isNoreturnSpecified())
  1043. EmitDiag(DS.getNoreturnSpecLoc());
  1044. };
  1045. CheckValidDeclSpecifiers();
  1046. if (TInfo->getType()->isUndeducedType()) {
  1047. Diag(D.getIdentifierLoc(),
  1048. diag::warn_cxx14_compat_template_nontype_parm_auto_type)
  1049. << QualType(TInfo->getType()->getContainedAutoType(), 0);
  1050. }
  1051. assert(S->isTemplateParamScope() &&
  1052. "Non-type template parameter not in template parameter scope!");
  1053. bool Invalid = false;
  1054. QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
  1055. if (T.isNull()) {
  1056. T = Context.IntTy; // Recover with an 'int' type.
  1057. Invalid = true;
  1058. }
  1059. CheckFunctionOrTemplateParamDeclarator(S, D);
  1060. IdentifierInfo *ParamName = D.getIdentifier();
  1061. bool IsParameterPack = D.hasEllipsis();
  1062. NonTypeTemplateParmDecl *Param = NonTypeTemplateParmDecl::Create(
  1063. Context, Context.getTranslationUnitDecl(), D.getBeginLoc(),
  1064. D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
  1065. TInfo);
  1066. Param->setAccess(AS_public);
  1067. if (Invalid)
  1068. Param->setInvalidDecl();
  1069. if (ParamName) {
  1070. maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
  1071. ParamName);
  1072. // Add the template parameter into the current scope.
  1073. S->AddDecl(Param);
  1074. IdResolver.AddDecl(Param);
  1075. }
  1076. // C++0x [temp.param]p9:
  1077. // A default template-argument may be specified for any kind of
  1078. // template-parameter that is not a template parameter pack.
  1079. if (Default && IsParameterPack) {
  1080. Diag(EqualLoc, diag::err_template_param_pack_default_arg);
  1081. Default = nullptr;
  1082. }
  1083. // Check the well-formedness of the default template argument, if provided.
  1084. if (Default) {
  1085. // Check for unexpanded parameter packs.
  1086. if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
  1087. return Param;
  1088. TemplateArgument Converted;
  1089. ExprResult DefaultRes =
  1090. CheckTemplateArgument(Param, Param->getType(), Default, Converted);
  1091. if (DefaultRes.isInvalid()) {
  1092. Param->setInvalidDecl();
  1093. return Param;
  1094. }
  1095. Default = DefaultRes.get();
  1096. Param->setDefaultArgument(Default);
  1097. }
  1098. return Param;
  1099. }
  1100. /// ActOnTemplateTemplateParameter - Called when a C++ template template
  1101. /// parameter (e.g. T in template <template \<typename> class T> class array)
  1102. /// has been parsed. S is the current scope.
  1103. NamedDecl *Sema::ActOnTemplateTemplateParameter(Scope* S,
  1104. SourceLocation TmpLoc,
  1105. TemplateParameterList *Params,
  1106. SourceLocation EllipsisLoc,
  1107. IdentifierInfo *Name,
  1108. SourceLocation NameLoc,
  1109. unsigned Depth,
  1110. unsigned Position,
  1111. SourceLocation EqualLoc,
  1112. ParsedTemplateArgument Default) {
  1113. assert(S->isTemplateParamScope() &&
  1114. "Template template parameter not in template parameter scope!");
  1115. // Construct the parameter object.
  1116. bool IsParameterPack = EllipsisLoc.isValid();
  1117. TemplateTemplateParmDecl *Param =
  1118. TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
  1119. NameLoc.isInvalid()? TmpLoc : NameLoc,
  1120. Depth, Position, IsParameterPack,
  1121. Name, Params);
  1122. Param->setAccess(AS_public);
  1123. // If the template template parameter has a name, then link the identifier
  1124. // into the scope and lookup mechanisms.
  1125. if (Name) {
  1126. maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
  1127. S->AddDecl(Param);
  1128. IdResolver.AddDecl(Param);
  1129. }
  1130. if (Params->size() == 0) {
  1131. Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
  1132. << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
  1133. Param->setInvalidDecl();
  1134. }
  1135. // C++0x [temp.param]p9:
  1136. // A default template-argument may be specified for any kind of
  1137. // template-parameter that is not a template parameter pack.
  1138. if (IsParameterPack && !Default.isInvalid()) {
  1139. Diag(EqualLoc, diag::err_template_param_pack_default_arg);
  1140. Default = ParsedTemplateArgument();
  1141. }
  1142. if (!Default.isInvalid()) {
  1143. // Check only that we have a template template argument. We don't want to
  1144. // try to check well-formedness now, because our template template parameter
  1145. // might have dependent types in its template parameters, which we wouldn't
  1146. // be able to match now.
  1147. //
  1148. // If none of the template template parameter's template arguments mention
  1149. // other template parameters, we could actually perform more checking here.
  1150. // However, it isn't worth doing.
  1151. TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
  1152. if (DefaultArg.getArgument().getAsTemplate().isNull()) {
  1153. Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
  1154. << DefaultArg.getSourceRange();
  1155. return Param;
  1156. }
  1157. // Check for unexpanded parameter packs.
  1158. if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
  1159. DefaultArg.getArgument().getAsTemplate(),
  1160. UPPC_DefaultArgument))
  1161. return Param;
  1162. Param->setDefaultArgument(Context, DefaultArg);
  1163. }
  1164. return Param;
  1165. }
  1166. /// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
  1167. /// constrained by RequiresClause, that contains the template parameters in
  1168. /// Params.
  1169. TemplateParameterList *
  1170. Sema::ActOnTemplateParameterList(unsigned Depth,
  1171. SourceLocation ExportLoc,
  1172. SourceLocation TemplateLoc,
  1173. SourceLocation LAngleLoc,
  1174. ArrayRef<NamedDecl *> Params,
  1175. SourceLocation RAngleLoc,
  1176. Expr *RequiresClause) {
  1177. if (ExportLoc.isValid())
  1178. Diag(ExportLoc, diag::warn_template_export_unsupported);
  1179. return TemplateParameterList::Create(
  1180. Context, TemplateLoc, LAngleLoc,
  1181. llvm::makeArrayRef(Params.data(), Params.size()),
  1182. RAngleLoc, RequiresClause);
  1183. }
  1184. static void SetNestedNameSpecifier(Sema &S, TagDecl *T,
  1185. const CXXScopeSpec &SS) {
  1186. if (SS.isSet())
  1187. T->setQualifierInfo(SS.getWithLocInContext(S.Context));
  1188. }
  1189. DeclResult Sema::CheckClassTemplate(
  1190. Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
  1191. CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
  1192. const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
  1193. AccessSpecifier AS, SourceLocation ModulePrivateLoc,
  1194. SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
  1195. TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
  1196. assert(TemplateParams && TemplateParams->size() > 0 &&
  1197. "No template parameters");
  1198. assert(TUK != TUK_Reference && "Can only declare or define class templates");
  1199. bool Invalid = false;
  1200. // Check that we can declare a template here.
  1201. if (CheckTemplateDeclScope(S, TemplateParams))
  1202. return true;
  1203. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  1204. assert(Kind != TTK_Enum && "can't build template of enumerated type");
  1205. // There is no such thing as an unnamed class template.
  1206. if (!Name) {
  1207. Diag(KWLoc, diag::err_template_unnamed_class);
  1208. return true;
  1209. }
  1210. // Find any previous declaration with this name. For a friend with no
  1211. // scope explicitly specified, we only look for tag declarations (per
  1212. // C++11 [basic.lookup.elab]p2).
  1213. DeclContext *SemanticContext;
  1214. LookupResult Previous(*this, Name, NameLoc,
  1215. (SS.isEmpty() && TUK == TUK_Friend)
  1216. ? LookupTagName : LookupOrdinaryName,
  1217. forRedeclarationInCurContext());
  1218. if (SS.isNotEmpty() && !SS.isInvalid()) {
  1219. SemanticContext = computeDeclContext(SS, true);
  1220. if (!SemanticContext) {
  1221. // FIXME: Horrible, horrible hack! We can't currently represent this
  1222. // in the AST, and historically we have just ignored such friend
  1223. // class templates, so don't complain here.
  1224. Diag(NameLoc, TUK == TUK_Friend
  1225. ? diag::warn_template_qualified_friend_ignored
  1226. : diag::err_template_qualified_declarator_no_match)
  1227. << SS.getScopeRep() << SS.getRange();
  1228. return TUK != TUK_Friend;
  1229. }
  1230. if (RequireCompleteDeclContext(SS, SemanticContext))
  1231. return true;
  1232. // If we're adding a template to a dependent context, we may need to
  1233. // rebuilding some of the types used within the template parameter list,
  1234. // now that we know what the current instantiation is.
  1235. if (SemanticContext->isDependentContext()) {
  1236. ContextRAII SavedContext(*this, SemanticContext);
  1237. if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
  1238. Invalid = true;
  1239. } else if (TUK != TUK_Friend && TUK != TUK_Reference)
  1240. diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc, false);
  1241. LookupQualifiedName(Previous, SemanticContext);
  1242. } else {
  1243. SemanticContext = CurContext;
  1244. // C++14 [class.mem]p14:
  1245. // If T is the name of a class, then each of the following shall have a
  1246. // name different from T:
  1247. // -- every member template of class T
  1248. if (TUK != TUK_Friend &&
  1249. DiagnoseClassNameShadow(SemanticContext,
  1250. DeclarationNameInfo(Name, NameLoc)))
  1251. return true;
  1252. LookupName(Previous, S);
  1253. }
  1254. if (Previous.isAmbiguous())
  1255. return true;
  1256. NamedDecl *PrevDecl = nullptr;
  1257. if (Previous.begin() != Previous.end())
  1258. PrevDecl = (*Previous.begin())->getUnderlyingDecl();
  1259. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  1260. // Maybe we will complain about the shadowed template parameter.
  1261. DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
  1262. // Just pretend that we didn't see the previous declaration.
  1263. PrevDecl = nullptr;
  1264. }
  1265. // If there is a previous declaration with the same name, check
  1266. // whether this is a valid redeclaration.
  1267. ClassTemplateDecl *PrevClassTemplate =
  1268. dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
  1269. // We may have found the injected-class-name of a class template,
  1270. // class template partial specialization, or class template specialization.
  1271. // In these cases, grab the template that is being defined or specialized.
  1272. if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
  1273. cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
  1274. PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
  1275. PrevClassTemplate
  1276. = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
  1277. if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
  1278. PrevClassTemplate
  1279. = cast<ClassTemplateSpecializationDecl>(PrevDecl)
  1280. ->getSpecializedTemplate();
  1281. }
  1282. }
  1283. if (TUK == TUK_Friend) {
  1284. // C++ [namespace.memdef]p3:
  1285. // [...] When looking for a prior declaration of a class or a function
  1286. // declared as a friend, and when the name of the friend class or
  1287. // function is neither a qualified name nor a template-id, scopes outside
  1288. // the innermost enclosing namespace scope are not considered.
  1289. if (!SS.isSet()) {
  1290. DeclContext *OutermostContext = CurContext;
  1291. while (!OutermostContext->isFileContext())
  1292. OutermostContext = OutermostContext->getLookupParent();
  1293. if (PrevDecl &&
  1294. (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
  1295. OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
  1296. SemanticContext = PrevDecl->getDeclContext();
  1297. } else {
  1298. // Declarations in outer scopes don't matter. However, the outermost
  1299. // context we computed is the semantic context for our new
  1300. // declaration.
  1301. PrevDecl = PrevClassTemplate = nullptr;
  1302. SemanticContext = OutermostContext;
  1303. // Check that the chosen semantic context doesn't already contain a
  1304. // declaration of this name as a non-tag type.
  1305. Previous.clear(LookupOrdinaryName);
  1306. DeclContext *LookupContext = SemanticContext;
  1307. while (LookupContext->isTransparentContext())
  1308. LookupContext = LookupContext->getLookupParent();
  1309. LookupQualifiedName(Previous, LookupContext);
  1310. if (Previous.isAmbiguous())
  1311. return true;
  1312. if (Previous.begin() != Previous.end())
  1313. PrevDecl = (*Previous.begin())->getUnderlyingDecl();
  1314. }
  1315. }
  1316. } else if (PrevDecl &&
  1317. !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
  1318. S, SS.isValid()))
  1319. PrevDecl = PrevClassTemplate = nullptr;
  1320. if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
  1321. PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
  1322. if (SS.isEmpty() &&
  1323. !(PrevClassTemplate &&
  1324. PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
  1325. SemanticContext->getRedeclContext()))) {
  1326. Diag(KWLoc, diag::err_using_decl_conflict_reverse);
  1327. Diag(Shadow->getTargetDecl()->getLocation(),
  1328. diag::note_using_decl_target);
  1329. Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
  1330. // Recover by ignoring the old declaration.
  1331. PrevDecl = PrevClassTemplate = nullptr;
  1332. }
  1333. }
  1334. // TODO Memory management; associated constraints are not always stored.
  1335. Expr *const CurAC = formAssociatedConstraints(TemplateParams, nullptr);
  1336. if (PrevClassTemplate) {
  1337. // Ensure that the template parameter lists are compatible. Skip this check
  1338. // for a friend in a dependent context: the template parameter list itself
  1339. // could be dependent.
  1340. if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
  1341. !TemplateParameterListsAreEqual(TemplateParams,
  1342. PrevClassTemplate->getTemplateParameters(),
  1343. /*Complain=*/true,
  1344. TPL_TemplateMatch))
  1345. return true;
  1346. // Check for matching associated constraints on redeclarations.
  1347. const Expr *const PrevAC = PrevClassTemplate->getAssociatedConstraints();
  1348. const bool RedeclACMismatch = [&] {
  1349. if (!(CurAC || PrevAC))
  1350. return false; // Nothing to check; no mismatch.
  1351. if (CurAC && PrevAC) {
  1352. llvm::FoldingSetNodeID CurACInfo, PrevACInfo;
  1353. CurAC->Profile(CurACInfo, Context, /*Canonical=*/true);
  1354. PrevAC->Profile(PrevACInfo, Context, /*Canonical=*/true);
  1355. if (CurACInfo == PrevACInfo)
  1356. return false; // All good; no mismatch.
  1357. }
  1358. return true;
  1359. }();
  1360. if (RedeclACMismatch) {
  1361. Diag(CurAC ? CurAC->getBeginLoc() : NameLoc,
  1362. diag::err_template_different_associated_constraints);
  1363. Diag(PrevAC ? PrevAC->getBeginLoc() : PrevClassTemplate->getLocation(),
  1364. diag::note_template_prev_declaration)
  1365. << /*declaration*/ 0;
  1366. return true;
  1367. }
  1368. // C++ [temp.class]p4:
  1369. // In a redeclaration, partial specialization, explicit
  1370. // specialization or explicit instantiation of a class template,
  1371. // the class-key shall agree in kind with the original class
  1372. // template declaration (7.1.5.3).
  1373. RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
  1374. if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
  1375. TUK == TUK_Definition, KWLoc, Name)) {
  1376. Diag(KWLoc, diag::err_use_with_wrong_tag)
  1377. << Name
  1378. << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
  1379. Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
  1380. Kind = PrevRecordDecl->getTagKind();
  1381. }
  1382. // Check for redefinition of this class template.
  1383. if (TUK == TUK_Definition) {
  1384. if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
  1385. // If we have a prior definition that is not visible, treat this as
  1386. // simply making that previous definition visible.
  1387. NamedDecl *Hidden = nullptr;
  1388. if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
  1389. SkipBody->ShouldSkip = true;
  1390. SkipBody->Previous = Def;
  1391. auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
  1392. assert(Tmpl && "original definition of a class template is not a "
  1393. "class template?");
  1394. makeMergedDefinitionVisible(Hidden);
  1395. makeMergedDefinitionVisible(Tmpl);
  1396. } else {
  1397. Diag(NameLoc, diag::err_redefinition) << Name;
  1398. Diag(Def->getLocation(), diag::note_previous_definition);
  1399. // FIXME: Would it make sense to try to "forget" the previous
  1400. // definition, as part of error recovery?
  1401. return true;
  1402. }
  1403. }
  1404. }
  1405. } else if (PrevDecl) {
  1406. // C++ [temp]p5:
  1407. // A class template shall not have the same name as any other
  1408. // template, class, function, object, enumeration, enumerator,
  1409. // namespace, or type in the same scope (3.3), except as specified
  1410. // in (14.5.4).
  1411. Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
  1412. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  1413. return true;
  1414. }
  1415. // Check the template parameter list of this declaration, possibly
  1416. // merging in the template parameter list from the previous class
  1417. // template declaration. Skip this check for a friend in a dependent
  1418. // context, because the template parameter list might be dependent.
  1419. if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
  1420. CheckTemplateParameterList(
  1421. TemplateParams,
  1422. PrevClassTemplate
  1423. ? PrevClassTemplate->getMostRecentDecl()->getTemplateParameters()
  1424. : nullptr,
  1425. (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
  1426. SemanticContext->isDependentContext())
  1427. ? TPC_ClassTemplateMember
  1428. : TUK == TUK_Friend ? TPC_FriendClassTemplate : TPC_ClassTemplate,
  1429. SkipBody))
  1430. Invalid = true;
  1431. if (SS.isSet()) {
  1432. // If the name of the template was qualified, we must be defining the
  1433. // template out-of-line.
  1434. if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
  1435. Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
  1436. : diag::err_member_decl_does_not_match)
  1437. << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
  1438. Invalid = true;
  1439. }
  1440. }
  1441. // If this is a templated friend in a dependent context we should not put it
  1442. // on the redecl chain. In some cases, the templated friend can be the most
  1443. // recent declaration tricking the template instantiator to make substitutions
  1444. // there.
  1445. // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
  1446. bool ShouldAddRedecl
  1447. = !(TUK == TUK_Friend && CurContext->isDependentContext());
  1448. CXXRecordDecl *NewClass =
  1449. CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
  1450. PrevClassTemplate && ShouldAddRedecl ?
  1451. PrevClassTemplate->getTemplatedDecl() : nullptr,
  1452. /*DelayTypeCreation=*/true);
  1453. SetNestedNameSpecifier(*this, NewClass, SS);
  1454. if (NumOuterTemplateParamLists > 0)
  1455. NewClass->setTemplateParameterListsInfo(
  1456. Context, llvm::makeArrayRef(OuterTemplateParamLists,
  1457. NumOuterTemplateParamLists));
  1458. // Add alignment attributes if necessary; these attributes are checked when
  1459. // the ASTContext lays out the structure.
  1460. if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
  1461. AddAlignmentAttributesForRecord(NewClass);
  1462. AddMsStructLayoutForRecord(NewClass);
  1463. }
  1464. // Attach the associated constraints when the declaration will not be part of
  1465. // a decl chain.
  1466. Expr *const ACtoAttach =
  1467. PrevClassTemplate && ShouldAddRedecl ? nullptr : CurAC;
  1468. ClassTemplateDecl *NewTemplate
  1469. = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
  1470. DeclarationName(Name), TemplateParams,
  1471. NewClass, ACtoAttach);
  1472. if (ShouldAddRedecl)
  1473. NewTemplate->setPreviousDecl(PrevClassTemplate);
  1474. NewClass->setDescribedClassTemplate(NewTemplate);
  1475. if (ModulePrivateLoc.isValid())
  1476. NewTemplate->setModulePrivate();
  1477. // Build the type for the class template declaration now.
  1478. QualType T = NewTemplate->getInjectedClassNameSpecialization();
  1479. T = Context.getInjectedClassNameType(NewClass, T);
  1480. assert(T->isDependentType() && "Class template type is not dependent?");
  1481. (void)T;
  1482. // If we are providing an explicit specialization of a member that is a
  1483. // class template, make a note of that.
  1484. if (PrevClassTemplate &&
  1485. PrevClassTemplate->getInstantiatedFromMemberTemplate())
  1486. PrevClassTemplate->setMemberSpecialization();
  1487. // Set the access specifier.
  1488. if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
  1489. SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
  1490. // Set the lexical context of these templates
  1491. NewClass->setLexicalDeclContext(CurContext);
  1492. NewTemplate->setLexicalDeclContext(CurContext);
  1493. if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
  1494. NewClass->startDefinition();
  1495. ProcessDeclAttributeList(S, NewClass, Attr);
  1496. if (PrevClassTemplate)
  1497. mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
  1498. AddPushedVisibilityAttribute(NewClass);
  1499. inferGslOwnerPointerAttribute(NewClass);
  1500. if (TUK != TUK_Friend) {
  1501. // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
  1502. Scope *Outer = S;
  1503. while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
  1504. Outer = Outer->getParent();
  1505. PushOnScopeChains(NewTemplate, Outer);
  1506. } else {
  1507. if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
  1508. NewTemplate->setAccess(PrevClassTemplate->getAccess());
  1509. NewClass->setAccess(PrevClassTemplate->getAccess());
  1510. }
  1511. NewTemplate->setObjectOfFriendDecl();
  1512. // Friend templates are visible in fairly strange ways.
  1513. if (!CurContext->isDependentContext()) {
  1514. DeclContext *DC = SemanticContext->getRedeclContext();
  1515. DC->makeDeclVisibleInContext(NewTemplate);
  1516. if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
  1517. PushOnScopeChains(NewTemplate, EnclosingScope,
  1518. /* AddToContext = */ false);
  1519. }
  1520. FriendDecl *Friend = FriendDecl::Create(
  1521. Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
  1522. Friend->setAccess(AS_public);
  1523. CurContext->addDecl(Friend);
  1524. }
  1525. if (PrevClassTemplate)
  1526. CheckRedeclarationModuleOwnership(NewTemplate, PrevClassTemplate);
  1527. if (Invalid) {
  1528. NewTemplate->setInvalidDecl();
  1529. NewClass->setInvalidDecl();
  1530. }
  1531. ActOnDocumentableDecl(NewTemplate);
  1532. if (SkipBody && SkipBody->ShouldSkip)
  1533. return SkipBody->Previous;
  1534. return NewTemplate;
  1535. }
  1536. namespace {
  1537. /// Tree transform to "extract" a transformed type from a class template's
  1538. /// constructor to a deduction guide.
  1539. class ExtractTypeForDeductionGuide
  1540. : public TreeTransform<ExtractTypeForDeductionGuide> {
  1541. public:
  1542. typedef TreeTransform<ExtractTypeForDeductionGuide> Base;
  1543. ExtractTypeForDeductionGuide(Sema &SemaRef) : Base(SemaRef) {}
  1544. TypeSourceInfo *transform(TypeSourceInfo *TSI) { return TransformType(TSI); }
  1545. QualType TransformTypedefType(TypeLocBuilder &TLB, TypedefTypeLoc TL) {
  1546. return TransformType(
  1547. TLB,
  1548. TL.getTypedefNameDecl()->getTypeSourceInfo()->getTypeLoc());
  1549. }
  1550. };
  1551. /// Transform to convert portions of a constructor declaration into the
  1552. /// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
  1553. struct ConvertConstructorToDeductionGuideTransform {
  1554. ConvertConstructorToDeductionGuideTransform(Sema &S,
  1555. ClassTemplateDecl *Template)
  1556. : SemaRef(S), Template(Template) {}
  1557. Sema &SemaRef;
  1558. ClassTemplateDecl *Template;
  1559. DeclContext *DC = Template->getDeclContext();
  1560. CXXRecordDecl *Primary = Template->getTemplatedDecl();
  1561. DeclarationName DeductionGuideName =
  1562. SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(Template);
  1563. QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary);
  1564. // Index adjustment to apply to convert depth-1 template parameters into
  1565. // depth-0 template parameters.
  1566. unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size();
  1567. /// Transform a constructor declaration into a deduction guide.
  1568. NamedDecl *transformConstructor(FunctionTemplateDecl *FTD,
  1569. CXXConstructorDecl *CD) {
  1570. SmallVector<TemplateArgument, 16> SubstArgs;
  1571. LocalInstantiationScope Scope(SemaRef);
  1572. // C++ [over.match.class.deduct]p1:
  1573. // -- For each constructor of the class template designated by the
  1574. // template-name, a function template with the following properties:
  1575. // -- The template parameters are the template parameters of the class
  1576. // template followed by the template parameters (including default
  1577. // template arguments) of the constructor, if any.
  1578. TemplateParameterList *TemplateParams = Template->getTemplateParameters();
  1579. if (FTD) {
  1580. TemplateParameterList *InnerParams = FTD->getTemplateParameters();
  1581. SmallVector<NamedDecl *, 16> AllParams;
  1582. AllParams.reserve(TemplateParams->size() + InnerParams->size());
  1583. AllParams.insert(AllParams.begin(),
  1584. TemplateParams->begin(), TemplateParams->end());
  1585. SubstArgs.reserve(InnerParams->size());
  1586. // Later template parameters could refer to earlier ones, so build up
  1587. // a list of substituted template arguments as we go.
  1588. for (NamedDecl *Param : *InnerParams) {
  1589. MultiLevelTemplateArgumentList Args;
  1590. Args.addOuterTemplateArguments(SubstArgs);
  1591. Args.addOuterRetainedLevel();
  1592. NamedDecl *NewParam = transformTemplateParameter(Param, Args);
  1593. if (!NewParam)
  1594. return nullptr;
  1595. AllParams.push_back(NewParam);
  1596. SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument(
  1597. SemaRef.Context.getInjectedTemplateArg(NewParam)));
  1598. }
  1599. TemplateParams = TemplateParameterList::Create(
  1600. SemaRef.Context, InnerParams->getTemplateLoc(),
  1601. InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
  1602. /*FIXME: RequiresClause*/ nullptr);
  1603. }
  1604. // If we built a new template-parameter-list, track that we need to
  1605. // substitute references to the old parameters into references to the
  1606. // new ones.
  1607. MultiLevelTemplateArgumentList Args;
  1608. if (FTD) {
  1609. Args.addOuterTemplateArguments(SubstArgs);
  1610. Args.addOuterRetainedLevel();
  1611. }
  1612. FunctionProtoTypeLoc FPTL = CD->getTypeSourceInfo()->getTypeLoc()
  1613. .getAsAdjusted<FunctionProtoTypeLoc>();
  1614. assert(FPTL && "no prototype for constructor declaration");
  1615. // Transform the type of the function, adjusting the return type and
  1616. // replacing references to the old parameters with references to the
  1617. // new ones.
  1618. TypeLocBuilder TLB;
  1619. SmallVector<ParmVarDecl*, 8> Params;
  1620. QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args);
  1621. if (NewType.isNull())
  1622. return nullptr;
  1623. TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
  1624. return buildDeductionGuide(TemplateParams, CD->getExplicitSpecifier(),
  1625. NewTInfo, CD->getBeginLoc(), CD->getLocation(),
  1626. CD->getEndLoc());
  1627. }
  1628. /// Build a deduction guide with the specified parameter types.
  1629. NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
  1630. SourceLocation Loc = Template->getLocation();
  1631. // Build the requested type.
  1632. FunctionProtoType::ExtProtoInfo EPI;
  1633. EPI.HasTrailingReturn = true;
  1634. QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
  1635. DeductionGuideName, EPI);
  1636. TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
  1637. FunctionProtoTypeLoc FPTL =
  1638. TSI->getTypeLoc().castAs<FunctionProtoTypeLoc>();
  1639. // Build the parameters, needed during deduction / substitution.
  1640. SmallVector<ParmVarDecl*, 4> Params;
  1641. for (auto T : ParamTypes) {
  1642. ParmVarDecl *NewParam = ParmVarDecl::Create(
  1643. SemaRef.Context, DC, Loc, Loc, nullptr, T,
  1644. SemaRef.Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr);
  1645. NewParam->setScopeInfo(0, Params.size());
  1646. FPTL.setParam(Params.size(), NewParam);
  1647. Params.push_back(NewParam);
  1648. }
  1649. return buildDeductionGuide(Template->getTemplateParameters(),
  1650. ExplicitSpecifier(), TSI, Loc, Loc, Loc);
  1651. }
  1652. private:
  1653. /// Transform a constructor template parameter into a deduction guide template
  1654. /// parameter, rebuilding any internal references to earlier parameters and
  1655. /// renumbering as we go.
  1656. NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam,
  1657. MultiLevelTemplateArgumentList &Args) {
  1658. if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam)) {
  1659. // TemplateTypeParmDecl's index cannot be changed after creation, so
  1660. // substitute it directly.
  1661. auto *NewTTP = TemplateTypeParmDecl::Create(
  1662. SemaRef.Context, DC, TTP->getBeginLoc(), TTP->getLocation(),
  1663. /*Depth*/ 0, Depth1IndexAdjustment + TTP->getIndex(),
  1664. TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
  1665. TTP->isParameterPack());
  1666. if (TTP->hasDefaultArgument()) {
  1667. TypeSourceInfo *InstantiatedDefaultArg =
  1668. SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args,
  1669. TTP->getDefaultArgumentLoc(), TTP->getDeclName());
  1670. if (InstantiatedDefaultArg)
  1671. NewTTP->setDefaultArgument(InstantiatedDefaultArg);
  1672. }
  1673. SemaRef.CurrentInstantiationScope->InstantiatedLocal(TemplateParam,
  1674. NewTTP);
  1675. return NewTTP;
  1676. }
  1677. if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
  1678. return transformTemplateParameterImpl(TTP, Args);
  1679. return transformTemplateParameterImpl(
  1680. cast<NonTypeTemplateParmDecl>(TemplateParam), Args);
  1681. }
  1682. template<typename TemplateParmDecl>
  1683. TemplateParmDecl *
  1684. transformTemplateParameterImpl(TemplateParmDecl *OldParam,
  1685. MultiLevelTemplateArgumentList &Args) {
  1686. // Ask the template instantiator to do the heavy lifting for us, then adjust
  1687. // the index of the parameter once it's done.
  1688. auto *NewParam =
  1689. cast_or_null<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args));
  1690. assert(NewParam->getDepth() == 0 && "unexpected template param depth");
  1691. NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment);
  1692. return NewParam;
  1693. }
  1694. QualType transformFunctionProtoType(TypeLocBuilder &TLB,
  1695. FunctionProtoTypeLoc TL,
  1696. SmallVectorImpl<ParmVarDecl*> &Params,
  1697. MultiLevelTemplateArgumentList &Args) {
  1698. SmallVector<QualType, 4> ParamTypes;
  1699. const FunctionProtoType *T = TL.getTypePtr();
  1700. // -- The types of the function parameters are those of the constructor.
  1701. for (auto *OldParam : TL.getParams()) {
  1702. ParmVarDecl *NewParam = transformFunctionTypeParam(OldParam, Args);
  1703. if (!NewParam)
  1704. return QualType();
  1705. ParamTypes.push_back(NewParam->getType());
  1706. Params.push_back(NewParam);
  1707. }
  1708. // -- The return type is the class template specialization designated by
  1709. // the template-name and template arguments corresponding to the
  1710. // template parameters obtained from the class template.
  1711. //
  1712. // We use the injected-class-name type of the primary template instead.
  1713. // This has the convenient property that it is different from any type that
  1714. // the user can write in a deduction-guide (because they cannot enter the
  1715. // context of the template), so implicit deduction guides can never collide
  1716. // with explicit ones.
  1717. QualType ReturnType = DeducedType;
  1718. TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation());
  1719. // Resolving a wording defect, we also inherit the variadicness of the
  1720. // constructor.
  1721. FunctionProtoType::ExtProtoInfo EPI;
  1722. EPI.Variadic = T->isVariadic();
  1723. EPI.HasTrailingReturn = true;
  1724. QualType Result = SemaRef.BuildFunctionType(
  1725. ReturnType, ParamTypes, TL.getBeginLoc(), DeductionGuideName, EPI);
  1726. if (Result.isNull())
  1727. return QualType();
  1728. FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
  1729. NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
  1730. NewTL.setLParenLoc(TL.getLParenLoc());
  1731. NewTL.setRParenLoc(TL.getRParenLoc());
  1732. NewTL.setExceptionSpecRange(SourceRange());
  1733. NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
  1734. for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I)
  1735. NewTL.setParam(I, Params[I]);
  1736. return Result;
  1737. }
  1738. ParmVarDecl *
  1739. transformFunctionTypeParam(ParmVarDecl *OldParam,
  1740. MultiLevelTemplateArgumentList &Args) {
  1741. TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
  1742. TypeSourceInfo *NewDI;
  1743. if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) {
  1744. // Expand out the one and only element in each inner pack.
  1745. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0);
  1746. NewDI =
  1747. SemaRef.SubstType(PackTL.getPatternLoc(), Args,
  1748. OldParam->getLocation(), OldParam->getDeclName());
  1749. if (!NewDI) return nullptr;
  1750. NewDI =
  1751. SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(),
  1752. PackTL.getTypePtr()->getNumExpansions());
  1753. } else
  1754. NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(),
  1755. OldParam->getDeclName());
  1756. if (!NewDI)
  1757. return nullptr;
  1758. // Extract the type. This (for instance) replaces references to typedef
  1759. // members of the current instantiations with the definitions of those
  1760. // typedefs, avoiding triggering instantiation of the deduced type during
  1761. // deduction.
  1762. NewDI = ExtractTypeForDeductionGuide(SemaRef).transform(NewDI);
  1763. // Resolving a wording defect, we also inherit default arguments from the
  1764. // constructor.
  1765. ExprResult NewDefArg;
  1766. if (OldParam->hasDefaultArg()) {
  1767. NewDefArg = SemaRef.SubstExpr(OldParam->getDefaultArg(), Args);
  1768. if (NewDefArg.isInvalid())
  1769. return nullptr;
  1770. }
  1771. ParmVarDecl *NewParam = ParmVarDecl::Create(SemaRef.Context, DC,
  1772. OldParam->getInnerLocStart(),
  1773. OldParam->getLocation(),
  1774. OldParam->getIdentifier(),
  1775. NewDI->getType(),
  1776. NewDI,
  1777. OldParam->getStorageClass(),
  1778. NewDefArg.get());
  1779. NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
  1780. OldParam->getFunctionScopeIndex());
  1781. SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam, NewParam);
  1782. return NewParam;
  1783. }
  1784. NamedDecl *buildDeductionGuide(TemplateParameterList *TemplateParams,
  1785. ExplicitSpecifier ES, TypeSourceInfo *TInfo,
  1786. SourceLocation LocStart, SourceLocation Loc,
  1787. SourceLocation LocEnd) {
  1788. DeclarationNameInfo Name(DeductionGuideName, Loc);
  1789. ArrayRef<ParmVarDecl *> Params =
  1790. TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams();
  1791. // Build the implicit deduction guide template.
  1792. auto *Guide =
  1793. CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, ES, Name,
  1794. TInfo->getType(), TInfo, LocEnd);
  1795. Guide->setImplicit();
  1796. Guide->setParams(Params);
  1797. for (auto *Param : Params)
  1798. Param->setDeclContext(Guide);
  1799. auto *GuideTemplate = FunctionTemplateDecl::Create(
  1800. SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
  1801. GuideTemplate->setImplicit();
  1802. Guide->setDescribedFunctionTemplate(GuideTemplate);
  1803. if (isa<CXXRecordDecl>(DC)) {
  1804. Guide->setAccess(AS_public);
  1805. GuideTemplate->setAccess(AS_public);
  1806. }
  1807. DC->addDecl(GuideTemplate);
  1808. return GuideTemplate;
  1809. }
  1810. };
  1811. }
  1812. void Sema::DeclareImplicitDeductionGuides(TemplateDecl *Template,
  1813. SourceLocation Loc) {
  1814. if (CXXRecordDecl *DefRecord =
  1815. cast<CXXRecordDecl>(Template->getTemplatedDecl())->getDefinition()) {
  1816. TemplateDecl *DescribedTemplate = DefRecord->getDescribedClassTemplate();
  1817. Template = DescribedTemplate ? DescribedTemplate : Template;
  1818. }
  1819. DeclContext *DC = Template->getDeclContext();
  1820. if (DC->isDependentContext())
  1821. return;
  1822. ConvertConstructorToDeductionGuideTransform Transform(
  1823. *this, cast<ClassTemplateDecl>(Template));
  1824. if (!isCompleteType(Loc, Transform.DeducedType))
  1825. return;
  1826. // Check whether we've already declared deduction guides for this template.
  1827. // FIXME: Consider storing a flag on the template to indicate this.
  1828. auto Existing = DC->lookup(Transform.DeductionGuideName);
  1829. for (auto *D : Existing)
  1830. if (D->isImplicit())
  1831. return;
  1832. // In case we were expanding a pack when we attempted to declare deduction
  1833. // guides, turn off pack expansion for everything we're about to do.
  1834. ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
  1835. // Create a template instantiation record to track the "instantiation" of
  1836. // constructors into deduction guides.
  1837. // FIXME: Add a kind for this to give more meaningful diagnostics. But can
  1838. // this substitution process actually fail?
  1839. InstantiatingTemplate BuildingDeductionGuides(*this, Loc, Template);
  1840. if (BuildingDeductionGuides.isInvalid())
  1841. return;
  1842. // Convert declared constructors into deduction guide templates.
  1843. // FIXME: Skip constructors for which deduction must necessarily fail (those
  1844. // for which some class template parameter without a default argument never
  1845. // appears in a deduced context).
  1846. bool AddedAny = false;
  1847. for (NamedDecl *D : LookupConstructors(Transform.Primary)) {
  1848. D = D->getUnderlyingDecl();
  1849. if (D->isInvalidDecl() || D->isImplicit())
  1850. continue;
  1851. D = cast<NamedDecl>(D->getCanonicalDecl());
  1852. auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
  1853. auto *CD =
  1854. dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D);
  1855. // Class-scope explicit specializations (MS extension) do not result in
  1856. // deduction guides.
  1857. if (!CD || (!FTD && CD->isFunctionTemplateSpecialization()))
  1858. continue;
  1859. Transform.transformConstructor(FTD, CD);
  1860. AddedAny = true;
  1861. }
  1862. // C++17 [over.match.class.deduct]
  1863. // -- If C is not defined or does not declare any constructors, an
  1864. // additional function template derived as above from a hypothetical
  1865. // constructor C().
  1866. if (!AddedAny)
  1867. Transform.buildSimpleDeductionGuide(None);
  1868. // -- An additional function template derived as above from a hypothetical
  1869. // constructor C(C), called the copy deduction candidate.
  1870. cast<CXXDeductionGuideDecl>(
  1871. cast<FunctionTemplateDecl>(
  1872. Transform.buildSimpleDeductionGuide(Transform.DeducedType))
  1873. ->getTemplatedDecl())
  1874. ->setIsCopyDeductionCandidate();
  1875. }
  1876. /// Diagnose the presence of a default template argument on a
  1877. /// template parameter, which is ill-formed in certain contexts.
  1878. ///
  1879. /// \returns true if the default template argument should be dropped.
  1880. static bool DiagnoseDefaultTemplateArgument(Sema &S,
  1881. Sema::TemplateParamListContext TPC,
  1882. SourceLocation ParamLoc,
  1883. SourceRange DefArgRange) {
  1884. switch (TPC) {
  1885. case Sema::TPC_ClassTemplate:
  1886. case Sema::TPC_VarTemplate:
  1887. case Sema::TPC_TypeAliasTemplate:
  1888. return false;
  1889. case Sema::TPC_FunctionTemplate:
  1890. case Sema::TPC_FriendFunctionTemplateDefinition:
  1891. // C++ [temp.param]p9:
  1892. // A default template-argument shall not be specified in a
  1893. // function template declaration or a function template
  1894. // definition [...]
  1895. // If a friend function template declaration specifies a default
  1896. // template-argument, that declaration shall be a definition and shall be
  1897. // the only declaration of the function template in the translation unit.
  1898. // (C++98/03 doesn't have this wording; see DR226).
  1899. S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
  1900. diag::warn_cxx98_compat_template_parameter_default_in_function_template
  1901. : diag::ext_template_parameter_default_in_function_template)
  1902. << DefArgRange;
  1903. return false;
  1904. case Sema::TPC_ClassTemplateMember:
  1905. // C++0x [temp.param]p9:
  1906. // A default template-argument shall not be specified in the
  1907. // template-parameter-lists of the definition of a member of a
  1908. // class template that appears outside of the member's class.
  1909. S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
  1910. << DefArgRange;
  1911. return true;
  1912. case Sema::TPC_FriendClassTemplate:
  1913. case Sema::TPC_FriendFunctionTemplate:
  1914. // C++ [temp.param]p9:
  1915. // A default template-argument shall not be specified in a
  1916. // friend template declaration.
  1917. S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
  1918. << DefArgRange;
  1919. return true;
  1920. // FIXME: C++0x [temp.param]p9 allows default template-arguments
  1921. // for friend function templates if there is only a single
  1922. // declaration (and it is a definition). Strange!
  1923. }
  1924. llvm_unreachable("Invalid TemplateParamListContext!");
  1925. }
  1926. /// Check for unexpanded parameter packs within the template parameters
  1927. /// of a template template parameter, recursively.
  1928. static bool DiagnoseUnexpandedParameterPacks(Sema &S,
  1929. TemplateTemplateParmDecl *TTP) {
  1930. // A template template parameter which is a parameter pack is also a pack
  1931. // expansion.
  1932. if (TTP->isParameterPack())
  1933. return false;
  1934. TemplateParameterList *Params = TTP->getTemplateParameters();
  1935. for (unsigned I = 0, N = Params->size(); I != N; ++I) {
  1936. NamedDecl *P = Params->getParam(I);
  1937. if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
  1938. if (!NTTP->isParameterPack() &&
  1939. S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
  1940. NTTP->getTypeSourceInfo(),
  1941. Sema::UPPC_NonTypeTemplateParameterType))
  1942. return true;
  1943. continue;
  1944. }
  1945. if (TemplateTemplateParmDecl *InnerTTP
  1946. = dyn_cast<TemplateTemplateParmDecl>(P))
  1947. if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
  1948. return true;
  1949. }
  1950. return false;
  1951. }
  1952. /// Checks the validity of a template parameter list, possibly
  1953. /// considering the template parameter list from a previous
  1954. /// declaration.
  1955. ///
  1956. /// If an "old" template parameter list is provided, it must be
  1957. /// equivalent (per TemplateParameterListsAreEqual) to the "new"
  1958. /// template parameter list.
  1959. ///
  1960. /// \param NewParams Template parameter list for a new template
  1961. /// declaration. This template parameter list will be updated with any
  1962. /// default arguments that are carried through from the previous
  1963. /// template parameter list.
  1964. ///
  1965. /// \param OldParams If provided, template parameter list from a
  1966. /// previous declaration of the same template. Default template
  1967. /// arguments will be merged from the old template parameter list to
  1968. /// the new template parameter list.
  1969. ///
  1970. /// \param TPC Describes the context in which we are checking the given
  1971. /// template parameter list.
  1972. ///
  1973. /// \param SkipBody If we might have already made a prior merged definition
  1974. /// of this template visible, the corresponding body-skipping information.
  1975. /// Default argument redefinition is not an error when skipping such a body,
  1976. /// because (under the ODR) we can assume the default arguments are the same
  1977. /// as the prior merged definition.
  1978. ///
  1979. /// \returns true if an error occurred, false otherwise.
  1980. bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
  1981. TemplateParameterList *OldParams,
  1982. TemplateParamListContext TPC,
  1983. SkipBodyInfo *SkipBody) {
  1984. bool Invalid = false;
  1985. // C++ [temp.param]p10:
  1986. // The set of default template-arguments available for use with a
  1987. // template declaration or definition is obtained by merging the
  1988. // default arguments from the definition (if in scope) and all
  1989. // declarations in scope in the same way default function
  1990. // arguments are (8.3.6).
  1991. bool SawDefaultArgument = false;
  1992. SourceLocation PreviousDefaultArgLoc;
  1993. // Dummy initialization to avoid warnings.
  1994. TemplateParameterList::iterator OldParam = NewParams->end();
  1995. if (OldParams)
  1996. OldParam = OldParams->begin();
  1997. bool RemoveDefaultArguments = false;
  1998. for (TemplateParameterList::iterator NewParam = NewParams->begin(),
  1999. NewParamEnd = NewParams->end();
  2000. NewParam != NewParamEnd; ++NewParam) {
  2001. // Variables used to diagnose redundant default arguments
  2002. bool RedundantDefaultArg = false;
  2003. SourceLocation OldDefaultLoc;
  2004. SourceLocation NewDefaultLoc;
  2005. // Variable used to diagnose missing default arguments
  2006. bool MissingDefaultArg = false;
  2007. // Variable used to diagnose non-final parameter packs
  2008. bool SawParameterPack = false;
  2009. if (TemplateTypeParmDecl *NewTypeParm
  2010. = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
  2011. // Check the presence of a default argument here.
  2012. if (NewTypeParm->hasDefaultArgument() &&
  2013. DiagnoseDefaultTemplateArgument(*this, TPC,
  2014. NewTypeParm->getLocation(),
  2015. NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
  2016. .getSourceRange()))
  2017. NewTypeParm->removeDefaultArgument();
  2018. // Merge default arguments for template type parameters.
  2019. TemplateTypeParmDecl *OldTypeParm
  2020. = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
  2021. if (NewTypeParm->isParameterPack()) {
  2022. assert(!NewTypeParm->hasDefaultArgument() &&
  2023. "Parameter packs can't have a default argument!");
  2024. SawParameterPack = true;
  2025. } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
  2026. NewTypeParm->hasDefaultArgument() &&
  2027. (!SkipBody || !SkipBody->ShouldSkip)) {
  2028. OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
  2029. NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
  2030. SawDefaultArgument = true;
  2031. RedundantDefaultArg = true;
  2032. PreviousDefaultArgLoc = NewDefaultLoc;
  2033. } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
  2034. // Merge the default argument from the old declaration to the
  2035. // new declaration.
  2036. NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
  2037. PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
  2038. } else if (NewTypeParm->hasDefaultArgument()) {
  2039. SawDefaultArgument = true;
  2040. PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
  2041. } else if (SawDefaultArgument)
  2042. MissingDefaultArg = true;
  2043. } else if (NonTypeTemplateParmDecl *NewNonTypeParm
  2044. = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
  2045. // Check for unexpanded parameter packs.
  2046. if (!NewNonTypeParm->isParameterPack() &&
  2047. DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
  2048. NewNonTypeParm->getTypeSourceInfo(),
  2049. UPPC_NonTypeTemplateParameterType)) {
  2050. Invalid = true;
  2051. continue;
  2052. }
  2053. // Check the presence of a default argument here.
  2054. if (NewNonTypeParm->hasDefaultArgument() &&
  2055. DiagnoseDefaultTemplateArgument(*this, TPC,
  2056. NewNonTypeParm->getLocation(),
  2057. NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
  2058. NewNonTypeParm->removeDefaultArgument();
  2059. }
  2060. // Merge default arguments for non-type template parameters
  2061. NonTypeTemplateParmDecl *OldNonTypeParm
  2062. = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
  2063. if (NewNonTypeParm->isParameterPack()) {
  2064. assert(!NewNonTypeParm->hasDefaultArgument() &&
  2065. "Parameter packs can't have a default argument!");
  2066. if (!NewNonTypeParm->isPackExpansion())
  2067. SawParameterPack = true;
  2068. } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
  2069. NewNonTypeParm->hasDefaultArgument() &&
  2070. (!SkipBody || !SkipBody->ShouldSkip)) {
  2071. OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
  2072. NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
  2073. SawDefaultArgument = true;
  2074. RedundantDefaultArg = true;
  2075. PreviousDefaultArgLoc = NewDefaultLoc;
  2076. } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
  2077. // Merge the default argument from the old declaration to the
  2078. // new declaration.
  2079. NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
  2080. PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
  2081. } else if (NewNonTypeParm->hasDefaultArgument()) {
  2082. SawDefaultArgument = true;
  2083. PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
  2084. } else if (SawDefaultArgument)
  2085. MissingDefaultArg = true;
  2086. } else {
  2087. TemplateTemplateParmDecl *NewTemplateParm
  2088. = cast<TemplateTemplateParmDecl>(*NewParam);
  2089. // Check for unexpanded parameter packs, recursively.
  2090. if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
  2091. Invalid = true;
  2092. continue;
  2093. }
  2094. // Check the presence of a default argument here.
  2095. if (NewTemplateParm->hasDefaultArgument() &&
  2096. DiagnoseDefaultTemplateArgument(*this, TPC,
  2097. NewTemplateParm->getLocation(),
  2098. NewTemplateParm->getDefaultArgument().getSourceRange()))
  2099. NewTemplateParm->removeDefaultArgument();
  2100. // Merge default arguments for template template parameters
  2101. TemplateTemplateParmDecl *OldTemplateParm
  2102. = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
  2103. if (NewTemplateParm->isParameterPack()) {
  2104. assert(!NewTemplateParm->hasDefaultArgument() &&
  2105. "Parameter packs can't have a default argument!");
  2106. if (!NewTemplateParm->isPackExpansion())
  2107. SawParameterPack = true;
  2108. } else if (OldTemplateParm &&
  2109. hasVisibleDefaultArgument(OldTemplateParm) &&
  2110. NewTemplateParm->hasDefaultArgument() &&
  2111. (!SkipBody || !SkipBody->ShouldSkip)) {
  2112. OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
  2113. NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
  2114. SawDefaultArgument = true;
  2115. RedundantDefaultArg = true;
  2116. PreviousDefaultArgLoc = NewDefaultLoc;
  2117. } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
  2118. // Merge the default argument from the old declaration to the
  2119. // new declaration.
  2120. NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
  2121. PreviousDefaultArgLoc
  2122. = OldTemplateParm->getDefaultArgument().getLocation();
  2123. } else if (NewTemplateParm->hasDefaultArgument()) {
  2124. SawDefaultArgument = true;
  2125. PreviousDefaultArgLoc
  2126. = NewTemplateParm->getDefaultArgument().getLocation();
  2127. } else if (SawDefaultArgument)
  2128. MissingDefaultArg = true;
  2129. }
  2130. // C++11 [temp.param]p11:
  2131. // If a template parameter of a primary class template or alias template
  2132. // is a template parameter pack, it shall be the last template parameter.
  2133. if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
  2134. (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
  2135. TPC == TPC_TypeAliasTemplate)) {
  2136. Diag((*NewParam)->getLocation(),
  2137. diag::err_template_param_pack_must_be_last_template_parameter);
  2138. Invalid = true;
  2139. }
  2140. if (RedundantDefaultArg) {
  2141. // C++ [temp.param]p12:
  2142. // A template-parameter shall not be given default arguments
  2143. // by two different declarations in the same scope.
  2144. Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
  2145. Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
  2146. Invalid = true;
  2147. } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
  2148. // C++ [temp.param]p11:
  2149. // If a template-parameter of a class template has a default
  2150. // template-argument, each subsequent template-parameter shall either
  2151. // have a default template-argument supplied or be a template parameter
  2152. // pack.
  2153. Diag((*NewParam)->getLocation(),
  2154. diag::err_template_param_default_arg_missing);
  2155. Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
  2156. Invalid = true;
  2157. RemoveDefaultArguments = true;
  2158. }
  2159. // If we have an old template parameter list that we're merging
  2160. // in, move on to the next parameter.
  2161. if (OldParams)
  2162. ++OldParam;
  2163. }
  2164. // We were missing some default arguments at the end of the list, so remove
  2165. // all of the default arguments.
  2166. if (RemoveDefaultArguments) {
  2167. for (TemplateParameterList::iterator NewParam = NewParams->begin(),
  2168. NewParamEnd = NewParams->end();
  2169. NewParam != NewParamEnd; ++NewParam) {
  2170. if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
  2171. TTP->removeDefaultArgument();
  2172. else if (NonTypeTemplateParmDecl *NTTP
  2173. = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
  2174. NTTP->removeDefaultArgument();
  2175. else
  2176. cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
  2177. }
  2178. }
  2179. return Invalid;
  2180. }
  2181. namespace {
  2182. /// A class which looks for a use of a certain level of template
  2183. /// parameter.
  2184. struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
  2185. typedef RecursiveASTVisitor<DependencyChecker> super;
  2186. unsigned Depth;
  2187. // Whether we're looking for a use of a template parameter that makes the
  2188. // overall construct type-dependent / a dependent type. This is strictly
  2189. // best-effort for now; we may fail to match at all for a dependent type
  2190. // in some cases if this is set.
  2191. bool IgnoreNonTypeDependent;
  2192. bool Match;
  2193. SourceLocation MatchLoc;
  2194. DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
  2195. : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
  2196. Match(false) {}
  2197. DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
  2198. : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
  2199. NamedDecl *ND = Params->getParam(0);
  2200. if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
  2201. Depth = PD->getDepth();
  2202. } else if (NonTypeTemplateParmDecl *PD =
  2203. dyn_cast<NonTypeTemplateParmDecl>(ND)) {
  2204. Depth = PD->getDepth();
  2205. } else {
  2206. Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
  2207. }
  2208. }
  2209. bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
  2210. if (ParmDepth >= Depth) {
  2211. Match = true;
  2212. MatchLoc = Loc;
  2213. return true;
  2214. }
  2215. return false;
  2216. }
  2217. bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
  2218. // Prune out non-type-dependent expressions if requested. This can
  2219. // sometimes result in us failing to find a template parameter reference
  2220. // (if a value-dependent expression creates a dependent type), but this
  2221. // mode is best-effort only.
  2222. if (auto *E = dyn_cast_or_null<Expr>(S))
  2223. if (IgnoreNonTypeDependent && !E->isTypeDependent())
  2224. return true;
  2225. return super::TraverseStmt(S, Q);
  2226. }
  2227. bool TraverseTypeLoc(TypeLoc TL) {
  2228. if (IgnoreNonTypeDependent && !TL.isNull() &&
  2229. !TL.getType()->isDependentType())
  2230. return true;
  2231. return super::TraverseTypeLoc(TL);
  2232. }
  2233. bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
  2234. return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
  2235. }
  2236. bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
  2237. // For a best-effort search, keep looking until we find a location.
  2238. return IgnoreNonTypeDependent || !Matches(T->getDepth());
  2239. }
  2240. bool TraverseTemplateName(TemplateName N) {
  2241. if (TemplateTemplateParmDecl *PD =
  2242. dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
  2243. if (Matches(PD->getDepth()))
  2244. return false;
  2245. return super::TraverseTemplateName(N);
  2246. }
  2247. bool VisitDeclRefExpr(DeclRefExpr *E) {
  2248. if (NonTypeTemplateParmDecl *PD =
  2249. dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
  2250. if (Matches(PD->getDepth(), E->getExprLoc()))
  2251. return false;
  2252. return super::VisitDeclRefExpr(E);
  2253. }
  2254. bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
  2255. return TraverseType(T->getReplacementType());
  2256. }
  2257. bool
  2258. VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
  2259. return TraverseTemplateArgument(T->getArgumentPack());
  2260. }
  2261. bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
  2262. return TraverseType(T->getInjectedSpecializationType());
  2263. }
  2264. };
  2265. } // end anonymous namespace
  2266. /// Determines whether a given type depends on the given parameter
  2267. /// list.
  2268. static bool
  2269. DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
  2270. DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
  2271. Checker.TraverseType(T);
  2272. return Checker.Match;
  2273. }
  2274. // Find the source range corresponding to the named type in the given
  2275. // nested-name-specifier, if any.
  2276. static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
  2277. QualType T,
  2278. const CXXScopeSpec &SS) {
  2279. NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
  2280. while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
  2281. if (const Type *CurType = NNS->getAsType()) {
  2282. if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
  2283. return NNSLoc.getTypeLoc().getSourceRange();
  2284. } else
  2285. break;
  2286. NNSLoc = NNSLoc.getPrefix();
  2287. }
  2288. return SourceRange();
  2289. }
  2290. /// Match the given template parameter lists to the given scope
  2291. /// specifier, returning the template parameter list that applies to the
  2292. /// name.
  2293. ///
  2294. /// \param DeclStartLoc the start of the declaration that has a scope
  2295. /// specifier or a template parameter list.
  2296. ///
  2297. /// \param DeclLoc The location of the declaration itself.
  2298. ///
  2299. /// \param SS the scope specifier that will be matched to the given template
  2300. /// parameter lists. This scope specifier precedes a qualified name that is
  2301. /// being declared.
  2302. ///
  2303. /// \param TemplateId The template-id following the scope specifier, if there
  2304. /// is one. Used to check for a missing 'template<>'.
  2305. ///
  2306. /// \param ParamLists the template parameter lists, from the outermost to the
  2307. /// innermost template parameter lists.
  2308. ///
  2309. /// \param IsFriend Whether to apply the slightly different rules for
  2310. /// matching template parameters to scope specifiers in friend
  2311. /// declarations.
  2312. ///
  2313. /// \param IsMemberSpecialization will be set true if the scope specifier
  2314. /// denotes a fully-specialized type, and therefore this is a declaration of
  2315. /// a member specialization.
  2316. ///
  2317. /// \returns the template parameter list, if any, that corresponds to the
  2318. /// name that is preceded by the scope specifier @p SS. This template
  2319. /// parameter list may have template parameters (if we're declaring a
  2320. /// template) or may have no template parameters (if we're declaring a
  2321. /// template specialization), or may be NULL (if what we're declaring isn't
  2322. /// itself a template).
  2323. TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
  2324. SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
  2325. TemplateIdAnnotation *TemplateId,
  2326. ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
  2327. bool &IsMemberSpecialization, bool &Invalid) {
  2328. IsMemberSpecialization = false;
  2329. Invalid = false;
  2330. // The sequence of nested types to which we will match up the template
  2331. // parameter lists. We first build this list by starting with the type named
  2332. // by the nested-name-specifier and walking out until we run out of types.
  2333. SmallVector<QualType, 4> NestedTypes;
  2334. QualType T;
  2335. if (SS.getScopeRep()) {
  2336. if (CXXRecordDecl *Record
  2337. = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
  2338. T = Context.getTypeDeclType(Record);
  2339. else
  2340. T = QualType(SS.getScopeRep()->getAsType(), 0);
  2341. }
  2342. // If we found an explicit specialization that prevents us from needing
  2343. // 'template<>' headers, this will be set to the location of that
  2344. // explicit specialization.
  2345. SourceLocation ExplicitSpecLoc;
  2346. while (!T.isNull()) {
  2347. NestedTypes.push_back(T);
  2348. // Retrieve the parent of a record type.
  2349. if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
  2350. // If this type is an explicit specialization, we're done.
  2351. if (ClassTemplateSpecializationDecl *Spec
  2352. = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
  2353. if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
  2354. Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
  2355. ExplicitSpecLoc = Spec->getLocation();
  2356. break;
  2357. }
  2358. } else if (Record->getTemplateSpecializationKind()
  2359. == TSK_ExplicitSpecialization) {
  2360. ExplicitSpecLoc = Record->getLocation();
  2361. break;
  2362. }
  2363. if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
  2364. T = Context.getTypeDeclType(Parent);
  2365. else
  2366. T = QualType();
  2367. continue;
  2368. }
  2369. if (const TemplateSpecializationType *TST
  2370. = T->getAs<TemplateSpecializationType>()) {
  2371. if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
  2372. if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
  2373. T = Context.getTypeDeclType(Parent);
  2374. else
  2375. T = QualType();
  2376. continue;
  2377. }
  2378. }
  2379. // Look one step prior in a dependent template specialization type.
  2380. if (const DependentTemplateSpecializationType *DependentTST
  2381. = T->getAs<DependentTemplateSpecializationType>()) {
  2382. if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
  2383. T = QualType(NNS->getAsType(), 0);
  2384. else
  2385. T = QualType();
  2386. continue;
  2387. }
  2388. // Look one step prior in a dependent name type.
  2389. if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
  2390. if (NestedNameSpecifier *NNS = DependentName->getQualifier())
  2391. T = QualType(NNS->getAsType(), 0);
  2392. else
  2393. T = QualType();
  2394. continue;
  2395. }
  2396. // Retrieve the parent of an enumeration type.
  2397. if (const EnumType *EnumT = T->getAs<EnumType>()) {
  2398. // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
  2399. // check here.
  2400. EnumDecl *Enum = EnumT->getDecl();
  2401. // Get to the parent type.
  2402. if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
  2403. T = Context.getTypeDeclType(Parent);
  2404. else
  2405. T = QualType();
  2406. continue;
  2407. }
  2408. T = QualType();
  2409. }
  2410. // Reverse the nested types list, since we want to traverse from the outermost
  2411. // to the innermost while checking template-parameter-lists.
  2412. std::reverse(NestedTypes.begin(), NestedTypes.end());
  2413. // C++0x [temp.expl.spec]p17:
  2414. // A member or a member template may be nested within many
  2415. // enclosing class templates. In an explicit specialization for
  2416. // such a member, the member declaration shall be preceded by a
  2417. // template<> for each enclosing class template that is
  2418. // explicitly specialized.
  2419. bool SawNonEmptyTemplateParameterList = false;
  2420. auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
  2421. if (SawNonEmptyTemplateParameterList) {
  2422. Diag(DeclLoc, diag::err_specialize_member_of_template)
  2423. << !Recovery << Range;
  2424. Invalid = true;
  2425. IsMemberSpecialization = false;
  2426. return true;
  2427. }
  2428. return false;
  2429. };
  2430. auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
  2431. // Check that we can have an explicit specialization here.
  2432. if (CheckExplicitSpecialization(Range, true))
  2433. return true;
  2434. // We don't have a template header, but we should.
  2435. SourceLocation ExpectedTemplateLoc;
  2436. if (!ParamLists.empty())
  2437. ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
  2438. else
  2439. ExpectedTemplateLoc = DeclStartLoc;
  2440. Diag(DeclLoc, diag::err_template_spec_needs_header)
  2441. << Range
  2442. << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
  2443. return false;
  2444. };
  2445. unsigned ParamIdx = 0;
  2446. for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
  2447. ++TypeIdx) {
  2448. T = NestedTypes[TypeIdx];
  2449. // Whether we expect a 'template<>' header.
  2450. bool NeedEmptyTemplateHeader = false;
  2451. // Whether we expect a template header with parameters.
  2452. bool NeedNonemptyTemplateHeader = false;
  2453. // For a dependent type, the set of template parameters that we
  2454. // expect to see.
  2455. TemplateParameterList *ExpectedTemplateParams = nullptr;
  2456. // C++0x [temp.expl.spec]p15:
  2457. // A member or a member template may be nested within many enclosing
  2458. // class templates. In an explicit specialization for such a member, the
  2459. // member declaration shall be preceded by a template<> for each
  2460. // enclosing class template that is explicitly specialized.
  2461. if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
  2462. if (ClassTemplatePartialSpecializationDecl *Partial
  2463. = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
  2464. ExpectedTemplateParams = Partial->getTemplateParameters();
  2465. NeedNonemptyTemplateHeader = true;
  2466. } else if (Record->isDependentType()) {
  2467. if (Record->getDescribedClassTemplate()) {
  2468. ExpectedTemplateParams = Record->getDescribedClassTemplate()
  2469. ->getTemplateParameters();
  2470. NeedNonemptyTemplateHeader = true;
  2471. }
  2472. } else if (ClassTemplateSpecializationDecl *Spec
  2473. = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
  2474. // C++0x [temp.expl.spec]p4:
  2475. // Members of an explicitly specialized class template are defined
  2476. // in the same manner as members of normal classes, and not using
  2477. // the template<> syntax.
  2478. if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
  2479. NeedEmptyTemplateHeader = true;
  2480. else
  2481. continue;
  2482. } else if (Record->getTemplateSpecializationKind()) {
  2483. if (Record->getTemplateSpecializationKind()
  2484. != TSK_ExplicitSpecialization &&
  2485. TypeIdx == NumTypes - 1)
  2486. IsMemberSpecialization = true;
  2487. continue;
  2488. }
  2489. } else if (const TemplateSpecializationType *TST
  2490. = T->getAs<TemplateSpecializationType>()) {
  2491. if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
  2492. ExpectedTemplateParams = Template->getTemplateParameters();
  2493. NeedNonemptyTemplateHeader = true;
  2494. }
  2495. } else if (T->getAs<DependentTemplateSpecializationType>()) {
  2496. // FIXME: We actually could/should check the template arguments here
  2497. // against the corresponding template parameter list.
  2498. NeedNonemptyTemplateHeader = false;
  2499. }
  2500. // C++ [temp.expl.spec]p16:
  2501. // In an explicit specialization declaration for a member of a class
  2502. // template or a member template that ap- pears in namespace scope, the
  2503. // member template and some of its enclosing class templates may remain
  2504. // unspecialized, except that the declaration shall not explicitly
  2505. // specialize a class member template if its en- closing class templates
  2506. // are not explicitly specialized as well.
  2507. if (ParamIdx < ParamLists.size()) {
  2508. if (ParamLists[ParamIdx]->size() == 0) {
  2509. if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
  2510. false))
  2511. return nullptr;
  2512. } else
  2513. SawNonEmptyTemplateParameterList = true;
  2514. }
  2515. if (NeedEmptyTemplateHeader) {
  2516. // If we're on the last of the types, and we need a 'template<>' header
  2517. // here, then it's a member specialization.
  2518. if (TypeIdx == NumTypes - 1)
  2519. IsMemberSpecialization = true;
  2520. if (ParamIdx < ParamLists.size()) {
  2521. if (ParamLists[ParamIdx]->size() > 0) {
  2522. // The header has template parameters when it shouldn't. Complain.
  2523. Diag(ParamLists[ParamIdx]->getTemplateLoc(),
  2524. diag::err_template_param_list_matches_nontemplate)
  2525. << T
  2526. << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
  2527. ParamLists[ParamIdx]->getRAngleLoc())
  2528. << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
  2529. Invalid = true;
  2530. return nullptr;
  2531. }
  2532. // Consume this template header.
  2533. ++ParamIdx;
  2534. continue;
  2535. }
  2536. if (!IsFriend)
  2537. if (DiagnoseMissingExplicitSpecialization(
  2538. getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
  2539. return nullptr;
  2540. continue;
  2541. }
  2542. if (NeedNonemptyTemplateHeader) {
  2543. // In friend declarations we can have template-ids which don't
  2544. // depend on the corresponding template parameter lists. But
  2545. // assume that empty parameter lists are supposed to match this
  2546. // template-id.
  2547. if (IsFriend && T->isDependentType()) {
  2548. if (ParamIdx < ParamLists.size() &&
  2549. DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
  2550. ExpectedTemplateParams = nullptr;
  2551. else
  2552. continue;
  2553. }
  2554. if (ParamIdx < ParamLists.size()) {
  2555. // Check the template parameter list, if we can.
  2556. if (ExpectedTemplateParams &&
  2557. !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
  2558. ExpectedTemplateParams,
  2559. true, TPL_TemplateMatch))
  2560. Invalid = true;
  2561. if (!Invalid &&
  2562. CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
  2563. TPC_ClassTemplateMember))
  2564. Invalid = true;
  2565. ++ParamIdx;
  2566. continue;
  2567. }
  2568. Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
  2569. << T
  2570. << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
  2571. Invalid = true;
  2572. continue;
  2573. }
  2574. }
  2575. // If there were at least as many template-ids as there were template
  2576. // parameter lists, then there are no template parameter lists remaining for
  2577. // the declaration itself.
  2578. if (ParamIdx >= ParamLists.size()) {
  2579. if (TemplateId && !IsFriend) {
  2580. // We don't have a template header for the declaration itself, but we
  2581. // should.
  2582. DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
  2583. TemplateId->RAngleLoc));
  2584. // Fabricate an empty template parameter list for the invented header.
  2585. return TemplateParameterList::Create(Context, SourceLocation(),
  2586. SourceLocation(), None,
  2587. SourceLocation(), nullptr);
  2588. }
  2589. return nullptr;
  2590. }
  2591. // If there were too many template parameter lists, complain about that now.
  2592. if (ParamIdx < ParamLists.size() - 1) {
  2593. bool HasAnyExplicitSpecHeader = false;
  2594. bool AllExplicitSpecHeaders = true;
  2595. for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
  2596. if (ParamLists[I]->size() == 0)
  2597. HasAnyExplicitSpecHeader = true;
  2598. else
  2599. AllExplicitSpecHeaders = false;
  2600. }
  2601. Diag(ParamLists[ParamIdx]->getTemplateLoc(),
  2602. AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
  2603. : diag::err_template_spec_extra_headers)
  2604. << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
  2605. ParamLists[ParamLists.size() - 2]->getRAngleLoc());
  2606. // If there was a specialization somewhere, such that 'template<>' is
  2607. // not required, and there were any 'template<>' headers, note where the
  2608. // specialization occurred.
  2609. if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
  2610. Diag(ExplicitSpecLoc,
  2611. diag::note_explicit_template_spec_does_not_need_header)
  2612. << NestedTypes.back();
  2613. // We have a template parameter list with no corresponding scope, which
  2614. // means that the resulting template declaration can't be instantiated
  2615. // properly (we'll end up with dependent nodes when we shouldn't).
  2616. if (!AllExplicitSpecHeaders)
  2617. Invalid = true;
  2618. }
  2619. // C++ [temp.expl.spec]p16:
  2620. // In an explicit specialization declaration for a member of a class
  2621. // template or a member template that ap- pears in namespace scope, the
  2622. // member template and some of its enclosing class templates may remain
  2623. // unspecialized, except that the declaration shall not explicitly
  2624. // specialize a class member template if its en- closing class templates
  2625. // are not explicitly specialized as well.
  2626. if (ParamLists.back()->size() == 0 &&
  2627. CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
  2628. false))
  2629. return nullptr;
  2630. // Return the last template parameter list, which corresponds to the
  2631. // entity being declared.
  2632. return ParamLists.back();
  2633. }
  2634. void Sema::NoteAllFoundTemplates(TemplateName Name) {
  2635. if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
  2636. Diag(Template->getLocation(), diag::note_template_declared_here)
  2637. << (isa<FunctionTemplateDecl>(Template)
  2638. ? 0
  2639. : isa<ClassTemplateDecl>(Template)
  2640. ? 1
  2641. : isa<VarTemplateDecl>(Template)
  2642. ? 2
  2643. : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
  2644. << Template->getDeclName();
  2645. return;
  2646. }
  2647. if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
  2648. for (OverloadedTemplateStorage::iterator I = OST->begin(),
  2649. IEnd = OST->end();
  2650. I != IEnd; ++I)
  2651. Diag((*I)->getLocation(), diag::note_template_declared_here)
  2652. << 0 << (*I)->getDeclName();
  2653. return;
  2654. }
  2655. }
  2656. static QualType
  2657. checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
  2658. const SmallVectorImpl<TemplateArgument> &Converted,
  2659. SourceLocation TemplateLoc,
  2660. TemplateArgumentListInfo &TemplateArgs) {
  2661. ASTContext &Context = SemaRef.getASTContext();
  2662. switch (BTD->getBuiltinTemplateKind()) {
  2663. case BTK__make_integer_seq: {
  2664. // Specializations of __make_integer_seq<S, T, N> are treated like
  2665. // S<T, 0, ..., N-1>.
  2666. // C++14 [inteseq.intseq]p1:
  2667. // T shall be an integer type.
  2668. if (!Converted[1].getAsType()->isIntegralType(Context)) {
  2669. SemaRef.Diag(TemplateArgs[1].getLocation(),
  2670. diag::err_integer_sequence_integral_element_type);
  2671. return QualType();
  2672. }
  2673. // C++14 [inteseq.make]p1:
  2674. // If N is negative the program is ill-formed.
  2675. TemplateArgument NumArgsArg = Converted[2];
  2676. llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
  2677. if (NumArgs < 0) {
  2678. SemaRef.Diag(TemplateArgs[2].getLocation(),
  2679. diag::err_integer_sequence_negative_length);
  2680. return QualType();
  2681. }
  2682. QualType ArgTy = NumArgsArg.getIntegralType();
  2683. TemplateArgumentListInfo SyntheticTemplateArgs;
  2684. // The type argument gets reused as the first template argument in the
  2685. // synthetic template argument list.
  2686. SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
  2687. // Expand N into 0 ... N-1.
  2688. for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
  2689. I < NumArgs; ++I) {
  2690. TemplateArgument TA(Context, I, ArgTy);
  2691. SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
  2692. TA, ArgTy, TemplateArgs[2].getLocation()));
  2693. }
  2694. // The first template argument will be reused as the template decl that
  2695. // our synthetic template arguments will be applied to.
  2696. return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
  2697. TemplateLoc, SyntheticTemplateArgs);
  2698. }
  2699. case BTK__type_pack_element:
  2700. // Specializations of
  2701. // __type_pack_element<Index, T_1, ..., T_N>
  2702. // are treated like T_Index.
  2703. assert(Converted.size() == 2 &&
  2704. "__type_pack_element should be given an index and a parameter pack");
  2705. // If the Index is out of bounds, the program is ill-formed.
  2706. TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
  2707. llvm::APSInt Index = IndexArg.getAsIntegral();
  2708. assert(Index >= 0 && "the index used with __type_pack_element should be of "
  2709. "type std::size_t, and hence be non-negative");
  2710. if (Index >= Ts.pack_size()) {
  2711. SemaRef.Diag(TemplateArgs[0].getLocation(),
  2712. diag::err_type_pack_element_out_of_bounds);
  2713. return QualType();
  2714. }
  2715. // We simply return the type at index `Index`.
  2716. auto Nth = std::next(Ts.pack_begin(), Index.getExtValue());
  2717. return Nth->getAsType();
  2718. }
  2719. llvm_unreachable("unexpected BuiltinTemplateDecl!");
  2720. }
  2721. /// Determine whether this alias template is "enable_if_t".
  2722. static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
  2723. return AliasTemplate->getName().equals("enable_if_t");
  2724. }
  2725. /// Collect all of the separable terms in the given condition, which
  2726. /// might be a conjunction.
  2727. ///
  2728. /// FIXME: The right answer is to convert the logical expression into
  2729. /// disjunctive normal form, so we can find the first failed term
  2730. /// within each possible clause.
  2731. static void collectConjunctionTerms(Expr *Clause,
  2732. SmallVectorImpl<Expr *> &Terms) {
  2733. if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
  2734. if (BinOp->getOpcode() == BO_LAnd) {
  2735. collectConjunctionTerms(BinOp->getLHS(), Terms);
  2736. collectConjunctionTerms(BinOp->getRHS(), Terms);
  2737. }
  2738. return;
  2739. }
  2740. Terms.push_back(Clause);
  2741. }
  2742. // The ranges-v3 library uses an odd pattern of a top-level "||" with
  2743. // a left-hand side that is value-dependent but never true. Identify
  2744. // the idiom and ignore that term.
  2745. static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) {
  2746. // Top-level '||'.
  2747. auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
  2748. if (!BinOp) return Cond;
  2749. if (BinOp->getOpcode() != BO_LOr) return Cond;
  2750. // With an inner '==' that has a literal on the right-hand side.
  2751. Expr *LHS = BinOp->getLHS();
  2752. auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
  2753. if (!InnerBinOp) return Cond;
  2754. if (InnerBinOp->getOpcode() != BO_EQ ||
  2755. !isa<IntegerLiteral>(InnerBinOp->getRHS()))
  2756. return Cond;
  2757. // If the inner binary operation came from a macro expansion named
  2758. // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
  2759. // of the '||', which is the real, user-provided condition.
  2760. SourceLocation Loc = InnerBinOp->getExprLoc();
  2761. if (!Loc.isMacroID()) return Cond;
  2762. StringRef MacroName = PP.getImmediateMacroName(Loc);
  2763. if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
  2764. return BinOp->getRHS();
  2765. return Cond;
  2766. }
  2767. namespace {
  2768. // A PrinterHelper that prints more helpful diagnostics for some sub-expressions
  2769. // within failing boolean expression, such as substituting template parameters
  2770. // for actual types.
  2771. class FailedBooleanConditionPrinterHelper : public PrinterHelper {
  2772. public:
  2773. explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
  2774. : Policy(P) {}
  2775. bool handledStmt(Stmt *E, raw_ostream &OS) override {
  2776. const auto *DR = dyn_cast<DeclRefExpr>(E);
  2777. if (DR && DR->getQualifier()) {
  2778. // If this is a qualified name, expand the template arguments in nested
  2779. // qualifiers.
  2780. DR->getQualifier()->print(OS, Policy, true);
  2781. // Then print the decl itself.
  2782. const ValueDecl *VD = DR->getDecl();
  2783. OS << VD->getName();
  2784. if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
  2785. // This is a template variable, print the expanded template arguments.
  2786. printTemplateArgumentList(OS, IV->getTemplateArgs().asArray(), Policy);
  2787. }
  2788. return true;
  2789. }
  2790. return false;
  2791. }
  2792. private:
  2793. const PrintingPolicy Policy;
  2794. };
  2795. } // end anonymous namespace
  2796. std::pair<Expr *, std::string>
  2797. Sema::findFailedBooleanCondition(Expr *Cond) {
  2798. Cond = lookThroughRangesV3Condition(PP, Cond);
  2799. // Separate out all of the terms in a conjunction.
  2800. SmallVector<Expr *, 4> Terms;
  2801. collectConjunctionTerms(Cond, Terms);
  2802. // Determine which term failed.
  2803. Expr *FailedCond = nullptr;
  2804. for (Expr *Term : Terms) {
  2805. Expr *TermAsWritten = Term->IgnoreParenImpCasts();
  2806. // Literals are uninteresting.
  2807. if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
  2808. isa<IntegerLiteral>(TermAsWritten))
  2809. continue;
  2810. // The initialization of the parameter from the argument is
  2811. // a constant-evaluated context.
  2812. EnterExpressionEvaluationContext ConstantEvaluated(
  2813. *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  2814. bool Succeeded;
  2815. if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
  2816. !Succeeded) {
  2817. FailedCond = TermAsWritten;
  2818. break;
  2819. }
  2820. }
  2821. if (!FailedCond)
  2822. FailedCond = Cond->IgnoreParenImpCasts();
  2823. std::string Description;
  2824. {
  2825. llvm::raw_string_ostream Out(Description);
  2826. PrintingPolicy Policy = getPrintingPolicy();
  2827. Policy.PrintCanonicalTypes = true;
  2828. FailedBooleanConditionPrinterHelper Helper(Policy);
  2829. FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
  2830. }
  2831. return { FailedCond, Description };
  2832. }
  2833. QualType Sema::CheckTemplateIdType(TemplateName Name,
  2834. SourceLocation TemplateLoc,
  2835. TemplateArgumentListInfo &TemplateArgs) {
  2836. DependentTemplateName *DTN
  2837. = Name.getUnderlying().getAsDependentTemplateName();
  2838. if (DTN && DTN->isIdentifier())
  2839. // When building a template-id where the template-name is dependent,
  2840. // assume the template is a type template. Either our assumption is
  2841. // correct, or the code is ill-formed and will be diagnosed when the
  2842. // dependent name is substituted.
  2843. return Context.getDependentTemplateSpecializationType(ETK_None,
  2844. DTN->getQualifier(),
  2845. DTN->getIdentifier(),
  2846. TemplateArgs);
  2847. TemplateDecl *Template = Name.getAsTemplateDecl();
  2848. if (!Template || isa<FunctionTemplateDecl>(Template) ||
  2849. isa<VarTemplateDecl>(Template) ||
  2850. isa<ConceptDecl>(Template)) {
  2851. // We might have a substituted template template parameter pack. If so,
  2852. // build a template specialization type for it.
  2853. if (Name.getAsSubstTemplateTemplateParmPack())
  2854. return Context.getTemplateSpecializationType(Name, TemplateArgs);
  2855. Diag(TemplateLoc, diag::err_template_id_not_a_type)
  2856. << Name;
  2857. NoteAllFoundTemplates(Name);
  2858. return QualType();
  2859. }
  2860. // Check that the template argument list is well-formed for this
  2861. // template.
  2862. SmallVector<TemplateArgument, 4> Converted;
  2863. if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
  2864. false, Converted))
  2865. return QualType();
  2866. QualType CanonType;
  2867. bool InstantiationDependent = false;
  2868. if (TypeAliasTemplateDecl *AliasTemplate =
  2869. dyn_cast<TypeAliasTemplateDecl>(Template)) {
  2870. // Find the canonical type for this type alias template specialization.
  2871. TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
  2872. if (Pattern->isInvalidDecl())
  2873. return QualType();
  2874. TemplateArgumentList StackTemplateArgs(TemplateArgumentList::OnStack,
  2875. Converted);
  2876. // Only substitute for the innermost template argument list.
  2877. MultiLevelTemplateArgumentList TemplateArgLists;
  2878. TemplateArgLists.addOuterTemplateArguments(&StackTemplateArgs);
  2879. unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
  2880. for (unsigned I = 0; I < Depth; ++I)
  2881. TemplateArgLists.addOuterTemplateArguments(None);
  2882. LocalInstantiationScope Scope(*this);
  2883. InstantiatingTemplate Inst(*this, TemplateLoc, Template);
  2884. if (Inst.isInvalid())
  2885. return QualType();
  2886. CanonType = SubstType(Pattern->getUnderlyingType(),
  2887. TemplateArgLists, AliasTemplate->getLocation(),
  2888. AliasTemplate->getDeclName());
  2889. if (CanonType.isNull()) {
  2890. // If this was enable_if and we failed to find the nested type
  2891. // within enable_if in a SFINAE context, dig out the specific
  2892. // enable_if condition that failed and present that instead.
  2893. if (isEnableIfAliasTemplate(AliasTemplate)) {
  2894. if (auto DeductionInfo = isSFINAEContext()) {
  2895. if (*DeductionInfo &&
  2896. (*DeductionInfo)->hasSFINAEDiagnostic() &&
  2897. (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
  2898. diag::err_typename_nested_not_found_enable_if &&
  2899. TemplateArgs[0].getArgument().getKind()
  2900. == TemplateArgument::Expression) {
  2901. Expr *FailedCond;
  2902. std::string FailedDescription;
  2903. std::tie(FailedCond, FailedDescription) =
  2904. findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
  2905. // Remove the old SFINAE diagnostic.
  2906. PartialDiagnosticAt OldDiag =
  2907. {SourceLocation(), PartialDiagnostic::NullDiagnostic()};
  2908. (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
  2909. // Add a new SFINAE diagnostic specifying which condition
  2910. // failed.
  2911. (*DeductionInfo)->addSFINAEDiagnostic(
  2912. OldDiag.first,
  2913. PDiag(diag::err_typename_nested_not_found_requirement)
  2914. << FailedDescription
  2915. << FailedCond->getSourceRange());
  2916. }
  2917. }
  2918. }
  2919. return QualType();
  2920. }
  2921. } else if (Name.isDependent() ||
  2922. TemplateSpecializationType::anyDependentTemplateArguments(
  2923. TemplateArgs, InstantiationDependent)) {
  2924. // This class template specialization is a dependent
  2925. // type. Therefore, its canonical type is another class template
  2926. // specialization type that contains all of the converted
  2927. // arguments in canonical form. This ensures that, e.g., A<T> and
  2928. // A<T, T> have identical types when A is declared as:
  2929. //
  2930. // template<typename T, typename U = T> struct A;
  2931. CanonType = Context.getCanonicalTemplateSpecializationType(Name, Converted);
  2932. // This might work out to be a current instantiation, in which
  2933. // case the canonical type needs to be the InjectedClassNameType.
  2934. //
  2935. // TODO: in theory this could be a simple hashtable lookup; most
  2936. // changes to CurContext don't change the set of current
  2937. // instantiations.
  2938. if (isa<ClassTemplateDecl>(Template)) {
  2939. for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
  2940. // If we get out to a namespace, we're done.
  2941. if (Ctx->isFileContext()) break;
  2942. // If this isn't a record, keep looking.
  2943. CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
  2944. if (!Record) continue;
  2945. // Look for one of the two cases with InjectedClassNameTypes
  2946. // and check whether it's the same template.
  2947. if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
  2948. !Record->getDescribedClassTemplate())
  2949. continue;
  2950. // Fetch the injected class name type and check whether its
  2951. // injected type is equal to the type we just built.
  2952. QualType ICNT = Context.getTypeDeclType(Record);
  2953. QualType Injected = cast<InjectedClassNameType>(ICNT)
  2954. ->getInjectedSpecializationType();
  2955. if (CanonType != Injected->getCanonicalTypeInternal())
  2956. continue;
  2957. // If so, the canonical type of this TST is the injected
  2958. // class name type of the record we just found.
  2959. assert(ICNT.isCanonical());
  2960. CanonType = ICNT;
  2961. break;
  2962. }
  2963. }
  2964. } else if (ClassTemplateDecl *ClassTemplate
  2965. = dyn_cast<ClassTemplateDecl>(Template)) {
  2966. // Find the class template specialization declaration that
  2967. // corresponds to these arguments.
  2968. void *InsertPos = nullptr;
  2969. ClassTemplateSpecializationDecl *Decl
  2970. = ClassTemplate->findSpecialization(Converted, InsertPos);
  2971. if (!Decl) {
  2972. // This is the first time we have referenced this class template
  2973. // specialization. Create the canonical declaration and add it to
  2974. // the set of specializations.
  2975. Decl = ClassTemplateSpecializationDecl::Create(
  2976. Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
  2977. ClassTemplate->getDeclContext(),
  2978. ClassTemplate->getTemplatedDecl()->getBeginLoc(),
  2979. ClassTemplate->getLocation(), ClassTemplate, Converted, nullptr);
  2980. ClassTemplate->AddSpecialization(Decl, InsertPos);
  2981. if (ClassTemplate->isOutOfLine())
  2982. Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
  2983. }
  2984. if (Decl->getSpecializationKind() == TSK_Undeclared) {
  2985. MultiLevelTemplateArgumentList TemplateArgLists;
  2986. TemplateArgLists.addOuterTemplateArguments(Converted);
  2987. InstantiateAttrsForDecl(TemplateArgLists, ClassTemplate->getTemplatedDecl(),
  2988. Decl);
  2989. }
  2990. // Diagnose uses of this specialization.
  2991. (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
  2992. CanonType = Context.getTypeDeclType(Decl);
  2993. assert(isa<RecordType>(CanonType) &&
  2994. "type of non-dependent specialization is not a RecordType");
  2995. } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
  2996. CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
  2997. TemplateArgs);
  2998. }
  2999. // Build the fully-sugared type for this class template
  3000. // specialization, which refers back to the class template
  3001. // specialization we created or found.
  3002. return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
  3003. }
  3004. void Sema::ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &ParsedName,
  3005. TemplateNameKind &TNK,
  3006. SourceLocation NameLoc,
  3007. IdentifierInfo *&II) {
  3008. assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
  3009. TemplateName Name = ParsedName.get();
  3010. auto *ATN = Name.getAsAssumedTemplateName();
  3011. assert(ATN && "not an assumed template name");
  3012. II = ATN->getDeclName().getAsIdentifierInfo();
  3013. if (!resolveAssumedTemplateNameAsType(S, Name, NameLoc, /*Diagnose*/false)) {
  3014. // Resolved to a type template name.
  3015. ParsedName = TemplateTy::make(Name);
  3016. TNK = TNK_Type_template;
  3017. }
  3018. }
  3019. bool Sema::resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name,
  3020. SourceLocation NameLoc,
  3021. bool Diagnose) {
  3022. // We assumed this undeclared identifier to be an (ADL-only) function
  3023. // template name, but it was used in a context where a type was required.
  3024. // Try to typo-correct it now.
  3025. AssumedTemplateStorage *ATN = Name.getAsAssumedTemplateName();
  3026. assert(ATN && "not an assumed template name");
  3027. LookupResult R(*this, ATN->getDeclName(), NameLoc, LookupOrdinaryName);
  3028. struct CandidateCallback : CorrectionCandidateCallback {
  3029. bool ValidateCandidate(const TypoCorrection &TC) override {
  3030. return TC.getCorrectionDecl() &&
  3031. getAsTypeTemplateDecl(TC.getCorrectionDecl());
  3032. }
  3033. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  3034. return std::make_unique<CandidateCallback>(*this);
  3035. }
  3036. } FilterCCC;
  3037. TypoCorrection Corrected =
  3038. CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
  3039. FilterCCC, CTK_ErrorRecovery);
  3040. if (Corrected && Corrected.getFoundDecl()) {
  3041. diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest)
  3042. << ATN->getDeclName());
  3043. Name = TemplateName(Corrected.getCorrectionDeclAs<TemplateDecl>());
  3044. return false;
  3045. }
  3046. if (Diagnose)
  3047. Diag(R.getNameLoc(), diag::err_no_template) << R.getLookupName();
  3048. return true;
  3049. }
  3050. TypeResult Sema::ActOnTemplateIdType(
  3051. Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
  3052. TemplateTy TemplateD, IdentifierInfo *TemplateII,
  3053. SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
  3054. ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc,
  3055. bool IsCtorOrDtorName, bool IsClassName) {
  3056. if (SS.isInvalid())
  3057. return true;
  3058. if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
  3059. DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
  3060. // C++ [temp.res]p3:
  3061. // A qualified-id that refers to a type and in which the
  3062. // nested-name-specifier depends on a template-parameter (14.6.2)
  3063. // shall be prefixed by the keyword typename to indicate that the
  3064. // qualified-id denotes a type, forming an
  3065. // elaborated-type-specifier (7.1.5.3).
  3066. if (!LookupCtx && isDependentScopeSpecifier(SS)) {
  3067. Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
  3068. << SS.getScopeRep() << TemplateII->getName();
  3069. // Recover as if 'typename' were specified.
  3070. // FIXME: This is not quite correct recovery as we don't transform SS
  3071. // into the corresponding dependent form (and we don't diagnose missing
  3072. // 'template' keywords within SS as a result).
  3073. return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
  3074. TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
  3075. TemplateArgsIn, RAngleLoc);
  3076. }
  3077. // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
  3078. // it's not actually allowed to be used as a type in most cases. Because
  3079. // we annotate it before we know whether it's valid, we have to check for
  3080. // this case here.
  3081. auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
  3082. if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
  3083. Diag(TemplateIILoc,
  3084. TemplateKWLoc.isInvalid()
  3085. ? diag::err_out_of_line_qualified_id_type_names_constructor
  3086. : diag::ext_out_of_line_qualified_id_type_names_constructor)
  3087. << TemplateII << 0 /*injected-class-name used as template name*/
  3088. << 1 /*if any keyword was present, it was 'template'*/;
  3089. }
  3090. }
  3091. TemplateName Template = TemplateD.get();
  3092. if (Template.getAsAssumedTemplateName() &&
  3093. resolveAssumedTemplateNameAsType(S, Template, TemplateIILoc))
  3094. return true;
  3095. // Translate the parser's template argument list in our AST format.
  3096. TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
  3097. translateTemplateArguments(TemplateArgsIn, TemplateArgs);
  3098. if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
  3099. QualType T
  3100. = Context.getDependentTemplateSpecializationType(ETK_None,
  3101. DTN->getQualifier(),
  3102. DTN->getIdentifier(),
  3103. TemplateArgs);
  3104. // Build type-source information.
  3105. TypeLocBuilder TLB;
  3106. DependentTemplateSpecializationTypeLoc SpecTL
  3107. = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
  3108. SpecTL.setElaboratedKeywordLoc(SourceLocation());
  3109. SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
  3110. SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
  3111. SpecTL.setTemplateNameLoc(TemplateIILoc);
  3112. SpecTL.setLAngleLoc(LAngleLoc);
  3113. SpecTL.setRAngleLoc(RAngleLoc);
  3114. for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
  3115. SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
  3116. return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
  3117. }
  3118. QualType Result = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
  3119. if (Result.isNull())
  3120. return true;
  3121. // Build type-source information.
  3122. TypeLocBuilder TLB;
  3123. TemplateSpecializationTypeLoc SpecTL
  3124. = TLB.push<TemplateSpecializationTypeLoc>(Result);
  3125. SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
  3126. SpecTL.setTemplateNameLoc(TemplateIILoc);
  3127. SpecTL.setLAngleLoc(LAngleLoc);
  3128. SpecTL.setRAngleLoc(RAngleLoc);
  3129. for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
  3130. SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
  3131. // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
  3132. // constructor or destructor name (in such a case, the scope specifier
  3133. // will be attached to the enclosing Decl or Expr node).
  3134. if (SS.isNotEmpty() && !IsCtorOrDtorName) {
  3135. // Create an elaborated-type-specifier containing the nested-name-specifier.
  3136. Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
  3137. ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
  3138. ElabTL.setElaboratedKeywordLoc(SourceLocation());
  3139. ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
  3140. }
  3141. return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
  3142. }
  3143. TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
  3144. TypeSpecifierType TagSpec,
  3145. SourceLocation TagLoc,
  3146. CXXScopeSpec &SS,
  3147. SourceLocation TemplateKWLoc,
  3148. TemplateTy TemplateD,
  3149. SourceLocation TemplateLoc,
  3150. SourceLocation LAngleLoc,
  3151. ASTTemplateArgsPtr TemplateArgsIn,
  3152. SourceLocation RAngleLoc) {
  3153. TemplateName Template = TemplateD.get();
  3154. // Translate the parser's template argument list in our AST format.
  3155. TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
  3156. translateTemplateArguments(TemplateArgsIn, TemplateArgs);
  3157. // Determine the tag kind
  3158. TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  3159. ElaboratedTypeKeyword Keyword
  3160. = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
  3161. if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
  3162. QualType T = Context.getDependentTemplateSpecializationType(Keyword,
  3163. DTN->getQualifier(),
  3164. DTN->getIdentifier(),
  3165. TemplateArgs);
  3166. // Build type-source information.
  3167. TypeLocBuilder TLB;
  3168. DependentTemplateSpecializationTypeLoc SpecTL
  3169. = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
  3170. SpecTL.setElaboratedKeywordLoc(TagLoc);
  3171. SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
  3172. SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
  3173. SpecTL.setTemplateNameLoc(TemplateLoc);
  3174. SpecTL.setLAngleLoc(LAngleLoc);
  3175. SpecTL.setRAngleLoc(RAngleLoc);
  3176. for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
  3177. SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
  3178. return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
  3179. }
  3180. if (TypeAliasTemplateDecl *TAT =
  3181. dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
  3182. // C++0x [dcl.type.elab]p2:
  3183. // If the identifier resolves to a typedef-name or the simple-template-id
  3184. // resolves to an alias template specialization, the
  3185. // elaborated-type-specifier is ill-formed.
  3186. Diag(TemplateLoc, diag::err_tag_reference_non_tag)
  3187. << TAT << NTK_TypeAliasTemplate << TagKind;
  3188. Diag(TAT->getLocation(), diag::note_declared_at);
  3189. }
  3190. QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
  3191. if (Result.isNull())
  3192. return TypeResult(true);
  3193. // Check the tag kind
  3194. if (const RecordType *RT = Result->getAs<RecordType>()) {
  3195. RecordDecl *D = RT->getDecl();
  3196. IdentifierInfo *Id = D->getIdentifier();
  3197. assert(Id && "templated class must have an identifier");
  3198. if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
  3199. TagLoc, Id)) {
  3200. Diag(TagLoc, diag::err_use_with_wrong_tag)
  3201. << Result
  3202. << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
  3203. Diag(D->getLocation(), diag::note_previous_use);
  3204. }
  3205. }
  3206. // Provide source-location information for the template specialization.
  3207. TypeLocBuilder TLB;
  3208. TemplateSpecializationTypeLoc SpecTL
  3209. = TLB.push<TemplateSpecializationTypeLoc>(Result);
  3210. SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
  3211. SpecTL.setTemplateNameLoc(TemplateLoc);
  3212. SpecTL.setLAngleLoc(LAngleLoc);
  3213. SpecTL.setRAngleLoc(RAngleLoc);
  3214. for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
  3215. SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
  3216. // Construct an elaborated type containing the nested-name-specifier (if any)
  3217. // and tag keyword.
  3218. Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
  3219. ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
  3220. ElabTL.setElaboratedKeywordLoc(TagLoc);
  3221. ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
  3222. return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
  3223. }
  3224. static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
  3225. NamedDecl *PrevDecl,
  3226. SourceLocation Loc,
  3227. bool IsPartialSpecialization);
  3228. static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
  3229. static bool isTemplateArgumentTemplateParameter(
  3230. const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
  3231. switch (Arg.getKind()) {
  3232. case TemplateArgument::Null:
  3233. case TemplateArgument::NullPtr:
  3234. case TemplateArgument::Integral:
  3235. case TemplateArgument::Declaration:
  3236. case TemplateArgument::Pack:
  3237. case TemplateArgument::TemplateExpansion:
  3238. return false;
  3239. case TemplateArgument::Type: {
  3240. QualType Type = Arg.getAsType();
  3241. const TemplateTypeParmType *TPT =
  3242. Arg.getAsType()->getAs<TemplateTypeParmType>();
  3243. return TPT && !Type.hasQualifiers() &&
  3244. TPT->getDepth() == Depth && TPT->getIndex() == Index;
  3245. }
  3246. case TemplateArgument::Expression: {
  3247. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
  3248. if (!DRE || !DRE->getDecl())
  3249. return false;
  3250. const NonTypeTemplateParmDecl *NTTP =
  3251. dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
  3252. return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
  3253. }
  3254. case TemplateArgument::Template:
  3255. const TemplateTemplateParmDecl *TTP =
  3256. dyn_cast_or_null<TemplateTemplateParmDecl>(
  3257. Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
  3258. return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
  3259. }
  3260. llvm_unreachable("unexpected kind of template argument");
  3261. }
  3262. static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
  3263. ArrayRef<TemplateArgument> Args) {
  3264. if (Params->size() != Args.size())
  3265. return false;
  3266. unsigned Depth = Params->getDepth();
  3267. for (unsigned I = 0, N = Args.size(); I != N; ++I) {
  3268. TemplateArgument Arg = Args[I];
  3269. // If the parameter is a pack expansion, the argument must be a pack
  3270. // whose only element is a pack expansion.
  3271. if (Params->getParam(I)->isParameterPack()) {
  3272. if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
  3273. !Arg.pack_begin()->isPackExpansion())
  3274. return false;
  3275. Arg = Arg.pack_begin()->getPackExpansionPattern();
  3276. }
  3277. if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
  3278. return false;
  3279. }
  3280. return true;
  3281. }
  3282. /// Convert the parser's template argument list representation into our form.
  3283. static TemplateArgumentListInfo
  3284. makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
  3285. TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
  3286. TemplateId.RAngleLoc);
  3287. ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
  3288. TemplateId.NumArgs);
  3289. S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
  3290. return TemplateArgs;
  3291. }
  3292. template<typename PartialSpecDecl>
  3293. static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
  3294. if (Partial->getDeclContext()->isDependentContext())
  3295. return;
  3296. // FIXME: Get the TDK from deduction in order to provide better diagnostics
  3297. // for non-substitution-failure issues?
  3298. TemplateDeductionInfo Info(Partial->getLocation());
  3299. if (S.isMoreSpecializedThanPrimary(Partial, Info))
  3300. return;
  3301. auto *Template = Partial->getSpecializedTemplate();
  3302. S.Diag(Partial->getLocation(),
  3303. diag::ext_partial_spec_not_more_specialized_than_primary)
  3304. << isa<VarTemplateDecl>(Template);
  3305. if (Info.hasSFINAEDiagnostic()) {
  3306. PartialDiagnosticAt Diag = {SourceLocation(),
  3307. PartialDiagnostic::NullDiagnostic()};
  3308. Info.takeSFINAEDiagnostic(Diag);
  3309. SmallString<128> SFINAEArgString;
  3310. Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
  3311. S.Diag(Diag.first,
  3312. diag::note_partial_spec_not_more_specialized_than_primary)
  3313. << SFINAEArgString;
  3314. }
  3315. S.Diag(Template->getLocation(), diag::note_template_decl_here);
  3316. }
  3317. static void
  3318. noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
  3319. const llvm::SmallBitVector &DeducibleParams) {
  3320. for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
  3321. if (!DeducibleParams[I]) {
  3322. NamedDecl *Param = TemplateParams->getParam(I);
  3323. if (Param->getDeclName())
  3324. S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
  3325. << Param->getDeclName();
  3326. else
  3327. S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
  3328. << "(anonymous)";
  3329. }
  3330. }
  3331. }
  3332. template<typename PartialSpecDecl>
  3333. static void checkTemplatePartialSpecialization(Sema &S,
  3334. PartialSpecDecl *Partial) {
  3335. // C++1z [temp.class.spec]p8: (DR1495)
  3336. // - The specialization shall be more specialized than the primary
  3337. // template (14.5.5.2).
  3338. checkMoreSpecializedThanPrimary(S, Partial);
  3339. // C++ [temp.class.spec]p8: (DR1315)
  3340. // - Each template-parameter shall appear at least once in the
  3341. // template-id outside a non-deduced context.
  3342. // C++1z [temp.class.spec.match]p3 (P0127R2)
  3343. // If the template arguments of a partial specialization cannot be
  3344. // deduced because of the structure of its template-parameter-list
  3345. // and the template-id, the program is ill-formed.
  3346. auto *TemplateParams = Partial->getTemplateParameters();
  3347. llvm::SmallBitVector DeducibleParams(TemplateParams->size());
  3348. S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
  3349. TemplateParams->getDepth(), DeducibleParams);
  3350. if (!DeducibleParams.all()) {
  3351. unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
  3352. S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
  3353. << isa<VarTemplatePartialSpecializationDecl>(Partial)
  3354. << (NumNonDeducible > 1)
  3355. << SourceRange(Partial->getLocation(),
  3356. Partial->getTemplateArgsAsWritten()->RAngleLoc);
  3357. noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
  3358. }
  3359. }
  3360. void Sema::CheckTemplatePartialSpecialization(
  3361. ClassTemplatePartialSpecializationDecl *Partial) {
  3362. checkTemplatePartialSpecialization(*this, Partial);
  3363. }
  3364. void Sema::CheckTemplatePartialSpecialization(
  3365. VarTemplatePartialSpecializationDecl *Partial) {
  3366. checkTemplatePartialSpecialization(*this, Partial);
  3367. }
  3368. void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
  3369. // C++1z [temp.param]p11:
  3370. // A template parameter of a deduction guide template that does not have a
  3371. // default-argument shall be deducible from the parameter-type-list of the
  3372. // deduction guide template.
  3373. auto *TemplateParams = TD->getTemplateParameters();
  3374. llvm::SmallBitVector DeducibleParams(TemplateParams->size());
  3375. MarkDeducedTemplateParameters(TD, DeducibleParams);
  3376. for (unsigned I = 0; I != TemplateParams->size(); ++I) {
  3377. // A parameter pack is deducible (to an empty pack).
  3378. auto *Param = TemplateParams->getParam(I);
  3379. if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
  3380. DeducibleParams[I] = true;
  3381. }
  3382. if (!DeducibleParams.all()) {
  3383. unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
  3384. Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
  3385. << (NumNonDeducible > 1);
  3386. noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
  3387. }
  3388. }
  3389. DeclResult Sema::ActOnVarTemplateSpecialization(
  3390. Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
  3391. TemplateParameterList *TemplateParams, StorageClass SC,
  3392. bool IsPartialSpecialization) {
  3393. // D must be variable template id.
  3394. assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
  3395. "Variable template specialization is declared with a template it.");
  3396. TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
  3397. TemplateArgumentListInfo TemplateArgs =
  3398. makeTemplateArgumentListInfo(*this, *TemplateId);
  3399. SourceLocation TemplateNameLoc = D.getIdentifierLoc();
  3400. SourceLocation LAngleLoc = TemplateId->LAngleLoc;
  3401. SourceLocation RAngleLoc = TemplateId->RAngleLoc;
  3402. TemplateName Name = TemplateId->Template.get();
  3403. // The template-id must name a variable template.
  3404. VarTemplateDecl *VarTemplate =
  3405. dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
  3406. if (!VarTemplate) {
  3407. NamedDecl *FnTemplate;
  3408. if (auto *OTS = Name.getAsOverloadedTemplate())
  3409. FnTemplate = *OTS->begin();
  3410. else
  3411. FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
  3412. if (FnTemplate)
  3413. return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
  3414. << FnTemplate->getDeclName();
  3415. return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
  3416. << IsPartialSpecialization;
  3417. }
  3418. // Check for unexpanded parameter packs in any of the template arguments.
  3419. for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
  3420. if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
  3421. UPPC_PartialSpecialization))
  3422. return true;
  3423. // Check that the template argument list is well-formed for this
  3424. // template.
  3425. SmallVector<TemplateArgument, 4> Converted;
  3426. if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
  3427. false, Converted))
  3428. return true;
  3429. // Find the variable template (partial) specialization declaration that
  3430. // corresponds to these arguments.
  3431. if (IsPartialSpecialization) {
  3432. if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
  3433. TemplateArgs.size(), Converted))
  3434. return true;
  3435. // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
  3436. // also do them during instantiation.
  3437. bool InstantiationDependent;
  3438. if (!Name.isDependent() &&
  3439. !TemplateSpecializationType::anyDependentTemplateArguments(
  3440. TemplateArgs.arguments(),
  3441. InstantiationDependent)) {
  3442. Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
  3443. << VarTemplate->getDeclName();
  3444. IsPartialSpecialization = false;
  3445. }
  3446. if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
  3447. Converted)) {
  3448. // C++ [temp.class.spec]p9b3:
  3449. //
  3450. // -- The argument list of the specialization shall not be identical
  3451. // to the implicit argument list of the primary template.
  3452. Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
  3453. << /*variable template*/ 1
  3454. << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
  3455. << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
  3456. // FIXME: Recover from this by treating the declaration as a redeclaration
  3457. // of the primary template.
  3458. return true;
  3459. }
  3460. }
  3461. void *InsertPos = nullptr;
  3462. VarTemplateSpecializationDecl *PrevDecl = nullptr;
  3463. if (IsPartialSpecialization)
  3464. // FIXME: Template parameter list matters too
  3465. PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
  3466. else
  3467. PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
  3468. VarTemplateSpecializationDecl *Specialization = nullptr;
  3469. // Check whether we can declare a variable template specialization in
  3470. // the current scope.
  3471. if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
  3472. TemplateNameLoc,
  3473. IsPartialSpecialization))
  3474. return true;
  3475. if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
  3476. // Since the only prior variable template specialization with these
  3477. // arguments was referenced but not declared, reuse that
  3478. // declaration node as our own, updating its source location and
  3479. // the list of outer template parameters to reflect our new declaration.
  3480. Specialization = PrevDecl;
  3481. Specialization->setLocation(TemplateNameLoc);
  3482. PrevDecl = nullptr;
  3483. } else if (IsPartialSpecialization) {
  3484. // Create a new class template partial specialization declaration node.
  3485. VarTemplatePartialSpecializationDecl *PrevPartial =
  3486. cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
  3487. VarTemplatePartialSpecializationDecl *Partial =
  3488. VarTemplatePartialSpecializationDecl::Create(
  3489. Context, VarTemplate->getDeclContext(), TemplateKWLoc,
  3490. TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
  3491. Converted, TemplateArgs);
  3492. if (!PrevPartial)
  3493. VarTemplate->AddPartialSpecialization(Partial, InsertPos);
  3494. Specialization = Partial;
  3495. // If we are providing an explicit specialization of a member variable
  3496. // template specialization, make a note of that.
  3497. if (PrevPartial && PrevPartial->getInstantiatedFromMember())
  3498. PrevPartial->setMemberSpecialization();
  3499. CheckTemplatePartialSpecialization(Partial);
  3500. } else {
  3501. // Create a new class template specialization declaration node for
  3502. // this explicit specialization or friend declaration.
  3503. Specialization = VarTemplateSpecializationDecl::Create(
  3504. Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
  3505. VarTemplate, DI->getType(), DI, SC, Converted);
  3506. Specialization->setTemplateArgsInfo(TemplateArgs);
  3507. if (!PrevDecl)
  3508. VarTemplate->AddSpecialization(Specialization, InsertPos);
  3509. }
  3510. // C++ [temp.expl.spec]p6:
  3511. // If a template, a member template or the member of a class template is
  3512. // explicitly specialized then that specialization shall be declared
  3513. // before the first use of that specialization that would cause an implicit
  3514. // instantiation to take place, in every translation unit in which such a
  3515. // use occurs; no diagnostic is required.
  3516. if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
  3517. bool Okay = false;
  3518. for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
  3519. // Is there any previous explicit specialization declaration?
  3520. if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
  3521. Okay = true;
  3522. break;
  3523. }
  3524. }
  3525. if (!Okay) {
  3526. SourceRange Range(TemplateNameLoc, RAngleLoc);
  3527. Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
  3528. << Name << Range;
  3529. Diag(PrevDecl->getPointOfInstantiation(),
  3530. diag::note_instantiation_required_here)
  3531. << (PrevDecl->getTemplateSpecializationKind() !=
  3532. TSK_ImplicitInstantiation);
  3533. return true;
  3534. }
  3535. }
  3536. Specialization->setTemplateKeywordLoc(TemplateKWLoc);
  3537. Specialization->setLexicalDeclContext(CurContext);
  3538. // Add the specialization into its lexical context, so that it can
  3539. // be seen when iterating through the list of declarations in that
  3540. // context. However, specializations are not found by name lookup.
  3541. CurContext->addDecl(Specialization);
  3542. // Note that this is an explicit specialization.
  3543. Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
  3544. if (PrevDecl) {
  3545. // Check that this isn't a redefinition of this specialization,
  3546. // merging with previous declarations.
  3547. LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
  3548. forRedeclarationInCurContext());
  3549. PrevSpec.addDecl(PrevDecl);
  3550. D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
  3551. } else if (Specialization->isStaticDataMember() &&
  3552. Specialization->isOutOfLine()) {
  3553. Specialization->setAccess(VarTemplate->getAccess());
  3554. }
  3555. return Specialization;
  3556. }
  3557. namespace {
  3558. /// A partial specialization whose template arguments have matched
  3559. /// a given template-id.
  3560. struct PartialSpecMatchResult {
  3561. VarTemplatePartialSpecializationDecl *Partial;
  3562. TemplateArgumentList *Args;
  3563. };
  3564. } // end anonymous namespace
  3565. DeclResult
  3566. Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
  3567. SourceLocation TemplateNameLoc,
  3568. const TemplateArgumentListInfo &TemplateArgs) {
  3569. assert(Template && "A variable template id without template?");
  3570. // Check that the template argument list is well-formed for this template.
  3571. SmallVector<TemplateArgument, 4> Converted;
  3572. if (CheckTemplateArgumentList(
  3573. Template, TemplateNameLoc,
  3574. const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
  3575. Converted))
  3576. return true;
  3577. // Find the variable template specialization declaration that
  3578. // corresponds to these arguments.
  3579. void *InsertPos = nullptr;
  3580. if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
  3581. Converted, InsertPos)) {
  3582. checkSpecializationVisibility(TemplateNameLoc, Spec);
  3583. // If we already have a variable template specialization, return it.
  3584. return Spec;
  3585. }
  3586. // This is the first time we have referenced this variable template
  3587. // specialization. Create the canonical declaration and add it to
  3588. // the set of specializations, based on the closest partial specialization
  3589. // that it represents. That is,
  3590. VarDecl *InstantiationPattern = Template->getTemplatedDecl();
  3591. TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
  3592. Converted);
  3593. TemplateArgumentList *InstantiationArgs = &TemplateArgList;
  3594. bool AmbiguousPartialSpec = false;
  3595. typedef PartialSpecMatchResult MatchResult;
  3596. SmallVector<MatchResult, 4> Matched;
  3597. SourceLocation PointOfInstantiation = TemplateNameLoc;
  3598. TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
  3599. /*ForTakingAddress=*/false);
  3600. // 1. Attempt to find the closest partial specialization that this
  3601. // specializes, if any.
  3602. // If any of the template arguments is dependent, then this is probably
  3603. // a placeholder for an incomplete declarative context; which must be
  3604. // complete by instantiation time. Thus, do not search through the partial
  3605. // specializations yet.
  3606. // TODO: Unify with InstantiateClassTemplateSpecialization()?
  3607. // Perhaps better after unification of DeduceTemplateArguments() and
  3608. // getMoreSpecializedPartialSpecialization().
  3609. bool InstantiationDependent = false;
  3610. if (!TemplateSpecializationType::anyDependentTemplateArguments(
  3611. TemplateArgs, InstantiationDependent)) {
  3612. SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
  3613. Template->getPartialSpecializations(PartialSpecs);
  3614. for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
  3615. VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
  3616. TemplateDeductionInfo Info(FailedCandidates.getLocation());
  3617. if (TemplateDeductionResult Result =
  3618. DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
  3619. // Store the failed-deduction information for use in diagnostics, later.
  3620. // TODO: Actually use the failed-deduction info?
  3621. FailedCandidates.addCandidate().set(
  3622. DeclAccessPair::make(Template, AS_public), Partial,
  3623. MakeDeductionFailureInfo(Context, Result, Info));
  3624. (void)Result;
  3625. } else {
  3626. Matched.push_back(PartialSpecMatchResult());
  3627. Matched.back().Partial = Partial;
  3628. Matched.back().Args = Info.take();
  3629. }
  3630. }
  3631. if (Matched.size() >= 1) {
  3632. SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
  3633. if (Matched.size() == 1) {
  3634. // -- If exactly one matching specialization is found, the
  3635. // instantiation is generated from that specialization.
  3636. // We don't need to do anything for this.
  3637. } else {
  3638. // -- If more than one matching specialization is found, the
  3639. // partial order rules (14.5.4.2) are used to determine
  3640. // whether one of the specializations is more specialized
  3641. // than the others. If none of the specializations is more
  3642. // specialized than all of the other matching
  3643. // specializations, then the use of the variable template is
  3644. // ambiguous and the program is ill-formed.
  3645. for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
  3646. PEnd = Matched.end();
  3647. P != PEnd; ++P) {
  3648. if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
  3649. PointOfInstantiation) ==
  3650. P->Partial)
  3651. Best = P;
  3652. }
  3653. // Determine if the best partial specialization is more specialized than
  3654. // the others.
  3655. for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
  3656. PEnd = Matched.end();
  3657. P != PEnd; ++P) {
  3658. if (P != Best && getMoreSpecializedPartialSpecialization(
  3659. P->Partial, Best->Partial,
  3660. PointOfInstantiation) != Best->Partial) {
  3661. AmbiguousPartialSpec = true;
  3662. break;
  3663. }
  3664. }
  3665. }
  3666. // Instantiate using the best variable template partial specialization.
  3667. InstantiationPattern = Best->Partial;
  3668. InstantiationArgs = Best->Args;
  3669. } else {
  3670. // -- If no match is found, the instantiation is generated
  3671. // from the primary template.
  3672. // InstantiationPattern = Template->getTemplatedDecl();
  3673. }
  3674. }
  3675. // 2. Create the canonical declaration.
  3676. // Note that we do not instantiate a definition until we see an odr-use
  3677. // in DoMarkVarDeclReferenced().
  3678. // FIXME: LateAttrs et al.?
  3679. VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
  3680. Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
  3681. Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
  3682. if (!Decl)
  3683. return true;
  3684. if (AmbiguousPartialSpec) {
  3685. // Partial ordering did not produce a clear winner. Complain.
  3686. Decl->setInvalidDecl();
  3687. Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
  3688. << Decl;
  3689. // Print the matching partial specializations.
  3690. for (MatchResult P : Matched)
  3691. Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
  3692. << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
  3693. *P.Args);
  3694. return true;
  3695. }
  3696. if (VarTemplatePartialSpecializationDecl *D =
  3697. dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
  3698. Decl->setInstantiationOf(D, InstantiationArgs);
  3699. checkSpecializationVisibility(TemplateNameLoc, Decl);
  3700. assert(Decl && "No variable template specialization?");
  3701. return Decl;
  3702. }
  3703. ExprResult
  3704. Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
  3705. const DeclarationNameInfo &NameInfo,
  3706. VarTemplateDecl *Template, SourceLocation TemplateLoc,
  3707. const TemplateArgumentListInfo *TemplateArgs) {
  3708. DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
  3709. *TemplateArgs);
  3710. if (Decl.isInvalid())
  3711. return ExprError();
  3712. VarDecl *Var = cast<VarDecl>(Decl.get());
  3713. if (!Var->getTemplateSpecializationKind())
  3714. Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
  3715. NameInfo.getLoc());
  3716. // Build an ordinary singleton decl ref.
  3717. return BuildDeclarationNameExpr(SS, NameInfo, Var,
  3718. /*FoundD=*/nullptr, TemplateArgs);
  3719. }
  3720. void Sema::diagnoseMissingTemplateArguments(TemplateName Name,
  3721. SourceLocation Loc) {
  3722. Diag(Loc, diag::err_template_missing_args)
  3723. << (int)getTemplateNameKindForDiagnostics(Name) << Name;
  3724. if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
  3725. Diag(TD->getLocation(), diag::note_template_decl_here)
  3726. << TD->getTemplateParameters()->getSourceRange();
  3727. }
  3728. }
  3729. ExprResult
  3730. Sema::CheckConceptTemplateId(const CXXScopeSpec &SS,
  3731. const DeclarationNameInfo &NameInfo,
  3732. ConceptDecl *Template,
  3733. SourceLocation TemplateLoc,
  3734. const TemplateArgumentListInfo *TemplateArgs) {
  3735. // TODO: Do concept specialization here.
  3736. Diag(NameInfo.getBeginLoc(), diag::err_concept_not_implemented) <<
  3737. "concept specialization";
  3738. return ExprError();
  3739. }
  3740. ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
  3741. SourceLocation TemplateKWLoc,
  3742. LookupResult &R,
  3743. bool RequiresADL,
  3744. const TemplateArgumentListInfo *TemplateArgs) {
  3745. // FIXME: Can we do any checking at this point? I guess we could check the
  3746. // template arguments that we have against the template name, if the template
  3747. // name refers to a single template. That's not a terribly common case,
  3748. // though.
  3749. // foo<int> could identify a single function unambiguously
  3750. // This approach does NOT work, since f<int>(1);
  3751. // gets resolved prior to resorting to overload resolution
  3752. // i.e., template<class T> void f(double);
  3753. // vs template<class T, class U> void f(U);
  3754. // These should be filtered out by our callers.
  3755. assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
  3756. // Non-function templates require a template argument list.
  3757. if (auto *TD = R.getAsSingle<TemplateDecl>()) {
  3758. if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
  3759. diagnoseMissingTemplateArguments(TemplateName(TD), R.getNameLoc());
  3760. return ExprError();
  3761. }
  3762. }
  3763. auto AnyDependentArguments = [&]() -> bool {
  3764. bool InstantiationDependent;
  3765. return TemplateArgs &&
  3766. TemplateSpecializationType::anyDependentTemplateArguments(
  3767. *TemplateArgs, InstantiationDependent);
  3768. };
  3769. // In C++1y, check variable template ids.
  3770. if (R.getAsSingle<VarTemplateDecl>() && !AnyDependentArguments()) {
  3771. return CheckVarTemplateId(SS, R.getLookupNameInfo(),
  3772. R.getAsSingle<VarTemplateDecl>(),
  3773. TemplateKWLoc, TemplateArgs);
  3774. }
  3775. if (R.getAsSingle<ConceptDecl>() && !AnyDependentArguments()) {
  3776. return CheckConceptTemplateId(SS, R.getLookupNameInfo(),
  3777. R.getAsSingle<ConceptDecl>(),
  3778. TemplateKWLoc, TemplateArgs);
  3779. }
  3780. // We don't want lookup warnings at this point.
  3781. R.suppressDiagnostics();
  3782. UnresolvedLookupExpr *ULE
  3783. = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
  3784. SS.getWithLocInContext(Context),
  3785. TemplateKWLoc,
  3786. R.getLookupNameInfo(),
  3787. RequiresADL, TemplateArgs,
  3788. R.begin(), R.end());
  3789. return ULE;
  3790. }
  3791. // We actually only call this from template instantiation.
  3792. ExprResult
  3793. Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
  3794. SourceLocation TemplateKWLoc,
  3795. const DeclarationNameInfo &NameInfo,
  3796. const TemplateArgumentListInfo *TemplateArgs) {
  3797. assert(TemplateArgs || TemplateKWLoc.isValid());
  3798. DeclContext *DC;
  3799. if (!(DC = computeDeclContext(SS, false)) ||
  3800. DC->isDependentContext() ||
  3801. RequireCompleteDeclContext(SS, DC))
  3802. return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
  3803. bool MemberOfUnknownSpecialization;
  3804. LookupResult R(*this, NameInfo, LookupOrdinaryName);
  3805. if (LookupTemplateName(R, (Scope *)nullptr, SS, QualType(),
  3806. /*Entering*/false, MemberOfUnknownSpecialization,
  3807. TemplateKWLoc))
  3808. return ExprError();
  3809. if (R.isAmbiguous())
  3810. return ExprError();
  3811. if (R.empty()) {
  3812. Diag(NameInfo.getLoc(), diag::err_no_member)
  3813. << NameInfo.getName() << DC << SS.getRange();
  3814. return ExprError();
  3815. }
  3816. if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
  3817. Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
  3818. << SS.getScopeRep()
  3819. << NameInfo.getName().getAsString() << SS.getRange();
  3820. Diag(Temp->getLocation(), diag::note_referenced_class_template);
  3821. return ExprError();
  3822. }
  3823. return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
  3824. }
  3825. /// Form a dependent template name.
  3826. ///
  3827. /// This action forms a dependent template name given the template
  3828. /// name and its (presumably dependent) scope specifier. For
  3829. /// example, given "MetaFun::template apply", the scope specifier \p
  3830. /// SS will be "MetaFun::", \p TemplateKWLoc contains the location
  3831. /// of the "template" keyword, and "apply" is the \p Name.
  3832. TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
  3833. CXXScopeSpec &SS,
  3834. SourceLocation TemplateKWLoc,
  3835. const UnqualifiedId &Name,
  3836. ParsedType ObjectType,
  3837. bool EnteringContext,
  3838. TemplateTy &Result,
  3839. bool AllowInjectedClassName) {
  3840. if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
  3841. Diag(TemplateKWLoc,
  3842. getLangOpts().CPlusPlus11 ?
  3843. diag::warn_cxx98_compat_template_outside_of_template :
  3844. diag::ext_template_outside_of_template)
  3845. << FixItHint::CreateRemoval(TemplateKWLoc);
  3846. DeclContext *LookupCtx = nullptr;
  3847. if (SS.isSet())
  3848. LookupCtx = computeDeclContext(SS, EnteringContext);
  3849. if (!LookupCtx && ObjectType)
  3850. LookupCtx = computeDeclContext(ObjectType.get());
  3851. if (LookupCtx) {
  3852. // C++0x [temp.names]p5:
  3853. // If a name prefixed by the keyword template is not the name of
  3854. // a template, the program is ill-formed. [Note: the keyword
  3855. // template may not be applied to non-template members of class
  3856. // templates. -end note ] [ Note: as is the case with the
  3857. // typename prefix, the template prefix is allowed in cases
  3858. // where it is not strictly necessary; i.e., when the
  3859. // nested-name-specifier or the expression on the left of the ->
  3860. // or . is not dependent on a template-parameter, or the use
  3861. // does not appear in the scope of a template. -end note]
  3862. //
  3863. // Note: C++03 was more strict here, because it banned the use of
  3864. // the "template" keyword prior to a template-name that was not a
  3865. // dependent name. C++ DR468 relaxed this requirement (the
  3866. // "template" keyword is now permitted). We follow the C++0x
  3867. // rules, even in C++03 mode with a warning, retroactively applying the DR.
  3868. bool MemberOfUnknownSpecialization;
  3869. TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
  3870. ObjectType, EnteringContext, Result,
  3871. MemberOfUnknownSpecialization);
  3872. if (TNK == TNK_Non_template && MemberOfUnknownSpecialization) {
  3873. // This is a dependent template. Handle it below.
  3874. } else if (TNK == TNK_Non_template) {
  3875. // Do the lookup again to determine if this is a "nothing found" case or
  3876. // a "not a template" case. FIXME: Refactor isTemplateName so we don't
  3877. // need to do this.
  3878. DeclarationNameInfo DNI = GetNameFromUnqualifiedId(Name);
  3879. LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
  3880. LookupOrdinaryName);
  3881. bool MOUS;
  3882. if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext,
  3883. MOUS, TemplateKWLoc) && !R.isAmbiguous())
  3884. Diag(Name.getBeginLoc(), diag::err_no_member)
  3885. << DNI.getName() << LookupCtx << SS.getRange();
  3886. return TNK_Non_template;
  3887. } else {
  3888. // We found something; return it.
  3889. auto *LookupRD = dyn_cast<CXXRecordDecl>(LookupCtx);
  3890. if (!AllowInjectedClassName && SS.isSet() && LookupRD &&
  3891. Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
  3892. Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
  3893. // C++14 [class.qual]p2:
  3894. // In a lookup in which function names are not ignored and the
  3895. // nested-name-specifier nominates a class C, if the name specified
  3896. // [...] is the injected-class-name of C, [...] the name is instead
  3897. // considered to name the constructor
  3898. //
  3899. // We don't get here if naming the constructor would be valid, so we
  3900. // just reject immediately and recover by treating the
  3901. // injected-class-name as naming the template.
  3902. Diag(Name.getBeginLoc(),
  3903. diag::ext_out_of_line_qualified_id_type_names_constructor)
  3904. << Name.Identifier
  3905. << 0 /*injected-class-name used as template name*/
  3906. << 1 /*'template' keyword was used*/;
  3907. }
  3908. return TNK;
  3909. }
  3910. }
  3911. NestedNameSpecifier *Qualifier = SS.getScopeRep();
  3912. switch (Name.getKind()) {
  3913. case UnqualifiedIdKind::IK_Identifier:
  3914. Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
  3915. Name.Identifier));
  3916. return TNK_Dependent_template_name;
  3917. case UnqualifiedIdKind::IK_OperatorFunctionId:
  3918. Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
  3919. Name.OperatorFunctionId.Operator));
  3920. return TNK_Function_template;
  3921. case UnqualifiedIdKind::IK_LiteralOperatorId:
  3922. llvm_unreachable("literal operator id cannot have a dependent scope");
  3923. default:
  3924. break;
  3925. }
  3926. Diag(Name.getBeginLoc(), diag::err_template_kw_refers_to_non_template)
  3927. << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()
  3928. << TemplateKWLoc;
  3929. return TNK_Non_template;
  3930. }
  3931. bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
  3932. TemplateArgumentLoc &AL,
  3933. SmallVectorImpl<TemplateArgument> &Converted) {
  3934. const TemplateArgument &Arg = AL.getArgument();
  3935. QualType ArgType;
  3936. TypeSourceInfo *TSI = nullptr;
  3937. // Check template type parameter.
  3938. switch(Arg.getKind()) {
  3939. case TemplateArgument::Type:
  3940. // C++ [temp.arg.type]p1:
  3941. // A template-argument for a template-parameter which is a
  3942. // type shall be a type-id.
  3943. ArgType = Arg.getAsType();
  3944. TSI = AL.getTypeSourceInfo();
  3945. break;
  3946. case TemplateArgument::Template:
  3947. case TemplateArgument::TemplateExpansion: {
  3948. // We have a template type parameter but the template argument
  3949. // is a template without any arguments.
  3950. SourceRange SR = AL.getSourceRange();
  3951. TemplateName Name = Arg.getAsTemplateOrTemplatePattern();
  3952. diagnoseMissingTemplateArguments(Name, SR.getEnd());
  3953. return true;
  3954. }
  3955. case TemplateArgument::Expression: {
  3956. // We have a template type parameter but the template argument is an
  3957. // expression; see if maybe it is missing the "typename" keyword.
  3958. CXXScopeSpec SS;
  3959. DeclarationNameInfo NameInfo;
  3960. if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
  3961. SS.Adopt(ArgExpr->getQualifierLoc());
  3962. NameInfo = ArgExpr->getNameInfo();
  3963. } else if (DependentScopeDeclRefExpr *ArgExpr =
  3964. dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
  3965. SS.Adopt(ArgExpr->getQualifierLoc());
  3966. NameInfo = ArgExpr->getNameInfo();
  3967. } else if (CXXDependentScopeMemberExpr *ArgExpr =
  3968. dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
  3969. if (ArgExpr->isImplicitAccess()) {
  3970. SS.Adopt(ArgExpr->getQualifierLoc());
  3971. NameInfo = ArgExpr->getMemberNameInfo();
  3972. }
  3973. }
  3974. if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
  3975. LookupResult Result(*this, NameInfo, LookupOrdinaryName);
  3976. LookupParsedName(Result, CurScope, &SS);
  3977. if (Result.getAsSingle<TypeDecl>() ||
  3978. Result.getResultKind() ==
  3979. LookupResult::NotFoundInCurrentInstantiation) {
  3980. // Suggest that the user add 'typename' before the NNS.
  3981. SourceLocation Loc = AL.getSourceRange().getBegin();
  3982. Diag(Loc, getLangOpts().MSVCCompat
  3983. ? diag::ext_ms_template_type_arg_missing_typename
  3984. : diag::err_template_arg_must_be_type_suggest)
  3985. << FixItHint::CreateInsertion(Loc, "typename ");
  3986. Diag(Param->getLocation(), diag::note_template_param_here);
  3987. // Recover by synthesizing a type using the location information that we
  3988. // already have.
  3989. ArgType =
  3990. Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
  3991. TypeLocBuilder TLB;
  3992. DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
  3993. TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
  3994. TL.setQualifierLoc(SS.getWithLocInContext(Context));
  3995. TL.setNameLoc(NameInfo.getLoc());
  3996. TSI = TLB.getTypeSourceInfo(Context, ArgType);
  3997. // Overwrite our input TemplateArgumentLoc so that we can recover
  3998. // properly.
  3999. AL = TemplateArgumentLoc(TemplateArgument(ArgType),
  4000. TemplateArgumentLocInfo(TSI));
  4001. break;
  4002. }
  4003. }
  4004. // fallthrough
  4005. LLVM_FALLTHROUGH;
  4006. }
  4007. default: {
  4008. // We have a template type parameter but the template argument
  4009. // is not a type.
  4010. SourceRange SR = AL.getSourceRange();
  4011. Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
  4012. Diag(Param->getLocation(), diag::note_template_param_here);
  4013. return true;
  4014. }
  4015. }
  4016. if (CheckTemplateArgument(Param, TSI))
  4017. return true;
  4018. // Add the converted template type argument.
  4019. ArgType = Context.getCanonicalType(ArgType);
  4020. // Objective-C ARC:
  4021. // If an explicitly-specified template argument type is a lifetime type
  4022. // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
  4023. if (getLangOpts().ObjCAutoRefCount &&
  4024. ArgType->isObjCLifetimeType() &&
  4025. !ArgType.getObjCLifetime()) {
  4026. Qualifiers Qs;
  4027. Qs.setObjCLifetime(Qualifiers::OCL_Strong);
  4028. ArgType = Context.getQualifiedType(ArgType, Qs);
  4029. }
  4030. Converted.push_back(TemplateArgument(ArgType));
  4031. return false;
  4032. }
  4033. /// Substitute template arguments into the default template argument for
  4034. /// the given template type parameter.
  4035. ///
  4036. /// \param SemaRef the semantic analysis object for which we are performing
  4037. /// the substitution.
  4038. ///
  4039. /// \param Template the template that we are synthesizing template arguments
  4040. /// for.
  4041. ///
  4042. /// \param TemplateLoc the location of the template name that started the
  4043. /// template-id we are checking.
  4044. ///
  4045. /// \param RAngleLoc the location of the right angle bracket ('>') that
  4046. /// terminates the template-id.
  4047. ///
  4048. /// \param Param the template template parameter whose default we are
  4049. /// substituting into.
  4050. ///
  4051. /// \param Converted the list of template arguments provided for template
  4052. /// parameters that precede \p Param in the template parameter list.
  4053. /// \returns the substituted template argument, or NULL if an error occurred.
  4054. static TypeSourceInfo *
  4055. SubstDefaultTemplateArgument(Sema &SemaRef,
  4056. TemplateDecl *Template,
  4057. SourceLocation TemplateLoc,
  4058. SourceLocation RAngleLoc,
  4059. TemplateTypeParmDecl *Param,
  4060. SmallVectorImpl<TemplateArgument> &Converted) {
  4061. TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
  4062. // If the argument type is dependent, instantiate it now based
  4063. // on the previously-computed template arguments.
  4064. if (ArgType->getType()->isInstantiationDependentType()) {
  4065. Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
  4066. Param, Template, Converted,
  4067. SourceRange(TemplateLoc, RAngleLoc));
  4068. if (Inst.isInvalid())
  4069. return nullptr;
  4070. TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
  4071. // Only substitute for the innermost template argument list.
  4072. MultiLevelTemplateArgumentList TemplateArgLists;
  4073. TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
  4074. for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
  4075. TemplateArgLists.addOuterTemplateArguments(None);
  4076. Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
  4077. ArgType =
  4078. SemaRef.SubstType(ArgType, TemplateArgLists,
  4079. Param->getDefaultArgumentLoc(), Param->getDeclName());
  4080. }
  4081. return ArgType;
  4082. }
  4083. /// Substitute template arguments into the default template argument for
  4084. /// the given non-type template parameter.
  4085. ///
  4086. /// \param SemaRef the semantic analysis object for which we are performing
  4087. /// the substitution.
  4088. ///
  4089. /// \param Template the template that we are synthesizing template arguments
  4090. /// for.
  4091. ///
  4092. /// \param TemplateLoc the location of the template name that started the
  4093. /// template-id we are checking.
  4094. ///
  4095. /// \param RAngleLoc the location of the right angle bracket ('>') that
  4096. /// terminates the template-id.
  4097. ///
  4098. /// \param Param the non-type template parameter whose default we are
  4099. /// substituting into.
  4100. ///
  4101. /// \param Converted the list of template arguments provided for template
  4102. /// parameters that precede \p Param in the template parameter list.
  4103. ///
  4104. /// \returns the substituted template argument, or NULL if an error occurred.
  4105. static ExprResult
  4106. SubstDefaultTemplateArgument(Sema &SemaRef,
  4107. TemplateDecl *Template,
  4108. SourceLocation TemplateLoc,
  4109. SourceLocation RAngleLoc,
  4110. NonTypeTemplateParmDecl *Param,
  4111. SmallVectorImpl<TemplateArgument> &Converted) {
  4112. Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
  4113. Param, Template, Converted,
  4114. SourceRange(TemplateLoc, RAngleLoc));
  4115. if (Inst.isInvalid())
  4116. return ExprError();
  4117. TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
  4118. // Only substitute for the innermost template argument list.
  4119. MultiLevelTemplateArgumentList TemplateArgLists;
  4120. TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
  4121. for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
  4122. TemplateArgLists.addOuterTemplateArguments(None);
  4123. Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
  4124. EnterExpressionEvaluationContext ConstantEvaluated(
  4125. SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  4126. return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
  4127. }
  4128. /// Substitute template arguments into the default template argument for
  4129. /// the given template template parameter.
  4130. ///
  4131. /// \param SemaRef the semantic analysis object for which we are performing
  4132. /// the substitution.
  4133. ///
  4134. /// \param Template the template that we are synthesizing template arguments
  4135. /// for.
  4136. ///
  4137. /// \param TemplateLoc the location of the template name that started the
  4138. /// template-id we are checking.
  4139. ///
  4140. /// \param RAngleLoc the location of the right angle bracket ('>') that
  4141. /// terminates the template-id.
  4142. ///
  4143. /// \param Param the template template parameter whose default we are
  4144. /// substituting into.
  4145. ///
  4146. /// \param Converted the list of template arguments provided for template
  4147. /// parameters that precede \p Param in the template parameter list.
  4148. ///
  4149. /// \param QualifierLoc Will be set to the nested-name-specifier (with
  4150. /// source-location information) that precedes the template name.
  4151. ///
  4152. /// \returns the substituted template argument, or NULL if an error occurred.
  4153. static TemplateName
  4154. SubstDefaultTemplateArgument(Sema &SemaRef,
  4155. TemplateDecl *Template,
  4156. SourceLocation TemplateLoc,
  4157. SourceLocation RAngleLoc,
  4158. TemplateTemplateParmDecl *Param,
  4159. SmallVectorImpl<TemplateArgument> &Converted,
  4160. NestedNameSpecifierLoc &QualifierLoc) {
  4161. Sema::InstantiatingTemplate Inst(
  4162. SemaRef, TemplateLoc, TemplateParameter(Param), Template, Converted,
  4163. SourceRange(TemplateLoc, RAngleLoc));
  4164. if (Inst.isInvalid())
  4165. return TemplateName();
  4166. TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
  4167. // Only substitute for the innermost template argument list.
  4168. MultiLevelTemplateArgumentList TemplateArgLists;
  4169. TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
  4170. for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
  4171. TemplateArgLists.addOuterTemplateArguments(None);
  4172. Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
  4173. // Substitute into the nested-name-specifier first,
  4174. QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
  4175. if (QualifierLoc) {
  4176. QualifierLoc =
  4177. SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
  4178. if (!QualifierLoc)
  4179. return TemplateName();
  4180. }
  4181. return SemaRef.SubstTemplateName(
  4182. QualifierLoc,
  4183. Param->getDefaultArgument().getArgument().getAsTemplate(),
  4184. Param->getDefaultArgument().getTemplateNameLoc(),
  4185. TemplateArgLists);
  4186. }
  4187. /// If the given template parameter has a default template
  4188. /// argument, substitute into that default template argument and
  4189. /// return the corresponding template argument.
  4190. TemplateArgumentLoc
  4191. Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
  4192. SourceLocation TemplateLoc,
  4193. SourceLocation RAngleLoc,
  4194. Decl *Param,
  4195. SmallVectorImpl<TemplateArgument>
  4196. &Converted,
  4197. bool &HasDefaultArg) {
  4198. HasDefaultArg = false;
  4199. if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
  4200. if (!hasVisibleDefaultArgument(TypeParm))
  4201. return TemplateArgumentLoc();
  4202. HasDefaultArg = true;
  4203. TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
  4204. TemplateLoc,
  4205. RAngleLoc,
  4206. TypeParm,
  4207. Converted);
  4208. if (DI)
  4209. return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
  4210. return TemplateArgumentLoc();
  4211. }
  4212. if (NonTypeTemplateParmDecl *NonTypeParm
  4213. = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
  4214. if (!hasVisibleDefaultArgument(NonTypeParm))
  4215. return TemplateArgumentLoc();
  4216. HasDefaultArg = true;
  4217. ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
  4218. TemplateLoc,
  4219. RAngleLoc,
  4220. NonTypeParm,
  4221. Converted);
  4222. if (Arg.isInvalid())
  4223. return TemplateArgumentLoc();
  4224. Expr *ArgE = Arg.getAs<Expr>();
  4225. return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
  4226. }
  4227. TemplateTemplateParmDecl *TempTempParm
  4228. = cast<TemplateTemplateParmDecl>(Param);
  4229. if (!hasVisibleDefaultArgument(TempTempParm))
  4230. return TemplateArgumentLoc();
  4231. HasDefaultArg = true;
  4232. NestedNameSpecifierLoc QualifierLoc;
  4233. TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
  4234. TemplateLoc,
  4235. RAngleLoc,
  4236. TempTempParm,
  4237. Converted,
  4238. QualifierLoc);
  4239. if (TName.isNull())
  4240. return TemplateArgumentLoc();
  4241. return TemplateArgumentLoc(TemplateArgument(TName),
  4242. TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
  4243. TempTempParm->getDefaultArgument().getTemplateNameLoc());
  4244. }
  4245. /// Convert a template-argument that we parsed as a type into a template, if
  4246. /// possible. C++ permits injected-class-names to perform dual service as
  4247. /// template template arguments and as template type arguments.
  4248. static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(TypeLoc TLoc) {
  4249. // Extract and step over any surrounding nested-name-specifier.
  4250. NestedNameSpecifierLoc QualLoc;
  4251. if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
  4252. if (ETLoc.getTypePtr()->getKeyword() != ETK_None)
  4253. return TemplateArgumentLoc();
  4254. QualLoc = ETLoc.getQualifierLoc();
  4255. TLoc = ETLoc.getNamedTypeLoc();
  4256. }
  4257. // If this type was written as an injected-class-name, it can be used as a
  4258. // template template argument.
  4259. if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
  4260. return TemplateArgumentLoc(InjLoc.getTypePtr()->getTemplateName(),
  4261. QualLoc, InjLoc.getNameLoc());
  4262. // If this type was written as an injected-class-name, it may have been
  4263. // converted to a RecordType during instantiation. If the RecordType is
  4264. // *not* wrapped in a TemplateSpecializationType and denotes a class
  4265. // template specialization, it must have come from an injected-class-name.
  4266. if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
  4267. if (auto *CTSD =
  4268. dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
  4269. return TemplateArgumentLoc(TemplateName(CTSD->getSpecializedTemplate()),
  4270. QualLoc, RecLoc.getNameLoc());
  4271. return TemplateArgumentLoc();
  4272. }
  4273. /// Check that the given template argument corresponds to the given
  4274. /// template parameter.
  4275. ///
  4276. /// \param Param The template parameter against which the argument will be
  4277. /// checked.
  4278. ///
  4279. /// \param Arg The template argument, which may be updated due to conversions.
  4280. ///
  4281. /// \param Template The template in which the template argument resides.
  4282. ///
  4283. /// \param TemplateLoc The location of the template name for the template
  4284. /// whose argument list we're matching.
  4285. ///
  4286. /// \param RAngleLoc The location of the right angle bracket ('>') that closes
  4287. /// the template argument list.
  4288. ///
  4289. /// \param ArgumentPackIndex The index into the argument pack where this
  4290. /// argument will be placed. Only valid if the parameter is a parameter pack.
  4291. ///
  4292. /// \param Converted The checked, converted argument will be added to the
  4293. /// end of this small vector.
  4294. ///
  4295. /// \param CTAK Describes how we arrived at this particular template argument:
  4296. /// explicitly written, deduced, etc.
  4297. ///
  4298. /// \returns true on error, false otherwise.
  4299. bool Sema::CheckTemplateArgument(NamedDecl *Param,
  4300. TemplateArgumentLoc &Arg,
  4301. NamedDecl *Template,
  4302. SourceLocation TemplateLoc,
  4303. SourceLocation RAngleLoc,
  4304. unsigned ArgumentPackIndex,
  4305. SmallVectorImpl<TemplateArgument> &Converted,
  4306. CheckTemplateArgumentKind CTAK) {
  4307. // Check template type parameters.
  4308. if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
  4309. return CheckTemplateTypeArgument(TTP, Arg, Converted);
  4310. // Check non-type template parameters.
  4311. if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
  4312. // Do substitution on the type of the non-type template parameter
  4313. // with the template arguments we've seen thus far. But if the
  4314. // template has a dependent context then we cannot substitute yet.
  4315. QualType NTTPType = NTTP->getType();
  4316. if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
  4317. NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
  4318. // FIXME: Do we need to substitute into parameters here if they're
  4319. // instantiation-dependent but not dependent?
  4320. if (NTTPType->isDependentType() &&
  4321. !isa<TemplateTemplateParmDecl>(Template) &&
  4322. !Template->getDeclContext()->isDependentContext()) {
  4323. // Do substitution on the type of the non-type template parameter.
  4324. InstantiatingTemplate Inst(*this, TemplateLoc, Template,
  4325. NTTP, Converted,
  4326. SourceRange(TemplateLoc, RAngleLoc));
  4327. if (Inst.isInvalid())
  4328. return true;
  4329. TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
  4330. Converted);
  4331. // If the parameter is a pack expansion, expand this slice of the pack.
  4332. if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
  4333. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this,
  4334. ArgumentPackIndex);
  4335. NTTPType = SubstType(PET->getPattern(),
  4336. MultiLevelTemplateArgumentList(TemplateArgs),
  4337. NTTP->getLocation(),
  4338. NTTP->getDeclName());
  4339. } else {
  4340. NTTPType = SubstType(NTTPType,
  4341. MultiLevelTemplateArgumentList(TemplateArgs),
  4342. NTTP->getLocation(),
  4343. NTTP->getDeclName());
  4344. }
  4345. // If that worked, check the non-type template parameter type
  4346. // for validity.
  4347. if (!NTTPType.isNull())
  4348. NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
  4349. NTTP->getLocation());
  4350. if (NTTPType.isNull())
  4351. return true;
  4352. }
  4353. switch (Arg.getArgument().getKind()) {
  4354. case TemplateArgument::Null:
  4355. llvm_unreachable("Should never see a NULL template argument here");
  4356. case TemplateArgument::Expression: {
  4357. TemplateArgument Result;
  4358. unsigned CurSFINAEErrors = NumSFINAEErrors;
  4359. ExprResult Res =
  4360. CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
  4361. Result, CTAK);
  4362. if (Res.isInvalid())
  4363. return true;
  4364. // If the current template argument causes an error, give up now.
  4365. if (CurSFINAEErrors < NumSFINAEErrors)
  4366. return true;
  4367. // If the resulting expression is new, then use it in place of the
  4368. // old expression in the template argument.
  4369. if (Res.get() != Arg.getArgument().getAsExpr()) {
  4370. TemplateArgument TA(Res.get());
  4371. Arg = TemplateArgumentLoc(TA, Res.get());
  4372. }
  4373. Converted.push_back(Result);
  4374. break;
  4375. }
  4376. case TemplateArgument::Declaration:
  4377. case TemplateArgument::Integral:
  4378. case TemplateArgument::NullPtr:
  4379. // We've already checked this template argument, so just copy
  4380. // it to the list of converted arguments.
  4381. Converted.push_back(Arg.getArgument());
  4382. break;
  4383. case TemplateArgument::Template:
  4384. case TemplateArgument::TemplateExpansion:
  4385. // We were given a template template argument. It may not be ill-formed;
  4386. // see below.
  4387. if (DependentTemplateName *DTN
  4388. = Arg.getArgument().getAsTemplateOrTemplatePattern()
  4389. .getAsDependentTemplateName()) {
  4390. // We have a template argument such as \c T::template X, which we
  4391. // parsed as a template template argument. However, since we now
  4392. // know that we need a non-type template argument, convert this
  4393. // template name into an expression.
  4394. DeclarationNameInfo NameInfo(DTN->getIdentifier(),
  4395. Arg.getTemplateNameLoc());
  4396. CXXScopeSpec SS;
  4397. SS.Adopt(Arg.getTemplateQualifierLoc());
  4398. // FIXME: the template-template arg was a DependentTemplateName,
  4399. // so it was provided with a template keyword. However, its source
  4400. // location is not stored in the template argument structure.
  4401. SourceLocation TemplateKWLoc;
  4402. ExprResult E = DependentScopeDeclRefExpr::Create(
  4403. Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
  4404. nullptr);
  4405. // If we parsed the template argument as a pack expansion, create a
  4406. // pack expansion expression.
  4407. if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
  4408. E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
  4409. if (E.isInvalid())
  4410. return true;
  4411. }
  4412. TemplateArgument Result;
  4413. E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
  4414. if (E.isInvalid())
  4415. return true;
  4416. Converted.push_back(Result);
  4417. break;
  4418. }
  4419. // We have a template argument that actually does refer to a class
  4420. // template, alias template, or template template parameter, and
  4421. // therefore cannot be a non-type template argument.
  4422. Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
  4423. << Arg.getSourceRange();
  4424. Diag(Param->getLocation(), diag::note_template_param_here);
  4425. return true;
  4426. case TemplateArgument::Type: {
  4427. // We have a non-type template parameter but the template
  4428. // argument is a type.
  4429. // C++ [temp.arg]p2:
  4430. // In a template-argument, an ambiguity between a type-id and
  4431. // an expression is resolved to a type-id, regardless of the
  4432. // form of the corresponding template-parameter.
  4433. //
  4434. // We warn specifically about this case, since it can be rather
  4435. // confusing for users.
  4436. QualType T = Arg.getArgument().getAsType();
  4437. SourceRange SR = Arg.getSourceRange();
  4438. if (T->isFunctionType())
  4439. Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
  4440. else
  4441. Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
  4442. Diag(Param->getLocation(), diag::note_template_param_here);
  4443. return true;
  4444. }
  4445. case TemplateArgument::Pack:
  4446. llvm_unreachable("Caller must expand template argument packs");
  4447. }
  4448. return false;
  4449. }
  4450. // Check template template parameters.
  4451. TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
  4452. TemplateParameterList *Params = TempParm->getTemplateParameters();
  4453. if (TempParm->isExpandedParameterPack())
  4454. Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
  4455. // Substitute into the template parameter list of the template
  4456. // template parameter, since previously-supplied template arguments
  4457. // may appear within the template template parameter.
  4458. //
  4459. // FIXME: Skip this if the parameters aren't instantiation-dependent.
  4460. {
  4461. // Set up a template instantiation context.
  4462. LocalInstantiationScope Scope(*this);
  4463. InstantiatingTemplate Inst(*this, TemplateLoc, Template,
  4464. TempParm, Converted,
  4465. SourceRange(TemplateLoc, RAngleLoc));
  4466. if (Inst.isInvalid())
  4467. return true;
  4468. TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
  4469. Params = SubstTemplateParams(Params, CurContext,
  4470. MultiLevelTemplateArgumentList(TemplateArgs));
  4471. if (!Params)
  4472. return true;
  4473. }
  4474. // C++1z [temp.local]p1: (DR1004)
  4475. // When [the injected-class-name] is used [...] as a template-argument for
  4476. // a template template-parameter [...] it refers to the class template
  4477. // itself.
  4478. if (Arg.getArgument().getKind() == TemplateArgument::Type) {
  4479. TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
  4480. Arg.getTypeSourceInfo()->getTypeLoc());
  4481. if (!ConvertedArg.getArgument().isNull())
  4482. Arg = ConvertedArg;
  4483. }
  4484. switch (Arg.getArgument().getKind()) {
  4485. case TemplateArgument::Null:
  4486. llvm_unreachable("Should never see a NULL template argument here");
  4487. case TemplateArgument::Template:
  4488. case TemplateArgument::TemplateExpansion:
  4489. if (CheckTemplateTemplateArgument(Params, Arg))
  4490. return true;
  4491. Converted.push_back(Arg.getArgument());
  4492. break;
  4493. case TemplateArgument::Expression:
  4494. case TemplateArgument::Type:
  4495. // We have a template template parameter but the template
  4496. // argument does not refer to a template.
  4497. Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
  4498. << getLangOpts().CPlusPlus11;
  4499. return true;
  4500. case TemplateArgument::Declaration:
  4501. llvm_unreachable("Declaration argument with template template parameter");
  4502. case TemplateArgument::Integral:
  4503. llvm_unreachable("Integral argument with template template parameter");
  4504. case TemplateArgument::NullPtr:
  4505. llvm_unreachable("Null pointer argument with template template parameter");
  4506. case TemplateArgument::Pack:
  4507. llvm_unreachable("Caller must expand template argument packs");
  4508. }
  4509. return false;
  4510. }
  4511. /// Check whether the template parameter is a pack expansion, and if so,
  4512. /// determine the number of parameters produced by that expansion. For instance:
  4513. ///
  4514. /// \code
  4515. /// template<typename ...Ts> struct A {
  4516. /// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
  4517. /// };
  4518. /// \endcode
  4519. ///
  4520. /// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
  4521. /// is not a pack expansion, so returns an empty Optional.
  4522. static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
  4523. if (NonTypeTemplateParmDecl *NTTP
  4524. = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
  4525. if (NTTP->isExpandedParameterPack())
  4526. return NTTP->getNumExpansionTypes();
  4527. }
  4528. if (TemplateTemplateParmDecl *TTP
  4529. = dyn_cast<TemplateTemplateParmDecl>(Param)) {
  4530. if (TTP->isExpandedParameterPack())
  4531. return TTP->getNumExpansionTemplateParameters();
  4532. }
  4533. return None;
  4534. }
  4535. /// Diagnose a missing template argument.
  4536. template<typename TemplateParmDecl>
  4537. static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
  4538. TemplateDecl *TD,
  4539. const TemplateParmDecl *D,
  4540. TemplateArgumentListInfo &Args) {
  4541. // Dig out the most recent declaration of the template parameter; there may be
  4542. // declarations of the template that are more recent than TD.
  4543. D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
  4544. ->getTemplateParameters()
  4545. ->getParam(D->getIndex()));
  4546. // If there's a default argument that's not visible, diagnose that we're
  4547. // missing a module import.
  4548. llvm::SmallVector<Module*, 8> Modules;
  4549. if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
  4550. S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
  4551. D->getDefaultArgumentLoc(), Modules,
  4552. Sema::MissingImportKind::DefaultArgument,
  4553. /*Recover*/true);
  4554. return true;
  4555. }
  4556. // FIXME: If there's a more recent default argument that *is* visible,
  4557. // diagnose that it was declared too late.
  4558. TemplateParameterList *Params = TD->getTemplateParameters();
  4559. S.Diag(Loc, diag::err_template_arg_list_different_arity)
  4560. << /*not enough args*/0
  4561. << (int)S.getTemplateNameKindForDiagnostics(TemplateName(TD))
  4562. << TD;
  4563. S.Diag(TD->getLocation(), diag::note_template_decl_here)
  4564. << Params->getSourceRange();
  4565. return true;
  4566. }
  4567. /// Check that the given template argument list is well-formed
  4568. /// for specializing the given template.
  4569. bool Sema::CheckTemplateArgumentList(
  4570. TemplateDecl *Template, SourceLocation TemplateLoc,
  4571. TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
  4572. SmallVectorImpl<TemplateArgument> &Converted,
  4573. bool UpdateArgsWithConversions) {
  4574. // Make a copy of the template arguments for processing. Only make the
  4575. // changes at the end when successful in matching the arguments to the
  4576. // template.
  4577. TemplateArgumentListInfo NewArgs = TemplateArgs;
  4578. // Make sure we get the template parameter list from the most
  4579. // recentdeclaration, since that is the only one that has is guaranteed to
  4580. // have all the default template argument information.
  4581. TemplateParameterList *Params =
  4582. cast<TemplateDecl>(Template->getMostRecentDecl())
  4583. ->getTemplateParameters();
  4584. SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
  4585. // C++ [temp.arg]p1:
  4586. // [...] The type and form of each template-argument specified in
  4587. // a template-id shall match the type and form specified for the
  4588. // corresponding parameter declared by the template in its
  4589. // template-parameter-list.
  4590. bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
  4591. SmallVector<TemplateArgument, 2> ArgumentPack;
  4592. unsigned ArgIdx = 0, NumArgs = NewArgs.size();
  4593. LocalInstantiationScope InstScope(*this, true);
  4594. for (TemplateParameterList::iterator Param = Params->begin(),
  4595. ParamEnd = Params->end();
  4596. Param != ParamEnd; /* increment in loop */) {
  4597. // If we have an expanded parameter pack, make sure we don't have too
  4598. // many arguments.
  4599. if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
  4600. if (*Expansions == ArgumentPack.size()) {
  4601. // We're done with this parameter pack. Pack up its arguments and add
  4602. // them to the list.
  4603. Converted.push_back(
  4604. TemplateArgument::CreatePackCopy(Context, ArgumentPack));
  4605. ArgumentPack.clear();
  4606. // This argument is assigned to the next parameter.
  4607. ++Param;
  4608. continue;
  4609. } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
  4610. // Not enough arguments for this parameter pack.
  4611. Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
  4612. << /*not enough args*/0
  4613. << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
  4614. << Template;
  4615. Diag(Template->getLocation(), diag::note_template_decl_here)
  4616. << Params->getSourceRange();
  4617. return true;
  4618. }
  4619. }
  4620. if (ArgIdx < NumArgs) {
  4621. // Check the template argument we were given.
  4622. if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
  4623. TemplateLoc, RAngleLoc,
  4624. ArgumentPack.size(), Converted))
  4625. return true;
  4626. bool PackExpansionIntoNonPack =
  4627. NewArgs[ArgIdx].getArgument().isPackExpansion() &&
  4628. (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
  4629. if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
  4630. // Core issue 1430: we have a pack expansion as an argument to an
  4631. // alias template, and it's not part of a parameter pack. This
  4632. // can't be canonicalized, so reject it now.
  4633. Diag(NewArgs[ArgIdx].getLocation(),
  4634. diag::err_alias_template_expansion_into_fixed_list)
  4635. << NewArgs[ArgIdx].getSourceRange();
  4636. Diag((*Param)->getLocation(), diag::note_template_param_here);
  4637. return true;
  4638. }
  4639. // We're now done with this argument.
  4640. ++ArgIdx;
  4641. if ((*Param)->isTemplateParameterPack()) {
  4642. // The template parameter was a template parameter pack, so take the
  4643. // deduced argument and place it on the argument pack. Note that we
  4644. // stay on the same template parameter so that we can deduce more
  4645. // arguments.
  4646. ArgumentPack.push_back(Converted.pop_back_val());
  4647. } else {
  4648. // Move to the next template parameter.
  4649. ++Param;
  4650. }
  4651. // If we just saw a pack expansion into a non-pack, then directly convert
  4652. // the remaining arguments, because we don't know what parameters they'll
  4653. // match up with.
  4654. if (PackExpansionIntoNonPack) {
  4655. if (!ArgumentPack.empty()) {
  4656. // If we were part way through filling in an expanded parameter pack,
  4657. // fall back to just producing individual arguments.
  4658. Converted.insert(Converted.end(),
  4659. ArgumentPack.begin(), ArgumentPack.end());
  4660. ArgumentPack.clear();
  4661. }
  4662. while (ArgIdx < NumArgs) {
  4663. Converted.push_back(NewArgs[ArgIdx].getArgument());
  4664. ++ArgIdx;
  4665. }
  4666. return false;
  4667. }
  4668. continue;
  4669. }
  4670. // If we're checking a partial template argument list, we're done.
  4671. if (PartialTemplateArgs) {
  4672. if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
  4673. Converted.push_back(
  4674. TemplateArgument::CreatePackCopy(Context, ArgumentPack));
  4675. return false;
  4676. }
  4677. // If we have a template parameter pack with no more corresponding
  4678. // arguments, just break out now and we'll fill in the argument pack below.
  4679. if ((*Param)->isTemplateParameterPack()) {
  4680. assert(!getExpandedPackSize(*Param) &&
  4681. "Should have dealt with this already");
  4682. // A non-expanded parameter pack before the end of the parameter list
  4683. // only occurs for an ill-formed template parameter list, unless we've
  4684. // got a partial argument list for a function template, so just bail out.
  4685. if (Param + 1 != ParamEnd)
  4686. return true;
  4687. Converted.push_back(
  4688. TemplateArgument::CreatePackCopy(Context, ArgumentPack));
  4689. ArgumentPack.clear();
  4690. ++Param;
  4691. continue;
  4692. }
  4693. // Check whether we have a default argument.
  4694. TemplateArgumentLoc Arg;
  4695. // Retrieve the default template argument from the template
  4696. // parameter. For each kind of template parameter, we substitute the
  4697. // template arguments provided thus far and any "outer" template arguments
  4698. // (when the template parameter was part of a nested template) into
  4699. // the default argument.
  4700. if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
  4701. if (!hasVisibleDefaultArgument(TTP))
  4702. return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
  4703. NewArgs);
  4704. TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
  4705. Template,
  4706. TemplateLoc,
  4707. RAngleLoc,
  4708. TTP,
  4709. Converted);
  4710. if (!ArgType)
  4711. return true;
  4712. Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
  4713. ArgType);
  4714. } else if (NonTypeTemplateParmDecl *NTTP
  4715. = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
  4716. if (!hasVisibleDefaultArgument(NTTP))
  4717. return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
  4718. NewArgs);
  4719. ExprResult E = SubstDefaultTemplateArgument(*this, Template,
  4720. TemplateLoc,
  4721. RAngleLoc,
  4722. NTTP,
  4723. Converted);
  4724. if (E.isInvalid())
  4725. return true;
  4726. Expr *Ex = E.getAs<Expr>();
  4727. Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
  4728. } else {
  4729. TemplateTemplateParmDecl *TempParm
  4730. = cast<TemplateTemplateParmDecl>(*Param);
  4731. if (!hasVisibleDefaultArgument(TempParm))
  4732. return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
  4733. NewArgs);
  4734. NestedNameSpecifierLoc QualifierLoc;
  4735. TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
  4736. TemplateLoc,
  4737. RAngleLoc,
  4738. TempParm,
  4739. Converted,
  4740. QualifierLoc);
  4741. if (Name.isNull())
  4742. return true;
  4743. Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
  4744. TempParm->getDefaultArgument().getTemplateNameLoc());
  4745. }
  4746. // Introduce an instantiation record that describes where we are using
  4747. // the default template argument. We're not actually instantiating a
  4748. // template here, we just create this object to put a note into the
  4749. // context stack.
  4750. InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
  4751. SourceRange(TemplateLoc, RAngleLoc));
  4752. if (Inst.isInvalid())
  4753. return true;
  4754. // Check the default template argument.
  4755. if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
  4756. RAngleLoc, 0, Converted))
  4757. return true;
  4758. // Core issue 150 (assumed resolution): if this is a template template
  4759. // parameter, keep track of the default template arguments from the
  4760. // template definition.
  4761. if (isTemplateTemplateParameter)
  4762. NewArgs.addArgument(Arg);
  4763. // Move to the next template parameter and argument.
  4764. ++Param;
  4765. ++ArgIdx;
  4766. }
  4767. // If we're performing a partial argument substitution, allow any trailing
  4768. // pack expansions; they might be empty. This can happen even if
  4769. // PartialTemplateArgs is false (the list of arguments is complete but
  4770. // still dependent).
  4771. if (ArgIdx < NumArgs && CurrentInstantiationScope &&
  4772. CurrentInstantiationScope->getPartiallySubstitutedPack()) {
  4773. while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
  4774. Converted.push_back(NewArgs[ArgIdx++].getArgument());
  4775. }
  4776. // If we have any leftover arguments, then there were too many arguments.
  4777. // Complain and fail.
  4778. if (ArgIdx < NumArgs) {
  4779. Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
  4780. << /*too many args*/1
  4781. << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
  4782. << Template
  4783. << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
  4784. Diag(Template->getLocation(), diag::note_template_decl_here)
  4785. << Params->getSourceRange();
  4786. return true;
  4787. }
  4788. // No problems found with the new argument list, propagate changes back
  4789. // to caller.
  4790. if (UpdateArgsWithConversions)
  4791. TemplateArgs = std::move(NewArgs);
  4792. return false;
  4793. }
  4794. namespace {
  4795. class UnnamedLocalNoLinkageFinder
  4796. : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
  4797. {
  4798. Sema &S;
  4799. SourceRange SR;
  4800. typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
  4801. public:
  4802. UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
  4803. bool Visit(QualType T) {
  4804. return T.isNull() ? false : inherited::Visit(T.getTypePtr());
  4805. }
  4806. #define TYPE(Class, Parent) \
  4807. bool Visit##Class##Type(const Class##Type *);
  4808. #define ABSTRACT_TYPE(Class, Parent) \
  4809. bool Visit##Class##Type(const Class##Type *) { return false; }
  4810. #define NON_CANONICAL_TYPE(Class, Parent) \
  4811. bool Visit##Class##Type(const Class##Type *) { return false; }
  4812. #include "clang/AST/TypeNodes.def"
  4813. bool VisitTagDecl(const TagDecl *Tag);
  4814. bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
  4815. };
  4816. } // end anonymous namespace
  4817. bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
  4818. return false;
  4819. }
  4820. bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
  4821. return Visit(T->getElementType());
  4822. }
  4823. bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
  4824. return Visit(T->getPointeeType());
  4825. }
  4826. bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
  4827. const BlockPointerType* T) {
  4828. return Visit(T->getPointeeType());
  4829. }
  4830. bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
  4831. const LValueReferenceType* T) {
  4832. return Visit(T->getPointeeType());
  4833. }
  4834. bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
  4835. const RValueReferenceType* T) {
  4836. return Visit(T->getPointeeType());
  4837. }
  4838. bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
  4839. const MemberPointerType* T) {
  4840. return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
  4841. }
  4842. bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
  4843. const ConstantArrayType* T) {
  4844. return Visit(T->getElementType());
  4845. }
  4846. bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
  4847. const IncompleteArrayType* T) {
  4848. return Visit(T->getElementType());
  4849. }
  4850. bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
  4851. const VariableArrayType* T) {
  4852. return Visit(T->getElementType());
  4853. }
  4854. bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
  4855. const DependentSizedArrayType* T) {
  4856. return Visit(T->getElementType());
  4857. }
  4858. bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
  4859. const DependentSizedExtVectorType* T) {
  4860. return Visit(T->getElementType());
  4861. }
  4862. bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
  4863. const DependentAddressSpaceType *T) {
  4864. return Visit(T->getPointeeType());
  4865. }
  4866. bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
  4867. return Visit(T->getElementType());
  4868. }
  4869. bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
  4870. const DependentVectorType *T) {
  4871. return Visit(T->getElementType());
  4872. }
  4873. bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
  4874. return Visit(T->getElementType());
  4875. }
  4876. bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
  4877. const FunctionProtoType* T) {
  4878. for (const auto &A : T->param_types()) {
  4879. if (Visit(A))
  4880. return true;
  4881. }
  4882. return Visit(T->getReturnType());
  4883. }
  4884. bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
  4885. const FunctionNoProtoType* T) {
  4886. return Visit(T->getReturnType());
  4887. }
  4888. bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
  4889. const UnresolvedUsingType*) {
  4890. return false;
  4891. }
  4892. bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
  4893. return false;
  4894. }
  4895. bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
  4896. return Visit(T->getUnderlyingType());
  4897. }
  4898. bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
  4899. return false;
  4900. }
  4901. bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
  4902. const UnaryTransformType*) {
  4903. return false;
  4904. }
  4905. bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
  4906. return Visit(T->getDeducedType());
  4907. }
  4908. bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
  4909. const DeducedTemplateSpecializationType *T) {
  4910. return Visit(T->getDeducedType());
  4911. }
  4912. bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
  4913. return VisitTagDecl(T->getDecl());
  4914. }
  4915. bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
  4916. return VisitTagDecl(T->getDecl());
  4917. }
  4918. bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
  4919. const TemplateTypeParmType*) {
  4920. return false;
  4921. }
  4922. bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
  4923. const SubstTemplateTypeParmPackType *) {
  4924. return false;
  4925. }
  4926. bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
  4927. const TemplateSpecializationType*) {
  4928. return false;
  4929. }
  4930. bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
  4931. const InjectedClassNameType* T) {
  4932. return VisitTagDecl(T->getDecl());
  4933. }
  4934. bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
  4935. const DependentNameType* T) {
  4936. return VisitNestedNameSpecifier(T->getQualifier());
  4937. }
  4938. bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
  4939. const DependentTemplateSpecializationType* T) {
  4940. return VisitNestedNameSpecifier(T->getQualifier());
  4941. }
  4942. bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
  4943. const PackExpansionType* T) {
  4944. return Visit(T->getPattern());
  4945. }
  4946. bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
  4947. return false;
  4948. }
  4949. bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
  4950. const ObjCInterfaceType *) {
  4951. return false;
  4952. }
  4953. bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
  4954. const ObjCObjectPointerType *) {
  4955. return false;
  4956. }
  4957. bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
  4958. return Visit(T->getValueType());
  4959. }
  4960. bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
  4961. return false;
  4962. }
  4963. bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
  4964. if (Tag->getDeclContext()->isFunctionOrMethod()) {
  4965. S.Diag(SR.getBegin(),
  4966. S.getLangOpts().CPlusPlus11 ?
  4967. diag::warn_cxx98_compat_template_arg_local_type :
  4968. diag::ext_template_arg_local_type)
  4969. << S.Context.getTypeDeclType(Tag) << SR;
  4970. return true;
  4971. }
  4972. if (!Tag->hasNameForLinkage()) {
  4973. S.Diag(SR.getBegin(),
  4974. S.getLangOpts().CPlusPlus11 ?
  4975. diag::warn_cxx98_compat_template_arg_unnamed_type :
  4976. diag::ext_template_arg_unnamed_type) << SR;
  4977. S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
  4978. return true;
  4979. }
  4980. return false;
  4981. }
  4982. bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
  4983. NestedNameSpecifier *NNS) {
  4984. if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
  4985. return true;
  4986. switch (NNS->getKind()) {
  4987. case NestedNameSpecifier::Identifier:
  4988. case NestedNameSpecifier::Namespace:
  4989. case NestedNameSpecifier::NamespaceAlias:
  4990. case NestedNameSpecifier::Global:
  4991. case NestedNameSpecifier::Super:
  4992. return false;
  4993. case NestedNameSpecifier::TypeSpec:
  4994. case NestedNameSpecifier::TypeSpecWithTemplate:
  4995. return Visit(QualType(NNS->getAsType(), 0));
  4996. }
  4997. llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
  4998. }
  4999. /// Check a template argument against its corresponding
  5000. /// template type parameter.
  5001. ///
  5002. /// This routine implements the semantics of C++ [temp.arg.type]. It
  5003. /// returns true if an error occurred, and false otherwise.
  5004. bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
  5005. TypeSourceInfo *ArgInfo) {
  5006. assert(ArgInfo && "invalid TypeSourceInfo");
  5007. QualType Arg = ArgInfo->getType();
  5008. SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
  5009. if (Arg->isVariablyModifiedType()) {
  5010. return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
  5011. } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
  5012. return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
  5013. }
  5014. // C++03 [temp.arg.type]p2:
  5015. // A local type, a type with no linkage, an unnamed type or a type
  5016. // compounded from any of these types shall not be used as a
  5017. // template-argument for a template type-parameter.
  5018. //
  5019. // C++11 allows these, and even in C++03 we allow them as an extension with
  5020. // a warning.
  5021. if (LangOpts.CPlusPlus11 || Arg->hasUnnamedOrLocalType()) {
  5022. UnnamedLocalNoLinkageFinder Finder(*this, SR);
  5023. (void)Finder.Visit(Context.getCanonicalType(Arg));
  5024. }
  5025. return false;
  5026. }
  5027. enum NullPointerValueKind {
  5028. NPV_NotNullPointer,
  5029. NPV_NullPointer,
  5030. NPV_Error
  5031. };
  5032. /// Determine whether the given template argument is a null pointer
  5033. /// value of the appropriate type.
  5034. static NullPointerValueKind
  5035. isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
  5036. QualType ParamType, Expr *Arg,
  5037. Decl *Entity = nullptr) {
  5038. if (Arg->isValueDependent() || Arg->isTypeDependent())
  5039. return NPV_NotNullPointer;
  5040. // dllimport'd entities aren't constant but are available inside of template
  5041. // arguments.
  5042. if (Entity && Entity->hasAttr<DLLImportAttr>())
  5043. return NPV_NotNullPointer;
  5044. if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
  5045. llvm_unreachable(
  5046. "Incomplete parameter type in isNullPointerValueTemplateArgument!");
  5047. if (!S.getLangOpts().CPlusPlus11)
  5048. return NPV_NotNullPointer;
  5049. // Determine whether we have a constant expression.
  5050. ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
  5051. if (ArgRV.isInvalid())
  5052. return NPV_Error;
  5053. Arg = ArgRV.get();
  5054. Expr::EvalResult EvalResult;
  5055. SmallVector<PartialDiagnosticAt, 8> Notes;
  5056. EvalResult.Diag = &Notes;
  5057. if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
  5058. EvalResult.HasSideEffects) {
  5059. SourceLocation DiagLoc = Arg->getExprLoc();
  5060. // If our only note is the usual "invalid subexpression" note, just point
  5061. // the caret at its location rather than producing an essentially
  5062. // redundant note.
  5063. if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
  5064. diag::note_invalid_subexpr_in_const_expr) {
  5065. DiagLoc = Notes[0].first;
  5066. Notes.clear();
  5067. }
  5068. S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
  5069. << Arg->getType() << Arg->getSourceRange();
  5070. for (unsigned I = 0, N = Notes.size(); I != N; ++I)
  5071. S.Diag(Notes[I].first, Notes[I].second);
  5072. S.Diag(Param->getLocation(), diag::note_template_param_here);
  5073. return NPV_Error;
  5074. }
  5075. // C++11 [temp.arg.nontype]p1:
  5076. // - an address constant expression of type std::nullptr_t
  5077. if (Arg->getType()->isNullPtrType())
  5078. return NPV_NullPointer;
  5079. // - a constant expression that evaluates to a null pointer value (4.10); or
  5080. // - a constant expression that evaluates to a null member pointer value
  5081. // (4.11); or
  5082. if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
  5083. (EvalResult.Val.isMemberPointer() &&
  5084. !EvalResult.Val.getMemberPointerDecl())) {
  5085. // If our expression has an appropriate type, we've succeeded.
  5086. bool ObjCLifetimeConversion;
  5087. if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
  5088. S.IsQualificationConversion(Arg->getType(), ParamType, false,
  5089. ObjCLifetimeConversion))
  5090. return NPV_NullPointer;
  5091. // The types didn't match, but we know we got a null pointer; complain,
  5092. // then recover as if the types were correct.
  5093. S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
  5094. << Arg->getType() << ParamType << Arg->getSourceRange();
  5095. S.Diag(Param->getLocation(), diag::note_template_param_here);
  5096. return NPV_NullPointer;
  5097. }
  5098. // If we don't have a null pointer value, but we do have a NULL pointer
  5099. // constant, suggest a cast to the appropriate type.
  5100. if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
  5101. std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
  5102. S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
  5103. << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
  5104. << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getEndLoc()),
  5105. ")");
  5106. S.Diag(Param->getLocation(), diag::note_template_param_here);
  5107. return NPV_NullPointer;
  5108. }
  5109. // FIXME: If we ever want to support general, address-constant expressions
  5110. // as non-type template arguments, we should return the ExprResult here to
  5111. // be interpreted by the caller.
  5112. return NPV_NotNullPointer;
  5113. }
  5114. /// Checks whether the given template argument is compatible with its
  5115. /// template parameter.
  5116. static bool CheckTemplateArgumentIsCompatibleWithParameter(
  5117. Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
  5118. Expr *Arg, QualType ArgType) {
  5119. bool ObjCLifetimeConversion;
  5120. if (ParamType->isPointerType() &&
  5121. !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
  5122. S.IsQualificationConversion(ArgType, ParamType, false,
  5123. ObjCLifetimeConversion)) {
  5124. // For pointer-to-object types, qualification conversions are
  5125. // permitted.
  5126. } else {
  5127. if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
  5128. if (!ParamRef->getPointeeType()->isFunctionType()) {
  5129. // C++ [temp.arg.nontype]p5b3:
  5130. // For a non-type template-parameter of type reference to
  5131. // object, no conversions apply. The type referred to by the
  5132. // reference may be more cv-qualified than the (otherwise
  5133. // identical) type of the template- argument. The
  5134. // template-parameter is bound directly to the
  5135. // template-argument, which shall be an lvalue.
  5136. // FIXME: Other qualifiers?
  5137. unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
  5138. unsigned ArgQuals = ArgType.getCVRQualifiers();
  5139. if ((ParamQuals | ArgQuals) != ParamQuals) {
  5140. S.Diag(Arg->getBeginLoc(),
  5141. diag::err_template_arg_ref_bind_ignores_quals)
  5142. << ParamType << Arg->getType() << Arg->getSourceRange();
  5143. S.Diag(Param->getLocation(), diag::note_template_param_here);
  5144. return true;
  5145. }
  5146. }
  5147. }
  5148. // At this point, the template argument refers to an object or
  5149. // function with external linkage. We now need to check whether the
  5150. // argument and parameter types are compatible.
  5151. if (!S.Context.hasSameUnqualifiedType(ArgType,
  5152. ParamType.getNonReferenceType())) {
  5153. // We can't perform this conversion or binding.
  5154. if (ParamType->isReferenceType())
  5155. S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
  5156. << ParamType << ArgIn->getType() << Arg->getSourceRange();
  5157. else
  5158. S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
  5159. << ArgIn->getType() << ParamType << Arg->getSourceRange();
  5160. S.Diag(Param->getLocation(), diag::note_template_param_here);
  5161. return true;
  5162. }
  5163. }
  5164. return false;
  5165. }
  5166. /// Checks whether the given template argument is the address
  5167. /// of an object or function according to C++ [temp.arg.nontype]p1.
  5168. static bool
  5169. CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
  5170. NonTypeTemplateParmDecl *Param,
  5171. QualType ParamType,
  5172. Expr *ArgIn,
  5173. TemplateArgument &Converted) {
  5174. bool Invalid = false;
  5175. Expr *Arg = ArgIn;
  5176. QualType ArgType = Arg->getType();
  5177. bool AddressTaken = false;
  5178. SourceLocation AddrOpLoc;
  5179. if (S.getLangOpts().MicrosoftExt) {
  5180. // Microsoft Visual C++ strips all casts, allows an arbitrary number of
  5181. // dereference and address-of operators.
  5182. Arg = Arg->IgnoreParenCasts();
  5183. bool ExtWarnMSTemplateArg = false;
  5184. UnaryOperatorKind FirstOpKind;
  5185. SourceLocation FirstOpLoc;
  5186. while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
  5187. UnaryOperatorKind UnOpKind = UnOp->getOpcode();
  5188. if (UnOpKind == UO_Deref)
  5189. ExtWarnMSTemplateArg = true;
  5190. if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
  5191. Arg = UnOp->getSubExpr()->IgnoreParenCasts();
  5192. if (!AddrOpLoc.isValid()) {
  5193. FirstOpKind = UnOpKind;
  5194. FirstOpLoc = UnOp->getOperatorLoc();
  5195. }
  5196. } else
  5197. break;
  5198. }
  5199. if (FirstOpLoc.isValid()) {
  5200. if (ExtWarnMSTemplateArg)
  5201. S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
  5202. << ArgIn->getSourceRange();
  5203. if (FirstOpKind == UO_AddrOf)
  5204. AddressTaken = true;
  5205. else if (Arg->getType()->isPointerType()) {
  5206. // We cannot let pointers get dereferenced here, that is obviously not a
  5207. // constant expression.
  5208. assert(FirstOpKind == UO_Deref);
  5209. S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
  5210. << Arg->getSourceRange();
  5211. }
  5212. }
  5213. } else {
  5214. // See through any implicit casts we added to fix the type.
  5215. Arg = Arg->IgnoreImpCasts();
  5216. // C++ [temp.arg.nontype]p1:
  5217. //
  5218. // A template-argument for a non-type, non-template
  5219. // template-parameter shall be one of: [...]
  5220. //
  5221. // -- the address of an object or function with external
  5222. // linkage, including function templates and function
  5223. // template-ids but excluding non-static class members,
  5224. // expressed as & id-expression where the & is optional if
  5225. // the name refers to a function or array, or if the
  5226. // corresponding template-parameter is a reference; or
  5227. // In C++98/03 mode, give an extension warning on any extra parentheses.
  5228. // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
  5229. bool ExtraParens = false;
  5230. while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
  5231. if (!Invalid && !ExtraParens) {
  5232. S.Diag(Arg->getBeginLoc(),
  5233. S.getLangOpts().CPlusPlus11
  5234. ? diag::warn_cxx98_compat_template_arg_extra_parens
  5235. : diag::ext_template_arg_extra_parens)
  5236. << Arg->getSourceRange();
  5237. ExtraParens = true;
  5238. }
  5239. Arg = Parens->getSubExpr();
  5240. }
  5241. while (SubstNonTypeTemplateParmExpr *subst =
  5242. dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
  5243. Arg = subst->getReplacement()->IgnoreImpCasts();
  5244. if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
  5245. if (UnOp->getOpcode() == UO_AddrOf) {
  5246. Arg = UnOp->getSubExpr();
  5247. AddressTaken = true;
  5248. AddrOpLoc = UnOp->getOperatorLoc();
  5249. }
  5250. }
  5251. while (SubstNonTypeTemplateParmExpr *subst =
  5252. dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
  5253. Arg = subst->getReplacement()->IgnoreImpCasts();
  5254. }
  5255. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
  5256. ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
  5257. // If our parameter has pointer type, check for a null template value.
  5258. if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
  5259. switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
  5260. Entity)) {
  5261. case NPV_NullPointer:
  5262. S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
  5263. Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
  5264. /*isNullPtr=*/true);
  5265. return false;
  5266. case NPV_Error:
  5267. return true;
  5268. case NPV_NotNullPointer:
  5269. break;
  5270. }
  5271. }
  5272. // Stop checking the precise nature of the argument if it is value dependent,
  5273. // it should be checked when instantiated.
  5274. if (Arg->isValueDependent()) {
  5275. Converted = TemplateArgument(ArgIn);
  5276. return false;
  5277. }
  5278. if (isa<CXXUuidofExpr>(Arg)) {
  5279. if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
  5280. ArgIn, Arg, ArgType))
  5281. return true;
  5282. Converted = TemplateArgument(ArgIn);
  5283. return false;
  5284. }
  5285. if (!DRE) {
  5286. S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
  5287. << Arg->getSourceRange();
  5288. S.Diag(Param->getLocation(), diag::note_template_param_here);
  5289. return true;
  5290. }
  5291. // Cannot refer to non-static data members
  5292. if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
  5293. S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
  5294. << Entity << Arg->getSourceRange();
  5295. S.Diag(Param->getLocation(), diag::note_template_param_here);
  5296. return true;
  5297. }
  5298. // Cannot refer to non-static member functions
  5299. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
  5300. if (!Method->isStatic()) {
  5301. S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
  5302. << Method << Arg->getSourceRange();
  5303. S.Diag(Param->getLocation(), diag::note_template_param_here);
  5304. return true;
  5305. }
  5306. }
  5307. FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
  5308. VarDecl *Var = dyn_cast<VarDecl>(Entity);
  5309. // A non-type template argument must refer to an object or function.
  5310. if (!Func && !Var) {
  5311. // We found something, but we don't know specifically what it is.
  5312. S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
  5313. << Arg->getSourceRange();
  5314. S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
  5315. return true;
  5316. }
  5317. // Address / reference template args must have external linkage in C++98.
  5318. if (Entity->getFormalLinkage() == InternalLinkage) {
  5319. S.Diag(Arg->getBeginLoc(),
  5320. S.getLangOpts().CPlusPlus11
  5321. ? diag::warn_cxx98_compat_template_arg_object_internal
  5322. : diag::ext_template_arg_object_internal)
  5323. << !Func << Entity << Arg->getSourceRange();
  5324. S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
  5325. << !Func;
  5326. } else if (!Entity->hasLinkage()) {
  5327. S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
  5328. << !Func << Entity << Arg->getSourceRange();
  5329. S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
  5330. << !Func;
  5331. return true;
  5332. }
  5333. if (Func) {
  5334. // If the template parameter has pointer type, the function decays.
  5335. if (ParamType->isPointerType() && !AddressTaken)
  5336. ArgType = S.Context.getPointerType(Func->getType());
  5337. else if (AddressTaken && ParamType->isReferenceType()) {
  5338. // If we originally had an address-of operator, but the
  5339. // parameter has reference type, complain and (if things look
  5340. // like they will work) drop the address-of operator.
  5341. if (!S.Context.hasSameUnqualifiedType(Func->getType(),
  5342. ParamType.getNonReferenceType())) {
  5343. S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
  5344. << ParamType;
  5345. S.Diag(Param->getLocation(), diag::note_template_param_here);
  5346. return true;
  5347. }
  5348. S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
  5349. << ParamType
  5350. << FixItHint::CreateRemoval(AddrOpLoc);
  5351. S.Diag(Param->getLocation(), diag::note_template_param_here);
  5352. ArgType = Func->getType();
  5353. }
  5354. } else {
  5355. // A value of reference type is not an object.
  5356. if (Var->getType()->isReferenceType()) {
  5357. S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
  5358. << Var->getType() << Arg->getSourceRange();
  5359. S.Diag(Param->getLocation(), diag::note_template_param_here);
  5360. return true;
  5361. }
  5362. // A template argument must have static storage duration.
  5363. if (Var->getTLSKind()) {
  5364. S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
  5365. << Arg->getSourceRange();
  5366. S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
  5367. return true;
  5368. }
  5369. // If the template parameter has pointer type, we must have taken
  5370. // the address of this object.
  5371. if (ParamType->isReferenceType()) {
  5372. if (AddressTaken) {
  5373. // If we originally had an address-of operator, but the
  5374. // parameter has reference type, complain and (if things look
  5375. // like they will work) drop the address-of operator.
  5376. if (!S.Context.hasSameUnqualifiedType(Var->getType(),
  5377. ParamType.getNonReferenceType())) {
  5378. S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
  5379. << ParamType;
  5380. S.Diag(Param->getLocation(), diag::note_template_param_here);
  5381. return true;
  5382. }
  5383. S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
  5384. << ParamType
  5385. << FixItHint::CreateRemoval(AddrOpLoc);
  5386. S.Diag(Param->getLocation(), diag::note_template_param_here);
  5387. ArgType = Var->getType();
  5388. }
  5389. } else if (!AddressTaken && ParamType->isPointerType()) {
  5390. if (Var->getType()->isArrayType()) {
  5391. // Array-to-pointer decay.
  5392. ArgType = S.Context.getArrayDecayedType(Var->getType());
  5393. } else {
  5394. // If the template parameter has pointer type but the address of
  5395. // this object was not taken, complain and (possibly) recover by
  5396. // taking the address of the entity.
  5397. ArgType = S.Context.getPointerType(Var->getType());
  5398. if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
  5399. S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
  5400. << ParamType;
  5401. S.Diag(Param->getLocation(), diag::note_template_param_here);
  5402. return true;
  5403. }
  5404. S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
  5405. << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
  5406. S.Diag(Param->getLocation(), diag::note_template_param_here);
  5407. }
  5408. }
  5409. }
  5410. if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
  5411. Arg, ArgType))
  5412. return true;
  5413. // Create the template argument.
  5414. Converted =
  5415. TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
  5416. S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);
  5417. return false;
  5418. }
  5419. /// Checks whether the given template argument is a pointer to
  5420. /// member constant according to C++ [temp.arg.nontype]p1.
  5421. static bool CheckTemplateArgumentPointerToMember(Sema &S,
  5422. NonTypeTemplateParmDecl *Param,
  5423. QualType ParamType,
  5424. Expr *&ResultArg,
  5425. TemplateArgument &Converted) {
  5426. bool Invalid = false;
  5427. Expr *Arg = ResultArg;
  5428. bool ObjCLifetimeConversion;
  5429. // C++ [temp.arg.nontype]p1:
  5430. //
  5431. // A template-argument for a non-type, non-template
  5432. // template-parameter shall be one of: [...]
  5433. //
  5434. // -- a pointer to member expressed as described in 5.3.1.
  5435. DeclRefExpr *DRE = nullptr;
  5436. // In C++98/03 mode, give an extension warning on any extra parentheses.
  5437. // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
  5438. bool ExtraParens = false;
  5439. while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
  5440. if (!Invalid && !ExtraParens) {
  5441. S.Diag(Arg->getBeginLoc(),
  5442. S.getLangOpts().CPlusPlus11
  5443. ? diag::warn_cxx98_compat_template_arg_extra_parens
  5444. : diag::ext_template_arg_extra_parens)
  5445. << Arg->getSourceRange();
  5446. ExtraParens = true;
  5447. }
  5448. Arg = Parens->getSubExpr();
  5449. }
  5450. while (SubstNonTypeTemplateParmExpr *subst =
  5451. dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
  5452. Arg = subst->getReplacement()->IgnoreImpCasts();
  5453. // A pointer-to-member constant written &Class::member.
  5454. if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
  5455. if (UnOp->getOpcode() == UO_AddrOf) {
  5456. DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
  5457. if (DRE && !DRE->getQualifier())
  5458. DRE = nullptr;
  5459. }
  5460. }
  5461. // A constant of pointer-to-member type.
  5462. else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
  5463. ValueDecl *VD = DRE->getDecl();
  5464. if (VD->getType()->isMemberPointerType()) {
  5465. if (isa<NonTypeTemplateParmDecl>(VD)) {
  5466. if (Arg->isTypeDependent() || Arg->isValueDependent()) {
  5467. Converted = TemplateArgument(Arg);
  5468. } else {
  5469. VD = cast<ValueDecl>(VD->getCanonicalDecl());
  5470. Converted = TemplateArgument(VD, ParamType);
  5471. }
  5472. return Invalid;
  5473. }
  5474. }
  5475. DRE = nullptr;
  5476. }
  5477. ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
  5478. // Check for a null pointer value.
  5479. switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
  5480. Entity)) {
  5481. case NPV_Error:
  5482. return true;
  5483. case NPV_NullPointer:
  5484. S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
  5485. Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
  5486. /*isNullPtr*/true);
  5487. return false;
  5488. case NPV_NotNullPointer:
  5489. break;
  5490. }
  5491. if (S.IsQualificationConversion(ResultArg->getType(),
  5492. ParamType.getNonReferenceType(), false,
  5493. ObjCLifetimeConversion)) {
  5494. ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
  5495. ResultArg->getValueKind())
  5496. .get();
  5497. } else if (!S.Context.hasSameUnqualifiedType(
  5498. ResultArg->getType(), ParamType.getNonReferenceType())) {
  5499. // We can't perform this conversion.
  5500. S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
  5501. << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
  5502. S.Diag(Param->getLocation(), diag::note_template_param_here);
  5503. return true;
  5504. }
  5505. if (!DRE)
  5506. return S.Diag(Arg->getBeginLoc(),
  5507. diag::err_template_arg_not_pointer_to_member_form)
  5508. << Arg->getSourceRange();
  5509. if (isa<FieldDecl>(DRE->getDecl()) ||
  5510. isa<IndirectFieldDecl>(DRE->getDecl()) ||
  5511. isa<CXXMethodDecl>(DRE->getDecl())) {
  5512. assert((isa<FieldDecl>(DRE->getDecl()) ||
  5513. isa<IndirectFieldDecl>(DRE->getDecl()) ||
  5514. !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
  5515. "Only non-static member pointers can make it here");
  5516. // Okay: this is the address of a non-static member, and therefore
  5517. // a member pointer constant.
  5518. if (Arg->isTypeDependent() || Arg->isValueDependent()) {
  5519. Converted = TemplateArgument(Arg);
  5520. } else {
  5521. ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
  5522. Converted = TemplateArgument(D, ParamType);
  5523. }
  5524. return Invalid;
  5525. }
  5526. // We found something else, but we don't know specifically what it is.
  5527. S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
  5528. << Arg->getSourceRange();
  5529. S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
  5530. return true;
  5531. }
  5532. /// Check a template argument against its corresponding
  5533. /// non-type template parameter.
  5534. ///
  5535. /// This routine implements the semantics of C++ [temp.arg.nontype].
  5536. /// If an error occurred, it returns ExprError(); otherwise, it
  5537. /// returns the converted template argument. \p ParamType is the
  5538. /// type of the non-type template parameter after it has been instantiated.
  5539. ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
  5540. QualType ParamType, Expr *Arg,
  5541. TemplateArgument &Converted,
  5542. CheckTemplateArgumentKind CTAK) {
  5543. SourceLocation StartLoc = Arg->getBeginLoc();
  5544. // If the parameter type somehow involves auto, deduce the type now.
  5545. if (getLangOpts().CPlusPlus17 && ParamType->isUndeducedType()) {
  5546. // During template argument deduction, we allow 'decltype(auto)' to
  5547. // match an arbitrary dependent argument.
  5548. // FIXME: The language rules don't say what happens in this case.
  5549. // FIXME: We get an opaque dependent type out of decltype(auto) if the
  5550. // expression is merely instantiation-dependent; is this enough?
  5551. if (CTAK == CTAK_Deduced && Arg->isTypeDependent()) {
  5552. auto *AT = dyn_cast<AutoType>(ParamType);
  5553. if (AT && AT->isDecltypeAuto()) {
  5554. Converted = TemplateArgument(Arg);
  5555. return Arg;
  5556. }
  5557. }
  5558. // When checking a deduced template argument, deduce from its type even if
  5559. // the type is dependent, in order to check the types of non-type template
  5560. // arguments line up properly in partial ordering.
  5561. Optional<unsigned> Depth = Param->getDepth() + 1;
  5562. Expr *DeductionArg = Arg;
  5563. if (auto *PE = dyn_cast<PackExpansionExpr>(DeductionArg))
  5564. DeductionArg = PE->getPattern();
  5565. if (DeduceAutoType(
  5566. Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation()),
  5567. DeductionArg, ParamType, Depth) == DAR_Failed) {
  5568. Diag(Arg->getExprLoc(),
  5569. diag::err_non_type_template_parm_type_deduction_failure)
  5570. << Param->getDeclName() << Param->getType() << Arg->getType()
  5571. << Arg->getSourceRange();
  5572. Diag(Param->getLocation(), diag::note_template_param_here);
  5573. return ExprError();
  5574. }
  5575. // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
  5576. // an error. The error message normally references the parameter
  5577. // declaration, but here we'll pass the argument location because that's
  5578. // where the parameter type is deduced.
  5579. ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
  5580. if (ParamType.isNull()) {
  5581. Diag(Param->getLocation(), diag::note_template_param_here);
  5582. return ExprError();
  5583. }
  5584. }
  5585. // We should have already dropped all cv-qualifiers by now.
  5586. assert(!ParamType.hasQualifiers() &&
  5587. "non-type template parameter type cannot be qualified");
  5588. if (CTAK == CTAK_Deduced &&
  5589. !Context.hasSameType(ParamType.getNonLValueExprType(Context),
  5590. Arg->getType())) {
  5591. // FIXME: If either type is dependent, we skip the check. This isn't
  5592. // correct, since during deduction we're supposed to have replaced each
  5593. // template parameter with some unique (non-dependent) placeholder.
  5594. // FIXME: If the argument type contains 'auto', we carry on and fail the
  5595. // type check in order to force specific types to be more specialized than
  5596. // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
  5597. // work.
  5598. if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
  5599. !Arg->getType()->getContainedAutoType()) {
  5600. Converted = TemplateArgument(Arg);
  5601. return Arg;
  5602. }
  5603. // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
  5604. // we should actually be checking the type of the template argument in P,
  5605. // not the type of the template argument deduced from A, against the
  5606. // template parameter type.
  5607. Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
  5608. << Arg->getType()
  5609. << ParamType.getUnqualifiedType();
  5610. Diag(Param->getLocation(), diag::note_template_param_here);
  5611. return ExprError();
  5612. }
  5613. // If either the parameter has a dependent type or the argument is
  5614. // type-dependent, there's nothing we can check now.
  5615. if (ParamType->isDependentType() || Arg->isTypeDependent()) {
  5616. // Force the argument to the type of the parameter to maintain invariants.
  5617. auto *PE = dyn_cast<PackExpansionExpr>(Arg);
  5618. if (PE)
  5619. Arg = PE->getPattern();
  5620. ExprResult E = ImpCastExprToType(
  5621. Arg, ParamType.getNonLValueExprType(Context), CK_Dependent,
  5622. ParamType->isLValueReferenceType() ? VK_LValue :
  5623. ParamType->isRValueReferenceType() ? VK_XValue : VK_RValue);
  5624. if (E.isInvalid())
  5625. return ExprError();
  5626. if (PE) {
  5627. // Recreate a pack expansion if we unwrapped one.
  5628. E = new (Context)
  5629. PackExpansionExpr(E.get()->getType(), E.get(), PE->getEllipsisLoc(),
  5630. PE->getNumExpansions());
  5631. }
  5632. Converted = TemplateArgument(E.get());
  5633. return E;
  5634. }
  5635. // The initialization of the parameter from the argument is
  5636. // a constant-evaluated context.
  5637. EnterExpressionEvaluationContext ConstantEvaluated(
  5638. *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  5639. if (getLangOpts().CPlusPlus17) {
  5640. // C++17 [temp.arg.nontype]p1:
  5641. // A template-argument for a non-type template parameter shall be
  5642. // a converted constant expression of the type of the template-parameter.
  5643. APValue Value;
  5644. ExprResult ArgResult = CheckConvertedConstantExpression(
  5645. Arg, ParamType, Value, CCEK_TemplateArg);
  5646. if (ArgResult.isInvalid())
  5647. return ExprError();
  5648. // For a value-dependent argument, CheckConvertedConstantExpression is
  5649. // permitted (and expected) to be unable to determine a value.
  5650. if (ArgResult.get()->isValueDependent()) {
  5651. Converted = TemplateArgument(ArgResult.get());
  5652. return ArgResult;
  5653. }
  5654. QualType CanonParamType = Context.getCanonicalType(ParamType);
  5655. // Convert the APValue to a TemplateArgument.
  5656. switch (Value.getKind()) {
  5657. case APValue::None:
  5658. assert(ParamType->isNullPtrType());
  5659. Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
  5660. break;
  5661. case APValue::Indeterminate:
  5662. llvm_unreachable("result of constant evaluation should be initialized");
  5663. break;
  5664. case APValue::Int:
  5665. assert(ParamType->isIntegralOrEnumerationType());
  5666. Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
  5667. break;
  5668. case APValue::MemberPointer: {
  5669. assert(ParamType->isMemberPointerType());
  5670. // FIXME: We need TemplateArgument representation and mangling for these.
  5671. if (!Value.getMemberPointerPath().empty()) {
  5672. Diag(Arg->getBeginLoc(),
  5673. diag::err_template_arg_member_ptr_base_derived_not_supported)
  5674. << Value.getMemberPointerDecl() << ParamType
  5675. << Arg->getSourceRange();
  5676. return ExprError();
  5677. }
  5678. auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
  5679. Converted = VD ? TemplateArgument(VD, CanonParamType)
  5680. : TemplateArgument(CanonParamType, /*isNullPtr*/true);
  5681. break;
  5682. }
  5683. case APValue::LValue: {
  5684. // For a non-type template-parameter of pointer or reference type,
  5685. // the value of the constant expression shall not refer to
  5686. assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
  5687. ParamType->isNullPtrType());
  5688. // -- a temporary object
  5689. // -- a string literal
  5690. // -- the result of a typeid expression, or
  5691. // -- a predefined __func__ variable
  5692. APValue::LValueBase Base = Value.getLValueBase();
  5693. auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
  5694. if (Base && !VD) {
  5695. auto *E = Base.dyn_cast<const Expr *>();
  5696. if (E && isa<CXXUuidofExpr>(E)) {
  5697. Converted = TemplateArgument(ArgResult.get()->IgnoreImpCasts());
  5698. break;
  5699. }
  5700. Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
  5701. << Arg->getSourceRange();
  5702. return ExprError();
  5703. }
  5704. // -- a subobject
  5705. if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
  5706. VD && VD->getType()->isArrayType() &&
  5707. Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
  5708. !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
  5709. // Per defect report (no number yet):
  5710. // ... other than a pointer to the first element of a complete array
  5711. // object.
  5712. } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
  5713. Value.isLValueOnePastTheEnd()) {
  5714. Diag(StartLoc, diag::err_non_type_template_arg_subobject)
  5715. << Value.getAsString(Context, ParamType);
  5716. return ExprError();
  5717. }
  5718. assert((VD || !ParamType->isReferenceType()) &&
  5719. "null reference should not be a constant expression");
  5720. assert((!VD || !ParamType->isNullPtrType()) &&
  5721. "non-null value of type nullptr_t?");
  5722. Converted = VD ? TemplateArgument(VD, CanonParamType)
  5723. : TemplateArgument(CanonParamType, /*isNullPtr*/true);
  5724. break;
  5725. }
  5726. case APValue::AddrLabelDiff:
  5727. return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
  5728. case APValue::FixedPoint:
  5729. case APValue::Float:
  5730. case APValue::ComplexInt:
  5731. case APValue::ComplexFloat:
  5732. case APValue::Vector:
  5733. case APValue::Array:
  5734. case APValue::Struct:
  5735. case APValue::Union:
  5736. llvm_unreachable("invalid kind for template argument");
  5737. }
  5738. return ArgResult.get();
  5739. }
  5740. // C++ [temp.arg.nontype]p5:
  5741. // The following conversions are performed on each expression used
  5742. // as a non-type template-argument. If a non-type
  5743. // template-argument cannot be converted to the type of the
  5744. // corresponding template-parameter then the program is
  5745. // ill-formed.
  5746. if (ParamType->isIntegralOrEnumerationType()) {
  5747. // C++11:
  5748. // -- for a non-type template-parameter of integral or
  5749. // enumeration type, conversions permitted in a converted
  5750. // constant expression are applied.
  5751. //
  5752. // C++98:
  5753. // -- for a non-type template-parameter of integral or
  5754. // enumeration type, integral promotions (4.5) and integral
  5755. // conversions (4.7) are applied.
  5756. if (getLangOpts().CPlusPlus11) {
  5757. // C++ [temp.arg.nontype]p1:
  5758. // A template-argument for a non-type, non-template template-parameter
  5759. // shall be one of:
  5760. //
  5761. // -- for a non-type template-parameter of integral or enumeration
  5762. // type, a converted constant expression of the type of the
  5763. // template-parameter; or
  5764. llvm::APSInt Value;
  5765. ExprResult ArgResult =
  5766. CheckConvertedConstantExpression(Arg, ParamType, Value,
  5767. CCEK_TemplateArg);
  5768. if (ArgResult.isInvalid())
  5769. return ExprError();
  5770. // We can't check arbitrary value-dependent arguments.
  5771. if (ArgResult.get()->isValueDependent()) {
  5772. Converted = TemplateArgument(ArgResult.get());
  5773. return ArgResult;
  5774. }
  5775. // Widen the argument value to sizeof(parameter type). This is almost
  5776. // always a no-op, except when the parameter type is bool. In
  5777. // that case, this may extend the argument from 1 bit to 8 bits.
  5778. QualType IntegerType = ParamType;
  5779. if (const EnumType *Enum = IntegerType->getAs<EnumType>())
  5780. IntegerType = Enum->getDecl()->getIntegerType();
  5781. Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
  5782. Converted = TemplateArgument(Context, Value,
  5783. Context.getCanonicalType(ParamType));
  5784. return ArgResult;
  5785. }
  5786. ExprResult ArgResult = DefaultLvalueConversion(Arg);
  5787. if (ArgResult.isInvalid())
  5788. return ExprError();
  5789. Arg = ArgResult.get();
  5790. QualType ArgType = Arg->getType();
  5791. // C++ [temp.arg.nontype]p1:
  5792. // A template-argument for a non-type, non-template
  5793. // template-parameter shall be one of:
  5794. //
  5795. // -- an integral constant-expression of integral or enumeration
  5796. // type; or
  5797. // -- the name of a non-type template-parameter; or
  5798. llvm::APSInt Value;
  5799. if (!ArgType->isIntegralOrEnumerationType()) {
  5800. Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral)
  5801. << ArgType << Arg->getSourceRange();
  5802. Diag(Param->getLocation(), diag::note_template_param_here);
  5803. return ExprError();
  5804. } else if (!Arg->isValueDependent()) {
  5805. class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
  5806. QualType T;
  5807. public:
  5808. TmplArgICEDiagnoser(QualType T) : T(T) { }
  5809. void diagnoseNotICE(Sema &S, SourceLocation Loc,
  5810. SourceRange SR) override {
  5811. S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
  5812. }
  5813. } Diagnoser(ArgType);
  5814. Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
  5815. false).get();
  5816. if (!Arg)
  5817. return ExprError();
  5818. }
  5819. // From here on out, all we care about is the unqualified form
  5820. // of the argument type.
  5821. ArgType = ArgType.getUnqualifiedType();
  5822. // Try to convert the argument to the parameter's type.
  5823. if (Context.hasSameType(ParamType, ArgType)) {
  5824. // Okay: no conversion necessary
  5825. } else if (ParamType->isBooleanType()) {
  5826. // This is an integral-to-boolean conversion.
  5827. Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
  5828. } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
  5829. !ParamType->isEnumeralType()) {
  5830. // This is an integral promotion or conversion.
  5831. Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
  5832. } else {
  5833. // We can't perform this conversion.
  5834. Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
  5835. << Arg->getType() << ParamType << Arg->getSourceRange();
  5836. Diag(Param->getLocation(), diag::note_template_param_here);
  5837. return ExprError();
  5838. }
  5839. // Add the value of this argument to the list of converted
  5840. // arguments. We use the bitwidth and signedness of the template
  5841. // parameter.
  5842. if (Arg->isValueDependent()) {
  5843. // The argument is value-dependent. Create a new
  5844. // TemplateArgument with the converted expression.
  5845. Converted = TemplateArgument(Arg);
  5846. return Arg;
  5847. }
  5848. QualType IntegerType = Context.getCanonicalType(ParamType);
  5849. if (const EnumType *Enum = IntegerType->getAs<EnumType>())
  5850. IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
  5851. if (ParamType->isBooleanType()) {
  5852. // Value must be zero or one.
  5853. Value = Value != 0;
  5854. unsigned AllowedBits = Context.getTypeSize(IntegerType);
  5855. if (Value.getBitWidth() != AllowedBits)
  5856. Value = Value.extOrTrunc(AllowedBits);
  5857. Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
  5858. } else {
  5859. llvm::APSInt OldValue = Value;
  5860. // Coerce the template argument's value to the value it will have
  5861. // based on the template parameter's type.
  5862. unsigned AllowedBits = Context.getTypeSize(IntegerType);
  5863. if (Value.getBitWidth() != AllowedBits)
  5864. Value = Value.extOrTrunc(AllowedBits);
  5865. Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
  5866. // Complain if an unsigned parameter received a negative value.
  5867. if (IntegerType->isUnsignedIntegerOrEnumerationType()
  5868. && (OldValue.isSigned() && OldValue.isNegative())) {
  5869. Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
  5870. << OldValue.toString(10) << Value.toString(10) << Param->getType()
  5871. << Arg->getSourceRange();
  5872. Diag(Param->getLocation(), diag::note_template_param_here);
  5873. }
  5874. // Complain if we overflowed the template parameter's type.
  5875. unsigned RequiredBits;
  5876. if (IntegerType->isUnsignedIntegerOrEnumerationType())
  5877. RequiredBits = OldValue.getActiveBits();
  5878. else if (OldValue.isUnsigned())
  5879. RequiredBits = OldValue.getActiveBits() + 1;
  5880. else
  5881. RequiredBits = OldValue.getMinSignedBits();
  5882. if (RequiredBits > AllowedBits) {
  5883. Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
  5884. << OldValue.toString(10) << Value.toString(10) << Param->getType()
  5885. << Arg->getSourceRange();
  5886. Diag(Param->getLocation(), diag::note_template_param_here);
  5887. }
  5888. }
  5889. Converted = TemplateArgument(Context, Value,
  5890. ParamType->isEnumeralType()
  5891. ? Context.getCanonicalType(ParamType)
  5892. : IntegerType);
  5893. return Arg;
  5894. }
  5895. QualType ArgType = Arg->getType();
  5896. DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
  5897. // Handle pointer-to-function, reference-to-function, and
  5898. // pointer-to-member-function all in (roughly) the same way.
  5899. if (// -- For a non-type template-parameter of type pointer to
  5900. // function, only the function-to-pointer conversion (4.3) is
  5901. // applied. If the template-argument represents a set of
  5902. // overloaded functions (or a pointer to such), the matching
  5903. // function is selected from the set (13.4).
  5904. (ParamType->isPointerType() &&
  5905. ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
  5906. // -- For a non-type template-parameter of type reference to
  5907. // function, no conversions apply. If the template-argument
  5908. // represents a set of overloaded functions, the matching
  5909. // function is selected from the set (13.4).
  5910. (ParamType->isReferenceType() &&
  5911. ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
  5912. // -- For a non-type template-parameter of type pointer to
  5913. // member function, no conversions apply. If the
  5914. // template-argument represents a set of overloaded member
  5915. // functions, the matching member function is selected from
  5916. // the set (13.4).
  5917. (ParamType->isMemberPointerType() &&
  5918. ParamType->getAs<MemberPointerType>()->getPointeeType()
  5919. ->isFunctionType())) {
  5920. if (Arg->getType() == Context.OverloadTy) {
  5921. if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
  5922. true,
  5923. FoundResult)) {
  5924. if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
  5925. return ExprError();
  5926. Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
  5927. ArgType = Arg->getType();
  5928. } else
  5929. return ExprError();
  5930. }
  5931. if (!ParamType->isMemberPointerType()) {
  5932. if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
  5933. ParamType,
  5934. Arg, Converted))
  5935. return ExprError();
  5936. return Arg;
  5937. }
  5938. if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
  5939. Converted))
  5940. return ExprError();
  5941. return Arg;
  5942. }
  5943. if (ParamType->isPointerType()) {
  5944. // -- for a non-type template-parameter of type pointer to
  5945. // object, qualification conversions (4.4) and the
  5946. // array-to-pointer conversion (4.2) are applied.
  5947. // C++0x also allows a value of std::nullptr_t.
  5948. assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
  5949. "Only object pointers allowed here");
  5950. if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
  5951. ParamType,
  5952. Arg, Converted))
  5953. return ExprError();
  5954. return Arg;
  5955. }
  5956. if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
  5957. // -- For a non-type template-parameter of type reference to
  5958. // object, no conversions apply. The type referred to by the
  5959. // reference may be more cv-qualified than the (otherwise
  5960. // identical) type of the template-argument. The
  5961. // template-parameter is bound directly to the
  5962. // template-argument, which must be an lvalue.
  5963. assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
  5964. "Only object references allowed here");
  5965. if (Arg->getType() == Context.OverloadTy) {
  5966. if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
  5967. ParamRefType->getPointeeType(),
  5968. true,
  5969. FoundResult)) {
  5970. if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
  5971. return ExprError();
  5972. Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
  5973. ArgType = Arg->getType();
  5974. } else
  5975. return ExprError();
  5976. }
  5977. if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
  5978. ParamType,
  5979. Arg, Converted))
  5980. return ExprError();
  5981. return Arg;
  5982. }
  5983. // Deal with parameters of type std::nullptr_t.
  5984. if (ParamType->isNullPtrType()) {
  5985. if (Arg->isTypeDependent() || Arg->isValueDependent()) {
  5986. Converted = TemplateArgument(Arg);
  5987. return Arg;
  5988. }
  5989. switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
  5990. case NPV_NotNullPointer:
  5991. Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
  5992. << Arg->getType() << ParamType;
  5993. Diag(Param->getLocation(), diag::note_template_param_here);
  5994. return ExprError();
  5995. case NPV_Error:
  5996. return ExprError();
  5997. case NPV_NullPointer:
  5998. Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
  5999. Converted = TemplateArgument(Context.getCanonicalType(ParamType),
  6000. /*isNullPtr*/true);
  6001. return Arg;
  6002. }
  6003. }
  6004. // -- For a non-type template-parameter of type pointer to data
  6005. // member, qualification conversions (4.4) are applied.
  6006. assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
  6007. if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
  6008. Converted))
  6009. return ExprError();
  6010. return Arg;
  6011. }
  6012. static void DiagnoseTemplateParameterListArityMismatch(
  6013. Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
  6014. Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
  6015. /// Check a template argument against its corresponding
  6016. /// template template parameter.
  6017. ///
  6018. /// This routine implements the semantics of C++ [temp.arg.template].
  6019. /// It returns true if an error occurred, and false otherwise.
  6020. bool Sema::CheckTemplateTemplateArgument(TemplateParameterList *Params,
  6021. TemplateArgumentLoc &Arg) {
  6022. TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
  6023. TemplateDecl *Template = Name.getAsTemplateDecl();
  6024. if (!Template) {
  6025. // Any dependent template name is fine.
  6026. assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
  6027. return false;
  6028. }
  6029. if (Template->isInvalidDecl())
  6030. return true;
  6031. // C++0x [temp.arg.template]p1:
  6032. // A template-argument for a template template-parameter shall be
  6033. // the name of a class template or an alias template, expressed as an
  6034. // id-expression. When the template-argument names a class template, only
  6035. // primary class templates are considered when matching the
  6036. // template template argument with the corresponding parameter;
  6037. // partial specializations are not considered even if their
  6038. // parameter lists match that of the template template parameter.
  6039. //
  6040. // Note that we also allow template template parameters here, which
  6041. // will happen when we are dealing with, e.g., class template
  6042. // partial specializations.
  6043. if (!isa<ClassTemplateDecl>(Template) &&
  6044. !isa<TemplateTemplateParmDecl>(Template) &&
  6045. !isa<TypeAliasTemplateDecl>(Template) &&
  6046. !isa<BuiltinTemplateDecl>(Template)) {
  6047. assert(isa<FunctionTemplateDecl>(Template) &&
  6048. "Only function templates are possible here");
  6049. Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
  6050. Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
  6051. << Template;
  6052. }
  6053. // C++1z [temp.arg.template]p3: (DR 150)
  6054. // A template-argument matches a template template-parameter P when P
  6055. // is at least as specialized as the template-argument A.
  6056. if (getLangOpts().RelaxedTemplateTemplateArgs) {
  6057. // Quick check for the common case:
  6058. // If P contains a parameter pack, then A [...] matches P if each of A's
  6059. // template parameters matches the corresponding template parameter in
  6060. // the template-parameter-list of P.
  6061. if (TemplateParameterListsAreEqual(
  6062. Template->getTemplateParameters(), Params, false,
  6063. TPL_TemplateTemplateArgumentMatch, Arg.getLocation()))
  6064. return false;
  6065. if (isTemplateTemplateParameterAtLeastAsSpecializedAs(Params, Template,
  6066. Arg.getLocation()))
  6067. return false;
  6068. // FIXME: Produce better diagnostics for deduction failures.
  6069. }
  6070. return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
  6071. Params,
  6072. true,
  6073. TPL_TemplateTemplateArgumentMatch,
  6074. Arg.getLocation());
  6075. }
  6076. /// Given a non-type template argument that refers to a
  6077. /// declaration and the type of its corresponding non-type template
  6078. /// parameter, produce an expression that properly refers to that
  6079. /// declaration.
  6080. ExprResult
  6081. Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
  6082. QualType ParamType,
  6083. SourceLocation Loc) {
  6084. // C++ [temp.param]p8:
  6085. //
  6086. // A non-type template-parameter of type "array of T" or
  6087. // "function returning T" is adjusted to be of type "pointer to
  6088. // T" or "pointer to function returning T", respectively.
  6089. if (ParamType->isArrayType())
  6090. ParamType = Context.getArrayDecayedType(ParamType);
  6091. else if (ParamType->isFunctionType())
  6092. ParamType = Context.getPointerType(ParamType);
  6093. // For a NULL non-type template argument, return nullptr casted to the
  6094. // parameter's type.
  6095. if (Arg.getKind() == TemplateArgument::NullPtr) {
  6096. return ImpCastExprToType(
  6097. new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
  6098. ParamType,
  6099. ParamType->getAs<MemberPointerType>()
  6100. ? CK_NullToMemberPointer
  6101. : CK_NullToPointer);
  6102. }
  6103. assert(Arg.getKind() == TemplateArgument::Declaration &&
  6104. "Only declaration template arguments permitted here");
  6105. ValueDecl *VD = Arg.getAsDecl();
  6106. if (VD->getDeclContext()->isRecord() &&
  6107. (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
  6108. isa<IndirectFieldDecl>(VD))) {
  6109. // If the value is a class member, we might have a pointer-to-member.
  6110. // Determine whether the non-type template template parameter is of
  6111. // pointer-to-member type. If so, we need to build an appropriate
  6112. // expression for a pointer-to-member, since a "normal" DeclRefExpr
  6113. // would refer to the member itself.
  6114. if (ParamType->isMemberPointerType()) {
  6115. QualType ClassType
  6116. = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
  6117. NestedNameSpecifier *Qualifier
  6118. = NestedNameSpecifier::Create(Context, nullptr, false,
  6119. ClassType.getTypePtr());
  6120. CXXScopeSpec SS;
  6121. SS.MakeTrivial(Context, Qualifier, Loc);
  6122. // The actual value-ness of this is unimportant, but for
  6123. // internal consistency's sake, references to instance methods
  6124. // are r-values.
  6125. ExprValueKind VK = VK_LValue;
  6126. if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
  6127. VK = VK_RValue;
  6128. ExprResult RefExpr = BuildDeclRefExpr(VD,
  6129. VD->getType().getNonReferenceType(),
  6130. VK,
  6131. Loc,
  6132. &SS);
  6133. if (RefExpr.isInvalid())
  6134. return ExprError();
  6135. RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
  6136. // We might need to perform a trailing qualification conversion, since
  6137. // the element type on the parameter could be more qualified than the
  6138. // element type in the expression we constructed.
  6139. bool ObjCLifetimeConversion;
  6140. if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
  6141. ParamType.getUnqualifiedType(), false,
  6142. ObjCLifetimeConversion))
  6143. RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
  6144. assert(!RefExpr.isInvalid() &&
  6145. Context.hasSameType(((Expr*) RefExpr.get())->getType(),
  6146. ParamType.getUnqualifiedType()));
  6147. return RefExpr;
  6148. }
  6149. }
  6150. QualType T = VD->getType().getNonReferenceType();
  6151. if (ParamType->isPointerType()) {
  6152. // When the non-type template parameter is a pointer, take the
  6153. // address of the declaration.
  6154. ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
  6155. if (RefExpr.isInvalid())
  6156. return ExprError();
  6157. if (!Context.hasSameUnqualifiedType(ParamType->getPointeeType(), T) &&
  6158. (T->isFunctionType() || T->isArrayType())) {
  6159. // Decay functions and arrays unless we're forming a pointer to array.
  6160. RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
  6161. if (RefExpr.isInvalid())
  6162. return ExprError();
  6163. return RefExpr;
  6164. }
  6165. // Take the address of everything else
  6166. return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
  6167. }
  6168. ExprValueKind VK = VK_RValue;
  6169. // If the non-type template parameter has reference type, qualify the
  6170. // resulting declaration reference with the extra qualifiers on the
  6171. // type that the reference refers to.
  6172. if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
  6173. VK = VK_LValue;
  6174. T = Context.getQualifiedType(T,
  6175. TargetRef->getPointeeType().getQualifiers());
  6176. } else if (isa<FunctionDecl>(VD)) {
  6177. // References to functions are always lvalues.
  6178. VK = VK_LValue;
  6179. }
  6180. return BuildDeclRefExpr(VD, T, VK, Loc);
  6181. }
  6182. /// Construct a new expression that refers to the given
  6183. /// integral template argument with the given source-location
  6184. /// information.
  6185. ///
  6186. /// This routine takes care of the mapping from an integral template
  6187. /// argument (which may have any integral type) to the appropriate
  6188. /// literal value.
  6189. ExprResult
  6190. Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
  6191. SourceLocation Loc) {
  6192. assert(Arg.getKind() == TemplateArgument::Integral &&
  6193. "Operation is only valid for integral template arguments");
  6194. QualType OrigT = Arg.getIntegralType();
  6195. // If this is an enum type that we're instantiating, we need to use an integer
  6196. // type the same size as the enumerator. We don't want to build an
  6197. // IntegerLiteral with enum type. The integer type of an enum type can be of
  6198. // any integral type with C++11 enum classes, make sure we create the right
  6199. // type of literal for it.
  6200. QualType T = OrigT;
  6201. if (const EnumType *ET = OrigT->getAs<EnumType>())
  6202. T = ET->getDecl()->getIntegerType();
  6203. Expr *E;
  6204. if (T->isAnyCharacterType()) {
  6205. CharacterLiteral::CharacterKind Kind;
  6206. if (T->isWideCharType())
  6207. Kind = CharacterLiteral::Wide;
  6208. else if (T->isChar8Type() && getLangOpts().Char8)
  6209. Kind = CharacterLiteral::UTF8;
  6210. else if (T->isChar16Type())
  6211. Kind = CharacterLiteral::UTF16;
  6212. else if (T->isChar32Type())
  6213. Kind = CharacterLiteral::UTF32;
  6214. else
  6215. Kind = CharacterLiteral::Ascii;
  6216. E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
  6217. Kind, T, Loc);
  6218. } else if (T->isBooleanType()) {
  6219. E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
  6220. T, Loc);
  6221. } else if (T->isNullPtrType()) {
  6222. E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
  6223. } else {
  6224. E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
  6225. }
  6226. if (OrigT->isEnumeralType()) {
  6227. // FIXME: This is a hack. We need a better way to handle substituted
  6228. // non-type template parameters.
  6229. E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
  6230. nullptr,
  6231. Context.getTrivialTypeSourceInfo(OrigT, Loc),
  6232. Loc, Loc);
  6233. }
  6234. return E;
  6235. }
  6236. /// Match two template parameters within template parameter lists.
  6237. static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
  6238. bool Complain,
  6239. Sema::TemplateParameterListEqualKind Kind,
  6240. SourceLocation TemplateArgLoc) {
  6241. // Check the actual kind (type, non-type, template).
  6242. if (Old->getKind() != New->getKind()) {
  6243. if (Complain) {
  6244. unsigned NextDiag = diag::err_template_param_different_kind;
  6245. if (TemplateArgLoc.isValid()) {
  6246. S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
  6247. NextDiag = diag::note_template_param_different_kind;
  6248. }
  6249. S.Diag(New->getLocation(), NextDiag)
  6250. << (Kind != Sema::TPL_TemplateMatch);
  6251. S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
  6252. << (Kind != Sema::TPL_TemplateMatch);
  6253. }
  6254. return false;
  6255. }
  6256. // Check that both are parameter packs or neither are parameter packs.
  6257. // However, if we are matching a template template argument to a
  6258. // template template parameter, the template template parameter can have
  6259. // a parameter pack where the template template argument does not.
  6260. if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
  6261. !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
  6262. Old->isTemplateParameterPack())) {
  6263. if (Complain) {
  6264. unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
  6265. if (TemplateArgLoc.isValid()) {
  6266. S.Diag(TemplateArgLoc,
  6267. diag::err_template_arg_template_params_mismatch);
  6268. NextDiag = diag::note_template_parameter_pack_non_pack;
  6269. }
  6270. unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
  6271. : isa<NonTypeTemplateParmDecl>(New)? 1
  6272. : 2;
  6273. S.Diag(New->getLocation(), NextDiag)
  6274. << ParamKind << New->isParameterPack();
  6275. S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
  6276. << ParamKind << Old->isParameterPack();
  6277. }
  6278. return false;
  6279. }
  6280. // For non-type template parameters, check the type of the parameter.
  6281. if (NonTypeTemplateParmDecl *OldNTTP
  6282. = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
  6283. NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
  6284. // If we are matching a template template argument to a template
  6285. // template parameter and one of the non-type template parameter types
  6286. // is dependent, then we must wait until template instantiation time
  6287. // to actually compare the arguments.
  6288. if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
  6289. (OldNTTP->getType()->isDependentType() ||
  6290. NewNTTP->getType()->isDependentType()))
  6291. return true;
  6292. if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
  6293. if (Complain) {
  6294. unsigned NextDiag = diag::err_template_nontype_parm_different_type;
  6295. if (TemplateArgLoc.isValid()) {
  6296. S.Diag(TemplateArgLoc,
  6297. diag::err_template_arg_template_params_mismatch);
  6298. NextDiag = diag::note_template_nontype_parm_different_type;
  6299. }
  6300. S.Diag(NewNTTP->getLocation(), NextDiag)
  6301. << NewNTTP->getType()
  6302. << (Kind != Sema::TPL_TemplateMatch);
  6303. S.Diag(OldNTTP->getLocation(),
  6304. diag::note_template_nontype_parm_prev_declaration)
  6305. << OldNTTP->getType();
  6306. }
  6307. return false;
  6308. }
  6309. return true;
  6310. }
  6311. // For template template parameters, check the template parameter types.
  6312. // The template parameter lists of template template
  6313. // parameters must agree.
  6314. if (TemplateTemplateParmDecl *OldTTP
  6315. = dyn_cast<TemplateTemplateParmDecl>(Old)) {
  6316. TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
  6317. return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
  6318. OldTTP->getTemplateParameters(),
  6319. Complain,
  6320. (Kind == Sema::TPL_TemplateMatch
  6321. ? Sema::TPL_TemplateTemplateParmMatch
  6322. : Kind),
  6323. TemplateArgLoc);
  6324. }
  6325. return true;
  6326. }
  6327. /// Diagnose a known arity mismatch when comparing template argument
  6328. /// lists.
  6329. static
  6330. void DiagnoseTemplateParameterListArityMismatch(Sema &S,
  6331. TemplateParameterList *New,
  6332. TemplateParameterList *Old,
  6333. Sema::TemplateParameterListEqualKind Kind,
  6334. SourceLocation TemplateArgLoc) {
  6335. unsigned NextDiag = diag::err_template_param_list_different_arity;
  6336. if (TemplateArgLoc.isValid()) {
  6337. S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
  6338. NextDiag = diag::note_template_param_list_different_arity;
  6339. }
  6340. S.Diag(New->getTemplateLoc(), NextDiag)
  6341. << (New->size() > Old->size())
  6342. << (Kind != Sema::TPL_TemplateMatch)
  6343. << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
  6344. S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
  6345. << (Kind != Sema::TPL_TemplateMatch)
  6346. << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
  6347. }
  6348. /// Determine whether the given template parameter lists are
  6349. /// equivalent.
  6350. ///
  6351. /// \param New The new template parameter list, typically written in the
  6352. /// source code as part of a new template declaration.
  6353. ///
  6354. /// \param Old The old template parameter list, typically found via
  6355. /// name lookup of the template declared with this template parameter
  6356. /// list.
  6357. ///
  6358. /// \param Complain If true, this routine will produce a diagnostic if
  6359. /// the template parameter lists are not equivalent.
  6360. ///
  6361. /// \param Kind describes how we are to match the template parameter lists.
  6362. ///
  6363. /// \param TemplateArgLoc If this source location is valid, then we
  6364. /// are actually checking the template parameter list of a template
  6365. /// argument (New) against the template parameter list of its
  6366. /// corresponding template template parameter (Old). We produce
  6367. /// slightly different diagnostics in this scenario.
  6368. ///
  6369. /// \returns True if the template parameter lists are equal, false
  6370. /// otherwise.
  6371. bool
  6372. Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
  6373. TemplateParameterList *Old,
  6374. bool Complain,
  6375. TemplateParameterListEqualKind Kind,
  6376. SourceLocation TemplateArgLoc) {
  6377. if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
  6378. if (Complain)
  6379. DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
  6380. TemplateArgLoc);
  6381. return false;
  6382. }
  6383. // C++0x [temp.arg.template]p3:
  6384. // A template-argument matches a template template-parameter (call it P)
  6385. // when each of the template parameters in the template-parameter-list of
  6386. // the template-argument's corresponding class template or alias template
  6387. // (call it A) matches the corresponding template parameter in the
  6388. // template-parameter-list of P. [...]
  6389. TemplateParameterList::iterator NewParm = New->begin();
  6390. TemplateParameterList::iterator NewParmEnd = New->end();
  6391. for (TemplateParameterList::iterator OldParm = Old->begin(),
  6392. OldParmEnd = Old->end();
  6393. OldParm != OldParmEnd; ++OldParm) {
  6394. if (Kind != TPL_TemplateTemplateArgumentMatch ||
  6395. !(*OldParm)->isTemplateParameterPack()) {
  6396. if (NewParm == NewParmEnd) {
  6397. if (Complain)
  6398. DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
  6399. TemplateArgLoc);
  6400. return false;
  6401. }
  6402. if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
  6403. Kind, TemplateArgLoc))
  6404. return false;
  6405. ++NewParm;
  6406. continue;
  6407. }
  6408. // C++0x [temp.arg.template]p3:
  6409. // [...] When P's template- parameter-list contains a template parameter
  6410. // pack (14.5.3), the template parameter pack will match zero or more
  6411. // template parameters or template parameter packs in the
  6412. // template-parameter-list of A with the same type and form as the
  6413. // template parameter pack in P (ignoring whether those template
  6414. // parameters are template parameter packs).
  6415. for (; NewParm != NewParmEnd; ++NewParm) {
  6416. if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
  6417. Kind, TemplateArgLoc))
  6418. return false;
  6419. }
  6420. }
  6421. // Make sure we exhausted all of the arguments.
  6422. if (NewParm != NewParmEnd) {
  6423. if (Complain)
  6424. DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
  6425. TemplateArgLoc);
  6426. return false;
  6427. }
  6428. return true;
  6429. }
  6430. /// Check whether a template can be declared within this scope.
  6431. ///
  6432. /// If the template declaration is valid in this scope, returns
  6433. /// false. Otherwise, issues a diagnostic and returns true.
  6434. bool
  6435. Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
  6436. if (!S)
  6437. return false;
  6438. // Find the nearest enclosing declaration scope.
  6439. while ((S->getFlags() & Scope::DeclScope) == 0 ||
  6440. (S->getFlags() & Scope::TemplateParamScope) != 0)
  6441. S = S->getParent();
  6442. // C++ [temp]p4:
  6443. // A template [...] shall not have C linkage.
  6444. DeclContext *Ctx = S->getEntity();
  6445. if (Ctx && Ctx->isExternCContext()) {
  6446. Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
  6447. << TemplateParams->getSourceRange();
  6448. if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
  6449. Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
  6450. return true;
  6451. }
  6452. Ctx = Ctx->getRedeclContext();
  6453. // C++ [temp]p2:
  6454. // A template-declaration can appear only as a namespace scope or
  6455. // class scope declaration.
  6456. if (Ctx) {
  6457. if (Ctx->isFileContext())
  6458. return false;
  6459. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
  6460. // C++ [temp.mem]p2:
  6461. // A local class shall not have member templates.
  6462. if (RD->isLocalClass())
  6463. return Diag(TemplateParams->getTemplateLoc(),
  6464. diag::err_template_inside_local_class)
  6465. << TemplateParams->getSourceRange();
  6466. else
  6467. return false;
  6468. }
  6469. }
  6470. return Diag(TemplateParams->getTemplateLoc(),
  6471. diag::err_template_outside_namespace_or_class_scope)
  6472. << TemplateParams->getSourceRange();
  6473. }
  6474. /// Determine what kind of template specialization the given declaration
  6475. /// is.
  6476. static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
  6477. if (!D)
  6478. return TSK_Undeclared;
  6479. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
  6480. return Record->getTemplateSpecializationKind();
  6481. if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
  6482. return Function->getTemplateSpecializationKind();
  6483. if (VarDecl *Var = dyn_cast<VarDecl>(D))
  6484. return Var->getTemplateSpecializationKind();
  6485. return TSK_Undeclared;
  6486. }
  6487. /// Check whether a specialization is well-formed in the current
  6488. /// context.
  6489. ///
  6490. /// This routine determines whether a template specialization can be declared
  6491. /// in the current context (C++ [temp.expl.spec]p2).
  6492. ///
  6493. /// \param S the semantic analysis object for which this check is being
  6494. /// performed.
  6495. ///
  6496. /// \param Specialized the entity being specialized or instantiated, which
  6497. /// may be a kind of template (class template, function template, etc.) or
  6498. /// a member of a class template (member function, static data member,
  6499. /// member class).
  6500. ///
  6501. /// \param PrevDecl the previous declaration of this entity, if any.
  6502. ///
  6503. /// \param Loc the location of the explicit specialization or instantiation of
  6504. /// this entity.
  6505. ///
  6506. /// \param IsPartialSpecialization whether this is a partial specialization of
  6507. /// a class template.
  6508. ///
  6509. /// \returns true if there was an error that we cannot recover from, false
  6510. /// otherwise.
  6511. static bool CheckTemplateSpecializationScope(Sema &S,
  6512. NamedDecl *Specialized,
  6513. NamedDecl *PrevDecl,
  6514. SourceLocation Loc,
  6515. bool IsPartialSpecialization) {
  6516. // Keep these "kind" numbers in sync with the %select statements in the
  6517. // various diagnostics emitted by this routine.
  6518. int EntityKind = 0;
  6519. if (isa<ClassTemplateDecl>(Specialized))
  6520. EntityKind = IsPartialSpecialization? 1 : 0;
  6521. else if (isa<VarTemplateDecl>(Specialized))
  6522. EntityKind = IsPartialSpecialization ? 3 : 2;
  6523. else if (isa<FunctionTemplateDecl>(Specialized))
  6524. EntityKind = 4;
  6525. else if (isa<CXXMethodDecl>(Specialized))
  6526. EntityKind = 5;
  6527. else if (isa<VarDecl>(Specialized))
  6528. EntityKind = 6;
  6529. else if (isa<RecordDecl>(Specialized))
  6530. EntityKind = 7;
  6531. else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
  6532. EntityKind = 8;
  6533. else {
  6534. S.Diag(Loc, diag::err_template_spec_unknown_kind)
  6535. << S.getLangOpts().CPlusPlus11;
  6536. S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
  6537. return true;
  6538. }
  6539. // C++ [temp.expl.spec]p2:
  6540. // An explicit specialization may be declared in any scope in which
  6541. // the corresponding primary template may be defined.
  6542. if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
  6543. S.Diag(Loc, diag::err_template_spec_decl_function_scope)
  6544. << Specialized;
  6545. return true;
  6546. }
  6547. // C++ [temp.class.spec]p6:
  6548. // A class template partial specialization may be declared in any
  6549. // scope in which the primary template may be defined.
  6550. DeclContext *SpecializedContext =
  6551. Specialized->getDeclContext()->getRedeclContext();
  6552. DeclContext *DC = S.CurContext->getRedeclContext();
  6553. // Make sure that this redeclaration (or definition) occurs in the same
  6554. // scope or an enclosing namespace.
  6555. if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
  6556. : DC->Equals(SpecializedContext))) {
  6557. if (isa<TranslationUnitDecl>(SpecializedContext))
  6558. S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
  6559. << EntityKind << Specialized;
  6560. else {
  6561. auto *ND = cast<NamedDecl>(SpecializedContext);
  6562. int Diag = diag::err_template_spec_redecl_out_of_scope;
  6563. if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
  6564. Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
  6565. S.Diag(Loc, Diag) << EntityKind << Specialized
  6566. << ND << isa<CXXRecordDecl>(ND);
  6567. }
  6568. S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
  6569. // Don't allow specializing in the wrong class during error recovery.
  6570. // Otherwise, things can go horribly wrong.
  6571. if (DC->isRecord())
  6572. return true;
  6573. }
  6574. return false;
  6575. }
  6576. static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
  6577. if (!E->isTypeDependent())
  6578. return SourceLocation();
  6579. DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
  6580. Checker.TraverseStmt(E);
  6581. if (Checker.MatchLoc.isInvalid())
  6582. return E->getSourceRange();
  6583. return Checker.MatchLoc;
  6584. }
  6585. static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
  6586. if (!TL.getType()->isDependentType())
  6587. return SourceLocation();
  6588. DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
  6589. Checker.TraverseTypeLoc(TL);
  6590. if (Checker.MatchLoc.isInvalid())
  6591. return TL.getSourceRange();
  6592. return Checker.MatchLoc;
  6593. }
  6594. /// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
  6595. /// that checks non-type template partial specialization arguments.
  6596. static bool CheckNonTypeTemplatePartialSpecializationArgs(
  6597. Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
  6598. const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
  6599. for (unsigned I = 0; I != NumArgs; ++I) {
  6600. if (Args[I].getKind() == TemplateArgument::Pack) {
  6601. if (CheckNonTypeTemplatePartialSpecializationArgs(
  6602. S, TemplateNameLoc, Param, Args[I].pack_begin(),
  6603. Args[I].pack_size(), IsDefaultArgument))
  6604. return true;
  6605. continue;
  6606. }
  6607. if (Args[I].getKind() != TemplateArgument::Expression)
  6608. continue;
  6609. Expr *ArgExpr = Args[I].getAsExpr();
  6610. // We can have a pack expansion of any of the bullets below.
  6611. if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
  6612. ArgExpr = Expansion->getPattern();
  6613. // Strip off any implicit casts we added as part of type checking.
  6614. while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
  6615. ArgExpr = ICE->getSubExpr();
  6616. // C++ [temp.class.spec]p8:
  6617. // A non-type argument is non-specialized if it is the name of a
  6618. // non-type parameter. All other non-type arguments are
  6619. // specialized.
  6620. //
  6621. // Below, we check the two conditions that only apply to
  6622. // specialized non-type arguments, so skip any non-specialized
  6623. // arguments.
  6624. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
  6625. if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
  6626. continue;
  6627. // C++ [temp.class.spec]p9:
  6628. // Within the argument list of a class template partial
  6629. // specialization, the following restrictions apply:
  6630. // -- A partially specialized non-type argument expression
  6631. // shall not involve a template parameter of the partial
  6632. // specialization except when the argument expression is a
  6633. // simple identifier.
  6634. // -- The type of a template parameter corresponding to a
  6635. // specialized non-type argument shall not be dependent on a
  6636. // parameter of the specialization.
  6637. // DR1315 removes the first bullet, leaving an incoherent set of rules.
  6638. // We implement a compromise between the original rules and DR1315:
  6639. // -- A specialized non-type template argument shall not be
  6640. // type-dependent and the corresponding template parameter
  6641. // shall have a non-dependent type.
  6642. SourceRange ParamUseRange =
  6643. findTemplateParameterInType(Param->getDepth(), ArgExpr);
  6644. if (ParamUseRange.isValid()) {
  6645. if (IsDefaultArgument) {
  6646. S.Diag(TemplateNameLoc,
  6647. diag::err_dependent_non_type_arg_in_partial_spec);
  6648. S.Diag(ParamUseRange.getBegin(),
  6649. diag::note_dependent_non_type_default_arg_in_partial_spec)
  6650. << ParamUseRange;
  6651. } else {
  6652. S.Diag(ParamUseRange.getBegin(),
  6653. diag::err_dependent_non_type_arg_in_partial_spec)
  6654. << ParamUseRange;
  6655. }
  6656. return true;
  6657. }
  6658. ParamUseRange = findTemplateParameter(
  6659. Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
  6660. if (ParamUseRange.isValid()) {
  6661. S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
  6662. diag::err_dependent_typed_non_type_arg_in_partial_spec)
  6663. << Param->getType();
  6664. S.Diag(Param->getLocation(), diag::note_template_param_here)
  6665. << (IsDefaultArgument ? ParamUseRange : SourceRange())
  6666. << ParamUseRange;
  6667. return true;
  6668. }
  6669. }
  6670. return false;
  6671. }
  6672. /// Check the non-type template arguments of a class template
  6673. /// partial specialization according to C++ [temp.class.spec]p9.
  6674. ///
  6675. /// \param TemplateNameLoc the location of the template name.
  6676. /// \param PrimaryTemplate the template parameters of the primary class
  6677. /// template.
  6678. /// \param NumExplicit the number of explicitly-specified template arguments.
  6679. /// \param TemplateArgs the template arguments of the class template
  6680. /// partial specialization.
  6681. ///
  6682. /// \returns \c true if there was an error, \c false otherwise.
  6683. bool Sema::CheckTemplatePartialSpecializationArgs(
  6684. SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
  6685. unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
  6686. // We have to be conservative when checking a template in a dependent
  6687. // context.
  6688. if (PrimaryTemplate->getDeclContext()->isDependentContext())
  6689. return false;
  6690. TemplateParameterList *TemplateParams =
  6691. PrimaryTemplate->getTemplateParameters();
  6692. for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
  6693. NonTypeTemplateParmDecl *Param
  6694. = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
  6695. if (!Param)
  6696. continue;
  6697. if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
  6698. Param, &TemplateArgs[I],
  6699. 1, I >= NumExplicit))
  6700. return true;
  6701. }
  6702. return false;
  6703. }
  6704. DeclResult Sema::ActOnClassTemplateSpecialization(
  6705. Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
  6706. SourceLocation ModulePrivateLoc, TemplateIdAnnotation &TemplateId,
  6707. const ParsedAttributesView &Attr,
  6708. MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
  6709. assert(TUK != TUK_Reference && "References are not specializations");
  6710. CXXScopeSpec &SS = TemplateId.SS;
  6711. // NOTE: KWLoc is the location of the tag keyword. This will instead
  6712. // store the location of the outermost template keyword in the declaration.
  6713. SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
  6714. ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
  6715. SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
  6716. SourceLocation LAngleLoc = TemplateId.LAngleLoc;
  6717. SourceLocation RAngleLoc = TemplateId.RAngleLoc;
  6718. // Find the class template we're specializing
  6719. TemplateName Name = TemplateId.Template.get();
  6720. ClassTemplateDecl *ClassTemplate
  6721. = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
  6722. if (!ClassTemplate) {
  6723. Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
  6724. << (Name.getAsTemplateDecl() &&
  6725. isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
  6726. return true;
  6727. }
  6728. bool isMemberSpecialization = false;
  6729. bool isPartialSpecialization = false;
  6730. // Check the validity of the template headers that introduce this
  6731. // template.
  6732. // FIXME: We probably shouldn't complain about these headers for
  6733. // friend declarations.
  6734. bool Invalid = false;
  6735. TemplateParameterList *TemplateParams =
  6736. MatchTemplateParametersToScopeSpecifier(
  6737. KWLoc, TemplateNameLoc, SS, &TemplateId,
  6738. TemplateParameterLists, TUK == TUK_Friend, isMemberSpecialization,
  6739. Invalid);
  6740. if (Invalid)
  6741. return true;
  6742. if (TemplateParams && TemplateParams->size() > 0) {
  6743. isPartialSpecialization = true;
  6744. if (TUK == TUK_Friend) {
  6745. Diag(KWLoc, diag::err_partial_specialization_friend)
  6746. << SourceRange(LAngleLoc, RAngleLoc);
  6747. return true;
  6748. }
  6749. // C++ [temp.class.spec]p10:
  6750. // The template parameter list of a specialization shall not
  6751. // contain default template argument values.
  6752. for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
  6753. Decl *Param = TemplateParams->getParam(I);
  6754. if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
  6755. if (TTP->hasDefaultArgument()) {
  6756. Diag(TTP->getDefaultArgumentLoc(),
  6757. diag::err_default_arg_in_partial_spec);
  6758. TTP->removeDefaultArgument();
  6759. }
  6760. } else if (NonTypeTemplateParmDecl *NTTP
  6761. = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
  6762. if (Expr *DefArg = NTTP->getDefaultArgument()) {
  6763. Diag(NTTP->getDefaultArgumentLoc(),
  6764. diag::err_default_arg_in_partial_spec)
  6765. << DefArg->getSourceRange();
  6766. NTTP->removeDefaultArgument();
  6767. }
  6768. } else {
  6769. TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
  6770. if (TTP->hasDefaultArgument()) {
  6771. Diag(TTP->getDefaultArgument().getLocation(),
  6772. diag::err_default_arg_in_partial_spec)
  6773. << TTP->getDefaultArgument().getSourceRange();
  6774. TTP->removeDefaultArgument();
  6775. }
  6776. }
  6777. }
  6778. } else if (TemplateParams) {
  6779. if (TUK == TUK_Friend)
  6780. Diag(KWLoc, diag::err_template_spec_friend)
  6781. << FixItHint::CreateRemoval(
  6782. SourceRange(TemplateParams->getTemplateLoc(),
  6783. TemplateParams->getRAngleLoc()))
  6784. << SourceRange(LAngleLoc, RAngleLoc);
  6785. } else {
  6786. assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
  6787. }
  6788. // Check that the specialization uses the same tag kind as the
  6789. // original template.
  6790. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  6791. assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
  6792. if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
  6793. Kind, TUK == TUK_Definition, KWLoc,
  6794. ClassTemplate->getIdentifier())) {
  6795. Diag(KWLoc, diag::err_use_with_wrong_tag)
  6796. << ClassTemplate
  6797. << FixItHint::CreateReplacement(KWLoc,
  6798. ClassTemplate->getTemplatedDecl()->getKindName());
  6799. Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
  6800. diag::note_previous_use);
  6801. Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
  6802. }
  6803. // Translate the parser's template argument list in our AST format.
  6804. TemplateArgumentListInfo TemplateArgs =
  6805. makeTemplateArgumentListInfo(*this, TemplateId);
  6806. // Check for unexpanded parameter packs in any of the template arguments.
  6807. for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
  6808. if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
  6809. UPPC_PartialSpecialization))
  6810. return true;
  6811. // Check that the template argument list is well-formed for this
  6812. // template.
  6813. SmallVector<TemplateArgument, 4> Converted;
  6814. if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
  6815. TemplateArgs, false, Converted))
  6816. return true;
  6817. // Find the class template (partial) specialization declaration that
  6818. // corresponds to these arguments.
  6819. if (isPartialSpecialization) {
  6820. if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate,
  6821. TemplateArgs.size(), Converted))
  6822. return true;
  6823. // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
  6824. // also do it during instantiation.
  6825. bool InstantiationDependent;
  6826. if (!Name.isDependent() &&
  6827. !TemplateSpecializationType::anyDependentTemplateArguments(
  6828. TemplateArgs.arguments(), InstantiationDependent)) {
  6829. Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
  6830. << ClassTemplate->getDeclName();
  6831. isPartialSpecialization = false;
  6832. }
  6833. }
  6834. void *InsertPos = nullptr;
  6835. ClassTemplateSpecializationDecl *PrevDecl = nullptr;
  6836. if (isPartialSpecialization)
  6837. // FIXME: Template parameter list matters, too
  6838. PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
  6839. else
  6840. PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
  6841. ClassTemplateSpecializationDecl *Specialization = nullptr;
  6842. // Check whether we can declare a class template specialization in
  6843. // the current scope.
  6844. if (TUK != TUK_Friend &&
  6845. CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
  6846. TemplateNameLoc,
  6847. isPartialSpecialization))
  6848. return true;
  6849. // The canonical type
  6850. QualType CanonType;
  6851. if (isPartialSpecialization) {
  6852. // Build the canonical type that describes the converted template
  6853. // arguments of the class template partial specialization.
  6854. TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
  6855. CanonType = Context.getTemplateSpecializationType(CanonTemplate,
  6856. Converted);
  6857. if (Context.hasSameType(CanonType,
  6858. ClassTemplate->getInjectedClassNameSpecialization())) {
  6859. // C++ [temp.class.spec]p9b3:
  6860. //
  6861. // -- The argument list of the specialization shall not be identical
  6862. // to the implicit argument list of the primary template.
  6863. //
  6864. // This rule has since been removed, because it's redundant given DR1495,
  6865. // but we keep it because it produces better diagnostics and recovery.
  6866. Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
  6867. << /*class template*/0 << (TUK == TUK_Definition)
  6868. << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
  6869. return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
  6870. ClassTemplate->getIdentifier(),
  6871. TemplateNameLoc,
  6872. Attr,
  6873. TemplateParams,
  6874. AS_none, /*ModulePrivateLoc=*/SourceLocation(),
  6875. /*FriendLoc*/SourceLocation(),
  6876. TemplateParameterLists.size() - 1,
  6877. TemplateParameterLists.data());
  6878. }
  6879. // Create a new class template partial specialization declaration node.
  6880. ClassTemplatePartialSpecializationDecl *PrevPartial
  6881. = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
  6882. ClassTemplatePartialSpecializationDecl *Partial
  6883. = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
  6884. ClassTemplate->getDeclContext(),
  6885. KWLoc, TemplateNameLoc,
  6886. TemplateParams,
  6887. ClassTemplate,
  6888. Converted,
  6889. TemplateArgs,
  6890. CanonType,
  6891. PrevPartial);
  6892. SetNestedNameSpecifier(*this, Partial, SS);
  6893. if (TemplateParameterLists.size() > 1 && SS.isSet()) {
  6894. Partial->setTemplateParameterListsInfo(
  6895. Context, TemplateParameterLists.drop_back(1));
  6896. }
  6897. if (!PrevPartial)
  6898. ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
  6899. Specialization = Partial;
  6900. // If we are providing an explicit specialization of a member class
  6901. // template specialization, make a note of that.
  6902. if (PrevPartial && PrevPartial->getInstantiatedFromMember())
  6903. PrevPartial->setMemberSpecialization();
  6904. CheckTemplatePartialSpecialization(Partial);
  6905. } else {
  6906. // Create a new class template specialization declaration node for
  6907. // this explicit specialization or friend declaration.
  6908. Specialization
  6909. = ClassTemplateSpecializationDecl::Create(Context, Kind,
  6910. ClassTemplate->getDeclContext(),
  6911. KWLoc, TemplateNameLoc,
  6912. ClassTemplate,
  6913. Converted,
  6914. PrevDecl);
  6915. SetNestedNameSpecifier(*this, Specialization, SS);
  6916. if (TemplateParameterLists.size() > 0) {
  6917. Specialization->setTemplateParameterListsInfo(Context,
  6918. TemplateParameterLists);
  6919. }
  6920. if (!PrevDecl)
  6921. ClassTemplate->AddSpecialization(Specialization, InsertPos);
  6922. if (CurContext->isDependentContext()) {
  6923. TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
  6924. CanonType = Context.getTemplateSpecializationType(
  6925. CanonTemplate, Converted);
  6926. } else {
  6927. CanonType = Context.getTypeDeclType(Specialization);
  6928. }
  6929. }
  6930. // C++ [temp.expl.spec]p6:
  6931. // If a template, a member template or the member of a class template is
  6932. // explicitly specialized then that specialization shall be declared
  6933. // before the first use of that specialization that would cause an implicit
  6934. // instantiation to take place, in every translation unit in which such a
  6935. // use occurs; no diagnostic is required.
  6936. if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
  6937. bool Okay = false;
  6938. for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
  6939. // Is there any previous explicit specialization declaration?
  6940. if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
  6941. Okay = true;
  6942. break;
  6943. }
  6944. }
  6945. if (!Okay) {
  6946. SourceRange Range(TemplateNameLoc, RAngleLoc);
  6947. Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
  6948. << Context.getTypeDeclType(Specialization) << Range;
  6949. Diag(PrevDecl->getPointOfInstantiation(),
  6950. diag::note_instantiation_required_here)
  6951. << (PrevDecl->getTemplateSpecializationKind()
  6952. != TSK_ImplicitInstantiation);
  6953. return true;
  6954. }
  6955. }
  6956. // If this is not a friend, note that this is an explicit specialization.
  6957. if (TUK != TUK_Friend)
  6958. Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
  6959. // Check that this isn't a redefinition of this specialization.
  6960. if (TUK == TUK_Definition) {
  6961. RecordDecl *Def = Specialization->getDefinition();
  6962. NamedDecl *Hidden = nullptr;
  6963. if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
  6964. SkipBody->ShouldSkip = true;
  6965. SkipBody->Previous = Def;
  6966. makeMergedDefinitionVisible(Hidden);
  6967. } else if (Def) {
  6968. SourceRange Range(TemplateNameLoc, RAngleLoc);
  6969. Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
  6970. Diag(Def->getLocation(), diag::note_previous_definition);
  6971. Specialization->setInvalidDecl();
  6972. return true;
  6973. }
  6974. }
  6975. ProcessDeclAttributeList(S, Specialization, Attr);
  6976. // Add alignment attributes if necessary; these attributes are checked when
  6977. // the ASTContext lays out the structure.
  6978. if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
  6979. AddAlignmentAttributesForRecord(Specialization);
  6980. AddMsStructLayoutForRecord(Specialization);
  6981. }
  6982. if (ModulePrivateLoc.isValid())
  6983. Diag(Specialization->getLocation(), diag::err_module_private_specialization)
  6984. << (isPartialSpecialization? 1 : 0)
  6985. << FixItHint::CreateRemoval(ModulePrivateLoc);
  6986. // Build the fully-sugared type for this class template
  6987. // specialization as the user wrote in the specialization
  6988. // itself. This means that we'll pretty-print the type retrieved
  6989. // from the specialization's declaration the way that the user
  6990. // actually wrote the specialization, rather than formatting the
  6991. // name based on the "canonical" representation used to store the
  6992. // template arguments in the specialization.
  6993. TypeSourceInfo *WrittenTy
  6994. = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
  6995. TemplateArgs, CanonType);
  6996. if (TUK != TUK_Friend) {
  6997. Specialization->setTypeAsWritten(WrittenTy);
  6998. Specialization->setTemplateKeywordLoc(TemplateKWLoc);
  6999. }
  7000. // C++ [temp.expl.spec]p9:
  7001. // A template explicit specialization is in the scope of the
  7002. // namespace in which the template was defined.
  7003. //
  7004. // We actually implement this paragraph where we set the semantic
  7005. // context (in the creation of the ClassTemplateSpecializationDecl),
  7006. // but we also maintain the lexical context where the actual
  7007. // definition occurs.
  7008. Specialization->setLexicalDeclContext(CurContext);
  7009. // We may be starting the definition of this specialization.
  7010. if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
  7011. Specialization->startDefinition();
  7012. if (TUK == TUK_Friend) {
  7013. FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
  7014. TemplateNameLoc,
  7015. WrittenTy,
  7016. /*FIXME:*/KWLoc);
  7017. Friend->setAccess(AS_public);
  7018. CurContext->addDecl(Friend);
  7019. } else {
  7020. // Add the specialization into its lexical context, so that it can
  7021. // be seen when iterating through the list of declarations in that
  7022. // context. However, specializations are not found by name lookup.
  7023. CurContext->addDecl(Specialization);
  7024. }
  7025. if (SkipBody && SkipBody->ShouldSkip)
  7026. return SkipBody->Previous;
  7027. return Specialization;
  7028. }
  7029. Decl *Sema::ActOnTemplateDeclarator(Scope *S,
  7030. MultiTemplateParamsArg TemplateParameterLists,
  7031. Declarator &D) {
  7032. Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
  7033. ActOnDocumentableDecl(NewDecl);
  7034. return NewDecl;
  7035. }
  7036. Decl *Sema::ActOnConceptDefinition(Scope *S,
  7037. MultiTemplateParamsArg TemplateParameterLists,
  7038. IdentifierInfo *Name, SourceLocation NameLoc,
  7039. Expr *ConstraintExpr) {
  7040. DeclContext *DC = CurContext;
  7041. if (!DC->getRedeclContext()->isFileContext()) {
  7042. Diag(NameLoc,
  7043. diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
  7044. return nullptr;
  7045. }
  7046. if (TemplateParameterLists.size() > 1) {
  7047. Diag(NameLoc, diag::err_concept_extra_headers);
  7048. return nullptr;
  7049. }
  7050. if (TemplateParameterLists.front()->size() == 0) {
  7051. Diag(NameLoc, diag::err_concept_no_parameters);
  7052. return nullptr;
  7053. }
  7054. ConceptDecl *NewDecl = ConceptDecl::Create(Context, DC, NameLoc, Name,
  7055. TemplateParameterLists.front(),
  7056. ConstraintExpr);
  7057. if (!ConstraintExpr->isTypeDependent() &&
  7058. ConstraintExpr->getType() != Context.BoolTy) {
  7059. // C++2a [temp.constr.atomic]p3:
  7060. // E shall be a constant expression of type bool.
  7061. // TODO: Do this check for individual atomic constraints
  7062. // and not the constraint expression. Probably should do it in
  7063. // ParseConstraintExpression.
  7064. Diag(ConstraintExpr->getSourceRange().getBegin(),
  7065. diag::err_concept_initialized_with_non_bool_type)
  7066. << ConstraintExpr->getType();
  7067. NewDecl->setInvalidDecl();
  7068. }
  7069. if (NewDecl->getAssociatedConstraints()) {
  7070. // C++2a [temp.concept]p4:
  7071. // A concept shall not have associated constraints.
  7072. // TODO: Make a test once we have actual associated constraints.
  7073. Diag(NameLoc, diag::err_concept_no_associated_constraints);
  7074. NewDecl->setInvalidDecl();
  7075. }
  7076. // Check for conflicting previous declaration.
  7077. DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NameLoc);
  7078. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  7079. ForVisibleRedeclaration);
  7080. LookupName(Previous, S);
  7081. FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage=*/false,
  7082. /*AllowInlineNamespace*/false);
  7083. if (!Previous.empty()) {
  7084. auto *Old = Previous.getRepresentativeDecl();
  7085. Diag(NameLoc, isa<ConceptDecl>(Old) ? diag::err_redefinition :
  7086. diag::err_redefinition_different_kind) << NewDecl->getDeclName();
  7087. Diag(Old->getLocation(), diag::note_previous_definition);
  7088. }
  7089. ActOnDocumentableDecl(NewDecl);
  7090. PushOnScopeChains(NewDecl, S);
  7091. return NewDecl;
  7092. }
  7093. /// \brief Strips various properties off an implicit instantiation
  7094. /// that has just been explicitly specialized.
  7095. static void StripImplicitInstantiation(NamedDecl *D) {
  7096. D->dropAttr<DLLImportAttr>();
  7097. D->dropAttr<DLLExportAttr>();
  7098. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
  7099. FD->setInlineSpecified(false);
  7100. }
  7101. /// Compute the diagnostic location for an explicit instantiation
  7102. // declaration or definition.
  7103. static SourceLocation DiagLocForExplicitInstantiation(
  7104. NamedDecl* D, SourceLocation PointOfInstantiation) {
  7105. // Explicit instantiations following a specialization have no effect and
  7106. // hence no PointOfInstantiation. In that case, walk decl backwards
  7107. // until a valid name loc is found.
  7108. SourceLocation PrevDiagLoc = PointOfInstantiation;
  7109. for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
  7110. Prev = Prev->getPreviousDecl()) {
  7111. PrevDiagLoc = Prev->getLocation();
  7112. }
  7113. assert(PrevDiagLoc.isValid() &&
  7114. "Explicit instantiation without point of instantiation?");
  7115. return PrevDiagLoc;
  7116. }
  7117. /// Diagnose cases where we have an explicit template specialization
  7118. /// before/after an explicit template instantiation, producing diagnostics
  7119. /// for those cases where they are required and determining whether the
  7120. /// new specialization/instantiation will have any effect.
  7121. ///
  7122. /// \param NewLoc the location of the new explicit specialization or
  7123. /// instantiation.
  7124. ///
  7125. /// \param NewTSK the kind of the new explicit specialization or instantiation.
  7126. ///
  7127. /// \param PrevDecl the previous declaration of the entity.
  7128. ///
  7129. /// \param PrevTSK the kind of the old explicit specialization or instantiatin.
  7130. ///
  7131. /// \param PrevPointOfInstantiation if valid, indicates where the previus
  7132. /// declaration was instantiated (either implicitly or explicitly).
  7133. ///
  7134. /// \param HasNoEffect will be set to true to indicate that the new
  7135. /// specialization or instantiation has no effect and should be ignored.
  7136. ///
  7137. /// \returns true if there was an error that should prevent the introduction of
  7138. /// the new declaration into the AST, false otherwise.
  7139. bool
  7140. Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
  7141. TemplateSpecializationKind NewTSK,
  7142. NamedDecl *PrevDecl,
  7143. TemplateSpecializationKind PrevTSK,
  7144. SourceLocation PrevPointOfInstantiation,
  7145. bool &HasNoEffect) {
  7146. HasNoEffect = false;
  7147. switch (NewTSK) {
  7148. case TSK_Undeclared:
  7149. case TSK_ImplicitInstantiation:
  7150. assert(
  7151. (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
  7152. "previous declaration must be implicit!");
  7153. return false;
  7154. case TSK_ExplicitSpecialization:
  7155. switch (PrevTSK) {
  7156. case TSK_Undeclared:
  7157. case TSK_ExplicitSpecialization:
  7158. // Okay, we're just specializing something that is either already
  7159. // explicitly specialized or has merely been mentioned without any
  7160. // instantiation.
  7161. return false;
  7162. case TSK_ImplicitInstantiation:
  7163. if (PrevPointOfInstantiation.isInvalid()) {
  7164. // The declaration itself has not actually been instantiated, so it is
  7165. // still okay to specialize it.
  7166. StripImplicitInstantiation(PrevDecl);
  7167. return false;
  7168. }
  7169. // Fall through
  7170. LLVM_FALLTHROUGH;
  7171. case TSK_ExplicitInstantiationDeclaration:
  7172. case TSK_ExplicitInstantiationDefinition:
  7173. assert((PrevTSK == TSK_ImplicitInstantiation ||
  7174. PrevPointOfInstantiation.isValid()) &&
  7175. "Explicit instantiation without point of instantiation?");
  7176. // C++ [temp.expl.spec]p6:
  7177. // If a template, a member template or the member of a class template
  7178. // is explicitly specialized then that specialization shall be declared
  7179. // before the first use of that specialization that would cause an
  7180. // implicit instantiation to take place, in every translation unit in
  7181. // which such a use occurs; no diagnostic is required.
  7182. for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
  7183. // Is there any previous explicit specialization declaration?
  7184. if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
  7185. return false;
  7186. }
  7187. Diag(NewLoc, diag::err_specialization_after_instantiation)
  7188. << PrevDecl;
  7189. Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
  7190. << (PrevTSK != TSK_ImplicitInstantiation);
  7191. return true;
  7192. }
  7193. llvm_unreachable("The switch over PrevTSK must be exhaustive.");
  7194. case TSK_ExplicitInstantiationDeclaration:
  7195. switch (PrevTSK) {
  7196. case TSK_ExplicitInstantiationDeclaration:
  7197. // This explicit instantiation declaration is redundant (that's okay).
  7198. HasNoEffect = true;
  7199. return false;
  7200. case TSK_Undeclared:
  7201. case TSK_ImplicitInstantiation:
  7202. // We're explicitly instantiating something that may have already been
  7203. // implicitly instantiated; that's fine.
  7204. return false;
  7205. case TSK_ExplicitSpecialization:
  7206. // C++0x [temp.explicit]p4:
  7207. // For a given set of template parameters, if an explicit instantiation
  7208. // of a template appears after a declaration of an explicit
  7209. // specialization for that template, the explicit instantiation has no
  7210. // effect.
  7211. HasNoEffect = true;
  7212. return false;
  7213. case TSK_ExplicitInstantiationDefinition:
  7214. // C++0x [temp.explicit]p10:
  7215. // If an entity is the subject of both an explicit instantiation
  7216. // declaration and an explicit instantiation definition in the same
  7217. // translation unit, the definition shall follow the declaration.
  7218. Diag(NewLoc,
  7219. diag::err_explicit_instantiation_declaration_after_definition);
  7220. // Explicit instantiations following a specialization have no effect and
  7221. // hence no PrevPointOfInstantiation. In that case, walk decl backwards
  7222. // until a valid name loc is found.
  7223. Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
  7224. diag::note_explicit_instantiation_definition_here);
  7225. HasNoEffect = true;
  7226. return false;
  7227. }
  7228. llvm_unreachable("Unexpected TemplateSpecializationKind!");
  7229. case TSK_ExplicitInstantiationDefinition:
  7230. switch (PrevTSK) {
  7231. case TSK_Undeclared:
  7232. case TSK_ImplicitInstantiation:
  7233. // We're explicitly instantiating something that may have already been
  7234. // implicitly instantiated; that's fine.
  7235. return false;
  7236. case TSK_ExplicitSpecialization:
  7237. // C++ DR 259, C++0x [temp.explicit]p4:
  7238. // For a given set of template parameters, if an explicit
  7239. // instantiation of a template appears after a declaration of
  7240. // an explicit specialization for that template, the explicit
  7241. // instantiation has no effect.
  7242. Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
  7243. << PrevDecl;
  7244. Diag(PrevDecl->getLocation(),
  7245. diag::note_previous_template_specialization);
  7246. HasNoEffect = true;
  7247. return false;
  7248. case TSK_ExplicitInstantiationDeclaration:
  7249. // We're explicitly instantiating a definition for something for which we
  7250. // were previously asked to suppress instantiations. That's fine.
  7251. // C++0x [temp.explicit]p4:
  7252. // For a given set of template parameters, if an explicit instantiation
  7253. // of a template appears after a declaration of an explicit
  7254. // specialization for that template, the explicit instantiation has no
  7255. // effect.
  7256. for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
  7257. // Is there any previous explicit specialization declaration?
  7258. if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
  7259. HasNoEffect = true;
  7260. break;
  7261. }
  7262. }
  7263. return false;
  7264. case TSK_ExplicitInstantiationDefinition:
  7265. // C++0x [temp.spec]p5:
  7266. // For a given template and a given set of template-arguments,
  7267. // - an explicit instantiation definition shall appear at most once
  7268. // in a program,
  7269. // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
  7270. Diag(NewLoc, (getLangOpts().MSVCCompat)
  7271. ? diag::ext_explicit_instantiation_duplicate
  7272. : diag::err_explicit_instantiation_duplicate)
  7273. << PrevDecl;
  7274. Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
  7275. diag::note_previous_explicit_instantiation);
  7276. HasNoEffect = true;
  7277. return false;
  7278. }
  7279. }
  7280. llvm_unreachable("Missing specialization/instantiation case?");
  7281. }
  7282. /// Perform semantic analysis for the given dependent function
  7283. /// template specialization.
  7284. ///
  7285. /// The only possible way to get a dependent function template specialization
  7286. /// is with a friend declaration, like so:
  7287. ///
  7288. /// \code
  7289. /// template \<class T> void foo(T);
  7290. /// template \<class T> class A {
  7291. /// friend void foo<>(T);
  7292. /// };
  7293. /// \endcode
  7294. ///
  7295. /// There really isn't any useful analysis we can do here, so we
  7296. /// just store the information.
  7297. bool
  7298. Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
  7299. const TemplateArgumentListInfo &ExplicitTemplateArgs,
  7300. LookupResult &Previous) {
  7301. // Remove anything from Previous that isn't a function template in
  7302. // the correct context.
  7303. DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
  7304. LookupResult::Filter F = Previous.makeFilter();
  7305. enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
  7306. SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
  7307. while (F.hasNext()) {
  7308. NamedDecl *D = F.next()->getUnderlyingDecl();
  7309. if (!isa<FunctionTemplateDecl>(D)) {
  7310. F.erase();
  7311. DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
  7312. continue;
  7313. }
  7314. if (!FDLookupContext->InEnclosingNamespaceSetOf(
  7315. D->getDeclContext()->getRedeclContext())) {
  7316. F.erase();
  7317. DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
  7318. continue;
  7319. }
  7320. }
  7321. F.done();
  7322. if (Previous.empty()) {
  7323. Diag(FD->getLocation(),
  7324. diag::err_dependent_function_template_spec_no_match);
  7325. for (auto &P : DiscardedCandidates)
  7326. Diag(P.second->getLocation(),
  7327. diag::note_dependent_function_template_spec_discard_reason)
  7328. << P.first;
  7329. return true;
  7330. }
  7331. FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
  7332. ExplicitTemplateArgs);
  7333. return false;
  7334. }
  7335. /// Perform semantic analysis for the given function template
  7336. /// specialization.
  7337. ///
  7338. /// This routine performs all of the semantic analysis required for an
  7339. /// explicit function template specialization. On successful completion,
  7340. /// the function declaration \p FD will become a function template
  7341. /// specialization.
  7342. ///
  7343. /// \param FD the function declaration, which will be updated to become a
  7344. /// function template specialization.
  7345. ///
  7346. /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
  7347. /// if any. Note that this may be valid info even when 0 arguments are
  7348. /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
  7349. /// as it anyway contains info on the angle brackets locations.
  7350. ///
  7351. /// \param Previous the set of declarations that may be specialized by
  7352. /// this function specialization.
  7353. ///
  7354. /// \param QualifiedFriend whether this is a lookup for a qualified friend
  7355. /// declaration with no explicit template argument list that might be
  7356. /// befriending a function template specialization.
  7357. bool Sema::CheckFunctionTemplateSpecialization(
  7358. FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
  7359. LookupResult &Previous, bool QualifiedFriend) {
  7360. // The set of function template specializations that could match this
  7361. // explicit function template specialization.
  7362. UnresolvedSet<8> Candidates;
  7363. TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
  7364. /*ForTakingAddress=*/false);
  7365. llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
  7366. ConvertedTemplateArgs;
  7367. DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
  7368. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  7369. I != E; ++I) {
  7370. NamedDecl *Ovl = (*I)->getUnderlyingDecl();
  7371. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
  7372. // Only consider templates found within the same semantic lookup scope as
  7373. // FD.
  7374. if (!FDLookupContext->InEnclosingNamespaceSetOf(
  7375. Ovl->getDeclContext()->getRedeclContext()))
  7376. continue;
  7377. // When matching a constexpr member function template specialization
  7378. // against the primary template, we don't yet know whether the
  7379. // specialization has an implicit 'const' (because we don't know whether
  7380. // it will be a static member function until we know which template it
  7381. // specializes), so adjust it now assuming it specializes this template.
  7382. QualType FT = FD->getType();
  7383. if (FD->isConstexpr()) {
  7384. CXXMethodDecl *OldMD =
  7385. dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
  7386. if (OldMD && OldMD->isConst()) {
  7387. const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
  7388. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  7389. EPI.TypeQuals.addConst();
  7390. FT = Context.getFunctionType(FPT->getReturnType(),
  7391. FPT->getParamTypes(), EPI);
  7392. }
  7393. }
  7394. TemplateArgumentListInfo Args;
  7395. if (ExplicitTemplateArgs)
  7396. Args = *ExplicitTemplateArgs;
  7397. // C++ [temp.expl.spec]p11:
  7398. // A trailing template-argument can be left unspecified in the
  7399. // template-id naming an explicit function template specialization
  7400. // provided it can be deduced from the function argument type.
  7401. // Perform template argument deduction to determine whether we may be
  7402. // specializing this template.
  7403. // FIXME: It is somewhat wasteful to build
  7404. TemplateDeductionInfo Info(FailedCandidates.getLocation());
  7405. FunctionDecl *Specialization = nullptr;
  7406. if (TemplateDeductionResult TDK = DeduceTemplateArguments(
  7407. cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
  7408. ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
  7409. Info)) {
  7410. // Template argument deduction failed; record why it failed, so
  7411. // that we can provide nifty diagnostics.
  7412. FailedCandidates.addCandidate().set(
  7413. I.getPair(), FunTmpl->getTemplatedDecl(),
  7414. MakeDeductionFailureInfo(Context, TDK, Info));
  7415. (void)TDK;
  7416. continue;
  7417. }
  7418. // Target attributes are part of the cuda function signature, so
  7419. // the deduced template's cuda target must match that of the
  7420. // specialization. Given that C++ template deduction does not
  7421. // take target attributes into account, we reject candidates
  7422. // here that have a different target.
  7423. if (LangOpts.CUDA &&
  7424. IdentifyCUDATarget(Specialization,
  7425. /* IgnoreImplicitHDAttr = */ true) !=
  7426. IdentifyCUDATarget(FD, /* IgnoreImplicitHDAttr = */ true)) {
  7427. FailedCandidates.addCandidate().set(
  7428. I.getPair(), FunTmpl->getTemplatedDecl(),
  7429. MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
  7430. continue;
  7431. }
  7432. // Record this candidate.
  7433. if (ExplicitTemplateArgs)
  7434. ConvertedTemplateArgs[Specialization] = std::move(Args);
  7435. Candidates.addDecl(Specialization, I.getAccess());
  7436. }
  7437. }
  7438. // For a qualified friend declaration (with no explicit marker to indicate
  7439. // that a template specialization was intended), note all (template and
  7440. // non-template) candidates.
  7441. if (QualifiedFriend && Candidates.empty()) {
  7442. Diag(FD->getLocation(), diag::err_qualified_friend_no_match)
  7443. << FD->getDeclName() << FDLookupContext;
  7444. // FIXME: We should form a single candidate list and diagnose all
  7445. // candidates at once, to get proper sorting and limiting.
  7446. for (auto *OldND : Previous) {
  7447. if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl()))
  7448. NoteOverloadCandidate(OldND, OldFD, FD->getType(), false);
  7449. }
  7450. FailedCandidates.NoteCandidates(*this, FD->getLocation());
  7451. return true;
  7452. }
  7453. // Find the most specialized function template.
  7454. UnresolvedSetIterator Result = getMostSpecialized(
  7455. Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),
  7456. PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
  7457. PDiag(diag::err_function_template_spec_ambiguous)
  7458. << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
  7459. PDiag(diag::note_function_template_spec_matched));
  7460. if (Result == Candidates.end())
  7461. return true;
  7462. // Ignore access information; it doesn't figure into redeclaration checking.
  7463. FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
  7464. FunctionTemplateSpecializationInfo *SpecInfo
  7465. = Specialization->getTemplateSpecializationInfo();
  7466. assert(SpecInfo && "Function template specialization info missing?");
  7467. // Note: do not overwrite location info if previous template
  7468. // specialization kind was explicit.
  7469. TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
  7470. if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
  7471. Specialization->setLocation(FD->getLocation());
  7472. Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
  7473. // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
  7474. // function can differ from the template declaration with respect to
  7475. // the constexpr specifier.
  7476. // FIXME: We need an update record for this AST mutation.
  7477. // FIXME: What if there are multiple such prior declarations (for instance,
  7478. // from different modules)?
  7479. Specialization->setConstexprKind(FD->getConstexprKind());
  7480. }
  7481. // FIXME: Check if the prior specialization has a point of instantiation.
  7482. // If so, we have run afoul of .
  7483. // If this is a friend declaration, then we're not really declaring
  7484. // an explicit specialization.
  7485. bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
  7486. // Check the scope of this explicit specialization.
  7487. if (!isFriend &&
  7488. CheckTemplateSpecializationScope(*this,
  7489. Specialization->getPrimaryTemplate(),
  7490. Specialization, FD->getLocation(),
  7491. false))
  7492. return true;
  7493. // C++ [temp.expl.spec]p6:
  7494. // If a template, a member template or the member of a class template is
  7495. // explicitly specialized then that specialization shall be declared
  7496. // before the first use of that specialization that would cause an implicit
  7497. // instantiation to take place, in every translation unit in which such a
  7498. // use occurs; no diagnostic is required.
  7499. bool HasNoEffect = false;
  7500. if (!isFriend &&
  7501. CheckSpecializationInstantiationRedecl(FD->getLocation(),
  7502. TSK_ExplicitSpecialization,
  7503. Specialization,
  7504. SpecInfo->getTemplateSpecializationKind(),
  7505. SpecInfo->getPointOfInstantiation(),
  7506. HasNoEffect))
  7507. return true;
  7508. // Mark the prior declaration as an explicit specialization, so that later
  7509. // clients know that this is an explicit specialization.
  7510. if (!isFriend) {
  7511. // Since explicit specializations do not inherit '=delete' from their
  7512. // primary function template - check if the 'specialization' that was
  7513. // implicitly generated (during template argument deduction for partial
  7514. // ordering) from the most specialized of all the function templates that
  7515. // 'FD' could have been specializing, has a 'deleted' definition. If so,
  7516. // first check that it was implicitly generated during template argument
  7517. // deduction by making sure it wasn't referenced, and then reset the deleted
  7518. // flag to not-deleted, so that we can inherit that information from 'FD'.
  7519. if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
  7520. !Specialization->getCanonicalDecl()->isReferenced()) {
  7521. // FIXME: This assert will not hold in the presence of modules.
  7522. assert(
  7523. Specialization->getCanonicalDecl() == Specialization &&
  7524. "This must be the only existing declaration of this specialization");
  7525. // FIXME: We need an update record for this AST mutation.
  7526. Specialization->setDeletedAsWritten(false);
  7527. }
  7528. // FIXME: We need an update record for this AST mutation.
  7529. SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
  7530. MarkUnusedFileScopedDecl(Specialization);
  7531. }
  7532. // Turn the given function declaration into a function template
  7533. // specialization, with the template arguments from the previous
  7534. // specialization.
  7535. // Take copies of (semantic and syntactic) template argument lists.
  7536. const TemplateArgumentList* TemplArgs = new (Context)
  7537. TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
  7538. FD->setFunctionTemplateSpecialization(
  7539. Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
  7540. SpecInfo->getTemplateSpecializationKind(),
  7541. ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
  7542. // A function template specialization inherits the target attributes
  7543. // of its template. (We require the attributes explicitly in the
  7544. // code to match, but a template may have implicit attributes by
  7545. // virtue e.g. of being constexpr, and it passes these implicit
  7546. // attributes on to its specializations.)
  7547. if (LangOpts.CUDA)
  7548. inheritCUDATargetAttrs(FD, *Specialization->getPrimaryTemplate());
  7549. // The "previous declaration" for this function template specialization is
  7550. // the prior function template specialization.
  7551. Previous.clear();
  7552. Previous.addDecl(Specialization);
  7553. return false;
  7554. }
  7555. /// Perform semantic analysis for the given non-template member
  7556. /// specialization.
  7557. ///
  7558. /// This routine performs all of the semantic analysis required for an
  7559. /// explicit member function specialization. On successful completion,
  7560. /// the function declaration \p FD will become a member function
  7561. /// specialization.
  7562. ///
  7563. /// \param Member the member declaration, which will be updated to become a
  7564. /// specialization.
  7565. ///
  7566. /// \param Previous the set of declarations, one of which may be specialized
  7567. /// by this function specialization; the set will be modified to contain the
  7568. /// redeclared member.
  7569. bool
  7570. Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
  7571. assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
  7572. // Try to find the member we are instantiating.
  7573. NamedDecl *FoundInstantiation = nullptr;
  7574. NamedDecl *Instantiation = nullptr;
  7575. NamedDecl *InstantiatedFrom = nullptr;
  7576. MemberSpecializationInfo *MSInfo = nullptr;
  7577. if (Previous.empty()) {
  7578. // Nowhere to look anyway.
  7579. } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
  7580. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  7581. I != E; ++I) {
  7582. NamedDecl *D = (*I)->getUnderlyingDecl();
  7583. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
  7584. QualType Adjusted = Function->getType();
  7585. if (!hasExplicitCallingConv(Adjusted))
  7586. Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
  7587. // This doesn't handle deduced return types, but both function
  7588. // declarations should be undeduced at this point.
  7589. if (Context.hasSameType(Adjusted, Method->getType())) {
  7590. FoundInstantiation = *I;
  7591. Instantiation = Method;
  7592. InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
  7593. MSInfo = Method->getMemberSpecializationInfo();
  7594. break;
  7595. }
  7596. }
  7597. }
  7598. } else if (isa<VarDecl>(Member)) {
  7599. VarDecl *PrevVar;
  7600. if (Previous.isSingleResult() &&
  7601. (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
  7602. if (PrevVar->isStaticDataMember()) {
  7603. FoundInstantiation = Previous.getRepresentativeDecl();
  7604. Instantiation = PrevVar;
  7605. InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
  7606. MSInfo = PrevVar->getMemberSpecializationInfo();
  7607. }
  7608. } else if (isa<RecordDecl>(Member)) {
  7609. CXXRecordDecl *PrevRecord;
  7610. if (Previous.isSingleResult() &&
  7611. (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
  7612. FoundInstantiation = Previous.getRepresentativeDecl();
  7613. Instantiation = PrevRecord;
  7614. InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
  7615. MSInfo = PrevRecord->getMemberSpecializationInfo();
  7616. }
  7617. } else if (isa<EnumDecl>(Member)) {
  7618. EnumDecl *PrevEnum;
  7619. if (Previous.isSingleResult() &&
  7620. (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
  7621. FoundInstantiation = Previous.getRepresentativeDecl();
  7622. Instantiation = PrevEnum;
  7623. InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
  7624. MSInfo = PrevEnum->getMemberSpecializationInfo();
  7625. }
  7626. }
  7627. if (!Instantiation) {
  7628. // There is no previous declaration that matches. Since member
  7629. // specializations are always out-of-line, the caller will complain about
  7630. // this mismatch later.
  7631. return false;
  7632. }
  7633. // A member specialization in a friend declaration isn't really declaring
  7634. // an explicit specialization, just identifying a specific (possibly implicit)
  7635. // specialization. Don't change the template specialization kind.
  7636. //
  7637. // FIXME: Is this really valid? Other compilers reject.
  7638. if (Member->getFriendObjectKind() != Decl::FOK_None) {
  7639. // Preserve instantiation information.
  7640. if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
  7641. cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
  7642. cast<CXXMethodDecl>(InstantiatedFrom),
  7643. cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
  7644. } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
  7645. cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
  7646. cast<CXXRecordDecl>(InstantiatedFrom),
  7647. cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
  7648. }
  7649. Previous.clear();
  7650. Previous.addDecl(FoundInstantiation);
  7651. return false;
  7652. }
  7653. // Make sure that this is a specialization of a member.
  7654. if (!InstantiatedFrom) {
  7655. Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
  7656. << Member;
  7657. Diag(Instantiation->getLocation(), diag::note_specialized_decl);
  7658. return true;
  7659. }
  7660. // C++ [temp.expl.spec]p6:
  7661. // If a template, a member template or the member of a class template is
  7662. // explicitly specialized then that specialization shall be declared
  7663. // before the first use of that specialization that would cause an implicit
  7664. // instantiation to take place, in every translation unit in which such a
  7665. // use occurs; no diagnostic is required.
  7666. assert(MSInfo && "Member specialization info missing?");
  7667. bool HasNoEffect = false;
  7668. if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
  7669. TSK_ExplicitSpecialization,
  7670. Instantiation,
  7671. MSInfo->getTemplateSpecializationKind(),
  7672. MSInfo->getPointOfInstantiation(),
  7673. HasNoEffect))
  7674. return true;
  7675. // Check the scope of this explicit specialization.
  7676. if (CheckTemplateSpecializationScope(*this,
  7677. InstantiatedFrom,
  7678. Instantiation, Member->getLocation(),
  7679. false))
  7680. return true;
  7681. // Note that this member specialization is an "instantiation of" the
  7682. // corresponding member of the original template.
  7683. if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
  7684. FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
  7685. if (InstantiationFunction->getTemplateSpecializationKind() ==
  7686. TSK_ImplicitInstantiation) {
  7687. // Explicit specializations of member functions of class templates do not
  7688. // inherit '=delete' from the member function they are specializing.
  7689. if (InstantiationFunction->isDeleted()) {
  7690. // FIXME: This assert will not hold in the presence of modules.
  7691. assert(InstantiationFunction->getCanonicalDecl() ==
  7692. InstantiationFunction);
  7693. // FIXME: We need an update record for this AST mutation.
  7694. InstantiationFunction->setDeletedAsWritten(false);
  7695. }
  7696. }
  7697. MemberFunction->setInstantiationOfMemberFunction(
  7698. cast<CXXMethodDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
  7699. } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
  7700. MemberVar->setInstantiationOfStaticDataMember(
  7701. cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
  7702. } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
  7703. MemberClass->setInstantiationOfMemberClass(
  7704. cast<CXXRecordDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
  7705. } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
  7706. MemberEnum->setInstantiationOfMemberEnum(
  7707. cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
  7708. } else {
  7709. llvm_unreachable("unknown member specialization kind");
  7710. }
  7711. // Save the caller the trouble of having to figure out which declaration
  7712. // this specialization matches.
  7713. Previous.clear();
  7714. Previous.addDecl(FoundInstantiation);
  7715. return false;
  7716. }
  7717. /// Complete the explicit specialization of a member of a class template by
  7718. /// updating the instantiated member to be marked as an explicit specialization.
  7719. ///
  7720. /// \param OrigD The member declaration instantiated from the template.
  7721. /// \param Loc The location of the explicit specialization of the member.
  7722. template<typename DeclT>
  7723. static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
  7724. SourceLocation Loc) {
  7725. if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
  7726. return;
  7727. // FIXME: Inform AST mutation listeners of this AST mutation.
  7728. // FIXME: If there are multiple in-class declarations of the member (from
  7729. // multiple modules, or a declaration and later definition of a member type),
  7730. // should we update all of them?
  7731. OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
  7732. OrigD->setLocation(Loc);
  7733. }
  7734. void Sema::CompleteMemberSpecialization(NamedDecl *Member,
  7735. LookupResult &Previous) {
  7736. NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
  7737. if (Instantiation == Member)
  7738. return;
  7739. if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
  7740. completeMemberSpecializationImpl(*this, Function, Member->getLocation());
  7741. else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
  7742. completeMemberSpecializationImpl(*this, Var, Member->getLocation());
  7743. else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
  7744. completeMemberSpecializationImpl(*this, Record, Member->getLocation());
  7745. else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
  7746. completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
  7747. else
  7748. llvm_unreachable("unknown member specialization kind");
  7749. }
  7750. /// Check the scope of an explicit instantiation.
  7751. ///
  7752. /// \returns true if a serious error occurs, false otherwise.
  7753. static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
  7754. SourceLocation InstLoc,
  7755. bool WasQualifiedName) {
  7756. DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
  7757. DeclContext *CurContext = S.CurContext->getRedeclContext();
  7758. if (CurContext->isRecord()) {
  7759. S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
  7760. << D;
  7761. return true;
  7762. }
  7763. // C++11 [temp.explicit]p3:
  7764. // An explicit instantiation shall appear in an enclosing namespace of its
  7765. // template. If the name declared in the explicit instantiation is an
  7766. // unqualified name, the explicit instantiation shall appear in the
  7767. // namespace where its template is declared or, if that namespace is inline
  7768. // (7.3.1), any namespace from its enclosing namespace set.
  7769. //
  7770. // This is DR275, which we do not retroactively apply to C++98/03.
  7771. if (WasQualifiedName) {
  7772. if (CurContext->Encloses(OrigContext))
  7773. return false;
  7774. } else {
  7775. if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
  7776. return false;
  7777. }
  7778. if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
  7779. if (WasQualifiedName)
  7780. S.Diag(InstLoc,
  7781. S.getLangOpts().CPlusPlus11?
  7782. diag::err_explicit_instantiation_out_of_scope :
  7783. diag::warn_explicit_instantiation_out_of_scope_0x)
  7784. << D << NS;
  7785. else
  7786. S.Diag(InstLoc,
  7787. S.getLangOpts().CPlusPlus11?
  7788. diag::err_explicit_instantiation_unqualified_wrong_namespace :
  7789. diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
  7790. << D << NS;
  7791. } else
  7792. S.Diag(InstLoc,
  7793. S.getLangOpts().CPlusPlus11?
  7794. diag::err_explicit_instantiation_must_be_global :
  7795. diag::warn_explicit_instantiation_must_be_global_0x)
  7796. << D;
  7797. S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
  7798. return false;
  7799. }
  7800. /// Common checks for whether an explicit instantiation of \p D is valid.
  7801. static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D,
  7802. SourceLocation InstLoc,
  7803. bool WasQualifiedName,
  7804. TemplateSpecializationKind TSK) {
  7805. // C++ [temp.explicit]p13:
  7806. // An explicit instantiation declaration shall not name a specialization of
  7807. // a template with internal linkage.
  7808. if (TSK == TSK_ExplicitInstantiationDeclaration &&
  7809. D->getFormalLinkage() == InternalLinkage) {
  7810. S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D;
  7811. return true;
  7812. }
  7813. // C++11 [temp.explicit]p3: [DR 275]
  7814. // An explicit instantiation shall appear in an enclosing namespace of its
  7815. // template.
  7816. if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
  7817. return true;
  7818. return false;
  7819. }
  7820. /// Determine whether the given scope specifier has a template-id in it.
  7821. static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
  7822. if (!SS.isSet())
  7823. return false;
  7824. // C++11 [temp.explicit]p3:
  7825. // If the explicit instantiation is for a member function, a member class
  7826. // or a static data member of a class template specialization, the name of
  7827. // the class template specialization in the qualified-id for the member
  7828. // name shall be a simple-template-id.
  7829. //
  7830. // C++98 has the same restriction, just worded differently.
  7831. for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
  7832. NNS = NNS->getPrefix())
  7833. if (const Type *T = NNS->getAsType())
  7834. if (isa<TemplateSpecializationType>(T))
  7835. return true;
  7836. return false;
  7837. }
  7838. /// Make a dllexport or dllimport attr on a class template specialization take
  7839. /// effect.
  7840. static void dllExportImportClassTemplateSpecialization(
  7841. Sema &S, ClassTemplateSpecializationDecl *Def) {
  7842. auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
  7843. assert(A && "dllExportImportClassTemplateSpecialization called "
  7844. "on Def without dllexport or dllimport");
  7845. // We reject explicit instantiations in class scope, so there should
  7846. // never be any delayed exported classes to worry about.
  7847. assert(S.DelayedDllExportClasses.empty() &&
  7848. "delayed exports present at explicit instantiation");
  7849. S.checkClassLevelDLLAttribute(Def);
  7850. // Propagate attribute to base class templates.
  7851. for (auto &B : Def->bases()) {
  7852. if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
  7853. B.getType()->getAsCXXRecordDecl()))
  7854. S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getBeginLoc());
  7855. }
  7856. S.referenceDLLExportedClassMethods();
  7857. }
  7858. // Explicit instantiation of a class template specialization
  7859. DeclResult Sema::ActOnExplicitInstantiation(
  7860. Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
  7861. unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
  7862. TemplateTy TemplateD, SourceLocation TemplateNameLoc,
  7863. SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
  7864. SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
  7865. // Find the class template we're specializing
  7866. TemplateName Name = TemplateD.get();
  7867. TemplateDecl *TD = Name.getAsTemplateDecl();
  7868. // Check that the specialization uses the same tag kind as the
  7869. // original template.
  7870. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  7871. assert(Kind != TTK_Enum &&
  7872. "Invalid enum tag in class template explicit instantiation!");
  7873. ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
  7874. if (!ClassTemplate) {
  7875. NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
  7876. Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
  7877. Diag(TD->getLocation(), diag::note_previous_use);
  7878. return true;
  7879. }
  7880. if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
  7881. Kind, /*isDefinition*/false, KWLoc,
  7882. ClassTemplate->getIdentifier())) {
  7883. Diag(KWLoc, diag::err_use_with_wrong_tag)
  7884. << ClassTemplate
  7885. << FixItHint::CreateReplacement(KWLoc,
  7886. ClassTemplate->getTemplatedDecl()->getKindName());
  7887. Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
  7888. diag::note_previous_use);
  7889. Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
  7890. }
  7891. // C++0x [temp.explicit]p2:
  7892. // There are two forms of explicit instantiation: an explicit instantiation
  7893. // definition and an explicit instantiation declaration. An explicit
  7894. // instantiation declaration begins with the extern keyword. [...]
  7895. TemplateSpecializationKind TSK = ExternLoc.isInvalid()
  7896. ? TSK_ExplicitInstantiationDefinition
  7897. : TSK_ExplicitInstantiationDeclaration;
  7898. if (TSK == TSK_ExplicitInstantiationDeclaration &&
  7899. !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
  7900. // Check for dllexport class template instantiation declarations,
  7901. // except for MinGW mode.
  7902. for (const ParsedAttr &AL : Attr) {
  7903. if (AL.getKind() == ParsedAttr::AT_DLLExport) {
  7904. Diag(ExternLoc,
  7905. diag::warn_attribute_dllexport_explicit_instantiation_decl);
  7906. Diag(AL.getLoc(), diag::note_attribute);
  7907. break;
  7908. }
  7909. }
  7910. if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
  7911. Diag(ExternLoc,
  7912. diag::warn_attribute_dllexport_explicit_instantiation_decl);
  7913. Diag(A->getLocation(), diag::note_attribute);
  7914. }
  7915. }
  7916. // In MSVC mode, dllimported explicit instantiation definitions are treated as
  7917. // instantiation declarations for most purposes.
  7918. bool DLLImportExplicitInstantiationDef = false;
  7919. if (TSK == TSK_ExplicitInstantiationDefinition &&
  7920. Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  7921. // Check for dllimport class template instantiation definitions.
  7922. bool DLLImport =
  7923. ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
  7924. for (const ParsedAttr &AL : Attr) {
  7925. if (AL.getKind() == ParsedAttr::AT_DLLImport)
  7926. DLLImport = true;
  7927. if (AL.getKind() == ParsedAttr::AT_DLLExport) {
  7928. // dllexport trumps dllimport here.
  7929. DLLImport = false;
  7930. break;
  7931. }
  7932. }
  7933. if (DLLImport) {
  7934. TSK = TSK_ExplicitInstantiationDeclaration;
  7935. DLLImportExplicitInstantiationDef = true;
  7936. }
  7937. }
  7938. // Translate the parser's template argument list in our AST format.
  7939. TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
  7940. translateTemplateArguments(TemplateArgsIn, TemplateArgs);
  7941. // Check that the template argument list is well-formed for this
  7942. // template.
  7943. SmallVector<TemplateArgument, 4> Converted;
  7944. if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
  7945. TemplateArgs, false, Converted))
  7946. return true;
  7947. // Find the class template specialization declaration that
  7948. // corresponds to these arguments.
  7949. void *InsertPos = nullptr;
  7950. ClassTemplateSpecializationDecl *PrevDecl
  7951. = ClassTemplate->findSpecialization(Converted, InsertPos);
  7952. TemplateSpecializationKind PrevDecl_TSK
  7953. = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
  7954. if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
  7955. Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
  7956. // Check for dllexport class template instantiation definitions in MinGW
  7957. // mode, if a previous declaration of the instantiation was seen.
  7958. for (const ParsedAttr &AL : Attr) {
  7959. if (AL.getKind() == ParsedAttr::AT_DLLExport) {
  7960. Diag(AL.getLoc(),
  7961. diag::warn_attribute_dllexport_explicit_instantiation_def);
  7962. break;
  7963. }
  7964. }
  7965. }
  7966. if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc,
  7967. SS.isSet(), TSK))
  7968. return true;
  7969. ClassTemplateSpecializationDecl *Specialization = nullptr;
  7970. bool HasNoEffect = false;
  7971. if (PrevDecl) {
  7972. if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
  7973. PrevDecl, PrevDecl_TSK,
  7974. PrevDecl->getPointOfInstantiation(),
  7975. HasNoEffect))
  7976. return PrevDecl;
  7977. // Even though HasNoEffect == true means that this explicit instantiation
  7978. // has no effect on semantics, we go on to put its syntax in the AST.
  7979. if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
  7980. PrevDecl_TSK == TSK_Undeclared) {
  7981. // Since the only prior class template specialization with these
  7982. // arguments was referenced but not declared, reuse that
  7983. // declaration node as our own, updating the source location
  7984. // for the template name to reflect our new declaration.
  7985. // (Other source locations will be updated later.)
  7986. Specialization = PrevDecl;
  7987. Specialization->setLocation(TemplateNameLoc);
  7988. PrevDecl = nullptr;
  7989. }
  7990. if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
  7991. DLLImportExplicitInstantiationDef) {
  7992. // The new specialization might add a dllimport attribute.
  7993. HasNoEffect = false;
  7994. }
  7995. }
  7996. if (!Specialization) {
  7997. // Create a new class template specialization declaration node for
  7998. // this explicit specialization.
  7999. Specialization
  8000. = ClassTemplateSpecializationDecl::Create(Context, Kind,
  8001. ClassTemplate->getDeclContext(),
  8002. KWLoc, TemplateNameLoc,
  8003. ClassTemplate,
  8004. Converted,
  8005. PrevDecl);
  8006. SetNestedNameSpecifier(*this, Specialization, SS);
  8007. if (!HasNoEffect && !PrevDecl) {
  8008. // Insert the new specialization.
  8009. ClassTemplate->AddSpecialization(Specialization, InsertPos);
  8010. }
  8011. }
  8012. // Build the fully-sugared type for this explicit instantiation as
  8013. // the user wrote in the explicit instantiation itself. This means
  8014. // that we'll pretty-print the type retrieved from the
  8015. // specialization's declaration the way that the user actually wrote
  8016. // the explicit instantiation, rather than formatting the name based
  8017. // on the "canonical" representation used to store the template
  8018. // arguments in the specialization.
  8019. TypeSourceInfo *WrittenTy
  8020. = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
  8021. TemplateArgs,
  8022. Context.getTypeDeclType(Specialization));
  8023. Specialization->setTypeAsWritten(WrittenTy);
  8024. // Set source locations for keywords.
  8025. Specialization->setExternLoc(ExternLoc);
  8026. Specialization->setTemplateKeywordLoc(TemplateLoc);
  8027. Specialization->setBraceRange(SourceRange());
  8028. bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
  8029. ProcessDeclAttributeList(S, Specialization, Attr);
  8030. // Add the explicit instantiation into its lexical context. However,
  8031. // since explicit instantiations are never found by name lookup, we
  8032. // just put it into the declaration context directly.
  8033. Specialization->setLexicalDeclContext(CurContext);
  8034. CurContext->addDecl(Specialization);
  8035. // Syntax is now OK, so return if it has no other effect on semantics.
  8036. if (HasNoEffect) {
  8037. // Set the template specialization kind.
  8038. Specialization->setTemplateSpecializationKind(TSK);
  8039. return Specialization;
  8040. }
  8041. // C++ [temp.explicit]p3:
  8042. // A definition of a class template or class member template
  8043. // shall be in scope at the point of the explicit instantiation of
  8044. // the class template or class member template.
  8045. //
  8046. // This check comes when we actually try to perform the
  8047. // instantiation.
  8048. ClassTemplateSpecializationDecl *Def
  8049. = cast_or_null<ClassTemplateSpecializationDecl>(
  8050. Specialization->getDefinition());
  8051. if (!Def)
  8052. InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
  8053. else if (TSK == TSK_ExplicitInstantiationDefinition) {
  8054. MarkVTableUsed(TemplateNameLoc, Specialization, true);
  8055. Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
  8056. }
  8057. // Instantiate the members of this class template specialization.
  8058. Def = cast_or_null<ClassTemplateSpecializationDecl>(
  8059. Specialization->getDefinition());
  8060. if (Def) {
  8061. TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
  8062. // Fix a TSK_ExplicitInstantiationDeclaration followed by a
  8063. // TSK_ExplicitInstantiationDefinition
  8064. if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
  8065. (TSK == TSK_ExplicitInstantiationDefinition ||
  8066. DLLImportExplicitInstantiationDef)) {
  8067. // FIXME: Need to notify the ASTMutationListener that we did this.
  8068. Def->setTemplateSpecializationKind(TSK);
  8069. if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
  8070. (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
  8071. Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
  8072. // In the MS ABI, an explicit instantiation definition can add a dll
  8073. // attribute to a template with a previous instantiation declaration.
  8074. // MinGW doesn't allow this.
  8075. auto *A = cast<InheritableAttr>(
  8076. getDLLAttr(Specialization)->clone(getASTContext()));
  8077. A->setInherited(true);
  8078. Def->addAttr(A);
  8079. dllExportImportClassTemplateSpecialization(*this, Def);
  8080. }
  8081. }
  8082. // Fix a TSK_ImplicitInstantiation followed by a
  8083. // TSK_ExplicitInstantiationDefinition
  8084. bool NewlyDLLExported =
  8085. !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
  8086. if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
  8087. (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
  8088. Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
  8089. // In the MS ABI, an explicit instantiation definition can add a dll
  8090. // attribute to a template with a previous implicit instantiation.
  8091. // MinGW doesn't allow this. We limit clang to only adding dllexport, to
  8092. // avoid potentially strange codegen behavior. For example, if we extend
  8093. // this conditional to dllimport, and we have a source file calling a
  8094. // method on an implicitly instantiated template class instance and then
  8095. // declaring a dllimport explicit instantiation definition for the same
  8096. // template class, the codegen for the method call will not respect the
  8097. // dllimport, while it will with cl. The Def will already have the DLL
  8098. // attribute, since the Def and Specialization will be the same in the
  8099. // case of Old_TSK == TSK_ImplicitInstantiation, and we already added the
  8100. // attribute to the Specialization; we just need to make it take effect.
  8101. assert(Def == Specialization &&
  8102. "Def and Specialization should match for implicit instantiation");
  8103. dllExportImportClassTemplateSpecialization(*this, Def);
  8104. }
  8105. // In MinGW mode, export the template instantiation if the declaration
  8106. // was marked dllexport.
  8107. if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
  8108. Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
  8109. PrevDecl->hasAttr<DLLExportAttr>()) {
  8110. dllExportImportClassTemplateSpecialization(*this, Def);
  8111. }
  8112. // Set the template specialization kind. Make sure it is set before
  8113. // instantiating the members which will trigger ASTConsumer callbacks.
  8114. Specialization->setTemplateSpecializationKind(TSK);
  8115. InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
  8116. } else {
  8117. // Set the template specialization kind.
  8118. Specialization->setTemplateSpecializationKind(TSK);
  8119. }
  8120. return Specialization;
  8121. }
  8122. // Explicit instantiation of a member class of a class template.
  8123. DeclResult
  8124. Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
  8125. SourceLocation TemplateLoc, unsigned TagSpec,
  8126. SourceLocation KWLoc, CXXScopeSpec &SS,
  8127. IdentifierInfo *Name, SourceLocation NameLoc,
  8128. const ParsedAttributesView &Attr) {
  8129. bool Owned = false;
  8130. bool IsDependent = false;
  8131. Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
  8132. KWLoc, SS, Name, NameLoc, Attr, AS_none,
  8133. /*ModulePrivateLoc=*/SourceLocation(),
  8134. MultiTemplateParamsArg(), Owned, IsDependent,
  8135. SourceLocation(), false, TypeResult(),
  8136. /*IsTypeSpecifier*/false,
  8137. /*IsTemplateParamOrArg*/false);
  8138. assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
  8139. if (!TagD)
  8140. return true;
  8141. TagDecl *Tag = cast<TagDecl>(TagD);
  8142. assert(!Tag->isEnum() && "shouldn't see enumerations here");
  8143. if (Tag->isInvalidDecl())
  8144. return true;
  8145. CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
  8146. CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
  8147. if (!Pattern) {
  8148. Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
  8149. << Context.getTypeDeclType(Record);
  8150. Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
  8151. return true;
  8152. }
  8153. // C++0x [temp.explicit]p2:
  8154. // If the explicit instantiation is for a class or member class, the
  8155. // elaborated-type-specifier in the declaration shall include a
  8156. // simple-template-id.
  8157. //
  8158. // C++98 has the same restriction, just worded differently.
  8159. if (!ScopeSpecifierHasTemplateId(SS))
  8160. Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
  8161. << Record << SS.getRange();
  8162. // C++0x [temp.explicit]p2:
  8163. // There are two forms of explicit instantiation: an explicit instantiation
  8164. // definition and an explicit instantiation declaration. An explicit
  8165. // instantiation declaration begins with the extern keyword. [...]
  8166. TemplateSpecializationKind TSK
  8167. = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
  8168. : TSK_ExplicitInstantiationDeclaration;
  8169. CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK);
  8170. // Verify that it is okay to explicitly instantiate here.
  8171. CXXRecordDecl *PrevDecl
  8172. = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
  8173. if (!PrevDecl && Record->getDefinition())
  8174. PrevDecl = Record;
  8175. if (PrevDecl) {
  8176. MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
  8177. bool HasNoEffect = false;
  8178. assert(MSInfo && "No member specialization information?");
  8179. if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
  8180. PrevDecl,
  8181. MSInfo->getTemplateSpecializationKind(),
  8182. MSInfo->getPointOfInstantiation(),
  8183. HasNoEffect))
  8184. return true;
  8185. if (HasNoEffect)
  8186. return TagD;
  8187. }
  8188. CXXRecordDecl *RecordDef
  8189. = cast_or_null<CXXRecordDecl>(Record->getDefinition());
  8190. if (!RecordDef) {
  8191. // C++ [temp.explicit]p3:
  8192. // A definition of a member class of a class template shall be in scope
  8193. // at the point of an explicit instantiation of the member class.
  8194. CXXRecordDecl *Def
  8195. = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
  8196. if (!Def) {
  8197. Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
  8198. << 0 << Record->getDeclName() << Record->getDeclContext();
  8199. Diag(Pattern->getLocation(), diag::note_forward_declaration)
  8200. << Pattern;
  8201. return true;
  8202. } else {
  8203. if (InstantiateClass(NameLoc, Record, Def,
  8204. getTemplateInstantiationArgs(Record),
  8205. TSK))
  8206. return true;
  8207. RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
  8208. if (!RecordDef)
  8209. return true;
  8210. }
  8211. }
  8212. // Instantiate all of the members of the class.
  8213. InstantiateClassMembers(NameLoc, RecordDef,
  8214. getTemplateInstantiationArgs(Record), TSK);
  8215. if (TSK == TSK_ExplicitInstantiationDefinition)
  8216. MarkVTableUsed(NameLoc, RecordDef, true);
  8217. // FIXME: We don't have any representation for explicit instantiations of
  8218. // member classes. Such a representation is not needed for compilation, but it
  8219. // should be available for clients that want to see all of the declarations in
  8220. // the source code.
  8221. return TagD;
  8222. }
  8223. DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
  8224. SourceLocation ExternLoc,
  8225. SourceLocation TemplateLoc,
  8226. Declarator &D) {
  8227. // Explicit instantiations always require a name.
  8228. // TODO: check if/when DNInfo should replace Name.
  8229. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  8230. DeclarationName Name = NameInfo.getName();
  8231. if (!Name) {
  8232. if (!D.isInvalidType())
  8233. Diag(D.getDeclSpec().getBeginLoc(),
  8234. diag::err_explicit_instantiation_requires_name)
  8235. << D.getDeclSpec().getSourceRange() << D.getSourceRange();
  8236. return true;
  8237. }
  8238. // The scope passed in may not be a decl scope. Zip up the scope tree until
  8239. // we find one that is.
  8240. while ((S->getFlags() & Scope::DeclScope) == 0 ||
  8241. (S->getFlags() & Scope::TemplateParamScope) != 0)
  8242. S = S->getParent();
  8243. // Determine the type of the declaration.
  8244. TypeSourceInfo *T = GetTypeForDeclarator(D, S);
  8245. QualType R = T->getType();
  8246. if (R.isNull())
  8247. return true;
  8248. // C++ [dcl.stc]p1:
  8249. // A storage-class-specifier shall not be specified in [...] an explicit
  8250. // instantiation (14.7.2) directive.
  8251. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
  8252. Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
  8253. << Name;
  8254. return true;
  8255. } else if (D.getDeclSpec().getStorageClassSpec()
  8256. != DeclSpec::SCS_unspecified) {
  8257. // Complain about then remove the storage class specifier.
  8258. Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
  8259. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  8260. D.getMutableDeclSpec().ClearStorageClassSpecs();
  8261. }
  8262. // C++0x [temp.explicit]p1:
  8263. // [...] An explicit instantiation of a function template shall not use the
  8264. // inline or constexpr specifiers.
  8265. // Presumably, this also applies to member functions of class templates as
  8266. // well.
  8267. if (D.getDeclSpec().isInlineSpecified())
  8268. Diag(D.getDeclSpec().getInlineSpecLoc(),
  8269. getLangOpts().CPlusPlus11 ?
  8270. diag::err_explicit_instantiation_inline :
  8271. diag::warn_explicit_instantiation_inline_0x)
  8272. << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
  8273. if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType())
  8274. // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
  8275. // not already specified.
  8276. Diag(D.getDeclSpec().getConstexprSpecLoc(),
  8277. diag::err_explicit_instantiation_constexpr);
  8278. // A deduction guide is not on the list of entities that can be explicitly
  8279. // instantiated.
  8280. if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
  8281. Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
  8282. << /*explicit instantiation*/ 0;
  8283. return true;
  8284. }
  8285. // C++0x [temp.explicit]p2:
  8286. // There are two forms of explicit instantiation: an explicit instantiation
  8287. // definition and an explicit instantiation declaration. An explicit
  8288. // instantiation declaration begins with the extern keyword. [...]
  8289. TemplateSpecializationKind TSK
  8290. = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
  8291. : TSK_ExplicitInstantiationDeclaration;
  8292. LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
  8293. LookupParsedName(Previous, S, &D.getCXXScopeSpec());
  8294. if (!R->isFunctionType()) {
  8295. // C++ [temp.explicit]p1:
  8296. // A [...] static data member of a class template can be explicitly
  8297. // instantiated from the member definition associated with its class
  8298. // template.
  8299. // C++1y [temp.explicit]p1:
  8300. // A [...] variable [...] template specialization can be explicitly
  8301. // instantiated from its template.
  8302. if (Previous.isAmbiguous())
  8303. return true;
  8304. VarDecl *Prev = Previous.getAsSingle<VarDecl>();
  8305. VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
  8306. if (!PrevTemplate) {
  8307. if (!Prev || !Prev->isStaticDataMember()) {
  8308. // We expect to see a static data member here.
  8309. Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
  8310. << Name;
  8311. for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
  8312. P != PEnd; ++P)
  8313. Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
  8314. return true;
  8315. }
  8316. if (!Prev->getInstantiatedFromStaticDataMember()) {
  8317. // FIXME: Check for explicit specialization?
  8318. Diag(D.getIdentifierLoc(),
  8319. diag::err_explicit_instantiation_data_member_not_instantiated)
  8320. << Prev;
  8321. Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
  8322. // FIXME: Can we provide a note showing where this was declared?
  8323. return true;
  8324. }
  8325. } else {
  8326. // Explicitly instantiate a variable template.
  8327. // C++1y [dcl.spec.auto]p6:
  8328. // ... A program that uses auto or decltype(auto) in a context not
  8329. // explicitly allowed in this section is ill-formed.
  8330. //
  8331. // This includes auto-typed variable template instantiations.
  8332. if (R->isUndeducedType()) {
  8333. Diag(T->getTypeLoc().getBeginLoc(),
  8334. diag::err_auto_not_allowed_var_inst);
  8335. return true;
  8336. }
  8337. if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
  8338. // C++1y [temp.explicit]p3:
  8339. // If the explicit instantiation is for a variable, the unqualified-id
  8340. // in the declaration shall be a template-id.
  8341. Diag(D.getIdentifierLoc(),
  8342. diag::err_explicit_instantiation_without_template_id)
  8343. << PrevTemplate;
  8344. Diag(PrevTemplate->getLocation(),
  8345. diag::note_explicit_instantiation_here);
  8346. return true;
  8347. }
  8348. // Translate the parser's template argument list into our AST format.
  8349. TemplateArgumentListInfo TemplateArgs =
  8350. makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
  8351. DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
  8352. D.getIdentifierLoc(), TemplateArgs);
  8353. if (Res.isInvalid())
  8354. return true;
  8355. // Ignore access control bits, we don't need them for redeclaration
  8356. // checking.
  8357. Prev = cast<VarDecl>(Res.get());
  8358. }
  8359. // C++0x [temp.explicit]p2:
  8360. // If the explicit instantiation is for a member function, a member class
  8361. // or a static data member of a class template specialization, the name of
  8362. // the class template specialization in the qualified-id for the member
  8363. // name shall be a simple-template-id.
  8364. //
  8365. // C++98 has the same restriction, just worded differently.
  8366. //
  8367. // This does not apply to variable template specializations, where the
  8368. // template-id is in the unqualified-id instead.
  8369. if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
  8370. Diag(D.getIdentifierLoc(),
  8371. diag::ext_explicit_instantiation_without_qualified_id)
  8372. << Prev << D.getCXXScopeSpec().getRange();
  8373. CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK);
  8374. // Verify that it is okay to explicitly instantiate here.
  8375. TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
  8376. SourceLocation POI = Prev->getPointOfInstantiation();
  8377. bool HasNoEffect = false;
  8378. if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
  8379. PrevTSK, POI, HasNoEffect))
  8380. return true;
  8381. if (!HasNoEffect) {
  8382. // Instantiate static data member or variable template.
  8383. Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
  8384. // Merge attributes.
  8385. ProcessDeclAttributeList(S, Prev, D.getDeclSpec().getAttributes());
  8386. if (TSK == TSK_ExplicitInstantiationDefinition)
  8387. InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
  8388. }
  8389. // Check the new variable specialization against the parsed input.
  8390. if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
  8391. Diag(T->getTypeLoc().getBeginLoc(),
  8392. diag::err_invalid_var_template_spec_type)
  8393. << 0 << PrevTemplate << R << Prev->getType();
  8394. Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
  8395. << 2 << PrevTemplate->getDeclName();
  8396. return true;
  8397. }
  8398. // FIXME: Create an ExplicitInstantiation node?
  8399. return (Decl*) nullptr;
  8400. }
  8401. // If the declarator is a template-id, translate the parser's template
  8402. // argument list into our AST format.
  8403. bool HasExplicitTemplateArgs = false;
  8404. TemplateArgumentListInfo TemplateArgs;
  8405. if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
  8406. TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
  8407. HasExplicitTemplateArgs = true;
  8408. }
  8409. // C++ [temp.explicit]p1:
  8410. // A [...] function [...] can be explicitly instantiated from its template.
  8411. // A member function [...] of a class template can be explicitly
  8412. // instantiated from the member definition associated with its class
  8413. // template.
  8414. UnresolvedSet<8> TemplateMatches;
  8415. FunctionDecl *NonTemplateMatch = nullptr;
  8416. TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
  8417. for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
  8418. P != PEnd; ++P) {
  8419. NamedDecl *Prev = *P;
  8420. if (!HasExplicitTemplateArgs) {
  8421. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
  8422. QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
  8423. /*AdjustExceptionSpec*/true);
  8424. if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
  8425. if (Method->getPrimaryTemplate()) {
  8426. TemplateMatches.addDecl(Method, P.getAccess());
  8427. } else {
  8428. // FIXME: Can this assert ever happen? Needs a test.
  8429. assert(!NonTemplateMatch && "Multiple NonTemplateMatches");
  8430. NonTemplateMatch = Method;
  8431. }
  8432. }
  8433. }
  8434. }
  8435. FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
  8436. if (!FunTmpl)
  8437. continue;
  8438. TemplateDeductionInfo Info(FailedCandidates.getLocation());
  8439. FunctionDecl *Specialization = nullptr;
  8440. if (TemplateDeductionResult TDK
  8441. = DeduceTemplateArguments(FunTmpl,
  8442. (HasExplicitTemplateArgs ? &TemplateArgs
  8443. : nullptr),
  8444. R, Specialization, Info)) {
  8445. // Keep track of almost-matches.
  8446. FailedCandidates.addCandidate()
  8447. .set(P.getPair(), FunTmpl->getTemplatedDecl(),
  8448. MakeDeductionFailureInfo(Context, TDK, Info));
  8449. (void)TDK;
  8450. continue;
  8451. }
  8452. // Target attributes are part of the cuda function signature, so
  8453. // the cuda target of the instantiated function must match that of its
  8454. // template. Given that C++ template deduction does not take
  8455. // target attributes into account, we reject candidates here that
  8456. // have a different target.
  8457. if (LangOpts.CUDA &&
  8458. IdentifyCUDATarget(Specialization,
  8459. /* IgnoreImplicitHDAttr = */ true) !=
  8460. IdentifyCUDATarget(D.getDeclSpec().getAttributes())) {
  8461. FailedCandidates.addCandidate().set(
  8462. P.getPair(), FunTmpl->getTemplatedDecl(),
  8463. MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
  8464. continue;
  8465. }
  8466. TemplateMatches.addDecl(Specialization, P.getAccess());
  8467. }
  8468. FunctionDecl *Specialization = NonTemplateMatch;
  8469. if (!Specialization) {
  8470. // Find the most specialized function template specialization.
  8471. UnresolvedSetIterator Result = getMostSpecialized(
  8472. TemplateMatches.begin(), TemplateMatches.end(), FailedCandidates,
  8473. D.getIdentifierLoc(),
  8474. PDiag(diag::err_explicit_instantiation_not_known) << Name,
  8475. PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
  8476. PDiag(diag::note_explicit_instantiation_candidate));
  8477. if (Result == TemplateMatches.end())
  8478. return true;
  8479. // Ignore access control bits, we don't need them for redeclaration checking.
  8480. Specialization = cast<FunctionDecl>(*Result);
  8481. }
  8482. // C++11 [except.spec]p4
  8483. // In an explicit instantiation an exception-specification may be specified,
  8484. // but is not required.
  8485. // If an exception-specification is specified in an explicit instantiation
  8486. // directive, it shall be compatible with the exception-specifications of
  8487. // other declarations of that function.
  8488. if (auto *FPT = R->getAs<FunctionProtoType>())
  8489. if (FPT->hasExceptionSpec()) {
  8490. unsigned DiagID =
  8491. diag::err_mismatched_exception_spec_explicit_instantiation;
  8492. if (getLangOpts().MicrosoftExt)
  8493. DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
  8494. bool Result = CheckEquivalentExceptionSpec(
  8495. PDiag(DiagID) << Specialization->getType(),
  8496. PDiag(diag::note_explicit_instantiation_here),
  8497. Specialization->getType()->getAs<FunctionProtoType>(),
  8498. Specialization->getLocation(), FPT, D.getBeginLoc());
  8499. // In Microsoft mode, mismatching exception specifications just cause a
  8500. // warning.
  8501. if (!getLangOpts().MicrosoftExt && Result)
  8502. return true;
  8503. }
  8504. if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
  8505. Diag(D.getIdentifierLoc(),
  8506. diag::err_explicit_instantiation_member_function_not_instantiated)
  8507. << Specialization
  8508. << (Specialization->getTemplateSpecializationKind() ==
  8509. TSK_ExplicitSpecialization);
  8510. Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
  8511. return true;
  8512. }
  8513. FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
  8514. if (!PrevDecl && Specialization->isThisDeclarationADefinition())
  8515. PrevDecl = Specialization;
  8516. if (PrevDecl) {
  8517. bool HasNoEffect = false;
  8518. if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
  8519. PrevDecl,
  8520. PrevDecl->getTemplateSpecializationKind(),
  8521. PrevDecl->getPointOfInstantiation(),
  8522. HasNoEffect))
  8523. return true;
  8524. // FIXME: We may still want to build some representation of this
  8525. // explicit specialization.
  8526. if (HasNoEffect)
  8527. return (Decl*) nullptr;
  8528. }
  8529. // HACK: libc++ has a bug where it attempts to explicitly instantiate the
  8530. // functions
  8531. // valarray<size_t>::valarray(size_t) and
  8532. // valarray<size_t>::~valarray()
  8533. // that it declared to have internal linkage with the internal_linkage
  8534. // attribute. Ignore the explicit instantiation declaration in this case.
  8535. if (Specialization->hasAttr<InternalLinkageAttr>() &&
  8536. TSK == TSK_ExplicitInstantiationDeclaration) {
  8537. if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext()))
  8538. if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") &&
  8539. RD->isInStdNamespace())
  8540. return (Decl*) nullptr;
  8541. }
  8542. ProcessDeclAttributeList(S, Specialization, D.getDeclSpec().getAttributes());
  8543. // In MSVC mode, dllimported explicit instantiation definitions are treated as
  8544. // instantiation declarations.
  8545. if (TSK == TSK_ExplicitInstantiationDefinition &&
  8546. Specialization->hasAttr<DLLImportAttr>() &&
  8547. Context.getTargetInfo().getCXXABI().isMicrosoft())
  8548. TSK = TSK_ExplicitInstantiationDeclaration;
  8549. Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
  8550. if (Specialization->isDefined()) {
  8551. // Let the ASTConsumer know that this function has been explicitly
  8552. // instantiated now, and its linkage might have changed.
  8553. Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
  8554. } else if (TSK == TSK_ExplicitInstantiationDefinition)
  8555. InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
  8556. // C++0x [temp.explicit]p2:
  8557. // If the explicit instantiation is for a member function, a member class
  8558. // or a static data member of a class template specialization, the name of
  8559. // the class template specialization in the qualified-id for the member
  8560. // name shall be a simple-template-id.
  8561. //
  8562. // C++98 has the same restriction, just worded differently.
  8563. FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
  8564. if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
  8565. D.getCXXScopeSpec().isSet() &&
  8566. !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
  8567. Diag(D.getIdentifierLoc(),
  8568. diag::ext_explicit_instantiation_without_qualified_id)
  8569. << Specialization << D.getCXXScopeSpec().getRange();
  8570. CheckExplicitInstantiation(
  8571. *this,
  8572. FunTmpl ? (NamedDecl *)FunTmpl
  8573. : Specialization->getInstantiatedFromMemberFunction(),
  8574. D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK);
  8575. // FIXME: Create some kind of ExplicitInstantiationDecl here.
  8576. return (Decl*) nullptr;
  8577. }
  8578. TypeResult
  8579. Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
  8580. const CXXScopeSpec &SS, IdentifierInfo *Name,
  8581. SourceLocation TagLoc, SourceLocation NameLoc) {
  8582. // This has to hold, because SS is expected to be defined.
  8583. assert(Name && "Expected a name in a dependent tag");
  8584. NestedNameSpecifier *NNS = SS.getScopeRep();
  8585. if (!NNS)
  8586. return true;
  8587. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  8588. if (TUK == TUK_Declaration || TUK == TUK_Definition) {
  8589. Diag(NameLoc, diag::err_dependent_tag_decl)
  8590. << (TUK == TUK_Definition) << Kind << SS.getRange();
  8591. return true;
  8592. }
  8593. // Create the resulting type.
  8594. ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
  8595. QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
  8596. // Create type-source location information for this type.
  8597. TypeLocBuilder TLB;
  8598. DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
  8599. TL.setElaboratedKeywordLoc(TagLoc);
  8600. TL.setQualifierLoc(SS.getWithLocInContext(Context));
  8601. TL.setNameLoc(NameLoc);
  8602. return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
  8603. }
  8604. TypeResult
  8605. Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
  8606. const CXXScopeSpec &SS, const IdentifierInfo &II,
  8607. SourceLocation IdLoc) {
  8608. if (SS.isInvalid())
  8609. return true;
  8610. if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
  8611. Diag(TypenameLoc,
  8612. getLangOpts().CPlusPlus11 ?
  8613. diag::warn_cxx98_compat_typename_outside_of_template :
  8614. diag::ext_typename_outside_of_template)
  8615. << FixItHint::CreateRemoval(TypenameLoc);
  8616. NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
  8617. QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
  8618. TypenameLoc, QualifierLoc, II, IdLoc);
  8619. if (T.isNull())
  8620. return true;
  8621. TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
  8622. if (isa<DependentNameType>(T)) {
  8623. DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
  8624. TL.setElaboratedKeywordLoc(TypenameLoc);
  8625. TL.setQualifierLoc(QualifierLoc);
  8626. TL.setNameLoc(IdLoc);
  8627. } else {
  8628. ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
  8629. TL.setElaboratedKeywordLoc(TypenameLoc);
  8630. TL.setQualifierLoc(QualifierLoc);
  8631. TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
  8632. }
  8633. return CreateParsedType(T, TSI);
  8634. }
  8635. TypeResult
  8636. Sema::ActOnTypenameType(Scope *S,
  8637. SourceLocation TypenameLoc,
  8638. const CXXScopeSpec &SS,
  8639. SourceLocation TemplateKWLoc,
  8640. TemplateTy TemplateIn,
  8641. IdentifierInfo *TemplateII,
  8642. SourceLocation TemplateIILoc,
  8643. SourceLocation LAngleLoc,
  8644. ASTTemplateArgsPtr TemplateArgsIn,
  8645. SourceLocation RAngleLoc) {
  8646. if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
  8647. Diag(TypenameLoc,
  8648. getLangOpts().CPlusPlus11 ?
  8649. diag::warn_cxx98_compat_typename_outside_of_template :
  8650. diag::ext_typename_outside_of_template)
  8651. << FixItHint::CreateRemoval(TypenameLoc);
  8652. // Strangely, non-type results are not ignored by this lookup, so the
  8653. // program is ill-formed if it finds an injected-class-name.
  8654. if (TypenameLoc.isValid()) {
  8655. auto *LookupRD =
  8656. dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
  8657. if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
  8658. Diag(TemplateIILoc,
  8659. diag::ext_out_of_line_qualified_id_type_names_constructor)
  8660. << TemplateII << 0 /*injected-class-name used as template name*/
  8661. << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
  8662. }
  8663. }
  8664. // Translate the parser's template argument list in our AST format.
  8665. TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
  8666. translateTemplateArguments(TemplateArgsIn, TemplateArgs);
  8667. TemplateName Template = TemplateIn.get();
  8668. if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
  8669. // Construct a dependent template specialization type.
  8670. assert(DTN && "dependent template has non-dependent name?");
  8671. assert(DTN->getQualifier() == SS.getScopeRep());
  8672. QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
  8673. DTN->getQualifier(),
  8674. DTN->getIdentifier(),
  8675. TemplateArgs);
  8676. // Create source-location information for this type.
  8677. TypeLocBuilder Builder;
  8678. DependentTemplateSpecializationTypeLoc SpecTL
  8679. = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
  8680. SpecTL.setElaboratedKeywordLoc(TypenameLoc);
  8681. SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
  8682. SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
  8683. SpecTL.setTemplateNameLoc(TemplateIILoc);
  8684. SpecTL.setLAngleLoc(LAngleLoc);
  8685. SpecTL.setRAngleLoc(RAngleLoc);
  8686. for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
  8687. SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
  8688. return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  8689. }
  8690. QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
  8691. if (T.isNull())
  8692. return true;
  8693. // Provide source-location information for the template specialization type.
  8694. TypeLocBuilder Builder;
  8695. TemplateSpecializationTypeLoc SpecTL
  8696. = Builder.push<TemplateSpecializationTypeLoc>(T);
  8697. SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
  8698. SpecTL.setTemplateNameLoc(TemplateIILoc);
  8699. SpecTL.setLAngleLoc(LAngleLoc);
  8700. SpecTL.setRAngleLoc(RAngleLoc);
  8701. for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
  8702. SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
  8703. T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
  8704. ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
  8705. TL.setElaboratedKeywordLoc(TypenameLoc);
  8706. TL.setQualifierLoc(SS.getWithLocInContext(Context));
  8707. TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
  8708. return CreateParsedType(T, TSI);
  8709. }
  8710. /// Determine whether this failed name lookup should be treated as being
  8711. /// disabled by a usage of std::enable_if.
  8712. static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
  8713. SourceRange &CondRange, Expr *&Cond) {
  8714. // We must be looking for a ::type...
  8715. if (!II.isStr("type"))
  8716. return false;
  8717. // ... within an explicitly-written template specialization...
  8718. if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
  8719. return false;
  8720. TypeLoc EnableIfTy = NNS.getTypeLoc();
  8721. TemplateSpecializationTypeLoc EnableIfTSTLoc =
  8722. EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
  8723. if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
  8724. return false;
  8725. const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
  8726. // ... which names a complete class template declaration...
  8727. const TemplateDecl *EnableIfDecl =
  8728. EnableIfTST->getTemplateName().getAsTemplateDecl();
  8729. if (!EnableIfDecl || EnableIfTST->isIncompleteType())
  8730. return false;
  8731. // ... called "enable_if".
  8732. const IdentifierInfo *EnableIfII =
  8733. EnableIfDecl->getDeclName().getAsIdentifierInfo();
  8734. if (!EnableIfII || !EnableIfII->isStr("enable_if"))
  8735. return false;
  8736. // Assume the first template argument is the condition.
  8737. CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
  8738. // Dig out the condition.
  8739. Cond = nullptr;
  8740. if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
  8741. != TemplateArgument::Expression)
  8742. return true;
  8743. Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
  8744. // Ignore Boolean literals; they add no value.
  8745. if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
  8746. Cond = nullptr;
  8747. return true;
  8748. }
  8749. /// Build the type that describes a C++ typename specifier,
  8750. /// e.g., "typename T::type".
  8751. QualType
  8752. Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
  8753. SourceLocation KeywordLoc,
  8754. NestedNameSpecifierLoc QualifierLoc,
  8755. const IdentifierInfo &II,
  8756. SourceLocation IILoc) {
  8757. CXXScopeSpec SS;
  8758. SS.Adopt(QualifierLoc);
  8759. DeclContext *Ctx = computeDeclContext(SS);
  8760. if (!Ctx) {
  8761. // If the nested-name-specifier is dependent and couldn't be
  8762. // resolved to a type, build a typename type.
  8763. assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
  8764. return Context.getDependentNameType(Keyword,
  8765. QualifierLoc.getNestedNameSpecifier(),
  8766. &II);
  8767. }
  8768. // If the nested-name-specifier refers to the current instantiation,
  8769. // the "typename" keyword itself is superfluous. In C++03, the
  8770. // program is actually ill-formed. However, DR 382 (in C++0x CD1)
  8771. // allows such extraneous "typename" keywords, and we retroactively
  8772. // apply this DR to C++03 code with only a warning. In any case we continue.
  8773. if (RequireCompleteDeclContext(SS, Ctx))
  8774. return QualType();
  8775. DeclarationName Name(&II);
  8776. LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
  8777. LookupQualifiedName(Result, Ctx, SS);
  8778. unsigned DiagID = 0;
  8779. Decl *Referenced = nullptr;
  8780. switch (Result.getResultKind()) {
  8781. case LookupResult::NotFound: {
  8782. // If we're looking up 'type' within a template named 'enable_if', produce
  8783. // a more specific diagnostic.
  8784. SourceRange CondRange;
  8785. Expr *Cond = nullptr;
  8786. if (isEnableIf(QualifierLoc, II, CondRange, Cond)) {
  8787. // If we have a condition, narrow it down to the specific failed
  8788. // condition.
  8789. if (Cond) {
  8790. Expr *FailedCond;
  8791. std::string FailedDescription;
  8792. std::tie(FailedCond, FailedDescription) =
  8793. findFailedBooleanCondition(Cond);
  8794. Diag(FailedCond->getExprLoc(),
  8795. diag::err_typename_nested_not_found_requirement)
  8796. << FailedDescription
  8797. << FailedCond->getSourceRange();
  8798. return QualType();
  8799. }
  8800. Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
  8801. << Ctx << CondRange;
  8802. return QualType();
  8803. }
  8804. DiagID = diag::err_typename_nested_not_found;
  8805. break;
  8806. }
  8807. case LookupResult::FoundUnresolvedValue: {
  8808. // We found a using declaration that is a value. Most likely, the using
  8809. // declaration itself is meant to have the 'typename' keyword.
  8810. SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
  8811. IILoc);
  8812. Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
  8813. << Name << Ctx << FullRange;
  8814. if (UnresolvedUsingValueDecl *Using
  8815. = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
  8816. SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
  8817. Diag(Loc, diag::note_using_value_decl_missing_typename)
  8818. << FixItHint::CreateInsertion(Loc, "typename ");
  8819. }
  8820. }
  8821. // Fall through to create a dependent typename type, from which we can recover
  8822. // better.
  8823. LLVM_FALLTHROUGH;
  8824. case LookupResult::NotFoundInCurrentInstantiation:
  8825. // Okay, it's a member of an unknown instantiation.
  8826. return Context.getDependentNameType(Keyword,
  8827. QualifierLoc.getNestedNameSpecifier(),
  8828. &II);
  8829. case LookupResult::Found:
  8830. if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
  8831. // C++ [class.qual]p2:
  8832. // In a lookup in which function names are not ignored and the
  8833. // nested-name-specifier nominates a class C, if the name specified
  8834. // after the nested-name-specifier, when looked up in C, is the
  8835. // injected-class-name of C [...] then the name is instead considered
  8836. // to name the constructor of class C.
  8837. //
  8838. // Unlike in an elaborated-type-specifier, function names are not ignored
  8839. // in typename-specifier lookup. However, they are ignored in all the
  8840. // contexts where we form a typename type with no keyword (that is, in
  8841. // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
  8842. //
  8843. // FIXME: That's not strictly true: mem-initializer-id lookup does not
  8844. // ignore functions, but that appears to be an oversight.
  8845. auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
  8846. auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
  8847. if (Keyword == ETK_Typename && LookupRD && FoundRD &&
  8848. FoundRD->isInjectedClassName() &&
  8849. declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
  8850. Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
  8851. << &II << 1 << 0 /*'typename' keyword used*/;
  8852. // We found a type. Build an ElaboratedType, since the
  8853. // typename-specifier was just sugar.
  8854. MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
  8855. return Context.getElaboratedType(Keyword,
  8856. QualifierLoc.getNestedNameSpecifier(),
  8857. Context.getTypeDeclType(Type));
  8858. }
  8859. // C++ [dcl.type.simple]p2:
  8860. // A type-specifier of the form
  8861. // typename[opt] nested-name-specifier[opt] template-name
  8862. // is a placeholder for a deduced class type [...].
  8863. if (getLangOpts().CPlusPlus17) {
  8864. if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
  8865. return Context.getElaboratedType(
  8866. Keyword, QualifierLoc.getNestedNameSpecifier(),
  8867. Context.getDeducedTemplateSpecializationType(TemplateName(TD),
  8868. QualType(), false));
  8869. }
  8870. }
  8871. DiagID = diag::err_typename_nested_not_type;
  8872. Referenced = Result.getFoundDecl();
  8873. break;
  8874. case LookupResult::FoundOverloaded:
  8875. DiagID = diag::err_typename_nested_not_type;
  8876. Referenced = *Result.begin();
  8877. break;
  8878. case LookupResult::Ambiguous:
  8879. return QualType();
  8880. }
  8881. // If we get here, it's because name lookup did not find a
  8882. // type. Emit an appropriate diagnostic and return an error.
  8883. SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
  8884. IILoc);
  8885. Diag(IILoc, DiagID) << FullRange << Name << Ctx;
  8886. if (Referenced)
  8887. Diag(Referenced->getLocation(), diag::note_typename_refers_here)
  8888. << Name;
  8889. return QualType();
  8890. }
  8891. namespace {
  8892. // See Sema::RebuildTypeInCurrentInstantiation
  8893. class CurrentInstantiationRebuilder
  8894. : public TreeTransform<CurrentInstantiationRebuilder> {
  8895. SourceLocation Loc;
  8896. DeclarationName Entity;
  8897. public:
  8898. typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
  8899. CurrentInstantiationRebuilder(Sema &SemaRef,
  8900. SourceLocation Loc,
  8901. DeclarationName Entity)
  8902. : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
  8903. Loc(Loc), Entity(Entity) { }
  8904. /// Determine whether the given type \p T has already been
  8905. /// transformed.
  8906. ///
  8907. /// For the purposes of type reconstruction, a type has already been
  8908. /// transformed if it is NULL or if it is not dependent.
  8909. bool AlreadyTransformed(QualType T) {
  8910. return T.isNull() || !T->isDependentType();
  8911. }
  8912. /// Returns the location of the entity whose type is being
  8913. /// rebuilt.
  8914. SourceLocation getBaseLocation() { return Loc; }
  8915. /// Returns the name of the entity whose type is being rebuilt.
  8916. DeclarationName getBaseEntity() { return Entity; }
  8917. /// Sets the "base" location and entity when that
  8918. /// information is known based on another transformation.
  8919. void setBase(SourceLocation Loc, DeclarationName Entity) {
  8920. this->Loc = Loc;
  8921. this->Entity = Entity;
  8922. }
  8923. ExprResult TransformLambdaExpr(LambdaExpr *E) {
  8924. // Lambdas never need to be transformed.
  8925. return E;
  8926. }
  8927. };
  8928. } // end anonymous namespace
  8929. /// Rebuilds a type within the context of the current instantiation.
  8930. ///
  8931. /// The type \p T is part of the type of an out-of-line member definition of
  8932. /// a class template (or class template partial specialization) that was parsed
  8933. /// and constructed before we entered the scope of the class template (or
  8934. /// partial specialization thereof). This routine will rebuild that type now
  8935. /// that we have entered the declarator's scope, which may produce different
  8936. /// canonical types, e.g.,
  8937. ///
  8938. /// \code
  8939. /// template<typename T>
  8940. /// struct X {
  8941. /// typedef T* pointer;
  8942. /// pointer data();
  8943. /// };
  8944. ///
  8945. /// template<typename T>
  8946. /// typename X<T>::pointer X<T>::data() { ... }
  8947. /// \endcode
  8948. ///
  8949. /// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
  8950. /// since we do not know that we can look into X<T> when we parsed the type.
  8951. /// This function will rebuild the type, performing the lookup of "pointer"
  8952. /// in X<T> and returning an ElaboratedType whose canonical type is the same
  8953. /// as the canonical type of T*, allowing the return types of the out-of-line
  8954. /// definition and the declaration to match.
  8955. TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
  8956. SourceLocation Loc,
  8957. DeclarationName Name) {
  8958. if (!T || !T->getType()->isDependentType())
  8959. return T;
  8960. CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
  8961. return Rebuilder.TransformType(T);
  8962. }
  8963. ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
  8964. CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
  8965. DeclarationName());
  8966. return Rebuilder.TransformExpr(E);
  8967. }
  8968. bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
  8969. if (SS.isInvalid())
  8970. return true;
  8971. NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
  8972. CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
  8973. DeclarationName());
  8974. NestedNameSpecifierLoc Rebuilt
  8975. = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
  8976. if (!Rebuilt)
  8977. return true;
  8978. SS.Adopt(Rebuilt);
  8979. return false;
  8980. }
  8981. /// Rebuild the template parameters now that we know we're in a current
  8982. /// instantiation.
  8983. bool Sema::RebuildTemplateParamsInCurrentInstantiation(
  8984. TemplateParameterList *Params) {
  8985. for (unsigned I = 0, N = Params->size(); I != N; ++I) {
  8986. Decl *Param = Params->getParam(I);
  8987. // There is nothing to rebuild in a type parameter.
  8988. if (isa<TemplateTypeParmDecl>(Param))
  8989. continue;
  8990. // Rebuild the template parameter list of a template template parameter.
  8991. if (TemplateTemplateParmDecl *TTP
  8992. = dyn_cast<TemplateTemplateParmDecl>(Param)) {
  8993. if (RebuildTemplateParamsInCurrentInstantiation(
  8994. TTP->getTemplateParameters()))
  8995. return true;
  8996. continue;
  8997. }
  8998. // Rebuild the type of a non-type template parameter.
  8999. NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
  9000. TypeSourceInfo *NewTSI
  9001. = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
  9002. NTTP->getLocation(),
  9003. NTTP->getDeclName());
  9004. if (!NewTSI)
  9005. return true;
  9006. if (NewTSI->getType()->isUndeducedType()) {
  9007. // C++17 [temp.dep.expr]p3:
  9008. // An id-expression is type-dependent if it contains
  9009. // - an identifier associated by name lookup with a non-type
  9010. // template-parameter declared with a type that contains a
  9011. // placeholder type (7.1.7.4),
  9012. NewTSI = SubstAutoTypeSourceInfo(NewTSI, Context.DependentTy);
  9013. }
  9014. if (NewTSI != NTTP->getTypeSourceInfo()) {
  9015. NTTP->setTypeSourceInfo(NewTSI);
  9016. NTTP->setType(NewTSI->getType());
  9017. }
  9018. }
  9019. return false;
  9020. }
  9021. /// Produces a formatted string that describes the binding of
  9022. /// template parameters to template arguments.
  9023. std::string
  9024. Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
  9025. const TemplateArgumentList &Args) {
  9026. return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
  9027. }
  9028. std::string
  9029. Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
  9030. const TemplateArgument *Args,
  9031. unsigned NumArgs) {
  9032. SmallString<128> Str;
  9033. llvm::raw_svector_ostream Out(Str);
  9034. if (!Params || Params->size() == 0 || NumArgs == 0)
  9035. return std::string();
  9036. for (unsigned I = 0, N = Params->size(); I != N; ++I) {
  9037. if (I >= NumArgs)
  9038. break;
  9039. if (I == 0)
  9040. Out << "[with ";
  9041. else
  9042. Out << ", ";
  9043. if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
  9044. Out << Id->getName();
  9045. } else {
  9046. Out << '$' << I;
  9047. }
  9048. Out << " = ";
  9049. Args[I].print(getPrintingPolicy(), Out);
  9050. }
  9051. Out << ']';
  9052. return Out.str();
  9053. }
  9054. void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
  9055. CachedTokens &Toks) {
  9056. if (!FD)
  9057. return;
  9058. auto LPT = std::make_unique<LateParsedTemplate>();
  9059. // Take tokens to avoid allocations
  9060. LPT->Toks.swap(Toks);
  9061. LPT->D = FnD;
  9062. LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
  9063. FD->setLateTemplateParsed(true);
  9064. }
  9065. void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
  9066. if (!FD)
  9067. return;
  9068. FD->setLateTemplateParsed(false);
  9069. }
  9070. bool Sema::IsInsideALocalClassWithinATemplateFunction() {
  9071. DeclContext *DC = CurContext;
  9072. while (DC) {
  9073. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
  9074. const FunctionDecl *FD = RD->isLocalClass();
  9075. return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
  9076. } else if (DC->isTranslationUnit() || DC->isNamespace())
  9077. return false;
  9078. DC = DC->getParent();
  9079. }
  9080. return false;
  9081. }
  9082. namespace {
  9083. /// Walk the path from which a declaration was instantiated, and check
  9084. /// that every explicit specialization along that path is visible. This enforces
  9085. /// C++ [temp.expl.spec]/6:
  9086. ///
  9087. /// If a template, a member template or a member of a class template is
  9088. /// explicitly specialized then that specialization shall be declared before
  9089. /// the first use of that specialization that would cause an implicit
  9090. /// instantiation to take place, in every translation unit in which such a
  9091. /// use occurs; no diagnostic is required.
  9092. ///
  9093. /// and also C++ [temp.class.spec]/1:
  9094. ///
  9095. /// A partial specialization shall be declared before the first use of a
  9096. /// class template specialization that would make use of the partial
  9097. /// specialization as the result of an implicit or explicit instantiation
  9098. /// in every translation unit in which such a use occurs; no diagnostic is
  9099. /// required.
  9100. class ExplicitSpecializationVisibilityChecker {
  9101. Sema &S;
  9102. SourceLocation Loc;
  9103. llvm::SmallVector<Module *, 8> Modules;
  9104. public:
  9105. ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc)
  9106. : S(S), Loc(Loc) {}
  9107. void check(NamedDecl *ND) {
  9108. if (auto *FD = dyn_cast<FunctionDecl>(ND))
  9109. return checkImpl(FD);
  9110. if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
  9111. return checkImpl(RD);
  9112. if (auto *VD = dyn_cast<VarDecl>(ND))
  9113. return checkImpl(VD);
  9114. if (auto *ED = dyn_cast<EnumDecl>(ND))
  9115. return checkImpl(ED);
  9116. }
  9117. private:
  9118. void diagnose(NamedDecl *D, bool IsPartialSpec) {
  9119. auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
  9120. : Sema::MissingImportKind::ExplicitSpecialization;
  9121. const bool Recover = true;
  9122. // If we got a custom set of modules (because only a subset of the
  9123. // declarations are interesting), use them, otherwise let
  9124. // diagnoseMissingImport intelligently pick some.
  9125. if (Modules.empty())
  9126. S.diagnoseMissingImport(Loc, D, Kind, Recover);
  9127. else
  9128. S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
  9129. }
  9130. // Check a specific declaration. There are three problematic cases:
  9131. //
  9132. // 1) The declaration is an explicit specialization of a template
  9133. // specialization.
  9134. // 2) The declaration is an explicit specialization of a member of an
  9135. // templated class.
  9136. // 3) The declaration is an instantiation of a template, and that template
  9137. // is an explicit specialization of a member of a templated class.
  9138. //
  9139. // We don't need to go any deeper than that, as the instantiation of the
  9140. // surrounding class / etc is not triggered by whatever triggered this
  9141. // instantiation, and thus should be checked elsewhere.
  9142. template<typename SpecDecl>
  9143. void checkImpl(SpecDecl *Spec) {
  9144. bool IsHiddenExplicitSpecialization = false;
  9145. if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
  9146. IsHiddenExplicitSpecialization =
  9147. Spec->getMemberSpecializationInfo()
  9148. ? !S.hasVisibleMemberSpecialization(Spec, &Modules)
  9149. : !S.hasVisibleExplicitSpecialization(Spec, &Modules);
  9150. } else {
  9151. checkInstantiated(Spec);
  9152. }
  9153. if (IsHiddenExplicitSpecialization)
  9154. diagnose(Spec->getMostRecentDecl(), false);
  9155. }
  9156. void checkInstantiated(FunctionDecl *FD) {
  9157. if (auto *TD = FD->getPrimaryTemplate())
  9158. checkTemplate(TD);
  9159. }
  9160. void checkInstantiated(CXXRecordDecl *RD) {
  9161. auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
  9162. if (!SD)
  9163. return;
  9164. auto From = SD->getSpecializedTemplateOrPartial();
  9165. if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
  9166. checkTemplate(TD);
  9167. else if (auto *TD =
  9168. From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
  9169. if (!S.hasVisibleDeclaration(TD))
  9170. diagnose(TD, true);
  9171. checkTemplate(TD);
  9172. }
  9173. }
  9174. void checkInstantiated(VarDecl *RD) {
  9175. auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
  9176. if (!SD)
  9177. return;
  9178. auto From = SD->getSpecializedTemplateOrPartial();
  9179. if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
  9180. checkTemplate(TD);
  9181. else if (auto *TD =
  9182. From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
  9183. if (!S.hasVisibleDeclaration(TD))
  9184. diagnose(TD, true);
  9185. checkTemplate(TD);
  9186. }
  9187. }
  9188. void checkInstantiated(EnumDecl *FD) {}
  9189. template<typename TemplDecl>
  9190. void checkTemplate(TemplDecl *TD) {
  9191. if (TD->isMemberSpecialization()) {
  9192. if (!S.hasVisibleMemberSpecialization(TD, &Modules))
  9193. diagnose(TD->getMostRecentDecl(), false);
  9194. }
  9195. }
  9196. };
  9197. } // end anonymous namespace
  9198. void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
  9199. if (!getLangOpts().Modules)
  9200. return;
  9201. ExplicitSpecializationVisibilityChecker(*this, Loc).check(Spec);
  9202. }
  9203. /// Check whether a template partial specialization that we've discovered
  9204. /// is hidden, and produce suitable diagnostics if so.
  9205. void Sema::checkPartialSpecializationVisibility(SourceLocation Loc,
  9206. NamedDecl *Spec) {
  9207. llvm::SmallVector<Module *, 8> Modules;
  9208. if (!hasVisibleDeclaration(Spec, &Modules))
  9209. diagnoseMissingImport(Loc, Spec, Spec->getLocation(), Modules,
  9210. MissingImportKind::PartialSpecialization,
  9211. /*Recover*/true);
  9212. }