SemaTemplateInstantiateDecl.cpp 250 KB

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