SemaTemplateDeduction.cpp 227 KB

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