SemaTemplateDeduction.cpp 201 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023
  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. /// \brief Given a function declaration (e.g. a generic lambda conversion
  3146. /// function) that contains an 'auto' in its result type, substitute it
  3147. /// with TypeToReplaceAutoWith. Be careful to pass in the type you want
  3148. /// to replace 'auto' with and not the actual result type you want
  3149. /// to set the function to.
  3150. static inline void
  3151. SubstAutoWithinFunctionReturnType(FunctionDecl *F,
  3152. QualType TypeToReplaceAutoWith, Sema &S) {
  3153. assert(!TypeToReplaceAutoWith->getContainedAutoType());
  3154. QualType AutoResultType = F->getReturnType();
  3155. assert(AutoResultType->getContainedAutoType());
  3156. QualType DeducedResultType = S.SubstAutoType(AutoResultType,
  3157. TypeToReplaceAutoWith);
  3158. S.Context.adjustDeducedFunctionResultType(F, DeducedResultType);
  3159. }
  3160. /// \brief Given a specialized conversion operator of a generic lambda
  3161. /// create the corresponding specializations of the call operator and
  3162. /// the static-invoker. If the return type of the call operator is auto,
  3163. /// deduce its return type and check if that matches the
  3164. /// return type of the destination function ptr.
  3165. static inline Sema::TemplateDeductionResult
  3166. SpecializeCorrespondingLambdaCallOperatorAndInvoker(
  3167. CXXConversionDecl *ConversionSpecialized,
  3168. SmallVectorImpl<DeducedTemplateArgument> &DeducedArguments,
  3169. QualType ReturnTypeOfDestFunctionPtr,
  3170. TemplateDeductionInfo &TDInfo,
  3171. Sema &S) {
  3172. // HLSL Change Start
  3173. // No support for lambdas.
  3174. return Sema::TDK_Invalid;
  3175. #if 0
  3176. // HLSL Change Ends
  3177. CXXRecordDecl *LambdaClass = ConversionSpecialized->getParent();
  3178. assert(LambdaClass && LambdaClass->isGenericLambda());
  3179. CXXMethodDecl *CallOpGeneric = LambdaClass->getLambdaCallOperator();
  3180. QualType CallOpResultType = CallOpGeneric->getReturnType();
  3181. const bool GenericLambdaCallOperatorHasDeducedReturnType =
  3182. CallOpResultType->getContainedAutoType();
  3183. FunctionTemplateDecl *CallOpTemplate =
  3184. CallOpGeneric->getDescribedFunctionTemplate();
  3185. FunctionDecl *CallOpSpecialized = nullptr;
  3186. // Use the deduced arguments of the conversion function, to specialize our
  3187. // generic lambda's call operator.
  3188. if (Sema::TemplateDeductionResult Result
  3189. = S.FinishTemplateArgumentDeduction(CallOpTemplate,
  3190. DeducedArguments,
  3191. 0, CallOpSpecialized, TDInfo))
  3192. return Result;
  3193. // If we need to deduce the return type, do so (instantiates the callop).
  3194. if (GenericLambdaCallOperatorHasDeducedReturnType &&
  3195. CallOpSpecialized->getReturnType()->isUndeducedType())
  3196. S.DeduceReturnType(CallOpSpecialized,
  3197. CallOpSpecialized->getPointOfInstantiation(),
  3198. /*Diagnose*/ true);
  3199. // Check to see if the return type of the destination ptr-to-function
  3200. // matches the return type of the call operator.
  3201. if (!S.Context.hasSameType(CallOpSpecialized->getReturnType(),
  3202. ReturnTypeOfDestFunctionPtr))
  3203. return Sema::TDK_NonDeducedMismatch;
  3204. // Since we have succeeded in matching the source and destination
  3205. // ptr-to-functions (now including return type), and have successfully
  3206. // specialized our corresponding call operator, we are ready to
  3207. // specialize the static invoker with the deduced arguments of our
  3208. // ptr-to-function.
  3209. FunctionDecl *InvokerSpecialized = nullptr;
  3210. FunctionTemplateDecl *InvokerTemplate = LambdaClass->
  3211. getLambdaStaticInvoker()->getDescribedFunctionTemplate();
  3212. #ifndef NDEBUG
  3213. Sema::TemplateDeductionResult LLVM_ATTRIBUTE_UNUSED Result =
  3214. #endif
  3215. S.FinishTemplateArgumentDeduction(InvokerTemplate, DeducedArguments, 0,
  3216. InvokerSpecialized, TDInfo);
  3217. assert(Result == Sema::TDK_Success &&
  3218. "If the call operator succeeded so should the invoker!");
  3219. // Set the result type to match the corresponding call operator
  3220. // specialization's result type.
  3221. if (GenericLambdaCallOperatorHasDeducedReturnType &&
  3222. InvokerSpecialized->getReturnType()->isUndeducedType()) {
  3223. // Be sure to get the type to replace 'auto' with and not
  3224. // the full result type of the call op specialization
  3225. // to substitute into the 'auto' of the invoker and conversion
  3226. // function.
  3227. // For e.g.
  3228. // int* (*fp)(int*) = [](auto* a) -> auto* { return a; };
  3229. // We don't want to subst 'int*' into 'auto' to get int**.
  3230. QualType TypeToReplaceAutoWith = CallOpSpecialized->getReturnType()
  3231. ->getContainedAutoType()
  3232. ->getDeducedType();
  3233. SubstAutoWithinFunctionReturnType(InvokerSpecialized,
  3234. TypeToReplaceAutoWith, S);
  3235. SubstAutoWithinFunctionReturnType(ConversionSpecialized,
  3236. TypeToReplaceAutoWith, S);
  3237. }
  3238. // Ensure that static invoker doesn't have a const qualifier.
  3239. // FIXME: When creating the InvokerTemplate in SemaLambda.cpp
  3240. // do not use the CallOperator's TypeSourceInfo which allows
  3241. // the const qualifier to leak through.
  3242. const FunctionProtoType *InvokerFPT = InvokerSpecialized->
  3243. getType().getTypePtr()->castAs<FunctionProtoType>();
  3244. FunctionProtoType::ExtProtoInfo EPI = InvokerFPT->getExtProtoInfo();
  3245. EPI.TypeQuals = 0;
  3246. InvokerSpecialized->setType(S.Context.getFunctionType(
  3247. InvokerFPT->getReturnType(), InvokerFPT->getParamTypes(), EPI));
  3248. return Sema::TDK_Success;
  3249. #endif // HLSL Change
  3250. }
  3251. /// \brief Deduce template arguments for a templated conversion
  3252. /// function (C++ [temp.deduct.conv]) and, if successful, produce a
  3253. /// conversion function template specialization.
  3254. Sema::TemplateDeductionResult
  3255. Sema::DeduceTemplateArguments(FunctionTemplateDecl *ConversionTemplate,
  3256. QualType ToType,
  3257. CXXConversionDecl *&Specialization,
  3258. TemplateDeductionInfo &Info) {
  3259. if (ConversionTemplate->isInvalidDecl())
  3260. return TDK_Invalid;
  3261. CXXConversionDecl *ConversionGeneric
  3262. = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
  3263. QualType FromType = ConversionGeneric->getConversionType();
  3264. // Canonicalize the types for deduction.
  3265. QualType P = Context.getCanonicalType(FromType);
  3266. QualType A = Context.getCanonicalType(ToType);
  3267. // C++0x [temp.deduct.conv]p2:
  3268. // If P is a reference type, the type referred to by P is used for
  3269. // type deduction.
  3270. if (const ReferenceType *PRef = P->getAs<ReferenceType>())
  3271. P = PRef->getPointeeType();
  3272. // C++0x [temp.deduct.conv]p4:
  3273. // [...] If A is a reference type, the type referred to by A is used
  3274. // for type deduction.
  3275. if (const ReferenceType *ARef = A->getAs<ReferenceType>())
  3276. A = ARef->getPointeeType().getUnqualifiedType();
  3277. // C++ [temp.deduct.conv]p3:
  3278. //
  3279. // If A is not a reference type:
  3280. else {
  3281. assert(!A->isReferenceType() && "Reference types were handled above");
  3282. // - If P is an array type, the pointer type produced by the
  3283. // array-to-pointer standard conversion (4.2) is used in place
  3284. // of P for type deduction; otherwise,
  3285. if (P->isArrayType())
  3286. P = Context.getArrayDecayedType(P);
  3287. // - If P is a function type, the pointer type produced by the
  3288. // function-to-pointer standard conversion (4.3) is used in
  3289. // place of P for type deduction; otherwise,
  3290. else if (P->isFunctionType())
  3291. P = Context.getPointerType(P);
  3292. // - If P is a cv-qualified type, the top level cv-qualifiers of
  3293. // P's type are ignored for type deduction.
  3294. else
  3295. P = P.getUnqualifiedType();
  3296. // C++0x [temp.deduct.conv]p4:
  3297. // If A is a cv-qualified type, the top level cv-qualifiers of A's
  3298. // type are ignored for type deduction. If A is a reference type, the type
  3299. // referred to by A is used for type deduction.
  3300. A = A.getUnqualifiedType();
  3301. }
  3302. // Unevaluated SFINAE context.
  3303. EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
  3304. SFINAETrap Trap(*this);
  3305. // C++ [temp.deduct.conv]p1:
  3306. // Template argument deduction is done by comparing the return
  3307. // type of the template conversion function (call it P) with the
  3308. // type that is required as the result of the conversion (call it
  3309. // A) as described in 14.8.2.4.
  3310. TemplateParameterList *TemplateParams
  3311. = ConversionTemplate->getTemplateParameters();
  3312. SmallVector<DeducedTemplateArgument, 4> Deduced;
  3313. Deduced.resize(TemplateParams->size());
  3314. // C++0x [temp.deduct.conv]p4:
  3315. // In general, the deduction process attempts to find template
  3316. // argument values that will make the deduced A identical to
  3317. // A. However, there are two cases that allow a difference:
  3318. unsigned TDF = 0;
  3319. // - If the original A is a reference type, A can be more
  3320. // cv-qualified than the deduced A (i.e., the type referred to
  3321. // by the reference)
  3322. if (ToType->isReferenceType())
  3323. TDF |= TDF_ParamWithReferenceType;
  3324. // - The deduced A can be another pointer or pointer to member
  3325. // type that can be converted to A via a qualification
  3326. // conversion.
  3327. //
  3328. // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
  3329. // both P and A are pointers or member pointers. In this case, we
  3330. // just ignore cv-qualifiers completely).
  3331. if ((P->isPointerType() && A->isPointerType()) ||
  3332. (P->isMemberPointerType() && A->isMemberPointerType()))
  3333. TDF |= TDF_IgnoreQualifiers;
  3334. if (TemplateDeductionResult Result
  3335. = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
  3336. P, A, Info, Deduced, TDF))
  3337. return Result;
  3338. // Create an Instantiation Scope for finalizing the operator.
  3339. LocalInstantiationScope InstScope(*this);
  3340. // Finish template argument deduction.
  3341. FunctionDecl *ConversionSpecialized = nullptr;
  3342. TemplateDeductionResult Result
  3343. = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
  3344. ConversionSpecialized, Info);
  3345. Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
  3346. // If the conversion operator is being invoked on a lambda closure to convert
  3347. // to a ptr-to-function, use the deduced arguments from the conversion
  3348. // function to specialize the corresponding call operator.
  3349. // e.g., int (*fp)(int) = [](auto a) { return a; };
  3350. if (Result == TDK_Success && isLambdaConversionOperator(ConversionGeneric)) {
  3351. // Get the return type of the destination ptr-to-function we are converting
  3352. // to. This is necessary for matching the lambda call operator's return
  3353. // type to that of the destination ptr-to-function's return type.
  3354. assert(A->isPointerType() &&
  3355. "Can only convert from lambda to ptr-to-function");
  3356. const FunctionType *ToFunType =
  3357. A->getPointeeType().getTypePtr()->getAs<FunctionType>();
  3358. const QualType DestFunctionPtrReturnType = ToFunType->getReturnType();
  3359. // Create the corresponding specializations of the call operator and
  3360. // the static-invoker; and if the return type is auto,
  3361. // deduce the return type and check if it matches the
  3362. // DestFunctionPtrReturnType.
  3363. // For instance:
  3364. // auto L = [](auto a) { return f(a); };
  3365. // int (*fp)(int) = L;
  3366. // char (*fp2)(int) = L; <-- Not OK.
  3367. Result = SpecializeCorrespondingLambdaCallOperatorAndInvoker(
  3368. Specialization, Deduced, DestFunctionPtrReturnType,
  3369. Info, *this);
  3370. }
  3371. return Result;
  3372. }
  3373. /// \brief Deduce template arguments for a function template when there is
  3374. /// nothing to deduce against (C++0x [temp.arg.explicit]p3).
  3375. ///
  3376. /// \param FunctionTemplate the function template for which we are performing
  3377. /// template argument deduction.
  3378. ///
  3379. /// \param ExplicitTemplateArgs the explicitly-specified template
  3380. /// arguments.
  3381. ///
  3382. /// \param Specialization if template argument deduction was successful,
  3383. /// this will be set to the function template specialization produced by
  3384. /// template argument deduction.
  3385. ///
  3386. /// \param Info the argument will be updated to provide additional information
  3387. /// about template argument deduction.
  3388. ///
  3389. /// \returns the result of template argument deduction.
  3390. Sema::TemplateDeductionResult
  3391. Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
  3392. TemplateArgumentListInfo *ExplicitTemplateArgs,
  3393. FunctionDecl *&Specialization,
  3394. TemplateDeductionInfo &Info,
  3395. bool InOverloadResolution) {
  3396. return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
  3397. QualType(), Specialization, Info,
  3398. InOverloadResolution);
  3399. }
  3400. namespace {
  3401. /// Substitute the 'auto' type specifier within a type for a given replacement
  3402. /// type.
  3403. class SubstituteAutoTransform :
  3404. public TreeTransform<SubstituteAutoTransform> {
  3405. QualType Replacement;
  3406. public:
  3407. SubstituteAutoTransform(Sema &SemaRef, QualType Replacement)
  3408. : TreeTransform<SubstituteAutoTransform>(SemaRef),
  3409. Replacement(Replacement) {}
  3410. QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
  3411. // If we're building the type pattern to deduce against, don't wrap the
  3412. // substituted type in an AutoType. Certain template deduction rules
  3413. // apply only when a template type parameter appears directly (and not if
  3414. // the parameter is found through desugaring). For instance:
  3415. // auto &&lref = lvalue;
  3416. // must transform into "rvalue reference to T" not "rvalue reference to
  3417. // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
  3418. if (!Replacement.isNull() && isa<TemplateTypeParmType>(Replacement)) {
  3419. QualType Result = Replacement;
  3420. TemplateTypeParmTypeLoc NewTL =
  3421. TLB.push<TemplateTypeParmTypeLoc>(Result);
  3422. NewTL.setNameLoc(TL.getNameLoc());
  3423. return Result;
  3424. } else {
  3425. bool Dependent =
  3426. !Replacement.isNull() && Replacement->isDependentType();
  3427. QualType Result =
  3428. SemaRef.Context.getAutoType(Dependent ? QualType() : Replacement,
  3429. TL.getTypePtr()->isDecltypeAuto(),
  3430. Dependent);
  3431. AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
  3432. NewTL.setNameLoc(TL.getNameLoc());
  3433. return Result;
  3434. }
  3435. }
  3436. ExprResult TransformLambdaExpr(LambdaExpr *E) {
  3437. // Lambdas never need to be transformed.
  3438. return E;
  3439. }
  3440. QualType Apply(TypeLoc TL) {
  3441. // Create some scratch storage for the transformed type locations.
  3442. // FIXME: We're just going to throw this information away. Don't build it.
  3443. TypeLocBuilder TLB;
  3444. TLB.reserve(TL.getFullDataSize());
  3445. return TransformType(TLB, TL);
  3446. }
  3447. };
  3448. }
  3449. Sema::DeduceAutoResult
  3450. Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init, QualType &Result) {
  3451. return DeduceAutoType(Type->getTypeLoc(), Init, Result);
  3452. }
  3453. /// \brief Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
  3454. ///
  3455. /// \param Type the type pattern using the auto type-specifier.
  3456. /// \param Init the initializer for the variable whose type is to be deduced.
  3457. /// \param Result if type deduction was successful, this will be set to the
  3458. /// deduced type.
  3459. Sema::DeduceAutoResult
  3460. Sema::DeduceAutoType(TypeLoc Type, Expr *&Init, QualType &Result) {
  3461. if (Init->getType()->isNonOverloadPlaceholderType()) {
  3462. ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
  3463. if (NonPlaceholder.isInvalid())
  3464. return DAR_FailedAlreadyDiagnosed;
  3465. Init = NonPlaceholder.get();
  3466. }
  3467. if (Init->isTypeDependent() || Type.getType()->isDependentType()) {
  3468. Result = SubstituteAutoTransform(*this, Context.DependentTy).Apply(Type);
  3469. assert(!Result.isNull() && "substituting DependentTy can't fail");
  3470. return DAR_Succeeded;
  3471. }
  3472. // If this is a 'decltype(auto)' specifier, do the decltype dance.
  3473. // Since 'decltype(auto)' can only occur at the top of the type, we
  3474. // don't need to go digging for it.
  3475. if (const AutoType *AT = Type.getType()->getAs<AutoType>()) {
  3476. if (AT->isDecltypeAuto()) {
  3477. if (isa<InitListExpr>(Init)) {
  3478. Diag(Init->getLocStart(), diag::err_decltype_auto_initializer_list);
  3479. return DAR_FailedAlreadyDiagnosed;
  3480. }
  3481. QualType Deduced = BuildDecltypeType(Init, Init->getLocStart(), false);
  3482. if (Deduced.isNull())
  3483. return DAR_FailedAlreadyDiagnosed;
  3484. // FIXME: Support a non-canonical deduced type for 'auto'.
  3485. Deduced = Context.getCanonicalType(Deduced);
  3486. Result = SubstituteAutoTransform(*this, Deduced).Apply(Type);
  3487. if (Result.isNull())
  3488. return DAR_FailedAlreadyDiagnosed;
  3489. return DAR_Succeeded;
  3490. }
  3491. }
  3492. SourceLocation Loc = Init->getExprLoc();
  3493. LocalInstantiationScope InstScope(*this);
  3494. // Build template<class TemplParam> void Func(FuncParam);
  3495. TemplateTypeParmDecl *TemplParam =
  3496. TemplateTypeParmDecl::Create(Context, nullptr, SourceLocation(), Loc, 0, 0,
  3497. nullptr, false, false);
  3498. QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
  3499. NamedDecl *TemplParamPtr = TemplParam;
  3500. FixedSizeTemplateParameterList<1> TemplateParams(Loc, Loc, &TemplParamPtr,
  3501. Loc);
  3502. QualType FuncParam = SubstituteAutoTransform(*this, TemplArg).Apply(Type);
  3503. assert(!FuncParam.isNull() &&
  3504. "substituting template parameter for 'auto' failed");
  3505. // Deduce type of TemplParam in Func(Init)
  3506. SmallVector<DeducedTemplateArgument, 1> Deduced;
  3507. Deduced.resize(1);
  3508. QualType InitType = Init->getType();
  3509. unsigned TDF = 0;
  3510. TemplateDeductionInfo Info(Loc);
  3511. InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
  3512. if (InitList) {
  3513. for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) {
  3514. if (DeduceTemplateArgumentByListElement(*this, &TemplateParams,
  3515. TemplArg,
  3516. InitList->getInit(i),
  3517. Info, Deduced, TDF))
  3518. return DAR_Failed;
  3519. }
  3520. } else {
  3521. if (AdjustFunctionParmAndArgTypesForDeduction(*this, &TemplateParams,
  3522. FuncParam, InitType, Init,
  3523. TDF))
  3524. return DAR_Failed;
  3525. if (DeduceTemplateArgumentsByTypeMatch(*this, &TemplateParams, FuncParam,
  3526. InitType, Info, Deduced, TDF))
  3527. return DAR_Failed;
  3528. }
  3529. if (Deduced[0].getKind() != TemplateArgument::Type)
  3530. return DAR_Failed;
  3531. QualType DeducedType = Deduced[0].getAsType();
  3532. if (InitList) {
  3533. DeducedType = BuildStdInitializerList(DeducedType, Loc);
  3534. if (DeducedType.isNull())
  3535. return DAR_FailedAlreadyDiagnosed;
  3536. }
  3537. Result = SubstituteAutoTransform(*this, DeducedType).Apply(Type);
  3538. if (Result.isNull())
  3539. return DAR_FailedAlreadyDiagnosed;
  3540. // Check that the deduced argument type is compatible with the original
  3541. // argument type per C++ [temp.deduct.call]p4.
  3542. if (!InitList && !Result.isNull() &&
  3543. CheckOriginalCallArgDeduction(*this,
  3544. Sema::OriginalCallArg(FuncParam,0,InitType),
  3545. Result)) {
  3546. Result = QualType();
  3547. return DAR_Failed;
  3548. }
  3549. return DAR_Succeeded;
  3550. }
  3551. QualType Sema::SubstAutoType(QualType TypeWithAuto,
  3552. QualType TypeToReplaceAuto) {
  3553. return SubstituteAutoTransform(*this, TypeToReplaceAuto).
  3554. TransformType(TypeWithAuto);
  3555. }
  3556. TypeSourceInfo* Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
  3557. QualType TypeToReplaceAuto) {
  3558. return SubstituteAutoTransform(*this, TypeToReplaceAuto).
  3559. TransformType(TypeWithAuto);
  3560. }
  3561. void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) {
  3562. if (isa<InitListExpr>(Init))
  3563. Diag(VDecl->getLocation(),
  3564. VDecl->isInitCapture()
  3565. ? diag::err_init_capture_deduction_failure_from_init_list
  3566. : diag::err_auto_var_deduction_failure_from_init_list)
  3567. << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
  3568. else
  3569. Diag(VDecl->getLocation(),
  3570. VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
  3571. : diag::err_auto_var_deduction_failure)
  3572. << VDecl->getDeclName() << VDecl->getType() << Init->getType()
  3573. << Init->getSourceRange();
  3574. }
  3575. bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
  3576. bool Diagnose) {
  3577. assert(FD->getReturnType()->isUndeducedType());
  3578. if (FD->getTemplateInstantiationPattern())
  3579. InstantiateFunctionDefinition(Loc, FD);
  3580. bool StillUndeduced = FD->getReturnType()->isUndeducedType();
  3581. if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
  3582. Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
  3583. Diag(FD->getLocation(), diag::note_callee_decl) << FD;
  3584. }
  3585. return StillUndeduced;
  3586. }
  3587. static void
  3588. MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
  3589. bool OnlyDeduced,
  3590. unsigned Level,
  3591. llvm::SmallBitVector &Deduced);
  3592. /// \brief If this is a non-static member function,
  3593. static void
  3594. AddImplicitObjectParameterType(ASTContext &Context,
  3595. CXXMethodDecl *Method,
  3596. SmallVectorImpl<QualType> &ArgTypes) {
  3597. // C++11 [temp.func.order]p3:
  3598. // [...] The new parameter is of type "reference to cv A," where cv are
  3599. // the cv-qualifiers of the function template (if any) and A is
  3600. // the class of which the function template is a member.
  3601. //
  3602. // The standard doesn't say explicitly, but we pick the appropriate kind of
  3603. // reference type based on [over.match.funcs]p4.
  3604. QualType ArgTy = Context.getTypeDeclType(Method->getParent());
  3605. ArgTy = Context.getQualifiedType(ArgTy,
  3606. Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
  3607. if (Method->getRefQualifier() == RQ_RValue)
  3608. ArgTy = Context.getRValueReferenceType(ArgTy);
  3609. else
  3610. ArgTy = Context.getLValueReferenceType(ArgTy);
  3611. ArgTypes.push_back(ArgTy);
  3612. }
  3613. /// \brief Determine whether the function template \p FT1 is at least as
  3614. /// specialized as \p FT2.
  3615. static bool isAtLeastAsSpecializedAs(Sema &S,
  3616. SourceLocation Loc,
  3617. FunctionTemplateDecl *FT1,
  3618. FunctionTemplateDecl *FT2,
  3619. TemplatePartialOrderingContext TPOC,
  3620. unsigned NumCallArguments1) {
  3621. FunctionDecl *FD1 = FT1->getTemplatedDecl();
  3622. FunctionDecl *FD2 = FT2->getTemplatedDecl();
  3623. const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
  3624. const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
  3625. assert(Proto1 && Proto2 && "Function templates must have prototypes");
  3626. TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
  3627. SmallVector<DeducedTemplateArgument, 4> Deduced;
  3628. Deduced.resize(TemplateParams->size());
  3629. // C++0x [temp.deduct.partial]p3:
  3630. // The types used to determine the ordering depend on the context in which
  3631. // the partial ordering is done:
  3632. TemplateDeductionInfo Info(Loc);
  3633. SmallVector<QualType, 4> Args2;
  3634. switch (TPOC) {
  3635. case TPOC_Call: {
  3636. // - In the context of a function call, the function parameter types are
  3637. // used.
  3638. CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
  3639. CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
  3640. // C++11 [temp.func.order]p3:
  3641. // [...] If only one of the function templates is a non-static
  3642. // member, that function template is considered to have a new
  3643. // first parameter inserted in its function parameter list. The
  3644. // new parameter is of type "reference to cv A," where cv are
  3645. // the cv-qualifiers of the function template (if any) and A is
  3646. // the class of which the function template is a member.
  3647. //
  3648. // Note that we interpret this to mean "if one of the function
  3649. // templates is a non-static member and the other is a non-member";
  3650. // otherwise, the ordering rules for static functions against non-static
  3651. // functions don't make any sense.
  3652. //
  3653. // C++98/03 doesn't have this provision but we've extended DR532 to cover
  3654. // it as wording was broken prior to it.
  3655. SmallVector<QualType, 4> Args1;
  3656. unsigned NumComparedArguments = NumCallArguments1;
  3657. if (!Method2 && Method1 && !Method1->isStatic()) {
  3658. // Compare 'this' from Method1 against first parameter from Method2.
  3659. AddImplicitObjectParameterType(S.Context, Method1, Args1);
  3660. ++NumComparedArguments;
  3661. } else if (!Method1 && Method2 && !Method2->isStatic()) {
  3662. // Compare 'this' from Method2 against first parameter from Method1.
  3663. AddImplicitObjectParameterType(S.Context, Method2, Args2);
  3664. }
  3665. Args1.insert(Args1.end(), Proto1->param_type_begin(),
  3666. Proto1->param_type_end());
  3667. Args2.insert(Args2.end(), Proto2->param_type_begin(),
  3668. Proto2->param_type_end());
  3669. // C++ [temp.func.order]p5:
  3670. // The presence of unused ellipsis and default arguments has no effect on
  3671. // the partial ordering of function templates.
  3672. if (Args1.size() > NumComparedArguments)
  3673. Args1.resize(NumComparedArguments);
  3674. if (Args2.size() > NumComparedArguments)
  3675. Args2.resize(NumComparedArguments);
  3676. if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
  3677. Args1.data(), Args1.size(), Info, Deduced,
  3678. TDF_None, /*PartialOrdering=*/true))
  3679. return false;
  3680. break;
  3681. }
  3682. case TPOC_Conversion:
  3683. // - In the context of a call to a conversion operator, the return types
  3684. // of the conversion function templates are used.
  3685. if (DeduceTemplateArgumentsByTypeMatch(
  3686. S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
  3687. Info, Deduced, TDF_None,
  3688. /*PartialOrdering=*/true))
  3689. return false;
  3690. break;
  3691. case TPOC_Other:
  3692. // - In other contexts (14.6.6.2) the function template's function type
  3693. // is used.
  3694. if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
  3695. FD2->getType(), FD1->getType(),
  3696. Info, Deduced, TDF_None,
  3697. /*PartialOrdering=*/true))
  3698. return false;
  3699. break;
  3700. }
  3701. // C++0x [temp.deduct.partial]p11:
  3702. // In most cases, all template parameters must have values in order for
  3703. // deduction to succeed, but for partial ordering purposes a template
  3704. // parameter may remain without a value provided it is not used in the
  3705. // types being used for partial ordering. [ Note: a template parameter used
  3706. // in a non-deduced context is considered used. -end note]
  3707. unsigned ArgIdx = 0, NumArgs = Deduced.size();
  3708. for (; ArgIdx != NumArgs; ++ArgIdx)
  3709. if (Deduced[ArgIdx].isNull())
  3710. break;
  3711. if (ArgIdx == NumArgs) {
  3712. // All template arguments were deduced. FT1 is at least as specialized
  3713. // as FT2.
  3714. return true;
  3715. }
  3716. // Figure out which template parameters were used.
  3717. llvm::SmallBitVector UsedParameters(TemplateParams->size());
  3718. switch (TPOC) {
  3719. case TPOC_Call:
  3720. for (unsigned I = 0, N = Args2.size(); I != N; ++I)
  3721. ::MarkUsedTemplateParameters(S.Context, Args2[I], false,
  3722. TemplateParams->getDepth(),
  3723. UsedParameters);
  3724. break;
  3725. case TPOC_Conversion:
  3726. ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false,
  3727. TemplateParams->getDepth(), UsedParameters);
  3728. break;
  3729. case TPOC_Other:
  3730. ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false,
  3731. TemplateParams->getDepth(),
  3732. UsedParameters);
  3733. break;
  3734. }
  3735. for (; ArgIdx != NumArgs; ++ArgIdx)
  3736. // If this argument had no value deduced but was used in one of the types
  3737. // used for partial ordering, then deduction fails.
  3738. if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
  3739. return false;
  3740. return true;
  3741. }
  3742. /// \brief Determine whether this a function template whose parameter-type-list
  3743. /// ends with a function parameter pack.
  3744. static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) {
  3745. FunctionDecl *Function = FunTmpl->getTemplatedDecl();
  3746. unsigned NumParams = Function->getNumParams();
  3747. if (NumParams == 0)
  3748. return false;
  3749. ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
  3750. if (!Last->isParameterPack())
  3751. return false;
  3752. // Make sure that no previous parameter is a parameter pack.
  3753. while (--NumParams > 0) {
  3754. if (Function->getParamDecl(NumParams - 1)->isParameterPack())
  3755. return false;
  3756. }
  3757. return true;
  3758. }
  3759. /// \brief Returns the more specialized function template according
  3760. /// to the rules of function template partial ordering (C++ [temp.func.order]).
  3761. ///
  3762. /// \param FT1 the first function template
  3763. ///
  3764. /// \param FT2 the second function template
  3765. ///
  3766. /// \param TPOC the context in which we are performing partial ordering of
  3767. /// function templates.
  3768. ///
  3769. /// \param NumCallArguments1 The number of arguments in the call to FT1, used
  3770. /// only when \c TPOC is \c TPOC_Call.
  3771. ///
  3772. /// \param NumCallArguments2 The number of arguments in the call to FT2, used
  3773. /// only when \c TPOC is \c TPOC_Call.
  3774. ///
  3775. /// \returns the more specialized function template. If neither
  3776. /// template is more specialized, returns NULL.
  3777. FunctionTemplateDecl *
  3778. Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
  3779. FunctionTemplateDecl *FT2,
  3780. SourceLocation Loc,
  3781. TemplatePartialOrderingContext TPOC,
  3782. unsigned NumCallArguments1,
  3783. unsigned NumCallArguments2) {
  3784. bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
  3785. NumCallArguments1);
  3786. bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
  3787. NumCallArguments2);
  3788. if (Better1 != Better2) // We have a clear winner
  3789. return Better1 ? FT1 : FT2;
  3790. if (!Better1 && !Better2) // Neither is better than the other
  3791. return nullptr;
  3792. // FIXME: This mimics what GCC implements, but doesn't match up with the
  3793. // proposed resolution for core issue 692. This area needs to be sorted out,
  3794. // but for now we attempt to maintain compatibility.
  3795. bool Variadic1 = isVariadicFunctionTemplate(FT1);
  3796. bool Variadic2 = isVariadicFunctionTemplate(FT2);
  3797. if (Variadic1 != Variadic2)
  3798. return Variadic1? FT2 : FT1;
  3799. return nullptr;
  3800. }
  3801. /// \brief Determine if the two templates are equivalent.
  3802. static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
  3803. if (T1 == T2)
  3804. return true;
  3805. if (!T1 || !T2)
  3806. return false;
  3807. return T1->getCanonicalDecl() == T2->getCanonicalDecl();
  3808. }
  3809. /// \brief Retrieve the most specialized of the given function template
  3810. /// specializations.
  3811. ///
  3812. /// \param SpecBegin the start iterator of the function template
  3813. /// specializations that we will be comparing.
  3814. ///
  3815. /// \param SpecEnd the end iterator of the function template
  3816. /// specializations, paired with \p SpecBegin.
  3817. ///
  3818. /// \param Loc the location where the ambiguity or no-specializations
  3819. /// diagnostic should occur.
  3820. ///
  3821. /// \param NoneDiag partial diagnostic used to diagnose cases where there are
  3822. /// no matching candidates.
  3823. ///
  3824. /// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
  3825. /// occurs.
  3826. ///
  3827. /// \param CandidateDiag partial diagnostic used for each function template
  3828. /// specialization that is a candidate in the ambiguous ordering. One parameter
  3829. /// in this diagnostic should be unbound, which will correspond to the string
  3830. /// describing the template arguments for the function template specialization.
  3831. ///
  3832. /// \returns the most specialized function template specialization, if
  3833. /// found. Otherwise, returns SpecEnd.
  3834. UnresolvedSetIterator Sema::getMostSpecialized(
  3835. UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd,
  3836. TemplateSpecCandidateSet &FailedCandidates,
  3837. SourceLocation Loc, const PartialDiagnostic &NoneDiag,
  3838. const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
  3839. bool Complain, QualType TargetType) {
  3840. if (SpecBegin == SpecEnd) {
  3841. if (Complain) {
  3842. Diag(Loc, NoneDiag);
  3843. FailedCandidates.NoteCandidates(*this, Loc);
  3844. }
  3845. return SpecEnd;
  3846. }
  3847. if (SpecBegin + 1 == SpecEnd)
  3848. return SpecBegin;
  3849. // Find the function template that is better than all of the templates it
  3850. // has been compared to.
  3851. UnresolvedSetIterator Best = SpecBegin;
  3852. FunctionTemplateDecl *BestTemplate
  3853. = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
  3854. assert(BestTemplate && "Not a function template specialization?");
  3855. for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
  3856. FunctionTemplateDecl *Challenger
  3857. = cast<FunctionDecl>(*I)->getPrimaryTemplate();
  3858. assert(Challenger && "Not a function template specialization?");
  3859. if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
  3860. Loc, TPOC_Other, 0, 0),
  3861. Challenger)) {
  3862. Best = I;
  3863. BestTemplate = Challenger;
  3864. }
  3865. }
  3866. // Make sure that the "best" function template is more specialized than all
  3867. // of the others.
  3868. bool Ambiguous = false;
  3869. for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
  3870. FunctionTemplateDecl *Challenger
  3871. = cast<FunctionDecl>(*I)->getPrimaryTemplate();
  3872. if (I != Best &&
  3873. !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
  3874. Loc, TPOC_Other, 0, 0),
  3875. BestTemplate)) {
  3876. Ambiguous = true;
  3877. break;
  3878. }
  3879. }
  3880. if (!Ambiguous) {
  3881. // We found an answer. Return it.
  3882. return Best;
  3883. }
  3884. // Diagnose the ambiguity.
  3885. if (Complain) {
  3886. Diag(Loc, AmbigDiag);
  3887. // FIXME: Can we order the candidates in some sane way?
  3888. for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
  3889. PartialDiagnostic PD = CandidateDiag;
  3890. PD << getTemplateArgumentBindingsText(
  3891. cast<FunctionDecl>(*I)->getPrimaryTemplate()->getTemplateParameters(),
  3892. *cast<FunctionDecl>(*I)->getTemplateSpecializationArgs());
  3893. if (!TargetType.isNull())
  3894. HandleFunctionTypeMismatch(PD, cast<FunctionDecl>(*I)->getType(),
  3895. TargetType);
  3896. Diag((*I)->getLocation(), PD);
  3897. }
  3898. }
  3899. return SpecEnd;
  3900. }
  3901. /// \brief Returns the more specialized class template partial specialization
  3902. /// according to the rules of partial ordering of class template partial
  3903. /// specializations (C++ [temp.class.order]).
  3904. ///
  3905. /// \param PS1 the first class template partial specialization
  3906. ///
  3907. /// \param PS2 the second class template partial specialization
  3908. ///
  3909. /// \returns the more specialized class template partial specialization. If
  3910. /// neither partial specialization is more specialized, returns NULL.
  3911. ClassTemplatePartialSpecializationDecl *
  3912. Sema::getMoreSpecializedPartialSpecialization(
  3913. ClassTemplatePartialSpecializationDecl *PS1,
  3914. ClassTemplatePartialSpecializationDecl *PS2,
  3915. SourceLocation Loc) {
  3916. // C++ [temp.class.order]p1:
  3917. // For two class template partial specializations, the first is at least as
  3918. // specialized as the second if, given the following rewrite to two
  3919. // function templates, the first function template is at least as
  3920. // specialized as the second according to the ordering rules for function
  3921. // templates (14.6.6.2):
  3922. // - the first function template has the same template parameters as the
  3923. // first partial specialization and has a single function parameter
  3924. // whose type is a class template specialization with the template
  3925. // arguments of the first partial specialization, and
  3926. // - the second function template has the same template parameters as the
  3927. // second partial specialization and has a single function parameter
  3928. // whose type is a class template specialization with the template
  3929. // arguments of the second partial specialization.
  3930. //
  3931. // Rather than synthesize function templates, we merely perform the
  3932. // equivalent partial ordering by performing deduction directly on
  3933. // the template arguments of the class template partial
  3934. // specializations. This computation is slightly simpler than the
  3935. // general problem of function template partial ordering, because
  3936. // class template partial specializations are more constrained. We
  3937. // know that every template parameter is deducible from the class
  3938. // template partial specialization's template arguments, for
  3939. // example.
  3940. SmallVector<DeducedTemplateArgument, 4> Deduced;
  3941. TemplateDeductionInfo Info(Loc);
  3942. QualType PT1 = PS1->getInjectedSpecializationType();
  3943. QualType PT2 = PS2->getInjectedSpecializationType();
  3944. // Determine whether PS1 is at least as specialized as PS2
  3945. Deduced.resize(PS2->getTemplateParameters()->size());
  3946. bool Better1 = !DeduceTemplateArgumentsByTypeMatch(*this,
  3947. PS2->getTemplateParameters(),
  3948. PT2, PT1, Info, Deduced, TDF_None,
  3949. /*PartialOrdering=*/true);
  3950. if (Better1) {
  3951. SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),Deduced.end());
  3952. InstantiatingTemplate Inst(*this, Loc, PS2, DeducedArgs, Info);
  3953. Better1 = !::FinishTemplateArgumentDeduction(
  3954. *this, PS2, PS1->getTemplateArgs(), Deduced, Info);
  3955. }
  3956. // Determine whether PS2 is at least as specialized as PS1
  3957. Deduced.clear();
  3958. Deduced.resize(PS1->getTemplateParameters()->size());
  3959. bool Better2 = !DeduceTemplateArgumentsByTypeMatch(
  3960. *this, PS1->getTemplateParameters(), PT1, PT2, Info, Deduced, TDF_None,
  3961. /*PartialOrdering=*/true);
  3962. if (Better2) {
  3963. SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
  3964. Deduced.end());
  3965. InstantiatingTemplate Inst(*this, Loc, PS1, DeducedArgs, Info);
  3966. Better2 = !::FinishTemplateArgumentDeduction(
  3967. *this, PS1, PS2->getTemplateArgs(), Deduced, Info);
  3968. }
  3969. if (Better1 == Better2)
  3970. return nullptr;
  3971. return Better1 ? PS1 : PS2;
  3972. }
  3973. /// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
  3974. /// May require unifying ClassTemplate(Partial)SpecializationDecl and
  3975. /// VarTemplate(Partial)SpecializationDecl with a new data
  3976. /// structure Template(Partial)SpecializationDecl, and
  3977. /// using Template(Partial)SpecializationDecl as input type.
  3978. VarTemplatePartialSpecializationDecl *
  3979. Sema::getMoreSpecializedPartialSpecialization(
  3980. VarTemplatePartialSpecializationDecl *PS1,
  3981. VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) {
  3982. SmallVector<DeducedTemplateArgument, 4> Deduced;
  3983. TemplateDeductionInfo Info(Loc);
  3984. assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
  3985. "the partial specializations being compared should specialize"
  3986. " the same template.");
  3987. TemplateName Name(PS1->getSpecializedTemplate());
  3988. TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
  3989. QualType PT1 = Context.getTemplateSpecializationType(
  3990. CanonTemplate, PS1->getTemplateArgs().data(),
  3991. PS1->getTemplateArgs().size());
  3992. QualType PT2 = Context.getTemplateSpecializationType(
  3993. CanonTemplate, PS2->getTemplateArgs().data(),
  3994. PS2->getTemplateArgs().size());
  3995. // Determine whether PS1 is at least as specialized as PS2
  3996. Deduced.resize(PS2->getTemplateParameters()->size());
  3997. bool Better1 = !DeduceTemplateArgumentsByTypeMatch(
  3998. *this, PS2->getTemplateParameters(), PT2, PT1, Info, Deduced, TDF_None,
  3999. /*PartialOrdering=*/true);
  4000. if (Better1) {
  4001. SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
  4002. Deduced.end());
  4003. InstantiatingTemplate Inst(*this, Loc, PS2, DeducedArgs, Info);
  4004. Better1 = !::FinishTemplateArgumentDeduction(*this, PS2,
  4005. PS1->getTemplateArgs(),
  4006. Deduced, Info);
  4007. }
  4008. // Determine whether PS2 is at least as specialized as PS1
  4009. Deduced.clear();
  4010. Deduced.resize(PS1->getTemplateParameters()->size());
  4011. bool Better2 = !DeduceTemplateArgumentsByTypeMatch(*this,
  4012. PS1->getTemplateParameters(),
  4013. PT1, PT2, Info, Deduced, TDF_None,
  4014. /*PartialOrdering=*/true);
  4015. if (Better2) {
  4016. SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),Deduced.end());
  4017. InstantiatingTemplate Inst(*this, Loc, PS1, DeducedArgs, Info);
  4018. Better2 = !::FinishTemplateArgumentDeduction(*this, PS1,
  4019. PS2->getTemplateArgs(),
  4020. Deduced, Info);
  4021. }
  4022. if (Better1 == Better2)
  4023. return nullptr;
  4024. return Better1? PS1 : PS2;
  4025. }
  4026. static void
  4027. MarkUsedTemplateParameters(ASTContext &Ctx,
  4028. const TemplateArgument &TemplateArg,
  4029. bool OnlyDeduced,
  4030. unsigned Depth,
  4031. llvm::SmallBitVector &Used);
  4032. /// \brief Mark the template parameters that are used by the given
  4033. /// expression.
  4034. static void
  4035. MarkUsedTemplateParameters(ASTContext &Ctx,
  4036. const Expr *E,
  4037. bool OnlyDeduced,
  4038. unsigned Depth,
  4039. llvm::SmallBitVector &Used) {
  4040. // We can deduce from a pack expansion.
  4041. if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
  4042. E = Expansion->getPattern();
  4043. // Skip through any implicit casts we added while type-checking, and any
  4044. // substitutions performed by template alias expansion.
  4045. while (1) {
  4046. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
  4047. E = ICE->getSubExpr();
  4048. else if (const SubstNonTypeTemplateParmExpr *Subst =
  4049. dyn_cast<SubstNonTypeTemplateParmExpr>(E))
  4050. E = Subst->getReplacement();
  4051. else
  4052. break;
  4053. }
  4054. // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
  4055. // find other occurrences of template parameters.
  4056. const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
  4057. if (!DRE)
  4058. return;
  4059. const NonTypeTemplateParmDecl *NTTP
  4060. = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
  4061. if (!NTTP)
  4062. return;
  4063. if (NTTP->getDepth() == Depth)
  4064. Used[NTTP->getIndex()] = true;
  4065. }
  4066. /// \brief Mark the template parameters that are used by the given
  4067. /// nested name specifier.
  4068. static void
  4069. MarkUsedTemplateParameters(ASTContext &Ctx,
  4070. NestedNameSpecifier *NNS,
  4071. bool OnlyDeduced,
  4072. unsigned Depth,
  4073. llvm::SmallBitVector &Used) {
  4074. if (!NNS)
  4075. return;
  4076. MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
  4077. Used);
  4078. MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0),
  4079. OnlyDeduced, Depth, Used);
  4080. }
  4081. /// \brief Mark the template parameters that are used by the given
  4082. /// template name.
  4083. static void
  4084. MarkUsedTemplateParameters(ASTContext &Ctx,
  4085. TemplateName Name,
  4086. bool OnlyDeduced,
  4087. unsigned Depth,
  4088. llvm::SmallBitVector &Used) {
  4089. if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
  4090. if (TemplateTemplateParmDecl *TTP
  4091. = dyn_cast<TemplateTemplateParmDecl>(Template)) {
  4092. if (TTP->getDepth() == Depth)
  4093. Used[TTP->getIndex()] = true;
  4094. }
  4095. return;
  4096. }
  4097. if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
  4098. MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
  4099. Depth, Used);
  4100. if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
  4101. MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
  4102. Depth, Used);
  4103. }
  4104. /// \brief Mark the template parameters that are used by the given
  4105. /// type.
  4106. static void
  4107. MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
  4108. bool OnlyDeduced,
  4109. unsigned Depth,
  4110. llvm::SmallBitVector &Used) {
  4111. if (T.isNull())
  4112. return;
  4113. // Non-dependent types have nothing deducible
  4114. if (!T->isDependentType())
  4115. return;
  4116. T = Ctx.getCanonicalType(T);
  4117. switch (T->getTypeClass()) {
  4118. case Type::Pointer:
  4119. MarkUsedTemplateParameters(Ctx,
  4120. cast<PointerType>(T)->getPointeeType(),
  4121. OnlyDeduced,
  4122. Depth,
  4123. Used);
  4124. break;
  4125. case Type::BlockPointer:
  4126. MarkUsedTemplateParameters(Ctx,
  4127. cast<BlockPointerType>(T)->getPointeeType(),
  4128. OnlyDeduced,
  4129. Depth,
  4130. Used);
  4131. break;
  4132. case Type::LValueReference:
  4133. case Type::RValueReference:
  4134. MarkUsedTemplateParameters(Ctx,
  4135. cast<ReferenceType>(T)->getPointeeType(),
  4136. OnlyDeduced,
  4137. Depth,
  4138. Used);
  4139. break;
  4140. case Type::MemberPointer: {
  4141. const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
  4142. MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
  4143. Depth, Used);
  4144. MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
  4145. OnlyDeduced, Depth, Used);
  4146. break;
  4147. }
  4148. case Type::DependentSizedArray:
  4149. MarkUsedTemplateParameters(Ctx,
  4150. cast<DependentSizedArrayType>(T)->getSizeExpr(),
  4151. OnlyDeduced, Depth, Used);
  4152. // Fall through to check the element type
  4153. case Type::ConstantArray:
  4154. case Type::IncompleteArray:
  4155. MarkUsedTemplateParameters(Ctx,
  4156. cast<ArrayType>(T)->getElementType(),
  4157. OnlyDeduced, Depth, Used);
  4158. break;
  4159. case Type::Vector:
  4160. case Type::ExtVector:
  4161. MarkUsedTemplateParameters(Ctx,
  4162. cast<VectorType>(T)->getElementType(),
  4163. OnlyDeduced, Depth, Used);
  4164. break;
  4165. case Type::DependentSizedExtVector: {
  4166. const DependentSizedExtVectorType *VecType
  4167. = cast<DependentSizedExtVectorType>(T);
  4168. MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
  4169. Depth, Used);
  4170. MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
  4171. Depth, Used);
  4172. break;
  4173. }
  4174. case Type::FunctionProto: {
  4175. const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
  4176. MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
  4177. Used);
  4178. for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I)
  4179. MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
  4180. Depth, Used);
  4181. break;
  4182. }
  4183. case Type::TemplateTypeParm: {
  4184. const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
  4185. if (TTP->getDepth() == Depth)
  4186. Used[TTP->getIndex()] = true;
  4187. break;
  4188. }
  4189. case Type::SubstTemplateTypeParmPack: {
  4190. const SubstTemplateTypeParmPackType *Subst
  4191. = cast<SubstTemplateTypeParmPackType>(T);
  4192. MarkUsedTemplateParameters(Ctx,
  4193. QualType(Subst->getReplacedParameter(), 0),
  4194. OnlyDeduced, Depth, Used);
  4195. MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(),
  4196. OnlyDeduced, Depth, Used);
  4197. break;
  4198. }
  4199. case Type::InjectedClassName:
  4200. T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
  4201. // fall through
  4202. case Type::TemplateSpecialization: {
  4203. const TemplateSpecializationType *Spec
  4204. = cast<TemplateSpecializationType>(T);
  4205. MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
  4206. Depth, Used);
  4207. // C++0x [temp.deduct.type]p9:
  4208. // If the template argument list of P contains a pack expansion that is
  4209. // not the last template argument, the entire template argument list is a
  4210. // non-deduced context.
  4211. if (OnlyDeduced &&
  4212. hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
  4213. break;
  4214. for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
  4215. MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
  4216. Used);
  4217. break;
  4218. }
  4219. case Type::Complex:
  4220. if (!OnlyDeduced)
  4221. MarkUsedTemplateParameters(Ctx,
  4222. cast<ComplexType>(T)->getElementType(),
  4223. OnlyDeduced, Depth, Used);
  4224. break;
  4225. case Type::Atomic:
  4226. if (!OnlyDeduced)
  4227. MarkUsedTemplateParameters(Ctx,
  4228. cast<AtomicType>(T)->getValueType(),
  4229. OnlyDeduced, Depth, Used);
  4230. break;
  4231. case Type::DependentName:
  4232. if (!OnlyDeduced)
  4233. MarkUsedTemplateParameters(Ctx,
  4234. cast<DependentNameType>(T)->getQualifier(),
  4235. OnlyDeduced, Depth, Used);
  4236. break;
  4237. case Type::DependentTemplateSpecialization: {
  4238. const DependentTemplateSpecializationType *Spec
  4239. = cast<DependentTemplateSpecializationType>(T);
  4240. if (!OnlyDeduced)
  4241. MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
  4242. OnlyDeduced, Depth, Used);
  4243. // C++0x [temp.deduct.type]p9:
  4244. // If the template argument list of P contains a pack expansion that is not
  4245. // the last template argument, the entire template argument list is a
  4246. // non-deduced context.
  4247. if (OnlyDeduced &&
  4248. hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
  4249. break;
  4250. for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
  4251. MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
  4252. Used);
  4253. break;
  4254. }
  4255. case Type::TypeOf:
  4256. if (!OnlyDeduced)
  4257. MarkUsedTemplateParameters(Ctx,
  4258. cast<TypeOfType>(T)->getUnderlyingType(),
  4259. OnlyDeduced, Depth, Used);
  4260. break;
  4261. case Type::TypeOfExpr:
  4262. if (!OnlyDeduced)
  4263. MarkUsedTemplateParameters(Ctx,
  4264. cast<TypeOfExprType>(T)->getUnderlyingExpr(),
  4265. OnlyDeduced, Depth, Used);
  4266. break;
  4267. case Type::Decltype:
  4268. if (!OnlyDeduced)
  4269. MarkUsedTemplateParameters(Ctx,
  4270. cast<DecltypeType>(T)->getUnderlyingExpr(),
  4271. OnlyDeduced, Depth, Used);
  4272. break;
  4273. case Type::UnaryTransform:
  4274. if (!OnlyDeduced)
  4275. MarkUsedTemplateParameters(Ctx,
  4276. cast<UnaryTransformType>(T)->getUnderlyingType(),
  4277. OnlyDeduced, Depth, Used);
  4278. break;
  4279. case Type::PackExpansion:
  4280. MarkUsedTemplateParameters(Ctx,
  4281. cast<PackExpansionType>(T)->getPattern(),
  4282. OnlyDeduced, Depth, Used);
  4283. break;
  4284. case Type::Auto:
  4285. MarkUsedTemplateParameters(Ctx,
  4286. cast<AutoType>(T)->getDeducedType(),
  4287. OnlyDeduced, Depth, Used);
  4288. // None of these types have any template parameters in them.
  4289. case Type::Builtin:
  4290. case Type::VariableArray:
  4291. case Type::FunctionNoProto:
  4292. case Type::Record:
  4293. case Type::Enum:
  4294. case Type::ObjCInterface:
  4295. case Type::ObjCObject:
  4296. case Type::ObjCObjectPointer:
  4297. case Type::UnresolvedUsing:
  4298. #define TYPE(Class, Base)
  4299. #define ABSTRACT_TYPE(Class, Base)
  4300. #define DEPENDENT_TYPE(Class, Base)
  4301. #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
  4302. #include "clang/AST/TypeNodes.def"
  4303. break;
  4304. }
  4305. }
  4306. /// \brief Mark the template parameters that are used by this
  4307. /// template argument.
  4308. static void
  4309. MarkUsedTemplateParameters(ASTContext &Ctx,
  4310. const TemplateArgument &TemplateArg,
  4311. bool OnlyDeduced,
  4312. unsigned Depth,
  4313. llvm::SmallBitVector &Used) {
  4314. switch (TemplateArg.getKind()) {
  4315. case TemplateArgument::Null:
  4316. case TemplateArgument::Integral:
  4317. case TemplateArgument::Declaration:
  4318. break;
  4319. case TemplateArgument::NullPtr:
  4320. MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced,
  4321. Depth, Used);
  4322. break;
  4323. case TemplateArgument::Type:
  4324. MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
  4325. Depth, Used);
  4326. break;
  4327. case TemplateArgument::Template:
  4328. case TemplateArgument::TemplateExpansion:
  4329. MarkUsedTemplateParameters(Ctx,
  4330. TemplateArg.getAsTemplateOrTemplatePattern(),
  4331. OnlyDeduced, Depth, Used);
  4332. break;
  4333. case TemplateArgument::Expression:
  4334. MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
  4335. Depth, Used);
  4336. break;
  4337. case TemplateArgument::Pack:
  4338. for (const auto &P : TemplateArg.pack_elements())
  4339. MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
  4340. break;
  4341. }
  4342. }
  4343. /// \brief Mark which template parameters can be deduced from a given
  4344. /// template argument list.
  4345. ///
  4346. /// \param TemplateArgs the template argument list from which template
  4347. /// parameters will be deduced.
  4348. ///
  4349. /// \param Used a bit vector whose elements will be set to \c true
  4350. /// to indicate when the corresponding template parameter will be
  4351. /// deduced.
  4352. void
  4353. Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
  4354. bool OnlyDeduced, unsigned Depth,
  4355. llvm::SmallBitVector &Used) {
  4356. // C++0x [temp.deduct.type]p9:
  4357. // If the template argument list of P contains a pack expansion that is not
  4358. // the last template argument, the entire template argument list is a
  4359. // non-deduced context.
  4360. if (OnlyDeduced &&
  4361. hasPackExpansionBeforeEnd(TemplateArgs.data(), TemplateArgs.size()))
  4362. return;
  4363. for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
  4364. ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
  4365. Depth, Used);
  4366. }
  4367. /// \brief Marks all of the template parameters that will be deduced by a
  4368. /// call to the given function template.
  4369. void Sema::MarkDeducedTemplateParameters(
  4370. ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
  4371. llvm::SmallBitVector &Deduced) {
  4372. TemplateParameterList *TemplateParams
  4373. = FunctionTemplate->getTemplateParameters();
  4374. Deduced.clear();
  4375. Deduced.resize(TemplateParams->size());
  4376. FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
  4377. for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
  4378. ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
  4379. true, TemplateParams->getDepth(), Deduced);
  4380. }
  4381. bool hasDeducibleTemplateParameters(Sema &S,
  4382. FunctionTemplateDecl *FunctionTemplate,
  4383. QualType T) {
  4384. if (!T->isDependentType())
  4385. return false;
  4386. TemplateParameterList *TemplateParams
  4387. = FunctionTemplate->getTemplateParameters();
  4388. llvm::SmallBitVector Deduced(TemplateParams->size());
  4389. ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
  4390. Deduced);
  4391. return Deduced.any();
  4392. }