SemaTemplate.cpp 461 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501
  1. //===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //===----------------------------------------------------------------------===//
  7. //
  8. // This file implements semantic analysis for C++ templates.
  9. //===----------------------------------------------------------------------===//
  10. #include "TreeTransform.h"
  11. #include "clang/AST/ASTConsumer.h"
  12. #include "clang/AST/ASTContext.h"
  13. #include "clang/AST/Decl.h"
  14. #include "clang/AST/DeclFriend.h"
  15. #include "clang/AST/DeclTemplate.h"
  16. #include "clang/AST/Expr.h"
  17. #include "clang/AST/ExprCXX.h"
  18. #include "clang/AST/RecursiveASTVisitor.h"
  19. #include "clang/AST/TemplateName.h"
  20. #include "clang/AST/TypeVisitor.h"
  21. #include "clang/Basic/Builtins.h"
  22. #include "clang/Basic/DiagnosticSema.h"
  23. #include "clang/Basic/LangOptions.h"
  24. #include "clang/Basic/PartialDiagnostic.h"
  25. #include "clang/Basic/Stack.h"
  26. #include "clang/Basic/TargetInfo.h"
  27. #include "clang/Sema/DeclSpec.h"
  28. #include "clang/Sema/Initialization.h"
  29. #include "clang/Sema/Lookup.h"
  30. #include "clang/Sema/Overload.h"
  31. #include "clang/Sema/ParsedTemplate.h"
  32. #include "clang/Sema/Scope.h"
  33. #include "clang/Sema/SemaInternal.h"
  34. #include "clang/Sema/Template.h"
  35. #include "clang/Sema/TemplateDeduction.h"
  36. #include "llvm/ADT/SmallBitVector.h"
  37. #include "llvm/ADT/SmallString.h"
  38. #include "llvm/ADT/StringExtras.h"
  39. #include <iterator>
  40. #include <optional>
  41. using namespace clang;
  42. using namespace sema;
  43. // Exported for use by Parser.
  44. SourceRange
  45. clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
  46. unsigned N) {
  47. if (!N) return SourceRange();
  48. return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
  49. }
  50. unsigned Sema::getTemplateDepth(Scope *S) const {
  51. unsigned Depth = 0;
  52. // Each template parameter scope represents one level of template parameter
  53. // depth.
  54. for (Scope *TempParamScope = S->getTemplateParamParent(); TempParamScope;
  55. TempParamScope = TempParamScope->getParent()->getTemplateParamParent()) {
  56. ++Depth;
  57. }
  58. // Note that there are template parameters with the given depth.
  59. auto ParamsAtDepth = [&](unsigned D) { Depth = std::max(Depth, D + 1); };
  60. // Look for parameters of an enclosing generic lambda. We don't create a
  61. // template parameter scope for these.
  62. for (FunctionScopeInfo *FSI : getFunctionScopes()) {
  63. if (auto *LSI = dyn_cast<LambdaScopeInfo>(FSI)) {
  64. if (!LSI->TemplateParams.empty()) {
  65. ParamsAtDepth(LSI->AutoTemplateParameterDepth);
  66. break;
  67. }
  68. if (LSI->GLTemplateParameterList) {
  69. ParamsAtDepth(LSI->GLTemplateParameterList->getDepth());
  70. break;
  71. }
  72. }
  73. }
  74. // Look for parameters of an enclosing terse function template. We don't
  75. // create a template parameter scope for these either.
  76. for (const InventedTemplateParameterInfo &Info :
  77. getInventedParameterInfos()) {
  78. if (!Info.TemplateParams.empty()) {
  79. ParamsAtDepth(Info.AutoTemplateParameterDepth);
  80. break;
  81. }
  82. }
  83. return Depth;
  84. }
  85. /// \brief Determine whether the declaration found is acceptable as the name
  86. /// of a template and, if so, return that template declaration. Otherwise,
  87. /// returns null.
  88. ///
  89. /// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
  90. /// is true. In all other cases it will return a TemplateDecl (or null).
  91. NamedDecl *Sema::getAsTemplateNameDecl(NamedDecl *D,
  92. bool AllowFunctionTemplates,
  93. bool AllowDependent) {
  94. D = D->getUnderlyingDecl();
  95. if (isa<TemplateDecl>(D)) {
  96. if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
  97. return nullptr;
  98. return D;
  99. }
  100. if (const auto *Record = dyn_cast<CXXRecordDecl>(D)) {
  101. // C++ [temp.local]p1:
  102. // Like normal (non-template) classes, class templates have an
  103. // injected-class-name (Clause 9). The injected-class-name
  104. // can be used with or without a template-argument-list. When
  105. // it is used without a template-argument-list, it is
  106. // equivalent to the injected-class-name followed by the
  107. // template-parameters of the class template enclosed in
  108. // <>. When it is used with a template-argument-list, it
  109. // refers to the specified class template specialization,
  110. // which could be the current specialization or another
  111. // specialization.
  112. if (Record->isInjectedClassName()) {
  113. Record = cast<CXXRecordDecl>(Record->getDeclContext());
  114. if (Record->getDescribedClassTemplate())
  115. return Record->getDescribedClassTemplate();
  116. if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Record))
  117. return Spec->getSpecializedTemplate();
  118. }
  119. return nullptr;
  120. }
  121. // 'using Dependent::foo;' can resolve to a template name.
  122. // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
  123. // injected-class-name).
  124. if (AllowDependent && isa<UnresolvedUsingValueDecl>(D))
  125. return D;
  126. return nullptr;
  127. }
  128. void Sema::FilterAcceptableTemplateNames(LookupResult &R,
  129. bool AllowFunctionTemplates,
  130. bool AllowDependent) {
  131. LookupResult::Filter filter = R.makeFilter();
  132. while (filter.hasNext()) {
  133. NamedDecl *Orig = filter.next();
  134. if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent))
  135. filter.erase();
  136. }
  137. filter.done();
  138. }
  139. bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
  140. bool AllowFunctionTemplates,
  141. bool AllowDependent,
  142. bool AllowNonTemplateFunctions) {
  143. for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
  144. if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent))
  145. return true;
  146. if (AllowNonTemplateFunctions &&
  147. isa<FunctionDecl>((*I)->getUnderlyingDecl()))
  148. return true;
  149. }
  150. return false;
  151. }
  152. TemplateNameKind Sema::isTemplateName(Scope *S,
  153. CXXScopeSpec &SS,
  154. bool hasTemplateKeyword,
  155. const UnqualifiedId &Name,
  156. ParsedType ObjectTypePtr,
  157. bool EnteringContext,
  158. TemplateTy &TemplateResult,
  159. bool &MemberOfUnknownSpecialization,
  160. bool Disambiguation) {
  161. assert(getLangOpts().CPlusPlus && "No template names in C!");
  162. DeclarationName TName;
  163. MemberOfUnknownSpecialization = false;
  164. switch (Name.getKind()) {
  165. case UnqualifiedIdKind::IK_Identifier:
  166. TName = DeclarationName(Name.Identifier);
  167. break;
  168. case UnqualifiedIdKind::IK_OperatorFunctionId:
  169. TName = Context.DeclarationNames.getCXXOperatorName(
  170. Name.OperatorFunctionId.Operator);
  171. break;
  172. case UnqualifiedIdKind::IK_LiteralOperatorId:
  173. TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
  174. break;
  175. default:
  176. return TNK_Non_template;
  177. }
  178. QualType ObjectType = ObjectTypePtr.get();
  179. AssumedTemplateKind AssumedTemplate;
  180. LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
  181. if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
  182. MemberOfUnknownSpecialization, SourceLocation(),
  183. &AssumedTemplate,
  184. /*AllowTypoCorrection=*/!Disambiguation))
  185. return TNK_Non_template;
  186. if (AssumedTemplate != AssumedTemplateKind::None) {
  187. TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName));
  188. // Let the parser know whether we found nothing or found functions; if we
  189. // found nothing, we want to more carefully check whether this is actually
  190. // a function template name versus some other kind of undeclared identifier.
  191. return AssumedTemplate == AssumedTemplateKind::FoundNothing
  192. ? TNK_Undeclared_template
  193. : TNK_Function_template;
  194. }
  195. if (R.empty())
  196. return TNK_Non_template;
  197. NamedDecl *D = nullptr;
  198. UsingShadowDecl *FoundUsingShadow = dyn_cast<UsingShadowDecl>(*R.begin());
  199. if (R.isAmbiguous()) {
  200. // If we got an ambiguity involving a non-function template, treat this
  201. // as a template name, and pick an arbitrary template for error recovery.
  202. bool AnyFunctionTemplates = false;
  203. for (NamedDecl *FoundD : R) {
  204. if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) {
  205. if (isa<FunctionTemplateDecl>(FoundTemplate))
  206. AnyFunctionTemplates = true;
  207. else {
  208. D = FoundTemplate;
  209. FoundUsingShadow = dyn_cast<UsingShadowDecl>(FoundD);
  210. break;
  211. }
  212. }
  213. }
  214. // If we didn't find any templates at all, this isn't a template name.
  215. // Leave the ambiguity for a later lookup to diagnose.
  216. if (!D && !AnyFunctionTemplates) {
  217. R.suppressDiagnostics();
  218. return TNK_Non_template;
  219. }
  220. // If the only templates were function templates, filter out the rest.
  221. // We'll diagnose the ambiguity later.
  222. if (!D)
  223. FilterAcceptableTemplateNames(R);
  224. }
  225. // At this point, we have either picked a single template name declaration D
  226. // or we have a non-empty set of results R containing either one template name
  227. // declaration or a set of function templates.
  228. TemplateName Template;
  229. TemplateNameKind TemplateKind;
  230. unsigned ResultCount = R.end() - R.begin();
  231. if (!D && ResultCount > 1) {
  232. // We assume that we'll preserve the qualifier from a function
  233. // template name in other ways.
  234. Template = Context.getOverloadedTemplateName(R.begin(), R.end());
  235. TemplateKind = TNK_Function_template;
  236. // We'll do this lookup again later.
  237. R.suppressDiagnostics();
  238. } else {
  239. if (!D) {
  240. D = getAsTemplateNameDecl(*R.begin());
  241. assert(D && "unambiguous result is not a template name");
  242. }
  243. if (isa<UnresolvedUsingValueDecl>(D)) {
  244. // We don't yet know whether this is a template-name or not.
  245. MemberOfUnknownSpecialization = true;
  246. return TNK_Non_template;
  247. }
  248. TemplateDecl *TD = cast<TemplateDecl>(D);
  249. Template =
  250. FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
  251. assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
  252. if (SS.isSet() && !SS.isInvalid()) {
  253. NestedNameSpecifier *Qualifier = SS.getScopeRep();
  254. Template = Context.getQualifiedTemplateName(Qualifier, hasTemplateKeyword,
  255. Template);
  256. }
  257. if (isa<FunctionTemplateDecl>(TD)) {
  258. TemplateKind = TNK_Function_template;
  259. // We'll do this lookup again later.
  260. R.suppressDiagnostics();
  261. } else {
  262. assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
  263. isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
  264. isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD));
  265. TemplateKind =
  266. isa<VarTemplateDecl>(TD) ? TNK_Var_template :
  267. isa<ConceptDecl>(TD) ? TNK_Concept_template :
  268. TNK_Type_template;
  269. }
  270. }
  271. TemplateResult = TemplateTy::make(Template);
  272. return TemplateKind;
  273. }
  274. bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
  275. SourceLocation NameLoc,
  276. ParsedTemplateTy *Template) {
  277. CXXScopeSpec SS;
  278. bool MemberOfUnknownSpecialization = false;
  279. // We could use redeclaration lookup here, but we don't need to: the
  280. // syntactic form of a deduction guide is enough to identify it even
  281. // if we can't look up the template name at all.
  282. LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
  283. if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
  284. /*EnteringContext*/ false,
  285. MemberOfUnknownSpecialization))
  286. return false;
  287. if (R.empty()) return false;
  288. if (R.isAmbiguous()) {
  289. // FIXME: Diagnose an ambiguity if we find at least one template.
  290. R.suppressDiagnostics();
  291. return false;
  292. }
  293. // We only treat template-names that name type templates as valid deduction
  294. // guide names.
  295. TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
  296. if (!TD || !getAsTypeTemplateDecl(TD))
  297. return false;
  298. if (Template)
  299. *Template = TemplateTy::make(TemplateName(TD));
  300. return true;
  301. }
  302. bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
  303. SourceLocation IILoc,
  304. Scope *S,
  305. const CXXScopeSpec *SS,
  306. TemplateTy &SuggestedTemplate,
  307. TemplateNameKind &SuggestedKind) {
  308. // We can't recover unless there's a dependent scope specifier preceding the
  309. // template name.
  310. // FIXME: Typo correction?
  311. if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
  312. computeDeclContext(*SS))
  313. return false;
  314. // The code is missing a 'template' keyword prior to the dependent template
  315. // name.
  316. NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
  317. Diag(IILoc, diag::err_template_kw_missing)
  318. << Qualifier << II.getName()
  319. << FixItHint::CreateInsertion(IILoc, "template ");
  320. SuggestedTemplate
  321. = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
  322. SuggestedKind = TNK_Dependent_template_name;
  323. return true;
  324. }
  325. bool Sema::LookupTemplateName(LookupResult &Found,
  326. Scope *S, CXXScopeSpec &SS,
  327. QualType ObjectType,
  328. bool EnteringContext,
  329. bool &MemberOfUnknownSpecialization,
  330. RequiredTemplateKind RequiredTemplate,
  331. AssumedTemplateKind *ATK,
  332. bool AllowTypoCorrection) {
  333. if (ATK)
  334. *ATK = AssumedTemplateKind::None;
  335. if (SS.isInvalid())
  336. return true;
  337. Found.setTemplateNameLookup(true);
  338. // Determine where to perform name lookup
  339. MemberOfUnknownSpecialization = false;
  340. DeclContext *LookupCtx = nullptr;
  341. bool IsDependent = false;
  342. if (!ObjectType.isNull()) {
  343. // This nested-name-specifier occurs in a member access expression, e.g.,
  344. // x->B::f, and we are looking into the type of the object.
  345. assert(SS.isEmpty() && "ObjectType and scope specifier cannot coexist");
  346. LookupCtx = computeDeclContext(ObjectType);
  347. IsDependent = !LookupCtx && ObjectType->isDependentType();
  348. assert((IsDependent || !ObjectType->isIncompleteType() ||
  349. !ObjectType->getAs<TagType>() ||
  350. ObjectType->castAs<TagType>()->isBeingDefined()) &&
  351. "Caller should have completed object type");
  352. // Template names cannot appear inside an Objective-C class or object type
  353. // or a vector type.
  354. //
  355. // FIXME: This is wrong. For example:
  356. //
  357. // template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
  358. // Vec<int> vi;
  359. // vi.Vec<int>::~Vec<int>();
  360. //
  361. // ... should be accepted but we will not treat 'Vec' as a template name
  362. // here. The right thing to do would be to check if the name is a valid
  363. // vector component name, and look up a template name if not. And similarly
  364. // for lookups into Objective-C class and object types, where the same
  365. // problem can arise.
  366. if (ObjectType->isObjCObjectOrInterfaceType() ||
  367. ObjectType->isVectorType()) {
  368. Found.clear();
  369. return false;
  370. }
  371. } else if (SS.isNotEmpty()) {
  372. // This nested-name-specifier occurs after another nested-name-specifier,
  373. // so long into the context associated with the prior nested-name-specifier.
  374. LookupCtx = computeDeclContext(SS, EnteringContext);
  375. IsDependent = !LookupCtx && isDependentScopeSpecifier(SS);
  376. // The declaration context must be complete.
  377. if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
  378. return true;
  379. }
  380. bool ObjectTypeSearchedInScope = false;
  381. bool AllowFunctionTemplatesInLookup = true;
  382. if (LookupCtx) {
  383. // Perform "qualified" name lookup into the declaration context we
  384. // computed, which is either the type of the base of a member access
  385. // expression or the declaration context associated with a prior
  386. // nested-name-specifier.
  387. LookupQualifiedName(Found, LookupCtx);
  388. // FIXME: The C++ standard does not clearly specify what happens in the
  389. // case where the object type is dependent, and implementations vary. In
  390. // Clang, we treat a name after a . or -> as a template-name if lookup
  391. // finds a non-dependent member or member of the current instantiation that
  392. // is a type template, or finds no such members and lookup in the context
  393. // of the postfix-expression finds a type template. In the latter case, the
  394. // name is nonetheless dependent, and we may resolve it to a member of an
  395. // unknown specialization when we come to instantiate the template.
  396. IsDependent |= Found.wasNotFoundInCurrentInstantiation();
  397. }
  398. if (SS.isEmpty() && (ObjectType.isNull() || Found.empty())) {
  399. // C++ [basic.lookup.classref]p1:
  400. // In a class member access expression (5.2.5), if the . or -> token is
  401. // immediately followed by an identifier followed by a <, the
  402. // identifier must be looked up to determine whether the < is the
  403. // beginning of a template argument list (14.2) or a less-than operator.
  404. // The identifier is first looked up in the class of the object
  405. // expression. If the identifier is not found, it is then looked up in
  406. // the context of the entire postfix-expression and shall name a class
  407. // template.
  408. if (S)
  409. LookupName(Found, S);
  410. if (!ObjectType.isNull()) {
  411. // FIXME: We should filter out all non-type templates here, particularly
  412. // variable templates and concepts. But the exclusion of alias templates
  413. // and template template parameters is a wording defect.
  414. AllowFunctionTemplatesInLookup = false;
  415. ObjectTypeSearchedInScope = true;
  416. }
  417. IsDependent |= Found.wasNotFoundInCurrentInstantiation();
  418. }
  419. if (Found.isAmbiguous())
  420. return false;
  421. if (ATK && SS.isEmpty() && ObjectType.isNull() &&
  422. !RequiredTemplate.hasTemplateKeyword()) {
  423. // C++2a [temp.names]p2:
  424. // A name is also considered to refer to a template if it is an
  425. // unqualified-id followed by a < and name lookup finds either one or more
  426. // functions or finds nothing.
  427. //
  428. // To keep our behavior consistent, we apply the "finds nothing" part in
  429. // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
  430. // successfully form a call to an undeclared template-id.
  431. bool AllFunctions =
  432. getLangOpts().CPlusPlus20 && llvm::all_of(Found, [](NamedDecl *ND) {
  433. return isa<FunctionDecl>(ND->getUnderlyingDecl());
  434. });
  435. if (AllFunctions || (Found.empty() && !IsDependent)) {
  436. // If lookup found any functions, or if this is a name that can only be
  437. // used for a function, then strongly assume this is a function
  438. // template-id.
  439. *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
  440. ? AssumedTemplateKind::FoundNothing
  441. : AssumedTemplateKind::FoundFunctions;
  442. Found.clear();
  443. return false;
  444. }
  445. }
  446. if (Found.empty() && !IsDependent && AllowTypoCorrection) {
  447. // If we did not find any names, and this is not a disambiguation, attempt
  448. // to correct any typos.
  449. DeclarationName Name = Found.getLookupName();
  450. Found.clear();
  451. // Simple filter callback that, for keywords, only accepts the C++ *_cast
  452. DefaultFilterCCC FilterCCC{};
  453. FilterCCC.WantTypeSpecifiers = false;
  454. FilterCCC.WantExpressionKeywords = false;
  455. FilterCCC.WantRemainingKeywords = false;
  456. FilterCCC.WantCXXNamedCasts = true;
  457. if (TypoCorrection Corrected =
  458. CorrectTypo(Found.getLookupNameInfo(), Found.getLookupKind(), S,
  459. &SS, FilterCCC, CTK_ErrorRecovery, LookupCtx)) {
  460. if (auto *ND = Corrected.getFoundDecl())
  461. Found.addDecl(ND);
  462. FilterAcceptableTemplateNames(Found);
  463. if (Found.isAmbiguous()) {
  464. Found.clear();
  465. } else if (!Found.empty()) {
  466. Found.setLookupName(Corrected.getCorrection());
  467. if (LookupCtx) {
  468. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  469. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  470. Name.getAsString() == CorrectedStr;
  471. diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
  472. << Name << LookupCtx << DroppedSpecifier
  473. << SS.getRange());
  474. } else {
  475. diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
  476. }
  477. }
  478. }
  479. }
  480. NamedDecl *ExampleLookupResult =
  481. Found.empty() ? nullptr : Found.getRepresentativeDecl();
  482. FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
  483. if (Found.empty()) {
  484. if (IsDependent) {
  485. MemberOfUnknownSpecialization = true;
  486. return false;
  487. }
  488. // If a 'template' keyword was used, a lookup that finds only non-template
  489. // names is an error.
  490. if (ExampleLookupResult && RequiredTemplate) {
  491. Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
  492. << Found.getLookupName() << SS.getRange()
  493. << RequiredTemplate.hasTemplateKeyword()
  494. << RequiredTemplate.getTemplateKeywordLoc();
  495. Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
  496. diag::note_template_kw_refers_to_non_template)
  497. << Found.getLookupName();
  498. return true;
  499. }
  500. return false;
  501. }
  502. if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
  503. !getLangOpts().CPlusPlus11) {
  504. // C++03 [basic.lookup.classref]p1:
  505. // [...] If the lookup in the class of the object expression finds a
  506. // template, the name is also looked up in the context of the entire
  507. // postfix-expression and [...]
  508. //
  509. // Note: C++11 does not perform this second lookup.
  510. LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
  511. LookupOrdinaryName);
  512. FoundOuter.setTemplateNameLookup(true);
  513. LookupName(FoundOuter, S);
  514. // FIXME: We silently accept an ambiguous lookup here, in violation of
  515. // [basic.lookup]/1.
  516. FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
  517. NamedDecl *OuterTemplate;
  518. if (FoundOuter.empty()) {
  519. // - if the name is not found, the name found in the class of the
  520. // object expression is used, otherwise
  521. } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
  522. !(OuterTemplate =
  523. getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) {
  524. // - if the name is found in the context of the entire
  525. // postfix-expression and does not name a class template, the name
  526. // found in the class of the object expression is used, otherwise
  527. FoundOuter.clear();
  528. } else if (!Found.isSuppressingDiagnostics()) {
  529. // - if the name found is a class template, it must refer to the same
  530. // entity as the one found in the class of the object expression,
  531. // otherwise the program is ill-formed.
  532. if (!Found.isSingleResult() ||
  533. getAsTemplateNameDecl(Found.getFoundDecl())->getCanonicalDecl() !=
  534. OuterTemplate->getCanonicalDecl()) {
  535. Diag(Found.getNameLoc(),
  536. diag::ext_nested_name_member_ref_lookup_ambiguous)
  537. << Found.getLookupName()
  538. << ObjectType;
  539. Diag(Found.getRepresentativeDecl()->getLocation(),
  540. diag::note_ambig_member_ref_object_type)
  541. << ObjectType;
  542. Diag(FoundOuter.getFoundDecl()->getLocation(),
  543. diag::note_ambig_member_ref_scope);
  544. // Recover by taking the template that we found in the object
  545. // expression's type.
  546. }
  547. }
  548. }
  549. return false;
  550. }
  551. void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
  552. SourceLocation Less,
  553. SourceLocation Greater) {
  554. if (TemplateName.isInvalid())
  555. return;
  556. DeclarationNameInfo NameInfo;
  557. CXXScopeSpec SS;
  558. LookupNameKind LookupKind;
  559. DeclContext *LookupCtx = nullptr;
  560. NamedDecl *Found = nullptr;
  561. bool MissingTemplateKeyword = false;
  562. // Figure out what name we looked up.
  563. if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {
  564. NameInfo = DRE->getNameInfo();
  565. SS.Adopt(DRE->getQualifierLoc());
  566. LookupKind = LookupOrdinaryName;
  567. Found = DRE->getFoundDecl();
  568. } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
  569. NameInfo = ME->getMemberNameInfo();
  570. SS.Adopt(ME->getQualifierLoc());
  571. LookupKind = LookupMemberName;
  572. LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
  573. Found = ME->getMemberDecl();
  574. } else if (auto *DSDRE =
  575. dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
  576. NameInfo = DSDRE->getNameInfo();
  577. SS.Adopt(DSDRE->getQualifierLoc());
  578. MissingTemplateKeyword = true;
  579. } else if (auto *DSME =
  580. dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
  581. NameInfo = DSME->getMemberNameInfo();
  582. SS.Adopt(DSME->getQualifierLoc());
  583. MissingTemplateKeyword = true;
  584. } else {
  585. llvm_unreachable("unexpected kind of potential template name");
  586. }
  587. // If this is a dependent-scope lookup, diagnose that the 'template' keyword
  588. // was missing.
  589. if (MissingTemplateKeyword) {
  590. Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)
  591. << "" << NameInfo.getName().getAsString() << SourceRange(Less, Greater);
  592. return;
  593. }
  594. // Try to correct the name by looking for templates and C++ named casts.
  595. struct TemplateCandidateFilter : CorrectionCandidateCallback {
  596. Sema &S;
  597. TemplateCandidateFilter(Sema &S) : S(S) {
  598. WantTypeSpecifiers = false;
  599. WantExpressionKeywords = false;
  600. WantRemainingKeywords = false;
  601. WantCXXNamedCasts = true;
  602. };
  603. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  604. if (auto *ND = Candidate.getCorrectionDecl())
  605. return S.getAsTemplateNameDecl(ND);
  606. return Candidate.isKeyword();
  607. }
  608. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  609. return std::make_unique<TemplateCandidateFilter>(*this);
  610. }
  611. };
  612. DeclarationName Name = NameInfo.getName();
  613. TemplateCandidateFilter CCC(*this);
  614. if (TypoCorrection Corrected = CorrectTypo(NameInfo, LookupKind, S, &SS, CCC,
  615. CTK_ErrorRecovery, LookupCtx)) {
  616. auto *ND = Corrected.getFoundDecl();
  617. if (ND)
  618. ND = getAsTemplateNameDecl(ND);
  619. if (ND || Corrected.isKeyword()) {
  620. if (LookupCtx) {
  621. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  622. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  623. Name.getAsString() == CorrectedStr;
  624. diagnoseTypo(Corrected,
  625. PDiag(diag::err_non_template_in_member_template_id_suggest)
  626. << Name << LookupCtx << DroppedSpecifier
  627. << SS.getRange(), false);
  628. } else {
  629. diagnoseTypo(Corrected,
  630. PDiag(diag::err_non_template_in_template_id_suggest)
  631. << Name, false);
  632. }
  633. if (Found)
  634. Diag(Found->getLocation(),
  635. diag::note_non_template_in_template_id_found);
  636. return;
  637. }
  638. }
  639. Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
  640. << Name << SourceRange(Less, Greater);
  641. if (Found)
  642. Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
  643. }
  644. /// ActOnDependentIdExpression - Handle a dependent id-expression that
  645. /// was just parsed. This is only possible with an explicit scope
  646. /// specifier naming a dependent type.
  647. ExprResult
  648. Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
  649. SourceLocation TemplateKWLoc,
  650. const DeclarationNameInfo &NameInfo,
  651. bool isAddressOfOperand,
  652. const TemplateArgumentListInfo *TemplateArgs) {
  653. DeclContext *DC = getFunctionLevelDeclContext();
  654. // C++11 [expr.prim.general]p12:
  655. // An id-expression that denotes a non-static data member or non-static
  656. // member function of a class can only be used:
  657. // (...)
  658. // - if that id-expression denotes a non-static data member and it
  659. // appears in an unevaluated operand.
  660. //
  661. // If this might be the case, form a DependentScopeDeclRefExpr instead of a
  662. // CXXDependentScopeMemberExpr. The former can instantiate to either
  663. // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
  664. // always a MemberExpr.
  665. bool MightBeCxx11UnevalField =
  666. getLangOpts().CPlusPlus11 && isUnevaluatedContext();
  667. // Check if the nested name specifier is an enum type.
  668. bool IsEnum = false;
  669. if (NestedNameSpecifier *NNS = SS.getScopeRep())
  670. IsEnum = isa_and_nonnull<EnumType>(NNS->getAsType());
  671. if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum &&
  672. isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) {
  673. QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType();
  674. // Since the 'this' expression is synthesized, we don't need to
  675. // perform the double-lookup check.
  676. NamedDecl *FirstQualifierInScope = nullptr;
  677. return CXXDependentScopeMemberExpr::Create(
  678. Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
  679. /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
  680. FirstQualifierInScope, NameInfo, TemplateArgs);
  681. }
  682. return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
  683. }
  684. ExprResult
  685. Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
  686. SourceLocation TemplateKWLoc,
  687. const DeclarationNameInfo &NameInfo,
  688. const TemplateArgumentListInfo *TemplateArgs) {
  689. // DependentScopeDeclRefExpr::Create requires a valid QualifierLoc
  690. NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
  691. if (!QualifierLoc)
  692. return ExprError();
  693. return DependentScopeDeclRefExpr::Create(
  694. Context, QualifierLoc, TemplateKWLoc, NameInfo, TemplateArgs);
  695. }
  696. /// Determine whether we would be unable to instantiate this template (because
  697. /// it either has no definition, or is in the process of being instantiated).
  698. bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
  699. NamedDecl *Instantiation,
  700. bool InstantiatedFromMember,
  701. const NamedDecl *Pattern,
  702. const NamedDecl *PatternDef,
  703. TemplateSpecializationKind TSK,
  704. bool Complain /*= true*/) {
  705. assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
  706. isa<VarDecl>(Instantiation));
  707. bool IsEntityBeingDefined = false;
  708. if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
  709. IsEntityBeingDefined = TD->isBeingDefined();
  710. if (PatternDef && !IsEntityBeingDefined) {
  711. NamedDecl *SuggestedDef = nullptr;
  712. if (!hasReachableDefinition(const_cast<NamedDecl *>(PatternDef),
  713. &SuggestedDef,
  714. /*OnlyNeedComplete*/ false)) {
  715. // If we're allowed to diagnose this and recover, do so.
  716. bool Recover = Complain && !isSFINAEContext();
  717. if (Complain)
  718. diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
  719. Sema::MissingImportKind::Definition, Recover);
  720. return !Recover;
  721. }
  722. return false;
  723. }
  724. if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
  725. return true;
  726. std::optional<unsigned> Note;
  727. QualType InstantiationTy;
  728. if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
  729. InstantiationTy = Context.getTypeDeclType(TD);
  730. if (PatternDef) {
  731. Diag(PointOfInstantiation,
  732. diag::err_template_instantiate_within_definition)
  733. << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
  734. << InstantiationTy;
  735. // Not much point in noting the template declaration here, since
  736. // we're lexically inside it.
  737. Instantiation->setInvalidDecl();
  738. } else if (InstantiatedFromMember) {
  739. if (isa<FunctionDecl>(Instantiation)) {
  740. Diag(PointOfInstantiation,
  741. diag::err_explicit_instantiation_undefined_member)
  742. << /*member function*/ 1 << Instantiation->getDeclName()
  743. << Instantiation->getDeclContext();
  744. Note = diag::note_explicit_instantiation_here;
  745. } else {
  746. assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
  747. Diag(PointOfInstantiation,
  748. diag::err_implicit_instantiate_member_undefined)
  749. << InstantiationTy;
  750. Note = diag::note_member_declared_at;
  751. }
  752. } else {
  753. if (isa<FunctionDecl>(Instantiation)) {
  754. Diag(PointOfInstantiation,
  755. diag::err_explicit_instantiation_undefined_func_template)
  756. << Pattern;
  757. Note = diag::note_explicit_instantiation_here;
  758. } else if (isa<TagDecl>(Instantiation)) {
  759. Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
  760. << (TSK != TSK_ImplicitInstantiation)
  761. << InstantiationTy;
  762. Note = diag::note_template_decl_here;
  763. } else {
  764. assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
  765. if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
  766. Diag(PointOfInstantiation,
  767. diag::err_explicit_instantiation_undefined_var_template)
  768. << Instantiation;
  769. Instantiation->setInvalidDecl();
  770. } else
  771. Diag(PointOfInstantiation,
  772. diag::err_explicit_instantiation_undefined_member)
  773. << /*static data member*/ 2 << Instantiation->getDeclName()
  774. << Instantiation->getDeclContext();
  775. Note = diag::note_explicit_instantiation_here;
  776. }
  777. }
  778. if (Note) // Diagnostics were emitted.
  779. Diag(Pattern->getLocation(), *Note);
  780. // In general, Instantiation isn't marked invalid to get more than one
  781. // error for multiple undefined instantiations. But the code that does
  782. // explicit declaration -> explicit definition conversion can't handle
  783. // invalid declarations, so mark as invalid in that case.
  784. if (TSK == TSK_ExplicitInstantiationDeclaration)
  785. Instantiation->setInvalidDecl();
  786. return true;
  787. }
  788. /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
  789. /// that the template parameter 'PrevDecl' is being shadowed by a new
  790. /// declaration at location Loc. Returns true to indicate that this is
  791. /// an error, and false otherwise.
  792. void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
  793. assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
  794. // C++ [temp.local]p4:
  795. // A template-parameter shall not be redeclared within its
  796. // scope (including nested scopes).
  797. //
  798. // Make this a warning when MSVC compatibility is requested.
  799. unsigned DiagId = getLangOpts().MSVCCompat ? diag::ext_template_param_shadow
  800. : diag::err_template_param_shadow;
  801. Diag(Loc, DiagId) << cast<NamedDecl>(PrevDecl)->getDeclName();
  802. Diag(PrevDecl->getLocation(), diag::note_template_param_here);
  803. }
  804. /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
  805. /// the parameter D to reference the templated declaration and return a pointer
  806. /// to the template declaration. Otherwise, do nothing to D and return null.
  807. TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
  808. if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
  809. D = Temp->getTemplatedDecl();
  810. return Temp;
  811. }
  812. return nullptr;
  813. }
  814. ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
  815. SourceLocation EllipsisLoc) const {
  816. assert(Kind == Template &&
  817. "Only template template arguments can be pack expansions here");
  818. assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
  819. "Template template argument pack expansion without packs");
  820. ParsedTemplateArgument Result(*this);
  821. Result.EllipsisLoc = EllipsisLoc;
  822. return Result;
  823. }
  824. static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
  825. const ParsedTemplateArgument &Arg) {
  826. switch (Arg.getKind()) {
  827. case ParsedTemplateArgument::Type: {
  828. TypeSourceInfo *DI;
  829. QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
  830. if (!DI)
  831. DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
  832. return TemplateArgumentLoc(TemplateArgument(T), DI);
  833. }
  834. case ParsedTemplateArgument::NonType: {
  835. Expr *E = static_cast<Expr *>(Arg.getAsExpr());
  836. return TemplateArgumentLoc(TemplateArgument(E), E);
  837. }
  838. case ParsedTemplateArgument::Template: {
  839. TemplateName Template = Arg.getAsTemplate().get();
  840. TemplateArgument TArg;
  841. if (Arg.getEllipsisLoc().isValid())
  842. TArg = TemplateArgument(Template, std::optional<unsigned int>());
  843. else
  844. TArg = Template;
  845. return TemplateArgumentLoc(
  846. SemaRef.Context, TArg,
  847. Arg.getScopeSpec().getWithLocInContext(SemaRef.Context),
  848. Arg.getLocation(), Arg.getEllipsisLoc());
  849. }
  850. }
  851. llvm_unreachable("Unhandled parsed template argument");
  852. }
  853. /// Translates template arguments as provided by the parser
  854. /// into template arguments used by semantic analysis.
  855. void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
  856. TemplateArgumentListInfo &TemplateArgs) {
  857. for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
  858. TemplateArgs.addArgument(translateTemplateArgument(*this,
  859. TemplateArgsIn[I]));
  860. }
  861. static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
  862. SourceLocation Loc,
  863. IdentifierInfo *Name) {
  864. NamedDecl *PrevDecl = SemaRef.LookupSingleName(
  865. S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
  866. if (PrevDecl && PrevDecl->isTemplateParameter())
  867. SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
  868. }
  869. /// Convert a parsed type into a parsed template argument. This is mostly
  870. /// trivial, except that we may have parsed a C++17 deduced class template
  871. /// specialization type, in which case we should form a template template
  872. /// argument instead of a type template argument.
  873. ParsedTemplateArgument Sema::ActOnTemplateTypeArgument(TypeResult ParsedType) {
  874. TypeSourceInfo *TInfo;
  875. QualType T = GetTypeFromParser(ParsedType.get(), &TInfo);
  876. if (T.isNull())
  877. return ParsedTemplateArgument();
  878. assert(TInfo && "template argument with no location");
  879. // If we might have formed a deduced template specialization type, convert
  880. // it to a template template argument.
  881. if (getLangOpts().CPlusPlus17) {
  882. TypeLoc TL = TInfo->getTypeLoc();
  883. SourceLocation EllipsisLoc;
  884. if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
  885. EllipsisLoc = PET.getEllipsisLoc();
  886. TL = PET.getPatternLoc();
  887. }
  888. CXXScopeSpec SS;
  889. if (auto ET = TL.getAs<ElaboratedTypeLoc>()) {
  890. SS.Adopt(ET.getQualifierLoc());
  891. TL = ET.getNamedTypeLoc();
  892. }
  893. if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
  894. TemplateName Name = DTST.getTypePtr()->getTemplateName();
  895. if (SS.isSet())
  896. Name = Context.getQualifiedTemplateName(SS.getScopeRep(),
  897. /*HasTemplateKeyword=*/false,
  898. Name);
  899. ParsedTemplateArgument Result(SS, TemplateTy::make(Name),
  900. DTST.getTemplateNameLoc());
  901. if (EllipsisLoc.isValid())
  902. Result = Result.getTemplatePackExpansion(EllipsisLoc);
  903. return Result;
  904. }
  905. }
  906. // This is a normal type template argument. Note, if the type template
  907. // argument is an injected-class-name for a template, it has a dual nature
  908. // and can be used as either a type or a template. We handle that in
  909. // convertTypeTemplateArgumentToTemplate.
  910. return ParsedTemplateArgument(ParsedTemplateArgument::Type,
  911. ParsedType.get().getAsOpaquePtr(),
  912. TInfo->getTypeLoc().getBeginLoc());
  913. }
  914. /// ActOnTypeParameter - Called when a C++ template type parameter
  915. /// (e.g., "typename T") has been parsed. Typename specifies whether
  916. /// the keyword "typename" was used to declare the type parameter
  917. /// (otherwise, "class" was used), and KeyLoc is the location of the
  918. /// "class" or "typename" keyword. ParamName is the name of the
  919. /// parameter (NULL indicates an unnamed template parameter) and
  920. /// ParamNameLoc is the location of the parameter name (if any).
  921. /// If the type parameter has a default argument, it will be added
  922. /// later via ActOnTypeParameterDefault.
  923. NamedDecl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
  924. SourceLocation EllipsisLoc,
  925. SourceLocation KeyLoc,
  926. IdentifierInfo *ParamName,
  927. SourceLocation ParamNameLoc,
  928. unsigned Depth, unsigned Position,
  929. SourceLocation EqualLoc,
  930. ParsedType DefaultArg,
  931. bool HasTypeConstraint) {
  932. assert(S->isTemplateParamScope() &&
  933. "Template type parameter not in template parameter scope!");
  934. bool IsParameterPack = EllipsisLoc.isValid();
  935. TemplateTypeParmDecl *Param
  936. = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
  937. KeyLoc, ParamNameLoc, Depth, Position,
  938. ParamName, Typename, IsParameterPack,
  939. HasTypeConstraint);
  940. Param->setAccess(AS_public);
  941. if (Param->isParameterPack())
  942. if (auto *LSI = getEnclosingLambda())
  943. LSI->LocalPacks.push_back(Param);
  944. if (ParamName) {
  945. maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
  946. // Add the template parameter into the current scope.
  947. S->AddDecl(Param);
  948. IdResolver.AddDecl(Param);
  949. }
  950. // C++0x [temp.param]p9:
  951. // A default template-argument may be specified for any kind of
  952. // template-parameter that is not a template parameter pack.
  953. if (DefaultArg && IsParameterPack) {
  954. Diag(EqualLoc, diag::err_template_param_pack_default_arg);
  955. DefaultArg = nullptr;
  956. }
  957. // Handle the default argument, if provided.
  958. if (DefaultArg) {
  959. TypeSourceInfo *DefaultTInfo;
  960. GetTypeFromParser(DefaultArg, &DefaultTInfo);
  961. assert(DefaultTInfo && "expected source information for type");
  962. // Check for unexpanded parameter packs.
  963. if (DiagnoseUnexpandedParameterPack(ParamNameLoc, DefaultTInfo,
  964. UPPC_DefaultArgument))
  965. return Param;
  966. // Check the template argument itself.
  967. if (CheckTemplateArgument(DefaultTInfo)) {
  968. Param->setInvalidDecl();
  969. return Param;
  970. }
  971. Param->setDefaultArgument(DefaultTInfo);
  972. }
  973. return Param;
  974. }
  975. /// Convert the parser's template argument list representation into our form.
  976. static TemplateArgumentListInfo
  977. makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
  978. TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
  979. TemplateId.RAngleLoc);
  980. ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
  981. TemplateId.NumArgs);
  982. S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
  983. return TemplateArgs;
  984. }
  985. bool Sema::ActOnTypeConstraint(const CXXScopeSpec &SS,
  986. TemplateIdAnnotation *TypeConstr,
  987. TemplateTypeParmDecl *ConstrainedParameter,
  988. SourceLocation EllipsisLoc) {
  989. return BuildTypeConstraint(SS, TypeConstr, ConstrainedParameter, EllipsisLoc,
  990. false);
  991. }
  992. bool Sema::BuildTypeConstraint(const CXXScopeSpec &SS,
  993. TemplateIdAnnotation *TypeConstr,
  994. TemplateTypeParmDecl *ConstrainedParameter,
  995. SourceLocation EllipsisLoc,
  996. bool AllowUnexpandedPack) {
  997. TemplateName TN = TypeConstr->Template.get();
  998. ConceptDecl *CD = cast<ConceptDecl>(TN.getAsTemplateDecl());
  999. // C++2a [temp.param]p4:
  1000. // [...] The concept designated by a type-constraint shall be a type
  1001. // concept ([temp.concept]).
  1002. if (!CD->isTypeConcept()) {
  1003. Diag(TypeConstr->TemplateNameLoc,
  1004. diag::err_type_constraint_non_type_concept);
  1005. return true;
  1006. }
  1007. bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
  1008. if (!WereArgsSpecified &&
  1009. CD->getTemplateParameters()->getMinRequiredArguments() > 1) {
  1010. Diag(TypeConstr->TemplateNameLoc,
  1011. diag::err_type_constraint_missing_arguments) << CD;
  1012. return true;
  1013. }
  1014. DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name),
  1015. TypeConstr->TemplateNameLoc);
  1016. TemplateArgumentListInfo TemplateArgs;
  1017. if (TypeConstr->LAngleLoc.isValid()) {
  1018. TemplateArgs =
  1019. makeTemplateArgumentListInfo(*this, *TypeConstr);
  1020. if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) {
  1021. for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) {
  1022. if (DiagnoseUnexpandedParameterPack(Arg, UPPC_TypeConstraint))
  1023. return true;
  1024. }
  1025. }
  1026. }
  1027. return AttachTypeConstraint(
  1028. SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc(),
  1029. ConceptName, CD,
  1030. TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,
  1031. ConstrainedParameter, EllipsisLoc);
  1032. }
  1033. template<typename ArgumentLocAppender>
  1034. static ExprResult formImmediatelyDeclaredConstraint(
  1035. Sema &S, NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo,
  1036. ConceptDecl *NamedConcept, SourceLocation LAngleLoc,
  1037. SourceLocation RAngleLoc, QualType ConstrainedType,
  1038. SourceLocation ParamNameLoc, ArgumentLocAppender Appender,
  1039. SourceLocation EllipsisLoc) {
  1040. TemplateArgumentListInfo ConstraintArgs;
  1041. ConstraintArgs.addArgument(
  1042. S.getTrivialTemplateArgumentLoc(TemplateArgument(ConstrainedType),
  1043. /*NTTPType=*/QualType(), ParamNameLoc));
  1044. ConstraintArgs.setRAngleLoc(RAngleLoc);
  1045. ConstraintArgs.setLAngleLoc(LAngleLoc);
  1046. Appender(ConstraintArgs);
  1047. // C++2a [temp.param]p4:
  1048. // [...] This constraint-expression E is called the immediately-declared
  1049. // constraint of T. [...]
  1050. CXXScopeSpec SS;
  1051. SS.Adopt(NS);
  1052. ExprResult ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
  1053. SS, /*TemplateKWLoc=*/SourceLocation(), NameInfo,
  1054. /*FoundDecl=*/NamedConcept, NamedConcept, &ConstraintArgs);
  1055. if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
  1056. return ImmediatelyDeclaredConstraint;
  1057. // C++2a [temp.param]p4:
  1058. // [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
  1059. //
  1060. // We have the following case:
  1061. //
  1062. // template<typename T> concept C1 = true;
  1063. // template<C1... T> struct s1;
  1064. //
  1065. // The constraint: (C1<T> && ...)
  1066. //
  1067. // Note that the type of C1<T> is known to be 'bool', so we don't need to do
  1068. // any unqualified lookups for 'operator&&' here.
  1069. return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/nullptr,
  1070. /*LParenLoc=*/SourceLocation(),
  1071. ImmediatelyDeclaredConstraint.get(), BO_LAnd,
  1072. EllipsisLoc, /*RHS=*/nullptr,
  1073. /*RParenLoc=*/SourceLocation(),
  1074. /*NumExpansions=*/std::nullopt);
  1075. }
  1076. /// Attach a type-constraint to a template parameter.
  1077. /// \returns true if an error occurred. This can happen if the
  1078. /// immediately-declared constraint could not be formed (e.g. incorrect number
  1079. /// of arguments for the named concept).
  1080. bool Sema::AttachTypeConstraint(NestedNameSpecifierLoc NS,
  1081. DeclarationNameInfo NameInfo,
  1082. ConceptDecl *NamedConcept,
  1083. const TemplateArgumentListInfo *TemplateArgs,
  1084. TemplateTypeParmDecl *ConstrainedParameter,
  1085. SourceLocation EllipsisLoc) {
  1086. // C++2a [temp.param]p4:
  1087. // [...] If Q is of the form C<A1, ..., An>, then let E' be
  1088. // C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
  1089. const ASTTemplateArgumentListInfo *ArgsAsWritten =
  1090. TemplateArgs ? ASTTemplateArgumentListInfo::Create(Context,
  1091. *TemplateArgs) : nullptr;
  1092. QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0);
  1093. ExprResult ImmediatelyDeclaredConstraint =
  1094. formImmediatelyDeclaredConstraint(
  1095. *this, NS, NameInfo, NamedConcept,
  1096. TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(),
  1097. TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(),
  1098. ParamAsArgument, ConstrainedParameter->getLocation(),
  1099. [&] (TemplateArgumentListInfo &ConstraintArgs) {
  1100. if (TemplateArgs)
  1101. for (const auto &ArgLoc : TemplateArgs->arguments())
  1102. ConstraintArgs.addArgument(ArgLoc);
  1103. }, EllipsisLoc);
  1104. if (ImmediatelyDeclaredConstraint.isInvalid())
  1105. return true;
  1106. ConstrainedParameter->setTypeConstraint(NS, NameInfo,
  1107. /*FoundDecl=*/NamedConcept,
  1108. NamedConcept, ArgsAsWritten,
  1109. ImmediatelyDeclaredConstraint.get());
  1110. return false;
  1111. }
  1112. bool Sema::AttachTypeConstraint(AutoTypeLoc TL, NonTypeTemplateParmDecl *NTTP,
  1113. SourceLocation EllipsisLoc) {
  1114. if (NTTP->getType() != TL.getType() ||
  1115. TL.getAutoKeyword() != AutoTypeKeyword::Auto) {
  1116. Diag(NTTP->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
  1117. diag::err_unsupported_placeholder_constraint)
  1118. << NTTP->getTypeSourceInfo()->getTypeLoc().getSourceRange();
  1119. return true;
  1120. }
  1121. // FIXME: Concepts: This should be the type of the placeholder, but this is
  1122. // unclear in the wording right now.
  1123. DeclRefExpr *Ref =
  1124. BuildDeclRefExpr(NTTP, NTTP->getType(), VK_PRValue, NTTP->getLocation());
  1125. if (!Ref)
  1126. return true;
  1127. ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
  1128. *this, TL.getNestedNameSpecifierLoc(), TL.getConceptNameInfo(),
  1129. TL.getNamedConcept(), TL.getLAngleLoc(), TL.getRAngleLoc(),
  1130. BuildDecltypeType(Ref), NTTP->getLocation(),
  1131. [&](TemplateArgumentListInfo &ConstraintArgs) {
  1132. for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
  1133. ConstraintArgs.addArgument(TL.getArgLoc(I));
  1134. },
  1135. EllipsisLoc);
  1136. if (ImmediatelyDeclaredConstraint.isInvalid() ||
  1137. !ImmediatelyDeclaredConstraint.isUsable())
  1138. return true;
  1139. NTTP->setPlaceholderTypeConstraint(ImmediatelyDeclaredConstraint.get());
  1140. return false;
  1141. }
  1142. /// Check that the type of a non-type template parameter is
  1143. /// well-formed.
  1144. ///
  1145. /// \returns the (possibly-promoted) parameter type if valid;
  1146. /// otherwise, produces a diagnostic and returns a NULL type.
  1147. QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
  1148. SourceLocation Loc) {
  1149. if (TSI->getType()->isUndeducedType()) {
  1150. // C++17 [temp.dep.expr]p3:
  1151. // An id-expression is type-dependent if it contains
  1152. // - an identifier associated by name lookup with a non-type
  1153. // template-parameter declared with a type that contains a
  1154. // placeholder type (7.1.7.4),
  1155. TSI = SubstAutoTypeSourceInfoDependent(TSI);
  1156. }
  1157. return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
  1158. }
  1159. /// Require the given type to be a structural type, and diagnose if it is not.
  1160. ///
  1161. /// \return \c true if an error was produced.
  1162. bool Sema::RequireStructuralType(QualType T, SourceLocation Loc) {
  1163. if (T->isDependentType())
  1164. return false;
  1165. if (RequireCompleteType(Loc, T, diag::err_template_nontype_parm_incomplete))
  1166. return true;
  1167. if (T->isStructuralType())
  1168. return false;
  1169. // Structural types are required to be object types or lvalue references.
  1170. if (T->isRValueReferenceType()) {
  1171. Diag(Loc, diag::err_template_nontype_parm_rvalue_ref) << T;
  1172. return true;
  1173. }
  1174. // Don't mention structural types in our diagnostic prior to C++20. Also,
  1175. // there's not much more we can say about non-scalar non-class types --
  1176. // because we can't see functions or arrays here, those can only be language
  1177. // extensions.
  1178. if (!getLangOpts().CPlusPlus20 ||
  1179. (!T->isScalarType() && !T->isRecordType())) {
  1180. Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;
  1181. return true;
  1182. }
  1183. // Structural types are required to be literal types.
  1184. if (RequireLiteralType(Loc, T, diag::err_template_nontype_parm_not_literal))
  1185. return true;
  1186. Diag(Loc, diag::err_template_nontype_parm_not_structural) << T;
  1187. // Drill down into the reason why the class is non-structural.
  1188. while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
  1189. // All members are required to be public and non-mutable, and can't be of
  1190. // rvalue reference type. Check these conditions first to prefer a "local"
  1191. // reason over a more distant one.
  1192. for (const FieldDecl *FD : RD->fields()) {
  1193. if (FD->getAccess() != AS_public) {
  1194. Diag(FD->getLocation(), diag::note_not_structural_non_public) << T << 0;
  1195. return true;
  1196. }
  1197. if (FD->isMutable()) {
  1198. Diag(FD->getLocation(), diag::note_not_structural_mutable_field) << T;
  1199. return true;
  1200. }
  1201. if (FD->getType()->isRValueReferenceType()) {
  1202. Diag(FD->getLocation(), diag::note_not_structural_rvalue_ref_field)
  1203. << T;
  1204. return true;
  1205. }
  1206. }
  1207. // All bases are required to be public.
  1208. for (const auto &BaseSpec : RD->bases()) {
  1209. if (BaseSpec.getAccessSpecifier() != AS_public) {
  1210. Diag(BaseSpec.getBaseTypeLoc(), diag::note_not_structural_non_public)
  1211. << T << 1;
  1212. return true;
  1213. }
  1214. }
  1215. // All subobjects are required to be of structural types.
  1216. SourceLocation SubLoc;
  1217. QualType SubType;
  1218. int Kind = -1;
  1219. for (const FieldDecl *FD : RD->fields()) {
  1220. QualType T = Context.getBaseElementType(FD->getType());
  1221. if (!T->isStructuralType()) {
  1222. SubLoc = FD->getLocation();
  1223. SubType = T;
  1224. Kind = 0;
  1225. break;
  1226. }
  1227. }
  1228. if (Kind == -1) {
  1229. for (const auto &BaseSpec : RD->bases()) {
  1230. QualType T = BaseSpec.getType();
  1231. if (!T->isStructuralType()) {
  1232. SubLoc = BaseSpec.getBaseTypeLoc();
  1233. SubType = T;
  1234. Kind = 1;
  1235. break;
  1236. }
  1237. }
  1238. }
  1239. assert(Kind != -1 && "couldn't find reason why type is not structural");
  1240. Diag(SubLoc, diag::note_not_structural_subobject)
  1241. << T << Kind << SubType;
  1242. T = SubType;
  1243. RD = T->getAsCXXRecordDecl();
  1244. }
  1245. return true;
  1246. }
  1247. QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
  1248. SourceLocation Loc) {
  1249. // We don't allow variably-modified types as the type of non-type template
  1250. // parameters.
  1251. if (T->isVariablyModifiedType()) {
  1252. Diag(Loc, diag::err_variably_modified_nontype_template_param)
  1253. << T;
  1254. return QualType();
  1255. }
  1256. // C++ [temp.param]p4:
  1257. //
  1258. // A non-type template-parameter shall have one of the following
  1259. // (optionally cv-qualified) types:
  1260. //
  1261. // -- integral or enumeration type,
  1262. if (T->isIntegralOrEnumerationType() ||
  1263. // -- pointer to object or pointer to function,
  1264. T->isPointerType() ||
  1265. // -- lvalue reference to object or lvalue reference to function,
  1266. T->isLValueReferenceType() ||
  1267. // -- pointer to member,
  1268. T->isMemberPointerType() ||
  1269. // -- std::nullptr_t, or
  1270. T->isNullPtrType() ||
  1271. // -- a type that contains a placeholder type.
  1272. T->isUndeducedType()) {
  1273. // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
  1274. // are ignored when determining its type.
  1275. return T.getUnqualifiedType();
  1276. }
  1277. // C++ [temp.param]p8:
  1278. //
  1279. // A non-type template-parameter of type "array of T" or
  1280. // "function returning T" is adjusted to be of type "pointer to
  1281. // T" or "pointer to function returning T", respectively.
  1282. if (T->isArrayType() || T->isFunctionType())
  1283. return Context.getDecayedType(T);
  1284. // If T is a dependent type, we can't do the check now, so we
  1285. // assume that it is well-formed. Note that stripping off the
  1286. // qualifiers here is not really correct if T turns out to be
  1287. // an array type, but we'll recompute the type everywhere it's
  1288. // used during instantiation, so that should be OK. (Using the
  1289. // qualified type is equally wrong.)
  1290. if (T->isDependentType())
  1291. return T.getUnqualifiedType();
  1292. // C++20 [temp.param]p6:
  1293. // -- a structural type
  1294. if (RequireStructuralType(T, Loc))
  1295. return QualType();
  1296. if (!getLangOpts().CPlusPlus20) {
  1297. // FIXME: Consider allowing structural types as an extension in C++17. (In
  1298. // earlier language modes, the template argument evaluation rules are too
  1299. // inflexible.)
  1300. Diag(Loc, diag::err_template_nontype_parm_bad_structural_type) << T;
  1301. return QualType();
  1302. }
  1303. Diag(Loc, diag::warn_cxx17_compat_template_nontype_parm_type) << T;
  1304. return T.getUnqualifiedType();
  1305. }
  1306. NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
  1307. unsigned Depth,
  1308. unsigned Position,
  1309. SourceLocation EqualLoc,
  1310. Expr *Default) {
  1311. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  1312. // Check that we have valid decl-specifiers specified.
  1313. auto CheckValidDeclSpecifiers = [this, &D] {
  1314. // C++ [temp.param]
  1315. // p1
  1316. // template-parameter:
  1317. // ...
  1318. // parameter-declaration
  1319. // p2
  1320. // ... A storage class shall not be specified in a template-parameter
  1321. // declaration.
  1322. // [dcl.typedef]p1:
  1323. // The typedef specifier [...] shall not be used in the decl-specifier-seq
  1324. // of a parameter-declaration
  1325. const DeclSpec &DS = D.getDeclSpec();
  1326. auto EmitDiag = [this](SourceLocation Loc) {
  1327. Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
  1328. << FixItHint::CreateRemoval(Loc);
  1329. };
  1330. if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified)
  1331. EmitDiag(DS.getStorageClassSpecLoc());
  1332. if (DS.getThreadStorageClassSpec() != TSCS_unspecified)
  1333. EmitDiag(DS.getThreadStorageClassSpecLoc());
  1334. // [dcl.inline]p1:
  1335. // The inline specifier can be applied only to the declaration or
  1336. // definition of a variable or function.
  1337. if (DS.isInlineSpecified())
  1338. EmitDiag(DS.getInlineSpecLoc());
  1339. // [dcl.constexpr]p1:
  1340. // The constexpr specifier shall be applied only to the definition of a
  1341. // variable or variable template or the declaration of a function or
  1342. // function template.
  1343. if (DS.hasConstexprSpecifier())
  1344. EmitDiag(DS.getConstexprSpecLoc());
  1345. // [dcl.fct.spec]p1:
  1346. // Function-specifiers can be used only in function declarations.
  1347. if (DS.isVirtualSpecified())
  1348. EmitDiag(DS.getVirtualSpecLoc());
  1349. if (DS.hasExplicitSpecifier())
  1350. EmitDiag(DS.getExplicitSpecLoc());
  1351. if (DS.isNoreturnSpecified())
  1352. EmitDiag(DS.getNoreturnSpecLoc());
  1353. };
  1354. CheckValidDeclSpecifiers();
  1355. if (const auto *T = TInfo->getType()->getContainedDeducedType())
  1356. if (isa<AutoType>(T))
  1357. Diag(D.getIdentifierLoc(),
  1358. diag::warn_cxx14_compat_template_nontype_parm_auto_type)
  1359. << QualType(TInfo->getType()->getContainedAutoType(), 0);
  1360. assert(S->isTemplateParamScope() &&
  1361. "Non-type template parameter not in template parameter scope!");
  1362. bool Invalid = false;
  1363. QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
  1364. if (T.isNull()) {
  1365. T = Context.IntTy; // Recover with an 'int' type.
  1366. Invalid = true;
  1367. }
  1368. CheckFunctionOrTemplateParamDeclarator(S, D);
  1369. IdentifierInfo *ParamName = D.getIdentifier();
  1370. bool IsParameterPack = D.hasEllipsis();
  1371. NonTypeTemplateParmDecl *Param = NonTypeTemplateParmDecl::Create(
  1372. Context, Context.getTranslationUnitDecl(), D.getBeginLoc(),
  1373. D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
  1374. TInfo);
  1375. Param->setAccess(AS_public);
  1376. if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc())
  1377. if (TL.isConstrained())
  1378. if (AttachTypeConstraint(TL, Param, D.getEllipsisLoc()))
  1379. Invalid = true;
  1380. if (Invalid)
  1381. Param->setInvalidDecl();
  1382. if (Param->isParameterPack())
  1383. if (auto *LSI = getEnclosingLambda())
  1384. LSI->LocalPacks.push_back(Param);
  1385. if (ParamName) {
  1386. maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
  1387. ParamName);
  1388. // Add the template parameter into the current scope.
  1389. S->AddDecl(Param);
  1390. IdResolver.AddDecl(Param);
  1391. }
  1392. // C++0x [temp.param]p9:
  1393. // A default template-argument may be specified for any kind of
  1394. // template-parameter that is not a template parameter pack.
  1395. if (Default && IsParameterPack) {
  1396. Diag(EqualLoc, diag::err_template_param_pack_default_arg);
  1397. Default = nullptr;
  1398. }
  1399. // Check the well-formedness of the default template argument, if provided.
  1400. if (Default) {
  1401. // Check for unexpanded parameter packs.
  1402. if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
  1403. return Param;
  1404. TemplateArgument SugaredConverted, CanonicalConverted;
  1405. ExprResult DefaultRes = CheckTemplateArgument(
  1406. Param, Param->getType(), Default, SugaredConverted, CanonicalConverted,
  1407. CTAK_Specified);
  1408. if (DefaultRes.isInvalid()) {
  1409. Param->setInvalidDecl();
  1410. return Param;
  1411. }
  1412. Default = DefaultRes.get();
  1413. Param->setDefaultArgument(Default);
  1414. }
  1415. return Param;
  1416. }
  1417. /// ActOnTemplateTemplateParameter - Called when a C++ template template
  1418. /// parameter (e.g. T in template <template \<typename> class T> class array)
  1419. /// has been parsed. S is the current scope.
  1420. NamedDecl *Sema::ActOnTemplateTemplateParameter(Scope* S,
  1421. SourceLocation TmpLoc,
  1422. TemplateParameterList *Params,
  1423. SourceLocation EllipsisLoc,
  1424. IdentifierInfo *Name,
  1425. SourceLocation NameLoc,
  1426. unsigned Depth,
  1427. unsigned Position,
  1428. SourceLocation EqualLoc,
  1429. ParsedTemplateArgument Default) {
  1430. assert(S->isTemplateParamScope() &&
  1431. "Template template parameter not in template parameter scope!");
  1432. // Construct the parameter object.
  1433. bool IsParameterPack = EllipsisLoc.isValid();
  1434. TemplateTemplateParmDecl *Param =
  1435. TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
  1436. NameLoc.isInvalid()? TmpLoc : NameLoc,
  1437. Depth, Position, IsParameterPack,
  1438. Name, Params);
  1439. Param->setAccess(AS_public);
  1440. if (Param->isParameterPack())
  1441. if (auto *LSI = getEnclosingLambda())
  1442. LSI->LocalPacks.push_back(Param);
  1443. // If the template template parameter has a name, then link the identifier
  1444. // into the scope and lookup mechanisms.
  1445. if (Name) {
  1446. maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
  1447. S->AddDecl(Param);
  1448. IdResolver.AddDecl(Param);
  1449. }
  1450. if (Params->size() == 0) {
  1451. Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
  1452. << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
  1453. Param->setInvalidDecl();
  1454. }
  1455. // C++0x [temp.param]p9:
  1456. // A default template-argument may be specified for any kind of
  1457. // template-parameter that is not a template parameter pack.
  1458. if (IsParameterPack && !Default.isInvalid()) {
  1459. Diag(EqualLoc, diag::err_template_param_pack_default_arg);
  1460. Default = ParsedTemplateArgument();
  1461. }
  1462. if (!Default.isInvalid()) {
  1463. // Check only that we have a template template argument. We don't want to
  1464. // try to check well-formedness now, because our template template parameter
  1465. // might have dependent types in its template parameters, which we wouldn't
  1466. // be able to match now.
  1467. //
  1468. // If none of the template template parameter's template arguments mention
  1469. // other template parameters, we could actually perform more checking here.
  1470. // However, it isn't worth doing.
  1471. TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
  1472. if (DefaultArg.getArgument().getAsTemplate().isNull()) {
  1473. Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
  1474. << DefaultArg.getSourceRange();
  1475. return Param;
  1476. }
  1477. // Check for unexpanded parameter packs.
  1478. if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
  1479. DefaultArg.getArgument().getAsTemplate(),
  1480. UPPC_DefaultArgument))
  1481. return Param;
  1482. Param->setDefaultArgument(Context, DefaultArg);
  1483. }
  1484. return Param;
  1485. }
  1486. namespace {
  1487. class ConstraintRefersToContainingTemplateChecker
  1488. : public TreeTransform<ConstraintRefersToContainingTemplateChecker> {
  1489. bool Result = false;
  1490. const FunctionDecl *Friend = nullptr;
  1491. unsigned TemplateDepth = 0;
  1492. // Check a record-decl that we've seen to see if it is a lexical parent of the
  1493. // Friend, likely because it was referred to without its template arguments.
  1494. void CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) {
  1495. CheckingRD = CheckingRD->getMostRecentDecl();
  1496. for (const DeclContext *DC = Friend->getLexicalDeclContext();
  1497. DC && !DC->isFileContext(); DC = DC->getParent())
  1498. if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
  1499. if (CheckingRD == RD->getMostRecentDecl())
  1500. Result = true;
  1501. }
  1502. void CheckNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
  1503. assert(D->getDepth() <= TemplateDepth &&
  1504. "Nothing should reference a value below the actual template depth, "
  1505. "depth is likely wrong");
  1506. if (D->getDepth() != TemplateDepth)
  1507. Result = true;
  1508. // Necessary because the type of the NTTP might be what refers to the parent
  1509. // constriant.
  1510. TransformType(D->getType());
  1511. }
  1512. public:
  1513. using inherited = TreeTransform<ConstraintRefersToContainingTemplateChecker>;
  1514. ConstraintRefersToContainingTemplateChecker(Sema &SemaRef,
  1515. const FunctionDecl *Friend,
  1516. unsigned TemplateDepth)
  1517. : inherited(SemaRef), Friend(Friend), TemplateDepth(TemplateDepth) {}
  1518. bool getResult() const { return Result; }
  1519. // This should be the only template parm type that we have to deal with.
  1520. // SubstTempalteTypeParmPack, SubstNonTypeTemplateParmPack, and
  1521. // FunctionParmPackExpr are all partially substituted, which cannot happen
  1522. // with concepts at this point in translation.
  1523. using inherited::TransformTemplateTypeParmType;
  1524. QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
  1525. TemplateTypeParmTypeLoc TL, bool) {
  1526. assert(TL.getDecl()->getDepth() <= TemplateDepth &&
  1527. "Nothing should reference a value below the actual template depth, "
  1528. "depth is likely wrong");
  1529. if (TL.getDecl()->getDepth() != TemplateDepth)
  1530. Result = true;
  1531. return inherited::TransformTemplateTypeParmType(
  1532. TLB, TL,
  1533. /*SuppressObjCLifetime=*/false);
  1534. }
  1535. Decl *TransformDecl(SourceLocation Loc, Decl *D) {
  1536. if (!D)
  1537. return D;
  1538. // FIXME : This is possibly an incomplete list, but it is unclear what other
  1539. // Decl kinds could be used to refer to the template parameters. This is a
  1540. // best guess so far based on examples currently available, but the
  1541. // unreachable should catch future instances/cases.
  1542. if (auto *TD = dyn_cast<TypedefNameDecl>(D))
  1543. TransformType(TD->getUnderlyingType());
  1544. else if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(D))
  1545. CheckNonTypeTemplateParmDecl(NTTPD);
  1546. else if (auto *VD = dyn_cast<ValueDecl>(D))
  1547. TransformType(VD->getType());
  1548. else if (auto *TD = dyn_cast<TemplateDecl>(D))
  1549. TransformTemplateParameterList(TD->getTemplateParameters());
  1550. else if (auto *RD = dyn_cast<CXXRecordDecl>(D))
  1551. CheckIfContainingRecord(RD);
  1552. else if (isa<NamedDecl>(D)) {
  1553. // No direct types to visit here I believe.
  1554. } else
  1555. llvm_unreachable("Don't know how to handle this declaration type yet");
  1556. return D;
  1557. }
  1558. };
  1559. } // namespace
  1560. bool Sema::ConstraintExpressionDependsOnEnclosingTemplate(
  1561. const FunctionDecl *Friend, unsigned TemplateDepth,
  1562. const Expr *Constraint) {
  1563. assert(Friend->getFriendObjectKind() && "Only works on a friend");
  1564. ConstraintRefersToContainingTemplateChecker Checker(*this, Friend,
  1565. TemplateDepth);
  1566. Checker.TransformExpr(const_cast<Expr *>(Constraint));
  1567. return Checker.getResult();
  1568. }
  1569. /// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
  1570. /// constrained by RequiresClause, that contains the template parameters in
  1571. /// Params.
  1572. TemplateParameterList *
  1573. Sema::ActOnTemplateParameterList(unsigned Depth,
  1574. SourceLocation ExportLoc,
  1575. SourceLocation TemplateLoc,
  1576. SourceLocation LAngleLoc,
  1577. ArrayRef<NamedDecl *> Params,
  1578. SourceLocation RAngleLoc,
  1579. Expr *RequiresClause) {
  1580. if (ExportLoc.isValid())
  1581. Diag(ExportLoc, diag::warn_template_export_unsupported);
  1582. for (NamedDecl *P : Params)
  1583. warnOnReservedIdentifier(P);
  1584. return TemplateParameterList::Create(
  1585. Context, TemplateLoc, LAngleLoc,
  1586. llvm::ArrayRef(Params.data(), Params.size()), RAngleLoc, RequiresClause);
  1587. }
  1588. static void SetNestedNameSpecifier(Sema &S, TagDecl *T,
  1589. const CXXScopeSpec &SS) {
  1590. if (SS.isSet())
  1591. T->setQualifierInfo(SS.getWithLocInContext(S.Context));
  1592. }
  1593. DeclResult Sema::CheckClassTemplate(
  1594. Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
  1595. CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
  1596. const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
  1597. AccessSpecifier AS, SourceLocation ModulePrivateLoc,
  1598. SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
  1599. TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
  1600. assert(TemplateParams && TemplateParams->size() > 0 &&
  1601. "No template parameters");
  1602. assert(TUK != TUK_Reference && "Can only declare or define class templates");
  1603. bool Invalid = false;
  1604. // Check that we can declare a template here.
  1605. if (CheckTemplateDeclScope(S, TemplateParams))
  1606. return true;
  1607. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  1608. assert(Kind != TTK_Enum && "can't build template of enumerated type");
  1609. // There is no such thing as an unnamed class template.
  1610. if (!Name) {
  1611. Diag(KWLoc, diag::err_template_unnamed_class);
  1612. return true;
  1613. }
  1614. // Find any previous declaration with this name. For a friend with no
  1615. // scope explicitly specified, we only look for tag declarations (per
  1616. // C++11 [basic.lookup.elab]p2).
  1617. DeclContext *SemanticContext;
  1618. LookupResult Previous(*this, Name, NameLoc,
  1619. (SS.isEmpty() && TUK == TUK_Friend)
  1620. ? LookupTagName : LookupOrdinaryName,
  1621. forRedeclarationInCurContext());
  1622. if (SS.isNotEmpty() && !SS.isInvalid()) {
  1623. SemanticContext = computeDeclContext(SS, true);
  1624. if (!SemanticContext) {
  1625. // FIXME: Horrible, horrible hack! We can't currently represent this
  1626. // in the AST, and historically we have just ignored such friend
  1627. // class templates, so don't complain here.
  1628. Diag(NameLoc, TUK == TUK_Friend
  1629. ? diag::warn_template_qualified_friend_ignored
  1630. : diag::err_template_qualified_declarator_no_match)
  1631. << SS.getScopeRep() << SS.getRange();
  1632. return TUK != TUK_Friend;
  1633. }
  1634. if (RequireCompleteDeclContext(SS, SemanticContext))
  1635. return true;
  1636. // If we're adding a template to a dependent context, we may need to
  1637. // rebuilding some of the types used within the template parameter list,
  1638. // now that we know what the current instantiation is.
  1639. if (SemanticContext->isDependentContext()) {
  1640. ContextRAII SavedContext(*this, SemanticContext);
  1641. if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
  1642. Invalid = true;
  1643. } else if (TUK != TUK_Friend && TUK != TUK_Reference)
  1644. diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc, false);
  1645. LookupQualifiedName(Previous, SemanticContext);
  1646. } else {
  1647. SemanticContext = CurContext;
  1648. // C++14 [class.mem]p14:
  1649. // If T is the name of a class, then each of the following shall have a
  1650. // name different from T:
  1651. // -- every member template of class T
  1652. if (TUK != TUK_Friend &&
  1653. DiagnoseClassNameShadow(SemanticContext,
  1654. DeclarationNameInfo(Name, NameLoc)))
  1655. return true;
  1656. LookupName(Previous, S);
  1657. }
  1658. if (Previous.isAmbiguous())
  1659. return true;
  1660. NamedDecl *PrevDecl = nullptr;
  1661. if (Previous.begin() != Previous.end())
  1662. PrevDecl = (*Previous.begin())->getUnderlyingDecl();
  1663. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  1664. // Maybe we will complain about the shadowed template parameter.
  1665. DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
  1666. // Just pretend that we didn't see the previous declaration.
  1667. PrevDecl = nullptr;
  1668. }
  1669. // If there is a previous declaration with the same name, check
  1670. // whether this is a valid redeclaration.
  1671. ClassTemplateDecl *PrevClassTemplate =
  1672. dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
  1673. // We may have found the injected-class-name of a class template,
  1674. // class template partial specialization, or class template specialization.
  1675. // In these cases, grab the template that is being defined or specialized.
  1676. if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
  1677. cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
  1678. PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
  1679. PrevClassTemplate
  1680. = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
  1681. if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
  1682. PrevClassTemplate
  1683. = cast<ClassTemplateSpecializationDecl>(PrevDecl)
  1684. ->getSpecializedTemplate();
  1685. }
  1686. }
  1687. if (TUK == TUK_Friend) {
  1688. // C++ [namespace.memdef]p3:
  1689. // [...] When looking for a prior declaration of a class or a function
  1690. // declared as a friend, and when the name of the friend class or
  1691. // function is neither a qualified name nor a template-id, scopes outside
  1692. // the innermost enclosing namespace scope are not considered.
  1693. if (!SS.isSet()) {
  1694. DeclContext *OutermostContext = CurContext;
  1695. while (!OutermostContext->isFileContext())
  1696. OutermostContext = OutermostContext->getLookupParent();
  1697. if (PrevDecl &&
  1698. (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
  1699. OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
  1700. SemanticContext = PrevDecl->getDeclContext();
  1701. } else {
  1702. // Declarations in outer scopes don't matter. However, the outermost
  1703. // context we computed is the semantic context for our new
  1704. // declaration.
  1705. PrevDecl = PrevClassTemplate = nullptr;
  1706. SemanticContext = OutermostContext;
  1707. // Check that the chosen semantic context doesn't already contain a
  1708. // declaration of this name as a non-tag type.
  1709. Previous.clear(LookupOrdinaryName);
  1710. DeclContext *LookupContext = SemanticContext;
  1711. while (LookupContext->isTransparentContext())
  1712. LookupContext = LookupContext->getLookupParent();
  1713. LookupQualifiedName(Previous, LookupContext);
  1714. if (Previous.isAmbiguous())
  1715. return true;
  1716. if (Previous.begin() != Previous.end())
  1717. PrevDecl = (*Previous.begin())->getUnderlyingDecl();
  1718. }
  1719. }
  1720. } else if (PrevDecl &&
  1721. !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
  1722. S, SS.isValid()))
  1723. PrevDecl = PrevClassTemplate = nullptr;
  1724. if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
  1725. PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
  1726. if (SS.isEmpty() &&
  1727. !(PrevClassTemplate &&
  1728. PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
  1729. SemanticContext->getRedeclContext()))) {
  1730. Diag(KWLoc, diag::err_using_decl_conflict_reverse);
  1731. Diag(Shadow->getTargetDecl()->getLocation(),
  1732. diag::note_using_decl_target);
  1733. Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
  1734. // Recover by ignoring the old declaration.
  1735. PrevDecl = PrevClassTemplate = nullptr;
  1736. }
  1737. }
  1738. if (PrevClassTemplate) {
  1739. // Ensure that the template parameter lists are compatible. Skip this check
  1740. // for a friend in a dependent context: the template parameter list itself
  1741. // could be dependent.
  1742. if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
  1743. !TemplateParameterListsAreEqual(TemplateParams,
  1744. PrevClassTemplate->getTemplateParameters(),
  1745. /*Complain=*/true,
  1746. TPL_TemplateMatch))
  1747. return true;
  1748. // C++ [temp.class]p4:
  1749. // In a redeclaration, partial specialization, explicit
  1750. // specialization or explicit instantiation of a class template,
  1751. // the class-key shall agree in kind with the original class
  1752. // template declaration (7.1.5.3).
  1753. RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
  1754. if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
  1755. TUK == TUK_Definition, KWLoc, Name)) {
  1756. Diag(KWLoc, diag::err_use_with_wrong_tag)
  1757. << Name
  1758. << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
  1759. Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
  1760. Kind = PrevRecordDecl->getTagKind();
  1761. }
  1762. // Check for redefinition of this class template.
  1763. if (TUK == TUK_Definition) {
  1764. if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
  1765. // If we have a prior definition that is not visible, treat this as
  1766. // simply making that previous definition visible.
  1767. NamedDecl *Hidden = nullptr;
  1768. if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
  1769. SkipBody->ShouldSkip = true;
  1770. SkipBody->Previous = Def;
  1771. auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
  1772. assert(Tmpl && "original definition of a class template is not a "
  1773. "class template?");
  1774. makeMergedDefinitionVisible(Hidden);
  1775. makeMergedDefinitionVisible(Tmpl);
  1776. } else {
  1777. Diag(NameLoc, diag::err_redefinition) << Name;
  1778. Diag(Def->getLocation(), diag::note_previous_definition);
  1779. // FIXME: Would it make sense to try to "forget" the previous
  1780. // definition, as part of error recovery?
  1781. return true;
  1782. }
  1783. }
  1784. }
  1785. } else if (PrevDecl) {
  1786. // C++ [temp]p5:
  1787. // A class template shall not have the same name as any other
  1788. // template, class, function, object, enumeration, enumerator,
  1789. // namespace, or type in the same scope (3.3), except as specified
  1790. // in (14.5.4).
  1791. Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
  1792. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  1793. return true;
  1794. }
  1795. // Check the template parameter list of this declaration, possibly
  1796. // merging in the template parameter list from the previous class
  1797. // template declaration. Skip this check for a friend in a dependent
  1798. // context, because the template parameter list might be dependent.
  1799. if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
  1800. CheckTemplateParameterList(
  1801. TemplateParams,
  1802. PrevClassTemplate
  1803. ? PrevClassTemplate->getMostRecentDecl()->getTemplateParameters()
  1804. : nullptr,
  1805. (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
  1806. SemanticContext->isDependentContext())
  1807. ? TPC_ClassTemplateMember
  1808. : TUK == TUK_Friend ? TPC_FriendClassTemplate : TPC_ClassTemplate,
  1809. SkipBody))
  1810. Invalid = true;
  1811. if (SS.isSet()) {
  1812. // If the name of the template was qualified, we must be defining the
  1813. // template out-of-line.
  1814. if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
  1815. Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
  1816. : diag::err_member_decl_does_not_match)
  1817. << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
  1818. Invalid = true;
  1819. }
  1820. }
  1821. // If this is a templated friend in a dependent context we should not put it
  1822. // on the redecl chain. In some cases, the templated friend can be the most
  1823. // recent declaration tricking the template instantiator to make substitutions
  1824. // there.
  1825. // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
  1826. bool ShouldAddRedecl
  1827. = !(TUK == TUK_Friend && CurContext->isDependentContext());
  1828. CXXRecordDecl *NewClass =
  1829. CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
  1830. PrevClassTemplate && ShouldAddRedecl ?
  1831. PrevClassTemplate->getTemplatedDecl() : nullptr,
  1832. /*DelayTypeCreation=*/true);
  1833. SetNestedNameSpecifier(*this, NewClass, SS);
  1834. if (NumOuterTemplateParamLists > 0)
  1835. NewClass->setTemplateParameterListsInfo(
  1836. Context,
  1837. llvm::ArrayRef(OuterTemplateParamLists, NumOuterTemplateParamLists));
  1838. // Add alignment attributes if necessary; these attributes are checked when
  1839. // the ASTContext lays out the structure.
  1840. if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
  1841. AddAlignmentAttributesForRecord(NewClass);
  1842. AddMsStructLayoutForRecord(NewClass);
  1843. }
  1844. ClassTemplateDecl *NewTemplate
  1845. = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
  1846. DeclarationName(Name), TemplateParams,
  1847. NewClass);
  1848. if (ShouldAddRedecl)
  1849. NewTemplate->setPreviousDecl(PrevClassTemplate);
  1850. NewClass->setDescribedClassTemplate(NewTemplate);
  1851. if (ModulePrivateLoc.isValid())
  1852. NewTemplate->setModulePrivate();
  1853. // Build the type for the class template declaration now.
  1854. QualType T = NewTemplate->getInjectedClassNameSpecialization();
  1855. T = Context.getInjectedClassNameType(NewClass, T);
  1856. assert(T->isDependentType() && "Class template type is not dependent?");
  1857. (void)T;
  1858. // If we are providing an explicit specialization of a member that is a
  1859. // class template, make a note of that.
  1860. if (PrevClassTemplate &&
  1861. PrevClassTemplate->getInstantiatedFromMemberTemplate())
  1862. PrevClassTemplate->setMemberSpecialization();
  1863. // Set the access specifier.
  1864. if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
  1865. SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
  1866. // Set the lexical context of these templates
  1867. NewClass->setLexicalDeclContext(CurContext);
  1868. NewTemplate->setLexicalDeclContext(CurContext);
  1869. if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
  1870. NewClass->startDefinition();
  1871. ProcessDeclAttributeList(S, NewClass, Attr);
  1872. if (PrevClassTemplate)
  1873. mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
  1874. AddPushedVisibilityAttribute(NewClass);
  1875. inferGslOwnerPointerAttribute(NewClass);
  1876. if (TUK != TUK_Friend) {
  1877. // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
  1878. Scope *Outer = S;
  1879. while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
  1880. Outer = Outer->getParent();
  1881. PushOnScopeChains(NewTemplate, Outer);
  1882. } else {
  1883. if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
  1884. NewTemplate->setAccess(PrevClassTemplate->getAccess());
  1885. NewClass->setAccess(PrevClassTemplate->getAccess());
  1886. }
  1887. NewTemplate->setObjectOfFriendDecl();
  1888. // Friend templates are visible in fairly strange ways.
  1889. if (!CurContext->isDependentContext()) {
  1890. DeclContext *DC = SemanticContext->getRedeclContext();
  1891. DC->makeDeclVisibleInContext(NewTemplate);
  1892. if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
  1893. PushOnScopeChains(NewTemplate, EnclosingScope,
  1894. /* AddToContext = */ false);
  1895. }
  1896. FriendDecl *Friend = FriendDecl::Create(
  1897. Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
  1898. Friend->setAccess(AS_public);
  1899. CurContext->addDecl(Friend);
  1900. }
  1901. if (PrevClassTemplate)
  1902. CheckRedeclarationInModule(NewTemplate, PrevClassTemplate);
  1903. if (Invalid) {
  1904. NewTemplate->setInvalidDecl();
  1905. NewClass->setInvalidDecl();
  1906. }
  1907. ActOnDocumentableDecl(NewTemplate);
  1908. if (SkipBody && SkipBody->ShouldSkip)
  1909. return SkipBody->Previous;
  1910. return NewTemplate;
  1911. }
  1912. namespace {
  1913. /// Tree transform to "extract" a transformed type from a class template's
  1914. /// constructor to a deduction guide.
  1915. class ExtractTypeForDeductionGuide
  1916. : public TreeTransform<ExtractTypeForDeductionGuide> {
  1917. llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs;
  1918. public:
  1919. typedef TreeTransform<ExtractTypeForDeductionGuide> Base;
  1920. ExtractTypeForDeductionGuide(
  1921. Sema &SemaRef,
  1922. llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs)
  1923. : Base(SemaRef), MaterializedTypedefs(MaterializedTypedefs) {}
  1924. TypeSourceInfo *transform(TypeSourceInfo *TSI) { return TransformType(TSI); }
  1925. QualType TransformTypedefType(TypeLocBuilder &TLB, TypedefTypeLoc TL) {
  1926. ASTContext &Context = SemaRef.getASTContext();
  1927. TypedefNameDecl *OrigDecl = TL.getTypedefNameDecl();
  1928. TypedefNameDecl *Decl = OrigDecl;
  1929. // Transform the underlying type of the typedef and clone the Decl only if
  1930. // the typedef has a dependent context.
  1931. if (OrigDecl->getDeclContext()->isDependentContext()) {
  1932. TypeLocBuilder InnerTLB;
  1933. QualType Transformed =
  1934. TransformType(InnerTLB, OrigDecl->getTypeSourceInfo()->getTypeLoc());
  1935. TypeSourceInfo *TSI = InnerTLB.getTypeSourceInfo(Context, Transformed);
  1936. if (isa<TypeAliasDecl>(OrigDecl))
  1937. Decl = TypeAliasDecl::Create(
  1938. Context, Context.getTranslationUnitDecl(), OrigDecl->getBeginLoc(),
  1939. OrigDecl->getLocation(), OrigDecl->getIdentifier(), TSI);
  1940. else {
  1941. assert(isa<TypedefDecl>(OrigDecl) && "Not a Type alias or typedef");
  1942. Decl = TypedefDecl::Create(
  1943. Context, Context.getTranslationUnitDecl(), OrigDecl->getBeginLoc(),
  1944. OrigDecl->getLocation(), OrigDecl->getIdentifier(), TSI);
  1945. }
  1946. MaterializedTypedefs.push_back(Decl);
  1947. }
  1948. QualType TDTy = Context.getTypedefType(Decl);
  1949. TypedefTypeLoc TypedefTL = TLB.push<TypedefTypeLoc>(TDTy);
  1950. TypedefTL.setNameLoc(TL.getNameLoc());
  1951. return TDTy;
  1952. }
  1953. };
  1954. /// Transform to convert portions of a constructor declaration into the
  1955. /// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
  1956. struct ConvertConstructorToDeductionGuideTransform {
  1957. ConvertConstructorToDeductionGuideTransform(Sema &S,
  1958. ClassTemplateDecl *Template)
  1959. : SemaRef(S), Template(Template) {}
  1960. Sema &SemaRef;
  1961. ClassTemplateDecl *Template;
  1962. DeclContext *DC = Template->getDeclContext();
  1963. CXXRecordDecl *Primary = Template->getTemplatedDecl();
  1964. DeclarationName DeductionGuideName =
  1965. SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(Template);
  1966. QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary);
  1967. // Index adjustment to apply to convert depth-1 template parameters into
  1968. // depth-0 template parameters.
  1969. unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size();
  1970. /// Transform a constructor declaration into a deduction guide.
  1971. NamedDecl *transformConstructor(FunctionTemplateDecl *FTD,
  1972. CXXConstructorDecl *CD) {
  1973. SmallVector<TemplateArgument, 16> SubstArgs;
  1974. LocalInstantiationScope Scope(SemaRef);
  1975. // C++ [over.match.class.deduct]p1:
  1976. // -- For each constructor of the class template designated by the
  1977. // template-name, a function template with the following properties:
  1978. // -- The template parameters are the template parameters of the class
  1979. // template followed by the template parameters (including default
  1980. // template arguments) of the constructor, if any.
  1981. TemplateParameterList *TemplateParams = Template->getTemplateParameters();
  1982. if (FTD) {
  1983. TemplateParameterList *InnerParams = FTD->getTemplateParameters();
  1984. SmallVector<NamedDecl *, 16> AllParams;
  1985. AllParams.reserve(TemplateParams->size() + InnerParams->size());
  1986. AllParams.insert(AllParams.begin(),
  1987. TemplateParams->begin(), TemplateParams->end());
  1988. SubstArgs.reserve(InnerParams->size());
  1989. // Later template parameters could refer to earlier ones, so build up
  1990. // a list of substituted template arguments as we go.
  1991. for (NamedDecl *Param : *InnerParams) {
  1992. MultiLevelTemplateArgumentList Args;
  1993. Args.setKind(TemplateSubstitutionKind::Rewrite);
  1994. Args.addOuterTemplateArguments(SubstArgs);
  1995. Args.addOuterRetainedLevel();
  1996. NamedDecl *NewParam = transformTemplateParameter(Param, Args);
  1997. if (!NewParam)
  1998. return nullptr;
  1999. AllParams.push_back(NewParam);
  2000. SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument(
  2001. SemaRef.Context.getInjectedTemplateArg(NewParam)));
  2002. }
  2003. // Substitute new template parameters into requires-clause if present.
  2004. Expr *RequiresClause = nullptr;
  2005. if (Expr *InnerRC = InnerParams->getRequiresClause()) {
  2006. MultiLevelTemplateArgumentList Args;
  2007. Args.setKind(TemplateSubstitutionKind::Rewrite);
  2008. Args.addOuterTemplateArguments(SubstArgs);
  2009. Args.addOuterRetainedLevel();
  2010. ExprResult E = SemaRef.SubstExpr(InnerRC, Args);
  2011. if (E.isInvalid())
  2012. return nullptr;
  2013. RequiresClause = E.getAs<Expr>();
  2014. }
  2015. TemplateParams = TemplateParameterList::Create(
  2016. SemaRef.Context, InnerParams->getTemplateLoc(),
  2017. InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
  2018. RequiresClause);
  2019. }
  2020. // If we built a new template-parameter-list, track that we need to
  2021. // substitute references to the old parameters into references to the
  2022. // new ones.
  2023. MultiLevelTemplateArgumentList Args;
  2024. Args.setKind(TemplateSubstitutionKind::Rewrite);
  2025. if (FTD) {
  2026. Args.addOuterTemplateArguments(SubstArgs);
  2027. Args.addOuterRetainedLevel();
  2028. }
  2029. FunctionProtoTypeLoc FPTL = CD->getTypeSourceInfo()->getTypeLoc()
  2030. .getAsAdjusted<FunctionProtoTypeLoc>();
  2031. assert(FPTL && "no prototype for constructor declaration");
  2032. // Transform the type of the function, adjusting the return type and
  2033. // replacing references to the old parameters with references to the
  2034. // new ones.
  2035. TypeLocBuilder TLB;
  2036. SmallVector<ParmVarDecl*, 8> Params;
  2037. SmallVector<TypedefNameDecl *, 4> MaterializedTypedefs;
  2038. QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args,
  2039. MaterializedTypedefs);
  2040. if (NewType.isNull())
  2041. return nullptr;
  2042. TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
  2043. return buildDeductionGuide(TemplateParams, CD, CD->getExplicitSpecifier(),
  2044. NewTInfo, CD->getBeginLoc(), CD->getLocation(),
  2045. CD->getEndLoc(), MaterializedTypedefs);
  2046. }
  2047. /// Build a deduction guide with the specified parameter types.
  2048. NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
  2049. SourceLocation Loc = Template->getLocation();
  2050. // Build the requested type.
  2051. FunctionProtoType::ExtProtoInfo EPI;
  2052. EPI.HasTrailingReturn = true;
  2053. QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
  2054. DeductionGuideName, EPI);
  2055. TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
  2056. FunctionProtoTypeLoc FPTL =
  2057. TSI->getTypeLoc().castAs<FunctionProtoTypeLoc>();
  2058. // Build the parameters, needed during deduction / substitution.
  2059. SmallVector<ParmVarDecl*, 4> Params;
  2060. for (auto T : ParamTypes) {
  2061. ParmVarDecl *NewParam = ParmVarDecl::Create(
  2062. SemaRef.Context, DC, Loc, Loc, nullptr, T,
  2063. SemaRef.Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr);
  2064. NewParam->setScopeInfo(0, Params.size());
  2065. FPTL.setParam(Params.size(), NewParam);
  2066. Params.push_back(NewParam);
  2067. }
  2068. return buildDeductionGuide(Template->getTemplateParameters(), nullptr,
  2069. ExplicitSpecifier(), TSI, Loc, Loc, Loc);
  2070. }
  2071. private:
  2072. /// Transform a constructor template parameter into a deduction guide template
  2073. /// parameter, rebuilding any internal references to earlier parameters and
  2074. /// renumbering as we go.
  2075. NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam,
  2076. MultiLevelTemplateArgumentList &Args) {
  2077. if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam)) {
  2078. // TemplateTypeParmDecl's index cannot be changed after creation, so
  2079. // substitute it directly.
  2080. auto *NewTTP = TemplateTypeParmDecl::Create(
  2081. SemaRef.Context, DC, TTP->getBeginLoc(), TTP->getLocation(),
  2082. /*Depth*/ 0, Depth1IndexAdjustment + TTP->getIndex(),
  2083. TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
  2084. TTP->isParameterPack(), TTP->hasTypeConstraint(),
  2085. TTP->isExpandedParameterPack()
  2086. ? std::optional<unsigned>(TTP->getNumExpansionParameters())
  2087. : std::nullopt);
  2088. if (const auto *TC = TTP->getTypeConstraint())
  2089. SemaRef.SubstTypeConstraint(NewTTP, TC, Args,
  2090. /*EvaluateConstraint*/ true);
  2091. if (TTP->hasDefaultArgument()) {
  2092. TypeSourceInfo *InstantiatedDefaultArg =
  2093. SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args,
  2094. TTP->getDefaultArgumentLoc(), TTP->getDeclName());
  2095. if (InstantiatedDefaultArg)
  2096. NewTTP->setDefaultArgument(InstantiatedDefaultArg);
  2097. }
  2098. SemaRef.CurrentInstantiationScope->InstantiatedLocal(TemplateParam,
  2099. NewTTP);
  2100. return NewTTP;
  2101. }
  2102. if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
  2103. return transformTemplateParameterImpl(TTP, Args);
  2104. return transformTemplateParameterImpl(
  2105. cast<NonTypeTemplateParmDecl>(TemplateParam), Args);
  2106. }
  2107. template<typename TemplateParmDecl>
  2108. TemplateParmDecl *
  2109. transformTemplateParameterImpl(TemplateParmDecl *OldParam,
  2110. MultiLevelTemplateArgumentList &Args) {
  2111. // Ask the template instantiator to do the heavy lifting for us, then adjust
  2112. // the index of the parameter once it's done.
  2113. auto *NewParam =
  2114. cast<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args));
  2115. assert(NewParam->getDepth() == 0 && "unexpected template param depth");
  2116. NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment);
  2117. return NewParam;
  2118. }
  2119. QualType transformFunctionProtoType(
  2120. TypeLocBuilder &TLB, FunctionProtoTypeLoc TL,
  2121. SmallVectorImpl<ParmVarDecl *> &Params,
  2122. MultiLevelTemplateArgumentList &Args,
  2123. SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs) {
  2124. SmallVector<QualType, 4> ParamTypes;
  2125. const FunctionProtoType *T = TL.getTypePtr();
  2126. // -- The types of the function parameters are those of the constructor.
  2127. for (auto *OldParam : TL.getParams()) {
  2128. ParmVarDecl *NewParam =
  2129. transformFunctionTypeParam(OldParam, Args, MaterializedTypedefs);
  2130. if (!NewParam)
  2131. return QualType();
  2132. ParamTypes.push_back(NewParam->getType());
  2133. Params.push_back(NewParam);
  2134. }
  2135. // -- The return type is the class template specialization designated by
  2136. // the template-name and template arguments corresponding to the
  2137. // template parameters obtained from the class template.
  2138. //
  2139. // We use the injected-class-name type of the primary template instead.
  2140. // This has the convenient property that it is different from any type that
  2141. // the user can write in a deduction-guide (because they cannot enter the
  2142. // context of the template), so implicit deduction guides can never collide
  2143. // with explicit ones.
  2144. QualType ReturnType = DeducedType;
  2145. TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation());
  2146. // Resolving a wording defect, we also inherit the variadicness of the
  2147. // constructor.
  2148. FunctionProtoType::ExtProtoInfo EPI;
  2149. EPI.Variadic = T->isVariadic();
  2150. EPI.HasTrailingReturn = true;
  2151. QualType Result = SemaRef.BuildFunctionType(
  2152. ReturnType, ParamTypes, TL.getBeginLoc(), DeductionGuideName, EPI);
  2153. if (Result.isNull())
  2154. return QualType();
  2155. FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
  2156. NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
  2157. NewTL.setLParenLoc(TL.getLParenLoc());
  2158. NewTL.setRParenLoc(TL.getRParenLoc());
  2159. NewTL.setExceptionSpecRange(SourceRange());
  2160. NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
  2161. for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I)
  2162. NewTL.setParam(I, Params[I]);
  2163. return Result;
  2164. }
  2165. ParmVarDecl *transformFunctionTypeParam(
  2166. ParmVarDecl *OldParam, MultiLevelTemplateArgumentList &Args,
  2167. llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs) {
  2168. TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
  2169. TypeSourceInfo *NewDI;
  2170. if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) {
  2171. // Expand out the one and only element in each inner pack.
  2172. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0);
  2173. NewDI =
  2174. SemaRef.SubstType(PackTL.getPatternLoc(), Args,
  2175. OldParam->getLocation(), OldParam->getDeclName());
  2176. if (!NewDI) return nullptr;
  2177. NewDI =
  2178. SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(),
  2179. PackTL.getTypePtr()->getNumExpansions());
  2180. } else
  2181. NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(),
  2182. OldParam->getDeclName());
  2183. if (!NewDI)
  2184. return nullptr;
  2185. // Extract the type. This (for instance) replaces references to typedef
  2186. // members of the current instantiations with the definitions of those
  2187. // typedefs, avoiding triggering instantiation of the deduced type during
  2188. // deduction.
  2189. NewDI = ExtractTypeForDeductionGuide(SemaRef, MaterializedTypedefs)
  2190. .transform(NewDI);
  2191. // Resolving a wording defect, we also inherit default arguments from the
  2192. // constructor.
  2193. ExprResult NewDefArg;
  2194. if (OldParam->hasDefaultArg()) {
  2195. // We don't care what the value is (we won't use it); just create a
  2196. // placeholder to indicate there is a default argument.
  2197. QualType ParamTy = NewDI->getType();
  2198. NewDefArg = new (SemaRef.Context)
  2199. OpaqueValueExpr(OldParam->getDefaultArg()->getBeginLoc(),
  2200. ParamTy.getNonLValueExprType(SemaRef.Context),
  2201. ParamTy->isLValueReferenceType() ? VK_LValue
  2202. : ParamTy->isRValueReferenceType() ? VK_XValue
  2203. : VK_PRValue);
  2204. }
  2205. ParmVarDecl *NewParam = ParmVarDecl::Create(SemaRef.Context, DC,
  2206. OldParam->getInnerLocStart(),
  2207. OldParam->getLocation(),
  2208. OldParam->getIdentifier(),
  2209. NewDI->getType(),
  2210. NewDI,
  2211. OldParam->getStorageClass(),
  2212. NewDefArg.get());
  2213. NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
  2214. OldParam->getFunctionScopeIndex());
  2215. SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam, NewParam);
  2216. return NewParam;
  2217. }
  2218. FunctionTemplateDecl *buildDeductionGuide(
  2219. TemplateParameterList *TemplateParams, CXXConstructorDecl *Ctor,
  2220. ExplicitSpecifier ES, TypeSourceInfo *TInfo, SourceLocation LocStart,
  2221. SourceLocation Loc, SourceLocation LocEnd,
  2222. llvm::ArrayRef<TypedefNameDecl *> MaterializedTypedefs = {}) {
  2223. DeclarationNameInfo Name(DeductionGuideName, Loc);
  2224. ArrayRef<ParmVarDecl *> Params =
  2225. TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams();
  2226. // Build the implicit deduction guide template.
  2227. auto *Guide =
  2228. CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, ES, Name,
  2229. TInfo->getType(), TInfo, LocEnd, Ctor);
  2230. Guide->setImplicit();
  2231. Guide->setParams(Params);
  2232. for (auto *Param : Params)
  2233. Param->setDeclContext(Guide);
  2234. for (auto *TD : MaterializedTypedefs)
  2235. TD->setDeclContext(Guide);
  2236. auto *GuideTemplate = FunctionTemplateDecl::Create(
  2237. SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
  2238. GuideTemplate->setImplicit();
  2239. Guide->setDescribedFunctionTemplate(GuideTemplate);
  2240. if (isa<CXXRecordDecl>(DC)) {
  2241. Guide->setAccess(AS_public);
  2242. GuideTemplate->setAccess(AS_public);
  2243. }
  2244. DC->addDecl(GuideTemplate);
  2245. return GuideTemplate;
  2246. }
  2247. };
  2248. }
  2249. void Sema::DeclareImplicitDeductionGuides(TemplateDecl *Template,
  2250. SourceLocation Loc) {
  2251. if (CXXRecordDecl *DefRecord =
  2252. cast<CXXRecordDecl>(Template->getTemplatedDecl())->getDefinition()) {
  2253. TemplateDecl *DescribedTemplate = DefRecord->getDescribedClassTemplate();
  2254. Template = DescribedTemplate ? DescribedTemplate : Template;
  2255. }
  2256. DeclContext *DC = Template->getDeclContext();
  2257. if (DC->isDependentContext())
  2258. return;
  2259. ConvertConstructorToDeductionGuideTransform Transform(
  2260. *this, cast<ClassTemplateDecl>(Template));
  2261. if (!isCompleteType(Loc, Transform.DeducedType))
  2262. return;
  2263. // Check whether we've already declared deduction guides for this template.
  2264. // FIXME: Consider storing a flag on the template to indicate this.
  2265. auto Existing = DC->lookup(Transform.DeductionGuideName);
  2266. for (auto *D : Existing)
  2267. if (D->isImplicit())
  2268. return;
  2269. // In case we were expanding a pack when we attempted to declare deduction
  2270. // guides, turn off pack expansion for everything we're about to do.
  2271. ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
  2272. // Create a template instantiation record to track the "instantiation" of
  2273. // constructors into deduction guides.
  2274. // FIXME: Add a kind for this to give more meaningful diagnostics. But can
  2275. // this substitution process actually fail?
  2276. InstantiatingTemplate BuildingDeductionGuides(*this, Loc, Template);
  2277. if (BuildingDeductionGuides.isInvalid())
  2278. return;
  2279. // Convert declared constructors into deduction guide templates.
  2280. // FIXME: Skip constructors for which deduction must necessarily fail (those
  2281. // for which some class template parameter without a default argument never
  2282. // appears in a deduced context).
  2283. bool AddedAny = false;
  2284. for (NamedDecl *D : LookupConstructors(Transform.Primary)) {
  2285. D = D->getUnderlyingDecl();
  2286. if (D->isInvalidDecl() || D->isImplicit())
  2287. continue;
  2288. D = cast<NamedDecl>(D->getCanonicalDecl());
  2289. auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
  2290. auto *CD =
  2291. dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D);
  2292. // Class-scope explicit specializations (MS extension) do not result in
  2293. // deduction guides.
  2294. if (!CD || (!FTD && CD->isFunctionTemplateSpecialization()))
  2295. continue;
  2296. // Cannot make a deduction guide when unparsed arguments are present.
  2297. if (llvm::any_of(CD->parameters(), [](ParmVarDecl *P) {
  2298. return !P || P->hasUnparsedDefaultArg();
  2299. }))
  2300. continue;
  2301. Transform.transformConstructor(FTD, CD);
  2302. AddedAny = true;
  2303. }
  2304. // C++17 [over.match.class.deduct]
  2305. // -- If C is not defined or does not declare any constructors, an
  2306. // additional function template derived as above from a hypothetical
  2307. // constructor C().
  2308. if (!AddedAny)
  2309. Transform.buildSimpleDeductionGuide(std::nullopt);
  2310. // -- An additional function template derived as above from a hypothetical
  2311. // constructor C(C), called the copy deduction candidate.
  2312. cast<CXXDeductionGuideDecl>(
  2313. cast<FunctionTemplateDecl>(
  2314. Transform.buildSimpleDeductionGuide(Transform.DeducedType))
  2315. ->getTemplatedDecl())
  2316. ->setIsCopyDeductionCandidate();
  2317. }
  2318. /// Diagnose the presence of a default template argument on a
  2319. /// template parameter, which is ill-formed in certain contexts.
  2320. ///
  2321. /// \returns true if the default template argument should be dropped.
  2322. static bool DiagnoseDefaultTemplateArgument(Sema &S,
  2323. Sema::TemplateParamListContext TPC,
  2324. SourceLocation ParamLoc,
  2325. SourceRange DefArgRange) {
  2326. switch (TPC) {
  2327. case Sema::TPC_ClassTemplate:
  2328. case Sema::TPC_VarTemplate:
  2329. case Sema::TPC_TypeAliasTemplate:
  2330. return false;
  2331. case Sema::TPC_FunctionTemplate:
  2332. case Sema::TPC_FriendFunctionTemplateDefinition:
  2333. // C++ [temp.param]p9:
  2334. // A default template-argument shall not be specified in a
  2335. // function template declaration or a function template
  2336. // definition [...]
  2337. // If a friend function template declaration specifies a default
  2338. // template-argument, that declaration shall be a definition and shall be
  2339. // the only declaration of the function template in the translation unit.
  2340. // (C++98/03 doesn't have this wording; see DR226).
  2341. S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
  2342. diag::warn_cxx98_compat_template_parameter_default_in_function_template
  2343. : diag::ext_template_parameter_default_in_function_template)
  2344. << DefArgRange;
  2345. return false;
  2346. case Sema::TPC_ClassTemplateMember:
  2347. // C++0x [temp.param]p9:
  2348. // A default template-argument shall not be specified in the
  2349. // template-parameter-lists of the definition of a member of a
  2350. // class template that appears outside of the member's class.
  2351. S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
  2352. << DefArgRange;
  2353. return true;
  2354. case Sema::TPC_FriendClassTemplate:
  2355. case Sema::TPC_FriendFunctionTemplate:
  2356. // C++ [temp.param]p9:
  2357. // A default template-argument shall not be specified in a
  2358. // friend template declaration.
  2359. S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
  2360. << DefArgRange;
  2361. return true;
  2362. // FIXME: C++0x [temp.param]p9 allows default template-arguments
  2363. // for friend function templates if there is only a single
  2364. // declaration (and it is a definition). Strange!
  2365. }
  2366. llvm_unreachable("Invalid TemplateParamListContext!");
  2367. }
  2368. /// Check for unexpanded parameter packs within the template parameters
  2369. /// of a template template parameter, recursively.
  2370. static bool DiagnoseUnexpandedParameterPacks(Sema &S,
  2371. TemplateTemplateParmDecl *TTP) {
  2372. // A template template parameter which is a parameter pack is also a pack
  2373. // expansion.
  2374. if (TTP->isParameterPack())
  2375. return false;
  2376. TemplateParameterList *Params = TTP->getTemplateParameters();
  2377. for (unsigned I = 0, N = Params->size(); I != N; ++I) {
  2378. NamedDecl *P = Params->getParam(I);
  2379. if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(P)) {
  2380. if (!TTP->isParameterPack())
  2381. if (const TypeConstraint *TC = TTP->getTypeConstraint())
  2382. if (TC->hasExplicitTemplateArgs())
  2383. for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
  2384. if (S.DiagnoseUnexpandedParameterPack(ArgLoc,
  2385. Sema::UPPC_TypeConstraint))
  2386. return true;
  2387. continue;
  2388. }
  2389. if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
  2390. if (!NTTP->isParameterPack() &&
  2391. S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
  2392. NTTP->getTypeSourceInfo(),
  2393. Sema::UPPC_NonTypeTemplateParameterType))
  2394. return true;
  2395. continue;
  2396. }
  2397. if (TemplateTemplateParmDecl *InnerTTP
  2398. = dyn_cast<TemplateTemplateParmDecl>(P))
  2399. if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
  2400. return true;
  2401. }
  2402. return false;
  2403. }
  2404. /// Checks the validity of a template parameter list, possibly
  2405. /// considering the template parameter list from a previous
  2406. /// declaration.
  2407. ///
  2408. /// If an "old" template parameter list is provided, it must be
  2409. /// equivalent (per TemplateParameterListsAreEqual) to the "new"
  2410. /// template parameter list.
  2411. ///
  2412. /// \param NewParams Template parameter list for a new template
  2413. /// declaration. This template parameter list will be updated with any
  2414. /// default arguments that are carried through from the previous
  2415. /// template parameter list.
  2416. ///
  2417. /// \param OldParams If provided, template parameter list from a
  2418. /// previous declaration of the same template. Default template
  2419. /// arguments will be merged from the old template parameter list to
  2420. /// the new template parameter list.
  2421. ///
  2422. /// \param TPC Describes the context in which we are checking the given
  2423. /// template parameter list.
  2424. ///
  2425. /// \param SkipBody If we might have already made a prior merged definition
  2426. /// of this template visible, the corresponding body-skipping information.
  2427. /// Default argument redefinition is not an error when skipping such a body,
  2428. /// because (under the ODR) we can assume the default arguments are the same
  2429. /// as the prior merged definition.
  2430. ///
  2431. /// \returns true if an error occurred, false otherwise.
  2432. bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
  2433. TemplateParameterList *OldParams,
  2434. TemplateParamListContext TPC,
  2435. SkipBodyInfo *SkipBody) {
  2436. bool Invalid = false;
  2437. // C++ [temp.param]p10:
  2438. // The set of default template-arguments available for use with a
  2439. // template declaration or definition is obtained by merging the
  2440. // default arguments from the definition (if in scope) and all
  2441. // declarations in scope in the same way default function
  2442. // arguments are (8.3.6).
  2443. bool SawDefaultArgument = false;
  2444. SourceLocation PreviousDefaultArgLoc;
  2445. // Dummy initialization to avoid warnings.
  2446. TemplateParameterList::iterator OldParam = NewParams->end();
  2447. if (OldParams)
  2448. OldParam = OldParams->begin();
  2449. bool RemoveDefaultArguments = false;
  2450. for (TemplateParameterList::iterator NewParam = NewParams->begin(),
  2451. NewParamEnd = NewParams->end();
  2452. NewParam != NewParamEnd; ++NewParam) {
  2453. // Whether we've seen a duplicate default argument in the same translation
  2454. // unit.
  2455. bool RedundantDefaultArg = false;
  2456. // Whether we've found inconsis inconsitent default arguments in different
  2457. // translation unit.
  2458. bool InconsistentDefaultArg = false;
  2459. // The name of the module which contains the inconsistent default argument.
  2460. std::string PrevModuleName;
  2461. SourceLocation OldDefaultLoc;
  2462. SourceLocation NewDefaultLoc;
  2463. // Variable used to diagnose missing default arguments
  2464. bool MissingDefaultArg = false;
  2465. // Variable used to diagnose non-final parameter packs
  2466. bool SawParameterPack = false;
  2467. if (TemplateTypeParmDecl *NewTypeParm
  2468. = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
  2469. // Check the presence of a default argument here.
  2470. if (NewTypeParm->hasDefaultArgument() &&
  2471. DiagnoseDefaultTemplateArgument(*this, TPC,
  2472. NewTypeParm->getLocation(),
  2473. NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
  2474. .getSourceRange()))
  2475. NewTypeParm->removeDefaultArgument();
  2476. // Merge default arguments for template type parameters.
  2477. TemplateTypeParmDecl *OldTypeParm
  2478. = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
  2479. if (NewTypeParm->isParameterPack()) {
  2480. assert(!NewTypeParm->hasDefaultArgument() &&
  2481. "Parameter packs can't have a default argument!");
  2482. SawParameterPack = true;
  2483. } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
  2484. NewTypeParm->hasDefaultArgument() &&
  2485. (!SkipBody || !SkipBody->ShouldSkip)) {
  2486. OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
  2487. NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
  2488. SawDefaultArgument = true;
  2489. if (!OldTypeParm->getOwningModule() ||
  2490. isModuleUnitOfCurrentTU(OldTypeParm->getOwningModule()))
  2491. RedundantDefaultArg = true;
  2492. else if (!getASTContext().isSameDefaultTemplateArgument(OldTypeParm,
  2493. NewTypeParm)) {
  2494. InconsistentDefaultArg = true;
  2495. PrevModuleName =
  2496. OldTypeParm->getImportedOwningModule()->getFullModuleName();
  2497. }
  2498. PreviousDefaultArgLoc = NewDefaultLoc;
  2499. } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
  2500. // Merge the default argument from the old declaration to the
  2501. // new declaration.
  2502. NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
  2503. PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
  2504. } else if (NewTypeParm->hasDefaultArgument()) {
  2505. SawDefaultArgument = true;
  2506. PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
  2507. } else if (SawDefaultArgument)
  2508. MissingDefaultArg = true;
  2509. } else if (NonTypeTemplateParmDecl *NewNonTypeParm
  2510. = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
  2511. // Check for unexpanded parameter packs.
  2512. if (!NewNonTypeParm->isParameterPack() &&
  2513. DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
  2514. NewNonTypeParm->getTypeSourceInfo(),
  2515. UPPC_NonTypeTemplateParameterType)) {
  2516. Invalid = true;
  2517. continue;
  2518. }
  2519. // Check the presence of a default argument here.
  2520. if (NewNonTypeParm->hasDefaultArgument() &&
  2521. DiagnoseDefaultTemplateArgument(*this, TPC,
  2522. NewNonTypeParm->getLocation(),
  2523. NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
  2524. NewNonTypeParm->removeDefaultArgument();
  2525. }
  2526. // Merge default arguments for non-type template parameters
  2527. NonTypeTemplateParmDecl *OldNonTypeParm
  2528. = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
  2529. if (NewNonTypeParm->isParameterPack()) {
  2530. assert(!NewNonTypeParm->hasDefaultArgument() &&
  2531. "Parameter packs can't have a default argument!");
  2532. if (!NewNonTypeParm->isPackExpansion())
  2533. SawParameterPack = true;
  2534. } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
  2535. NewNonTypeParm->hasDefaultArgument() &&
  2536. (!SkipBody || !SkipBody->ShouldSkip)) {
  2537. OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
  2538. NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
  2539. SawDefaultArgument = true;
  2540. if (!OldNonTypeParm->getOwningModule() ||
  2541. isModuleUnitOfCurrentTU(OldNonTypeParm->getOwningModule()))
  2542. RedundantDefaultArg = true;
  2543. else if (!getASTContext().isSameDefaultTemplateArgument(
  2544. OldNonTypeParm, NewNonTypeParm)) {
  2545. InconsistentDefaultArg = true;
  2546. PrevModuleName =
  2547. OldNonTypeParm->getImportedOwningModule()->getFullModuleName();
  2548. }
  2549. PreviousDefaultArgLoc = NewDefaultLoc;
  2550. } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
  2551. // Merge the default argument from the old declaration to the
  2552. // new declaration.
  2553. NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
  2554. PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
  2555. } else if (NewNonTypeParm->hasDefaultArgument()) {
  2556. SawDefaultArgument = true;
  2557. PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
  2558. } else if (SawDefaultArgument)
  2559. MissingDefaultArg = true;
  2560. } else {
  2561. TemplateTemplateParmDecl *NewTemplateParm
  2562. = cast<TemplateTemplateParmDecl>(*NewParam);
  2563. // Check for unexpanded parameter packs, recursively.
  2564. if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
  2565. Invalid = true;
  2566. continue;
  2567. }
  2568. // Check the presence of a default argument here.
  2569. if (NewTemplateParm->hasDefaultArgument() &&
  2570. DiagnoseDefaultTemplateArgument(*this, TPC,
  2571. NewTemplateParm->getLocation(),
  2572. NewTemplateParm->getDefaultArgument().getSourceRange()))
  2573. NewTemplateParm->removeDefaultArgument();
  2574. // Merge default arguments for template template parameters
  2575. TemplateTemplateParmDecl *OldTemplateParm
  2576. = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
  2577. if (NewTemplateParm->isParameterPack()) {
  2578. assert(!NewTemplateParm->hasDefaultArgument() &&
  2579. "Parameter packs can't have a default argument!");
  2580. if (!NewTemplateParm->isPackExpansion())
  2581. SawParameterPack = true;
  2582. } else if (OldTemplateParm &&
  2583. hasVisibleDefaultArgument(OldTemplateParm) &&
  2584. NewTemplateParm->hasDefaultArgument() &&
  2585. (!SkipBody || !SkipBody->ShouldSkip)) {
  2586. OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
  2587. NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
  2588. SawDefaultArgument = true;
  2589. if (!OldTemplateParm->getOwningModule() ||
  2590. isModuleUnitOfCurrentTU(OldTemplateParm->getOwningModule()))
  2591. RedundantDefaultArg = true;
  2592. else if (!getASTContext().isSameDefaultTemplateArgument(
  2593. OldTemplateParm, NewTemplateParm)) {
  2594. InconsistentDefaultArg = true;
  2595. PrevModuleName =
  2596. OldTemplateParm->getImportedOwningModule()->getFullModuleName();
  2597. }
  2598. PreviousDefaultArgLoc = NewDefaultLoc;
  2599. } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
  2600. // Merge the default argument from the old declaration to the
  2601. // new declaration.
  2602. NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
  2603. PreviousDefaultArgLoc
  2604. = OldTemplateParm->getDefaultArgument().getLocation();
  2605. } else if (NewTemplateParm->hasDefaultArgument()) {
  2606. SawDefaultArgument = true;
  2607. PreviousDefaultArgLoc
  2608. = NewTemplateParm->getDefaultArgument().getLocation();
  2609. } else if (SawDefaultArgument)
  2610. MissingDefaultArg = true;
  2611. }
  2612. // C++11 [temp.param]p11:
  2613. // If a template parameter of a primary class template or alias template
  2614. // is a template parameter pack, it shall be the last template parameter.
  2615. if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
  2616. (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
  2617. TPC == TPC_TypeAliasTemplate)) {
  2618. Diag((*NewParam)->getLocation(),
  2619. diag::err_template_param_pack_must_be_last_template_parameter);
  2620. Invalid = true;
  2621. }
  2622. // [basic.def.odr]/13:
  2623. // There can be more than one definition of a
  2624. // ...
  2625. // default template argument
  2626. // ...
  2627. // in a program provided that each definition appears in a different
  2628. // translation unit and the definitions satisfy the [same-meaning
  2629. // criteria of the ODR].
  2630. //
  2631. // Simply, the design of modules allows the definition of template default
  2632. // argument to be repeated across translation unit. Note that the ODR is
  2633. // checked elsewhere. But it is still not allowed to repeat template default
  2634. // argument in the same translation unit.
  2635. if (RedundantDefaultArg) {
  2636. Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
  2637. Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
  2638. Invalid = true;
  2639. } else if (InconsistentDefaultArg) {
  2640. // We could only diagnose about the case that the OldParam is imported.
  2641. // The case NewParam is imported should be handled in ASTReader.
  2642. Diag(NewDefaultLoc,
  2643. diag::err_template_param_default_arg_inconsistent_redefinition);
  2644. Diag(OldDefaultLoc,
  2645. diag::note_template_param_prev_default_arg_in_other_module)
  2646. << PrevModuleName;
  2647. Invalid = true;
  2648. } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
  2649. // C++ [temp.param]p11:
  2650. // If a template-parameter of a class template has a default
  2651. // template-argument, each subsequent template-parameter shall either
  2652. // have a default template-argument supplied or be a template parameter
  2653. // pack.
  2654. Diag((*NewParam)->getLocation(),
  2655. diag::err_template_param_default_arg_missing);
  2656. Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
  2657. Invalid = true;
  2658. RemoveDefaultArguments = true;
  2659. }
  2660. // If we have an old template parameter list that we're merging
  2661. // in, move on to the next parameter.
  2662. if (OldParams)
  2663. ++OldParam;
  2664. }
  2665. // We were missing some default arguments at the end of the list, so remove
  2666. // all of the default arguments.
  2667. if (RemoveDefaultArguments) {
  2668. for (TemplateParameterList::iterator NewParam = NewParams->begin(),
  2669. NewParamEnd = NewParams->end();
  2670. NewParam != NewParamEnd; ++NewParam) {
  2671. if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
  2672. TTP->removeDefaultArgument();
  2673. else if (NonTypeTemplateParmDecl *NTTP
  2674. = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
  2675. NTTP->removeDefaultArgument();
  2676. else
  2677. cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
  2678. }
  2679. }
  2680. return Invalid;
  2681. }
  2682. namespace {
  2683. /// A class which looks for a use of a certain level of template
  2684. /// parameter.
  2685. struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
  2686. typedef RecursiveASTVisitor<DependencyChecker> super;
  2687. unsigned Depth;
  2688. // Whether we're looking for a use of a template parameter that makes the
  2689. // overall construct type-dependent / a dependent type. This is strictly
  2690. // best-effort for now; we may fail to match at all for a dependent type
  2691. // in some cases if this is set.
  2692. bool IgnoreNonTypeDependent;
  2693. bool Match;
  2694. SourceLocation MatchLoc;
  2695. DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
  2696. : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
  2697. Match(false) {}
  2698. DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
  2699. : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
  2700. NamedDecl *ND = Params->getParam(0);
  2701. if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
  2702. Depth = PD->getDepth();
  2703. } else if (NonTypeTemplateParmDecl *PD =
  2704. dyn_cast<NonTypeTemplateParmDecl>(ND)) {
  2705. Depth = PD->getDepth();
  2706. } else {
  2707. Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
  2708. }
  2709. }
  2710. bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
  2711. if (ParmDepth >= Depth) {
  2712. Match = true;
  2713. MatchLoc = Loc;
  2714. return true;
  2715. }
  2716. return false;
  2717. }
  2718. bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
  2719. // Prune out non-type-dependent expressions if requested. This can
  2720. // sometimes result in us failing to find a template parameter reference
  2721. // (if a value-dependent expression creates a dependent type), but this
  2722. // mode is best-effort only.
  2723. if (auto *E = dyn_cast_or_null<Expr>(S))
  2724. if (IgnoreNonTypeDependent && !E->isTypeDependent())
  2725. return true;
  2726. return super::TraverseStmt(S, Q);
  2727. }
  2728. bool TraverseTypeLoc(TypeLoc TL) {
  2729. if (IgnoreNonTypeDependent && !TL.isNull() &&
  2730. !TL.getType()->isDependentType())
  2731. return true;
  2732. return super::TraverseTypeLoc(TL);
  2733. }
  2734. bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
  2735. return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
  2736. }
  2737. bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
  2738. // For a best-effort search, keep looking until we find a location.
  2739. return IgnoreNonTypeDependent || !Matches(T->getDepth());
  2740. }
  2741. bool TraverseTemplateName(TemplateName N) {
  2742. if (TemplateTemplateParmDecl *PD =
  2743. dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
  2744. if (Matches(PD->getDepth()))
  2745. return false;
  2746. return super::TraverseTemplateName(N);
  2747. }
  2748. bool VisitDeclRefExpr(DeclRefExpr *E) {
  2749. if (NonTypeTemplateParmDecl *PD =
  2750. dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
  2751. if (Matches(PD->getDepth(), E->getExprLoc()))
  2752. return false;
  2753. return super::VisitDeclRefExpr(E);
  2754. }
  2755. bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
  2756. return TraverseType(T->getReplacementType());
  2757. }
  2758. bool
  2759. VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
  2760. return TraverseTemplateArgument(T->getArgumentPack());
  2761. }
  2762. bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
  2763. return TraverseType(T->getInjectedSpecializationType());
  2764. }
  2765. };
  2766. } // end anonymous namespace
  2767. /// Determines whether a given type depends on the given parameter
  2768. /// list.
  2769. static bool
  2770. DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
  2771. if (!Params->size())
  2772. return false;
  2773. DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
  2774. Checker.TraverseType(T);
  2775. return Checker.Match;
  2776. }
  2777. // Find the source range corresponding to the named type in the given
  2778. // nested-name-specifier, if any.
  2779. static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
  2780. QualType T,
  2781. const CXXScopeSpec &SS) {
  2782. NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
  2783. while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
  2784. if (const Type *CurType = NNS->getAsType()) {
  2785. if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
  2786. return NNSLoc.getTypeLoc().getSourceRange();
  2787. } else
  2788. break;
  2789. NNSLoc = NNSLoc.getPrefix();
  2790. }
  2791. return SourceRange();
  2792. }
  2793. /// Match the given template parameter lists to the given scope
  2794. /// specifier, returning the template parameter list that applies to the
  2795. /// name.
  2796. ///
  2797. /// \param DeclStartLoc the start of the declaration that has a scope
  2798. /// specifier or a template parameter list.
  2799. ///
  2800. /// \param DeclLoc The location of the declaration itself.
  2801. ///
  2802. /// \param SS the scope specifier that will be matched to the given template
  2803. /// parameter lists. This scope specifier precedes a qualified name that is
  2804. /// being declared.
  2805. ///
  2806. /// \param TemplateId The template-id following the scope specifier, if there
  2807. /// is one. Used to check for a missing 'template<>'.
  2808. ///
  2809. /// \param ParamLists the template parameter lists, from the outermost to the
  2810. /// innermost template parameter lists.
  2811. ///
  2812. /// \param IsFriend Whether to apply the slightly different rules for
  2813. /// matching template parameters to scope specifiers in friend
  2814. /// declarations.
  2815. ///
  2816. /// \param IsMemberSpecialization will be set true if the scope specifier
  2817. /// denotes a fully-specialized type, and therefore this is a declaration of
  2818. /// a member specialization.
  2819. ///
  2820. /// \returns the template parameter list, if any, that corresponds to the
  2821. /// name that is preceded by the scope specifier @p SS. This template
  2822. /// parameter list may have template parameters (if we're declaring a
  2823. /// template) or may have no template parameters (if we're declaring a
  2824. /// template specialization), or may be NULL (if what we're declaring isn't
  2825. /// itself a template).
  2826. TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
  2827. SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
  2828. TemplateIdAnnotation *TemplateId,
  2829. ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
  2830. bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
  2831. IsMemberSpecialization = false;
  2832. Invalid = false;
  2833. // The sequence of nested types to which we will match up the template
  2834. // parameter lists. We first build this list by starting with the type named
  2835. // by the nested-name-specifier and walking out until we run out of types.
  2836. SmallVector<QualType, 4> NestedTypes;
  2837. QualType T;
  2838. if (SS.getScopeRep()) {
  2839. if (CXXRecordDecl *Record
  2840. = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
  2841. T = Context.getTypeDeclType(Record);
  2842. else
  2843. T = QualType(SS.getScopeRep()->getAsType(), 0);
  2844. }
  2845. // If we found an explicit specialization that prevents us from needing
  2846. // 'template<>' headers, this will be set to the location of that
  2847. // explicit specialization.
  2848. SourceLocation ExplicitSpecLoc;
  2849. while (!T.isNull()) {
  2850. NestedTypes.push_back(T);
  2851. // Retrieve the parent of a record type.
  2852. if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
  2853. // If this type is an explicit specialization, we're done.
  2854. if (ClassTemplateSpecializationDecl *Spec
  2855. = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
  2856. if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
  2857. Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
  2858. ExplicitSpecLoc = Spec->getLocation();
  2859. break;
  2860. }
  2861. } else if (Record->getTemplateSpecializationKind()
  2862. == TSK_ExplicitSpecialization) {
  2863. ExplicitSpecLoc = Record->getLocation();
  2864. break;
  2865. }
  2866. if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
  2867. T = Context.getTypeDeclType(Parent);
  2868. else
  2869. T = QualType();
  2870. continue;
  2871. }
  2872. if (const TemplateSpecializationType *TST
  2873. = T->getAs<TemplateSpecializationType>()) {
  2874. if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
  2875. if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
  2876. T = Context.getTypeDeclType(Parent);
  2877. else
  2878. T = QualType();
  2879. continue;
  2880. }
  2881. }
  2882. // Look one step prior in a dependent template specialization type.
  2883. if (const DependentTemplateSpecializationType *DependentTST
  2884. = T->getAs<DependentTemplateSpecializationType>()) {
  2885. if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
  2886. T = QualType(NNS->getAsType(), 0);
  2887. else
  2888. T = QualType();
  2889. continue;
  2890. }
  2891. // Look one step prior in a dependent name type.
  2892. if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
  2893. if (NestedNameSpecifier *NNS = DependentName->getQualifier())
  2894. T = QualType(NNS->getAsType(), 0);
  2895. else
  2896. T = QualType();
  2897. continue;
  2898. }
  2899. // Retrieve the parent of an enumeration type.
  2900. if (const EnumType *EnumT = T->getAs<EnumType>()) {
  2901. // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
  2902. // check here.
  2903. EnumDecl *Enum = EnumT->getDecl();
  2904. // Get to the parent type.
  2905. if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
  2906. T = Context.getTypeDeclType(Parent);
  2907. else
  2908. T = QualType();
  2909. continue;
  2910. }
  2911. T = QualType();
  2912. }
  2913. // Reverse the nested types list, since we want to traverse from the outermost
  2914. // to the innermost while checking template-parameter-lists.
  2915. std::reverse(NestedTypes.begin(), NestedTypes.end());
  2916. // C++0x [temp.expl.spec]p17:
  2917. // A member or a member template may be nested within many
  2918. // enclosing class templates. In an explicit specialization for
  2919. // such a member, the member declaration shall be preceded by a
  2920. // template<> for each enclosing class template that is
  2921. // explicitly specialized.
  2922. bool SawNonEmptyTemplateParameterList = false;
  2923. auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
  2924. if (SawNonEmptyTemplateParameterList) {
  2925. if (!SuppressDiagnostic)
  2926. Diag(DeclLoc, diag::err_specialize_member_of_template)
  2927. << !Recovery << Range;
  2928. Invalid = true;
  2929. IsMemberSpecialization = false;
  2930. return true;
  2931. }
  2932. return false;
  2933. };
  2934. auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
  2935. // Check that we can have an explicit specialization here.
  2936. if (CheckExplicitSpecialization(Range, true))
  2937. return true;
  2938. // We don't have a template header, but we should.
  2939. SourceLocation ExpectedTemplateLoc;
  2940. if (!ParamLists.empty())
  2941. ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
  2942. else
  2943. ExpectedTemplateLoc = DeclStartLoc;
  2944. if (!SuppressDiagnostic)
  2945. Diag(DeclLoc, diag::err_template_spec_needs_header)
  2946. << Range
  2947. << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
  2948. return false;
  2949. };
  2950. unsigned ParamIdx = 0;
  2951. for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
  2952. ++TypeIdx) {
  2953. T = NestedTypes[TypeIdx];
  2954. // Whether we expect a 'template<>' header.
  2955. bool NeedEmptyTemplateHeader = false;
  2956. // Whether we expect a template header with parameters.
  2957. bool NeedNonemptyTemplateHeader = false;
  2958. // For a dependent type, the set of template parameters that we
  2959. // expect to see.
  2960. TemplateParameterList *ExpectedTemplateParams = nullptr;
  2961. // C++0x [temp.expl.spec]p15:
  2962. // A member or a member template may be nested within many enclosing
  2963. // class templates. In an explicit specialization for such a member, the
  2964. // member declaration shall be preceded by a template<> for each
  2965. // enclosing class template that is explicitly specialized.
  2966. if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
  2967. if (ClassTemplatePartialSpecializationDecl *Partial
  2968. = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
  2969. ExpectedTemplateParams = Partial->getTemplateParameters();
  2970. NeedNonemptyTemplateHeader = true;
  2971. } else if (Record->isDependentType()) {
  2972. if (Record->getDescribedClassTemplate()) {
  2973. ExpectedTemplateParams = Record->getDescribedClassTemplate()
  2974. ->getTemplateParameters();
  2975. NeedNonemptyTemplateHeader = true;
  2976. }
  2977. } else if (ClassTemplateSpecializationDecl *Spec
  2978. = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
  2979. // C++0x [temp.expl.spec]p4:
  2980. // Members of an explicitly specialized class template are defined
  2981. // in the same manner as members of normal classes, and not using
  2982. // the template<> syntax.
  2983. if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
  2984. NeedEmptyTemplateHeader = true;
  2985. else
  2986. continue;
  2987. } else if (Record->getTemplateSpecializationKind()) {
  2988. if (Record->getTemplateSpecializationKind()
  2989. != TSK_ExplicitSpecialization &&
  2990. TypeIdx == NumTypes - 1)
  2991. IsMemberSpecialization = true;
  2992. continue;
  2993. }
  2994. } else if (const TemplateSpecializationType *TST
  2995. = T->getAs<TemplateSpecializationType>()) {
  2996. if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
  2997. ExpectedTemplateParams = Template->getTemplateParameters();
  2998. NeedNonemptyTemplateHeader = true;
  2999. }
  3000. } else if (T->getAs<DependentTemplateSpecializationType>()) {
  3001. // FIXME: We actually could/should check the template arguments here
  3002. // against the corresponding template parameter list.
  3003. NeedNonemptyTemplateHeader = false;
  3004. }
  3005. // C++ [temp.expl.spec]p16:
  3006. // In an explicit specialization declaration for a member of a class
  3007. // template or a member template that ap- pears in namespace scope, the
  3008. // member template and some of its enclosing class templates may remain
  3009. // unspecialized, except that the declaration shall not explicitly
  3010. // specialize a class member template if its en- closing class templates
  3011. // are not explicitly specialized as well.
  3012. if (ParamIdx < ParamLists.size()) {
  3013. if (ParamLists[ParamIdx]->size() == 0) {
  3014. if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
  3015. false))
  3016. return nullptr;
  3017. } else
  3018. SawNonEmptyTemplateParameterList = true;
  3019. }
  3020. if (NeedEmptyTemplateHeader) {
  3021. // If we're on the last of the types, and we need a 'template<>' header
  3022. // here, then it's a member specialization.
  3023. if (TypeIdx == NumTypes - 1)
  3024. IsMemberSpecialization = true;
  3025. if (ParamIdx < ParamLists.size()) {
  3026. if (ParamLists[ParamIdx]->size() > 0) {
  3027. // The header has template parameters when it shouldn't. Complain.
  3028. if (!SuppressDiagnostic)
  3029. Diag(ParamLists[ParamIdx]->getTemplateLoc(),
  3030. diag::err_template_param_list_matches_nontemplate)
  3031. << T
  3032. << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
  3033. ParamLists[ParamIdx]->getRAngleLoc())
  3034. << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
  3035. Invalid = true;
  3036. return nullptr;
  3037. }
  3038. // Consume this template header.
  3039. ++ParamIdx;
  3040. continue;
  3041. }
  3042. if (!IsFriend)
  3043. if (DiagnoseMissingExplicitSpecialization(
  3044. getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
  3045. return nullptr;
  3046. continue;
  3047. }
  3048. if (NeedNonemptyTemplateHeader) {
  3049. // In friend declarations we can have template-ids which don't
  3050. // depend on the corresponding template parameter lists. But
  3051. // assume that empty parameter lists are supposed to match this
  3052. // template-id.
  3053. if (IsFriend && T->isDependentType()) {
  3054. if (ParamIdx < ParamLists.size() &&
  3055. DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
  3056. ExpectedTemplateParams = nullptr;
  3057. else
  3058. continue;
  3059. }
  3060. if (ParamIdx < ParamLists.size()) {
  3061. // Check the template parameter list, if we can.
  3062. if (ExpectedTemplateParams &&
  3063. !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
  3064. ExpectedTemplateParams,
  3065. !SuppressDiagnostic, TPL_TemplateMatch))
  3066. Invalid = true;
  3067. if (!Invalid &&
  3068. CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
  3069. TPC_ClassTemplateMember))
  3070. Invalid = true;
  3071. ++ParamIdx;
  3072. continue;
  3073. }
  3074. if (!SuppressDiagnostic)
  3075. Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
  3076. << T
  3077. << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
  3078. Invalid = true;
  3079. continue;
  3080. }
  3081. }
  3082. // If there were at least as many template-ids as there were template
  3083. // parameter lists, then there are no template parameter lists remaining for
  3084. // the declaration itself.
  3085. if (ParamIdx >= ParamLists.size()) {
  3086. if (TemplateId && !IsFriend) {
  3087. // We don't have a template header for the declaration itself, but we
  3088. // should.
  3089. DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
  3090. TemplateId->RAngleLoc));
  3091. // Fabricate an empty template parameter list for the invented header.
  3092. return TemplateParameterList::Create(Context, SourceLocation(),
  3093. SourceLocation(), std::nullopt,
  3094. SourceLocation(), nullptr);
  3095. }
  3096. return nullptr;
  3097. }
  3098. // If there were too many template parameter lists, complain about that now.
  3099. if (ParamIdx < ParamLists.size() - 1) {
  3100. bool HasAnyExplicitSpecHeader = false;
  3101. bool AllExplicitSpecHeaders = true;
  3102. for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
  3103. if (ParamLists[I]->size() == 0)
  3104. HasAnyExplicitSpecHeader = true;
  3105. else
  3106. AllExplicitSpecHeaders = false;
  3107. }
  3108. if (!SuppressDiagnostic)
  3109. Diag(ParamLists[ParamIdx]->getTemplateLoc(),
  3110. AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
  3111. : diag::err_template_spec_extra_headers)
  3112. << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
  3113. ParamLists[ParamLists.size() - 2]->getRAngleLoc());
  3114. // If there was a specialization somewhere, such that 'template<>' is
  3115. // not required, and there were any 'template<>' headers, note where the
  3116. // specialization occurred.
  3117. if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
  3118. !SuppressDiagnostic)
  3119. Diag(ExplicitSpecLoc,
  3120. diag::note_explicit_template_spec_does_not_need_header)
  3121. << NestedTypes.back();
  3122. // We have a template parameter list with no corresponding scope, which
  3123. // means that the resulting template declaration can't be instantiated
  3124. // properly (we'll end up with dependent nodes when we shouldn't).
  3125. if (!AllExplicitSpecHeaders)
  3126. Invalid = true;
  3127. }
  3128. // C++ [temp.expl.spec]p16:
  3129. // In an explicit specialization declaration for a member of a class
  3130. // template or a member template that ap- pears in namespace scope, the
  3131. // member template and some of its enclosing class templates may remain
  3132. // unspecialized, except that the declaration shall not explicitly
  3133. // specialize a class member template if its en- closing class templates
  3134. // are not explicitly specialized as well.
  3135. if (ParamLists.back()->size() == 0 &&
  3136. CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
  3137. false))
  3138. return nullptr;
  3139. // Return the last template parameter list, which corresponds to the
  3140. // entity being declared.
  3141. return ParamLists.back();
  3142. }
  3143. void Sema::NoteAllFoundTemplates(TemplateName Name) {
  3144. if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
  3145. Diag(Template->getLocation(), diag::note_template_declared_here)
  3146. << (isa<FunctionTemplateDecl>(Template)
  3147. ? 0
  3148. : isa<ClassTemplateDecl>(Template)
  3149. ? 1
  3150. : isa<VarTemplateDecl>(Template)
  3151. ? 2
  3152. : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
  3153. << Template->getDeclName();
  3154. return;
  3155. }
  3156. if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
  3157. for (OverloadedTemplateStorage::iterator I = OST->begin(),
  3158. IEnd = OST->end();
  3159. I != IEnd; ++I)
  3160. Diag((*I)->getLocation(), diag::note_template_declared_here)
  3161. << 0 << (*I)->getDeclName();
  3162. return;
  3163. }
  3164. }
  3165. static QualType
  3166. checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
  3167. ArrayRef<TemplateArgument> Converted,
  3168. SourceLocation TemplateLoc,
  3169. TemplateArgumentListInfo &TemplateArgs) {
  3170. ASTContext &Context = SemaRef.getASTContext();
  3171. switch (BTD->getBuiltinTemplateKind()) {
  3172. case BTK__make_integer_seq: {
  3173. // Specializations of __make_integer_seq<S, T, N> are treated like
  3174. // S<T, 0, ..., N-1>.
  3175. QualType OrigType = Converted[1].getAsType();
  3176. // C++14 [inteseq.intseq]p1:
  3177. // T shall be an integer type.
  3178. if (!OrigType->isDependentType() && !OrigType->isIntegralType(Context)) {
  3179. SemaRef.Diag(TemplateArgs[1].getLocation(),
  3180. diag::err_integer_sequence_integral_element_type);
  3181. return QualType();
  3182. }
  3183. TemplateArgument NumArgsArg = Converted[2];
  3184. if (NumArgsArg.isDependent())
  3185. return Context.getCanonicalTemplateSpecializationType(TemplateName(BTD),
  3186. Converted);
  3187. TemplateArgumentListInfo SyntheticTemplateArgs;
  3188. // The type argument, wrapped in substitution sugar, gets reused as the
  3189. // first template argument in the synthetic template argument list.
  3190. SyntheticTemplateArgs.addArgument(
  3191. TemplateArgumentLoc(TemplateArgument(OrigType),
  3192. SemaRef.Context.getTrivialTypeSourceInfo(
  3193. OrigType, TemplateArgs[1].getLocation())));
  3194. if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) {
  3195. // Expand N into 0 ... N-1.
  3196. for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
  3197. I < NumArgs; ++I) {
  3198. TemplateArgument TA(Context, I, OrigType);
  3199. SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
  3200. TA, OrigType, TemplateArgs[2].getLocation()));
  3201. }
  3202. } else {
  3203. // C++14 [inteseq.make]p1:
  3204. // If N is negative the program is ill-formed.
  3205. SemaRef.Diag(TemplateArgs[2].getLocation(),
  3206. diag::err_integer_sequence_negative_length);
  3207. return QualType();
  3208. }
  3209. // The first template argument will be reused as the template decl that
  3210. // our synthetic template arguments will be applied to.
  3211. return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
  3212. TemplateLoc, SyntheticTemplateArgs);
  3213. }
  3214. case BTK__type_pack_element:
  3215. // Specializations of
  3216. // __type_pack_element<Index, T_1, ..., T_N>
  3217. // are treated like T_Index.
  3218. assert(Converted.size() == 2 &&
  3219. "__type_pack_element should be given an index and a parameter pack");
  3220. TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
  3221. if (IndexArg.isDependent() || Ts.isDependent())
  3222. return Context.getCanonicalTemplateSpecializationType(TemplateName(BTD),
  3223. Converted);
  3224. llvm::APSInt Index = IndexArg.getAsIntegral();
  3225. assert(Index >= 0 && "the index used with __type_pack_element should be of "
  3226. "type std::size_t, and hence be non-negative");
  3227. // If the Index is out of bounds, the program is ill-formed.
  3228. if (Index >= Ts.pack_size()) {
  3229. SemaRef.Diag(TemplateArgs[0].getLocation(),
  3230. diag::err_type_pack_element_out_of_bounds);
  3231. return QualType();
  3232. }
  3233. // We simply return the type at index `Index`.
  3234. int64_t N = Index.getExtValue();
  3235. return Ts.getPackAsArray()[N].getAsType();
  3236. }
  3237. llvm_unreachable("unexpected BuiltinTemplateDecl!");
  3238. }
  3239. /// Determine whether this alias template is "enable_if_t".
  3240. /// libc++ >=14 uses "__enable_if_t" in C++11 mode.
  3241. static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
  3242. return AliasTemplate->getName().equals("enable_if_t") ||
  3243. AliasTemplate->getName().equals("__enable_if_t");
  3244. }
  3245. /// Collect all of the separable terms in the given condition, which
  3246. /// might be a conjunction.
  3247. ///
  3248. /// FIXME: The right answer is to convert the logical expression into
  3249. /// disjunctive normal form, so we can find the first failed term
  3250. /// within each possible clause.
  3251. static void collectConjunctionTerms(Expr *Clause,
  3252. SmallVectorImpl<Expr *> &Terms) {
  3253. if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
  3254. if (BinOp->getOpcode() == BO_LAnd) {
  3255. collectConjunctionTerms(BinOp->getLHS(), Terms);
  3256. collectConjunctionTerms(BinOp->getRHS(), Terms);
  3257. return;
  3258. }
  3259. }
  3260. Terms.push_back(Clause);
  3261. }
  3262. // The ranges-v3 library uses an odd pattern of a top-level "||" with
  3263. // a left-hand side that is value-dependent but never true. Identify
  3264. // the idiom and ignore that term.
  3265. static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) {
  3266. // Top-level '||'.
  3267. auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
  3268. if (!BinOp) return Cond;
  3269. if (BinOp->getOpcode() != BO_LOr) return Cond;
  3270. // With an inner '==' that has a literal on the right-hand side.
  3271. Expr *LHS = BinOp->getLHS();
  3272. auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
  3273. if (!InnerBinOp) return Cond;
  3274. if (InnerBinOp->getOpcode() != BO_EQ ||
  3275. !isa<IntegerLiteral>(InnerBinOp->getRHS()))
  3276. return Cond;
  3277. // If the inner binary operation came from a macro expansion named
  3278. // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
  3279. // of the '||', which is the real, user-provided condition.
  3280. SourceLocation Loc = InnerBinOp->getExprLoc();
  3281. if (!Loc.isMacroID()) return Cond;
  3282. StringRef MacroName = PP.getImmediateMacroName(Loc);
  3283. if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
  3284. return BinOp->getRHS();
  3285. return Cond;
  3286. }
  3287. namespace {
  3288. // A PrinterHelper that prints more helpful diagnostics for some sub-expressions
  3289. // within failing boolean expression, such as substituting template parameters
  3290. // for actual types.
  3291. class FailedBooleanConditionPrinterHelper : public PrinterHelper {
  3292. public:
  3293. explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
  3294. : Policy(P) {}
  3295. bool handledStmt(Stmt *E, raw_ostream &OS) override {
  3296. const auto *DR = dyn_cast<DeclRefExpr>(E);
  3297. if (DR && DR->getQualifier()) {
  3298. // If this is a qualified name, expand the template arguments in nested
  3299. // qualifiers.
  3300. DR->getQualifier()->print(OS, Policy, true);
  3301. // Then print the decl itself.
  3302. const ValueDecl *VD = DR->getDecl();
  3303. OS << VD->getName();
  3304. if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
  3305. // This is a template variable, print the expanded template arguments.
  3306. printTemplateArgumentList(
  3307. OS, IV->getTemplateArgs().asArray(), Policy,
  3308. IV->getSpecializedTemplate()->getTemplateParameters());
  3309. }
  3310. return true;
  3311. }
  3312. return false;
  3313. }
  3314. private:
  3315. const PrintingPolicy Policy;
  3316. };
  3317. } // end anonymous namespace
  3318. std::pair<Expr *, std::string>
  3319. Sema::findFailedBooleanCondition(Expr *Cond) {
  3320. Cond = lookThroughRangesV3Condition(PP, Cond);
  3321. // Separate out all of the terms in a conjunction.
  3322. SmallVector<Expr *, 4> Terms;
  3323. collectConjunctionTerms(Cond, Terms);
  3324. // Determine which term failed.
  3325. Expr *FailedCond = nullptr;
  3326. for (Expr *Term : Terms) {
  3327. Expr *TermAsWritten = Term->IgnoreParenImpCasts();
  3328. // Literals are uninteresting.
  3329. if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
  3330. isa<IntegerLiteral>(TermAsWritten))
  3331. continue;
  3332. // The initialization of the parameter from the argument is
  3333. // a constant-evaluated context.
  3334. EnterExpressionEvaluationContext ConstantEvaluated(
  3335. *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  3336. bool Succeeded;
  3337. if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
  3338. !Succeeded) {
  3339. FailedCond = TermAsWritten;
  3340. break;
  3341. }
  3342. }
  3343. if (!FailedCond)
  3344. FailedCond = Cond->IgnoreParenImpCasts();
  3345. std::string Description;
  3346. {
  3347. llvm::raw_string_ostream Out(Description);
  3348. PrintingPolicy Policy = getPrintingPolicy();
  3349. Policy.PrintCanonicalTypes = true;
  3350. FailedBooleanConditionPrinterHelper Helper(Policy);
  3351. FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
  3352. }
  3353. return { FailedCond, Description };
  3354. }
  3355. QualType Sema::CheckTemplateIdType(TemplateName Name,
  3356. SourceLocation TemplateLoc,
  3357. TemplateArgumentListInfo &TemplateArgs) {
  3358. DependentTemplateName *DTN
  3359. = Name.getUnderlying().getAsDependentTemplateName();
  3360. if (DTN && DTN->isIdentifier())
  3361. // When building a template-id where the template-name is dependent,
  3362. // assume the template is a type template. Either our assumption is
  3363. // correct, or the code is ill-formed and will be diagnosed when the
  3364. // dependent name is substituted.
  3365. return Context.getDependentTemplateSpecializationType(
  3366. ETK_None, DTN->getQualifier(), DTN->getIdentifier(),
  3367. TemplateArgs.arguments());
  3368. if (Name.getAsAssumedTemplateName() &&
  3369. resolveAssumedTemplateNameAsType(/*Scope*/nullptr, Name, TemplateLoc))
  3370. return QualType();
  3371. TemplateDecl *Template = Name.getAsTemplateDecl();
  3372. if (!Template || isa<FunctionTemplateDecl>(Template) ||
  3373. isa<VarTemplateDecl>(Template) || isa<ConceptDecl>(Template)) {
  3374. // We might have a substituted template template parameter pack. If so,
  3375. // build a template specialization type for it.
  3376. if (Name.getAsSubstTemplateTemplateParmPack())
  3377. return Context.getTemplateSpecializationType(Name,
  3378. TemplateArgs.arguments());
  3379. Diag(TemplateLoc, diag::err_template_id_not_a_type)
  3380. << Name;
  3381. NoteAllFoundTemplates(Name);
  3382. return QualType();
  3383. }
  3384. // Check that the template argument list is well-formed for this
  3385. // template.
  3386. SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
  3387. if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs, false,
  3388. SugaredConverted, CanonicalConverted,
  3389. /*UpdateArgsWithConversions=*/true))
  3390. return QualType();
  3391. QualType CanonType;
  3392. if (TypeAliasTemplateDecl *AliasTemplate =
  3393. dyn_cast<TypeAliasTemplateDecl>(Template)) {
  3394. // Find the canonical type for this type alias template specialization.
  3395. TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
  3396. if (Pattern->isInvalidDecl())
  3397. return QualType();
  3398. // Only substitute for the innermost template argument list.
  3399. MultiLevelTemplateArgumentList TemplateArgLists;
  3400. TemplateArgLists.addOuterTemplateArguments(Template, CanonicalConverted,
  3401. /*Final=*/false);
  3402. TemplateArgLists.addOuterRetainedLevels(
  3403. AliasTemplate->getTemplateParameters()->getDepth());
  3404. LocalInstantiationScope Scope(*this);
  3405. InstantiatingTemplate Inst(*this, TemplateLoc, Template);
  3406. if (Inst.isInvalid())
  3407. return QualType();
  3408. CanonType = SubstType(Pattern->getUnderlyingType(),
  3409. TemplateArgLists, AliasTemplate->getLocation(),
  3410. AliasTemplate->getDeclName());
  3411. if (CanonType.isNull()) {
  3412. // If this was enable_if and we failed to find the nested type
  3413. // within enable_if in a SFINAE context, dig out the specific
  3414. // enable_if condition that failed and present that instead.
  3415. if (isEnableIfAliasTemplate(AliasTemplate)) {
  3416. if (auto DeductionInfo = isSFINAEContext()) {
  3417. if (*DeductionInfo &&
  3418. (*DeductionInfo)->hasSFINAEDiagnostic() &&
  3419. (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
  3420. diag::err_typename_nested_not_found_enable_if &&
  3421. TemplateArgs[0].getArgument().getKind()
  3422. == TemplateArgument::Expression) {
  3423. Expr *FailedCond;
  3424. std::string FailedDescription;
  3425. std::tie(FailedCond, FailedDescription) =
  3426. findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
  3427. // Remove the old SFINAE diagnostic.
  3428. PartialDiagnosticAt OldDiag =
  3429. {SourceLocation(), PartialDiagnostic::NullDiagnostic()};
  3430. (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
  3431. // Add a new SFINAE diagnostic specifying which condition
  3432. // failed.
  3433. (*DeductionInfo)->addSFINAEDiagnostic(
  3434. OldDiag.first,
  3435. PDiag(diag::err_typename_nested_not_found_requirement)
  3436. << FailedDescription
  3437. << FailedCond->getSourceRange());
  3438. }
  3439. }
  3440. }
  3441. return QualType();
  3442. }
  3443. } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
  3444. CanonType = checkBuiltinTemplateIdType(*this, BTD, SugaredConverted,
  3445. TemplateLoc, TemplateArgs);
  3446. } else if (Name.isDependent() ||
  3447. TemplateSpecializationType::anyDependentTemplateArguments(
  3448. TemplateArgs, CanonicalConverted)) {
  3449. // This class template specialization is a dependent
  3450. // type. Therefore, its canonical type is another class template
  3451. // specialization type that contains all of the converted
  3452. // arguments in canonical form. This ensures that, e.g., A<T> and
  3453. // A<T, T> have identical types when A is declared as:
  3454. //
  3455. // template<typename T, typename U = T> struct A;
  3456. CanonType = Context.getCanonicalTemplateSpecializationType(
  3457. Name, CanonicalConverted);
  3458. // This might work out to be a current instantiation, in which
  3459. // case the canonical type needs to be the InjectedClassNameType.
  3460. //
  3461. // TODO: in theory this could be a simple hashtable lookup; most
  3462. // changes to CurContext don't change the set of current
  3463. // instantiations.
  3464. if (isa<ClassTemplateDecl>(Template)) {
  3465. for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
  3466. // If we get out to a namespace, we're done.
  3467. if (Ctx->isFileContext()) break;
  3468. // If this isn't a record, keep looking.
  3469. CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
  3470. if (!Record) continue;
  3471. // Look for one of the two cases with InjectedClassNameTypes
  3472. // and check whether it's the same template.
  3473. if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
  3474. !Record->getDescribedClassTemplate())
  3475. continue;
  3476. // Fetch the injected class name type and check whether its
  3477. // injected type is equal to the type we just built.
  3478. QualType ICNT = Context.getTypeDeclType(Record);
  3479. QualType Injected = cast<InjectedClassNameType>(ICNT)
  3480. ->getInjectedSpecializationType();
  3481. if (CanonType != Injected->getCanonicalTypeInternal())
  3482. continue;
  3483. // If so, the canonical type of this TST is the injected
  3484. // class name type of the record we just found.
  3485. assert(ICNT.isCanonical());
  3486. CanonType = ICNT;
  3487. break;
  3488. }
  3489. }
  3490. } else if (ClassTemplateDecl *ClassTemplate =
  3491. dyn_cast<ClassTemplateDecl>(Template)) {
  3492. // Find the class template specialization declaration that
  3493. // corresponds to these arguments.
  3494. void *InsertPos = nullptr;
  3495. ClassTemplateSpecializationDecl *Decl =
  3496. ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
  3497. if (!Decl) {
  3498. // This is the first time we have referenced this class template
  3499. // specialization. Create the canonical declaration and add it to
  3500. // the set of specializations.
  3501. Decl = ClassTemplateSpecializationDecl::Create(
  3502. Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
  3503. ClassTemplate->getDeclContext(),
  3504. ClassTemplate->getTemplatedDecl()->getBeginLoc(),
  3505. ClassTemplate->getLocation(), ClassTemplate, CanonicalConverted,
  3506. nullptr);
  3507. ClassTemplate->AddSpecialization(Decl, InsertPos);
  3508. if (ClassTemplate->isOutOfLine())
  3509. Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
  3510. }
  3511. if (Decl->getSpecializationKind() == TSK_Undeclared &&
  3512. ClassTemplate->getTemplatedDecl()->hasAttrs()) {
  3513. InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
  3514. if (!Inst.isInvalid()) {
  3515. MultiLevelTemplateArgumentList TemplateArgLists(Template,
  3516. CanonicalConverted,
  3517. /*Final=*/false);
  3518. InstantiateAttrsForDecl(TemplateArgLists,
  3519. ClassTemplate->getTemplatedDecl(), Decl);
  3520. }
  3521. }
  3522. // Diagnose uses of this specialization.
  3523. (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
  3524. CanonType = Context.getTypeDeclType(Decl);
  3525. assert(isa<RecordType>(CanonType) &&
  3526. "type of non-dependent specialization is not a RecordType");
  3527. } else {
  3528. llvm_unreachable("Unhandled template kind");
  3529. }
  3530. // Build the fully-sugared type for this class template
  3531. // specialization, which refers back to the class template
  3532. // specialization we created or found.
  3533. return Context.getTemplateSpecializationType(Name, TemplateArgs.arguments(),
  3534. CanonType);
  3535. }
  3536. void Sema::ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &ParsedName,
  3537. TemplateNameKind &TNK,
  3538. SourceLocation NameLoc,
  3539. IdentifierInfo *&II) {
  3540. assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
  3541. TemplateName Name = ParsedName.get();
  3542. auto *ATN = Name.getAsAssumedTemplateName();
  3543. assert(ATN && "not an assumed template name");
  3544. II = ATN->getDeclName().getAsIdentifierInfo();
  3545. if (!resolveAssumedTemplateNameAsType(S, Name, NameLoc, /*Diagnose*/false)) {
  3546. // Resolved to a type template name.
  3547. ParsedName = TemplateTy::make(Name);
  3548. TNK = TNK_Type_template;
  3549. }
  3550. }
  3551. bool Sema::resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name,
  3552. SourceLocation NameLoc,
  3553. bool Diagnose) {
  3554. // We assumed this undeclared identifier to be an (ADL-only) function
  3555. // template name, but it was used in a context where a type was required.
  3556. // Try to typo-correct it now.
  3557. AssumedTemplateStorage *ATN = Name.getAsAssumedTemplateName();
  3558. assert(ATN && "not an assumed template name");
  3559. LookupResult R(*this, ATN->getDeclName(), NameLoc, LookupOrdinaryName);
  3560. struct CandidateCallback : CorrectionCandidateCallback {
  3561. bool ValidateCandidate(const TypoCorrection &TC) override {
  3562. return TC.getCorrectionDecl() &&
  3563. getAsTypeTemplateDecl(TC.getCorrectionDecl());
  3564. }
  3565. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  3566. return std::make_unique<CandidateCallback>(*this);
  3567. }
  3568. } FilterCCC;
  3569. TypoCorrection Corrected =
  3570. CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
  3571. FilterCCC, CTK_ErrorRecovery);
  3572. if (Corrected && Corrected.getFoundDecl()) {
  3573. diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest)
  3574. << ATN->getDeclName());
  3575. Name = TemplateName(Corrected.getCorrectionDeclAs<TemplateDecl>());
  3576. return false;
  3577. }
  3578. if (Diagnose)
  3579. Diag(R.getNameLoc(), diag::err_no_template) << R.getLookupName();
  3580. return true;
  3581. }
  3582. TypeResult Sema::ActOnTemplateIdType(
  3583. Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
  3584. TemplateTy TemplateD, IdentifierInfo *TemplateII,
  3585. SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
  3586. ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc,
  3587. bool IsCtorOrDtorName, bool IsClassName,
  3588. ImplicitTypenameContext AllowImplicitTypename) {
  3589. if (SS.isInvalid())
  3590. return true;
  3591. if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
  3592. DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
  3593. // C++ [temp.res]p3:
  3594. // A qualified-id that refers to a type and in which the
  3595. // nested-name-specifier depends on a template-parameter (14.6.2)
  3596. // shall be prefixed by the keyword typename to indicate that the
  3597. // qualified-id denotes a type, forming an
  3598. // elaborated-type-specifier (7.1.5.3).
  3599. if (!LookupCtx && isDependentScopeSpecifier(SS)) {
  3600. // C++2a relaxes some of those restrictions in [temp.res]p5.
  3601. if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
  3602. if (getLangOpts().CPlusPlus20)
  3603. Diag(SS.getBeginLoc(), diag::warn_cxx17_compat_implicit_typename);
  3604. else
  3605. Diag(SS.getBeginLoc(), diag::ext_implicit_typename)
  3606. << SS.getScopeRep() << TemplateII->getName()
  3607. << FixItHint::CreateInsertion(SS.getBeginLoc(), "typename ");
  3608. } else
  3609. Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
  3610. << SS.getScopeRep() << TemplateII->getName();
  3611. // FIXME: This is not quite correct recovery as we don't transform SS
  3612. // into the corresponding dependent form (and we don't diagnose missing
  3613. // 'template' keywords within SS as a result).
  3614. return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
  3615. TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
  3616. TemplateArgsIn, RAngleLoc);
  3617. }
  3618. // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
  3619. // it's not actually allowed to be used as a type in most cases. Because
  3620. // we annotate it before we know whether it's valid, we have to check for
  3621. // this case here.
  3622. auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
  3623. if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
  3624. Diag(TemplateIILoc,
  3625. TemplateKWLoc.isInvalid()
  3626. ? diag::err_out_of_line_qualified_id_type_names_constructor
  3627. : diag::ext_out_of_line_qualified_id_type_names_constructor)
  3628. << TemplateII << 0 /*injected-class-name used as template name*/
  3629. << 1 /*if any keyword was present, it was 'template'*/;
  3630. }
  3631. }
  3632. TemplateName Template = TemplateD.get();
  3633. if (Template.getAsAssumedTemplateName() &&
  3634. resolveAssumedTemplateNameAsType(S, Template, TemplateIILoc))
  3635. return true;
  3636. // Translate the parser's template argument list in our AST format.
  3637. TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
  3638. translateTemplateArguments(TemplateArgsIn, TemplateArgs);
  3639. if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
  3640. assert(SS.getScopeRep() == DTN->getQualifier());
  3641. QualType T = Context.getDependentTemplateSpecializationType(
  3642. ETK_None, DTN->getQualifier(), DTN->getIdentifier(),
  3643. TemplateArgs.arguments());
  3644. // Build type-source information.
  3645. TypeLocBuilder TLB;
  3646. DependentTemplateSpecializationTypeLoc SpecTL
  3647. = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
  3648. SpecTL.setElaboratedKeywordLoc(SourceLocation());
  3649. SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
  3650. SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
  3651. SpecTL.setTemplateNameLoc(TemplateIILoc);
  3652. SpecTL.setLAngleLoc(LAngleLoc);
  3653. SpecTL.setRAngleLoc(RAngleLoc);
  3654. for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
  3655. SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
  3656. return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
  3657. }
  3658. QualType SpecTy = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
  3659. if (SpecTy.isNull())
  3660. return true;
  3661. // Build type-source information.
  3662. TypeLocBuilder TLB;
  3663. TemplateSpecializationTypeLoc SpecTL =
  3664. TLB.push<TemplateSpecializationTypeLoc>(SpecTy);
  3665. SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
  3666. SpecTL.setTemplateNameLoc(TemplateIILoc);
  3667. SpecTL.setLAngleLoc(LAngleLoc);
  3668. SpecTL.setRAngleLoc(RAngleLoc);
  3669. for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
  3670. SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
  3671. // Create an elaborated-type-specifier containing the nested-name-specifier.
  3672. QualType ElTy = getElaboratedType(
  3673. ETK_None, !IsCtorOrDtorName ? SS : CXXScopeSpec(), SpecTy);
  3674. ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(ElTy);
  3675. ElabTL.setElaboratedKeywordLoc(SourceLocation());
  3676. if (!ElabTL.isEmpty())
  3677. ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
  3678. return CreateParsedType(ElTy, TLB.getTypeSourceInfo(Context, ElTy));
  3679. }
  3680. TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
  3681. TypeSpecifierType TagSpec,
  3682. SourceLocation TagLoc,
  3683. CXXScopeSpec &SS,
  3684. SourceLocation TemplateKWLoc,
  3685. TemplateTy TemplateD,
  3686. SourceLocation TemplateLoc,
  3687. SourceLocation LAngleLoc,
  3688. ASTTemplateArgsPtr TemplateArgsIn,
  3689. SourceLocation RAngleLoc) {
  3690. if (SS.isInvalid())
  3691. return TypeResult(true);
  3692. TemplateName Template = TemplateD.get();
  3693. // Translate the parser's template argument list in our AST format.
  3694. TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
  3695. translateTemplateArguments(TemplateArgsIn, TemplateArgs);
  3696. // Determine the tag kind
  3697. TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  3698. ElaboratedTypeKeyword Keyword
  3699. = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
  3700. if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
  3701. assert(SS.getScopeRep() == DTN->getQualifier());
  3702. QualType T = Context.getDependentTemplateSpecializationType(
  3703. Keyword, DTN->getQualifier(), DTN->getIdentifier(),
  3704. TemplateArgs.arguments());
  3705. // Build type-source information.
  3706. TypeLocBuilder TLB;
  3707. DependentTemplateSpecializationTypeLoc SpecTL
  3708. = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
  3709. SpecTL.setElaboratedKeywordLoc(TagLoc);
  3710. SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
  3711. SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
  3712. SpecTL.setTemplateNameLoc(TemplateLoc);
  3713. SpecTL.setLAngleLoc(LAngleLoc);
  3714. SpecTL.setRAngleLoc(RAngleLoc);
  3715. for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
  3716. SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
  3717. return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
  3718. }
  3719. if (TypeAliasTemplateDecl *TAT =
  3720. dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
  3721. // C++0x [dcl.type.elab]p2:
  3722. // If the identifier resolves to a typedef-name or the simple-template-id
  3723. // resolves to an alias template specialization, the
  3724. // elaborated-type-specifier is ill-formed.
  3725. Diag(TemplateLoc, diag::err_tag_reference_non_tag)
  3726. << TAT << NTK_TypeAliasTemplate << TagKind;
  3727. Diag(TAT->getLocation(), diag::note_declared_at);
  3728. }
  3729. QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
  3730. if (Result.isNull())
  3731. return TypeResult(true);
  3732. // Check the tag kind
  3733. if (const RecordType *RT = Result->getAs<RecordType>()) {
  3734. RecordDecl *D = RT->getDecl();
  3735. IdentifierInfo *Id = D->getIdentifier();
  3736. assert(Id && "templated class must have an identifier");
  3737. if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
  3738. TagLoc, Id)) {
  3739. Diag(TagLoc, diag::err_use_with_wrong_tag)
  3740. << Result
  3741. << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
  3742. Diag(D->getLocation(), diag::note_previous_use);
  3743. }
  3744. }
  3745. // Provide source-location information for the template specialization.
  3746. TypeLocBuilder TLB;
  3747. TemplateSpecializationTypeLoc SpecTL
  3748. = TLB.push<TemplateSpecializationTypeLoc>(Result);
  3749. SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
  3750. SpecTL.setTemplateNameLoc(TemplateLoc);
  3751. SpecTL.setLAngleLoc(LAngleLoc);
  3752. SpecTL.setRAngleLoc(RAngleLoc);
  3753. for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
  3754. SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
  3755. // Construct an elaborated type containing the nested-name-specifier (if any)
  3756. // and tag keyword.
  3757. Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
  3758. ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
  3759. ElabTL.setElaboratedKeywordLoc(TagLoc);
  3760. ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
  3761. return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
  3762. }
  3763. static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
  3764. NamedDecl *PrevDecl,
  3765. SourceLocation Loc,
  3766. bool IsPartialSpecialization);
  3767. static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
  3768. static bool isTemplateArgumentTemplateParameter(
  3769. const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
  3770. switch (Arg.getKind()) {
  3771. case TemplateArgument::Null:
  3772. case TemplateArgument::NullPtr:
  3773. case TemplateArgument::Integral:
  3774. case TemplateArgument::Declaration:
  3775. case TemplateArgument::Pack:
  3776. case TemplateArgument::TemplateExpansion:
  3777. return false;
  3778. case TemplateArgument::Type: {
  3779. QualType Type = Arg.getAsType();
  3780. const TemplateTypeParmType *TPT =
  3781. Arg.getAsType()->getAs<TemplateTypeParmType>();
  3782. return TPT && !Type.hasQualifiers() &&
  3783. TPT->getDepth() == Depth && TPT->getIndex() == Index;
  3784. }
  3785. case TemplateArgument::Expression: {
  3786. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
  3787. if (!DRE || !DRE->getDecl())
  3788. return false;
  3789. const NonTypeTemplateParmDecl *NTTP =
  3790. dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
  3791. return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
  3792. }
  3793. case TemplateArgument::Template:
  3794. const TemplateTemplateParmDecl *TTP =
  3795. dyn_cast_or_null<TemplateTemplateParmDecl>(
  3796. Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
  3797. return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
  3798. }
  3799. llvm_unreachable("unexpected kind of template argument");
  3800. }
  3801. static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
  3802. ArrayRef<TemplateArgument> Args) {
  3803. if (Params->size() != Args.size())
  3804. return false;
  3805. unsigned Depth = Params->getDepth();
  3806. for (unsigned I = 0, N = Args.size(); I != N; ++I) {
  3807. TemplateArgument Arg = Args[I];
  3808. // If the parameter is a pack expansion, the argument must be a pack
  3809. // whose only element is a pack expansion.
  3810. if (Params->getParam(I)->isParameterPack()) {
  3811. if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
  3812. !Arg.pack_begin()->isPackExpansion())
  3813. return false;
  3814. Arg = Arg.pack_begin()->getPackExpansionPattern();
  3815. }
  3816. if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
  3817. return false;
  3818. }
  3819. return true;
  3820. }
  3821. template<typename PartialSpecDecl>
  3822. static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
  3823. if (Partial->getDeclContext()->isDependentContext())
  3824. return;
  3825. // FIXME: Get the TDK from deduction in order to provide better diagnostics
  3826. // for non-substitution-failure issues?
  3827. TemplateDeductionInfo Info(Partial->getLocation());
  3828. if (S.isMoreSpecializedThanPrimary(Partial, Info))
  3829. return;
  3830. auto *Template = Partial->getSpecializedTemplate();
  3831. S.Diag(Partial->getLocation(),
  3832. diag::ext_partial_spec_not_more_specialized_than_primary)
  3833. << isa<VarTemplateDecl>(Template);
  3834. if (Info.hasSFINAEDiagnostic()) {
  3835. PartialDiagnosticAt Diag = {SourceLocation(),
  3836. PartialDiagnostic::NullDiagnostic()};
  3837. Info.takeSFINAEDiagnostic(Diag);
  3838. SmallString<128> SFINAEArgString;
  3839. Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
  3840. S.Diag(Diag.first,
  3841. diag::note_partial_spec_not_more_specialized_than_primary)
  3842. << SFINAEArgString;
  3843. }
  3844. S.Diag(Template->getLocation(), diag::note_template_decl_here);
  3845. SmallVector<const Expr *, 3> PartialAC, TemplateAC;
  3846. Template->getAssociatedConstraints(TemplateAC);
  3847. Partial->getAssociatedConstraints(PartialAC);
  3848. S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Partial, PartialAC, Template,
  3849. TemplateAC);
  3850. }
  3851. static void
  3852. noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
  3853. const llvm::SmallBitVector &DeducibleParams) {
  3854. for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
  3855. if (!DeducibleParams[I]) {
  3856. NamedDecl *Param = TemplateParams->getParam(I);
  3857. if (Param->getDeclName())
  3858. S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
  3859. << Param->getDeclName();
  3860. else
  3861. S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
  3862. << "(anonymous)";
  3863. }
  3864. }
  3865. }
  3866. template<typename PartialSpecDecl>
  3867. static void checkTemplatePartialSpecialization(Sema &S,
  3868. PartialSpecDecl *Partial) {
  3869. // C++1z [temp.class.spec]p8: (DR1495)
  3870. // - The specialization shall be more specialized than the primary
  3871. // template (14.5.5.2).
  3872. checkMoreSpecializedThanPrimary(S, Partial);
  3873. // C++ [temp.class.spec]p8: (DR1315)
  3874. // - Each template-parameter shall appear at least once in the
  3875. // template-id outside a non-deduced context.
  3876. // C++1z [temp.class.spec.match]p3 (P0127R2)
  3877. // If the template arguments of a partial specialization cannot be
  3878. // deduced because of the structure of its template-parameter-list
  3879. // and the template-id, the program is ill-formed.
  3880. auto *TemplateParams = Partial->getTemplateParameters();
  3881. llvm::SmallBitVector DeducibleParams(TemplateParams->size());
  3882. S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
  3883. TemplateParams->getDepth(), DeducibleParams);
  3884. if (!DeducibleParams.all()) {
  3885. unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
  3886. S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
  3887. << isa<VarTemplatePartialSpecializationDecl>(Partial)
  3888. << (NumNonDeducible > 1)
  3889. << SourceRange(Partial->getLocation(),
  3890. Partial->getTemplateArgsAsWritten()->RAngleLoc);
  3891. noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
  3892. }
  3893. }
  3894. void Sema::CheckTemplatePartialSpecialization(
  3895. ClassTemplatePartialSpecializationDecl *Partial) {
  3896. checkTemplatePartialSpecialization(*this, Partial);
  3897. }
  3898. void Sema::CheckTemplatePartialSpecialization(
  3899. VarTemplatePartialSpecializationDecl *Partial) {
  3900. checkTemplatePartialSpecialization(*this, Partial);
  3901. }
  3902. void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
  3903. // C++1z [temp.param]p11:
  3904. // A template parameter of a deduction guide template that does not have a
  3905. // default-argument shall be deducible from the parameter-type-list of the
  3906. // deduction guide template.
  3907. auto *TemplateParams = TD->getTemplateParameters();
  3908. llvm::SmallBitVector DeducibleParams(TemplateParams->size());
  3909. MarkDeducedTemplateParameters(TD, DeducibleParams);
  3910. for (unsigned I = 0; I != TemplateParams->size(); ++I) {
  3911. // A parameter pack is deducible (to an empty pack).
  3912. auto *Param = TemplateParams->getParam(I);
  3913. if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
  3914. DeducibleParams[I] = true;
  3915. }
  3916. if (!DeducibleParams.all()) {
  3917. unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
  3918. Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
  3919. << (NumNonDeducible > 1);
  3920. noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
  3921. }
  3922. }
  3923. DeclResult Sema::ActOnVarTemplateSpecialization(
  3924. Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
  3925. TemplateParameterList *TemplateParams, StorageClass SC,
  3926. bool IsPartialSpecialization) {
  3927. // D must be variable template id.
  3928. assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
  3929. "Variable template specialization is declared with a template id.");
  3930. TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
  3931. TemplateArgumentListInfo TemplateArgs =
  3932. makeTemplateArgumentListInfo(*this, *TemplateId);
  3933. SourceLocation TemplateNameLoc = D.getIdentifierLoc();
  3934. SourceLocation LAngleLoc = TemplateId->LAngleLoc;
  3935. SourceLocation RAngleLoc = TemplateId->RAngleLoc;
  3936. TemplateName Name = TemplateId->Template.get();
  3937. // The template-id must name a variable template.
  3938. VarTemplateDecl *VarTemplate =
  3939. dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
  3940. if (!VarTemplate) {
  3941. NamedDecl *FnTemplate;
  3942. if (auto *OTS = Name.getAsOverloadedTemplate())
  3943. FnTemplate = *OTS->begin();
  3944. else
  3945. FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
  3946. if (FnTemplate)
  3947. return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
  3948. << FnTemplate->getDeclName();
  3949. return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
  3950. << IsPartialSpecialization;
  3951. }
  3952. // Check for unexpanded parameter packs in any of the template arguments.
  3953. for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
  3954. if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
  3955. UPPC_PartialSpecialization))
  3956. return true;
  3957. // Check that the template argument list is well-formed for this
  3958. // template.
  3959. SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
  3960. if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
  3961. false, SugaredConverted, CanonicalConverted,
  3962. /*UpdateArgsWithConversions=*/true))
  3963. return true;
  3964. // Find the variable template (partial) specialization declaration that
  3965. // corresponds to these arguments.
  3966. if (IsPartialSpecialization) {
  3967. if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
  3968. TemplateArgs.size(),
  3969. CanonicalConverted))
  3970. return true;
  3971. // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
  3972. // also do them during instantiation.
  3973. if (!Name.isDependent() &&
  3974. !TemplateSpecializationType::anyDependentTemplateArguments(
  3975. TemplateArgs, CanonicalConverted)) {
  3976. Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
  3977. << VarTemplate->getDeclName();
  3978. IsPartialSpecialization = false;
  3979. }
  3980. if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
  3981. CanonicalConverted) &&
  3982. (!Context.getLangOpts().CPlusPlus20 ||
  3983. !TemplateParams->hasAssociatedConstraints())) {
  3984. // C++ [temp.class.spec]p9b3:
  3985. //
  3986. // -- The argument list of the specialization shall not be identical
  3987. // to the implicit argument list of the primary template.
  3988. Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
  3989. << /*variable template*/ 1
  3990. << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
  3991. << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
  3992. // FIXME: Recover from this by treating the declaration as a redeclaration
  3993. // of the primary template.
  3994. return true;
  3995. }
  3996. }
  3997. void *InsertPos = nullptr;
  3998. VarTemplateSpecializationDecl *PrevDecl = nullptr;
  3999. if (IsPartialSpecialization)
  4000. PrevDecl = VarTemplate->findPartialSpecialization(
  4001. CanonicalConverted, TemplateParams, InsertPos);
  4002. else
  4003. PrevDecl = VarTemplate->findSpecialization(CanonicalConverted, InsertPos);
  4004. VarTemplateSpecializationDecl *Specialization = nullptr;
  4005. // Check whether we can declare a variable template specialization in
  4006. // the current scope.
  4007. if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
  4008. TemplateNameLoc,
  4009. IsPartialSpecialization))
  4010. return true;
  4011. if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
  4012. // Since the only prior variable template specialization with these
  4013. // arguments was referenced but not declared, reuse that
  4014. // declaration node as our own, updating its source location and
  4015. // the list of outer template parameters to reflect our new declaration.
  4016. Specialization = PrevDecl;
  4017. Specialization->setLocation(TemplateNameLoc);
  4018. PrevDecl = nullptr;
  4019. } else if (IsPartialSpecialization) {
  4020. // Create a new class template partial specialization declaration node.
  4021. VarTemplatePartialSpecializationDecl *PrevPartial =
  4022. cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
  4023. VarTemplatePartialSpecializationDecl *Partial =
  4024. VarTemplatePartialSpecializationDecl::Create(
  4025. Context, VarTemplate->getDeclContext(), TemplateKWLoc,
  4026. TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
  4027. CanonicalConverted, TemplateArgs);
  4028. if (!PrevPartial)
  4029. VarTemplate->AddPartialSpecialization(Partial, InsertPos);
  4030. Specialization = Partial;
  4031. // If we are providing an explicit specialization of a member variable
  4032. // template specialization, make a note of that.
  4033. if (PrevPartial && PrevPartial->getInstantiatedFromMember())
  4034. PrevPartial->setMemberSpecialization();
  4035. CheckTemplatePartialSpecialization(Partial);
  4036. } else {
  4037. // Create a new class template specialization declaration node for
  4038. // this explicit specialization or friend declaration.
  4039. Specialization = VarTemplateSpecializationDecl::Create(
  4040. Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
  4041. VarTemplate, DI->getType(), DI, SC, CanonicalConverted);
  4042. Specialization->setTemplateArgsInfo(TemplateArgs);
  4043. if (!PrevDecl)
  4044. VarTemplate->AddSpecialization(Specialization, InsertPos);
  4045. }
  4046. // C++ [temp.expl.spec]p6:
  4047. // If a template, a member template or the member of a class template is
  4048. // explicitly specialized then that specialization shall be declared
  4049. // before the first use of that specialization that would cause an implicit
  4050. // instantiation to take place, in every translation unit in which such a
  4051. // use occurs; no diagnostic is required.
  4052. if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
  4053. bool Okay = false;
  4054. for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
  4055. // Is there any previous explicit specialization declaration?
  4056. if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
  4057. Okay = true;
  4058. break;
  4059. }
  4060. }
  4061. if (!Okay) {
  4062. SourceRange Range(TemplateNameLoc, RAngleLoc);
  4063. Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
  4064. << Name << Range;
  4065. Diag(PrevDecl->getPointOfInstantiation(),
  4066. diag::note_instantiation_required_here)
  4067. << (PrevDecl->getTemplateSpecializationKind() !=
  4068. TSK_ImplicitInstantiation);
  4069. return true;
  4070. }
  4071. }
  4072. Specialization->setTemplateKeywordLoc(TemplateKWLoc);
  4073. Specialization->setLexicalDeclContext(CurContext);
  4074. // Add the specialization into its lexical context, so that it can
  4075. // be seen when iterating through the list of declarations in that
  4076. // context. However, specializations are not found by name lookup.
  4077. CurContext->addDecl(Specialization);
  4078. // Note that this is an explicit specialization.
  4079. Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
  4080. if (PrevDecl) {
  4081. // Check that this isn't a redefinition of this specialization,
  4082. // merging with previous declarations.
  4083. LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
  4084. forRedeclarationInCurContext());
  4085. PrevSpec.addDecl(PrevDecl);
  4086. D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
  4087. } else if (Specialization->isStaticDataMember() &&
  4088. Specialization->isOutOfLine()) {
  4089. Specialization->setAccess(VarTemplate->getAccess());
  4090. }
  4091. return Specialization;
  4092. }
  4093. namespace {
  4094. /// A partial specialization whose template arguments have matched
  4095. /// a given template-id.
  4096. struct PartialSpecMatchResult {
  4097. VarTemplatePartialSpecializationDecl *Partial;
  4098. TemplateArgumentList *Args;
  4099. };
  4100. } // end anonymous namespace
  4101. DeclResult
  4102. Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
  4103. SourceLocation TemplateNameLoc,
  4104. const TemplateArgumentListInfo &TemplateArgs) {
  4105. assert(Template && "A variable template id without template?");
  4106. // Check that the template argument list is well-formed for this template.
  4107. SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
  4108. if (CheckTemplateArgumentList(
  4109. Template, TemplateNameLoc,
  4110. const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
  4111. SugaredConverted, CanonicalConverted,
  4112. /*UpdateArgsWithConversions=*/true))
  4113. return true;
  4114. // Produce a placeholder value if the specialization is dependent.
  4115. if (Template->getDeclContext()->isDependentContext() ||
  4116. TemplateSpecializationType::anyDependentTemplateArguments(
  4117. TemplateArgs, CanonicalConverted))
  4118. return DeclResult();
  4119. // Find the variable template specialization declaration that
  4120. // corresponds to these arguments.
  4121. void *InsertPos = nullptr;
  4122. if (VarTemplateSpecializationDecl *Spec =
  4123. Template->findSpecialization(CanonicalConverted, InsertPos)) {
  4124. checkSpecializationReachability(TemplateNameLoc, Spec);
  4125. // If we already have a variable template specialization, return it.
  4126. return Spec;
  4127. }
  4128. // This is the first time we have referenced this variable template
  4129. // specialization. Create the canonical declaration and add it to
  4130. // the set of specializations, based on the closest partial specialization
  4131. // that it represents. That is,
  4132. VarDecl *InstantiationPattern = Template->getTemplatedDecl();
  4133. TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
  4134. CanonicalConverted);
  4135. TemplateArgumentList *InstantiationArgs = &TemplateArgList;
  4136. bool AmbiguousPartialSpec = false;
  4137. typedef PartialSpecMatchResult MatchResult;
  4138. SmallVector<MatchResult, 4> Matched;
  4139. SourceLocation PointOfInstantiation = TemplateNameLoc;
  4140. TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
  4141. /*ForTakingAddress=*/false);
  4142. // 1. Attempt to find the closest partial specialization that this
  4143. // specializes, if any.
  4144. // TODO: Unify with InstantiateClassTemplateSpecialization()?
  4145. // Perhaps better after unification of DeduceTemplateArguments() and
  4146. // getMoreSpecializedPartialSpecialization().
  4147. SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
  4148. Template->getPartialSpecializations(PartialSpecs);
  4149. for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
  4150. VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
  4151. TemplateDeductionInfo Info(FailedCandidates.getLocation());
  4152. if (TemplateDeductionResult Result =
  4153. DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
  4154. // Store the failed-deduction information for use in diagnostics, later.
  4155. // TODO: Actually use the failed-deduction info?
  4156. FailedCandidates.addCandidate().set(
  4157. DeclAccessPair::make(Template, AS_public), Partial,
  4158. MakeDeductionFailureInfo(Context, Result, Info));
  4159. (void)Result;
  4160. } else {
  4161. Matched.push_back(PartialSpecMatchResult());
  4162. Matched.back().Partial = Partial;
  4163. Matched.back().Args = Info.takeCanonical();
  4164. }
  4165. }
  4166. if (Matched.size() >= 1) {
  4167. SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
  4168. if (Matched.size() == 1) {
  4169. // -- If exactly one matching specialization is found, the
  4170. // instantiation is generated from that specialization.
  4171. // We don't need to do anything for this.
  4172. } else {
  4173. // -- If more than one matching specialization is found, the
  4174. // partial order rules (14.5.4.2) are used to determine
  4175. // whether one of the specializations is more specialized
  4176. // than the others. If none of the specializations is more
  4177. // specialized than all of the other matching
  4178. // specializations, then the use of the variable template is
  4179. // ambiguous and the program is ill-formed.
  4180. for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
  4181. PEnd = Matched.end();
  4182. P != PEnd; ++P) {
  4183. if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
  4184. PointOfInstantiation) ==
  4185. P->Partial)
  4186. Best = P;
  4187. }
  4188. // Determine if the best partial specialization is more specialized than
  4189. // the others.
  4190. for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
  4191. PEnd = Matched.end();
  4192. P != PEnd; ++P) {
  4193. if (P != Best && getMoreSpecializedPartialSpecialization(
  4194. P->Partial, Best->Partial,
  4195. PointOfInstantiation) != Best->Partial) {
  4196. AmbiguousPartialSpec = true;
  4197. break;
  4198. }
  4199. }
  4200. }
  4201. // Instantiate using the best variable template partial specialization.
  4202. InstantiationPattern = Best->Partial;
  4203. InstantiationArgs = Best->Args;
  4204. } else {
  4205. // -- If no match is found, the instantiation is generated
  4206. // from the primary template.
  4207. // InstantiationPattern = Template->getTemplatedDecl();
  4208. }
  4209. // 2. Create the canonical declaration.
  4210. // Note that we do not instantiate a definition until we see an odr-use
  4211. // in DoMarkVarDeclReferenced().
  4212. // FIXME: LateAttrs et al.?
  4213. VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
  4214. Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
  4215. CanonicalConverted, TemplateNameLoc /*, LateAttrs, StartingScope*/);
  4216. if (!Decl)
  4217. return true;
  4218. if (AmbiguousPartialSpec) {
  4219. // Partial ordering did not produce a clear winner. Complain.
  4220. Decl->setInvalidDecl();
  4221. Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
  4222. << Decl;
  4223. // Print the matching partial specializations.
  4224. for (MatchResult P : Matched)
  4225. Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
  4226. << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
  4227. *P.Args);
  4228. return true;
  4229. }
  4230. if (VarTemplatePartialSpecializationDecl *D =
  4231. dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
  4232. Decl->setInstantiationOf(D, InstantiationArgs);
  4233. checkSpecializationReachability(TemplateNameLoc, Decl);
  4234. assert(Decl && "No variable template specialization?");
  4235. return Decl;
  4236. }
  4237. ExprResult
  4238. Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
  4239. const DeclarationNameInfo &NameInfo,
  4240. VarTemplateDecl *Template, SourceLocation TemplateLoc,
  4241. const TemplateArgumentListInfo *TemplateArgs) {
  4242. DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
  4243. *TemplateArgs);
  4244. if (Decl.isInvalid())
  4245. return ExprError();
  4246. if (!Decl.get())
  4247. return ExprResult();
  4248. VarDecl *Var = cast<VarDecl>(Decl.get());
  4249. if (!Var->getTemplateSpecializationKind())
  4250. Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
  4251. NameInfo.getLoc());
  4252. // Build an ordinary singleton decl ref.
  4253. return BuildDeclarationNameExpr(SS, NameInfo, Var,
  4254. /*FoundD=*/nullptr, TemplateArgs);
  4255. }
  4256. void Sema::diagnoseMissingTemplateArguments(TemplateName Name,
  4257. SourceLocation Loc) {
  4258. Diag(Loc, diag::err_template_missing_args)
  4259. << (int)getTemplateNameKindForDiagnostics(Name) << Name;
  4260. if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
  4261. Diag(TD->getLocation(), diag::note_template_decl_here)
  4262. << TD->getTemplateParameters()->getSourceRange();
  4263. }
  4264. }
  4265. ExprResult
  4266. Sema::CheckConceptTemplateId(const CXXScopeSpec &SS,
  4267. SourceLocation TemplateKWLoc,
  4268. const DeclarationNameInfo &ConceptNameInfo,
  4269. NamedDecl *FoundDecl,
  4270. ConceptDecl *NamedConcept,
  4271. const TemplateArgumentListInfo *TemplateArgs) {
  4272. assert(NamedConcept && "A concept template id without a template?");
  4273. llvm::SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
  4274. if (CheckTemplateArgumentList(
  4275. NamedConcept, ConceptNameInfo.getLoc(),
  4276. const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
  4277. /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted,
  4278. /*UpdateArgsWithConversions=*/false))
  4279. return ExprError();
  4280. auto *CSD = ImplicitConceptSpecializationDecl::Create(
  4281. Context, NamedConcept->getDeclContext(), NamedConcept->getLocation(),
  4282. CanonicalConverted);
  4283. ConstraintSatisfaction Satisfaction;
  4284. bool AreArgsDependent =
  4285. TemplateSpecializationType::anyDependentTemplateArguments(
  4286. *TemplateArgs, CanonicalConverted);
  4287. MultiLevelTemplateArgumentList MLTAL(NamedConcept, CanonicalConverted,
  4288. /*Final=*/false);
  4289. LocalInstantiationScope Scope(*this);
  4290. EnterExpressionEvaluationContext EECtx{
  4291. *this, ExpressionEvaluationContext::ConstantEvaluated, CSD};
  4292. if (!AreArgsDependent &&
  4293. CheckConstraintSatisfaction(
  4294. NamedConcept, {NamedConcept->getConstraintExpr()}, MLTAL,
  4295. SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),
  4296. TemplateArgs->getRAngleLoc()),
  4297. Satisfaction))
  4298. return ExprError();
  4299. return ConceptSpecializationExpr::Create(
  4300. Context,
  4301. SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc{},
  4302. TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept,
  4303. ASTTemplateArgumentListInfo::Create(Context, *TemplateArgs), CSD,
  4304. AreArgsDependent ? nullptr : &Satisfaction);
  4305. }
  4306. ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
  4307. SourceLocation TemplateKWLoc,
  4308. LookupResult &R,
  4309. bool RequiresADL,
  4310. const TemplateArgumentListInfo *TemplateArgs) {
  4311. // FIXME: Can we do any checking at this point? I guess we could check the
  4312. // template arguments that we have against the template name, if the template
  4313. // name refers to a single template. That's not a terribly common case,
  4314. // though.
  4315. // foo<int> could identify a single function unambiguously
  4316. // This approach does NOT work, since f<int>(1);
  4317. // gets resolved prior to resorting to overload resolution
  4318. // i.e., template<class T> void f(double);
  4319. // vs template<class T, class U> void f(U);
  4320. // These should be filtered out by our callers.
  4321. assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
  4322. // Non-function templates require a template argument list.
  4323. if (auto *TD = R.getAsSingle<TemplateDecl>()) {
  4324. if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
  4325. diagnoseMissingTemplateArguments(TemplateName(TD), R.getNameLoc());
  4326. return ExprError();
  4327. }
  4328. }
  4329. // In C++1y, check variable template ids.
  4330. if (R.getAsSingle<VarTemplateDecl>()) {
  4331. ExprResult Res = CheckVarTemplateId(SS, R.getLookupNameInfo(),
  4332. R.getAsSingle<VarTemplateDecl>(),
  4333. TemplateKWLoc, TemplateArgs);
  4334. if (Res.isInvalid() || Res.isUsable())
  4335. return Res;
  4336. // Result is dependent. Carry on to build an UnresolvedLookupEpxr.
  4337. }
  4338. if (R.getAsSingle<ConceptDecl>()) {
  4339. return CheckConceptTemplateId(SS, TemplateKWLoc, R.getLookupNameInfo(),
  4340. R.getFoundDecl(),
  4341. R.getAsSingle<ConceptDecl>(), TemplateArgs);
  4342. }
  4343. // We don't want lookup warnings at this point.
  4344. R.suppressDiagnostics();
  4345. UnresolvedLookupExpr *ULE
  4346. = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
  4347. SS.getWithLocInContext(Context),
  4348. TemplateKWLoc,
  4349. R.getLookupNameInfo(),
  4350. RequiresADL, TemplateArgs,
  4351. R.begin(), R.end());
  4352. return ULE;
  4353. }
  4354. // We actually only call this from template instantiation.
  4355. ExprResult
  4356. Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
  4357. SourceLocation TemplateKWLoc,
  4358. const DeclarationNameInfo &NameInfo,
  4359. const TemplateArgumentListInfo *TemplateArgs) {
  4360. assert(TemplateArgs || TemplateKWLoc.isValid());
  4361. DeclContext *DC;
  4362. if (!(DC = computeDeclContext(SS, false)) ||
  4363. DC->isDependentContext() ||
  4364. RequireCompleteDeclContext(SS, DC))
  4365. return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
  4366. bool MemberOfUnknownSpecialization;
  4367. LookupResult R(*this, NameInfo, LookupOrdinaryName);
  4368. if (LookupTemplateName(R, (Scope *)nullptr, SS, QualType(),
  4369. /*Entering*/false, MemberOfUnknownSpecialization,
  4370. TemplateKWLoc))
  4371. return ExprError();
  4372. if (R.isAmbiguous())
  4373. return ExprError();
  4374. if (R.empty()) {
  4375. Diag(NameInfo.getLoc(), diag::err_no_member)
  4376. << NameInfo.getName() << DC << SS.getRange();
  4377. return ExprError();
  4378. }
  4379. if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
  4380. Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
  4381. << SS.getScopeRep()
  4382. << NameInfo.getName().getAsString() << SS.getRange();
  4383. Diag(Temp->getLocation(), diag::note_referenced_class_template);
  4384. return ExprError();
  4385. }
  4386. return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
  4387. }
  4388. /// Form a template name from a name that is syntactically required to name a
  4389. /// template, either due to use of the 'template' keyword or because a name in
  4390. /// this syntactic context is assumed to name a template (C++ [temp.names]p2-4).
  4391. ///
  4392. /// This action forms a template name given the name of the template and its
  4393. /// optional scope specifier. This is used when the 'template' keyword is used
  4394. /// or when the parsing context unambiguously treats a following '<' as
  4395. /// introducing a template argument list. Note that this may produce a
  4396. /// non-dependent template name if we can perform the lookup now and identify
  4397. /// the named template.
  4398. ///
  4399. /// For example, given "x.MetaFun::template apply", the scope specifier
  4400. /// \p SS will be "MetaFun::", \p TemplateKWLoc contains the location
  4401. /// of the "template" keyword, and "apply" is the \p Name.
  4402. TemplateNameKind Sema::ActOnTemplateName(Scope *S,
  4403. CXXScopeSpec &SS,
  4404. SourceLocation TemplateKWLoc,
  4405. const UnqualifiedId &Name,
  4406. ParsedType ObjectType,
  4407. bool EnteringContext,
  4408. TemplateTy &Result,
  4409. bool AllowInjectedClassName) {
  4410. if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
  4411. Diag(TemplateKWLoc,
  4412. getLangOpts().CPlusPlus11 ?
  4413. diag::warn_cxx98_compat_template_outside_of_template :
  4414. diag::ext_template_outside_of_template)
  4415. << FixItHint::CreateRemoval(TemplateKWLoc);
  4416. if (SS.isInvalid())
  4417. return TNK_Non_template;
  4418. // Figure out where isTemplateName is going to look.
  4419. DeclContext *LookupCtx = nullptr;
  4420. if (SS.isNotEmpty())
  4421. LookupCtx = computeDeclContext(SS, EnteringContext);
  4422. else if (ObjectType)
  4423. LookupCtx = computeDeclContext(GetTypeFromParser(ObjectType));
  4424. // C++0x [temp.names]p5:
  4425. // If a name prefixed by the keyword template is not the name of
  4426. // a template, the program is ill-formed. [Note: the keyword
  4427. // template may not be applied to non-template members of class
  4428. // templates. -end note ] [ Note: as is the case with the
  4429. // typename prefix, the template prefix is allowed in cases
  4430. // where it is not strictly necessary; i.e., when the
  4431. // nested-name-specifier or the expression on the left of the ->
  4432. // or . is not dependent on a template-parameter, or the use
  4433. // does not appear in the scope of a template. -end note]
  4434. //
  4435. // Note: C++03 was more strict here, because it banned the use of
  4436. // the "template" keyword prior to a template-name that was not a
  4437. // dependent name. C++ DR468 relaxed this requirement (the
  4438. // "template" keyword is now permitted). We follow the C++0x
  4439. // rules, even in C++03 mode with a warning, retroactively applying the DR.
  4440. bool MemberOfUnknownSpecialization;
  4441. TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
  4442. ObjectType, EnteringContext, Result,
  4443. MemberOfUnknownSpecialization);
  4444. if (TNK != TNK_Non_template) {
  4445. // We resolved this to a (non-dependent) template name. Return it.
  4446. auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
  4447. if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&
  4448. Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
  4449. Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
  4450. // C++14 [class.qual]p2:
  4451. // In a lookup in which function names are not ignored and the
  4452. // nested-name-specifier nominates a class C, if the name specified
  4453. // [...] is the injected-class-name of C, [...] the name is instead
  4454. // considered to name the constructor
  4455. //
  4456. // We don't get here if naming the constructor would be valid, so we
  4457. // just reject immediately and recover by treating the
  4458. // injected-class-name as naming the template.
  4459. Diag(Name.getBeginLoc(),
  4460. diag::ext_out_of_line_qualified_id_type_names_constructor)
  4461. << Name.Identifier
  4462. << 0 /*injected-class-name used as template name*/
  4463. << TemplateKWLoc.isValid();
  4464. }
  4465. return TNK;
  4466. }
  4467. if (!MemberOfUnknownSpecialization) {
  4468. // Didn't find a template name, and the lookup wasn't dependent.
  4469. // Do the lookup again to determine if this is a "nothing found" case or
  4470. // a "not a template" case. FIXME: Refactor isTemplateName so we don't
  4471. // need to do this.
  4472. DeclarationNameInfo DNI = GetNameFromUnqualifiedId(Name);
  4473. LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
  4474. LookupOrdinaryName);
  4475. bool MOUS;
  4476. // Tell LookupTemplateName that we require a template so that it diagnoses
  4477. // cases where it finds a non-template.
  4478. RequiredTemplateKind RTK = TemplateKWLoc.isValid()
  4479. ? RequiredTemplateKind(TemplateKWLoc)
  4480. : TemplateNameIsRequired;
  4481. if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext, MOUS,
  4482. RTK, nullptr, /*AllowTypoCorrection=*/false) &&
  4483. !R.isAmbiguous()) {
  4484. if (LookupCtx)
  4485. Diag(Name.getBeginLoc(), diag::err_no_member)
  4486. << DNI.getName() << LookupCtx << SS.getRange();
  4487. else
  4488. Diag(Name.getBeginLoc(), diag::err_undeclared_use)
  4489. << DNI.getName() << SS.getRange();
  4490. }
  4491. return TNK_Non_template;
  4492. }
  4493. NestedNameSpecifier *Qualifier = SS.getScopeRep();
  4494. switch (Name.getKind()) {
  4495. case UnqualifiedIdKind::IK_Identifier:
  4496. Result = TemplateTy::make(
  4497. Context.getDependentTemplateName(Qualifier, Name.Identifier));
  4498. return TNK_Dependent_template_name;
  4499. case UnqualifiedIdKind::IK_OperatorFunctionId:
  4500. Result = TemplateTy::make(Context.getDependentTemplateName(
  4501. Qualifier, Name.OperatorFunctionId.Operator));
  4502. return TNK_Function_template;
  4503. case UnqualifiedIdKind::IK_LiteralOperatorId:
  4504. // This is a kind of template name, but can never occur in a dependent
  4505. // scope (literal operators can only be declared at namespace scope).
  4506. break;
  4507. default:
  4508. break;
  4509. }
  4510. // This name cannot possibly name a dependent template. Diagnose this now
  4511. // rather than building a dependent template name that can never be valid.
  4512. Diag(Name.getBeginLoc(),
  4513. diag::err_template_kw_refers_to_dependent_non_template)
  4514. << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()
  4515. << TemplateKWLoc.isValid() << TemplateKWLoc;
  4516. return TNK_Non_template;
  4517. }
  4518. bool Sema::CheckTemplateTypeArgument(
  4519. TemplateTypeParmDecl *Param, TemplateArgumentLoc &AL,
  4520. SmallVectorImpl<TemplateArgument> &SugaredConverted,
  4521. SmallVectorImpl<TemplateArgument> &CanonicalConverted) {
  4522. const TemplateArgument &Arg = AL.getArgument();
  4523. QualType ArgType;
  4524. TypeSourceInfo *TSI = nullptr;
  4525. // Check template type parameter.
  4526. switch(Arg.getKind()) {
  4527. case TemplateArgument::Type:
  4528. // C++ [temp.arg.type]p1:
  4529. // A template-argument for a template-parameter which is a
  4530. // type shall be a type-id.
  4531. ArgType = Arg.getAsType();
  4532. TSI = AL.getTypeSourceInfo();
  4533. break;
  4534. case TemplateArgument::Template:
  4535. case TemplateArgument::TemplateExpansion: {
  4536. // We have a template type parameter but the template argument
  4537. // is a template without any arguments.
  4538. SourceRange SR = AL.getSourceRange();
  4539. TemplateName Name = Arg.getAsTemplateOrTemplatePattern();
  4540. diagnoseMissingTemplateArguments(Name, SR.getEnd());
  4541. return true;
  4542. }
  4543. case TemplateArgument::Expression: {
  4544. // We have a template type parameter but the template argument is an
  4545. // expression; see if maybe it is missing the "typename" keyword.
  4546. CXXScopeSpec SS;
  4547. DeclarationNameInfo NameInfo;
  4548. if (DependentScopeDeclRefExpr *ArgExpr =
  4549. dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
  4550. SS.Adopt(ArgExpr->getQualifierLoc());
  4551. NameInfo = ArgExpr->getNameInfo();
  4552. } else if (CXXDependentScopeMemberExpr *ArgExpr =
  4553. dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
  4554. if (ArgExpr->isImplicitAccess()) {
  4555. SS.Adopt(ArgExpr->getQualifierLoc());
  4556. NameInfo = ArgExpr->getMemberNameInfo();
  4557. }
  4558. }
  4559. if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
  4560. LookupResult Result(*this, NameInfo, LookupOrdinaryName);
  4561. LookupParsedName(Result, CurScope, &SS);
  4562. if (Result.getAsSingle<TypeDecl>() ||
  4563. Result.getResultKind() ==
  4564. LookupResult::NotFoundInCurrentInstantiation) {
  4565. assert(SS.getScopeRep() && "dependent scope expr must has a scope!");
  4566. // Suggest that the user add 'typename' before the NNS.
  4567. SourceLocation Loc = AL.getSourceRange().getBegin();
  4568. Diag(Loc, getLangOpts().MSVCCompat
  4569. ? diag::ext_ms_template_type_arg_missing_typename
  4570. : diag::err_template_arg_must_be_type_suggest)
  4571. << FixItHint::CreateInsertion(Loc, "typename ");
  4572. Diag(Param->getLocation(), diag::note_template_param_here);
  4573. // Recover by synthesizing a type using the location information that we
  4574. // already have.
  4575. ArgType =
  4576. Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
  4577. TypeLocBuilder TLB;
  4578. DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
  4579. TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
  4580. TL.setQualifierLoc(SS.getWithLocInContext(Context));
  4581. TL.setNameLoc(NameInfo.getLoc());
  4582. TSI = TLB.getTypeSourceInfo(Context, ArgType);
  4583. // Overwrite our input TemplateArgumentLoc so that we can recover
  4584. // properly.
  4585. AL = TemplateArgumentLoc(TemplateArgument(ArgType),
  4586. TemplateArgumentLocInfo(TSI));
  4587. break;
  4588. }
  4589. }
  4590. // fallthrough
  4591. [[fallthrough]];
  4592. }
  4593. default: {
  4594. // We have a template type parameter but the template argument
  4595. // is not a type.
  4596. SourceRange SR = AL.getSourceRange();
  4597. Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
  4598. Diag(Param->getLocation(), diag::note_template_param_here);
  4599. return true;
  4600. }
  4601. }
  4602. if (CheckTemplateArgument(TSI))
  4603. return true;
  4604. // Objective-C ARC:
  4605. // If an explicitly-specified template argument type is a lifetime type
  4606. // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
  4607. if (getLangOpts().ObjCAutoRefCount &&
  4608. ArgType->isObjCLifetimeType() &&
  4609. !ArgType.getObjCLifetime()) {
  4610. Qualifiers Qs;
  4611. Qs.setObjCLifetime(Qualifiers::OCL_Strong);
  4612. ArgType = Context.getQualifiedType(ArgType, Qs);
  4613. }
  4614. SugaredConverted.push_back(TemplateArgument(ArgType));
  4615. CanonicalConverted.push_back(
  4616. TemplateArgument(Context.getCanonicalType(ArgType)));
  4617. return false;
  4618. }
  4619. /// Substitute template arguments into the default template argument for
  4620. /// the given template type parameter.
  4621. ///
  4622. /// \param SemaRef the semantic analysis object for which we are performing
  4623. /// the substitution.
  4624. ///
  4625. /// \param Template the template that we are synthesizing template arguments
  4626. /// for.
  4627. ///
  4628. /// \param TemplateLoc the location of the template name that started the
  4629. /// template-id we are checking.
  4630. ///
  4631. /// \param RAngleLoc the location of the right angle bracket ('>') that
  4632. /// terminates the template-id.
  4633. ///
  4634. /// \param Param the template template parameter whose default we are
  4635. /// substituting into.
  4636. ///
  4637. /// \param Converted the list of template arguments provided for template
  4638. /// parameters that precede \p Param in the template parameter list.
  4639. /// \returns the substituted template argument, or NULL if an error occurred.
  4640. static TypeSourceInfo *SubstDefaultTemplateArgument(
  4641. Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
  4642. SourceLocation RAngleLoc, TemplateTypeParmDecl *Param,
  4643. ArrayRef<TemplateArgument> SugaredConverted,
  4644. ArrayRef<TemplateArgument> CanonicalConverted) {
  4645. TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
  4646. // If the argument type is dependent, instantiate it now based
  4647. // on the previously-computed template arguments.
  4648. if (ArgType->getType()->isInstantiationDependentType()) {
  4649. Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
  4650. SugaredConverted,
  4651. SourceRange(TemplateLoc, RAngleLoc));
  4652. if (Inst.isInvalid())
  4653. return nullptr;
  4654. // Only substitute for the innermost template argument list.
  4655. MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
  4656. /*Final=*/true);
  4657. for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
  4658. TemplateArgLists.addOuterTemplateArguments(std::nullopt);
  4659. bool ForLambdaCallOperator = false;
  4660. if (const auto *Rec = dyn_cast<CXXRecordDecl>(Template->getDeclContext()))
  4661. ForLambdaCallOperator = Rec->isLambda();
  4662. Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(),
  4663. !ForLambdaCallOperator);
  4664. ArgType =
  4665. SemaRef.SubstType(ArgType, TemplateArgLists,
  4666. Param->getDefaultArgumentLoc(), Param->getDeclName());
  4667. }
  4668. return ArgType;
  4669. }
  4670. /// Substitute template arguments into the default template argument for
  4671. /// the given non-type template parameter.
  4672. ///
  4673. /// \param SemaRef the semantic analysis object for which we are performing
  4674. /// the substitution.
  4675. ///
  4676. /// \param Template the template that we are synthesizing template arguments
  4677. /// for.
  4678. ///
  4679. /// \param TemplateLoc the location of the template name that started the
  4680. /// template-id we are checking.
  4681. ///
  4682. /// \param RAngleLoc the location of the right angle bracket ('>') that
  4683. /// terminates the template-id.
  4684. ///
  4685. /// \param Param the non-type template parameter whose default we are
  4686. /// substituting into.
  4687. ///
  4688. /// \param Converted the list of template arguments provided for template
  4689. /// parameters that precede \p Param in the template parameter list.
  4690. ///
  4691. /// \returns the substituted template argument, or NULL if an error occurred.
  4692. static ExprResult SubstDefaultTemplateArgument(
  4693. Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
  4694. SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param,
  4695. ArrayRef<TemplateArgument> SugaredConverted,
  4696. ArrayRef<TemplateArgument> CanonicalConverted) {
  4697. Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
  4698. SugaredConverted,
  4699. SourceRange(TemplateLoc, RAngleLoc));
  4700. if (Inst.isInvalid())
  4701. return ExprError();
  4702. // Only substitute for the innermost template argument list.
  4703. MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
  4704. /*Final=*/true);
  4705. for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
  4706. TemplateArgLists.addOuterTemplateArguments(std::nullopt);
  4707. Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
  4708. EnterExpressionEvaluationContext ConstantEvaluated(
  4709. SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  4710. return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
  4711. }
  4712. /// Substitute template arguments into the default template argument for
  4713. /// the given template template parameter.
  4714. ///
  4715. /// \param SemaRef the semantic analysis object for which we are performing
  4716. /// the substitution.
  4717. ///
  4718. /// \param Template the template that we are synthesizing template arguments
  4719. /// for.
  4720. ///
  4721. /// \param TemplateLoc the location of the template name that started the
  4722. /// template-id we are checking.
  4723. ///
  4724. /// \param RAngleLoc the location of the right angle bracket ('>') that
  4725. /// terminates the template-id.
  4726. ///
  4727. /// \param Param the template template parameter whose default we are
  4728. /// substituting into.
  4729. ///
  4730. /// \param Converted the list of template arguments provided for template
  4731. /// parameters that precede \p Param in the template parameter list.
  4732. ///
  4733. /// \param QualifierLoc Will be set to the nested-name-specifier (with
  4734. /// source-location information) that precedes the template name.
  4735. ///
  4736. /// \returns the substituted template argument, or NULL if an error occurred.
  4737. static TemplateName SubstDefaultTemplateArgument(
  4738. Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
  4739. SourceLocation RAngleLoc, TemplateTemplateParmDecl *Param,
  4740. ArrayRef<TemplateArgument> SugaredConverted,
  4741. ArrayRef<TemplateArgument> CanonicalConverted,
  4742. NestedNameSpecifierLoc &QualifierLoc) {
  4743. Sema::InstantiatingTemplate Inst(
  4744. SemaRef, TemplateLoc, TemplateParameter(Param), Template,
  4745. SugaredConverted, SourceRange(TemplateLoc, RAngleLoc));
  4746. if (Inst.isInvalid())
  4747. return TemplateName();
  4748. // Only substitute for the innermost template argument list.
  4749. MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
  4750. /*Final=*/true);
  4751. for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
  4752. TemplateArgLists.addOuterTemplateArguments(std::nullopt);
  4753. Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
  4754. // Substitute into the nested-name-specifier first,
  4755. QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
  4756. if (QualifierLoc) {
  4757. QualifierLoc =
  4758. SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
  4759. if (!QualifierLoc)
  4760. return TemplateName();
  4761. }
  4762. return SemaRef.SubstTemplateName(
  4763. QualifierLoc,
  4764. Param->getDefaultArgument().getArgument().getAsTemplate(),
  4765. Param->getDefaultArgument().getTemplateNameLoc(),
  4766. TemplateArgLists);
  4767. }
  4768. /// If the given template parameter has a default template
  4769. /// argument, substitute into that default template argument and
  4770. /// return the corresponding template argument.
  4771. TemplateArgumentLoc Sema::SubstDefaultTemplateArgumentIfAvailable(
  4772. TemplateDecl *Template, SourceLocation TemplateLoc,
  4773. SourceLocation RAngleLoc, Decl *Param,
  4774. ArrayRef<TemplateArgument> SugaredConverted,
  4775. ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) {
  4776. HasDefaultArg = false;
  4777. if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
  4778. if (!hasReachableDefaultArgument(TypeParm))
  4779. return TemplateArgumentLoc();
  4780. HasDefaultArg = true;
  4781. TypeSourceInfo *DI = SubstDefaultTemplateArgument(
  4782. *this, Template, TemplateLoc, RAngleLoc, TypeParm, SugaredConverted,
  4783. CanonicalConverted);
  4784. if (DI)
  4785. return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
  4786. return TemplateArgumentLoc();
  4787. }
  4788. if (NonTypeTemplateParmDecl *NonTypeParm
  4789. = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
  4790. if (!hasReachableDefaultArgument(NonTypeParm))
  4791. return TemplateArgumentLoc();
  4792. HasDefaultArg = true;
  4793. ExprResult Arg = SubstDefaultTemplateArgument(
  4794. *this, Template, TemplateLoc, RAngleLoc, NonTypeParm, SugaredConverted,
  4795. CanonicalConverted);
  4796. if (Arg.isInvalid())
  4797. return TemplateArgumentLoc();
  4798. Expr *ArgE = Arg.getAs<Expr>();
  4799. return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
  4800. }
  4801. TemplateTemplateParmDecl *TempTempParm
  4802. = cast<TemplateTemplateParmDecl>(Param);
  4803. if (!hasReachableDefaultArgument(TempTempParm))
  4804. return TemplateArgumentLoc();
  4805. HasDefaultArg = true;
  4806. NestedNameSpecifierLoc QualifierLoc;
  4807. TemplateName TName = SubstDefaultTemplateArgument(
  4808. *this, Template, TemplateLoc, RAngleLoc, TempTempParm, SugaredConverted,
  4809. CanonicalConverted, QualifierLoc);
  4810. if (TName.isNull())
  4811. return TemplateArgumentLoc();
  4812. return TemplateArgumentLoc(
  4813. Context, TemplateArgument(TName),
  4814. TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
  4815. TempTempParm->getDefaultArgument().getTemplateNameLoc());
  4816. }
  4817. /// Convert a template-argument that we parsed as a type into a template, if
  4818. /// possible. C++ permits injected-class-names to perform dual service as
  4819. /// template template arguments and as template type arguments.
  4820. static TemplateArgumentLoc
  4821. convertTypeTemplateArgumentToTemplate(ASTContext &Context, TypeLoc TLoc) {
  4822. // Extract and step over any surrounding nested-name-specifier.
  4823. NestedNameSpecifierLoc QualLoc;
  4824. if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
  4825. if (ETLoc.getTypePtr()->getKeyword() != ETK_None)
  4826. return TemplateArgumentLoc();
  4827. QualLoc = ETLoc.getQualifierLoc();
  4828. TLoc = ETLoc.getNamedTypeLoc();
  4829. }
  4830. // If this type was written as an injected-class-name, it can be used as a
  4831. // template template argument.
  4832. if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
  4833. return TemplateArgumentLoc(Context, InjLoc.getTypePtr()->getTemplateName(),
  4834. QualLoc, InjLoc.getNameLoc());
  4835. // If this type was written as an injected-class-name, it may have been
  4836. // converted to a RecordType during instantiation. If the RecordType is
  4837. // *not* wrapped in a TemplateSpecializationType and denotes a class
  4838. // template specialization, it must have come from an injected-class-name.
  4839. if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
  4840. if (auto *CTSD =
  4841. dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
  4842. return TemplateArgumentLoc(Context,
  4843. TemplateName(CTSD->getSpecializedTemplate()),
  4844. QualLoc, RecLoc.getNameLoc());
  4845. return TemplateArgumentLoc();
  4846. }
  4847. /// Check that the given template argument corresponds to the given
  4848. /// template parameter.
  4849. ///
  4850. /// \param Param The template parameter against which the argument will be
  4851. /// checked.
  4852. ///
  4853. /// \param Arg The template argument, which may be updated due to conversions.
  4854. ///
  4855. /// \param Template The template in which the template argument resides.
  4856. ///
  4857. /// \param TemplateLoc The location of the template name for the template
  4858. /// whose argument list we're matching.
  4859. ///
  4860. /// \param RAngleLoc The location of the right angle bracket ('>') that closes
  4861. /// the template argument list.
  4862. ///
  4863. /// \param ArgumentPackIndex The index into the argument pack where this
  4864. /// argument will be placed. Only valid if the parameter is a parameter pack.
  4865. ///
  4866. /// \param Converted The checked, converted argument will be added to the
  4867. /// end of this small vector.
  4868. ///
  4869. /// \param CTAK Describes how we arrived at this particular template argument:
  4870. /// explicitly written, deduced, etc.
  4871. ///
  4872. /// \returns true on error, false otherwise.
  4873. bool Sema::CheckTemplateArgument(
  4874. NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template,
  4875. SourceLocation TemplateLoc, SourceLocation RAngleLoc,
  4876. unsigned ArgumentPackIndex,
  4877. SmallVectorImpl<TemplateArgument> &SugaredConverted,
  4878. SmallVectorImpl<TemplateArgument> &CanonicalConverted,
  4879. CheckTemplateArgumentKind CTAK) {
  4880. // Check template type parameters.
  4881. if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
  4882. return CheckTemplateTypeArgument(TTP, Arg, SugaredConverted,
  4883. CanonicalConverted);
  4884. // Check non-type template parameters.
  4885. if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
  4886. // Do substitution on the type of the non-type template parameter
  4887. // with the template arguments we've seen thus far. But if the
  4888. // template has a dependent context then we cannot substitute yet.
  4889. QualType NTTPType = NTTP->getType();
  4890. if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
  4891. NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
  4892. if (NTTPType->isInstantiationDependentType() &&
  4893. !isa<TemplateTemplateParmDecl>(Template) &&
  4894. !Template->getDeclContext()->isDependentContext()) {
  4895. // Do substitution on the type of the non-type template parameter.
  4896. InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP,
  4897. SugaredConverted,
  4898. SourceRange(TemplateLoc, RAngleLoc));
  4899. if (Inst.isInvalid())
  4900. return true;
  4901. MultiLevelTemplateArgumentList MLTAL(Template, SugaredConverted,
  4902. /*Final=*/true);
  4903. // If the parameter is a pack expansion, expand this slice of the pack.
  4904. if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
  4905. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this,
  4906. ArgumentPackIndex);
  4907. NTTPType = SubstType(PET->getPattern(), MLTAL, NTTP->getLocation(),
  4908. NTTP->getDeclName());
  4909. } else {
  4910. NTTPType = SubstType(NTTPType, MLTAL, NTTP->getLocation(),
  4911. NTTP->getDeclName());
  4912. }
  4913. // If that worked, check the non-type template parameter type
  4914. // for validity.
  4915. if (!NTTPType.isNull())
  4916. NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
  4917. NTTP->getLocation());
  4918. if (NTTPType.isNull())
  4919. return true;
  4920. }
  4921. switch (Arg.getArgument().getKind()) {
  4922. case TemplateArgument::Null:
  4923. llvm_unreachable("Should never see a NULL template argument here");
  4924. case TemplateArgument::Expression: {
  4925. Expr *E = Arg.getArgument().getAsExpr();
  4926. TemplateArgument SugaredResult, CanonicalResult;
  4927. unsigned CurSFINAEErrors = NumSFINAEErrors;
  4928. ExprResult Res = CheckTemplateArgument(NTTP, NTTPType, E, SugaredResult,
  4929. CanonicalResult, CTAK);
  4930. if (Res.isInvalid())
  4931. return true;
  4932. // If the current template argument causes an error, give up now.
  4933. if (CurSFINAEErrors < NumSFINAEErrors)
  4934. return true;
  4935. // If the resulting expression is new, then use it in place of the
  4936. // old expression in the template argument.
  4937. if (Res.get() != E) {
  4938. TemplateArgument TA(Res.get());
  4939. Arg = TemplateArgumentLoc(TA, Res.get());
  4940. }
  4941. SugaredConverted.push_back(SugaredResult);
  4942. CanonicalConverted.push_back(CanonicalResult);
  4943. break;
  4944. }
  4945. case TemplateArgument::Declaration:
  4946. case TemplateArgument::Integral:
  4947. case TemplateArgument::NullPtr:
  4948. // We've already checked this template argument, so just copy
  4949. // it to the list of converted arguments.
  4950. SugaredConverted.push_back(Arg.getArgument());
  4951. CanonicalConverted.push_back(
  4952. Context.getCanonicalTemplateArgument(Arg.getArgument()));
  4953. break;
  4954. case TemplateArgument::Template:
  4955. case TemplateArgument::TemplateExpansion:
  4956. // We were given a template template argument. It may not be ill-formed;
  4957. // see below.
  4958. if (DependentTemplateName *DTN
  4959. = Arg.getArgument().getAsTemplateOrTemplatePattern()
  4960. .getAsDependentTemplateName()) {
  4961. // We have a template argument such as \c T::template X, which we
  4962. // parsed as a template template argument. However, since we now
  4963. // know that we need a non-type template argument, convert this
  4964. // template name into an expression.
  4965. DeclarationNameInfo NameInfo(DTN->getIdentifier(),
  4966. Arg.getTemplateNameLoc());
  4967. CXXScopeSpec SS;
  4968. SS.Adopt(Arg.getTemplateQualifierLoc());
  4969. // FIXME: the template-template arg was a DependentTemplateName,
  4970. // so it was provided with a template keyword. However, its source
  4971. // location is not stored in the template argument structure.
  4972. SourceLocation TemplateKWLoc;
  4973. ExprResult E = DependentScopeDeclRefExpr::Create(
  4974. Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
  4975. nullptr);
  4976. // If we parsed the template argument as a pack expansion, create a
  4977. // pack expansion expression.
  4978. if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
  4979. E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
  4980. if (E.isInvalid())
  4981. return true;
  4982. }
  4983. TemplateArgument SugaredResult, CanonicalResult;
  4984. E = CheckTemplateArgument(NTTP, NTTPType, E.get(), SugaredResult,
  4985. CanonicalResult, CTAK_Specified);
  4986. if (E.isInvalid())
  4987. return true;
  4988. SugaredConverted.push_back(SugaredResult);
  4989. CanonicalConverted.push_back(CanonicalResult);
  4990. break;
  4991. }
  4992. // We have a template argument that actually does refer to a class
  4993. // template, alias template, or template template parameter, and
  4994. // therefore cannot be a non-type template argument.
  4995. Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
  4996. << Arg.getSourceRange();
  4997. Diag(Param->getLocation(), diag::note_template_param_here);
  4998. return true;
  4999. case TemplateArgument::Type: {
  5000. // We have a non-type template parameter but the template
  5001. // argument is a type.
  5002. // C++ [temp.arg]p2:
  5003. // In a template-argument, an ambiguity between a type-id and
  5004. // an expression is resolved to a type-id, regardless of the
  5005. // form of the corresponding template-parameter.
  5006. //
  5007. // We warn specifically about this case, since it can be rather
  5008. // confusing for users.
  5009. QualType T = Arg.getArgument().getAsType();
  5010. SourceRange SR = Arg.getSourceRange();
  5011. if (T->isFunctionType())
  5012. Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
  5013. else
  5014. Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
  5015. Diag(Param->getLocation(), diag::note_template_param_here);
  5016. return true;
  5017. }
  5018. case TemplateArgument::Pack:
  5019. llvm_unreachable("Caller must expand template argument packs");
  5020. }
  5021. return false;
  5022. }
  5023. // Check template template parameters.
  5024. TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
  5025. TemplateParameterList *Params = TempParm->getTemplateParameters();
  5026. if (TempParm->isExpandedParameterPack())
  5027. Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
  5028. // Substitute into the template parameter list of the template
  5029. // template parameter, since previously-supplied template arguments
  5030. // may appear within the template template parameter.
  5031. //
  5032. // FIXME: Skip this if the parameters aren't instantiation-dependent.
  5033. {
  5034. // Set up a template instantiation context.
  5035. LocalInstantiationScope Scope(*this);
  5036. InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm,
  5037. SugaredConverted,
  5038. SourceRange(TemplateLoc, RAngleLoc));
  5039. if (Inst.isInvalid())
  5040. return true;
  5041. Params =
  5042. SubstTemplateParams(Params, CurContext,
  5043. MultiLevelTemplateArgumentList(
  5044. Template, SugaredConverted, /*Final=*/true),
  5045. /*EvaluateConstraints=*/false);
  5046. if (!Params)
  5047. return true;
  5048. }
  5049. // C++1z [temp.local]p1: (DR1004)
  5050. // When [the injected-class-name] is used [...] as a template-argument for
  5051. // a template template-parameter [...] it refers to the class template
  5052. // itself.
  5053. if (Arg.getArgument().getKind() == TemplateArgument::Type) {
  5054. TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
  5055. Context, Arg.getTypeSourceInfo()->getTypeLoc());
  5056. if (!ConvertedArg.getArgument().isNull())
  5057. Arg = ConvertedArg;
  5058. }
  5059. switch (Arg.getArgument().getKind()) {
  5060. case TemplateArgument::Null:
  5061. llvm_unreachable("Should never see a NULL template argument here");
  5062. case TemplateArgument::Template:
  5063. case TemplateArgument::TemplateExpansion:
  5064. if (CheckTemplateTemplateArgument(TempParm, Params, Arg))
  5065. return true;
  5066. SugaredConverted.push_back(Arg.getArgument());
  5067. CanonicalConverted.push_back(
  5068. Context.getCanonicalTemplateArgument(Arg.getArgument()));
  5069. break;
  5070. case TemplateArgument::Expression:
  5071. case TemplateArgument::Type:
  5072. // We have a template template parameter but the template
  5073. // argument does not refer to a template.
  5074. Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
  5075. << getLangOpts().CPlusPlus11;
  5076. return true;
  5077. case TemplateArgument::Declaration:
  5078. llvm_unreachable("Declaration argument with template template parameter");
  5079. case TemplateArgument::Integral:
  5080. llvm_unreachable("Integral argument with template template parameter");
  5081. case TemplateArgument::NullPtr:
  5082. llvm_unreachable("Null pointer argument with template template parameter");
  5083. case TemplateArgument::Pack:
  5084. llvm_unreachable("Caller must expand template argument packs");
  5085. }
  5086. return false;
  5087. }
  5088. /// Diagnose a missing template argument.
  5089. template<typename TemplateParmDecl>
  5090. static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
  5091. TemplateDecl *TD,
  5092. const TemplateParmDecl *D,
  5093. TemplateArgumentListInfo &Args) {
  5094. // Dig out the most recent declaration of the template parameter; there may be
  5095. // declarations of the template that are more recent than TD.
  5096. D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
  5097. ->getTemplateParameters()
  5098. ->getParam(D->getIndex()));
  5099. // If there's a default argument that's not reachable, diagnose that we're
  5100. // missing a module import.
  5101. llvm::SmallVector<Module*, 8> Modules;
  5102. if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, &Modules)) {
  5103. S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
  5104. D->getDefaultArgumentLoc(), Modules,
  5105. Sema::MissingImportKind::DefaultArgument,
  5106. /*Recover*/true);
  5107. return true;
  5108. }
  5109. // FIXME: If there's a more recent default argument that *is* visible,
  5110. // diagnose that it was declared too late.
  5111. TemplateParameterList *Params = TD->getTemplateParameters();
  5112. S.Diag(Loc, diag::err_template_arg_list_different_arity)
  5113. << /*not enough args*/0
  5114. << (int)S.getTemplateNameKindForDiagnostics(TemplateName(TD))
  5115. << TD;
  5116. S.Diag(TD->getLocation(), diag::note_template_decl_here)
  5117. << Params->getSourceRange();
  5118. return true;
  5119. }
  5120. /// Check that the given template argument list is well-formed
  5121. /// for specializing the given template.
  5122. bool Sema::CheckTemplateArgumentList(
  5123. TemplateDecl *Template, SourceLocation TemplateLoc,
  5124. TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
  5125. SmallVectorImpl<TemplateArgument> &SugaredConverted,
  5126. SmallVectorImpl<TemplateArgument> &CanonicalConverted,
  5127. bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied) {
  5128. if (ConstraintsNotSatisfied)
  5129. *ConstraintsNotSatisfied = false;
  5130. // Make a copy of the template arguments for processing. Only make the
  5131. // changes at the end when successful in matching the arguments to the
  5132. // template.
  5133. TemplateArgumentListInfo NewArgs = TemplateArgs;
  5134. // Make sure we get the template parameter list from the most
  5135. // recent declaration, since that is the only one that is guaranteed to
  5136. // have all the default template argument information.
  5137. TemplateParameterList *Params =
  5138. cast<TemplateDecl>(Template->getMostRecentDecl())
  5139. ->getTemplateParameters();
  5140. SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
  5141. // C++ [temp.arg]p1:
  5142. // [...] The type and form of each template-argument specified in
  5143. // a template-id shall match the type and form specified for the
  5144. // corresponding parameter declared by the template in its
  5145. // template-parameter-list.
  5146. bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
  5147. SmallVector<TemplateArgument, 2> SugaredArgumentPack;
  5148. SmallVector<TemplateArgument, 2> CanonicalArgumentPack;
  5149. unsigned ArgIdx = 0, NumArgs = NewArgs.size();
  5150. LocalInstantiationScope InstScope(*this, true);
  5151. for (TemplateParameterList::iterator Param = Params->begin(),
  5152. ParamEnd = Params->end();
  5153. Param != ParamEnd; /* increment in loop */) {
  5154. // If we have an expanded parameter pack, make sure we don't have too
  5155. // many arguments.
  5156. if (std::optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
  5157. if (*Expansions == SugaredArgumentPack.size()) {
  5158. // We're done with this parameter pack. Pack up its arguments and add
  5159. // them to the list.
  5160. SugaredConverted.push_back(
  5161. TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
  5162. SugaredArgumentPack.clear();
  5163. CanonicalConverted.push_back(
  5164. TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
  5165. CanonicalArgumentPack.clear();
  5166. // This argument is assigned to the next parameter.
  5167. ++Param;
  5168. continue;
  5169. } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
  5170. // Not enough arguments for this parameter pack.
  5171. Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
  5172. << /*not enough args*/0
  5173. << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
  5174. << Template;
  5175. Diag(Template->getLocation(), diag::note_template_decl_here)
  5176. << Params->getSourceRange();
  5177. return true;
  5178. }
  5179. }
  5180. if (ArgIdx < NumArgs) {
  5181. // Check the template argument we were given.
  5182. if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template, TemplateLoc,
  5183. RAngleLoc, SugaredArgumentPack.size(),
  5184. SugaredConverted, CanonicalConverted,
  5185. CTAK_Specified))
  5186. return true;
  5187. bool PackExpansionIntoNonPack =
  5188. NewArgs[ArgIdx].getArgument().isPackExpansion() &&
  5189. (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
  5190. if (PackExpansionIntoNonPack && (isa<TypeAliasTemplateDecl>(Template) ||
  5191. isa<ConceptDecl>(Template))) {
  5192. // Core issue 1430: we have a pack expansion as an argument to an
  5193. // alias template, and it's not part of a parameter pack. This
  5194. // can't be canonicalized, so reject it now.
  5195. // As for concepts - we cannot normalize constraints where this
  5196. // situation exists.
  5197. Diag(NewArgs[ArgIdx].getLocation(),
  5198. diag::err_template_expansion_into_fixed_list)
  5199. << (isa<ConceptDecl>(Template) ? 1 : 0)
  5200. << NewArgs[ArgIdx].getSourceRange();
  5201. Diag((*Param)->getLocation(), diag::note_template_param_here);
  5202. return true;
  5203. }
  5204. // We're now done with this argument.
  5205. ++ArgIdx;
  5206. if ((*Param)->isTemplateParameterPack()) {
  5207. // The template parameter was a template parameter pack, so take the
  5208. // deduced argument and place it on the argument pack. Note that we
  5209. // stay on the same template parameter so that we can deduce more
  5210. // arguments.
  5211. SugaredArgumentPack.push_back(SugaredConverted.pop_back_val());
  5212. CanonicalArgumentPack.push_back(CanonicalConverted.pop_back_val());
  5213. } else {
  5214. // Move to the next template parameter.
  5215. ++Param;
  5216. }
  5217. // If we just saw a pack expansion into a non-pack, then directly convert
  5218. // the remaining arguments, because we don't know what parameters they'll
  5219. // match up with.
  5220. if (PackExpansionIntoNonPack) {
  5221. if (!SugaredArgumentPack.empty()) {
  5222. // If we were part way through filling in an expanded parameter pack,
  5223. // fall back to just producing individual arguments.
  5224. SugaredConverted.insert(SugaredConverted.end(),
  5225. SugaredArgumentPack.begin(),
  5226. SugaredArgumentPack.end());
  5227. SugaredArgumentPack.clear();
  5228. CanonicalConverted.insert(CanonicalConverted.end(),
  5229. CanonicalArgumentPack.begin(),
  5230. CanonicalArgumentPack.end());
  5231. CanonicalArgumentPack.clear();
  5232. }
  5233. while (ArgIdx < NumArgs) {
  5234. const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument();
  5235. SugaredConverted.push_back(Arg);
  5236. CanonicalConverted.push_back(
  5237. Context.getCanonicalTemplateArgument(Arg));
  5238. ++ArgIdx;
  5239. }
  5240. return false;
  5241. }
  5242. continue;
  5243. }
  5244. // If we're checking a partial template argument list, we're done.
  5245. if (PartialTemplateArgs) {
  5246. if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) {
  5247. SugaredConverted.push_back(
  5248. TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
  5249. CanonicalConverted.push_back(
  5250. TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
  5251. }
  5252. return false;
  5253. }
  5254. // If we have a template parameter pack with no more corresponding
  5255. // arguments, just break out now and we'll fill in the argument pack below.
  5256. if ((*Param)->isTemplateParameterPack()) {
  5257. assert(!getExpandedPackSize(*Param) &&
  5258. "Should have dealt with this already");
  5259. // A non-expanded parameter pack before the end of the parameter list
  5260. // only occurs for an ill-formed template parameter list, unless we've
  5261. // got a partial argument list for a function template, so just bail out.
  5262. if (Param + 1 != ParamEnd) {
  5263. assert(
  5264. (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) &&
  5265. "Concept templates must have parameter packs at the end.");
  5266. return true;
  5267. }
  5268. SugaredConverted.push_back(
  5269. TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
  5270. SugaredArgumentPack.clear();
  5271. CanonicalConverted.push_back(
  5272. TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
  5273. CanonicalArgumentPack.clear();
  5274. ++Param;
  5275. continue;
  5276. }
  5277. // Check whether we have a default argument.
  5278. TemplateArgumentLoc Arg;
  5279. // Retrieve the default template argument from the template
  5280. // parameter. For each kind of template parameter, we substitute the
  5281. // template arguments provided thus far and any "outer" template arguments
  5282. // (when the template parameter was part of a nested template) into
  5283. // the default argument.
  5284. if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
  5285. if (!hasReachableDefaultArgument(TTP))
  5286. return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
  5287. NewArgs);
  5288. TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(
  5289. *this, Template, TemplateLoc, RAngleLoc, TTP, SugaredConverted,
  5290. CanonicalConverted);
  5291. if (!ArgType)
  5292. return true;
  5293. Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
  5294. ArgType);
  5295. } else if (NonTypeTemplateParmDecl *NTTP
  5296. = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
  5297. if (!hasReachableDefaultArgument(NTTP))
  5298. return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
  5299. NewArgs);
  5300. ExprResult E = SubstDefaultTemplateArgument(
  5301. *this, Template, TemplateLoc, RAngleLoc, NTTP, SugaredConverted,
  5302. CanonicalConverted);
  5303. if (E.isInvalid())
  5304. return true;
  5305. Expr *Ex = E.getAs<Expr>();
  5306. Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
  5307. } else {
  5308. TemplateTemplateParmDecl *TempParm
  5309. = cast<TemplateTemplateParmDecl>(*Param);
  5310. if (!hasReachableDefaultArgument(TempParm))
  5311. return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
  5312. NewArgs);
  5313. NestedNameSpecifierLoc QualifierLoc;
  5314. TemplateName Name = SubstDefaultTemplateArgument(
  5315. *this, Template, TemplateLoc, RAngleLoc, TempParm, SugaredConverted,
  5316. CanonicalConverted, QualifierLoc);
  5317. if (Name.isNull())
  5318. return true;
  5319. Arg = TemplateArgumentLoc(
  5320. Context, TemplateArgument(Name), QualifierLoc,
  5321. TempParm->getDefaultArgument().getTemplateNameLoc());
  5322. }
  5323. // Introduce an instantiation record that describes where we are using
  5324. // the default template argument. We're not actually instantiating a
  5325. // template here, we just create this object to put a note into the
  5326. // context stack.
  5327. InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param,
  5328. SugaredConverted,
  5329. SourceRange(TemplateLoc, RAngleLoc));
  5330. if (Inst.isInvalid())
  5331. return true;
  5332. // Check the default template argument.
  5333. if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, RAngleLoc, 0,
  5334. SugaredConverted, CanonicalConverted,
  5335. CTAK_Specified))
  5336. return true;
  5337. // Core issue 150 (assumed resolution): if this is a template template
  5338. // parameter, keep track of the default template arguments from the
  5339. // template definition.
  5340. if (isTemplateTemplateParameter)
  5341. NewArgs.addArgument(Arg);
  5342. // Move to the next template parameter and argument.
  5343. ++Param;
  5344. ++ArgIdx;
  5345. }
  5346. // If we're performing a partial argument substitution, allow any trailing
  5347. // pack expansions; they might be empty. This can happen even if
  5348. // PartialTemplateArgs is false (the list of arguments is complete but
  5349. // still dependent).
  5350. if (ArgIdx < NumArgs && CurrentInstantiationScope &&
  5351. CurrentInstantiationScope->getPartiallySubstitutedPack()) {
  5352. while (ArgIdx < NumArgs &&
  5353. NewArgs[ArgIdx].getArgument().isPackExpansion()) {
  5354. const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument();
  5355. SugaredConverted.push_back(Arg);
  5356. CanonicalConverted.push_back(Context.getCanonicalTemplateArgument(Arg));
  5357. }
  5358. }
  5359. // If we have any leftover arguments, then there were too many arguments.
  5360. // Complain and fail.
  5361. if (ArgIdx < NumArgs) {
  5362. Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
  5363. << /*too many args*/1
  5364. << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
  5365. << Template
  5366. << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
  5367. Diag(Template->getLocation(), diag::note_template_decl_here)
  5368. << Params->getSourceRange();
  5369. return true;
  5370. }
  5371. // No problems found with the new argument list, propagate changes back
  5372. // to caller.
  5373. if (UpdateArgsWithConversions)
  5374. TemplateArgs = std::move(NewArgs);
  5375. if (!PartialTemplateArgs) {
  5376. TemplateArgumentList StackTemplateArgs(TemplateArgumentList::OnStack,
  5377. CanonicalConverted);
  5378. // Setup the context/ThisScope for the case where we are needing to
  5379. // re-instantiate constraints outside of normal instantiation.
  5380. DeclContext *NewContext = Template->getDeclContext();
  5381. // If this template is in a template, make sure we extract the templated
  5382. // decl.
  5383. if (auto *TD = dyn_cast<TemplateDecl>(NewContext))
  5384. NewContext = Decl::castToDeclContext(TD->getTemplatedDecl());
  5385. auto *RD = dyn_cast<CXXRecordDecl>(NewContext);
  5386. Qualifiers ThisQuals;
  5387. if (const auto *Method =
  5388. dyn_cast_or_null<CXXMethodDecl>(Template->getTemplatedDecl()))
  5389. ThisQuals = Method->getMethodQualifiers();
  5390. ContextRAII Context(*this, NewContext);
  5391. CXXThisScopeRAII(*this, RD, ThisQuals, RD != nullptr);
  5392. MultiLevelTemplateArgumentList MLTAL = getTemplateInstantiationArgs(
  5393. Template, /*Final=*/false, &StackTemplateArgs,
  5394. /*RelativeToPrimary=*/true,
  5395. /*Pattern=*/nullptr,
  5396. /*ForConceptInstantiation=*/true);
  5397. if (EnsureTemplateArgumentListConstraints(
  5398. Template, MLTAL,
  5399. SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) {
  5400. if (ConstraintsNotSatisfied)
  5401. *ConstraintsNotSatisfied = true;
  5402. return true;
  5403. }
  5404. }
  5405. return false;
  5406. }
  5407. namespace {
  5408. class UnnamedLocalNoLinkageFinder
  5409. : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
  5410. {
  5411. Sema &S;
  5412. SourceRange SR;
  5413. typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
  5414. public:
  5415. UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
  5416. bool Visit(QualType T) {
  5417. return T.isNull() ? false : inherited::Visit(T.getTypePtr());
  5418. }
  5419. #define TYPE(Class, Parent) \
  5420. bool Visit##Class##Type(const Class##Type *);
  5421. #define ABSTRACT_TYPE(Class, Parent) \
  5422. bool Visit##Class##Type(const Class##Type *) { return false; }
  5423. #define NON_CANONICAL_TYPE(Class, Parent) \
  5424. bool Visit##Class##Type(const Class##Type *) { return false; }
  5425. #include "clang/AST/TypeNodes.inc"
  5426. bool VisitTagDecl(const TagDecl *Tag);
  5427. bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
  5428. };
  5429. } // end anonymous namespace
  5430. bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
  5431. return false;
  5432. }
  5433. bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
  5434. return Visit(T->getElementType());
  5435. }
  5436. bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
  5437. return Visit(T->getPointeeType());
  5438. }
  5439. bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
  5440. const BlockPointerType* T) {
  5441. return Visit(T->getPointeeType());
  5442. }
  5443. bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
  5444. const LValueReferenceType* T) {
  5445. return Visit(T->getPointeeType());
  5446. }
  5447. bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
  5448. const RValueReferenceType* T) {
  5449. return Visit(T->getPointeeType());
  5450. }
  5451. bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
  5452. const MemberPointerType* T) {
  5453. return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
  5454. }
  5455. bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
  5456. const ConstantArrayType* T) {
  5457. return Visit(T->getElementType());
  5458. }
  5459. bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
  5460. const IncompleteArrayType* T) {
  5461. return Visit(T->getElementType());
  5462. }
  5463. bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
  5464. const VariableArrayType* T) {
  5465. return Visit(T->getElementType());
  5466. }
  5467. bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
  5468. const DependentSizedArrayType* T) {
  5469. return Visit(T->getElementType());
  5470. }
  5471. bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
  5472. const DependentSizedExtVectorType* T) {
  5473. return Visit(T->getElementType());
  5474. }
  5475. bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType(
  5476. const DependentSizedMatrixType *T) {
  5477. return Visit(T->getElementType());
  5478. }
  5479. bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
  5480. const DependentAddressSpaceType *T) {
  5481. return Visit(T->getPointeeType());
  5482. }
  5483. bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
  5484. return Visit(T->getElementType());
  5485. }
  5486. bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
  5487. const DependentVectorType *T) {
  5488. return Visit(T->getElementType());
  5489. }
  5490. bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
  5491. return Visit(T->getElementType());
  5492. }
  5493. bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType(
  5494. const ConstantMatrixType *T) {
  5495. return Visit(T->getElementType());
  5496. }
  5497. bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
  5498. const FunctionProtoType* T) {
  5499. for (const auto &A : T->param_types()) {
  5500. if (Visit(A))
  5501. return true;
  5502. }
  5503. return Visit(T->getReturnType());
  5504. }
  5505. bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
  5506. const FunctionNoProtoType* T) {
  5507. return Visit(T->getReturnType());
  5508. }
  5509. bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
  5510. const UnresolvedUsingType*) {
  5511. return false;
  5512. }
  5513. bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
  5514. return false;
  5515. }
  5516. bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
  5517. return Visit(T->getUnmodifiedType());
  5518. }
  5519. bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
  5520. return false;
  5521. }
  5522. bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
  5523. const UnaryTransformType*) {
  5524. return false;
  5525. }
  5526. bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
  5527. return Visit(T->getDeducedType());
  5528. }
  5529. bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
  5530. const DeducedTemplateSpecializationType *T) {
  5531. return Visit(T->getDeducedType());
  5532. }
  5533. bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
  5534. return VisitTagDecl(T->getDecl());
  5535. }
  5536. bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
  5537. return VisitTagDecl(T->getDecl());
  5538. }
  5539. bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
  5540. const TemplateTypeParmType*) {
  5541. return false;
  5542. }
  5543. bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
  5544. const SubstTemplateTypeParmPackType *) {
  5545. return false;
  5546. }
  5547. bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
  5548. const TemplateSpecializationType*) {
  5549. return false;
  5550. }
  5551. bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
  5552. const InjectedClassNameType* T) {
  5553. return VisitTagDecl(T->getDecl());
  5554. }
  5555. bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
  5556. const DependentNameType* T) {
  5557. return VisitNestedNameSpecifier(T->getQualifier());
  5558. }
  5559. bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
  5560. const DependentTemplateSpecializationType* T) {
  5561. if (auto *Q = T->getQualifier())
  5562. return VisitNestedNameSpecifier(Q);
  5563. return false;
  5564. }
  5565. bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
  5566. const PackExpansionType* T) {
  5567. return Visit(T->getPattern());
  5568. }
  5569. bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
  5570. return false;
  5571. }
  5572. bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
  5573. const ObjCInterfaceType *) {
  5574. return false;
  5575. }
  5576. bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
  5577. const ObjCObjectPointerType *) {
  5578. return false;
  5579. }
  5580. bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
  5581. return Visit(T->getValueType());
  5582. }
  5583. bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
  5584. return false;
  5585. }
  5586. bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) {
  5587. return false;
  5588. }
  5589. bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType(
  5590. const DependentBitIntType *T) {
  5591. return false;
  5592. }
  5593. bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
  5594. if (Tag->getDeclContext()->isFunctionOrMethod()) {
  5595. S.Diag(SR.getBegin(),
  5596. S.getLangOpts().CPlusPlus11 ?
  5597. diag::warn_cxx98_compat_template_arg_local_type :
  5598. diag::ext_template_arg_local_type)
  5599. << S.Context.getTypeDeclType(Tag) << SR;
  5600. return true;
  5601. }
  5602. if (!Tag->hasNameForLinkage()) {
  5603. S.Diag(SR.getBegin(),
  5604. S.getLangOpts().CPlusPlus11 ?
  5605. diag::warn_cxx98_compat_template_arg_unnamed_type :
  5606. diag::ext_template_arg_unnamed_type) << SR;
  5607. S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
  5608. return true;
  5609. }
  5610. return false;
  5611. }
  5612. bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
  5613. NestedNameSpecifier *NNS) {
  5614. assert(NNS);
  5615. if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
  5616. return true;
  5617. switch (NNS->getKind()) {
  5618. case NestedNameSpecifier::Identifier:
  5619. case NestedNameSpecifier::Namespace:
  5620. case NestedNameSpecifier::NamespaceAlias:
  5621. case NestedNameSpecifier::Global:
  5622. case NestedNameSpecifier::Super:
  5623. return false;
  5624. case NestedNameSpecifier::TypeSpec:
  5625. case NestedNameSpecifier::TypeSpecWithTemplate:
  5626. return Visit(QualType(NNS->getAsType(), 0));
  5627. }
  5628. llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
  5629. }
  5630. /// Check a template argument against its corresponding
  5631. /// template type parameter.
  5632. ///
  5633. /// This routine implements the semantics of C++ [temp.arg.type]. It
  5634. /// returns true if an error occurred, and false otherwise.
  5635. bool Sema::CheckTemplateArgument(TypeSourceInfo *ArgInfo) {
  5636. assert(ArgInfo && "invalid TypeSourceInfo");
  5637. QualType Arg = ArgInfo->getType();
  5638. SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
  5639. QualType CanonArg = Context.getCanonicalType(Arg);
  5640. if (CanonArg->isVariablyModifiedType()) {
  5641. return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
  5642. } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
  5643. return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
  5644. }
  5645. // C++03 [temp.arg.type]p2:
  5646. // A local type, a type with no linkage, an unnamed type or a type
  5647. // compounded from any of these types shall not be used as a
  5648. // template-argument for a template type-parameter.
  5649. //
  5650. // C++11 allows these, and even in C++03 we allow them as an extension with
  5651. // a warning.
  5652. if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) {
  5653. UnnamedLocalNoLinkageFinder Finder(*this, SR);
  5654. (void)Finder.Visit(CanonArg);
  5655. }
  5656. return false;
  5657. }
  5658. enum NullPointerValueKind {
  5659. NPV_NotNullPointer,
  5660. NPV_NullPointer,
  5661. NPV_Error
  5662. };
  5663. /// Determine whether the given template argument is a null pointer
  5664. /// value of the appropriate type.
  5665. static NullPointerValueKind
  5666. isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
  5667. QualType ParamType, Expr *Arg,
  5668. Decl *Entity = nullptr) {
  5669. if (Arg->isValueDependent() || Arg->isTypeDependent())
  5670. return NPV_NotNullPointer;
  5671. // dllimport'd entities aren't constant but are available inside of template
  5672. // arguments.
  5673. if (Entity && Entity->hasAttr<DLLImportAttr>())
  5674. return NPV_NotNullPointer;
  5675. if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
  5676. llvm_unreachable(
  5677. "Incomplete parameter type in isNullPointerValueTemplateArgument!");
  5678. if (!S.getLangOpts().CPlusPlus11)
  5679. return NPV_NotNullPointer;
  5680. // Determine whether we have a constant expression.
  5681. ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
  5682. if (ArgRV.isInvalid())
  5683. return NPV_Error;
  5684. Arg = ArgRV.get();
  5685. Expr::EvalResult EvalResult;
  5686. SmallVector<PartialDiagnosticAt, 8> Notes;
  5687. EvalResult.Diag = &Notes;
  5688. if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
  5689. EvalResult.HasSideEffects) {
  5690. SourceLocation DiagLoc = Arg->getExprLoc();
  5691. // If our only note is the usual "invalid subexpression" note, just point
  5692. // the caret at its location rather than producing an essentially
  5693. // redundant note.
  5694. if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
  5695. diag::note_invalid_subexpr_in_const_expr) {
  5696. DiagLoc = Notes[0].first;
  5697. Notes.clear();
  5698. }
  5699. S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
  5700. << Arg->getType() << Arg->getSourceRange();
  5701. for (unsigned I = 0, N = Notes.size(); I != N; ++I)
  5702. S.Diag(Notes[I].first, Notes[I].second);
  5703. S.Diag(Param->getLocation(), diag::note_template_param_here);
  5704. return NPV_Error;
  5705. }
  5706. // C++11 [temp.arg.nontype]p1:
  5707. // - an address constant expression of type std::nullptr_t
  5708. if (Arg->getType()->isNullPtrType())
  5709. return NPV_NullPointer;
  5710. // - a constant expression that evaluates to a null pointer value (4.10); or
  5711. // - a constant expression that evaluates to a null member pointer value
  5712. // (4.11); or
  5713. if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) ||
  5714. (EvalResult.Val.isMemberPointer() &&
  5715. !EvalResult.Val.getMemberPointerDecl())) {
  5716. // If our expression has an appropriate type, we've succeeded.
  5717. bool ObjCLifetimeConversion;
  5718. if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
  5719. S.IsQualificationConversion(Arg->getType(), ParamType, false,
  5720. ObjCLifetimeConversion))
  5721. return NPV_NullPointer;
  5722. // The types didn't match, but we know we got a null pointer; complain,
  5723. // then recover as if the types were correct.
  5724. S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
  5725. << Arg->getType() << ParamType << Arg->getSourceRange();
  5726. S.Diag(Param->getLocation(), diag::note_template_param_here);
  5727. return NPV_NullPointer;
  5728. }
  5729. if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) {
  5730. // We found a pointer that isn't null, but doesn't refer to an object.
  5731. // We could just return NPV_NotNullPointer, but we can print a better
  5732. // message with the information we have here.
  5733. S.Diag(Arg->getExprLoc(), diag::err_template_arg_invalid)
  5734. << EvalResult.Val.getAsString(S.Context, ParamType);
  5735. S.Diag(Param->getLocation(), diag::note_template_param_here);
  5736. return NPV_Error;
  5737. }
  5738. // If we don't have a null pointer value, but we do have a NULL pointer
  5739. // constant, suggest a cast to the appropriate type.
  5740. if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
  5741. std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
  5742. S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
  5743. << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
  5744. << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getEndLoc()),
  5745. ")");
  5746. S.Diag(Param->getLocation(), diag::note_template_param_here);
  5747. return NPV_NullPointer;
  5748. }
  5749. // FIXME: If we ever want to support general, address-constant expressions
  5750. // as non-type template arguments, we should return the ExprResult here to
  5751. // be interpreted by the caller.
  5752. return NPV_NotNullPointer;
  5753. }
  5754. /// Checks whether the given template argument is compatible with its
  5755. /// template parameter.
  5756. static bool CheckTemplateArgumentIsCompatibleWithParameter(
  5757. Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
  5758. Expr *Arg, QualType ArgType) {
  5759. bool ObjCLifetimeConversion;
  5760. if (ParamType->isPointerType() &&
  5761. !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
  5762. S.IsQualificationConversion(ArgType, ParamType, false,
  5763. ObjCLifetimeConversion)) {
  5764. // For pointer-to-object types, qualification conversions are
  5765. // permitted.
  5766. } else {
  5767. if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
  5768. if (!ParamRef->getPointeeType()->isFunctionType()) {
  5769. // C++ [temp.arg.nontype]p5b3:
  5770. // For a non-type template-parameter of type reference to
  5771. // object, no conversions apply. The type referred to by the
  5772. // reference may be more cv-qualified than the (otherwise
  5773. // identical) type of the template- argument. The
  5774. // template-parameter is bound directly to the
  5775. // template-argument, which shall be an lvalue.
  5776. // FIXME: Other qualifiers?
  5777. unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
  5778. unsigned ArgQuals = ArgType.getCVRQualifiers();
  5779. if ((ParamQuals | ArgQuals) != ParamQuals) {
  5780. S.Diag(Arg->getBeginLoc(),
  5781. diag::err_template_arg_ref_bind_ignores_quals)
  5782. << ParamType << Arg->getType() << Arg->getSourceRange();
  5783. S.Diag(Param->getLocation(), diag::note_template_param_here);
  5784. return true;
  5785. }
  5786. }
  5787. }
  5788. // At this point, the template argument refers to an object or
  5789. // function with external linkage. We now need to check whether the
  5790. // argument and parameter types are compatible.
  5791. if (!S.Context.hasSameUnqualifiedType(ArgType,
  5792. ParamType.getNonReferenceType())) {
  5793. // We can't perform this conversion or binding.
  5794. if (ParamType->isReferenceType())
  5795. S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
  5796. << ParamType << ArgIn->getType() << Arg->getSourceRange();
  5797. else
  5798. S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
  5799. << ArgIn->getType() << ParamType << Arg->getSourceRange();
  5800. S.Diag(Param->getLocation(), diag::note_template_param_here);
  5801. return true;
  5802. }
  5803. }
  5804. return false;
  5805. }
  5806. /// Checks whether the given template argument is the address
  5807. /// of an object or function according to C++ [temp.arg.nontype]p1.
  5808. static bool CheckTemplateArgumentAddressOfObjectOrFunction(
  5809. Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
  5810. TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
  5811. bool Invalid = false;
  5812. Expr *Arg = ArgIn;
  5813. QualType ArgType = Arg->getType();
  5814. bool AddressTaken = false;
  5815. SourceLocation AddrOpLoc;
  5816. if (S.getLangOpts().MicrosoftExt) {
  5817. // Microsoft Visual C++ strips all casts, allows an arbitrary number of
  5818. // dereference and address-of operators.
  5819. Arg = Arg->IgnoreParenCasts();
  5820. bool ExtWarnMSTemplateArg = false;
  5821. UnaryOperatorKind FirstOpKind;
  5822. SourceLocation FirstOpLoc;
  5823. while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
  5824. UnaryOperatorKind UnOpKind = UnOp->getOpcode();
  5825. if (UnOpKind == UO_Deref)
  5826. ExtWarnMSTemplateArg = true;
  5827. if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
  5828. Arg = UnOp->getSubExpr()->IgnoreParenCasts();
  5829. if (!AddrOpLoc.isValid()) {
  5830. FirstOpKind = UnOpKind;
  5831. FirstOpLoc = UnOp->getOperatorLoc();
  5832. }
  5833. } else
  5834. break;
  5835. }
  5836. if (FirstOpLoc.isValid()) {
  5837. if (ExtWarnMSTemplateArg)
  5838. S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
  5839. << ArgIn->getSourceRange();
  5840. if (FirstOpKind == UO_AddrOf)
  5841. AddressTaken = true;
  5842. else if (Arg->getType()->isPointerType()) {
  5843. // We cannot let pointers get dereferenced here, that is obviously not a
  5844. // constant expression.
  5845. assert(FirstOpKind == UO_Deref);
  5846. S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
  5847. << Arg->getSourceRange();
  5848. }
  5849. }
  5850. } else {
  5851. // See through any implicit casts we added to fix the type.
  5852. Arg = Arg->IgnoreImpCasts();
  5853. // C++ [temp.arg.nontype]p1:
  5854. //
  5855. // A template-argument for a non-type, non-template
  5856. // template-parameter shall be one of: [...]
  5857. //
  5858. // -- the address of an object or function with external
  5859. // linkage, including function templates and function
  5860. // template-ids but excluding non-static class members,
  5861. // expressed as & id-expression where the & is optional if
  5862. // the name refers to a function or array, or if the
  5863. // corresponding template-parameter is a reference; or
  5864. // In C++98/03 mode, give an extension warning on any extra parentheses.
  5865. // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
  5866. bool ExtraParens = false;
  5867. while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
  5868. if (!Invalid && !ExtraParens) {
  5869. S.Diag(Arg->getBeginLoc(),
  5870. S.getLangOpts().CPlusPlus11
  5871. ? diag::warn_cxx98_compat_template_arg_extra_parens
  5872. : diag::ext_template_arg_extra_parens)
  5873. << Arg->getSourceRange();
  5874. ExtraParens = true;
  5875. }
  5876. Arg = Parens->getSubExpr();
  5877. }
  5878. while (SubstNonTypeTemplateParmExpr *subst =
  5879. dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
  5880. Arg = subst->getReplacement()->IgnoreImpCasts();
  5881. if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
  5882. if (UnOp->getOpcode() == UO_AddrOf) {
  5883. Arg = UnOp->getSubExpr();
  5884. AddressTaken = true;
  5885. AddrOpLoc = UnOp->getOperatorLoc();
  5886. }
  5887. }
  5888. while (SubstNonTypeTemplateParmExpr *subst =
  5889. dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
  5890. Arg = subst->getReplacement()->IgnoreImpCasts();
  5891. }
  5892. ValueDecl *Entity = nullptr;
  5893. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg))
  5894. Entity = DRE->getDecl();
  5895. else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Arg))
  5896. Entity = CUE->getGuidDecl();
  5897. // If our parameter has pointer type, check for a null template value.
  5898. if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
  5899. switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
  5900. Entity)) {
  5901. case NPV_NullPointer:
  5902. S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
  5903. SugaredConverted = TemplateArgument(ParamType,
  5904. /*isNullPtr=*/true);
  5905. CanonicalConverted =
  5906. TemplateArgument(S.Context.getCanonicalType(ParamType),
  5907. /*isNullPtr=*/true);
  5908. return false;
  5909. case NPV_Error:
  5910. return true;
  5911. case NPV_NotNullPointer:
  5912. break;
  5913. }
  5914. }
  5915. // Stop checking the precise nature of the argument if it is value dependent,
  5916. // it should be checked when instantiated.
  5917. if (Arg->isValueDependent()) {
  5918. SugaredConverted = TemplateArgument(ArgIn);
  5919. CanonicalConverted =
  5920. S.Context.getCanonicalTemplateArgument(SugaredConverted);
  5921. return false;
  5922. }
  5923. if (!Entity) {
  5924. S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
  5925. << Arg->getSourceRange();
  5926. S.Diag(Param->getLocation(), diag::note_template_param_here);
  5927. return true;
  5928. }
  5929. // Cannot refer to non-static data members
  5930. if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
  5931. S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
  5932. << Entity << Arg->getSourceRange();
  5933. S.Diag(Param->getLocation(), diag::note_template_param_here);
  5934. return true;
  5935. }
  5936. // Cannot refer to non-static member functions
  5937. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
  5938. if (!Method->isStatic()) {
  5939. S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
  5940. << Method << Arg->getSourceRange();
  5941. S.Diag(Param->getLocation(), diag::note_template_param_here);
  5942. return true;
  5943. }
  5944. }
  5945. FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
  5946. VarDecl *Var = dyn_cast<VarDecl>(Entity);
  5947. MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Entity);
  5948. // A non-type template argument must refer to an object or function.
  5949. if (!Func && !Var && !Guid) {
  5950. // We found something, but we don't know specifically what it is.
  5951. S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
  5952. << Arg->getSourceRange();
  5953. S.Diag(Entity->getLocation(), diag::note_template_arg_refers_here);
  5954. return true;
  5955. }
  5956. // Address / reference template args must have external linkage in C++98.
  5957. if (Entity->getFormalLinkage() == InternalLinkage) {
  5958. S.Diag(Arg->getBeginLoc(),
  5959. S.getLangOpts().CPlusPlus11
  5960. ? diag::warn_cxx98_compat_template_arg_object_internal
  5961. : diag::ext_template_arg_object_internal)
  5962. << !Func << Entity << Arg->getSourceRange();
  5963. S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
  5964. << !Func;
  5965. } else if (!Entity->hasLinkage()) {
  5966. S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
  5967. << !Func << Entity << Arg->getSourceRange();
  5968. S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
  5969. << !Func;
  5970. return true;
  5971. }
  5972. if (Var) {
  5973. // A value of reference type is not an object.
  5974. if (Var->getType()->isReferenceType()) {
  5975. S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
  5976. << Var->getType() << Arg->getSourceRange();
  5977. S.Diag(Param->getLocation(), diag::note_template_param_here);
  5978. return true;
  5979. }
  5980. // A template argument must have static storage duration.
  5981. if (Var->getTLSKind()) {
  5982. S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
  5983. << Arg->getSourceRange();
  5984. S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
  5985. return true;
  5986. }
  5987. }
  5988. if (AddressTaken && ParamType->isReferenceType()) {
  5989. // If we originally had an address-of operator, but the
  5990. // parameter has reference type, complain and (if things look
  5991. // like they will work) drop the address-of operator.
  5992. if (!S.Context.hasSameUnqualifiedType(Entity->getType(),
  5993. ParamType.getNonReferenceType())) {
  5994. S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
  5995. << ParamType;
  5996. S.Diag(Param->getLocation(), diag::note_template_param_here);
  5997. return true;
  5998. }
  5999. S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
  6000. << ParamType
  6001. << FixItHint::CreateRemoval(AddrOpLoc);
  6002. S.Diag(Param->getLocation(), diag::note_template_param_here);
  6003. ArgType = Entity->getType();
  6004. }
  6005. // If the template parameter has pointer type, either we must have taken the
  6006. // address or the argument must decay to a pointer.
  6007. if (!AddressTaken && ParamType->isPointerType()) {
  6008. if (Func) {
  6009. // Function-to-pointer decay.
  6010. ArgType = S.Context.getPointerType(Func->getType());
  6011. } else if (Entity->getType()->isArrayType()) {
  6012. // Array-to-pointer decay.
  6013. ArgType = S.Context.getArrayDecayedType(Entity->getType());
  6014. } else {
  6015. // If the template parameter has pointer type but the address of
  6016. // this object was not taken, complain and (possibly) recover by
  6017. // taking the address of the entity.
  6018. ArgType = S.Context.getPointerType(Entity->getType());
  6019. if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
  6020. S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
  6021. << ParamType;
  6022. S.Diag(Param->getLocation(), diag::note_template_param_here);
  6023. return true;
  6024. }
  6025. S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
  6026. << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
  6027. S.Diag(Param->getLocation(), diag::note_template_param_here);
  6028. }
  6029. }
  6030. if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
  6031. Arg, ArgType))
  6032. return true;
  6033. // Create the template argument.
  6034. SugaredConverted = TemplateArgument(Entity, ParamType);
  6035. CanonicalConverted =
  6036. TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()),
  6037. S.Context.getCanonicalType(ParamType));
  6038. S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);
  6039. return false;
  6040. }
  6041. /// Checks whether the given template argument is a pointer to
  6042. /// member constant according to C++ [temp.arg.nontype]p1.
  6043. static bool
  6044. CheckTemplateArgumentPointerToMember(Sema &S, NonTypeTemplateParmDecl *Param,
  6045. QualType ParamType, Expr *&ResultArg,
  6046. TemplateArgument &SugaredConverted,
  6047. TemplateArgument &CanonicalConverted) {
  6048. bool Invalid = false;
  6049. Expr *Arg = ResultArg;
  6050. bool ObjCLifetimeConversion;
  6051. // C++ [temp.arg.nontype]p1:
  6052. //
  6053. // A template-argument for a non-type, non-template
  6054. // template-parameter shall be one of: [...]
  6055. //
  6056. // -- a pointer to member expressed as described in 5.3.1.
  6057. DeclRefExpr *DRE = nullptr;
  6058. // In C++98/03 mode, give an extension warning on any extra parentheses.
  6059. // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
  6060. bool ExtraParens = false;
  6061. while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
  6062. if (!Invalid && !ExtraParens) {
  6063. S.Diag(Arg->getBeginLoc(),
  6064. S.getLangOpts().CPlusPlus11
  6065. ? diag::warn_cxx98_compat_template_arg_extra_parens
  6066. : diag::ext_template_arg_extra_parens)
  6067. << Arg->getSourceRange();
  6068. ExtraParens = true;
  6069. }
  6070. Arg = Parens->getSubExpr();
  6071. }
  6072. while (SubstNonTypeTemplateParmExpr *subst =
  6073. dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
  6074. Arg = subst->getReplacement()->IgnoreImpCasts();
  6075. // A pointer-to-member constant written &Class::member.
  6076. if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
  6077. if (UnOp->getOpcode() == UO_AddrOf) {
  6078. DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
  6079. if (DRE && !DRE->getQualifier())
  6080. DRE = nullptr;
  6081. }
  6082. }
  6083. // A constant of pointer-to-member type.
  6084. else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
  6085. ValueDecl *VD = DRE->getDecl();
  6086. if (VD->getType()->isMemberPointerType()) {
  6087. if (isa<NonTypeTemplateParmDecl>(VD)) {
  6088. if (Arg->isTypeDependent() || Arg->isValueDependent()) {
  6089. SugaredConverted = TemplateArgument(Arg);
  6090. CanonicalConverted =
  6091. S.Context.getCanonicalTemplateArgument(SugaredConverted);
  6092. } else {
  6093. SugaredConverted = TemplateArgument(VD, ParamType);
  6094. CanonicalConverted =
  6095. TemplateArgument(cast<ValueDecl>(VD->getCanonicalDecl()),
  6096. S.Context.getCanonicalType(ParamType));
  6097. }
  6098. return Invalid;
  6099. }
  6100. }
  6101. DRE = nullptr;
  6102. }
  6103. ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
  6104. // Check for a null pointer value.
  6105. switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
  6106. Entity)) {
  6107. case NPV_Error:
  6108. return true;
  6109. case NPV_NullPointer:
  6110. S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
  6111. SugaredConverted = TemplateArgument(ParamType,
  6112. /*isNullPtr*/ true);
  6113. CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(ParamType),
  6114. /*isNullPtr*/ true);
  6115. return false;
  6116. case NPV_NotNullPointer:
  6117. break;
  6118. }
  6119. if (S.IsQualificationConversion(ResultArg->getType(),
  6120. ParamType.getNonReferenceType(), false,
  6121. ObjCLifetimeConversion)) {
  6122. ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
  6123. ResultArg->getValueKind())
  6124. .get();
  6125. } else if (!S.Context.hasSameUnqualifiedType(
  6126. ResultArg->getType(), ParamType.getNonReferenceType())) {
  6127. // We can't perform this conversion.
  6128. S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
  6129. << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
  6130. S.Diag(Param->getLocation(), diag::note_template_param_here);
  6131. return true;
  6132. }
  6133. if (!DRE)
  6134. return S.Diag(Arg->getBeginLoc(),
  6135. diag::err_template_arg_not_pointer_to_member_form)
  6136. << Arg->getSourceRange();
  6137. if (isa<FieldDecl>(DRE->getDecl()) ||
  6138. isa<IndirectFieldDecl>(DRE->getDecl()) ||
  6139. isa<CXXMethodDecl>(DRE->getDecl())) {
  6140. assert((isa<FieldDecl>(DRE->getDecl()) ||
  6141. isa<IndirectFieldDecl>(DRE->getDecl()) ||
  6142. !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
  6143. "Only non-static member pointers can make it here");
  6144. // Okay: this is the address of a non-static member, and therefore
  6145. // a member pointer constant.
  6146. if (Arg->isTypeDependent() || Arg->isValueDependent()) {
  6147. SugaredConverted = TemplateArgument(Arg);
  6148. CanonicalConverted =
  6149. S.Context.getCanonicalTemplateArgument(SugaredConverted);
  6150. } else {
  6151. ValueDecl *D = DRE->getDecl();
  6152. SugaredConverted = TemplateArgument(D, ParamType);
  6153. CanonicalConverted =
  6154. TemplateArgument(cast<ValueDecl>(D->getCanonicalDecl()),
  6155. S.Context.getCanonicalType(ParamType));
  6156. }
  6157. return Invalid;
  6158. }
  6159. // We found something else, but we don't know specifically what it is.
  6160. S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
  6161. << Arg->getSourceRange();
  6162. S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
  6163. return true;
  6164. }
  6165. /// Check a template argument against its corresponding
  6166. /// non-type template parameter.
  6167. ///
  6168. /// This routine implements the semantics of C++ [temp.arg.nontype].
  6169. /// If an error occurred, it returns ExprError(); otherwise, it
  6170. /// returns the converted template argument. \p ParamType is the
  6171. /// type of the non-type template parameter after it has been instantiated.
  6172. ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
  6173. QualType ParamType, Expr *Arg,
  6174. TemplateArgument &SugaredConverted,
  6175. TemplateArgument &CanonicalConverted,
  6176. CheckTemplateArgumentKind CTAK) {
  6177. SourceLocation StartLoc = Arg->getBeginLoc();
  6178. // If the parameter type somehow involves auto, deduce the type now.
  6179. DeducedType *DeducedT = ParamType->getContainedDeducedType();
  6180. if (getLangOpts().CPlusPlus17 && DeducedT && !DeducedT->isDeduced()) {
  6181. // During template argument deduction, we allow 'decltype(auto)' to
  6182. // match an arbitrary dependent argument.
  6183. // FIXME: The language rules don't say what happens in this case.
  6184. // FIXME: We get an opaque dependent type out of decltype(auto) if the
  6185. // expression is merely instantiation-dependent; is this enough?
  6186. if (CTAK == CTAK_Deduced && Arg->isTypeDependent()) {
  6187. auto *AT = dyn_cast<AutoType>(DeducedT);
  6188. if (AT && AT->isDecltypeAuto()) {
  6189. SugaredConverted = TemplateArgument(Arg);
  6190. CanonicalConverted = TemplateArgument(
  6191. Context.getCanonicalTemplateArgument(SugaredConverted));
  6192. return Arg;
  6193. }
  6194. }
  6195. // When checking a deduced template argument, deduce from its type even if
  6196. // the type is dependent, in order to check the types of non-type template
  6197. // arguments line up properly in partial ordering.
  6198. Expr *DeductionArg = Arg;
  6199. if (auto *PE = dyn_cast<PackExpansionExpr>(DeductionArg))
  6200. DeductionArg = PE->getPattern();
  6201. TypeSourceInfo *TSI =
  6202. Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation());
  6203. if (isa<DeducedTemplateSpecializationType>(DeducedT)) {
  6204. InitializedEntity Entity =
  6205. InitializedEntity::InitializeTemplateParameter(ParamType, Param);
  6206. InitializationKind Kind = InitializationKind::CreateForInit(
  6207. DeductionArg->getBeginLoc(), /*DirectInit*/false, DeductionArg);
  6208. Expr *Inits[1] = {DeductionArg};
  6209. ParamType =
  6210. DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, Inits);
  6211. if (ParamType.isNull())
  6212. return ExprError();
  6213. } else {
  6214. TemplateDeductionInfo Info(DeductionArg->getExprLoc(),
  6215. Param->getDepth() + 1);
  6216. ParamType = QualType();
  6217. TemplateDeductionResult Result =
  6218. DeduceAutoType(TSI->getTypeLoc(), DeductionArg, ParamType, Info,
  6219. /*DependentDeduction=*/true,
  6220. // We do not check constraints right now because the
  6221. // immediately-declared constraint of the auto type is
  6222. // also an associated constraint, and will be checked
  6223. // along with the other associated constraints after
  6224. // checking the template argument list.
  6225. /*IgnoreConstraints=*/true);
  6226. if (Result == TDK_AlreadyDiagnosed) {
  6227. if (ParamType.isNull())
  6228. return ExprError();
  6229. } else if (Result != TDK_Success) {
  6230. Diag(Arg->getExprLoc(),
  6231. diag::err_non_type_template_parm_type_deduction_failure)
  6232. << Param->getDeclName() << Param->getType() << Arg->getType()
  6233. << Arg->getSourceRange();
  6234. Diag(Param->getLocation(), diag::note_template_param_here);
  6235. return ExprError();
  6236. }
  6237. }
  6238. // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
  6239. // an error. The error message normally references the parameter
  6240. // declaration, but here we'll pass the argument location because that's
  6241. // where the parameter type is deduced.
  6242. ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
  6243. if (ParamType.isNull()) {
  6244. Diag(Param->getLocation(), diag::note_template_param_here);
  6245. return ExprError();
  6246. }
  6247. }
  6248. // We should have already dropped all cv-qualifiers by now.
  6249. assert(!ParamType.hasQualifiers() &&
  6250. "non-type template parameter type cannot be qualified");
  6251. // FIXME: When Param is a reference, should we check that Arg is an lvalue?
  6252. if (CTAK == CTAK_Deduced &&
  6253. (ParamType->isReferenceType()
  6254. ? !Context.hasSameType(ParamType.getNonReferenceType(),
  6255. Arg->getType())
  6256. : !Context.hasSameUnqualifiedType(ParamType, Arg->getType()))) {
  6257. // FIXME: If either type is dependent, we skip the check. This isn't
  6258. // correct, since during deduction we're supposed to have replaced each
  6259. // template parameter with some unique (non-dependent) placeholder.
  6260. // FIXME: If the argument type contains 'auto', we carry on and fail the
  6261. // type check in order to force specific types to be more specialized than
  6262. // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
  6263. // work. Similarly for CTAD, when comparing 'A<x>' against 'A'.
  6264. if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
  6265. !Arg->getType()->getContainedDeducedType()) {
  6266. SugaredConverted = TemplateArgument(Arg);
  6267. CanonicalConverted = TemplateArgument(
  6268. Context.getCanonicalTemplateArgument(SugaredConverted));
  6269. return Arg;
  6270. }
  6271. // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
  6272. // we should actually be checking the type of the template argument in P,
  6273. // not the type of the template argument deduced from A, against the
  6274. // template parameter type.
  6275. Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
  6276. << Arg->getType()
  6277. << ParamType.getUnqualifiedType();
  6278. Diag(Param->getLocation(), diag::note_template_param_here);
  6279. return ExprError();
  6280. }
  6281. // If either the parameter has a dependent type or the argument is
  6282. // type-dependent, there's nothing we can check now.
  6283. if (ParamType->isDependentType() || Arg->isTypeDependent()) {
  6284. // Force the argument to the type of the parameter to maintain invariants.
  6285. auto *PE = dyn_cast<PackExpansionExpr>(Arg);
  6286. if (PE)
  6287. Arg = PE->getPattern();
  6288. ExprResult E = ImpCastExprToType(
  6289. Arg, ParamType.getNonLValueExprType(Context), CK_Dependent,
  6290. ParamType->isLValueReferenceType() ? VK_LValue
  6291. : ParamType->isRValueReferenceType() ? VK_XValue
  6292. : VK_PRValue);
  6293. if (E.isInvalid())
  6294. return ExprError();
  6295. if (PE) {
  6296. // Recreate a pack expansion if we unwrapped one.
  6297. E = new (Context)
  6298. PackExpansionExpr(E.get()->getType(), E.get(), PE->getEllipsisLoc(),
  6299. PE->getNumExpansions());
  6300. }
  6301. SugaredConverted = TemplateArgument(E.get());
  6302. CanonicalConverted = TemplateArgument(
  6303. Context.getCanonicalTemplateArgument(SugaredConverted));
  6304. return E;
  6305. }
  6306. // The initialization of the parameter from the argument is
  6307. // a constant-evaluated context.
  6308. EnterExpressionEvaluationContext ConstantEvaluated(
  6309. *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  6310. if (getLangOpts().CPlusPlus17) {
  6311. QualType CanonParamType = Context.getCanonicalType(ParamType);
  6312. // Avoid making a copy when initializing a template parameter of class type
  6313. // from a template parameter object of the same type. This is going beyond
  6314. // the standard, but is required for soundness: in
  6315. // template<A a> struct X { X *p; X<a> *q; };
  6316. // ... we need p and q to have the same type.
  6317. //
  6318. // Similarly, don't inject a call to a copy constructor when initializing
  6319. // from a template parameter of the same type.
  6320. Expr *InnerArg = Arg->IgnoreParenImpCasts();
  6321. if (ParamType->isRecordType() && isa<DeclRefExpr>(InnerArg) &&
  6322. Context.hasSameUnqualifiedType(ParamType, InnerArg->getType())) {
  6323. NamedDecl *ND = cast<DeclRefExpr>(InnerArg)->getDecl();
  6324. if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
  6325. SugaredConverted = TemplateArgument(TPO, ParamType);
  6326. CanonicalConverted =
  6327. TemplateArgument(TPO->getCanonicalDecl(), CanonParamType);
  6328. return Arg;
  6329. }
  6330. if (isa<NonTypeTemplateParmDecl>(ND)) {
  6331. SugaredConverted = TemplateArgument(Arg);
  6332. CanonicalConverted =
  6333. Context.getCanonicalTemplateArgument(SugaredConverted);
  6334. return Arg;
  6335. }
  6336. }
  6337. // C++17 [temp.arg.nontype]p1:
  6338. // A template-argument for a non-type template parameter shall be
  6339. // a converted constant expression of the type of the template-parameter.
  6340. APValue Value;
  6341. ExprResult ArgResult = CheckConvertedConstantExpression(
  6342. Arg, ParamType, Value, CCEK_TemplateArg, Param);
  6343. if (ArgResult.isInvalid())
  6344. return ExprError();
  6345. // For a value-dependent argument, CheckConvertedConstantExpression is
  6346. // permitted (and expected) to be unable to determine a value.
  6347. if (ArgResult.get()->isValueDependent()) {
  6348. SugaredConverted = TemplateArgument(ArgResult.get());
  6349. CanonicalConverted =
  6350. Context.getCanonicalTemplateArgument(SugaredConverted);
  6351. return ArgResult;
  6352. }
  6353. // Convert the APValue to a TemplateArgument.
  6354. switch (Value.getKind()) {
  6355. case APValue::None:
  6356. assert(ParamType->isNullPtrType());
  6357. SugaredConverted = TemplateArgument(ParamType, /*isNullPtr=*/true);
  6358. CanonicalConverted = TemplateArgument(CanonParamType, /*isNullPtr=*/true);
  6359. break;
  6360. case APValue::Indeterminate:
  6361. llvm_unreachable("result of constant evaluation should be initialized");
  6362. break;
  6363. case APValue::Int:
  6364. assert(ParamType->isIntegralOrEnumerationType());
  6365. SugaredConverted = TemplateArgument(Context, Value.getInt(), ParamType);
  6366. CanonicalConverted =
  6367. TemplateArgument(Context, Value.getInt(), CanonParamType);
  6368. break;
  6369. case APValue::MemberPointer: {
  6370. assert(ParamType->isMemberPointerType());
  6371. // FIXME: We need TemplateArgument representation and mangling for these.
  6372. if (!Value.getMemberPointerPath().empty()) {
  6373. Diag(Arg->getBeginLoc(),
  6374. diag::err_template_arg_member_ptr_base_derived_not_supported)
  6375. << Value.getMemberPointerDecl() << ParamType
  6376. << Arg->getSourceRange();
  6377. return ExprError();
  6378. }
  6379. auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
  6380. SugaredConverted = VD ? TemplateArgument(VD, ParamType)
  6381. : TemplateArgument(ParamType, /*isNullPtr=*/true);
  6382. CanonicalConverted =
  6383. VD ? TemplateArgument(cast<ValueDecl>(VD->getCanonicalDecl()),
  6384. CanonParamType)
  6385. : TemplateArgument(CanonParamType, /*isNullPtr=*/true);
  6386. break;
  6387. }
  6388. case APValue::LValue: {
  6389. // For a non-type template-parameter of pointer or reference type,
  6390. // the value of the constant expression shall not refer to
  6391. assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
  6392. ParamType->isNullPtrType());
  6393. // -- a temporary object
  6394. // -- a string literal
  6395. // -- the result of a typeid expression, or
  6396. // -- a predefined __func__ variable
  6397. APValue::LValueBase Base = Value.getLValueBase();
  6398. auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
  6399. if (Base &&
  6400. (!VD ||
  6401. isa<LifetimeExtendedTemporaryDecl, UnnamedGlobalConstantDecl>(VD))) {
  6402. Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
  6403. << Arg->getSourceRange();
  6404. return ExprError();
  6405. }
  6406. // -- a subobject
  6407. // FIXME: Until C++20
  6408. if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
  6409. VD && VD->getType()->isArrayType() &&
  6410. Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
  6411. !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
  6412. // Per defect report (no number yet):
  6413. // ... other than a pointer to the first element of a complete array
  6414. // object.
  6415. } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
  6416. Value.isLValueOnePastTheEnd()) {
  6417. Diag(StartLoc, diag::err_non_type_template_arg_subobject)
  6418. << Value.getAsString(Context, ParamType);
  6419. return ExprError();
  6420. }
  6421. assert((VD || !ParamType->isReferenceType()) &&
  6422. "null reference should not be a constant expression");
  6423. assert((!VD || !ParamType->isNullPtrType()) &&
  6424. "non-null value of type nullptr_t?");
  6425. SugaredConverted = VD ? TemplateArgument(VD, ParamType)
  6426. : TemplateArgument(ParamType, /*isNullPtr=*/true);
  6427. CanonicalConverted =
  6428. VD ? TemplateArgument(cast<ValueDecl>(VD->getCanonicalDecl()),
  6429. CanonParamType)
  6430. : TemplateArgument(CanonParamType, /*isNullPtr=*/true);
  6431. break;
  6432. }
  6433. case APValue::Struct:
  6434. case APValue::Union: {
  6435. // Get or create the corresponding template parameter object.
  6436. TemplateParamObjectDecl *D =
  6437. Context.getTemplateParamObjectDecl(ParamType, Value);
  6438. SugaredConverted = TemplateArgument(D, ParamType);
  6439. CanonicalConverted =
  6440. TemplateArgument(D->getCanonicalDecl(), CanonParamType);
  6441. break;
  6442. }
  6443. case APValue::AddrLabelDiff:
  6444. return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
  6445. case APValue::FixedPoint:
  6446. case APValue::Float:
  6447. case APValue::ComplexInt:
  6448. case APValue::ComplexFloat:
  6449. case APValue::Vector:
  6450. case APValue::Array:
  6451. return Diag(StartLoc, diag::err_non_type_template_arg_unsupported)
  6452. << ParamType;
  6453. }
  6454. return ArgResult.get();
  6455. }
  6456. // C++ [temp.arg.nontype]p5:
  6457. // The following conversions are performed on each expression used
  6458. // as a non-type template-argument. If a non-type
  6459. // template-argument cannot be converted to the type of the
  6460. // corresponding template-parameter then the program is
  6461. // ill-formed.
  6462. if (ParamType->isIntegralOrEnumerationType()) {
  6463. // C++11:
  6464. // -- for a non-type template-parameter of integral or
  6465. // enumeration type, conversions permitted in a converted
  6466. // constant expression are applied.
  6467. //
  6468. // C++98:
  6469. // -- for a non-type template-parameter of integral or
  6470. // enumeration type, integral promotions (4.5) and integral
  6471. // conversions (4.7) are applied.
  6472. if (getLangOpts().CPlusPlus11) {
  6473. // C++ [temp.arg.nontype]p1:
  6474. // A template-argument for a non-type, non-template template-parameter
  6475. // shall be one of:
  6476. //
  6477. // -- for a non-type template-parameter of integral or enumeration
  6478. // type, a converted constant expression of the type of the
  6479. // template-parameter; or
  6480. llvm::APSInt Value;
  6481. ExprResult ArgResult =
  6482. CheckConvertedConstantExpression(Arg, ParamType, Value,
  6483. CCEK_TemplateArg);
  6484. if (ArgResult.isInvalid())
  6485. return ExprError();
  6486. // We can't check arbitrary value-dependent arguments.
  6487. if (ArgResult.get()->isValueDependent()) {
  6488. SugaredConverted = TemplateArgument(ArgResult.get());
  6489. CanonicalConverted =
  6490. Context.getCanonicalTemplateArgument(SugaredConverted);
  6491. return ArgResult;
  6492. }
  6493. // Widen the argument value to sizeof(parameter type). This is almost
  6494. // always a no-op, except when the parameter type is bool. In
  6495. // that case, this may extend the argument from 1 bit to 8 bits.
  6496. QualType IntegerType = ParamType;
  6497. if (const EnumType *Enum = IntegerType->getAs<EnumType>())
  6498. IntegerType = Enum->getDecl()->getIntegerType();
  6499. Value = Value.extOrTrunc(IntegerType->isBitIntType()
  6500. ? Context.getIntWidth(IntegerType)
  6501. : Context.getTypeSize(IntegerType));
  6502. SugaredConverted = TemplateArgument(Context, Value, ParamType);
  6503. CanonicalConverted =
  6504. TemplateArgument(Context, Value, Context.getCanonicalType(ParamType));
  6505. return ArgResult;
  6506. }
  6507. ExprResult ArgResult = DefaultLvalueConversion(Arg);
  6508. if (ArgResult.isInvalid())
  6509. return ExprError();
  6510. Arg = ArgResult.get();
  6511. QualType ArgType = Arg->getType();
  6512. // C++ [temp.arg.nontype]p1:
  6513. // A template-argument for a non-type, non-template
  6514. // template-parameter shall be one of:
  6515. //
  6516. // -- an integral constant-expression of integral or enumeration
  6517. // type; or
  6518. // -- the name of a non-type template-parameter; or
  6519. llvm::APSInt Value;
  6520. if (!ArgType->isIntegralOrEnumerationType()) {
  6521. Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral)
  6522. << ArgType << Arg->getSourceRange();
  6523. Diag(Param->getLocation(), diag::note_template_param_here);
  6524. return ExprError();
  6525. } else if (!Arg->isValueDependent()) {
  6526. class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
  6527. QualType T;
  6528. public:
  6529. TmplArgICEDiagnoser(QualType T) : T(T) { }
  6530. SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
  6531. SourceLocation Loc) override {
  6532. return S.Diag(Loc, diag::err_template_arg_not_ice) << T;
  6533. }
  6534. } Diagnoser(ArgType);
  6535. Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser).get();
  6536. if (!Arg)
  6537. return ExprError();
  6538. }
  6539. // From here on out, all we care about is the unqualified form
  6540. // of the argument type.
  6541. ArgType = ArgType.getUnqualifiedType();
  6542. // Try to convert the argument to the parameter's type.
  6543. if (Context.hasSameType(ParamType, ArgType)) {
  6544. // Okay: no conversion necessary
  6545. } else if (ParamType->isBooleanType()) {
  6546. // This is an integral-to-boolean conversion.
  6547. Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
  6548. } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
  6549. !ParamType->isEnumeralType()) {
  6550. // This is an integral promotion or conversion.
  6551. Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
  6552. } else {
  6553. // We can't perform this conversion.
  6554. Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
  6555. << Arg->getType() << ParamType << Arg->getSourceRange();
  6556. Diag(Param->getLocation(), diag::note_template_param_here);
  6557. return ExprError();
  6558. }
  6559. // Add the value of this argument to the list of converted
  6560. // arguments. We use the bitwidth and signedness of the template
  6561. // parameter.
  6562. if (Arg->isValueDependent()) {
  6563. // The argument is value-dependent. Create a new
  6564. // TemplateArgument with the converted expression.
  6565. SugaredConverted = TemplateArgument(Arg);
  6566. CanonicalConverted =
  6567. Context.getCanonicalTemplateArgument(SugaredConverted);
  6568. return Arg;
  6569. }
  6570. QualType IntegerType = ParamType;
  6571. if (const EnumType *Enum = IntegerType->getAs<EnumType>()) {
  6572. IntegerType = Enum->getDecl()->getIntegerType();
  6573. }
  6574. if (ParamType->isBooleanType()) {
  6575. // Value must be zero or one.
  6576. Value = Value != 0;
  6577. unsigned AllowedBits = Context.getTypeSize(IntegerType);
  6578. if (Value.getBitWidth() != AllowedBits)
  6579. Value = Value.extOrTrunc(AllowedBits);
  6580. Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
  6581. } else {
  6582. llvm::APSInt OldValue = Value;
  6583. // Coerce the template argument's value to the value it will have
  6584. // based on the template parameter's type.
  6585. unsigned AllowedBits = IntegerType->isBitIntType()
  6586. ? Context.getIntWidth(IntegerType)
  6587. : Context.getTypeSize(IntegerType);
  6588. if (Value.getBitWidth() != AllowedBits)
  6589. Value = Value.extOrTrunc(AllowedBits);
  6590. Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
  6591. // Complain if an unsigned parameter received a negative value.
  6592. if (IntegerType->isUnsignedIntegerOrEnumerationType() &&
  6593. (OldValue.isSigned() && OldValue.isNegative())) {
  6594. Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
  6595. << toString(OldValue, 10) << toString(Value, 10) << Param->getType()
  6596. << Arg->getSourceRange();
  6597. Diag(Param->getLocation(), diag::note_template_param_here);
  6598. }
  6599. // Complain if we overflowed the template parameter's type.
  6600. unsigned RequiredBits;
  6601. if (IntegerType->isUnsignedIntegerOrEnumerationType())
  6602. RequiredBits = OldValue.getActiveBits();
  6603. else if (OldValue.isUnsigned())
  6604. RequiredBits = OldValue.getActiveBits() + 1;
  6605. else
  6606. RequiredBits = OldValue.getMinSignedBits();
  6607. if (RequiredBits > AllowedBits) {
  6608. Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
  6609. << toString(OldValue, 10) << toString(Value, 10) << Param->getType()
  6610. << Arg->getSourceRange();
  6611. Diag(Param->getLocation(), diag::note_template_param_here);
  6612. }
  6613. }
  6614. QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType;
  6615. SugaredConverted = TemplateArgument(Context, Value, T);
  6616. CanonicalConverted =
  6617. TemplateArgument(Context, Value, Context.getCanonicalType(T));
  6618. return Arg;
  6619. }
  6620. QualType ArgType = Arg->getType();
  6621. DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
  6622. // Handle pointer-to-function, reference-to-function, and
  6623. // pointer-to-member-function all in (roughly) the same way.
  6624. if (// -- For a non-type template-parameter of type pointer to
  6625. // function, only the function-to-pointer conversion (4.3) is
  6626. // applied. If the template-argument represents a set of
  6627. // overloaded functions (or a pointer to such), the matching
  6628. // function is selected from the set (13.4).
  6629. (ParamType->isPointerType() &&
  6630. ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
  6631. // -- For a non-type template-parameter of type reference to
  6632. // function, no conversions apply. If the template-argument
  6633. // represents a set of overloaded functions, the matching
  6634. // function is selected from the set (13.4).
  6635. (ParamType->isReferenceType() &&
  6636. ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
  6637. // -- For a non-type template-parameter of type pointer to
  6638. // member function, no conversions apply. If the
  6639. // template-argument represents a set of overloaded member
  6640. // functions, the matching member function is selected from
  6641. // the set (13.4).
  6642. (ParamType->isMemberPointerType() &&
  6643. ParamType->castAs<MemberPointerType>()->getPointeeType()
  6644. ->isFunctionType())) {
  6645. if (Arg->getType() == Context.OverloadTy) {
  6646. if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
  6647. true,
  6648. FoundResult)) {
  6649. if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
  6650. return ExprError();
  6651. Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
  6652. ArgType = Arg->getType();
  6653. } else
  6654. return ExprError();
  6655. }
  6656. if (!ParamType->isMemberPointerType()) {
  6657. if (CheckTemplateArgumentAddressOfObjectOrFunction(
  6658. *this, Param, ParamType, Arg, SugaredConverted,
  6659. CanonicalConverted))
  6660. return ExprError();
  6661. return Arg;
  6662. }
  6663. if (CheckTemplateArgumentPointerToMember(
  6664. *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
  6665. return ExprError();
  6666. return Arg;
  6667. }
  6668. if (ParamType->isPointerType()) {
  6669. // -- for a non-type template-parameter of type pointer to
  6670. // object, qualification conversions (4.4) and the
  6671. // array-to-pointer conversion (4.2) are applied.
  6672. // C++0x also allows a value of std::nullptr_t.
  6673. assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
  6674. "Only object pointers allowed here");
  6675. if (CheckTemplateArgumentAddressOfObjectOrFunction(
  6676. *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
  6677. return ExprError();
  6678. return Arg;
  6679. }
  6680. if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
  6681. // -- For a non-type template-parameter of type reference to
  6682. // object, no conversions apply. The type referred to by the
  6683. // reference may be more cv-qualified than the (otherwise
  6684. // identical) type of the template-argument. The
  6685. // template-parameter is bound directly to the
  6686. // template-argument, which must be an lvalue.
  6687. assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
  6688. "Only object references allowed here");
  6689. if (Arg->getType() == Context.OverloadTy) {
  6690. if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
  6691. ParamRefType->getPointeeType(),
  6692. true,
  6693. FoundResult)) {
  6694. if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
  6695. return ExprError();
  6696. Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
  6697. ArgType = Arg->getType();
  6698. } else
  6699. return ExprError();
  6700. }
  6701. if (CheckTemplateArgumentAddressOfObjectOrFunction(
  6702. *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
  6703. return ExprError();
  6704. return Arg;
  6705. }
  6706. // Deal with parameters of type std::nullptr_t.
  6707. if (ParamType->isNullPtrType()) {
  6708. if (Arg->isTypeDependent() || Arg->isValueDependent()) {
  6709. SugaredConverted = TemplateArgument(Arg);
  6710. CanonicalConverted =
  6711. Context.getCanonicalTemplateArgument(SugaredConverted);
  6712. return Arg;
  6713. }
  6714. switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
  6715. case NPV_NotNullPointer:
  6716. Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
  6717. << Arg->getType() << ParamType;
  6718. Diag(Param->getLocation(), diag::note_template_param_here);
  6719. return ExprError();
  6720. case NPV_Error:
  6721. return ExprError();
  6722. case NPV_NullPointer:
  6723. Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
  6724. SugaredConverted = TemplateArgument(ParamType,
  6725. /*isNullPtr=*/true);
  6726. CanonicalConverted = TemplateArgument(Context.getCanonicalType(ParamType),
  6727. /*isNullPtr=*/true);
  6728. return Arg;
  6729. }
  6730. }
  6731. // -- For a non-type template-parameter of type pointer to data
  6732. // member, qualification conversions (4.4) are applied.
  6733. assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
  6734. if (CheckTemplateArgumentPointerToMember(
  6735. *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
  6736. return ExprError();
  6737. return Arg;
  6738. }
  6739. static void DiagnoseTemplateParameterListArityMismatch(
  6740. Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
  6741. Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
  6742. /// Check a template argument against its corresponding
  6743. /// template template parameter.
  6744. ///
  6745. /// This routine implements the semantics of C++ [temp.arg.template].
  6746. /// It returns true if an error occurred, and false otherwise.
  6747. bool Sema::CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
  6748. TemplateParameterList *Params,
  6749. TemplateArgumentLoc &Arg) {
  6750. TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
  6751. TemplateDecl *Template = Name.getAsTemplateDecl();
  6752. if (!Template) {
  6753. // Any dependent template name is fine.
  6754. assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
  6755. return false;
  6756. }
  6757. if (Template->isInvalidDecl())
  6758. return true;
  6759. // C++0x [temp.arg.template]p1:
  6760. // A template-argument for a template template-parameter shall be
  6761. // the name of a class template or an alias template, expressed as an
  6762. // id-expression. When the template-argument names a class template, only
  6763. // primary class templates are considered when matching the
  6764. // template template argument with the corresponding parameter;
  6765. // partial specializations are not considered even if their
  6766. // parameter lists match that of the template template parameter.
  6767. //
  6768. // Note that we also allow template template parameters here, which
  6769. // will happen when we are dealing with, e.g., class template
  6770. // partial specializations.
  6771. if (!isa<ClassTemplateDecl>(Template) &&
  6772. !isa<TemplateTemplateParmDecl>(Template) &&
  6773. !isa<TypeAliasTemplateDecl>(Template) &&
  6774. !isa<BuiltinTemplateDecl>(Template)) {
  6775. assert(isa<FunctionTemplateDecl>(Template) &&
  6776. "Only function templates are possible here");
  6777. Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
  6778. Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
  6779. << Template;
  6780. }
  6781. // C++1z [temp.arg.template]p3: (DR 150)
  6782. // A template-argument matches a template template-parameter P when P
  6783. // is at least as specialized as the template-argument A.
  6784. // FIXME: We should enable RelaxedTemplateTemplateArgs by default as it is a
  6785. // defect report resolution from C++17 and shouldn't be introduced by
  6786. // concepts.
  6787. if (getLangOpts().RelaxedTemplateTemplateArgs) {
  6788. // Quick check for the common case:
  6789. // If P contains a parameter pack, then A [...] matches P if each of A's
  6790. // template parameters matches the corresponding template parameter in
  6791. // the template-parameter-list of P.
  6792. if (TemplateParameterListsAreEqual(
  6793. Template->getTemplateParameters(), Params, false,
  6794. TPL_TemplateTemplateArgumentMatch, Arg.getLocation()) &&
  6795. // If the argument has no associated constraints, then the parameter is
  6796. // definitely at least as specialized as the argument.
  6797. // Otherwise - we need a more thorough check.
  6798. !Template->hasAssociatedConstraints())
  6799. return false;
  6800. if (isTemplateTemplateParameterAtLeastAsSpecializedAs(Params, Template,
  6801. Arg.getLocation())) {
  6802. // P2113
  6803. // C++20[temp.func.order]p2
  6804. // [...] If both deductions succeed, the partial ordering selects the
  6805. // more constrained template (if one exists) as determined below.
  6806. SmallVector<const Expr *, 3> ParamsAC, TemplateAC;
  6807. Params->getAssociatedConstraints(ParamsAC);
  6808. // C++2a[temp.arg.template]p3
  6809. // [...] In this comparison, if P is unconstrained, the constraints on A
  6810. // are not considered.
  6811. if (ParamsAC.empty())
  6812. return false;
  6813. Template->getAssociatedConstraints(TemplateAC);
  6814. bool IsParamAtLeastAsConstrained;
  6815. if (IsAtLeastAsConstrained(Param, ParamsAC, Template, TemplateAC,
  6816. IsParamAtLeastAsConstrained))
  6817. return true;
  6818. if (!IsParamAtLeastAsConstrained) {
  6819. Diag(Arg.getLocation(),
  6820. diag::err_template_template_parameter_not_at_least_as_constrained)
  6821. << Template << Param << Arg.getSourceRange();
  6822. Diag(Param->getLocation(), diag::note_entity_declared_at) << Param;
  6823. Diag(Template->getLocation(), diag::note_entity_declared_at)
  6824. << Template;
  6825. MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Param, ParamsAC, Template,
  6826. TemplateAC);
  6827. return true;
  6828. }
  6829. return false;
  6830. }
  6831. // FIXME: Produce better diagnostics for deduction failures.
  6832. }
  6833. return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
  6834. Params,
  6835. true,
  6836. TPL_TemplateTemplateArgumentMatch,
  6837. Arg.getLocation());
  6838. }
  6839. /// Given a non-type template argument that refers to a
  6840. /// declaration and the type of its corresponding non-type template
  6841. /// parameter, produce an expression that properly refers to that
  6842. /// declaration.
  6843. ExprResult
  6844. Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
  6845. QualType ParamType,
  6846. SourceLocation Loc) {
  6847. // C++ [temp.param]p8:
  6848. //
  6849. // A non-type template-parameter of type "array of T" or
  6850. // "function returning T" is adjusted to be of type "pointer to
  6851. // T" or "pointer to function returning T", respectively.
  6852. if (ParamType->isArrayType())
  6853. ParamType = Context.getArrayDecayedType(ParamType);
  6854. else if (ParamType->isFunctionType())
  6855. ParamType = Context.getPointerType(ParamType);
  6856. // For a NULL non-type template argument, return nullptr casted to the
  6857. // parameter's type.
  6858. if (Arg.getKind() == TemplateArgument::NullPtr) {
  6859. return ImpCastExprToType(
  6860. new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
  6861. ParamType,
  6862. ParamType->getAs<MemberPointerType>()
  6863. ? CK_NullToMemberPointer
  6864. : CK_NullToPointer);
  6865. }
  6866. assert(Arg.getKind() == TemplateArgument::Declaration &&
  6867. "Only declaration template arguments permitted here");
  6868. ValueDecl *VD = Arg.getAsDecl();
  6869. CXXScopeSpec SS;
  6870. if (ParamType->isMemberPointerType()) {
  6871. // If this is a pointer to member, we need to use a qualified name to
  6872. // form a suitable pointer-to-member constant.
  6873. assert(VD->getDeclContext()->isRecord() &&
  6874. (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
  6875. isa<IndirectFieldDecl>(VD)));
  6876. QualType ClassType
  6877. = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
  6878. NestedNameSpecifier *Qualifier
  6879. = NestedNameSpecifier::Create(Context, nullptr, false,
  6880. ClassType.getTypePtr());
  6881. SS.MakeTrivial(Context, Qualifier, Loc);
  6882. }
  6883. ExprResult RefExpr = BuildDeclarationNameExpr(
  6884. SS, DeclarationNameInfo(VD->getDeclName(), Loc), VD);
  6885. if (RefExpr.isInvalid())
  6886. return ExprError();
  6887. // For a pointer, the argument declaration is the pointee. Take its address.
  6888. QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
  6889. if (ParamType->isPointerType() && !ElemT.isNull() &&
  6890. Context.hasSimilarType(ElemT, ParamType->getPointeeType())) {
  6891. // Decay an array argument if we want a pointer to its first element.
  6892. RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
  6893. if (RefExpr.isInvalid())
  6894. return ExprError();
  6895. } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
  6896. // For any other pointer, take the address (or form a pointer-to-member).
  6897. RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
  6898. if (RefExpr.isInvalid())
  6899. return ExprError();
  6900. } else if (ParamType->isRecordType()) {
  6901. assert(isa<TemplateParamObjectDecl>(VD) &&
  6902. "arg for class template param not a template parameter object");
  6903. // No conversions apply in this case.
  6904. return RefExpr;
  6905. } else {
  6906. assert(ParamType->isReferenceType() &&
  6907. "unexpected type for decl template argument");
  6908. }
  6909. // At this point we should have the right value category.
  6910. assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
  6911. "value kind mismatch for non-type template argument");
  6912. // The type of the template parameter can differ from the type of the
  6913. // argument in various ways; convert it now if necessary.
  6914. QualType DestExprType = ParamType.getNonLValueExprType(Context);
  6915. if (!Context.hasSameType(RefExpr.get()->getType(), DestExprType)) {
  6916. CastKind CK;
  6917. QualType Ignored;
  6918. if (Context.hasSimilarType(RefExpr.get()->getType(), DestExprType) ||
  6919. IsFunctionConversion(RefExpr.get()->getType(), DestExprType, Ignored)) {
  6920. CK = CK_NoOp;
  6921. } else if (ParamType->isVoidPointerType() &&
  6922. RefExpr.get()->getType()->isPointerType()) {
  6923. CK = CK_BitCast;
  6924. } else {
  6925. // FIXME: Pointers to members can need conversion derived-to-base or
  6926. // base-to-derived conversions. We currently don't retain enough
  6927. // information to convert properly (we need to track a cast path or
  6928. // subobject number in the template argument).
  6929. llvm_unreachable(
  6930. "unexpected conversion required for non-type template argument");
  6931. }
  6932. RefExpr = ImpCastExprToType(RefExpr.get(), DestExprType, CK,
  6933. RefExpr.get()->getValueKind());
  6934. }
  6935. return RefExpr;
  6936. }
  6937. /// Construct a new expression that refers to the given
  6938. /// integral template argument with the given source-location
  6939. /// information.
  6940. ///
  6941. /// This routine takes care of the mapping from an integral template
  6942. /// argument (which may have any integral type) to the appropriate
  6943. /// literal value.
  6944. ExprResult
  6945. Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
  6946. SourceLocation Loc) {
  6947. assert(Arg.getKind() == TemplateArgument::Integral &&
  6948. "Operation is only valid for integral template arguments");
  6949. QualType OrigT = Arg.getIntegralType();
  6950. // If this is an enum type that we're instantiating, we need to use an integer
  6951. // type the same size as the enumerator. We don't want to build an
  6952. // IntegerLiteral with enum type. The integer type of an enum type can be of
  6953. // any integral type with C++11 enum classes, make sure we create the right
  6954. // type of literal for it.
  6955. QualType T = OrigT;
  6956. if (const EnumType *ET = OrigT->getAs<EnumType>())
  6957. T = ET->getDecl()->getIntegerType();
  6958. Expr *E;
  6959. if (T->isAnyCharacterType()) {
  6960. CharacterLiteral::CharacterKind Kind;
  6961. if (T->isWideCharType())
  6962. Kind = CharacterLiteral::Wide;
  6963. else if (T->isChar8Type() && getLangOpts().Char8)
  6964. Kind = CharacterLiteral::UTF8;
  6965. else if (T->isChar16Type())
  6966. Kind = CharacterLiteral::UTF16;
  6967. else if (T->isChar32Type())
  6968. Kind = CharacterLiteral::UTF32;
  6969. else
  6970. Kind = CharacterLiteral::Ascii;
  6971. E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
  6972. Kind, T, Loc);
  6973. } else if (T->isBooleanType()) {
  6974. E = CXXBoolLiteralExpr::Create(Context, Arg.getAsIntegral().getBoolValue(),
  6975. T, Loc);
  6976. } else if (T->isNullPtrType()) {
  6977. E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
  6978. } else {
  6979. E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
  6980. }
  6981. if (OrigT->isEnumeralType()) {
  6982. // FIXME: This is a hack. We need a better way to handle substituted
  6983. // non-type template parameters.
  6984. E = CStyleCastExpr::Create(Context, OrigT, VK_PRValue, CK_IntegralCast, E,
  6985. nullptr, CurFPFeatureOverrides(),
  6986. Context.getTrivialTypeSourceInfo(OrigT, Loc),
  6987. Loc, Loc);
  6988. }
  6989. return E;
  6990. }
  6991. /// Match two template parameters within template parameter lists.
  6992. static bool MatchTemplateParameterKind(
  6993. Sema &S, NamedDecl *New, const NamedDecl *NewInstFrom, NamedDecl *Old,
  6994. const NamedDecl *OldInstFrom, bool Complain,
  6995. Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc,
  6996. bool PartialOrdering) {
  6997. // Check the actual kind (type, non-type, template).
  6998. if (Old->getKind() != New->getKind()) {
  6999. if (Complain) {
  7000. unsigned NextDiag = diag::err_template_param_different_kind;
  7001. if (TemplateArgLoc.isValid()) {
  7002. S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
  7003. NextDiag = diag::note_template_param_different_kind;
  7004. }
  7005. S.Diag(New->getLocation(), NextDiag)
  7006. << (Kind != Sema::TPL_TemplateMatch);
  7007. S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
  7008. << (Kind != Sema::TPL_TemplateMatch);
  7009. }
  7010. return false;
  7011. }
  7012. // Check that both are parameter packs or neither are parameter packs.
  7013. // However, if we are matching a template template argument to a
  7014. // template template parameter, the template template parameter can have
  7015. // a parameter pack where the template template argument does not.
  7016. if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
  7017. !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
  7018. Old->isTemplateParameterPack())) {
  7019. if (Complain) {
  7020. unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
  7021. if (TemplateArgLoc.isValid()) {
  7022. S.Diag(TemplateArgLoc,
  7023. diag::err_template_arg_template_params_mismatch);
  7024. NextDiag = diag::note_template_parameter_pack_non_pack;
  7025. }
  7026. unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
  7027. : isa<NonTypeTemplateParmDecl>(New)? 1
  7028. : 2;
  7029. S.Diag(New->getLocation(), NextDiag)
  7030. << ParamKind << New->isParameterPack();
  7031. S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
  7032. << ParamKind << Old->isParameterPack();
  7033. }
  7034. return false;
  7035. }
  7036. // For non-type template parameters, check the type of the parameter.
  7037. if (NonTypeTemplateParmDecl *OldNTTP
  7038. = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
  7039. NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
  7040. // If we are matching a template template argument to a template
  7041. // template parameter and one of the non-type template parameter types
  7042. // is dependent, then we must wait until template instantiation time
  7043. // to actually compare the arguments.
  7044. if (Kind != Sema::TPL_TemplateTemplateArgumentMatch ||
  7045. (!OldNTTP->getType()->isDependentType() &&
  7046. !NewNTTP->getType()->isDependentType()))
  7047. if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
  7048. if (Complain) {
  7049. unsigned NextDiag = diag::err_template_nontype_parm_different_type;
  7050. if (TemplateArgLoc.isValid()) {
  7051. S.Diag(TemplateArgLoc,
  7052. diag::err_template_arg_template_params_mismatch);
  7053. NextDiag = diag::note_template_nontype_parm_different_type;
  7054. }
  7055. S.Diag(NewNTTP->getLocation(), NextDiag)
  7056. << NewNTTP->getType()
  7057. << (Kind != Sema::TPL_TemplateMatch);
  7058. S.Diag(OldNTTP->getLocation(),
  7059. diag::note_template_nontype_parm_prev_declaration)
  7060. << OldNTTP->getType();
  7061. }
  7062. return false;
  7063. }
  7064. }
  7065. // For template template parameters, check the template parameter types.
  7066. // The template parameter lists of template template
  7067. // parameters must agree.
  7068. else if (TemplateTemplateParmDecl *OldTTP
  7069. = dyn_cast<TemplateTemplateParmDecl>(Old)) {
  7070. TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
  7071. if (!S.TemplateParameterListsAreEqual(
  7072. NewInstFrom, NewTTP->getTemplateParameters(), OldInstFrom,
  7073. OldTTP->getTemplateParameters(), Complain,
  7074. (Kind == Sema::TPL_TemplateMatch
  7075. ? Sema::TPL_TemplateTemplateParmMatch
  7076. : Kind),
  7077. TemplateArgLoc, PartialOrdering))
  7078. return false;
  7079. }
  7080. if (!PartialOrdering && Kind != Sema::TPL_TemplateTemplateArgumentMatch &&
  7081. !isa<TemplateTemplateParmDecl>(Old)) {
  7082. const Expr *NewC = nullptr, *OldC = nullptr;
  7083. if (isa<TemplateTypeParmDecl>(New)) {
  7084. if (const auto *TC = cast<TemplateTypeParmDecl>(New)->getTypeConstraint())
  7085. NewC = TC->getImmediatelyDeclaredConstraint();
  7086. if (const auto *TC = cast<TemplateTypeParmDecl>(Old)->getTypeConstraint())
  7087. OldC = TC->getImmediatelyDeclaredConstraint();
  7088. } else if (isa<NonTypeTemplateParmDecl>(New)) {
  7089. if (const Expr *E = cast<NonTypeTemplateParmDecl>(New)
  7090. ->getPlaceholderTypeConstraint())
  7091. NewC = E;
  7092. if (const Expr *E = cast<NonTypeTemplateParmDecl>(Old)
  7093. ->getPlaceholderTypeConstraint())
  7094. OldC = E;
  7095. } else
  7096. llvm_unreachable("unexpected template parameter type");
  7097. auto Diagnose = [&] {
  7098. S.Diag(NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
  7099. diag::err_template_different_type_constraint);
  7100. S.Diag(OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
  7101. diag::note_template_prev_declaration) << /*declaration*/0;
  7102. };
  7103. if (!NewC != !OldC) {
  7104. if (Complain)
  7105. Diagnose();
  7106. return false;
  7107. }
  7108. if (NewC) {
  7109. if (!S.AreConstraintExpressionsEqual(OldInstFrom, OldC, NewInstFrom,
  7110. NewC)) {
  7111. if (Complain)
  7112. Diagnose();
  7113. return false;
  7114. }
  7115. }
  7116. }
  7117. return true;
  7118. }
  7119. /// Diagnose a known arity mismatch when comparing template argument
  7120. /// lists.
  7121. static
  7122. void DiagnoseTemplateParameterListArityMismatch(Sema &S,
  7123. TemplateParameterList *New,
  7124. TemplateParameterList *Old,
  7125. Sema::TemplateParameterListEqualKind Kind,
  7126. SourceLocation TemplateArgLoc) {
  7127. unsigned NextDiag = diag::err_template_param_list_different_arity;
  7128. if (TemplateArgLoc.isValid()) {
  7129. S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
  7130. NextDiag = diag::note_template_param_list_different_arity;
  7131. }
  7132. S.Diag(New->getTemplateLoc(), NextDiag)
  7133. << (New->size() > Old->size())
  7134. << (Kind != Sema::TPL_TemplateMatch)
  7135. << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
  7136. S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
  7137. << (Kind != Sema::TPL_TemplateMatch)
  7138. << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
  7139. }
  7140. /// Determine whether the given template parameter lists are
  7141. /// equivalent.
  7142. ///
  7143. /// \param New The new template parameter list, typically written in the
  7144. /// source code as part of a new template declaration.
  7145. ///
  7146. /// \param Old The old template parameter list, typically found via
  7147. /// name lookup of the template declared with this template parameter
  7148. /// list.
  7149. ///
  7150. /// \param Complain If true, this routine will produce a diagnostic if
  7151. /// the template parameter lists are not equivalent.
  7152. ///
  7153. /// \param Kind describes how we are to match the template parameter lists.
  7154. ///
  7155. /// \param TemplateArgLoc If this source location is valid, then we
  7156. /// are actually checking the template parameter list of a template
  7157. /// argument (New) against the template parameter list of its
  7158. /// corresponding template template parameter (Old). We produce
  7159. /// slightly different diagnostics in this scenario.
  7160. ///
  7161. /// \returns True if the template parameter lists are equal, false
  7162. /// otherwise.
  7163. bool Sema::TemplateParameterListsAreEqual(
  7164. const NamedDecl *NewInstFrom, TemplateParameterList *New,
  7165. const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
  7166. TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc,
  7167. bool PartialOrdering) {
  7168. if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
  7169. if (Complain)
  7170. DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
  7171. TemplateArgLoc);
  7172. return false;
  7173. }
  7174. // C++0x [temp.arg.template]p3:
  7175. // A template-argument matches a template template-parameter (call it P)
  7176. // when each of the template parameters in the template-parameter-list of
  7177. // the template-argument's corresponding class template or alias template
  7178. // (call it A) matches the corresponding template parameter in the
  7179. // template-parameter-list of P. [...]
  7180. TemplateParameterList::iterator NewParm = New->begin();
  7181. TemplateParameterList::iterator NewParmEnd = New->end();
  7182. for (TemplateParameterList::iterator OldParm = Old->begin(),
  7183. OldParmEnd = Old->end();
  7184. OldParm != OldParmEnd; ++OldParm) {
  7185. if (Kind != TPL_TemplateTemplateArgumentMatch ||
  7186. !(*OldParm)->isTemplateParameterPack()) {
  7187. if (NewParm == NewParmEnd) {
  7188. if (Complain)
  7189. DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
  7190. TemplateArgLoc);
  7191. return false;
  7192. }
  7193. if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
  7194. OldInstFrom, Complain, Kind,
  7195. TemplateArgLoc, PartialOrdering))
  7196. return false;
  7197. ++NewParm;
  7198. continue;
  7199. }
  7200. // C++0x [temp.arg.template]p3:
  7201. // [...] When P's template- parameter-list contains a template parameter
  7202. // pack (14.5.3), the template parameter pack will match zero or more
  7203. // template parameters or template parameter packs in the
  7204. // template-parameter-list of A with the same type and form as the
  7205. // template parameter pack in P (ignoring whether those template
  7206. // parameters are template parameter packs).
  7207. for (; NewParm != NewParmEnd; ++NewParm) {
  7208. if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
  7209. OldInstFrom, Complain, Kind,
  7210. TemplateArgLoc, PartialOrdering))
  7211. return false;
  7212. }
  7213. }
  7214. // Make sure we exhausted all of the arguments.
  7215. if (NewParm != NewParmEnd) {
  7216. if (Complain)
  7217. DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
  7218. TemplateArgLoc);
  7219. return false;
  7220. }
  7221. if (!PartialOrdering && Kind != TPL_TemplateTemplateArgumentMatch) {
  7222. const Expr *NewRC = New->getRequiresClause();
  7223. const Expr *OldRC = Old->getRequiresClause();
  7224. auto Diagnose = [&] {
  7225. Diag(NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
  7226. diag::err_template_different_requires_clause);
  7227. Diag(OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
  7228. diag::note_template_prev_declaration) << /*declaration*/0;
  7229. };
  7230. if (!NewRC != !OldRC) {
  7231. if (Complain)
  7232. Diagnose();
  7233. return false;
  7234. }
  7235. if (NewRC) {
  7236. if (!AreConstraintExpressionsEqual(OldInstFrom, OldRC, NewInstFrom,
  7237. NewRC)) {
  7238. if (Complain)
  7239. Diagnose();
  7240. return false;
  7241. }
  7242. }
  7243. }
  7244. return true;
  7245. }
  7246. /// Check whether a template can be declared within this scope.
  7247. ///
  7248. /// If the template declaration is valid in this scope, returns
  7249. /// false. Otherwise, issues a diagnostic and returns true.
  7250. bool
  7251. Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
  7252. if (!S)
  7253. return false;
  7254. // Find the nearest enclosing declaration scope.
  7255. while ((S->getFlags() & Scope::DeclScope) == 0 ||
  7256. (S->getFlags() & Scope::TemplateParamScope) != 0)
  7257. S = S->getParent();
  7258. // C++ [temp.pre]p6: [P2096]
  7259. // A template, explicit specialization, or partial specialization shall not
  7260. // have C linkage.
  7261. DeclContext *Ctx = S->getEntity();
  7262. if (Ctx && Ctx->isExternCContext()) {
  7263. Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
  7264. << TemplateParams->getSourceRange();
  7265. if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
  7266. Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
  7267. return true;
  7268. }
  7269. Ctx = Ctx ? Ctx->getRedeclContext() : nullptr;
  7270. // C++ [temp]p2:
  7271. // A template-declaration can appear only as a namespace scope or
  7272. // class scope declaration.
  7273. // C++ [temp.expl.spec]p3:
  7274. // An explicit specialization may be declared in any scope in which the
  7275. // corresponding primary template may be defined.
  7276. // C++ [temp.class.spec]p6: [P2096]
  7277. // A partial specialization may be declared in any scope in which the
  7278. // corresponding primary template may be defined.
  7279. if (Ctx) {
  7280. if (Ctx->isFileContext())
  7281. return false;
  7282. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
  7283. // C++ [temp.mem]p2:
  7284. // A local class shall not have member templates.
  7285. if (RD->isLocalClass())
  7286. return Diag(TemplateParams->getTemplateLoc(),
  7287. diag::err_template_inside_local_class)
  7288. << TemplateParams->getSourceRange();
  7289. else
  7290. return false;
  7291. }
  7292. }
  7293. return Diag(TemplateParams->getTemplateLoc(),
  7294. diag::err_template_outside_namespace_or_class_scope)
  7295. << TemplateParams->getSourceRange();
  7296. }
  7297. /// Determine what kind of template specialization the given declaration
  7298. /// is.
  7299. static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
  7300. if (!D)
  7301. return TSK_Undeclared;
  7302. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
  7303. return Record->getTemplateSpecializationKind();
  7304. if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
  7305. return Function->getTemplateSpecializationKind();
  7306. if (VarDecl *Var = dyn_cast<VarDecl>(D))
  7307. return Var->getTemplateSpecializationKind();
  7308. return TSK_Undeclared;
  7309. }
  7310. /// Check whether a specialization is well-formed in the current
  7311. /// context.
  7312. ///
  7313. /// This routine determines whether a template specialization can be declared
  7314. /// in the current context (C++ [temp.expl.spec]p2).
  7315. ///
  7316. /// \param S the semantic analysis object for which this check is being
  7317. /// performed.
  7318. ///
  7319. /// \param Specialized the entity being specialized or instantiated, which
  7320. /// may be a kind of template (class template, function template, etc.) or
  7321. /// a member of a class template (member function, static data member,
  7322. /// member class).
  7323. ///
  7324. /// \param PrevDecl the previous declaration of this entity, if any.
  7325. ///
  7326. /// \param Loc the location of the explicit specialization or instantiation of
  7327. /// this entity.
  7328. ///
  7329. /// \param IsPartialSpecialization whether this is a partial specialization of
  7330. /// a class template.
  7331. ///
  7332. /// \returns true if there was an error that we cannot recover from, false
  7333. /// otherwise.
  7334. static bool CheckTemplateSpecializationScope(Sema &S,
  7335. NamedDecl *Specialized,
  7336. NamedDecl *PrevDecl,
  7337. SourceLocation Loc,
  7338. bool IsPartialSpecialization) {
  7339. // Keep these "kind" numbers in sync with the %select statements in the
  7340. // various diagnostics emitted by this routine.
  7341. int EntityKind = 0;
  7342. if (isa<ClassTemplateDecl>(Specialized))
  7343. EntityKind = IsPartialSpecialization? 1 : 0;
  7344. else if (isa<VarTemplateDecl>(Specialized))
  7345. EntityKind = IsPartialSpecialization ? 3 : 2;
  7346. else if (isa<FunctionTemplateDecl>(Specialized))
  7347. EntityKind = 4;
  7348. else if (isa<CXXMethodDecl>(Specialized))
  7349. EntityKind = 5;
  7350. else if (isa<VarDecl>(Specialized))
  7351. EntityKind = 6;
  7352. else if (isa<RecordDecl>(Specialized))
  7353. EntityKind = 7;
  7354. else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
  7355. EntityKind = 8;
  7356. else {
  7357. S.Diag(Loc, diag::err_template_spec_unknown_kind)
  7358. << S.getLangOpts().CPlusPlus11;
  7359. S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
  7360. return true;
  7361. }
  7362. // C++ [temp.expl.spec]p2:
  7363. // An explicit specialization may be declared in any scope in which
  7364. // the corresponding primary template may be defined.
  7365. if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
  7366. S.Diag(Loc, diag::err_template_spec_decl_function_scope)
  7367. << Specialized;
  7368. return true;
  7369. }
  7370. // C++ [temp.class.spec]p6:
  7371. // A class template partial specialization may be declared in any
  7372. // scope in which the primary template may be defined.
  7373. DeclContext *SpecializedContext =
  7374. Specialized->getDeclContext()->getRedeclContext();
  7375. DeclContext *DC = S.CurContext->getRedeclContext();
  7376. // Make sure that this redeclaration (or definition) occurs in the same
  7377. // scope or an enclosing namespace.
  7378. if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
  7379. : DC->Equals(SpecializedContext))) {
  7380. if (isa<TranslationUnitDecl>(SpecializedContext))
  7381. S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
  7382. << EntityKind << Specialized;
  7383. else {
  7384. auto *ND = cast<NamedDecl>(SpecializedContext);
  7385. int Diag = diag::err_template_spec_redecl_out_of_scope;
  7386. if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
  7387. Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
  7388. S.Diag(Loc, Diag) << EntityKind << Specialized
  7389. << ND << isa<CXXRecordDecl>(ND);
  7390. }
  7391. S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
  7392. // Don't allow specializing in the wrong class during error recovery.
  7393. // Otherwise, things can go horribly wrong.
  7394. if (DC->isRecord())
  7395. return true;
  7396. }
  7397. return false;
  7398. }
  7399. static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
  7400. if (!E->isTypeDependent())
  7401. return SourceLocation();
  7402. DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
  7403. Checker.TraverseStmt(E);
  7404. if (Checker.MatchLoc.isInvalid())
  7405. return E->getSourceRange();
  7406. return Checker.MatchLoc;
  7407. }
  7408. static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
  7409. if (!TL.getType()->isDependentType())
  7410. return SourceLocation();
  7411. DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
  7412. Checker.TraverseTypeLoc(TL);
  7413. if (Checker.MatchLoc.isInvalid())
  7414. return TL.getSourceRange();
  7415. return Checker.MatchLoc;
  7416. }
  7417. /// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
  7418. /// that checks non-type template partial specialization arguments.
  7419. static bool CheckNonTypeTemplatePartialSpecializationArgs(
  7420. Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
  7421. const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
  7422. for (unsigned I = 0; I != NumArgs; ++I) {
  7423. if (Args[I].getKind() == TemplateArgument::Pack) {
  7424. if (CheckNonTypeTemplatePartialSpecializationArgs(
  7425. S, TemplateNameLoc, Param, Args[I].pack_begin(),
  7426. Args[I].pack_size(), IsDefaultArgument))
  7427. return true;
  7428. continue;
  7429. }
  7430. if (Args[I].getKind() != TemplateArgument::Expression)
  7431. continue;
  7432. Expr *ArgExpr = Args[I].getAsExpr();
  7433. // We can have a pack expansion of any of the bullets below.
  7434. if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
  7435. ArgExpr = Expansion->getPattern();
  7436. // Strip off any implicit casts we added as part of type checking.
  7437. while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
  7438. ArgExpr = ICE->getSubExpr();
  7439. // C++ [temp.class.spec]p8:
  7440. // A non-type argument is non-specialized if it is the name of a
  7441. // non-type parameter. All other non-type arguments are
  7442. // specialized.
  7443. //
  7444. // Below, we check the two conditions that only apply to
  7445. // specialized non-type arguments, so skip any non-specialized
  7446. // arguments.
  7447. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
  7448. if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
  7449. continue;
  7450. // C++ [temp.class.spec]p9:
  7451. // Within the argument list of a class template partial
  7452. // specialization, the following restrictions apply:
  7453. // -- A partially specialized non-type argument expression
  7454. // shall not involve a template parameter of the partial
  7455. // specialization except when the argument expression is a
  7456. // simple identifier.
  7457. // -- The type of a template parameter corresponding to a
  7458. // specialized non-type argument shall not be dependent on a
  7459. // parameter of the specialization.
  7460. // DR1315 removes the first bullet, leaving an incoherent set of rules.
  7461. // We implement a compromise between the original rules and DR1315:
  7462. // -- A specialized non-type template argument shall not be
  7463. // type-dependent and the corresponding template parameter
  7464. // shall have a non-dependent type.
  7465. SourceRange ParamUseRange =
  7466. findTemplateParameterInType(Param->getDepth(), ArgExpr);
  7467. if (ParamUseRange.isValid()) {
  7468. if (IsDefaultArgument) {
  7469. S.Diag(TemplateNameLoc,
  7470. diag::err_dependent_non_type_arg_in_partial_spec);
  7471. S.Diag(ParamUseRange.getBegin(),
  7472. diag::note_dependent_non_type_default_arg_in_partial_spec)
  7473. << ParamUseRange;
  7474. } else {
  7475. S.Diag(ParamUseRange.getBegin(),
  7476. diag::err_dependent_non_type_arg_in_partial_spec)
  7477. << ParamUseRange;
  7478. }
  7479. return true;
  7480. }
  7481. ParamUseRange = findTemplateParameter(
  7482. Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
  7483. if (ParamUseRange.isValid()) {
  7484. S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
  7485. diag::err_dependent_typed_non_type_arg_in_partial_spec)
  7486. << Param->getType();
  7487. S.Diag(Param->getLocation(), diag::note_template_param_here)
  7488. << (IsDefaultArgument ? ParamUseRange : SourceRange())
  7489. << ParamUseRange;
  7490. return true;
  7491. }
  7492. }
  7493. return false;
  7494. }
  7495. /// Check the non-type template arguments of a class template
  7496. /// partial specialization according to C++ [temp.class.spec]p9.
  7497. ///
  7498. /// \param TemplateNameLoc the location of the template name.
  7499. /// \param PrimaryTemplate the template parameters of the primary class
  7500. /// template.
  7501. /// \param NumExplicit the number of explicitly-specified template arguments.
  7502. /// \param TemplateArgs the template arguments of the class template
  7503. /// partial specialization.
  7504. ///
  7505. /// \returns \c true if there was an error, \c false otherwise.
  7506. bool Sema::CheckTemplatePartialSpecializationArgs(
  7507. SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
  7508. unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
  7509. // We have to be conservative when checking a template in a dependent
  7510. // context.
  7511. if (PrimaryTemplate->getDeclContext()->isDependentContext())
  7512. return false;
  7513. TemplateParameterList *TemplateParams =
  7514. PrimaryTemplate->getTemplateParameters();
  7515. for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
  7516. NonTypeTemplateParmDecl *Param
  7517. = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
  7518. if (!Param)
  7519. continue;
  7520. if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
  7521. Param, &TemplateArgs[I],
  7522. 1, I >= NumExplicit))
  7523. return true;
  7524. }
  7525. return false;
  7526. }
  7527. DeclResult Sema::ActOnClassTemplateSpecialization(
  7528. Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
  7529. SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
  7530. TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr,
  7531. MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
  7532. assert(TUK != TUK_Reference && "References are not specializations");
  7533. // NOTE: KWLoc is the location of the tag keyword. This will instead
  7534. // store the location of the outermost template keyword in the declaration.
  7535. SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
  7536. ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
  7537. SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
  7538. SourceLocation LAngleLoc = TemplateId.LAngleLoc;
  7539. SourceLocation RAngleLoc = TemplateId.RAngleLoc;
  7540. // Find the class template we're specializing
  7541. TemplateName Name = TemplateId.Template.get();
  7542. ClassTemplateDecl *ClassTemplate
  7543. = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
  7544. if (!ClassTemplate) {
  7545. Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
  7546. << (Name.getAsTemplateDecl() &&
  7547. isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
  7548. return true;
  7549. }
  7550. bool isMemberSpecialization = false;
  7551. bool isPartialSpecialization = false;
  7552. // Check the validity of the template headers that introduce this
  7553. // template.
  7554. // FIXME: We probably shouldn't complain about these headers for
  7555. // friend declarations.
  7556. bool Invalid = false;
  7557. TemplateParameterList *TemplateParams =
  7558. MatchTemplateParametersToScopeSpecifier(
  7559. KWLoc, TemplateNameLoc, SS, &TemplateId,
  7560. TemplateParameterLists, TUK == TUK_Friend, isMemberSpecialization,
  7561. Invalid);
  7562. if (Invalid)
  7563. return true;
  7564. // Check that we can declare a template specialization here.
  7565. if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))
  7566. return true;
  7567. if (TemplateParams && TemplateParams->size() > 0) {
  7568. isPartialSpecialization = true;
  7569. if (TUK == TUK_Friend) {
  7570. Diag(KWLoc, diag::err_partial_specialization_friend)
  7571. << SourceRange(LAngleLoc, RAngleLoc);
  7572. return true;
  7573. }
  7574. // C++ [temp.class.spec]p10:
  7575. // The template parameter list of a specialization shall not
  7576. // contain default template argument values.
  7577. for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
  7578. Decl *Param = TemplateParams->getParam(I);
  7579. if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
  7580. if (TTP->hasDefaultArgument()) {
  7581. Diag(TTP->getDefaultArgumentLoc(),
  7582. diag::err_default_arg_in_partial_spec);
  7583. TTP->removeDefaultArgument();
  7584. }
  7585. } else if (NonTypeTemplateParmDecl *NTTP
  7586. = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
  7587. if (Expr *DefArg = NTTP->getDefaultArgument()) {
  7588. Diag(NTTP->getDefaultArgumentLoc(),
  7589. diag::err_default_arg_in_partial_spec)
  7590. << DefArg->getSourceRange();
  7591. NTTP->removeDefaultArgument();
  7592. }
  7593. } else {
  7594. TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
  7595. if (TTP->hasDefaultArgument()) {
  7596. Diag(TTP->getDefaultArgument().getLocation(),
  7597. diag::err_default_arg_in_partial_spec)
  7598. << TTP->getDefaultArgument().getSourceRange();
  7599. TTP->removeDefaultArgument();
  7600. }
  7601. }
  7602. }
  7603. } else if (TemplateParams) {
  7604. if (TUK == TUK_Friend)
  7605. Diag(KWLoc, diag::err_template_spec_friend)
  7606. << FixItHint::CreateRemoval(
  7607. SourceRange(TemplateParams->getTemplateLoc(),
  7608. TemplateParams->getRAngleLoc()))
  7609. << SourceRange(LAngleLoc, RAngleLoc);
  7610. } else {
  7611. assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
  7612. }
  7613. // Check that the specialization uses the same tag kind as the
  7614. // original template.
  7615. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  7616. assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
  7617. if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
  7618. Kind, TUK == TUK_Definition, KWLoc,
  7619. ClassTemplate->getIdentifier())) {
  7620. Diag(KWLoc, diag::err_use_with_wrong_tag)
  7621. << ClassTemplate
  7622. << FixItHint::CreateReplacement(KWLoc,
  7623. ClassTemplate->getTemplatedDecl()->getKindName());
  7624. Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
  7625. diag::note_previous_use);
  7626. Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
  7627. }
  7628. // Translate the parser's template argument list in our AST format.
  7629. TemplateArgumentListInfo TemplateArgs =
  7630. makeTemplateArgumentListInfo(*this, TemplateId);
  7631. // Check for unexpanded parameter packs in any of the template arguments.
  7632. for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
  7633. if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
  7634. UPPC_PartialSpecialization))
  7635. return true;
  7636. // Check that the template argument list is well-formed for this
  7637. // template.
  7638. SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
  7639. if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
  7640. false, SugaredConverted, CanonicalConverted,
  7641. /*UpdateArgsWithConversions=*/true))
  7642. return true;
  7643. // Find the class template (partial) specialization declaration that
  7644. // corresponds to these arguments.
  7645. if (isPartialSpecialization) {
  7646. if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate,
  7647. TemplateArgs.size(),
  7648. CanonicalConverted))
  7649. return true;
  7650. // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
  7651. // also do it during instantiation.
  7652. if (!Name.isDependent() &&
  7653. !TemplateSpecializationType::anyDependentTemplateArguments(
  7654. TemplateArgs, CanonicalConverted)) {
  7655. Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
  7656. << ClassTemplate->getDeclName();
  7657. isPartialSpecialization = false;
  7658. }
  7659. }
  7660. void *InsertPos = nullptr;
  7661. ClassTemplateSpecializationDecl *PrevDecl = nullptr;
  7662. if (isPartialSpecialization)
  7663. PrevDecl = ClassTemplate->findPartialSpecialization(
  7664. CanonicalConverted, TemplateParams, InsertPos);
  7665. else
  7666. PrevDecl = ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
  7667. ClassTemplateSpecializationDecl *Specialization = nullptr;
  7668. // Check whether we can declare a class template specialization in
  7669. // the current scope.
  7670. if (TUK != TUK_Friend &&
  7671. CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
  7672. TemplateNameLoc,
  7673. isPartialSpecialization))
  7674. return true;
  7675. // The canonical type
  7676. QualType CanonType;
  7677. if (isPartialSpecialization) {
  7678. // Build the canonical type that describes the converted template
  7679. // arguments of the class template partial specialization.
  7680. TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
  7681. CanonType = Context.getTemplateSpecializationType(CanonTemplate,
  7682. CanonicalConverted);
  7683. if (Context.hasSameType(CanonType,
  7684. ClassTemplate->getInjectedClassNameSpecialization()) &&
  7685. (!Context.getLangOpts().CPlusPlus20 ||
  7686. !TemplateParams->hasAssociatedConstraints())) {
  7687. // C++ [temp.class.spec]p9b3:
  7688. //
  7689. // -- The argument list of the specialization shall not be identical
  7690. // to the implicit argument list of the primary template.
  7691. //
  7692. // This rule has since been removed, because it's redundant given DR1495,
  7693. // but we keep it because it produces better diagnostics and recovery.
  7694. Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
  7695. << /*class template*/0 << (TUK == TUK_Definition)
  7696. << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
  7697. return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
  7698. ClassTemplate->getIdentifier(),
  7699. TemplateNameLoc,
  7700. Attr,
  7701. TemplateParams,
  7702. AS_none, /*ModulePrivateLoc=*/SourceLocation(),
  7703. /*FriendLoc*/SourceLocation(),
  7704. TemplateParameterLists.size() - 1,
  7705. TemplateParameterLists.data());
  7706. }
  7707. // Create a new class template partial specialization declaration node.
  7708. ClassTemplatePartialSpecializationDecl *PrevPartial
  7709. = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
  7710. ClassTemplatePartialSpecializationDecl *Partial =
  7711. ClassTemplatePartialSpecializationDecl::Create(
  7712. Context, Kind, ClassTemplate->getDeclContext(), KWLoc,
  7713. TemplateNameLoc, TemplateParams, ClassTemplate, CanonicalConverted,
  7714. TemplateArgs, CanonType, PrevPartial);
  7715. SetNestedNameSpecifier(*this, Partial, SS);
  7716. if (TemplateParameterLists.size() > 1 && SS.isSet()) {
  7717. Partial->setTemplateParameterListsInfo(
  7718. Context, TemplateParameterLists.drop_back(1));
  7719. }
  7720. if (!PrevPartial)
  7721. ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
  7722. Specialization = Partial;
  7723. // If we are providing an explicit specialization of a member class
  7724. // template specialization, make a note of that.
  7725. if (PrevPartial && PrevPartial->getInstantiatedFromMember())
  7726. PrevPartial->setMemberSpecialization();
  7727. CheckTemplatePartialSpecialization(Partial);
  7728. } else {
  7729. // Create a new class template specialization declaration node for
  7730. // this explicit specialization or friend declaration.
  7731. Specialization = ClassTemplateSpecializationDecl::Create(
  7732. Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
  7733. ClassTemplate, CanonicalConverted, PrevDecl);
  7734. SetNestedNameSpecifier(*this, Specialization, SS);
  7735. if (TemplateParameterLists.size() > 0) {
  7736. Specialization->setTemplateParameterListsInfo(Context,
  7737. TemplateParameterLists);
  7738. }
  7739. if (!PrevDecl)
  7740. ClassTemplate->AddSpecialization(Specialization, InsertPos);
  7741. if (CurContext->isDependentContext()) {
  7742. TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
  7743. CanonType = Context.getTemplateSpecializationType(CanonTemplate,
  7744. CanonicalConverted);
  7745. } else {
  7746. CanonType = Context.getTypeDeclType(Specialization);
  7747. }
  7748. }
  7749. // C++ [temp.expl.spec]p6:
  7750. // If a template, a member template or the member of a class template is
  7751. // explicitly specialized then that specialization shall be declared
  7752. // before the first use of that specialization that would cause an implicit
  7753. // instantiation to take place, in every translation unit in which such a
  7754. // use occurs; no diagnostic is required.
  7755. if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
  7756. bool Okay = false;
  7757. for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
  7758. // Is there any previous explicit specialization declaration?
  7759. if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
  7760. Okay = true;
  7761. break;
  7762. }
  7763. }
  7764. if (!Okay) {
  7765. SourceRange Range(TemplateNameLoc, RAngleLoc);
  7766. Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
  7767. << Context.getTypeDeclType(Specialization) << Range;
  7768. Diag(PrevDecl->getPointOfInstantiation(),
  7769. diag::note_instantiation_required_here)
  7770. << (PrevDecl->getTemplateSpecializationKind()
  7771. != TSK_ImplicitInstantiation);
  7772. return true;
  7773. }
  7774. }
  7775. // If this is not a friend, note that this is an explicit specialization.
  7776. if (TUK != TUK_Friend)
  7777. Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
  7778. // Check that this isn't a redefinition of this specialization.
  7779. if (TUK == TUK_Definition) {
  7780. RecordDecl *Def = Specialization->getDefinition();
  7781. NamedDecl *Hidden = nullptr;
  7782. if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
  7783. SkipBody->ShouldSkip = true;
  7784. SkipBody->Previous = Def;
  7785. makeMergedDefinitionVisible(Hidden);
  7786. } else if (Def) {
  7787. SourceRange Range(TemplateNameLoc, RAngleLoc);
  7788. Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
  7789. Diag(Def->getLocation(), diag::note_previous_definition);
  7790. Specialization->setInvalidDecl();
  7791. return true;
  7792. }
  7793. }
  7794. ProcessDeclAttributeList(S, Specialization, Attr);
  7795. // Add alignment attributes if necessary; these attributes are checked when
  7796. // the ASTContext lays out the structure.
  7797. if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
  7798. AddAlignmentAttributesForRecord(Specialization);
  7799. AddMsStructLayoutForRecord(Specialization);
  7800. }
  7801. if (ModulePrivateLoc.isValid())
  7802. Diag(Specialization->getLocation(), diag::err_module_private_specialization)
  7803. << (isPartialSpecialization? 1 : 0)
  7804. << FixItHint::CreateRemoval(ModulePrivateLoc);
  7805. // Build the fully-sugared type for this class template
  7806. // specialization as the user wrote in the specialization
  7807. // itself. This means that we'll pretty-print the type retrieved
  7808. // from the specialization's declaration the way that the user
  7809. // actually wrote the specialization, rather than formatting the
  7810. // name based on the "canonical" representation used to store the
  7811. // template arguments in the specialization.
  7812. TypeSourceInfo *WrittenTy
  7813. = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
  7814. TemplateArgs, CanonType);
  7815. if (TUK != TUK_Friend) {
  7816. Specialization->setTypeAsWritten(WrittenTy);
  7817. Specialization->setTemplateKeywordLoc(TemplateKWLoc);
  7818. }
  7819. // C++ [temp.expl.spec]p9:
  7820. // A template explicit specialization is in the scope of the
  7821. // namespace in which the template was defined.
  7822. //
  7823. // We actually implement this paragraph where we set the semantic
  7824. // context (in the creation of the ClassTemplateSpecializationDecl),
  7825. // but we also maintain the lexical context where the actual
  7826. // definition occurs.
  7827. Specialization->setLexicalDeclContext(CurContext);
  7828. // We may be starting the definition of this specialization.
  7829. if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
  7830. Specialization->startDefinition();
  7831. if (TUK == TUK_Friend) {
  7832. FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
  7833. TemplateNameLoc,
  7834. WrittenTy,
  7835. /*FIXME:*/KWLoc);
  7836. Friend->setAccess(AS_public);
  7837. CurContext->addDecl(Friend);
  7838. } else {
  7839. // Add the specialization into its lexical context, so that it can
  7840. // be seen when iterating through the list of declarations in that
  7841. // context. However, specializations are not found by name lookup.
  7842. CurContext->addDecl(Specialization);
  7843. }
  7844. if (SkipBody && SkipBody->ShouldSkip)
  7845. return SkipBody->Previous;
  7846. return Specialization;
  7847. }
  7848. Decl *Sema::ActOnTemplateDeclarator(Scope *S,
  7849. MultiTemplateParamsArg TemplateParameterLists,
  7850. Declarator &D) {
  7851. Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
  7852. ActOnDocumentableDecl(NewDecl);
  7853. return NewDecl;
  7854. }
  7855. Decl *Sema::ActOnConceptDefinition(Scope *S,
  7856. MultiTemplateParamsArg TemplateParameterLists,
  7857. IdentifierInfo *Name, SourceLocation NameLoc,
  7858. Expr *ConstraintExpr) {
  7859. DeclContext *DC = CurContext;
  7860. if (!DC->getRedeclContext()->isFileContext()) {
  7861. Diag(NameLoc,
  7862. diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
  7863. return nullptr;
  7864. }
  7865. if (TemplateParameterLists.size() > 1) {
  7866. Diag(NameLoc, diag::err_concept_extra_headers);
  7867. return nullptr;
  7868. }
  7869. TemplateParameterList *Params = TemplateParameterLists.front();
  7870. if (Params->size() == 0) {
  7871. Diag(NameLoc, diag::err_concept_no_parameters);
  7872. return nullptr;
  7873. }
  7874. // Ensure that the parameter pack, if present, is the last parameter in the
  7875. // template.
  7876. for (TemplateParameterList::const_iterator ParamIt = Params->begin(),
  7877. ParamEnd = Params->end();
  7878. ParamIt != ParamEnd; ++ParamIt) {
  7879. Decl const *Param = *ParamIt;
  7880. if (Param->isParameterPack()) {
  7881. if (++ParamIt == ParamEnd)
  7882. break;
  7883. Diag(Param->getLocation(),
  7884. diag::err_template_param_pack_must_be_last_template_parameter);
  7885. return nullptr;
  7886. }
  7887. }
  7888. if (DiagnoseUnexpandedParameterPack(ConstraintExpr))
  7889. return nullptr;
  7890. ConceptDecl *NewDecl =
  7891. ConceptDecl::Create(Context, DC, NameLoc, Name, Params, ConstraintExpr);
  7892. if (NewDecl->hasAssociatedConstraints()) {
  7893. // C++2a [temp.concept]p4:
  7894. // A concept shall not have associated constraints.
  7895. Diag(NameLoc, diag::err_concept_no_associated_constraints);
  7896. NewDecl->setInvalidDecl();
  7897. }
  7898. // Check for conflicting previous declaration.
  7899. DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NameLoc);
  7900. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  7901. forRedeclarationInCurContext());
  7902. LookupName(Previous, S);
  7903. FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage=*/false,
  7904. /*AllowInlineNamespace*/false);
  7905. bool AddToScope = true;
  7906. CheckConceptRedefinition(NewDecl, Previous, AddToScope);
  7907. ActOnDocumentableDecl(NewDecl);
  7908. if (AddToScope)
  7909. PushOnScopeChains(NewDecl, S);
  7910. return NewDecl;
  7911. }
  7912. void Sema::CheckConceptRedefinition(ConceptDecl *NewDecl,
  7913. LookupResult &Previous, bool &AddToScope) {
  7914. AddToScope = true;
  7915. if (Previous.empty())
  7916. return;
  7917. auto *OldConcept = dyn_cast<ConceptDecl>(Previous.getRepresentativeDecl()->getUnderlyingDecl());
  7918. if (!OldConcept) {
  7919. auto *Old = Previous.getRepresentativeDecl();
  7920. Diag(NewDecl->getLocation(), diag::err_redefinition_different_kind)
  7921. << NewDecl->getDeclName();
  7922. notePreviousDefinition(Old, NewDecl->getLocation());
  7923. AddToScope = false;
  7924. return;
  7925. }
  7926. // Check if we can merge with a concept declaration.
  7927. bool IsSame = Context.isSameEntity(NewDecl, OldConcept);
  7928. if (!IsSame) {
  7929. Diag(NewDecl->getLocation(), diag::err_redefinition_different_concept)
  7930. << NewDecl->getDeclName();
  7931. notePreviousDefinition(OldConcept, NewDecl->getLocation());
  7932. AddToScope = false;
  7933. return;
  7934. }
  7935. if (hasReachableDefinition(OldConcept) &&
  7936. IsRedefinitionInModule(NewDecl, OldConcept)) {
  7937. Diag(NewDecl->getLocation(), diag::err_redefinition)
  7938. << NewDecl->getDeclName();
  7939. notePreviousDefinition(OldConcept, NewDecl->getLocation());
  7940. AddToScope = false;
  7941. return;
  7942. }
  7943. if (!Previous.isSingleResult()) {
  7944. // FIXME: we should produce an error in case of ambig and failed lookups.
  7945. // Other decls (e.g. namespaces) also have this shortcoming.
  7946. return;
  7947. }
  7948. // We unwrap canonical decl late to check for module visibility.
  7949. Context.setPrimaryMergedDecl(NewDecl, OldConcept->getCanonicalDecl());
  7950. }
  7951. /// \brief Strips various properties off an implicit instantiation
  7952. /// that has just been explicitly specialized.
  7953. static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) {
  7954. if (MinGW || (isa<FunctionDecl>(D) &&
  7955. cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())) {
  7956. D->dropAttr<DLLImportAttr>();
  7957. D->dropAttr<DLLExportAttr>();
  7958. }
  7959. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
  7960. FD->setInlineSpecified(false);
  7961. }
  7962. /// Compute the diagnostic location for an explicit instantiation
  7963. // declaration or definition.
  7964. static SourceLocation DiagLocForExplicitInstantiation(
  7965. NamedDecl* D, SourceLocation PointOfInstantiation) {
  7966. // Explicit instantiations following a specialization have no effect and
  7967. // hence no PointOfInstantiation. In that case, walk decl backwards
  7968. // until a valid name loc is found.
  7969. SourceLocation PrevDiagLoc = PointOfInstantiation;
  7970. for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
  7971. Prev = Prev->getPreviousDecl()) {
  7972. PrevDiagLoc = Prev->getLocation();
  7973. }
  7974. assert(PrevDiagLoc.isValid() &&
  7975. "Explicit instantiation without point of instantiation?");
  7976. return PrevDiagLoc;
  7977. }
  7978. /// Diagnose cases where we have an explicit template specialization
  7979. /// before/after an explicit template instantiation, producing diagnostics
  7980. /// for those cases where they are required and determining whether the
  7981. /// new specialization/instantiation will have any effect.
  7982. ///
  7983. /// \param NewLoc the location of the new explicit specialization or
  7984. /// instantiation.
  7985. ///
  7986. /// \param NewTSK the kind of the new explicit specialization or instantiation.
  7987. ///
  7988. /// \param PrevDecl the previous declaration of the entity.
  7989. ///
  7990. /// \param PrevTSK the kind of the old explicit specialization or instantiatin.
  7991. ///
  7992. /// \param PrevPointOfInstantiation if valid, indicates where the previous
  7993. /// declaration was instantiated (either implicitly or explicitly).
  7994. ///
  7995. /// \param HasNoEffect will be set to true to indicate that the new
  7996. /// specialization or instantiation has no effect and should be ignored.
  7997. ///
  7998. /// \returns true if there was an error that should prevent the introduction of
  7999. /// the new declaration into the AST, false otherwise.
  8000. bool
  8001. Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
  8002. TemplateSpecializationKind NewTSK,
  8003. NamedDecl *PrevDecl,
  8004. TemplateSpecializationKind PrevTSK,
  8005. SourceLocation PrevPointOfInstantiation,
  8006. bool &HasNoEffect) {
  8007. HasNoEffect = false;
  8008. switch (NewTSK) {
  8009. case TSK_Undeclared:
  8010. case TSK_ImplicitInstantiation:
  8011. assert(
  8012. (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
  8013. "previous declaration must be implicit!");
  8014. return false;
  8015. case TSK_ExplicitSpecialization:
  8016. switch (PrevTSK) {
  8017. case TSK_Undeclared:
  8018. case TSK_ExplicitSpecialization:
  8019. // Okay, we're just specializing something that is either already
  8020. // explicitly specialized or has merely been mentioned without any
  8021. // instantiation.
  8022. return false;
  8023. case TSK_ImplicitInstantiation:
  8024. if (PrevPointOfInstantiation.isInvalid()) {
  8025. // The declaration itself has not actually been instantiated, so it is
  8026. // still okay to specialize it.
  8027. StripImplicitInstantiation(
  8028. PrevDecl,
  8029. Context.getTargetInfo().getTriple().isWindowsGNUEnvironment());
  8030. return false;
  8031. }
  8032. // Fall through
  8033. [[fallthrough]];
  8034. case TSK_ExplicitInstantiationDeclaration:
  8035. case TSK_ExplicitInstantiationDefinition:
  8036. assert((PrevTSK == TSK_ImplicitInstantiation ||
  8037. PrevPointOfInstantiation.isValid()) &&
  8038. "Explicit instantiation without point of instantiation?");
  8039. // C++ [temp.expl.spec]p6:
  8040. // If a template, a member template or the member of a class template
  8041. // is explicitly specialized then that specialization shall be declared
  8042. // before the first use of that specialization that would cause an
  8043. // implicit instantiation to take place, in every translation unit in
  8044. // which such a use occurs; no diagnostic is required.
  8045. for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
  8046. // Is there any previous explicit specialization declaration?
  8047. if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
  8048. return false;
  8049. }
  8050. Diag(NewLoc, diag::err_specialization_after_instantiation)
  8051. << PrevDecl;
  8052. Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
  8053. << (PrevTSK != TSK_ImplicitInstantiation);
  8054. return true;
  8055. }
  8056. llvm_unreachable("The switch over PrevTSK must be exhaustive.");
  8057. case TSK_ExplicitInstantiationDeclaration:
  8058. switch (PrevTSK) {
  8059. case TSK_ExplicitInstantiationDeclaration:
  8060. // This explicit instantiation declaration is redundant (that's okay).
  8061. HasNoEffect = true;
  8062. return false;
  8063. case TSK_Undeclared:
  8064. case TSK_ImplicitInstantiation:
  8065. // We're explicitly instantiating something that may have already been
  8066. // implicitly instantiated; that's fine.
  8067. return false;
  8068. case TSK_ExplicitSpecialization:
  8069. // C++0x [temp.explicit]p4:
  8070. // For a given set of template parameters, if an explicit instantiation
  8071. // of a template appears after a declaration of an explicit
  8072. // specialization for that template, the explicit instantiation has no
  8073. // effect.
  8074. HasNoEffect = true;
  8075. return false;
  8076. case TSK_ExplicitInstantiationDefinition:
  8077. // C++0x [temp.explicit]p10:
  8078. // If an entity is the subject of both an explicit instantiation
  8079. // declaration and an explicit instantiation definition in the same
  8080. // translation unit, the definition shall follow the declaration.
  8081. Diag(NewLoc,
  8082. diag::err_explicit_instantiation_declaration_after_definition);
  8083. // Explicit instantiations following a specialization have no effect and
  8084. // hence no PrevPointOfInstantiation. In that case, walk decl backwards
  8085. // until a valid name loc is found.
  8086. Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
  8087. diag::note_explicit_instantiation_definition_here);
  8088. HasNoEffect = true;
  8089. return false;
  8090. }
  8091. llvm_unreachable("Unexpected TemplateSpecializationKind!");
  8092. case TSK_ExplicitInstantiationDefinition:
  8093. switch (PrevTSK) {
  8094. case TSK_Undeclared:
  8095. case TSK_ImplicitInstantiation:
  8096. // We're explicitly instantiating something that may have already been
  8097. // implicitly instantiated; that's fine.
  8098. return false;
  8099. case TSK_ExplicitSpecialization:
  8100. // C++ DR 259, C++0x [temp.explicit]p4:
  8101. // For a given set of template parameters, if an explicit
  8102. // instantiation of a template appears after a declaration of
  8103. // an explicit specialization for that template, the explicit
  8104. // instantiation has no effect.
  8105. Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
  8106. << PrevDecl;
  8107. Diag(PrevDecl->getLocation(),
  8108. diag::note_previous_template_specialization);
  8109. HasNoEffect = true;
  8110. return false;
  8111. case TSK_ExplicitInstantiationDeclaration:
  8112. // We're explicitly instantiating a definition for something for which we
  8113. // were previously asked to suppress instantiations. That's fine.
  8114. // C++0x [temp.explicit]p4:
  8115. // For a given set of template parameters, if an explicit instantiation
  8116. // of a template appears after a declaration of an explicit
  8117. // specialization for that template, the explicit instantiation has no
  8118. // effect.
  8119. for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
  8120. // Is there any previous explicit specialization declaration?
  8121. if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
  8122. HasNoEffect = true;
  8123. break;
  8124. }
  8125. }
  8126. return false;
  8127. case TSK_ExplicitInstantiationDefinition:
  8128. // C++0x [temp.spec]p5:
  8129. // For a given template and a given set of template-arguments,
  8130. // - an explicit instantiation definition shall appear at most once
  8131. // in a program,
  8132. // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
  8133. Diag(NewLoc, (getLangOpts().MSVCCompat)
  8134. ? diag::ext_explicit_instantiation_duplicate
  8135. : diag::err_explicit_instantiation_duplicate)
  8136. << PrevDecl;
  8137. Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
  8138. diag::note_previous_explicit_instantiation);
  8139. HasNoEffect = true;
  8140. return false;
  8141. }
  8142. }
  8143. llvm_unreachable("Missing specialization/instantiation case?");
  8144. }
  8145. /// Perform semantic analysis for the given dependent function
  8146. /// template specialization.
  8147. ///
  8148. /// The only possible way to get a dependent function template specialization
  8149. /// is with a friend declaration, like so:
  8150. ///
  8151. /// \code
  8152. /// template \<class T> void foo(T);
  8153. /// template \<class T> class A {
  8154. /// friend void foo<>(T);
  8155. /// };
  8156. /// \endcode
  8157. ///
  8158. /// There really isn't any useful analysis we can do here, so we
  8159. /// just store the information.
  8160. bool
  8161. Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
  8162. const TemplateArgumentListInfo &ExplicitTemplateArgs,
  8163. LookupResult &Previous) {
  8164. // Remove anything from Previous that isn't a function template in
  8165. // the correct context.
  8166. DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
  8167. LookupResult::Filter F = Previous.makeFilter();
  8168. enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
  8169. SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
  8170. while (F.hasNext()) {
  8171. NamedDecl *D = F.next()->getUnderlyingDecl();
  8172. if (!isa<FunctionTemplateDecl>(D)) {
  8173. F.erase();
  8174. DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
  8175. continue;
  8176. }
  8177. if (!FDLookupContext->InEnclosingNamespaceSetOf(
  8178. D->getDeclContext()->getRedeclContext())) {
  8179. F.erase();
  8180. DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
  8181. continue;
  8182. }
  8183. }
  8184. F.done();
  8185. if (Previous.empty()) {
  8186. Diag(FD->getLocation(),
  8187. diag::err_dependent_function_template_spec_no_match);
  8188. for (auto &P : DiscardedCandidates)
  8189. Diag(P.second->getLocation(),
  8190. diag::note_dependent_function_template_spec_discard_reason)
  8191. << P.first;
  8192. return true;
  8193. }
  8194. FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
  8195. ExplicitTemplateArgs);
  8196. return false;
  8197. }
  8198. /// Perform semantic analysis for the given function template
  8199. /// specialization.
  8200. ///
  8201. /// This routine performs all of the semantic analysis required for an
  8202. /// explicit function template specialization. On successful completion,
  8203. /// the function declaration \p FD will become a function template
  8204. /// specialization.
  8205. ///
  8206. /// \param FD the function declaration, which will be updated to become a
  8207. /// function template specialization.
  8208. ///
  8209. /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
  8210. /// if any. Note that this may be valid info even when 0 arguments are
  8211. /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
  8212. /// as it anyway contains info on the angle brackets locations.
  8213. ///
  8214. /// \param Previous the set of declarations that may be specialized by
  8215. /// this function specialization.
  8216. ///
  8217. /// \param QualifiedFriend whether this is a lookup for a qualified friend
  8218. /// declaration with no explicit template argument list that might be
  8219. /// befriending a function template specialization.
  8220. bool Sema::CheckFunctionTemplateSpecialization(
  8221. FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
  8222. LookupResult &Previous, bool QualifiedFriend) {
  8223. // The set of function template specializations that could match this
  8224. // explicit function template specialization.
  8225. UnresolvedSet<8> Candidates;
  8226. TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
  8227. /*ForTakingAddress=*/false);
  8228. llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
  8229. ConvertedTemplateArgs;
  8230. DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
  8231. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  8232. I != E; ++I) {
  8233. NamedDecl *Ovl = (*I)->getUnderlyingDecl();
  8234. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
  8235. // Only consider templates found within the same semantic lookup scope as
  8236. // FD.
  8237. if (!FDLookupContext->InEnclosingNamespaceSetOf(
  8238. Ovl->getDeclContext()->getRedeclContext()))
  8239. continue;
  8240. // When matching a constexpr member function template specialization
  8241. // against the primary template, we don't yet know whether the
  8242. // specialization has an implicit 'const' (because we don't know whether
  8243. // it will be a static member function until we know which template it
  8244. // specializes), so adjust it now assuming it specializes this template.
  8245. QualType FT = FD->getType();
  8246. if (FD->isConstexpr()) {
  8247. CXXMethodDecl *OldMD =
  8248. dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
  8249. if (OldMD && OldMD->isConst()) {
  8250. const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
  8251. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  8252. EPI.TypeQuals.addConst();
  8253. FT = Context.getFunctionType(FPT->getReturnType(),
  8254. FPT->getParamTypes(), EPI);
  8255. }
  8256. }
  8257. TemplateArgumentListInfo Args;
  8258. if (ExplicitTemplateArgs)
  8259. Args = *ExplicitTemplateArgs;
  8260. // C++ [temp.expl.spec]p11:
  8261. // A trailing template-argument can be left unspecified in the
  8262. // template-id naming an explicit function template specialization
  8263. // provided it can be deduced from the function argument type.
  8264. // Perform template argument deduction to determine whether we may be
  8265. // specializing this template.
  8266. // FIXME: It is somewhat wasteful to build
  8267. TemplateDeductionInfo Info(FailedCandidates.getLocation());
  8268. FunctionDecl *Specialization = nullptr;
  8269. if (TemplateDeductionResult TDK = DeduceTemplateArguments(
  8270. cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
  8271. ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
  8272. Info)) {
  8273. // Template argument deduction failed; record why it failed, so
  8274. // that we can provide nifty diagnostics.
  8275. FailedCandidates.addCandidate().set(
  8276. I.getPair(), FunTmpl->getTemplatedDecl(),
  8277. MakeDeductionFailureInfo(Context, TDK, Info));
  8278. (void)TDK;
  8279. continue;
  8280. }
  8281. // Target attributes are part of the cuda function signature, so
  8282. // the deduced template's cuda target must match that of the
  8283. // specialization. Given that C++ template deduction does not
  8284. // take target attributes into account, we reject candidates
  8285. // here that have a different target.
  8286. if (LangOpts.CUDA &&
  8287. IdentifyCUDATarget(Specialization,
  8288. /* IgnoreImplicitHDAttr = */ true) !=
  8289. IdentifyCUDATarget(FD, /* IgnoreImplicitHDAttr = */ true)) {
  8290. FailedCandidates.addCandidate().set(
  8291. I.getPair(), FunTmpl->getTemplatedDecl(),
  8292. MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
  8293. continue;
  8294. }
  8295. // Record this candidate.
  8296. if (ExplicitTemplateArgs)
  8297. ConvertedTemplateArgs[Specialization] = std::move(Args);
  8298. Candidates.addDecl(Specialization, I.getAccess());
  8299. }
  8300. }
  8301. // For a qualified friend declaration (with no explicit marker to indicate
  8302. // that a template specialization was intended), note all (template and
  8303. // non-template) candidates.
  8304. if (QualifiedFriend && Candidates.empty()) {
  8305. Diag(FD->getLocation(), diag::err_qualified_friend_no_match)
  8306. << FD->getDeclName() << FDLookupContext;
  8307. // FIXME: We should form a single candidate list and diagnose all
  8308. // candidates at once, to get proper sorting and limiting.
  8309. for (auto *OldND : Previous) {
  8310. if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl()))
  8311. NoteOverloadCandidate(OldND, OldFD, CRK_None, FD->getType(), false);
  8312. }
  8313. FailedCandidates.NoteCandidates(*this, FD->getLocation());
  8314. return true;
  8315. }
  8316. // Find the most specialized function template.
  8317. UnresolvedSetIterator Result = getMostSpecialized(
  8318. Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),
  8319. PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
  8320. PDiag(diag::err_function_template_spec_ambiguous)
  8321. << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
  8322. PDiag(diag::note_function_template_spec_matched));
  8323. if (Result == Candidates.end())
  8324. return true;
  8325. // Ignore access information; it doesn't figure into redeclaration checking.
  8326. FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
  8327. FunctionTemplateSpecializationInfo *SpecInfo
  8328. = Specialization->getTemplateSpecializationInfo();
  8329. assert(SpecInfo && "Function template specialization info missing?");
  8330. // Note: do not overwrite location info if previous template
  8331. // specialization kind was explicit.
  8332. TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
  8333. if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
  8334. Specialization->setLocation(FD->getLocation());
  8335. Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
  8336. // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
  8337. // function can differ from the template declaration with respect to
  8338. // the constexpr specifier.
  8339. // FIXME: We need an update record for this AST mutation.
  8340. // FIXME: What if there are multiple such prior declarations (for instance,
  8341. // from different modules)?
  8342. Specialization->setConstexprKind(FD->getConstexprKind());
  8343. }
  8344. // FIXME: Check if the prior specialization has a point of instantiation.
  8345. // If so, we have run afoul of .
  8346. // If this is a friend declaration, then we're not really declaring
  8347. // an explicit specialization.
  8348. bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
  8349. // Check the scope of this explicit specialization.
  8350. if (!isFriend &&
  8351. CheckTemplateSpecializationScope(*this,
  8352. Specialization->getPrimaryTemplate(),
  8353. Specialization, FD->getLocation(),
  8354. false))
  8355. return true;
  8356. // C++ [temp.expl.spec]p6:
  8357. // If a template, a member template or the member of a class template is
  8358. // explicitly specialized then that specialization shall be declared
  8359. // before the first use of that specialization that would cause an implicit
  8360. // instantiation to take place, in every translation unit in which such a
  8361. // use occurs; no diagnostic is required.
  8362. bool HasNoEffect = false;
  8363. if (!isFriend &&
  8364. CheckSpecializationInstantiationRedecl(FD->getLocation(),
  8365. TSK_ExplicitSpecialization,
  8366. Specialization,
  8367. SpecInfo->getTemplateSpecializationKind(),
  8368. SpecInfo->getPointOfInstantiation(),
  8369. HasNoEffect))
  8370. return true;
  8371. // Mark the prior declaration as an explicit specialization, so that later
  8372. // clients know that this is an explicit specialization.
  8373. if (!isFriend) {
  8374. // Since explicit specializations do not inherit '=delete' from their
  8375. // primary function template - check if the 'specialization' that was
  8376. // implicitly generated (during template argument deduction for partial
  8377. // ordering) from the most specialized of all the function templates that
  8378. // 'FD' could have been specializing, has a 'deleted' definition. If so,
  8379. // first check that it was implicitly generated during template argument
  8380. // deduction by making sure it wasn't referenced, and then reset the deleted
  8381. // flag to not-deleted, so that we can inherit that information from 'FD'.
  8382. if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
  8383. !Specialization->getCanonicalDecl()->isReferenced()) {
  8384. // FIXME: This assert will not hold in the presence of modules.
  8385. assert(
  8386. Specialization->getCanonicalDecl() == Specialization &&
  8387. "This must be the only existing declaration of this specialization");
  8388. // FIXME: We need an update record for this AST mutation.
  8389. Specialization->setDeletedAsWritten(false);
  8390. }
  8391. // FIXME: We need an update record for this AST mutation.
  8392. SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
  8393. MarkUnusedFileScopedDecl(Specialization);
  8394. }
  8395. // Turn the given function declaration into a function template
  8396. // specialization, with the template arguments from the previous
  8397. // specialization.
  8398. // Take copies of (semantic and syntactic) template argument lists.
  8399. const TemplateArgumentList* TemplArgs = new (Context)
  8400. TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
  8401. FD->setFunctionTemplateSpecialization(
  8402. Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
  8403. SpecInfo->getTemplateSpecializationKind(),
  8404. ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
  8405. // A function template specialization inherits the target attributes
  8406. // of its template. (We require the attributes explicitly in the
  8407. // code to match, but a template may have implicit attributes by
  8408. // virtue e.g. of being constexpr, and it passes these implicit
  8409. // attributes on to its specializations.)
  8410. if (LangOpts.CUDA)
  8411. inheritCUDATargetAttrs(FD, *Specialization->getPrimaryTemplate());
  8412. // The "previous declaration" for this function template specialization is
  8413. // the prior function template specialization.
  8414. Previous.clear();
  8415. Previous.addDecl(Specialization);
  8416. return false;
  8417. }
  8418. /// Perform semantic analysis for the given non-template member
  8419. /// specialization.
  8420. ///
  8421. /// This routine performs all of the semantic analysis required for an
  8422. /// explicit member function specialization. On successful completion,
  8423. /// the function declaration \p FD will become a member function
  8424. /// specialization.
  8425. ///
  8426. /// \param Member the member declaration, which will be updated to become a
  8427. /// specialization.
  8428. ///
  8429. /// \param Previous the set of declarations, one of which may be specialized
  8430. /// by this function specialization; the set will be modified to contain the
  8431. /// redeclared member.
  8432. bool
  8433. Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
  8434. assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
  8435. // Try to find the member we are instantiating.
  8436. NamedDecl *FoundInstantiation = nullptr;
  8437. NamedDecl *Instantiation = nullptr;
  8438. NamedDecl *InstantiatedFrom = nullptr;
  8439. MemberSpecializationInfo *MSInfo = nullptr;
  8440. if (Previous.empty()) {
  8441. // Nowhere to look anyway.
  8442. } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
  8443. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  8444. I != E; ++I) {
  8445. NamedDecl *D = (*I)->getUnderlyingDecl();
  8446. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
  8447. QualType Adjusted = Function->getType();
  8448. if (!hasExplicitCallingConv(Adjusted))
  8449. Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
  8450. // This doesn't handle deduced return types, but both function
  8451. // declarations should be undeduced at this point.
  8452. if (Context.hasSameType(Adjusted, Method->getType())) {
  8453. FoundInstantiation = *I;
  8454. Instantiation = Method;
  8455. InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
  8456. MSInfo = Method->getMemberSpecializationInfo();
  8457. break;
  8458. }
  8459. }
  8460. }
  8461. } else if (isa<VarDecl>(Member)) {
  8462. VarDecl *PrevVar;
  8463. if (Previous.isSingleResult() &&
  8464. (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
  8465. if (PrevVar->isStaticDataMember()) {
  8466. FoundInstantiation = Previous.getRepresentativeDecl();
  8467. Instantiation = PrevVar;
  8468. InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
  8469. MSInfo = PrevVar->getMemberSpecializationInfo();
  8470. }
  8471. } else if (isa<RecordDecl>(Member)) {
  8472. CXXRecordDecl *PrevRecord;
  8473. if (Previous.isSingleResult() &&
  8474. (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
  8475. FoundInstantiation = Previous.getRepresentativeDecl();
  8476. Instantiation = PrevRecord;
  8477. InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
  8478. MSInfo = PrevRecord->getMemberSpecializationInfo();
  8479. }
  8480. } else if (isa<EnumDecl>(Member)) {
  8481. EnumDecl *PrevEnum;
  8482. if (Previous.isSingleResult() &&
  8483. (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
  8484. FoundInstantiation = Previous.getRepresentativeDecl();
  8485. Instantiation = PrevEnum;
  8486. InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
  8487. MSInfo = PrevEnum->getMemberSpecializationInfo();
  8488. }
  8489. }
  8490. if (!Instantiation) {
  8491. // There is no previous declaration that matches. Since member
  8492. // specializations are always out-of-line, the caller will complain about
  8493. // this mismatch later.
  8494. return false;
  8495. }
  8496. // A member specialization in a friend declaration isn't really declaring
  8497. // an explicit specialization, just identifying a specific (possibly implicit)
  8498. // specialization. Don't change the template specialization kind.
  8499. //
  8500. // FIXME: Is this really valid? Other compilers reject.
  8501. if (Member->getFriendObjectKind() != Decl::FOK_None) {
  8502. // Preserve instantiation information.
  8503. if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
  8504. cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
  8505. cast<CXXMethodDecl>(InstantiatedFrom),
  8506. cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
  8507. } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
  8508. cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
  8509. cast<CXXRecordDecl>(InstantiatedFrom),
  8510. cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
  8511. }
  8512. Previous.clear();
  8513. Previous.addDecl(FoundInstantiation);
  8514. return false;
  8515. }
  8516. // Make sure that this is a specialization of a member.
  8517. if (!InstantiatedFrom) {
  8518. Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
  8519. << Member;
  8520. Diag(Instantiation->getLocation(), diag::note_specialized_decl);
  8521. return true;
  8522. }
  8523. // C++ [temp.expl.spec]p6:
  8524. // If a template, a member template or the member of a class template is
  8525. // explicitly specialized then that specialization shall be declared
  8526. // before the first use of that specialization that would cause an implicit
  8527. // instantiation to take place, in every translation unit in which such a
  8528. // use occurs; no diagnostic is required.
  8529. assert(MSInfo && "Member specialization info missing?");
  8530. bool HasNoEffect = false;
  8531. if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
  8532. TSK_ExplicitSpecialization,
  8533. Instantiation,
  8534. MSInfo->getTemplateSpecializationKind(),
  8535. MSInfo->getPointOfInstantiation(),
  8536. HasNoEffect))
  8537. return true;
  8538. // Check the scope of this explicit specialization.
  8539. if (CheckTemplateSpecializationScope(*this,
  8540. InstantiatedFrom,
  8541. Instantiation, Member->getLocation(),
  8542. false))
  8543. return true;
  8544. // Note that this member specialization is an "instantiation of" the
  8545. // corresponding member of the original template.
  8546. if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
  8547. FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
  8548. if (InstantiationFunction->getTemplateSpecializationKind() ==
  8549. TSK_ImplicitInstantiation) {
  8550. // Explicit specializations of member functions of class templates do not
  8551. // inherit '=delete' from the member function they are specializing.
  8552. if (InstantiationFunction->isDeleted()) {
  8553. // FIXME: This assert will not hold in the presence of modules.
  8554. assert(InstantiationFunction->getCanonicalDecl() ==
  8555. InstantiationFunction);
  8556. // FIXME: We need an update record for this AST mutation.
  8557. InstantiationFunction->setDeletedAsWritten(false);
  8558. }
  8559. }
  8560. MemberFunction->setInstantiationOfMemberFunction(
  8561. cast<CXXMethodDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
  8562. } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
  8563. MemberVar->setInstantiationOfStaticDataMember(
  8564. cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
  8565. } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
  8566. MemberClass->setInstantiationOfMemberClass(
  8567. cast<CXXRecordDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
  8568. } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
  8569. MemberEnum->setInstantiationOfMemberEnum(
  8570. cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
  8571. } else {
  8572. llvm_unreachable("unknown member specialization kind");
  8573. }
  8574. // Save the caller the trouble of having to figure out which declaration
  8575. // this specialization matches.
  8576. Previous.clear();
  8577. Previous.addDecl(FoundInstantiation);
  8578. return false;
  8579. }
  8580. /// Complete the explicit specialization of a member of a class template by
  8581. /// updating the instantiated member to be marked as an explicit specialization.
  8582. ///
  8583. /// \param OrigD The member declaration instantiated from the template.
  8584. /// \param Loc The location of the explicit specialization of the member.
  8585. template<typename DeclT>
  8586. static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
  8587. SourceLocation Loc) {
  8588. if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
  8589. return;
  8590. // FIXME: Inform AST mutation listeners of this AST mutation.
  8591. // FIXME: If there are multiple in-class declarations of the member (from
  8592. // multiple modules, or a declaration and later definition of a member type),
  8593. // should we update all of them?
  8594. OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
  8595. OrigD->setLocation(Loc);
  8596. }
  8597. void Sema::CompleteMemberSpecialization(NamedDecl *Member,
  8598. LookupResult &Previous) {
  8599. NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
  8600. if (Instantiation == Member)
  8601. return;
  8602. if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
  8603. completeMemberSpecializationImpl(*this, Function, Member->getLocation());
  8604. else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
  8605. completeMemberSpecializationImpl(*this, Var, Member->getLocation());
  8606. else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
  8607. completeMemberSpecializationImpl(*this, Record, Member->getLocation());
  8608. else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
  8609. completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
  8610. else
  8611. llvm_unreachable("unknown member specialization kind");
  8612. }
  8613. /// Check the scope of an explicit instantiation.
  8614. ///
  8615. /// \returns true if a serious error occurs, false otherwise.
  8616. static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
  8617. SourceLocation InstLoc,
  8618. bool WasQualifiedName) {
  8619. DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
  8620. DeclContext *CurContext = S.CurContext->getRedeclContext();
  8621. if (CurContext->isRecord()) {
  8622. S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
  8623. << D;
  8624. return true;
  8625. }
  8626. // C++11 [temp.explicit]p3:
  8627. // An explicit instantiation shall appear in an enclosing namespace of its
  8628. // template. If the name declared in the explicit instantiation is an
  8629. // unqualified name, the explicit instantiation shall appear in the
  8630. // namespace where its template is declared or, if that namespace is inline
  8631. // (7.3.1), any namespace from its enclosing namespace set.
  8632. //
  8633. // This is DR275, which we do not retroactively apply to C++98/03.
  8634. if (WasQualifiedName) {
  8635. if (CurContext->Encloses(OrigContext))
  8636. return false;
  8637. } else {
  8638. if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
  8639. return false;
  8640. }
  8641. if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
  8642. if (WasQualifiedName)
  8643. S.Diag(InstLoc,
  8644. S.getLangOpts().CPlusPlus11?
  8645. diag::err_explicit_instantiation_out_of_scope :
  8646. diag::warn_explicit_instantiation_out_of_scope_0x)
  8647. << D << NS;
  8648. else
  8649. S.Diag(InstLoc,
  8650. S.getLangOpts().CPlusPlus11?
  8651. diag::err_explicit_instantiation_unqualified_wrong_namespace :
  8652. diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
  8653. << D << NS;
  8654. } else
  8655. S.Diag(InstLoc,
  8656. S.getLangOpts().CPlusPlus11?
  8657. diag::err_explicit_instantiation_must_be_global :
  8658. diag::warn_explicit_instantiation_must_be_global_0x)
  8659. << D;
  8660. S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
  8661. return false;
  8662. }
  8663. /// Common checks for whether an explicit instantiation of \p D is valid.
  8664. static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D,
  8665. SourceLocation InstLoc,
  8666. bool WasQualifiedName,
  8667. TemplateSpecializationKind TSK) {
  8668. // C++ [temp.explicit]p13:
  8669. // An explicit instantiation declaration shall not name a specialization of
  8670. // a template with internal linkage.
  8671. if (TSK == TSK_ExplicitInstantiationDeclaration &&
  8672. D->getFormalLinkage() == InternalLinkage) {
  8673. S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D;
  8674. return true;
  8675. }
  8676. // C++11 [temp.explicit]p3: [DR 275]
  8677. // An explicit instantiation shall appear in an enclosing namespace of its
  8678. // template.
  8679. if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
  8680. return true;
  8681. return false;
  8682. }
  8683. /// Determine whether the given scope specifier has a template-id in it.
  8684. static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
  8685. if (!SS.isSet())
  8686. return false;
  8687. // C++11 [temp.explicit]p3:
  8688. // If the explicit instantiation is for a member function, a member class
  8689. // or a static data member of a class template specialization, the name of
  8690. // the class template specialization in the qualified-id for the member
  8691. // name shall be a simple-template-id.
  8692. //
  8693. // C++98 has the same restriction, just worded differently.
  8694. for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
  8695. NNS = NNS->getPrefix())
  8696. if (const Type *T = NNS->getAsType())
  8697. if (isa<TemplateSpecializationType>(T))
  8698. return true;
  8699. return false;
  8700. }
  8701. /// Make a dllexport or dllimport attr on a class template specialization take
  8702. /// effect.
  8703. static void dllExportImportClassTemplateSpecialization(
  8704. Sema &S, ClassTemplateSpecializationDecl *Def) {
  8705. auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
  8706. assert(A && "dllExportImportClassTemplateSpecialization called "
  8707. "on Def without dllexport or dllimport");
  8708. // We reject explicit instantiations in class scope, so there should
  8709. // never be any delayed exported classes to worry about.
  8710. assert(S.DelayedDllExportClasses.empty() &&
  8711. "delayed exports present at explicit instantiation");
  8712. S.checkClassLevelDLLAttribute(Def);
  8713. // Propagate attribute to base class templates.
  8714. for (auto &B : Def->bases()) {
  8715. if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
  8716. B.getType()->getAsCXXRecordDecl()))
  8717. S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getBeginLoc());
  8718. }
  8719. S.referenceDLLExportedClassMethods();
  8720. }
  8721. // Explicit instantiation of a class template specialization
  8722. DeclResult Sema::ActOnExplicitInstantiation(
  8723. Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
  8724. unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
  8725. TemplateTy TemplateD, SourceLocation TemplateNameLoc,
  8726. SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
  8727. SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
  8728. // Find the class template we're specializing
  8729. TemplateName Name = TemplateD.get();
  8730. TemplateDecl *TD = Name.getAsTemplateDecl();
  8731. // Check that the specialization uses the same tag kind as the
  8732. // original template.
  8733. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  8734. assert(Kind != TTK_Enum &&
  8735. "Invalid enum tag in class template explicit instantiation!");
  8736. ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
  8737. if (!ClassTemplate) {
  8738. NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
  8739. Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
  8740. Diag(TD->getLocation(), diag::note_previous_use);
  8741. return true;
  8742. }
  8743. if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
  8744. Kind, /*isDefinition*/false, KWLoc,
  8745. ClassTemplate->getIdentifier())) {
  8746. Diag(KWLoc, diag::err_use_with_wrong_tag)
  8747. << ClassTemplate
  8748. << FixItHint::CreateReplacement(KWLoc,
  8749. ClassTemplate->getTemplatedDecl()->getKindName());
  8750. Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
  8751. diag::note_previous_use);
  8752. Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
  8753. }
  8754. // C++0x [temp.explicit]p2:
  8755. // There are two forms of explicit instantiation: an explicit instantiation
  8756. // definition and an explicit instantiation declaration. An explicit
  8757. // instantiation declaration begins with the extern keyword. [...]
  8758. TemplateSpecializationKind TSK = ExternLoc.isInvalid()
  8759. ? TSK_ExplicitInstantiationDefinition
  8760. : TSK_ExplicitInstantiationDeclaration;
  8761. if (TSK == TSK_ExplicitInstantiationDeclaration &&
  8762. !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
  8763. // Check for dllexport class template instantiation declarations,
  8764. // except for MinGW mode.
  8765. for (const ParsedAttr &AL : Attr) {
  8766. if (AL.getKind() == ParsedAttr::AT_DLLExport) {
  8767. Diag(ExternLoc,
  8768. diag::warn_attribute_dllexport_explicit_instantiation_decl);
  8769. Diag(AL.getLoc(), diag::note_attribute);
  8770. break;
  8771. }
  8772. }
  8773. if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
  8774. Diag(ExternLoc,
  8775. diag::warn_attribute_dllexport_explicit_instantiation_decl);
  8776. Diag(A->getLocation(), diag::note_attribute);
  8777. }
  8778. }
  8779. // In MSVC mode, dllimported explicit instantiation definitions are treated as
  8780. // instantiation declarations for most purposes.
  8781. bool DLLImportExplicitInstantiationDef = false;
  8782. if (TSK == TSK_ExplicitInstantiationDefinition &&
  8783. Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  8784. // Check for dllimport class template instantiation definitions.
  8785. bool DLLImport =
  8786. ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
  8787. for (const ParsedAttr &AL : Attr) {
  8788. if (AL.getKind() == ParsedAttr::AT_DLLImport)
  8789. DLLImport = true;
  8790. if (AL.getKind() == ParsedAttr::AT_DLLExport) {
  8791. // dllexport trumps dllimport here.
  8792. DLLImport = false;
  8793. break;
  8794. }
  8795. }
  8796. if (DLLImport) {
  8797. TSK = TSK_ExplicitInstantiationDeclaration;
  8798. DLLImportExplicitInstantiationDef = true;
  8799. }
  8800. }
  8801. // Translate the parser's template argument list in our AST format.
  8802. TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
  8803. translateTemplateArguments(TemplateArgsIn, TemplateArgs);
  8804. // Check that the template argument list is well-formed for this
  8805. // template.
  8806. SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
  8807. if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
  8808. false, SugaredConverted, CanonicalConverted,
  8809. /*UpdateArgsWithConversions=*/true))
  8810. return true;
  8811. // Find the class template specialization declaration that
  8812. // corresponds to these arguments.
  8813. void *InsertPos = nullptr;
  8814. ClassTemplateSpecializationDecl *PrevDecl =
  8815. ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
  8816. TemplateSpecializationKind PrevDecl_TSK
  8817. = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
  8818. if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
  8819. Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
  8820. // Check for dllexport class template instantiation definitions in MinGW
  8821. // mode, if a previous declaration of the instantiation was seen.
  8822. for (const ParsedAttr &AL : Attr) {
  8823. if (AL.getKind() == ParsedAttr::AT_DLLExport) {
  8824. Diag(AL.getLoc(),
  8825. diag::warn_attribute_dllexport_explicit_instantiation_def);
  8826. break;
  8827. }
  8828. }
  8829. }
  8830. if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc,
  8831. SS.isSet(), TSK))
  8832. return true;
  8833. ClassTemplateSpecializationDecl *Specialization = nullptr;
  8834. bool HasNoEffect = false;
  8835. if (PrevDecl) {
  8836. if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
  8837. PrevDecl, PrevDecl_TSK,
  8838. PrevDecl->getPointOfInstantiation(),
  8839. HasNoEffect))
  8840. return PrevDecl;
  8841. // Even though HasNoEffect == true means that this explicit instantiation
  8842. // has no effect on semantics, we go on to put its syntax in the AST.
  8843. if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
  8844. PrevDecl_TSK == TSK_Undeclared) {
  8845. // Since the only prior class template specialization with these
  8846. // arguments was referenced but not declared, reuse that
  8847. // declaration node as our own, updating the source location
  8848. // for the template name to reflect our new declaration.
  8849. // (Other source locations will be updated later.)
  8850. Specialization = PrevDecl;
  8851. Specialization->setLocation(TemplateNameLoc);
  8852. PrevDecl = nullptr;
  8853. }
  8854. if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
  8855. DLLImportExplicitInstantiationDef) {
  8856. // The new specialization might add a dllimport attribute.
  8857. HasNoEffect = false;
  8858. }
  8859. }
  8860. if (!Specialization) {
  8861. // Create a new class template specialization declaration node for
  8862. // this explicit specialization.
  8863. Specialization = ClassTemplateSpecializationDecl::Create(
  8864. Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
  8865. ClassTemplate, CanonicalConverted, PrevDecl);
  8866. SetNestedNameSpecifier(*this, Specialization, SS);
  8867. if (!HasNoEffect && !PrevDecl) {
  8868. // Insert the new specialization.
  8869. ClassTemplate->AddSpecialization(Specialization, InsertPos);
  8870. }
  8871. }
  8872. // Build the fully-sugared type for this explicit instantiation as
  8873. // the user wrote in the explicit instantiation itself. This means
  8874. // that we'll pretty-print the type retrieved from the
  8875. // specialization's declaration the way that the user actually wrote
  8876. // the explicit instantiation, rather than formatting the name based
  8877. // on the "canonical" representation used to store the template
  8878. // arguments in the specialization.
  8879. TypeSourceInfo *WrittenTy
  8880. = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
  8881. TemplateArgs,
  8882. Context.getTypeDeclType(Specialization));
  8883. Specialization->setTypeAsWritten(WrittenTy);
  8884. // Set source locations for keywords.
  8885. Specialization->setExternLoc(ExternLoc);
  8886. Specialization->setTemplateKeywordLoc(TemplateLoc);
  8887. Specialization->setBraceRange(SourceRange());
  8888. bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
  8889. ProcessDeclAttributeList(S, Specialization, Attr);
  8890. // Add the explicit instantiation into its lexical context. However,
  8891. // since explicit instantiations are never found by name lookup, we
  8892. // just put it into the declaration context directly.
  8893. Specialization->setLexicalDeclContext(CurContext);
  8894. CurContext->addDecl(Specialization);
  8895. // Syntax is now OK, so return if it has no other effect on semantics.
  8896. if (HasNoEffect) {
  8897. // Set the template specialization kind.
  8898. Specialization->setTemplateSpecializationKind(TSK);
  8899. return Specialization;
  8900. }
  8901. // C++ [temp.explicit]p3:
  8902. // A definition of a class template or class member template
  8903. // shall be in scope at the point of the explicit instantiation of
  8904. // the class template or class member template.
  8905. //
  8906. // This check comes when we actually try to perform the
  8907. // instantiation.
  8908. ClassTemplateSpecializationDecl *Def
  8909. = cast_or_null<ClassTemplateSpecializationDecl>(
  8910. Specialization->getDefinition());
  8911. if (!Def)
  8912. InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
  8913. else if (TSK == TSK_ExplicitInstantiationDefinition) {
  8914. MarkVTableUsed(TemplateNameLoc, Specialization, true);
  8915. Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
  8916. }
  8917. // Instantiate the members of this class template specialization.
  8918. Def = cast_or_null<ClassTemplateSpecializationDecl>(
  8919. Specialization->getDefinition());
  8920. if (Def) {
  8921. TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
  8922. // Fix a TSK_ExplicitInstantiationDeclaration followed by a
  8923. // TSK_ExplicitInstantiationDefinition
  8924. if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
  8925. (TSK == TSK_ExplicitInstantiationDefinition ||
  8926. DLLImportExplicitInstantiationDef)) {
  8927. // FIXME: Need to notify the ASTMutationListener that we did this.
  8928. Def->setTemplateSpecializationKind(TSK);
  8929. if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
  8930. (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
  8931. !Context.getTargetInfo().getTriple().isPS())) {
  8932. // An explicit instantiation definition can add a dll attribute to a
  8933. // template with a previous instantiation declaration. MinGW doesn't
  8934. // allow this.
  8935. auto *A = cast<InheritableAttr>(
  8936. getDLLAttr(Specialization)->clone(getASTContext()));
  8937. A->setInherited(true);
  8938. Def->addAttr(A);
  8939. dllExportImportClassTemplateSpecialization(*this, Def);
  8940. }
  8941. }
  8942. // Fix a TSK_ImplicitInstantiation followed by a
  8943. // TSK_ExplicitInstantiationDefinition
  8944. bool NewlyDLLExported =
  8945. !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
  8946. if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
  8947. (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
  8948. !Context.getTargetInfo().getTriple().isPS())) {
  8949. // An explicit instantiation definition can add a dll attribute to a
  8950. // template with a previous implicit instantiation. MinGW doesn't allow
  8951. // this. We limit clang to only adding dllexport, to avoid potentially
  8952. // strange codegen behavior. For example, if we extend this conditional
  8953. // to dllimport, and we have a source file calling a method on an
  8954. // implicitly instantiated template class instance and then declaring a
  8955. // dllimport explicit instantiation definition for the same template
  8956. // class, the codegen for the method call will not respect the dllimport,
  8957. // while it will with cl. The Def will already have the DLL attribute,
  8958. // since the Def and Specialization will be the same in the case of
  8959. // Old_TSK == TSK_ImplicitInstantiation, and we already added the
  8960. // attribute to the Specialization; we just need to make it take effect.
  8961. assert(Def == Specialization &&
  8962. "Def and Specialization should match for implicit instantiation");
  8963. dllExportImportClassTemplateSpecialization(*this, Def);
  8964. }
  8965. // In MinGW mode, export the template instantiation if the declaration
  8966. // was marked dllexport.
  8967. if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
  8968. Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
  8969. PrevDecl->hasAttr<DLLExportAttr>()) {
  8970. dllExportImportClassTemplateSpecialization(*this, Def);
  8971. }
  8972. if (Def->hasAttr<MSInheritanceAttr>()) {
  8973. Specialization->addAttr(Def->getAttr<MSInheritanceAttr>());
  8974. Consumer.AssignInheritanceModel(Specialization);
  8975. }
  8976. // Set the template specialization kind. Make sure it is set before
  8977. // instantiating the members which will trigger ASTConsumer callbacks.
  8978. Specialization->setTemplateSpecializationKind(TSK);
  8979. InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
  8980. } else {
  8981. // Set the template specialization kind.
  8982. Specialization->setTemplateSpecializationKind(TSK);
  8983. }
  8984. return Specialization;
  8985. }
  8986. // Explicit instantiation of a member class of a class template.
  8987. DeclResult
  8988. Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
  8989. SourceLocation TemplateLoc, unsigned TagSpec,
  8990. SourceLocation KWLoc, CXXScopeSpec &SS,
  8991. IdentifierInfo *Name, SourceLocation NameLoc,
  8992. const ParsedAttributesView &Attr) {
  8993. bool Owned = false;
  8994. bool IsDependent = false;
  8995. Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference, KWLoc, SS, Name,
  8996. NameLoc, Attr, AS_none, /*ModulePrivateLoc=*/SourceLocation(),
  8997. MultiTemplateParamsArg(), Owned, IsDependent, SourceLocation(),
  8998. false, TypeResult(), /*IsTypeSpecifier*/ false,
  8999. /*IsTemplateParamOrArg*/ false, /*OOK=*/OOK_Outside).get();
  9000. assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
  9001. if (!TagD)
  9002. return true;
  9003. TagDecl *Tag = cast<TagDecl>(TagD);
  9004. assert(!Tag->isEnum() && "shouldn't see enumerations here");
  9005. if (Tag->isInvalidDecl())
  9006. return true;
  9007. CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
  9008. CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
  9009. if (!Pattern) {
  9010. Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
  9011. << Context.getTypeDeclType(Record);
  9012. Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
  9013. return true;
  9014. }
  9015. // C++0x [temp.explicit]p2:
  9016. // If the explicit instantiation is for a class or member class, the
  9017. // elaborated-type-specifier in the declaration shall include a
  9018. // simple-template-id.
  9019. //
  9020. // C++98 has the same restriction, just worded differently.
  9021. if (!ScopeSpecifierHasTemplateId(SS))
  9022. Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
  9023. << Record << SS.getRange();
  9024. // C++0x [temp.explicit]p2:
  9025. // There are two forms of explicit instantiation: an explicit instantiation
  9026. // definition and an explicit instantiation declaration. An explicit
  9027. // instantiation declaration begins with the extern keyword. [...]
  9028. TemplateSpecializationKind TSK
  9029. = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
  9030. : TSK_ExplicitInstantiationDeclaration;
  9031. CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK);
  9032. // Verify that it is okay to explicitly instantiate here.
  9033. CXXRecordDecl *PrevDecl
  9034. = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
  9035. if (!PrevDecl && Record->getDefinition())
  9036. PrevDecl = Record;
  9037. if (PrevDecl) {
  9038. MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
  9039. bool HasNoEffect = false;
  9040. assert(MSInfo && "No member specialization information?");
  9041. if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
  9042. PrevDecl,
  9043. MSInfo->getTemplateSpecializationKind(),
  9044. MSInfo->getPointOfInstantiation(),
  9045. HasNoEffect))
  9046. return true;
  9047. if (HasNoEffect)
  9048. return TagD;
  9049. }
  9050. CXXRecordDecl *RecordDef
  9051. = cast_or_null<CXXRecordDecl>(Record->getDefinition());
  9052. if (!RecordDef) {
  9053. // C++ [temp.explicit]p3:
  9054. // A definition of a member class of a class template shall be in scope
  9055. // at the point of an explicit instantiation of the member class.
  9056. CXXRecordDecl *Def
  9057. = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
  9058. if (!Def) {
  9059. Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
  9060. << 0 << Record->getDeclName() << Record->getDeclContext();
  9061. Diag(Pattern->getLocation(), diag::note_forward_declaration)
  9062. << Pattern;
  9063. return true;
  9064. } else {
  9065. if (InstantiateClass(NameLoc, Record, Def,
  9066. getTemplateInstantiationArgs(Record),
  9067. TSK))
  9068. return true;
  9069. RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
  9070. if (!RecordDef)
  9071. return true;
  9072. }
  9073. }
  9074. // Instantiate all of the members of the class.
  9075. InstantiateClassMembers(NameLoc, RecordDef,
  9076. getTemplateInstantiationArgs(Record), TSK);
  9077. if (TSK == TSK_ExplicitInstantiationDefinition)
  9078. MarkVTableUsed(NameLoc, RecordDef, true);
  9079. // FIXME: We don't have any representation for explicit instantiations of
  9080. // member classes. Such a representation is not needed for compilation, but it
  9081. // should be available for clients that want to see all of the declarations in
  9082. // the source code.
  9083. return TagD;
  9084. }
  9085. DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
  9086. SourceLocation ExternLoc,
  9087. SourceLocation TemplateLoc,
  9088. Declarator &D) {
  9089. // Explicit instantiations always require a name.
  9090. // TODO: check if/when DNInfo should replace Name.
  9091. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  9092. DeclarationName Name = NameInfo.getName();
  9093. if (!Name) {
  9094. if (!D.isInvalidType())
  9095. Diag(D.getDeclSpec().getBeginLoc(),
  9096. diag::err_explicit_instantiation_requires_name)
  9097. << D.getDeclSpec().getSourceRange() << D.getSourceRange();
  9098. return true;
  9099. }
  9100. // The scope passed in may not be a decl scope. Zip up the scope tree until
  9101. // we find one that is.
  9102. while ((S->getFlags() & Scope::DeclScope) == 0 ||
  9103. (S->getFlags() & Scope::TemplateParamScope) != 0)
  9104. S = S->getParent();
  9105. // Determine the type of the declaration.
  9106. TypeSourceInfo *T = GetTypeForDeclarator(D, S);
  9107. QualType R = T->getType();
  9108. if (R.isNull())
  9109. return true;
  9110. // C++ [dcl.stc]p1:
  9111. // A storage-class-specifier shall not be specified in [...] an explicit
  9112. // instantiation (14.7.2) directive.
  9113. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
  9114. Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
  9115. << Name;
  9116. return true;
  9117. } else if (D.getDeclSpec().getStorageClassSpec()
  9118. != DeclSpec::SCS_unspecified) {
  9119. // Complain about then remove the storage class specifier.
  9120. Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
  9121. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  9122. D.getMutableDeclSpec().ClearStorageClassSpecs();
  9123. }
  9124. // C++0x [temp.explicit]p1:
  9125. // [...] An explicit instantiation of a function template shall not use the
  9126. // inline or constexpr specifiers.
  9127. // Presumably, this also applies to member functions of class templates as
  9128. // well.
  9129. if (D.getDeclSpec().isInlineSpecified())
  9130. Diag(D.getDeclSpec().getInlineSpecLoc(),
  9131. getLangOpts().CPlusPlus11 ?
  9132. diag::err_explicit_instantiation_inline :
  9133. diag::warn_explicit_instantiation_inline_0x)
  9134. << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
  9135. if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType())
  9136. // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
  9137. // not already specified.
  9138. Diag(D.getDeclSpec().getConstexprSpecLoc(),
  9139. diag::err_explicit_instantiation_constexpr);
  9140. // A deduction guide is not on the list of entities that can be explicitly
  9141. // instantiated.
  9142. if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
  9143. Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
  9144. << /*explicit instantiation*/ 0;
  9145. return true;
  9146. }
  9147. // C++0x [temp.explicit]p2:
  9148. // There are two forms of explicit instantiation: an explicit instantiation
  9149. // definition and an explicit instantiation declaration. An explicit
  9150. // instantiation declaration begins with the extern keyword. [...]
  9151. TemplateSpecializationKind TSK
  9152. = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
  9153. : TSK_ExplicitInstantiationDeclaration;
  9154. LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
  9155. LookupParsedName(Previous, S, &D.getCXXScopeSpec());
  9156. if (!R->isFunctionType()) {
  9157. // C++ [temp.explicit]p1:
  9158. // A [...] static data member of a class template can be explicitly
  9159. // instantiated from the member definition associated with its class
  9160. // template.
  9161. // C++1y [temp.explicit]p1:
  9162. // A [...] variable [...] template specialization can be explicitly
  9163. // instantiated from its template.
  9164. if (Previous.isAmbiguous())
  9165. return true;
  9166. VarDecl *Prev = Previous.getAsSingle<VarDecl>();
  9167. VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
  9168. if (!PrevTemplate) {
  9169. if (!Prev || !Prev->isStaticDataMember()) {
  9170. // We expect to see a static data member here.
  9171. Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
  9172. << Name;
  9173. for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
  9174. P != PEnd; ++P)
  9175. Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
  9176. return true;
  9177. }
  9178. if (!Prev->getInstantiatedFromStaticDataMember()) {
  9179. // FIXME: Check for explicit specialization?
  9180. Diag(D.getIdentifierLoc(),
  9181. diag::err_explicit_instantiation_data_member_not_instantiated)
  9182. << Prev;
  9183. Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
  9184. // FIXME: Can we provide a note showing where this was declared?
  9185. return true;
  9186. }
  9187. } else {
  9188. // Explicitly instantiate a variable template.
  9189. // C++1y [dcl.spec.auto]p6:
  9190. // ... A program that uses auto or decltype(auto) in a context not
  9191. // explicitly allowed in this section is ill-formed.
  9192. //
  9193. // This includes auto-typed variable template instantiations.
  9194. if (R->isUndeducedType()) {
  9195. Diag(T->getTypeLoc().getBeginLoc(),
  9196. diag::err_auto_not_allowed_var_inst);
  9197. return true;
  9198. }
  9199. if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
  9200. // C++1y [temp.explicit]p3:
  9201. // If the explicit instantiation is for a variable, the unqualified-id
  9202. // in the declaration shall be a template-id.
  9203. Diag(D.getIdentifierLoc(),
  9204. diag::err_explicit_instantiation_without_template_id)
  9205. << PrevTemplate;
  9206. Diag(PrevTemplate->getLocation(),
  9207. diag::note_explicit_instantiation_here);
  9208. return true;
  9209. }
  9210. // Translate the parser's template argument list into our AST format.
  9211. TemplateArgumentListInfo TemplateArgs =
  9212. makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
  9213. DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
  9214. D.getIdentifierLoc(), TemplateArgs);
  9215. if (Res.isInvalid())
  9216. return true;
  9217. if (!Res.isUsable()) {
  9218. // We somehow specified dependent template arguments in an explicit
  9219. // instantiation. This should probably only happen during error
  9220. // recovery.
  9221. Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_dependent);
  9222. return true;
  9223. }
  9224. // Ignore access control bits, we don't need them for redeclaration
  9225. // checking.
  9226. Prev = cast<VarDecl>(Res.get());
  9227. }
  9228. // C++0x [temp.explicit]p2:
  9229. // If the explicit instantiation is for a member function, a member class
  9230. // or a static data member of a class template specialization, the name of
  9231. // the class template specialization in the qualified-id for the member
  9232. // name shall be a simple-template-id.
  9233. //
  9234. // C++98 has the same restriction, just worded differently.
  9235. //
  9236. // This does not apply to variable template specializations, where the
  9237. // template-id is in the unqualified-id instead.
  9238. if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
  9239. Diag(D.getIdentifierLoc(),
  9240. diag::ext_explicit_instantiation_without_qualified_id)
  9241. << Prev << D.getCXXScopeSpec().getRange();
  9242. CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK);
  9243. // Verify that it is okay to explicitly instantiate here.
  9244. TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
  9245. SourceLocation POI = Prev->getPointOfInstantiation();
  9246. bool HasNoEffect = false;
  9247. if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
  9248. PrevTSK, POI, HasNoEffect))
  9249. return true;
  9250. if (!HasNoEffect) {
  9251. // Instantiate static data member or variable template.
  9252. Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
  9253. // Merge attributes.
  9254. ProcessDeclAttributeList(S, Prev, D.getDeclSpec().getAttributes());
  9255. if (TSK == TSK_ExplicitInstantiationDefinition)
  9256. InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
  9257. }
  9258. // Check the new variable specialization against the parsed input.
  9259. if (PrevTemplate && !Context.hasSameType(Prev->getType(), R)) {
  9260. Diag(T->getTypeLoc().getBeginLoc(),
  9261. diag::err_invalid_var_template_spec_type)
  9262. << 0 << PrevTemplate << R << Prev->getType();
  9263. Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
  9264. << 2 << PrevTemplate->getDeclName();
  9265. return true;
  9266. }
  9267. // FIXME: Create an ExplicitInstantiation node?
  9268. return (Decl*) nullptr;
  9269. }
  9270. // If the declarator is a template-id, translate the parser's template
  9271. // argument list into our AST format.
  9272. bool HasExplicitTemplateArgs = false;
  9273. TemplateArgumentListInfo TemplateArgs;
  9274. if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
  9275. TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
  9276. HasExplicitTemplateArgs = true;
  9277. }
  9278. // C++ [temp.explicit]p1:
  9279. // A [...] function [...] can be explicitly instantiated from its template.
  9280. // A member function [...] of a class template can be explicitly
  9281. // instantiated from the member definition associated with its class
  9282. // template.
  9283. UnresolvedSet<8> TemplateMatches;
  9284. FunctionDecl *NonTemplateMatch = nullptr;
  9285. TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
  9286. for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
  9287. P != PEnd; ++P) {
  9288. NamedDecl *Prev = *P;
  9289. if (!HasExplicitTemplateArgs) {
  9290. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
  9291. QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
  9292. /*AdjustExceptionSpec*/true);
  9293. if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
  9294. if (Method->getPrimaryTemplate()) {
  9295. TemplateMatches.addDecl(Method, P.getAccess());
  9296. } else {
  9297. // FIXME: Can this assert ever happen? Needs a test.
  9298. assert(!NonTemplateMatch && "Multiple NonTemplateMatches");
  9299. NonTemplateMatch = Method;
  9300. }
  9301. }
  9302. }
  9303. }
  9304. FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
  9305. if (!FunTmpl)
  9306. continue;
  9307. TemplateDeductionInfo Info(FailedCandidates.getLocation());
  9308. FunctionDecl *Specialization = nullptr;
  9309. if (TemplateDeductionResult TDK
  9310. = DeduceTemplateArguments(FunTmpl,
  9311. (HasExplicitTemplateArgs ? &TemplateArgs
  9312. : nullptr),
  9313. R, Specialization, Info)) {
  9314. // Keep track of almost-matches.
  9315. FailedCandidates.addCandidate()
  9316. .set(P.getPair(), FunTmpl->getTemplatedDecl(),
  9317. MakeDeductionFailureInfo(Context, TDK, Info));
  9318. (void)TDK;
  9319. continue;
  9320. }
  9321. // Target attributes are part of the cuda function signature, so
  9322. // the cuda target of the instantiated function must match that of its
  9323. // template. Given that C++ template deduction does not take
  9324. // target attributes into account, we reject candidates here that
  9325. // have a different target.
  9326. if (LangOpts.CUDA &&
  9327. IdentifyCUDATarget(Specialization,
  9328. /* IgnoreImplicitHDAttr = */ true) !=
  9329. IdentifyCUDATarget(D.getDeclSpec().getAttributes())) {
  9330. FailedCandidates.addCandidate().set(
  9331. P.getPair(), FunTmpl->getTemplatedDecl(),
  9332. MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
  9333. continue;
  9334. }
  9335. TemplateMatches.addDecl(Specialization, P.getAccess());
  9336. }
  9337. FunctionDecl *Specialization = NonTemplateMatch;
  9338. if (!Specialization) {
  9339. // Find the most specialized function template specialization.
  9340. UnresolvedSetIterator Result = getMostSpecialized(
  9341. TemplateMatches.begin(), TemplateMatches.end(), FailedCandidates,
  9342. D.getIdentifierLoc(),
  9343. PDiag(diag::err_explicit_instantiation_not_known) << Name,
  9344. PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
  9345. PDiag(diag::note_explicit_instantiation_candidate));
  9346. if (Result == TemplateMatches.end())
  9347. return true;
  9348. // Ignore access control bits, we don't need them for redeclaration checking.
  9349. Specialization = cast<FunctionDecl>(*Result);
  9350. }
  9351. // C++11 [except.spec]p4
  9352. // In an explicit instantiation an exception-specification may be specified,
  9353. // but is not required.
  9354. // If an exception-specification is specified in an explicit instantiation
  9355. // directive, it shall be compatible with the exception-specifications of
  9356. // other declarations of that function.
  9357. if (auto *FPT = R->getAs<FunctionProtoType>())
  9358. if (FPT->hasExceptionSpec()) {
  9359. unsigned DiagID =
  9360. diag::err_mismatched_exception_spec_explicit_instantiation;
  9361. if (getLangOpts().MicrosoftExt)
  9362. DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
  9363. bool Result = CheckEquivalentExceptionSpec(
  9364. PDiag(DiagID) << Specialization->getType(),
  9365. PDiag(diag::note_explicit_instantiation_here),
  9366. Specialization->getType()->getAs<FunctionProtoType>(),
  9367. Specialization->getLocation(), FPT, D.getBeginLoc());
  9368. // In Microsoft mode, mismatching exception specifications just cause a
  9369. // warning.
  9370. if (!getLangOpts().MicrosoftExt && Result)
  9371. return true;
  9372. }
  9373. if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
  9374. Diag(D.getIdentifierLoc(),
  9375. diag::err_explicit_instantiation_member_function_not_instantiated)
  9376. << Specialization
  9377. << (Specialization->getTemplateSpecializationKind() ==
  9378. TSK_ExplicitSpecialization);
  9379. Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
  9380. return true;
  9381. }
  9382. FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
  9383. if (!PrevDecl && Specialization->isThisDeclarationADefinition())
  9384. PrevDecl = Specialization;
  9385. if (PrevDecl) {
  9386. bool HasNoEffect = false;
  9387. if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
  9388. PrevDecl,
  9389. PrevDecl->getTemplateSpecializationKind(),
  9390. PrevDecl->getPointOfInstantiation(),
  9391. HasNoEffect))
  9392. return true;
  9393. // FIXME: We may still want to build some representation of this
  9394. // explicit specialization.
  9395. if (HasNoEffect)
  9396. return (Decl*) nullptr;
  9397. }
  9398. // HACK: libc++ has a bug where it attempts to explicitly instantiate the
  9399. // functions
  9400. // valarray<size_t>::valarray(size_t) and
  9401. // valarray<size_t>::~valarray()
  9402. // that it declared to have internal linkage with the internal_linkage
  9403. // attribute. Ignore the explicit instantiation declaration in this case.
  9404. if (Specialization->hasAttr<InternalLinkageAttr>() &&
  9405. TSK == TSK_ExplicitInstantiationDeclaration) {
  9406. if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext()))
  9407. if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") &&
  9408. RD->isInStdNamespace())
  9409. return (Decl*) nullptr;
  9410. }
  9411. ProcessDeclAttributeList(S, Specialization, D.getDeclSpec().getAttributes());
  9412. // In MSVC mode, dllimported explicit instantiation definitions are treated as
  9413. // instantiation declarations.
  9414. if (TSK == TSK_ExplicitInstantiationDefinition &&
  9415. Specialization->hasAttr<DLLImportAttr>() &&
  9416. Context.getTargetInfo().getCXXABI().isMicrosoft())
  9417. TSK = TSK_ExplicitInstantiationDeclaration;
  9418. Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
  9419. if (Specialization->isDefined()) {
  9420. // Let the ASTConsumer know that this function has been explicitly
  9421. // instantiated now, and its linkage might have changed.
  9422. Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
  9423. } else if (TSK == TSK_ExplicitInstantiationDefinition)
  9424. InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
  9425. // C++0x [temp.explicit]p2:
  9426. // If the explicit instantiation is for a member function, a member class
  9427. // or a static data member of a class template specialization, the name of
  9428. // the class template specialization in the qualified-id for the member
  9429. // name shall be a simple-template-id.
  9430. //
  9431. // C++98 has the same restriction, just worded differently.
  9432. FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
  9433. if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
  9434. D.getCXXScopeSpec().isSet() &&
  9435. !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
  9436. Diag(D.getIdentifierLoc(),
  9437. diag::ext_explicit_instantiation_without_qualified_id)
  9438. << Specialization << D.getCXXScopeSpec().getRange();
  9439. CheckExplicitInstantiation(
  9440. *this,
  9441. FunTmpl ? (NamedDecl *)FunTmpl
  9442. : Specialization->getInstantiatedFromMemberFunction(),
  9443. D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK);
  9444. // FIXME: Create some kind of ExplicitInstantiationDecl here.
  9445. return (Decl*) nullptr;
  9446. }
  9447. TypeResult
  9448. Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
  9449. const CXXScopeSpec &SS, IdentifierInfo *Name,
  9450. SourceLocation TagLoc, SourceLocation NameLoc) {
  9451. // This has to hold, because SS is expected to be defined.
  9452. assert(Name && "Expected a name in a dependent tag");
  9453. NestedNameSpecifier *NNS = SS.getScopeRep();
  9454. if (!NNS)
  9455. return true;
  9456. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  9457. if (TUK == TUK_Declaration || TUK == TUK_Definition) {
  9458. Diag(NameLoc, diag::err_dependent_tag_decl)
  9459. << (TUK == TUK_Definition) << Kind << SS.getRange();
  9460. return true;
  9461. }
  9462. // Create the resulting type.
  9463. ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
  9464. QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
  9465. // Create type-source location information for this type.
  9466. TypeLocBuilder TLB;
  9467. DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
  9468. TL.setElaboratedKeywordLoc(TagLoc);
  9469. TL.setQualifierLoc(SS.getWithLocInContext(Context));
  9470. TL.setNameLoc(NameLoc);
  9471. return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
  9472. }
  9473. TypeResult Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
  9474. const CXXScopeSpec &SS,
  9475. const IdentifierInfo &II,
  9476. SourceLocation IdLoc,
  9477. ImplicitTypenameContext IsImplicitTypename) {
  9478. if (SS.isInvalid())
  9479. return true;
  9480. if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
  9481. Diag(TypenameLoc,
  9482. getLangOpts().CPlusPlus11 ?
  9483. diag::warn_cxx98_compat_typename_outside_of_template :
  9484. diag::ext_typename_outside_of_template)
  9485. << FixItHint::CreateRemoval(TypenameLoc);
  9486. NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
  9487. TypeSourceInfo *TSI = nullptr;
  9488. QualType T =
  9489. CheckTypenameType((TypenameLoc.isValid() ||
  9490. IsImplicitTypename == ImplicitTypenameContext::Yes)
  9491. ? ETK_Typename
  9492. : ETK_None,
  9493. TypenameLoc, QualifierLoc, II, IdLoc, &TSI,
  9494. /*DeducedTSTContext=*/true);
  9495. if (T.isNull())
  9496. return true;
  9497. return CreateParsedType(T, TSI);
  9498. }
  9499. TypeResult
  9500. Sema::ActOnTypenameType(Scope *S,
  9501. SourceLocation TypenameLoc,
  9502. const CXXScopeSpec &SS,
  9503. SourceLocation TemplateKWLoc,
  9504. TemplateTy TemplateIn,
  9505. IdentifierInfo *TemplateII,
  9506. SourceLocation TemplateIILoc,
  9507. SourceLocation LAngleLoc,
  9508. ASTTemplateArgsPtr TemplateArgsIn,
  9509. SourceLocation RAngleLoc) {
  9510. if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
  9511. Diag(TypenameLoc,
  9512. getLangOpts().CPlusPlus11 ?
  9513. diag::warn_cxx98_compat_typename_outside_of_template :
  9514. diag::ext_typename_outside_of_template)
  9515. << FixItHint::CreateRemoval(TypenameLoc);
  9516. // Strangely, non-type results are not ignored by this lookup, so the
  9517. // program is ill-formed if it finds an injected-class-name.
  9518. if (TypenameLoc.isValid()) {
  9519. auto *LookupRD =
  9520. dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
  9521. if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
  9522. Diag(TemplateIILoc,
  9523. diag::ext_out_of_line_qualified_id_type_names_constructor)
  9524. << TemplateII << 0 /*injected-class-name used as template name*/
  9525. << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
  9526. }
  9527. }
  9528. // Translate the parser's template argument list in our AST format.
  9529. TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
  9530. translateTemplateArguments(TemplateArgsIn, TemplateArgs);
  9531. TemplateName Template = TemplateIn.get();
  9532. if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
  9533. // Construct a dependent template specialization type.
  9534. assert(DTN && "dependent template has non-dependent name?");
  9535. assert(DTN->getQualifier() == SS.getScopeRep());
  9536. QualType T = Context.getDependentTemplateSpecializationType(
  9537. ETK_Typename, DTN->getQualifier(), DTN->getIdentifier(),
  9538. TemplateArgs.arguments());
  9539. // Create source-location information for this type.
  9540. TypeLocBuilder Builder;
  9541. DependentTemplateSpecializationTypeLoc SpecTL
  9542. = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
  9543. SpecTL.setElaboratedKeywordLoc(TypenameLoc);
  9544. SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
  9545. SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
  9546. SpecTL.setTemplateNameLoc(TemplateIILoc);
  9547. SpecTL.setLAngleLoc(LAngleLoc);
  9548. SpecTL.setRAngleLoc(RAngleLoc);
  9549. for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
  9550. SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
  9551. return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  9552. }
  9553. QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
  9554. if (T.isNull())
  9555. return true;
  9556. // Provide source-location information for the template specialization type.
  9557. TypeLocBuilder Builder;
  9558. TemplateSpecializationTypeLoc SpecTL
  9559. = Builder.push<TemplateSpecializationTypeLoc>(T);
  9560. SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
  9561. SpecTL.setTemplateNameLoc(TemplateIILoc);
  9562. SpecTL.setLAngleLoc(LAngleLoc);
  9563. SpecTL.setRAngleLoc(RAngleLoc);
  9564. for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
  9565. SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
  9566. T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
  9567. ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
  9568. TL.setElaboratedKeywordLoc(TypenameLoc);
  9569. TL.setQualifierLoc(SS.getWithLocInContext(Context));
  9570. TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
  9571. return CreateParsedType(T, TSI);
  9572. }
  9573. /// Determine whether this failed name lookup should be treated as being
  9574. /// disabled by a usage of std::enable_if.
  9575. static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
  9576. SourceRange &CondRange, Expr *&Cond) {
  9577. // We must be looking for a ::type...
  9578. if (!II.isStr("type"))
  9579. return false;
  9580. // ... within an explicitly-written template specialization...
  9581. if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
  9582. return false;
  9583. TypeLoc EnableIfTy = NNS.getTypeLoc();
  9584. TemplateSpecializationTypeLoc EnableIfTSTLoc =
  9585. EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
  9586. if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
  9587. return false;
  9588. const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
  9589. // ... which names a complete class template declaration...
  9590. const TemplateDecl *EnableIfDecl =
  9591. EnableIfTST->getTemplateName().getAsTemplateDecl();
  9592. if (!EnableIfDecl || EnableIfTST->isIncompleteType())
  9593. return false;
  9594. // ... called "enable_if".
  9595. const IdentifierInfo *EnableIfII =
  9596. EnableIfDecl->getDeclName().getAsIdentifierInfo();
  9597. if (!EnableIfII || !EnableIfII->isStr("enable_if"))
  9598. return false;
  9599. // Assume the first template argument is the condition.
  9600. CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
  9601. // Dig out the condition.
  9602. Cond = nullptr;
  9603. if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
  9604. != TemplateArgument::Expression)
  9605. return true;
  9606. Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
  9607. // Ignore Boolean literals; they add no value.
  9608. if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
  9609. Cond = nullptr;
  9610. return true;
  9611. }
  9612. QualType
  9613. Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
  9614. SourceLocation KeywordLoc,
  9615. NestedNameSpecifierLoc QualifierLoc,
  9616. const IdentifierInfo &II,
  9617. SourceLocation IILoc,
  9618. TypeSourceInfo **TSI,
  9619. bool DeducedTSTContext) {
  9620. QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc,
  9621. DeducedTSTContext);
  9622. if (T.isNull())
  9623. return QualType();
  9624. *TSI = Context.CreateTypeSourceInfo(T);
  9625. if (isa<DependentNameType>(T)) {
  9626. DependentNameTypeLoc TL =
  9627. (*TSI)->getTypeLoc().castAs<DependentNameTypeLoc>();
  9628. TL.setElaboratedKeywordLoc(KeywordLoc);
  9629. TL.setQualifierLoc(QualifierLoc);
  9630. TL.setNameLoc(IILoc);
  9631. } else {
  9632. ElaboratedTypeLoc TL = (*TSI)->getTypeLoc().castAs<ElaboratedTypeLoc>();
  9633. TL.setElaboratedKeywordLoc(KeywordLoc);
  9634. TL.setQualifierLoc(QualifierLoc);
  9635. TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IILoc);
  9636. }
  9637. return T;
  9638. }
  9639. /// Build the type that describes a C++ typename specifier,
  9640. /// e.g., "typename T::type".
  9641. QualType
  9642. Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
  9643. SourceLocation KeywordLoc,
  9644. NestedNameSpecifierLoc QualifierLoc,
  9645. const IdentifierInfo &II,
  9646. SourceLocation IILoc, bool DeducedTSTContext) {
  9647. CXXScopeSpec SS;
  9648. SS.Adopt(QualifierLoc);
  9649. DeclContext *Ctx = nullptr;
  9650. if (QualifierLoc) {
  9651. Ctx = computeDeclContext(SS);
  9652. if (!Ctx) {
  9653. // If the nested-name-specifier is dependent and couldn't be
  9654. // resolved to a type, build a typename type.
  9655. assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
  9656. return Context.getDependentNameType(Keyword,
  9657. QualifierLoc.getNestedNameSpecifier(),
  9658. &II);
  9659. }
  9660. // If the nested-name-specifier refers to the current instantiation,
  9661. // the "typename" keyword itself is superfluous. In C++03, the
  9662. // program is actually ill-formed. However, DR 382 (in C++0x CD1)
  9663. // allows such extraneous "typename" keywords, and we retroactively
  9664. // apply this DR to C++03 code with only a warning. In any case we continue.
  9665. if (RequireCompleteDeclContext(SS, Ctx))
  9666. return QualType();
  9667. }
  9668. DeclarationName Name(&II);
  9669. LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
  9670. if (Ctx)
  9671. LookupQualifiedName(Result, Ctx, SS);
  9672. else
  9673. LookupName(Result, CurScope);
  9674. unsigned DiagID = 0;
  9675. Decl *Referenced = nullptr;
  9676. switch (Result.getResultKind()) {
  9677. case LookupResult::NotFound: {
  9678. // If we're looking up 'type' within a template named 'enable_if', produce
  9679. // a more specific diagnostic.
  9680. SourceRange CondRange;
  9681. Expr *Cond = nullptr;
  9682. if (Ctx && isEnableIf(QualifierLoc, II, CondRange, Cond)) {
  9683. // If we have a condition, narrow it down to the specific failed
  9684. // condition.
  9685. if (Cond) {
  9686. Expr *FailedCond;
  9687. std::string FailedDescription;
  9688. std::tie(FailedCond, FailedDescription) =
  9689. findFailedBooleanCondition(Cond);
  9690. Diag(FailedCond->getExprLoc(),
  9691. diag::err_typename_nested_not_found_requirement)
  9692. << FailedDescription
  9693. << FailedCond->getSourceRange();
  9694. return QualType();
  9695. }
  9696. Diag(CondRange.getBegin(),
  9697. diag::err_typename_nested_not_found_enable_if)
  9698. << Ctx << CondRange;
  9699. return QualType();
  9700. }
  9701. DiagID = Ctx ? diag::err_typename_nested_not_found
  9702. : diag::err_unknown_typename;
  9703. break;
  9704. }
  9705. case LookupResult::FoundUnresolvedValue: {
  9706. // We found a using declaration that is a value. Most likely, the using
  9707. // declaration itself is meant to have the 'typename' keyword.
  9708. SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
  9709. IILoc);
  9710. Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
  9711. << Name << Ctx << FullRange;
  9712. if (UnresolvedUsingValueDecl *Using
  9713. = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
  9714. SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
  9715. Diag(Loc, diag::note_using_value_decl_missing_typename)
  9716. << FixItHint::CreateInsertion(Loc, "typename ");
  9717. }
  9718. }
  9719. // Fall through to create a dependent typename type, from which we can recover
  9720. // better.
  9721. [[fallthrough]];
  9722. case LookupResult::NotFoundInCurrentInstantiation:
  9723. // Okay, it's a member of an unknown instantiation.
  9724. return Context.getDependentNameType(Keyword,
  9725. QualifierLoc.getNestedNameSpecifier(),
  9726. &II);
  9727. case LookupResult::Found:
  9728. if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
  9729. // C++ [class.qual]p2:
  9730. // In a lookup in which function names are not ignored and the
  9731. // nested-name-specifier nominates a class C, if the name specified
  9732. // after the nested-name-specifier, when looked up in C, is the
  9733. // injected-class-name of C [...] then the name is instead considered
  9734. // to name the constructor of class C.
  9735. //
  9736. // Unlike in an elaborated-type-specifier, function names are not ignored
  9737. // in typename-specifier lookup. However, they are ignored in all the
  9738. // contexts where we form a typename type with no keyword (that is, in
  9739. // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
  9740. //
  9741. // FIXME: That's not strictly true: mem-initializer-id lookup does not
  9742. // ignore functions, but that appears to be an oversight.
  9743. auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
  9744. auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
  9745. if (Keyword == ETK_Typename && LookupRD && FoundRD &&
  9746. FoundRD->isInjectedClassName() &&
  9747. declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
  9748. Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
  9749. << &II << 1 << 0 /*'typename' keyword used*/;
  9750. // We found a type. Build an ElaboratedType, since the
  9751. // typename-specifier was just sugar.
  9752. MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
  9753. return Context.getElaboratedType(Keyword,
  9754. QualifierLoc.getNestedNameSpecifier(),
  9755. Context.getTypeDeclType(Type));
  9756. }
  9757. // C++ [dcl.type.simple]p2:
  9758. // A type-specifier of the form
  9759. // typename[opt] nested-name-specifier[opt] template-name
  9760. // is a placeholder for a deduced class type [...].
  9761. if (getLangOpts().CPlusPlus17) {
  9762. if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
  9763. if (!DeducedTSTContext) {
  9764. QualType T(QualifierLoc
  9765. ? QualifierLoc.getNestedNameSpecifier()->getAsType()
  9766. : nullptr, 0);
  9767. if (!T.isNull())
  9768. Diag(IILoc, diag::err_dependent_deduced_tst)
  9769. << (int)getTemplateNameKindForDiagnostics(TemplateName(TD)) << T;
  9770. else
  9771. Diag(IILoc, diag::err_deduced_tst)
  9772. << (int)getTemplateNameKindForDiagnostics(TemplateName(TD));
  9773. Diag(TD->getLocation(), diag::note_template_decl_here);
  9774. return QualType();
  9775. }
  9776. return Context.getElaboratedType(
  9777. Keyword, QualifierLoc.getNestedNameSpecifier(),
  9778. Context.getDeducedTemplateSpecializationType(TemplateName(TD),
  9779. QualType(), false));
  9780. }
  9781. }
  9782. DiagID = Ctx ? diag::err_typename_nested_not_type
  9783. : diag::err_typename_not_type;
  9784. Referenced = Result.getFoundDecl();
  9785. break;
  9786. case LookupResult::FoundOverloaded:
  9787. DiagID = Ctx ? diag::err_typename_nested_not_type
  9788. : diag::err_typename_not_type;
  9789. Referenced = *Result.begin();
  9790. break;
  9791. case LookupResult::Ambiguous:
  9792. return QualType();
  9793. }
  9794. // If we get here, it's because name lookup did not find a
  9795. // type. Emit an appropriate diagnostic and return an error.
  9796. SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
  9797. IILoc);
  9798. if (Ctx)
  9799. Diag(IILoc, DiagID) << FullRange << Name << Ctx;
  9800. else
  9801. Diag(IILoc, DiagID) << FullRange << Name;
  9802. if (Referenced)
  9803. Diag(Referenced->getLocation(),
  9804. Ctx ? diag::note_typename_member_refers_here
  9805. : diag::note_typename_refers_here)
  9806. << Name;
  9807. return QualType();
  9808. }
  9809. namespace {
  9810. // See Sema::RebuildTypeInCurrentInstantiation
  9811. class CurrentInstantiationRebuilder
  9812. : public TreeTransform<CurrentInstantiationRebuilder> {
  9813. SourceLocation Loc;
  9814. DeclarationName Entity;
  9815. public:
  9816. typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
  9817. CurrentInstantiationRebuilder(Sema &SemaRef,
  9818. SourceLocation Loc,
  9819. DeclarationName Entity)
  9820. : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
  9821. Loc(Loc), Entity(Entity) { }
  9822. /// Determine whether the given type \p T has already been
  9823. /// transformed.
  9824. ///
  9825. /// For the purposes of type reconstruction, a type has already been
  9826. /// transformed if it is NULL or if it is not dependent.
  9827. bool AlreadyTransformed(QualType T) {
  9828. return T.isNull() || !T->isInstantiationDependentType();
  9829. }
  9830. /// Returns the location of the entity whose type is being
  9831. /// rebuilt.
  9832. SourceLocation getBaseLocation() { return Loc; }
  9833. /// Returns the name of the entity whose type is being rebuilt.
  9834. DeclarationName getBaseEntity() { return Entity; }
  9835. /// Sets the "base" location and entity when that
  9836. /// information is known based on another transformation.
  9837. void setBase(SourceLocation Loc, DeclarationName Entity) {
  9838. this->Loc = Loc;
  9839. this->Entity = Entity;
  9840. }
  9841. ExprResult TransformLambdaExpr(LambdaExpr *E) {
  9842. // Lambdas never need to be transformed.
  9843. return E;
  9844. }
  9845. };
  9846. } // end anonymous namespace
  9847. /// Rebuilds a type within the context of the current instantiation.
  9848. ///
  9849. /// The type \p T is part of the type of an out-of-line member definition of
  9850. /// a class template (or class template partial specialization) that was parsed
  9851. /// and constructed before we entered the scope of the class template (or
  9852. /// partial specialization thereof). This routine will rebuild that type now
  9853. /// that we have entered the declarator's scope, which may produce different
  9854. /// canonical types, e.g.,
  9855. ///
  9856. /// \code
  9857. /// template<typename T>
  9858. /// struct X {
  9859. /// typedef T* pointer;
  9860. /// pointer data();
  9861. /// };
  9862. ///
  9863. /// template<typename T>
  9864. /// typename X<T>::pointer X<T>::data() { ... }
  9865. /// \endcode
  9866. ///
  9867. /// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
  9868. /// since we do not know that we can look into X<T> when we parsed the type.
  9869. /// This function will rebuild the type, performing the lookup of "pointer"
  9870. /// in X<T> and returning an ElaboratedType whose canonical type is the same
  9871. /// as the canonical type of T*, allowing the return types of the out-of-line
  9872. /// definition and the declaration to match.
  9873. TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
  9874. SourceLocation Loc,
  9875. DeclarationName Name) {
  9876. if (!T || !T->getType()->isInstantiationDependentType())
  9877. return T;
  9878. CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
  9879. return Rebuilder.TransformType(T);
  9880. }
  9881. ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
  9882. CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
  9883. DeclarationName());
  9884. return Rebuilder.TransformExpr(E);
  9885. }
  9886. bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
  9887. if (SS.isInvalid())
  9888. return true;
  9889. NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
  9890. CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
  9891. DeclarationName());
  9892. NestedNameSpecifierLoc Rebuilt
  9893. = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
  9894. if (!Rebuilt)
  9895. return true;
  9896. SS.Adopt(Rebuilt);
  9897. return false;
  9898. }
  9899. /// Rebuild the template parameters now that we know we're in a current
  9900. /// instantiation.
  9901. bool Sema::RebuildTemplateParamsInCurrentInstantiation(
  9902. TemplateParameterList *Params) {
  9903. for (unsigned I = 0, N = Params->size(); I != N; ++I) {
  9904. Decl *Param = Params->getParam(I);
  9905. // There is nothing to rebuild in a type parameter.
  9906. if (isa<TemplateTypeParmDecl>(Param))
  9907. continue;
  9908. // Rebuild the template parameter list of a template template parameter.
  9909. if (TemplateTemplateParmDecl *TTP
  9910. = dyn_cast<TemplateTemplateParmDecl>(Param)) {
  9911. if (RebuildTemplateParamsInCurrentInstantiation(
  9912. TTP->getTemplateParameters()))
  9913. return true;
  9914. continue;
  9915. }
  9916. // Rebuild the type of a non-type template parameter.
  9917. NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
  9918. TypeSourceInfo *NewTSI
  9919. = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
  9920. NTTP->getLocation(),
  9921. NTTP->getDeclName());
  9922. if (!NewTSI)
  9923. return true;
  9924. if (NewTSI->getType()->isUndeducedType()) {
  9925. // C++17 [temp.dep.expr]p3:
  9926. // An id-expression is type-dependent if it contains
  9927. // - an identifier associated by name lookup with a non-type
  9928. // template-parameter declared with a type that contains a
  9929. // placeholder type (7.1.7.4),
  9930. NewTSI = SubstAutoTypeSourceInfoDependent(NewTSI);
  9931. }
  9932. if (NewTSI != NTTP->getTypeSourceInfo()) {
  9933. NTTP->setTypeSourceInfo(NewTSI);
  9934. NTTP->setType(NewTSI->getType());
  9935. }
  9936. }
  9937. return false;
  9938. }
  9939. /// Produces a formatted string that describes the binding of
  9940. /// template parameters to template arguments.
  9941. std::string
  9942. Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
  9943. const TemplateArgumentList &Args) {
  9944. return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
  9945. }
  9946. std::string
  9947. Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
  9948. const TemplateArgument *Args,
  9949. unsigned NumArgs) {
  9950. SmallString<128> Str;
  9951. llvm::raw_svector_ostream Out(Str);
  9952. if (!Params || Params->size() == 0 || NumArgs == 0)
  9953. return std::string();
  9954. for (unsigned I = 0, N = Params->size(); I != N; ++I) {
  9955. if (I >= NumArgs)
  9956. break;
  9957. if (I == 0)
  9958. Out << "[with ";
  9959. else
  9960. Out << ", ";
  9961. if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
  9962. Out << Id->getName();
  9963. } else {
  9964. Out << '$' << I;
  9965. }
  9966. Out << " = ";
  9967. Args[I].print(getPrintingPolicy(), Out,
  9968. TemplateParameterList::shouldIncludeTypeForArgument(
  9969. getPrintingPolicy(), Params, I));
  9970. }
  9971. Out << ']';
  9972. return std::string(Out.str());
  9973. }
  9974. void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
  9975. CachedTokens &Toks) {
  9976. if (!FD)
  9977. return;
  9978. auto LPT = std::make_unique<LateParsedTemplate>();
  9979. // Take tokens to avoid allocations
  9980. LPT->Toks.swap(Toks);
  9981. LPT->D = FnD;
  9982. LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
  9983. FD->setLateTemplateParsed(true);
  9984. }
  9985. void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
  9986. if (!FD)
  9987. return;
  9988. FD->setLateTemplateParsed(false);
  9989. }
  9990. bool Sema::IsInsideALocalClassWithinATemplateFunction() {
  9991. DeclContext *DC = CurContext;
  9992. while (DC) {
  9993. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
  9994. const FunctionDecl *FD = RD->isLocalClass();
  9995. return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
  9996. } else if (DC->isTranslationUnit() || DC->isNamespace())
  9997. return false;
  9998. DC = DC->getParent();
  9999. }
  10000. return false;
  10001. }
  10002. namespace {
  10003. /// Walk the path from which a declaration was instantiated, and check
  10004. /// that every explicit specialization along that path is visible. This enforces
  10005. /// C++ [temp.expl.spec]/6:
  10006. ///
  10007. /// If a template, a member template or a member of a class template is
  10008. /// explicitly specialized then that specialization shall be declared before
  10009. /// the first use of that specialization that would cause an implicit
  10010. /// instantiation to take place, in every translation unit in which such a
  10011. /// use occurs; no diagnostic is required.
  10012. ///
  10013. /// and also C++ [temp.class.spec]/1:
  10014. ///
  10015. /// A partial specialization shall be declared before the first use of a
  10016. /// class template specialization that would make use of the partial
  10017. /// specialization as the result of an implicit or explicit instantiation
  10018. /// in every translation unit in which such a use occurs; no diagnostic is
  10019. /// required.
  10020. class ExplicitSpecializationVisibilityChecker {
  10021. Sema &S;
  10022. SourceLocation Loc;
  10023. llvm::SmallVector<Module *, 8> Modules;
  10024. Sema::AcceptableKind Kind;
  10025. public:
  10026. ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc,
  10027. Sema::AcceptableKind Kind)
  10028. : S(S), Loc(Loc), Kind(Kind) {}
  10029. void check(NamedDecl *ND) {
  10030. if (auto *FD = dyn_cast<FunctionDecl>(ND))
  10031. return checkImpl(FD);
  10032. if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
  10033. return checkImpl(RD);
  10034. if (auto *VD = dyn_cast<VarDecl>(ND))
  10035. return checkImpl(VD);
  10036. if (auto *ED = dyn_cast<EnumDecl>(ND))
  10037. return checkImpl(ED);
  10038. }
  10039. private:
  10040. void diagnose(NamedDecl *D, bool IsPartialSpec) {
  10041. auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
  10042. : Sema::MissingImportKind::ExplicitSpecialization;
  10043. const bool Recover = true;
  10044. // If we got a custom set of modules (because only a subset of the
  10045. // declarations are interesting), use them, otherwise let
  10046. // diagnoseMissingImport intelligently pick some.
  10047. if (Modules.empty())
  10048. S.diagnoseMissingImport(Loc, D, Kind, Recover);
  10049. else
  10050. S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
  10051. }
  10052. bool CheckMemberSpecialization(const NamedDecl *D) {
  10053. return Kind == Sema::AcceptableKind::Visible
  10054. ? S.hasVisibleMemberSpecialization(D)
  10055. : S.hasReachableMemberSpecialization(D);
  10056. }
  10057. bool CheckExplicitSpecialization(const NamedDecl *D) {
  10058. return Kind == Sema::AcceptableKind::Visible
  10059. ? S.hasVisibleExplicitSpecialization(D)
  10060. : S.hasReachableExplicitSpecialization(D);
  10061. }
  10062. bool CheckDeclaration(const NamedDecl *D) {
  10063. return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D)
  10064. : S.hasReachableDeclaration(D);
  10065. }
  10066. // Check a specific declaration. There are three problematic cases:
  10067. //
  10068. // 1) The declaration is an explicit specialization of a template
  10069. // specialization.
  10070. // 2) The declaration is an explicit specialization of a member of an
  10071. // templated class.
  10072. // 3) The declaration is an instantiation of a template, and that template
  10073. // is an explicit specialization of a member of a templated class.
  10074. //
  10075. // We don't need to go any deeper than that, as the instantiation of the
  10076. // surrounding class / etc is not triggered by whatever triggered this
  10077. // instantiation, and thus should be checked elsewhere.
  10078. template<typename SpecDecl>
  10079. void checkImpl(SpecDecl *Spec) {
  10080. bool IsHiddenExplicitSpecialization = false;
  10081. if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
  10082. IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo()
  10083. ? !CheckMemberSpecialization(Spec)
  10084. : !CheckExplicitSpecialization(Spec);
  10085. } else {
  10086. checkInstantiated(Spec);
  10087. }
  10088. if (IsHiddenExplicitSpecialization)
  10089. diagnose(Spec->getMostRecentDecl(), false);
  10090. }
  10091. void checkInstantiated(FunctionDecl *FD) {
  10092. if (auto *TD = FD->getPrimaryTemplate())
  10093. checkTemplate(TD);
  10094. }
  10095. void checkInstantiated(CXXRecordDecl *RD) {
  10096. auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
  10097. if (!SD)
  10098. return;
  10099. auto From = SD->getSpecializedTemplateOrPartial();
  10100. if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
  10101. checkTemplate(TD);
  10102. else if (auto *TD =
  10103. From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
  10104. if (!CheckDeclaration(TD))
  10105. diagnose(TD, true);
  10106. checkTemplate(TD);
  10107. }
  10108. }
  10109. void checkInstantiated(VarDecl *RD) {
  10110. auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
  10111. if (!SD)
  10112. return;
  10113. auto From = SD->getSpecializedTemplateOrPartial();
  10114. if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
  10115. checkTemplate(TD);
  10116. else if (auto *TD =
  10117. From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
  10118. if (!CheckDeclaration(TD))
  10119. diagnose(TD, true);
  10120. checkTemplate(TD);
  10121. }
  10122. }
  10123. void checkInstantiated(EnumDecl *FD) {}
  10124. template<typename TemplDecl>
  10125. void checkTemplate(TemplDecl *TD) {
  10126. if (TD->isMemberSpecialization()) {
  10127. if (!CheckMemberSpecialization(TD))
  10128. diagnose(TD->getMostRecentDecl(), false);
  10129. }
  10130. }
  10131. };
  10132. } // end anonymous namespace
  10133. void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
  10134. if (!getLangOpts().Modules)
  10135. return;
  10136. ExplicitSpecializationVisibilityChecker(*this, Loc,
  10137. Sema::AcceptableKind::Visible)
  10138. .check(Spec);
  10139. }
  10140. void Sema::checkSpecializationReachability(SourceLocation Loc,
  10141. NamedDecl *Spec) {
  10142. if (!getLangOpts().CPlusPlusModules)
  10143. return checkSpecializationVisibility(Loc, Spec);
  10144. ExplicitSpecializationVisibilityChecker(*this, Loc,
  10145. Sema::AcceptableKind::Reachable)
  10146. .check(Spec);
  10147. }