SemaTemplate.cpp 402 KB

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