SemaTemplateDeduction.cpp 201 KB

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