SemaTemplateInstantiateDecl.cpp 129 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385
  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/Sema/Lookup.h"
  14. #include "clang/Sema/PrettyDeclStackTrace.h"
  15. #include "clang/Sema/Template.h"
  16. #include "clang/AST/ASTConsumer.h"
  17. #include "clang/AST/ASTContext.h"
  18. #include "clang/AST/DeclTemplate.h"
  19. #include "clang/AST/DeclVisitor.h"
  20. #include "clang/AST/DependentDiagnostic.h"
  21. #include "clang/AST/Expr.h"
  22. #include "clang/AST/ExprCXX.h"
  23. #include "clang/AST/TypeLoc.h"
  24. #include "clang/Lex/Preprocessor.h"
  25. using namespace clang;
  26. bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
  27. DeclaratorDecl *NewDecl) {
  28. if (!OldDecl->getQualifierLoc())
  29. return false;
  30. NestedNameSpecifierLoc NewQualifierLoc
  31. = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
  32. TemplateArgs);
  33. if (!NewQualifierLoc)
  34. return true;
  35. NewDecl->setQualifierInfo(NewQualifierLoc);
  36. return false;
  37. }
  38. bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
  39. TagDecl *NewDecl) {
  40. if (!OldDecl->getQualifierLoc())
  41. return false;
  42. NestedNameSpecifierLoc NewQualifierLoc
  43. = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
  44. TemplateArgs);
  45. if (!NewQualifierLoc)
  46. return true;
  47. NewDecl->setQualifierInfo(NewQualifierLoc);
  48. return false;
  49. }
  50. // FIXME: Is this still too simple?
  51. void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
  52. const Decl *Tmpl, Decl *New) {
  53. for (AttrVec::const_iterator i = Tmpl->attr_begin(), e = Tmpl->attr_end();
  54. i != e; ++i) {
  55. const Attr *TmplAttr = *i;
  56. // FIXME: This should be generalized to more than just the AlignedAttr.
  57. if (const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr)) {
  58. if (Aligned->isAlignmentDependent()) {
  59. if (Aligned->isAlignmentExpr()) {
  60. // The alignment expression is a constant expression.
  61. EnterExpressionEvaluationContext Unevaluated(*this,
  62. Sema::ConstantEvaluated);
  63. ExprResult Result = SubstExpr(Aligned->getAlignmentExpr(),
  64. TemplateArgs);
  65. if (!Result.isInvalid())
  66. AddAlignedAttr(Aligned->getLocation(), New, Result.takeAs<Expr>());
  67. } else {
  68. TypeSourceInfo *Result = SubstType(Aligned->getAlignmentType(),
  69. TemplateArgs,
  70. Aligned->getLocation(),
  71. DeclarationName());
  72. if (Result)
  73. AddAlignedAttr(Aligned->getLocation(), New, Result);
  74. }
  75. continue;
  76. }
  77. }
  78. // FIXME: Is cloning correct for all attributes?
  79. Attr *NewAttr = TmplAttr->clone(Context);
  80. New->addAttr(NewAttr);
  81. }
  82. }
  83. Decl *
  84. TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
  85. llvm_unreachable("Translation units cannot be instantiated");
  86. }
  87. Decl *
  88. TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
  89. LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
  90. D->getIdentifier());
  91. Owner->addDecl(Inst);
  92. return Inst;
  93. }
  94. Decl *
  95. TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
  96. llvm_unreachable("Namespaces cannot be instantiated");
  97. }
  98. Decl *
  99. TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
  100. NamespaceAliasDecl *Inst
  101. = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
  102. D->getNamespaceLoc(),
  103. D->getAliasLoc(),
  104. D->getIdentifier(),
  105. D->getQualifierLoc(),
  106. D->getTargetNameLoc(),
  107. D->getNamespace());
  108. Owner->addDecl(Inst);
  109. return Inst;
  110. }
  111. Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
  112. bool IsTypeAlias) {
  113. bool Invalid = false;
  114. TypeSourceInfo *DI = D->getTypeSourceInfo();
  115. if (DI->getType()->isInstantiationDependentType() ||
  116. DI->getType()->isVariablyModifiedType()) {
  117. DI = SemaRef.SubstType(DI, TemplateArgs,
  118. D->getLocation(), D->getDeclName());
  119. if (!DI) {
  120. Invalid = true;
  121. DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
  122. }
  123. } else {
  124. SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
  125. }
  126. // Create the new typedef
  127. TypedefNameDecl *Typedef;
  128. if (IsTypeAlias)
  129. Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
  130. D->getLocation(), D->getIdentifier(), DI);
  131. else
  132. Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
  133. D->getLocation(), D->getIdentifier(), DI);
  134. if (Invalid)
  135. Typedef->setInvalidDecl();
  136. // If the old typedef was the name for linkage purposes of an anonymous
  137. // tag decl, re-establish that relationship for the new typedef.
  138. if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
  139. TagDecl *oldTag = oldTagType->getDecl();
  140. if (oldTag->getTypedefNameForAnonDecl() == D) {
  141. TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
  142. assert(!newTag->getIdentifier() && !newTag->getTypedefNameForAnonDecl());
  143. newTag->setTypedefNameForAnonDecl(Typedef);
  144. }
  145. }
  146. if (TypedefNameDecl *Prev = D->getPreviousDecl()) {
  147. NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
  148. TemplateArgs);
  149. if (!InstPrev)
  150. return 0;
  151. TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
  152. // If the typedef types are not identical, reject them.
  153. SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
  154. Typedef->setPreviousDeclaration(InstPrevTypedef);
  155. }
  156. SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
  157. Typedef->setAccess(D->getAccess());
  158. return Typedef;
  159. }
  160. Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
  161. Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
  162. Owner->addDecl(Typedef);
  163. return Typedef;
  164. }
  165. Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
  166. Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
  167. Owner->addDecl(Typedef);
  168. return Typedef;
  169. }
  170. Decl *
  171. TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
  172. // Create a local instantiation scope for this type alias template, which
  173. // will contain the instantiations of the template parameters.
  174. LocalInstantiationScope Scope(SemaRef);
  175. TemplateParameterList *TempParams = D->getTemplateParameters();
  176. TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
  177. if (!InstParams)
  178. return 0;
  179. TypeAliasDecl *Pattern = D->getTemplatedDecl();
  180. TypeAliasTemplateDecl *PrevAliasTemplate = 0;
  181. if (Pattern->getPreviousDecl()) {
  182. DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
  183. if (Found.first != Found.second) {
  184. PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(*Found.first);
  185. }
  186. }
  187. TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
  188. InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
  189. if (!AliasInst)
  190. return 0;
  191. TypeAliasTemplateDecl *Inst
  192. = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
  193. D->getDeclName(), InstParams, AliasInst);
  194. if (PrevAliasTemplate)
  195. Inst->setPreviousDeclaration(PrevAliasTemplate);
  196. Inst->setAccess(D->getAccess());
  197. if (!PrevAliasTemplate)
  198. Inst->setInstantiatedFromMemberTemplate(D);
  199. Owner->addDecl(Inst);
  200. return Inst;
  201. }
  202. /// \brief Instantiate an initializer, breaking it into separate
  203. /// initialization arguments.
  204. ///
  205. /// \param Init The initializer to instantiate.
  206. ///
  207. /// \param TemplateArgs Template arguments to be substituted into the
  208. /// initializer.
  209. ///
  210. /// \param NewArgs Will be filled in with the instantiation arguments.
  211. ///
  212. /// \returns true if an error occurred, false otherwise
  213. bool Sema::InstantiateInitializer(Expr *Init,
  214. const MultiLevelTemplateArgumentList &TemplateArgs,
  215. SourceLocation &LParenLoc,
  216. ASTOwningVector<Expr*> &NewArgs,
  217. SourceLocation &RParenLoc) {
  218. NewArgs.clear();
  219. LParenLoc = SourceLocation();
  220. RParenLoc = SourceLocation();
  221. if (!Init)
  222. return false;
  223. if (ExprWithCleanups *ExprTemp = dyn_cast<ExprWithCleanups>(Init))
  224. Init = ExprTemp->getSubExpr();
  225. while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
  226. Init = Binder->getSubExpr();
  227. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
  228. Init = ICE->getSubExprAsWritten();
  229. if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
  230. LParenLoc = ParenList->getLParenLoc();
  231. RParenLoc = ParenList->getRParenLoc();
  232. return SubstExprs(ParenList->getExprs(), ParenList->getNumExprs(),
  233. true, TemplateArgs, NewArgs);
  234. }
  235. if (CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init)) {
  236. if (!isa<CXXTemporaryObjectExpr>(Construct)) {
  237. if (SubstExprs(Construct->getArgs(), Construct->getNumArgs(), true,
  238. TemplateArgs, NewArgs))
  239. return true;
  240. // FIXME: Fake locations!
  241. LParenLoc = PP.getLocForEndOfToken(Init->getLocStart());
  242. RParenLoc = LParenLoc;
  243. return false;
  244. }
  245. }
  246. ExprResult Result = SubstExpr(Init, TemplateArgs);
  247. if (Result.isInvalid())
  248. return true;
  249. NewArgs.push_back(Result.takeAs<Expr>());
  250. return false;
  251. }
  252. Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
  253. // If this is the variable for an anonymous struct or union,
  254. // instantiate the anonymous struct/union type first.
  255. if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
  256. if (RecordTy->getDecl()->isAnonymousStructOrUnion())
  257. if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
  258. return 0;
  259. // Do substitution on the type of the declaration
  260. TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
  261. TemplateArgs,
  262. D->getTypeSpecStartLoc(),
  263. D->getDeclName());
  264. if (!DI)
  265. return 0;
  266. if (DI->getType()->isFunctionType()) {
  267. SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
  268. << D->isStaticDataMember() << DI->getType();
  269. return 0;
  270. }
  271. // Build the instantiated declaration
  272. VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
  273. D->getInnerLocStart(),
  274. D->getLocation(), D->getIdentifier(),
  275. DI->getType(), DI,
  276. D->getStorageClass(),
  277. D->getStorageClassAsWritten());
  278. Var->setThreadSpecified(D->isThreadSpecified());
  279. Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
  280. Var->setCXXForRangeDecl(D->isCXXForRangeDecl());
  281. Var->setConstexpr(D->isConstexpr());
  282. // Substitute the nested name specifier, if any.
  283. if (SubstQualifier(D, Var))
  284. return 0;
  285. // If we are instantiating a static data member defined
  286. // out-of-line, the instantiation will have the same lexical
  287. // context (which will be a namespace scope) as the template.
  288. if (D->isOutOfLine())
  289. Var->setLexicalDeclContext(D->getLexicalDeclContext());
  290. Var->setAccess(D->getAccess());
  291. if (!D->isStaticDataMember()) {
  292. Var->setUsed(D->isUsed(false));
  293. Var->setReferenced(D->isReferenced());
  294. }
  295. // FIXME: In theory, we could have a previous declaration for variables that
  296. // are not static data members.
  297. // FIXME: having to fake up a LookupResult is dumb.
  298. LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
  299. Sema::LookupOrdinaryName, Sema::ForRedeclaration);
  300. if (D->isStaticDataMember())
  301. SemaRef.LookupQualifiedName(Previous, Owner, false);
  302. // In ARC, infer 'retaining' for variables of retainable type.
  303. if (SemaRef.getLangOptions().ObjCAutoRefCount &&
  304. SemaRef.inferObjCARCLifetime(Var))
  305. Var->setInvalidDecl();
  306. SemaRef.CheckVariableDeclaration(Var, Previous);
  307. if (D->isOutOfLine()) {
  308. D->getLexicalDeclContext()->addDecl(Var);
  309. Owner->makeDeclVisibleInContext(Var);
  310. } else {
  311. Owner->addDecl(Var);
  312. if (Owner->isFunctionOrMethod())
  313. SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Var);
  314. }
  315. SemaRef.InstantiateAttrs(TemplateArgs, D, Var);
  316. // Link instantiations of static data members back to the template from
  317. // which they were instantiated.
  318. if (Var->isStaticDataMember())
  319. SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
  320. TSK_ImplicitInstantiation);
  321. if (Var->getAnyInitializer()) {
  322. // We already have an initializer in the class.
  323. } else if (D->getInit()) {
  324. if (Var->isStaticDataMember() && !D->isOutOfLine())
  325. SemaRef.PushExpressionEvaluationContext(Sema::ConstantEvaluated);
  326. else
  327. SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
  328. // Instantiate the initializer.
  329. SourceLocation LParenLoc, RParenLoc;
  330. ASTOwningVector<Expr*> InitArgs(SemaRef);
  331. if (!SemaRef.InstantiateInitializer(D->getInit(), TemplateArgs, LParenLoc,
  332. InitArgs, RParenLoc)) {
  333. bool TypeMayContainAuto = true;
  334. if (D->hasCXXDirectInitializer()) {
  335. // Add the direct initializer to the declaration.
  336. SemaRef.AddCXXDirectInitializerToDecl(Var,
  337. LParenLoc,
  338. move_arg(InitArgs),
  339. RParenLoc,
  340. TypeMayContainAuto);
  341. } else if (InitArgs.size() == 0) {
  342. SemaRef.ActOnUninitializedDecl(Var, TypeMayContainAuto);
  343. } else {
  344. assert(InitArgs.size() == 1);
  345. Expr *Init = InitArgs.take()[0];
  346. SemaRef.AddInitializerToDecl(Var, Init, false, TypeMayContainAuto);
  347. }
  348. } else {
  349. // FIXME: Not too happy about invalidating the declaration
  350. // because of a bogus initializer.
  351. Var->setInvalidDecl();
  352. }
  353. SemaRef.PopExpressionEvaluationContext();
  354. } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) &&
  355. !Var->isCXXForRangeDecl())
  356. SemaRef.ActOnUninitializedDecl(Var, false);
  357. // Diagnose unused local variables with dependent types, where the diagnostic
  358. // will have been deferred.
  359. if (!Var->isInvalidDecl() && Owner->isFunctionOrMethod() && !Var->isUsed() &&
  360. D->getType()->isDependentType())
  361. SemaRef.DiagnoseUnusedDecl(Var);
  362. return Var;
  363. }
  364. Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
  365. AccessSpecDecl* AD
  366. = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
  367. D->getAccessSpecifierLoc(), D->getColonLoc());
  368. Owner->addHiddenDecl(AD);
  369. return AD;
  370. }
  371. Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
  372. bool Invalid = false;
  373. TypeSourceInfo *DI = D->getTypeSourceInfo();
  374. if (DI->getType()->isInstantiationDependentType() ||
  375. DI->getType()->isVariablyModifiedType()) {
  376. DI = SemaRef.SubstType(DI, TemplateArgs,
  377. D->getLocation(), D->getDeclName());
  378. if (!DI) {
  379. DI = D->getTypeSourceInfo();
  380. Invalid = true;
  381. } else if (DI->getType()->isFunctionType()) {
  382. // C++ [temp.arg.type]p3:
  383. // If a declaration acquires a function type through a type
  384. // dependent on a template-parameter and this causes a
  385. // declaration that does not use the syntactic form of a
  386. // function declarator to have function type, the program is
  387. // ill-formed.
  388. SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
  389. << DI->getType();
  390. Invalid = true;
  391. }
  392. } else {
  393. SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
  394. }
  395. Expr *BitWidth = D->getBitWidth();
  396. if (Invalid)
  397. BitWidth = 0;
  398. else if (BitWidth) {
  399. // The bit-width expression is a constant expression.
  400. EnterExpressionEvaluationContext Unevaluated(SemaRef,
  401. Sema::ConstantEvaluated);
  402. ExprResult InstantiatedBitWidth
  403. = SemaRef.SubstExpr(BitWidth, TemplateArgs);
  404. if (InstantiatedBitWidth.isInvalid()) {
  405. Invalid = true;
  406. BitWidth = 0;
  407. } else
  408. BitWidth = InstantiatedBitWidth.takeAs<Expr>();
  409. }
  410. FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
  411. DI->getType(), DI,
  412. cast<RecordDecl>(Owner),
  413. D->getLocation(),
  414. D->isMutable(),
  415. BitWidth,
  416. D->hasInClassInitializer(),
  417. D->getTypeSpecStartLoc(),
  418. D->getAccess(),
  419. 0);
  420. if (!Field) {
  421. cast<Decl>(Owner)->setInvalidDecl();
  422. return 0;
  423. }
  424. SemaRef.InstantiateAttrs(TemplateArgs, D, Field);
  425. if (Invalid)
  426. Field->setInvalidDecl();
  427. if (!Field->getDeclName()) {
  428. // Keep track of where this decl came from.
  429. SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
  430. }
  431. if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
  432. if (Parent->isAnonymousStructOrUnion() &&
  433. Parent->getRedeclContext()->isFunctionOrMethod())
  434. SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
  435. }
  436. Field->setImplicit(D->isImplicit());
  437. Field->setAccess(D->getAccess());
  438. Owner->addDecl(Field);
  439. return Field;
  440. }
  441. Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
  442. NamedDecl **NamedChain =
  443. new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
  444. int i = 0;
  445. for (IndirectFieldDecl::chain_iterator PI =
  446. D->chain_begin(), PE = D->chain_end();
  447. PI != PE; ++PI) {
  448. NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), *PI,
  449. TemplateArgs);
  450. if (!Next)
  451. return 0;
  452. NamedChain[i++] = Next;
  453. }
  454. QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
  455. IndirectFieldDecl* IndirectField
  456. = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(),
  457. D->getIdentifier(), T,
  458. NamedChain, D->getChainingSize());
  459. IndirectField->setImplicit(D->isImplicit());
  460. IndirectField->setAccess(D->getAccess());
  461. Owner->addDecl(IndirectField);
  462. return IndirectField;
  463. }
  464. Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
  465. // Handle friend type expressions by simply substituting template
  466. // parameters into the pattern type and checking the result.
  467. if (TypeSourceInfo *Ty = D->getFriendType()) {
  468. TypeSourceInfo *InstTy;
  469. // If this is an unsupported friend, don't bother substituting template
  470. // arguments into it. The actual type referred to won't be used by any
  471. // parts of Clang, and may not be valid for instantiating. Just use the
  472. // same info for the instantiated friend.
  473. if (D->isUnsupportedFriend()) {
  474. InstTy = Ty;
  475. } else {
  476. InstTy = SemaRef.SubstType(Ty, TemplateArgs,
  477. D->getLocation(), DeclarationName());
  478. }
  479. if (!InstTy)
  480. return 0;
  481. FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getLocation(),
  482. D->getFriendLoc(), InstTy);
  483. if (!FD)
  484. return 0;
  485. FD->setAccess(AS_public);
  486. FD->setUnsupportedFriend(D->isUnsupportedFriend());
  487. Owner->addDecl(FD);
  488. return FD;
  489. }
  490. NamedDecl *ND = D->getFriendDecl();
  491. assert(ND && "friend decl must be a decl or a type!");
  492. // All of the Visit implementations for the various potential friend
  493. // declarations have to be carefully written to work for friend
  494. // objects, with the most important detail being that the target
  495. // decl should almost certainly not be placed in Owner.
  496. Decl *NewND = Visit(ND);
  497. if (!NewND) return 0;
  498. FriendDecl *FD =
  499. FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
  500. cast<NamedDecl>(NewND), D->getFriendLoc());
  501. FD->setAccess(AS_public);
  502. FD->setUnsupportedFriend(D->isUnsupportedFriend());
  503. Owner->addDecl(FD);
  504. return FD;
  505. }
  506. Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
  507. Expr *AssertExpr = D->getAssertExpr();
  508. // The expression in a static assertion is a constant expression.
  509. EnterExpressionEvaluationContext Unevaluated(SemaRef,
  510. Sema::ConstantEvaluated);
  511. ExprResult InstantiatedAssertExpr
  512. = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
  513. if (InstantiatedAssertExpr.isInvalid())
  514. return 0;
  515. ExprResult Message(D->getMessage());
  516. D->getMessage();
  517. return SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
  518. InstantiatedAssertExpr.get(),
  519. Message.get(),
  520. D->getRParenLoc());
  521. }
  522. Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
  523. EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
  524. D->getLocation(), D->getIdentifier(),
  525. /*PrevDecl=*/0, D->isScoped(),
  526. D->isScopedUsingClassTag(), D->isFixed());
  527. if (D->isFixed()) {
  528. if (TypeSourceInfo* TI = D->getIntegerTypeSourceInfo()) {
  529. // If we have type source information for the underlying type, it means it
  530. // has been explicitly set by the user. Perform substitution on it before
  531. // moving on.
  532. SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
  533. Enum->setIntegerTypeSourceInfo(SemaRef.SubstType(TI,
  534. TemplateArgs,
  535. UnderlyingLoc,
  536. DeclarationName()));
  537. if (!Enum->getIntegerTypeSourceInfo())
  538. Enum->setIntegerType(SemaRef.Context.IntTy);
  539. }
  540. else {
  541. assert(!D->getIntegerType()->isDependentType()
  542. && "Dependent type without type source info");
  543. Enum->setIntegerType(D->getIntegerType());
  544. }
  545. }
  546. SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
  547. Enum->setInstantiationOfMemberEnum(D);
  548. Enum->setAccess(D->getAccess());
  549. if (SubstQualifier(D, Enum)) return 0;
  550. Owner->addDecl(Enum);
  551. Enum->startDefinition();
  552. if (D->getDeclContext()->isFunctionOrMethod())
  553. SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
  554. SmallVector<Decl*, 4> Enumerators;
  555. EnumConstantDecl *LastEnumConst = 0;
  556. for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
  557. ECEnd = D->enumerator_end();
  558. EC != ECEnd; ++EC) {
  559. // The specified value for the enumerator.
  560. ExprResult Value = SemaRef.Owned((Expr *)0);
  561. if (Expr *UninstValue = EC->getInitExpr()) {
  562. // The enumerator's value expression is a constant expression.
  563. EnterExpressionEvaluationContext Unevaluated(SemaRef,
  564. Sema::ConstantEvaluated);
  565. Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
  566. }
  567. // Drop the initial value and continue.
  568. bool isInvalid = false;
  569. if (Value.isInvalid()) {
  570. Value = SemaRef.Owned((Expr *)0);
  571. isInvalid = true;
  572. }
  573. EnumConstantDecl *EnumConst
  574. = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
  575. EC->getLocation(), EC->getIdentifier(),
  576. Value.get());
  577. if (isInvalid) {
  578. if (EnumConst)
  579. EnumConst->setInvalidDecl();
  580. Enum->setInvalidDecl();
  581. }
  582. if (EnumConst) {
  583. SemaRef.InstantiateAttrs(TemplateArgs, *EC, EnumConst);
  584. EnumConst->setAccess(Enum->getAccess());
  585. Enum->addDecl(EnumConst);
  586. Enumerators.push_back(EnumConst);
  587. LastEnumConst = EnumConst;
  588. if (D->getDeclContext()->isFunctionOrMethod()) {
  589. // If the enumeration is within a function or method, record the enum
  590. // constant as a local.
  591. SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
  592. }
  593. }
  594. }
  595. // FIXME: Fixup LBraceLoc and RBraceLoc
  596. // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
  597. SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
  598. Enum,
  599. Enumerators.data(), Enumerators.size(),
  600. 0, 0);
  601. return Enum;
  602. }
  603. Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
  604. llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
  605. }
  606. Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
  607. bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
  608. // Create a local instantiation scope for this class template, which
  609. // will contain the instantiations of the template parameters.
  610. LocalInstantiationScope Scope(SemaRef);
  611. TemplateParameterList *TempParams = D->getTemplateParameters();
  612. TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
  613. if (!InstParams)
  614. return NULL;
  615. CXXRecordDecl *Pattern = D->getTemplatedDecl();
  616. // Instantiate the qualifier. We have to do this first in case
  617. // we're a friend declaration, because if we are then we need to put
  618. // the new declaration in the appropriate context.
  619. NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
  620. if (QualifierLoc) {
  621. QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
  622. TemplateArgs);
  623. if (!QualifierLoc)
  624. return 0;
  625. }
  626. CXXRecordDecl *PrevDecl = 0;
  627. ClassTemplateDecl *PrevClassTemplate = 0;
  628. if (!isFriend && Pattern->getPreviousDecl()) {
  629. DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
  630. if (Found.first != Found.second) {
  631. PrevClassTemplate = dyn_cast<ClassTemplateDecl>(*Found.first);
  632. if (PrevClassTemplate)
  633. PrevDecl = PrevClassTemplate->getTemplatedDecl();
  634. }
  635. }
  636. // If this isn't a friend, then it's a member template, in which
  637. // case we just want to build the instantiation in the
  638. // specialization. If it is a friend, we want to build it in
  639. // the appropriate context.
  640. DeclContext *DC = Owner;
  641. if (isFriend) {
  642. if (QualifierLoc) {
  643. CXXScopeSpec SS;
  644. SS.Adopt(QualifierLoc);
  645. DC = SemaRef.computeDeclContext(SS);
  646. if (!DC) return 0;
  647. } else {
  648. DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
  649. Pattern->getDeclContext(),
  650. TemplateArgs);
  651. }
  652. // Look for a previous declaration of the template in the owning
  653. // context.
  654. LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
  655. Sema::LookupOrdinaryName, Sema::ForRedeclaration);
  656. SemaRef.LookupQualifiedName(R, DC);
  657. if (R.isSingleResult()) {
  658. PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
  659. if (PrevClassTemplate)
  660. PrevDecl = PrevClassTemplate->getTemplatedDecl();
  661. }
  662. if (!PrevClassTemplate && QualifierLoc) {
  663. SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
  664. << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
  665. << QualifierLoc.getSourceRange();
  666. return 0;
  667. }
  668. bool AdoptedPreviousTemplateParams = false;
  669. if (PrevClassTemplate) {
  670. bool Complain = true;
  671. // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
  672. // template for struct std::tr1::__detail::_Map_base, where the
  673. // template parameters of the friend declaration don't match the
  674. // template parameters of the original declaration. In this one
  675. // case, we don't complain about the ill-formed friend
  676. // declaration.
  677. if (isFriend && Pattern->getIdentifier() &&
  678. Pattern->getIdentifier()->isStr("_Map_base") &&
  679. DC->isNamespace() &&
  680. cast<NamespaceDecl>(DC)->getIdentifier() &&
  681. cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
  682. DeclContext *DCParent = DC->getParent();
  683. if (DCParent->isNamespace() &&
  684. cast<NamespaceDecl>(DCParent)->getIdentifier() &&
  685. cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
  686. DeclContext *DCParent2 = DCParent->getParent();
  687. if (DCParent2->isNamespace() &&
  688. cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
  689. cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
  690. DCParent2->getParent()->isTranslationUnit())
  691. Complain = false;
  692. }
  693. }
  694. TemplateParameterList *PrevParams
  695. = PrevClassTemplate->getTemplateParameters();
  696. // Make sure the parameter lists match.
  697. if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
  698. Complain,
  699. Sema::TPL_TemplateMatch)) {
  700. if (Complain)
  701. return 0;
  702. AdoptedPreviousTemplateParams = true;
  703. InstParams = PrevParams;
  704. }
  705. // Do some additional validation, then merge default arguments
  706. // from the existing declarations.
  707. if (!AdoptedPreviousTemplateParams &&
  708. SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
  709. Sema::TPC_ClassTemplate))
  710. return 0;
  711. }
  712. }
  713. CXXRecordDecl *RecordInst
  714. = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
  715. Pattern->getLocStart(), Pattern->getLocation(),
  716. Pattern->getIdentifier(), PrevDecl,
  717. /*DelayTypeCreation=*/true);
  718. if (QualifierLoc)
  719. RecordInst->setQualifierInfo(QualifierLoc);
  720. ClassTemplateDecl *Inst
  721. = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
  722. D->getIdentifier(), InstParams, RecordInst,
  723. PrevClassTemplate);
  724. RecordInst->setDescribedClassTemplate(Inst);
  725. if (isFriend) {
  726. if (PrevClassTemplate)
  727. Inst->setAccess(PrevClassTemplate->getAccess());
  728. else
  729. Inst->setAccess(D->getAccess());
  730. Inst->setObjectOfFriendDecl(PrevClassTemplate != 0);
  731. // TODO: do we want to track the instantiation progeny of this
  732. // friend target decl?
  733. } else {
  734. Inst->setAccess(D->getAccess());
  735. if (!PrevClassTemplate)
  736. Inst->setInstantiatedFromMemberTemplate(D);
  737. }
  738. // Trigger creation of the type for the instantiation.
  739. SemaRef.Context.getInjectedClassNameType(RecordInst,
  740. Inst->getInjectedClassNameSpecialization());
  741. // Finish handling of friends.
  742. if (isFriend) {
  743. DC->makeDeclVisibleInContext(Inst, /*Recoverable*/ false);
  744. Inst->setLexicalDeclContext(Owner);
  745. RecordInst->setLexicalDeclContext(Owner);
  746. return Inst;
  747. }
  748. if (D->isOutOfLine()) {
  749. Inst->setLexicalDeclContext(D->getLexicalDeclContext());
  750. RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
  751. }
  752. Owner->addDecl(Inst);
  753. if (!PrevClassTemplate) {
  754. // Queue up any out-of-line partial specializations of this member
  755. // class template; the client will force their instantiation once
  756. // the enclosing class has been instantiated.
  757. SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
  758. D->getPartialSpecializations(PartialSpecs);
  759. for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
  760. if (PartialSpecs[I]->isOutOfLine())
  761. OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
  762. }
  763. return Inst;
  764. }
  765. Decl *
  766. TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
  767. ClassTemplatePartialSpecializationDecl *D) {
  768. ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
  769. // Lookup the already-instantiated declaration in the instantiation
  770. // of the class template and return that.
  771. DeclContext::lookup_result Found
  772. = Owner->lookup(ClassTemplate->getDeclName());
  773. if (Found.first == Found.second)
  774. return 0;
  775. ClassTemplateDecl *InstClassTemplate
  776. = dyn_cast<ClassTemplateDecl>(*Found.first);
  777. if (!InstClassTemplate)
  778. return 0;
  779. if (ClassTemplatePartialSpecializationDecl *Result
  780. = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
  781. return Result;
  782. return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
  783. }
  784. Decl *
  785. TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
  786. // Create a local instantiation scope for this function template, which
  787. // will contain the instantiations of the template parameters and then get
  788. // merged with the local instantiation scope for the function template
  789. // itself.
  790. LocalInstantiationScope Scope(SemaRef);
  791. TemplateParameterList *TempParams = D->getTemplateParameters();
  792. TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
  793. if (!InstParams)
  794. return NULL;
  795. FunctionDecl *Instantiated = 0;
  796. if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
  797. Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
  798. InstParams));
  799. else
  800. Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
  801. D->getTemplatedDecl(),
  802. InstParams));
  803. if (!Instantiated)
  804. return 0;
  805. Instantiated->setAccess(D->getAccess());
  806. // Link the instantiated function template declaration to the function
  807. // template from which it was instantiated.
  808. FunctionTemplateDecl *InstTemplate
  809. = Instantiated->getDescribedFunctionTemplate();
  810. InstTemplate->setAccess(D->getAccess());
  811. assert(InstTemplate &&
  812. "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
  813. bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
  814. // Link the instantiation back to the pattern *unless* this is a
  815. // non-definition friend declaration.
  816. if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
  817. !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
  818. InstTemplate->setInstantiatedFromMemberTemplate(D);
  819. // Make declarations visible in the appropriate context.
  820. if (!isFriend)
  821. Owner->addDecl(InstTemplate);
  822. return InstTemplate;
  823. }
  824. Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
  825. CXXRecordDecl *PrevDecl = 0;
  826. if (D->isInjectedClassName())
  827. PrevDecl = cast<CXXRecordDecl>(Owner);
  828. else if (D->getPreviousDecl()) {
  829. NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
  830. D->getPreviousDecl(),
  831. TemplateArgs);
  832. if (!Prev) return 0;
  833. PrevDecl = cast<CXXRecordDecl>(Prev);
  834. }
  835. CXXRecordDecl *Record
  836. = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
  837. D->getLocStart(), D->getLocation(),
  838. D->getIdentifier(), PrevDecl);
  839. // Substitute the nested name specifier, if any.
  840. if (SubstQualifier(D, Record))
  841. return 0;
  842. Record->setImplicit(D->isImplicit());
  843. // FIXME: Check against AS_none is an ugly hack to work around the issue that
  844. // the tag decls introduced by friend class declarations don't have an access
  845. // specifier. Remove once this area of the code gets sorted out.
  846. if (D->getAccess() != AS_none)
  847. Record->setAccess(D->getAccess());
  848. if (!D->isInjectedClassName())
  849. Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
  850. // If the original function was part of a friend declaration,
  851. // inherit its namespace state.
  852. if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
  853. Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
  854. // Make sure that anonymous structs and unions are recorded.
  855. if (D->isAnonymousStructOrUnion()) {
  856. Record->setAnonymousStructOrUnion(true);
  857. if (Record->getDeclContext()->getRedeclContext()->isFunctionOrMethod())
  858. SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
  859. }
  860. Owner->addDecl(Record);
  861. return Record;
  862. }
  863. /// Normal class members are of more specific types and therefore
  864. /// don't make it here. This function serves two purposes:
  865. /// 1) instantiating function templates
  866. /// 2) substituting friend declarations
  867. /// FIXME: preserve function definitions in case #2
  868. Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
  869. TemplateParameterList *TemplateParams) {
  870. // Check whether there is already a function template specialization for
  871. // this declaration.
  872. FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
  873. void *InsertPos = 0;
  874. if (FunctionTemplate && !TemplateParams) {
  875. std::pair<const TemplateArgument *, unsigned> Innermost
  876. = TemplateArgs.getInnermost();
  877. FunctionDecl *SpecFunc
  878. = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
  879. InsertPos);
  880. // If we already have a function template specialization, return it.
  881. if (SpecFunc)
  882. return SpecFunc;
  883. }
  884. bool isFriend;
  885. if (FunctionTemplate)
  886. isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
  887. else
  888. isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
  889. bool MergeWithParentScope = (TemplateParams != 0) ||
  890. Owner->isFunctionOrMethod() ||
  891. !(isa<Decl>(Owner) &&
  892. cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
  893. LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
  894. SmallVector<ParmVarDecl *, 4> Params;
  895. TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
  896. if (!TInfo)
  897. return 0;
  898. QualType T = TInfo->getType();
  899. NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
  900. if (QualifierLoc) {
  901. QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
  902. TemplateArgs);
  903. if (!QualifierLoc)
  904. return 0;
  905. }
  906. // If we're instantiating a local function declaration, put the result
  907. // in the owner; otherwise we need to find the instantiated context.
  908. DeclContext *DC;
  909. if (D->getDeclContext()->isFunctionOrMethod())
  910. DC = Owner;
  911. else if (isFriend && QualifierLoc) {
  912. CXXScopeSpec SS;
  913. SS.Adopt(QualifierLoc);
  914. DC = SemaRef.computeDeclContext(SS);
  915. if (!DC) return 0;
  916. } else {
  917. DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
  918. TemplateArgs);
  919. }
  920. FunctionDecl *Function =
  921. FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
  922. D->getLocation(), D->getDeclName(), T, TInfo,
  923. D->getStorageClass(), D->getStorageClassAsWritten(),
  924. D->isInlineSpecified(), D->hasWrittenPrototype(),
  925. /*isConstexpr*/ false);
  926. if (QualifierLoc)
  927. Function->setQualifierInfo(QualifierLoc);
  928. DeclContext *LexicalDC = Owner;
  929. if (!isFriend && D->isOutOfLine()) {
  930. assert(D->getDeclContext()->isFileContext());
  931. LexicalDC = D->getDeclContext();
  932. }
  933. Function->setLexicalDeclContext(LexicalDC);
  934. // Attach the parameters
  935. if (isa<FunctionProtoType>(Function->getType().IgnoreParens())) {
  936. // Adopt the already-instantiated parameters into our own context.
  937. for (unsigned P = 0; P < Params.size(); ++P)
  938. if (Params[P])
  939. Params[P]->setOwningFunction(Function);
  940. } else {
  941. // Since we were instantiated via a typedef of a function type, create
  942. // new parameters.
  943. const FunctionProtoType *Proto
  944. = Function->getType()->getAs<FunctionProtoType>();
  945. assert(Proto && "No function prototype in template instantiation?");
  946. for (FunctionProtoType::arg_type_iterator AI = Proto->arg_type_begin(),
  947. AE = Proto->arg_type_end(); AI != AE; ++AI) {
  948. ParmVarDecl *Param
  949. = SemaRef.BuildParmVarDeclForTypedef(Function, Function->getLocation(),
  950. *AI);
  951. Param->setScopeInfo(0, Params.size());
  952. Params.push_back(Param);
  953. }
  954. }
  955. Function->setParams(Params);
  956. SourceLocation InstantiateAtPOI;
  957. if (TemplateParams) {
  958. // Our resulting instantiation is actually a function template, since we
  959. // are substituting only the outer template parameters. For example, given
  960. //
  961. // template<typename T>
  962. // struct X {
  963. // template<typename U> friend void f(T, U);
  964. // };
  965. //
  966. // X<int> x;
  967. //
  968. // We are instantiating the friend function template "f" within X<int>,
  969. // which means substituting int for T, but leaving "f" as a friend function
  970. // template.
  971. // Build the function template itself.
  972. FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
  973. Function->getLocation(),
  974. Function->getDeclName(),
  975. TemplateParams, Function);
  976. Function->setDescribedFunctionTemplate(FunctionTemplate);
  977. FunctionTemplate->setLexicalDeclContext(LexicalDC);
  978. if (isFriend && D->isThisDeclarationADefinition()) {
  979. // TODO: should we remember this connection regardless of whether
  980. // the friend declaration provided a body?
  981. FunctionTemplate->setInstantiatedFromMemberTemplate(
  982. D->getDescribedFunctionTemplate());
  983. }
  984. } else if (FunctionTemplate) {
  985. // Record this function template specialization.
  986. std::pair<const TemplateArgument *, unsigned> Innermost
  987. = TemplateArgs.getInnermost();
  988. Function->setFunctionTemplateSpecialization(FunctionTemplate,
  989. TemplateArgumentList::CreateCopy(SemaRef.Context,
  990. Innermost.first,
  991. Innermost.second),
  992. InsertPos);
  993. } else if (isFriend) {
  994. // Note, we need this connection even if the friend doesn't have a body.
  995. // Its body may exist but not have been attached yet due to deferred
  996. // parsing.
  997. // FIXME: It might be cleaner to set this when attaching the body to the
  998. // friend function declaration, however that would require finding all the
  999. // instantiations and modifying them.
  1000. Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
  1001. }
  1002. if (InitFunctionInstantiation(Function, D))
  1003. Function->setInvalidDecl();
  1004. bool isExplicitSpecialization = false;
  1005. LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
  1006. Sema::LookupOrdinaryName, Sema::ForRedeclaration);
  1007. if (DependentFunctionTemplateSpecializationInfo *Info
  1008. = D->getDependentSpecializationInfo()) {
  1009. assert(isFriend && "non-friend has dependent specialization info?");
  1010. // This needs to be set now for future sanity.
  1011. Function->setObjectOfFriendDecl(/*HasPrevious*/ true);
  1012. // Instantiate the explicit template arguments.
  1013. TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
  1014. Info->getRAngleLoc());
  1015. if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
  1016. ExplicitArgs, TemplateArgs))
  1017. return 0;
  1018. // Map the candidate templates to their instantiations.
  1019. for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
  1020. Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
  1021. Info->getTemplate(I),
  1022. TemplateArgs);
  1023. if (!Temp) return 0;
  1024. Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
  1025. }
  1026. if (SemaRef.CheckFunctionTemplateSpecialization(Function,
  1027. &ExplicitArgs,
  1028. Previous))
  1029. Function->setInvalidDecl();
  1030. isExplicitSpecialization = true;
  1031. } else if (TemplateParams || !FunctionTemplate) {
  1032. // Look only into the namespace where the friend would be declared to
  1033. // find a previous declaration. This is the innermost enclosing namespace,
  1034. // as described in ActOnFriendFunctionDecl.
  1035. SemaRef.LookupQualifiedName(Previous, DC);
  1036. // In C++, the previous declaration we find might be a tag type
  1037. // (class or enum). In this case, the new declaration will hide the
  1038. // tag type. Note that this does does not apply if we're declaring a
  1039. // typedef (C++ [dcl.typedef]p4).
  1040. if (Previous.isSingleTagDecl())
  1041. Previous.clear();
  1042. }
  1043. SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
  1044. isExplicitSpecialization);
  1045. NamedDecl *PrincipalDecl = (TemplateParams
  1046. ? cast<NamedDecl>(FunctionTemplate)
  1047. : Function);
  1048. // If the original function was part of a friend declaration,
  1049. // inherit its namespace state and add it to the owner.
  1050. if (isFriend) {
  1051. NamedDecl *PrevDecl;
  1052. if (TemplateParams)
  1053. PrevDecl = FunctionTemplate->getPreviousDecl();
  1054. else
  1055. PrevDecl = Function->getPreviousDecl();
  1056. PrincipalDecl->setObjectOfFriendDecl(PrevDecl != 0);
  1057. DC->makeDeclVisibleInContext(PrincipalDecl, /*Recoverable=*/ false);
  1058. bool queuedInstantiation = false;
  1059. // C++98 [temp.friend]p5: When a function is defined in a friend function
  1060. // declaration in a class template, the function is defined at each
  1061. // instantiation of the class template. The function is defined even if it
  1062. // is never used.
  1063. // C++11 [temp.friend]p4: When a function is defined in a friend function
  1064. // declaration in a class template, the function is instantiated when the
  1065. // function is odr-used.
  1066. //
  1067. // If -Wc++98-compat is enabled, we go through the motions of checking for a
  1068. // redefinition, but don't instantiate the function.
  1069. if ((!SemaRef.getLangOptions().CPlusPlus0x ||
  1070. SemaRef.Diags.getDiagnosticLevel(
  1071. diag::warn_cxx98_compat_friend_redefinition,
  1072. Function->getLocation())
  1073. != DiagnosticsEngine::Ignored) &&
  1074. D->isThisDeclarationADefinition()) {
  1075. // Check for a function body.
  1076. const FunctionDecl *Definition = 0;
  1077. if (Function->isDefined(Definition) &&
  1078. Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
  1079. SemaRef.Diag(Function->getLocation(),
  1080. SemaRef.getLangOptions().CPlusPlus0x ?
  1081. diag::warn_cxx98_compat_friend_redefinition :
  1082. diag::err_redefinition) << Function->getDeclName();
  1083. SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
  1084. if (!SemaRef.getLangOptions().CPlusPlus0x)
  1085. Function->setInvalidDecl();
  1086. }
  1087. // Check for redefinitions due to other instantiations of this or
  1088. // a similar friend function.
  1089. else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(),
  1090. REnd = Function->redecls_end();
  1091. R != REnd; ++R) {
  1092. if (*R == Function)
  1093. continue;
  1094. switch (R->getFriendObjectKind()) {
  1095. case Decl::FOK_None:
  1096. if (!SemaRef.getLangOptions().CPlusPlus0x &&
  1097. !queuedInstantiation && R->isUsed(false)) {
  1098. if (MemberSpecializationInfo *MSInfo
  1099. = Function->getMemberSpecializationInfo()) {
  1100. if (MSInfo->getPointOfInstantiation().isInvalid()) {
  1101. SourceLocation Loc = R->getLocation(); // FIXME
  1102. MSInfo->setPointOfInstantiation(Loc);
  1103. SemaRef.PendingLocalImplicitInstantiations.push_back(
  1104. std::make_pair(Function, Loc));
  1105. queuedInstantiation = true;
  1106. }
  1107. }
  1108. }
  1109. break;
  1110. default:
  1111. if (const FunctionDecl *RPattern
  1112. = R->getTemplateInstantiationPattern())
  1113. if (RPattern->isDefined(RPattern)) {
  1114. SemaRef.Diag(Function->getLocation(),
  1115. SemaRef.getLangOptions().CPlusPlus0x ?
  1116. diag::warn_cxx98_compat_friend_redefinition :
  1117. diag::err_redefinition)
  1118. << Function->getDeclName();
  1119. SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
  1120. if (!SemaRef.getLangOptions().CPlusPlus0x)
  1121. Function->setInvalidDecl();
  1122. break;
  1123. }
  1124. }
  1125. }
  1126. }
  1127. }
  1128. if (Function->isOverloadedOperator() && !DC->isRecord() &&
  1129. PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
  1130. PrincipalDecl->setNonMemberOperator();
  1131. assert(!D->isDefaulted() && "only methods should be defaulted");
  1132. return Function;
  1133. }
  1134. Decl *
  1135. TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
  1136. TemplateParameterList *TemplateParams,
  1137. bool IsClassScopeSpecialization) {
  1138. FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
  1139. void *InsertPos = 0;
  1140. if (FunctionTemplate && !TemplateParams) {
  1141. // We are creating a function template specialization from a function
  1142. // template. Check whether there is already a function template
  1143. // specialization for this particular set of template arguments.
  1144. std::pair<const TemplateArgument *, unsigned> Innermost
  1145. = TemplateArgs.getInnermost();
  1146. FunctionDecl *SpecFunc
  1147. = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
  1148. InsertPos);
  1149. // If we already have a function template specialization, return it.
  1150. if (SpecFunc)
  1151. return SpecFunc;
  1152. }
  1153. bool isFriend;
  1154. if (FunctionTemplate)
  1155. isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
  1156. else
  1157. isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
  1158. bool MergeWithParentScope = (TemplateParams != 0) ||
  1159. !(isa<Decl>(Owner) &&
  1160. cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
  1161. LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
  1162. // Instantiate enclosing template arguments for friends.
  1163. SmallVector<TemplateParameterList *, 4> TempParamLists;
  1164. unsigned NumTempParamLists = 0;
  1165. if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
  1166. TempParamLists.set_size(NumTempParamLists);
  1167. for (unsigned I = 0; I != NumTempParamLists; ++I) {
  1168. TemplateParameterList *TempParams = D->getTemplateParameterList(I);
  1169. TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
  1170. if (!InstParams)
  1171. return NULL;
  1172. TempParamLists[I] = InstParams;
  1173. }
  1174. }
  1175. SmallVector<ParmVarDecl *, 4> Params;
  1176. TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
  1177. if (!TInfo)
  1178. return 0;
  1179. QualType T = TInfo->getType();
  1180. // \brief If the type of this function, after ignoring parentheses,
  1181. // is not *directly* a function type, then we're instantiating a function
  1182. // that was declared via a typedef, e.g.,
  1183. //
  1184. // typedef int functype(int, int);
  1185. // functype func;
  1186. //
  1187. // In this case, we'll just go instantiate the ParmVarDecls that we
  1188. // synthesized in the method declaration.
  1189. if (!isa<FunctionProtoType>(T.IgnoreParens())) {
  1190. assert(!Params.size() && "Instantiating type could not yield parameters");
  1191. SmallVector<QualType, 4> ParamTypes;
  1192. if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(),
  1193. D->getNumParams(), TemplateArgs, ParamTypes,
  1194. &Params))
  1195. return 0;
  1196. }
  1197. NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
  1198. if (QualifierLoc) {
  1199. QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
  1200. TemplateArgs);
  1201. if (!QualifierLoc)
  1202. return 0;
  1203. }
  1204. DeclContext *DC = Owner;
  1205. if (isFriend) {
  1206. if (QualifierLoc) {
  1207. CXXScopeSpec SS;
  1208. SS.Adopt(QualifierLoc);
  1209. DC = SemaRef.computeDeclContext(SS);
  1210. if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
  1211. return 0;
  1212. } else {
  1213. DC = SemaRef.FindInstantiatedContext(D->getLocation(),
  1214. D->getDeclContext(),
  1215. TemplateArgs);
  1216. }
  1217. if (!DC) return 0;
  1218. }
  1219. // Build the instantiated method declaration.
  1220. CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
  1221. CXXMethodDecl *Method = 0;
  1222. SourceLocation StartLoc = D->getInnerLocStart();
  1223. DeclarationNameInfo NameInfo
  1224. = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
  1225. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
  1226. Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
  1227. StartLoc, NameInfo, T, TInfo,
  1228. Constructor->isExplicit(),
  1229. Constructor->isInlineSpecified(),
  1230. false, /*isConstexpr*/ false);
  1231. } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
  1232. Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
  1233. StartLoc, NameInfo, T, TInfo,
  1234. Destructor->isInlineSpecified(),
  1235. false);
  1236. } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
  1237. Method = CXXConversionDecl::Create(SemaRef.Context, Record,
  1238. StartLoc, NameInfo, T, TInfo,
  1239. Conversion->isInlineSpecified(),
  1240. Conversion->isExplicit(),
  1241. /*isConstexpr*/ false,
  1242. Conversion->getLocEnd());
  1243. } else {
  1244. Method = CXXMethodDecl::Create(SemaRef.Context, Record,
  1245. StartLoc, NameInfo, T, TInfo,
  1246. D->isStatic(),
  1247. D->getStorageClassAsWritten(),
  1248. D->isInlineSpecified(),
  1249. /*isConstexpr*/ false, D->getLocEnd());
  1250. }
  1251. if (QualifierLoc)
  1252. Method->setQualifierInfo(QualifierLoc);
  1253. if (TemplateParams) {
  1254. // Our resulting instantiation is actually a function template, since we
  1255. // are substituting only the outer template parameters. For example, given
  1256. //
  1257. // template<typename T>
  1258. // struct X {
  1259. // template<typename U> void f(T, U);
  1260. // };
  1261. //
  1262. // X<int> x;
  1263. //
  1264. // We are instantiating the member template "f" within X<int>, which means
  1265. // substituting int for T, but leaving "f" as a member function template.
  1266. // Build the function template itself.
  1267. FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
  1268. Method->getLocation(),
  1269. Method->getDeclName(),
  1270. TemplateParams, Method);
  1271. if (isFriend) {
  1272. FunctionTemplate->setLexicalDeclContext(Owner);
  1273. FunctionTemplate->setObjectOfFriendDecl(true);
  1274. } else if (D->isOutOfLine())
  1275. FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
  1276. Method->setDescribedFunctionTemplate(FunctionTemplate);
  1277. } else if (FunctionTemplate) {
  1278. // Record this function template specialization.
  1279. std::pair<const TemplateArgument *, unsigned> Innermost
  1280. = TemplateArgs.getInnermost();
  1281. Method->setFunctionTemplateSpecialization(FunctionTemplate,
  1282. TemplateArgumentList::CreateCopy(SemaRef.Context,
  1283. Innermost.first,
  1284. Innermost.second),
  1285. InsertPos);
  1286. } else if (!isFriend) {
  1287. // Record that this is an instantiation of a member function.
  1288. Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
  1289. }
  1290. // If we are instantiating a member function defined
  1291. // out-of-line, the instantiation will have the same lexical
  1292. // context (which will be a namespace scope) as the template.
  1293. if (isFriend) {
  1294. if (NumTempParamLists)
  1295. Method->setTemplateParameterListsInfo(SemaRef.Context,
  1296. NumTempParamLists,
  1297. TempParamLists.data());
  1298. Method->setLexicalDeclContext(Owner);
  1299. Method->setObjectOfFriendDecl(true);
  1300. } else if (D->isOutOfLine())
  1301. Method->setLexicalDeclContext(D->getLexicalDeclContext());
  1302. // Attach the parameters
  1303. for (unsigned P = 0; P < Params.size(); ++P)
  1304. Params[P]->setOwningFunction(Method);
  1305. Method->setParams(Params);
  1306. if (InitMethodInstantiation(Method, D))
  1307. Method->setInvalidDecl();
  1308. LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
  1309. Sema::ForRedeclaration);
  1310. if (!FunctionTemplate || TemplateParams || isFriend) {
  1311. SemaRef.LookupQualifiedName(Previous, Record);
  1312. // In C++, the previous declaration we find might be a tag type
  1313. // (class or enum). In this case, the new declaration will hide the
  1314. // tag type. Note that this does does not apply if we're declaring a
  1315. // typedef (C++ [dcl.typedef]p4).
  1316. if (Previous.isSingleTagDecl())
  1317. Previous.clear();
  1318. }
  1319. if (!IsClassScopeSpecialization)
  1320. SemaRef.CheckFunctionDeclaration(0, Method, Previous, false);
  1321. if (D->isPure())
  1322. SemaRef.CheckPureMethod(Method, SourceRange());
  1323. Method->setAccess(D->getAccess());
  1324. SemaRef.CheckOverrideControl(Method);
  1325. // If a function is defined as defaulted or deleted, mark it as such now.
  1326. if (D->isDefaulted())
  1327. Method->setDefaulted();
  1328. if (D->isDeletedAsWritten())
  1329. Method->setDeletedAsWritten();
  1330. if (FunctionTemplate) {
  1331. // If there's a function template, let our caller handle it.
  1332. } else if (Method->isInvalidDecl() && !Previous.empty()) {
  1333. // Don't hide a (potentially) valid declaration with an invalid one.
  1334. } else {
  1335. NamedDecl *DeclToAdd = (TemplateParams
  1336. ? cast<NamedDecl>(FunctionTemplate)
  1337. : Method);
  1338. if (isFriend)
  1339. Record->makeDeclVisibleInContext(DeclToAdd);
  1340. else if (!IsClassScopeSpecialization)
  1341. Owner->addDecl(DeclToAdd);
  1342. }
  1343. if (D->isExplicitlyDefaulted()) {
  1344. SemaRef.SetDeclDefaulted(Method, Method->getLocation());
  1345. } else {
  1346. assert(!D->isDefaulted() &&
  1347. "should not implicitly default uninstantiated function");
  1348. }
  1349. return Method;
  1350. }
  1351. Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
  1352. return VisitCXXMethodDecl(D);
  1353. }
  1354. Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
  1355. return VisitCXXMethodDecl(D);
  1356. }
  1357. Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
  1358. return VisitCXXMethodDecl(D);
  1359. }
  1360. ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
  1361. return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0,
  1362. llvm::Optional<unsigned>());
  1363. }
  1364. Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
  1365. TemplateTypeParmDecl *D) {
  1366. // TODO: don't always clone when decls are refcounted.
  1367. assert(D->getTypeForDecl()->isTemplateTypeParmType());
  1368. TemplateTypeParmDecl *Inst =
  1369. TemplateTypeParmDecl::Create(SemaRef.Context, Owner,
  1370. D->getLocStart(), D->getLocation(),
  1371. D->getDepth() - TemplateArgs.getNumLevels(),
  1372. D->getIndex(), D->getIdentifier(),
  1373. D->wasDeclaredWithTypename(),
  1374. D->isParameterPack());
  1375. Inst->setAccess(AS_public);
  1376. if (D->hasDefaultArgument())
  1377. Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
  1378. // Introduce this template parameter's instantiation into the instantiation
  1379. // scope.
  1380. SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
  1381. return Inst;
  1382. }
  1383. Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
  1384. NonTypeTemplateParmDecl *D) {
  1385. // Substitute into the type of the non-type template parameter.
  1386. TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
  1387. SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
  1388. SmallVector<QualType, 4> ExpandedParameterPackTypes;
  1389. bool IsExpandedParameterPack = false;
  1390. TypeSourceInfo *DI;
  1391. QualType T;
  1392. bool Invalid = false;
  1393. if (D->isExpandedParameterPack()) {
  1394. // The non-type template parameter pack is an already-expanded pack
  1395. // expansion of types. Substitute into each of the expanded types.
  1396. ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
  1397. ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
  1398. for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
  1399. TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I),
  1400. TemplateArgs,
  1401. D->getLocation(),
  1402. D->getDeclName());
  1403. if (!NewDI)
  1404. return 0;
  1405. ExpandedParameterPackTypesAsWritten.push_back(NewDI);
  1406. QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
  1407. D->getLocation());
  1408. if (NewT.isNull())
  1409. return 0;
  1410. ExpandedParameterPackTypes.push_back(NewT);
  1411. }
  1412. IsExpandedParameterPack = true;
  1413. DI = D->getTypeSourceInfo();
  1414. T = DI->getType();
  1415. } else if (isa<PackExpansionTypeLoc>(TL)) {
  1416. // The non-type template parameter pack's type is a pack expansion of types.
  1417. // Determine whether we need to expand this parameter pack into separate
  1418. // types.
  1419. PackExpansionTypeLoc Expansion = cast<PackExpansionTypeLoc>(TL);
  1420. TypeLoc Pattern = Expansion.getPatternLoc();
  1421. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  1422. SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
  1423. // Determine whether the set of unexpanded parameter packs can and should
  1424. // be expanded.
  1425. bool Expand = true;
  1426. bool RetainExpansion = false;
  1427. llvm::Optional<unsigned> OrigNumExpansions
  1428. = Expansion.getTypePtr()->getNumExpansions();
  1429. llvm::Optional<unsigned> NumExpansions = OrigNumExpansions;
  1430. if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
  1431. Pattern.getSourceRange(),
  1432. Unexpanded,
  1433. TemplateArgs,
  1434. Expand, RetainExpansion,
  1435. NumExpansions))
  1436. return 0;
  1437. if (Expand) {
  1438. for (unsigned I = 0; I != *NumExpansions; ++I) {
  1439. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
  1440. TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
  1441. D->getLocation(),
  1442. D->getDeclName());
  1443. if (!NewDI)
  1444. return 0;
  1445. ExpandedParameterPackTypesAsWritten.push_back(NewDI);
  1446. QualType NewT = SemaRef.CheckNonTypeTemplateParameterType(
  1447. NewDI->getType(),
  1448. D->getLocation());
  1449. if (NewT.isNull())
  1450. return 0;
  1451. ExpandedParameterPackTypes.push_back(NewT);
  1452. }
  1453. // Note that we have an expanded parameter pack. The "type" of this
  1454. // expanded parameter pack is the original expansion type, but callers
  1455. // will end up using the expanded parameter pack types for type-checking.
  1456. IsExpandedParameterPack = true;
  1457. DI = D->getTypeSourceInfo();
  1458. T = DI->getType();
  1459. } else {
  1460. // We cannot fully expand the pack expansion now, so substitute into the
  1461. // pattern and create a new pack expansion type.
  1462. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
  1463. TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
  1464. D->getLocation(),
  1465. D->getDeclName());
  1466. if (!NewPattern)
  1467. return 0;
  1468. DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
  1469. NumExpansions);
  1470. if (!DI)
  1471. return 0;
  1472. T = DI->getType();
  1473. }
  1474. } else {
  1475. // Simple case: substitution into a parameter that is not a parameter pack.
  1476. DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
  1477. D->getLocation(), D->getDeclName());
  1478. if (!DI)
  1479. return 0;
  1480. // Check that this type is acceptable for a non-type template parameter.
  1481. T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
  1482. D->getLocation());
  1483. if (T.isNull()) {
  1484. T = SemaRef.Context.IntTy;
  1485. Invalid = true;
  1486. }
  1487. }
  1488. NonTypeTemplateParmDecl *Param;
  1489. if (IsExpandedParameterPack)
  1490. Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
  1491. D->getInnerLocStart(),
  1492. D->getLocation(),
  1493. D->getDepth() - TemplateArgs.getNumLevels(),
  1494. D->getPosition(),
  1495. D->getIdentifier(), T,
  1496. DI,
  1497. ExpandedParameterPackTypes.data(),
  1498. ExpandedParameterPackTypes.size(),
  1499. ExpandedParameterPackTypesAsWritten.data());
  1500. else
  1501. Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
  1502. D->getInnerLocStart(),
  1503. D->getLocation(),
  1504. D->getDepth() - TemplateArgs.getNumLevels(),
  1505. D->getPosition(),
  1506. D->getIdentifier(), T,
  1507. D->isParameterPack(), DI);
  1508. Param->setAccess(AS_public);
  1509. if (Invalid)
  1510. Param->setInvalidDecl();
  1511. Param->setDefaultArgument(D->getDefaultArgument(), false);
  1512. // Introduce this template parameter's instantiation into the instantiation
  1513. // scope.
  1514. SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
  1515. return Param;
  1516. }
  1517. Decl *
  1518. TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
  1519. TemplateTemplateParmDecl *D) {
  1520. // Instantiate the template parameter list of the template template parameter.
  1521. TemplateParameterList *TempParams = D->getTemplateParameters();
  1522. TemplateParameterList *InstParams;
  1523. {
  1524. // Perform the actual substitution of template parameters within a new,
  1525. // local instantiation scope.
  1526. LocalInstantiationScope Scope(SemaRef);
  1527. InstParams = SubstTemplateParams(TempParams);
  1528. if (!InstParams)
  1529. return NULL;
  1530. }
  1531. // Build the template template parameter.
  1532. TemplateTemplateParmDecl *Param
  1533. = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
  1534. D->getDepth() - TemplateArgs.getNumLevels(),
  1535. D->getPosition(), D->isParameterPack(),
  1536. D->getIdentifier(), InstParams);
  1537. Param->setDefaultArgument(D->getDefaultArgument(), false);
  1538. Param->setAccess(AS_public);
  1539. // Introduce this template parameter's instantiation into the instantiation
  1540. // scope.
  1541. SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
  1542. return Param;
  1543. }
  1544. Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
  1545. // Using directives are never dependent (and never contain any types or
  1546. // expressions), so they require no explicit instantiation work.
  1547. UsingDirectiveDecl *Inst
  1548. = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
  1549. D->getNamespaceKeyLocation(),
  1550. D->getQualifierLoc(),
  1551. D->getIdentLocation(),
  1552. D->getNominatedNamespace(),
  1553. D->getCommonAncestor());
  1554. Owner->addDecl(Inst);
  1555. return Inst;
  1556. }
  1557. Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
  1558. // The nested name specifier may be dependent, for example
  1559. // template <typename T> struct t {
  1560. // struct s1 { T f1(); };
  1561. // struct s2 : s1 { using s1::f1; };
  1562. // };
  1563. // template struct t<int>;
  1564. // Here, in using s1::f1, s1 refers to t<T>::s1;
  1565. // we need to substitute for t<int>::s1.
  1566. NestedNameSpecifierLoc QualifierLoc
  1567. = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
  1568. TemplateArgs);
  1569. if (!QualifierLoc)
  1570. return 0;
  1571. // The name info is non-dependent, so no transformation
  1572. // is required.
  1573. DeclarationNameInfo NameInfo = D->getNameInfo();
  1574. // We only need to do redeclaration lookups if we're in a class
  1575. // scope (in fact, it's not really even possible in non-class
  1576. // scopes).
  1577. bool CheckRedeclaration = Owner->isRecord();
  1578. LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
  1579. Sema::ForRedeclaration);
  1580. UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
  1581. D->getUsingLocation(),
  1582. QualifierLoc,
  1583. NameInfo,
  1584. D->isTypeName());
  1585. CXXScopeSpec SS;
  1586. SS.Adopt(QualifierLoc);
  1587. if (CheckRedeclaration) {
  1588. Prev.setHideTags(false);
  1589. SemaRef.LookupQualifiedName(Prev, Owner);
  1590. // Check for invalid redeclarations.
  1591. if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
  1592. D->isTypeName(), SS,
  1593. D->getLocation(), Prev))
  1594. NewUD->setInvalidDecl();
  1595. }
  1596. if (!NewUD->isInvalidDecl() &&
  1597. SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
  1598. D->getLocation()))
  1599. NewUD->setInvalidDecl();
  1600. SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
  1601. NewUD->setAccess(D->getAccess());
  1602. Owner->addDecl(NewUD);
  1603. // Don't process the shadow decls for an invalid decl.
  1604. if (NewUD->isInvalidDecl())
  1605. return NewUD;
  1606. bool isFunctionScope = Owner->isFunctionOrMethod();
  1607. // Process the shadow decls.
  1608. for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
  1609. I != E; ++I) {
  1610. UsingShadowDecl *Shadow = *I;
  1611. NamedDecl *InstTarget =
  1612. cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
  1613. Shadow->getLocation(),
  1614. Shadow->getTargetDecl(),
  1615. TemplateArgs));
  1616. if (!InstTarget)
  1617. return 0;
  1618. if (CheckRedeclaration &&
  1619. SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
  1620. continue;
  1621. UsingShadowDecl *InstShadow
  1622. = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
  1623. SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
  1624. if (isFunctionScope)
  1625. SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
  1626. }
  1627. return NewUD;
  1628. }
  1629. Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
  1630. // Ignore these; we handle them in bulk when processing the UsingDecl.
  1631. return 0;
  1632. }
  1633. Decl * TemplateDeclInstantiator
  1634. ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
  1635. NestedNameSpecifierLoc QualifierLoc
  1636. = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
  1637. TemplateArgs);
  1638. if (!QualifierLoc)
  1639. return 0;
  1640. CXXScopeSpec SS;
  1641. SS.Adopt(QualifierLoc);
  1642. // Since NameInfo refers to a typename, it cannot be a C++ special name.
  1643. // Hence, no tranformation is required for it.
  1644. DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
  1645. NamedDecl *UD =
  1646. SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
  1647. D->getUsingLoc(), SS, NameInfo, 0,
  1648. /*instantiation*/ true,
  1649. /*typename*/ true, D->getTypenameLoc());
  1650. if (UD)
  1651. SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
  1652. return UD;
  1653. }
  1654. Decl * TemplateDeclInstantiator
  1655. ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
  1656. NestedNameSpecifierLoc QualifierLoc
  1657. = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs);
  1658. if (!QualifierLoc)
  1659. return 0;
  1660. CXXScopeSpec SS;
  1661. SS.Adopt(QualifierLoc);
  1662. DeclarationNameInfo NameInfo
  1663. = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
  1664. NamedDecl *UD =
  1665. SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
  1666. D->getUsingLoc(), SS, NameInfo, 0,
  1667. /*instantiation*/ true,
  1668. /*typename*/ false, SourceLocation());
  1669. if (UD)
  1670. SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
  1671. return UD;
  1672. }
  1673. Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
  1674. ClassScopeFunctionSpecializationDecl *Decl) {
  1675. CXXMethodDecl *OldFD = Decl->getSpecialization();
  1676. CXXMethodDecl *NewFD = cast<CXXMethodDecl>(VisitCXXMethodDecl(OldFD, 0, true));
  1677. LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName,
  1678. Sema::ForRedeclaration);
  1679. SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext);
  1680. if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, 0, Previous)) {
  1681. NewFD->setInvalidDecl();
  1682. return NewFD;
  1683. }
  1684. // Associate the specialization with the pattern.
  1685. FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl());
  1686. assert(Specialization && "Class scope Specialization is null");
  1687. SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD);
  1688. return NewFD;
  1689. }
  1690. Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
  1691. const MultiLevelTemplateArgumentList &TemplateArgs) {
  1692. TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
  1693. if (D->isInvalidDecl())
  1694. return 0;
  1695. return Instantiator.Visit(D);
  1696. }
  1697. /// \brief Instantiates a nested template parameter list in the current
  1698. /// instantiation context.
  1699. ///
  1700. /// \param L The parameter list to instantiate
  1701. ///
  1702. /// \returns NULL if there was an error
  1703. TemplateParameterList *
  1704. TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
  1705. // Get errors for all the parameters before bailing out.
  1706. bool Invalid = false;
  1707. unsigned N = L->size();
  1708. typedef SmallVector<NamedDecl *, 8> ParamVector;
  1709. ParamVector Params;
  1710. Params.reserve(N);
  1711. for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
  1712. PI != PE; ++PI) {
  1713. NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
  1714. Params.push_back(D);
  1715. Invalid = Invalid || !D || D->isInvalidDecl();
  1716. }
  1717. // Clean up if we had an error.
  1718. if (Invalid)
  1719. return NULL;
  1720. TemplateParameterList *InstL
  1721. = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
  1722. L->getLAngleLoc(), &Params.front(), N,
  1723. L->getRAngleLoc());
  1724. return InstL;
  1725. }
  1726. /// \brief Instantiate the declaration of a class template partial
  1727. /// specialization.
  1728. ///
  1729. /// \param ClassTemplate the (instantiated) class template that is partially
  1730. // specialized by the instantiation of \p PartialSpec.
  1731. ///
  1732. /// \param PartialSpec the (uninstantiated) class template partial
  1733. /// specialization that we are instantiating.
  1734. ///
  1735. /// \returns The instantiated partial specialization, if successful; otherwise,
  1736. /// NULL to indicate an error.
  1737. ClassTemplatePartialSpecializationDecl *
  1738. TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
  1739. ClassTemplateDecl *ClassTemplate,
  1740. ClassTemplatePartialSpecializationDecl *PartialSpec) {
  1741. // Create a local instantiation scope for this class template partial
  1742. // specialization, which will contain the instantiations of the template
  1743. // parameters.
  1744. LocalInstantiationScope Scope(SemaRef);
  1745. // Substitute into the template parameters of the class template partial
  1746. // specialization.
  1747. TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
  1748. TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
  1749. if (!InstParams)
  1750. return 0;
  1751. // Substitute into the template arguments of the class template partial
  1752. // specialization.
  1753. TemplateArgumentListInfo InstTemplateArgs; // no angle locations
  1754. if (SemaRef.Subst(PartialSpec->getTemplateArgsAsWritten(),
  1755. PartialSpec->getNumTemplateArgsAsWritten(),
  1756. InstTemplateArgs, TemplateArgs))
  1757. return 0;
  1758. // Check that the template argument list is well-formed for this
  1759. // class template.
  1760. SmallVector<TemplateArgument, 4> Converted;
  1761. if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
  1762. PartialSpec->getLocation(),
  1763. InstTemplateArgs,
  1764. false,
  1765. Converted))
  1766. return 0;
  1767. // Figure out where to insert this class template partial specialization
  1768. // in the member template's set of class template partial specializations.
  1769. void *InsertPos = 0;
  1770. ClassTemplateSpecializationDecl *PrevDecl
  1771. = ClassTemplate->findPartialSpecialization(Converted.data(),
  1772. Converted.size(), InsertPos);
  1773. // Build the canonical type that describes the converted template
  1774. // arguments of the class template partial specialization.
  1775. QualType CanonType
  1776. = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
  1777. Converted.data(),
  1778. Converted.size());
  1779. // Build the fully-sugared type for this class template
  1780. // specialization as the user wrote in the specialization
  1781. // itself. This means that we'll pretty-print the type retrieved
  1782. // from the specialization's declaration the way that the user
  1783. // actually wrote the specialization, rather than formatting the
  1784. // name based on the "canonical" representation used to store the
  1785. // template arguments in the specialization.
  1786. TypeSourceInfo *WrittenTy
  1787. = SemaRef.Context.getTemplateSpecializationTypeInfo(
  1788. TemplateName(ClassTemplate),
  1789. PartialSpec->getLocation(),
  1790. InstTemplateArgs,
  1791. CanonType);
  1792. if (PrevDecl) {
  1793. // We've already seen a partial specialization with the same template
  1794. // parameters and template arguments. This can happen, for example, when
  1795. // substituting the outer template arguments ends up causing two
  1796. // class template partial specializations of a member class template
  1797. // to have identical forms, e.g.,
  1798. //
  1799. // template<typename T, typename U>
  1800. // struct Outer {
  1801. // template<typename X, typename Y> struct Inner;
  1802. // template<typename Y> struct Inner<T, Y>;
  1803. // template<typename Y> struct Inner<U, Y>;
  1804. // };
  1805. //
  1806. // Outer<int, int> outer; // error: the partial specializations of Inner
  1807. // // have the same signature.
  1808. SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
  1809. << WrittenTy->getType();
  1810. SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
  1811. << SemaRef.Context.getTypeDeclType(PrevDecl);
  1812. return 0;
  1813. }
  1814. // Create the class template partial specialization declaration.
  1815. ClassTemplatePartialSpecializationDecl *InstPartialSpec
  1816. = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
  1817. PartialSpec->getTagKind(),
  1818. Owner,
  1819. PartialSpec->getLocStart(),
  1820. PartialSpec->getLocation(),
  1821. InstParams,
  1822. ClassTemplate,
  1823. Converted.data(),
  1824. Converted.size(),
  1825. InstTemplateArgs,
  1826. CanonType,
  1827. 0,
  1828. ClassTemplate->getNextPartialSpecSequenceNumber());
  1829. // Substitute the nested name specifier, if any.
  1830. if (SubstQualifier(PartialSpec, InstPartialSpec))
  1831. return 0;
  1832. InstPartialSpec->setInstantiatedFromMember(PartialSpec);
  1833. InstPartialSpec->setTypeAsWritten(WrittenTy);
  1834. // Add this partial specialization to the set of class template partial
  1835. // specializations.
  1836. ClassTemplate->AddPartialSpecialization(InstPartialSpec, InsertPos);
  1837. return InstPartialSpec;
  1838. }
  1839. TypeSourceInfo*
  1840. TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
  1841. SmallVectorImpl<ParmVarDecl *> &Params) {
  1842. TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
  1843. assert(OldTInfo && "substituting function without type source info");
  1844. assert(Params.empty() && "parameter vector is non-empty at start");
  1845. TypeSourceInfo *NewTInfo
  1846. = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
  1847. D->getTypeSpecStartLoc(),
  1848. D->getDeclName());
  1849. if (!NewTInfo)
  1850. return 0;
  1851. if (NewTInfo != OldTInfo) {
  1852. // Get parameters from the new type info.
  1853. TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
  1854. if (FunctionProtoTypeLoc *OldProtoLoc
  1855. = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
  1856. TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
  1857. FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL);
  1858. assert(NewProtoLoc && "Missing prototype?");
  1859. unsigned NewIdx = 0, NumNewParams = NewProtoLoc->getNumArgs();
  1860. for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc->getNumArgs();
  1861. OldIdx != NumOldParams; ++OldIdx) {
  1862. ParmVarDecl *OldParam = OldProtoLoc->getArg(OldIdx);
  1863. if (!OldParam->isParameterPack() ||
  1864. (NewIdx < NumNewParams &&
  1865. NewProtoLoc->getArg(NewIdx)->isParameterPack())) {
  1866. // Simple case: normal parameter, or a parameter pack that's
  1867. // instantiated to a (still-dependent) parameter pack.
  1868. ParmVarDecl *NewParam = NewProtoLoc->getArg(NewIdx++);
  1869. Params.push_back(NewParam);
  1870. SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam,
  1871. NewParam);
  1872. continue;
  1873. }
  1874. // Parameter pack: make the instantiation an argument pack.
  1875. SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(
  1876. OldParam);
  1877. unsigned NumArgumentsInExpansion
  1878. = SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
  1879. TemplateArgs);
  1880. while (NumArgumentsInExpansion--) {
  1881. ParmVarDecl *NewParam = NewProtoLoc->getArg(NewIdx++);
  1882. Params.push_back(NewParam);
  1883. SemaRef.CurrentInstantiationScope->InstantiatedLocalPackArg(OldParam,
  1884. NewParam);
  1885. }
  1886. }
  1887. }
  1888. } else {
  1889. // The function type itself was not dependent and therefore no
  1890. // substitution occurred. However, we still need to instantiate
  1891. // the function parameters themselves.
  1892. TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
  1893. if (FunctionProtoTypeLoc *OldProtoLoc
  1894. = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
  1895. for (unsigned i = 0, i_end = OldProtoLoc->getNumArgs(); i != i_end; ++i) {
  1896. ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc->getArg(i));
  1897. if (!Parm)
  1898. return 0;
  1899. Params.push_back(Parm);
  1900. }
  1901. }
  1902. }
  1903. return NewTInfo;
  1904. }
  1905. /// \brief Initializes the common fields of an instantiation function
  1906. /// declaration (New) from the corresponding fields of its template (Tmpl).
  1907. ///
  1908. /// \returns true if there was an error
  1909. bool
  1910. TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
  1911. FunctionDecl *Tmpl) {
  1912. if (Tmpl->isDeletedAsWritten())
  1913. New->setDeletedAsWritten();
  1914. // If we are performing substituting explicitly-specified template arguments
  1915. // or deduced template arguments into a function template and we reach this
  1916. // point, we are now past the point where SFINAE applies and have committed
  1917. // to keeping the new function template specialization. We therefore
  1918. // convert the active template instantiation for the function template
  1919. // into a template instantiation for this specific function template
  1920. // specialization, which is not a SFINAE context, so that we diagnose any
  1921. // further errors in the declaration itself.
  1922. typedef Sema::ActiveTemplateInstantiation ActiveInstType;
  1923. ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
  1924. if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
  1925. ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
  1926. if (FunctionTemplateDecl *FunTmpl
  1927. = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
  1928. assert(FunTmpl->getTemplatedDecl() == Tmpl &&
  1929. "Deduction from the wrong function template?");
  1930. (void) FunTmpl;
  1931. ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
  1932. ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
  1933. --SemaRef.NonInstantiationEntries;
  1934. }
  1935. }
  1936. const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
  1937. assert(Proto && "Function template without prototype?");
  1938. if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
  1939. // The function has an exception specification or a "noreturn"
  1940. // attribute. Substitute into each of the exception types.
  1941. SmallVector<QualType, 4> Exceptions;
  1942. for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
  1943. // FIXME: Poor location information!
  1944. if (const PackExpansionType *PackExpansion
  1945. = Proto->getExceptionType(I)->getAs<PackExpansionType>()) {
  1946. // We have a pack expansion. Instantiate it.
  1947. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  1948. SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
  1949. Unexpanded);
  1950. assert(!Unexpanded.empty() &&
  1951. "Pack expansion without parameter packs?");
  1952. bool Expand = false;
  1953. bool RetainExpansion = false;
  1954. llvm::Optional<unsigned> NumExpansions
  1955. = PackExpansion->getNumExpansions();
  1956. if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(),
  1957. SourceRange(),
  1958. Unexpanded,
  1959. TemplateArgs,
  1960. Expand,
  1961. RetainExpansion,
  1962. NumExpansions))
  1963. break;
  1964. if (!Expand) {
  1965. // We can't expand this pack expansion into separate arguments yet;
  1966. // just substitute into the pattern and create a new pack expansion
  1967. // type.
  1968. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
  1969. QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
  1970. TemplateArgs,
  1971. New->getLocation(), New->getDeclName());
  1972. if (T.isNull())
  1973. break;
  1974. T = SemaRef.Context.getPackExpansionType(T, NumExpansions);
  1975. Exceptions.push_back(T);
  1976. continue;
  1977. }
  1978. // Substitute into the pack expansion pattern for each template
  1979. bool Invalid = false;
  1980. for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
  1981. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx);
  1982. QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
  1983. TemplateArgs,
  1984. New->getLocation(), New->getDeclName());
  1985. if (T.isNull()) {
  1986. Invalid = true;
  1987. break;
  1988. }
  1989. Exceptions.push_back(T);
  1990. }
  1991. if (Invalid)
  1992. break;
  1993. continue;
  1994. }
  1995. QualType T
  1996. = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
  1997. New->getLocation(), New->getDeclName());
  1998. if (T.isNull() ||
  1999. SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
  2000. continue;
  2001. Exceptions.push_back(T);
  2002. }
  2003. Expr *NoexceptExpr = 0;
  2004. if (Expr *OldNoexceptExpr = Proto->getNoexceptExpr()) {
  2005. EnterExpressionEvaluationContext Unevaluated(SemaRef,
  2006. Sema::ConstantEvaluated);
  2007. ExprResult E = SemaRef.SubstExpr(OldNoexceptExpr, TemplateArgs);
  2008. if (E.isUsable())
  2009. E = SemaRef.CheckBooleanCondition(E.get(), E.get()->getLocStart());
  2010. if (E.isUsable()) {
  2011. SourceLocation ErrLoc;
  2012. llvm::APSInt NoexceptVal;
  2013. NoexceptExpr = E.take();
  2014. if (!NoexceptExpr->isTypeDependent() &&
  2015. !NoexceptExpr->isValueDependent() &&
  2016. !NoexceptExpr->isIntegerConstantExpr(NoexceptVal, SemaRef.Context,
  2017. &ErrLoc, /*evaluated=*/false)){
  2018. SemaRef.Diag(ErrLoc, diag::err_noexcept_needs_constant_expression)
  2019. << NoexceptExpr->getSourceRange();
  2020. NoexceptExpr = 0;
  2021. }
  2022. }
  2023. }
  2024. // Rebuild the function type
  2025. FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
  2026. EPI.ExceptionSpecType = Proto->getExceptionSpecType();
  2027. EPI.NumExceptions = Exceptions.size();
  2028. EPI.Exceptions = Exceptions.data();
  2029. EPI.NoexceptExpr = NoexceptExpr;
  2030. EPI.ExtInfo = Proto->getExtInfo();
  2031. const FunctionProtoType *NewProto
  2032. = New->getType()->getAs<FunctionProtoType>();
  2033. assert(NewProto && "Template instantiation without function prototype?");
  2034. New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
  2035. NewProto->arg_type_begin(),
  2036. NewProto->getNumArgs(),
  2037. EPI));
  2038. }
  2039. // C++0x [dcl.constexpr]p6: If the instantiated template specialization of
  2040. // a constexpr function template satisfies the requirements for a constexpr
  2041. // function, then it is a constexpr function.
  2042. if (Tmpl->isConstexpr() &&
  2043. SemaRef.CheckConstexprFunctionDecl(New, Sema::CCK_Instantiation))
  2044. New->setConstexpr(true);
  2045. const FunctionDecl* Definition = Tmpl;
  2046. // Get the definition. Leaves the variable unchanged if undefined.
  2047. Tmpl->isDefined(Definition);
  2048. SemaRef.InstantiateAttrs(TemplateArgs, Definition, New);
  2049. return false;
  2050. }
  2051. /// \brief Initializes common fields of an instantiated method
  2052. /// declaration (New) from the corresponding fields of its template
  2053. /// (Tmpl).
  2054. ///
  2055. /// \returns true if there was an error
  2056. bool
  2057. TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
  2058. CXXMethodDecl *Tmpl) {
  2059. if (InitFunctionInstantiation(New, Tmpl))
  2060. return true;
  2061. New->setAccess(Tmpl->getAccess());
  2062. if (Tmpl->isVirtualAsWritten())
  2063. New->setVirtualAsWritten(true);
  2064. // FIXME: attributes
  2065. // FIXME: New needs a pointer to Tmpl
  2066. return false;
  2067. }
  2068. /// \brief Instantiate the definition of the given function from its
  2069. /// template.
  2070. ///
  2071. /// \param PointOfInstantiation the point at which the instantiation was
  2072. /// required. Note that this is not precisely a "point of instantiation"
  2073. /// for the function, but it's close.
  2074. ///
  2075. /// \param Function the already-instantiated declaration of a
  2076. /// function template specialization or member function of a class template
  2077. /// specialization.
  2078. ///
  2079. /// \param Recursive if true, recursively instantiates any functions that
  2080. /// are required by this instantiation.
  2081. ///
  2082. /// \param DefinitionRequired if true, then we are performing an explicit
  2083. /// instantiation where the body of the function is required. Complain if
  2084. /// there is no such body.
  2085. void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
  2086. FunctionDecl *Function,
  2087. bool Recursive,
  2088. bool DefinitionRequired) {
  2089. if (Function->isInvalidDecl() || Function->isDefined())
  2090. return;
  2091. // Never instantiate an explicit specialization except if it is a class scope
  2092. // explicit specialization.
  2093. if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
  2094. !Function->getClassScopeSpecializationPattern())
  2095. return;
  2096. // Find the function body that we'll be substituting.
  2097. const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
  2098. assert(PatternDecl && "instantiating a non-template");
  2099. Stmt *Pattern = PatternDecl->getBody(PatternDecl);
  2100. assert(PatternDecl && "template definition is not a template");
  2101. if (!Pattern) {
  2102. // Try to find a defaulted definition
  2103. PatternDecl->isDefined(PatternDecl);
  2104. }
  2105. assert(PatternDecl && "template definition is not a template");
  2106. // Postpone late parsed template instantiations.
  2107. if (PatternDecl->isLateTemplateParsed() &&
  2108. !LateTemplateParser) {
  2109. PendingInstantiations.push_back(
  2110. std::make_pair(Function, PointOfInstantiation));
  2111. return;
  2112. }
  2113. // Call the LateTemplateParser callback if there a need to late parse
  2114. // a templated function definition.
  2115. if (!Pattern && PatternDecl->isLateTemplateParsed() &&
  2116. LateTemplateParser) {
  2117. LateTemplateParser(OpaqueParser, PatternDecl);
  2118. Pattern = PatternDecl->getBody(PatternDecl);
  2119. }
  2120. if (!Pattern && !PatternDecl->isDefaulted()) {
  2121. if (DefinitionRequired) {
  2122. if (Function->getPrimaryTemplate())
  2123. Diag(PointOfInstantiation,
  2124. diag::err_explicit_instantiation_undefined_func_template)
  2125. << Function->getPrimaryTemplate();
  2126. else
  2127. Diag(PointOfInstantiation,
  2128. diag::err_explicit_instantiation_undefined_member)
  2129. << 1 << Function->getDeclName() << Function->getDeclContext();
  2130. if (PatternDecl)
  2131. Diag(PatternDecl->getLocation(),
  2132. diag::note_explicit_instantiation_here);
  2133. Function->setInvalidDecl();
  2134. } else if (Function->getTemplateSpecializationKind()
  2135. == TSK_ExplicitInstantiationDefinition) {
  2136. PendingInstantiations.push_back(
  2137. std::make_pair(Function, PointOfInstantiation));
  2138. }
  2139. return;
  2140. }
  2141. // C++0x [temp.explicit]p9:
  2142. // Except for inline functions, other explicit instantiation declarations
  2143. // have the effect of suppressing the implicit instantiation of the entity
  2144. // to which they refer.
  2145. if (Function->getTemplateSpecializationKind()
  2146. == TSK_ExplicitInstantiationDeclaration &&
  2147. !PatternDecl->isInlined())
  2148. return;
  2149. InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
  2150. if (Inst)
  2151. return;
  2152. // Copy the inner loc start from the pattern.
  2153. Function->setInnerLocStart(PatternDecl->getInnerLocStart());
  2154. // If we're performing recursive template instantiation, create our own
  2155. // queue of pending implicit instantiations that we will instantiate later,
  2156. // while we're still within our own instantiation context.
  2157. SmallVector<VTableUse, 16> SavedVTableUses;
  2158. std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
  2159. if (Recursive) {
  2160. VTableUses.swap(SavedVTableUses);
  2161. PendingInstantiations.swap(SavedPendingInstantiations);
  2162. }
  2163. EnterExpressionEvaluationContext EvalContext(*this,
  2164. Sema::PotentiallyEvaluated);
  2165. ActOnStartOfFunctionDef(0, Function);
  2166. // Introduce a new scope where local variable instantiations will be
  2167. // recorded, unless we're actually a member function within a local
  2168. // class, in which case we need to merge our results with the parent
  2169. // scope (of the enclosing function).
  2170. bool MergeWithParentScope = false;
  2171. if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
  2172. MergeWithParentScope = Rec->isLocalClass();
  2173. LocalInstantiationScope Scope(*this, MergeWithParentScope);
  2174. // Introduce the instantiated function parameters into the local
  2175. // instantiation scope, and set the parameter names to those used
  2176. // in the template.
  2177. unsigned FParamIdx = 0;
  2178. for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
  2179. const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
  2180. if (!PatternParam->isParameterPack()) {
  2181. // Simple case: not a parameter pack.
  2182. assert(FParamIdx < Function->getNumParams());
  2183. ParmVarDecl *FunctionParam = Function->getParamDecl(I);
  2184. FunctionParam->setDeclName(PatternParam->getDeclName());
  2185. Scope.InstantiatedLocal(PatternParam, FunctionParam);
  2186. ++FParamIdx;
  2187. continue;
  2188. }
  2189. // Expand the parameter pack.
  2190. Scope.MakeInstantiatedLocalArgPack(PatternParam);
  2191. for (unsigned NumFParams = Function->getNumParams();
  2192. FParamIdx < NumFParams;
  2193. ++FParamIdx) {
  2194. ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
  2195. FunctionParam->setDeclName(PatternParam->getDeclName());
  2196. Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
  2197. }
  2198. }
  2199. // Enter the scope of this instantiation. We don't use
  2200. // PushDeclContext because we don't have a scope.
  2201. Sema::ContextRAII savedContext(*this, Function);
  2202. MultiLevelTemplateArgumentList TemplateArgs =
  2203. getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
  2204. if (PatternDecl->isDefaulted()) {
  2205. ActOnFinishFunctionBody(Function, 0, /*IsInstantiation=*/true);
  2206. SetDeclDefaulted(Function, PatternDecl->getLocation());
  2207. } else {
  2208. // If this is a constructor, instantiate the member initializers.
  2209. if (const CXXConstructorDecl *Ctor =
  2210. dyn_cast<CXXConstructorDecl>(PatternDecl)) {
  2211. InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
  2212. TemplateArgs);
  2213. }
  2214. // Instantiate the function body.
  2215. StmtResult Body = SubstStmt(Pattern, TemplateArgs);
  2216. if (Body.isInvalid())
  2217. Function->setInvalidDecl();
  2218. ActOnFinishFunctionBody(Function, Body.get(),
  2219. /*IsInstantiation=*/true);
  2220. }
  2221. PerformDependentDiagnostics(PatternDecl, TemplateArgs);
  2222. savedContext.pop();
  2223. DeclGroupRef DG(Function);
  2224. Consumer.HandleTopLevelDecl(DG);
  2225. // This class may have local implicit instantiations that need to be
  2226. // instantiation within this scope.
  2227. PerformPendingInstantiations(/*LocalOnly=*/true);
  2228. Scope.Exit();
  2229. if (Recursive) {
  2230. // Define any pending vtables.
  2231. DefineUsedVTables();
  2232. // Instantiate any pending implicit instantiations found during the
  2233. // instantiation of this template.
  2234. PerformPendingInstantiations();
  2235. // Restore the set of pending vtables.
  2236. assert(VTableUses.empty() &&
  2237. "VTableUses should be empty before it is discarded.");
  2238. VTableUses.swap(SavedVTableUses);
  2239. // Restore the set of pending implicit instantiations.
  2240. assert(PendingInstantiations.empty() &&
  2241. "PendingInstantiations should be empty before it is discarded.");
  2242. PendingInstantiations.swap(SavedPendingInstantiations);
  2243. }
  2244. }
  2245. /// \brief Instantiate the definition of the given variable from its
  2246. /// template.
  2247. ///
  2248. /// \param PointOfInstantiation the point at which the instantiation was
  2249. /// required. Note that this is not precisely a "point of instantiation"
  2250. /// for the function, but it's close.
  2251. ///
  2252. /// \param Var the already-instantiated declaration of a static member
  2253. /// variable of a class template specialization.
  2254. ///
  2255. /// \param Recursive if true, recursively instantiates any functions that
  2256. /// are required by this instantiation.
  2257. ///
  2258. /// \param DefinitionRequired if true, then we are performing an explicit
  2259. /// instantiation where an out-of-line definition of the member variable
  2260. /// is required. Complain if there is no such definition.
  2261. void Sema::InstantiateStaticDataMemberDefinition(
  2262. SourceLocation PointOfInstantiation,
  2263. VarDecl *Var,
  2264. bool Recursive,
  2265. bool DefinitionRequired) {
  2266. if (Var->isInvalidDecl())
  2267. return;
  2268. // Find the out-of-line definition of this static data member.
  2269. VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
  2270. assert(Def && "This data member was not instantiated from a template?");
  2271. assert(Def->isStaticDataMember() && "Not a static data member?");
  2272. Def = Def->getOutOfLineDefinition();
  2273. if (!Def) {
  2274. // We did not find an out-of-line definition of this static data member,
  2275. // so we won't perform any instantiation. Rather, we rely on the user to
  2276. // instantiate this definition (or provide a specialization for it) in
  2277. // another translation unit.
  2278. if (DefinitionRequired) {
  2279. Def = Var->getInstantiatedFromStaticDataMember();
  2280. Diag(PointOfInstantiation,
  2281. diag::err_explicit_instantiation_undefined_member)
  2282. << 2 << Var->getDeclName() << Var->getDeclContext();
  2283. Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
  2284. } else if (Var->getTemplateSpecializationKind()
  2285. == TSK_ExplicitInstantiationDefinition) {
  2286. PendingInstantiations.push_back(
  2287. std::make_pair(Var, PointOfInstantiation));
  2288. }
  2289. return;
  2290. }
  2291. // Never instantiate an explicit specialization.
  2292. if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
  2293. return;
  2294. // C++0x [temp.explicit]p9:
  2295. // Except for inline functions, other explicit instantiation declarations
  2296. // have the effect of suppressing the implicit instantiation of the entity
  2297. // to which they refer.
  2298. if (Var->getTemplateSpecializationKind()
  2299. == TSK_ExplicitInstantiationDeclaration)
  2300. return;
  2301. // If we already have a definition, we're done.
  2302. if (Var->getDefinition())
  2303. return;
  2304. InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
  2305. if (Inst)
  2306. return;
  2307. // If we're performing recursive template instantiation, create our own
  2308. // queue of pending implicit instantiations that we will instantiate later,
  2309. // while we're still within our own instantiation context.
  2310. SmallVector<VTableUse, 16> SavedVTableUses;
  2311. std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
  2312. if (Recursive) {
  2313. VTableUses.swap(SavedVTableUses);
  2314. PendingInstantiations.swap(SavedPendingInstantiations);
  2315. }
  2316. // Enter the scope of this instantiation. We don't use
  2317. // PushDeclContext because we don't have a scope.
  2318. ContextRAII previousContext(*this, Var->getDeclContext());
  2319. VarDecl *OldVar = Var;
  2320. Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
  2321. getTemplateInstantiationArgs(Var)));
  2322. previousContext.pop();
  2323. if (Var) {
  2324. MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
  2325. assert(MSInfo && "Missing member specialization information?");
  2326. Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
  2327. MSInfo->getPointOfInstantiation());
  2328. DeclGroupRef DG(Var);
  2329. Consumer.HandleTopLevelDecl(DG);
  2330. }
  2331. if (Recursive) {
  2332. // Define any newly required vtables.
  2333. DefineUsedVTables();
  2334. // Instantiate any pending implicit instantiations found during the
  2335. // instantiation of this template.
  2336. PerformPendingInstantiations();
  2337. // Restore the set of pending vtables.
  2338. assert(VTableUses.empty() &&
  2339. "VTableUses should be empty before it is discarded, "
  2340. "while instantiating static data member.");
  2341. VTableUses.swap(SavedVTableUses);
  2342. // Restore the set of pending implicit instantiations.
  2343. assert(PendingInstantiations.empty() &&
  2344. "PendingInstantiations should be empty before it is discarded, "
  2345. "while instantiating static data member.");
  2346. PendingInstantiations.swap(SavedPendingInstantiations);
  2347. }
  2348. }
  2349. static MultiInitializer CreateMultiInitializer(SmallVectorImpl<Expr*> &Args,
  2350. const CXXCtorInitializer *Init) {
  2351. // FIXME: This is a hack that will do slightly the wrong thing for an
  2352. // initializer of the form foo({...}).
  2353. // The right thing to do would be to modify InstantiateInitializer to create
  2354. // the MultiInitializer.
  2355. if (Args.size() == 1 && isa<InitListExpr>(Args[0]))
  2356. return MultiInitializer(Args[0]);
  2357. return MultiInitializer(Init->getLParenLoc(), Args.data(),
  2358. Args.size(), Init->getRParenLoc());
  2359. }
  2360. void
  2361. Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
  2362. const CXXConstructorDecl *Tmpl,
  2363. const MultiLevelTemplateArgumentList &TemplateArgs) {
  2364. SmallVector<CXXCtorInitializer*, 4> NewInits;
  2365. bool AnyErrors = false;
  2366. // Instantiate all the initializers.
  2367. for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
  2368. InitsEnd = Tmpl->init_end();
  2369. Inits != InitsEnd; ++Inits) {
  2370. CXXCtorInitializer *Init = *Inits;
  2371. // Only instantiate written initializers, let Sema re-construct implicit
  2372. // ones.
  2373. if (!Init->isWritten())
  2374. continue;
  2375. SourceLocation LParenLoc, RParenLoc;
  2376. ASTOwningVector<Expr*> NewArgs(*this);
  2377. SourceLocation EllipsisLoc;
  2378. if (Init->isPackExpansion()) {
  2379. // This is a pack expansion. We should expand it now.
  2380. TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
  2381. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  2382. collectUnexpandedParameterPacks(BaseTL, Unexpanded);
  2383. bool ShouldExpand = false;
  2384. bool RetainExpansion = false;
  2385. llvm::Optional<unsigned> NumExpansions;
  2386. if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
  2387. BaseTL.getSourceRange(),
  2388. Unexpanded,
  2389. TemplateArgs, ShouldExpand,
  2390. RetainExpansion,
  2391. NumExpansions)) {
  2392. AnyErrors = true;
  2393. New->setInvalidDecl();
  2394. continue;
  2395. }
  2396. assert(ShouldExpand && "Partial instantiation of base initializer?");
  2397. // Loop over all of the arguments in the argument pack(s),
  2398. for (unsigned I = 0; I != *NumExpansions; ++I) {
  2399. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
  2400. // Instantiate the initializer.
  2401. if (InstantiateInitializer(Init->getInit(), TemplateArgs,
  2402. LParenLoc, NewArgs, RParenLoc)) {
  2403. AnyErrors = true;
  2404. break;
  2405. }
  2406. // Instantiate the base type.
  2407. TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
  2408. TemplateArgs,
  2409. Init->getSourceLocation(),
  2410. New->getDeclName());
  2411. if (!BaseTInfo) {
  2412. AnyErrors = true;
  2413. break;
  2414. }
  2415. // Build the initializer.
  2416. MultiInitializer MultiInit(CreateMultiInitializer(NewArgs, Init));
  2417. MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
  2418. BaseTInfo, MultiInit,
  2419. New->getParent(),
  2420. SourceLocation());
  2421. if (NewInit.isInvalid()) {
  2422. AnyErrors = true;
  2423. break;
  2424. }
  2425. NewInits.push_back(NewInit.get());
  2426. NewArgs.clear();
  2427. }
  2428. continue;
  2429. }
  2430. // Instantiate the initializer.
  2431. if (InstantiateInitializer(Init->getInit(), TemplateArgs,
  2432. LParenLoc, NewArgs, RParenLoc)) {
  2433. AnyErrors = true;
  2434. continue;
  2435. }
  2436. MemInitResult NewInit;
  2437. if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
  2438. TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
  2439. TemplateArgs,
  2440. Init->getSourceLocation(),
  2441. New->getDeclName());
  2442. if (!TInfo) {
  2443. AnyErrors = true;
  2444. New->setInvalidDecl();
  2445. continue;
  2446. }
  2447. MultiInitializer MultiInit(CreateMultiInitializer(NewArgs, Init));
  2448. if (Init->isBaseInitializer())
  2449. NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, MultiInit,
  2450. New->getParent(), EllipsisLoc);
  2451. else
  2452. NewInit = BuildDelegatingInitializer(TInfo, MultiInit,
  2453. cast<CXXRecordDecl>(CurContext->getParent()));
  2454. } else if (Init->isMemberInitializer()) {
  2455. FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
  2456. Init->getMemberLocation(),
  2457. Init->getMember(),
  2458. TemplateArgs));
  2459. if (!Member) {
  2460. AnyErrors = true;
  2461. New->setInvalidDecl();
  2462. continue;
  2463. }
  2464. MultiInitializer MultiInit(CreateMultiInitializer(NewArgs, Init));
  2465. NewInit = BuildMemberInitializer(Member, MultiInit,
  2466. Init->getSourceLocation());
  2467. } else if (Init->isIndirectMemberInitializer()) {
  2468. IndirectFieldDecl *IndirectMember =
  2469. cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
  2470. Init->getMemberLocation(),
  2471. Init->getIndirectMember(), TemplateArgs));
  2472. if (!IndirectMember) {
  2473. AnyErrors = true;
  2474. New->setInvalidDecl();
  2475. continue;
  2476. }
  2477. MultiInitializer MultiInit(CreateMultiInitializer(NewArgs, Init));
  2478. NewInit = BuildMemberInitializer(IndirectMember, MultiInit,
  2479. Init->getSourceLocation());
  2480. }
  2481. if (NewInit.isInvalid()) {
  2482. AnyErrors = true;
  2483. New->setInvalidDecl();
  2484. } else {
  2485. // FIXME: It would be nice if ASTOwningVector had a release function.
  2486. NewArgs.take();
  2487. NewInits.push_back(NewInit.get());
  2488. }
  2489. }
  2490. // Assign all the initializers to the new constructor.
  2491. ActOnMemInitializers(New,
  2492. /*FIXME: ColonLoc */
  2493. SourceLocation(),
  2494. NewInits.data(), NewInits.size(),
  2495. AnyErrors);
  2496. }
  2497. // TODO: this could be templated if the various decl types used the
  2498. // same method name.
  2499. static bool isInstantiationOf(ClassTemplateDecl *Pattern,
  2500. ClassTemplateDecl *Instance) {
  2501. Pattern = Pattern->getCanonicalDecl();
  2502. do {
  2503. Instance = Instance->getCanonicalDecl();
  2504. if (Pattern == Instance) return true;
  2505. Instance = Instance->getInstantiatedFromMemberTemplate();
  2506. } while (Instance);
  2507. return false;
  2508. }
  2509. static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
  2510. FunctionTemplateDecl *Instance) {
  2511. Pattern = Pattern->getCanonicalDecl();
  2512. do {
  2513. Instance = Instance->getCanonicalDecl();
  2514. if (Pattern == Instance) return true;
  2515. Instance = Instance->getInstantiatedFromMemberTemplate();
  2516. } while (Instance);
  2517. return false;
  2518. }
  2519. static bool
  2520. isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
  2521. ClassTemplatePartialSpecializationDecl *Instance) {
  2522. Pattern
  2523. = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
  2524. do {
  2525. Instance = cast<ClassTemplatePartialSpecializationDecl>(
  2526. Instance->getCanonicalDecl());
  2527. if (Pattern == Instance)
  2528. return true;
  2529. Instance = Instance->getInstantiatedFromMember();
  2530. } while (Instance);
  2531. return false;
  2532. }
  2533. static bool isInstantiationOf(CXXRecordDecl *Pattern,
  2534. CXXRecordDecl *Instance) {
  2535. Pattern = Pattern->getCanonicalDecl();
  2536. do {
  2537. Instance = Instance->getCanonicalDecl();
  2538. if (Pattern == Instance) return true;
  2539. Instance = Instance->getInstantiatedFromMemberClass();
  2540. } while (Instance);
  2541. return false;
  2542. }
  2543. static bool isInstantiationOf(FunctionDecl *Pattern,
  2544. FunctionDecl *Instance) {
  2545. Pattern = Pattern->getCanonicalDecl();
  2546. do {
  2547. Instance = Instance->getCanonicalDecl();
  2548. if (Pattern == Instance) return true;
  2549. Instance = Instance->getInstantiatedFromMemberFunction();
  2550. } while (Instance);
  2551. return false;
  2552. }
  2553. static bool isInstantiationOf(EnumDecl *Pattern,
  2554. EnumDecl *Instance) {
  2555. Pattern = Pattern->getCanonicalDecl();
  2556. do {
  2557. Instance = Instance->getCanonicalDecl();
  2558. if (Pattern == Instance) return true;
  2559. Instance = Instance->getInstantiatedFromMemberEnum();
  2560. } while (Instance);
  2561. return false;
  2562. }
  2563. static bool isInstantiationOf(UsingShadowDecl *Pattern,
  2564. UsingShadowDecl *Instance,
  2565. ASTContext &C) {
  2566. return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
  2567. }
  2568. static bool isInstantiationOf(UsingDecl *Pattern,
  2569. UsingDecl *Instance,
  2570. ASTContext &C) {
  2571. return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
  2572. }
  2573. static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
  2574. UsingDecl *Instance,
  2575. ASTContext &C) {
  2576. return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
  2577. }
  2578. static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
  2579. UsingDecl *Instance,
  2580. ASTContext &C) {
  2581. return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
  2582. }
  2583. static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
  2584. VarDecl *Instance) {
  2585. assert(Instance->isStaticDataMember());
  2586. Pattern = Pattern->getCanonicalDecl();
  2587. do {
  2588. Instance = Instance->getCanonicalDecl();
  2589. if (Pattern == Instance) return true;
  2590. Instance = Instance->getInstantiatedFromStaticDataMember();
  2591. } while (Instance);
  2592. return false;
  2593. }
  2594. // Other is the prospective instantiation
  2595. // D is the prospective pattern
  2596. static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
  2597. if (D->getKind() != Other->getKind()) {
  2598. if (UnresolvedUsingTypenameDecl *UUD
  2599. = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
  2600. if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
  2601. return isInstantiationOf(UUD, UD, Ctx);
  2602. }
  2603. }
  2604. if (UnresolvedUsingValueDecl *UUD
  2605. = dyn_cast<UnresolvedUsingValueDecl>(D)) {
  2606. if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
  2607. return isInstantiationOf(UUD, UD, Ctx);
  2608. }
  2609. }
  2610. return false;
  2611. }
  2612. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
  2613. return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
  2614. if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
  2615. return isInstantiationOf(cast<FunctionDecl>(D), Function);
  2616. if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
  2617. return isInstantiationOf(cast<EnumDecl>(D), Enum);
  2618. if (VarDecl *Var = dyn_cast<VarDecl>(Other))
  2619. if (Var->isStaticDataMember())
  2620. return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
  2621. if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
  2622. return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
  2623. if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
  2624. return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
  2625. if (ClassTemplatePartialSpecializationDecl *PartialSpec
  2626. = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
  2627. return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
  2628. PartialSpec);
  2629. if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
  2630. if (!Field->getDeclName()) {
  2631. // This is an unnamed field.
  2632. return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
  2633. cast<FieldDecl>(D);
  2634. }
  2635. }
  2636. if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
  2637. return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
  2638. if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
  2639. return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
  2640. return D->getDeclName() && isa<NamedDecl>(Other) &&
  2641. D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
  2642. }
  2643. template<typename ForwardIterator>
  2644. static NamedDecl *findInstantiationOf(ASTContext &Ctx,
  2645. NamedDecl *D,
  2646. ForwardIterator first,
  2647. ForwardIterator last) {
  2648. for (; first != last; ++first)
  2649. if (isInstantiationOf(Ctx, D, *first))
  2650. return cast<NamedDecl>(*first);
  2651. return 0;
  2652. }
  2653. /// \brief Finds the instantiation of the given declaration context
  2654. /// within the current instantiation.
  2655. ///
  2656. /// \returns NULL if there was an error
  2657. DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
  2658. const MultiLevelTemplateArgumentList &TemplateArgs) {
  2659. if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
  2660. Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
  2661. return cast_or_null<DeclContext>(ID);
  2662. } else return DC;
  2663. }
  2664. /// \brief Find the instantiation of the given declaration within the
  2665. /// current instantiation.
  2666. ///
  2667. /// This routine is intended to be used when \p D is a declaration
  2668. /// referenced from within a template, that needs to mapped into the
  2669. /// corresponding declaration within an instantiation. For example,
  2670. /// given:
  2671. ///
  2672. /// \code
  2673. /// template<typename T>
  2674. /// struct X {
  2675. /// enum Kind {
  2676. /// KnownValue = sizeof(T)
  2677. /// };
  2678. ///
  2679. /// bool getKind() const { return KnownValue; }
  2680. /// };
  2681. ///
  2682. /// template struct X<int>;
  2683. /// \endcode
  2684. ///
  2685. /// In the instantiation of X<int>::getKind(), we need to map the
  2686. /// EnumConstantDecl for KnownValue (which refers to
  2687. /// X<T>::<Kind>::KnownValue) to its instantiation
  2688. /// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
  2689. /// this mapping from within the instantiation of X<int>.
  2690. NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
  2691. const MultiLevelTemplateArgumentList &TemplateArgs) {
  2692. DeclContext *ParentDC = D->getDeclContext();
  2693. if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
  2694. isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
  2695. (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext())) {
  2696. // D is a local of some kind. Look into the map of local
  2697. // declarations to their instantiations.
  2698. typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
  2699. llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
  2700. = CurrentInstantiationScope->findInstantiationOf(D);
  2701. if (Found) {
  2702. if (Decl *FD = Found->dyn_cast<Decl *>())
  2703. return cast<NamedDecl>(FD);
  2704. unsigned PackIdx = ArgumentPackSubstitutionIndex;
  2705. return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
  2706. }
  2707. // If we didn't find the decl, then we must have a label decl that hasn't
  2708. // been found yet. Lazily instantiate it and return it now.
  2709. assert(isa<LabelDecl>(D));
  2710. Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
  2711. assert(Inst && "Failed to instantiate label??");
  2712. CurrentInstantiationScope->InstantiatedLocal(D, Inst);
  2713. return cast<LabelDecl>(Inst);
  2714. }
  2715. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
  2716. if (!Record->isDependentContext())
  2717. return D;
  2718. // Determine whether this record is the "templated" declaration describing
  2719. // a class template or class template partial specialization.
  2720. ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
  2721. if (ClassTemplate)
  2722. ClassTemplate = ClassTemplate->getCanonicalDecl();
  2723. else if (ClassTemplatePartialSpecializationDecl *PartialSpec
  2724. = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
  2725. ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
  2726. // Walk the current context to find either the record or an instantiation of
  2727. // it.
  2728. DeclContext *DC = CurContext;
  2729. while (!DC->isFileContext()) {
  2730. // If we're performing substitution while we're inside the template
  2731. // definition, we'll find our own context. We're done.
  2732. if (DC->Equals(Record))
  2733. return Record;
  2734. if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
  2735. // Check whether we're in the process of instantiating a class template
  2736. // specialization of the template we're mapping.
  2737. if (ClassTemplateSpecializationDecl *InstSpec
  2738. = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
  2739. ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
  2740. if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
  2741. return InstRecord;
  2742. }
  2743. // Check whether we're in the process of instantiating a member class.
  2744. if (isInstantiationOf(Record, InstRecord))
  2745. return InstRecord;
  2746. }
  2747. // Move to the outer template scope.
  2748. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
  2749. if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
  2750. DC = FD->getLexicalDeclContext();
  2751. continue;
  2752. }
  2753. }
  2754. DC = DC->getParent();
  2755. }
  2756. // Fall through to deal with other dependent record types (e.g.,
  2757. // anonymous unions in class templates).
  2758. }
  2759. if (!ParentDC->isDependentContext())
  2760. return D;
  2761. ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
  2762. if (!ParentDC)
  2763. return 0;
  2764. if (ParentDC != D->getDeclContext()) {
  2765. // We performed some kind of instantiation in the parent context,
  2766. // so now we need to look into the instantiated parent context to
  2767. // find the instantiation of the declaration D.
  2768. // If our context used to be dependent, we may need to instantiate
  2769. // it before performing lookup into that context.
  2770. bool IsBeingInstantiated = false;
  2771. if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
  2772. if (!Spec->isDependentContext()) {
  2773. QualType T = Context.getTypeDeclType(Spec);
  2774. const RecordType *Tag = T->getAs<RecordType>();
  2775. assert(Tag && "type of non-dependent record is not a RecordType");
  2776. if (Tag->isBeingDefined())
  2777. IsBeingInstantiated = true;
  2778. if (!Tag->isBeingDefined() &&
  2779. RequireCompleteType(Loc, T, diag::err_incomplete_type))
  2780. return 0;
  2781. ParentDC = Tag->getDecl();
  2782. }
  2783. }
  2784. NamedDecl *Result = 0;
  2785. if (D->getDeclName()) {
  2786. DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
  2787. Result = findInstantiationOf(Context, D, Found.first, Found.second);
  2788. } else {
  2789. // Since we don't have a name for the entity we're looking for,
  2790. // our only option is to walk through all of the declarations to
  2791. // find that name. This will occur in a few cases:
  2792. //
  2793. // - anonymous struct/union within a template
  2794. // - unnamed class/struct/union/enum within a template
  2795. //
  2796. // FIXME: Find a better way to find these instantiations!
  2797. Result = findInstantiationOf(Context, D,
  2798. ParentDC->decls_begin(),
  2799. ParentDC->decls_end());
  2800. }
  2801. if (!Result) {
  2802. if (isa<UsingShadowDecl>(D)) {
  2803. // UsingShadowDecls can instantiate to nothing because of using hiding.
  2804. } else if (Diags.hasErrorOccurred()) {
  2805. // We've already complained about something, so most likely this
  2806. // declaration failed to instantiate. There's no point in complaining
  2807. // further, since this is normal in invalid code.
  2808. } else if (IsBeingInstantiated) {
  2809. // The class in which this member exists is currently being
  2810. // instantiated, and we haven't gotten around to instantiating this
  2811. // member yet. This can happen when the code uses forward declarations
  2812. // of member classes, and introduces ordering dependencies via
  2813. // template instantiation.
  2814. Diag(Loc, diag::err_member_not_yet_instantiated)
  2815. << D->getDeclName()
  2816. << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
  2817. Diag(D->getLocation(), diag::note_non_instantiated_member_here);
  2818. } else {
  2819. // We should have found something, but didn't.
  2820. llvm_unreachable("Unable to find instantiation of declaration!");
  2821. }
  2822. }
  2823. D = Result;
  2824. }
  2825. return D;
  2826. }
  2827. /// \brief Performs template instantiation for all implicit template
  2828. /// instantiations we have seen until this point.
  2829. void Sema::PerformPendingInstantiations(bool LocalOnly) {
  2830. // Load pending instantiations from the external source.
  2831. if (!LocalOnly && ExternalSource) {
  2832. SmallVector<std::pair<ValueDecl *, SourceLocation>, 4> Pending;
  2833. ExternalSource->ReadPendingInstantiations(Pending);
  2834. PendingInstantiations.insert(PendingInstantiations.begin(),
  2835. Pending.begin(), Pending.end());
  2836. }
  2837. while (!PendingLocalImplicitInstantiations.empty() ||
  2838. (!LocalOnly && !PendingInstantiations.empty())) {
  2839. PendingImplicitInstantiation Inst;
  2840. if (PendingLocalImplicitInstantiations.empty()) {
  2841. Inst = PendingInstantiations.front();
  2842. PendingInstantiations.pop_front();
  2843. } else {
  2844. Inst = PendingLocalImplicitInstantiations.front();
  2845. PendingLocalImplicitInstantiations.pop_front();
  2846. }
  2847. // Instantiate function definitions
  2848. if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
  2849. PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
  2850. "instantiating function definition");
  2851. bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
  2852. TSK_ExplicitInstantiationDefinition;
  2853. InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
  2854. DefinitionRequired);
  2855. continue;
  2856. }
  2857. // Instantiate static data member definitions.
  2858. VarDecl *Var = cast<VarDecl>(Inst.first);
  2859. assert(Var->isStaticDataMember() && "Not a static data member?");
  2860. // Don't try to instantiate declarations if the most recent redeclaration
  2861. // is invalid.
  2862. if (Var->getMostRecentDecl()->isInvalidDecl())
  2863. continue;
  2864. // Check if the most recent declaration has changed the specialization kind
  2865. // and removed the need for implicit instantiation.
  2866. switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) {
  2867. case TSK_Undeclared:
  2868. llvm_unreachable("Cannot instantitiate an undeclared specialization.");
  2869. case TSK_ExplicitInstantiationDeclaration:
  2870. case TSK_ExplicitSpecialization:
  2871. continue; // No longer need to instantiate this type.
  2872. case TSK_ExplicitInstantiationDefinition:
  2873. // We only need an instantiation if the pending instantiation *is* the
  2874. // explicit instantiation.
  2875. if (Var != Var->getMostRecentDecl()) continue;
  2876. case TSK_ImplicitInstantiation:
  2877. break;
  2878. }
  2879. PrettyDeclStackTraceEntry CrashInfo(*this, Var, Var->getLocation(),
  2880. "instantiating static data member "
  2881. "definition");
  2882. bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
  2883. TSK_ExplicitInstantiationDefinition;
  2884. InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true,
  2885. DefinitionRequired);
  2886. }
  2887. }
  2888. void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
  2889. const MultiLevelTemplateArgumentList &TemplateArgs) {
  2890. for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
  2891. E = Pattern->ddiag_end(); I != E; ++I) {
  2892. DependentDiagnostic *DD = *I;
  2893. switch (DD->getKind()) {
  2894. case DependentDiagnostic::Access:
  2895. HandleDependentAccessCheck(*DD, TemplateArgs);
  2896. break;
  2897. }
  2898. }
  2899. }