SemaTemplateDeduction.cpp 253 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315
  1. //===- SemaTemplateDeduction.cpp - Template Argument Deduction ------------===//
  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. //
  9. // This file implements C++ template argument deduction.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/Sema/TemplateDeduction.h"
  13. #include "TreeTransform.h"
  14. #include "TypeLocBuilder.h"
  15. #include "clang/AST/ASTContext.h"
  16. #include "clang/AST/ASTLambda.h"
  17. #include "clang/AST/Decl.h"
  18. #include "clang/AST/DeclAccessPair.h"
  19. #include "clang/AST/DeclBase.h"
  20. #include "clang/AST/DeclCXX.h"
  21. #include "clang/AST/DeclTemplate.h"
  22. #include "clang/AST/DeclarationName.h"
  23. #include "clang/AST/Expr.h"
  24. #include "clang/AST/ExprCXX.h"
  25. #include "clang/AST/NestedNameSpecifier.h"
  26. #include "clang/AST/RecursiveASTVisitor.h"
  27. #include "clang/AST/TemplateBase.h"
  28. #include "clang/AST/TemplateName.h"
  29. #include "clang/AST/Type.h"
  30. #include "clang/AST/TypeLoc.h"
  31. #include "clang/AST/UnresolvedSet.h"
  32. #include "clang/Basic/AddressSpaces.h"
  33. #include "clang/Basic/ExceptionSpecificationType.h"
  34. #include "clang/Basic/LLVM.h"
  35. #include "clang/Basic/LangOptions.h"
  36. #include "clang/Basic/PartialDiagnostic.h"
  37. #include "clang/Basic/SourceLocation.h"
  38. #include "clang/Basic/Specifiers.h"
  39. #include "clang/Sema/Ownership.h"
  40. #include "clang/Sema/Sema.h"
  41. #include "clang/Sema/Template.h"
  42. #include "llvm/ADT/APInt.h"
  43. #include "llvm/ADT/APSInt.h"
  44. #include "llvm/ADT/ArrayRef.h"
  45. #include "llvm/ADT/DenseMap.h"
  46. #include "llvm/ADT/FoldingSet.h"
  47. #include "llvm/ADT/SmallBitVector.h"
  48. #include "llvm/ADT/SmallPtrSet.h"
  49. #include "llvm/ADT/SmallVector.h"
  50. #include "llvm/Support/Casting.h"
  51. #include "llvm/Support/Compiler.h"
  52. #include "llvm/Support/ErrorHandling.h"
  53. #include <algorithm>
  54. #include <cassert>
  55. #include <optional>
  56. #include <tuple>
  57. #include <type_traits>
  58. #include <utility>
  59. namespace clang {
  60. /// Various flags that control template argument deduction.
  61. ///
  62. /// These flags can be bitwise-OR'd together.
  63. enum TemplateDeductionFlags {
  64. /// No template argument deduction flags, which indicates the
  65. /// strictest results for template argument deduction (as used for, e.g.,
  66. /// matching class template partial specializations).
  67. TDF_None = 0,
  68. /// Within template argument deduction from a function call, we are
  69. /// matching with a parameter type for which the original parameter was
  70. /// a reference.
  71. TDF_ParamWithReferenceType = 0x1,
  72. /// Within template argument deduction from a function call, we
  73. /// are matching in a case where we ignore cv-qualifiers.
  74. TDF_IgnoreQualifiers = 0x02,
  75. /// Within template argument deduction from a function call,
  76. /// we are matching in a case where we can perform template argument
  77. /// deduction from a template-id of a derived class of the argument type.
  78. TDF_DerivedClass = 0x04,
  79. /// Allow non-dependent types to differ, e.g., when performing
  80. /// template argument deduction from a function call where conversions
  81. /// may apply.
  82. TDF_SkipNonDependent = 0x08,
  83. /// Whether we are performing template argument deduction for
  84. /// parameters and arguments in a top-level template argument
  85. TDF_TopLevelParameterTypeList = 0x10,
  86. /// Within template argument deduction from overload resolution per
  87. /// C++ [over.over] allow matching function types that are compatible in
  88. /// terms of noreturn and default calling convention adjustments, or
  89. /// similarly matching a declared template specialization against a
  90. /// possible template, per C++ [temp.deduct.decl]. In either case, permit
  91. /// deduction where the parameter is a function type that can be converted
  92. /// to the argument type.
  93. TDF_AllowCompatibleFunctionType = 0x20,
  94. /// Within template argument deduction for a conversion function, we are
  95. /// matching with an argument type for which the original argument was
  96. /// a reference.
  97. TDF_ArgWithReferenceType = 0x40,
  98. };
  99. }
  100. using namespace clang;
  101. using namespace sema;
  102. /// Compare two APSInts, extending and switching the sign as
  103. /// necessary to compare their values regardless of underlying type.
  104. static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) {
  105. if (Y.getBitWidth() > X.getBitWidth())
  106. X = X.extend(Y.getBitWidth());
  107. else if (Y.getBitWidth() < X.getBitWidth())
  108. Y = Y.extend(X.getBitWidth());
  109. // If there is a signedness mismatch, correct it.
  110. if (X.isSigned() != Y.isSigned()) {
  111. // If the signed value is negative, then the values cannot be the same.
  112. if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative()))
  113. return false;
  114. Y.setIsSigned(true);
  115. X.setIsSigned(true);
  116. }
  117. return X == Y;
  118. }
  119. static Sema::TemplateDeductionResult DeduceTemplateArgumentsByTypeMatch(
  120. Sema &S, TemplateParameterList *TemplateParams, QualType Param,
  121. QualType Arg, TemplateDeductionInfo &Info,
  122. SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF,
  123. bool PartialOrdering = false, bool DeducedFromArrayBound = false);
  124. static Sema::TemplateDeductionResult
  125. DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
  126. ArrayRef<TemplateArgument> Ps,
  127. ArrayRef<TemplateArgument> As,
  128. TemplateDeductionInfo &Info,
  129. SmallVectorImpl<DeducedTemplateArgument> &Deduced,
  130. bool NumberOfArgumentsMustMatch);
  131. static void MarkUsedTemplateParameters(ASTContext &Ctx,
  132. const TemplateArgument &TemplateArg,
  133. bool OnlyDeduced, unsigned Depth,
  134. llvm::SmallBitVector &Used);
  135. static void MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
  136. bool OnlyDeduced, unsigned Level,
  137. llvm::SmallBitVector &Deduced);
  138. /// If the given expression is of a form that permits the deduction
  139. /// of a non-type template parameter, return the declaration of that
  140. /// non-type template parameter.
  141. static const NonTypeTemplateParmDecl *
  142. getDeducedParameterFromExpr(const Expr *E, unsigned Depth) {
  143. // If we are within an alias template, the expression may have undergone
  144. // any number of parameter substitutions already.
  145. while (true) {
  146. if (const auto *IC = dyn_cast<ImplicitCastExpr>(E))
  147. E = IC->getSubExpr();
  148. else if (const auto *CE = dyn_cast<ConstantExpr>(E))
  149. E = CE->getSubExpr();
  150. else if (const auto *Subst = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
  151. E = Subst->getReplacement();
  152. else if (const auto *CCE = dyn_cast<CXXConstructExpr>(E)) {
  153. // Look through implicit copy construction from an lvalue of the same type.
  154. if (CCE->getParenOrBraceRange().isValid())
  155. break;
  156. // Note, there could be default arguments.
  157. assert(CCE->getNumArgs() >= 1 && "implicit construct expr should have 1 arg");
  158. E = CCE->getArg(0);
  159. } else
  160. break;
  161. }
  162. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  163. if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()))
  164. if (NTTP->getDepth() == Depth)
  165. return NTTP;
  166. return nullptr;
  167. }
  168. static const NonTypeTemplateParmDecl *
  169. getDeducedParameterFromExpr(TemplateDeductionInfo &Info, Expr *E) {
  170. return getDeducedParameterFromExpr(E, Info.getDeducedDepth());
  171. }
  172. /// Determine whether two declaration pointers refer to the same
  173. /// declaration.
  174. static bool isSameDeclaration(Decl *X, Decl *Y) {
  175. if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
  176. X = NX->getUnderlyingDecl();
  177. if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
  178. Y = NY->getUnderlyingDecl();
  179. return X->getCanonicalDecl() == Y->getCanonicalDecl();
  180. }
  181. /// Verify that the given, deduced template arguments are compatible.
  182. ///
  183. /// \returns The deduced template argument, or a NULL template argument if
  184. /// the deduced template arguments were incompatible.
  185. static DeducedTemplateArgument
  186. checkDeducedTemplateArguments(ASTContext &Context,
  187. const DeducedTemplateArgument &X,
  188. const DeducedTemplateArgument &Y) {
  189. // We have no deduction for one or both of the arguments; they're compatible.
  190. if (X.isNull())
  191. return Y;
  192. if (Y.isNull())
  193. return X;
  194. // If we have two non-type template argument values deduced for the same
  195. // parameter, they must both match the type of the parameter, and thus must
  196. // match each other's type. As we're only keeping one of them, we must check
  197. // for that now. The exception is that if either was deduced from an array
  198. // bound, the type is permitted to differ.
  199. if (!X.wasDeducedFromArrayBound() && !Y.wasDeducedFromArrayBound()) {
  200. QualType XType = X.getNonTypeTemplateArgumentType();
  201. if (!XType.isNull()) {
  202. QualType YType = Y.getNonTypeTemplateArgumentType();
  203. if (YType.isNull() || !Context.hasSameType(XType, YType))
  204. return DeducedTemplateArgument();
  205. }
  206. }
  207. switch (X.getKind()) {
  208. case TemplateArgument::Null:
  209. llvm_unreachable("Non-deduced template arguments handled above");
  210. case TemplateArgument::Type: {
  211. // If two template type arguments have the same type, they're compatible.
  212. QualType TX = X.getAsType(), TY = Y.getAsType();
  213. if (Y.getKind() == TemplateArgument::Type && Context.hasSameType(TX, TY))
  214. return DeducedTemplateArgument(Context.getCommonSugaredType(TX, TY),
  215. X.wasDeducedFromArrayBound() ||
  216. Y.wasDeducedFromArrayBound());
  217. // If one of the two arguments was deduced from an array bound, the other
  218. // supersedes it.
  219. if (X.wasDeducedFromArrayBound() != Y.wasDeducedFromArrayBound())
  220. return X.wasDeducedFromArrayBound() ? Y : X;
  221. // The arguments are not compatible.
  222. return DeducedTemplateArgument();
  223. }
  224. case TemplateArgument::Integral:
  225. // If we deduced a constant in one case and either a dependent expression or
  226. // declaration in another case, keep the integral constant.
  227. // If both are integral constants with the same value, keep that value.
  228. if (Y.getKind() == TemplateArgument::Expression ||
  229. Y.getKind() == TemplateArgument::Declaration ||
  230. (Y.getKind() == TemplateArgument::Integral &&
  231. hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral())))
  232. return X.wasDeducedFromArrayBound() ? Y : X;
  233. // All other combinations are incompatible.
  234. return DeducedTemplateArgument();
  235. case TemplateArgument::Template:
  236. if (Y.getKind() == TemplateArgument::Template &&
  237. Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
  238. return X;
  239. // All other combinations are incompatible.
  240. return DeducedTemplateArgument();
  241. case TemplateArgument::TemplateExpansion:
  242. if (Y.getKind() == TemplateArgument::TemplateExpansion &&
  243. Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
  244. Y.getAsTemplateOrTemplatePattern()))
  245. return X;
  246. // All other combinations are incompatible.
  247. return DeducedTemplateArgument();
  248. case TemplateArgument::Expression: {
  249. if (Y.getKind() != TemplateArgument::Expression)
  250. return checkDeducedTemplateArguments(Context, Y, X);
  251. // Compare the expressions for equality
  252. llvm::FoldingSetNodeID ID1, ID2;
  253. X.getAsExpr()->Profile(ID1, Context, true);
  254. Y.getAsExpr()->Profile(ID2, Context, true);
  255. if (ID1 == ID2)
  256. return X.wasDeducedFromArrayBound() ? Y : X;
  257. // Differing dependent expressions are incompatible.
  258. return DeducedTemplateArgument();
  259. }
  260. case TemplateArgument::Declaration:
  261. assert(!X.wasDeducedFromArrayBound());
  262. // If we deduced a declaration and a dependent expression, keep the
  263. // declaration.
  264. if (Y.getKind() == TemplateArgument::Expression)
  265. return X;
  266. // If we deduced a declaration and an integral constant, keep the
  267. // integral constant and whichever type did not come from an array
  268. // bound.
  269. if (Y.getKind() == TemplateArgument::Integral) {
  270. if (Y.wasDeducedFromArrayBound())
  271. return TemplateArgument(Context, Y.getAsIntegral(),
  272. X.getParamTypeForDecl());
  273. return Y;
  274. }
  275. // If we deduced two declarations, make sure that they refer to the
  276. // same declaration.
  277. if (Y.getKind() == TemplateArgument::Declaration &&
  278. isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
  279. return X;
  280. // All other combinations are incompatible.
  281. return DeducedTemplateArgument();
  282. case TemplateArgument::NullPtr:
  283. // If we deduced a null pointer and a dependent expression, keep the
  284. // null pointer.
  285. if (Y.getKind() == TemplateArgument::Expression)
  286. return TemplateArgument(Context.getCommonSugaredType(
  287. X.getNullPtrType(), Y.getAsExpr()->getType()),
  288. true);
  289. // If we deduced a null pointer and an integral constant, keep the
  290. // integral constant.
  291. if (Y.getKind() == TemplateArgument::Integral)
  292. return Y;
  293. // If we deduced two null pointers, they are the same.
  294. if (Y.getKind() == TemplateArgument::NullPtr)
  295. return TemplateArgument(
  296. Context.getCommonSugaredType(X.getNullPtrType(), Y.getNullPtrType()),
  297. true);
  298. // All other combinations are incompatible.
  299. return DeducedTemplateArgument();
  300. case TemplateArgument::Pack: {
  301. if (Y.getKind() != TemplateArgument::Pack ||
  302. X.pack_size() != Y.pack_size())
  303. return DeducedTemplateArgument();
  304. llvm::SmallVector<TemplateArgument, 8> NewPack;
  305. for (TemplateArgument::pack_iterator XA = X.pack_begin(),
  306. XAEnd = X.pack_end(),
  307. YA = Y.pack_begin();
  308. XA != XAEnd; ++XA, ++YA) {
  309. TemplateArgument Merged = checkDeducedTemplateArguments(
  310. Context, DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
  311. DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound()));
  312. if (Merged.isNull() && !(XA->isNull() && YA->isNull()))
  313. return DeducedTemplateArgument();
  314. NewPack.push_back(Merged);
  315. }
  316. return DeducedTemplateArgument(
  317. TemplateArgument::CreatePackCopy(Context, NewPack),
  318. X.wasDeducedFromArrayBound() && Y.wasDeducedFromArrayBound());
  319. }
  320. }
  321. llvm_unreachable("Invalid TemplateArgument Kind!");
  322. }
  323. /// Deduce the value of the given non-type template parameter
  324. /// as the given deduced template argument. All non-type template parameter
  325. /// deduction is funneled through here.
  326. static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
  327. Sema &S, TemplateParameterList *TemplateParams,
  328. const NonTypeTemplateParmDecl *NTTP, const DeducedTemplateArgument &NewDeduced,
  329. QualType ValueType, TemplateDeductionInfo &Info,
  330. SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
  331. assert(NTTP->getDepth() == Info.getDeducedDepth() &&
  332. "deducing non-type template argument with wrong depth");
  333. DeducedTemplateArgument Result = checkDeducedTemplateArguments(
  334. S.Context, Deduced[NTTP->getIndex()], NewDeduced);
  335. if (Result.isNull()) {
  336. Info.Param = const_cast<NonTypeTemplateParmDecl*>(NTTP);
  337. Info.FirstArg = Deduced[NTTP->getIndex()];
  338. Info.SecondArg = NewDeduced;
  339. return Sema::TDK_Inconsistent;
  340. }
  341. Deduced[NTTP->getIndex()] = Result;
  342. if (!S.getLangOpts().CPlusPlus17)
  343. return Sema::TDK_Success;
  344. if (NTTP->isExpandedParameterPack())
  345. // FIXME: We may still need to deduce parts of the type here! But we
  346. // don't have any way to find which slice of the type to use, and the
  347. // type stored on the NTTP itself is nonsense. Perhaps the type of an
  348. // expanded NTTP should be a pack expansion type?
  349. return Sema::TDK_Success;
  350. // Get the type of the parameter for deduction. If it's a (dependent) array
  351. // or function type, we will not have decayed it yet, so do that now.
  352. QualType ParamType = S.Context.getAdjustedParameterType(NTTP->getType());
  353. if (auto *Expansion = dyn_cast<PackExpansionType>(ParamType))
  354. ParamType = Expansion->getPattern();
  355. // FIXME: It's not clear how deduction of a parameter of reference
  356. // type from an argument (of non-reference type) should be performed.
  357. // For now, we just remove reference types from both sides and let
  358. // the final check for matching types sort out the mess.
  359. ValueType = ValueType.getNonReferenceType();
  360. if (ParamType->isReferenceType())
  361. ParamType = ParamType.getNonReferenceType();
  362. else
  363. // Top-level cv-qualifiers are irrelevant for a non-reference type.
  364. ValueType = ValueType.getUnqualifiedType();
  365. return DeduceTemplateArgumentsByTypeMatch(
  366. S, TemplateParams, ParamType, ValueType, Info, Deduced,
  367. TDF_SkipNonDependent, /*PartialOrdering=*/false,
  368. /*ArrayBound=*/NewDeduced.wasDeducedFromArrayBound());
  369. }
  370. /// Deduce the value of the given non-type template parameter
  371. /// from the given integral constant.
  372. static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
  373. Sema &S, TemplateParameterList *TemplateParams,
  374. const NonTypeTemplateParmDecl *NTTP, const llvm::APSInt &Value,
  375. QualType ValueType, bool DeducedFromArrayBound, TemplateDeductionInfo &Info,
  376. SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
  377. return DeduceNonTypeTemplateArgument(
  378. S, TemplateParams, NTTP,
  379. DeducedTemplateArgument(S.Context, Value, ValueType,
  380. DeducedFromArrayBound),
  381. ValueType, Info, Deduced);
  382. }
  383. /// Deduce the value of the given non-type template parameter
  384. /// from the given null pointer template argument type.
  385. static Sema::TemplateDeductionResult DeduceNullPtrTemplateArgument(
  386. Sema &S, TemplateParameterList *TemplateParams,
  387. const NonTypeTemplateParmDecl *NTTP, QualType NullPtrType,
  388. TemplateDeductionInfo &Info,
  389. SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
  390. Expr *Value = S.ImpCastExprToType(
  391. new (S.Context) CXXNullPtrLiteralExpr(S.Context.NullPtrTy,
  392. NTTP->getLocation()),
  393. NullPtrType,
  394. NullPtrType->isMemberPointerType() ? CK_NullToMemberPointer
  395. : CK_NullToPointer)
  396. .get();
  397. return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
  398. DeducedTemplateArgument(Value),
  399. Value->getType(), Info, Deduced);
  400. }
  401. /// Deduce the value of the given non-type template parameter
  402. /// from the given type- or value-dependent expression.
  403. ///
  404. /// \returns true if deduction succeeded, false otherwise.
  405. static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
  406. Sema &S, TemplateParameterList *TemplateParams,
  407. const NonTypeTemplateParmDecl *NTTP, Expr *Value, TemplateDeductionInfo &Info,
  408. SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
  409. return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
  410. DeducedTemplateArgument(Value),
  411. Value->getType(), Info, Deduced);
  412. }
  413. /// Deduce the value of the given non-type template parameter
  414. /// from the given declaration.
  415. ///
  416. /// \returns true if deduction succeeded, false otherwise.
  417. static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
  418. Sema &S, TemplateParameterList *TemplateParams,
  419. const NonTypeTemplateParmDecl *NTTP, ValueDecl *D, QualType T,
  420. TemplateDeductionInfo &Info,
  421. SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
  422. D = D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
  423. TemplateArgument New(D, T);
  424. return DeduceNonTypeTemplateArgument(
  425. S, TemplateParams, NTTP, DeducedTemplateArgument(New), T, Info, Deduced);
  426. }
  427. static Sema::TemplateDeductionResult
  428. DeduceTemplateArguments(Sema &S,
  429. TemplateParameterList *TemplateParams,
  430. TemplateName Param,
  431. TemplateName Arg,
  432. TemplateDeductionInfo &Info,
  433. SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
  434. TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
  435. if (!ParamDecl) {
  436. // The parameter type is dependent and is not a template template parameter,
  437. // so there is nothing that we can deduce.
  438. return Sema::TDK_Success;
  439. }
  440. if (TemplateTemplateParmDecl *TempParam
  441. = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
  442. // If we're not deducing at this depth, there's nothing to deduce.
  443. if (TempParam->getDepth() != Info.getDeducedDepth())
  444. return Sema::TDK_Success;
  445. DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
  446. DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
  447. Deduced[TempParam->getIndex()],
  448. NewDeduced);
  449. if (Result.isNull()) {
  450. Info.Param = TempParam;
  451. Info.FirstArg = Deduced[TempParam->getIndex()];
  452. Info.SecondArg = NewDeduced;
  453. return Sema::TDK_Inconsistent;
  454. }
  455. Deduced[TempParam->getIndex()] = Result;
  456. return Sema::TDK_Success;
  457. }
  458. // Verify that the two template names are equivalent.
  459. if (S.Context.hasSameTemplateName(Param, Arg))
  460. return Sema::TDK_Success;
  461. // Mismatch of non-dependent template parameter to argument.
  462. Info.FirstArg = TemplateArgument(Param);
  463. Info.SecondArg = TemplateArgument(Arg);
  464. return Sema::TDK_NonDeducedMismatch;
  465. }
  466. /// Deduce the template arguments by comparing the template parameter
  467. /// type (which is a template-id) with the template argument type.
  468. ///
  469. /// \param S the Sema
  470. ///
  471. /// \param TemplateParams the template parameters that we are deducing
  472. ///
  473. /// \param P the parameter type
  474. ///
  475. /// \param A the argument type
  476. ///
  477. /// \param Info information about the template argument deduction itself
  478. ///
  479. /// \param Deduced the deduced template arguments
  480. ///
  481. /// \returns the result of template argument deduction so far. Note that a
  482. /// "success" result means that template argument deduction has not yet failed,
  483. /// but it may still fail, later, for other reasons.
  484. static Sema::TemplateDeductionResult
  485. DeduceTemplateSpecArguments(Sema &S, TemplateParameterList *TemplateParams,
  486. const QualType P, QualType A,
  487. TemplateDeductionInfo &Info,
  488. SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
  489. QualType UP = P;
  490. if (const auto *IP = P->getAs<InjectedClassNameType>())
  491. UP = IP->getInjectedSpecializationType();
  492. // FIXME: Try to preserve type sugar here, which is hard
  493. // because of the unresolved template arguments.
  494. const auto *TP = UP.getCanonicalType()->castAs<TemplateSpecializationType>();
  495. TemplateName TNP = TP->getTemplateName();
  496. // If the parameter is an alias template, there is nothing to deduce.
  497. if (const auto *TD = TNP.getAsTemplateDecl(); TD && TD->isTypeAlias())
  498. return Sema::TDK_Success;
  499. ArrayRef<TemplateArgument> PResolved = TP->template_arguments();
  500. QualType UA = A;
  501. // Treat an injected-class-name as its underlying template-id.
  502. if (const auto *Injected = A->getAs<InjectedClassNameType>())
  503. UA = Injected->getInjectedSpecializationType();
  504. // Check whether the template argument is a dependent template-id.
  505. // FIXME: Should not lose sugar here.
  506. if (const auto *SA =
  507. dyn_cast<TemplateSpecializationType>(UA.getCanonicalType())) {
  508. TemplateName TNA = SA->getTemplateName();
  509. // If the argument is an alias template, there is nothing to deduce.
  510. if (const auto *TD = TNA.getAsTemplateDecl(); TD && TD->isTypeAlias())
  511. return Sema::TDK_Success;
  512. // Perform template argument deduction for the template name.
  513. if (auto Result =
  514. DeduceTemplateArguments(S, TemplateParams, TNP, TNA, Info, Deduced))
  515. return Result;
  516. // Perform template argument deduction on each template
  517. // argument. Ignore any missing/extra arguments, since they could be
  518. // filled in by default arguments.
  519. return DeduceTemplateArguments(S, TemplateParams, PResolved,
  520. SA->template_arguments(), Info, Deduced,
  521. /*NumberOfArgumentsMustMatch=*/false);
  522. }
  523. // If the argument type is a class template specialization, we
  524. // perform template argument deduction using its template
  525. // arguments.
  526. const auto *RA = UA->getAs<RecordType>();
  527. const auto *SA =
  528. RA ? dyn_cast<ClassTemplateSpecializationDecl>(RA->getDecl()) : nullptr;
  529. if (!SA) {
  530. Info.FirstArg = TemplateArgument(P);
  531. Info.SecondArg = TemplateArgument(A);
  532. return Sema::TDK_NonDeducedMismatch;
  533. }
  534. // Perform template argument deduction for the template name.
  535. if (auto Result = DeduceTemplateArguments(
  536. S, TemplateParams, TP->getTemplateName(),
  537. TemplateName(SA->getSpecializedTemplate()), Info, Deduced))
  538. return Result;
  539. // Perform template argument deduction for the template arguments.
  540. return DeduceTemplateArguments(S, TemplateParams, PResolved,
  541. SA->getTemplateArgs().asArray(), Info, Deduced,
  542. /*NumberOfArgumentsMustMatch=*/true);
  543. }
  544. static bool IsPossiblyOpaquelyQualifiedTypeInternal(const Type *T) {
  545. assert(T->isCanonicalUnqualified());
  546. switch (T->getTypeClass()) {
  547. case Type::TypeOfExpr:
  548. case Type::TypeOf:
  549. case Type::DependentName:
  550. case Type::Decltype:
  551. case Type::UnresolvedUsing:
  552. case Type::TemplateTypeParm:
  553. return true;
  554. case Type::ConstantArray:
  555. case Type::IncompleteArray:
  556. case Type::VariableArray:
  557. case Type::DependentSizedArray:
  558. return IsPossiblyOpaquelyQualifiedTypeInternal(
  559. cast<ArrayType>(T)->getElementType().getTypePtr());
  560. default:
  561. return false;
  562. }
  563. }
  564. /// Determines whether the given type is an opaque type that
  565. /// might be more qualified when instantiated.
  566. static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
  567. return IsPossiblyOpaquelyQualifiedTypeInternal(
  568. T->getCanonicalTypeInternal().getTypePtr());
  569. }
  570. /// Helper function to build a TemplateParameter when we don't
  571. /// know its type statically.
  572. static TemplateParameter makeTemplateParameter(Decl *D) {
  573. if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
  574. return TemplateParameter(TTP);
  575. if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
  576. return TemplateParameter(NTTP);
  577. return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
  578. }
  579. /// A pack that we're currently deducing.
  580. struct clang::DeducedPack {
  581. // The index of the pack.
  582. unsigned Index;
  583. // The old value of the pack before we started deducing it.
  584. DeducedTemplateArgument Saved;
  585. // A deferred value of this pack from an inner deduction, that couldn't be
  586. // deduced because this deduction hadn't happened yet.
  587. DeducedTemplateArgument DeferredDeduction;
  588. // The new value of the pack.
  589. SmallVector<DeducedTemplateArgument, 4> New;
  590. // The outer deduction for this pack, if any.
  591. DeducedPack *Outer = nullptr;
  592. DeducedPack(unsigned Index) : Index(Index) {}
  593. };
  594. namespace {
  595. /// A scope in which we're performing pack deduction.
  596. class PackDeductionScope {
  597. public:
  598. /// Prepare to deduce the packs named within Pattern.
  599. PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
  600. SmallVectorImpl<DeducedTemplateArgument> &Deduced,
  601. TemplateDeductionInfo &Info, TemplateArgument Pattern)
  602. : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
  603. unsigned NumNamedPacks = addPacks(Pattern);
  604. finishConstruction(NumNamedPacks);
  605. }
  606. /// Prepare to directly deduce arguments of the parameter with index \p Index.
  607. PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
  608. SmallVectorImpl<DeducedTemplateArgument> &Deduced,
  609. TemplateDeductionInfo &Info, unsigned Index)
  610. : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
  611. addPack(Index);
  612. finishConstruction(1);
  613. }
  614. private:
  615. void addPack(unsigned Index) {
  616. // Save the deduced template argument for the parameter pack expanded
  617. // by this pack expansion, then clear out the deduction.
  618. DeducedPack Pack(Index);
  619. Pack.Saved = Deduced[Index];
  620. Deduced[Index] = TemplateArgument();
  621. // FIXME: What if we encounter multiple packs with different numbers of
  622. // pre-expanded expansions? (This should already have been diagnosed
  623. // during substitution.)
  624. if (std::optional<unsigned> ExpandedPackExpansions =
  625. getExpandedPackSize(TemplateParams->getParam(Index)))
  626. FixedNumExpansions = ExpandedPackExpansions;
  627. Packs.push_back(Pack);
  628. }
  629. unsigned addPacks(TemplateArgument Pattern) {
  630. // Compute the set of template parameter indices that correspond to
  631. // parameter packs expanded by the pack expansion.
  632. llvm::SmallBitVector SawIndices(TemplateParams->size());
  633. llvm::SmallVector<TemplateArgument, 4> ExtraDeductions;
  634. auto AddPack = [&](unsigned Index) {
  635. if (SawIndices[Index])
  636. return;
  637. SawIndices[Index] = true;
  638. addPack(Index);
  639. // Deducing a parameter pack that is a pack expansion also constrains the
  640. // packs appearing in that parameter to have the same deduced arity. Also,
  641. // in C++17 onwards, deducing a non-type template parameter deduces its
  642. // type, so we need to collect the pending deduced values for those packs.
  643. if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(
  644. TemplateParams->getParam(Index))) {
  645. if (!NTTP->isExpandedParameterPack())
  646. if (auto *Expansion = dyn_cast<PackExpansionType>(NTTP->getType()))
  647. ExtraDeductions.push_back(Expansion->getPattern());
  648. }
  649. // FIXME: Also collect the unexpanded packs in any type and template
  650. // parameter packs that are pack expansions.
  651. };
  652. auto Collect = [&](TemplateArgument Pattern) {
  653. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  654. S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
  655. for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
  656. unsigned Depth, Index;
  657. std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
  658. if (Depth == Info.getDeducedDepth())
  659. AddPack(Index);
  660. }
  661. };
  662. // Look for unexpanded packs in the pattern.
  663. Collect(Pattern);
  664. assert(!Packs.empty() && "Pack expansion without unexpanded packs?");
  665. unsigned NumNamedPacks = Packs.size();
  666. // Also look for unexpanded packs that are indirectly deduced by deducing
  667. // the sizes of the packs in this pattern.
  668. while (!ExtraDeductions.empty())
  669. Collect(ExtraDeductions.pop_back_val());
  670. return NumNamedPacks;
  671. }
  672. void finishConstruction(unsigned NumNamedPacks) {
  673. // Dig out the partially-substituted pack, if there is one.
  674. const TemplateArgument *PartialPackArgs = nullptr;
  675. unsigned NumPartialPackArgs = 0;
  676. std::pair<unsigned, unsigned> PartialPackDepthIndex(-1u, -1u);
  677. if (auto *Scope = S.CurrentInstantiationScope)
  678. if (auto *Partial = Scope->getPartiallySubstitutedPack(
  679. &PartialPackArgs, &NumPartialPackArgs))
  680. PartialPackDepthIndex = getDepthAndIndex(Partial);
  681. // This pack expansion will have been partially or fully expanded if
  682. // it only names explicitly-specified parameter packs (including the
  683. // partially-substituted one, if any).
  684. bool IsExpanded = true;
  685. for (unsigned I = 0; I != NumNamedPacks; ++I) {
  686. if (Packs[I].Index >= Info.getNumExplicitArgs()) {
  687. IsExpanded = false;
  688. IsPartiallyExpanded = false;
  689. break;
  690. }
  691. if (PartialPackDepthIndex ==
  692. std::make_pair(Info.getDeducedDepth(), Packs[I].Index)) {
  693. IsPartiallyExpanded = true;
  694. }
  695. }
  696. // Skip over the pack elements that were expanded into separate arguments.
  697. // If we partially expanded, this is the number of partial arguments.
  698. if (IsPartiallyExpanded)
  699. PackElements += NumPartialPackArgs;
  700. else if (IsExpanded)
  701. PackElements += *FixedNumExpansions;
  702. for (auto &Pack : Packs) {
  703. if (Info.PendingDeducedPacks.size() > Pack.Index)
  704. Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
  705. else
  706. Info.PendingDeducedPacks.resize(Pack.Index + 1);
  707. Info.PendingDeducedPacks[Pack.Index] = &Pack;
  708. if (PartialPackDepthIndex ==
  709. std::make_pair(Info.getDeducedDepth(), Pack.Index)) {
  710. Pack.New.append(PartialPackArgs, PartialPackArgs + NumPartialPackArgs);
  711. // We pre-populate the deduced value of the partially-substituted
  712. // pack with the specified value. This is not entirely correct: the
  713. // value is supposed to have been substituted, not deduced, but the
  714. // cases where this is observable require an exact type match anyway.
  715. //
  716. // FIXME: If we could represent a "depth i, index j, pack elem k"
  717. // parameter, we could substitute the partially-substituted pack
  718. // everywhere and avoid this.
  719. if (!IsPartiallyExpanded)
  720. Deduced[Pack.Index] = Pack.New[PackElements];
  721. }
  722. }
  723. }
  724. public:
  725. ~PackDeductionScope() {
  726. for (auto &Pack : Packs)
  727. Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
  728. }
  729. /// Determine whether this pack has already been partially expanded into a
  730. /// sequence of (prior) function parameters / template arguments.
  731. bool isPartiallyExpanded() { return IsPartiallyExpanded; }
  732. /// Determine whether this pack expansion scope has a known, fixed arity.
  733. /// This happens if it involves a pack from an outer template that has
  734. /// (notionally) already been expanded.
  735. bool hasFixedArity() { return FixedNumExpansions.has_value(); }
  736. /// Determine whether the next element of the argument is still part of this
  737. /// pack. This is the case unless the pack is already expanded to a fixed
  738. /// length.
  739. bool hasNextElement() {
  740. return !FixedNumExpansions || *FixedNumExpansions > PackElements;
  741. }
  742. /// Move to deducing the next element in each pack that is being deduced.
  743. void nextPackElement() {
  744. // Capture the deduced template arguments for each parameter pack expanded
  745. // by this pack expansion, add them to the list of arguments we've deduced
  746. // for that pack, then clear out the deduced argument.
  747. for (auto &Pack : Packs) {
  748. DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
  749. if (!Pack.New.empty() || !DeducedArg.isNull()) {
  750. while (Pack.New.size() < PackElements)
  751. Pack.New.push_back(DeducedTemplateArgument());
  752. if (Pack.New.size() == PackElements)
  753. Pack.New.push_back(DeducedArg);
  754. else
  755. Pack.New[PackElements] = DeducedArg;
  756. DeducedArg = Pack.New.size() > PackElements + 1
  757. ? Pack.New[PackElements + 1]
  758. : DeducedTemplateArgument();
  759. }
  760. }
  761. ++PackElements;
  762. }
  763. /// Finish template argument deduction for a set of argument packs,
  764. /// producing the argument packs and checking for consistency with prior
  765. /// deductions.
  766. Sema::TemplateDeductionResult finish() {
  767. // Build argument packs for each of the parameter packs expanded by this
  768. // pack expansion.
  769. for (auto &Pack : Packs) {
  770. // Put back the old value for this pack.
  771. Deduced[Pack.Index] = Pack.Saved;
  772. // Always make sure the size of this pack is correct, even if we didn't
  773. // deduce any values for it.
  774. //
  775. // FIXME: This isn't required by the normative wording, but substitution
  776. // and post-substitution checking will always fail if the arity of any
  777. // pack is not equal to the number of elements we processed. (Either that
  778. // or something else has gone *very* wrong.) We're permitted to skip any
  779. // hard errors from those follow-on steps by the intent (but not the
  780. // wording) of C++ [temp.inst]p8:
  781. //
  782. // If the function selected by overload resolution can be determined
  783. // without instantiating a class template definition, it is unspecified
  784. // whether that instantiation actually takes place
  785. Pack.New.resize(PackElements);
  786. // Build or find a new value for this pack.
  787. DeducedTemplateArgument NewPack;
  788. if (Pack.New.empty()) {
  789. // If we deduced an empty argument pack, create it now.
  790. NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack());
  791. } else {
  792. TemplateArgument *ArgumentPack =
  793. new (S.Context) TemplateArgument[Pack.New.size()];
  794. std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
  795. NewPack = DeducedTemplateArgument(
  796. TemplateArgument(llvm::ArrayRef(ArgumentPack, Pack.New.size())),
  797. // FIXME: This is wrong, it's possible that some pack elements are
  798. // deduced from an array bound and others are not:
  799. // template<typename ...T, T ...V> void g(const T (&...p)[V]);
  800. // g({1, 2, 3}, {{}, {}});
  801. // ... should deduce T = {int, size_t (from array bound)}.
  802. Pack.New[0].wasDeducedFromArrayBound());
  803. }
  804. // Pick where we're going to put the merged pack.
  805. DeducedTemplateArgument *Loc;
  806. if (Pack.Outer) {
  807. if (Pack.Outer->DeferredDeduction.isNull()) {
  808. // Defer checking this pack until we have a complete pack to compare
  809. // it against.
  810. Pack.Outer->DeferredDeduction = NewPack;
  811. continue;
  812. }
  813. Loc = &Pack.Outer->DeferredDeduction;
  814. } else {
  815. Loc = &Deduced[Pack.Index];
  816. }
  817. // Check the new pack matches any previous value.
  818. DeducedTemplateArgument OldPack = *Loc;
  819. DeducedTemplateArgument Result =
  820. checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
  821. // If we deferred a deduction of this pack, check that one now too.
  822. if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
  823. OldPack = Result;
  824. NewPack = Pack.DeferredDeduction;
  825. Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
  826. }
  827. NamedDecl *Param = TemplateParams->getParam(Pack.Index);
  828. if (Result.isNull()) {
  829. Info.Param = makeTemplateParameter(Param);
  830. Info.FirstArg = OldPack;
  831. Info.SecondArg = NewPack;
  832. return Sema::TDK_Inconsistent;
  833. }
  834. // If we have a pre-expanded pack and we didn't deduce enough elements
  835. // for it, fail deduction.
  836. if (std::optional<unsigned> Expansions = getExpandedPackSize(Param)) {
  837. if (*Expansions != PackElements) {
  838. Info.Param = makeTemplateParameter(Param);
  839. Info.FirstArg = Result;
  840. return Sema::TDK_IncompletePack;
  841. }
  842. }
  843. *Loc = Result;
  844. }
  845. return Sema::TDK_Success;
  846. }
  847. private:
  848. Sema &S;
  849. TemplateParameterList *TemplateParams;
  850. SmallVectorImpl<DeducedTemplateArgument> &Deduced;
  851. TemplateDeductionInfo &Info;
  852. unsigned PackElements = 0;
  853. bool IsPartiallyExpanded = false;
  854. /// The number of expansions, if we have a fully-expanded pack in this scope.
  855. std::optional<unsigned> FixedNumExpansions;
  856. SmallVector<DeducedPack, 2> Packs;
  857. };
  858. } // namespace
  859. /// Deduce the template arguments by comparing the list of parameter
  860. /// types to the list of argument types, as in the parameter-type-lists of
  861. /// function types (C++ [temp.deduct.type]p10).
  862. ///
  863. /// \param S The semantic analysis object within which we are deducing
  864. ///
  865. /// \param TemplateParams The template parameters that we are deducing
  866. ///
  867. /// \param Params The list of parameter types
  868. ///
  869. /// \param NumParams The number of types in \c Params
  870. ///
  871. /// \param Args The list of argument types
  872. ///
  873. /// \param NumArgs The number of types in \c Args
  874. ///
  875. /// \param Info information about the template argument deduction itself
  876. ///
  877. /// \param Deduced the deduced template arguments
  878. ///
  879. /// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
  880. /// how template argument deduction is performed.
  881. ///
  882. /// \param PartialOrdering If true, we are performing template argument
  883. /// deduction for during partial ordering for a call
  884. /// (C++0x [temp.deduct.partial]).
  885. ///
  886. /// \returns the result of template argument deduction so far. Note that a
  887. /// "success" result means that template argument deduction has not yet failed,
  888. /// but it may still fail, later, for other reasons.
  889. static Sema::TemplateDeductionResult
  890. DeduceTemplateArguments(Sema &S,
  891. TemplateParameterList *TemplateParams,
  892. const QualType *Params, unsigned NumParams,
  893. const QualType *Args, unsigned NumArgs,
  894. TemplateDeductionInfo &Info,
  895. SmallVectorImpl<DeducedTemplateArgument> &Deduced,
  896. unsigned TDF,
  897. bool PartialOrdering = false) {
  898. // C++0x [temp.deduct.type]p10:
  899. // Similarly, if P has a form that contains (T), then each parameter type
  900. // Pi of the respective parameter-type- list of P is compared with the
  901. // corresponding parameter type Ai of the corresponding parameter-type-list
  902. // of A. [...]
  903. unsigned ArgIdx = 0, ParamIdx = 0;
  904. for (; ParamIdx != NumParams; ++ParamIdx) {
  905. // Check argument types.
  906. const PackExpansionType *Expansion
  907. = dyn_cast<PackExpansionType>(Params[ParamIdx]);
  908. if (!Expansion) {
  909. // Simple case: compare the parameter and argument types at this point.
  910. // Make sure we have an argument.
  911. if (ArgIdx >= NumArgs)
  912. return Sema::TDK_MiscellaneousDeductionFailure;
  913. if (isa<PackExpansionType>(Args[ArgIdx])) {
  914. // C++0x [temp.deduct.type]p22:
  915. // If the original function parameter associated with A is a function
  916. // parameter pack and the function parameter associated with P is not
  917. // a function parameter pack, then template argument deduction fails.
  918. return Sema::TDK_MiscellaneousDeductionFailure;
  919. }
  920. if (Sema::TemplateDeductionResult Result =
  921. DeduceTemplateArgumentsByTypeMatch(
  922. S, TemplateParams, Params[ParamIdx].getUnqualifiedType(),
  923. Args[ArgIdx].getUnqualifiedType(), Info, Deduced, TDF,
  924. PartialOrdering,
  925. /*DeducedFromArrayBound=*/false))
  926. return Result;
  927. ++ArgIdx;
  928. continue;
  929. }
  930. // C++0x [temp.deduct.type]p10:
  931. // If the parameter-declaration corresponding to Pi is a function
  932. // parameter pack, then the type of its declarator- id is compared with
  933. // each remaining parameter type in the parameter-type-list of A. Each
  934. // comparison deduces template arguments for subsequent positions in the
  935. // template parameter packs expanded by the function parameter pack.
  936. QualType Pattern = Expansion->getPattern();
  937. PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
  938. // A pack scope with fixed arity is not really a pack any more, so is not
  939. // a non-deduced context.
  940. if (ParamIdx + 1 == NumParams || PackScope.hasFixedArity()) {
  941. for (; ArgIdx < NumArgs && PackScope.hasNextElement(); ++ArgIdx) {
  942. // Deduce template arguments from the pattern.
  943. if (Sema::TemplateDeductionResult Result =
  944. DeduceTemplateArgumentsByTypeMatch(
  945. S, TemplateParams, Pattern.getUnqualifiedType(),
  946. Args[ArgIdx].getUnqualifiedType(), Info, Deduced, TDF,
  947. PartialOrdering, /*DeducedFromArrayBound=*/false))
  948. return Result;
  949. PackScope.nextPackElement();
  950. }
  951. } else {
  952. // C++0x [temp.deduct.type]p5:
  953. // The non-deduced contexts are:
  954. // - A function parameter pack that does not occur at the end of the
  955. // parameter-declaration-clause.
  956. //
  957. // FIXME: There is no wording to say what we should do in this case. We
  958. // choose to resolve this by applying the same rule that is applied for a
  959. // function call: that is, deduce all contained packs to their
  960. // explicitly-specified values (or to <> if there is no such value).
  961. //
  962. // This is seemingly-arbitrarily different from the case of a template-id
  963. // with a non-trailing pack-expansion in its arguments, which renders the
  964. // entire template-argument-list a non-deduced context.
  965. // If the parameter type contains an explicitly-specified pack that we
  966. // could not expand, skip the number of parameters notionally created
  967. // by the expansion.
  968. std::optional<unsigned> NumExpansions = Expansion->getNumExpansions();
  969. if (NumExpansions && !PackScope.isPartiallyExpanded()) {
  970. for (unsigned I = 0; I != *NumExpansions && ArgIdx < NumArgs;
  971. ++I, ++ArgIdx)
  972. PackScope.nextPackElement();
  973. }
  974. }
  975. // Build argument packs for each of the parameter packs expanded by this
  976. // pack expansion.
  977. if (auto Result = PackScope.finish())
  978. return Result;
  979. }
  980. // DR692, DR1395
  981. // C++0x [temp.deduct.type]p10:
  982. // If the parameter-declaration corresponding to P_i ...
  983. // During partial ordering, if Ai was originally a function parameter pack:
  984. // - if P does not contain a function parameter type corresponding to Ai then
  985. // Ai is ignored;
  986. if (PartialOrdering && ArgIdx + 1 == NumArgs &&
  987. isa<PackExpansionType>(Args[ArgIdx]))
  988. return Sema::TDK_Success;
  989. // Make sure we don't have any extra arguments.
  990. if (ArgIdx < NumArgs)
  991. return Sema::TDK_MiscellaneousDeductionFailure;
  992. return Sema::TDK_Success;
  993. }
  994. /// Determine whether the parameter has qualifiers that the argument
  995. /// lacks. Put another way, determine whether there is no way to add
  996. /// a deduced set of qualifiers to the ParamType that would result in
  997. /// its qualifiers matching those of the ArgType.
  998. static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType,
  999. QualType ArgType) {
  1000. Qualifiers ParamQs = ParamType.getQualifiers();
  1001. Qualifiers ArgQs = ArgType.getQualifiers();
  1002. if (ParamQs == ArgQs)
  1003. return false;
  1004. // Mismatched (but not missing) Objective-C GC attributes.
  1005. if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
  1006. ParamQs.hasObjCGCAttr())
  1007. return true;
  1008. // Mismatched (but not missing) address spaces.
  1009. if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
  1010. ParamQs.hasAddressSpace())
  1011. return true;
  1012. // Mismatched (but not missing) Objective-C lifetime qualifiers.
  1013. if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
  1014. ParamQs.hasObjCLifetime())
  1015. return true;
  1016. // CVR qualifiers inconsistent or a superset.
  1017. return (ParamQs.getCVRQualifiers() & ~ArgQs.getCVRQualifiers()) != 0;
  1018. }
  1019. /// Compare types for equality with respect to possibly compatible
  1020. /// function types (noreturn adjustment, implicit calling conventions). If any
  1021. /// of parameter and argument is not a function, just perform type comparison.
  1022. ///
  1023. /// \param P the template parameter type.
  1024. ///
  1025. /// \param A the argument type.
  1026. bool Sema::isSameOrCompatibleFunctionType(QualType P, QualType A) {
  1027. const FunctionType *PF = P->getAs<FunctionType>(),
  1028. *AF = A->getAs<FunctionType>();
  1029. // Just compare if not functions.
  1030. if (!PF || !AF)
  1031. return Context.hasSameType(P, A);
  1032. // Noreturn and noexcept adjustment.
  1033. QualType AdjustedParam;
  1034. if (IsFunctionConversion(P, A, AdjustedParam))
  1035. return Context.hasSameType(AdjustedParam, A);
  1036. // FIXME: Compatible calling conventions.
  1037. return Context.hasSameType(P, A);
  1038. }
  1039. /// Get the index of the first template parameter that was originally from the
  1040. /// innermost template-parameter-list. This is 0 except when we concatenate
  1041. /// the template parameter lists of a class template and a constructor template
  1042. /// when forming an implicit deduction guide.
  1043. static unsigned getFirstInnerIndex(FunctionTemplateDecl *FTD) {
  1044. auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FTD->getTemplatedDecl());
  1045. if (!Guide || !Guide->isImplicit())
  1046. return 0;
  1047. return Guide->getDeducedTemplate()->getTemplateParameters()->size();
  1048. }
  1049. /// Determine whether a type denotes a forwarding reference.
  1050. static bool isForwardingReference(QualType Param, unsigned FirstInnerIndex) {
  1051. // C++1z [temp.deduct.call]p3:
  1052. // A forwarding reference is an rvalue reference to a cv-unqualified
  1053. // template parameter that does not represent a template parameter of a
  1054. // class template.
  1055. if (auto *ParamRef = Param->getAs<RValueReferenceType>()) {
  1056. if (ParamRef->getPointeeType().getQualifiers())
  1057. return false;
  1058. auto *TypeParm = ParamRef->getPointeeType()->getAs<TemplateTypeParmType>();
  1059. return TypeParm && TypeParm->getIndex() >= FirstInnerIndex;
  1060. }
  1061. return false;
  1062. }
  1063. static CXXRecordDecl *getCanonicalRD(QualType T) {
  1064. return cast<CXXRecordDecl>(
  1065. T->castAs<RecordType>()->getDecl()->getCanonicalDecl());
  1066. }
  1067. /// Attempt to deduce the template arguments by checking the base types
  1068. /// according to (C++20 [temp.deduct.call] p4b3.
  1069. ///
  1070. /// \param S the semantic analysis object within which we are deducing.
  1071. ///
  1072. /// \param RD the top level record object we are deducing against.
  1073. ///
  1074. /// \param TemplateParams the template parameters that we are deducing.
  1075. ///
  1076. /// \param P the template specialization parameter type.
  1077. ///
  1078. /// \param Info information about the template argument deduction itself.
  1079. ///
  1080. /// \param Deduced the deduced template arguments.
  1081. ///
  1082. /// \returns the result of template argument deduction with the bases. "invalid"
  1083. /// means no matches, "success" found a single item, and the
  1084. /// "MiscellaneousDeductionFailure" result happens when the match is ambiguous.
  1085. static Sema::TemplateDeductionResult
  1086. DeduceTemplateBases(Sema &S, const CXXRecordDecl *RD,
  1087. TemplateParameterList *TemplateParams, QualType P,
  1088. TemplateDeductionInfo &Info,
  1089. SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
  1090. // C++14 [temp.deduct.call] p4b3:
  1091. // If P is a class and P has the form simple-template-id, then the
  1092. // transformed A can be a derived class of the deduced A. Likewise if
  1093. // P is a pointer to a class of the form simple-template-id, the
  1094. // transformed A can be a pointer to a derived class pointed to by the
  1095. // deduced A. However, if there is a class C that is a (direct or
  1096. // indirect) base class of D and derived (directly or indirectly) from a
  1097. // class B and that would be a valid deduced A, the deduced A cannot be
  1098. // B or pointer to B, respectively.
  1099. //
  1100. // These alternatives are considered only if type deduction would
  1101. // otherwise fail. If they yield more than one possible deduced A, the
  1102. // type deduction fails.
  1103. // Use a breadth-first search through the bases to collect the set of
  1104. // successful matches. Visited contains the set of nodes we have already
  1105. // visited, while ToVisit is our stack of records that we still need to
  1106. // visit. Matches contains a list of matches that have yet to be
  1107. // disqualified.
  1108. llvm::SmallPtrSet<const CXXRecordDecl *, 8> Visited;
  1109. SmallVector<QualType, 8> ToVisit;
  1110. // We iterate over this later, so we have to use MapVector to ensure
  1111. // determinism.
  1112. llvm::MapVector<const CXXRecordDecl *,
  1113. SmallVector<DeducedTemplateArgument, 8>>
  1114. Matches;
  1115. auto AddBases = [&Visited, &ToVisit](const CXXRecordDecl *RD) {
  1116. for (const auto &Base : RD->bases()) {
  1117. QualType T = Base.getType();
  1118. assert(T->isRecordType() && "Base class that isn't a record?");
  1119. if (Visited.insert(::getCanonicalRD(T)).second)
  1120. ToVisit.push_back(T);
  1121. }
  1122. };
  1123. // Set up the loop by adding all the bases.
  1124. AddBases(RD);
  1125. // Search each path of bases until we either run into a successful match
  1126. // (where all bases of it are invalid), or we run out of bases.
  1127. while (!ToVisit.empty()) {
  1128. QualType NextT = ToVisit.pop_back_val();
  1129. SmallVector<DeducedTemplateArgument, 8> DeducedCopy(Deduced.begin(),
  1130. Deduced.end());
  1131. TemplateDeductionInfo BaseInfo(TemplateDeductionInfo::ForBase, Info);
  1132. Sema::TemplateDeductionResult BaseResult = DeduceTemplateSpecArguments(
  1133. S, TemplateParams, P, NextT, BaseInfo, DeducedCopy);
  1134. // If this was a successful deduction, add it to the list of matches,
  1135. // otherwise we need to continue searching its bases.
  1136. const CXXRecordDecl *RD = ::getCanonicalRD(NextT);
  1137. if (BaseResult == Sema::TDK_Success)
  1138. Matches.insert({RD, DeducedCopy});
  1139. else
  1140. AddBases(RD);
  1141. }
  1142. // At this point, 'Matches' contains a list of seemingly valid bases, however
  1143. // in the event that we have more than 1 match, it is possible that the base
  1144. // of one of the matches might be disqualified for being a base of another
  1145. // valid match. We can count on cyclical instantiations being invalid to
  1146. // simplify the disqualifications. That is, if A & B are both matches, and B
  1147. // inherits from A (disqualifying A), we know that A cannot inherit from B.
  1148. if (Matches.size() > 1) {
  1149. Visited.clear();
  1150. for (const auto &Match : Matches)
  1151. AddBases(Match.first);
  1152. // We can give up once we have a single item (or have run out of things to
  1153. // search) since cyclical inheritance isn't valid.
  1154. while (Matches.size() > 1 && !ToVisit.empty()) {
  1155. const CXXRecordDecl *RD = ::getCanonicalRD(ToVisit.pop_back_val());
  1156. Matches.erase(RD);
  1157. // Always add all bases, since the inheritance tree can contain
  1158. // disqualifications for multiple matches.
  1159. AddBases(RD);
  1160. }
  1161. }
  1162. if (Matches.empty())
  1163. return Sema::TDK_Invalid;
  1164. if (Matches.size() > 1)
  1165. return Sema::TDK_MiscellaneousDeductionFailure;
  1166. std::swap(Matches.front().second, Deduced);
  1167. return Sema::TDK_Success;
  1168. }
  1169. /// Deduce the template arguments by comparing the parameter type and
  1170. /// the argument type (C++ [temp.deduct.type]).
  1171. ///
  1172. /// \param S the semantic analysis object within which we are deducing
  1173. ///
  1174. /// \param TemplateParams the template parameters that we are deducing
  1175. ///
  1176. /// \param P the parameter type
  1177. ///
  1178. /// \param A the argument type
  1179. ///
  1180. /// \param Info information about the template argument deduction itself
  1181. ///
  1182. /// \param Deduced the deduced template arguments
  1183. ///
  1184. /// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
  1185. /// how template argument deduction is performed.
  1186. ///
  1187. /// \param PartialOrdering Whether we're performing template argument deduction
  1188. /// in the context of partial ordering (C++0x [temp.deduct.partial]).
  1189. ///
  1190. /// \returns the result of template argument deduction so far. Note that a
  1191. /// "success" result means that template argument deduction has not yet failed,
  1192. /// but it may still fail, later, for other reasons.
  1193. static Sema::TemplateDeductionResult DeduceTemplateArgumentsByTypeMatch(
  1194. Sema &S, TemplateParameterList *TemplateParams, QualType P, QualType A,
  1195. TemplateDeductionInfo &Info,
  1196. SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF,
  1197. bool PartialOrdering, bool DeducedFromArrayBound) {
  1198. // If the argument type is a pack expansion, look at its pattern.
  1199. // This isn't explicitly called out
  1200. if (const auto *AExp = dyn_cast<PackExpansionType>(A))
  1201. A = AExp->getPattern();
  1202. assert(!isa<PackExpansionType>(A.getCanonicalType()));
  1203. if (PartialOrdering) {
  1204. // C++11 [temp.deduct.partial]p5:
  1205. // Before the partial ordering is done, certain transformations are
  1206. // performed on the types used for partial ordering:
  1207. // - If P is a reference type, P is replaced by the type referred to.
  1208. const ReferenceType *PRef = P->getAs<ReferenceType>();
  1209. if (PRef)
  1210. P = PRef->getPointeeType();
  1211. // - If A is a reference type, A is replaced by the type referred to.
  1212. const ReferenceType *ARef = A->getAs<ReferenceType>();
  1213. if (ARef)
  1214. A = A->getPointeeType();
  1215. if (PRef && ARef && S.Context.hasSameUnqualifiedType(P, A)) {
  1216. // C++11 [temp.deduct.partial]p9:
  1217. // If, for a given type, deduction succeeds in both directions (i.e.,
  1218. // the types are identical after the transformations above) and both
  1219. // P and A were reference types [...]:
  1220. // - if [one type] was an lvalue reference and [the other type] was
  1221. // not, [the other type] is not considered to be at least as
  1222. // specialized as [the first type]
  1223. // - if [one type] is more cv-qualified than [the other type],
  1224. // [the other type] is not considered to be at least as specialized
  1225. // as [the first type]
  1226. // Objective-C ARC adds:
  1227. // - [one type] has non-trivial lifetime, [the other type] has
  1228. // __unsafe_unretained lifetime, and the types are otherwise
  1229. // identical
  1230. //
  1231. // A is "considered to be at least as specialized" as P iff deduction
  1232. // succeeds, so we model this as a deduction failure. Note that
  1233. // [the first type] is P and [the other type] is A here; the standard
  1234. // gets this backwards.
  1235. Qualifiers PQuals = P.getQualifiers(), AQuals = A.getQualifiers();
  1236. if ((PRef->isLValueReferenceType() && !ARef->isLValueReferenceType()) ||
  1237. PQuals.isStrictSupersetOf(AQuals) ||
  1238. (PQuals.hasNonTrivialObjCLifetime() &&
  1239. AQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
  1240. PQuals.withoutObjCLifetime() == AQuals.withoutObjCLifetime())) {
  1241. Info.FirstArg = TemplateArgument(P);
  1242. Info.SecondArg = TemplateArgument(A);
  1243. return Sema::TDK_NonDeducedMismatch;
  1244. }
  1245. }
  1246. Qualifiers DiscardedQuals;
  1247. // C++11 [temp.deduct.partial]p7:
  1248. // Remove any top-level cv-qualifiers:
  1249. // - If P is a cv-qualified type, P is replaced by the cv-unqualified
  1250. // version of P.
  1251. P = S.Context.getUnqualifiedArrayType(P, DiscardedQuals);
  1252. // - If A is a cv-qualified type, A is replaced by the cv-unqualified
  1253. // version of A.
  1254. A = S.Context.getUnqualifiedArrayType(A, DiscardedQuals);
  1255. } else {
  1256. // C++0x [temp.deduct.call]p4 bullet 1:
  1257. // - If the original P is a reference type, the deduced A (i.e., the type
  1258. // referred to by the reference) can be more cv-qualified than the
  1259. // transformed A.
  1260. if (TDF & TDF_ParamWithReferenceType) {
  1261. Qualifiers Quals;
  1262. QualType UnqualP = S.Context.getUnqualifiedArrayType(P, Quals);
  1263. Quals.setCVRQualifiers(Quals.getCVRQualifiers() & A.getCVRQualifiers());
  1264. P = S.Context.getQualifiedType(UnqualP, Quals);
  1265. }
  1266. if ((TDF & TDF_TopLevelParameterTypeList) && !P->isFunctionType()) {
  1267. // C++0x [temp.deduct.type]p10:
  1268. // If P and A are function types that originated from deduction when
  1269. // taking the address of a function template (14.8.2.2) or when deducing
  1270. // template arguments from a function declaration (14.8.2.6) and Pi and
  1271. // Ai are parameters of the top-level parameter-type-list of P and A,
  1272. // respectively, Pi is adjusted if it is a forwarding reference and Ai
  1273. // is an lvalue reference, in
  1274. // which case the type of Pi is changed to be the template parameter
  1275. // type (i.e., T&& is changed to simply T). [ Note: As a result, when
  1276. // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
  1277. // deduced as X&. - end note ]
  1278. TDF &= ~TDF_TopLevelParameterTypeList;
  1279. if (isForwardingReference(P, /*FirstInnerIndex=*/0) &&
  1280. A->isLValueReferenceType())
  1281. P = P->getPointeeType();
  1282. }
  1283. }
  1284. // C++ [temp.deduct.type]p9:
  1285. // A template type argument T, a template template argument TT or a
  1286. // template non-type argument i can be deduced if P and A have one of
  1287. // the following forms:
  1288. //
  1289. // T
  1290. // cv-list T
  1291. if (const auto *TTP = P->getAs<TemplateTypeParmType>()) {
  1292. // Just skip any attempts to deduce from a placeholder type or a parameter
  1293. // at a different depth.
  1294. if (A->isPlaceholderType() || Info.getDeducedDepth() != TTP->getDepth())
  1295. return Sema::TDK_Success;
  1296. unsigned Index = TTP->getIndex();
  1297. // If the argument type is an array type, move the qualifiers up to the
  1298. // top level, so they can be matched with the qualifiers on the parameter.
  1299. if (A->isArrayType()) {
  1300. Qualifiers Quals;
  1301. A = S.Context.getUnqualifiedArrayType(A, Quals);
  1302. if (Quals)
  1303. A = S.Context.getQualifiedType(A, Quals);
  1304. }
  1305. // The argument type can not be less qualified than the parameter
  1306. // type.
  1307. if (!(TDF & TDF_IgnoreQualifiers) &&
  1308. hasInconsistentOrSupersetQualifiersOf(P, A)) {
  1309. Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
  1310. Info.FirstArg = TemplateArgument(P);
  1311. Info.SecondArg = TemplateArgument(A);
  1312. return Sema::TDK_Underqualified;
  1313. }
  1314. // Do not match a function type with a cv-qualified type.
  1315. // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1584
  1316. if (A->isFunctionType() && P.hasQualifiers())
  1317. return Sema::TDK_NonDeducedMismatch;
  1318. assert(TTP->getDepth() == Info.getDeducedDepth() &&
  1319. "saw template type parameter with wrong depth");
  1320. assert(A->getCanonicalTypeInternal() != S.Context.OverloadTy &&
  1321. "Unresolved overloaded function");
  1322. QualType DeducedType = A;
  1323. // Remove any qualifiers on the parameter from the deduced type.
  1324. // We checked the qualifiers for consistency above.
  1325. Qualifiers DeducedQs = DeducedType.getQualifiers();
  1326. Qualifiers ParamQs = P.getQualifiers();
  1327. DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
  1328. if (ParamQs.hasObjCGCAttr())
  1329. DeducedQs.removeObjCGCAttr();
  1330. if (ParamQs.hasAddressSpace())
  1331. DeducedQs.removeAddressSpace();
  1332. if (ParamQs.hasObjCLifetime())
  1333. DeducedQs.removeObjCLifetime();
  1334. // Objective-C ARC:
  1335. // If template deduction would produce a lifetime qualifier on a type
  1336. // that is not a lifetime type, template argument deduction fails.
  1337. if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
  1338. !DeducedType->isDependentType()) {
  1339. Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
  1340. Info.FirstArg = TemplateArgument(P);
  1341. Info.SecondArg = TemplateArgument(A);
  1342. return Sema::TDK_Underqualified;
  1343. }
  1344. // Objective-C ARC:
  1345. // If template deduction would produce an argument type with lifetime type
  1346. // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
  1347. if (S.getLangOpts().ObjCAutoRefCount && DeducedType->isObjCLifetimeType() &&
  1348. !DeducedQs.hasObjCLifetime())
  1349. DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong);
  1350. DeducedType =
  1351. S.Context.getQualifiedType(DeducedType.getUnqualifiedType(), DeducedQs);
  1352. DeducedTemplateArgument NewDeduced(DeducedType, DeducedFromArrayBound);
  1353. DeducedTemplateArgument Result =
  1354. checkDeducedTemplateArguments(S.Context, Deduced[Index], NewDeduced);
  1355. if (Result.isNull()) {
  1356. Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
  1357. Info.FirstArg = Deduced[Index];
  1358. Info.SecondArg = NewDeduced;
  1359. return Sema::TDK_Inconsistent;
  1360. }
  1361. Deduced[Index] = Result;
  1362. return Sema::TDK_Success;
  1363. }
  1364. // Set up the template argument deduction information for a failure.
  1365. Info.FirstArg = TemplateArgument(P);
  1366. Info.SecondArg = TemplateArgument(A);
  1367. // If the parameter is an already-substituted template parameter
  1368. // pack, do nothing: we don't know which of its arguments to look
  1369. // at, so we have to wait until all of the parameter packs in this
  1370. // expansion have arguments.
  1371. if (P->getAs<SubstTemplateTypeParmPackType>())
  1372. return Sema::TDK_Success;
  1373. // Check the cv-qualifiers on the parameter and argument types.
  1374. if (!(TDF & TDF_IgnoreQualifiers)) {
  1375. if (TDF & TDF_ParamWithReferenceType) {
  1376. if (hasInconsistentOrSupersetQualifiersOf(P, A))
  1377. return Sema::TDK_NonDeducedMismatch;
  1378. } else if (TDF & TDF_ArgWithReferenceType) {
  1379. // C++ [temp.deduct.conv]p4:
  1380. // If the original A is a reference type, A can be more cv-qualified
  1381. // than the deduced A
  1382. if (!A.getQualifiers().compatiblyIncludes(P.getQualifiers()))
  1383. return Sema::TDK_NonDeducedMismatch;
  1384. // Strip out all extra qualifiers from the argument to figure out the
  1385. // type we're converting to, prior to the qualification conversion.
  1386. Qualifiers Quals;
  1387. A = S.Context.getUnqualifiedArrayType(A, Quals);
  1388. A = S.Context.getQualifiedType(A, P.getQualifiers());
  1389. } else if (!IsPossiblyOpaquelyQualifiedType(P)) {
  1390. if (P.getCVRQualifiers() != A.getCVRQualifiers())
  1391. return Sema::TDK_NonDeducedMismatch;
  1392. }
  1393. }
  1394. // If the parameter type is not dependent, there is nothing to deduce.
  1395. if (!P->isDependentType()) {
  1396. if (TDF & TDF_SkipNonDependent)
  1397. return Sema::TDK_Success;
  1398. if ((TDF & TDF_IgnoreQualifiers) ? S.Context.hasSameUnqualifiedType(P, A)
  1399. : S.Context.hasSameType(P, A))
  1400. return Sema::TDK_Success;
  1401. if (TDF & TDF_AllowCompatibleFunctionType &&
  1402. S.isSameOrCompatibleFunctionType(P, A))
  1403. return Sema::TDK_Success;
  1404. if (!(TDF & TDF_IgnoreQualifiers))
  1405. return Sema::TDK_NonDeducedMismatch;
  1406. // Otherwise, when ignoring qualifiers, the types not having the same
  1407. // unqualified type does not mean they do not match, so in this case we
  1408. // must keep going and analyze with a non-dependent parameter type.
  1409. }
  1410. switch (P.getCanonicalType()->getTypeClass()) {
  1411. // Non-canonical types cannot appear here.
  1412. #define NON_CANONICAL_TYPE(Class, Base) \
  1413. case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
  1414. #define TYPE(Class, Base)
  1415. #include "clang/AST/TypeNodes.inc"
  1416. case Type::TemplateTypeParm:
  1417. case Type::SubstTemplateTypeParmPack:
  1418. llvm_unreachable("Type nodes handled above");
  1419. case Type::Auto:
  1420. // FIXME: Implement deduction in dependent case.
  1421. if (P->isDependentType())
  1422. return Sema::TDK_Success;
  1423. [[fallthrough]];
  1424. case Type::Builtin:
  1425. case Type::VariableArray:
  1426. case Type::Vector:
  1427. case Type::FunctionNoProto:
  1428. case Type::Record:
  1429. case Type::Enum:
  1430. case Type::ObjCObject:
  1431. case Type::ObjCInterface:
  1432. case Type::ObjCObjectPointer:
  1433. case Type::BitInt:
  1434. return (TDF & TDF_SkipNonDependent) ||
  1435. ((TDF & TDF_IgnoreQualifiers)
  1436. ? S.Context.hasSameUnqualifiedType(P, A)
  1437. : S.Context.hasSameType(P, A))
  1438. ? Sema::TDK_Success
  1439. : Sema::TDK_NonDeducedMismatch;
  1440. // _Complex T [placeholder extension]
  1441. case Type::Complex: {
  1442. const auto *CP = P->castAs<ComplexType>(), *CA = A->getAs<ComplexType>();
  1443. if (!CA)
  1444. return Sema::TDK_NonDeducedMismatch;
  1445. return DeduceTemplateArgumentsByTypeMatch(
  1446. S, TemplateParams, CP->getElementType(), CA->getElementType(), Info,
  1447. Deduced, TDF);
  1448. }
  1449. // _Atomic T [extension]
  1450. case Type::Atomic: {
  1451. const auto *PA = P->castAs<AtomicType>(), *AA = A->getAs<AtomicType>();
  1452. if (!AA)
  1453. return Sema::TDK_NonDeducedMismatch;
  1454. return DeduceTemplateArgumentsByTypeMatch(
  1455. S, TemplateParams, PA->getValueType(), AA->getValueType(), Info,
  1456. Deduced, TDF);
  1457. }
  1458. // T *
  1459. case Type::Pointer: {
  1460. QualType PointeeType;
  1461. if (const auto *PA = A->getAs<PointerType>()) {
  1462. PointeeType = PA->getPointeeType();
  1463. } else if (const auto *PA = A->getAs<ObjCObjectPointerType>()) {
  1464. PointeeType = PA->getPointeeType();
  1465. } else {
  1466. return Sema::TDK_NonDeducedMismatch;
  1467. }
  1468. return DeduceTemplateArgumentsByTypeMatch(
  1469. S, TemplateParams, P->castAs<PointerType>()->getPointeeType(),
  1470. PointeeType, Info, Deduced,
  1471. TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass));
  1472. }
  1473. // T &
  1474. case Type::LValueReference: {
  1475. const auto *RP = P->castAs<LValueReferenceType>(),
  1476. *RA = A->getAs<LValueReferenceType>();
  1477. if (!RA)
  1478. return Sema::TDK_NonDeducedMismatch;
  1479. return DeduceTemplateArgumentsByTypeMatch(
  1480. S, TemplateParams, RP->getPointeeType(), RA->getPointeeType(), Info,
  1481. Deduced, 0);
  1482. }
  1483. // T && [C++0x]
  1484. case Type::RValueReference: {
  1485. const auto *RP = P->castAs<RValueReferenceType>(),
  1486. *RA = A->getAs<RValueReferenceType>();
  1487. if (!RA)
  1488. return Sema::TDK_NonDeducedMismatch;
  1489. return DeduceTemplateArgumentsByTypeMatch(
  1490. S, TemplateParams, RP->getPointeeType(), RA->getPointeeType(), Info,
  1491. Deduced, 0);
  1492. }
  1493. // T [] (implied, but not stated explicitly)
  1494. case Type::IncompleteArray: {
  1495. const auto *IAA = S.Context.getAsIncompleteArrayType(A);
  1496. if (!IAA)
  1497. return Sema::TDK_NonDeducedMismatch;
  1498. return DeduceTemplateArgumentsByTypeMatch(
  1499. S, TemplateParams,
  1500. S.Context.getAsIncompleteArrayType(P)->getElementType(),
  1501. IAA->getElementType(), Info, Deduced, TDF & TDF_IgnoreQualifiers);
  1502. }
  1503. // T [integer-constant]
  1504. case Type::ConstantArray: {
  1505. const auto *CAA = S.Context.getAsConstantArrayType(A),
  1506. *CAP = S.Context.getAsConstantArrayType(P);
  1507. assert(CAP);
  1508. if (!CAA || CAA->getSize() != CAP->getSize())
  1509. return Sema::TDK_NonDeducedMismatch;
  1510. return DeduceTemplateArgumentsByTypeMatch(
  1511. S, TemplateParams, CAP->getElementType(), CAA->getElementType(), Info,
  1512. Deduced, TDF & TDF_IgnoreQualifiers);
  1513. }
  1514. // type [i]
  1515. case Type::DependentSizedArray: {
  1516. const auto *AA = S.Context.getAsArrayType(A);
  1517. if (!AA)
  1518. return Sema::TDK_NonDeducedMismatch;
  1519. // Check the element type of the arrays
  1520. const auto *DAP = S.Context.getAsDependentSizedArrayType(P);
  1521. assert(DAP);
  1522. if (auto Result = DeduceTemplateArgumentsByTypeMatch(
  1523. S, TemplateParams, DAP->getElementType(), AA->getElementType(),
  1524. Info, Deduced, TDF & TDF_IgnoreQualifiers))
  1525. return Result;
  1526. // Determine the array bound is something we can deduce.
  1527. const NonTypeTemplateParmDecl *NTTP =
  1528. getDeducedParameterFromExpr(Info, DAP->getSizeExpr());
  1529. if (!NTTP)
  1530. return Sema::TDK_Success;
  1531. // We can perform template argument deduction for the given non-type
  1532. // template parameter.
  1533. assert(NTTP->getDepth() == Info.getDeducedDepth() &&
  1534. "saw non-type template parameter with wrong depth");
  1535. if (const auto *CAA = dyn_cast<ConstantArrayType>(AA)) {
  1536. llvm::APSInt Size(CAA->getSize());
  1537. return DeduceNonTypeTemplateArgument(
  1538. S, TemplateParams, NTTP, Size, S.Context.getSizeType(),
  1539. /*ArrayBound=*/true, Info, Deduced);
  1540. }
  1541. if (const auto *DAA = dyn_cast<DependentSizedArrayType>(AA))
  1542. if (DAA->getSizeExpr())
  1543. return DeduceNonTypeTemplateArgument(
  1544. S, TemplateParams, NTTP, DAA->getSizeExpr(), Info, Deduced);
  1545. // Incomplete type does not match a dependently-sized array type
  1546. return Sema::TDK_NonDeducedMismatch;
  1547. }
  1548. // type(*)(T)
  1549. // T(*)()
  1550. // T(*)(T)
  1551. case Type::FunctionProto: {
  1552. const auto *FPP = P->castAs<FunctionProtoType>(),
  1553. *FPA = A->getAs<FunctionProtoType>();
  1554. if (!FPA)
  1555. return Sema::TDK_NonDeducedMismatch;
  1556. if (FPP->getMethodQuals() != FPA->getMethodQuals() ||
  1557. FPP->getRefQualifier() != FPA->getRefQualifier() ||
  1558. FPP->isVariadic() != FPA->isVariadic())
  1559. return Sema::TDK_NonDeducedMismatch;
  1560. // Check return types.
  1561. if (auto Result = DeduceTemplateArgumentsByTypeMatch(
  1562. S, TemplateParams, FPP->getReturnType(), FPA->getReturnType(),
  1563. Info, Deduced, 0,
  1564. /*PartialOrdering=*/false,
  1565. /*DeducedFromArrayBound=*/false))
  1566. return Result;
  1567. // Check parameter types.
  1568. if (auto Result = DeduceTemplateArguments(
  1569. S, TemplateParams, FPP->param_type_begin(), FPP->getNumParams(),
  1570. FPA->param_type_begin(), FPA->getNumParams(), Info, Deduced,
  1571. TDF & TDF_TopLevelParameterTypeList, PartialOrdering))
  1572. return Result;
  1573. if (TDF & TDF_AllowCompatibleFunctionType)
  1574. return Sema::TDK_Success;
  1575. // FIXME: Per core-2016/10/1019 (no corresponding core issue yet), permit
  1576. // deducing through the noexcept-specifier if it's part of the canonical
  1577. // type. libstdc++ relies on this.
  1578. Expr *NoexceptExpr = FPP->getNoexceptExpr();
  1579. if (const NonTypeTemplateParmDecl *NTTP =
  1580. NoexceptExpr ? getDeducedParameterFromExpr(Info, NoexceptExpr)
  1581. : nullptr) {
  1582. assert(NTTP->getDepth() == Info.getDeducedDepth() &&
  1583. "saw non-type template parameter with wrong depth");
  1584. llvm::APSInt Noexcept(1);
  1585. switch (FPA->canThrow()) {
  1586. case CT_Cannot:
  1587. Noexcept = 1;
  1588. [[fallthrough]];
  1589. case CT_Can:
  1590. // We give E in noexcept(E) the "deduced from array bound" treatment.
  1591. // FIXME: Should we?
  1592. return DeduceNonTypeTemplateArgument(
  1593. S, TemplateParams, NTTP, Noexcept, S.Context.BoolTy,
  1594. /*DeducedFromArrayBound=*/true, Info, Deduced);
  1595. case CT_Dependent:
  1596. if (Expr *ArgNoexceptExpr = FPA->getNoexceptExpr())
  1597. return DeduceNonTypeTemplateArgument(
  1598. S, TemplateParams, NTTP, ArgNoexceptExpr, Info, Deduced);
  1599. // Can't deduce anything from throw(T...).
  1600. break;
  1601. }
  1602. }
  1603. // FIXME: Detect non-deduced exception specification mismatches?
  1604. //
  1605. // Careful about [temp.deduct.call] and [temp.deduct.conv], which allow
  1606. // top-level differences in noexcept-specifications.
  1607. return Sema::TDK_Success;
  1608. }
  1609. case Type::InjectedClassName:
  1610. // Treat a template's injected-class-name as if the template
  1611. // specialization type had been used.
  1612. // template-name<T> (where template-name refers to a class template)
  1613. // template-name<i>
  1614. // TT<T>
  1615. // TT<i>
  1616. // TT<>
  1617. case Type::TemplateSpecialization: {
  1618. // When Arg cannot be a derived class, we can just try to deduce template
  1619. // arguments from the template-id.
  1620. if (!(TDF & TDF_DerivedClass) || !A->isRecordType())
  1621. return DeduceTemplateSpecArguments(S, TemplateParams, P, A, Info,
  1622. Deduced);
  1623. SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
  1624. Deduced.end());
  1625. auto Result =
  1626. DeduceTemplateSpecArguments(S, TemplateParams, P, A, Info, Deduced);
  1627. if (Result == Sema::TDK_Success)
  1628. return Result;
  1629. // We cannot inspect base classes as part of deduction when the type
  1630. // is incomplete, so either instantiate any templates necessary to
  1631. // complete the type, or skip over it if it cannot be completed.
  1632. if (!S.isCompleteType(Info.getLocation(), A))
  1633. return Result;
  1634. // Reset the incorrectly deduced argument from above.
  1635. Deduced = DeducedOrig;
  1636. // Check bases according to C++14 [temp.deduct.call] p4b3:
  1637. auto BaseResult = DeduceTemplateBases(S, getCanonicalRD(A),
  1638. TemplateParams, P, Info, Deduced);
  1639. return BaseResult != Sema::TDK_Invalid ? BaseResult : Result;
  1640. }
  1641. // T type::*
  1642. // T T::*
  1643. // T (type::*)()
  1644. // type (T::*)()
  1645. // type (type::*)(T)
  1646. // type (T::*)(T)
  1647. // T (type::*)(T)
  1648. // T (T::*)()
  1649. // T (T::*)(T)
  1650. case Type::MemberPointer: {
  1651. const auto *MPP = P->castAs<MemberPointerType>(),
  1652. *MPA = A->getAs<MemberPointerType>();
  1653. if (!MPA)
  1654. return Sema::TDK_NonDeducedMismatch;
  1655. QualType PPT = MPP->getPointeeType();
  1656. if (PPT->isFunctionType())
  1657. S.adjustMemberFunctionCC(PPT, /*IsStatic=*/true,
  1658. /*IsCtorOrDtor=*/false, Info.getLocation());
  1659. QualType APT = MPA->getPointeeType();
  1660. if (APT->isFunctionType())
  1661. S.adjustMemberFunctionCC(APT, /*IsStatic=*/true,
  1662. /*IsCtorOrDtor=*/false, Info.getLocation());
  1663. unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
  1664. if (auto Result = DeduceTemplateArgumentsByTypeMatch(
  1665. S, TemplateParams, PPT, APT, Info, Deduced, SubTDF))
  1666. return Result;
  1667. return DeduceTemplateArgumentsByTypeMatch(
  1668. S, TemplateParams, QualType(MPP->getClass(), 0),
  1669. QualType(MPA->getClass(), 0), Info, Deduced, SubTDF);
  1670. }
  1671. // (clang extension)
  1672. //
  1673. // type(^)(T)
  1674. // T(^)()
  1675. // T(^)(T)
  1676. case Type::BlockPointer: {
  1677. const auto *BPP = P->castAs<BlockPointerType>(),
  1678. *BPA = A->getAs<BlockPointerType>();
  1679. if (!BPA)
  1680. return Sema::TDK_NonDeducedMismatch;
  1681. return DeduceTemplateArgumentsByTypeMatch(
  1682. S, TemplateParams, BPP->getPointeeType(), BPA->getPointeeType(), Info,
  1683. Deduced, 0);
  1684. }
  1685. // (clang extension)
  1686. //
  1687. // T __attribute__(((ext_vector_type(<integral constant>))))
  1688. case Type::ExtVector: {
  1689. const auto *VP = P->castAs<ExtVectorType>();
  1690. QualType ElementType;
  1691. if (const auto *VA = A->getAs<ExtVectorType>()) {
  1692. // Make sure that the vectors have the same number of elements.
  1693. if (VP->getNumElements() != VA->getNumElements())
  1694. return Sema::TDK_NonDeducedMismatch;
  1695. ElementType = VA->getElementType();
  1696. } else if (const auto *VA = A->getAs<DependentSizedExtVectorType>()) {
  1697. // We can't check the number of elements, since the argument has a
  1698. // dependent number of elements. This can only occur during partial
  1699. // ordering.
  1700. ElementType = VA->getElementType();
  1701. } else {
  1702. return Sema::TDK_NonDeducedMismatch;
  1703. }
  1704. // Perform deduction on the element types.
  1705. return DeduceTemplateArgumentsByTypeMatch(
  1706. S, TemplateParams, VP->getElementType(), ElementType, Info, Deduced,
  1707. TDF);
  1708. }
  1709. case Type::DependentVector: {
  1710. const auto *VP = P->castAs<DependentVectorType>();
  1711. if (const auto *VA = A->getAs<VectorType>()) {
  1712. // Perform deduction on the element types.
  1713. if (auto Result = DeduceTemplateArgumentsByTypeMatch(
  1714. S, TemplateParams, VP->getElementType(), VA->getElementType(),
  1715. Info, Deduced, TDF))
  1716. return Result;
  1717. // Perform deduction on the vector size, if we can.
  1718. const NonTypeTemplateParmDecl *NTTP =
  1719. getDeducedParameterFromExpr(Info, VP->getSizeExpr());
  1720. if (!NTTP)
  1721. return Sema::TDK_Success;
  1722. llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
  1723. ArgSize = VA->getNumElements();
  1724. // Note that we use the "array bound" rules here; just like in that
  1725. // case, we don't have any particular type for the vector size, but
  1726. // we can provide one if necessary.
  1727. return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
  1728. S.Context.UnsignedIntTy, true,
  1729. Info, Deduced);
  1730. }
  1731. if (const auto *VA = A->getAs<DependentVectorType>()) {
  1732. // Perform deduction on the element types.
  1733. if (auto Result = DeduceTemplateArgumentsByTypeMatch(
  1734. S, TemplateParams, VP->getElementType(), VA->getElementType(),
  1735. Info, Deduced, TDF))
  1736. return Result;
  1737. // Perform deduction on the vector size, if we can.
  1738. const NonTypeTemplateParmDecl *NTTP =
  1739. getDeducedParameterFromExpr(Info, VP->getSizeExpr());
  1740. if (!NTTP)
  1741. return Sema::TDK_Success;
  1742. return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
  1743. VA->getSizeExpr(), Info, Deduced);
  1744. }
  1745. return Sema::TDK_NonDeducedMismatch;
  1746. }
  1747. // (clang extension)
  1748. //
  1749. // T __attribute__(((ext_vector_type(N))))
  1750. case Type::DependentSizedExtVector: {
  1751. const auto *VP = P->castAs<DependentSizedExtVectorType>();
  1752. if (const auto *VA = A->getAs<ExtVectorType>()) {
  1753. // Perform deduction on the element types.
  1754. if (auto Result = DeduceTemplateArgumentsByTypeMatch(
  1755. S, TemplateParams, VP->getElementType(), VA->getElementType(),
  1756. Info, Deduced, TDF))
  1757. return Result;
  1758. // Perform deduction on the vector size, if we can.
  1759. const NonTypeTemplateParmDecl *NTTP =
  1760. getDeducedParameterFromExpr(Info, VP->getSizeExpr());
  1761. if (!NTTP)
  1762. return Sema::TDK_Success;
  1763. llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
  1764. ArgSize = VA->getNumElements();
  1765. // Note that we use the "array bound" rules here; just like in that
  1766. // case, we don't have any particular type for the vector size, but
  1767. // we can provide one if necessary.
  1768. return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
  1769. S.Context.IntTy, true, Info,
  1770. Deduced);
  1771. }
  1772. if (const auto *VA = A->getAs<DependentSizedExtVectorType>()) {
  1773. // Perform deduction on the element types.
  1774. if (auto Result = DeduceTemplateArgumentsByTypeMatch(
  1775. S, TemplateParams, VP->getElementType(), VA->getElementType(),
  1776. Info, Deduced, TDF))
  1777. return Result;
  1778. // Perform deduction on the vector size, if we can.
  1779. const NonTypeTemplateParmDecl *NTTP =
  1780. getDeducedParameterFromExpr(Info, VP->getSizeExpr());
  1781. if (!NTTP)
  1782. return Sema::TDK_Success;
  1783. return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
  1784. VA->getSizeExpr(), Info, Deduced);
  1785. }
  1786. return Sema::TDK_NonDeducedMismatch;
  1787. }
  1788. // (clang extension)
  1789. //
  1790. // T __attribute__((matrix_type(<integral constant>,
  1791. // <integral constant>)))
  1792. case Type::ConstantMatrix: {
  1793. const auto *MP = P->castAs<ConstantMatrixType>(),
  1794. *MA = A->getAs<ConstantMatrixType>();
  1795. if (!MA)
  1796. return Sema::TDK_NonDeducedMismatch;
  1797. // Check that the dimensions are the same
  1798. if (MP->getNumRows() != MA->getNumRows() ||
  1799. MP->getNumColumns() != MA->getNumColumns()) {
  1800. return Sema::TDK_NonDeducedMismatch;
  1801. }
  1802. // Perform deduction on element types.
  1803. return DeduceTemplateArgumentsByTypeMatch(
  1804. S, TemplateParams, MP->getElementType(), MA->getElementType(), Info,
  1805. Deduced, TDF);
  1806. }
  1807. case Type::DependentSizedMatrix: {
  1808. const auto *MP = P->castAs<DependentSizedMatrixType>();
  1809. const auto *MA = A->getAs<MatrixType>();
  1810. if (!MA)
  1811. return Sema::TDK_NonDeducedMismatch;
  1812. // Check the element type of the matrixes.
  1813. if (auto Result = DeduceTemplateArgumentsByTypeMatch(
  1814. S, TemplateParams, MP->getElementType(), MA->getElementType(),
  1815. Info, Deduced, TDF))
  1816. return Result;
  1817. // Try to deduce a matrix dimension.
  1818. auto DeduceMatrixArg =
  1819. [&S, &Info, &Deduced, &TemplateParams](
  1820. Expr *ParamExpr, const MatrixType *A,
  1821. unsigned (ConstantMatrixType::*GetArgDimension)() const,
  1822. Expr *(DependentSizedMatrixType::*GetArgDimensionExpr)() const) {
  1823. const auto *ACM = dyn_cast<ConstantMatrixType>(A);
  1824. const auto *ADM = dyn_cast<DependentSizedMatrixType>(A);
  1825. if (!ParamExpr->isValueDependent()) {
  1826. std::optional<llvm::APSInt> ParamConst =
  1827. ParamExpr->getIntegerConstantExpr(S.Context);
  1828. if (!ParamConst)
  1829. return Sema::TDK_NonDeducedMismatch;
  1830. if (ACM) {
  1831. if ((ACM->*GetArgDimension)() == *ParamConst)
  1832. return Sema::TDK_Success;
  1833. return Sema::TDK_NonDeducedMismatch;
  1834. }
  1835. Expr *ArgExpr = (ADM->*GetArgDimensionExpr)();
  1836. if (std::optional<llvm::APSInt> ArgConst =
  1837. ArgExpr->getIntegerConstantExpr(S.Context))
  1838. if (*ArgConst == *ParamConst)
  1839. return Sema::TDK_Success;
  1840. return Sema::TDK_NonDeducedMismatch;
  1841. }
  1842. const NonTypeTemplateParmDecl *NTTP =
  1843. getDeducedParameterFromExpr(Info, ParamExpr);
  1844. if (!NTTP)
  1845. return Sema::TDK_Success;
  1846. if (ACM) {
  1847. llvm::APSInt ArgConst(
  1848. S.Context.getTypeSize(S.Context.getSizeType()));
  1849. ArgConst = (ACM->*GetArgDimension)();
  1850. return DeduceNonTypeTemplateArgument(
  1851. S, TemplateParams, NTTP, ArgConst, S.Context.getSizeType(),
  1852. /*ArrayBound=*/true, Info, Deduced);
  1853. }
  1854. return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
  1855. (ADM->*GetArgDimensionExpr)(),
  1856. Info, Deduced);
  1857. };
  1858. if (auto Result = DeduceMatrixArg(MP->getRowExpr(), MA,
  1859. &ConstantMatrixType::getNumRows,
  1860. &DependentSizedMatrixType::getRowExpr))
  1861. return Result;
  1862. return DeduceMatrixArg(MP->getColumnExpr(), MA,
  1863. &ConstantMatrixType::getNumColumns,
  1864. &DependentSizedMatrixType::getColumnExpr);
  1865. }
  1866. // (clang extension)
  1867. //
  1868. // T __attribute__(((address_space(N))))
  1869. case Type::DependentAddressSpace: {
  1870. const auto *ASP = P->castAs<DependentAddressSpaceType>();
  1871. if (const auto *ASA = A->getAs<DependentAddressSpaceType>()) {
  1872. // Perform deduction on the pointer type.
  1873. if (auto Result = DeduceTemplateArgumentsByTypeMatch(
  1874. S, TemplateParams, ASP->getPointeeType(), ASA->getPointeeType(),
  1875. Info, Deduced, TDF))
  1876. return Result;
  1877. // Perform deduction on the address space, if we can.
  1878. const NonTypeTemplateParmDecl *NTTP =
  1879. getDeducedParameterFromExpr(Info, ASP->getAddrSpaceExpr());
  1880. if (!NTTP)
  1881. return Sema::TDK_Success;
  1882. return DeduceNonTypeTemplateArgument(
  1883. S, TemplateParams, NTTP, ASA->getAddrSpaceExpr(), Info, Deduced);
  1884. }
  1885. if (isTargetAddressSpace(A.getAddressSpace())) {
  1886. llvm::APSInt ArgAddressSpace(S.Context.getTypeSize(S.Context.IntTy),
  1887. false);
  1888. ArgAddressSpace = toTargetAddressSpace(A.getAddressSpace());
  1889. // Perform deduction on the pointer types.
  1890. if (auto Result = DeduceTemplateArgumentsByTypeMatch(
  1891. S, TemplateParams, ASP->getPointeeType(),
  1892. S.Context.removeAddrSpaceQualType(A), Info, Deduced, TDF))
  1893. return Result;
  1894. // Perform deduction on the address space, if we can.
  1895. const NonTypeTemplateParmDecl *NTTP =
  1896. getDeducedParameterFromExpr(Info, ASP->getAddrSpaceExpr());
  1897. if (!NTTP)
  1898. return Sema::TDK_Success;
  1899. return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
  1900. ArgAddressSpace, S.Context.IntTy,
  1901. true, Info, Deduced);
  1902. }
  1903. return Sema::TDK_NonDeducedMismatch;
  1904. }
  1905. case Type::DependentBitInt: {
  1906. const auto *IP = P->castAs<DependentBitIntType>();
  1907. if (const auto *IA = A->getAs<BitIntType>()) {
  1908. if (IP->isUnsigned() != IA->isUnsigned())
  1909. return Sema::TDK_NonDeducedMismatch;
  1910. const NonTypeTemplateParmDecl *NTTP =
  1911. getDeducedParameterFromExpr(Info, IP->getNumBitsExpr());
  1912. if (!NTTP)
  1913. return Sema::TDK_Success;
  1914. llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
  1915. ArgSize = IA->getNumBits();
  1916. return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
  1917. S.Context.IntTy, true, Info,
  1918. Deduced);
  1919. }
  1920. if (const auto *IA = A->getAs<DependentBitIntType>()) {
  1921. if (IP->isUnsigned() != IA->isUnsigned())
  1922. return Sema::TDK_NonDeducedMismatch;
  1923. return Sema::TDK_Success;
  1924. }
  1925. return Sema::TDK_NonDeducedMismatch;
  1926. }
  1927. case Type::TypeOfExpr:
  1928. case Type::TypeOf:
  1929. case Type::DependentName:
  1930. case Type::UnresolvedUsing:
  1931. case Type::Decltype:
  1932. case Type::UnaryTransform:
  1933. case Type::DeducedTemplateSpecialization:
  1934. case Type::DependentTemplateSpecialization:
  1935. case Type::PackExpansion:
  1936. case Type::Pipe:
  1937. // No template argument deduction for these types
  1938. return Sema::TDK_Success;
  1939. }
  1940. llvm_unreachable("Invalid Type Class!");
  1941. }
  1942. static Sema::TemplateDeductionResult
  1943. DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
  1944. const TemplateArgument &P, TemplateArgument A,
  1945. TemplateDeductionInfo &Info,
  1946. SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
  1947. // If the template argument is a pack expansion, perform template argument
  1948. // deduction against the pattern of that expansion. This only occurs during
  1949. // partial ordering.
  1950. if (A.isPackExpansion())
  1951. A = A.getPackExpansionPattern();
  1952. switch (P.getKind()) {
  1953. case TemplateArgument::Null:
  1954. llvm_unreachable("Null template argument in parameter list");
  1955. case TemplateArgument::Type:
  1956. if (A.getKind() == TemplateArgument::Type)
  1957. return DeduceTemplateArgumentsByTypeMatch(
  1958. S, TemplateParams, P.getAsType(), A.getAsType(), Info, Deduced, 0);
  1959. Info.FirstArg = P;
  1960. Info.SecondArg = A;
  1961. return Sema::TDK_NonDeducedMismatch;
  1962. case TemplateArgument::Template:
  1963. if (A.getKind() == TemplateArgument::Template)
  1964. return DeduceTemplateArguments(S, TemplateParams, P.getAsTemplate(),
  1965. A.getAsTemplate(), Info, Deduced);
  1966. Info.FirstArg = P;
  1967. Info.SecondArg = A;
  1968. return Sema::TDK_NonDeducedMismatch;
  1969. case TemplateArgument::TemplateExpansion:
  1970. llvm_unreachable("caller should handle pack expansions");
  1971. case TemplateArgument::Declaration:
  1972. if (A.getKind() == TemplateArgument::Declaration &&
  1973. isSameDeclaration(P.getAsDecl(), A.getAsDecl()))
  1974. return Sema::TDK_Success;
  1975. Info.FirstArg = P;
  1976. Info.SecondArg = A;
  1977. return Sema::TDK_NonDeducedMismatch;
  1978. case TemplateArgument::NullPtr:
  1979. if (A.getKind() == TemplateArgument::NullPtr &&
  1980. S.Context.hasSameType(P.getNullPtrType(), A.getNullPtrType()))
  1981. return Sema::TDK_Success;
  1982. Info.FirstArg = P;
  1983. Info.SecondArg = A;
  1984. return Sema::TDK_NonDeducedMismatch;
  1985. case TemplateArgument::Integral:
  1986. if (A.getKind() == TemplateArgument::Integral) {
  1987. if (hasSameExtendedValue(P.getAsIntegral(), A.getAsIntegral()))
  1988. return Sema::TDK_Success;
  1989. }
  1990. Info.FirstArg = P;
  1991. Info.SecondArg = A;
  1992. return Sema::TDK_NonDeducedMismatch;
  1993. case TemplateArgument::Expression:
  1994. if (const NonTypeTemplateParmDecl *NTTP =
  1995. getDeducedParameterFromExpr(Info, P.getAsExpr())) {
  1996. if (A.getKind() == TemplateArgument::Integral)
  1997. return DeduceNonTypeTemplateArgument(
  1998. S, TemplateParams, NTTP, A.getAsIntegral(), A.getIntegralType(),
  1999. /*ArrayBound=*/false, Info, Deduced);
  2000. if (A.getKind() == TemplateArgument::NullPtr)
  2001. return DeduceNullPtrTemplateArgument(S, TemplateParams, NTTP,
  2002. A.getNullPtrType(), Info, Deduced);
  2003. if (A.getKind() == TemplateArgument::Expression)
  2004. return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
  2005. A.getAsExpr(), Info, Deduced);
  2006. if (A.getKind() == TemplateArgument::Declaration)
  2007. return DeduceNonTypeTemplateArgument(
  2008. S, TemplateParams, NTTP, A.getAsDecl(), A.getParamTypeForDecl(),
  2009. Info, Deduced);
  2010. Info.FirstArg = P;
  2011. Info.SecondArg = A;
  2012. return Sema::TDK_NonDeducedMismatch;
  2013. }
  2014. // Can't deduce anything, but that's okay.
  2015. return Sema::TDK_Success;
  2016. case TemplateArgument::Pack:
  2017. llvm_unreachable("Argument packs should be expanded by the caller!");
  2018. }
  2019. llvm_unreachable("Invalid TemplateArgument Kind!");
  2020. }
  2021. /// Determine whether there is a template argument to be used for
  2022. /// deduction.
  2023. ///
  2024. /// This routine "expands" argument packs in-place, overriding its input
  2025. /// parameters so that \c Args[ArgIdx] will be the available template argument.
  2026. ///
  2027. /// \returns true if there is another template argument (which will be at
  2028. /// \c Args[ArgIdx]), false otherwise.
  2029. static bool hasTemplateArgumentForDeduction(ArrayRef<TemplateArgument> &Args,
  2030. unsigned &ArgIdx) {
  2031. if (ArgIdx == Args.size())
  2032. return false;
  2033. const TemplateArgument &Arg = Args[ArgIdx];
  2034. if (Arg.getKind() != TemplateArgument::Pack)
  2035. return true;
  2036. assert(ArgIdx == Args.size() - 1 && "Pack not at the end of argument list?");
  2037. Args = Arg.pack_elements();
  2038. ArgIdx = 0;
  2039. return ArgIdx < Args.size();
  2040. }
  2041. /// Determine whether the given set of template arguments has a pack
  2042. /// expansion that is not the last template argument.
  2043. static bool hasPackExpansionBeforeEnd(ArrayRef<TemplateArgument> Args) {
  2044. bool FoundPackExpansion = false;
  2045. for (const auto &A : Args) {
  2046. if (FoundPackExpansion)
  2047. return true;
  2048. if (A.getKind() == TemplateArgument::Pack)
  2049. return hasPackExpansionBeforeEnd(A.pack_elements());
  2050. // FIXME: If this is a fixed-arity pack expansion from an outer level of
  2051. // templates, it should not be treated as a pack expansion.
  2052. if (A.isPackExpansion())
  2053. FoundPackExpansion = true;
  2054. }
  2055. return false;
  2056. }
  2057. static Sema::TemplateDeductionResult
  2058. DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
  2059. ArrayRef<TemplateArgument> Ps,
  2060. ArrayRef<TemplateArgument> As,
  2061. TemplateDeductionInfo &Info,
  2062. SmallVectorImpl<DeducedTemplateArgument> &Deduced,
  2063. bool NumberOfArgumentsMustMatch) {
  2064. // C++0x [temp.deduct.type]p9:
  2065. // If the template argument list of P contains a pack expansion that is not
  2066. // the last template argument, the entire template argument list is a
  2067. // non-deduced context.
  2068. if (hasPackExpansionBeforeEnd(Ps))
  2069. return Sema::TDK_Success;
  2070. // C++0x [temp.deduct.type]p9:
  2071. // If P has a form that contains <T> or <i>, then each argument Pi of the
  2072. // respective template argument list P is compared with the corresponding
  2073. // argument Ai of the corresponding template argument list of A.
  2074. unsigned ArgIdx = 0, ParamIdx = 0;
  2075. for (; hasTemplateArgumentForDeduction(Ps, ParamIdx); ++ParamIdx) {
  2076. const TemplateArgument &P = Ps[ParamIdx];
  2077. if (!P.isPackExpansion()) {
  2078. // The simple case: deduce template arguments by matching Pi and Ai.
  2079. // Check whether we have enough arguments.
  2080. if (!hasTemplateArgumentForDeduction(As, ArgIdx))
  2081. return NumberOfArgumentsMustMatch
  2082. ? Sema::TDK_MiscellaneousDeductionFailure
  2083. : Sema::TDK_Success;
  2084. // C++1z [temp.deduct.type]p9:
  2085. // During partial ordering, if Ai was originally a pack expansion [and]
  2086. // Pi is not a pack expansion, template argument deduction fails.
  2087. if (As[ArgIdx].isPackExpansion())
  2088. return Sema::TDK_MiscellaneousDeductionFailure;
  2089. // Perform deduction for this Pi/Ai pair.
  2090. if (auto Result = DeduceTemplateArguments(S, TemplateParams, P,
  2091. As[ArgIdx], Info, Deduced))
  2092. return Result;
  2093. // Move to the next argument.
  2094. ++ArgIdx;
  2095. continue;
  2096. }
  2097. // The parameter is a pack expansion.
  2098. // C++0x [temp.deduct.type]p9:
  2099. // If Pi is a pack expansion, then the pattern of Pi is compared with
  2100. // each remaining argument in the template argument list of A. Each
  2101. // comparison deduces template arguments for subsequent positions in the
  2102. // template parameter packs expanded by Pi.
  2103. TemplateArgument Pattern = P.getPackExpansionPattern();
  2104. // Prepare to deduce the packs within the pattern.
  2105. PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
  2106. // Keep track of the deduced template arguments for each parameter pack
  2107. // expanded by this pack expansion (the outer index) and for each
  2108. // template argument (the inner SmallVectors).
  2109. for (; hasTemplateArgumentForDeduction(As, ArgIdx) &&
  2110. PackScope.hasNextElement();
  2111. ++ArgIdx) {
  2112. // Deduce template arguments from the pattern.
  2113. if (auto Result = DeduceTemplateArguments(S, TemplateParams, Pattern,
  2114. As[ArgIdx], Info, Deduced))
  2115. return Result;
  2116. PackScope.nextPackElement();
  2117. }
  2118. // Build argument packs for each of the parameter packs expanded by this
  2119. // pack expansion.
  2120. if (auto Result = PackScope.finish())
  2121. return Result;
  2122. }
  2123. return Sema::TDK_Success;
  2124. }
  2125. static Sema::TemplateDeductionResult
  2126. DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
  2127. const TemplateArgumentList &ParamList,
  2128. const TemplateArgumentList &ArgList,
  2129. TemplateDeductionInfo &Info,
  2130. SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
  2131. return DeduceTemplateArguments(S, TemplateParams, ParamList.asArray(),
  2132. ArgList.asArray(), Info, Deduced,
  2133. /*NumberOfArgumentsMustMatch=*/false);
  2134. }
  2135. /// Determine whether two template arguments are the same.
  2136. static bool isSameTemplateArg(ASTContext &Context,
  2137. TemplateArgument X,
  2138. const TemplateArgument &Y,
  2139. bool PartialOrdering,
  2140. bool PackExpansionMatchesPack = false) {
  2141. // If we're checking deduced arguments (X) against original arguments (Y),
  2142. // we will have flattened packs to non-expansions in X.
  2143. if (PackExpansionMatchesPack && X.isPackExpansion() && !Y.isPackExpansion())
  2144. X = X.getPackExpansionPattern();
  2145. if (X.getKind() != Y.getKind())
  2146. return false;
  2147. switch (X.getKind()) {
  2148. case TemplateArgument::Null:
  2149. llvm_unreachable("Comparing NULL template argument");
  2150. case TemplateArgument::Type:
  2151. return Context.getCanonicalType(X.getAsType()) ==
  2152. Context.getCanonicalType(Y.getAsType());
  2153. case TemplateArgument::Declaration:
  2154. return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
  2155. case TemplateArgument::NullPtr:
  2156. return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
  2157. case TemplateArgument::Template:
  2158. case TemplateArgument::TemplateExpansion:
  2159. return Context.getCanonicalTemplateName(
  2160. X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
  2161. Context.getCanonicalTemplateName(
  2162. Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
  2163. case TemplateArgument::Integral:
  2164. return hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral());
  2165. case TemplateArgument::Expression: {
  2166. llvm::FoldingSetNodeID XID, YID;
  2167. X.getAsExpr()->Profile(XID, Context, true);
  2168. Y.getAsExpr()->Profile(YID, Context, true);
  2169. return XID == YID;
  2170. }
  2171. case TemplateArgument::Pack: {
  2172. unsigned PackIterationSize = X.pack_size();
  2173. if (X.pack_size() != Y.pack_size()) {
  2174. if (!PartialOrdering)
  2175. return false;
  2176. // C++0x [temp.deduct.type]p9:
  2177. // During partial ordering, if Ai was originally a pack expansion:
  2178. // - if P does not contain a template argument corresponding to Ai
  2179. // then Ai is ignored;
  2180. bool XHasMoreArg = X.pack_size() > Y.pack_size();
  2181. if (!(XHasMoreArg && X.pack_elements().back().isPackExpansion()) &&
  2182. !(!XHasMoreArg && Y.pack_elements().back().isPackExpansion()))
  2183. return false;
  2184. if (XHasMoreArg)
  2185. PackIterationSize = Y.pack_size();
  2186. }
  2187. ArrayRef<TemplateArgument> XP = X.pack_elements();
  2188. ArrayRef<TemplateArgument> YP = Y.pack_elements();
  2189. for (unsigned i = 0; i < PackIterationSize; ++i)
  2190. if (!isSameTemplateArg(Context, XP[i], YP[i], PartialOrdering,
  2191. PackExpansionMatchesPack))
  2192. return false;
  2193. return true;
  2194. }
  2195. }
  2196. llvm_unreachable("Invalid TemplateArgument Kind!");
  2197. }
  2198. /// Allocate a TemplateArgumentLoc where all locations have
  2199. /// been initialized to the given location.
  2200. ///
  2201. /// \param Arg The template argument we are producing template argument
  2202. /// location information for.
  2203. ///
  2204. /// \param NTTPType For a declaration template argument, the type of
  2205. /// the non-type template parameter that corresponds to this template
  2206. /// argument. Can be null if no type sugar is available to add to the
  2207. /// type from the template argument.
  2208. ///
  2209. /// \param Loc The source location to use for the resulting template
  2210. /// argument.
  2211. TemplateArgumentLoc
  2212. Sema::getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
  2213. QualType NTTPType, SourceLocation Loc) {
  2214. switch (Arg.getKind()) {
  2215. case TemplateArgument::Null:
  2216. llvm_unreachable("Can't get a NULL template argument here");
  2217. case TemplateArgument::Type:
  2218. return TemplateArgumentLoc(
  2219. Arg, Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
  2220. case TemplateArgument::Declaration: {
  2221. if (NTTPType.isNull())
  2222. NTTPType = Arg.getParamTypeForDecl();
  2223. Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
  2224. .getAs<Expr>();
  2225. return TemplateArgumentLoc(TemplateArgument(E), E);
  2226. }
  2227. case TemplateArgument::NullPtr: {
  2228. if (NTTPType.isNull())
  2229. NTTPType = Arg.getNullPtrType();
  2230. Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
  2231. .getAs<Expr>();
  2232. return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
  2233. E);
  2234. }
  2235. case TemplateArgument::Integral: {
  2236. Expr *E =
  2237. BuildExpressionFromIntegralTemplateArgument(Arg, Loc).getAs<Expr>();
  2238. return TemplateArgumentLoc(TemplateArgument(E), E);
  2239. }
  2240. case TemplateArgument::Template:
  2241. case TemplateArgument::TemplateExpansion: {
  2242. NestedNameSpecifierLocBuilder Builder;
  2243. TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
  2244. if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
  2245. Builder.MakeTrivial(Context, DTN->getQualifier(), Loc);
  2246. else if (QualifiedTemplateName *QTN =
  2247. Template.getAsQualifiedTemplateName())
  2248. Builder.MakeTrivial(Context, QTN->getQualifier(), Loc);
  2249. if (Arg.getKind() == TemplateArgument::Template)
  2250. return TemplateArgumentLoc(Context, Arg,
  2251. Builder.getWithLocInContext(Context), Loc);
  2252. return TemplateArgumentLoc(
  2253. Context, Arg, Builder.getWithLocInContext(Context), Loc, Loc);
  2254. }
  2255. case TemplateArgument::Expression:
  2256. return TemplateArgumentLoc(Arg, Arg.getAsExpr());
  2257. case TemplateArgument::Pack:
  2258. return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
  2259. }
  2260. llvm_unreachable("Invalid TemplateArgument Kind!");
  2261. }
  2262. TemplateArgumentLoc
  2263. Sema::getIdentityTemplateArgumentLoc(NamedDecl *TemplateParm,
  2264. SourceLocation Location) {
  2265. return getTrivialTemplateArgumentLoc(
  2266. Context.getInjectedTemplateArg(TemplateParm), QualType(), Location);
  2267. }
  2268. /// Convert the given deduced template argument and add it to the set of
  2269. /// fully-converted template arguments.
  2270. static bool ConvertDeducedTemplateArgument(
  2271. Sema &S, NamedDecl *Param, DeducedTemplateArgument Arg, NamedDecl *Template,
  2272. TemplateDeductionInfo &Info, bool IsDeduced,
  2273. SmallVectorImpl<TemplateArgument> &SugaredOutput,
  2274. SmallVectorImpl<TemplateArgument> &CanonicalOutput) {
  2275. auto ConvertArg = [&](DeducedTemplateArgument Arg,
  2276. unsigned ArgumentPackIndex) {
  2277. // Convert the deduced template argument into a template
  2278. // argument that we can check, almost as if the user had written
  2279. // the template argument explicitly.
  2280. TemplateArgumentLoc ArgLoc =
  2281. S.getTrivialTemplateArgumentLoc(Arg, QualType(), Info.getLocation());
  2282. // Check the template argument, converting it as necessary.
  2283. return S.CheckTemplateArgument(
  2284. Param, ArgLoc, Template, Template->getLocation(),
  2285. Template->getSourceRange().getEnd(), ArgumentPackIndex, SugaredOutput,
  2286. CanonicalOutput,
  2287. IsDeduced
  2288. ? (Arg.wasDeducedFromArrayBound() ? Sema::CTAK_DeducedFromArrayBound
  2289. : Sema::CTAK_Deduced)
  2290. : Sema::CTAK_Specified);
  2291. };
  2292. if (Arg.getKind() == TemplateArgument::Pack) {
  2293. // This is a template argument pack, so check each of its arguments against
  2294. // the template parameter.
  2295. SmallVector<TemplateArgument, 2> SugaredPackedArgsBuilder,
  2296. CanonicalPackedArgsBuilder;
  2297. for (const auto &P : Arg.pack_elements()) {
  2298. // When converting the deduced template argument, append it to the
  2299. // general output list. We need to do this so that the template argument
  2300. // checking logic has all of the prior template arguments available.
  2301. DeducedTemplateArgument InnerArg(P);
  2302. InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
  2303. assert(InnerArg.getKind() != TemplateArgument::Pack &&
  2304. "deduced nested pack");
  2305. if (P.isNull()) {
  2306. // We deduced arguments for some elements of this pack, but not for
  2307. // all of them. This happens if we get a conditionally-non-deduced
  2308. // context in a pack expansion (such as an overload set in one of the
  2309. // arguments).
  2310. S.Diag(Param->getLocation(),
  2311. diag::err_template_arg_deduced_incomplete_pack)
  2312. << Arg << Param;
  2313. return true;
  2314. }
  2315. if (ConvertArg(InnerArg, SugaredPackedArgsBuilder.size()))
  2316. return true;
  2317. // Move the converted template argument into our argument pack.
  2318. SugaredPackedArgsBuilder.push_back(SugaredOutput.pop_back_val());
  2319. CanonicalPackedArgsBuilder.push_back(CanonicalOutput.pop_back_val());
  2320. }
  2321. // If the pack is empty, we still need to substitute into the parameter
  2322. // itself, in case that substitution fails.
  2323. if (SugaredPackedArgsBuilder.empty()) {
  2324. LocalInstantiationScope Scope(S);
  2325. MultiLevelTemplateArgumentList Args(Template, SugaredOutput,
  2326. /*Final=*/true);
  2327. if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
  2328. Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
  2329. NTTP, SugaredOutput,
  2330. Template->getSourceRange());
  2331. if (Inst.isInvalid() ||
  2332. S.SubstType(NTTP->getType(), Args, NTTP->getLocation(),
  2333. NTTP->getDeclName()).isNull())
  2334. return true;
  2335. } else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
  2336. Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
  2337. TTP, SugaredOutput,
  2338. Template->getSourceRange());
  2339. if (Inst.isInvalid() || !S.SubstDecl(TTP, S.CurContext, Args))
  2340. return true;
  2341. }
  2342. // For type parameters, no substitution is ever required.
  2343. }
  2344. // Create the resulting argument pack.
  2345. SugaredOutput.push_back(
  2346. TemplateArgument::CreatePackCopy(S.Context, SugaredPackedArgsBuilder));
  2347. CanonicalOutput.push_back(TemplateArgument::CreatePackCopy(
  2348. S.Context, CanonicalPackedArgsBuilder));
  2349. return false;
  2350. }
  2351. return ConvertArg(Arg, 0);
  2352. }
  2353. // FIXME: This should not be a template, but
  2354. // ClassTemplatePartialSpecializationDecl sadly does not derive from
  2355. // TemplateDecl.
  2356. template <typename TemplateDeclT>
  2357. static Sema::TemplateDeductionResult ConvertDeducedTemplateArguments(
  2358. Sema &S, TemplateDeclT *Template, bool IsDeduced,
  2359. SmallVectorImpl<DeducedTemplateArgument> &Deduced,
  2360. TemplateDeductionInfo &Info,
  2361. SmallVectorImpl<TemplateArgument> &SugaredBuilder,
  2362. SmallVectorImpl<TemplateArgument> &CanonicalBuilder,
  2363. LocalInstantiationScope *CurrentInstantiationScope = nullptr,
  2364. unsigned NumAlreadyConverted = 0, bool PartialOverloading = false) {
  2365. TemplateParameterList *TemplateParams = Template->getTemplateParameters();
  2366. for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
  2367. NamedDecl *Param = TemplateParams->getParam(I);
  2368. // C++0x [temp.arg.explicit]p3:
  2369. // A trailing template parameter pack (14.5.3) not otherwise deduced will
  2370. // be deduced to an empty sequence of template arguments.
  2371. // FIXME: Where did the word "trailing" come from?
  2372. if (Deduced[I].isNull() && Param->isTemplateParameterPack()) {
  2373. if (auto Result =
  2374. PackDeductionScope(S, TemplateParams, Deduced, Info, I).finish())
  2375. return Result;
  2376. }
  2377. if (!Deduced[I].isNull()) {
  2378. if (I < NumAlreadyConverted) {
  2379. // We may have had explicitly-specified template arguments for a
  2380. // template parameter pack (that may or may not have been extended
  2381. // via additional deduced arguments).
  2382. if (Param->isParameterPack() && CurrentInstantiationScope &&
  2383. CurrentInstantiationScope->getPartiallySubstitutedPack() == Param) {
  2384. // Forget the partially-substituted pack; its substitution is now
  2385. // complete.
  2386. CurrentInstantiationScope->ResetPartiallySubstitutedPack();
  2387. // We still need to check the argument in case it was extended by
  2388. // deduction.
  2389. } else {
  2390. // We have already fully type-checked and converted this
  2391. // argument, because it was explicitly-specified. Just record the
  2392. // presence of this argument.
  2393. SugaredBuilder.push_back(Deduced[I]);
  2394. CanonicalBuilder.push_back(
  2395. S.Context.getCanonicalTemplateArgument(Deduced[I]));
  2396. continue;
  2397. }
  2398. }
  2399. // We may have deduced this argument, so it still needs to be
  2400. // checked and converted.
  2401. if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info,
  2402. IsDeduced, SugaredBuilder,
  2403. CanonicalBuilder)) {
  2404. Info.Param = makeTemplateParameter(Param);
  2405. // FIXME: These template arguments are temporary. Free them!
  2406. Info.reset(
  2407. TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder),
  2408. TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder));
  2409. return Sema::TDK_SubstitutionFailure;
  2410. }
  2411. continue;
  2412. }
  2413. // Substitute into the default template argument, if available.
  2414. bool HasDefaultArg = false;
  2415. TemplateDecl *TD = dyn_cast<TemplateDecl>(Template);
  2416. if (!TD) {
  2417. assert(isa<ClassTemplatePartialSpecializationDecl>(Template) ||
  2418. isa<VarTemplatePartialSpecializationDecl>(Template));
  2419. return Sema::TDK_Incomplete;
  2420. }
  2421. TemplateArgumentLoc DefArg;
  2422. {
  2423. Qualifiers ThisTypeQuals;
  2424. CXXRecordDecl *ThisContext = nullptr;
  2425. if (auto *Rec = dyn_cast<CXXRecordDecl>(TD->getDeclContext()))
  2426. if (Rec->isLambda())
  2427. if (auto *Method = dyn_cast<CXXMethodDecl>(Rec->getDeclContext())) {
  2428. ThisContext = Method->getParent();
  2429. ThisTypeQuals = Method->getMethodQualifiers();
  2430. }
  2431. Sema::CXXThisScopeRAII ThisScope(S, ThisContext, ThisTypeQuals,
  2432. S.getLangOpts().CPlusPlus17);
  2433. DefArg = S.SubstDefaultTemplateArgumentIfAvailable(
  2434. TD, TD->getLocation(), TD->getSourceRange().getEnd(), Param,
  2435. SugaredBuilder, CanonicalBuilder, HasDefaultArg);
  2436. }
  2437. // If there was no default argument, deduction is incomplete.
  2438. if (DefArg.getArgument().isNull()) {
  2439. Info.Param = makeTemplateParameter(
  2440. const_cast<NamedDecl *>(TemplateParams->getParam(I)));
  2441. Info.reset(TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder),
  2442. TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder));
  2443. if (PartialOverloading) break;
  2444. return HasDefaultArg ? Sema::TDK_SubstitutionFailure
  2445. : Sema::TDK_Incomplete;
  2446. }
  2447. // Check whether we can actually use the default argument.
  2448. if (S.CheckTemplateArgument(
  2449. Param, DefArg, TD, TD->getLocation(), TD->getSourceRange().getEnd(),
  2450. 0, SugaredBuilder, CanonicalBuilder, Sema::CTAK_Specified)) {
  2451. Info.Param = makeTemplateParameter(
  2452. const_cast<NamedDecl *>(TemplateParams->getParam(I)));
  2453. // FIXME: These template arguments are temporary. Free them!
  2454. Info.reset(TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder),
  2455. TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder));
  2456. return Sema::TDK_SubstitutionFailure;
  2457. }
  2458. // If we get here, we successfully used the default template argument.
  2459. }
  2460. return Sema::TDK_Success;
  2461. }
  2462. static DeclContext *getAsDeclContextOrEnclosing(Decl *D) {
  2463. if (auto *DC = dyn_cast<DeclContext>(D))
  2464. return DC;
  2465. return D->getDeclContext();
  2466. }
  2467. template<typename T> struct IsPartialSpecialization {
  2468. static constexpr bool value = false;
  2469. };
  2470. template<>
  2471. struct IsPartialSpecialization<ClassTemplatePartialSpecializationDecl> {
  2472. static constexpr bool value = true;
  2473. };
  2474. template<>
  2475. struct IsPartialSpecialization<VarTemplatePartialSpecializationDecl> {
  2476. static constexpr bool value = true;
  2477. };
  2478. template <typename TemplateDeclT>
  2479. static bool DeducedArgsNeedReplacement(TemplateDeclT *Template) {
  2480. return false;
  2481. }
  2482. template <>
  2483. bool DeducedArgsNeedReplacement<VarTemplatePartialSpecializationDecl>(
  2484. VarTemplatePartialSpecializationDecl *Spec) {
  2485. return !Spec->isClassScopeExplicitSpecialization();
  2486. }
  2487. template <>
  2488. bool DeducedArgsNeedReplacement<ClassTemplatePartialSpecializationDecl>(
  2489. ClassTemplatePartialSpecializationDecl *Spec) {
  2490. return !Spec->isClassScopeExplicitSpecialization();
  2491. }
  2492. template <typename TemplateDeclT>
  2493. static Sema::TemplateDeductionResult
  2494. CheckDeducedArgumentConstraints(Sema &S, TemplateDeclT *Template,
  2495. ArrayRef<TemplateArgument> SugaredDeducedArgs,
  2496. ArrayRef<TemplateArgument> CanonicalDeducedArgs,
  2497. TemplateDeductionInfo &Info) {
  2498. llvm::SmallVector<const Expr *, 3> AssociatedConstraints;
  2499. Template->getAssociatedConstraints(AssociatedConstraints);
  2500. bool NeedsReplacement = DeducedArgsNeedReplacement(Template);
  2501. TemplateArgumentList DeducedTAL{TemplateArgumentList::OnStack,
  2502. CanonicalDeducedArgs};
  2503. MultiLevelTemplateArgumentList MLTAL = S.getTemplateInstantiationArgs(
  2504. Template, /*Final=*/false,
  2505. /*InnerMost=*/NeedsReplacement ? nullptr : &DeducedTAL,
  2506. /*RelativeToPrimary=*/true, /*Pattern=*/
  2507. nullptr, /*ForConstraintInstantiation=*/true);
  2508. // getTemplateInstantiationArgs picks up the non-deduced version of the
  2509. // template args when this is a variable template partial specialization and
  2510. // not class-scope explicit specialization, so replace with Deduced Args
  2511. // instead of adding to inner-most.
  2512. if (NeedsReplacement)
  2513. MLTAL.replaceInnermostTemplateArguments(CanonicalDeducedArgs);
  2514. if (S.CheckConstraintSatisfaction(Template, AssociatedConstraints, MLTAL,
  2515. Info.getLocation(),
  2516. Info.AssociatedConstraintsSatisfaction) ||
  2517. !Info.AssociatedConstraintsSatisfaction.IsSatisfied) {
  2518. Info.reset(
  2519. TemplateArgumentList::CreateCopy(S.Context, SugaredDeducedArgs),
  2520. TemplateArgumentList::CreateCopy(S.Context, CanonicalDeducedArgs));
  2521. return Sema::TDK_ConstraintsNotSatisfied;
  2522. }
  2523. return Sema::TDK_Success;
  2524. }
  2525. /// Complete template argument deduction for a partial specialization.
  2526. template <typename T>
  2527. static std::enable_if_t<IsPartialSpecialization<T>::value,
  2528. Sema::TemplateDeductionResult>
  2529. FinishTemplateArgumentDeduction(
  2530. Sema &S, T *Partial, bool IsPartialOrdering,
  2531. const TemplateArgumentList &TemplateArgs,
  2532. SmallVectorImpl<DeducedTemplateArgument> &Deduced,
  2533. TemplateDeductionInfo &Info) {
  2534. // Unevaluated SFINAE context.
  2535. EnterExpressionEvaluationContext Unevaluated(
  2536. S, Sema::ExpressionEvaluationContext::Unevaluated);
  2537. Sema::SFINAETrap Trap(S);
  2538. Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Partial));
  2539. // C++ [temp.deduct.type]p2:
  2540. // [...] or if any template argument remains neither deduced nor
  2541. // explicitly specified, template argument deduction fails.
  2542. SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
  2543. if (auto Result = ConvertDeducedTemplateArguments(
  2544. S, Partial, IsPartialOrdering, Deduced, Info, SugaredBuilder,
  2545. CanonicalBuilder))
  2546. return Result;
  2547. // Form the template argument list from the deduced template arguments.
  2548. TemplateArgumentList *SugaredDeducedArgumentList =
  2549. TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder);
  2550. TemplateArgumentList *CanonicalDeducedArgumentList =
  2551. TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder);
  2552. Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
  2553. // Substitute the deduced template arguments into the template
  2554. // arguments of the class template partial specialization, and
  2555. // verify that the instantiated template arguments are both valid
  2556. // and are equivalent to the template arguments originally provided
  2557. // to the class template.
  2558. LocalInstantiationScope InstScope(S);
  2559. auto *Template = Partial->getSpecializedTemplate();
  2560. const ASTTemplateArgumentListInfo *PartialTemplArgInfo =
  2561. Partial->getTemplateArgsAsWritten();
  2562. TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
  2563. PartialTemplArgInfo->RAngleLoc);
  2564. if (S.SubstTemplateArguments(PartialTemplArgInfo->arguments(),
  2565. MultiLevelTemplateArgumentList(Partial,
  2566. SugaredBuilder,
  2567. /*Final=*/true),
  2568. InstArgs)) {
  2569. unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
  2570. if (ParamIdx >= Partial->getTemplateParameters()->size())
  2571. ParamIdx = Partial->getTemplateParameters()->size() - 1;
  2572. Decl *Param = const_cast<NamedDecl *>(
  2573. Partial->getTemplateParameters()->getParam(ParamIdx));
  2574. Info.Param = makeTemplateParameter(Param);
  2575. Info.FirstArg = (*PartialTemplArgInfo)[ArgIdx].getArgument();
  2576. return Sema::TDK_SubstitutionFailure;
  2577. }
  2578. bool ConstraintsNotSatisfied;
  2579. SmallVector<TemplateArgument, 4> SugaredConvertedInstArgs,
  2580. CanonicalConvertedInstArgs;
  2581. if (S.CheckTemplateArgumentList(
  2582. Template, Partial->getLocation(), InstArgs, false,
  2583. SugaredConvertedInstArgs, CanonicalConvertedInstArgs,
  2584. /*UpdateArgsWithConversions=*/true, &ConstraintsNotSatisfied))
  2585. return ConstraintsNotSatisfied ? Sema::TDK_ConstraintsNotSatisfied
  2586. : Sema::TDK_SubstitutionFailure;
  2587. TemplateParameterList *TemplateParams = Template->getTemplateParameters();
  2588. for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
  2589. TemplateArgument InstArg = SugaredConvertedInstArgs.data()[I];
  2590. if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg,
  2591. IsPartialOrdering)) {
  2592. Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
  2593. Info.FirstArg = TemplateArgs[I];
  2594. Info.SecondArg = InstArg;
  2595. return Sema::TDK_NonDeducedMismatch;
  2596. }
  2597. }
  2598. if (Trap.hasErrorOccurred())
  2599. return Sema::TDK_SubstitutionFailure;
  2600. if (auto Result = CheckDeducedArgumentConstraints(S, Partial, SugaredBuilder,
  2601. CanonicalBuilder, Info))
  2602. return Result;
  2603. return Sema::TDK_Success;
  2604. }
  2605. /// Complete template argument deduction for a class or variable template,
  2606. /// when partial ordering against a partial specialization.
  2607. // FIXME: Factor out duplication with partial specialization version above.
  2608. static Sema::TemplateDeductionResult FinishTemplateArgumentDeduction(
  2609. Sema &S, TemplateDecl *Template, bool PartialOrdering,
  2610. const TemplateArgumentList &TemplateArgs,
  2611. SmallVectorImpl<DeducedTemplateArgument> &Deduced,
  2612. TemplateDeductionInfo &Info) {
  2613. // Unevaluated SFINAE context.
  2614. EnterExpressionEvaluationContext Unevaluated(
  2615. S, Sema::ExpressionEvaluationContext::Unevaluated);
  2616. Sema::SFINAETrap Trap(S);
  2617. Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Template));
  2618. // C++ [temp.deduct.type]p2:
  2619. // [...] or if any template argument remains neither deduced nor
  2620. // explicitly specified, template argument deduction fails.
  2621. SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
  2622. if (auto Result = ConvertDeducedTemplateArguments(
  2623. S, Template, /*IsDeduced*/ PartialOrdering, Deduced, Info,
  2624. SugaredBuilder, CanonicalBuilder,
  2625. /*CurrentInstantiationScope=*/nullptr,
  2626. /*NumAlreadyConverted=*/0U, /*PartialOverloading=*/false))
  2627. return Result;
  2628. // Check that we produced the correct argument list.
  2629. TemplateParameterList *TemplateParams = Template->getTemplateParameters();
  2630. for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
  2631. TemplateArgument InstArg = CanonicalBuilder[I];
  2632. if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg, PartialOrdering,
  2633. /*PackExpansionMatchesPack=*/true)) {
  2634. Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
  2635. Info.FirstArg = TemplateArgs[I];
  2636. Info.SecondArg = InstArg;
  2637. return Sema::TDK_NonDeducedMismatch;
  2638. }
  2639. }
  2640. if (Trap.hasErrorOccurred())
  2641. return Sema::TDK_SubstitutionFailure;
  2642. if (auto Result = CheckDeducedArgumentConstraints(S, Template, SugaredBuilder,
  2643. CanonicalBuilder, Info))
  2644. return Result;
  2645. return Sema::TDK_Success;
  2646. }
  2647. /// Perform template argument deduction to determine whether
  2648. /// the given template arguments match the given class template
  2649. /// partial specialization per C++ [temp.class.spec.match].
  2650. Sema::TemplateDeductionResult
  2651. Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
  2652. const TemplateArgumentList &TemplateArgs,
  2653. TemplateDeductionInfo &Info) {
  2654. if (Partial->isInvalidDecl())
  2655. return TDK_Invalid;
  2656. // C++ [temp.class.spec.match]p2:
  2657. // A partial specialization matches a given actual template
  2658. // argument list if the template arguments of the partial
  2659. // specialization can be deduced from the actual template argument
  2660. // list (14.8.2).
  2661. // Unevaluated SFINAE context.
  2662. EnterExpressionEvaluationContext Unevaluated(
  2663. *this, Sema::ExpressionEvaluationContext::Unevaluated);
  2664. SFINAETrap Trap(*this);
  2665. // This deduction has no relation to any outer instantiation we might be
  2666. // performing.
  2667. LocalInstantiationScope InstantiationScope(*this);
  2668. SmallVector<DeducedTemplateArgument, 4> Deduced;
  2669. Deduced.resize(Partial->getTemplateParameters()->size());
  2670. if (TemplateDeductionResult Result
  2671. = ::DeduceTemplateArguments(*this,
  2672. Partial->getTemplateParameters(),
  2673. Partial->getTemplateArgs(),
  2674. TemplateArgs, Info, Deduced))
  2675. return Result;
  2676. SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
  2677. InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
  2678. Info);
  2679. if (Inst.isInvalid())
  2680. return TDK_InstantiationDepth;
  2681. if (Trap.hasErrorOccurred())
  2682. return Sema::TDK_SubstitutionFailure;
  2683. TemplateDeductionResult Result;
  2684. runWithSufficientStackSpace(Info.getLocation(), [&] {
  2685. Result = ::FinishTemplateArgumentDeduction(*this, Partial,
  2686. /*IsPartialOrdering=*/false,
  2687. TemplateArgs, Deduced, Info);
  2688. });
  2689. return Result;
  2690. }
  2691. /// Perform template argument deduction to determine whether
  2692. /// the given template arguments match the given variable template
  2693. /// partial specialization per C++ [temp.class.spec.match].
  2694. Sema::TemplateDeductionResult
  2695. Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
  2696. const TemplateArgumentList &TemplateArgs,
  2697. TemplateDeductionInfo &Info) {
  2698. if (Partial->isInvalidDecl())
  2699. return TDK_Invalid;
  2700. // C++ [temp.class.spec.match]p2:
  2701. // A partial specialization matches a given actual template
  2702. // argument list if the template arguments of the partial
  2703. // specialization can be deduced from the actual template argument
  2704. // list (14.8.2).
  2705. // Unevaluated SFINAE context.
  2706. EnterExpressionEvaluationContext Unevaluated(
  2707. *this, Sema::ExpressionEvaluationContext::Unevaluated);
  2708. SFINAETrap Trap(*this);
  2709. // This deduction has no relation to any outer instantiation we might be
  2710. // performing.
  2711. LocalInstantiationScope InstantiationScope(*this);
  2712. SmallVector<DeducedTemplateArgument, 4> Deduced;
  2713. Deduced.resize(Partial->getTemplateParameters()->size());
  2714. if (TemplateDeductionResult Result = ::DeduceTemplateArguments(
  2715. *this, Partial->getTemplateParameters(), Partial->getTemplateArgs(),
  2716. TemplateArgs, Info, Deduced))
  2717. return Result;
  2718. SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
  2719. InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
  2720. Info);
  2721. if (Inst.isInvalid())
  2722. return TDK_InstantiationDepth;
  2723. if (Trap.hasErrorOccurred())
  2724. return Sema::TDK_SubstitutionFailure;
  2725. TemplateDeductionResult Result;
  2726. runWithSufficientStackSpace(Info.getLocation(), [&] {
  2727. Result = ::FinishTemplateArgumentDeduction(*this, Partial,
  2728. /*IsPartialOrdering=*/false,
  2729. TemplateArgs, Deduced, Info);
  2730. });
  2731. return Result;
  2732. }
  2733. /// Determine whether the given type T is a simple-template-id type.
  2734. static bool isSimpleTemplateIdType(QualType T) {
  2735. if (const TemplateSpecializationType *Spec
  2736. = T->getAs<TemplateSpecializationType>())
  2737. return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
  2738. // C++17 [temp.local]p2:
  2739. // the injected-class-name [...] is equivalent to the template-name followed
  2740. // by the template-arguments of the class template specialization or partial
  2741. // specialization enclosed in <>
  2742. // ... which means it's equivalent to a simple-template-id.
  2743. //
  2744. // This only arises during class template argument deduction for a copy
  2745. // deduction candidate, where it permits slicing.
  2746. if (T->getAs<InjectedClassNameType>())
  2747. return true;
  2748. return false;
  2749. }
  2750. /// Substitute the explicitly-provided template arguments into the
  2751. /// given function template according to C++ [temp.arg.explicit].
  2752. ///
  2753. /// \param FunctionTemplate the function template into which the explicit
  2754. /// template arguments will be substituted.
  2755. ///
  2756. /// \param ExplicitTemplateArgs the explicitly-specified template
  2757. /// arguments.
  2758. ///
  2759. /// \param Deduced the deduced template arguments, which will be populated
  2760. /// with the converted and checked explicit template arguments.
  2761. ///
  2762. /// \param ParamTypes will be populated with the instantiated function
  2763. /// parameters.
  2764. ///
  2765. /// \param FunctionType if non-NULL, the result type of the function template
  2766. /// will also be instantiated and the pointed-to value will be updated with
  2767. /// the instantiated function type.
  2768. ///
  2769. /// \param Info if substitution fails for any reason, this object will be
  2770. /// populated with more information about the failure.
  2771. ///
  2772. /// \returns TDK_Success if substitution was successful, or some failure
  2773. /// condition.
  2774. Sema::TemplateDeductionResult Sema::SubstituteExplicitTemplateArguments(
  2775. FunctionTemplateDecl *FunctionTemplate,
  2776. TemplateArgumentListInfo &ExplicitTemplateArgs,
  2777. SmallVectorImpl<DeducedTemplateArgument> &Deduced,
  2778. SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
  2779. TemplateDeductionInfo &Info) {
  2780. FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
  2781. TemplateParameterList *TemplateParams
  2782. = FunctionTemplate->getTemplateParameters();
  2783. if (ExplicitTemplateArgs.size() == 0) {
  2784. // No arguments to substitute; just copy over the parameter types and
  2785. // fill in the function type.
  2786. for (auto *P : Function->parameters())
  2787. ParamTypes.push_back(P->getType());
  2788. if (FunctionType)
  2789. *FunctionType = Function->getType();
  2790. return TDK_Success;
  2791. }
  2792. // Unevaluated SFINAE context.
  2793. EnterExpressionEvaluationContext Unevaluated(
  2794. *this, Sema::ExpressionEvaluationContext::Unevaluated);
  2795. SFINAETrap Trap(*this);
  2796. // C++ [temp.arg.explicit]p3:
  2797. // Template arguments that are present shall be specified in the
  2798. // declaration order of their corresponding template-parameters. The
  2799. // template argument list shall not specify more template-arguments than
  2800. // there are corresponding template-parameters.
  2801. SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
  2802. // Enter a new template instantiation context where we check the
  2803. // explicitly-specified template arguments against this function template,
  2804. // and then substitute them into the function parameter types.
  2805. SmallVector<TemplateArgument, 4> DeducedArgs;
  2806. InstantiatingTemplate Inst(
  2807. *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
  2808. CodeSynthesisContext::ExplicitTemplateArgumentSubstitution, Info);
  2809. if (Inst.isInvalid())
  2810. return TDK_InstantiationDepth;
  2811. if (CheckTemplateArgumentList(FunctionTemplate, SourceLocation(),
  2812. ExplicitTemplateArgs, true, SugaredBuilder,
  2813. CanonicalBuilder,
  2814. /*UpdateArgsWithConversions=*/false) ||
  2815. Trap.hasErrorOccurred()) {
  2816. unsigned Index = SugaredBuilder.size();
  2817. if (Index >= TemplateParams->size())
  2818. return TDK_SubstitutionFailure;
  2819. Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
  2820. return TDK_InvalidExplicitArguments;
  2821. }
  2822. // Form the template argument list from the explicitly-specified
  2823. // template arguments.
  2824. TemplateArgumentList *SugaredExplicitArgumentList =
  2825. TemplateArgumentList::CreateCopy(Context, SugaredBuilder);
  2826. TemplateArgumentList *CanonicalExplicitArgumentList =
  2827. TemplateArgumentList::CreateCopy(Context, CanonicalBuilder);
  2828. Info.setExplicitArgs(SugaredExplicitArgumentList,
  2829. CanonicalExplicitArgumentList);
  2830. // Template argument deduction and the final substitution should be
  2831. // done in the context of the templated declaration. Explicit
  2832. // argument substitution, on the other hand, needs to happen in the
  2833. // calling context.
  2834. ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
  2835. // If we deduced template arguments for a template parameter pack,
  2836. // note that the template argument pack is partially substituted and record
  2837. // the explicit template arguments. They'll be used as part of deduction
  2838. // for this template parameter pack.
  2839. unsigned PartiallySubstitutedPackIndex = -1u;
  2840. if (!CanonicalBuilder.empty()) {
  2841. const TemplateArgument &Arg = CanonicalBuilder.back();
  2842. if (Arg.getKind() == TemplateArgument::Pack) {
  2843. auto *Param = TemplateParams->getParam(CanonicalBuilder.size() - 1);
  2844. // If this is a fully-saturated fixed-size pack, it should be
  2845. // fully-substituted, not partially-substituted.
  2846. std::optional<unsigned> Expansions = getExpandedPackSize(Param);
  2847. if (!Expansions || Arg.pack_size() < *Expansions) {
  2848. PartiallySubstitutedPackIndex = CanonicalBuilder.size() - 1;
  2849. CurrentInstantiationScope->SetPartiallySubstitutedPack(
  2850. Param, Arg.pack_begin(), Arg.pack_size());
  2851. }
  2852. }
  2853. }
  2854. const FunctionProtoType *Proto
  2855. = Function->getType()->getAs<FunctionProtoType>();
  2856. assert(Proto && "Function template does not have a prototype?");
  2857. // Isolate our substituted parameters from our caller.
  2858. LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
  2859. ExtParameterInfoBuilder ExtParamInfos;
  2860. MultiLevelTemplateArgumentList MLTAL(FunctionTemplate,
  2861. SugaredExplicitArgumentList->asArray(),
  2862. /*Final=*/true);
  2863. // Instantiate the types of each of the function parameters given the
  2864. // explicitly-specified template arguments. If the function has a trailing
  2865. // return type, substitute it after the arguments to ensure we substitute
  2866. // in lexical order.
  2867. if (Proto->hasTrailingReturn()) {
  2868. if (SubstParmTypes(Function->getLocation(), Function->parameters(),
  2869. Proto->getExtParameterInfosOrNull(), MLTAL, ParamTypes,
  2870. /*params=*/nullptr, ExtParamInfos))
  2871. return TDK_SubstitutionFailure;
  2872. }
  2873. // Instantiate the return type.
  2874. QualType ResultType;
  2875. {
  2876. // C++11 [expr.prim.general]p3:
  2877. // If a declaration declares a member function or member function
  2878. // template of a class X, the expression this is a prvalue of type
  2879. // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
  2880. // and the end of the function-definition, member-declarator, or
  2881. // declarator.
  2882. Qualifiers ThisTypeQuals;
  2883. CXXRecordDecl *ThisContext = nullptr;
  2884. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
  2885. ThisContext = Method->getParent();
  2886. ThisTypeQuals = Method->getMethodQualifiers();
  2887. }
  2888. CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
  2889. getLangOpts().CPlusPlus11);
  2890. ResultType =
  2891. SubstType(Proto->getReturnType(), MLTAL,
  2892. Function->getTypeSpecStartLoc(), Function->getDeclName());
  2893. if (ResultType.isNull() || Trap.hasErrorOccurred())
  2894. return TDK_SubstitutionFailure;
  2895. // CUDA: Kernel function must have 'void' return type.
  2896. if (getLangOpts().CUDA)
  2897. if (Function->hasAttr<CUDAGlobalAttr>() && !ResultType->isVoidType()) {
  2898. Diag(Function->getLocation(), diag::err_kern_type_not_void_return)
  2899. << Function->getType() << Function->getSourceRange();
  2900. return TDK_SubstitutionFailure;
  2901. }
  2902. }
  2903. // Instantiate the types of each of the function parameters given the
  2904. // explicitly-specified template arguments if we didn't do so earlier.
  2905. if (!Proto->hasTrailingReturn() &&
  2906. SubstParmTypes(Function->getLocation(), Function->parameters(),
  2907. Proto->getExtParameterInfosOrNull(), MLTAL, ParamTypes,
  2908. /*params*/ nullptr, ExtParamInfos))
  2909. return TDK_SubstitutionFailure;
  2910. if (FunctionType) {
  2911. auto EPI = Proto->getExtProtoInfo();
  2912. EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
  2913. // In C++1z onwards, exception specifications are part of the function type,
  2914. // so substitution into the type must also substitute into the exception
  2915. // specification.
  2916. SmallVector<QualType, 4> ExceptionStorage;
  2917. if (getLangOpts().CPlusPlus17 &&
  2918. SubstExceptionSpec(Function->getLocation(), EPI.ExceptionSpec,
  2919. ExceptionStorage, MLTAL))
  2920. return TDK_SubstitutionFailure;
  2921. *FunctionType = BuildFunctionType(ResultType, ParamTypes,
  2922. Function->getLocation(),
  2923. Function->getDeclName(),
  2924. EPI);
  2925. if (FunctionType->isNull() || Trap.hasErrorOccurred())
  2926. return TDK_SubstitutionFailure;
  2927. }
  2928. // C++ [temp.arg.explicit]p2:
  2929. // Trailing template arguments that can be deduced (14.8.2) may be
  2930. // omitted from the list of explicit template-arguments. If all of the
  2931. // template arguments can be deduced, they may all be omitted; in this
  2932. // case, the empty template argument list <> itself may also be omitted.
  2933. //
  2934. // Take all of the explicitly-specified arguments and put them into
  2935. // the set of deduced template arguments. The partially-substituted
  2936. // parameter pack, however, will be set to NULL since the deduction
  2937. // mechanism handles the partially-substituted argument pack directly.
  2938. Deduced.reserve(TemplateParams->size());
  2939. for (unsigned I = 0, N = SugaredExplicitArgumentList->size(); I != N; ++I) {
  2940. const TemplateArgument &Arg = SugaredExplicitArgumentList->get(I);
  2941. if (I == PartiallySubstitutedPackIndex)
  2942. Deduced.push_back(DeducedTemplateArgument());
  2943. else
  2944. Deduced.push_back(Arg);
  2945. }
  2946. return TDK_Success;
  2947. }
  2948. /// Check whether the deduced argument type for a call to a function
  2949. /// template matches the actual argument type per C++ [temp.deduct.call]p4.
  2950. static Sema::TemplateDeductionResult
  2951. CheckOriginalCallArgDeduction(Sema &S, TemplateDeductionInfo &Info,
  2952. Sema::OriginalCallArg OriginalArg,
  2953. QualType DeducedA) {
  2954. ASTContext &Context = S.Context;
  2955. auto Failed = [&]() -> Sema::TemplateDeductionResult {
  2956. Info.FirstArg = TemplateArgument(DeducedA);
  2957. Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
  2958. Info.CallArgIndex = OriginalArg.ArgIdx;
  2959. return OriginalArg.DecomposedParam ? Sema::TDK_DeducedMismatchNested
  2960. : Sema::TDK_DeducedMismatch;
  2961. };
  2962. QualType A = OriginalArg.OriginalArgType;
  2963. QualType OriginalParamType = OriginalArg.OriginalParamType;
  2964. // Check for type equality (top-level cv-qualifiers are ignored).
  2965. if (Context.hasSameUnqualifiedType(A, DeducedA))
  2966. return Sema::TDK_Success;
  2967. // Strip off references on the argument types; they aren't needed for
  2968. // the following checks.
  2969. if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
  2970. DeducedA = DeducedARef->getPointeeType();
  2971. if (const ReferenceType *ARef = A->getAs<ReferenceType>())
  2972. A = ARef->getPointeeType();
  2973. // C++ [temp.deduct.call]p4:
  2974. // [...] However, there are three cases that allow a difference:
  2975. // - If the original P is a reference type, the deduced A (i.e., the
  2976. // type referred to by the reference) can be more cv-qualified than
  2977. // the transformed A.
  2978. if (const ReferenceType *OriginalParamRef
  2979. = OriginalParamType->getAs<ReferenceType>()) {
  2980. // We don't want to keep the reference around any more.
  2981. OriginalParamType = OriginalParamRef->getPointeeType();
  2982. // FIXME: Resolve core issue (no number yet): if the original P is a
  2983. // reference type and the transformed A is function type "noexcept F",
  2984. // the deduced A can be F.
  2985. QualType Tmp;
  2986. if (A->isFunctionType() && S.IsFunctionConversion(A, DeducedA, Tmp))
  2987. return Sema::TDK_Success;
  2988. Qualifiers AQuals = A.getQualifiers();
  2989. Qualifiers DeducedAQuals = DeducedA.getQualifiers();
  2990. // Under Objective-C++ ARC, the deduced type may have implicitly
  2991. // been given strong or (when dealing with a const reference)
  2992. // unsafe_unretained lifetime. If so, update the original
  2993. // qualifiers to include this lifetime.
  2994. if (S.getLangOpts().ObjCAutoRefCount &&
  2995. ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
  2996. AQuals.getObjCLifetime() == Qualifiers::OCL_None) ||
  2997. (DeducedAQuals.hasConst() &&
  2998. DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
  2999. AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
  3000. }
  3001. if (AQuals == DeducedAQuals) {
  3002. // Qualifiers match; there's nothing to do.
  3003. } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
  3004. return Failed();
  3005. } else {
  3006. // Qualifiers are compatible, so have the argument type adopt the
  3007. // deduced argument type's qualifiers as if we had performed the
  3008. // qualification conversion.
  3009. A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
  3010. }
  3011. }
  3012. // - The transformed A can be another pointer or pointer to member
  3013. // type that can be converted to the deduced A via a function pointer
  3014. // conversion and/or a qualification conversion.
  3015. //
  3016. // Also allow conversions which merely strip __attribute__((noreturn)) from
  3017. // function types (recursively).
  3018. bool ObjCLifetimeConversion = false;
  3019. QualType ResultTy;
  3020. if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
  3021. (S.IsQualificationConversion(A, DeducedA, false,
  3022. ObjCLifetimeConversion) ||
  3023. S.IsFunctionConversion(A, DeducedA, ResultTy)))
  3024. return Sema::TDK_Success;
  3025. // - If P is a class and P has the form simple-template-id, then the
  3026. // transformed A can be a derived class of the deduced A. [...]
  3027. // [...] Likewise, if P is a pointer to a class of the form
  3028. // simple-template-id, the transformed A can be a pointer to a
  3029. // derived class pointed to by the deduced A.
  3030. if (const PointerType *OriginalParamPtr
  3031. = OriginalParamType->getAs<PointerType>()) {
  3032. if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
  3033. if (const PointerType *APtr = A->getAs<PointerType>()) {
  3034. if (A->getPointeeType()->isRecordType()) {
  3035. OriginalParamType = OriginalParamPtr->getPointeeType();
  3036. DeducedA = DeducedAPtr->getPointeeType();
  3037. A = APtr->getPointeeType();
  3038. }
  3039. }
  3040. }
  3041. }
  3042. if (Context.hasSameUnqualifiedType(A, DeducedA))
  3043. return Sema::TDK_Success;
  3044. if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
  3045. S.IsDerivedFrom(Info.getLocation(), A, DeducedA))
  3046. return Sema::TDK_Success;
  3047. return Failed();
  3048. }
  3049. /// Find the pack index for a particular parameter index in an instantiation of
  3050. /// a function template with specific arguments.
  3051. ///
  3052. /// \return The pack index for whichever pack produced this parameter, or -1
  3053. /// if this was not produced by a parameter. Intended to be used as the
  3054. /// ArgumentPackSubstitutionIndex for further substitutions.
  3055. // FIXME: We should track this in OriginalCallArgs so we don't need to
  3056. // reconstruct it here.
  3057. static unsigned getPackIndexForParam(Sema &S,
  3058. FunctionTemplateDecl *FunctionTemplate,
  3059. const MultiLevelTemplateArgumentList &Args,
  3060. unsigned ParamIdx) {
  3061. unsigned Idx = 0;
  3062. for (auto *PD : FunctionTemplate->getTemplatedDecl()->parameters()) {
  3063. if (PD->isParameterPack()) {
  3064. unsigned NumExpansions =
  3065. S.getNumArgumentsInExpansion(PD->getType(), Args).value_or(1);
  3066. if (Idx + NumExpansions > ParamIdx)
  3067. return ParamIdx - Idx;
  3068. Idx += NumExpansions;
  3069. } else {
  3070. if (Idx == ParamIdx)
  3071. return -1; // Not a pack expansion
  3072. ++Idx;
  3073. }
  3074. }
  3075. llvm_unreachable("parameter index would not be produced from template");
  3076. }
  3077. /// Finish template argument deduction for a function template,
  3078. /// checking the deduced template arguments for completeness and forming
  3079. /// the function template specialization.
  3080. ///
  3081. /// \param OriginalCallArgs If non-NULL, the original call arguments against
  3082. /// which the deduced argument types should be compared.
  3083. Sema::TemplateDeductionResult Sema::FinishTemplateArgumentDeduction(
  3084. FunctionTemplateDecl *FunctionTemplate,
  3085. SmallVectorImpl<DeducedTemplateArgument> &Deduced,
  3086. unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
  3087. TemplateDeductionInfo &Info,
  3088. SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
  3089. bool PartialOverloading, llvm::function_ref<bool()> CheckNonDependent) {
  3090. // Unevaluated SFINAE context.
  3091. EnterExpressionEvaluationContext Unevaluated(
  3092. *this, Sema::ExpressionEvaluationContext::Unevaluated);
  3093. SFINAETrap Trap(*this);
  3094. // Enter a new template instantiation context while we instantiate the
  3095. // actual function declaration.
  3096. SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
  3097. InstantiatingTemplate Inst(
  3098. *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
  3099. CodeSynthesisContext::DeducedTemplateArgumentSubstitution, Info);
  3100. if (Inst.isInvalid())
  3101. return TDK_InstantiationDepth;
  3102. ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
  3103. // C++ [temp.deduct.type]p2:
  3104. // [...] or if any template argument remains neither deduced nor
  3105. // explicitly specified, template argument deduction fails.
  3106. SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
  3107. if (auto Result = ConvertDeducedTemplateArguments(
  3108. *this, FunctionTemplate, /*IsDeduced*/ true, Deduced, Info,
  3109. SugaredBuilder, CanonicalBuilder, CurrentInstantiationScope,
  3110. NumExplicitlySpecified, PartialOverloading))
  3111. return Result;
  3112. // C++ [temp.deduct.call]p10: [DR1391]
  3113. // If deduction succeeds for all parameters that contain
  3114. // template-parameters that participate in template argument deduction,
  3115. // and all template arguments are explicitly specified, deduced, or
  3116. // obtained from default template arguments, remaining parameters are then
  3117. // compared with the corresponding arguments. For each remaining parameter
  3118. // P with a type that was non-dependent before substitution of any
  3119. // explicitly-specified template arguments, if the corresponding argument
  3120. // A cannot be implicitly converted to P, deduction fails.
  3121. if (CheckNonDependent())
  3122. return TDK_NonDependentConversionFailure;
  3123. // Form the template argument list from the deduced template arguments.
  3124. TemplateArgumentList *SugaredDeducedArgumentList =
  3125. TemplateArgumentList::CreateCopy(Context, SugaredBuilder);
  3126. TemplateArgumentList *CanonicalDeducedArgumentList =
  3127. TemplateArgumentList::CreateCopy(Context, CanonicalBuilder);
  3128. Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
  3129. // Substitute the deduced template arguments into the function template
  3130. // declaration to produce the function template specialization.
  3131. DeclContext *Owner = FunctionTemplate->getDeclContext();
  3132. if (FunctionTemplate->getFriendObjectKind())
  3133. Owner = FunctionTemplate->getLexicalDeclContext();
  3134. MultiLevelTemplateArgumentList SubstArgs(
  3135. FunctionTemplate, CanonicalDeducedArgumentList->asArray(),
  3136. /*Final=*/false);
  3137. Specialization = cast_or_null<FunctionDecl>(
  3138. SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner, SubstArgs));
  3139. if (!Specialization || Specialization->isInvalidDecl())
  3140. return TDK_SubstitutionFailure;
  3141. assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
  3142. FunctionTemplate->getCanonicalDecl());
  3143. // If the template argument list is owned by the function template
  3144. // specialization, release it.
  3145. if (Specialization->getTemplateSpecializationArgs() ==
  3146. CanonicalDeducedArgumentList &&
  3147. !Trap.hasErrorOccurred())
  3148. Info.takeCanonical();
  3149. // There may have been an error that did not prevent us from constructing a
  3150. // declaration. Mark the declaration invalid and return with a substitution
  3151. // failure.
  3152. if (Trap.hasErrorOccurred()) {
  3153. Specialization->setInvalidDecl(true);
  3154. return TDK_SubstitutionFailure;
  3155. }
  3156. // C++2a [temp.deduct]p5
  3157. // [...] When all template arguments have been deduced [...] all uses of
  3158. // template parameters [...] are replaced with the corresponding deduced
  3159. // or default argument values.
  3160. // [...] If the function template has associated constraints
  3161. // ([temp.constr.decl]), those constraints are checked for satisfaction
  3162. // ([temp.constr.constr]). If the constraints are not satisfied, type
  3163. // deduction fails.
  3164. if (!PartialOverloading ||
  3165. (CanonicalBuilder.size() ==
  3166. FunctionTemplate->getTemplateParameters()->size())) {
  3167. if (CheckInstantiatedFunctionTemplateConstraints(
  3168. Info.getLocation(), Specialization, CanonicalBuilder,
  3169. Info.AssociatedConstraintsSatisfaction))
  3170. return TDK_MiscellaneousDeductionFailure;
  3171. if (!Info.AssociatedConstraintsSatisfaction.IsSatisfied) {
  3172. Info.reset(Info.takeSugared(),
  3173. TemplateArgumentList::CreateCopy(Context, CanonicalBuilder));
  3174. return TDK_ConstraintsNotSatisfied;
  3175. }
  3176. }
  3177. if (OriginalCallArgs) {
  3178. // C++ [temp.deduct.call]p4:
  3179. // In general, the deduction process attempts to find template argument
  3180. // values that will make the deduced A identical to A (after the type A
  3181. // is transformed as described above). [...]
  3182. llvm::SmallDenseMap<std::pair<unsigned, QualType>, QualType> DeducedATypes;
  3183. for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
  3184. OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
  3185. auto ParamIdx = OriginalArg.ArgIdx;
  3186. if (ParamIdx >= Specialization->getNumParams())
  3187. // FIXME: This presumably means a pack ended up smaller than we
  3188. // expected while deducing. Should this not result in deduction
  3189. // failure? Can it even happen?
  3190. continue;
  3191. QualType DeducedA;
  3192. if (!OriginalArg.DecomposedParam) {
  3193. // P is one of the function parameters, just look up its substituted
  3194. // type.
  3195. DeducedA = Specialization->getParamDecl(ParamIdx)->getType();
  3196. } else {
  3197. // P is a decomposed element of a parameter corresponding to a
  3198. // braced-init-list argument. Substitute back into P to find the
  3199. // deduced A.
  3200. QualType &CacheEntry =
  3201. DeducedATypes[{ParamIdx, OriginalArg.OriginalParamType}];
  3202. if (CacheEntry.isNull()) {
  3203. ArgumentPackSubstitutionIndexRAII PackIndex(
  3204. *this, getPackIndexForParam(*this, FunctionTemplate, SubstArgs,
  3205. ParamIdx));
  3206. CacheEntry =
  3207. SubstType(OriginalArg.OriginalParamType, SubstArgs,
  3208. Specialization->getTypeSpecStartLoc(),
  3209. Specialization->getDeclName());
  3210. }
  3211. DeducedA = CacheEntry;
  3212. }
  3213. if (auto TDK =
  3214. CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA))
  3215. return TDK;
  3216. }
  3217. }
  3218. // If we suppressed any diagnostics while performing template argument
  3219. // deduction, and if we haven't already instantiated this declaration,
  3220. // keep track of these diagnostics. They'll be emitted if this specialization
  3221. // is actually used.
  3222. if (Info.diag_begin() != Info.diag_end()) {
  3223. SuppressedDiagnosticsMap::iterator
  3224. Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
  3225. if (Pos == SuppressedDiagnostics.end())
  3226. SuppressedDiagnostics[Specialization->getCanonicalDecl()]
  3227. .append(Info.diag_begin(), Info.diag_end());
  3228. }
  3229. return TDK_Success;
  3230. }
  3231. /// Gets the type of a function for template-argument-deducton
  3232. /// purposes when it's considered as part of an overload set.
  3233. static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R,
  3234. FunctionDecl *Fn) {
  3235. // We may need to deduce the return type of the function now.
  3236. if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
  3237. S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
  3238. return {};
  3239. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
  3240. if (Method->isInstance()) {
  3241. // An instance method that's referenced in a form that doesn't
  3242. // look like a member pointer is just invalid.
  3243. if (!R.HasFormOfMemberPointer)
  3244. return {};
  3245. return S.Context.getMemberPointerType(Fn->getType(),
  3246. S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
  3247. }
  3248. if (!R.IsAddressOfOperand) return Fn->getType();
  3249. return S.Context.getPointerType(Fn->getType());
  3250. }
  3251. /// Apply the deduction rules for overload sets.
  3252. ///
  3253. /// \return the null type if this argument should be treated as an
  3254. /// undeduced context
  3255. static QualType
  3256. ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
  3257. Expr *Arg, QualType ParamType,
  3258. bool ParamWasReference) {
  3259. OverloadExpr::FindResult R = OverloadExpr::find(Arg);
  3260. OverloadExpr *Ovl = R.Expression;
  3261. // C++0x [temp.deduct.call]p4
  3262. unsigned TDF = 0;
  3263. if (ParamWasReference)
  3264. TDF |= TDF_ParamWithReferenceType;
  3265. if (R.IsAddressOfOperand)
  3266. TDF |= TDF_IgnoreQualifiers;
  3267. // C++0x [temp.deduct.call]p6:
  3268. // When P is a function type, pointer to function type, or pointer
  3269. // to member function type:
  3270. if (!ParamType->isFunctionType() &&
  3271. !ParamType->isFunctionPointerType() &&
  3272. !ParamType->isMemberFunctionPointerType()) {
  3273. if (Ovl->hasExplicitTemplateArgs()) {
  3274. // But we can still look for an explicit specialization.
  3275. if (FunctionDecl *ExplicitSpec
  3276. = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
  3277. return GetTypeOfFunction(S, R, ExplicitSpec);
  3278. }
  3279. DeclAccessPair DAP;
  3280. if (FunctionDecl *Viable =
  3281. S.resolveAddressOfSingleOverloadCandidate(Arg, DAP))
  3282. return GetTypeOfFunction(S, R, Viable);
  3283. return {};
  3284. }
  3285. // Gather the explicit template arguments, if any.
  3286. TemplateArgumentListInfo ExplicitTemplateArgs;
  3287. if (Ovl->hasExplicitTemplateArgs())
  3288. Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
  3289. QualType Match;
  3290. for (UnresolvedSetIterator I = Ovl->decls_begin(),
  3291. E = Ovl->decls_end(); I != E; ++I) {
  3292. NamedDecl *D = (*I)->getUnderlyingDecl();
  3293. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
  3294. // - If the argument is an overload set containing one or more
  3295. // function templates, the parameter is treated as a
  3296. // non-deduced context.
  3297. if (!Ovl->hasExplicitTemplateArgs())
  3298. return {};
  3299. // Otherwise, see if we can resolve a function type
  3300. FunctionDecl *Specialization = nullptr;
  3301. TemplateDeductionInfo Info(Ovl->getNameLoc());
  3302. if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
  3303. Specialization, Info))
  3304. continue;
  3305. D = Specialization;
  3306. }
  3307. FunctionDecl *Fn = cast<FunctionDecl>(D);
  3308. QualType ArgType = GetTypeOfFunction(S, R, Fn);
  3309. if (ArgType.isNull()) continue;
  3310. // Function-to-pointer conversion.
  3311. if (!ParamWasReference && ParamType->isPointerType() &&
  3312. ArgType->isFunctionType())
  3313. ArgType = S.Context.getPointerType(ArgType);
  3314. // - If the argument is an overload set (not containing function
  3315. // templates), trial argument deduction is attempted using each
  3316. // of the members of the set. If deduction succeeds for only one
  3317. // of the overload set members, that member is used as the
  3318. // argument value for the deduction. If deduction succeeds for
  3319. // more than one member of the overload set the parameter is
  3320. // treated as a non-deduced context.
  3321. // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
  3322. // Type deduction is done independently for each P/A pair, and
  3323. // the deduced template argument values are then combined.
  3324. // So we do not reject deductions which were made elsewhere.
  3325. SmallVector<DeducedTemplateArgument, 8>
  3326. Deduced(TemplateParams->size());
  3327. TemplateDeductionInfo Info(Ovl->getNameLoc());
  3328. Sema::TemplateDeductionResult Result
  3329. = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
  3330. ArgType, Info, Deduced, TDF);
  3331. if (Result) continue;
  3332. if (!Match.isNull())
  3333. return {};
  3334. Match = ArgType;
  3335. }
  3336. return Match;
  3337. }
  3338. /// Perform the adjustments to the parameter and argument types
  3339. /// described in C++ [temp.deduct.call].
  3340. ///
  3341. /// \returns true if the caller should not attempt to perform any template
  3342. /// argument deduction based on this P/A pair because the argument is an
  3343. /// overloaded function set that could not be resolved.
  3344. static bool AdjustFunctionParmAndArgTypesForDeduction(
  3345. Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
  3346. QualType &ParamType, QualType &ArgType, Expr *Arg, unsigned &TDF) {
  3347. // C++0x [temp.deduct.call]p3:
  3348. // If P is a cv-qualified type, the top level cv-qualifiers of P's type
  3349. // are ignored for type deduction.
  3350. if (ParamType.hasQualifiers())
  3351. ParamType = ParamType.getUnqualifiedType();
  3352. // [...] If P is a reference type, the type referred to by P is
  3353. // used for type deduction.
  3354. const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
  3355. if (ParamRefType)
  3356. ParamType = ParamRefType->getPointeeType();
  3357. // Overload sets usually make this parameter an undeduced context,
  3358. // but there are sometimes special circumstances. Typically
  3359. // involving a template-id-expr.
  3360. if (ArgType == S.Context.OverloadTy) {
  3361. ArgType = ResolveOverloadForDeduction(S, TemplateParams,
  3362. Arg, ParamType,
  3363. ParamRefType != nullptr);
  3364. if (ArgType.isNull())
  3365. return true;
  3366. }
  3367. if (ParamRefType) {
  3368. // If the argument has incomplete array type, try to complete its type.
  3369. if (ArgType->isIncompleteArrayType())
  3370. ArgType = S.getCompletedType(Arg);
  3371. // C++1z [temp.deduct.call]p3:
  3372. // If P is a forwarding reference and the argument is an lvalue, the type
  3373. // "lvalue reference to A" is used in place of A for type deduction.
  3374. if (isForwardingReference(QualType(ParamRefType, 0), FirstInnerIndex) &&
  3375. Arg->isLValue()) {
  3376. if (S.getLangOpts().OpenCL && !ArgType.hasAddressSpace())
  3377. ArgType = S.Context.getAddrSpaceQualType(
  3378. ArgType, S.Context.getDefaultOpenCLPointeeAddrSpace());
  3379. ArgType = S.Context.getLValueReferenceType(ArgType);
  3380. }
  3381. } else {
  3382. // C++ [temp.deduct.call]p2:
  3383. // If P is not a reference type:
  3384. // - If A is an array type, the pointer type produced by the
  3385. // array-to-pointer standard conversion (4.2) is used in place of
  3386. // A for type deduction; otherwise,
  3387. // - If A is a function type, the pointer type produced by the
  3388. // function-to-pointer standard conversion (4.3) is used in place
  3389. // of A for type deduction; otherwise,
  3390. if (ArgType->canDecayToPointerType())
  3391. ArgType = S.Context.getDecayedType(ArgType);
  3392. else {
  3393. // - If A is a cv-qualified type, the top level cv-qualifiers of A's
  3394. // type are ignored for type deduction.
  3395. ArgType = ArgType.getUnqualifiedType();
  3396. }
  3397. }
  3398. // C++0x [temp.deduct.call]p4:
  3399. // In general, the deduction process attempts to find template argument
  3400. // values that will make the deduced A identical to A (after the type A
  3401. // is transformed as described above). [...]
  3402. TDF = TDF_SkipNonDependent;
  3403. // - If the original P is a reference type, the deduced A (i.e., the
  3404. // type referred to by the reference) can be more cv-qualified than
  3405. // the transformed A.
  3406. if (ParamRefType)
  3407. TDF |= TDF_ParamWithReferenceType;
  3408. // - The transformed A can be another pointer or pointer to member
  3409. // type that can be converted to the deduced A via a qualification
  3410. // conversion (4.4).
  3411. if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
  3412. ArgType->isObjCObjectPointerType())
  3413. TDF |= TDF_IgnoreQualifiers;
  3414. // - If P is a class and P has the form simple-template-id, then the
  3415. // transformed A can be a derived class of the deduced A. Likewise,
  3416. // if P is a pointer to a class of the form simple-template-id, the
  3417. // transformed A can be a pointer to a derived class pointed to by
  3418. // the deduced A.
  3419. if (isSimpleTemplateIdType(ParamType) ||
  3420. (isa<PointerType>(ParamType) &&
  3421. isSimpleTemplateIdType(
  3422. ParamType->castAs<PointerType>()->getPointeeType())))
  3423. TDF |= TDF_DerivedClass;
  3424. return false;
  3425. }
  3426. static bool
  3427. hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate,
  3428. QualType T);
  3429. static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
  3430. Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
  3431. QualType ParamType, Expr *Arg, TemplateDeductionInfo &Info,
  3432. SmallVectorImpl<DeducedTemplateArgument> &Deduced,
  3433. SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs,
  3434. bool DecomposedParam, unsigned ArgIdx, unsigned TDF);
  3435. /// Attempt template argument deduction from an initializer list
  3436. /// deemed to be an argument in a function call.
  3437. static Sema::TemplateDeductionResult DeduceFromInitializerList(
  3438. Sema &S, TemplateParameterList *TemplateParams, QualType AdjustedParamType,
  3439. InitListExpr *ILE, TemplateDeductionInfo &Info,
  3440. SmallVectorImpl<DeducedTemplateArgument> &Deduced,
  3441. SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs, unsigned ArgIdx,
  3442. unsigned TDF) {
  3443. // C++ [temp.deduct.call]p1: (CWG 1591)
  3444. // If removing references and cv-qualifiers from P gives
  3445. // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is
  3446. // a non-empty initializer list, then deduction is performed instead for
  3447. // each element of the initializer list, taking P0 as a function template
  3448. // parameter type and the initializer element as its argument
  3449. //
  3450. // We've already removed references and cv-qualifiers here.
  3451. if (!ILE->getNumInits())
  3452. return Sema::TDK_Success;
  3453. QualType ElTy;
  3454. auto *ArrTy = S.Context.getAsArrayType(AdjustedParamType);
  3455. if (ArrTy)
  3456. ElTy = ArrTy->getElementType();
  3457. else if (!S.isStdInitializerList(AdjustedParamType, &ElTy)) {
  3458. // Otherwise, an initializer list argument causes the parameter to be
  3459. // considered a non-deduced context
  3460. return Sema::TDK_Success;
  3461. }
  3462. // Resolving a core issue: a braced-init-list containing any designators is
  3463. // a non-deduced context.
  3464. for (Expr *E : ILE->inits())
  3465. if (isa<DesignatedInitExpr>(E))
  3466. return Sema::TDK_Success;
  3467. // Deduction only needs to be done for dependent types.
  3468. if (ElTy->isDependentType()) {
  3469. for (Expr *E : ILE->inits()) {
  3470. if (auto Result = DeduceTemplateArgumentsFromCallArgument(
  3471. S, TemplateParams, 0, ElTy, E, Info, Deduced, OriginalCallArgs, true,
  3472. ArgIdx, TDF))
  3473. return Result;
  3474. }
  3475. }
  3476. // in the P0[N] case, if N is a non-type template parameter, N is deduced
  3477. // from the length of the initializer list.
  3478. if (auto *DependentArrTy = dyn_cast_or_null<DependentSizedArrayType>(ArrTy)) {
  3479. // Determine the array bound is something we can deduce.
  3480. if (const NonTypeTemplateParmDecl *NTTP =
  3481. getDeducedParameterFromExpr(Info, DependentArrTy->getSizeExpr())) {
  3482. // We can perform template argument deduction for the given non-type
  3483. // template parameter.
  3484. // C++ [temp.deduct.type]p13:
  3485. // The type of N in the type T[N] is std::size_t.
  3486. QualType T = S.Context.getSizeType();
  3487. llvm::APInt Size(S.Context.getIntWidth(T), ILE->getNumInits());
  3488. if (auto Result = DeduceNonTypeTemplateArgument(
  3489. S, TemplateParams, NTTP, llvm::APSInt(Size), T,
  3490. /*ArrayBound=*/true, Info, Deduced))
  3491. return Result;
  3492. }
  3493. }
  3494. return Sema::TDK_Success;
  3495. }
  3496. /// Perform template argument deduction per [temp.deduct.call] for a
  3497. /// single parameter / argument pair.
  3498. static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
  3499. Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
  3500. QualType ParamType, Expr *Arg, TemplateDeductionInfo &Info,
  3501. SmallVectorImpl<DeducedTemplateArgument> &Deduced,
  3502. SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs,
  3503. bool DecomposedParam, unsigned ArgIdx, unsigned TDF) {
  3504. QualType ArgType = Arg->getType();
  3505. QualType OrigParamType = ParamType;
  3506. // If P is a reference type [...]
  3507. // If P is a cv-qualified type [...]
  3508. if (AdjustFunctionParmAndArgTypesForDeduction(
  3509. S, TemplateParams, FirstInnerIndex, ParamType, ArgType, Arg, TDF))
  3510. return Sema::TDK_Success;
  3511. // If [...] the argument is a non-empty initializer list [...]
  3512. if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg))
  3513. return DeduceFromInitializerList(S, TemplateParams, ParamType, ILE, Info,
  3514. Deduced, OriginalCallArgs, ArgIdx, TDF);
  3515. // [...] the deduction process attempts to find template argument values
  3516. // that will make the deduced A identical to A
  3517. //
  3518. // Keep track of the argument type and corresponding parameter index,
  3519. // so we can check for compatibility between the deduced A and A.
  3520. OriginalCallArgs.push_back(
  3521. Sema::OriginalCallArg(OrigParamType, DecomposedParam, ArgIdx, ArgType));
  3522. return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
  3523. ArgType, Info, Deduced, TDF);
  3524. }
  3525. /// Perform template argument deduction from a function call
  3526. /// (C++ [temp.deduct.call]).
  3527. ///
  3528. /// \param FunctionTemplate the function template for which we are performing
  3529. /// template argument deduction.
  3530. ///
  3531. /// \param ExplicitTemplateArgs the explicit template arguments provided
  3532. /// for this call.
  3533. ///
  3534. /// \param Args the function call arguments
  3535. ///
  3536. /// \param Specialization if template argument deduction was successful,
  3537. /// this will be set to the function template specialization produced by
  3538. /// template argument deduction.
  3539. ///
  3540. /// \param Info the argument will be updated to provide additional information
  3541. /// about template argument deduction.
  3542. ///
  3543. /// \param CheckNonDependent A callback to invoke to check conversions for
  3544. /// non-dependent parameters, between deduction and substitution, per DR1391.
  3545. /// If this returns true, substitution will be skipped and we return
  3546. /// TDK_NonDependentConversionFailure. The callback is passed the parameter
  3547. /// types (after substituting explicit template arguments).
  3548. ///
  3549. /// \returns the result of template argument deduction.
  3550. Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
  3551. FunctionTemplateDecl *FunctionTemplate,
  3552. TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
  3553. FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
  3554. bool PartialOverloading,
  3555. llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent) {
  3556. if (FunctionTemplate->isInvalidDecl())
  3557. return TDK_Invalid;
  3558. FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
  3559. unsigned NumParams = Function->getNumParams();
  3560. unsigned FirstInnerIndex = getFirstInnerIndex(FunctionTemplate);
  3561. // C++ [temp.deduct.call]p1:
  3562. // Template argument deduction is done by comparing each function template
  3563. // parameter type (call it P) with the type of the corresponding argument
  3564. // of the call (call it A) as described below.
  3565. if (Args.size() < Function->getMinRequiredArguments() && !PartialOverloading)
  3566. return TDK_TooFewArguments;
  3567. else if (TooManyArguments(NumParams, Args.size(), PartialOverloading)) {
  3568. const auto *Proto = Function->getType()->castAs<FunctionProtoType>();
  3569. if (Proto->isTemplateVariadic())
  3570. /* Do nothing */;
  3571. else if (!Proto->isVariadic())
  3572. return TDK_TooManyArguments;
  3573. }
  3574. // The types of the parameters from which we will perform template argument
  3575. // deduction.
  3576. LocalInstantiationScope InstScope(*this);
  3577. TemplateParameterList *TemplateParams
  3578. = FunctionTemplate->getTemplateParameters();
  3579. SmallVector<DeducedTemplateArgument, 4> Deduced;
  3580. SmallVector<QualType, 8> ParamTypes;
  3581. unsigned NumExplicitlySpecified = 0;
  3582. if (ExplicitTemplateArgs) {
  3583. TemplateDeductionResult Result;
  3584. runWithSufficientStackSpace(Info.getLocation(), [&] {
  3585. Result = SubstituteExplicitTemplateArguments(
  3586. FunctionTemplate, *ExplicitTemplateArgs, Deduced, ParamTypes, nullptr,
  3587. Info);
  3588. });
  3589. if (Result)
  3590. return Result;
  3591. NumExplicitlySpecified = Deduced.size();
  3592. } else {
  3593. // Just fill in the parameter types from the function declaration.
  3594. for (unsigned I = 0; I != NumParams; ++I)
  3595. ParamTypes.push_back(Function->getParamDecl(I)->getType());
  3596. }
  3597. SmallVector<OriginalCallArg, 8> OriginalCallArgs;
  3598. // Deduce an argument of type ParamType from an expression with index ArgIdx.
  3599. auto DeduceCallArgument = [&](QualType ParamType, unsigned ArgIdx) {
  3600. // C++ [demp.deduct.call]p1: (DR1391)
  3601. // Template argument deduction is done by comparing each function template
  3602. // parameter that contains template-parameters that participate in
  3603. // template argument deduction ...
  3604. if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
  3605. return Sema::TDK_Success;
  3606. // ... with the type of the corresponding argument
  3607. return DeduceTemplateArgumentsFromCallArgument(
  3608. *this, TemplateParams, FirstInnerIndex, ParamType, Args[ArgIdx], Info, Deduced,
  3609. OriginalCallArgs, /*Decomposed*/false, ArgIdx, /*TDF*/ 0);
  3610. };
  3611. // Deduce template arguments from the function parameters.
  3612. Deduced.resize(TemplateParams->size());
  3613. SmallVector<QualType, 8> ParamTypesForArgChecking;
  3614. for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size(), ArgIdx = 0;
  3615. ParamIdx != NumParamTypes; ++ParamIdx) {
  3616. QualType ParamType = ParamTypes[ParamIdx];
  3617. const PackExpansionType *ParamExpansion =
  3618. dyn_cast<PackExpansionType>(ParamType);
  3619. if (!ParamExpansion) {
  3620. // Simple case: matching a function parameter to a function argument.
  3621. if (ArgIdx >= Args.size())
  3622. break;
  3623. ParamTypesForArgChecking.push_back(ParamType);
  3624. if (auto Result = DeduceCallArgument(ParamType, ArgIdx++))
  3625. return Result;
  3626. continue;
  3627. }
  3628. QualType ParamPattern = ParamExpansion->getPattern();
  3629. PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
  3630. ParamPattern);
  3631. // C++0x [temp.deduct.call]p1:
  3632. // For a function parameter pack that occurs at the end of the
  3633. // parameter-declaration-list, the type A of each remaining argument of
  3634. // the call is compared with the type P of the declarator-id of the
  3635. // function parameter pack. Each comparison deduces template arguments
  3636. // for subsequent positions in the template parameter packs expanded by
  3637. // the function parameter pack. When a function parameter pack appears
  3638. // in a non-deduced context [not at the end of the list], the type of
  3639. // that parameter pack is never deduced.
  3640. //
  3641. // FIXME: The above rule allows the size of the parameter pack to change
  3642. // after we skip it (in the non-deduced case). That makes no sense, so
  3643. // we instead notionally deduce the pack against N arguments, where N is
  3644. // the length of the explicitly-specified pack if it's expanded by the
  3645. // parameter pack and 0 otherwise, and we treat each deduction as a
  3646. // non-deduced context.
  3647. if (ParamIdx + 1 == NumParamTypes || PackScope.hasFixedArity()) {
  3648. for (; ArgIdx < Args.size() && PackScope.hasNextElement();
  3649. PackScope.nextPackElement(), ++ArgIdx) {
  3650. ParamTypesForArgChecking.push_back(ParamPattern);
  3651. if (auto Result = DeduceCallArgument(ParamPattern, ArgIdx))
  3652. return Result;
  3653. }
  3654. } else {
  3655. // If the parameter type contains an explicitly-specified pack that we
  3656. // could not expand, skip the number of parameters notionally created
  3657. // by the expansion.
  3658. std::optional<unsigned> NumExpansions =
  3659. ParamExpansion->getNumExpansions();
  3660. if (NumExpansions && !PackScope.isPartiallyExpanded()) {
  3661. for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size();
  3662. ++I, ++ArgIdx) {
  3663. ParamTypesForArgChecking.push_back(ParamPattern);
  3664. // FIXME: Should we add OriginalCallArgs for these? What if the
  3665. // corresponding argument is a list?
  3666. PackScope.nextPackElement();
  3667. }
  3668. }
  3669. }
  3670. // Build argument packs for each of the parameter packs expanded by this
  3671. // pack expansion.
  3672. if (auto Result = PackScope.finish())
  3673. return Result;
  3674. }
  3675. // Capture the context in which the function call is made. This is the context
  3676. // that is needed when the accessibility of template arguments is checked.
  3677. DeclContext *CallingCtx = CurContext;
  3678. TemplateDeductionResult Result;
  3679. runWithSufficientStackSpace(Info.getLocation(), [&] {
  3680. Result = FinishTemplateArgumentDeduction(
  3681. FunctionTemplate, Deduced, NumExplicitlySpecified, Specialization, Info,
  3682. &OriginalCallArgs, PartialOverloading, [&, CallingCtx]() {
  3683. ContextRAII SavedContext(*this, CallingCtx);
  3684. return CheckNonDependent(ParamTypesForArgChecking);
  3685. });
  3686. });
  3687. return Result;
  3688. }
  3689. QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType,
  3690. QualType FunctionType,
  3691. bool AdjustExceptionSpec) {
  3692. if (ArgFunctionType.isNull())
  3693. return ArgFunctionType;
  3694. const auto *FunctionTypeP = FunctionType->castAs<FunctionProtoType>();
  3695. const auto *ArgFunctionTypeP = ArgFunctionType->castAs<FunctionProtoType>();
  3696. FunctionProtoType::ExtProtoInfo EPI = ArgFunctionTypeP->getExtProtoInfo();
  3697. bool Rebuild = false;
  3698. CallingConv CC = FunctionTypeP->getCallConv();
  3699. if (EPI.ExtInfo.getCC() != CC) {
  3700. EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC);
  3701. Rebuild = true;
  3702. }
  3703. bool NoReturn = FunctionTypeP->getNoReturnAttr();
  3704. if (EPI.ExtInfo.getNoReturn() != NoReturn) {
  3705. EPI.ExtInfo = EPI.ExtInfo.withNoReturn(NoReturn);
  3706. Rebuild = true;
  3707. }
  3708. if (AdjustExceptionSpec && (FunctionTypeP->hasExceptionSpec() ||
  3709. ArgFunctionTypeP->hasExceptionSpec())) {
  3710. EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec;
  3711. Rebuild = true;
  3712. }
  3713. if (!Rebuild)
  3714. return ArgFunctionType;
  3715. return Context.getFunctionType(ArgFunctionTypeP->getReturnType(),
  3716. ArgFunctionTypeP->getParamTypes(), EPI);
  3717. }
  3718. /// Deduce template arguments when taking the address of a function
  3719. /// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
  3720. /// a template.
  3721. ///
  3722. /// \param FunctionTemplate the function template for which we are performing
  3723. /// template argument deduction.
  3724. ///
  3725. /// \param ExplicitTemplateArgs the explicitly-specified template
  3726. /// arguments.
  3727. ///
  3728. /// \param ArgFunctionType the function type that will be used as the
  3729. /// "argument" type (A) when performing template argument deduction from the
  3730. /// function template's function type. This type may be NULL, if there is no
  3731. /// argument type to compare against, in C++0x [temp.arg.explicit]p3.
  3732. ///
  3733. /// \param Specialization if template argument deduction was successful,
  3734. /// this will be set to the function template specialization produced by
  3735. /// template argument deduction.
  3736. ///
  3737. /// \param Info the argument will be updated to provide additional information
  3738. /// about template argument deduction.
  3739. ///
  3740. /// \param IsAddressOfFunction If \c true, we are deducing as part of taking
  3741. /// the address of a function template per [temp.deduct.funcaddr] and
  3742. /// [over.over]. If \c false, we are looking up a function template
  3743. /// specialization based on its signature, per [temp.deduct.decl].
  3744. ///
  3745. /// \returns the result of template argument deduction.
  3746. Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
  3747. FunctionTemplateDecl *FunctionTemplate,
  3748. TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
  3749. FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
  3750. bool IsAddressOfFunction) {
  3751. if (FunctionTemplate->isInvalidDecl())
  3752. return TDK_Invalid;
  3753. FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
  3754. TemplateParameterList *TemplateParams
  3755. = FunctionTemplate->getTemplateParameters();
  3756. QualType FunctionType = Function->getType();
  3757. // Substitute any explicit template arguments.
  3758. LocalInstantiationScope InstScope(*this);
  3759. SmallVector<DeducedTemplateArgument, 4> Deduced;
  3760. unsigned NumExplicitlySpecified = 0;
  3761. SmallVector<QualType, 4> ParamTypes;
  3762. if (ExplicitTemplateArgs) {
  3763. TemplateDeductionResult Result;
  3764. runWithSufficientStackSpace(Info.getLocation(), [&] {
  3765. Result = SubstituteExplicitTemplateArguments(
  3766. FunctionTemplate, *ExplicitTemplateArgs, Deduced, ParamTypes,
  3767. &FunctionType, Info);
  3768. });
  3769. if (Result)
  3770. return Result;
  3771. NumExplicitlySpecified = Deduced.size();
  3772. }
  3773. // When taking the address of a function, we require convertibility of
  3774. // the resulting function type. Otherwise, we allow arbitrary mismatches
  3775. // of calling convention and noreturn.
  3776. if (!IsAddressOfFunction)
  3777. ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType,
  3778. /*AdjustExceptionSpec*/false);
  3779. // Unevaluated SFINAE context.
  3780. EnterExpressionEvaluationContext Unevaluated(
  3781. *this, Sema::ExpressionEvaluationContext::Unevaluated);
  3782. SFINAETrap Trap(*this);
  3783. Deduced.resize(TemplateParams->size());
  3784. // If the function has a deduced return type, substitute it for a dependent
  3785. // type so that we treat it as a non-deduced context in what follows. If we
  3786. // are looking up by signature, the signature type should also have a deduced
  3787. // return type, which we instead expect to exactly match.
  3788. bool HasDeducedReturnType = false;
  3789. if (getLangOpts().CPlusPlus14 && IsAddressOfFunction &&
  3790. Function->getReturnType()->getContainedAutoType()) {
  3791. FunctionType = SubstAutoTypeDependent(FunctionType);
  3792. HasDeducedReturnType = true;
  3793. }
  3794. if (!ArgFunctionType.isNull() && !FunctionType.isNull()) {
  3795. unsigned TDF =
  3796. TDF_TopLevelParameterTypeList | TDF_AllowCompatibleFunctionType;
  3797. // Deduce template arguments from the function type.
  3798. if (TemplateDeductionResult Result
  3799. = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
  3800. FunctionType, ArgFunctionType,
  3801. Info, Deduced, TDF))
  3802. return Result;
  3803. }
  3804. TemplateDeductionResult Result;
  3805. runWithSufficientStackSpace(Info.getLocation(), [&] {
  3806. Result = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
  3807. NumExplicitlySpecified,
  3808. Specialization, Info);
  3809. });
  3810. if (Result)
  3811. return Result;
  3812. // If the function has a deduced return type, deduce it now, so we can check
  3813. // that the deduced function type matches the requested type.
  3814. if (HasDeducedReturnType &&
  3815. Specialization->getReturnType()->isUndeducedType() &&
  3816. DeduceReturnType(Specialization, Info.getLocation(), false))
  3817. return TDK_MiscellaneousDeductionFailure;
  3818. // If the function has a dependent exception specification, resolve it now,
  3819. // so we can check that the exception specification matches.
  3820. auto *SpecializationFPT =
  3821. Specialization->getType()->castAs<FunctionProtoType>();
  3822. if (getLangOpts().CPlusPlus17 &&
  3823. isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
  3824. !ResolveExceptionSpec(Info.getLocation(), SpecializationFPT))
  3825. return TDK_MiscellaneousDeductionFailure;
  3826. // Adjust the exception specification of the argument to match the
  3827. // substituted and resolved type we just formed. (Calling convention and
  3828. // noreturn can't be dependent, so we don't actually need this for them
  3829. // right now.)
  3830. QualType SpecializationType = Specialization->getType();
  3831. if (!IsAddressOfFunction)
  3832. ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, SpecializationType,
  3833. /*AdjustExceptionSpec*/true);
  3834. // If the requested function type does not match the actual type of the
  3835. // specialization with respect to arguments of compatible pointer to function
  3836. // types, template argument deduction fails.
  3837. if (!ArgFunctionType.isNull()) {
  3838. if (IsAddressOfFunction &&
  3839. !isSameOrCompatibleFunctionType(
  3840. Context.getCanonicalType(SpecializationType),
  3841. Context.getCanonicalType(ArgFunctionType)))
  3842. return TDK_MiscellaneousDeductionFailure;
  3843. if (!IsAddressOfFunction &&
  3844. !Context.hasSameType(SpecializationType, ArgFunctionType))
  3845. return TDK_MiscellaneousDeductionFailure;
  3846. }
  3847. return TDK_Success;
  3848. }
  3849. /// Deduce template arguments for a templated conversion
  3850. /// function (C++ [temp.deduct.conv]) and, if successful, produce a
  3851. /// conversion function template specialization.
  3852. Sema::TemplateDeductionResult
  3853. Sema::DeduceTemplateArguments(FunctionTemplateDecl *ConversionTemplate,
  3854. QualType ToType,
  3855. CXXConversionDecl *&Specialization,
  3856. TemplateDeductionInfo &Info) {
  3857. if (ConversionTemplate->isInvalidDecl())
  3858. return TDK_Invalid;
  3859. CXXConversionDecl *ConversionGeneric
  3860. = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
  3861. QualType FromType = ConversionGeneric->getConversionType();
  3862. // Canonicalize the types for deduction.
  3863. QualType P = Context.getCanonicalType(FromType);
  3864. QualType A = Context.getCanonicalType(ToType);
  3865. // C++0x [temp.deduct.conv]p2:
  3866. // If P is a reference type, the type referred to by P is used for
  3867. // type deduction.
  3868. if (const ReferenceType *PRef = P->getAs<ReferenceType>())
  3869. P = PRef->getPointeeType();
  3870. // C++0x [temp.deduct.conv]p4:
  3871. // [...] If A is a reference type, the type referred to by A is used
  3872. // for type deduction.
  3873. if (const ReferenceType *ARef = A->getAs<ReferenceType>()) {
  3874. A = ARef->getPointeeType();
  3875. // We work around a defect in the standard here: cv-qualifiers are also
  3876. // removed from P and A in this case, unless P was a reference type. This
  3877. // seems to mostly match what other compilers are doing.
  3878. if (!FromType->getAs<ReferenceType>()) {
  3879. A = A.getUnqualifiedType();
  3880. P = P.getUnqualifiedType();
  3881. }
  3882. // C++ [temp.deduct.conv]p3:
  3883. //
  3884. // If A is not a reference type:
  3885. } else {
  3886. assert(!A->isReferenceType() && "Reference types were handled above");
  3887. // - If P is an array type, the pointer type produced by the
  3888. // array-to-pointer standard conversion (4.2) is used in place
  3889. // of P for type deduction; otherwise,
  3890. if (P->isArrayType())
  3891. P = Context.getArrayDecayedType(P);
  3892. // - If P is a function type, the pointer type produced by the
  3893. // function-to-pointer standard conversion (4.3) is used in
  3894. // place of P for type deduction; otherwise,
  3895. else if (P->isFunctionType())
  3896. P = Context.getPointerType(P);
  3897. // - If P is a cv-qualified type, the top level cv-qualifiers of
  3898. // P's type are ignored for type deduction.
  3899. else
  3900. P = P.getUnqualifiedType();
  3901. // C++0x [temp.deduct.conv]p4:
  3902. // If A is a cv-qualified type, the top level cv-qualifiers of A's
  3903. // type are ignored for type deduction. If A is a reference type, the type
  3904. // referred to by A is used for type deduction.
  3905. A = A.getUnqualifiedType();
  3906. }
  3907. // Unevaluated SFINAE context.
  3908. EnterExpressionEvaluationContext Unevaluated(
  3909. *this, Sema::ExpressionEvaluationContext::Unevaluated);
  3910. SFINAETrap Trap(*this);
  3911. // C++ [temp.deduct.conv]p1:
  3912. // Template argument deduction is done by comparing the return
  3913. // type of the template conversion function (call it P) with the
  3914. // type that is required as the result of the conversion (call it
  3915. // A) as described in 14.8.2.4.
  3916. TemplateParameterList *TemplateParams
  3917. = ConversionTemplate->getTemplateParameters();
  3918. SmallVector<DeducedTemplateArgument, 4> Deduced;
  3919. Deduced.resize(TemplateParams->size());
  3920. // C++0x [temp.deduct.conv]p4:
  3921. // In general, the deduction process attempts to find template
  3922. // argument values that will make the deduced A identical to
  3923. // A. However, there are two cases that allow a difference:
  3924. unsigned TDF = 0;
  3925. // - If the original A is a reference type, A can be more
  3926. // cv-qualified than the deduced A (i.e., the type referred to
  3927. // by the reference)
  3928. if (ToType->isReferenceType())
  3929. TDF |= TDF_ArgWithReferenceType;
  3930. // - The deduced A can be another pointer or pointer to member
  3931. // type that can be converted to A via a qualification
  3932. // conversion.
  3933. //
  3934. // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
  3935. // both P and A are pointers or member pointers. In this case, we
  3936. // just ignore cv-qualifiers completely).
  3937. if ((P->isPointerType() && A->isPointerType()) ||
  3938. (P->isMemberPointerType() && A->isMemberPointerType()))
  3939. TDF |= TDF_IgnoreQualifiers;
  3940. if (TemplateDeductionResult Result
  3941. = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
  3942. P, A, Info, Deduced, TDF))
  3943. return Result;
  3944. // Create an Instantiation Scope for finalizing the operator.
  3945. LocalInstantiationScope InstScope(*this);
  3946. // Finish template argument deduction.
  3947. FunctionDecl *ConversionSpecialized = nullptr;
  3948. TemplateDeductionResult Result;
  3949. runWithSufficientStackSpace(Info.getLocation(), [&] {
  3950. Result = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
  3951. ConversionSpecialized, Info);
  3952. });
  3953. Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
  3954. return Result;
  3955. }
  3956. /// Deduce template arguments for a function template when there is
  3957. /// nothing to deduce against (C++0x [temp.arg.explicit]p3).
  3958. ///
  3959. /// \param FunctionTemplate the function template for which we are performing
  3960. /// template argument deduction.
  3961. ///
  3962. /// \param ExplicitTemplateArgs the explicitly-specified template
  3963. /// arguments.
  3964. ///
  3965. /// \param Specialization if template argument deduction was successful,
  3966. /// this will be set to the function template specialization produced by
  3967. /// template argument deduction.
  3968. ///
  3969. /// \param Info the argument will be updated to provide additional information
  3970. /// about template argument deduction.
  3971. ///
  3972. /// \param IsAddressOfFunction If \c true, we are deducing as part of taking
  3973. /// the address of a function template in a context where we do not have a
  3974. /// target type, per [over.over]. If \c false, we are looking up a function
  3975. /// template specialization based on its signature, which only happens when
  3976. /// deducing a function parameter type from an argument that is a template-id
  3977. /// naming a function template specialization.
  3978. ///
  3979. /// \returns the result of template argument deduction.
  3980. Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
  3981. FunctionTemplateDecl *FunctionTemplate,
  3982. TemplateArgumentListInfo *ExplicitTemplateArgs,
  3983. FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
  3984. bool IsAddressOfFunction) {
  3985. return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
  3986. QualType(), Specialization, Info,
  3987. IsAddressOfFunction);
  3988. }
  3989. namespace {
  3990. struct DependentAuto { bool IsPack; };
  3991. /// Substitute the 'auto' specifier or deduced template specialization type
  3992. /// specifier within a type for a given replacement type.
  3993. class SubstituteDeducedTypeTransform :
  3994. public TreeTransform<SubstituteDeducedTypeTransform> {
  3995. QualType Replacement;
  3996. bool ReplacementIsPack;
  3997. bool UseTypeSugar;
  3998. public:
  3999. SubstituteDeducedTypeTransform(Sema &SemaRef, DependentAuto DA)
  4000. : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
  4001. ReplacementIsPack(DA.IsPack), UseTypeSugar(true) {}
  4002. SubstituteDeducedTypeTransform(Sema &SemaRef, QualType Replacement,
  4003. bool UseTypeSugar = true)
  4004. : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
  4005. Replacement(Replacement), ReplacementIsPack(false),
  4006. UseTypeSugar(UseTypeSugar) {}
  4007. QualType TransformDesugared(TypeLocBuilder &TLB, DeducedTypeLoc TL) {
  4008. assert(isa<TemplateTypeParmType>(Replacement) &&
  4009. "unexpected unsugared replacement kind");
  4010. QualType Result = Replacement;
  4011. TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
  4012. NewTL.setNameLoc(TL.getNameLoc());
  4013. return Result;
  4014. }
  4015. QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
  4016. // If we're building the type pattern to deduce against, don't wrap the
  4017. // substituted type in an AutoType. Certain template deduction rules
  4018. // apply only when a template type parameter appears directly (and not if
  4019. // the parameter is found through desugaring). For instance:
  4020. // auto &&lref = lvalue;
  4021. // must transform into "rvalue reference to T" not "rvalue reference to
  4022. // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
  4023. //
  4024. // FIXME: Is this still necessary?
  4025. if (!UseTypeSugar)
  4026. return TransformDesugared(TLB, TL);
  4027. QualType Result = SemaRef.Context.getAutoType(
  4028. Replacement, TL.getTypePtr()->getKeyword(), Replacement.isNull(),
  4029. ReplacementIsPack, TL.getTypePtr()->getTypeConstraintConcept(),
  4030. TL.getTypePtr()->getTypeConstraintArguments());
  4031. auto NewTL = TLB.push<AutoTypeLoc>(Result);
  4032. NewTL.copy(TL);
  4033. return Result;
  4034. }
  4035. QualType TransformDeducedTemplateSpecializationType(
  4036. TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) {
  4037. if (!UseTypeSugar)
  4038. return TransformDesugared(TLB, TL);
  4039. QualType Result = SemaRef.Context.getDeducedTemplateSpecializationType(
  4040. TL.getTypePtr()->getTemplateName(),
  4041. Replacement, Replacement.isNull());
  4042. auto NewTL = TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
  4043. NewTL.setNameLoc(TL.getNameLoc());
  4044. return Result;
  4045. }
  4046. ExprResult TransformLambdaExpr(LambdaExpr *E) {
  4047. // Lambdas never need to be transformed.
  4048. return E;
  4049. }
  4050. QualType Apply(TypeLoc TL) {
  4051. // Create some scratch storage for the transformed type locations.
  4052. // FIXME: We're just going to throw this information away. Don't build it.
  4053. TypeLocBuilder TLB;
  4054. TLB.reserve(TL.getFullDataSize());
  4055. return TransformType(TLB, TL);
  4056. }
  4057. };
  4058. } // namespace
  4059. static bool CheckDeducedPlaceholderConstraints(Sema &S, const AutoType &Type,
  4060. AutoTypeLoc TypeLoc,
  4061. QualType Deduced) {
  4062. ConstraintSatisfaction Satisfaction;
  4063. ConceptDecl *Concept = Type.getTypeConstraintConcept();
  4064. TemplateArgumentListInfo TemplateArgs(TypeLoc.getLAngleLoc(),
  4065. TypeLoc.getRAngleLoc());
  4066. TemplateArgs.addArgument(
  4067. TemplateArgumentLoc(TemplateArgument(Deduced),
  4068. S.Context.getTrivialTypeSourceInfo(
  4069. Deduced, TypeLoc.getNameLoc())));
  4070. for (unsigned I = 0, C = TypeLoc.getNumArgs(); I != C; ++I)
  4071. TemplateArgs.addArgument(TypeLoc.getArgLoc(I));
  4072. llvm::SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
  4073. if (S.CheckTemplateArgumentList(Concept, SourceLocation(), TemplateArgs,
  4074. /*PartialTemplateArgs=*/false,
  4075. SugaredConverted, CanonicalConverted))
  4076. return true;
  4077. MultiLevelTemplateArgumentList MLTAL(Concept, CanonicalConverted,
  4078. /*Final=*/false);
  4079. if (S.CheckConstraintSatisfaction(Concept, {Concept->getConstraintExpr()},
  4080. MLTAL, TypeLoc.getLocalSourceRange(),
  4081. Satisfaction))
  4082. return true;
  4083. if (!Satisfaction.IsSatisfied) {
  4084. std::string Buf;
  4085. llvm::raw_string_ostream OS(Buf);
  4086. OS << "'" << Concept->getName();
  4087. if (TypeLoc.hasExplicitTemplateArgs()) {
  4088. printTemplateArgumentList(
  4089. OS, Type.getTypeConstraintArguments(), S.getPrintingPolicy(),
  4090. Type.getTypeConstraintConcept()->getTemplateParameters());
  4091. }
  4092. OS << "'";
  4093. OS.flush();
  4094. S.Diag(TypeLoc.getConceptNameLoc(),
  4095. diag::err_placeholder_constraints_not_satisfied)
  4096. << Deduced << Buf << TypeLoc.getLocalSourceRange();
  4097. S.DiagnoseUnsatisfiedConstraint(Satisfaction);
  4098. return true;
  4099. }
  4100. return false;
  4101. }
  4102. /// Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
  4103. ///
  4104. /// Note that this is done even if the initializer is dependent. (This is
  4105. /// necessary to support partial ordering of templates using 'auto'.)
  4106. /// A dependent type will be produced when deducing from a dependent type.
  4107. ///
  4108. /// \param Type the type pattern using the auto type-specifier.
  4109. /// \param Init the initializer for the variable whose type is to be deduced.
  4110. /// \param Result if type deduction was successful, this will be set to the
  4111. /// deduced type.
  4112. /// \param Info the argument will be updated to provide additional information
  4113. /// about template argument deduction.
  4114. /// \param DependentDeduction Set if we should permit deduction in
  4115. /// dependent cases. This is necessary for template partial ordering with
  4116. /// 'auto' template parameters. The template parameter depth to be used
  4117. /// should be specified in the 'Info' parameter.
  4118. /// \param IgnoreConstraints Set if we should not fail if the deduced type does
  4119. /// not satisfy the type-constraint in the auto type.
  4120. Sema::TemplateDeductionResult Sema::DeduceAutoType(TypeLoc Type, Expr *Init,
  4121. QualType &Result,
  4122. TemplateDeductionInfo &Info,
  4123. bool DependentDeduction,
  4124. bool IgnoreConstraints) {
  4125. assert(DependentDeduction || Info.getDeducedDepth() == 0);
  4126. if (Init->containsErrors())
  4127. return TDK_AlreadyDiagnosed;
  4128. const AutoType *AT = Type.getType()->getContainedAutoType();
  4129. assert(AT);
  4130. if (Init->getType()->isNonOverloadPlaceholderType() || AT->isDecltypeAuto()) {
  4131. ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
  4132. if (NonPlaceholder.isInvalid())
  4133. return TDK_AlreadyDiagnosed;
  4134. Init = NonPlaceholder.get();
  4135. }
  4136. DependentAuto DependentResult = {
  4137. /*.IsPack = */ (bool)Type.getAs<PackExpansionTypeLoc>()};
  4138. if (!DependentDeduction &&
  4139. (Type.getType()->isDependentType() || Init->isTypeDependent() ||
  4140. Init->containsUnexpandedParameterPack())) {
  4141. Result = SubstituteDeducedTypeTransform(*this, DependentResult).Apply(Type);
  4142. assert(!Result.isNull() && "substituting DependentTy can't fail");
  4143. return TDK_Success;
  4144. }
  4145. auto *InitList = dyn_cast<InitListExpr>(Init);
  4146. if (!getLangOpts().CPlusPlus && InitList) {
  4147. Diag(Init->getBeginLoc(), diag::err_auto_init_list_from_c);
  4148. return TDK_AlreadyDiagnosed;
  4149. }
  4150. // Deduce type of TemplParam in Func(Init)
  4151. SmallVector<DeducedTemplateArgument, 1> Deduced;
  4152. Deduced.resize(1);
  4153. // If deduction failed, don't diagnose if the initializer is dependent; it
  4154. // might acquire a matching type in the instantiation.
  4155. auto DeductionFailed = [&](TemplateDeductionResult TDK) {
  4156. if (Init->isTypeDependent()) {
  4157. Result =
  4158. SubstituteDeducedTypeTransform(*this, DependentResult).Apply(Type);
  4159. assert(!Result.isNull() && "substituting DependentTy can't fail");
  4160. return TDK_Success;
  4161. }
  4162. return TDK;
  4163. };
  4164. SmallVector<OriginalCallArg, 4> OriginalCallArgs;
  4165. QualType DeducedType;
  4166. // If this is a 'decltype(auto)' specifier, do the decltype dance.
  4167. if (AT->isDecltypeAuto()) {
  4168. if (InitList) {
  4169. Diag(Init->getBeginLoc(), diag::err_decltype_auto_initializer_list);
  4170. return TDK_AlreadyDiagnosed;
  4171. }
  4172. DeducedType = getDecltypeForExpr(Init);
  4173. assert(!DeducedType.isNull());
  4174. } else {
  4175. LocalInstantiationScope InstScope(*this);
  4176. // Build template<class TemplParam> void Func(FuncParam);
  4177. SourceLocation Loc = Init->getExprLoc();
  4178. TemplateTypeParmDecl *TemplParam = TemplateTypeParmDecl::Create(
  4179. Context, nullptr, SourceLocation(), Loc, Info.getDeducedDepth(), 0,
  4180. nullptr, false, false, false);
  4181. QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
  4182. NamedDecl *TemplParamPtr = TemplParam;
  4183. FixedSizeTemplateParameterListStorage<1, false> TemplateParamsSt(
  4184. Context, Loc, Loc, TemplParamPtr, Loc, nullptr);
  4185. if (InitList) {
  4186. // Notionally, we substitute std::initializer_list<T> for 'auto' and
  4187. // deduce against that. Such deduction only succeeds if removing
  4188. // cv-qualifiers and references results in std::initializer_list<T>.
  4189. if (!Type.getType().getNonReferenceType()->getAs<AutoType>())
  4190. return TDK_Invalid;
  4191. SourceRange DeducedFromInitRange;
  4192. for (Expr *Init : InitList->inits()) {
  4193. // Resolving a core issue: a braced-init-list containing any designators
  4194. // is a non-deduced context.
  4195. if (isa<DesignatedInitExpr>(Init))
  4196. return TDK_Invalid;
  4197. if (auto TDK = DeduceTemplateArgumentsFromCallArgument(
  4198. *this, TemplateParamsSt.get(), 0, TemplArg, Init, Info, Deduced,
  4199. OriginalCallArgs, /*Decomposed=*/true,
  4200. /*ArgIdx=*/0, /*TDF=*/0)) {
  4201. if (TDK == TDK_Inconsistent) {
  4202. Diag(Info.getLocation(), diag::err_auto_inconsistent_deduction)
  4203. << Info.FirstArg << Info.SecondArg << DeducedFromInitRange
  4204. << Init->getSourceRange();
  4205. return DeductionFailed(TDK_AlreadyDiagnosed);
  4206. }
  4207. return DeductionFailed(TDK);
  4208. }
  4209. if (DeducedFromInitRange.isInvalid() &&
  4210. Deduced[0].getKind() != TemplateArgument::Null)
  4211. DeducedFromInitRange = Init->getSourceRange();
  4212. }
  4213. } else {
  4214. if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
  4215. Diag(Loc, diag::err_auto_bitfield);
  4216. return TDK_AlreadyDiagnosed;
  4217. }
  4218. QualType FuncParam =
  4219. SubstituteDeducedTypeTransform(*this, TemplArg).Apply(Type);
  4220. assert(!FuncParam.isNull() &&
  4221. "substituting template parameter for 'auto' failed");
  4222. if (auto TDK = DeduceTemplateArgumentsFromCallArgument(
  4223. *this, TemplateParamsSt.get(), 0, FuncParam, Init, Info, Deduced,
  4224. OriginalCallArgs, /*Decomposed=*/false, /*ArgIdx=*/0, /*TDF=*/0))
  4225. return DeductionFailed(TDK);
  4226. }
  4227. // Could be null if somehow 'auto' appears in a non-deduced context.
  4228. if (Deduced[0].getKind() != TemplateArgument::Type)
  4229. return DeductionFailed(TDK_Incomplete);
  4230. DeducedType = Deduced[0].getAsType();
  4231. if (InitList) {
  4232. DeducedType = BuildStdInitializerList(DeducedType, Loc);
  4233. if (DeducedType.isNull())
  4234. return TDK_AlreadyDiagnosed;
  4235. }
  4236. }
  4237. if (!Result.isNull()) {
  4238. if (!Context.hasSameType(DeducedType, Result)) {
  4239. Info.FirstArg = Result;
  4240. Info.SecondArg = DeducedType;
  4241. return DeductionFailed(TDK_Inconsistent);
  4242. }
  4243. DeducedType = Context.getCommonSugaredType(Result, DeducedType);
  4244. }
  4245. if (AT->isConstrained() && !IgnoreConstraints &&
  4246. CheckDeducedPlaceholderConstraints(
  4247. *this, *AT, Type.getContainedAutoTypeLoc(), DeducedType))
  4248. return TDK_AlreadyDiagnosed;
  4249. Result = SubstituteDeducedTypeTransform(*this, DeducedType).Apply(Type);
  4250. if (Result.isNull())
  4251. return TDK_AlreadyDiagnosed;
  4252. // Check that the deduced argument type is compatible with the original
  4253. // argument type per C++ [temp.deduct.call]p4.
  4254. QualType DeducedA = InitList ? Deduced[0].getAsType() : Result;
  4255. for (const OriginalCallArg &OriginalArg : OriginalCallArgs) {
  4256. assert((bool)InitList == OriginalArg.DecomposedParam &&
  4257. "decomposed non-init-list in auto deduction?");
  4258. if (auto TDK =
  4259. CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA)) {
  4260. Result = QualType();
  4261. return DeductionFailed(TDK);
  4262. }
  4263. }
  4264. return TDK_Success;
  4265. }
  4266. QualType Sema::SubstAutoType(QualType TypeWithAuto,
  4267. QualType TypeToReplaceAuto) {
  4268. assert(TypeToReplaceAuto != Context.DependentTy);
  4269. return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
  4270. .TransformType(TypeWithAuto);
  4271. }
  4272. TypeSourceInfo *Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
  4273. QualType TypeToReplaceAuto) {
  4274. assert(TypeToReplaceAuto != Context.DependentTy);
  4275. return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
  4276. .TransformType(TypeWithAuto);
  4277. }
  4278. QualType Sema::SubstAutoTypeDependent(QualType TypeWithAuto) {
  4279. return SubstituteDeducedTypeTransform(*this, DependentAuto{false})
  4280. .TransformType(TypeWithAuto);
  4281. }
  4282. TypeSourceInfo *
  4283. Sema::SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto) {
  4284. return SubstituteDeducedTypeTransform(*this, DependentAuto{false})
  4285. .TransformType(TypeWithAuto);
  4286. }
  4287. QualType Sema::ReplaceAutoType(QualType TypeWithAuto,
  4288. QualType TypeToReplaceAuto) {
  4289. return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
  4290. /*UseTypeSugar*/ false)
  4291. .TransformType(TypeWithAuto);
  4292. }
  4293. TypeSourceInfo *Sema::ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
  4294. QualType TypeToReplaceAuto) {
  4295. return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
  4296. /*UseTypeSugar*/ false)
  4297. .TransformType(TypeWithAuto);
  4298. }
  4299. void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) {
  4300. if (isa<InitListExpr>(Init))
  4301. Diag(VDecl->getLocation(),
  4302. VDecl->isInitCapture()
  4303. ? diag::err_init_capture_deduction_failure_from_init_list
  4304. : diag::err_auto_var_deduction_failure_from_init_list)
  4305. << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
  4306. else
  4307. Diag(VDecl->getLocation(),
  4308. VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
  4309. : diag::err_auto_var_deduction_failure)
  4310. << VDecl->getDeclName() << VDecl->getType() << Init->getType()
  4311. << Init->getSourceRange();
  4312. }
  4313. bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
  4314. bool Diagnose) {
  4315. assert(FD->getReturnType()->isUndeducedType());
  4316. // For a lambda's conversion operator, deduce any 'auto' or 'decltype(auto)'
  4317. // within the return type from the call operator's type.
  4318. if (isLambdaConversionOperator(FD)) {
  4319. CXXRecordDecl *Lambda = cast<CXXMethodDecl>(FD)->getParent();
  4320. FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
  4321. // For a generic lambda, instantiate the call operator if needed.
  4322. if (auto *Args = FD->getTemplateSpecializationArgs()) {
  4323. CallOp = InstantiateFunctionDeclaration(
  4324. CallOp->getDescribedFunctionTemplate(), Args, Loc);
  4325. if (!CallOp || CallOp->isInvalidDecl())
  4326. return true;
  4327. // We might need to deduce the return type by instantiating the definition
  4328. // of the operator() function.
  4329. if (CallOp->getReturnType()->isUndeducedType()) {
  4330. runWithSufficientStackSpace(Loc, [&] {
  4331. InstantiateFunctionDefinition(Loc, CallOp);
  4332. });
  4333. }
  4334. }
  4335. if (CallOp->isInvalidDecl())
  4336. return true;
  4337. assert(!CallOp->getReturnType()->isUndeducedType() &&
  4338. "failed to deduce lambda return type");
  4339. // Build the new return type from scratch.
  4340. CallingConv RetTyCC = FD->getReturnType()
  4341. ->getPointeeType()
  4342. ->castAs<FunctionType>()
  4343. ->getCallConv();
  4344. QualType RetType = getLambdaConversionFunctionResultType(
  4345. CallOp->getType()->castAs<FunctionProtoType>(), RetTyCC);
  4346. if (FD->getReturnType()->getAs<PointerType>())
  4347. RetType = Context.getPointerType(RetType);
  4348. else {
  4349. assert(FD->getReturnType()->getAs<BlockPointerType>());
  4350. RetType = Context.getBlockPointerType(RetType);
  4351. }
  4352. Context.adjustDeducedFunctionResultType(FD, RetType);
  4353. return false;
  4354. }
  4355. if (FD->getTemplateInstantiationPattern()) {
  4356. runWithSufficientStackSpace(Loc, [&] {
  4357. InstantiateFunctionDefinition(Loc, FD);
  4358. });
  4359. }
  4360. bool StillUndeduced = FD->getReturnType()->isUndeducedType();
  4361. if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
  4362. Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
  4363. Diag(FD->getLocation(), diag::note_callee_decl) << FD;
  4364. }
  4365. return StillUndeduced;
  4366. }
  4367. /// If this is a non-static member function,
  4368. static void
  4369. AddImplicitObjectParameterType(ASTContext &Context,
  4370. CXXMethodDecl *Method,
  4371. SmallVectorImpl<QualType> &ArgTypes) {
  4372. // C++11 [temp.func.order]p3:
  4373. // [...] The new parameter is of type "reference to cv A," where cv are
  4374. // the cv-qualifiers of the function template (if any) and A is
  4375. // the class of which the function template is a member.
  4376. //
  4377. // The standard doesn't say explicitly, but we pick the appropriate kind of
  4378. // reference type based on [over.match.funcs]p4.
  4379. QualType ArgTy = Context.getTypeDeclType(Method->getParent());
  4380. ArgTy = Context.getQualifiedType(ArgTy, Method->getMethodQualifiers());
  4381. if (Method->getRefQualifier() == RQ_RValue)
  4382. ArgTy = Context.getRValueReferenceType(ArgTy);
  4383. else
  4384. ArgTy = Context.getLValueReferenceType(ArgTy);
  4385. ArgTypes.push_back(ArgTy);
  4386. }
  4387. /// Determine whether the function template \p FT1 is at least as
  4388. /// specialized as \p FT2.
  4389. static bool isAtLeastAsSpecializedAs(Sema &S,
  4390. SourceLocation Loc,
  4391. FunctionTemplateDecl *FT1,
  4392. FunctionTemplateDecl *FT2,
  4393. TemplatePartialOrderingContext TPOC,
  4394. unsigned NumCallArguments1,
  4395. bool Reversed) {
  4396. assert(!Reversed || TPOC == TPOC_Call);
  4397. FunctionDecl *FD1 = FT1->getTemplatedDecl();
  4398. FunctionDecl *FD2 = FT2->getTemplatedDecl();
  4399. const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
  4400. const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
  4401. assert(Proto1 && Proto2 && "Function templates must have prototypes");
  4402. TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
  4403. SmallVector<DeducedTemplateArgument, 4> Deduced;
  4404. Deduced.resize(TemplateParams->size());
  4405. // C++0x [temp.deduct.partial]p3:
  4406. // The types used to determine the ordering depend on the context in which
  4407. // the partial ordering is done:
  4408. TemplateDeductionInfo Info(Loc);
  4409. SmallVector<QualType, 4> Args2;
  4410. switch (TPOC) {
  4411. case TPOC_Call: {
  4412. // - In the context of a function call, the function parameter types are
  4413. // used.
  4414. CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
  4415. CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
  4416. // C++11 [temp.func.order]p3:
  4417. // [...] If only one of the function templates is a non-static
  4418. // member, that function template is considered to have a new
  4419. // first parameter inserted in its function parameter list. The
  4420. // new parameter is of type "reference to cv A," where cv are
  4421. // the cv-qualifiers of the function template (if any) and A is
  4422. // the class of which the function template is a member.
  4423. //
  4424. // Note that we interpret this to mean "if one of the function
  4425. // templates is a non-static member and the other is a non-member";
  4426. // otherwise, the ordering rules for static functions against non-static
  4427. // functions don't make any sense.
  4428. //
  4429. // C++98/03 doesn't have this provision but we've extended DR532 to cover
  4430. // it as wording was broken prior to it.
  4431. SmallVector<QualType, 4> Args1;
  4432. unsigned NumComparedArguments = NumCallArguments1;
  4433. if (!Method2 && Method1 && !Method1->isStatic()) {
  4434. // Compare 'this' from Method1 against first parameter from Method2.
  4435. AddImplicitObjectParameterType(S.Context, Method1, Args1);
  4436. ++NumComparedArguments;
  4437. } else if (!Method1 && Method2 && !Method2->isStatic()) {
  4438. // Compare 'this' from Method2 against first parameter from Method1.
  4439. AddImplicitObjectParameterType(S.Context, Method2, Args2);
  4440. } else if (Method1 && Method2 && Reversed) {
  4441. // Compare 'this' from Method1 against second parameter from Method2
  4442. // and 'this' from Method2 against second parameter from Method1.
  4443. AddImplicitObjectParameterType(S.Context, Method1, Args1);
  4444. AddImplicitObjectParameterType(S.Context, Method2, Args2);
  4445. ++NumComparedArguments;
  4446. }
  4447. Args1.insert(Args1.end(), Proto1->param_type_begin(),
  4448. Proto1->param_type_end());
  4449. Args2.insert(Args2.end(), Proto2->param_type_begin(),
  4450. Proto2->param_type_end());
  4451. // C++ [temp.func.order]p5:
  4452. // The presence of unused ellipsis and default arguments has no effect on
  4453. // the partial ordering of function templates.
  4454. if (Args1.size() > NumComparedArguments)
  4455. Args1.resize(NumComparedArguments);
  4456. if (Args2.size() > NumComparedArguments)
  4457. Args2.resize(NumComparedArguments);
  4458. if (Reversed)
  4459. std::reverse(Args2.begin(), Args2.end());
  4460. if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
  4461. Args1.data(), Args1.size(), Info, Deduced,
  4462. TDF_None, /*PartialOrdering=*/true))
  4463. return false;
  4464. break;
  4465. }
  4466. case TPOC_Conversion:
  4467. // - In the context of a call to a conversion operator, the return types
  4468. // of the conversion function templates are used.
  4469. if (DeduceTemplateArgumentsByTypeMatch(
  4470. S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
  4471. Info, Deduced, TDF_None,
  4472. /*PartialOrdering=*/true))
  4473. return false;
  4474. break;
  4475. case TPOC_Other:
  4476. // - In other contexts (14.6.6.2) the function template's function type
  4477. // is used.
  4478. if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
  4479. FD2->getType(), FD1->getType(),
  4480. Info, Deduced, TDF_None,
  4481. /*PartialOrdering=*/true))
  4482. return false;
  4483. break;
  4484. }
  4485. // C++0x [temp.deduct.partial]p11:
  4486. // In most cases, all template parameters must have values in order for
  4487. // deduction to succeed, but for partial ordering purposes a template
  4488. // parameter may remain without a value provided it is not used in the
  4489. // types being used for partial ordering. [ Note: a template parameter used
  4490. // in a non-deduced context is considered used. -end note]
  4491. unsigned ArgIdx = 0, NumArgs = Deduced.size();
  4492. for (; ArgIdx != NumArgs; ++ArgIdx)
  4493. if (Deduced[ArgIdx].isNull())
  4494. break;
  4495. // FIXME: We fail to implement [temp.deduct.type]p1 along this path. We need
  4496. // to substitute the deduced arguments back into the template and check that
  4497. // we get the right type.
  4498. if (ArgIdx == NumArgs) {
  4499. // All template arguments were deduced. FT1 is at least as specialized
  4500. // as FT2.
  4501. return true;
  4502. }
  4503. // Figure out which template parameters were used.
  4504. llvm::SmallBitVector UsedParameters(TemplateParams->size());
  4505. switch (TPOC) {
  4506. case TPOC_Call:
  4507. for (unsigned I = 0, N = Args2.size(); I != N; ++I)
  4508. ::MarkUsedTemplateParameters(S.Context, Args2[I], false,
  4509. TemplateParams->getDepth(),
  4510. UsedParameters);
  4511. break;
  4512. case TPOC_Conversion:
  4513. ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false,
  4514. TemplateParams->getDepth(), UsedParameters);
  4515. break;
  4516. case TPOC_Other:
  4517. ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false,
  4518. TemplateParams->getDepth(),
  4519. UsedParameters);
  4520. break;
  4521. }
  4522. for (; ArgIdx != NumArgs; ++ArgIdx)
  4523. // If this argument had no value deduced but was used in one of the types
  4524. // used for partial ordering, then deduction fails.
  4525. if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
  4526. return false;
  4527. return true;
  4528. }
  4529. /// Returns the more specialized function template according
  4530. /// to the rules of function template partial ordering (C++ [temp.func.order]).
  4531. ///
  4532. /// \param FT1 the first function template
  4533. ///
  4534. /// \param FT2 the second function template
  4535. ///
  4536. /// \param TPOC the context in which we are performing partial ordering of
  4537. /// function templates.
  4538. ///
  4539. /// \param NumCallArguments1 The number of arguments in the call to FT1, used
  4540. /// only when \c TPOC is \c TPOC_Call.
  4541. ///
  4542. /// \param NumCallArguments2 The number of arguments in the call to FT2, used
  4543. /// only when \c TPOC is \c TPOC_Call.
  4544. ///
  4545. /// \param Reversed If \c true, exactly one of FT1 and FT2 is an overload
  4546. /// candidate with a reversed parameter order. In this case, the corresponding
  4547. /// P/A pairs between FT1 and FT2 are reversed.
  4548. ///
  4549. /// \returns the more specialized function template. If neither
  4550. /// template is more specialized, returns NULL.
  4551. FunctionTemplateDecl *Sema::getMoreSpecializedTemplate(
  4552. FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc,
  4553. TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1,
  4554. unsigned NumCallArguments2, bool Reversed) {
  4555. bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
  4556. NumCallArguments1, Reversed);
  4557. bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
  4558. NumCallArguments2, Reversed);
  4559. // C++ [temp.deduct.partial]p10:
  4560. // F is more specialized than G if F is at least as specialized as G and G
  4561. // is not at least as specialized as F.
  4562. if (Better1 != Better2) // We have a clear winner
  4563. return Better1 ? FT1 : FT2;
  4564. if (!Better1 && !Better2) // Neither is better than the other
  4565. return nullptr;
  4566. // C++ [temp.deduct.partial]p11:
  4567. // ... and if G has a trailing function parameter pack for which F does not
  4568. // have a corresponding parameter, and if F does not have a trailing
  4569. // function parameter pack, then F is more specialized than G.
  4570. FunctionDecl *FD1 = FT1->getTemplatedDecl();
  4571. FunctionDecl *FD2 = FT2->getTemplatedDecl();
  4572. unsigned NumParams1 = FD1->getNumParams();
  4573. unsigned NumParams2 = FD2->getNumParams();
  4574. bool Variadic1 = NumParams1 && FD1->parameters().back()->isParameterPack();
  4575. bool Variadic2 = NumParams2 && FD2->parameters().back()->isParameterPack();
  4576. if (Variadic1 != Variadic2) {
  4577. if (Variadic1 && NumParams1 > NumParams2)
  4578. return FT2;
  4579. if (Variadic2 && NumParams2 > NumParams1)
  4580. return FT1;
  4581. }
  4582. // This a speculative fix for CWG1432 (Similar to the fix for CWG1395) that
  4583. // there is no wording or even resolution for this issue.
  4584. for (int i = 0, e = std::min(NumParams1, NumParams2); i < e; ++i) {
  4585. QualType T1 = FD1->getParamDecl(i)->getType().getCanonicalType();
  4586. QualType T2 = FD2->getParamDecl(i)->getType().getCanonicalType();
  4587. auto *TST1 = dyn_cast<TemplateSpecializationType>(T1);
  4588. auto *TST2 = dyn_cast<TemplateSpecializationType>(T2);
  4589. if (!TST1 || !TST2)
  4590. continue;
  4591. const TemplateArgument &TA1 = TST1->template_arguments().back();
  4592. if (TA1.getKind() == TemplateArgument::Pack) {
  4593. assert(TST1->template_arguments().size() ==
  4594. TST2->template_arguments().size());
  4595. const TemplateArgument &TA2 = TST2->template_arguments().back();
  4596. assert(TA2.getKind() == TemplateArgument::Pack);
  4597. unsigned PackSize1 = TA1.pack_size();
  4598. unsigned PackSize2 = TA2.pack_size();
  4599. bool IsPackExpansion1 =
  4600. PackSize1 && TA1.pack_elements().back().isPackExpansion();
  4601. bool IsPackExpansion2 =
  4602. PackSize2 && TA2.pack_elements().back().isPackExpansion();
  4603. if (PackSize1 != PackSize2 && IsPackExpansion1 != IsPackExpansion2) {
  4604. if (PackSize1 > PackSize2 && IsPackExpansion1)
  4605. return FT2;
  4606. if (PackSize1 < PackSize2 && IsPackExpansion2)
  4607. return FT1;
  4608. }
  4609. }
  4610. }
  4611. if (!Context.getLangOpts().CPlusPlus20)
  4612. return nullptr;
  4613. // Match GCC on not implementing [temp.func.order]p6.2.1.
  4614. // C++20 [temp.func.order]p6:
  4615. // If deduction against the other template succeeds for both transformed
  4616. // templates, constraints can be considered as follows:
  4617. // C++20 [temp.func.order]p6.1:
  4618. // If their template-parameter-lists (possibly including template-parameters
  4619. // invented for an abbreviated function template ([dcl.fct])) or function
  4620. // parameter lists differ in length, neither template is more specialized
  4621. // than the other.
  4622. TemplateParameterList *TPL1 = FT1->getTemplateParameters();
  4623. TemplateParameterList *TPL2 = FT2->getTemplateParameters();
  4624. if (TPL1->size() != TPL2->size() || NumParams1 != NumParams2)
  4625. return nullptr;
  4626. // C++20 [temp.func.order]p6.2.2:
  4627. // Otherwise, if the corresponding template-parameters of the
  4628. // template-parameter-lists are not equivalent ([temp.over.link]) or if the
  4629. // function parameters that positionally correspond between the two
  4630. // templates are not of the same type, neither template is more specialized
  4631. // than the other.
  4632. if (!TemplateParameterListsAreEqual(
  4633. TPL1, TPL2, false, Sema::TPL_TemplateMatch, SourceLocation(), true))
  4634. return nullptr;
  4635. for (unsigned i = 0; i < NumParams1; ++i)
  4636. if (!Context.hasSameType(FD1->getParamDecl(i)->getType(),
  4637. FD2->getParamDecl(i)->getType()))
  4638. return nullptr;
  4639. // C++20 [temp.func.order]p6.3:
  4640. // Otherwise, if the context in which the partial ordering is done is
  4641. // that of a call to a conversion function and the return types of the
  4642. // templates are not the same, then neither template is more specialized
  4643. // than the other.
  4644. if (TPOC == TPOC_Conversion &&
  4645. !Context.hasSameType(FD1->getReturnType(), FD2->getReturnType()))
  4646. return nullptr;
  4647. llvm::SmallVector<const Expr *, 3> AC1, AC2;
  4648. FT1->getAssociatedConstraints(AC1);
  4649. FT2->getAssociatedConstraints(AC2);
  4650. bool AtLeastAsConstrained1, AtLeastAsConstrained2;
  4651. if (IsAtLeastAsConstrained(FT1, AC1, FT2, AC2, AtLeastAsConstrained1))
  4652. return nullptr;
  4653. if (IsAtLeastAsConstrained(FT2, AC2, FT1, AC1, AtLeastAsConstrained2))
  4654. return nullptr;
  4655. if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
  4656. return nullptr;
  4657. return AtLeastAsConstrained1 ? FT1 : FT2;
  4658. }
  4659. /// Determine if the two templates are equivalent.
  4660. static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
  4661. if (T1 == T2)
  4662. return true;
  4663. if (!T1 || !T2)
  4664. return false;
  4665. return T1->getCanonicalDecl() == T2->getCanonicalDecl();
  4666. }
  4667. /// Retrieve the most specialized of the given function template
  4668. /// specializations.
  4669. ///
  4670. /// \param SpecBegin the start iterator of the function template
  4671. /// specializations that we will be comparing.
  4672. ///
  4673. /// \param SpecEnd the end iterator of the function template
  4674. /// specializations, paired with \p SpecBegin.
  4675. ///
  4676. /// \param Loc the location where the ambiguity or no-specializations
  4677. /// diagnostic should occur.
  4678. ///
  4679. /// \param NoneDiag partial diagnostic used to diagnose cases where there are
  4680. /// no matching candidates.
  4681. ///
  4682. /// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
  4683. /// occurs.
  4684. ///
  4685. /// \param CandidateDiag partial diagnostic used for each function template
  4686. /// specialization that is a candidate in the ambiguous ordering. One parameter
  4687. /// in this diagnostic should be unbound, which will correspond to the string
  4688. /// describing the template arguments for the function template specialization.
  4689. ///
  4690. /// \returns the most specialized function template specialization, if
  4691. /// found. Otherwise, returns SpecEnd.
  4692. UnresolvedSetIterator Sema::getMostSpecialized(
  4693. UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd,
  4694. TemplateSpecCandidateSet &FailedCandidates,
  4695. SourceLocation Loc, const PartialDiagnostic &NoneDiag,
  4696. const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
  4697. bool Complain, QualType TargetType) {
  4698. if (SpecBegin == SpecEnd) {
  4699. if (Complain) {
  4700. Diag(Loc, NoneDiag);
  4701. FailedCandidates.NoteCandidates(*this, Loc);
  4702. }
  4703. return SpecEnd;
  4704. }
  4705. if (SpecBegin + 1 == SpecEnd)
  4706. return SpecBegin;
  4707. // Find the function template that is better than all of the templates it
  4708. // has been compared to.
  4709. UnresolvedSetIterator Best = SpecBegin;
  4710. FunctionTemplateDecl *BestTemplate
  4711. = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
  4712. assert(BestTemplate && "Not a function template specialization?");
  4713. for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
  4714. FunctionTemplateDecl *Challenger
  4715. = cast<FunctionDecl>(*I)->getPrimaryTemplate();
  4716. assert(Challenger && "Not a function template specialization?");
  4717. if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
  4718. Loc, TPOC_Other, 0, 0),
  4719. Challenger)) {
  4720. Best = I;
  4721. BestTemplate = Challenger;
  4722. }
  4723. }
  4724. // Make sure that the "best" function template is more specialized than all
  4725. // of the others.
  4726. bool Ambiguous = false;
  4727. for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
  4728. FunctionTemplateDecl *Challenger
  4729. = cast<FunctionDecl>(*I)->getPrimaryTemplate();
  4730. if (I != Best &&
  4731. !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
  4732. Loc, TPOC_Other, 0, 0),
  4733. BestTemplate)) {
  4734. Ambiguous = true;
  4735. break;
  4736. }
  4737. }
  4738. if (!Ambiguous) {
  4739. // We found an answer. Return it.
  4740. return Best;
  4741. }
  4742. // Diagnose the ambiguity.
  4743. if (Complain) {
  4744. Diag(Loc, AmbigDiag);
  4745. // FIXME: Can we order the candidates in some sane way?
  4746. for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
  4747. PartialDiagnostic PD = CandidateDiag;
  4748. const auto *FD = cast<FunctionDecl>(*I);
  4749. PD << FD << getTemplateArgumentBindingsText(
  4750. FD->getPrimaryTemplate()->getTemplateParameters(),
  4751. *FD->getTemplateSpecializationArgs());
  4752. if (!TargetType.isNull())
  4753. HandleFunctionTypeMismatch(PD, FD->getType(), TargetType);
  4754. Diag((*I)->getLocation(), PD);
  4755. }
  4756. }
  4757. return SpecEnd;
  4758. }
  4759. /// Determine whether one partial specialization, P1, is at least as
  4760. /// specialized than another, P2.
  4761. ///
  4762. /// \tparam TemplateLikeDecl The kind of P2, which must be a
  4763. /// TemplateDecl or {Class,Var}TemplatePartialSpecializationDecl.
  4764. /// \param T1 The injected-class-name of P1 (faked for a variable template).
  4765. /// \param T2 The injected-class-name of P2 (faked for a variable template).
  4766. template<typename TemplateLikeDecl>
  4767. static bool isAtLeastAsSpecializedAs(Sema &S, QualType T1, QualType T2,
  4768. TemplateLikeDecl *P2,
  4769. TemplateDeductionInfo &Info) {
  4770. // C++ [temp.class.order]p1:
  4771. // For two class template partial specializations, the first is at least as
  4772. // specialized as the second if, given the following rewrite to two
  4773. // function templates, the first function template is at least as
  4774. // specialized as the second according to the ordering rules for function
  4775. // templates (14.6.6.2):
  4776. // - the first function template has the same template parameters as the
  4777. // first partial specialization and has a single function parameter
  4778. // whose type is a class template specialization with the template
  4779. // arguments of the first partial specialization, and
  4780. // - the second function template has the same template parameters as the
  4781. // second partial specialization and has a single function parameter
  4782. // whose type is a class template specialization with the template
  4783. // arguments of the second partial specialization.
  4784. //
  4785. // Rather than synthesize function templates, we merely perform the
  4786. // equivalent partial ordering by performing deduction directly on
  4787. // the template arguments of the class template partial
  4788. // specializations. This computation is slightly simpler than the
  4789. // general problem of function template partial ordering, because
  4790. // class template partial specializations are more constrained. We
  4791. // know that every template parameter is deducible from the class
  4792. // template partial specialization's template arguments, for
  4793. // example.
  4794. SmallVector<DeducedTemplateArgument, 4> Deduced;
  4795. // Determine whether P1 is at least as specialized as P2.
  4796. Deduced.resize(P2->getTemplateParameters()->size());
  4797. if (DeduceTemplateArgumentsByTypeMatch(S, P2->getTemplateParameters(),
  4798. T2, T1, Info, Deduced, TDF_None,
  4799. /*PartialOrdering=*/true))
  4800. return false;
  4801. SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
  4802. Deduced.end());
  4803. Sema::InstantiatingTemplate Inst(S, Info.getLocation(), P2, DeducedArgs,
  4804. Info);
  4805. if (Inst.isInvalid())
  4806. return false;
  4807. const auto *TST1 = cast<TemplateSpecializationType>(T1);
  4808. bool AtLeastAsSpecialized;
  4809. S.runWithSufficientStackSpace(Info.getLocation(), [&] {
  4810. AtLeastAsSpecialized = !FinishTemplateArgumentDeduction(
  4811. S, P2, /*IsPartialOrdering=*/true,
  4812. TemplateArgumentList(TemplateArgumentList::OnStack,
  4813. TST1->template_arguments()),
  4814. Deduced, Info);
  4815. });
  4816. return AtLeastAsSpecialized;
  4817. }
  4818. namespace {
  4819. // A dummy class to return nullptr instead of P2 when performing "more
  4820. // specialized than primary" check.
  4821. struct GetP2 {
  4822. template <typename T1, typename T2,
  4823. std::enable_if_t<std::is_same_v<T1, T2>, bool> = true>
  4824. T2 *operator()(T1 *, T2 *P2) {
  4825. return P2;
  4826. }
  4827. template <typename T1, typename T2,
  4828. std::enable_if_t<!std::is_same_v<T1, T2>, bool> = true>
  4829. T1 *operator()(T1 *, T2 *) {
  4830. return nullptr;
  4831. }
  4832. };
  4833. // The assumption is that two template argument lists have the same size.
  4834. struct TemplateArgumentListAreEqual {
  4835. ASTContext &Ctx;
  4836. TemplateArgumentListAreEqual(ASTContext &Ctx) : Ctx(Ctx) {}
  4837. template <typename T1, typename T2,
  4838. std::enable_if_t<std::is_same_v<T1, T2>, bool> = true>
  4839. bool operator()(T1 *PS1, T2 *PS2) {
  4840. ArrayRef<TemplateArgument> Args1 = PS1->getTemplateArgs().asArray(),
  4841. Args2 = PS2->getTemplateArgs().asArray();
  4842. for (unsigned I = 0, E = Args1.size(); I < E; ++I) {
  4843. // We use profile, instead of structural comparison of the arguments,
  4844. // because canonicalization can't do the right thing for dependent
  4845. // expressions.
  4846. llvm::FoldingSetNodeID IDA, IDB;
  4847. Args1[I].Profile(IDA, Ctx);
  4848. Args2[I].Profile(IDB, Ctx);
  4849. if (IDA != IDB)
  4850. return false;
  4851. }
  4852. return true;
  4853. }
  4854. template <typename T1, typename T2,
  4855. std::enable_if_t<!std::is_same_v<T1, T2>, bool> = true>
  4856. bool operator()(T1 *Spec, T2 *Primary) {
  4857. ArrayRef<TemplateArgument> Args1 = Spec->getTemplateArgs().asArray(),
  4858. Args2 = Primary->getInjectedTemplateArgs();
  4859. for (unsigned I = 0, E = Args1.size(); I < E; ++I) {
  4860. // We use profile, instead of structural comparison of the arguments,
  4861. // because canonicalization can't do the right thing for dependent
  4862. // expressions.
  4863. llvm::FoldingSetNodeID IDA, IDB;
  4864. Args1[I].Profile(IDA, Ctx);
  4865. // Unlike the specialization arguments, the injected arguments are not
  4866. // always canonical.
  4867. Ctx.getCanonicalTemplateArgument(Args2[I]).Profile(IDB, Ctx);
  4868. if (IDA != IDB)
  4869. return false;
  4870. }
  4871. return true;
  4872. }
  4873. };
  4874. } // namespace
  4875. /// Returns the more specialized template specialization between T1/P1 and
  4876. /// T2/P2.
  4877. /// - If IsMoreSpecialThanPrimaryCheck is true, T1/P1 is the partial
  4878. /// specialization and T2/P2 is the primary template.
  4879. /// - otherwise, both T1/P1 and T2/P2 are the partial specialization.
  4880. ///
  4881. /// \param T1 the type of the first template partial specialization
  4882. ///
  4883. /// \param T2 if IsMoreSpecialThanPrimaryCheck is true, the type of the second
  4884. /// template partial specialization; otherwise, the type of the
  4885. /// primary template.
  4886. ///
  4887. /// \param P1 the first template partial specialization
  4888. ///
  4889. /// \param P2 if IsMoreSpecialThanPrimaryCheck is true, the second template
  4890. /// partial specialization; otherwise, the primary template.
  4891. ///
  4892. /// \returns - If IsMoreSpecialThanPrimaryCheck is true, returns P1 if P1 is
  4893. /// more specialized, returns nullptr if P1 is not more specialized.
  4894. /// - otherwise, returns the more specialized template partial
  4895. /// specialization. If neither partial specialization is more
  4896. /// specialized, returns NULL.
  4897. template <typename TemplateLikeDecl, typename PrimaryDel>
  4898. static TemplateLikeDecl *
  4899. getMoreSpecialized(Sema &S, QualType T1, QualType T2, TemplateLikeDecl *P1,
  4900. PrimaryDel *P2, TemplateDeductionInfo &Info) {
  4901. constexpr bool IsMoreSpecialThanPrimaryCheck =
  4902. !std::is_same_v<TemplateLikeDecl, PrimaryDel>;
  4903. bool Better1 = isAtLeastAsSpecializedAs(S, T1, T2, P2, Info);
  4904. if (IsMoreSpecialThanPrimaryCheck && !Better1)
  4905. return nullptr;
  4906. bool Better2 = isAtLeastAsSpecializedAs(S, T2, T1, P1, Info);
  4907. if (IsMoreSpecialThanPrimaryCheck && !Better2)
  4908. return P1;
  4909. // C++ [temp.deduct.partial]p10:
  4910. // F is more specialized than G if F is at least as specialized as G and G
  4911. // is not at least as specialized as F.
  4912. if (Better1 != Better2) // We have a clear winner
  4913. return Better1 ? P1 : GetP2()(P1, P2);
  4914. if (!Better1 && !Better2)
  4915. return nullptr;
  4916. // This a speculative fix for CWG1432 (Similar to the fix for CWG1395) that
  4917. // there is no wording or even resolution for this issue.
  4918. auto *TST1 = cast<TemplateSpecializationType>(T1);
  4919. auto *TST2 = cast<TemplateSpecializationType>(T2);
  4920. const TemplateArgument &TA1 = TST1->template_arguments().back();
  4921. if (TA1.getKind() == TemplateArgument::Pack) {
  4922. assert(TST1->template_arguments().size() ==
  4923. TST2->template_arguments().size());
  4924. const TemplateArgument &TA2 = TST2->template_arguments().back();
  4925. assert(TA2.getKind() == TemplateArgument::Pack);
  4926. unsigned PackSize1 = TA1.pack_size();
  4927. unsigned PackSize2 = TA2.pack_size();
  4928. bool IsPackExpansion1 =
  4929. PackSize1 && TA1.pack_elements().back().isPackExpansion();
  4930. bool IsPackExpansion2 =
  4931. PackSize2 && TA2.pack_elements().back().isPackExpansion();
  4932. if (PackSize1 != PackSize2 && IsPackExpansion1 != IsPackExpansion2) {
  4933. if (PackSize1 > PackSize2 && IsPackExpansion1)
  4934. return GetP2()(P1, P2);
  4935. if (PackSize1 < PackSize2 && IsPackExpansion2)
  4936. return P1;
  4937. }
  4938. }
  4939. if (!S.Context.getLangOpts().CPlusPlus20)
  4940. return nullptr;
  4941. // Match GCC on not implementing [temp.func.order]p6.2.1.
  4942. // C++20 [temp.func.order]p6:
  4943. // If deduction against the other template succeeds for both transformed
  4944. // templates, constraints can be considered as follows:
  4945. TemplateParameterList *TPL1 = P1->getTemplateParameters();
  4946. TemplateParameterList *TPL2 = P2->getTemplateParameters();
  4947. if (TPL1->size() != TPL2->size())
  4948. return nullptr;
  4949. // C++20 [temp.func.order]p6.2.2:
  4950. // Otherwise, if the corresponding template-parameters of the
  4951. // template-parameter-lists are not equivalent ([temp.over.link]) or if the
  4952. // function parameters that positionally correspond between the two
  4953. // templates are not of the same type, neither template is more specialized
  4954. // than the other.
  4955. if (!S.TemplateParameterListsAreEqual(
  4956. TPL1, TPL2, false, Sema::TPL_TemplateMatch, SourceLocation(), true))
  4957. return nullptr;
  4958. if (!TemplateArgumentListAreEqual(S.getASTContext())(P1, P2))
  4959. return nullptr;
  4960. llvm::SmallVector<const Expr *, 3> AC1, AC2;
  4961. P1->getAssociatedConstraints(AC1);
  4962. P2->getAssociatedConstraints(AC2);
  4963. bool AtLeastAsConstrained1, AtLeastAsConstrained2;
  4964. if (S.IsAtLeastAsConstrained(P1, AC1, P2, AC2, AtLeastAsConstrained1) ||
  4965. (IsMoreSpecialThanPrimaryCheck && !AtLeastAsConstrained1))
  4966. return nullptr;
  4967. if (S.IsAtLeastAsConstrained(P2, AC2, P1, AC1, AtLeastAsConstrained2))
  4968. return nullptr;
  4969. if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
  4970. return nullptr;
  4971. return AtLeastAsConstrained1 ? P1 : GetP2()(P1, P2);
  4972. }
  4973. /// Returns the more specialized class template partial specialization
  4974. /// according to the rules of partial ordering of class template partial
  4975. /// specializations (C++ [temp.class.order]).
  4976. ///
  4977. /// \param PS1 the first class template partial specialization
  4978. ///
  4979. /// \param PS2 the second class template partial specialization
  4980. ///
  4981. /// \returns the more specialized class template partial specialization. If
  4982. /// neither partial specialization is more specialized, returns NULL.
  4983. ClassTemplatePartialSpecializationDecl *
  4984. Sema::getMoreSpecializedPartialSpecialization(
  4985. ClassTemplatePartialSpecializationDecl *PS1,
  4986. ClassTemplatePartialSpecializationDecl *PS2,
  4987. SourceLocation Loc) {
  4988. QualType PT1 = PS1->getInjectedSpecializationType();
  4989. QualType PT2 = PS2->getInjectedSpecializationType();
  4990. TemplateDeductionInfo Info(Loc);
  4991. return getMoreSpecialized(*this, PT1, PT2, PS1, PS2, Info);
  4992. }
  4993. bool Sema::isMoreSpecializedThanPrimary(
  4994. ClassTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
  4995. ClassTemplateDecl *Primary = Spec->getSpecializedTemplate();
  4996. QualType PrimaryT = Primary->getInjectedClassNameSpecialization();
  4997. QualType PartialT = Spec->getInjectedSpecializationType();
  4998. ClassTemplatePartialSpecializationDecl *MaybeSpec =
  4999. getMoreSpecialized(*this, PartialT, PrimaryT, Spec, Primary, Info);
  5000. if (MaybeSpec)
  5001. Info.clearSFINAEDiagnostic();
  5002. return MaybeSpec;
  5003. }
  5004. VarTemplatePartialSpecializationDecl *
  5005. Sema::getMoreSpecializedPartialSpecialization(
  5006. VarTemplatePartialSpecializationDecl *PS1,
  5007. VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) {
  5008. // Pretend the variable template specializations are class template
  5009. // specializations and form a fake injected class name type for comparison.
  5010. assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
  5011. "the partial specializations being compared should specialize"
  5012. " the same template.");
  5013. TemplateName Name(PS1->getSpecializedTemplate());
  5014. TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
  5015. QualType PT1 = Context.getTemplateSpecializationType(
  5016. CanonTemplate, PS1->getTemplateArgs().asArray());
  5017. QualType PT2 = Context.getTemplateSpecializationType(
  5018. CanonTemplate, PS2->getTemplateArgs().asArray());
  5019. TemplateDeductionInfo Info(Loc);
  5020. return getMoreSpecialized(*this, PT1, PT2, PS1, PS2, Info);
  5021. }
  5022. bool Sema::isMoreSpecializedThanPrimary(
  5023. VarTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
  5024. VarTemplateDecl *Primary = Spec->getSpecializedTemplate();
  5025. TemplateName CanonTemplate =
  5026. Context.getCanonicalTemplateName(TemplateName(Primary));
  5027. QualType PrimaryT = Context.getTemplateSpecializationType(
  5028. CanonTemplate, Primary->getInjectedTemplateArgs());
  5029. QualType PartialT = Context.getTemplateSpecializationType(
  5030. CanonTemplate, Spec->getTemplateArgs().asArray());
  5031. VarTemplatePartialSpecializationDecl *MaybeSpec =
  5032. getMoreSpecialized(*this, PartialT, PrimaryT, Spec, Primary, Info);
  5033. if (MaybeSpec)
  5034. Info.clearSFINAEDiagnostic();
  5035. return MaybeSpec;
  5036. }
  5037. bool Sema::isTemplateTemplateParameterAtLeastAsSpecializedAs(
  5038. TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc) {
  5039. // C++1z [temp.arg.template]p4: (DR 150)
  5040. // A template template-parameter P is at least as specialized as a
  5041. // template template-argument A if, given the following rewrite to two
  5042. // function templates...
  5043. // Rather than synthesize function templates, we merely perform the
  5044. // equivalent partial ordering by performing deduction directly on
  5045. // the template parameter lists of the template template parameters.
  5046. //
  5047. // Given an invented class template X with the template parameter list of
  5048. // A (including default arguments):
  5049. TemplateName X = Context.getCanonicalTemplateName(TemplateName(AArg));
  5050. TemplateParameterList *A = AArg->getTemplateParameters();
  5051. // - Each function template has a single function parameter whose type is
  5052. // a specialization of X with template arguments corresponding to the
  5053. // template parameters from the respective function template
  5054. SmallVector<TemplateArgument, 8> AArgs;
  5055. Context.getInjectedTemplateArgs(A, AArgs);
  5056. // Check P's arguments against A's parameter list. This will fill in default
  5057. // template arguments as needed. AArgs are already correct by construction.
  5058. // We can't just use CheckTemplateIdType because that will expand alias
  5059. // templates.
  5060. SmallVector<TemplateArgument, 4> PArgs;
  5061. {
  5062. SFINAETrap Trap(*this);
  5063. Context.getInjectedTemplateArgs(P, PArgs);
  5064. TemplateArgumentListInfo PArgList(P->getLAngleLoc(),
  5065. P->getRAngleLoc());
  5066. for (unsigned I = 0, N = P->size(); I != N; ++I) {
  5067. // Unwrap packs that getInjectedTemplateArgs wrapped around pack
  5068. // expansions, to form an "as written" argument list.
  5069. TemplateArgument Arg = PArgs[I];
  5070. if (Arg.getKind() == TemplateArgument::Pack) {
  5071. assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion());
  5072. Arg = *Arg.pack_begin();
  5073. }
  5074. PArgList.addArgument(getTrivialTemplateArgumentLoc(
  5075. Arg, QualType(), P->getParam(I)->getLocation()));
  5076. }
  5077. PArgs.clear();
  5078. // C++1z [temp.arg.template]p3:
  5079. // If the rewrite produces an invalid type, then P is not at least as
  5080. // specialized as A.
  5081. SmallVector<TemplateArgument, 4> SugaredPArgs;
  5082. if (CheckTemplateArgumentList(AArg, Loc, PArgList, false, SugaredPArgs,
  5083. PArgs) ||
  5084. Trap.hasErrorOccurred())
  5085. return false;
  5086. }
  5087. QualType AType = Context.getCanonicalTemplateSpecializationType(X, AArgs);
  5088. QualType PType = Context.getCanonicalTemplateSpecializationType(X, PArgs);
  5089. // ... the function template corresponding to P is at least as specialized
  5090. // as the function template corresponding to A according to the partial
  5091. // ordering rules for function templates.
  5092. TemplateDeductionInfo Info(Loc, A->getDepth());
  5093. return isAtLeastAsSpecializedAs(*this, PType, AType, AArg, Info);
  5094. }
  5095. namespace {
  5096. struct MarkUsedTemplateParameterVisitor :
  5097. RecursiveASTVisitor<MarkUsedTemplateParameterVisitor> {
  5098. llvm::SmallBitVector &Used;
  5099. unsigned Depth;
  5100. MarkUsedTemplateParameterVisitor(llvm::SmallBitVector &Used,
  5101. unsigned Depth)
  5102. : Used(Used), Depth(Depth) { }
  5103. bool VisitTemplateTypeParmType(TemplateTypeParmType *T) {
  5104. if (T->getDepth() == Depth)
  5105. Used[T->getIndex()] = true;
  5106. return true;
  5107. }
  5108. bool TraverseTemplateName(TemplateName Template) {
  5109. if (auto *TTP = llvm::dyn_cast_or_null<TemplateTemplateParmDecl>(
  5110. Template.getAsTemplateDecl()))
  5111. if (TTP->getDepth() == Depth)
  5112. Used[TTP->getIndex()] = true;
  5113. RecursiveASTVisitor<MarkUsedTemplateParameterVisitor>::
  5114. TraverseTemplateName(Template);
  5115. return true;
  5116. }
  5117. bool VisitDeclRefExpr(DeclRefExpr *E) {
  5118. if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
  5119. if (NTTP->getDepth() == Depth)
  5120. Used[NTTP->getIndex()] = true;
  5121. return true;
  5122. }
  5123. };
  5124. }
  5125. /// Mark the template parameters that are used by the given
  5126. /// expression.
  5127. static void
  5128. MarkUsedTemplateParameters(ASTContext &Ctx,
  5129. const Expr *E,
  5130. bool OnlyDeduced,
  5131. unsigned Depth,
  5132. llvm::SmallBitVector &Used) {
  5133. if (!OnlyDeduced) {
  5134. MarkUsedTemplateParameterVisitor(Used, Depth)
  5135. .TraverseStmt(const_cast<Expr *>(E));
  5136. return;
  5137. }
  5138. // We can deduce from a pack expansion.
  5139. if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
  5140. E = Expansion->getPattern();
  5141. const NonTypeTemplateParmDecl *NTTP = getDeducedParameterFromExpr(E, Depth);
  5142. if (!NTTP)
  5143. return;
  5144. if (NTTP->getDepth() == Depth)
  5145. Used[NTTP->getIndex()] = true;
  5146. // In C++17 mode, additional arguments may be deduced from the type of a
  5147. // non-type argument.
  5148. if (Ctx.getLangOpts().CPlusPlus17)
  5149. MarkUsedTemplateParameters(Ctx, NTTP->getType(), OnlyDeduced, Depth, Used);
  5150. }
  5151. /// Mark the template parameters that are used by the given
  5152. /// nested name specifier.
  5153. static void
  5154. MarkUsedTemplateParameters(ASTContext &Ctx,
  5155. NestedNameSpecifier *NNS,
  5156. bool OnlyDeduced,
  5157. unsigned Depth,
  5158. llvm::SmallBitVector &Used) {
  5159. if (!NNS)
  5160. return;
  5161. MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
  5162. Used);
  5163. MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0),
  5164. OnlyDeduced, Depth, Used);
  5165. }
  5166. /// Mark the template parameters that are used by the given
  5167. /// template name.
  5168. static void
  5169. MarkUsedTemplateParameters(ASTContext &Ctx,
  5170. TemplateName Name,
  5171. bool OnlyDeduced,
  5172. unsigned Depth,
  5173. llvm::SmallBitVector &Used) {
  5174. if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
  5175. if (TemplateTemplateParmDecl *TTP
  5176. = dyn_cast<TemplateTemplateParmDecl>(Template)) {
  5177. if (TTP->getDepth() == Depth)
  5178. Used[TTP->getIndex()] = true;
  5179. }
  5180. return;
  5181. }
  5182. if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
  5183. MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
  5184. Depth, Used);
  5185. if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
  5186. MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
  5187. Depth, Used);
  5188. }
  5189. /// Mark the template parameters that are used by the given
  5190. /// type.
  5191. static void
  5192. MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
  5193. bool OnlyDeduced,
  5194. unsigned Depth,
  5195. llvm::SmallBitVector &Used) {
  5196. if (T.isNull())
  5197. return;
  5198. // Non-dependent types have nothing deducible
  5199. if (!T->isDependentType())
  5200. return;
  5201. T = Ctx.getCanonicalType(T);
  5202. switch (T->getTypeClass()) {
  5203. case Type::Pointer:
  5204. MarkUsedTemplateParameters(Ctx,
  5205. cast<PointerType>(T)->getPointeeType(),
  5206. OnlyDeduced,
  5207. Depth,
  5208. Used);
  5209. break;
  5210. case Type::BlockPointer:
  5211. MarkUsedTemplateParameters(Ctx,
  5212. cast<BlockPointerType>(T)->getPointeeType(),
  5213. OnlyDeduced,
  5214. Depth,
  5215. Used);
  5216. break;
  5217. case Type::LValueReference:
  5218. case Type::RValueReference:
  5219. MarkUsedTemplateParameters(Ctx,
  5220. cast<ReferenceType>(T)->getPointeeType(),
  5221. OnlyDeduced,
  5222. Depth,
  5223. Used);
  5224. break;
  5225. case Type::MemberPointer: {
  5226. const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
  5227. MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
  5228. Depth, Used);
  5229. MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
  5230. OnlyDeduced, Depth, Used);
  5231. break;
  5232. }
  5233. case Type::DependentSizedArray:
  5234. MarkUsedTemplateParameters(Ctx,
  5235. cast<DependentSizedArrayType>(T)->getSizeExpr(),
  5236. OnlyDeduced, Depth, Used);
  5237. // Fall through to check the element type
  5238. [[fallthrough]];
  5239. case Type::ConstantArray:
  5240. case Type::IncompleteArray:
  5241. MarkUsedTemplateParameters(Ctx,
  5242. cast<ArrayType>(T)->getElementType(),
  5243. OnlyDeduced, Depth, Used);
  5244. break;
  5245. case Type::Vector:
  5246. case Type::ExtVector:
  5247. MarkUsedTemplateParameters(Ctx,
  5248. cast<VectorType>(T)->getElementType(),
  5249. OnlyDeduced, Depth, Used);
  5250. break;
  5251. case Type::DependentVector: {
  5252. const auto *VecType = cast<DependentVectorType>(T);
  5253. MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
  5254. Depth, Used);
  5255. MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced, Depth,
  5256. Used);
  5257. break;
  5258. }
  5259. case Type::DependentSizedExtVector: {
  5260. const DependentSizedExtVectorType *VecType
  5261. = cast<DependentSizedExtVectorType>(T);
  5262. MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
  5263. Depth, Used);
  5264. MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
  5265. Depth, Used);
  5266. break;
  5267. }
  5268. case Type::DependentAddressSpace: {
  5269. const DependentAddressSpaceType *DependentASType =
  5270. cast<DependentAddressSpaceType>(T);
  5271. MarkUsedTemplateParameters(Ctx, DependentASType->getPointeeType(),
  5272. OnlyDeduced, Depth, Used);
  5273. MarkUsedTemplateParameters(Ctx,
  5274. DependentASType->getAddrSpaceExpr(),
  5275. OnlyDeduced, Depth, Used);
  5276. break;
  5277. }
  5278. case Type::ConstantMatrix: {
  5279. const ConstantMatrixType *MatType = cast<ConstantMatrixType>(T);
  5280. MarkUsedTemplateParameters(Ctx, MatType->getElementType(), OnlyDeduced,
  5281. Depth, Used);
  5282. break;
  5283. }
  5284. case Type::DependentSizedMatrix: {
  5285. const DependentSizedMatrixType *MatType = cast<DependentSizedMatrixType>(T);
  5286. MarkUsedTemplateParameters(Ctx, MatType->getElementType(), OnlyDeduced,
  5287. Depth, Used);
  5288. MarkUsedTemplateParameters(Ctx, MatType->getRowExpr(), OnlyDeduced, Depth,
  5289. Used);
  5290. MarkUsedTemplateParameters(Ctx, MatType->getColumnExpr(), OnlyDeduced,
  5291. Depth, Used);
  5292. break;
  5293. }
  5294. case Type::FunctionProto: {
  5295. const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
  5296. MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
  5297. Used);
  5298. for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I) {
  5299. // C++17 [temp.deduct.type]p5:
  5300. // The non-deduced contexts are: [...]
  5301. // -- A function parameter pack that does not occur at the end of the
  5302. // parameter-declaration-list.
  5303. if (!OnlyDeduced || I + 1 == N ||
  5304. !Proto->getParamType(I)->getAs<PackExpansionType>()) {
  5305. MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
  5306. Depth, Used);
  5307. } else {
  5308. // FIXME: C++17 [temp.deduct.call]p1:
  5309. // When a function parameter pack appears in a non-deduced context,
  5310. // the type of that pack is never deduced.
  5311. //
  5312. // We should also track a set of "never deduced" parameters, and
  5313. // subtract that from the list of deduced parameters after marking.
  5314. }
  5315. }
  5316. if (auto *E = Proto->getNoexceptExpr())
  5317. MarkUsedTemplateParameters(Ctx, E, OnlyDeduced, Depth, Used);
  5318. break;
  5319. }
  5320. case Type::TemplateTypeParm: {
  5321. const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
  5322. if (TTP->getDepth() == Depth)
  5323. Used[TTP->getIndex()] = true;
  5324. break;
  5325. }
  5326. case Type::SubstTemplateTypeParmPack: {
  5327. const SubstTemplateTypeParmPackType *Subst
  5328. = cast<SubstTemplateTypeParmPackType>(T);
  5329. if (Subst->getReplacedParameter()->getDepth() == Depth)
  5330. Used[Subst->getIndex()] = true;
  5331. MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(),
  5332. OnlyDeduced, Depth, Used);
  5333. break;
  5334. }
  5335. case Type::InjectedClassName:
  5336. T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
  5337. [[fallthrough]];
  5338. case Type::TemplateSpecialization: {
  5339. const TemplateSpecializationType *Spec
  5340. = cast<TemplateSpecializationType>(T);
  5341. MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
  5342. Depth, Used);
  5343. // C++0x [temp.deduct.type]p9:
  5344. // If the template argument list of P contains a pack expansion that is
  5345. // not the last template argument, the entire template argument list is a
  5346. // non-deduced context.
  5347. if (OnlyDeduced &&
  5348. hasPackExpansionBeforeEnd(Spec->template_arguments()))
  5349. break;
  5350. for (const auto &Arg : Spec->template_arguments())
  5351. MarkUsedTemplateParameters(Ctx, Arg, OnlyDeduced, Depth, Used);
  5352. break;
  5353. }
  5354. case Type::Complex:
  5355. if (!OnlyDeduced)
  5356. MarkUsedTemplateParameters(Ctx,
  5357. cast<ComplexType>(T)->getElementType(),
  5358. OnlyDeduced, Depth, Used);
  5359. break;
  5360. case Type::Atomic:
  5361. if (!OnlyDeduced)
  5362. MarkUsedTemplateParameters(Ctx,
  5363. cast<AtomicType>(T)->getValueType(),
  5364. OnlyDeduced, Depth, Used);
  5365. break;
  5366. case Type::DependentName:
  5367. if (!OnlyDeduced)
  5368. MarkUsedTemplateParameters(Ctx,
  5369. cast<DependentNameType>(T)->getQualifier(),
  5370. OnlyDeduced, Depth, Used);
  5371. break;
  5372. case Type::DependentTemplateSpecialization: {
  5373. // C++14 [temp.deduct.type]p5:
  5374. // The non-deduced contexts are:
  5375. // -- The nested-name-specifier of a type that was specified using a
  5376. // qualified-id
  5377. //
  5378. // C++14 [temp.deduct.type]p6:
  5379. // When a type name is specified in a way that includes a non-deduced
  5380. // context, all of the types that comprise that type name are also
  5381. // non-deduced.
  5382. if (OnlyDeduced)
  5383. break;
  5384. const DependentTemplateSpecializationType *Spec
  5385. = cast<DependentTemplateSpecializationType>(T);
  5386. MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
  5387. OnlyDeduced, Depth, Used);
  5388. for (const auto &Arg : Spec->template_arguments())
  5389. MarkUsedTemplateParameters(Ctx, Arg, OnlyDeduced, Depth, Used);
  5390. break;
  5391. }
  5392. case Type::TypeOf:
  5393. if (!OnlyDeduced)
  5394. MarkUsedTemplateParameters(Ctx, cast<TypeOfType>(T)->getUnmodifiedType(),
  5395. OnlyDeduced, Depth, Used);
  5396. break;
  5397. case Type::TypeOfExpr:
  5398. if (!OnlyDeduced)
  5399. MarkUsedTemplateParameters(Ctx,
  5400. cast<TypeOfExprType>(T)->getUnderlyingExpr(),
  5401. OnlyDeduced, Depth, Used);
  5402. break;
  5403. case Type::Decltype:
  5404. if (!OnlyDeduced)
  5405. MarkUsedTemplateParameters(Ctx,
  5406. cast<DecltypeType>(T)->getUnderlyingExpr(),
  5407. OnlyDeduced, Depth, Used);
  5408. break;
  5409. case Type::UnaryTransform:
  5410. if (!OnlyDeduced)
  5411. MarkUsedTemplateParameters(Ctx,
  5412. cast<UnaryTransformType>(T)->getUnderlyingType(),
  5413. OnlyDeduced, Depth, Used);
  5414. break;
  5415. case Type::PackExpansion:
  5416. MarkUsedTemplateParameters(Ctx,
  5417. cast<PackExpansionType>(T)->getPattern(),
  5418. OnlyDeduced, Depth, Used);
  5419. break;
  5420. case Type::Auto:
  5421. case Type::DeducedTemplateSpecialization:
  5422. MarkUsedTemplateParameters(Ctx,
  5423. cast<DeducedType>(T)->getDeducedType(),
  5424. OnlyDeduced, Depth, Used);
  5425. break;
  5426. case Type::DependentBitInt:
  5427. MarkUsedTemplateParameters(Ctx,
  5428. cast<DependentBitIntType>(T)->getNumBitsExpr(),
  5429. OnlyDeduced, Depth, Used);
  5430. break;
  5431. // None of these types have any template parameters in them.
  5432. case Type::Builtin:
  5433. case Type::VariableArray:
  5434. case Type::FunctionNoProto:
  5435. case Type::Record:
  5436. case Type::Enum:
  5437. case Type::ObjCInterface:
  5438. case Type::ObjCObject:
  5439. case Type::ObjCObjectPointer:
  5440. case Type::UnresolvedUsing:
  5441. case Type::Pipe:
  5442. case Type::BitInt:
  5443. #define TYPE(Class, Base)
  5444. #define ABSTRACT_TYPE(Class, Base)
  5445. #define DEPENDENT_TYPE(Class, Base)
  5446. #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
  5447. #include "clang/AST/TypeNodes.inc"
  5448. break;
  5449. }
  5450. }
  5451. /// Mark the template parameters that are used by this
  5452. /// template argument.
  5453. static void
  5454. MarkUsedTemplateParameters(ASTContext &Ctx,
  5455. const TemplateArgument &TemplateArg,
  5456. bool OnlyDeduced,
  5457. unsigned Depth,
  5458. llvm::SmallBitVector &Used) {
  5459. switch (TemplateArg.getKind()) {
  5460. case TemplateArgument::Null:
  5461. case TemplateArgument::Integral:
  5462. case TemplateArgument::Declaration:
  5463. break;
  5464. case TemplateArgument::NullPtr:
  5465. MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced,
  5466. Depth, Used);
  5467. break;
  5468. case TemplateArgument::Type:
  5469. MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
  5470. Depth, Used);
  5471. break;
  5472. case TemplateArgument::Template:
  5473. case TemplateArgument::TemplateExpansion:
  5474. MarkUsedTemplateParameters(Ctx,
  5475. TemplateArg.getAsTemplateOrTemplatePattern(),
  5476. OnlyDeduced, Depth, Used);
  5477. break;
  5478. case TemplateArgument::Expression:
  5479. MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
  5480. Depth, Used);
  5481. break;
  5482. case TemplateArgument::Pack:
  5483. for (const auto &P : TemplateArg.pack_elements())
  5484. MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
  5485. break;
  5486. }
  5487. }
  5488. /// Mark which template parameters are used in a given expression.
  5489. ///
  5490. /// \param E the expression from which template parameters will be deduced.
  5491. ///
  5492. /// \param Used a bit vector whose elements will be set to \c true
  5493. /// to indicate when the corresponding template parameter will be
  5494. /// deduced.
  5495. void
  5496. Sema::MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
  5497. unsigned Depth,
  5498. llvm::SmallBitVector &Used) {
  5499. ::MarkUsedTemplateParameters(Context, E, OnlyDeduced, Depth, Used);
  5500. }
  5501. /// Mark which template parameters can be deduced from a given
  5502. /// template argument list.
  5503. ///
  5504. /// \param TemplateArgs the template argument list from which template
  5505. /// parameters will be deduced.
  5506. ///
  5507. /// \param Used a bit vector whose elements will be set to \c true
  5508. /// to indicate when the corresponding template parameter will be
  5509. /// deduced.
  5510. void
  5511. Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
  5512. bool OnlyDeduced, unsigned Depth,
  5513. llvm::SmallBitVector &Used) {
  5514. // C++0x [temp.deduct.type]p9:
  5515. // If the template argument list of P contains a pack expansion that is not
  5516. // the last template argument, the entire template argument list is a
  5517. // non-deduced context.
  5518. if (OnlyDeduced &&
  5519. hasPackExpansionBeforeEnd(TemplateArgs.asArray()))
  5520. return;
  5521. for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
  5522. ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
  5523. Depth, Used);
  5524. }
  5525. /// Marks all of the template parameters that will be deduced by a
  5526. /// call to the given function template.
  5527. void Sema::MarkDeducedTemplateParameters(
  5528. ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
  5529. llvm::SmallBitVector &Deduced) {
  5530. TemplateParameterList *TemplateParams
  5531. = FunctionTemplate->getTemplateParameters();
  5532. Deduced.clear();
  5533. Deduced.resize(TemplateParams->size());
  5534. FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
  5535. for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
  5536. ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
  5537. true, TemplateParams->getDepth(), Deduced);
  5538. }
  5539. bool hasDeducibleTemplateParameters(Sema &S,
  5540. FunctionTemplateDecl *FunctionTemplate,
  5541. QualType T) {
  5542. if (!T->isDependentType())
  5543. return false;
  5544. TemplateParameterList *TemplateParams
  5545. = FunctionTemplate->getTemplateParameters();
  5546. llvm::SmallBitVector Deduced(TemplateParams->size());
  5547. ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
  5548. Deduced);
  5549. return Deduced.any();
  5550. }