SemaTemplate.cpp 338 KB

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