SemaTemplateDeduction.cpp 229 KB

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