SemaTemplateInstantiateDecl.cpp 206 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276
  1. //===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl Instantiation ===/
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //===----------------------------------------------------------------------===/
  8. //
  9. // This file implements C++ template instantiation for declarations.
  10. //
  11. //===----------------------------------------------------------------------===/
  12. #include "clang/Sema/SemaInternal.h"
  13. #include "clang/AST/ASTConsumer.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/ASTMutationListener.h"
  16. #include "clang/AST/DeclTemplate.h"
  17. #include "clang/AST/DeclVisitor.h"
  18. #include "clang/AST/DependentDiagnostic.h"
  19. #include "clang/AST/Expr.h"
  20. #include "clang/AST/ExprCXX.h"
  21. #include "clang/AST/PrettyDeclStackTrace.h"
  22. #include "clang/AST/TypeLoc.h"
  23. #include "clang/Sema/Initialization.h"
  24. #include "clang/Sema/Lookup.h"
  25. #include "clang/Sema/Template.h"
  26. #include "clang/Sema/TemplateInstCallback.h"
  27. using namespace clang;
  28. static bool isDeclWithinFunction(const Decl *D) {
  29. const DeclContext *DC = D->getDeclContext();
  30. if (DC->isFunctionOrMethod())
  31. return true;
  32. if (DC->isRecord())
  33. return cast<CXXRecordDecl>(DC)->isLocalClass();
  34. return false;
  35. }
  36. template<typename DeclT>
  37. static bool SubstQualifier(Sema &SemaRef, const DeclT *OldDecl, DeclT *NewDecl,
  38. const MultiLevelTemplateArgumentList &TemplateArgs) {
  39. if (!OldDecl->getQualifierLoc())
  40. return false;
  41. assert((NewDecl->getFriendObjectKind() ||
  42. !OldDecl->getLexicalDeclContext()->isDependentContext()) &&
  43. "non-friend with qualified name defined in dependent context");
  44. Sema::ContextRAII SavedContext(
  45. SemaRef,
  46. const_cast<DeclContext *>(NewDecl->getFriendObjectKind()
  47. ? NewDecl->getLexicalDeclContext()
  48. : OldDecl->getLexicalDeclContext()));
  49. NestedNameSpecifierLoc NewQualifierLoc
  50. = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
  51. TemplateArgs);
  52. if (!NewQualifierLoc)
  53. return true;
  54. NewDecl->setQualifierInfo(NewQualifierLoc);
  55. return false;
  56. }
  57. bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
  58. DeclaratorDecl *NewDecl) {
  59. return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
  60. }
  61. bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
  62. TagDecl *NewDecl) {
  63. return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
  64. }
  65. // Include attribute instantiation code.
  66. #include "clang/Sema/AttrTemplateInstantiate.inc"
  67. static void instantiateDependentAlignedAttr(
  68. Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
  69. const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
  70. if (Aligned->isAlignmentExpr()) {
  71. // The alignment expression is a constant expression.
  72. EnterExpressionEvaluationContext Unevaluated(
  73. S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  74. ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
  75. if (!Result.isInvalid())
  76. S.AddAlignedAttr(Aligned->getLocation(), New, Result.getAs<Expr>(),
  77. Aligned->getSpellingListIndex(), IsPackExpansion);
  78. } else {
  79. TypeSourceInfo *Result = S.SubstType(Aligned->getAlignmentType(),
  80. TemplateArgs, Aligned->getLocation(),
  81. DeclarationName());
  82. if (Result)
  83. S.AddAlignedAttr(Aligned->getLocation(), New, Result,
  84. Aligned->getSpellingListIndex(), IsPackExpansion);
  85. }
  86. }
  87. static void instantiateDependentAlignedAttr(
  88. Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
  89. const AlignedAttr *Aligned, Decl *New) {
  90. if (!Aligned->isPackExpansion()) {
  91. instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
  92. return;
  93. }
  94. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  95. if (Aligned->isAlignmentExpr())
  96. S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
  97. Unexpanded);
  98. else
  99. S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
  100. Unexpanded);
  101. assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
  102. // Determine whether we can expand this attribute pack yet.
  103. bool Expand = true, RetainExpansion = false;
  104. Optional<unsigned> NumExpansions;
  105. // FIXME: Use the actual location of the ellipsis.
  106. SourceLocation EllipsisLoc = Aligned->getLocation();
  107. if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
  108. Unexpanded, TemplateArgs, Expand,
  109. RetainExpansion, NumExpansions))
  110. return;
  111. if (!Expand) {
  112. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1);
  113. instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
  114. } else {
  115. for (unsigned I = 0; I != *NumExpansions; ++I) {
  116. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I);
  117. instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
  118. }
  119. }
  120. }
  121. static void instantiateDependentAssumeAlignedAttr(
  122. Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
  123. const AssumeAlignedAttr *Aligned, Decl *New) {
  124. // The alignment expression is a constant expression.
  125. EnterExpressionEvaluationContext Unevaluated(
  126. S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  127. Expr *E, *OE = nullptr;
  128. ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
  129. if (Result.isInvalid())
  130. return;
  131. E = Result.getAs<Expr>();
  132. if (Aligned->getOffset()) {
  133. Result = S.SubstExpr(Aligned->getOffset(), TemplateArgs);
  134. if (Result.isInvalid())
  135. return;
  136. OE = Result.getAs<Expr>();
  137. }
  138. S.AddAssumeAlignedAttr(Aligned->getLocation(), New, E, OE,
  139. Aligned->getSpellingListIndex());
  140. }
  141. static void instantiateDependentAlignValueAttr(
  142. Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
  143. const AlignValueAttr *Aligned, Decl *New) {
  144. // The alignment expression is a constant expression.
  145. EnterExpressionEvaluationContext Unevaluated(
  146. S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  147. ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
  148. if (!Result.isInvalid())
  149. S.AddAlignValueAttr(Aligned->getLocation(), New, Result.getAs<Expr>(),
  150. Aligned->getSpellingListIndex());
  151. }
  152. static void instantiateDependentAllocAlignAttr(
  153. Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
  154. const AllocAlignAttr *Align, Decl *New) {
  155. Expr *Param = IntegerLiteral::Create(
  156. S.getASTContext(),
  157. llvm::APInt(64, Align->getParamIndex().getSourceIndex()),
  158. S.getASTContext().UnsignedLongLongTy, Align->getLocation());
  159. S.AddAllocAlignAttr(Align->getLocation(), New, Param,
  160. Align->getSpellingListIndex());
  161. }
  162. static Expr *instantiateDependentFunctionAttrCondition(
  163. Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
  164. const Attr *A, Expr *OldCond, const Decl *Tmpl, FunctionDecl *New) {
  165. Expr *Cond = nullptr;
  166. {
  167. Sema::ContextRAII SwitchContext(S, New);
  168. EnterExpressionEvaluationContext Unevaluated(
  169. S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  170. ExprResult Result = S.SubstExpr(OldCond, TemplateArgs);
  171. if (Result.isInvalid())
  172. return nullptr;
  173. Cond = Result.getAs<Expr>();
  174. }
  175. if (!Cond->isTypeDependent()) {
  176. ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
  177. if (Converted.isInvalid())
  178. return nullptr;
  179. Cond = Converted.get();
  180. }
  181. SmallVector<PartialDiagnosticAt, 8> Diags;
  182. if (OldCond->isValueDependent() && !Cond->isValueDependent() &&
  183. !Expr::isPotentialConstantExprUnevaluated(Cond, New, Diags)) {
  184. S.Diag(A->getLocation(), diag::err_attr_cond_never_constant_expr) << A;
  185. for (const auto &P : Diags)
  186. S.Diag(P.first, P.second);
  187. return nullptr;
  188. }
  189. return Cond;
  190. }
  191. static void instantiateDependentEnableIfAttr(
  192. Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
  193. const EnableIfAttr *EIA, const Decl *Tmpl, FunctionDecl *New) {
  194. Expr *Cond = instantiateDependentFunctionAttrCondition(
  195. S, TemplateArgs, EIA, EIA->getCond(), Tmpl, New);
  196. if (Cond)
  197. New->addAttr(new (S.getASTContext()) EnableIfAttr(
  198. EIA->getLocation(), S.getASTContext(), Cond, EIA->getMessage(),
  199. EIA->getSpellingListIndex()));
  200. }
  201. static void instantiateDependentDiagnoseIfAttr(
  202. Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
  203. const DiagnoseIfAttr *DIA, const Decl *Tmpl, FunctionDecl *New) {
  204. Expr *Cond = instantiateDependentFunctionAttrCondition(
  205. S, TemplateArgs, DIA, DIA->getCond(), Tmpl, New);
  206. if (Cond)
  207. New->addAttr(new (S.getASTContext()) DiagnoseIfAttr(
  208. DIA->getLocation(), S.getASTContext(), Cond, DIA->getMessage(),
  209. DIA->getDiagnosticType(), DIA->getArgDependent(), New,
  210. DIA->getSpellingListIndex()));
  211. }
  212. // Constructs and adds to New a new instance of CUDALaunchBoundsAttr using
  213. // template A as the base and arguments from TemplateArgs.
  214. static void instantiateDependentCUDALaunchBoundsAttr(
  215. Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
  216. const CUDALaunchBoundsAttr &Attr, Decl *New) {
  217. // The alignment expression is a constant expression.
  218. EnterExpressionEvaluationContext Unevaluated(
  219. S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  220. ExprResult Result = S.SubstExpr(Attr.getMaxThreads(), TemplateArgs);
  221. if (Result.isInvalid())
  222. return;
  223. Expr *MaxThreads = Result.getAs<Expr>();
  224. Expr *MinBlocks = nullptr;
  225. if (Attr.getMinBlocks()) {
  226. Result = S.SubstExpr(Attr.getMinBlocks(), TemplateArgs);
  227. if (Result.isInvalid())
  228. return;
  229. MinBlocks = Result.getAs<Expr>();
  230. }
  231. S.AddLaunchBoundsAttr(Attr.getLocation(), New, MaxThreads, MinBlocks,
  232. Attr.getSpellingListIndex());
  233. }
  234. static void
  235. instantiateDependentModeAttr(Sema &S,
  236. const MultiLevelTemplateArgumentList &TemplateArgs,
  237. const ModeAttr &Attr, Decl *New) {
  238. S.AddModeAttr(Attr.getRange(), New, Attr.getMode(),
  239. Attr.getSpellingListIndex(), /*InInstantiation=*/true);
  240. }
  241. /// Instantiation of 'declare simd' attribute and its arguments.
  242. static void instantiateOMPDeclareSimdDeclAttr(
  243. Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
  244. const OMPDeclareSimdDeclAttr &Attr, Decl *New) {
  245. // Allow 'this' in clauses with varlists.
  246. if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
  247. New = FTD->getTemplatedDecl();
  248. auto *FD = cast<FunctionDecl>(New);
  249. auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
  250. SmallVector<Expr *, 4> Uniforms, Aligneds, Alignments, Linears, Steps;
  251. SmallVector<unsigned, 4> LinModifiers;
  252. auto &&Subst = [&](Expr *E) -> ExprResult {
  253. if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
  254. if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  255. Sema::ContextRAII SavedContext(S, FD);
  256. LocalInstantiationScope Local(S);
  257. if (FD->getNumParams() > PVD->getFunctionScopeIndex())
  258. Local.InstantiatedLocal(
  259. PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
  260. return S.SubstExpr(E, TemplateArgs);
  261. }
  262. Sema::CXXThisScopeRAII ThisScope(S, ThisContext, /*TypeQuals=*/0,
  263. FD->isCXXInstanceMember());
  264. return S.SubstExpr(E, TemplateArgs);
  265. };
  266. ExprResult Simdlen;
  267. if (auto *E = Attr.getSimdlen())
  268. Simdlen = Subst(E);
  269. if (Attr.uniforms_size() > 0) {
  270. for(auto *E : Attr.uniforms()) {
  271. ExprResult Inst = Subst(E);
  272. if (Inst.isInvalid())
  273. continue;
  274. Uniforms.push_back(Inst.get());
  275. }
  276. }
  277. auto AI = Attr.alignments_begin();
  278. for (auto *E : Attr.aligneds()) {
  279. ExprResult Inst = Subst(E);
  280. if (Inst.isInvalid())
  281. continue;
  282. Aligneds.push_back(Inst.get());
  283. Inst = ExprEmpty();
  284. if (*AI)
  285. Inst = S.SubstExpr(*AI, TemplateArgs);
  286. Alignments.push_back(Inst.get());
  287. ++AI;
  288. }
  289. auto SI = Attr.steps_begin();
  290. for (auto *E : Attr.linears()) {
  291. ExprResult Inst = Subst(E);
  292. if (Inst.isInvalid())
  293. continue;
  294. Linears.push_back(Inst.get());
  295. Inst = ExprEmpty();
  296. if (*SI)
  297. Inst = S.SubstExpr(*SI, TemplateArgs);
  298. Steps.push_back(Inst.get());
  299. ++SI;
  300. }
  301. LinModifiers.append(Attr.modifiers_begin(), Attr.modifiers_end());
  302. (void)S.ActOnOpenMPDeclareSimdDirective(
  303. S.ConvertDeclToDeclGroup(New), Attr.getBranchState(), Simdlen.get(),
  304. Uniforms, Aligneds, Alignments, Linears, LinModifiers, Steps,
  305. Attr.getRange());
  306. }
  307. void Sema::InstantiateAttrsForDecl(
  308. const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Tmpl,
  309. Decl *New, LateInstantiatedAttrVec *LateAttrs,
  310. LocalInstantiationScope *OuterMostScope) {
  311. if (NamedDecl *ND = dyn_cast<NamedDecl>(New)) {
  312. for (const auto *TmplAttr : Tmpl->attrs()) {
  313. // FIXME: If any of the special case versions from InstantiateAttrs become
  314. // applicable to template declaration, we'll need to add them here.
  315. CXXThisScopeRAII ThisScope(
  316. *this, dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext()),
  317. /*TypeQuals*/ 0, ND->isCXXInstanceMember());
  318. Attr *NewAttr = sema::instantiateTemplateAttributeForDecl(
  319. TmplAttr, Context, *this, TemplateArgs);
  320. if (NewAttr)
  321. New->addAttr(NewAttr);
  322. }
  323. }
  324. }
  325. void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
  326. const Decl *Tmpl, Decl *New,
  327. LateInstantiatedAttrVec *LateAttrs,
  328. LocalInstantiationScope *OuterMostScope) {
  329. for (const auto *TmplAttr : Tmpl->attrs()) {
  330. // FIXME: This should be generalized to more than just the AlignedAttr.
  331. const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
  332. if (Aligned && Aligned->isAlignmentDependent()) {
  333. instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
  334. continue;
  335. }
  336. const AssumeAlignedAttr *AssumeAligned = dyn_cast<AssumeAlignedAttr>(TmplAttr);
  337. if (AssumeAligned) {
  338. instantiateDependentAssumeAlignedAttr(*this, TemplateArgs, AssumeAligned, New);
  339. continue;
  340. }
  341. const AlignValueAttr *AlignValue = dyn_cast<AlignValueAttr>(TmplAttr);
  342. if (AlignValue) {
  343. instantiateDependentAlignValueAttr(*this, TemplateArgs, AlignValue, New);
  344. continue;
  345. }
  346. if (const auto *AllocAlign = dyn_cast<AllocAlignAttr>(TmplAttr)) {
  347. instantiateDependentAllocAlignAttr(*this, TemplateArgs, AllocAlign, New);
  348. continue;
  349. }
  350. if (const auto *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr)) {
  351. instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl,
  352. cast<FunctionDecl>(New));
  353. continue;
  354. }
  355. if (const auto *DiagnoseIf = dyn_cast<DiagnoseIfAttr>(TmplAttr)) {
  356. instantiateDependentDiagnoseIfAttr(*this, TemplateArgs, DiagnoseIf, Tmpl,
  357. cast<FunctionDecl>(New));
  358. continue;
  359. }
  360. if (const CUDALaunchBoundsAttr *CUDALaunchBounds =
  361. dyn_cast<CUDALaunchBoundsAttr>(TmplAttr)) {
  362. instantiateDependentCUDALaunchBoundsAttr(*this, TemplateArgs,
  363. *CUDALaunchBounds, New);
  364. continue;
  365. }
  366. if (const ModeAttr *Mode = dyn_cast<ModeAttr>(TmplAttr)) {
  367. instantiateDependentModeAttr(*this, TemplateArgs, *Mode, New);
  368. continue;
  369. }
  370. if (const auto *OMPAttr = dyn_cast<OMPDeclareSimdDeclAttr>(TmplAttr)) {
  371. instantiateOMPDeclareSimdDeclAttr(*this, TemplateArgs, *OMPAttr, New);
  372. continue;
  373. }
  374. // Existing DLL attribute on the instantiation takes precedence.
  375. if (TmplAttr->getKind() == attr::DLLExport ||
  376. TmplAttr->getKind() == attr::DLLImport) {
  377. if (New->hasAttr<DLLExportAttr>() || New->hasAttr<DLLImportAttr>()) {
  378. continue;
  379. }
  380. }
  381. if (auto ABIAttr = dyn_cast<ParameterABIAttr>(TmplAttr)) {
  382. AddParameterABIAttr(ABIAttr->getRange(), New, ABIAttr->getABI(),
  383. ABIAttr->getSpellingListIndex());
  384. continue;
  385. }
  386. if (isa<NSConsumedAttr>(TmplAttr) || isa<CFConsumedAttr>(TmplAttr)) {
  387. AddNSConsumedAttr(TmplAttr->getRange(), New,
  388. TmplAttr->getSpellingListIndex(),
  389. isa<NSConsumedAttr>(TmplAttr),
  390. /*template instantiation*/ true);
  391. continue;
  392. }
  393. assert(!TmplAttr->isPackExpansion());
  394. if (TmplAttr->isLateParsed() && LateAttrs) {
  395. // Late parsed attributes must be instantiated and attached after the
  396. // enclosing class has been instantiated. See Sema::InstantiateClass.
  397. LocalInstantiationScope *Saved = nullptr;
  398. if (CurrentInstantiationScope)
  399. Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
  400. LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
  401. } else {
  402. // Allow 'this' within late-parsed attributes.
  403. NamedDecl *ND = dyn_cast<NamedDecl>(New);
  404. CXXRecordDecl *ThisContext =
  405. dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
  406. CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
  407. ND && ND->isCXXInstanceMember());
  408. Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
  409. *this, TemplateArgs);
  410. if (NewAttr)
  411. New->addAttr(NewAttr);
  412. }
  413. }
  414. }
  415. /// Get the previous declaration of a declaration for the purposes of template
  416. /// instantiation. If this finds a previous declaration, then the previous
  417. /// declaration of the instantiation of D should be an instantiation of the
  418. /// result of this function.
  419. template<typename DeclT>
  420. static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
  421. DeclT *Result = D->getPreviousDecl();
  422. // If the declaration is within a class, and the previous declaration was
  423. // merged from a different definition of that class, then we don't have a
  424. // previous declaration for the purpose of template instantiation.
  425. if (Result && isa<CXXRecordDecl>(D->getDeclContext()) &&
  426. D->getLexicalDeclContext() != Result->getLexicalDeclContext())
  427. return nullptr;
  428. return Result;
  429. }
  430. Decl *
  431. TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
  432. llvm_unreachable("Translation units cannot be instantiated");
  433. }
  434. Decl *
  435. TemplateDeclInstantiator::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
  436. llvm_unreachable("pragma comment cannot be instantiated");
  437. }
  438. Decl *TemplateDeclInstantiator::VisitPragmaDetectMismatchDecl(
  439. PragmaDetectMismatchDecl *D) {
  440. llvm_unreachable("pragma comment cannot be instantiated");
  441. }
  442. Decl *
  443. TemplateDeclInstantiator::VisitExternCContextDecl(ExternCContextDecl *D) {
  444. llvm_unreachable("extern \"C\" context cannot be instantiated");
  445. }
  446. Decl *
  447. TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
  448. LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
  449. D->getIdentifier());
  450. Owner->addDecl(Inst);
  451. return Inst;
  452. }
  453. Decl *
  454. TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
  455. llvm_unreachable("Namespaces cannot be instantiated");
  456. }
  457. Decl *
  458. TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
  459. NamespaceAliasDecl *Inst
  460. = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
  461. D->getNamespaceLoc(),
  462. D->getAliasLoc(),
  463. D->getIdentifier(),
  464. D->getQualifierLoc(),
  465. D->getTargetNameLoc(),
  466. D->getNamespace());
  467. Owner->addDecl(Inst);
  468. return Inst;
  469. }
  470. Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
  471. bool IsTypeAlias) {
  472. bool Invalid = false;
  473. TypeSourceInfo *DI = D->getTypeSourceInfo();
  474. if (DI->getType()->isInstantiationDependentType() ||
  475. DI->getType()->isVariablyModifiedType()) {
  476. DI = SemaRef.SubstType(DI, TemplateArgs,
  477. D->getLocation(), D->getDeclName());
  478. if (!DI) {
  479. Invalid = true;
  480. DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
  481. }
  482. } else {
  483. SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
  484. }
  485. // HACK: g++ has a bug where it gets the value kind of ?: wrong.
  486. // libstdc++ relies upon this bug in its implementation of common_type.
  487. // If we happen to be processing that implementation, fake up the g++ ?:
  488. // semantics. See LWG issue 2141 for more information on the bug.
  489. const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
  490. CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
  491. if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
  492. DT->isReferenceType() &&
  493. RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
  494. RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
  495. D->getIdentifier() && D->getIdentifier()->isStr("type") &&
  496. SemaRef.getSourceManager().isInSystemHeader(D->getBeginLoc()))
  497. // Fold it to the (non-reference) type which g++ would have produced.
  498. DI = SemaRef.Context.getTrivialTypeSourceInfo(
  499. DI->getType().getNonReferenceType());
  500. // Create the new typedef
  501. TypedefNameDecl *Typedef;
  502. if (IsTypeAlias)
  503. Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
  504. D->getLocation(), D->getIdentifier(), DI);
  505. else
  506. Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
  507. D->getLocation(), D->getIdentifier(), DI);
  508. if (Invalid)
  509. Typedef->setInvalidDecl();
  510. // If the old typedef was the name for linkage purposes of an anonymous
  511. // tag decl, re-establish that relationship for the new typedef.
  512. if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
  513. TagDecl *oldTag = oldTagType->getDecl();
  514. if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
  515. TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
  516. assert(!newTag->hasNameForLinkage());
  517. newTag->setTypedefNameForAnonDecl(Typedef);
  518. }
  519. }
  520. if (TypedefNameDecl *Prev = getPreviousDeclForInstantiation(D)) {
  521. NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
  522. TemplateArgs);
  523. if (!InstPrev)
  524. return nullptr;
  525. TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
  526. // If the typedef types are not identical, reject them.
  527. SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
  528. Typedef->setPreviousDecl(InstPrevTypedef);
  529. }
  530. SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
  531. Typedef->setAccess(D->getAccess());
  532. return Typedef;
  533. }
  534. Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
  535. Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
  536. if (Typedef)
  537. Owner->addDecl(Typedef);
  538. return Typedef;
  539. }
  540. Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
  541. Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
  542. if (Typedef)
  543. Owner->addDecl(Typedef);
  544. return Typedef;
  545. }
  546. Decl *
  547. TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
  548. // Create a local instantiation scope for this type alias template, which
  549. // will contain the instantiations of the template parameters.
  550. LocalInstantiationScope Scope(SemaRef);
  551. TemplateParameterList *TempParams = D->getTemplateParameters();
  552. TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
  553. if (!InstParams)
  554. return nullptr;
  555. TypeAliasDecl *Pattern = D->getTemplatedDecl();
  556. TypeAliasTemplateDecl *PrevAliasTemplate = nullptr;
  557. if (getPreviousDeclForInstantiation<TypedefNameDecl>(Pattern)) {
  558. DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
  559. if (!Found.empty()) {
  560. PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
  561. }
  562. }
  563. TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
  564. InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
  565. if (!AliasInst)
  566. return nullptr;
  567. TypeAliasTemplateDecl *Inst
  568. = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
  569. D->getDeclName(), InstParams, AliasInst);
  570. AliasInst->setDescribedAliasTemplate(Inst);
  571. if (PrevAliasTemplate)
  572. Inst->setPreviousDecl(PrevAliasTemplate);
  573. Inst->setAccess(D->getAccess());
  574. if (!PrevAliasTemplate)
  575. Inst->setInstantiatedFromMemberTemplate(D);
  576. Owner->addDecl(Inst);
  577. return Inst;
  578. }
  579. Decl *TemplateDeclInstantiator::VisitBindingDecl(BindingDecl *D) {
  580. auto *NewBD = BindingDecl::Create(SemaRef.Context, Owner, D->getLocation(),
  581. D->getIdentifier());
  582. NewBD->setReferenced(D->isReferenced());
  583. SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewBD);
  584. return NewBD;
  585. }
  586. Decl *TemplateDeclInstantiator::VisitDecompositionDecl(DecompositionDecl *D) {
  587. // Transform the bindings first.
  588. SmallVector<BindingDecl*, 16> NewBindings;
  589. for (auto *OldBD : D->bindings())
  590. NewBindings.push_back(cast<BindingDecl>(VisitBindingDecl(OldBD)));
  591. ArrayRef<BindingDecl*> NewBindingArray = NewBindings;
  592. auto *NewDD = cast_or_null<DecompositionDecl>(
  593. VisitVarDecl(D, /*InstantiatingVarTemplate=*/false, &NewBindingArray));
  594. if (!NewDD || NewDD->isInvalidDecl())
  595. for (auto *NewBD : NewBindings)
  596. NewBD->setInvalidDecl();
  597. return NewDD;
  598. }
  599. Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
  600. return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
  601. }
  602. Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D,
  603. bool InstantiatingVarTemplate,
  604. ArrayRef<BindingDecl*> *Bindings) {
  605. // Do substitution on the type of the declaration
  606. TypeSourceInfo *DI = SemaRef.SubstType(
  607. D->getTypeSourceInfo(), TemplateArgs, D->getTypeSpecStartLoc(),
  608. D->getDeclName(), /*AllowDeducedTST*/true);
  609. if (!DI)
  610. return nullptr;
  611. if (DI->getType()->isFunctionType()) {
  612. SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
  613. << D->isStaticDataMember() << DI->getType();
  614. return nullptr;
  615. }
  616. DeclContext *DC = Owner;
  617. if (D->isLocalExternDecl())
  618. SemaRef.adjustContextForLocalExternDecl(DC);
  619. // Build the instantiated declaration.
  620. VarDecl *Var;
  621. if (Bindings)
  622. Var = DecompositionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
  623. D->getLocation(), DI->getType(), DI,
  624. D->getStorageClass(), *Bindings);
  625. else
  626. Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
  627. D->getLocation(), D->getIdentifier(), DI->getType(),
  628. DI, D->getStorageClass());
  629. // In ARC, infer 'retaining' for variables of retainable type.
  630. if (SemaRef.getLangOpts().ObjCAutoRefCount &&
  631. SemaRef.inferObjCARCLifetime(Var))
  632. Var->setInvalidDecl();
  633. // Substitute the nested name specifier, if any.
  634. if (SubstQualifier(D, Var))
  635. return nullptr;
  636. SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
  637. StartingScope, InstantiatingVarTemplate);
  638. if (D->isNRVOVariable()) {
  639. QualType ReturnType = cast<FunctionDecl>(DC)->getReturnType();
  640. if (SemaRef.isCopyElisionCandidate(ReturnType, Var, Sema::CES_Strict))
  641. Var->setNRVOVariable(true);
  642. }
  643. Var->setImplicit(D->isImplicit());
  644. return Var;
  645. }
  646. Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
  647. AccessSpecDecl* AD
  648. = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
  649. D->getAccessSpecifierLoc(), D->getColonLoc());
  650. Owner->addHiddenDecl(AD);
  651. return AD;
  652. }
  653. Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
  654. bool Invalid = false;
  655. TypeSourceInfo *DI = D->getTypeSourceInfo();
  656. if (DI->getType()->isInstantiationDependentType() ||
  657. DI->getType()->isVariablyModifiedType()) {
  658. DI = SemaRef.SubstType(DI, TemplateArgs,
  659. D->getLocation(), D->getDeclName());
  660. if (!DI) {
  661. DI = D->getTypeSourceInfo();
  662. Invalid = true;
  663. } else if (DI->getType()->isFunctionType()) {
  664. // C++ [temp.arg.type]p3:
  665. // If a declaration acquires a function type through a type
  666. // dependent on a template-parameter and this causes a
  667. // declaration that does not use the syntactic form of a
  668. // function declarator to have function type, the program is
  669. // ill-formed.
  670. SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
  671. << DI->getType();
  672. Invalid = true;
  673. }
  674. } else {
  675. SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
  676. }
  677. Expr *BitWidth = D->getBitWidth();
  678. if (Invalid)
  679. BitWidth = nullptr;
  680. else if (BitWidth) {
  681. // The bit-width expression is a constant expression.
  682. EnterExpressionEvaluationContext Unevaluated(
  683. SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  684. ExprResult InstantiatedBitWidth
  685. = SemaRef.SubstExpr(BitWidth, TemplateArgs);
  686. if (InstantiatedBitWidth.isInvalid()) {
  687. Invalid = true;
  688. BitWidth = nullptr;
  689. } else
  690. BitWidth = InstantiatedBitWidth.getAs<Expr>();
  691. }
  692. FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
  693. DI->getType(), DI,
  694. cast<RecordDecl>(Owner),
  695. D->getLocation(),
  696. D->isMutable(),
  697. BitWidth,
  698. D->getInClassInitStyle(),
  699. D->getInnerLocStart(),
  700. D->getAccess(),
  701. nullptr);
  702. if (!Field) {
  703. cast<Decl>(Owner)->setInvalidDecl();
  704. return nullptr;
  705. }
  706. SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
  707. if (Field->hasAttrs())
  708. SemaRef.CheckAlignasUnderalignment(Field);
  709. if (Invalid)
  710. Field->setInvalidDecl();
  711. if (!Field->getDeclName()) {
  712. // Keep track of where this decl came from.
  713. SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
  714. }
  715. if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
  716. if (Parent->isAnonymousStructOrUnion() &&
  717. Parent->getRedeclContext()->isFunctionOrMethod())
  718. SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
  719. }
  720. Field->setImplicit(D->isImplicit());
  721. Field->setAccess(D->getAccess());
  722. Owner->addDecl(Field);
  723. return Field;
  724. }
  725. Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
  726. bool Invalid = false;
  727. TypeSourceInfo *DI = D->getTypeSourceInfo();
  728. if (DI->getType()->isVariablyModifiedType()) {
  729. SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
  730. << D;
  731. Invalid = true;
  732. } else if (DI->getType()->isInstantiationDependentType()) {
  733. DI = SemaRef.SubstType(DI, TemplateArgs,
  734. D->getLocation(), D->getDeclName());
  735. if (!DI) {
  736. DI = D->getTypeSourceInfo();
  737. Invalid = true;
  738. } else if (DI->getType()->isFunctionType()) {
  739. // C++ [temp.arg.type]p3:
  740. // If a declaration acquires a function type through a type
  741. // dependent on a template-parameter and this causes a
  742. // declaration that does not use the syntactic form of a
  743. // function declarator to have function type, the program is
  744. // ill-formed.
  745. SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
  746. << DI->getType();
  747. Invalid = true;
  748. }
  749. } else {
  750. SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
  751. }
  752. MSPropertyDecl *Property = MSPropertyDecl::Create(
  753. SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(),
  754. DI, D->getBeginLoc(), D->getGetterId(), D->getSetterId());
  755. SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
  756. StartingScope);
  757. if (Invalid)
  758. Property->setInvalidDecl();
  759. Property->setAccess(D->getAccess());
  760. Owner->addDecl(Property);
  761. return Property;
  762. }
  763. Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
  764. NamedDecl **NamedChain =
  765. new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
  766. int i = 0;
  767. for (auto *PI : D->chain()) {
  768. NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI,
  769. TemplateArgs);
  770. if (!Next)
  771. return nullptr;
  772. NamedChain[i++] = Next;
  773. }
  774. QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
  775. IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
  776. SemaRef.Context, Owner, D->getLocation(), D->getIdentifier(), T,
  777. {NamedChain, D->getChainingSize()});
  778. for (const auto *Attr : D->attrs())
  779. IndirectField->addAttr(Attr->clone(SemaRef.Context));
  780. IndirectField->setImplicit(D->isImplicit());
  781. IndirectField->setAccess(D->getAccess());
  782. Owner->addDecl(IndirectField);
  783. return IndirectField;
  784. }
  785. Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
  786. // Handle friend type expressions by simply substituting template
  787. // parameters into the pattern type and checking the result.
  788. if (TypeSourceInfo *Ty = D->getFriendType()) {
  789. TypeSourceInfo *InstTy;
  790. // If this is an unsupported friend, don't bother substituting template
  791. // arguments into it. The actual type referred to won't be used by any
  792. // parts of Clang, and may not be valid for instantiating. Just use the
  793. // same info for the instantiated friend.
  794. if (D->isUnsupportedFriend()) {
  795. InstTy = Ty;
  796. } else {
  797. InstTy = SemaRef.SubstType(Ty, TemplateArgs,
  798. D->getLocation(), DeclarationName());
  799. }
  800. if (!InstTy)
  801. return nullptr;
  802. FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getBeginLoc(),
  803. D->getFriendLoc(), InstTy);
  804. if (!FD)
  805. return nullptr;
  806. FD->setAccess(AS_public);
  807. FD->setUnsupportedFriend(D->isUnsupportedFriend());
  808. Owner->addDecl(FD);
  809. return FD;
  810. }
  811. NamedDecl *ND = D->getFriendDecl();
  812. assert(ND && "friend decl must be a decl or a type!");
  813. // All of the Visit implementations for the various potential friend
  814. // declarations have to be carefully written to work for friend
  815. // objects, with the most important detail being that the target
  816. // decl should almost certainly not be placed in Owner.
  817. Decl *NewND = Visit(ND);
  818. if (!NewND) return nullptr;
  819. FriendDecl *FD =
  820. FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
  821. cast<NamedDecl>(NewND), D->getFriendLoc());
  822. FD->setAccess(AS_public);
  823. FD->setUnsupportedFriend(D->isUnsupportedFriend());
  824. Owner->addDecl(FD);
  825. return FD;
  826. }
  827. Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
  828. Expr *AssertExpr = D->getAssertExpr();
  829. // The expression in a static assertion is a constant expression.
  830. EnterExpressionEvaluationContext Unevaluated(
  831. SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  832. ExprResult InstantiatedAssertExpr
  833. = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
  834. if (InstantiatedAssertExpr.isInvalid())
  835. return nullptr;
  836. return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
  837. InstantiatedAssertExpr.get(),
  838. D->getMessage(),
  839. D->getRParenLoc(),
  840. D->isFailed());
  841. }
  842. Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
  843. EnumDecl *PrevDecl = nullptr;
  844. if (EnumDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
  845. NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
  846. PatternPrev,
  847. TemplateArgs);
  848. if (!Prev) return nullptr;
  849. PrevDecl = cast<EnumDecl>(Prev);
  850. }
  851. EnumDecl *Enum =
  852. EnumDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
  853. D->getLocation(), D->getIdentifier(), PrevDecl,
  854. D->isScoped(), D->isScopedUsingClassTag(), D->isFixed());
  855. if (D->isFixed()) {
  856. if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
  857. // If we have type source information for the underlying type, it means it
  858. // has been explicitly set by the user. Perform substitution on it before
  859. // moving on.
  860. SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
  861. TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
  862. DeclarationName());
  863. if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
  864. Enum->setIntegerType(SemaRef.Context.IntTy);
  865. else
  866. Enum->setIntegerTypeSourceInfo(NewTI);
  867. } else {
  868. assert(!D->getIntegerType()->isDependentType()
  869. && "Dependent type without type source info");
  870. Enum->setIntegerType(D->getIntegerType());
  871. }
  872. }
  873. SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
  874. Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
  875. Enum->setAccess(D->getAccess());
  876. // Forward the mangling number from the template to the instantiated decl.
  877. SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D));
  878. // See if the old tag was defined along with a declarator.
  879. // If it did, mark the new tag as being associated with that declarator.
  880. if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
  881. SemaRef.Context.addDeclaratorForUnnamedTagDecl(Enum, DD);
  882. // See if the old tag was defined along with a typedef.
  883. // If it did, mark the new tag as being associated with that typedef.
  884. if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
  885. SemaRef.Context.addTypedefNameForUnnamedTagDecl(Enum, TND);
  886. if (SubstQualifier(D, Enum)) return nullptr;
  887. Owner->addDecl(Enum);
  888. EnumDecl *Def = D->getDefinition();
  889. if (Def && Def != D) {
  890. // If this is an out-of-line definition of an enum member template, check
  891. // that the underlying types match in the instantiation of both
  892. // declarations.
  893. if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
  894. SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
  895. QualType DefnUnderlying =
  896. SemaRef.SubstType(TI->getType(), TemplateArgs,
  897. UnderlyingLoc, DeclarationName());
  898. SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
  899. DefnUnderlying, /*IsFixed=*/true, Enum);
  900. }
  901. }
  902. // C++11 [temp.inst]p1: The implicit instantiation of a class template
  903. // specialization causes the implicit instantiation of the declarations, but
  904. // not the definitions of scoped member enumerations.
  905. //
  906. // DR1484 clarifies that enumeration definitions inside of a template
  907. // declaration aren't considered entities that can be separately instantiated
  908. // from the rest of the entity they are declared inside of.
  909. if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
  910. SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
  911. InstantiateEnumDefinition(Enum, Def);
  912. }
  913. return Enum;
  914. }
  915. void TemplateDeclInstantiator::InstantiateEnumDefinition(
  916. EnumDecl *Enum, EnumDecl *Pattern) {
  917. Enum->startDefinition();
  918. // Update the location to refer to the definition.
  919. Enum->setLocation(Pattern->getLocation());
  920. SmallVector<Decl*, 4> Enumerators;
  921. EnumConstantDecl *LastEnumConst = nullptr;
  922. for (auto *EC : Pattern->enumerators()) {
  923. // The specified value for the enumerator.
  924. ExprResult Value((Expr *)nullptr);
  925. if (Expr *UninstValue = EC->getInitExpr()) {
  926. // The enumerator's value expression is a constant expression.
  927. EnterExpressionEvaluationContext Unevaluated(
  928. SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  929. Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
  930. }
  931. // Drop the initial value and continue.
  932. bool isInvalid = false;
  933. if (Value.isInvalid()) {
  934. Value = nullptr;
  935. isInvalid = true;
  936. }
  937. EnumConstantDecl *EnumConst
  938. = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
  939. EC->getLocation(), EC->getIdentifier(),
  940. Value.get());
  941. if (isInvalid) {
  942. if (EnumConst)
  943. EnumConst->setInvalidDecl();
  944. Enum->setInvalidDecl();
  945. }
  946. if (EnumConst) {
  947. SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst);
  948. EnumConst->setAccess(Enum->getAccess());
  949. Enum->addDecl(EnumConst);
  950. Enumerators.push_back(EnumConst);
  951. LastEnumConst = EnumConst;
  952. if (Pattern->getDeclContext()->isFunctionOrMethod() &&
  953. !Enum->isScoped()) {
  954. // If the enumeration is within a function or method, record the enum
  955. // constant as a local.
  956. SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst);
  957. }
  958. }
  959. }
  960. SemaRef.ActOnEnumBody(Enum->getLocation(), Enum->getBraceRange(), Enum,
  961. Enumerators, nullptr, ParsedAttributesView());
  962. }
  963. Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
  964. llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
  965. }
  966. Decl *
  967. TemplateDeclInstantiator::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
  968. llvm_unreachable("BuiltinTemplateDecls cannot be instantiated.");
  969. }
  970. Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
  971. bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
  972. // Create a local instantiation scope for this class template, which
  973. // will contain the instantiations of the template parameters.
  974. LocalInstantiationScope Scope(SemaRef);
  975. TemplateParameterList *TempParams = D->getTemplateParameters();
  976. TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
  977. if (!InstParams)
  978. return nullptr;
  979. CXXRecordDecl *Pattern = D->getTemplatedDecl();
  980. // Instantiate the qualifier. We have to do this first in case
  981. // we're a friend declaration, because if we are then we need to put
  982. // the new declaration in the appropriate context.
  983. NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
  984. if (QualifierLoc) {
  985. QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
  986. TemplateArgs);
  987. if (!QualifierLoc)
  988. return nullptr;
  989. }
  990. CXXRecordDecl *PrevDecl = nullptr;
  991. ClassTemplateDecl *PrevClassTemplate = nullptr;
  992. if (!isFriend && getPreviousDeclForInstantiation(Pattern)) {
  993. DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
  994. if (!Found.empty()) {
  995. PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
  996. if (PrevClassTemplate)
  997. PrevDecl = PrevClassTemplate->getTemplatedDecl();
  998. }
  999. }
  1000. // If this isn't a friend, then it's a member template, in which
  1001. // case we just want to build the instantiation in the
  1002. // specialization. If it is a friend, we want to build it in
  1003. // the appropriate context.
  1004. DeclContext *DC = Owner;
  1005. if (isFriend) {
  1006. if (QualifierLoc) {
  1007. CXXScopeSpec SS;
  1008. SS.Adopt(QualifierLoc);
  1009. DC = SemaRef.computeDeclContext(SS);
  1010. if (!DC) return nullptr;
  1011. } else {
  1012. DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
  1013. Pattern->getDeclContext(),
  1014. TemplateArgs);
  1015. }
  1016. // Look for a previous declaration of the template in the owning
  1017. // context.
  1018. LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
  1019. Sema::LookupOrdinaryName,
  1020. SemaRef.forRedeclarationInCurContext());
  1021. SemaRef.LookupQualifiedName(R, DC);
  1022. if (R.isSingleResult()) {
  1023. PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
  1024. if (PrevClassTemplate)
  1025. PrevDecl = PrevClassTemplate->getTemplatedDecl();
  1026. }
  1027. if (!PrevClassTemplate && QualifierLoc) {
  1028. SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
  1029. << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
  1030. << QualifierLoc.getSourceRange();
  1031. return nullptr;
  1032. }
  1033. bool AdoptedPreviousTemplateParams = false;
  1034. if (PrevClassTemplate) {
  1035. bool Complain = true;
  1036. // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
  1037. // template for struct std::tr1::__detail::_Map_base, where the
  1038. // template parameters of the friend declaration don't match the
  1039. // template parameters of the original declaration. In this one
  1040. // case, we don't complain about the ill-formed friend
  1041. // declaration.
  1042. if (isFriend && Pattern->getIdentifier() &&
  1043. Pattern->getIdentifier()->isStr("_Map_base") &&
  1044. DC->isNamespace() &&
  1045. cast<NamespaceDecl>(DC)->getIdentifier() &&
  1046. cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
  1047. DeclContext *DCParent = DC->getParent();
  1048. if (DCParent->isNamespace() &&
  1049. cast<NamespaceDecl>(DCParent)->getIdentifier() &&
  1050. cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
  1051. if (cast<Decl>(DCParent)->isInStdNamespace())
  1052. Complain = false;
  1053. }
  1054. }
  1055. TemplateParameterList *PrevParams
  1056. = PrevClassTemplate->getMostRecentDecl()->getTemplateParameters();
  1057. // Make sure the parameter lists match.
  1058. if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
  1059. Complain,
  1060. Sema::TPL_TemplateMatch)) {
  1061. if (Complain)
  1062. return nullptr;
  1063. AdoptedPreviousTemplateParams = true;
  1064. InstParams = PrevParams;
  1065. }
  1066. // Do some additional validation, then merge default arguments
  1067. // from the existing declarations.
  1068. if (!AdoptedPreviousTemplateParams &&
  1069. SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
  1070. Sema::TPC_ClassTemplate))
  1071. return nullptr;
  1072. }
  1073. }
  1074. CXXRecordDecl *RecordInst = CXXRecordDecl::Create(
  1075. SemaRef.Context, Pattern->getTagKind(), DC, Pattern->getBeginLoc(),
  1076. Pattern->getLocation(), Pattern->getIdentifier(), PrevDecl,
  1077. /*DelayTypeCreation=*/true);
  1078. if (QualifierLoc)
  1079. RecordInst->setQualifierInfo(QualifierLoc);
  1080. SemaRef.InstantiateAttrsForDecl(TemplateArgs, Pattern, RecordInst, LateAttrs,
  1081. StartingScope);
  1082. ClassTemplateDecl *Inst
  1083. = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
  1084. D->getIdentifier(), InstParams, RecordInst);
  1085. assert(!(isFriend && Owner->isDependentContext()));
  1086. Inst->setPreviousDecl(PrevClassTemplate);
  1087. RecordInst->setDescribedClassTemplate(Inst);
  1088. if (isFriend) {
  1089. if (PrevClassTemplate)
  1090. Inst->setAccess(PrevClassTemplate->getAccess());
  1091. else
  1092. Inst->setAccess(D->getAccess());
  1093. Inst->setObjectOfFriendDecl();
  1094. // TODO: do we want to track the instantiation progeny of this
  1095. // friend target decl?
  1096. } else {
  1097. Inst->setAccess(D->getAccess());
  1098. if (!PrevClassTemplate)
  1099. Inst->setInstantiatedFromMemberTemplate(D);
  1100. }
  1101. // Trigger creation of the type for the instantiation.
  1102. SemaRef.Context.getInjectedClassNameType(RecordInst,
  1103. Inst->getInjectedClassNameSpecialization());
  1104. // Finish handling of friends.
  1105. if (isFriend) {
  1106. DC->makeDeclVisibleInContext(Inst);
  1107. Inst->setLexicalDeclContext(Owner);
  1108. RecordInst->setLexicalDeclContext(Owner);
  1109. return Inst;
  1110. }
  1111. if (D->isOutOfLine()) {
  1112. Inst->setLexicalDeclContext(D->getLexicalDeclContext());
  1113. RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
  1114. }
  1115. Owner->addDecl(Inst);
  1116. if (!PrevClassTemplate) {
  1117. // Queue up any out-of-line partial specializations of this member
  1118. // class template; the client will force their instantiation once
  1119. // the enclosing class has been instantiated.
  1120. SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
  1121. D->getPartialSpecializations(PartialSpecs);
  1122. for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
  1123. if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
  1124. OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
  1125. }
  1126. return Inst;
  1127. }
  1128. Decl *
  1129. TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
  1130. ClassTemplatePartialSpecializationDecl *D) {
  1131. ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
  1132. // Lookup the already-instantiated declaration in the instantiation
  1133. // of the class template and return that.
  1134. DeclContext::lookup_result Found
  1135. = Owner->lookup(ClassTemplate->getDeclName());
  1136. if (Found.empty())
  1137. return nullptr;
  1138. ClassTemplateDecl *InstClassTemplate
  1139. = dyn_cast<ClassTemplateDecl>(Found.front());
  1140. if (!InstClassTemplate)
  1141. return nullptr;
  1142. if (ClassTemplatePartialSpecializationDecl *Result
  1143. = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
  1144. return Result;
  1145. return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
  1146. }
  1147. Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
  1148. assert(D->getTemplatedDecl()->isStaticDataMember() &&
  1149. "Only static data member templates are allowed.");
  1150. // Create a local instantiation scope for this variable template, which
  1151. // will contain the instantiations of the template parameters.
  1152. LocalInstantiationScope Scope(SemaRef);
  1153. TemplateParameterList *TempParams = D->getTemplateParameters();
  1154. TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
  1155. if (!InstParams)
  1156. return nullptr;
  1157. VarDecl *Pattern = D->getTemplatedDecl();
  1158. VarTemplateDecl *PrevVarTemplate = nullptr;
  1159. if (getPreviousDeclForInstantiation(Pattern)) {
  1160. DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
  1161. if (!Found.empty())
  1162. PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
  1163. }
  1164. VarDecl *VarInst =
  1165. cast_or_null<VarDecl>(VisitVarDecl(Pattern,
  1166. /*InstantiatingVarTemplate=*/true));
  1167. if (!VarInst) return nullptr;
  1168. DeclContext *DC = Owner;
  1169. VarTemplateDecl *Inst = VarTemplateDecl::Create(
  1170. SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
  1171. VarInst);
  1172. VarInst->setDescribedVarTemplate(Inst);
  1173. Inst->setPreviousDecl(PrevVarTemplate);
  1174. Inst->setAccess(D->getAccess());
  1175. if (!PrevVarTemplate)
  1176. Inst->setInstantiatedFromMemberTemplate(D);
  1177. if (D->isOutOfLine()) {
  1178. Inst->setLexicalDeclContext(D->getLexicalDeclContext());
  1179. VarInst->setLexicalDeclContext(D->getLexicalDeclContext());
  1180. }
  1181. Owner->addDecl(Inst);
  1182. if (!PrevVarTemplate) {
  1183. // Queue up any out-of-line partial specializations of this member
  1184. // variable template; the client will force their instantiation once
  1185. // the enclosing class has been instantiated.
  1186. SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
  1187. D->getPartialSpecializations(PartialSpecs);
  1188. for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
  1189. if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
  1190. OutOfLineVarPartialSpecs.push_back(
  1191. std::make_pair(Inst, PartialSpecs[I]));
  1192. }
  1193. return Inst;
  1194. }
  1195. Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
  1196. VarTemplatePartialSpecializationDecl *D) {
  1197. assert(D->isStaticDataMember() &&
  1198. "Only static data member templates are allowed.");
  1199. VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
  1200. // Lookup the already-instantiated declaration and return that.
  1201. DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
  1202. assert(!Found.empty() && "Instantiation found nothing?");
  1203. VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
  1204. assert(InstVarTemplate && "Instantiation did not find a variable template?");
  1205. if (VarTemplatePartialSpecializationDecl *Result =
  1206. InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
  1207. return Result;
  1208. return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
  1209. }
  1210. Decl *
  1211. TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
  1212. // Create a local instantiation scope for this function template, which
  1213. // will contain the instantiations of the template parameters and then get
  1214. // merged with the local instantiation scope for the function template
  1215. // itself.
  1216. LocalInstantiationScope Scope(SemaRef);
  1217. TemplateParameterList *TempParams = D->getTemplateParameters();
  1218. TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
  1219. if (!InstParams)
  1220. return nullptr;
  1221. FunctionDecl *Instantiated = nullptr;
  1222. if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
  1223. Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
  1224. InstParams));
  1225. else
  1226. Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
  1227. D->getTemplatedDecl(),
  1228. InstParams));
  1229. if (!Instantiated)
  1230. return nullptr;
  1231. // Link the instantiated function template declaration to the function
  1232. // template from which it was instantiated.
  1233. FunctionTemplateDecl *InstTemplate
  1234. = Instantiated->getDescribedFunctionTemplate();
  1235. InstTemplate->setAccess(D->getAccess());
  1236. assert(InstTemplate &&
  1237. "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
  1238. bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
  1239. // Link the instantiation back to the pattern *unless* this is a
  1240. // non-definition friend declaration.
  1241. if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
  1242. !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
  1243. InstTemplate->setInstantiatedFromMemberTemplate(D);
  1244. // Make declarations visible in the appropriate context.
  1245. if (!isFriend) {
  1246. Owner->addDecl(InstTemplate);
  1247. } else if (InstTemplate->getDeclContext()->isRecord() &&
  1248. !getPreviousDeclForInstantiation(D)) {
  1249. SemaRef.CheckFriendAccess(InstTemplate);
  1250. }
  1251. return InstTemplate;
  1252. }
  1253. Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
  1254. CXXRecordDecl *PrevDecl = nullptr;
  1255. if (D->isInjectedClassName())
  1256. PrevDecl = cast<CXXRecordDecl>(Owner);
  1257. else if (CXXRecordDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
  1258. NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
  1259. PatternPrev,
  1260. TemplateArgs);
  1261. if (!Prev) return nullptr;
  1262. PrevDecl = cast<CXXRecordDecl>(Prev);
  1263. }
  1264. CXXRecordDecl *Record = CXXRecordDecl::Create(
  1265. SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(),
  1266. D->getLocation(), D->getIdentifier(), PrevDecl);
  1267. // Substitute the nested name specifier, if any.
  1268. if (SubstQualifier(D, Record))
  1269. return nullptr;
  1270. SemaRef.InstantiateAttrsForDecl(TemplateArgs, D, Record, LateAttrs,
  1271. StartingScope);
  1272. Record->setImplicit(D->isImplicit());
  1273. // FIXME: Check against AS_none is an ugly hack to work around the issue that
  1274. // the tag decls introduced by friend class declarations don't have an access
  1275. // specifier. Remove once this area of the code gets sorted out.
  1276. if (D->getAccess() != AS_none)
  1277. Record->setAccess(D->getAccess());
  1278. if (!D->isInjectedClassName())
  1279. Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
  1280. // If the original function was part of a friend declaration,
  1281. // inherit its namespace state.
  1282. if (D->getFriendObjectKind())
  1283. Record->setObjectOfFriendDecl();
  1284. // Make sure that anonymous structs and unions are recorded.
  1285. if (D->isAnonymousStructOrUnion())
  1286. Record->setAnonymousStructOrUnion(true);
  1287. if (D->isLocalClass())
  1288. SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
  1289. // Forward the mangling number from the template to the instantiated decl.
  1290. SemaRef.Context.setManglingNumber(Record,
  1291. SemaRef.Context.getManglingNumber(D));
  1292. // See if the old tag was defined along with a declarator.
  1293. // If it did, mark the new tag as being associated with that declarator.
  1294. if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
  1295. SemaRef.Context.addDeclaratorForUnnamedTagDecl(Record, DD);
  1296. // See if the old tag was defined along with a typedef.
  1297. // If it did, mark the new tag as being associated with that typedef.
  1298. if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
  1299. SemaRef.Context.addTypedefNameForUnnamedTagDecl(Record, TND);
  1300. Owner->addDecl(Record);
  1301. // DR1484 clarifies that the members of a local class are instantiated as part
  1302. // of the instantiation of their enclosing entity.
  1303. if (D->isCompleteDefinition() && D->isLocalClass()) {
  1304. Sema::LocalEagerInstantiationScope LocalInstantiations(SemaRef);
  1305. SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
  1306. TSK_ImplicitInstantiation,
  1307. /*Complain=*/true);
  1308. // For nested local classes, we will instantiate the members when we
  1309. // reach the end of the outermost (non-nested) local class.
  1310. if (!D->isCXXClassMember())
  1311. SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
  1312. TSK_ImplicitInstantiation);
  1313. // This class may have local implicit instantiations that need to be
  1314. // performed within this scope.
  1315. LocalInstantiations.perform();
  1316. }
  1317. SemaRef.DiagnoseUnusedNestedTypedefs(Record);
  1318. return Record;
  1319. }
  1320. /// Adjust the given function type for an instantiation of the
  1321. /// given declaration, to cope with modifications to the function's type that
  1322. /// aren't reflected in the type-source information.
  1323. ///
  1324. /// \param D The declaration we're instantiating.
  1325. /// \param TInfo The already-instantiated type.
  1326. static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
  1327. FunctionDecl *D,
  1328. TypeSourceInfo *TInfo) {
  1329. const FunctionProtoType *OrigFunc
  1330. = D->getType()->castAs<FunctionProtoType>();
  1331. const FunctionProtoType *NewFunc
  1332. = TInfo->getType()->castAs<FunctionProtoType>();
  1333. if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
  1334. return TInfo->getType();
  1335. FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
  1336. NewEPI.ExtInfo = OrigFunc->getExtInfo();
  1337. return Context.getFunctionType(NewFunc->getReturnType(),
  1338. NewFunc->getParamTypes(), NewEPI);
  1339. }
  1340. /// Normal class members are of more specific types and therefore
  1341. /// don't make it here. This function serves three purposes:
  1342. /// 1) instantiating function templates
  1343. /// 2) substituting friend declarations
  1344. /// 3) substituting deduction guide declarations for nested class templates
  1345. Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
  1346. TemplateParameterList *TemplateParams) {
  1347. // Check whether there is already a function template specialization for
  1348. // this declaration.
  1349. FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
  1350. if (FunctionTemplate && !TemplateParams) {
  1351. ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
  1352. void *InsertPos = nullptr;
  1353. FunctionDecl *SpecFunc
  1354. = FunctionTemplate->findSpecialization(Innermost, InsertPos);
  1355. // If we already have a function template specialization, return it.
  1356. if (SpecFunc)
  1357. return SpecFunc;
  1358. }
  1359. bool isFriend;
  1360. if (FunctionTemplate)
  1361. isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
  1362. else
  1363. isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
  1364. bool MergeWithParentScope = (TemplateParams != nullptr) ||
  1365. Owner->isFunctionOrMethod() ||
  1366. !(isa<Decl>(Owner) &&
  1367. cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
  1368. LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
  1369. SmallVector<ParmVarDecl *, 4> Params;
  1370. TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
  1371. if (!TInfo)
  1372. return nullptr;
  1373. QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
  1374. NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
  1375. if (QualifierLoc) {
  1376. QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
  1377. TemplateArgs);
  1378. if (!QualifierLoc)
  1379. return nullptr;
  1380. }
  1381. // If we're instantiating a local function declaration, put the result
  1382. // in the enclosing namespace; otherwise we need to find the instantiated
  1383. // context.
  1384. DeclContext *DC;
  1385. if (D->isLocalExternDecl()) {
  1386. DC = Owner;
  1387. SemaRef.adjustContextForLocalExternDecl(DC);
  1388. } else if (isFriend && QualifierLoc) {
  1389. CXXScopeSpec SS;
  1390. SS.Adopt(QualifierLoc);
  1391. DC = SemaRef.computeDeclContext(SS);
  1392. if (!DC) return nullptr;
  1393. } else {
  1394. DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
  1395. TemplateArgs);
  1396. }
  1397. DeclarationNameInfo NameInfo
  1398. = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
  1399. FunctionDecl *Function;
  1400. if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
  1401. Function = CXXDeductionGuideDecl::Create(
  1402. SemaRef.Context, DC, D->getInnerLocStart(), DGuide->isExplicit(),
  1403. NameInfo, T, TInfo, D->getSourceRange().getEnd());
  1404. if (DGuide->isCopyDeductionCandidate())
  1405. cast<CXXDeductionGuideDecl>(Function)->setIsCopyDeductionCandidate();
  1406. Function->setAccess(D->getAccess());
  1407. } else {
  1408. Function = FunctionDecl::Create(
  1409. SemaRef.Context, DC, D->getInnerLocStart(), NameInfo, T, TInfo,
  1410. D->getCanonicalDecl()->getStorageClass(), D->isInlineSpecified(),
  1411. D->hasWrittenPrototype(), D->isConstexpr());
  1412. Function->setRangeEnd(D->getSourceRange().getEnd());
  1413. }
  1414. if (D->isInlined())
  1415. Function->setImplicitlyInline();
  1416. if (QualifierLoc)
  1417. Function->setQualifierInfo(QualifierLoc);
  1418. if (D->isLocalExternDecl())
  1419. Function->setLocalExternDecl();
  1420. DeclContext *LexicalDC = Owner;
  1421. if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
  1422. assert(D->getDeclContext()->isFileContext());
  1423. LexicalDC = D->getDeclContext();
  1424. }
  1425. Function->setLexicalDeclContext(LexicalDC);
  1426. // Attach the parameters
  1427. for (unsigned P = 0; P < Params.size(); ++P)
  1428. if (Params[P])
  1429. Params[P]->setOwningFunction(Function);
  1430. Function->setParams(Params);
  1431. if (TemplateParams) {
  1432. // Our resulting instantiation is actually a function template, since we
  1433. // are substituting only the outer template parameters. For example, given
  1434. //
  1435. // template<typename T>
  1436. // struct X {
  1437. // template<typename U> friend void f(T, U);
  1438. // };
  1439. //
  1440. // X<int> x;
  1441. //
  1442. // We are instantiating the friend function template "f" within X<int>,
  1443. // which means substituting int for T, but leaving "f" as a friend function
  1444. // template.
  1445. // Build the function template itself.
  1446. FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
  1447. Function->getLocation(),
  1448. Function->getDeclName(),
  1449. TemplateParams, Function);
  1450. Function->setDescribedFunctionTemplate(FunctionTemplate);
  1451. FunctionTemplate->setLexicalDeclContext(LexicalDC);
  1452. if (isFriend && D->isThisDeclarationADefinition()) {
  1453. FunctionTemplate->setInstantiatedFromMemberTemplate(
  1454. D->getDescribedFunctionTemplate());
  1455. }
  1456. } else if (FunctionTemplate) {
  1457. // Record this function template specialization.
  1458. ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
  1459. Function->setFunctionTemplateSpecialization(FunctionTemplate,
  1460. TemplateArgumentList::CreateCopy(SemaRef.Context,
  1461. Innermost),
  1462. /*InsertPos=*/nullptr);
  1463. } else if (isFriend && D->isThisDeclarationADefinition()) {
  1464. // Do not connect the friend to the template unless it's actually a
  1465. // definition. We don't want non-template functions to be marked as being
  1466. // template instantiations.
  1467. Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
  1468. }
  1469. if (InitFunctionInstantiation(Function, D))
  1470. Function->setInvalidDecl();
  1471. bool isExplicitSpecialization = false;
  1472. LookupResult Previous(
  1473. SemaRef, Function->getDeclName(), SourceLocation(),
  1474. D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
  1475. : Sema::LookupOrdinaryName,
  1476. D->isLocalExternDecl() ? Sema::ForExternalRedeclaration
  1477. : SemaRef.forRedeclarationInCurContext());
  1478. if (DependentFunctionTemplateSpecializationInfo *Info
  1479. = D->getDependentSpecializationInfo()) {
  1480. assert(isFriend && "non-friend has dependent specialization info?");
  1481. // This needs to be set now for future sanity.
  1482. Function->setObjectOfFriendDecl();
  1483. // Instantiate the explicit template arguments.
  1484. TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
  1485. Info->getRAngleLoc());
  1486. if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
  1487. ExplicitArgs, TemplateArgs))
  1488. return nullptr;
  1489. // Map the candidate templates to their instantiations.
  1490. for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
  1491. Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
  1492. Info->getTemplate(I),
  1493. TemplateArgs);
  1494. if (!Temp) return nullptr;
  1495. Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
  1496. }
  1497. if (SemaRef.CheckFunctionTemplateSpecialization(Function,
  1498. &ExplicitArgs,
  1499. Previous))
  1500. Function->setInvalidDecl();
  1501. isExplicitSpecialization = true;
  1502. } else if (TemplateParams || !FunctionTemplate) {
  1503. // Look only into the namespace where the friend would be declared to
  1504. // find a previous declaration. This is the innermost enclosing namespace,
  1505. // as described in ActOnFriendFunctionDecl.
  1506. SemaRef.LookupQualifiedName(Previous, DC);
  1507. // In C++, the previous declaration we find might be a tag type
  1508. // (class or enum). In this case, the new declaration will hide the
  1509. // tag type. Note that this does does not apply if we're declaring a
  1510. // typedef (C++ [dcl.typedef]p4).
  1511. if (Previous.isSingleTagDecl())
  1512. Previous.clear();
  1513. }
  1514. if (isFriend)
  1515. Function->setObjectOfFriendDecl();
  1516. SemaRef.CheckFunctionDeclaration(/*Scope*/ nullptr, Function, Previous,
  1517. isExplicitSpecialization);
  1518. NamedDecl *PrincipalDecl = (TemplateParams
  1519. ? cast<NamedDecl>(FunctionTemplate)
  1520. : Function);
  1521. // If the original function was part of a friend declaration,
  1522. // inherit its namespace state and add it to the owner.
  1523. if (isFriend) {
  1524. PrincipalDecl->setObjectOfFriendDecl();
  1525. DC->makeDeclVisibleInContext(PrincipalDecl);
  1526. bool QueuedInstantiation = false;
  1527. // C++11 [temp.friend]p4 (DR329):
  1528. // When a function is defined in a friend function declaration in a class
  1529. // template, the function is instantiated when the function is odr-used.
  1530. // The same restrictions on multiple declarations and definitions that
  1531. // apply to non-template function declarations and definitions also apply
  1532. // to these implicit definitions.
  1533. if (D->isThisDeclarationADefinition()) {
  1534. SemaRef.CheckForFunctionRedefinition(Function);
  1535. if (!Function->isInvalidDecl()) {
  1536. for (auto R : Function->redecls()) {
  1537. if (R == Function)
  1538. continue;
  1539. // If some prior declaration of this function has been used, we need
  1540. // to instantiate its definition.
  1541. if (!QueuedInstantiation && R->isUsed(false)) {
  1542. if (MemberSpecializationInfo *MSInfo =
  1543. Function->getMemberSpecializationInfo()) {
  1544. if (MSInfo->getPointOfInstantiation().isInvalid()) {
  1545. SourceLocation Loc = R->getLocation(); // FIXME
  1546. MSInfo->setPointOfInstantiation(Loc);
  1547. SemaRef.PendingLocalImplicitInstantiations.push_back(
  1548. std::make_pair(Function, Loc));
  1549. QueuedInstantiation = true;
  1550. }
  1551. }
  1552. }
  1553. }
  1554. }
  1555. }
  1556. // Check the template parameter list against the previous declaration. The
  1557. // goal here is to pick up default arguments added since the friend was
  1558. // declared; we know the template parameter lists match, since otherwise
  1559. // we would not have picked this template as the previous declaration.
  1560. if (TemplateParams && FunctionTemplate->getPreviousDecl()) {
  1561. SemaRef.CheckTemplateParameterList(
  1562. TemplateParams,
  1563. FunctionTemplate->getPreviousDecl()->getTemplateParameters(),
  1564. Function->isThisDeclarationADefinition()
  1565. ? Sema::TPC_FriendFunctionTemplateDefinition
  1566. : Sema::TPC_FriendFunctionTemplate);
  1567. }
  1568. }
  1569. if (Function->isLocalExternDecl() && !Function->getPreviousDecl())
  1570. DC->makeDeclVisibleInContext(PrincipalDecl);
  1571. if (Function->isOverloadedOperator() && !DC->isRecord() &&
  1572. PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
  1573. PrincipalDecl->setNonMemberOperator();
  1574. assert(!D->isDefaulted() && "only methods should be defaulted");
  1575. return Function;
  1576. }
  1577. Decl *
  1578. TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
  1579. TemplateParameterList *TemplateParams,
  1580. bool IsClassScopeSpecialization) {
  1581. FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
  1582. if (FunctionTemplate && !TemplateParams) {
  1583. // We are creating a function template specialization from a function
  1584. // template. Check whether there is already a function template
  1585. // specialization for this particular set of template arguments.
  1586. ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
  1587. void *InsertPos = nullptr;
  1588. FunctionDecl *SpecFunc
  1589. = FunctionTemplate->findSpecialization(Innermost, InsertPos);
  1590. // If we already have a function template specialization, return it.
  1591. if (SpecFunc)
  1592. return SpecFunc;
  1593. }
  1594. bool isFriend;
  1595. if (FunctionTemplate)
  1596. isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
  1597. else
  1598. isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
  1599. bool MergeWithParentScope = (TemplateParams != nullptr) ||
  1600. !(isa<Decl>(Owner) &&
  1601. cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
  1602. LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
  1603. // Instantiate enclosing template arguments for friends.
  1604. SmallVector<TemplateParameterList *, 4> TempParamLists;
  1605. unsigned NumTempParamLists = 0;
  1606. if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
  1607. TempParamLists.resize(NumTempParamLists);
  1608. for (unsigned I = 0; I != NumTempParamLists; ++I) {
  1609. TemplateParameterList *TempParams = D->getTemplateParameterList(I);
  1610. TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
  1611. if (!InstParams)
  1612. return nullptr;
  1613. TempParamLists[I] = InstParams;
  1614. }
  1615. }
  1616. SmallVector<ParmVarDecl *, 4> Params;
  1617. TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
  1618. if (!TInfo)
  1619. return nullptr;
  1620. QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
  1621. NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
  1622. if (QualifierLoc) {
  1623. QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
  1624. TemplateArgs);
  1625. if (!QualifierLoc)
  1626. return nullptr;
  1627. }
  1628. DeclContext *DC = Owner;
  1629. if (isFriend) {
  1630. if (QualifierLoc) {
  1631. CXXScopeSpec SS;
  1632. SS.Adopt(QualifierLoc);
  1633. DC = SemaRef.computeDeclContext(SS);
  1634. if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
  1635. return nullptr;
  1636. } else {
  1637. DC = SemaRef.FindInstantiatedContext(D->getLocation(),
  1638. D->getDeclContext(),
  1639. TemplateArgs);
  1640. }
  1641. if (!DC) return nullptr;
  1642. }
  1643. // Build the instantiated method declaration.
  1644. CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
  1645. CXXMethodDecl *Method = nullptr;
  1646. SourceLocation StartLoc = D->getInnerLocStart();
  1647. DeclarationNameInfo NameInfo
  1648. = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
  1649. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
  1650. Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
  1651. StartLoc, NameInfo, T, TInfo,
  1652. Constructor->isExplicit(),
  1653. Constructor->isInlineSpecified(),
  1654. false, Constructor->isConstexpr());
  1655. Method->setRangeEnd(Constructor->getEndLoc());
  1656. } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
  1657. Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
  1658. StartLoc, NameInfo, T, TInfo,
  1659. Destructor->isInlineSpecified(),
  1660. false);
  1661. Method->setRangeEnd(Destructor->getEndLoc());
  1662. } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
  1663. Method = CXXConversionDecl::Create(
  1664. SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
  1665. Conversion->isInlineSpecified(), Conversion->isExplicit(),
  1666. Conversion->isConstexpr(), Conversion->getEndLoc());
  1667. } else {
  1668. StorageClass SC = D->isStatic() ? SC_Static : SC_None;
  1669. Method = CXXMethodDecl::Create(SemaRef.Context, Record, StartLoc, NameInfo,
  1670. T, TInfo, SC, D->isInlineSpecified(),
  1671. D->isConstexpr(), D->getEndLoc());
  1672. }
  1673. if (D->isInlined())
  1674. Method->setImplicitlyInline();
  1675. if (QualifierLoc)
  1676. Method->setQualifierInfo(QualifierLoc);
  1677. if (TemplateParams) {
  1678. // Our resulting instantiation is actually a function template, since we
  1679. // are substituting only the outer template parameters. For example, given
  1680. //
  1681. // template<typename T>
  1682. // struct X {
  1683. // template<typename U> void f(T, U);
  1684. // };
  1685. //
  1686. // X<int> x;
  1687. //
  1688. // We are instantiating the member template "f" within X<int>, which means
  1689. // substituting int for T, but leaving "f" as a member function template.
  1690. // Build the function template itself.
  1691. FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
  1692. Method->getLocation(),
  1693. Method->getDeclName(),
  1694. TemplateParams, Method);
  1695. if (isFriend) {
  1696. FunctionTemplate->setLexicalDeclContext(Owner);
  1697. FunctionTemplate->setObjectOfFriendDecl();
  1698. } else if (D->isOutOfLine())
  1699. FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
  1700. Method->setDescribedFunctionTemplate(FunctionTemplate);
  1701. } else if (FunctionTemplate) {
  1702. // Record this function template specialization.
  1703. ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
  1704. Method->setFunctionTemplateSpecialization(FunctionTemplate,
  1705. TemplateArgumentList::CreateCopy(SemaRef.Context,
  1706. Innermost),
  1707. /*InsertPos=*/nullptr);
  1708. } else if (!isFriend) {
  1709. // Record that this is an instantiation of a member function.
  1710. Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
  1711. }
  1712. // If we are instantiating a member function defined
  1713. // out-of-line, the instantiation will have the same lexical
  1714. // context (which will be a namespace scope) as the template.
  1715. if (isFriend) {
  1716. if (NumTempParamLists)
  1717. Method->setTemplateParameterListsInfo(
  1718. SemaRef.Context,
  1719. llvm::makeArrayRef(TempParamLists.data(), NumTempParamLists));
  1720. Method->setLexicalDeclContext(Owner);
  1721. Method->setObjectOfFriendDecl();
  1722. } else if (D->isOutOfLine())
  1723. Method->setLexicalDeclContext(D->getLexicalDeclContext());
  1724. // Attach the parameters
  1725. for (unsigned P = 0; P < Params.size(); ++P)
  1726. Params[P]->setOwningFunction(Method);
  1727. Method->setParams(Params);
  1728. if (InitMethodInstantiation(Method, D))
  1729. Method->setInvalidDecl();
  1730. LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
  1731. Sema::ForExternalRedeclaration);
  1732. if (!FunctionTemplate || TemplateParams || isFriend) {
  1733. SemaRef.LookupQualifiedName(Previous, Record);
  1734. // In C++, the previous declaration we find might be a tag type
  1735. // (class or enum). In this case, the new declaration will hide the
  1736. // tag type. Note that this does does not apply if we're declaring a
  1737. // typedef (C++ [dcl.typedef]p4).
  1738. if (Previous.isSingleTagDecl())
  1739. Previous.clear();
  1740. }
  1741. if (!IsClassScopeSpecialization)
  1742. SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous, false);
  1743. if (D->isPure())
  1744. SemaRef.CheckPureMethod(Method, SourceRange());
  1745. // Propagate access. For a non-friend declaration, the access is
  1746. // whatever we're propagating from. For a friend, it should be the
  1747. // previous declaration we just found.
  1748. if (isFriend && Method->getPreviousDecl())
  1749. Method->setAccess(Method->getPreviousDecl()->getAccess());
  1750. else
  1751. Method->setAccess(D->getAccess());
  1752. if (FunctionTemplate)
  1753. FunctionTemplate->setAccess(Method->getAccess());
  1754. SemaRef.CheckOverrideControl(Method);
  1755. // If a function is defined as defaulted or deleted, mark it as such now.
  1756. if (D->isExplicitlyDefaulted())
  1757. SemaRef.SetDeclDefaulted(Method, Method->getLocation());
  1758. if (D->isDeletedAsWritten())
  1759. SemaRef.SetDeclDeleted(Method, Method->getLocation());
  1760. // If there's a function template, let our caller handle it.
  1761. if (FunctionTemplate) {
  1762. // do nothing
  1763. // Don't hide a (potentially) valid declaration with an invalid one.
  1764. } else if (Method->isInvalidDecl() && !Previous.empty()) {
  1765. // do nothing
  1766. // Otherwise, check access to friends and make them visible.
  1767. } else if (isFriend) {
  1768. // We only need to re-check access for methods which we didn't
  1769. // manage to match during parsing.
  1770. if (!D->getPreviousDecl())
  1771. SemaRef.CheckFriendAccess(Method);
  1772. Record->makeDeclVisibleInContext(Method);
  1773. // Otherwise, add the declaration. We don't need to do this for
  1774. // class-scope specializations because we'll have matched them with
  1775. // the appropriate template.
  1776. } else if (!IsClassScopeSpecialization) {
  1777. Owner->addDecl(Method);
  1778. }
  1779. return Method;
  1780. }
  1781. Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
  1782. return VisitCXXMethodDecl(D);
  1783. }
  1784. Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
  1785. return VisitCXXMethodDecl(D);
  1786. }
  1787. Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
  1788. return VisitCXXMethodDecl(D);
  1789. }
  1790. Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
  1791. return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None,
  1792. /*ExpectParameterPack=*/ false);
  1793. }
  1794. Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
  1795. TemplateTypeParmDecl *D) {
  1796. // TODO: don't always clone when decls are refcounted.
  1797. assert(D->getTypeForDecl()->isTemplateTypeParmType());
  1798. TemplateTypeParmDecl *Inst = TemplateTypeParmDecl::Create(
  1799. SemaRef.Context, Owner, D->getBeginLoc(), D->getLocation(),
  1800. D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), D->getIndex(),
  1801. D->getIdentifier(), D->wasDeclaredWithTypename(), D->isParameterPack());
  1802. Inst->setAccess(AS_public);
  1803. if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
  1804. TypeSourceInfo *InstantiatedDefaultArg =
  1805. SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs,
  1806. D->getDefaultArgumentLoc(), D->getDeclName());
  1807. if (InstantiatedDefaultArg)
  1808. Inst->setDefaultArgument(InstantiatedDefaultArg);
  1809. }
  1810. // Introduce this template parameter's instantiation into the instantiation
  1811. // scope.
  1812. SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
  1813. return Inst;
  1814. }
  1815. Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
  1816. NonTypeTemplateParmDecl *D) {
  1817. // Substitute into the type of the non-type template parameter.
  1818. TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
  1819. SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
  1820. SmallVector<QualType, 4> ExpandedParameterPackTypes;
  1821. bool IsExpandedParameterPack = false;
  1822. TypeSourceInfo *DI;
  1823. QualType T;
  1824. bool Invalid = false;
  1825. if (D->isExpandedParameterPack()) {
  1826. // The non-type template parameter pack is an already-expanded pack
  1827. // expansion of types. Substitute into each of the expanded types.
  1828. ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
  1829. ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
  1830. for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
  1831. TypeSourceInfo *NewDI =
  1832. SemaRef.SubstType(D->getExpansionTypeSourceInfo(I), TemplateArgs,
  1833. D->getLocation(), D->getDeclName());
  1834. if (!NewDI)
  1835. return nullptr;
  1836. QualType NewT =
  1837. SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
  1838. if (NewT.isNull())
  1839. return nullptr;
  1840. ExpandedParameterPackTypesAsWritten.push_back(NewDI);
  1841. ExpandedParameterPackTypes.push_back(NewT);
  1842. }
  1843. IsExpandedParameterPack = true;
  1844. DI = D->getTypeSourceInfo();
  1845. T = DI->getType();
  1846. } else if (D->isPackExpansion()) {
  1847. // The non-type template parameter pack's type is a pack expansion of types.
  1848. // Determine whether we need to expand this parameter pack into separate
  1849. // types.
  1850. PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
  1851. TypeLoc Pattern = Expansion.getPatternLoc();
  1852. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  1853. SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
  1854. // Determine whether the set of unexpanded parameter packs can and should
  1855. // be expanded.
  1856. bool Expand = true;
  1857. bool RetainExpansion = false;
  1858. Optional<unsigned> OrigNumExpansions
  1859. = Expansion.getTypePtr()->getNumExpansions();
  1860. Optional<unsigned> NumExpansions = OrigNumExpansions;
  1861. if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
  1862. Pattern.getSourceRange(),
  1863. Unexpanded,
  1864. TemplateArgs,
  1865. Expand, RetainExpansion,
  1866. NumExpansions))
  1867. return nullptr;
  1868. if (Expand) {
  1869. for (unsigned I = 0; I != *NumExpansions; ++I) {
  1870. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
  1871. TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
  1872. D->getLocation(),
  1873. D->getDeclName());
  1874. if (!NewDI)
  1875. return nullptr;
  1876. QualType NewT =
  1877. SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
  1878. if (NewT.isNull())
  1879. return nullptr;
  1880. ExpandedParameterPackTypesAsWritten.push_back(NewDI);
  1881. ExpandedParameterPackTypes.push_back(NewT);
  1882. }
  1883. // Note that we have an expanded parameter pack. The "type" of this
  1884. // expanded parameter pack is the original expansion type, but callers
  1885. // will end up using the expanded parameter pack types for type-checking.
  1886. IsExpandedParameterPack = true;
  1887. DI = D->getTypeSourceInfo();
  1888. T = DI->getType();
  1889. } else {
  1890. // We cannot fully expand the pack expansion now, so substitute into the
  1891. // pattern and create a new pack expansion type.
  1892. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
  1893. TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
  1894. D->getLocation(),
  1895. D->getDeclName());
  1896. if (!NewPattern)
  1897. return nullptr;
  1898. SemaRef.CheckNonTypeTemplateParameterType(NewPattern, D->getLocation());
  1899. DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
  1900. NumExpansions);
  1901. if (!DI)
  1902. return nullptr;
  1903. T = DI->getType();
  1904. }
  1905. } else {
  1906. // Simple case: substitution into a parameter that is not a parameter pack.
  1907. DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
  1908. D->getLocation(), D->getDeclName());
  1909. if (!DI)
  1910. return nullptr;
  1911. // Check that this type is acceptable for a non-type template parameter.
  1912. T = SemaRef.CheckNonTypeTemplateParameterType(DI, D->getLocation());
  1913. if (T.isNull()) {
  1914. T = SemaRef.Context.IntTy;
  1915. Invalid = true;
  1916. }
  1917. }
  1918. NonTypeTemplateParmDecl *Param;
  1919. if (IsExpandedParameterPack)
  1920. Param = NonTypeTemplateParmDecl::Create(
  1921. SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
  1922. D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
  1923. D->getPosition(), D->getIdentifier(), T, DI, ExpandedParameterPackTypes,
  1924. ExpandedParameterPackTypesAsWritten);
  1925. else
  1926. Param = NonTypeTemplateParmDecl::Create(
  1927. SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
  1928. D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
  1929. D->getPosition(), D->getIdentifier(), T, D->isParameterPack(), DI);
  1930. Param->setAccess(AS_public);
  1931. if (Invalid)
  1932. Param->setInvalidDecl();
  1933. if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
  1934. EnterExpressionEvaluationContext ConstantEvaluated(
  1935. SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  1936. ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs);
  1937. if (!Value.isInvalid())
  1938. Param->setDefaultArgument(Value.get());
  1939. }
  1940. // Introduce this template parameter's instantiation into the instantiation
  1941. // scope.
  1942. SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
  1943. return Param;
  1944. }
  1945. static void collectUnexpandedParameterPacks(
  1946. Sema &S,
  1947. TemplateParameterList *Params,
  1948. SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
  1949. for (const auto &P : *Params) {
  1950. if (P->isTemplateParameterPack())
  1951. continue;
  1952. if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P))
  1953. S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
  1954. Unexpanded);
  1955. if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(P))
  1956. collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
  1957. Unexpanded);
  1958. }
  1959. }
  1960. Decl *
  1961. TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
  1962. TemplateTemplateParmDecl *D) {
  1963. // Instantiate the template parameter list of the template template parameter.
  1964. TemplateParameterList *TempParams = D->getTemplateParameters();
  1965. TemplateParameterList *InstParams;
  1966. SmallVector<TemplateParameterList*, 8> ExpandedParams;
  1967. bool IsExpandedParameterPack = false;
  1968. if (D->isExpandedParameterPack()) {
  1969. // The template template parameter pack is an already-expanded pack
  1970. // expansion of template parameters. Substitute into each of the expanded
  1971. // parameters.
  1972. ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
  1973. for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
  1974. I != N; ++I) {
  1975. LocalInstantiationScope Scope(SemaRef);
  1976. TemplateParameterList *Expansion =
  1977. SubstTemplateParams(D->getExpansionTemplateParameters(I));
  1978. if (!Expansion)
  1979. return nullptr;
  1980. ExpandedParams.push_back(Expansion);
  1981. }
  1982. IsExpandedParameterPack = true;
  1983. InstParams = TempParams;
  1984. } else if (D->isPackExpansion()) {
  1985. // The template template parameter pack expands to a pack of template
  1986. // template parameters. Determine whether we need to expand this parameter
  1987. // pack into separate parameters.
  1988. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  1989. collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
  1990. Unexpanded);
  1991. // Determine whether the set of unexpanded parameter packs can and should
  1992. // be expanded.
  1993. bool Expand = true;
  1994. bool RetainExpansion = false;
  1995. Optional<unsigned> NumExpansions;
  1996. if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
  1997. TempParams->getSourceRange(),
  1998. Unexpanded,
  1999. TemplateArgs,
  2000. Expand, RetainExpansion,
  2001. NumExpansions))
  2002. return nullptr;
  2003. if (Expand) {
  2004. for (unsigned I = 0; I != *NumExpansions; ++I) {
  2005. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
  2006. LocalInstantiationScope Scope(SemaRef);
  2007. TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
  2008. if (!Expansion)
  2009. return nullptr;
  2010. ExpandedParams.push_back(Expansion);
  2011. }
  2012. // Note that we have an expanded parameter pack. The "type" of this
  2013. // expanded parameter pack is the original expansion type, but callers
  2014. // will end up using the expanded parameter pack types for type-checking.
  2015. IsExpandedParameterPack = true;
  2016. InstParams = TempParams;
  2017. } else {
  2018. // We cannot fully expand the pack expansion now, so just substitute
  2019. // into the pattern.
  2020. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
  2021. LocalInstantiationScope Scope(SemaRef);
  2022. InstParams = SubstTemplateParams(TempParams);
  2023. if (!InstParams)
  2024. return nullptr;
  2025. }
  2026. } else {
  2027. // Perform the actual substitution of template parameters within a new,
  2028. // local instantiation scope.
  2029. LocalInstantiationScope Scope(SemaRef);
  2030. InstParams = SubstTemplateParams(TempParams);
  2031. if (!InstParams)
  2032. return nullptr;
  2033. }
  2034. // Build the template template parameter.
  2035. TemplateTemplateParmDecl *Param;
  2036. if (IsExpandedParameterPack)
  2037. Param = TemplateTemplateParmDecl::Create(
  2038. SemaRef.Context, Owner, D->getLocation(),
  2039. D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
  2040. D->getPosition(), D->getIdentifier(), InstParams, ExpandedParams);
  2041. else
  2042. Param = TemplateTemplateParmDecl::Create(
  2043. SemaRef.Context, Owner, D->getLocation(),
  2044. D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
  2045. D->getPosition(), D->isParameterPack(), D->getIdentifier(), InstParams);
  2046. if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
  2047. NestedNameSpecifierLoc QualifierLoc =
  2048. D->getDefaultArgument().getTemplateQualifierLoc();
  2049. QualifierLoc =
  2050. SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
  2051. TemplateName TName = SemaRef.SubstTemplateName(
  2052. QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
  2053. D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
  2054. if (!TName.isNull())
  2055. Param->setDefaultArgument(
  2056. SemaRef.Context,
  2057. TemplateArgumentLoc(TemplateArgument(TName),
  2058. D->getDefaultArgument().getTemplateQualifierLoc(),
  2059. D->getDefaultArgument().getTemplateNameLoc()));
  2060. }
  2061. Param->setAccess(AS_public);
  2062. // Introduce this template parameter's instantiation into the instantiation
  2063. // scope.
  2064. SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
  2065. return Param;
  2066. }
  2067. Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
  2068. // Using directives are never dependent (and never contain any types or
  2069. // expressions), so they require no explicit instantiation work.
  2070. UsingDirectiveDecl *Inst
  2071. = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
  2072. D->getNamespaceKeyLocation(),
  2073. D->getQualifierLoc(),
  2074. D->getIdentLocation(),
  2075. D->getNominatedNamespace(),
  2076. D->getCommonAncestor());
  2077. // Add the using directive to its declaration context
  2078. // only if this is not a function or method.
  2079. if (!Owner->isFunctionOrMethod())
  2080. Owner->addDecl(Inst);
  2081. return Inst;
  2082. }
  2083. Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
  2084. // The nested name specifier may be dependent, for example
  2085. // template <typename T> struct t {
  2086. // struct s1 { T f1(); };
  2087. // struct s2 : s1 { using s1::f1; };
  2088. // };
  2089. // template struct t<int>;
  2090. // Here, in using s1::f1, s1 refers to t<T>::s1;
  2091. // we need to substitute for t<int>::s1.
  2092. NestedNameSpecifierLoc QualifierLoc
  2093. = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
  2094. TemplateArgs);
  2095. if (!QualifierLoc)
  2096. return nullptr;
  2097. // For an inheriting constructor declaration, the name of the using
  2098. // declaration is the name of a constructor in this class, not in the
  2099. // base class.
  2100. DeclarationNameInfo NameInfo = D->getNameInfo();
  2101. if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
  2102. if (auto *RD = dyn_cast<CXXRecordDecl>(SemaRef.CurContext))
  2103. NameInfo.setName(SemaRef.Context.DeclarationNames.getCXXConstructorName(
  2104. SemaRef.Context.getCanonicalType(SemaRef.Context.getRecordType(RD))));
  2105. // We only need to do redeclaration lookups if we're in a class
  2106. // scope (in fact, it's not really even possible in non-class
  2107. // scopes).
  2108. bool CheckRedeclaration = Owner->isRecord();
  2109. LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
  2110. Sema::ForVisibleRedeclaration);
  2111. UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
  2112. D->getUsingLoc(),
  2113. QualifierLoc,
  2114. NameInfo,
  2115. D->hasTypename());
  2116. CXXScopeSpec SS;
  2117. SS.Adopt(QualifierLoc);
  2118. if (CheckRedeclaration) {
  2119. Prev.setHideTags(false);
  2120. SemaRef.LookupQualifiedName(Prev, Owner);
  2121. // Check for invalid redeclarations.
  2122. if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
  2123. D->hasTypename(), SS,
  2124. D->getLocation(), Prev))
  2125. NewUD->setInvalidDecl();
  2126. }
  2127. if (!NewUD->isInvalidDecl() &&
  2128. SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), D->hasTypename(),
  2129. SS, NameInfo, D->getLocation()))
  2130. NewUD->setInvalidDecl();
  2131. SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
  2132. NewUD->setAccess(D->getAccess());
  2133. Owner->addDecl(NewUD);
  2134. // Don't process the shadow decls for an invalid decl.
  2135. if (NewUD->isInvalidDecl())
  2136. return NewUD;
  2137. if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
  2138. SemaRef.CheckInheritingConstructorUsingDecl(NewUD);
  2139. bool isFunctionScope = Owner->isFunctionOrMethod();
  2140. // Process the shadow decls.
  2141. for (auto *Shadow : D->shadows()) {
  2142. // FIXME: UsingShadowDecl doesn't preserve its immediate target, so
  2143. // reconstruct it in the case where it matters.
  2144. NamedDecl *OldTarget = Shadow->getTargetDecl();
  2145. if (auto *CUSD = dyn_cast<ConstructorUsingShadowDecl>(Shadow))
  2146. if (auto *BaseShadow = CUSD->getNominatedBaseClassShadowDecl())
  2147. OldTarget = BaseShadow;
  2148. NamedDecl *InstTarget =
  2149. cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
  2150. Shadow->getLocation(), OldTarget, TemplateArgs));
  2151. if (!InstTarget)
  2152. return nullptr;
  2153. UsingShadowDecl *PrevDecl = nullptr;
  2154. if (CheckRedeclaration) {
  2155. if (SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev, PrevDecl))
  2156. continue;
  2157. } else if (UsingShadowDecl *OldPrev =
  2158. getPreviousDeclForInstantiation(Shadow)) {
  2159. PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
  2160. Shadow->getLocation(), OldPrev, TemplateArgs));
  2161. }
  2162. UsingShadowDecl *InstShadow =
  2163. SemaRef.BuildUsingShadowDecl(/*Scope*/nullptr, NewUD, InstTarget,
  2164. PrevDecl);
  2165. SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
  2166. if (isFunctionScope)
  2167. SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
  2168. }
  2169. return NewUD;
  2170. }
  2171. Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
  2172. // Ignore these; we handle them in bulk when processing the UsingDecl.
  2173. return nullptr;
  2174. }
  2175. Decl *TemplateDeclInstantiator::VisitConstructorUsingShadowDecl(
  2176. ConstructorUsingShadowDecl *D) {
  2177. // Ignore these; we handle them in bulk when processing the UsingDecl.
  2178. return nullptr;
  2179. }
  2180. template <typename T>
  2181. Decl *TemplateDeclInstantiator::instantiateUnresolvedUsingDecl(
  2182. T *D, bool InstantiatingPackElement) {
  2183. // If this is a pack expansion, expand it now.
  2184. if (D->isPackExpansion() && !InstantiatingPackElement) {
  2185. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  2186. SemaRef.collectUnexpandedParameterPacks(D->getQualifierLoc(), Unexpanded);
  2187. SemaRef.collectUnexpandedParameterPacks(D->getNameInfo(), Unexpanded);
  2188. // Determine whether the set of unexpanded parameter packs can and should
  2189. // be expanded.
  2190. bool Expand = true;
  2191. bool RetainExpansion = false;
  2192. Optional<unsigned> NumExpansions;
  2193. if (SemaRef.CheckParameterPacksForExpansion(
  2194. D->getEllipsisLoc(), D->getSourceRange(), Unexpanded, TemplateArgs,
  2195. Expand, RetainExpansion, NumExpansions))
  2196. return nullptr;
  2197. // This declaration cannot appear within a function template signature,
  2198. // so we can't have a partial argument list for a parameter pack.
  2199. assert(!RetainExpansion &&
  2200. "should never need to retain an expansion for UsingPackDecl");
  2201. if (!Expand) {
  2202. // We cannot fully expand the pack expansion now, so substitute into the
  2203. // pattern and create a new pack expansion.
  2204. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
  2205. return instantiateUnresolvedUsingDecl(D, true);
  2206. }
  2207. // Within a function, we don't have any normal way to check for conflicts
  2208. // between shadow declarations from different using declarations in the
  2209. // same pack expansion, but this is always ill-formed because all expansions
  2210. // must produce (conflicting) enumerators.
  2211. //
  2212. // Sadly we can't just reject this in the template definition because it
  2213. // could be valid if the pack is empty or has exactly one expansion.
  2214. if (D->getDeclContext()->isFunctionOrMethod() && *NumExpansions > 1) {
  2215. SemaRef.Diag(D->getEllipsisLoc(),
  2216. diag::err_using_decl_redeclaration_expansion);
  2217. return nullptr;
  2218. }
  2219. // Instantiate the slices of this pack and build a UsingPackDecl.
  2220. SmallVector<NamedDecl*, 8> Expansions;
  2221. for (unsigned I = 0; I != *NumExpansions; ++I) {
  2222. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
  2223. Decl *Slice = instantiateUnresolvedUsingDecl(D, true);
  2224. if (!Slice)
  2225. return nullptr;
  2226. // Note that we can still get unresolved using declarations here, if we
  2227. // had arguments for all packs but the pattern also contained other
  2228. // template arguments (this only happens during partial substitution, eg
  2229. // into the body of a generic lambda in a function template).
  2230. Expansions.push_back(cast<NamedDecl>(Slice));
  2231. }
  2232. auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
  2233. if (isDeclWithinFunction(D))
  2234. SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
  2235. return NewD;
  2236. }
  2237. UnresolvedUsingTypenameDecl *TD = dyn_cast<UnresolvedUsingTypenameDecl>(D);
  2238. SourceLocation TypenameLoc = TD ? TD->getTypenameLoc() : SourceLocation();
  2239. NestedNameSpecifierLoc QualifierLoc
  2240. = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
  2241. TemplateArgs);
  2242. if (!QualifierLoc)
  2243. return nullptr;
  2244. CXXScopeSpec SS;
  2245. SS.Adopt(QualifierLoc);
  2246. DeclarationNameInfo NameInfo
  2247. = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
  2248. // Produce a pack expansion only if we're not instantiating a particular
  2249. // slice of a pack expansion.
  2250. bool InstantiatingSlice = D->getEllipsisLoc().isValid() &&
  2251. SemaRef.ArgumentPackSubstitutionIndex != -1;
  2252. SourceLocation EllipsisLoc =
  2253. InstantiatingSlice ? SourceLocation() : D->getEllipsisLoc();
  2254. NamedDecl *UD = SemaRef.BuildUsingDeclaration(
  2255. /*Scope*/ nullptr, D->getAccess(), D->getUsingLoc(),
  2256. /*HasTypename*/ TD, TypenameLoc, SS, NameInfo, EllipsisLoc,
  2257. ParsedAttributesView(),
  2258. /*IsInstantiation*/ true);
  2259. if (UD)
  2260. SemaRef.Context.setInstantiatedFromUsingDecl(UD, D);
  2261. return UD;
  2262. }
  2263. Decl *TemplateDeclInstantiator::VisitUnresolvedUsingTypenameDecl(
  2264. UnresolvedUsingTypenameDecl *D) {
  2265. return instantiateUnresolvedUsingDecl(D);
  2266. }
  2267. Decl *TemplateDeclInstantiator::VisitUnresolvedUsingValueDecl(
  2268. UnresolvedUsingValueDecl *D) {
  2269. return instantiateUnresolvedUsingDecl(D);
  2270. }
  2271. Decl *TemplateDeclInstantiator::VisitUsingPackDecl(UsingPackDecl *D) {
  2272. SmallVector<NamedDecl*, 8> Expansions;
  2273. for (auto *UD : D->expansions()) {
  2274. if (NamedDecl *NewUD =
  2275. SemaRef.FindInstantiatedDecl(D->getLocation(), UD, TemplateArgs))
  2276. Expansions.push_back(NewUD);
  2277. else
  2278. return nullptr;
  2279. }
  2280. auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
  2281. if (isDeclWithinFunction(D))
  2282. SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
  2283. return NewD;
  2284. }
  2285. Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
  2286. ClassScopeFunctionSpecializationDecl *Decl) {
  2287. CXXMethodDecl *OldFD = Decl->getSpecialization();
  2288. CXXMethodDecl *NewFD =
  2289. cast_or_null<CXXMethodDecl>(VisitCXXMethodDecl(OldFD, nullptr, true));
  2290. if (!NewFD)
  2291. return nullptr;
  2292. LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName,
  2293. Sema::ForExternalRedeclaration);
  2294. TemplateArgumentListInfo TemplateArgs;
  2295. TemplateArgumentListInfo *TemplateArgsPtr = nullptr;
  2296. if (Decl->hasExplicitTemplateArgs()) {
  2297. TemplateArgs = Decl->templateArgs();
  2298. TemplateArgsPtr = &TemplateArgs;
  2299. }
  2300. SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext);
  2301. if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, TemplateArgsPtr,
  2302. Previous)) {
  2303. NewFD->setInvalidDecl();
  2304. return NewFD;
  2305. }
  2306. // Associate the specialization with the pattern.
  2307. FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl());
  2308. assert(Specialization && "Class scope Specialization is null");
  2309. SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD);
  2310. // FIXME: If this is a definition, check for redefinition errors!
  2311. return NewFD;
  2312. }
  2313. Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
  2314. OMPThreadPrivateDecl *D) {
  2315. SmallVector<Expr *, 5> Vars;
  2316. for (auto *I : D->varlists()) {
  2317. Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
  2318. assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
  2319. Vars.push_back(Var);
  2320. }
  2321. OMPThreadPrivateDecl *TD =
  2322. SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
  2323. TD->setAccess(AS_public);
  2324. Owner->addDecl(TD);
  2325. return TD;
  2326. }
  2327. Decl *TemplateDeclInstantiator::VisitOMPRequiresDecl(OMPRequiresDecl *D) {
  2328. llvm_unreachable(
  2329. "Requires directive cannot be instantiated within a dependent context");
  2330. }
  2331. Decl *TemplateDeclInstantiator::VisitOMPDeclareReductionDecl(
  2332. OMPDeclareReductionDecl *D) {
  2333. // Instantiate type and check if it is allowed.
  2334. const bool RequiresInstantiation =
  2335. D->getType()->isDependentType() ||
  2336. D->getType()->isInstantiationDependentType() ||
  2337. D->getType()->containsUnexpandedParameterPack();
  2338. QualType SubstReductionType;
  2339. if (RequiresInstantiation) {
  2340. SubstReductionType = SemaRef.ActOnOpenMPDeclareReductionType(
  2341. D->getLocation(),
  2342. ParsedType::make(SemaRef.SubstType(
  2343. D->getType(), TemplateArgs, D->getLocation(), DeclarationName())));
  2344. } else {
  2345. SubstReductionType = D->getType();
  2346. }
  2347. if (SubstReductionType.isNull())
  2348. return nullptr;
  2349. bool IsCorrect = !SubstReductionType.isNull();
  2350. // Create instantiated copy.
  2351. std::pair<QualType, SourceLocation> ReductionTypes[] = {
  2352. std::make_pair(SubstReductionType, D->getLocation())};
  2353. auto *PrevDeclInScope = D->getPrevDeclInScope();
  2354. if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
  2355. PrevDeclInScope = cast<OMPDeclareReductionDecl>(
  2356. SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
  2357. ->get<Decl *>());
  2358. }
  2359. auto DRD = SemaRef.ActOnOpenMPDeclareReductionDirectiveStart(
  2360. /*S=*/nullptr, Owner, D->getDeclName(), ReductionTypes, D->getAccess(),
  2361. PrevDeclInScope);
  2362. auto *NewDRD = cast<OMPDeclareReductionDecl>(DRD.get().getSingleDecl());
  2363. SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDRD);
  2364. if (!RequiresInstantiation) {
  2365. if (Expr *Combiner = D->getCombiner()) {
  2366. NewDRD->setCombinerData(D->getCombinerIn(), D->getCombinerOut());
  2367. NewDRD->setCombiner(Combiner);
  2368. if (Expr *Init = D->getInitializer()) {
  2369. NewDRD->setInitializerData(D->getInitOrig(), D->getInitPriv());
  2370. NewDRD->setInitializer(Init, D->getInitializerKind());
  2371. }
  2372. }
  2373. (void)SemaRef.ActOnOpenMPDeclareReductionDirectiveEnd(
  2374. /*S=*/nullptr, DRD, IsCorrect && !D->isInvalidDecl());
  2375. return NewDRD;
  2376. }
  2377. Expr *SubstCombiner = nullptr;
  2378. Expr *SubstInitializer = nullptr;
  2379. // Combiners instantiation sequence.
  2380. if (D->getCombiner()) {
  2381. SemaRef.ActOnOpenMPDeclareReductionCombinerStart(
  2382. /*S=*/nullptr, NewDRD);
  2383. SemaRef.CurrentInstantiationScope->InstantiatedLocal(
  2384. cast<DeclRefExpr>(D->getCombinerIn())->getDecl(),
  2385. cast<DeclRefExpr>(NewDRD->getCombinerIn())->getDecl());
  2386. SemaRef.CurrentInstantiationScope->InstantiatedLocal(
  2387. cast<DeclRefExpr>(D->getCombinerOut())->getDecl(),
  2388. cast<DeclRefExpr>(NewDRD->getCombinerOut())->getDecl());
  2389. auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
  2390. Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, /*TypeQuals*/ 0,
  2391. ThisContext);
  2392. SubstCombiner = SemaRef.SubstExpr(D->getCombiner(), TemplateArgs).get();
  2393. SemaRef.ActOnOpenMPDeclareReductionCombinerEnd(NewDRD, SubstCombiner);
  2394. // Initializers instantiation sequence.
  2395. if (D->getInitializer()) {
  2396. VarDecl *OmpPrivParm =
  2397. SemaRef.ActOnOpenMPDeclareReductionInitializerStart(
  2398. /*S=*/nullptr, NewDRD);
  2399. SemaRef.CurrentInstantiationScope->InstantiatedLocal(
  2400. cast<DeclRefExpr>(D->getInitOrig())->getDecl(),
  2401. cast<DeclRefExpr>(NewDRD->getInitOrig())->getDecl());
  2402. SemaRef.CurrentInstantiationScope->InstantiatedLocal(
  2403. cast<DeclRefExpr>(D->getInitPriv())->getDecl(),
  2404. cast<DeclRefExpr>(NewDRD->getInitPriv())->getDecl());
  2405. if (D->getInitializerKind() == OMPDeclareReductionDecl::CallInit) {
  2406. SubstInitializer =
  2407. SemaRef.SubstExpr(D->getInitializer(), TemplateArgs).get();
  2408. } else {
  2409. IsCorrect = IsCorrect && OmpPrivParm->hasInit();
  2410. }
  2411. SemaRef.ActOnOpenMPDeclareReductionInitializerEnd(
  2412. NewDRD, SubstInitializer, OmpPrivParm);
  2413. }
  2414. IsCorrect =
  2415. IsCorrect && SubstCombiner &&
  2416. (!D->getInitializer() ||
  2417. (D->getInitializerKind() == OMPDeclareReductionDecl::CallInit &&
  2418. SubstInitializer) ||
  2419. (D->getInitializerKind() != OMPDeclareReductionDecl::CallInit &&
  2420. !SubstInitializer && !SubstInitializer));
  2421. } else {
  2422. IsCorrect = false;
  2423. }
  2424. (void)SemaRef.ActOnOpenMPDeclareReductionDirectiveEnd(/*S=*/nullptr, DRD,
  2425. IsCorrect);
  2426. return NewDRD;
  2427. }
  2428. Decl *TemplateDeclInstantiator::VisitOMPCapturedExprDecl(
  2429. OMPCapturedExprDecl * /*D*/) {
  2430. llvm_unreachable("Should not be met in templates");
  2431. }
  2432. Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
  2433. return VisitFunctionDecl(D, nullptr);
  2434. }
  2435. Decl *
  2436. TemplateDeclInstantiator::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
  2437. Decl *Inst = VisitFunctionDecl(D, nullptr);
  2438. if (Inst && !D->getDescribedFunctionTemplate())
  2439. Owner->addDecl(Inst);
  2440. return Inst;
  2441. }
  2442. Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
  2443. return VisitCXXMethodDecl(D, nullptr);
  2444. }
  2445. Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
  2446. llvm_unreachable("There are only CXXRecordDecls in C++");
  2447. }
  2448. Decl *
  2449. TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
  2450. ClassTemplateSpecializationDecl *D) {
  2451. // As a MS extension, we permit class-scope explicit specialization
  2452. // of member class templates.
  2453. ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
  2454. assert(ClassTemplate->getDeclContext()->isRecord() &&
  2455. D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
  2456. "can only instantiate an explicit specialization "
  2457. "for a member class template");
  2458. // Lookup the already-instantiated declaration in the instantiation
  2459. // of the class template. FIXME: Diagnose or assert if this fails?
  2460. DeclContext::lookup_result Found
  2461. = Owner->lookup(ClassTemplate->getDeclName());
  2462. if (Found.empty())
  2463. return nullptr;
  2464. ClassTemplateDecl *InstClassTemplate
  2465. = dyn_cast<ClassTemplateDecl>(Found.front());
  2466. if (!InstClassTemplate)
  2467. return nullptr;
  2468. // Substitute into the template arguments of the class template explicit
  2469. // specialization.
  2470. TemplateSpecializationTypeLoc Loc = D->getTypeAsWritten()->getTypeLoc().
  2471. castAs<TemplateSpecializationTypeLoc>();
  2472. TemplateArgumentListInfo InstTemplateArgs(Loc.getLAngleLoc(),
  2473. Loc.getRAngleLoc());
  2474. SmallVector<TemplateArgumentLoc, 4> ArgLocs;
  2475. for (unsigned I = 0; I != Loc.getNumArgs(); ++I)
  2476. ArgLocs.push_back(Loc.getArgLoc(I));
  2477. if (SemaRef.Subst(ArgLocs.data(), ArgLocs.size(),
  2478. InstTemplateArgs, TemplateArgs))
  2479. return nullptr;
  2480. // Check that the template argument list is well-formed for this
  2481. // class template.
  2482. SmallVector<TemplateArgument, 4> Converted;
  2483. if (SemaRef.CheckTemplateArgumentList(InstClassTemplate,
  2484. D->getLocation(),
  2485. InstTemplateArgs,
  2486. false,
  2487. Converted))
  2488. return nullptr;
  2489. // Figure out where to insert this class template explicit specialization
  2490. // in the member template's set of class template explicit specializations.
  2491. void *InsertPos = nullptr;
  2492. ClassTemplateSpecializationDecl *PrevDecl =
  2493. InstClassTemplate->findSpecialization(Converted, InsertPos);
  2494. // Check whether we've already seen a conflicting instantiation of this
  2495. // declaration (for instance, if there was a prior implicit instantiation).
  2496. bool Ignored;
  2497. if (PrevDecl &&
  2498. SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(),
  2499. D->getSpecializationKind(),
  2500. PrevDecl,
  2501. PrevDecl->getSpecializationKind(),
  2502. PrevDecl->getPointOfInstantiation(),
  2503. Ignored))
  2504. return nullptr;
  2505. // If PrevDecl was a definition and D is also a definition, diagnose.
  2506. // This happens in cases like:
  2507. //
  2508. // template<typename T, typename U>
  2509. // struct Outer {
  2510. // template<typename X> struct Inner;
  2511. // template<> struct Inner<T> {};
  2512. // template<> struct Inner<U> {};
  2513. // };
  2514. //
  2515. // Outer<int, int> outer; // error: the explicit specializations of Inner
  2516. // // have the same signature.
  2517. if (PrevDecl && PrevDecl->getDefinition() &&
  2518. D->isThisDeclarationADefinition()) {
  2519. SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
  2520. SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
  2521. diag::note_previous_definition);
  2522. return nullptr;
  2523. }
  2524. // Create the class template partial specialization declaration.
  2525. ClassTemplateSpecializationDecl *InstD =
  2526. ClassTemplateSpecializationDecl::Create(
  2527. SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(),
  2528. D->getLocation(), InstClassTemplate, Converted, PrevDecl);
  2529. // Add this partial specialization to the set of class template partial
  2530. // specializations.
  2531. if (!PrevDecl)
  2532. InstClassTemplate->AddSpecialization(InstD, InsertPos);
  2533. // Substitute the nested name specifier, if any.
  2534. if (SubstQualifier(D, InstD))
  2535. return nullptr;
  2536. // Build the canonical type that describes the converted template
  2537. // arguments of the class template explicit specialization.
  2538. QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
  2539. TemplateName(InstClassTemplate), Converted,
  2540. SemaRef.Context.getRecordType(InstD));
  2541. // Build the fully-sugared type for this class template
  2542. // specialization as the user wrote in the specialization
  2543. // itself. This means that we'll pretty-print the type retrieved
  2544. // from the specialization's declaration the way that the user
  2545. // actually wrote the specialization, rather than formatting the
  2546. // name based on the "canonical" representation used to store the
  2547. // template arguments in the specialization.
  2548. TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
  2549. TemplateName(InstClassTemplate), D->getLocation(), InstTemplateArgs,
  2550. CanonType);
  2551. InstD->setAccess(D->getAccess());
  2552. InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
  2553. InstD->setSpecializationKind(D->getSpecializationKind());
  2554. InstD->setTypeAsWritten(WrittenTy);
  2555. InstD->setExternLoc(D->getExternLoc());
  2556. InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc());
  2557. Owner->addDecl(InstD);
  2558. // Instantiate the members of the class-scope explicit specialization eagerly.
  2559. // We don't have support for lazy instantiation of an explicit specialization
  2560. // yet, and MSVC eagerly instantiates in this case.
  2561. if (D->isThisDeclarationADefinition() &&
  2562. SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
  2563. TSK_ImplicitInstantiation,
  2564. /*Complain=*/true))
  2565. return nullptr;
  2566. return InstD;
  2567. }
  2568. Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
  2569. VarTemplateSpecializationDecl *D) {
  2570. TemplateArgumentListInfo VarTemplateArgsInfo;
  2571. VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
  2572. assert(VarTemplate &&
  2573. "A template specialization without specialized template?");
  2574. // Substitute the current template arguments.
  2575. const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo();
  2576. VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc());
  2577. VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc());
  2578. if (SemaRef.Subst(TemplateArgsInfo.getArgumentArray(),
  2579. TemplateArgsInfo.size(), VarTemplateArgsInfo, TemplateArgs))
  2580. return nullptr;
  2581. // Check that the template argument list is well-formed for this template.
  2582. SmallVector<TemplateArgument, 4> Converted;
  2583. if (SemaRef.CheckTemplateArgumentList(
  2584. VarTemplate, VarTemplate->getBeginLoc(),
  2585. const_cast<TemplateArgumentListInfo &>(VarTemplateArgsInfo), false,
  2586. Converted))
  2587. return nullptr;
  2588. // Find the variable template specialization declaration that
  2589. // corresponds to these arguments.
  2590. void *InsertPos = nullptr;
  2591. if (VarTemplateSpecializationDecl *VarSpec = VarTemplate->findSpecialization(
  2592. Converted, InsertPos))
  2593. // If we already have a variable template specialization, return it.
  2594. return VarSpec;
  2595. return VisitVarTemplateSpecializationDecl(VarTemplate, D, InsertPos,
  2596. VarTemplateArgsInfo, Converted);
  2597. }
  2598. Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
  2599. VarTemplateDecl *VarTemplate, VarDecl *D, void *InsertPos,
  2600. const TemplateArgumentListInfo &TemplateArgsInfo,
  2601. ArrayRef<TemplateArgument> Converted) {
  2602. // Do substitution on the type of the declaration
  2603. TypeSourceInfo *DI =
  2604. SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
  2605. D->getTypeSpecStartLoc(), D->getDeclName());
  2606. if (!DI)
  2607. return nullptr;
  2608. if (DI->getType()->isFunctionType()) {
  2609. SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
  2610. << D->isStaticDataMember() << DI->getType();
  2611. return nullptr;
  2612. }
  2613. // Build the instantiated declaration
  2614. VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create(
  2615. SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
  2616. VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted);
  2617. Var->setTemplateArgsInfo(TemplateArgsInfo);
  2618. if (InsertPos)
  2619. VarTemplate->AddSpecialization(Var, InsertPos);
  2620. // Substitute the nested name specifier, if any.
  2621. if (SubstQualifier(D, Var))
  2622. return nullptr;
  2623. SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs,
  2624. Owner, StartingScope);
  2625. return Var;
  2626. }
  2627. Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
  2628. llvm_unreachable("@defs is not supported in Objective-C++");
  2629. }
  2630. Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
  2631. // FIXME: We need to be able to instantiate FriendTemplateDecls.
  2632. unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
  2633. DiagnosticsEngine::Error,
  2634. "cannot instantiate %0 yet");
  2635. SemaRef.Diag(D->getLocation(), DiagID)
  2636. << D->getDeclKindName();
  2637. return nullptr;
  2638. }
  2639. Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
  2640. llvm_unreachable("Unexpected decl");
  2641. }
  2642. Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
  2643. const MultiLevelTemplateArgumentList &TemplateArgs) {
  2644. TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
  2645. if (D->isInvalidDecl())
  2646. return nullptr;
  2647. return Instantiator.Visit(D);
  2648. }
  2649. /// Instantiates a nested template parameter list in the current
  2650. /// instantiation context.
  2651. ///
  2652. /// \param L The parameter list to instantiate
  2653. ///
  2654. /// \returns NULL if there was an error
  2655. TemplateParameterList *
  2656. TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
  2657. // Get errors for all the parameters before bailing out.
  2658. bool Invalid = false;
  2659. unsigned N = L->size();
  2660. typedef SmallVector<NamedDecl *, 8> ParamVector;
  2661. ParamVector Params;
  2662. Params.reserve(N);
  2663. for (auto &P : *L) {
  2664. NamedDecl *D = cast_or_null<NamedDecl>(Visit(P));
  2665. Params.push_back(D);
  2666. Invalid = Invalid || !D || D->isInvalidDecl();
  2667. }
  2668. // Clean up if we had an error.
  2669. if (Invalid)
  2670. return nullptr;
  2671. // Note: we substitute into associated constraints later
  2672. Expr *const UninstantiatedRequiresClause = L->getRequiresClause();
  2673. TemplateParameterList *InstL
  2674. = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
  2675. L->getLAngleLoc(), Params,
  2676. L->getRAngleLoc(),
  2677. UninstantiatedRequiresClause);
  2678. return InstL;
  2679. }
  2680. TemplateParameterList *
  2681. Sema::SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
  2682. const MultiLevelTemplateArgumentList &TemplateArgs) {
  2683. TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
  2684. return Instantiator.SubstTemplateParams(Params);
  2685. }
  2686. /// Instantiate the declaration of a class template partial
  2687. /// specialization.
  2688. ///
  2689. /// \param ClassTemplate the (instantiated) class template that is partially
  2690. // specialized by the instantiation of \p PartialSpec.
  2691. ///
  2692. /// \param PartialSpec the (uninstantiated) class template partial
  2693. /// specialization that we are instantiating.
  2694. ///
  2695. /// \returns The instantiated partial specialization, if successful; otherwise,
  2696. /// NULL to indicate an error.
  2697. ClassTemplatePartialSpecializationDecl *
  2698. TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
  2699. ClassTemplateDecl *ClassTemplate,
  2700. ClassTemplatePartialSpecializationDecl *PartialSpec) {
  2701. // Create a local instantiation scope for this class template partial
  2702. // specialization, which will contain the instantiations of the template
  2703. // parameters.
  2704. LocalInstantiationScope Scope(SemaRef);
  2705. // Substitute into the template parameters of the class template partial
  2706. // specialization.
  2707. TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
  2708. TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
  2709. if (!InstParams)
  2710. return nullptr;
  2711. // Substitute into the template arguments of the class template partial
  2712. // specialization.
  2713. const ASTTemplateArgumentListInfo *TemplArgInfo
  2714. = PartialSpec->getTemplateArgsAsWritten();
  2715. TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
  2716. TemplArgInfo->RAngleLoc);
  2717. if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
  2718. TemplArgInfo->NumTemplateArgs,
  2719. InstTemplateArgs, TemplateArgs))
  2720. return nullptr;
  2721. // Check that the template argument list is well-formed for this
  2722. // class template.
  2723. SmallVector<TemplateArgument, 4> Converted;
  2724. if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
  2725. PartialSpec->getLocation(),
  2726. InstTemplateArgs,
  2727. false,
  2728. Converted))
  2729. return nullptr;
  2730. // Check these arguments are valid for a template partial specialization.
  2731. if (SemaRef.CheckTemplatePartialSpecializationArgs(
  2732. PartialSpec->getLocation(), ClassTemplate, InstTemplateArgs.size(),
  2733. Converted))
  2734. return nullptr;
  2735. // Figure out where to insert this class template partial specialization
  2736. // in the member template's set of class template partial specializations.
  2737. void *InsertPos = nullptr;
  2738. ClassTemplateSpecializationDecl *PrevDecl
  2739. = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
  2740. // Build the canonical type that describes the converted template
  2741. // arguments of the class template partial specialization.
  2742. QualType CanonType
  2743. = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
  2744. Converted);
  2745. // Build the fully-sugared type for this class template
  2746. // specialization as the user wrote in the specialization
  2747. // itself. This means that we'll pretty-print the type retrieved
  2748. // from the specialization's declaration the way that the user
  2749. // actually wrote the specialization, rather than formatting the
  2750. // name based on the "canonical" representation used to store the
  2751. // template arguments in the specialization.
  2752. TypeSourceInfo *WrittenTy
  2753. = SemaRef.Context.getTemplateSpecializationTypeInfo(
  2754. TemplateName(ClassTemplate),
  2755. PartialSpec->getLocation(),
  2756. InstTemplateArgs,
  2757. CanonType);
  2758. if (PrevDecl) {
  2759. // We've already seen a partial specialization with the same template
  2760. // parameters and template arguments. This can happen, for example, when
  2761. // substituting the outer template arguments ends up causing two
  2762. // class template partial specializations of a member class template
  2763. // to have identical forms, e.g.,
  2764. //
  2765. // template<typename T, typename U>
  2766. // struct Outer {
  2767. // template<typename X, typename Y> struct Inner;
  2768. // template<typename Y> struct Inner<T, Y>;
  2769. // template<typename Y> struct Inner<U, Y>;
  2770. // };
  2771. //
  2772. // Outer<int, int> outer; // error: the partial specializations of Inner
  2773. // // have the same signature.
  2774. SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
  2775. << WrittenTy->getType();
  2776. SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
  2777. << SemaRef.Context.getTypeDeclType(PrevDecl);
  2778. return nullptr;
  2779. }
  2780. // Create the class template partial specialization declaration.
  2781. ClassTemplatePartialSpecializationDecl *InstPartialSpec =
  2782. ClassTemplatePartialSpecializationDecl::Create(
  2783. SemaRef.Context, PartialSpec->getTagKind(), Owner,
  2784. PartialSpec->getBeginLoc(), PartialSpec->getLocation(), InstParams,
  2785. ClassTemplate, Converted, InstTemplateArgs, CanonType, nullptr);
  2786. // Substitute the nested name specifier, if any.
  2787. if (SubstQualifier(PartialSpec, InstPartialSpec))
  2788. return nullptr;
  2789. InstPartialSpec->setInstantiatedFromMember(PartialSpec);
  2790. InstPartialSpec->setTypeAsWritten(WrittenTy);
  2791. // Check the completed partial specialization.
  2792. SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
  2793. // Add this partial specialization to the set of class template partial
  2794. // specializations.
  2795. ClassTemplate->AddPartialSpecialization(InstPartialSpec,
  2796. /*InsertPos=*/nullptr);
  2797. return InstPartialSpec;
  2798. }
  2799. /// Instantiate the declaration of a variable template partial
  2800. /// specialization.
  2801. ///
  2802. /// \param VarTemplate the (instantiated) variable template that is partially
  2803. /// specialized by the instantiation of \p PartialSpec.
  2804. ///
  2805. /// \param PartialSpec the (uninstantiated) variable template partial
  2806. /// specialization that we are instantiating.
  2807. ///
  2808. /// \returns The instantiated partial specialization, if successful; otherwise,
  2809. /// NULL to indicate an error.
  2810. VarTemplatePartialSpecializationDecl *
  2811. TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
  2812. VarTemplateDecl *VarTemplate,
  2813. VarTemplatePartialSpecializationDecl *PartialSpec) {
  2814. // Create a local instantiation scope for this variable template partial
  2815. // specialization, which will contain the instantiations of the template
  2816. // parameters.
  2817. LocalInstantiationScope Scope(SemaRef);
  2818. // Substitute into the template parameters of the variable template partial
  2819. // specialization.
  2820. TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
  2821. TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
  2822. if (!InstParams)
  2823. return nullptr;
  2824. // Substitute into the template arguments of the variable template partial
  2825. // specialization.
  2826. const ASTTemplateArgumentListInfo *TemplArgInfo
  2827. = PartialSpec->getTemplateArgsAsWritten();
  2828. TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
  2829. TemplArgInfo->RAngleLoc);
  2830. if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
  2831. TemplArgInfo->NumTemplateArgs,
  2832. InstTemplateArgs, TemplateArgs))
  2833. return nullptr;
  2834. // Check that the template argument list is well-formed for this
  2835. // class template.
  2836. SmallVector<TemplateArgument, 4> Converted;
  2837. if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
  2838. InstTemplateArgs, false, Converted))
  2839. return nullptr;
  2840. // Check these arguments are valid for a template partial specialization.
  2841. if (SemaRef.CheckTemplatePartialSpecializationArgs(
  2842. PartialSpec->getLocation(), VarTemplate, InstTemplateArgs.size(),
  2843. Converted))
  2844. return nullptr;
  2845. // Figure out where to insert this variable template partial specialization
  2846. // in the member template's set of variable template partial specializations.
  2847. void *InsertPos = nullptr;
  2848. VarTemplateSpecializationDecl *PrevDecl =
  2849. VarTemplate->findPartialSpecialization(Converted, InsertPos);
  2850. // Build the canonical type that describes the converted template
  2851. // arguments of the variable template partial specialization.
  2852. QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
  2853. TemplateName(VarTemplate), Converted);
  2854. // Build the fully-sugared type for this variable template
  2855. // specialization as the user wrote in the specialization
  2856. // itself. This means that we'll pretty-print the type retrieved
  2857. // from the specialization's declaration the way that the user
  2858. // actually wrote the specialization, rather than formatting the
  2859. // name based on the "canonical" representation used to store the
  2860. // template arguments in the specialization.
  2861. TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
  2862. TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs,
  2863. CanonType);
  2864. if (PrevDecl) {
  2865. // We've already seen a partial specialization with the same template
  2866. // parameters and template arguments. This can happen, for example, when
  2867. // substituting the outer template arguments ends up causing two
  2868. // variable template partial specializations of a member variable template
  2869. // to have identical forms, e.g.,
  2870. //
  2871. // template<typename T, typename U>
  2872. // struct Outer {
  2873. // template<typename X, typename Y> pair<X,Y> p;
  2874. // template<typename Y> pair<T, Y> p;
  2875. // template<typename Y> pair<U, Y> p;
  2876. // };
  2877. //
  2878. // Outer<int, int> outer; // error: the partial specializations of Inner
  2879. // // have the same signature.
  2880. SemaRef.Diag(PartialSpec->getLocation(),
  2881. diag::err_var_partial_spec_redeclared)
  2882. << WrittenTy->getType();
  2883. SemaRef.Diag(PrevDecl->getLocation(),
  2884. diag::note_var_prev_partial_spec_here);
  2885. return nullptr;
  2886. }
  2887. // Do substitution on the type of the declaration
  2888. TypeSourceInfo *DI = SemaRef.SubstType(
  2889. PartialSpec->getTypeSourceInfo(), TemplateArgs,
  2890. PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
  2891. if (!DI)
  2892. return nullptr;
  2893. if (DI->getType()->isFunctionType()) {
  2894. SemaRef.Diag(PartialSpec->getLocation(),
  2895. diag::err_variable_instantiates_to_function)
  2896. << PartialSpec->isStaticDataMember() << DI->getType();
  2897. return nullptr;
  2898. }
  2899. // Create the variable template partial specialization declaration.
  2900. VarTemplatePartialSpecializationDecl *InstPartialSpec =
  2901. VarTemplatePartialSpecializationDecl::Create(
  2902. SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
  2903. PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
  2904. DI, PartialSpec->getStorageClass(), Converted, InstTemplateArgs);
  2905. // Substitute the nested name specifier, if any.
  2906. if (SubstQualifier(PartialSpec, InstPartialSpec))
  2907. return nullptr;
  2908. InstPartialSpec->setInstantiatedFromMember(PartialSpec);
  2909. InstPartialSpec->setTypeAsWritten(WrittenTy);
  2910. // Check the completed partial specialization.
  2911. SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
  2912. // Add this partial specialization to the set of variable template partial
  2913. // specializations. The instantiation of the initializer is not necessary.
  2914. VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr);
  2915. SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
  2916. LateAttrs, Owner, StartingScope);
  2917. return InstPartialSpec;
  2918. }
  2919. TypeSourceInfo*
  2920. TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
  2921. SmallVectorImpl<ParmVarDecl *> &Params) {
  2922. TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
  2923. assert(OldTInfo && "substituting function without type source info");
  2924. assert(Params.empty() && "parameter vector is non-empty at start");
  2925. CXXRecordDecl *ThisContext = nullptr;
  2926. unsigned ThisTypeQuals = 0;
  2927. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
  2928. ThisContext = cast<CXXRecordDecl>(Owner);
  2929. ThisTypeQuals = Method->getTypeQualifiers();
  2930. }
  2931. TypeSourceInfo *NewTInfo
  2932. = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
  2933. D->getTypeSpecStartLoc(),
  2934. D->getDeclName(),
  2935. ThisContext, ThisTypeQuals);
  2936. if (!NewTInfo)
  2937. return nullptr;
  2938. TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
  2939. if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
  2940. if (NewTInfo != OldTInfo) {
  2941. // Get parameters from the new type info.
  2942. TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
  2943. FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
  2944. unsigned NewIdx = 0;
  2945. for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
  2946. OldIdx != NumOldParams; ++OldIdx) {
  2947. ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
  2948. LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
  2949. Optional<unsigned> NumArgumentsInExpansion;
  2950. if (OldParam->isParameterPack())
  2951. NumArgumentsInExpansion =
  2952. SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
  2953. TemplateArgs);
  2954. if (!NumArgumentsInExpansion) {
  2955. // Simple case: normal parameter, or a parameter pack that's
  2956. // instantiated to a (still-dependent) parameter pack.
  2957. ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
  2958. Params.push_back(NewParam);
  2959. Scope->InstantiatedLocal(OldParam, NewParam);
  2960. } else {
  2961. // Parameter pack expansion: make the instantiation an argument pack.
  2962. Scope->MakeInstantiatedLocalArgPack(OldParam);
  2963. for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
  2964. ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
  2965. Params.push_back(NewParam);
  2966. Scope->InstantiatedLocalPackArg(OldParam, NewParam);
  2967. }
  2968. }
  2969. }
  2970. } else {
  2971. // The function type itself was not dependent and therefore no
  2972. // substitution occurred. However, we still need to instantiate
  2973. // the function parameters themselves.
  2974. const FunctionProtoType *OldProto =
  2975. cast<FunctionProtoType>(OldProtoLoc.getType());
  2976. for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
  2977. ++i) {
  2978. ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
  2979. if (!OldParam) {
  2980. Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
  2981. D, D->getLocation(), OldProto->getParamType(i)));
  2982. continue;
  2983. }
  2984. ParmVarDecl *Parm =
  2985. cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
  2986. if (!Parm)
  2987. return nullptr;
  2988. Params.push_back(Parm);
  2989. }
  2990. }
  2991. } else {
  2992. // If the type of this function, after ignoring parentheses, is not
  2993. // *directly* a function type, then we're instantiating a function that
  2994. // was declared via a typedef or with attributes, e.g.,
  2995. //
  2996. // typedef int functype(int, int);
  2997. // functype func;
  2998. // int __cdecl meth(int, int);
  2999. //
  3000. // In this case, we'll just go instantiate the ParmVarDecls that we
  3001. // synthesized in the method declaration.
  3002. SmallVector<QualType, 4> ParamTypes;
  3003. Sema::ExtParameterInfoBuilder ExtParamInfos;
  3004. if (SemaRef.SubstParmTypes(D->getLocation(), D->parameters(), nullptr,
  3005. TemplateArgs, ParamTypes, &Params,
  3006. ExtParamInfos))
  3007. return nullptr;
  3008. }
  3009. return NewTInfo;
  3010. }
  3011. /// Introduce the instantiated function parameters into the local
  3012. /// instantiation scope, and set the parameter names to those used
  3013. /// in the template.
  3014. static bool addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
  3015. const FunctionDecl *PatternDecl,
  3016. LocalInstantiationScope &Scope,
  3017. const MultiLevelTemplateArgumentList &TemplateArgs) {
  3018. unsigned FParamIdx = 0;
  3019. for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
  3020. const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
  3021. if (!PatternParam->isParameterPack()) {
  3022. // Simple case: not a parameter pack.
  3023. assert(FParamIdx < Function->getNumParams());
  3024. ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
  3025. FunctionParam->setDeclName(PatternParam->getDeclName());
  3026. // If the parameter's type is not dependent, update it to match the type
  3027. // in the pattern. They can differ in top-level cv-qualifiers, and we want
  3028. // the pattern's type here. If the type is dependent, they can't differ,
  3029. // per core issue 1668. Substitute into the type from the pattern, in case
  3030. // it's instantiation-dependent.
  3031. // FIXME: Updating the type to work around this is at best fragile.
  3032. if (!PatternDecl->getType()->isDependentType()) {
  3033. QualType T = S.SubstType(PatternParam->getType(), TemplateArgs,
  3034. FunctionParam->getLocation(),
  3035. FunctionParam->getDeclName());
  3036. if (T.isNull())
  3037. return true;
  3038. FunctionParam->setType(T);
  3039. }
  3040. Scope.InstantiatedLocal(PatternParam, FunctionParam);
  3041. ++FParamIdx;
  3042. continue;
  3043. }
  3044. // Expand the parameter pack.
  3045. Scope.MakeInstantiatedLocalArgPack(PatternParam);
  3046. Optional<unsigned> NumArgumentsInExpansion
  3047. = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
  3048. assert(NumArgumentsInExpansion &&
  3049. "should only be called when all template arguments are known");
  3050. QualType PatternType =
  3051. PatternParam->getType()->castAs<PackExpansionType>()->getPattern();
  3052. for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
  3053. ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
  3054. FunctionParam->setDeclName(PatternParam->getDeclName());
  3055. if (!PatternDecl->getType()->isDependentType()) {
  3056. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, Arg);
  3057. QualType T = S.SubstType(PatternType, TemplateArgs,
  3058. FunctionParam->getLocation(),
  3059. FunctionParam->getDeclName());
  3060. if (T.isNull())
  3061. return true;
  3062. FunctionParam->setType(T);
  3063. }
  3064. Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
  3065. ++FParamIdx;
  3066. }
  3067. }
  3068. return false;
  3069. }
  3070. void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
  3071. FunctionDecl *Decl) {
  3072. const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
  3073. if (Proto->getExceptionSpecType() != EST_Uninstantiated)
  3074. return;
  3075. InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
  3076. InstantiatingTemplate::ExceptionSpecification());
  3077. if (Inst.isInvalid()) {
  3078. // We hit the instantiation depth limit. Clear the exception specification
  3079. // so that our callers don't have to cope with EST_Uninstantiated.
  3080. UpdateExceptionSpec(Decl, EST_None);
  3081. return;
  3082. }
  3083. if (Inst.isAlreadyInstantiating()) {
  3084. // This exception specification indirectly depends on itself. Reject.
  3085. // FIXME: Corresponding rule in the standard?
  3086. Diag(PointOfInstantiation, diag::err_exception_spec_cycle) << Decl;
  3087. UpdateExceptionSpec(Decl, EST_None);
  3088. return;
  3089. }
  3090. // Enter the scope of this instantiation. We don't use
  3091. // PushDeclContext because we don't have a scope.
  3092. Sema::ContextRAII savedContext(*this, Decl);
  3093. LocalInstantiationScope Scope(*this);
  3094. MultiLevelTemplateArgumentList TemplateArgs =
  3095. getTemplateInstantiationArgs(Decl, nullptr, /*RelativeToPrimary*/true);
  3096. FunctionDecl *Template = Proto->getExceptionSpecTemplate();
  3097. if (addInstantiatedParametersToScope(*this, Decl, Template, Scope,
  3098. TemplateArgs)) {
  3099. UpdateExceptionSpec(Decl, EST_None);
  3100. return;
  3101. }
  3102. SubstExceptionSpec(Decl, Template->getType()->castAs<FunctionProtoType>(),
  3103. TemplateArgs);
  3104. }
  3105. /// Initializes the common fields of an instantiation function
  3106. /// declaration (New) from the corresponding fields of its template (Tmpl).
  3107. ///
  3108. /// \returns true if there was an error
  3109. bool
  3110. TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
  3111. FunctionDecl *Tmpl) {
  3112. if (Tmpl->isDeleted())
  3113. New->setDeletedAsWritten();
  3114. New->setImplicit(Tmpl->isImplicit());
  3115. // Forward the mangling number from the template to the instantiated decl.
  3116. SemaRef.Context.setManglingNumber(New,
  3117. SemaRef.Context.getManglingNumber(Tmpl));
  3118. // If we are performing substituting explicitly-specified template arguments
  3119. // or deduced template arguments into a function template and we reach this
  3120. // point, we are now past the point where SFINAE applies and have committed
  3121. // to keeping the new function template specialization. We therefore
  3122. // convert the active template instantiation for the function template
  3123. // into a template instantiation for this specific function template
  3124. // specialization, which is not a SFINAE context, so that we diagnose any
  3125. // further errors in the declaration itself.
  3126. typedef Sema::CodeSynthesisContext ActiveInstType;
  3127. ActiveInstType &ActiveInst = SemaRef.CodeSynthesisContexts.back();
  3128. if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
  3129. ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
  3130. if (FunctionTemplateDecl *FunTmpl
  3131. = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
  3132. assert(FunTmpl->getTemplatedDecl() == Tmpl &&
  3133. "Deduction from the wrong function template?");
  3134. (void) FunTmpl;
  3135. atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
  3136. ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
  3137. ActiveInst.Entity = New;
  3138. atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
  3139. }
  3140. }
  3141. const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
  3142. assert(Proto && "Function template without prototype?");
  3143. if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
  3144. FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
  3145. // DR1330: In C++11, defer instantiation of a non-trivial
  3146. // exception specification.
  3147. // DR1484: Local classes and their members are instantiated along with the
  3148. // containing function.
  3149. if (SemaRef.getLangOpts().CPlusPlus11 &&
  3150. EPI.ExceptionSpec.Type != EST_None &&
  3151. EPI.ExceptionSpec.Type != EST_DynamicNone &&
  3152. EPI.ExceptionSpec.Type != EST_BasicNoexcept &&
  3153. !Tmpl->isLexicallyWithinFunctionOrMethod()) {
  3154. FunctionDecl *ExceptionSpecTemplate = Tmpl;
  3155. if (EPI.ExceptionSpec.Type == EST_Uninstantiated)
  3156. ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate;
  3157. ExceptionSpecificationType NewEST = EST_Uninstantiated;
  3158. if (EPI.ExceptionSpec.Type == EST_Unevaluated)
  3159. NewEST = EST_Unevaluated;
  3160. // Mark the function has having an uninstantiated exception specification.
  3161. const FunctionProtoType *NewProto
  3162. = New->getType()->getAs<FunctionProtoType>();
  3163. assert(NewProto && "Template instantiation without function prototype?");
  3164. EPI = NewProto->getExtProtoInfo();
  3165. EPI.ExceptionSpec.Type = NewEST;
  3166. EPI.ExceptionSpec.SourceDecl = New;
  3167. EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate;
  3168. New->setType(SemaRef.Context.getFunctionType(
  3169. NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
  3170. } else {
  3171. Sema::ContextRAII SwitchContext(SemaRef, New);
  3172. SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs);
  3173. }
  3174. }
  3175. // Get the definition. Leaves the variable unchanged if undefined.
  3176. const FunctionDecl *Definition = Tmpl;
  3177. Tmpl->isDefined(Definition);
  3178. SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
  3179. LateAttrs, StartingScope);
  3180. return false;
  3181. }
  3182. /// Initializes common fields of an instantiated method
  3183. /// declaration (New) from the corresponding fields of its template
  3184. /// (Tmpl).
  3185. ///
  3186. /// \returns true if there was an error
  3187. bool
  3188. TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
  3189. CXXMethodDecl *Tmpl) {
  3190. if (InitFunctionInstantiation(New, Tmpl))
  3191. return true;
  3192. if (isa<CXXDestructorDecl>(New) && SemaRef.getLangOpts().CPlusPlus11)
  3193. SemaRef.AdjustDestructorExceptionSpec(cast<CXXDestructorDecl>(New));
  3194. New->setAccess(Tmpl->getAccess());
  3195. if (Tmpl->isVirtualAsWritten())
  3196. New->setVirtualAsWritten(true);
  3197. // FIXME: New needs a pointer to Tmpl
  3198. return false;
  3199. }
  3200. /// Instantiate (or find existing instantiation of) a function template with a
  3201. /// given set of template arguments.
  3202. ///
  3203. /// Usually this should not be used, and template argument deduction should be
  3204. /// used in its place.
  3205. FunctionDecl *
  3206. Sema::InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD,
  3207. const TemplateArgumentList *Args,
  3208. SourceLocation Loc) {
  3209. FunctionDecl *FD = FTD->getTemplatedDecl();
  3210. sema::TemplateDeductionInfo Info(Loc);
  3211. InstantiatingTemplate Inst(
  3212. *this, Loc, FTD, Args->asArray(),
  3213. CodeSynthesisContext::ExplicitTemplateArgumentSubstitution, Info);
  3214. if (Inst.isInvalid())
  3215. return nullptr;
  3216. ContextRAII SavedContext(*this, FD);
  3217. MultiLevelTemplateArgumentList MArgs(*Args);
  3218. return cast_or_null<FunctionDecl>(SubstDecl(FD, FD->getParent(), MArgs));
  3219. }
  3220. /// In the MS ABI, we need to instantiate default arguments of dllexported
  3221. /// default constructors along with the constructor definition. This allows IR
  3222. /// gen to emit a constructor closure which calls the default constructor with
  3223. /// its default arguments.
  3224. static void InstantiateDefaultCtorDefaultArgs(Sema &S,
  3225. CXXConstructorDecl *Ctor) {
  3226. assert(S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  3227. Ctor->isDefaultConstructor());
  3228. unsigned NumParams = Ctor->getNumParams();
  3229. if (NumParams == 0)
  3230. return;
  3231. DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>();
  3232. if (!Attr)
  3233. return;
  3234. for (unsigned I = 0; I != NumParams; ++I) {
  3235. (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), Ctor,
  3236. Ctor->getParamDecl(I));
  3237. S.DiscardCleanupsInEvaluationContext();
  3238. }
  3239. }
  3240. /// Instantiate the definition of the given function from its
  3241. /// template.
  3242. ///
  3243. /// \param PointOfInstantiation the point at which the instantiation was
  3244. /// required. Note that this is not precisely a "point of instantiation"
  3245. /// for the function, but it's close.
  3246. ///
  3247. /// \param Function the already-instantiated declaration of a
  3248. /// function template specialization or member function of a class template
  3249. /// specialization.
  3250. ///
  3251. /// \param Recursive if true, recursively instantiates any functions that
  3252. /// are required by this instantiation.
  3253. ///
  3254. /// \param DefinitionRequired if true, then we are performing an explicit
  3255. /// instantiation where the body of the function is required. Complain if
  3256. /// there is no such body.
  3257. void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
  3258. FunctionDecl *Function,
  3259. bool Recursive,
  3260. bool DefinitionRequired,
  3261. bool AtEndOfTU) {
  3262. if (Function->isInvalidDecl() || Function->isDefined() ||
  3263. isa<CXXDeductionGuideDecl>(Function))
  3264. return;
  3265. // Never instantiate an explicit specialization except if it is a class scope
  3266. // explicit specialization.
  3267. TemplateSpecializationKind TSK = Function->getTemplateSpecializationKind();
  3268. if (TSK == TSK_ExplicitSpecialization &&
  3269. !Function->getClassScopeSpecializationPattern())
  3270. return;
  3271. // Find the function body that we'll be substituting.
  3272. const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
  3273. assert(PatternDecl && "instantiating a non-template");
  3274. const FunctionDecl *PatternDef = PatternDecl->getDefinition();
  3275. Stmt *Pattern = nullptr;
  3276. if (PatternDef) {
  3277. Pattern = PatternDef->getBody(PatternDef);
  3278. PatternDecl = PatternDef;
  3279. if (PatternDef->willHaveBody())
  3280. PatternDef = nullptr;
  3281. }
  3282. // FIXME: We need to track the instantiation stack in order to know which
  3283. // definitions should be visible within this instantiation.
  3284. if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Function,
  3285. Function->getInstantiatedFromMemberFunction(),
  3286. PatternDecl, PatternDef, TSK,
  3287. /*Complain*/DefinitionRequired)) {
  3288. if (DefinitionRequired)
  3289. Function->setInvalidDecl();
  3290. else if (TSK == TSK_ExplicitInstantiationDefinition) {
  3291. // Try again at the end of the translation unit (at which point a
  3292. // definition will be required).
  3293. assert(!Recursive);
  3294. Function->setInstantiationIsPending(true);
  3295. PendingInstantiations.push_back(
  3296. std::make_pair(Function, PointOfInstantiation));
  3297. } else if (TSK == TSK_ImplicitInstantiation) {
  3298. if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
  3299. !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
  3300. Diag(PointOfInstantiation, diag::warn_func_template_missing)
  3301. << Function;
  3302. Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
  3303. if (getLangOpts().CPlusPlus11)
  3304. Diag(PointOfInstantiation, diag::note_inst_declaration_hint)
  3305. << Function;
  3306. }
  3307. }
  3308. return;
  3309. }
  3310. // Postpone late parsed template instantiations.
  3311. if (PatternDecl->isLateTemplateParsed() &&
  3312. !LateTemplateParser) {
  3313. Function->setInstantiationIsPending(true);
  3314. LateParsedInstantiations.push_back(
  3315. std::make_pair(Function, PointOfInstantiation));
  3316. return;
  3317. }
  3318. // If we're performing recursive template instantiation, create our own
  3319. // queue of pending implicit instantiations that we will instantiate later,
  3320. // while we're still within our own instantiation context.
  3321. // This has to happen before LateTemplateParser below is called, so that
  3322. // it marks vtables used in late parsed templates as used.
  3323. GlobalEagerInstantiationScope GlobalInstantiations(*this,
  3324. /*Enabled=*/Recursive);
  3325. LocalEagerInstantiationScope LocalInstantiations(*this);
  3326. // Call the LateTemplateParser callback if there is a need to late parse
  3327. // a templated function definition.
  3328. if (!Pattern && PatternDecl->isLateTemplateParsed() &&
  3329. LateTemplateParser) {
  3330. // FIXME: Optimize to allow individual templates to be deserialized.
  3331. if (PatternDecl->isFromASTFile())
  3332. ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
  3333. auto LPTIter = LateParsedTemplateMap.find(PatternDecl);
  3334. assert(LPTIter != LateParsedTemplateMap.end() &&
  3335. "missing LateParsedTemplate");
  3336. LateTemplateParser(OpaqueParser, *LPTIter->second);
  3337. Pattern = PatternDecl->getBody(PatternDecl);
  3338. }
  3339. // Note, we should never try to instantiate a deleted function template.
  3340. assert((Pattern || PatternDecl->isDefaulted() ||
  3341. PatternDecl->hasSkippedBody()) &&
  3342. "unexpected kind of function template definition");
  3343. // C++1y [temp.explicit]p10:
  3344. // Except for inline functions, declarations with types deduced from their
  3345. // initializer or return value, and class template specializations, other
  3346. // explicit instantiation declarations have the effect of suppressing the
  3347. // implicit instantiation of the entity to which they refer.
  3348. if (TSK == TSK_ExplicitInstantiationDeclaration &&
  3349. !PatternDecl->isInlined() &&
  3350. !PatternDecl->getReturnType()->getContainedAutoType())
  3351. return;
  3352. if (PatternDecl->isInlined()) {
  3353. // Function, and all later redeclarations of it (from imported modules,
  3354. // for instance), are now implicitly inline.
  3355. for (auto *D = Function->getMostRecentDecl(); /**/;
  3356. D = D->getPreviousDecl()) {
  3357. D->setImplicitlyInline();
  3358. if (D == Function)
  3359. break;
  3360. }
  3361. }
  3362. InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
  3363. if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
  3364. return;
  3365. PrettyDeclStackTraceEntry CrashInfo(Context, Function, SourceLocation(),
  3366. "instantiating function definition");
  3367. // The instantiation is visible here, even if it was first declared in an
  3368. // unimported module.
  3369. Function->setVisibleDespiteOwningModule();
  3370. // Copy the inner loc start from the pattern.
  3371. Function->setInnerLocStart(PatternDecl->getInnerLocStart());
  3372. EnterExpressionEvaluationContext EvalContext(
  3373. *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
  3374. // Introduce a new scope where local variable instantiations will be
  3375. // recorded, unless we're actually a member function within a local
  3376. // class, in which case we need to merge our results with the parent
  3377. // scope (of the enclosing function).
  3378. bool MergeWithParentScope = false;
  3379. if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
  3380. MergeWithParentScope = Rec->isLocalClass();
  3381. LocalInstantiationScope Scope(*this, MergeWithParentScope);
  3382. if (PatternDecl->isDefaulted())
  3383. SetDeclDefaulted(Function, PatternDecl->getLocation());
  3384. else {
  3385. MultiLevelTemplateArgumentList TemplateArgs =
  3386. getTemplateInstantiationArgs(Function, nullptr, false, PatternDecl);
  3387. // Substitute into the qualifier; we can get a substitution failure here
  3388. // through evil use of alias templates.
  3389. // FIXME: Is CurContext correct for this? Should we go to the (instantiation
  3390. // of the) lexical context of the pattern?
  3391. SubstQualifier(*this, PatternDecl, Function, TemplateArgs);
  3392. ActOnStartOfFunctionDef(nullptr, Function);
  3393. // Enter the scope of this instantiation. We don't use
  3394. // PushDeclContext because we don't have a scope.
  3395. Sema::ContextRAII savedContext(*this, Function);
  3396. if (addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
  3397. TemplateArgs))
  3398. return;
  3399. StmtResult Body;
  3400. if (PatternDecl->hasSkippedBody()) {
  3401. ActOnSkippedFunctionBody(Function);
  3402. Body = nullptr;
  3403. } else {
  3404. if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Function)) {
  3405. // If this is a constructor, instantiate the member initializers.
  3406. InstantiateMemInitializers(Ctor, cast<CXXConstructorDecl>(PatternDecl),
  3407. TemplateArgs);
  3408. // If this is an MS ABI dllexport default constructor, instantiate any
  3409. // default arguments.
  3410. if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  3411. Ctor->isDefaultConstructor()) {
  3412. InstantiateDefaultCtorDefaultArgs(*this, Ctor);
  3413. }
  3414. }
  3415. // Instantiate the function body.
  3416. Body = SubstStmt(Pattern, TemplateArgs);
  3417. if (Body.isInvalid())
  3418. Function->setInvalidDecl();
  3419. }
  3420. // FIXME: finishing the function body while in an expression evaluation
  3421. // context seems wrong. Investigate more.
  3422. ActOnFinishFunctionBody(Function, Body.get(), /*IsInstantiation=*/true);
  3423. PerformDependentDiagnostics(PatternDecl, TemplateArgs);
  3424. if (auto *Listener = getASTMutationListener())
  3425. Listener->FunctionDefinitionInstantiated(Function);
  3426. savedContext.pop();
  3427. }
  3428. DeclGroupRef DG(Function);
  3429. Consumer.HandleTopLevelDecl(DG);
  3430. // This class may have local implicit instantiations that need to be
  3431. // instantiation within this scope.
  3432. LocalInstantiations.perform();
  3433. Scope.Exit();
  3434. GlobalInstantiations.perform();
  3435. }
  3436. VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation(
  3437. VarTemplateDecl *VarTemplate, VarDecl *FromVar,
  3438. const TemplateArgumentList &TemplateArgList,
  3439. const TemplateArgumentListInfo &TemplateArgsInfo,
  3440. SmallVectorImpl<TemplateArgument> &Converted,
  3441. SourceLocation PointOfInstantiation, void *InsertPos,
  3442. LateInstantiatedAttrVec *LateAttrs,
  3443. LocalInstantiationScope *StartingScope) {
  3444. if (FromVar->isInvalidDecl())
  3445. return nullptr;
  3446. InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
  3447. if (Inst.isInvalid())
  3448. return nullptr;
  3449. MultiLevelTemplateArgumentList TemplateArgLists;
  3450. TemplateArgLists.addOuterTemplateArguments(&TemplateArgList);
  3451. // Instantiate the first declaration of the variable template: for a partial
  3452. // specialization of a static data member template, the first declaration may
  3453. // or may not be the declaration in the class; if it's in the class, we want
  3454. // to instantiate a member in the class (a declaration), and if it's outside,
  3455. // we want to instantiate a definition.
  3456. //
  3457. // If we're instantiating an explicitly-specialized member template or member
  3458. // partial specialization, don't do this. The member specialization completely
  3459. // replaces the original declaration in this case.
  3460. bool IsMemberSpec = false;
  3461. if (VarTemplatePartialSpecializationDecl *PartialSpec =
  3462. dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar))
  3463. IsMemberSpec = PartialSpec->isMemberSpecialization();
  3464. else if (VarTemplateDecl *FromTemplate = FromVar->getDescribedVarTemplate())
  3465. IsMemberSpec = FromTemplate->isMemberSpecialization();
  3466. if (!IsMemberSpec)
  3467. FromVar = FromVar->getFirstDecl();
  3468. MultiLevelTemplateArgumentList MultiLevelList(TemplateArgList);
  3469. TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
  3470. MultiLevelList);
  3471. // TODO: Set LateAttrs and StartingScope ...
  3472. return cast_or_null<VarTemplateSpecializationDecl>(
  3473. Instantiator.VisitVarTemplateSpecializationDecl(
  3474. VarTemplate, FromVar, InsertPos, TemplateArgsInfo, Converted));
  3475. }
  3476. /// Instantiates a variable template specialization by completing it
  3477. /// with appropriate type information and initializer.
  3478. VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl(
  3479. VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
  3480. const MultiLevelTemplateArgumentList &TemplateArgs) {
  3481. assert(PatternDecl->isThisDeclarationADefinition() &&
  3482. "don't have a definition to instantiate from");
  3483. // Do substitution on the type of the declaration
  3484. TypeSourceInfo *DI =
  3485. SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
  3486. PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
  3487. if (!DI)
  3488. return nullptr;
  3489. // Update the type of this variable template specialization.
  3490. VarSpec->setType(DI->getType());
  3491. // Convert the declaration into a definition now.
  3492. VarSpec->setCompleteDefinition();
  3493. // Instantiate the initializer.
  3494. InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
  3495. return VarSpec;
  3496. }
  3497. /// BuildVariableInstantiation - Used after a new variable has been created.
  3498. /// Sets basic variable data and decides whether to postpone the
  3499. /// variable instantiation.
  3500. void Sema::BuildVariableInstantiation(
  3501. VarDecl *NewVar, VarDecl *OldVar,
  3502. const MultiLevelTemplateArgumentList &TemplateArgs,
  3503. LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
  3504. LocalInstantiationScope *StartingScope,
  3505. bool InstantiatingVarTemplate) {
  3506. // If we are instantiating a local extern declaration, the
  3507. // instantiation belongs lexically to the containing function.
  3508. // If we are instantiating a static data member defined
  3509. // out-of-line, the instantiation will have the same lexical
  3510. // context (which will be a namespace scope) as the template.
  3511. if (OldVar->isLocalExternDecl()) {
  3512. NewVar->setLocalExternDecl();
  3513. NewVar->setLexicalDeclContext(Owner);
  3514. } else if (OldVar->isOutOfLine())
  3515. NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
  3516. NewVar->setTSCSpec(OldVar->getTSCSpec());
  3517. NewVar->setInitStyle(OldVar->getInitStyle());
  3518. NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
  3519. NewVar->setObjCForDecl(OldVar->isObjCForDecl());
  3520. NewVar->setConstexpr(OldVar->isConstexpr());
  3521. NewVar->setInitCapture(OldVar->isInitCapture());
  3522. NewVar->setPreviousDeclInSameBlockScope(
  3523. OldVar->isPreviousDeclInSameBlockScope());
  3524. NewVar->setAccess(OldVar->getAccess());
  3525. if (!OldVar->isStaticDataMember()) {
  3526. if (OldVar->isUsed(false))
  3527. NewVar->setIsUsed();
  3528. NewVar->setReferenced(OldVar->isReferenced());
  3529. }
  3530. InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
  3531. LookupResult Previous(
  3532. *this, NewVar->getDeclName(), NewVar->getLocation(),
  3533. NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
  3534. : Sema::LookupOrdinaryName,
  3535. NewVar->isLocalExternDecl() ? Sema::ForExternalRedeclaration
  3536. : forRedeclarationInCurContext());
  3537. if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
  3538. (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() ||
  3539. OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
  3540. // We have a previous declaration. Use that one, so we merge with the
  3541. // right type.
  3542. if (NamedDecl *NewPrev = FindInstantiatedDecl(
  3543. NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
  3544. Previous.addDecl(NewPrev);
  3545. } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
  3546. OldVar->hasLinkage())
  3547. LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
  3548. CheckVariableDeclaration(NewVar, Previous);
  3549. if (!InstantiatingVarTemplate) {
  3550. NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
  3551. if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
  3552. NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
  3553. }
  3554. if (!OldVar->isOutOfLine()) {
  3555. if (NewVar->getDeclContext()->isFunctionOrMethod())
  3556. CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
  3557. }
  3558. // Link instantiations of static data members back to the template from
  3559. // which they were instantiated.
  3560. if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate)
  3561. NewVar->setInstantiationOfStaticDataMember(OldVar,
  3562. TSK_ImplicitInstantiation);
  3563. // Forward the mangling number from the template to the instantiated decl.
  3564. Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar));
  3565. Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar));
  3566. // Delay instantiation of the initializer for variable templates or inline
  3567. // static data members until a definition of the variable is needed. We need
  3568. // it right away if the type contains 'auto'.
  3569. if ((!isa<VarTemplateSpecializationDecl>(NewVar) &&
  3570. !InstantiatingVarTemplate &&
  3571. !(OldVar->isInline() && OldVar->isThisDeclarationADefinition() &&
  3572. !NewVar->isThisDeclarationADefinition())) ||
  3573. NewVar->getType()->isUndeducedType())
  3574. InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
  3575. // Diagnose unused local variables with dependent types, where the diagnostic
  3576. // will have been deferred.
  3577. if (!NewVar->isInvalidDecl() &&
  3578. NewVar->getDeclContext()->isFunctionOrMethod() &&
  3579. OldVar->getType()->isDependentType())
  3580. DiagnoseUnusedDecl(NewVar);
  3581. }
  3582. /// Instantiate the initializer of a variable.
  3583. void Sema::InstantiateVariableInitializer(
  3584. VarDecl *Var, VarDecl *OldVar,
  3585. const MultiLevelTemplateArgumentList &TemplateArgs) {
  3586. if (ASTMutationListener *L = getASTContext().getASTMutationListener())
  3587. L->VariableDefinitionInstantiated(Var);
  3588. // We propagate the 'inline' flag with the initializer, because it
  3589. // would otherwise imply that the variable is a definition for a
  3590. // non-static data member.
  3591. if (OldVar->isInlineSpecified())
  3592. Var->setInlineSpecified();
  3593. else if (OldVar->isInline())
  3594. Var->setImplicitlyInline();
  3595. if (OldVar->getInit()) {
  3596. EnterExpressionEvaluationContext Evaluated(
  3597. *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, Var);
  3598. // Instantiate the initializer.
  3599. ExprResult Init;
  3600. {
  3601. ContextRAII SwitchContext(*this, Var->getDeclContext());
  3602. Init = SubstInitializer(OldVar->getInit(), TemplateArgs,
  3603. OldVar->getInitStyle() == VarDecl::CallInit);
  3604. }
  3605. if (!Init.isInvalid()) {
  3606. Expr *InitExpr = Init.get();
  3607. if (Var->hasAttr<DLLImportAttr>() &&
  3608. (!InitExpr ||
  3609. !InitExpr->isConstantInitializer(getASTContext(), false))) {
  3610. // Do not dynamically initialize dllimport variables.
  3611. } else if (InitExpr) {
  3612. bool DirectInit = OldVar->isDirectInit();
  3613. AddInitializerToDecl(Var, InitExpr, DirectInit);
  3614. } else
  3615. ActOnUninitializedDecl(Var);
  3616. } else {
  3617. // FIXME: Not too happy about invalidating the declaration
  3618. // because of a bogus initializer.
  3619. Var->setInvalidDecl();
  3620. }
  3621. } else {
  3622. // `inline` variables are a definition and declaration all in one; we won't
  3623. // pick up an initializer from anywhere else.
  3624. if (Var->isStaticDataMember() && !Var->isInline()) {
  3625. if (!Var->isOutOfLine())
  3626. return;
  3627. // If the declaration inside the class had an initializer, don't add
  3628. // another one to the out-of-line definition.
  3629. if (OldVar->getFirstDecl()->hasInit())
  3630. return;
  3631. }
  3632. // We'll add an initializer to a for-range declaration later.
  3633. if (Var->isCXXForRangeDecl() || Var->isObjCForDecl())
  3634. return;
  3635. ActOnUninitializedDecl(Var);
  3636. }
  3637. if (getLangOpts().CUDA)
  3638. checkAllowedCUDAInitializer(Var);
  3639. }
  3640. /// Instantiate the definition of the given variable from its
  3641. /// template.
  3642. ///
  3643. /// \param PointOfInstantiation the point at which the instantiation was
  3644. /// required. Note that this is not precisely a "point of instantiation"
  3645. /// for the variable, but it's close.
  3646. ///
  3647. /// \param Var the already-instantiated declaration of a templated variable.
  3648. ///
  3649. /// \param Recursive if true, recursively instantiates any functions that
  3650. /// are required by this instantiation.
  3651. ///
  3652. /// \param DefinitionRequired if true, then we are performing an explicit
  3653. /// instantiation where a definition of the variable is required. Complain
  3654. /// if there is no such definition.
  3655. void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
  3656. VarDecl *Var, bool Recursive,
  3657. bool DefinitionRequired, bool AtEndOfTU) {
  3658. if (Var->isInvalidDecl())
  3659. return;
  3660. VarTemplateSpecializationDecl *VarSpec =
  3661. dyn_cast<VarTemplateSpecializationDecl>(Var);
  3662. VarDecl *PatternDecl = nullptr, *Def = nullptr;
  3663. MultiLevelTemplateArgumentList TemplateArgs =
  3664. getTemplateInstantiationArgs(Var);
  3665. if (VarSpec) {
  3666. // If this is a variable template specialization, make sure that it is
  3667. // non-dependent, then find its instantiation pattern.
  3668. bool InstantiationDependent = false;
  3669. assert(!TemplateSpecializationType::anyDependentTemplateArguments(
  3670. VarSpec->getTemplateArgsInfo(), InstantiationDependent) &&
  3671. "Only instantiate variable template specializations that are "
  3672. "not type-dependent");
  3673. (void)InstantiationDependent;
  3674. // Find the variable initialization that we'll be substituting. If the
  3675. // pattern was instantiated from a member template, look back further to
  3676. // find the real pattern.
  3677. assert(VarSpec->getSpecializedTemplate() &&
  3678. "Specialization without specialized template?");
  3679. llvm::PointerUnion<VarTemplateDecl *,
  3680. VarTemplatePartialSpecializationDecl *> PatternPtr =
  3681. VarSpec->getSpecializedTemplateOrPartial();
  3682. if (PatternPtr.is<VarTemplatePartialSpecializationDecl *>()) {
  3683. VarTemplatePartialSpecializationDecl *Tmpl =
  3684. PatternPtr.get<VarTemplatePartialSpecializationDecl *>();
  3685. while (VarTemplatePartialSpecializationDecl *From =
  3686. Tmpl->getInstantiatedFromMember()) {
  3687. if (Tmpl->isMemberSpecialization())
  3688. break;
  3689. Tmpl = From;
  3690. }
  3691. PatternDecl = Tmpl;
  3692. } else {
  3693. VarTemplateDecl *Tmpl = PatternPtr.get<VarTemplateDecl *>();
  3694. while (VarTemplateDecl *From =
  3695. Tmpl->getInstantiatedFromMemberTemplate()) {
  3696. if (Tmpl->isMemberSpecialization())
  3697. break;
  3698. Tmpl = From;
  3699. }
  3700. PatternDecl = Tmpl->getTemplatedDecl();
  3701. }
  3702. // If this is a static data member template, there might be an
  3703. // uninstantiated initializer on the declaration. If so, instantiate
  3704. // it now.
  3705. //
  3706. // FIXME: This largely duplicates what we would do below. The difference
  3707. // is that along this path we may instantiate an initializer from an
  3708. // in-class declaration of the template and instantiate the definition
  3709. // from a separate out-of-class definition.
  3710. if (PatternDecl->isStaticDataMember() &&
  3711. (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
  3712. !Var->hasInit()) {
  3713. // FIXME: Factor out the duplicated instantiation context setup/tear down
  3714. // code here.
  3715. InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
  3716. if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
  3717. return;
  3718. PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
  3719. "instantiating variable initializer");
  3720. // The instantiation is visible here, even if it was first declared in an
  3721. // unimported module.
  3722. Var->setVisibleDespiteOwningModule();
  3723. // If we're performing recursive template instantiation, create our own
  3724. // queue of pending implicit instantiations that we will instantiate
  3725. // later, while we're still within our own instantiation context.
  3726. GlobalEagerInstantiationScope GlobalInstantiations(*this,
  3727. /*Enabled=*/Recursive);
  3728. LocalInstantiationScope Local(*this);
  3729. LocalEagerInstantiationScope LocalInstantiations(*this);
  3730. // Enter the scope of this instantiation. We don't use
  3731. // PushDeclContext because we don't have a scope.
  3732. ContextRAII PreviousContext(*this, Var->getDeclContext());
  3733. InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
  3734. PreviousContext.pop();
  3735. // This variable may have local implicit instantiations that need to be
  3736. // instantiated within this scope.
  3737. LocalInstantiations.perform();
  3738. Local.Exit();
  3739. GlobalInstantiations.perform();
  3740. }
  3741. // Find actual definition
  3742. Def = PatternDecl->getDefinition(getASTContext());
  3743. } else {
  3744. // If this is a static data member, find its out-of-line definition.
  3745. assert(Var->isStaticDataMember() && "not a static data member?");
  3746. PatternDecl = Var->getInstantiatedFromStaticDataMember();
  3747. assert(PatternDecl && "data member was not instantiated from a template?");
  3748. assert(PatternDecl->isStaticDataMember() && "not a static data member?");
  3749. Def = PatternDecl->getDefinition();
  3750. }
  3751. TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
  3752. // If we don't have a definition of the variable template, we won't perform
  3753. // any instantiation. Rather, we rely on the user to instantiate this
  3754. // definition (or provide a specialization for it) in another translation
  3755. // unit.
  3756. if (!Def && !DefinitionRequired) {
  3757. if (TSK == TSK_ExplicitInstantiationDefinition) {
  3758. PendingInstantiations.push_back(
  3759. std::make_pair(Var, PointOfInstantiation));
  3760. } else if (TSK == TSK_ImplicitInstantiation) {
  3761. // Warn about missing definition at the end of translation unit.
  3762. if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
  3763. !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
  3764. Diag(PointOfInstantiation, diag::warn_var_template_missing)
  3765. << Var;
  3766. Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
  3767. if (getLangOpts().CPlusPlus11)
  3768. Diag(PointOfInstantiation, diag::note_inst_declaration_hint) << Var;
  3769. }
  3770. return;
  3771. }
  3772. }
  3773. // FIXME: We need to track the instantiation stack in order to know which
  3774. // definitions should be visible within this instantiation.
  3775. // FIXME: Produce diagnostics when Var->getInstantiatedFromStaticDataMember().
  3776. if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Var,
  3777. /*InstantiatedFromMember*/false,
  3778. PatternDecl, Def, TSK,
  3779. /*Complain*/DefinitionRequired))
  3780. return;
  3781. // Never instantiate an explicit specialization.
  3782. if (TSK == TSK_ExplicitSpecialization)
  3783. return;
  3784. // C++11 [temp.explicit]p10:
  3785. // Except for inline functions, const variables of literal types, variables
  3786. // of reference types, [...] explicit instantiation declarations
  3787. // have the effect of suppressing the implicit instantiation of the entity
  3788. // to which they refer.
  3789. if (TSK == TSK_ExplicitInstantiationDeclaration &&
  3790. !Var->isUsableInConstantExpressions(getASTContext()))
  3791. return;
  3792. // Make sure to pass the instantiated variable to the consumer at the end.
  3793. struct PassToConsumerRAII {
  3794. ASTConsumer &Consumer;
  3795. VarDecl *Var;
  3796. PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
  3797. : Consumer(Consumer), Var(Var) { }
  3798. ~PassToConsumerRAII() {
  3799. Consumer.HandleCXXStaticMemberVarInstantiation(Var);
  3800. }
  3801. } PassToConsumerRAII(Consumer, Var);
  3802. // If we already have a definition, we're done.
  3803. if (VarDecl *Def = Var->getDefinition()) {
  3804. // We may be explicitly instantiating something we've already implicitly
  3805. // instantiated.
  3806. Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
  3807. PointOfInstantiation);
  3808. return;
  3809. }
  3810. InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
  3811. if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
  3812. return;
  3813. PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
  3814. "instantiating variable definition");
  3815. // If we're performing recursive template instantiation, create our own
  3816. // queue of pending implicit instantiations that we will instantiate later,
  3817. // while we're still within our own instantiation context.
  3818. GlobalEagerInstantiationScope GlobalInstantiations(*this,
  3819. /*Enabled=*/Recursive);
  3820. // Enter the scope of this instantiation. We don't use
  3821. // PushDeclContext because we don't have a scope.
  3822. ContextRAII PreviousContext(*this, Var->getDeclContext());
  3823. LocalInstantiationScope Local(*this);
  3824. LocalEagerInstantiationScope LocalInstantiations(*this);
  3825. VarDecl *OldVar = Var;
  3826. if (Def->isStaticDataMember() && !Def->isOutOfLine()) {
  3827. // We're instantiating an inline static data member whose definition was
  3828. // provided inside the class.
  3829. InstantiateVariableInitializer(Var, Def, TemplateArgs);
  3830. } else if (!VarSpec) {
  3831. Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
  3832. TemplateArgs));
  3833. } else if (Var->isStaticDataMember() &&
  3834. Var->getLexicalDeclContext()->isRecord()) {
  3835. // We need to instantiate the definition of a static data member template,
  3836. // and all we have is the in-class declaration of it. Instantiate a separate
  3837. // declaration of the definition.
  3838. TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
  3839. TemplateArgs);
  3840. Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl(
  3841. VarSpec->getSpecializedTemplate(), Def, nullptr,
  3842. VarSpec->getTemplateArgsInfo(), VarSpec->getTemplateArgs().asArray()));
  3843. if (Var) {
  3844. llvm::PointerUnion<VarTemplateDecl *,
  3845. VarTemplatePartialSpecializationDecl *> PatternPtr =
  3846. VarSpec->getSpecializedTemplateOrPartial();
  3847. if (VarTemplatePartialSpecializationDecl *Partial =
  3848. PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
  3849. cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
  3850. Partial, &VarSpec->getTemplateInstantiationArgs());
  3851. // Merge the definition with the declaration.
  3852. LookupResult R(*this, Var->getDeclName(), Var->getLocation(),
  3853. LookupOrdinaryName, forRedeclarationInCurContext());
  3854. R.addDecl(OldVar);
  3855. MergeVarDecl(Var, R);
  3856. // Attach the initializer.
  3857. InstantiateVariableInitializer(Var, Def, TemplateArgs);
  3858. }
  3859. } else
  3860. // Complete the existing variable's definition with an appropriately
  3861. // substituted type and initializer.
  3862. Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
  3863. PreviousContext.pop();
  3864. if (Var) {
  3865. PassToConsumerRAII.Var = Var;
  3866. Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(),
  3867. OldVar->getPointOfInstantiation());
  3868. }
  3869. // This variable may have local implicit instantiations that need to be
  3870. // instantiated within this scope.
  3871. LocalInstantiations.perform();
  3872. Local.Exit();
  3873. GlobalInstantiations.perform();
  3874. }
  3875. void
  3876. Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
  3877. const CXXConstructorDecl *Tmpl,
  3878. const MultiLevelTemplateArgumentList &TemplateArgs) {
  3879. SmallVector<CXXCtorInitializer*, 4> NewInits;
  3880. bool AnyErrors = Tmpl->isInvalidDecl();
  3881. // Instantiate all the initializers.
  3882. for (const auto *Init : Tmpl->inits()) {
  3883. // Only instantiate written initializers, let Sema re-construct implicit
  3884. // ones.
  3885. if (!Init->isWritten())
  3886. continue;
  3887. SourceLocation EllipsisLoc;
  3888. if (Init->isPackExpansion()) {
  3889. // This is a pack expansion. We should expand it now.
  3890. TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
  3891. SmallVector<UnexpandedParameterPack, 4> Unexpanded;
  3892. collectUnexpandedParameterPacks(BaseTL, Unexpanded);
  3893. collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
  3894. bool ShouldExpand = false;
  3895. bool RetainExpansion = false;
  3896. Optional<unsigned> NumExpansions;
  3897. if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
  3898. BaseTL.getSourceRange(),
  3899. Unexpanded,
  3900. TemplateArgs, ShouldExpand,
  3901. RetainExpansion,
  3902. NumExpansions)) {
  3903. AnyErrors = true;
  3904. New->setInvalidDecl();
  3905. continue;
  3906. }
  3907. assert(ShouldExpand && "Partial instantiation of base initializer?");
  3908. // Loop over all of the arguments in the argument pack(s),
  3909. for (unsigned I = 0; I != *NumExpansions; ++I) {
  3910. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
  3911. // Instantiate the initializer.
  3912. ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
  3913. /*CXXDirectInit=*/true);
  3914. if (TempInit.isInvalid()) {
  3915. AnyErrors = true;
  3916. break;
  3917. }
  3918. // Instantiate the base type.
  3919. TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
  3920. TemplateArgs,
  3921. Init->getSourceLocation(),
  3922. New->getDeclName());
  3923. if (!BaseTInfo) {
  3924. AnyErrors = true;
  3925. break;
  3926. }
  3927. // Build the initializer.
  3928. MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
  3929. BaseTInfo, TempInit.get(),
  3930. New->getParent(),
  3931. SourceLocation());
  3932. if (NewInit.isInvalid()) {
  3933. AnyErrors = true;
  3934. break;
  3935. }
  3936. NewInits.push_back(NewInit.get());
  3937. }
  3938. continue;
  3939. }
  3940. // Instantiate the initializer.
  3941. ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
  3942. /*CXXDirectInit=*/true);
  3943. if (TempInit.isInvalid()) {
  3944. AnyErrors = true;
  3945. continue;
  3946. }
  3947. MemInitResult NewInit;
  3948. if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
  3949. TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
  3950. TemplateArgs,
  3951. Init->getSourceLocation(),
  3952. New->getDeclName());
  3953. if (!TInfo) {
  3954. AnyErrors = true;
  3955. New->setInvalidDecl();
  3956. continue;
  3957. }
  3958. if (Init->isBaseInitializer())
  3959. NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.get(),
  3960. New->getParent(), EllipsisLoc);
  3961. else
  3962. NewInit = BuildDelegatingInitializer(TInfo, TempInit.get(),
  3963. cast<CXXRecordDecl>(CurContext->getParent()));
  3964. } else if (Init->isMemberInitializer()) {
  3965. FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
  3966. Init->getMemberLocation(),
  3967. Init->getMember(),
  3968. TemplateArgs));
  3969. if (!Member) {
  3970. AnyErrors = true;
  3971. New->setInvalidDecl();
  3972. continue;
  3973. }
  3974. NewInit = BuildMemberInitializer(Member, TempInit.get(),
  3975. Init->getSourceLocation());
  3976. } else if (Init->isIndirectMemberInitializer()) {
  3977. IndirectFieldDecl *IndirectMember =
  3978. cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
  3979. Init->getMemberLocation(),
  3980. Init->getIndirectMember(), TemplateArgs));
  3981. if (!IndirectMember) {
  3982. AnyErrors = true;
  3983. New->setInvalidDecl();
  3984. continue;
  3985. }
  3986. NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(),
  3987. Init->getSourceLocation());
  3988. }
  3989. if (NewInit.isInvalid()) {
  3990. AnyErrors = true;
  3991. New->setInvalidDecl();
  3992. } else {
  3993. NewInits.push_back(NewInit.get());
  3994. }
  3995. }
  3996. // Assign all the initializers to the new constructor.
  3997. ActOnMemInitializers(New,
  3998. /*FIXME: ColonLoc */
  3999. SourceLocation(),
  4000. NewInits,
  4001. AnyErrors);
  4002. }
  4003. // TODO: this could be templated if the various decl types used the
  4004. // same method name.
  4005. static bool isInstantiationOf(ClassTemplateDecl *Pattern,
  4006. ClassTemplateDecl *Instance) {
  4007. Pattern = Pattern->getCanonicalDecl();
  4008. do {
  4009. Instance = Instance->getCanonicalDecl();
  4010. if (Pattern == Instance) return true;
  4011. Instance = Instance->getInstantiatedFromMemberTemplate();
  4012. } while (Instance);
  4013. return false;
  4014. }
  4015. static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
  4016. FunctionTemplateDecl *Instance) {
  4017. Pattern = Pattern->getCanonicalDecl();
  4018. do {
  4019. Instance = Instance->getCanonicalDecl();
  4020. if (Pattern == Instance) return true;
  4021. Instance = Instance->getInstantiatedFromMemberTemplate();
  4022. } while (Instance);
  4023. return false;
  4024. }
  4025. static bool
  4026. isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
  4027. ClassTemplatePartialSpecializationDecl *Instance) {
  4028. Pattern
  4029. = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
  4030. do {
  4031. Instance = cast<ClassTemplatePartialSpecializationDecl>(
  4032. Instance->getCanonicalDecl());
  4033. if (Pattern == Instance)
  4034. return true;
  4035. Instance = Instance->getInstantiatedFromMember();
  4036. } while (Instance);
  4037. return false;
  4038. }
  4039. static bool isInstantiationOf(CXXRecordDecl *Pattern,
  4040. CXXRecordDecl *Instance) {
  4041. Pattern = Pattern->getCanonicalDecl();
  4042. do {
  4043. Instance = Instance->getCanonicalDecl();
  4044. if (Pattern == Instance) return true;
  4045. Instance = Instance->getInstantiatedFromMemberClass();
  4046. } while (Instance);
  4047. return false;
  4048. }
  4049. static bool isInstantiationOf(FunctionDecl *Pattern,
  4050. FunctionDecl *Instance) {
  4051. Pattern = Pattern->getCanonicalDecl();
  4052. do {
  4053. Instance = Instance->getCanonicalDecl();
  4054. if (Pattern == Instance) return true;
  4055. Instance = Instance->getInstantiatedFromMemberFunction();
  4056. } while (Instance);
  4057. return false;
  4058. }
  4059. static bool isInstantiationOf(EnumDecl *Pattern,
  4060. EnumDecl *Instance) {
  4061. Pattern = Pattern->getCanonicalDecl();
  4062. do {
  4063. Instance = Instance->getCanonicalDecl();
  4064. if (Pattern == Instance) return true;
  4065. Instance = Instance->getInstantiatedFromMemberEnum();
  4066. } while (Instance);
  4067. return false;
  4068. }
  4069. static bool isInstantiationOf(UsingShadowDecl *Pattern,
  4070. UsingShadowDecl *Instance,
  4071. ASTContext &C) {
  4072. return declaresSameEntity(C.getInstantiatedFromUsingShadowDecl(Instance),
  4073. Pattern);
  4074. }
  4075. static bool isInstantiationOf(UsingDecl *Pattern, UsingDecl *Instance,
  4076. ASTContext &C) {
  4077. return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
  4078. }
  4079. template<typename T>
  4080. static bool isInstantiationOfUnresolvedUsingDecl(T *Pattern, Decl *Other,
  4081. ASTContext &Ctx) {
  4082. // An unresolved using declaration can instantiate to an unresolved using
  4083. // declaration, or to a using declaration or a using declaration pack.
  4084. //
  4085. // Multiple declarations can claim to be instantiated from an unresolved
  4086. // using declaration if it's a pack expansion. We want the UsingPackDecl
  4087. // in that case, not the individual UsingDecls within the pack.
  4088. bool OtherIsPackExpansion;
  4089. NamedDecl *OtherFrom;
  4090. if (auto *OtherUUD = dyn_cast<T>(Other)) {
  4091. OtherIsPackExpansion = OtherUUD->isPackExpansion();
  4092. OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUUD);
  4093. } else if (auto *OtherUPD = dyn_cast<UsingPackDecl>(Other)) {
  4094. OtherIsPackExpansion = true;
  4095. OtherFrom = OtherUPD->getInstantiatedFromUsingDecl();
  4096. } else if (auto *OtherUD = dyn_cast<UsingDecl>(Other)) {
  4097. OtherIsPackExpansion = false;
  4098. OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUD);
  4099. } else {
  4100. return false;
  4101. }
  4102. return Pattern->isPackExpansion() == OtherIsPackExpansion &&
  4103. declaresSameEntity(OtherFrom, Pattern);
  4104. }
  4105. static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
  4106. VarDecl *Instance) {
  4107. assert(Instance->isStaticDataMember());
  4108. Pattern = Pattern->getCanonicalDecl();
  4109. do {
  4110. Instance = Instance->getCanonicalDecl();
  4111. if (Pattern == Instance) return true;
  4112. Instance = Instance->getInstantiatedFromStaticDataMember();
  4113. } while (Instance);
  4114. return false;
  4115. }
  4116. // Other is the prospective instantiation
  4117. // D is the prospective pattern
  4118. static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
  4119. if (auto *UUD = dyn_cast<UnresolvedUsingTypenameDecl>(D))
  4120. return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx);
  4121. if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(D))
  4122. return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx);
  4123. if (D->getKind() != Other->getKind())
  4124. return false;
  4125. if (auto *Record = dyn_cast<CXXRecordDecl>(Other))
  4126. return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
  4127. if (auto *Function = dyn_cast<FunctionDecl>(Other))
  4128. return isInstantiationOf(cast<FunctionDecl>(D), Function);
  4129. if (auto *Enum = dyn_cast<EnumDecl>(Other))
  4130. return isInstantiationOf(cast<EnumDecl>(D), Enum);
  4131. if (auto *Var = dyn_cast<VarDecl>(Other))
  4132. if (Var->isStaticDataMember())
  4133. return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
  4134. if (auto *Temp = dyn_cast<ClassTemplateDecl>(Other))
  4135. return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
  4136. if (auto *Temp = dyn_cast<FunctionTemplateDecl>(Other))
  4137. return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
  4138. if (auto *PartialSpec =
  4139. dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
  4140. return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
  4141. PartialSpec);
  4142. if (auto *Field = dyn_cast<FieldDecl>(Other)) {
  4143. if (!Field->getDeclName()) {
  4144. // This is an unnamed field.
  4145. return declaresSameEntity(Ctx.getInstantiatedFromUnnamedFieldDecl(Field),
  4146. cast<FieldDecl>(D));
  4147. }
  4148. }
  4149. if (auto *Using = dyn_cast<UsingDecl>(Other))
  4150. return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
  4151. if (auto *Shadow = dyn_cast<UsingShadowDecl>(Other))
  4152. return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
  4153. return D->getDeclName() &&
  4154. D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
  4155. }
  4156. template<typename ForwardIterator>
  4157. static NamedDecl *findInstantiationOf(ASTContext &Ctx,
  4158. NamedDecl *D,
  4159. ForwardIterator first,
  4160. ForwardIterator last) {
  4161. for (; first != last; ++first)
  4162. if (isInstantiationOf(Ctx, D, *first))
  4163. return cast<NamedDecl>(*first);
  4164. return nullptr;
  4165. }
  4166. /// Finds the instantiation of the given declaration context
  4167. /// within the current instantiation.
  4168. ///
  4169. /// \returns NULL if there was an error
  4170. DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
  4171. const MultiLevelTemplateArgumentList &TemplateArgs) {
  4172. if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
  4173. Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs, true);
  4174. return cast_or_null<DeclContext>(ID);
  4175. } else return DC;
  4176. }
  4177. /// Find the instantiation of the given declaration within the
  4178. /// current instantiation.
  4179. ///
  4180. /// This routine is intended to be used when \p D is a declaration
  4181. /// referenced from within a template, that needs to mapped into the
  4182. /// corresponding declaration within an instantiation. For example,
  4183. /// given:
  4184. ///
  4185. /// \code
  4186. /// template<typename T>
  4187. /// struct X {
  4188. /// enum Kind {
  4189. /// KnownValue = sizeof(T)
  4190. /// };
  4191. ///
  4192. /// bool getKind() const { return KnownValue; }
  4193. /// };
  4194. ///
  4195. /// template struct X<int>;
  4196. /// \endcode
  4197. ///
  4198. /// In the instantiation of <tt>X<int>::getKind()</tt>, we need to map the
  4199. /// \p EnumConstantDecl for \p KnownValue (which refers to
  4200. /// <tt>X<T>::<Kind>::KnownValue</tt>) to its instantiation
  4201. /// (<tt>X<int>::<Kind>::KnownValue</tt>). \p FindInstantiatedDecl performs
  4202. /// this mapping from within the instantiation of <tt>X<int></tt>.
  4203. NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
  4204. const MultiLevelTemplateArgumentList &TemplateArgs,
  4205. bool FindingInstantiatedContext) {
  4206. DeclContext *ParentDC = D->getDeclContext();
  4207. // FIXME: Parmeters of pointer to functions (y below) that are themselves
  4208. // parameters (p below) can have their ParentDC set to the translation-unit
  4209. // - thus we can not consistently check if the ParentDC of such a parameter
  4210. // is Dependent or/and a FunctionOrMethod.
  4211. // For e.g. this code, during Template argument deduction tries to
  4212. // find an instantiated decl for (T y) when the ParentDC for y is
  4213. // the translation unit.
  4214. // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
  4215. // float baz(float(*)()) { return 0.0; }
  4216. // Foo(baz);
  4217. // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
  4218. // it gets here, always has a FunctionOrMethod as its ParentDC??
  4219. // For now:
  4220. // - as long as we have a ParmVarDecl whose parent is non-dependent and
  4221. // whose type is not instantiation dependent, do nothing to the decl
  4222. // - otherwise find its instantiated decl.
  4223. if (isa<ParmVarDecl>(D) && !ParentDC->isDependentContext() &&
  4224. !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
  4225. return D;
  4226. if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
  4227. isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
  4228. ((ParentDC->isFunctionOrMethod() ||
  4229. isa<OMPDeclareReductionDecl>(ParentDC)) &&
  4230. ParentDC->isDependentContext()) ||
  4231. (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
  4232. // D is a local of some kind. Look into the map of local
  4233. // declarations to their instantiations.
  4234. if (CurrentInstantiationScope) {
  4235. if (auto Found = CurrentInstantiationScope->findInstantiationOf(D)) {
  4236. if (Decl *FD = Found->dyn_cast<Decl *>())
  4237. return cast<NamedDecl>(FD);
  4238. int PackIdx = ArgumentPackSubstitutionIndex;
  4239. assert(PackIdx != -1 &&
  4240. "found declaration pack but not pack expanding");
  4241. typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
  4242. return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
  4243. }
  4244. }
  4245. // If we're performing a partial substitution during template argument
  4246. // deduction, we may not have values for template parameters yet. They
  4247. // just map to themselves.
  4248. if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
  4249. isa<TemplateTemplateParmDecl>(D))
  4250. return D;
  4251. if (D->isInvalidDecl())
  4252. return nullptr;
  4253. // Normally this function only searches for already instantiated declaration
  4254. // however we have to make an exclusion for local types used before
  4255. // definition as in the code:
  4256. //
  4257. // template<typename T> void f1() {
  4258. // void g1(struct x1);
  4259. // struct x1 {};
  4260. // }
  4261. //
  4262. // In this case instantiation of the type of 'g1' requires definition of
  4263. // 'x1', which is defined later. Error recovery may produce an enum used
  4264. // before definition. In these cases we need to instantiate relevant
  4265. // declarations here.
  4266. bool NeedInstantiate = false;
  4267. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
  4268. NeedInstantiate = RD->isLocalClass();
  4269. else
  4270. NeedInstantiate = isa<EnumDecl>(D);
  4271. if (NeedInstantiate) {
  4272. Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
  4273. CurrentInstantiationScope->InstantiatedLocal(D, Inst);
  4274. return cast<TypeDecl>(Inst);
  4275. }
  4276. // If we didn't find the decl, then we must have a label decl that hasn't
  4277. // been found yet. Lazily instantiate it and return it now.
  4278. assert(isa<LabelDecl>(D));
  4279. Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
  4280. assert(Inst && "Failed to instantiate label??");
  4281. CurrentInstantiationScope->InstantiatedLocal(D, Inst);
  4282. return cast<LabelDecl>(Inst);
  4283. }
  4284. // For variable template specializations, update those that are still
  4285. // type-dependent.
  4286. if (VarTemplateSpecializationDecl *VarSpec =
  4287. dyn_cast<VarTemplateSpecializationDecl>(D)) {
  4288. bool InstantiationDependent = false;
  4289. const TemplateArgumentListInfo &VarTemplateArgs =
  4290. VarSpec->getTemplateArgsInfo();
  4291. if (TemplateSpecializationType::anyDependentTemplateArguments(
  4292. VarTemplateArgs, InstantiationDependent))
  4293. D = cast<NamedDecl>(
  4294. SubstDecl(D, VarSpec->getDeclContext(), TemplateArgs));
  4295. return D;
  4296. }
  4297. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
  4298. if (!Record->isDependentContext())
  4299. return D;
  4300. // Determine whether this record is the "templated" declaration describing
  4301. // a class template or class template partial specialization.
  4302. ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
  4303. if (ClassTemplate)
  4304. ClassTemplate = ClassTemplate->getCanonicalDecl();
  4305. else if (ClassTemplatePartialSpecializationDecl *PartialSpec
  4306. = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
  4307. ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
  4308. // Walk the current context to find either the record or an instantiation of
  4309. // it.
  4310. DeclContext *DC = CurContext;
  4311. while (!DC->isFileContext()) {
  4312. // If we're performing substitution while we're inside the template
  4313. // definition, we'll find our own context. We're done.
  4314. if (DC->Equals(Record))
  4315. return Record;
  4316. if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
  4317. // Check whether we're in the process of instantiating a class template
  4318. // specialization of the template we're mapping.
  4319. if (ClassTemplateSpecializationDecl *InstSpec
  4320. = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
  4321. ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
  4322. if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
  4323. return InstRecord;
  4324. }
  4325. // Check whether we're in the process of instantiating a member class.
  4326. if (isInstantiationOf(Record, InstRecord))
  4327. return InstRecord;
  4328. }
  4329. // Move to the outer template scope.
  4330. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
  4331. if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
  4332. DC = FD->getLexicalDeclContext();
  4333. continue;
  4334. }
  4335. // An implicit deduction guide acts as if it's within the class template
  4336. // specialization described by its name and first N template params.
  4337. auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FD);
  4338. if (Guide && Guide->isImplicit()) {
  4339. TemplateDecl *TD = Guide->getDeducedTemplate();
  4340. // Convert the arguments to an "as-written" list.
  4341. TemplateArgumentListInfo Args(Loc, Loc);
  4342. for (TemplateArgument Arg : TemplateArgs.getInnermost().take_front(
  4343. TD->getTemplateParameters()->size())) {
  4344. ArrayRef<TemplateArgument> Unpacked(Arg);
  4345. if (Arg.getKind() == TemplateArgument::Pack)
  4346. Unpacked = Arg.pack_elements();
  4347. for (TemplateArgument UnpackedArg : Unpacked)
  4348. Args.addArgument(
  4349. getTrivialTemplateArgumentLoc(UnpackedArg, QualType(), Loc));
  4350. }
  4351. QualType T = CheckTemplateIdType(TemplateName(TD), Loc, Args);
  4352. if (T.isNull())
  4353. return nullptr;
  4354. auto *SubstRecord = T->getAsCXXRecordDecl();
  4355. assert(SubstRecord && "class template id not a class type?");
  4356. // Check that this template-id names the primary template and not a
  4357. // partial or explicit specialization. (In the latter cases, it's
  4358. // meaningless to attempt to find an instantiation of D within the
  4359. // specialization.)
  4360. // FIXME: The standard doesn't say what should happen here.
  4361. if (FindingInstantiatedContext &&
  4362. usesPartialOrExplicitSpecialization(
  4363. Loc, cast<ClassTemplateSpecializationDecl>(SubstRecord))) {
  4364. Diag(Loc, diag::err_specialization_not_primary_template)
  4365. << T << (SubstRecord->getTemplateSpecializationKind() ==
  4366. TSK_ExplicitSpecialization);
  4367. return nullptr;
  4368. }
  4369. DC = SubstRecord;
  4370. continue;
  4371. }
  4372. }
  4373. DC = DC->getParent();
  4374. }
  4375. // Fall through to deal with other dependent record types (e.g.,
  4376. // anonymous unions in class templates).
  4377. }
  4378. if (!ParentDC->isDependentContext())
  4379. return D;
  4380. ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
  4381. if (!ParentDC)
  4382. return nullptr;
  4383. if (ParentDC != D->getDeclContext()) {
  4384. // We performed some kind of instantiation in the parent context,
  4385. // so now we need to look into the instantiated parent context to
  4386. // find the instantiation of the declaration D.
  4387. // If our context used to be dependent, we may need to instantiate
  4388. // it before performing lookup into that context.
  4389. bool IsBeingInstantiated = false;
  4390. if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
  4391. if (!Spec->isDependentContext()) {
  4392. QualType T = Context.getTypeDeclType(Spec);
  4393. const RecordType *Tag = T->getAs<RecordType>();
  4394. assert(Tag && "type of non-dependent record is not a RecordType");
  4395. if (Tag->isBeingDefined())
  4396. IsBeingInstantiated = true;
  4397. if (!Tag->isBeingDefined() &&
  4398. RequireCompleteType(Loc, T, diag::err_incomplete_type))
  4399. return nullptr;
  4400. ParentDC = Tag->getDecl();
  4401. }
  4402. }
  4403. NamedDecl *Result = nullptr;
  4404. // FIXME: If the name is a dependent name, this lookup won't necessarily
  4405. // find it. Does that ever matter?
  4406. if (auto Name = D->getDeclName()) {
  4407. DeclarationNameInfo NameInfo(Name, D->getLocation());
  4408. Name = SubstDeclarationNameInfo(NameInfo, TemplateArgs).getName();
  4409. if (!Name)
  4410. return nullptr;
  4411. DeclContext::lookup_result Found = ParentDC->lookup(Name);
  4412. Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
  4413. } else {
  4414. // Since we don't have a name for the entity we're looking for,
  4415. // our only option is to walk through all of the declarations to
  4416. // find that name. This will occur in a few cases:
  4417. //
  4418. // - anonymous struct/union within a template
  4419. // - unnamed class/struct/union/enum within a template
  4420. //
  4421. // FIXME: Find a better way to find these instantiations!
  4422. Result = findInstantiationOf(Context, D,
  4423. ParentDC->decls_begin(),
  4424. ParentDC->decls_end());
  4425. }
  4426. if (!Result) {
  4427. if (isa<UsingShadowDecl>(D)) {
  4428. // UsingShadowDecls can instantiate to nothing because of using hiding.
  4429. } else if (Diags.hasErrorOccurred()) {
  4430. // We've already complained about something, so most likely this
  4431. // declaration failed to instantiate. There's no point in complaining
  4432. // further, since this is normal in invalid code.
  4433. } else if (IsBeingInstantiated) {
  4434. // The class in which this member exists is currently being
  4435. // instantiated, and we haven't gotten around to instantiating this
  4436. // member yet. This can happen when the code uses forward declarations
  4437. // of member classes, and introduces ordering dependencies via
  4438. // template instantiation.
  4439. Diag(Loc, diag::err_member_not_yet_instantiated)
  4440. << D->getDeclName()
  4441. << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
  4442. Diag(D->getLocation(), diag::note_non_instantiated_member_here);
  4443. } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
  4444. // This enumeration constant was found when the template was defined,
  4445. // but can't be found in the instantiation. This can happen if an
  4446. // unscoped enumeration member is explicitly specialized.
  4447. EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
  4448. EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
  4449. TemplateArgs));
  4450. assert(Spec->getTemplateSpecializationKind() ==
  4451. TSK_ExplicitSpecialization);
  4452. Diag(Loc, diag::err_enumerator_does_not_exist)
  4453. << D->getDeclName()
  4454. << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
  4455. Diag(Spec->getLocation(), diag::note_enum_specialized_here)
  4456. << Context.getTypeDeclType(Spec);
  4457. } else {
  4458. // We should have found something, but didn't.
  4459. llvm_unreachable("Unable to find instantiation of declaration!");
  4460. }
  4461. }
  4462. D = Result;
  4463. }
  4464. return D;
  4465. }
  4466. /// Performs template instantiation for all implicit template
  4467. /// instantiations we have seen until this point.
  4468. void Sema::PerformPendingInstantiations(bool LocalOnly) {
  4469. while (!PendingLocalImplicitInstantiations.empty() ||
  4470. (!LocalOnly && !PendingInstantiations.empty())) {
  4471. PendingImplicitInstantiation Inst;
  4472. if (PendingLocalImplicitInstantiations.empty()) {
  4473. Inst = PendingInstantiations.front();
  4474. PendingInstantiations.pop_front();
  4475. } else {
  4476. Inst = PendingLocalImplicitInstantiations.front();
  4477. PendingLocalImplicitInstantiations.pop_front();
  4478. }
  4479. // Instantiate function definitions
  4480. if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
  4481. bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
  4482. TSK_ExplicitInstantiationDefinition;
  4483. if (Function->isMultiVersion()) {
  4484. getASTContext().forEachMultiversionedFunctionVersion(
  4485. Function, [this, Inst, DefinitionRequired](FunctionDecl *CurFD) {
  4486. InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, CurFD, true,
  4487. DefinitionRequired, true);
  4488. if (CurFD->isDefined())
  4489. CurFD->setInstantiationIsPending(false);
  4490. });
  4491. } else {
  4492. InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, Function, true,
  4493. DefinitionRequired, true);
  4494. if (Function->isDefined())
  4495. Function->setInstantiationIsPending(false);
  4496. }
  4497. continue;
  4498. }
  4499. // Instantiate variable definitions
  4500. VarDecl *Var = cast<VarDecl>(Inst.first);
  4501. assert((Var->isStaticDataMember() ||
  4502. isa<VarTemplateSpecializationDecl>(Var)) &&
  4503. "Not a static data member, nor a variable template"
  4504. " specialization?");
  4505. // Don't try to instantiate declarations if the most recent redeclaration
  4506. // is invalid.
  4507. if (Var->getMostRecentDecl()->isInvalidDecl())
  4508. continue;
  4509. // Check if the most recent declaration has changed the specialization kind
  4510. // and removed the need for implicit instantiation.
  4511. switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) {
  4512. case TSK_Undeclared:
  4513. llvm_unreachable("Cannot instantitiate an undeclared specialization.");
  4514. case TSK_ExplicitInstantiationDeclaration:
  4515. case TSK_ExplicitSpecialization:
  4516. continue; // No longer need to instantiate this type.
  4517. case TSK_ExplicitInstantiationDefinition:
  4518. // We only need an instantiation if the pending instantiation *is* the
  4519. // explicit instantiation.
  4520. if (Var != Var->getMostRecentDecl())
  4521. continue;
  4522. break;
  4523. case TSK_ImplicitInstantiation:
  4524. break;
  4525. }
  4526. PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
  4527. "instantiating variable definition");
  4528. bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
  4529. TSK_ExplicitInstantiationDefinition;
  4530. // Instantiate static data member definitions or variable template
  4531. // specializations.
  4532. InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
  4533. DefinitionRequired, true);
  4534. }
  4535. }
  4536. void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
  4537. const MultiLevelTemplateArgumentList &TemplateArgs) {
  4538. for (auto DD : Pattern->ddiags()) {
  4539. switch (DD->getKind()) {
  4540. case DependentDiagnostic::Access:
  4541. HandleDependentAccessCheck(*DD, TemplateArgs);
  4542. break;
  4543. }
  4544. }
  4545. }