SemaTemplateInstantiate.cpp 110 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641
  1. //===------- SemaTemplateInstantiate.cpp - C++ Template 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.
  10. //
  11. //===----------------------------------------------------------------------===/
  12. #include "clang/Sema/SemaInternal.h"
  13. #include "TreeTransform.h"
  14. #include "clang/Sema/DeclSpec.h"
  15. #include "clang/Sema/Initialization.h"
  16. #include "clang/Sema/Lookup.h"
  17. #include "clang/Sema/Template.h"
  18. #include "clang/Sema/TemplateDeduction.h"
  19. #include "clang/AST/ASTConsumer.h"
  20. #include "clang/AST/ASTContext.h"
  21. #include "clang/AST/Expr.h"
  22. #include "clang/AST/DeclTemplate.h"
  23. #include "clang/Basic/LangOptions.h"
  24. using namespace clang;
  25. using namespace sema;
  26. //===----------------------------------------------------------------------===/
  27. // Template Instantiation Support
  28. //===----------------------------------------------------------------------===/
  29. /// \brief Retrieve the template argument list(s) that should be used to
  30. /// instantiate the definition of the given declaration.
  31. ///
  32. /// \param D the declaration for which we are computing template instantiation
  33. /// arguments.
  34. ///
  35. /// \param Innermost if non-NULL, the innermost template argument list.
  36. ///
  37. /// \param RelativeToPrimary true if we should get the template
  38. /// arguments relative to the primary template, even when we're
  39. /// dealing with a specialization. This is only relevant for function
  40. /// template specializations.
  41. ///
  42. /// \param Pattern If non-NULL, indicates the pattern from which we will be
  43. /// instantiating the definition of the given declaration, \p D. This is
  44. /// used to determine the proper set of template instantiation arguments for
  45. /// friend function template specializations.
  46. MultiLevelTemplateArgumentList
  47. Sema::getTemplateInstantiationArgs(NamedDecl *D,
  48. const TemplateArgumentList *Innermost,
  49. bool RelativeToPrimary,
  50. const FunctionDecl *Pattern) {
  51. // Accumulate the set of template argument lists in this structure.
  52. MultiLevelTemplateArgumentList Result;
  53. if (Innermost)
  54. Result.addOuterTemplateArguments(Innermost);
  55. DeclContext *Ctx = dyn_cast<DeclContext>(D);
  56. if (!Ctx) {
  57. Ctx = D->getDeclContext();
  58. // If we have a template template parameter with translation unit context,
  59. // then we're performing substitution into a default template argument of
  60. // this template template parameter before we've constructed the template
  61. // that will own this template template parameter. In this case, we
  62. // use empty template parameter lists for all of the outer templates
  63. // to avoid performing any substitutions.
  64. if (Ctx->isTranslationUnit()) {
  65. if (TemplateTemplateParmDecl *TTP
  66. = dyn_cast<TemplateTemplateParmDecl>(D)) {
  67. for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
  68. Result.addOuterTemplateArguments(0, 0);
  69. return Result;
  70. }
  71. }
  72. }
  73. while (!Ctx->isFileContext()) {
  74. // Add template arguments from a class template instantiation.
  75. if (ClassTemplateSpecializationDecl *Spec
  76. = dyn_cast<ClassTemplateSpecializationDecl>(Ctx)) {
  77. // We're done when we hit an explicit specialization.
  78. if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
  79. !isa<ClassTemplatePartialSpecializationDecl>(Spec))
  80. break;
  81. Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
  82. // If this class template specialization was instantiated from a
  83. // specialized member that is a class template, we're done.
  84. assert(Spec->getSpecializedTemplate() && "No class template?");
  85. if (Spec->getSpecializedTemplate()->isMemberSpecialization())
  86. break;
  87. }
  88. // Add template arguments from a function template specialization.
  89. else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
  90. if (!RelativeToPrimary &&
  91. (Function->getTemplateSpecializationKind() ==
  92. TSK_ExplicitSpecialization &&
  93. !Function->getClassScopeSpecializationPattern()))
  94. break;
  95. if (const TemplateArgumentList *TemplateArgs
  96. = Function->getTemplateSpecializationArgs()) {
  97. // Add the template arguments for this specialization.
  98. Result.addOuterTemplateArguments(TemplateArgs);
  99. // If this function was instantiated from a specialized member that is
  100. // a function template, we're done.
  101. assert(Function->getPrimaryTemplate() && "No function template?");
  102. if (Function->getPrimaryTemplate()->isMemberSpecialization())
  103. break;
  104. } else if (FunctionTemplateDecl *FunTmpl
  105. = Function->getDescribedFunctionTemplate()) {
  106. // Add the "injected" template arguments.
  107. std::pair<const TemplateArgument *, unsigned>
  108. Injected = FunTmpl->getInjectedTemplateArgs();
  109. Result.addOuterTemplateArguments(Injected.first, Injected.second);
  110. }
  111. // If this is a friend declaration and it declares an entity at
  112. // namespace scope, take arguments from its lexical parent
  113. // instead of its semantic parent, unless of course the pattern we're
  114. // instantiating actually comes from the file's context!
  115. if (Function->getFriendObjectKind() &&
  116. Function->getDeclContext()->isFileContext() &&
  117. (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
  118. Ctx = Function->getLexicalDeclContext();
  119. RelativeToPrimary = false;
  120. continue;
  121. }
  122. } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
  123. if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
  124. QualType T = ClassTemplate->getInjectedClassNameSpecialization();
  125. const TemplateSpecializationType *TST
  126. = cast<TemplateSpecializationType>(Context.getCanonicalType(T));
  127. Result.addOuterTemplateArguments(TST->getArgs(), TST->getNumArgs());
  128. if (ClassTemplate->isMemberSpecialization())
  129. break;
  130. }
  131. }
  132. Ctx = Ctx->getParent();
  133. RelativeToPrimary = false;
  134. }
  135. return Result;
  136. }
  137. bool Sema::ActiveTemplateInstantiation::isInstantiationRecord() const {
  138. switch (Kind) {
  139. case TemplateInstantiation:
  140. case ExceptionSpecInstantiation:
  141. case DefaultTemplateArgumentInstantiation:
  142. case DefaultFunctionArgumentInstantiation:
  143. case ExplicitTemplateArgumentSubstitution:
  144. case DeducedTemplateArgumentSubstitution:
  145. case PriorTemplateArgumentSubstitution:
  146. return true;
  147. case DefaultTemplateArgumentChecking:
  148. return false;
  149. }
  150. llvm_unreachable("Invalid InstantiationKind!");
  151. }
  152. Sema::InstantiatingTemplate::
  153. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
  154. Decl *Entity,
  155. SourceRange InstantiationRange)
  156. : SemaRef(SemaRef),
  157. SavedInNonInstantiationSFINAEContext(
  158. SemaRef.InNonInstantiationSFINAEContext)
  159. {
  160. Invalid = CheckInstantiationDepth(PointOfInstantiation,
  161. InstantiationRange);
  162. if (!Invalid) {
  163. ActiveTemplateInstantiation Inst;
  164. Inst.Kind = ActiveTemplateInstantiation::TemplateInstantiation;
  165. Inst.PointOfInstantiation = PointOfInstantiation;
  166. Inst.Entity = reinterpret_cast<uintptr_t>(Entity);
  167. Inst.TemplateArgs = 0;
  168. Inst.NumTemplateArgs = 0;
  169. Inst.InstantiationRange = InstantiationRange;
  170. SemaRef.InNonInstantiationSFINAEContext = false;
  171. SemaRef.ActiveTemplateInstantiations.push_back(Inst);
  172. }
  173. }
  174. Sema::InstantiatingTemplate::
  175. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
  176. FunctionDecl *Entity, ExceptionSpecification,
  177. SourceRange InstantiationRange)
  178. : SemaRef(SemaRef),
  179. SavedInNonInstantiationSFINAEContext(
  180. SemaRef.InNonInstantiationSFINAEContext)
  181. {
  182. Invalid = CheckInstantiationDepth(PointOfInstantiation,
  183. InstantiationRange);
  184. if (!Invalid) {
  185. ActiveTemplateInstantiation Inst;
  186. Inst.Kind = ActiveTemplateInstantiation::ExceptionSpecInstantiation;
  187. Inst.PointOfInstantiation = PointOfInstantiation;
  188. Inst.Entity = reinterpret_cast<uintptr_t>(Entity);
  189. Inst.TemplateArgs = 0;
  190. Inst.NumTemplateArgs = 0;
  191. Inst.InstantiationRange = InstantiationRange;
  192. SemaRef.InNonInstantiationSFINAEContext = false;
  193. SemaRef.ActiveTemplateInstantiations.push_back(Inst);
  194. }
  195. }
  196. Sema::InstantiatingTemplate::
  197. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
  198. TemplateDecl *Template,
  199. ArrayRef<TemplateArgument> TemplateArgs,
  200. SourceRange InstantiationRange)
  201. : SemaRef(SemaRef),
  202. SavedInNonInstantiationSFINAEContext(
  203. SemaRef.InNonInstantiationSFINAEContext)
  204. {
  205. Invalid = CheckInstantiationDepth(PointOfInstantiation,
  206. InstantiationRange);
  207. if (!Invalid) {
  208. ActiveTemplateInstantiation Inst;
  209. Inst.Kind
  210. = ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation;
  211. Inst.PointOfInstantiation = PointOfInstantiation;
  212. Inst.Entity = reinterpret_cast<uintptr_t>(Template);
  213. Inst.TemplateArgs = TemplateArgs.data();
  214. Inst.NumTemplateArgs = TemplateArgs.size();
  215. Inst.InstantiationRange = InstantiationRange;
  216. SemaRef.InNonInstantiationSFINAEContext = false;
  217. SemaRef.ActiveTemplateInstantiations.push_back(Inst);
  218. }
  219. }
  220. Sema::InstantiatingTemplate::
  221. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
  222. FunctionTemplateDecl *FunctionTemplate,
  223. ArrayRef<TemplateArgument> TemplateArgs,
  224. ActiveTemplateInstantiation::InstantiationKind Kind,
  225. sema::TemplateDeductionInfo &DeductionInfo,
  226. SourceRange InstantiationRange)
  227. : SemaRef(SemaRef),
  228. SavedInNonInstantiationSFINAEContext(
  229. SemaRef.InNonInstantiationSFINAEContext)
  230. {
  231. Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
  232. if (!Invalid) {
  233. ActiveTemplateInstantiation Inst;
  234. Inst.Kind = Kind;
  235. Inst.PointOfInstantiation = PointOfInstantiation;
  236. Inst.Entity = reinterpret_cast<uintptr_t>(FunctionTemplate);
  237. Inst.TemplateArgs = TemplateArgs.data();
  238. Inst.NumTemplateArgs = TemplateArgs.size();
  239. Inst.DeductionInfo = &DeductionInfo;
  240. Inst.InstantiationRange = InstantiationRange;
  241. SemaRef.InNonInstantiationSFINAEContext = false;
  242. SemaRef.ActiveTemplateInstantiations.push_back(Inst);
  243. if (!Inst.isInstantiationRecord())
  244. ++SemaRef.NonInstantiationEntries;
  245. }
  246. }
  247. Sema::InstantiatingTemplate::
  248. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
  249. ClassTemplatePartialSpecializationDecl *PartialSpec,
  250. ArrayRef<TemplateArgument> TemplateArgs,
  251. sema::TemplateDeductionInfo &DeductionInfo,
  252. SourceRange InstantiationRange)
  253. : SemaRef(SemaRef),
  254. SavedInNonInstantiationSFINAEContext(
  255. SemaRef.InNonInstantiationSFINAEContext)
  256. {
  257. Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
  258. if (!Invalid) {
  259. ActiveTemplateInstantiation Inst;
  260. Inst.Kind = ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution;
  261. Inst.PointOfInstantiation = PointOfInstantiation;
  262. Inst.Entity = reinterpret_cast<uintptr_t>(PartialSpec);
  263. Inst.TemplateArgs = TemplateArgs.data();
  264. Inst.NumTemplateArgs = TemplateArgs.size();
  265. Inst.DeductionInfo = &DeductionInfo;
  266. Inst.InstantiationRange = InstantiationRange;
  267. SemaRef.InNonInstantiationSFINAEContext = false;
  268. SemaRef.ActiveTemplateInstantiations.push_back(Inst);
  269. }
  270. }
  271. Sema::InstantiatingTemplate::
  272. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
  273. ParmVarDecl *Param,
  274. ArrayRef<TemplateArgument> TemplateArgs,
  275. SourceRange InstantiationRange)
  276. : SemaRef(SemaRef),
  277. SavedInNonInstantiationSFINAEContext(
  278. SemaRef.InNonInstantiationSFINAEContext)
  279. {
  280. Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
  281. if (!Invalid) {
  282. ActiveTemplateInstantiation Inst;
  283. Inst.Kind
  284. = ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
  285. Inst.PointOfInstantiation = PointOfInstantiation;
  286. Inst.Entity = reinterpret_cast<uintptr_t>(Param);
  287. Inst.TemplateArgs = TemplateArgs.data();
  288. Inst.NumTemplateArgs = TemplateArgs.size();
  289. Inst.InstantiationRange = InstantiationRange;
  290. SemaRef.InNonInstantiationSFINAEContext = false;
  291. SemaRef.ActiveTemplateInstantiations.push_back(Inst);
  292. }
  293. }
  294. Sema::InstantiatingTemplate::
  295. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
  296. NamedDecl *Template, NonTypeTemplateParmDecl *Param,
  297. ArrayRef<TemplateArgument> TemplateArgs,
  298. SourceRange InstantiationRange)
  299. : SemaRef(SemaRef),
  300. SavedInNonInstantiationSFINAEContext(
  301. SemaRef.InNonInstantiationSFINAEContext)
  302. {
  303. Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
  304. if (!Invalid) {
  305. ActiveTemplateInstantiation Inst;
  306. Inst.Kind = ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution;
  307. Inst.PointOfInstantiation = PointOfInstantiation;
  308. Inst.Template = Template;
  309. Inst.Entity = reinterpret_cast<uintptr_t>(Param);
  310. Inst.TemplateArgs = TemplateArgs.data();
  311. Inst.NumTemplateArgs = TemplateArgs.size();
  312. Inst.InstantiationRange = InstantiationRange;
  313. SemaRef.InNonInstantiationSFINAEContext = false;
  314. SemaRef.ActiveTemplateInstantiations.push_back(Inst);
  315. }
  316. }
  317. Sema::InstantiatingTemplate::
  318. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
  319. NamedDecl *Template, TemplateTemplateParmDecl *Param,
  320. ArrayRef<TemplateArgument> TemplateArgs,
  321. SourceRange InstantiationRange)
  322. : SemaRef(SemaRef),
  323. SavedInNonInstantiationSFINAEContext(
  324. SemaRef.InNonInstantiationSFINAEContext)
  325. {
  326. Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
  327. if (!Invalid) {
  328. ActiveTemplateInstantiation Inst;
  329. Inst.Kind = ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution;
  330. Inst.PointOfInstantiation = PointOfInstantiation;
  331. Inst.Template = Template;
  332. Inst.Entity = reinterpret_cast<uintptr_t>(Param);
  333. Inst.TemplateArgs = TemplateArgs.data();
  334. Inst.NumTemplateArgs = TemplateArgs.size();
  335. Inst.InstantiationRange = InstantiationRange;
  336. SemaRef.InNonInstantiationSFINAEContext = false;
  337. SemaRef.ActiveTemplateInstantiations.push_back(Inst);
  338. }
  339. }
  340. Sema::InstantiatingTemplate::
  341. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
  342. TemplateDecl *Template, NamedDecl *Param,
  343. ArrayRef<TemplateArgument> TemplateArgs,
  344. SourceRange InstantiationRange)
  345. : SemaRef(SemaRef),
  346. SavedInNonInstantiationSFINAEContext(
  347. SemaRef.InNonInstantiationSFINAEContext)
  348. {
  349. Invalid = false;
  350. ActiveTemplateInstantiation Inst;
  351. Inst.Kind = ActiveTemplateInstantiation::DefaultTemplateArgumentChecking;
  352. Inst.PointOfInstantiation = PointOfInstantiation;
  353. Inst.Template = Template;
  354. Inst.Entity = reinterpret_cast<uintptr_t>(Param);
  355. Inst.TemplateArgs = TemplateArgs.data();
  356. Inst.NumTemplateArgs = TemplateArgs.size();
  357. Inst.InstantiationRange = InstantiationRange;
  358. SemaRef.InNonInstantiationSFINAEContext = false;
  359. SemaRef.ActiveTemplateInstantiations.push_back(Inst);
  360. assert(!Inst.isInstantiationRecord());
  361. ++SemaRef.NonInstantiationEntries;
  362. }
  363. void Sema::InstantiatingTemplate::Clear() {
  364. if (!Invalid) {
  365. if (!SemaRef.ActiveTemplateInstantiations.back().isInstantiationRecord()) {
  366. assert(SemaRef.NonInstantiationEntries > 0);
  367. --SemaRef.NonInstantiationEntries;
  368. }
  369. SemaRef.InNonInstantiationSFINAEContext
  370. = SavedInNonInstantiationSFINAEContext;
  371. SemaRef.ActiveTemplateInstantiations.pop_back();
  372. Invalid = true;
  373. }
  374. }
  375. bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
  376. SourceLocation PointOfInstantiation,
  377. SourceRange InstantiationRange) {
  378. assert(SemaRef.NonInstantiationEntries <=
  379. SemaRef.ActiveTemplateInstantiations.size());
  380. if ((SemaRef.ActiveTemplateInstantiations.size() -
  381. SemaRef.NonInstantiationEntries)
  382. <= SemaRef.getLangOpts().InstantiationDepth)
  383. return false;
  384. SemaRef.Diag(PointOfInstantiation,
  385. diag::err_template_recursion_depth_exceeded)
  386. << SemaRef.getLangOpts().InstantiationDepth
  387. << InstantiationRange;
  388. SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
  389. << SemaRef.getLangOpts().InstantiationDepth;
  390. return true;
  391. }
  392. /// \brief Prints the current instantiation stack through a series of
  393. /// notes.
  394. void Sema::PrintInstantiationStack() {
  395. // Determine which template instantiations to skip, if any.
  396. unsigned SkipStart = ActiveTemplateInstantiations.size(), SkipEnd = SkipStart;
  397. unsigned Limit = Diags.getTemplateBacktraceLimit();
  398. if (Limit && Limit < ActiveTemplateInstantiations.size()) {
  399. SkipStart = Limit / 2 + Limit % 2;
  400. SkipEnd = ActiveTemplateInstantiations.size() - Limit / 2;
  401. }
  402. // FIXME: In all of these cases, we need to show the template arguments
  403. unsigned InstantiationIdx = 0;
  404. for (SmallVector<ActiveTemplateInstantiation, 16>::reverse_iterator
  405. Active = ActiveTemplateInstantiations.rbegin(),
  406. ActiveEnd = ActiveTemplateInstantiations.rend();
  407. Active != ActiveEnd;
  408. ++Active, ++InstantiationIdx) {
  409. // Skip this instantiation?
  410. if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
  411. if (InstantiationIdx == SkipStart) {
  412. // Note that we're skipping instantiations.
  413. Diags.Report(Active->PointOfInstantiation,
  414. diag::note_instantiation_contexts_suppressed)
  415. << unsigned(ActiveTemplateInstantiations.size() - Limit);
  416. }
  417. continue;
  418. }
  419. switch (Active->Kind) {
  420. case ActiveTemplateInstantiation::TemplateInstantiation: {
  421. Decl *D = reinterpret_cast<Decl *>(Active->Entity);
  422. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
  423. unsigned DiagID = diag::note_template_member_class_here;
  424. if (isa<ClassTemplateSpecializationDecl>(Record))
  425. DiagID = diag::note_template_class_instantiation_here;
  426. Diags.Report(Active->PointOfInstantiation, DiagID)
  427. << Context.getTypeDeclType(Record)
  428. << Active->InstantiationRange;
  429. } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
  430. unsigned DiagID;
  431. if (Function->getPrimaryTemplate())
  432. DiagID = diag::note_function_template_spec_here;
  433. else
  434. DiagID = diag::note_template_member_function_here;
  435. Diags.Report(Active->PointOfInstantiation, DiagID)
  436. << Function
  437. << Active->InstantiationRange;
  438. } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
  439. Diags.Report(Active->PointOfInstantiation,
  440. diag::note_template_static_data_member_def_here)
  441. << VD
  442. << Active->InstantiationRange;
  443. } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
  444. Diags.Report(Active->PointOfInstantiation,
  445. diag::note_template_enum_def_here)
  446. << ED
  447. << Active->InstantiationRange;
  448. } else {
  449. Diags.Report(Active->PointOfInstantiation,
  450. diag::note_template_type_alias_instantiation_here)
  451. << cast<TypeAliasTemplateDecl>(D)
  452. << Active->InstantiationRange;
  453. }
  454. break;
  455. }
  456. case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: {
  457. TemplateDecl *Template = cast<TemplateDecl>((Decl *)Active->Entity);
  458. std::string TemplateArgsStr
  459. = TemplateSpecializationType::PrintTemplateArgumentList(
  460. Active->TemplateArgs,
  461. Active->NumTemplateArgs,
  462. getPrintingPolicy());
  463. Diags.Report(Active->PointOfInstantiation,
  464. diag::note_default_arg_instantiation_here)
  465. << (Template->getNameAsString() + TemplateArgsStr)
  466. << Active->InstantiationRange;
  467. break;
  468. }
  469. case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: {
  470. FunctionTemplateDecl *FnTmpl
  471. = cast<FunctionTemplateDecl>((Decl *)Active->Entity);
  472. Diags.Report(Active->PointOfInstantiation,
  473. diag::note_explicit_template_arg_substitution_here)
  474. << FnTmpl
  475. << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
  476. Active->TemplateArgs,
  477. Active->NumTemplateArgs)
  478. << Active->InstantiationRange;
  479. break;
  480. }
  481. case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
  482. if (ClassTemplatePartialSpecializationDecl *PartialSpec
  483. = dyn_cast<ClassTemplatePartialSpecializationDecl>(
  484. (Decl *)Active->Entity)) {
  485. Diags.Report(Active->PointOfInstantiation,
  486. diag::note_partial_spec_deduct_instantiation_here)
  487. << Context.getTypeDeclType(PartialSpec)
  488. << getTemplateArgumentBindingsText(
  489. PartialSpec->getTemplateParameters(),
  490. Active->TemplateArgs,
  491. Active->NumTemplateArgs)
  492. << Active->InstantiationRange;
  493. } else {
  494. FunctionTemplateDecl *FnTmpl
  495. = cast<FunctionTemplateDecl>((Decl *)Active->Entity);
  496. Diags.Report(Active->PointOfInstantiation,
  497. diag::note_function_template_deduction_instantiation_here)
  498. << FnTmpl
  499. << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
  500. Active->TemplateArgs,
  501. Active->NumTemplateArgs)
  502. << Active->InstantiationRange;
  503. }
  504. break;
  505. case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation: {
  506. ParmVarDecl *Param = cast<ParmVarDecl>((Decl *)Active->Entity);
  507. FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
  508. std::string TemplateArgsStr
  509. = TemplateSpecializationType::PrintTemplateArgumentList(
  510. Active->TemplateArgs,
  511. Active->NumTemplateArgs,
  512. getPrintingPolicy());
  513. Diags.Report(Active->PointOfInstantiation,
  514. diag::note_default_function_arg_instantiation_here)
  515. << (FD->getNameAsString() + TemplateArgsStr)
  516. << Active->InstantiationRange;
  517. break;
  518. }
  519. case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution: {
  520. NamedDecl *Parm = cast<NamedDecl>((Decl *)Active->Entity);
  521. std::string Name;
  522. if (!Parm->getName().empty())
  523. Name = std::string(" '") + Parm->getName().str() + "'";
  524. TemplateParameterList *TemplateParams = 0;
  525. if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
  526. TemplateParams = Template->getTemplateParameters();
  527. else
  528. TemplateParams =
  529. cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
  530. ->getTemplateParameters();
  531. Diags.Report(Active->PointOfInstantiation,
  532. diag::note_prior_template_arg_substitution)
  533. << isa<TemplateTemplateParmDecl>(Parm)
  534. << Name
  535. << getTemplateArgumentBindingsText(TemplateParams,
  536. Active->TemplateArgs,
  537. Active->NumTemplateArgs)
  538. << Active->InstantiationRange;
  539. break;
  540. }
  541. case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking: {
  542. TemplateParameterList *TemplateParams = 0;
  543. if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
  544. TemplateParams = Template->getTemplateParameters();
  545. else
  546. TemplateParams =
  547. cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
  548. ->getTemplateParameters();
  549. Diags.Report(Active->PointOfInstantiation,
  550. diag::note_template_default_arg_checking)
  551. << getTemplateArgumentBindingsText(TemplateParams,
  552. Active->TemplateArgs,
  553. Active->NumTemplateArgs)
  554. << Active->InstantiationRange;
  555. break;
  556. }
  557. case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
  558. Diags.Report(Active->PointOfInstantiation,
  559. diag::note_template_exception_spec_instantiation_here)
  560. << cast<FunctionDecl>((Decl *)Active->Entity)
  561. << Active->InstantiationRange;
  562. break;
  563. }
  564. }
  565. }
  566. llvm::Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
  567. if (InNonInstantiationSFINAEContext)
  568. return llvm::Optional<TemplateDeductionInfo *>(0);
  569. for (SmallVector<ActiveTemplateInstantiation, 16>::const_reverse_iterator
  570. Active = ActiveTemplateInstantiations.rbegin(),
  571. ActiveEnd = ActiveTemplateInstantiations.rend();
  572. Active != ActiveEnd;
  573. ++Active)
  574. {
  575. switch(Active->Kind) {
  576. case ActiveTemplateInstantiation::TemplateInstantiation:
  577. // An instantiation of an alias template may or may not be a SFINAE
  578. // context, depending on what else is on the stack.
  579. if (isa<TypeAliasTemplateDecl>(reinterpret_cast<Decl *>(Active->Entity)))
  580. break;
  581. // Fall through.
  582. case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation:
  583. case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
  584. // This is a template instantiation, so there is no SFINAE.
  585. return llvm::Optional<TemplateDeductionInfo *>();
  586. case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation:
  587. case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution:
  588. case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking:
  589. // A default template argument instantiation and substitution into
  590. // template parameters with arguments for prior parameters may or may
  591. // not be a SFINAE context; look further up the stack.
  592. break;
  593. case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution:
  594. case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
  595. // We're either substitution explicitly-specified template arguments
  596. // or deduced template arguments, so SFINAE applies.
  597. assert(Active->DeductionInfo && "Missing deduction info pointer");
  598. return Active->DeductionInfo;
  599. }
  600. }
  601. return llvm::Optional<TemplateDeductionInfo *>();
  602. }
  603. /// \brief Retrieve the depth and index of a parameter pack.
  604. static std::pair<unsigned, unsigned>
  605. getDepthAndIndex(NamedDecl *ND) {
  606. if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
  607. return std::make_pair(TTP->getDepth(), TTP->getIndex());
  608. if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
  609. return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
  610. TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
  611. return std::make_pair(TTP->getDepth(), TTP->getIndex());
  612. }
  613. //===----------------------------------------------------------------------===/
  614. // Template Instantiation for Types
  615. //===----------------------------------------------------------------------===/
  616. namespace {
  617. class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
  618. const MultiLevelTemplateArgumentList &TemplateArgs;
  619. SourceLocation Loc;
  620. DeclarationName Entity;
  621. public:
  622. typedef TreeTransform<TemplateInstantiator> inherited;
  623. TemplateInstantiator(Sema &SemaRef,
  624. const MultiLevelTemplateArgumentList &TemplateArgs,
  625. SourceLocation Loc,
  626. DeclarationName Entity)
  627. : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
  628. Entity(Entity) { }
  629. /// \brief Determine whether the given type \p T has already been
  630. /// transformed.
  631. ///
  632. /// For the purposes of template instantiation, a type has already been
  633. /// transformed if it is NULL or if it is not dependent.
  634. bool AlreadyTransformed(QualType T);
  635. /// \brief Returns the location of the entity being instantiated, if known.
  636. SourceLocation getBaseLocation() { return Loc; }
  637. /// \brief Returns the name of the entity being instantiated, if any.
  638. DeclarationName getBaseEntity() { return Entity; }
  639. /// \brief Sets the "base" location and entity when that
  640. /// information is known based on another transformation.
  641. void setBase(SourceLocation Loc, DeclarationName Entity) {
  642. this->Loc = Loc;
  643. this->Entity = Entity;
  644. }
  645. bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
  646. SourceRange PatternRange,
  647. llvm::ArrayRef<UnexpandedParameterPack> Unexpanded,
  648. bool &ShouldExpand,
  649. bool &RetainExpansion,
  650. llvm::Optional<unsigned> &NumExpansions) {
  651. return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
  652. PatternRange, Unexpanded,
  653. TemplateArgs,
  654. ShouldExpand,
  655. RetainExpansion,
  656. NumExpansions);
  657. }
  658. void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
  659. SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
  660. }
  661. TemplateArgument ForgetPartiallySubstitutedPack() {
  662. TemplateArgument Result;
  663. if (NamedDecl *PartialPack
  664. = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
  665. MultiLevelTemplateArgumentList &TemplateArgs
  666. = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
  667. unsigned Depth, Index;
  668. llvm::tie(Depth, Index) = getDepthAndIndex(PartialPack);
  669. if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
  670. Result = TemplateArgs(Depth, Index);
  671. TemplateArgs.setArgument(Depth, Index, TemplateArgument());
  672. }
  673. }
  674. return Result;
  675. }
  676. void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
  677. if (Arg.isNull())
  678. return;
  679. if (NamedDecl *PartialPack
  680. = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
  681. MultiLevelTemplateArgumentList &TemplateArgs
  682. = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
  683. unsigned Depth, Index;
  684. llvm::tie(Depth, Index) = getDepthAndIndex(PartialPack);
  685. TemplateArgs.setArgument(Depth, Index, Arg);
  686. }
  687. }
  688. /// \brief Transform the given declaration by instantiating a reference to
  689. /// this declaration.
  690. Decl *TransformDecl(SourceLocation Loc, Decl *D);
  691. void transformAttrs(Decl *Old, Decl *New) {
  692. SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
  693. }
  694. void transformedLocalDecl(Decl *Old, Decl *New) {
  695. SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
  696. }
  697. /// \brief Transform the definition of the given declaration by
  698. /// instantiating it.
  699. Decl *TransformDefinition(SourceLocation Loc, Decl *D);
  700. /// \bried Transform the first qualifier within a scope by instantiating the
  701. /// declaration.
  702. NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
  703. /// \brief Rebuild the exception declaration and register the declaration
  704. /// as an instantiated local.
  705. VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
  706. TypeSourceInfo *Declarator,
  707. SourceLocation StartLoc,
  708. SourceLocation NameLoc,
  709. IdentifierInfo *Name);
  710. /// \brief Rebuild the Objective-C exception declaration and register the
  711. /// declaration as an instantiated local.
  712. VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
  713. TypeSourceInfo *TSInfo, QualType T);
  714. /// \brief Check for tag mismatches when instantiating an
  715. /// elaborated type.
  716. QualType RebuildElaboratedType(SourceLocation KeywordLoc,
  717. ElaboratedTypeKeyword Keyword,
  718. NestedNameSpecifierLoc QualifierLoc,
  719. QualType T);
  720. TemplateName TransformTemplateName(CXXScopeSpec &SS,
  721. TemplateName Name,
  722. SourceLocation NameLoc,
  723. QualType ObjectType = QualType(),
  724. NamedDecl *FirstQualifierInScope = 0);
  725. ExprResult TransformPredefinedExpr(PredefinedExpr *E);
  726. ExprResult TransformDeclRefExpr(DeclRefExpr *E);
  727. ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
  728. ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
  729. NonTypeTemplateParmDecl *D);
  730. ExprResult TransformSubstNonTypeTemplateParmPackExpr(
  731. SubstNonTypeTemplateParmPackExpr *E);
  732. QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
  733. FunctionProtoTypeLoc TL);
  734. QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
  735. FunctionProtoTypeLoc TL,
  736. CXXRecordDecl *ThisContext,
  737. unsigned ThisTypeQuals);
  738. ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
  739. int indexAdjustment,
  740. llvm::Optional<unsigned> NumExpansions,
  741. bool ExpectParameterPack);
  742. /// \brief Transforms a template type parameter type by performing
  743. /// substitution of the corresponding template type argument.
  744. QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
  745. TemplateTypeParmTypeLoc TL);
  746. /// \brief Transforms an already-substituted template type parameter pack
  747. /// into either itself (if we aren't substituting into its pack expansion)
  748. /// or the appropriate substituted argument.
  749. QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
  750. SubstTemplateTypeParmPackTypeLoc TL);
  751. ExprResult TransformCallExpr(CallExpr *CE) {
  752. getSema().CallsUndergoingInstantiation.push_back(CE);
  753. ExprResult Result =
  754. TreeTransform<TemplateInstantiator>::TransformCallExpr(CE);
  755. getSema().CallsUndergoingInstantiation.pop_back();
  756. return move(Result);
  757. }
  758. ExprResult TransformLambdaExpr(LambdaExpr *E) {
  759. LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
  760. return TreeTransform<TemplateInstantiator>::TransformLambdaExpr(E);
  761. }
  762. ExprResult TransformLambdaScope(LambdaExpr *E,
  763. CXXMethodDecl *CallOperator) {
  764. CallOperator->setInstantiationOfMemberFunction(E->getCallOperator(),
  765. TSK_ImplicitInstantiation);
  766. return TreeTransform<TemplateInstantiator>::
  767. TransformLambdaScope(E, CallOperator);
  768. }
  769. private:
  770. ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
  771. SourceLocation loc,
  772. TemplateArgument arg);
  773. };
  774. }
  775. bool TemplateInstantiator::AlreadyTransformed(QualType T) {
  776. if (T.isNull())
  777. return true;
  778. if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
  779. return false;
  780. getSema().MarkDeclarationsReferencedInType(Loc, T);
  781. return true;
  782. }
  783. Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
  784. if (!D)
  785. return 0;
  786. if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
  787. if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
  788. // If the corresponding template argument is NULL or non-existent, it's
  789. // because we are performing instantiation from explicitly-specified
  790. // template arguments in a function template, but there were some
  791. // arguments left unspecified.
  792. if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
  793. TTP->getPosition()))
  794. return D;
  795. TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
  796. if (TTP->isParameterPack()) {
  797. assert(Arg.getKind() == TemplateArgument::Pack &&
  798. "Missing argument pack");
  799. assert(getSema().ArgumentPackSubstitutionIndex >= 0);
  800. assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
  801. Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
  802. }
  803. TemplateName Template = Arg.getAsTemplate();
  804. assert(!Template.isNull() && Template.getAsTemplateDecl() &&
  805. "Wrong kind of template template argument");
  806. return Template.getAsTemplateDecl();
  807. }
  808. // Fall through to find the instantiated declaration for this template
  809. // template parameter.
  810. }
  811. return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
  812. }
  813. Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
  814. Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
  815. if (!Inst)
  816. return 0;
  817. getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
  818. return Inst;
  819. }
  820. NamedDecl *
  821. TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
  822. SourceLocation Loc) {
  823. // If the first part of the nested-name-specifier was a template type
  824. // parameter, instantiate that type parameter down to a tag type.
  825. if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
  826. const TemplateTypeParmType *TTP
  827. = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
  828. if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
  829. // FIXME: This needs testing w/ member access expressions.
  830. TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
  831. if (TTP->isParameterPack()) {
  832. assert(Arg.getKind() == TemplateArgument::Pack &&
  833. "Missing argument pack");
  834. if (getSema().ArgumentPackSubstitutionIndex == -1)
  835. return 0;
  836. assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
  837. Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
  838. }
  839. QualType T = Arg.getAsType();
  840. if (T.isNull())
  841. return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
  842. if (const TagType *Tag = T->getAs<TagType>())
  843. return Tag->getDecl();
  844. // The resulting type is not a tag; complain.
  845. getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
  846. return 0;
  847. }
  848. }
  849. return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
  850. }
  851. VarDecl *
  852. TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
  853. TypeSourceInfo *Declarator,
  854. SourceLocation StartLoc,
  855. SourceLocation NameLoc,
  856. IdentifierInfo *Name) {
  857. VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
  858. StartLoc, NameLoc, Name);
  859. if (Var)
  860. getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
  861. return Var;
  862. }
  863. VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
  864. TypeSourceInfo *TSInfo,
  865. QualType T) {
  866. VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
  867. if (Var)
  868. getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
  869. return Var;
  870. }
  871. QualType
  872. TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
  873. ElaboratedTypeKeyword Keyword,
  874. NestedNameSpecifierLoc QualifierLoc,
  875. QualType T) {
  876. if (const TagType *TT = T->getAs<TagType>()) {
  877. TagDecl* TD = TT->getDecl();
  878. SourceLocation TagLocation = KeywordLoc;
  879. // FIXME: type might be anonymous.
  880. IdentifierInfo *Id = TD->getIdentifier();
  881. // TODO: should we even warn on struct/class mismatches for this? Seems
  882. // like it's likely to produce a lot of spurious errors.
  883. if (Keyword != ETK_None && Keyword != ETK_Typename) {
  884. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
  885. if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
  886. TagLocation, *Id)) {
  887. SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
  888. << Id
  889. << FixItHint::CreateReplacement(SourceRange(TagLocation),
  890. TD->getKindName());
  891. SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
  892. }
  893. }
  894. }
  895. return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
  896. Keyword,
  897. QualifierLoc,
  898. T);
  899. }
  900. TemplateName TemplateInstantiator::TransformTemplateName(CXXScopeSpec &SS,
  901. TemplateName Name,
  902. SourceLocation NameLoc,
  903. QualType ObjectType,
  904. NamedDecl *FirstQualifierInScope) {
  905. if (TemplateTemplateParmDecl *TTP
  906. = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
  907. if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
  908. // If the corresponding template argument is NULL or non-existent, it's
  909. // because we are performing instantiation from explicitly-specified
  910. // template arguments in a function template, but there were some
  911. // arguments left unspecified.
  912. if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
  913. TTP->getPosition()))
  914. return Name;
  915. TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
  916. if (TTP->isParameterPack()) {
  917. assert(Arg.getKind() == TemplateArgument::Pack &&
  918. "Missing argument pack");
  919. if (getSema().ArgumentPackSubstitutionIndex == -1) {
  920. // We have the template argument pack to substitute, but we're not
  921. // actually expanding the enclosing pack expansion yet. So, just
  922. // keep the entire argument pack.
  923. return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
  924. }
  925. assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
  926. Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
  927. }
  928. TemplateName Template = Arg.getAsTemplate();
  929. assert(!Template.isNull() && "Null template template argument");
  930. // We don't ever want to substitute for a qualified template name, since
  931. // the qualifier is handled separately. So, look through the qualified
  932. // template name to its underlying declaration.
  933. if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
  934. Template = TemplateName(QTN->getTemplateDecl());
  935. Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
  936. return Template;
  937. }
  938. }
  939. if (SubstTemplateTemplateParmPackStorage *SubstPack
  940. = Name.getAsSubstTemplateTemplateParmPack()) {
  941. if (getSema().ArgumentPackSubstitutionIndex == -1)
  942. return Name;
  943. const TemplateArgument &ArgPack = SubstPack->getArgumentPack();
  944. assert(getSema().ArgumentPackSubstitutionIndex < (int)ArgPack.pack_size() &&
  945. "Pack substitution index out-of-range");
  946. return ArgPack.pack_begin()[getSema().ArgumentPackSubstitutionIndex]
  947. .getAsTemplate();
  948. }
  949. return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
  950. FirstQualifierInScope);
  951. }
  952. ExprResult
  953. TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
  954. if (!E->isTypeDependent())
  955. return SemaRef.Owned(E);
  956. FunctionDecl *currentDecl = getSema().getCurFunctionDecl();
  957. assert(currentDecl && "Must have current function declaration when "
  958. "instantiating.");
  959. PredefinedExpr::IdentType IT = E->getIdentType();
  960. unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
  961. llvm::APInt LengthI(32, Length + 1);
  962. QualType ResTy;
  963. if (IT == PredefinedExpr::LFunction)
  964. ResTy = getSema().Context.WCharTy.withConst();
  965. else
  966. ResTy = getSema().Context.CharTy.withConst();
  967. ResTy = getSema().Context.getConstantArrayType(ResTy, LengthI,
  968. ArrayType::Normal, 0);
  969. PredefinedExpr *PE =
  970. new (getSema().Context) PredefinedExpr(E->getLocation(), ResTy, IT);
  971. return getSema().Owned(PE);
  972. }
  973. ExprResult
  974. TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
  975. NonTypeTemplateParmDecl *NTTP) {
  976. // If the corresponding template argument is NULL or non-existent, it's
  977. // because we are performing instantiation from explicitly-specified
  978. // template arguments in a function template, but there were some
  979. // arguments left unspecified.
  980. if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
  981. NTTP->getPosition()))
  982. return SemaRef.Owned(E);
  983. TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
  984. if (NTTP->isParameterPack()) {
  985. assert(Arg.getKind() == TemplateArgument::Pack &&
  986. "Missing argument pack");
  987. if (getSema().ArgumentPackSubstitutionIndex == -1) {
  988. // We have an argument pack, but we can't select a particular argument
  989. // out of it yet. Therefore, we'll build an expression to hold on to that
  990. // argument pack.
  991. QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
  992. E->getLocation(),
  993. NTTP->getDeclName());
  994. if (TargetType.isNull())
  995. return ExprError();
  996. return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(TargetType,
  997. NTTP,
  998. E->getLocation(),
  999. Arg);
  1000. }
  1001. assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
  1002. Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
  1003. }
  1004. return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
  1005. }
  1006. ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
  1007. NonTypeTemplateParmDecl *parm,
  1008. SourceLocation loc,
  1009. TemplateArgument arg) {
  1010. ExprResult result;
  1011. QualType type;
  1012. // If the argument is a pack expansion, the parameter must actually be a
  1013. // parameter pack, and we should substitute the pattern itself, producing
  1014. // an expression which contains an unexpanded parameter pack.
  1015. if (arg.isPackExpansion()) {
  1016. assert(parm->isParameterPack() && "pack expansion for non-pack");
  1017. arg = arg.getPackExpansionPattern();
  1018. }
  1019. // The template argument itself might be an expression, in which
  1020. // case we just return that expression.
  1021. if (arg.getKind() == TemplateArgument::Expression) {
  1022. Expr *argExpr = arg.getAsExpr();
  1023. result = SemaRef.Owned(argExpr);
  1024. type = argExpr->getType();
  1025. } else if (arg.getKind() == TemplateArgument::Declaration) {
  1026. ValueDecl *VD;
  1027. if (Decl *D = arg.getAsDecl()) {
  1028. VD = cast<ValueDecl>(D);
  1029. // Find the instantiation of the template argument. This is
  1030. // required for nested templates.
  1031. VD = cast_or_null<ValueDecl>(
  1032. getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
  1033. if (!VD)
  1034. return ExprError();
  1035. } else {
  1036. // Propagate NULL template argument.
  1037. VD = 0;
  1038. }
  1039. // Derive the type we want the substituted decl to have. This had
  1040. // better be non-dependent, or these checks will have serious problems.
  1041. if (parm->isExpandedParameterPack()) {
  1042. type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
  1043. } else if (parm->isParameterPack() &&
  1044. isa<PackExpansionType>(parm->getType())) {
  1045. type = SemaRef.SubstType(
  1046. cast<PackExpansionType>(parm->getType())->getPattern(),
  1047. TemplateArgs, loc, parm->getDeclName());
  1048. } else {
  1049. type = SemaRef.SubstType(parm->getType(), TemplateArgs,
  1050. loc, parm->getDeclName());
  1051. }
  1052. assert(!type.isNull() && "type substitution failed for param type");
  1053. assert(!type->isDependentType() && "param type still dependent");
  1054. result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
  1055. if (!result.isInvalid()) type = result.get()->getType();
  1056. } else {
  1057. result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
  1058. // Note that this type can be different from the type of 'result',
  1059. // e.g. if it's an enum type.
  1060. type = arg.getIntegralType();
  1061. }
  1062. if (result.isInvalid()) return ExprError();
  1063. Expr *resultExpr = result.take();
  1064. return SemaRef.Owned(new (SemaRef.Context)
  1065. SubstNonTypeTemplateParmExpr(type,
  1066. resultExpr->getValueKind(),
  1067. loc, parm, resultExpr));
  1068. }
  1069. ExprResult
  1070. TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
  1071. SubstNonTypeTemplateParmPackExpr *E) {
  1072. if (getSema().ArgumentPackSubstitutionIndex == -1) {
  1073. // We aren't expanding the parameter pack, so just return ourselves.
  1074. return getSema().Owned(E);
  1075. }
  1076. const TemplateArgument &ArgPack = E->getArgumentPack();
  1077. unsigned Index = (unsigned)getSema().ArgumentPackSubstitutionIndex;
  1078. assert(Index < ArgPack.pack_size() && "Substitution index out-of-range");
  1079. const TemplateArgument &Arg = ArgPack.pack_begin()[Index];
  1080. return transformNonTypeTemplateParmRef(E->getParameterPack(),
  1081. E->getParameterPackLocation(),
  1082. Arg);
  1083. }
  1084. ExprResult
  1085. TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
  1086. NamedDecl *D = E->getDecl();
  1087. if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
  1088. if (NTTP->getDepth() < TemplateArgs.getNumLevels())
  1089. return TransformTemplateParmRefExpr(E, NTTP);
  1090. // We have a non-type template parameter that isn't fully substituted;
  1091. // FindInstantiatedDecl will find it in the local instantiation scope.
  1092. }
  1093. return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
  1094. }
  1095. ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
  1096. CXXDefaultArgExpr *E) {
  1097. assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
  1098. getDescribedFunctionTemplate() &&
  1099. "Default arg expressions are never formed in dependent cases.");
  1100. return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
  1101. cast<FunctionDecl>(E->getParam()->getDeclContext()),
  1102. E->getParam());
  1103. }
  1104. QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
  1105. FunctionProtoTypeLoc TL) {
  1106. // We need a local instantiation scope for this function prototype.
  1107. LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
  1108. return inherited::TransformFunctionProtoType(TLB, TL);
  1109. }
  1110. QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
  1111. FunctionProtoTypeLoc TL,
  1112. CXXRecordDecl *ThisContext,
  1113. unsigned ThisTypeQuals) {
  1114. // We need a local instantiation scope for this function prototype.
  1115. LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
  1116. return inherited::TransformFunctionProtoType(TLB, TL, ThisContext,
  1117. ThisTypeQuals);
  1118. }
  1119. ParmVarDecl *
  1120. TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
  1121. int indexAdjustment,
  1122. llvm::Optional<unsigned> NumExpansions,
  1123. bool ExpectParameterPack) {
  1124. return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
  1125. NumExpansions, ExpectParameterPack);
  1126. }
  1127. QualType
  1128. TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
  1129. TemplateTypeParmTypeLoc TL) {
  1130. const TemplateTypeParmType *T = TL.getTypePtr();
  1131. if (T->getDepth() < TemplateArgs.getNumLevels()) {
  1132. // Replace the template type parameter with its corresponding
  1133. // template argument.
  1134. // If the corresponding template argument is NULL or doesn't exist, it's
  1135. // because we are performing instantiation from explicitly-specified
  1136. // template arguments in a function template class, but there were some
  1137. // arguments left unspecified.
  1138. if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
  1139. TemplateTypeParmTypeLoc NewTL
  1140. = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
  1141. NewTL.setNameLoc(TL.getNameLoc());
  1142. return TL.getType();
  1143. }
  1144. TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
  1145. if (T->isParameterPack()) {
  1146. assert(Arg.getKind() == TemplateArgument::Pack &&
  1147. "Missing argument pack");
  1148. if (getSema().ArgumentPackSubstitutionIndex == -1) {
  1149. // We have the template argument pack, but we're not expanding the
  1150. // enclosing pack expansion yet. Just save the template argument
  1151. // pack for later substitution.
  1152. QualType Result
  1153. = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
  1154. SubstTemplateTypeParmPackTypeLoc NewTL
  1155. = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
  1156. NewTL.setNameLoc(TL.getNameLoc());
  1157. return Result;
  1158. }
  1159. assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
  1160. Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
  1161. }
  1162. assert(Arg.getKind() == TemplateArgument::Type &&
  1163. "Template argument kind mismatch");
  1164. QualType Replacement = Arg.getAsType();
  1165. // TODO: only do this uniquing once, at the start of instantiation.
  1166. QualType Result
  1167. = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
  1168. SubstTemplateTypeParmTypeLoc NewTL
  1169. = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
  1170. NewTL.setNameLoc(TL.getNameLoc());
  1171. return Result;
  1172. }
  1173. // The template type parameter comes from an inner template (e.g.,
  1174. // the template parameter list of a member template inside the
  1175. // template we are instantiating). Create a new template type
  1176. // parameter with the template "level" reduced by one.
  1177. TemplateTypeParmDecl *NewTTPDecl = 0;
  1178. if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
  1179. NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
  1180. TransformDecl(TL.getNameLoc(), OldTTPDecl));
  1181. QualType Result
  1182. = getSema().Context.getTemplateTypeParmType(T->getDepth()
  1183. - TemplateArgs.getNumLevels(),
  1184. T->getIndex(),
  1185. T->isParameterPack(),
  1186. NewTTPDecl);
  1187. TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
  1188. NewTL.setNameLoc(TL.getNameLoc());
  1189. return Result;
  1190. }
  1191. QualType
  1192. TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
  1193. TypeLocBuilder &TLB,
  1194. SubstTemplateTypeParmPackTypeLoc TL) {
  1195. if (getSema().ArgumentPackSubstitutionIndex == -1) {
  1196. // We aren't expanding the parameter pack, so just return ourselves.
  1197. SubstTemplateTypeParmPackTypeLoc NewTL
  1198. = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
  1199. NewTL.setNameLoc(TL.getNameLoc());
  1200. return TL.getType();
  1201. }
  1202. const TemplateArgument &ArgPack = TL.getTypePtr()->getArgumentPack();
  1203. unsigned Index = (unsigned)getSema().ArgumentPackSubstitutionIndex;
  1204. assert(Index < ArgPack.pack_size() && "Substitution index out-of-range");
  1205. QualType Result = ArgPack.pack_begin()[Index].getAsType();
  1206. Result = getSema().Context.getSubstTemplateTypeParmType(
  1207. TL.getTypePtr()->getReplacedParameter(),
  1208. Result);
  1209. SubstTemplateTypeParmTypeLoc NewTL
  1210. = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
  1211. NewTL.setNameLoc(TL.getNameLoc());
  1212. return Result;
  1213. }
  1214. /// \brief Perform substitution on the type T with a given set of template
  1215. /// arguments.
  1216. ///
  1217. /// This routine substitutes the given template arguments into the
  1218. /// type T and produces the instantiated type.
  1219. ///
  1220. /// \param T the type into which the template arguments will be
  1221. /// substituted. If this type is not dependent, it will be returned
  1222. /// immediately.
  1223. ///
  1224. /// \param Args the template arguments that will be
  1225. /// substituted for the top-level template parameters within T.
  1226. ///
  1227. /// \param Loc the location in the source code where this substitution
  1228. /// is being performed. It will typically be the location of the
  1229. /// declarator (if we're instantiating the type of some declaration)
  1230. /// or the location of the type in the source code (if, e.g., we're
  1231. /// instantiating the type of a cast expression).
  1232. ///
  1233. /// \param Entity the name of the entity associated with a declaration
  1234. /// being instantiated (if any). May be empty to indicate that there
  1235. /// is no such entity (if, e.g., this is a type that occurs as part of
  1236. /// a cast expression) or that the entity has no name (e.g., an
  1237. /// unnamed function parameter).
  1238. ///
  1239. /// \returns If the instantiation succeeds, the instantiated
  1240. /// type. Otherwise, produces diagnostics and returns a NULL type.
  1241. TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
  1242. const MultiLevelTemplateArgumentList &Args,
  1243. SourceLocation Loc,
  1244. DeclarationName Entity) {
  1245. assert(!ActiveTemplateInstantiations.empty() &&
  1246. "Cannot perform an instantiation without some context on the "
  1247. "instantiation stack");
  1248. if (!T->getType()->isInstantiationDependentType() &&
  1249. !T->getType()->isVariablyModifiedType())
  1250. return T;
  1251. TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
  1252. return Instantiator.TransformType(T);
  1253. }
  1254. TypeSourceInfo *Sema::SubstType(TypeLoc TL,
  1255. const MultiLevelTemplateArgumentList &Args,
  1256. SourceLocation Loc,
  1257. DeclarationName Entity) {
  1258. assert(!ActiveTemplateInstantiations.empty() &&
  1259. "Cannot perform an instantiation without some context on the "
  1260. "instantiation stack");
  1261. if (TL.getType().isNull())
  1262. return 0;
  1263. if (!TL.getType()->isInstantiationDependentType() &&
  1264. !TL.getType()->isVariablyModifiedType()) {
  1265. // FIXME: Make a copy of the TypeLoc data here, so that we can
  1266. // return a new TypeSourceInfo. Inefficient!
  1267. TypeLocBuilder TLB;
  1268. TLB.pushFullCopy(TL);
  1269. return TLB.getTypeSourceInfo(Context, TL.getType());
  1270. }
  1271. TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
  1272. TypeLocBuilder TLB;
  1273. TLB.reserve(TL.getFullDataSize());
  1274. QualType Result = Instantiator.TransformType(TLB, TL);
  1275. if (Result.isNull())
  1276. return 0;
  1277. return TLB.getTypeSourceInfo(Context, Result);
  1278. }
  1279. /// Deprecated form of the above.
  1280. QualType Sema::SubstType(QualType T,
  1281. const MultiLevelTemplateArgumentList &TemplateArgs,
  1282. SourceLocation Loc, DeclarationName Entity) {
  1283. assert(!ActiveTemplateInstantiations.empty() &&
  1284. "Cannot perform an instantiation without some context on the "
  1285. "instantiation stack");
  1286. // If T is not a dependent type or a variably-modified type, there
  1287. // is nothing to do.
  1288. if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
  1289. return T;
  1290. TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
  1291. return Instantiator.TransformType(T);
  1292. }
  1293. static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
  1294. if (T->getType()->isInstantiationDependentType() ||
  1295. T->getType()->isVariablyModifiedType())
  1296. return true;
  1297. TypeLoc TL = T->getTypeLoc().IgnoreParens();
  1298. if (!isa<FunctionProtoTypeLoc>(TL))
  1299. return false;
  1300. FunctionProtoTypeLoc FP = cast<FunctionProtoTypeLoc>(TL);
  1301. for (unsigned I = 0, E = FP.getNumArgs(); I != E; ++I) {
  1302. ParmVarDecl *P = FP.getArg(I);
  1303. // The parameter's type as written might be dependent even if the
  1304. // decayed type was not dependent.
  1305. if (TypeSourceInfo *TSInfo = P->getTypeSourceInfo())
  1306. if (TSInfo->getType()->isInstantiationDependentType())
  1307. return true;
  1308. // TODO: currently we always rebuild expressions. When we
  1309. // properly get lazier about this, we should use the same
  1310. // logic to avoid rebuilding prototypes here.
  1311. if (P->hasDefaultArg())
  1312. return true;
  1313. }
  1314. return false;
  1315. }
  1316. /// A form of SubstType intended specifically for instantiating the
  1317. /// type of a FunctionDecl. Its purpose is solely to force the
  1318. /// instantiation of default-argument expressions.
  1319. TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
  1320. const MultiLevelTemplateArgumentList &Args,
  1321. SourceLocation Loc,
  1322. DeclarationName Entity,
  1323. CXXRecordDecl *ThisContext,
  1324. unsigned ThisTypeQuals) {
  1325. assert(!ActiveTemplateInstantiations.empty() &&
  1326. "Cannot perform an instantiation without some context on the "
  1327. "instantiation stack");
  1328. if (!NeedsInstantiationAsFunctionType(T))
  1329. return T;
  1330. TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
  1331. TypeLocBuilder TLB;
  1332. TypeLoc TL = T->getTypeLoc();
  1333. TLB.reserve(TL.getFullDataSize());
  1334. QualType Result;
  1335. if (FunctionProtoTypeLoc *Proto = dyn_cast<FunctionProtoTypeLoc>(&TL)) {
  1336. Result = Instantiator.TransformFunctionProtoType(TLB, *Proto, ThisContext,
  1337. ThisTypeQuals);
  1338. } else {
  1339. Result = Instantiator.TransformType(TLB, TL);
  1340. }
  1341. if (Result.isNull())
  1342. return 0;
  1343. return TLB.getTypeSourceInfo(Context, Result);
  1344. }
  1345. ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
  1346. const MultiLevelTemplateArgumentList &TemplateArgs,
  1347. int indexAdjustment,
  1348. llvm::Optional<unsigned> NumExpansions,
  1349. bool ExpectParameterPack) {
  1350. TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
  1351. TypeSourceInfo *NewDI = 0;
  1352. TypeLoc OldTL = OldDI->getTypeLoc();
  1353. if (isa<PackExpansionTypeLoc>(OldTL)) {
  1354. PackExpansionTypeLoc ExpansionTL = cast<PackExpansionTypeLoc>(OldTL);
  1355. // We have a function parameter pack. Substitute into the pattern of the
  1356. // expansion.
  1357. NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
  1358. OldParm->getLocation(), OldParm->getDeclName());
  1359. if (!NewDI)
  1360. return 0;
  1361. if (NewDI->getType()->containsUnexpandedParameterPack()) {
  1362. // We still have unexpanded parameter packs, which means that
  1363. // our function parameter is still a function parameter pack.
  1364. // Therefore, make its type a pack expansion type.
  1365. NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
  1366. NumExpansions);
  1367. } else if (ExpectParameterPack) {
  1368. // We expected to get a parameter pack but didn't (because the type
  1369. // itself is not a pack expansion type), so complain. This can occur when
  1370. // the substitution goes through an alias template that "loses" the
  1371. // pack expansion.
  1372. Diag(OldParm->getLocation(),
  1373. diag::err_function_parameter_pack_without_parameter_packs)
  1374. << NewDI->getType();
  1375. return 0;
  1376. }
  1377. } else {
  1378. NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
  1379. OldParm->getDeclName());
  1380. }
  1381. if (!NewDI)
  1382. return 0;
  1383. if (NewDI->getType()->isVoidType()) {
  1384. Diag(OldParm->getLocation(), diag::err_param_with_void_type);
  1385. return 0;
  1386. }
  1387. ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
  1388. OldParm->getInnerLocStart(),
  1389. OldParm->getLocation(),
  1390. OldParm->getIdentifier(),
  1391. NewDI->getType(), NewDI,
  1392. OldParm->getStorageClass(),
  1393. OldParm->getStorageClassAsWritten());
  1394. if (!NewParm)
  1395. return 0;
  1396. // Mark the (new) default argument as uninstantiated (if any).
  1397. if (OldParm->hasUninstantiatedDefaultArg()) {
  1398. Expr *Arg = OldParm->getUninstantiatedDefaultArg();
  1399. NewParm->setUninstantiatedDefaultArg(Arg);
  1400. } else if (OldParm->hasUnparsedDefaultArg()) {
  1401. NewParm->setUnparsedDefaultArg();
  1402. UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
  1403. } else if (Expr *Arg = OldParm->getDefaultArg())
  1404. // FIXME: if we non-lazily instantiated non-dependent default args for
  1405. // non-dependent parameter types we could remove a bunch of duplicate
  1406. // conversion warnings for such arguments.
  1407. NewParm->setUninstantiatedDefaultArg(Arg);
  1408. NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
  1409. if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
  1410. // Add the new parameter to the instantiated parameter pack.
  1411. CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
  1412. } else {
  1413. // Introduce an Old -> New mapping
  1414. CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
  1415. }
  1416. // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
  1417. // can be anything, is this right ?
  1418. NewParm->setDeclContext(CurContext);
  1419. NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
  1420. OldParm->getFunctionScopeIndex() + indexAdjustment);
  1421. return NewParm;
  1422. }
  1423. /// \brief Substitute the given template arguments into the given set of
  1424. /// parameters, producing the set of parameter types that would be generated
  1425. /// from such a substitution.
  1426. bool Sema::SubstParmTypes(SourceLocation Loc,
  1427. ParmVarDecl **Params, unsigned NumParams,
  1428. const MultiLevelTemplateArgumentList &TemplateArgs,
  1429. SmallVectorImpl<QualType> &ParamTypes,
  1430. SmallVectorImpl<ParmVarDecl *> *OutParams) {
  1431. assert(!ActiveTemplateInstantiations.empty() &&
  1432. "Cannot perform an instantiation without some context on the "
  1433. "instantiation stack");
  1434. TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
  1435. DeclarationName());
  1436. return Instantiator.TransformFunctionTypeParams(Loc, Params, NumParams, 0,
  1437. ParamTypes, OutParams);
  1438. }
  1439. /// \brief Perform substitution on the base class specifiers of the
  1440. /// given class template specialization.
  1441. ///
  1442. /// Produces a diagnostic and returns true on error, returns false and
  1443. /// attaches the instantiated base classes to the class template
  1444. /// specialization if successful.
  1445. bool
  1446. Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
  1447. CXXRecordDecl *Pattern,
  1448. const MultiLevelTemplateArgumentList &TemplateArgs) {
  1449. bool Invalid = false;
  1450. SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
  1451. for (ClassTemplateSpecializationDecl::base_class_iterator
  1452. Base = Pattern->bases_begin(), BaseEnd = Pattern->bases_end();
  1453. Base != BaseEnd; ++Base) {
  1454. if (!Base->getType()->isDependentType()) {
  1455. InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(*Base));
  1456. continue;
  1457. }
  1458. SourceLocation EllipsisLoc;
  1459. TypeSourceInfo *BaseTypeLoc;
  1460. if (Base->isPackExpansion()) {
  1461. // This is a pack expansion. See whether we should expand it now, or
  1462. // wait until later.
  1463. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  1464. collectUnexpandedParameterPacks(Base->getTypeSourceInfo()->getTypeLoc(),
  1465. Unexpanded);
  1466. bool ShouldExpand = false;
  1467. bool RetainExpansion = false;
  1468. llvm::Optional<unsigned> NumExpansions;
  1469. if (CheckParameterPacksForExpansion(Base->getEllipsisLoc(),
  1470. Base->getSourceRange(),
  1471. Unexpanded,
  1472. TemplateArgs, ShouldExpand,
  1473. RetainExpansion,
  1474. NumExpansions)) {
  1475. Invalid = true;
  1476. continue;
  1477. }
  1478. // If we should expand this pack expansion now, do so.
  1479. if (ShouldExpand) {
  1480. for (unsigned I = 0; I != *NumExpansions; ++I) {
  1481. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
  1482. TypeSourceInfo *BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
  1483. TemplateArgs,
  1484. Base->getSourceRange().getBegin(),
  1485. DeclarationName());
  1486. if (!BaseTypeLoc) {
  1487. Invalid = true;
  1488. continue;
  1489. }
  1490. if (CXXBaseSpecifier *InstantiatedBase
  1491. = CheckBaseSpecifier(Instantiation,
  1492. Base->getSourceRange(),
  1493. Base->isVirtual(),
  1494. Base->getAccessSpecifierAsWritten(),
  1495. BaseTypeLoc,
  1496. SourceLocation()))
  1497. InstantiatedBases.push_back(InstantiatedBase);
  1498. else
  1499. Invalid = true;
  1500. }
  1501. continue;
  1502. }
  1503. // The resulting base specifier will (still) be a pack expansion.
  1504. EllipsisLoc = Base->getEllipsisLoc();
  1505. Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
  1506. BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
  1507. TemplateArgs,
  1508. Base->getSourceRange().getBegin(),
  1509. DeclarationName());
  1510. } else {
  1511. BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
  1512. TemplateArgs,
  1513. Base->getSourceRange().getBegin(),
  1514. DeclarationName());
  1515. }
  1516. if (!BaseTypeLoc) {
  1517. Invalid = true;
  1518. continue;
  1519. }
  1520. if (CXXBaseSpecifier *InstantiatedBase
  1521. = CheckBaseSpecifier(Instantiation,
  1522. Base->getSourceRange(),
  1523. Base->isVirtual(),
  1524. Base->getAccessSpecifierAsWritten(),
  1525. BaseTypeLoc,
  1526. EllipsisLoc))
  1527. InstantiatedBases.push_back(InstantiatedBase);
  1528. else
  1529. Invalid = true;
  1530. }
  1531. if (!Invalid &&
  1532. AttachBaseSpecifiers(Instantiation, InstantiatedBases.data(),
  1533. InstantiatedBases.size()))
  1534. Invalid = true;
  1535. return Invalid;
  1536. }
  1537. // Defined via #include from SemaTemplateInstantiateDecl.cpp
  1538. namespace clang {
  1539. namespace sema {
  1540. Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
  1541. const MultiLevelTemplateArgumentList &TemplateArgs);
  1542. }
  1543. }
  1544. /// Determine whether we would be unable to instantiate this template (because
  1545. /// it either has no definition, or is in the process of being instantiated).
  1546. static bool DiagnoseUninstantiableTemplate(Sema &S,
  1547. SourceLocation PointOfInstantiation,
  1548. TagDecl *Instantiation,
  1549. bool InstantiatedFromMember,
  1550. TagDecl *Pattern,
  1551. TagDecl *PatternDef,
  1552. TemplateSpecializationKind TSK,
  1553. bool Complain = true) {
  1554. if (PatternDef && !PatternDef->isBeingDefined())
  1555. return false;
  1556. if (!Complain || (PatternDef && PatternDef->isInvalidDecl())) {
  1557. // Say nothing
  1558. } else if (PatternDef) {
  1559. assert(PatternDef->isBeingDefined());
  1560. S.Diag(PointOfInstantiation,
  1561. diag::err_template_instantiate_within_definition)
  1562. << (TSK != TSK_ImplicitInstantiation)
  1563. << S.Context.getTypeDeclType(Instantiation);
  1564. // Not much point in noting the template declaration here, since
  1565. // we're lexically inside it.
  1566. Instantiation->setInvalidDecl();
  1567. } else if (InstantiatedFromMember) {
  1568. S.Diag(PointOfInstantiation,
  1569. diag::err_implicit_instantiate_member_undefined)
  1570. << S.Context.getTypeDeclType(Instantiation);
  1571. S.Diag(Pattern->getLocation(), diag::note_member_of_template_here);
  1572. } else {
  1573. S.Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
  1574. << (TSK != TSK_ImplicitInstantiation)
  1575. << S.Context.getTypeDeclType(Instantiation);
  1576. S.Diag(Pattern->getLocation(), diag::note_template_decl_here);
  1577. }
  1578. // In general, Instantiation isn't marked invalid to get more than one
  1579. // error for multiple undefined instantiations. But the code that does
  1580. // explicit declaration -> explicit definition conversion can't handle
  1581. // invalid declarations, so mark as invalid in that case.
  1582. if (TSK == TSK_ExplicitInstantiationDeclaration)
  1583. Instantiation->setInvalidDecl();
  1584. return true;
  1585. }
  1586. /// \brief Instantiate the definition of a class from a given pattern.
  1587. ///
  1588. /// \param PointOfInstantiation The point of instantiation within the
  1589. /// source code.
  1590. ///
  1591. /// \param Instantiation is the declaration whose definition is being
  1592. /// instantiated. This will be either a class template specialization
  1593. /// or a member class of a class template specialization.
  1594. ///
  1595. /// \param Pattern is the pattern from which the instantiation
  1596. /// occurs. This will be either the declaration of a class template or
  1597. /// the declaration of a member class of a class template.
  1598. ///
  1599. /// \param TemplateArgs The template arguments to be substituted into
  1600. /// the pattern.
  1601. ///
  1602. /// \param TSK the kind of implicit or explicit instantiation to perform.
  1603. ///
  1604. /// \param Complain whether to complain if the class cannot be instantiated due
  1605. /// to the lack of a definition.
  1606. ///
  1607. /// \returns true if an error occurred, false otherwise.
  1608. bool
  1609. Sema::InstantiateClass(SourceLocation PointOfInstantiation,
  1610. CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
  1611. const MultiLevelTemplateArgumentList &TemplateArgs,
  1612. TemplateSpecializationKind TSK,
  1613. bool Complain) {
  1614. CXXRecordDecl *PatternDef
  1615. = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
  1616. if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
  1617. Instantiation->getInstantiatedFromMemberClass(),
  1618. Pattern, PatternDef, TSK, Complain))
  1619. return true;
  1620. Pattern = PatternDef;
  1621. // \brief Record the point of instantiation.
  1622. if (MemberSpecializationInfo *MSInfo
  1623. = Instantiation->getMemberSpecializationInfo()) {
  1624. MSInfo->setTemplateSpecializationKind(TSK);
  1625. MSInfo->setPointOfInstantiation(PointOfInstantiation);
  1626. } else if (ClassTemplateSpecializationDecl *Spec
  1627. = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
  1628. Spec->setTemplateSpecializationKind(TSK);
  1629. Spec->setPointOfInstantiation(PointOfInstantiation);
  1630. }
  1631. InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
  1632. if (Inst)
  1633. return true;
  1634. // Enter the scope of this instantiation. We don't use
  1635. // PushDeclContext because we don't have a scope.
  1636. ContextRAII SavedContext(*this, Instantiation);
  1637. EnterExpressionEvaluationContext EvalContext(*this,
  1638. Sema::PotentiallyEvaluated);
  1639. // If this is an instantiation of a local class, merge this local
  1640. // instantiation scope with the enclosing scope. Otherwise, every
  1641. // instantiation of a class has its own local instantiation scope.
  1642. bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
  1643. LocalInstantiationScope Scope(*this, MergeWithParentScope);
  1644. // Pull attributes from the pattern onto the instantiation.
  1645. InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
  1646. // Start the definition of this instantiation.
  1647. Instantiation->startDefinition();
  1648. Instantiation->setTagKind(Pattern->getTagKind());
  1649. // Do substitution on the base class specifiers.
  1650. if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
  1651. Instantiation->setInvalidDecl();
  1652. TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
  1653. SmallVector<Decl*, 4> Fields;
  1654. SmallVector<std::pair<FieldDecl*, FieldDecl*>, 4>
  1655. FieldsWithMemberInitializers;
  1656. // Delay instantiation of late parsed attributes.
  1657. LateInstantiatedAttrVec LateAttrs;
  1658. Instantiator.enableLateAttributeInstantiation(&LateAttrs);
  1659. for (RecordDecl::decl_iterator Member = Pattern->decls_begin(),
  1660. MemberEnd = Pattern->decls_end();
  1661. Member != MemberEnd; ++Member) {
  1662. // Don't instantiate members not belonging in this semantic context.
  1663. // e.g. for:
  1664. // @code
  1665. // template <int i> class A {
  1666. // class B *g;
  1667. // };
  1668. // @endcode
  1669. // 'class B' has the template as lexical context but semantically it is
  1670. // introduced in namespace scope.
  1671. if ((*Member)->getDeclContext() != Pattern)
  1672. continue;
  1673. if ((*Member)->isInvalidDecl()) {
  1674. Instantiation->setInvalidDecl();
  1675. continue;
  1676. }
  1677. Decl *NewMember = Instantiator.Visit(*Member);
  1678. if (NewMember) {
  1679. if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
  1680. Fields.push_back(Field);
  1681. FieldDecl *OldField = cast<FieldDecl>(*Member);
  1682. if (OldField->getInClassInitializer())
  1683. FieldsWithMemberInitializers.push_back(std::make_pair(OldField,
  1684. Field));
  1685. } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
  1686. // C++11 [temp.inst]p1: The implicit instantiation of a class template
  1687. // specialization causes the implicit instantiation of the definitions
  1688. // of unscoped member enumerations.
  1689. // Record a point of instantiation for this implicit instantiation.
  1690. if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
  1691. Enum->isCompleteDefinition()) {
  1692. MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
  1693. assert(MSInfo && "no spec info for member enum specialization");
  1694. MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
  1695. MSInfo->setPointOfInstantiation(PointOfInstantiation);
  1696. }
  1697. } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
  1698. if (SA->isFailed()) {
  1699. // A static_assert failed. Bail out; instantiating this
  1700. // class is probably not meaningful.
  1701. Instantiation->setInvalidDecl();
  1702. break;
  1703. }
  1704. }
  1705. if (NewMember->isInvalidDecl())
  1706. Instantiation->setInvalidDecl();
  1707. } else {
  1708. // FIXME: Eventually, a NULL return will mean that one of the
  1709. // instantiations was a semantic disaster, and we'll want to mark the
  1710. // declaration invalid.
  1711. // For now, we expect to skip some members that we can't yet handle.
  1712. }
  1713. }
  1714. // Finish checking fields.
  1715. ActOnFields(0, Instantiation->getLocation(), Instantiation, Fields,
  1716. SourceLocation(), SourceLocation(), 0);
  1717. CheckCompletedCXXClass(Instantiation);
  1718. // Attach any in-class member initializers now the class is complete.
  1719. if (!FieldsWithMemberInitializers.empty()) {
  1720. // C++11 [expr.prim.general]p4:
  1721. // Otherwise, if a member-declarator declares a non-static data member
  1722. // (9.2) of a class X, the expression this is a prvalue of type "pointer
  1723. // to X" within the optional brace-or-equal-initializer. It shall not
  1724. // appear elsewhere in the member-declarator.
  1725. CXXThisScopeRAII ThisScope(*this, Instantiation, (unsigned)0);
  1726. for (unsigned I = 0, N = FieldsWithMemberInitializers.size(); I != N; ++I) {
  1727. FieldDecl *OldField = FieldsWithMemberInitializers[I].first;
  1728. FieldDecl *NewField = FieldsWithMemberInitializers[I].second;
  1729. Expr *OldInit = OldField->getInClassInitializer();
  1730. ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
  1731. /*CXXDirectInit=*/false);
  1732. if (NewInit.isInvalid())
  1733. NewField->setInvalidDecl();
  1734. else {
  1735. Expr *Init = NewInit.take();
  1736. assert(Init && "no-argument initializer in class");
  1737. assert(!isa<ParenListExpr>(Init) && "call-style init in class");
  1738. ActOnCXXInClassMemberInitializer(NewField, Init->getLocStart(), Init);
  1739. }
  1740. }
  1741. }
  1742. // Instantiate late parsed attributes, and attach them to their decls.
  1743. // See Sema::InstantiateAttrs
  1744. for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
  1745. E = LateAttrs.end(); I != E; ++I) {
  1746. assert(CurrentInstantiationScope == Instantiator.getStartingScope());
  1747. CurrentInstantiationScope = I->Scope;
  1748. Attr *NewAttr =
  1749. instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
  1750. I->NewDecl->addAttr(NewAttr);
  1751. LocalInstantiationScope::deleteScopes(I->Scope,
  1752. Instantiator.getStartingScope());
  1753. }
  1754. Instantiator.disableLateAttributeInstantiation();
  1755. LateAttrs.clear();
  1756. ActOnFinishDelayedMemberInitializers(Instantiation);
  1757. if (TSK == TSK_ImplicitInstantiation) {
  1758. Instantiation->setLocation(Pattern->getLocation());
  1759. Instantiation->setLocStart(Pattern->getInnerLocStart());
  1760. Instantiation->setRBraceLoc(Pattern->getRBraceLoc());
  1761. }
  1762. if (!Instantiation->isInvalidDecl()) {
  1763. // Perform any dependent diagnostics from the pattern.
  1764. PerformDependentDiagnostics(Pattern, TemplateArgs);
  1765. // Instantiate any out-of-line class template partial
  1766. // specializations now.
  1767. for (TemplateDeclInstantiator::delayed_partial_spec_iterator
  1768. P = Instantiator.delayed_partial_spec_begin(),
  1769. PEnd = Instantiator.delayed_partial_spec_end();
  1770. P != PEnd; ++P) {
  1771. if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
  1772. P->first,
  1773. P->second)) {
  1774. Instantiation->setInvalidDecl();
  1775. break;
  1776. }
  1777. }
  1778. }
  1779. // Exit the scope of this instantiation.
  1780. SavedContext.pop();
  1781. if (!Instantiation->isInvalidDecl()) {
  1782. Consumer.HandleTagDeclDefinition(Instantiation);
  1783. // Always emit the vtable for an explicit instantiation definition
  1784. // of a polymorphic class template specialization.
  1785. if (TSK == TSK_ExplicitInstantiationDefinition)
  1786. MarkVTableUsed(PointOfInstantiation, Instantiation, true);
  1787. }
  1788. return Instantiation->isInvalidDecl();
  1789. }
  1790. /// \brief Instantiate the definition of an enum from a given pattern.
  1791. ///
  1792. /// \param PointOfInstantiation The point of instantiation within the
  1793. /// source code.
  1794. /// \param Instantiation is the declaration whose definition is being
  1795. /// instantiated. This will be a member enumeration of a class
  1796. /// temploid specialization, or a local enumeration within a
  1797. /// function temploid specialization.
  1798. /// \param Pattern The templated declaration from which the instantiation
  1799. /// occurs.
  1800. /// \param TemplateArgs The template arguments to be substituted into
  1801. /// the pattern.
  1802. /// \param TSK The kind of implicit or explicit instantiation to perform.
  1803. ///
  1804. /// \return \c true if an error occurred, \c false otherwise.
  1805. bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
  1806. EnumDecl *Instantiation, EnumDecl *Pattern,
  1807. const MultiLevelTemplateArgumentList &TemplateArgs,
  1808. TemplateSpecializationKind TSK) {
  1809. EnumDecl *PatternDef = Pattern->getDefinition();
  1810. if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
  1811. Instantiation->getInstantiatedFromMemberEnum(),
  1812. Pattern, PatternDef, TSK,/*Complain*/true))
  1813. return true;
  1814. Pattern = PatternDef;
  1815. // Record the point of instantiation.
  1816. if (MemberSpecializationInfo *MSInfo
  1817. = Instantiation->getMemberSpecializationInfo()) {
  1818. MSInfo->setTemplateSpecializationKind(TSK);
  1819. MSInfo->setPointOfInstantiation(PointOfInstantiation);
  1820. }
  1821. InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
  1822. if (Inst)
  1823. return true;
  1824. // Enter the scope of this instantiation. We don't use
  1825. // PushDeclContext because we don't have a scope.
  1826. ContextRAII SavedContext(*this, Instantiation);
  1827. EnterExpressionEvaluationContext EvalContext(*this,
  1828. Sema::PotentiallyEvaluated);
  1829. LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
  1830. // Pull attributes from the pattern onto the instantiation.
  1831. InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
  1832. TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
  1833. Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
  1834. // Exit the scope of this instantiation.
  1835. SavedContext.pop();
  1836. return Instantiation->isInvalidDecl();
  1837. }
  1838. namespace {
  1839. /// \brief A partial specialization whose template arguments have matched
  1840. /// a given template-id.
  1841. struct PartialSpecMatchResult {
  1842. ClassTemplatePartialSpecializationDecl *Partial;
  1843. TemplateArgumentList *Args;
  1844. };
  1845. }
  1846. bool
  1847. Sema::InstantiateClassTemplateSpecialization(
  1848. SourceLocation PointOfInstantiation,
  1849. ClassTemplateSpecializationDecl *ClassTemplateSpec,
  1850. TemplateSpecializationKind TSK,
  1851. bool Complain) {
  1852. // Perform the actual instantiation on the canonical declaration.
  1853. ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
  1854. ClassTemplateSpec->getCanonicalDecl());
  1855. // Check whether we have already instantiated or specialized this class
  1856. // template specialization.
  1857. if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared) {
  1858. if (ClassTemplateSpec->getSpecializationKind() ==
  1859. TSK_ExplicitInstantiationDeclaration &&
  1860. TSK == TSK_ExplicitInstantiationDefinition) {
  1861. // An explicit instantiation definition follows an explicit instantiation
  1862. // declaration (C++0x [temp.explicit]p10); go ahead and perform the
  1863. // explicit instantiation.
  1864. ClassTemplateSpec->setSpecializationKind(TSK);
  1865. // If this is an explicit instantiation definition, mark the
  1866. // vtable as used.
  1867. if (TSK == TSK_ExplicitInstantiationDefinition &&
  1868. !ClassTemplateSpec->isInvalidDecl())
  1869. MarkVTableUsed(PointOfInstantiation, ClassTemplateSpec, true);
  1870. return false;
  1871. }
  1872. // We can only instantiate something that hasn't already been
  1873. // instantiated or specialized. Fail without any diagnostics: our
  1874. // caller will provide an error message.
  1875. return true;
  1876. }
  1877. if (ClassTemplateSpec->isInvalidDecl())
  1878. return true;
  1879. ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
  1880. CXXRecordDecl *Pattern = 0;
  1881. // C++ [temp.class.spec.match]p1:
  1882. // When a class template is used in a context that requires an
  1883. // instantiation of the class, it is necessary to determine
  1884. // whether the instantiation is to be generated using the primary
  1885. // template or one of the partial specializations. This is done by
  1886. // matching the template arguments of the class template
  1887. // specialization with the template argument lists of the partial
  1888. // specializations.
  1889. typedef PartialSpecMatchResult MatchResult;
  1890. SmallVector<MatchResult, 4> Matched;
  1891. SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
  1892. Template->getPartialSpecializations(PartialSpecs);
  1893. for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
  1894. ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
  1895. TemplateDeductionInfo Info(Context, PointOfInstantiation);
  1896. if (TemplateDeductionResult Result
  1897. = DeduceTemplateArguments(Partial,
  1898. ClassTemplateSpec->getTemplateArgs(),
  1899. Info)) {
  1900. // FIXME: Store the failed-deduction information for use in
  1901. // diagnostics, later.
  1902. (void)Result;
  1903. } else {
  1904. Matched.push_back(PartialSpecMatchResult());
  1905. Matched.back().Partial = Partial;
  1906. Matched.back().Args = Info.take();
  1907. }
  1908. }
  1909. // If we're dealing with a member template where the template parameters
  1910. // have been instantiated, this provides the original template parameters
  1911. // from which the member template's parameters were instantiated.
  1912. SmallVector<const NamedDecl *, 4> InstantiatedTemplateParameters;
  1913. if (Matched.size() >= 1) {
  1914. SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
  1915. if (Matched.size() == 1) {
  1916. // -- If exactly one matching specialization is found, the
  1917. // instantiation is generated from that specialization.
  1918. // We don't need to do anything for this.
  1919. } else {
  1920. // -- If more than one matching specialization is found, the
  1921. // partial order rules (14.5.4.2) are used to determine
  1922. // whether one of the specializations is more specialized
  1923. // than the others. If none of the specializations is more
  1924. // specialized than all of the other matching
  1925. // specializations, then the use of the class template is
  1926. // ambiguous and the program is ill-formed.
  1927. for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
  1928. PEnd = Matched.end();
  1929. P != PEnd; ++P) {
  1930. if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
  1931. PointOfInstantiation)
  1932. == P->Partial)
  1933. Best = P;
  1934. }
  1935. // Determine if the best partial specialization is more specialized than
  1936. // the others.
  1937. bool Ambiguous = false;
  1938. for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
  1939. PEnd = Matched.end();
  1940. P != PEnd; ++P) {
  1941. if (P != Best &&
  1942. getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
  1943. PointOfInstantiation)
  1944. != Best->Partial) {
  1945. Ambiguous = true;
  1946. break;
  1947. }
  1948. }
  1949. if (Ambiguous) {
  1950. // Partial ordering did not produce a clear winner. Complain.
  1951. ClassTemplateSpec->setInvalidDecl();
  1952. Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
  1953. << ClassTemplateSpec;
  1954. // Print the matching partial specializations.
  1955. for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
  1956. PEnd = Matched.end();
  1957. P != PEnd; ++P)
  1958. Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
  1959. << getTemplateArgumentBindingsText(
  1960. P->Partial->getTemplateParameters(),
  1961. *P->Args);
  1962. return true;
  1963. }
  1964. }
  1965. // Instantiate using the best class template partial specialization.
  1966. ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->Partial;
  1967. while (OrigPartialSpec->getInstantiatedFromMember()) {
  1968. // If we've found an explicit specialization of this class template,
  1969. // stop here and use that as the pattern.
  1970. if (OrigPartialSpec->isMemberSpecialization())
  1971. break;
  1972. OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember();
  1973. }
  1974. Pattern = OrigPartialSpec;
  1975. ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
  1976. } else {
  1977. // -- If no matches are found, the instantiation is generated
  1978. // from the primary template.
  1979. ClassTemplateDecl *OrigTemplate = Template;
  1980. while (OrigTemplate->getInstantiatedFromMemberTemplate()) {
  1981. // If we've found an explicit specialization of this class template,
  1982. // stop here and use that as the pattern.
  1983. if (OrigTemplate->isMemberSpecialization())
  1984. break;
  1985. OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
  1986. }
  1987. Pattern = OrigTemplate->getTemplatedDecl();
  1988. }
  1989. bool Result = InstantiateClass(PointOfInstantiation, ClassTemplateSpec,
  1990. Pattern,
  1991. getTemplateInstantiationArgs(ClassTemplateSpec),
  1992. TSK,
  1993. Complain);
  1994. return Result;
  1995. }
  1996. /// \brief Instantiates the definitions of all of the member
  1997. /// of the given class, which is an instantiation of a class template
  1998. /// or a member class of a template.
  1999. void
  2000. Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
  2001. CXXRecordDecl *Instantiation,
  2002. const MultiLevelTemplateArgumentList &TemplateArgs,
  2003. TemplateSpecializationKind TSK) {
  2004. for (DeclContext::decl_iterator D = Instantiation->decls_begin(),
  2005. DEnd = Instantiation->decls_end();
  2006. D != DEnd; ++D) {
  2007. bool SuppressNew = false;
  2008. if (FunctionDecl *Function = dyn_cast<FunctionDecl>(*D)) {
  2009. if (FunctionDecl *Pattern
  2010. = Function->getInstantiatedFromMemberFunction()) {
  2011. MemberSpecializationInfo *MSInfo
  2012. = Function->getMemberSpecializationInfo();
  2013. assert(MSInfo && "No member specialization information?");
  2014. if (MSInfo->getTemplateSpecializationKind()
  2015. == TSK_ExplicitSpecialization)
  2016. continue;
  2017. if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
  2018. Function,
  2019. MSInfo->getTemplateSpecializationKind(),
  2020. MSInfo->getPointOfInstantiation(),
  2021. SuppressNew) ||
  2022. SuppressNew)
  2023. continue;
  2024. if (Function->isDefined())
  2025. continue;
  2026. if (TSK == TSK_ExplicitInstantiationDefinition) {
  2027. // C++0x [temp.explicit]p8:
  2028. // An explicit instantiation definition that names a class template
  2029. // specialization explicitly instantiates the class template
  2030. // specialization and is only an explicit instantiation definition
  2031. // of members whose definition is visible at the point of
  2032. // instantiation.
  2033. if (!Pattern->isDefined())
  2034. continue;
  2035. Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
  2036. InstantiateFunctionDefinition(PointOfInstantiation, Function);
  2037. } else {
  2038. Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
  2039. }
  2040. }
  2041. } else if (VarDecl *Var = dyn_cast<VarDecl>(*D)) {
  2042. if (Var->isStaticDataMember()) {
  2043. MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
  2044. assert(MSInfo && "No member specialization information?");
  2045. if (MSInfo->getTemplateSpecializationKind()
  2046. == TSK_ExplicitSpecialization)
  2047. continue;
  2048. if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
  2049. Var,
  2050. MSInfo->getTemplateSpecializationKind(),
  2051. MSInfo->getPointOfInstantiation(),
  2052. SuppressNew) ||
  2053. SuppressNew)
  2054. continue;
  2055. if (TSK == TSK_ExplicitInstantiationDefinition) {
  2056. // C++0x [temp.explicit]p8:
  2057. // An explicit instantiation definition that names a class template
  2058. // specialization explicitly instantiates the class template
  2059. // specialization and is only an explicit instantiation definition
  2060. // of members whose definition is visible at the point of
  2061. // instantiation.
  2062. if (!Var->getInstantiatedFromStaticDataMember()
  2063. ->getOutOfLineDefinition())
  2064. continue;
  2065. Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
  2066. InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
  2067. } else {
  2068. Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
  2069. }
  2070. }
  2071. } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(*D)) {
  2072. // Always skip the injected-class-name, along with any
  2073. // redeclarations of nested classes, since both would cause us
  2074. // to try to instantiate the members of a class twice.
  2075. if (Record->isInjectedClassName() || Record->getPreviousDecl())
  2076. continue;
  2077. MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
  2078. assert(MSInfo && "No member specialization information?");
  2079. if (MSInfo->getTemplateSpecializationKind()
  2080. == TSK_ExplicitSpecialization)
  2081. continue;
  2082. if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
  2083. Record,
  2084. MSInfo->getTemplateSpecializationKind(),
  2085. MSInfo->getPointOfInstantiation(),
  2086. SuppressNew) ||
  2087. SuppressNew)
  2088. continue;
  2089. CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
  2090. assert(Pattern && "Missing instantiated-from-template information");
  2091. if (!Record->getDefinition()) {
  2092. if (!Pattern->getDefinition()) {
  2093. // C++0x [temp.explicit]p8:
  2094. // An explicit instantiation definition that names a class template
  2095. // specialization explicitly instantiates the class template
  2096. // specialization and is only an explicit instantiation definition
  2097. // of members whose definition is visible at the point of
  2098. // instantiation.
  2099. if (TSK == TSK_ExplicitInstantiationDeclaration) {
  2100. MSInfo->setTemplateSpecializationKind(TSK);
  2101. MSInfo->setPointOfInstantiation(PointOfInstantiation);
  2102. }
  2103. continue;
  2104. }
  2105. InstantiateClass(PointOfInstantiation, Record, Pattern,
  2106. TemplateArgs,
  2107. TSK);
  2108. } else {
  2109. if (TSK == TSK_ExplicitInstantiationDefinition &&
  2110. Record->getTemplateSpecializationKind() ==
  2111. TSK_ExplicitInstantiationDeclaration) {
  2112. Record->setTemplateSpecializationKind(TSK);
  2113. MarkVTableUsed(PointOfInstantiation, Record, true);
  2114. }
  2115. }
  2116. Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
  2117. if (Pattern)
  2118. InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
  2119. TSK);
  2120. } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(*D)) {
  2121. MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
  2122. assert(MSInfo && "No member specialization information?");
  2123. if (MSInfo->getTemplateSpecializationKind()
  2124. == TSK_ExplicitSpecialization)
  2125. continue;
  2126. if (CheckSpecializationInstantiationRedecl(
  2127. PointOfInstantiation, TSK, Enum,
  2128. MSInfo->getTemplateSpecializationKind(),
  2129. MSInfo->getPointOfInstantiation(), SuppressNew) ||
  2130. SuppressNew)
  2131. continue;
  2132. if (Enum->getDefinition())
  2133. continue;
  2134. EnumDecl *Pattern = Enum->getInstantiatedFromMemberEnum();
  2135. assert(Pattern && "Missing instantiated-from-template information");
  2136. if (TSK == TSK_ExplicitInstantiationDefinition) {
  2137. if (!Pattern->getDefinition())
  2138. continue;
  2139. InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
  2140. } else {
  2141. MSInfo->setTemplateSpecializationKind(TSK);
  2142. MSInfo->setPointOfInstantiation(PointOfInstantiation);
  2143. }
  2144. }
  2145. }
  2146. }
  2147. /// \brief Instantiate the definitions of all of the members of the
  2148. /// given class template specialization, which was named as part of an
  2149. /// explicit instantiation.
  2150. void
  2151. Sema::InstantiateClassTemplateSpecializationMembers(
  2152. SourceLocation PointOfInstantiation,
  2153. ClassTemplateSpecializationDecl *ClassTemplateSpec,
  2154. TemplateSpecializationKind TSK) {
  2155. // C++0x [temp.explicit]p7:
  2156. // An explicit instantiation that names a class template
  2157. // specialization is an explicit instantion of the same kind
  2158. // (declaration or definition) of each of its members (not
  2159. // including members inherited from base classes) that has not
  2160. // been previously explicitly specialized in the translation unit
  2161. // containing the explicit instantiation, except as described
  2162. // below.
  2163. InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
  2164. getTemplateInstantiationArgs(ClassTemplateSpec),
  2165. TSK);
  2166. }
  2167. StmtResult
  2168. Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
  2169. if (!S)
  2170. return Owned(S);
  2171. TemplateInstantiator Instantiator(*this, TemplateArgs,
  2172. SourceLocation(),
  2173. DeclarationName());
  2174. return Instantiator.TransformStmt(S);
  2175. }
  2176. ExprResult
  2177. Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
  2178. if (!E)
  2179. return Owned(E);
  2180. TemplateInstantiator Instantiator(*this, TemplateArgs,
  2181. SourceLocation(),
  2182. DeclarationName());
  2183. return Instantiator.TransformExpr(E);
  2184. }
  2185. bool Sema::SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
  2186. const MultiLevelTemplateArgumentList &TemplateArgs,
  2187. SmallVectorImpl<Expr *> &Outputs) {
  2188. if (NumExprs == 0)
  2189. return false;
  2190. TemplateInstantiator Instantiator(*this, TemplateArgs,
  2191. SourceLocation(),
  2192. DeclarationName());
  2193. return Instantiator.TransformExprs(Exprs, NumExprs, IsCall, Outputs);
  2194. }
  2195. NestedNameSpecifierLoc
  2196. Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
  2197. const MultiLevelTemplateArgumentList &TemplateArgs) {
  2198. if (!NNS)
  2199. return NestedNameSpecifierLoc();
  2200. TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
  2201. DeclarationName());
  2202. return Instantiator.TransformNestedNameSpecifierLoc(NNS);
  2203. }
  2204. /// \brief Do template substitution on declaration name info.
  2205. DeclarationNameInfo
  2206. Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
  2207. const MultiLevelTemplateArgumentList &TemplateArgs) {
  2208. TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
  2209. NameInfo.getName());
  2210. return Instantiator.TransformDeclarationNameInfo(NameInfo);
  2211. }
  2212. TemplateName
  2213. Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
  2214. TemplateName Name, SourceLocation Loc,
  2215. const MultiLevelTemplateArgumentList &TemplateArgs) {
  2216. TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
  2217. DeclarationName());
  2218. CXXScopeSpec SS;
  2219. SS.Adopt(QualifierLoc);
  2220. return Instantiator.TransformTemplateName(SS, Name, Loc);
  2221. }
  2222. bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
  2223. TemplateArgumentListInfo &Result,
  2224. const MultiLevelTemplateArgumentList &TemplateArgs) {
  2225. TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
  2226. DeclarationName());
  2227. return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
  2228. }
  2229. llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
  2230. LocalInstantiationScope::findInstantiationOf(const Decl *D) {
  2231. for (LocalInstantiationScope *Current = this; Current;
  2232. Current = Current->Outer) {
  2233. // Check if we found something within this scope.
  2234. const Decl *CheckD = D;
  2235. do {
  2236. LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
  2237. if (Found != Current->LocalDecls.end())
  2238. return &Found->second;
  2239. // If this is a tag declaration, it's possible that we need to look for
  2240. // a previous declaration.
  2241. if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
  2242. CheckD = Tag->getPreviousDecl();
  2243. else
  2244. CheckD = 0;
  2245. } while (CheckD);
  2246. // If we aren't combined with our outer scope, we're done.
  2247. if (!Current->CombineWithOuterScope)
  2248. break;
  2249. }
  2250. // If we didn't find the decl, then we either have a sema bug, or we have a
  2251. // forward reference to a label declaration. Return null to indicate that
  2252. // we have an uninstantiated label.
  2253. assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
  2254. return 0;
  2255. }
  2256. void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
  2257. llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
  2258. if (Stored.isNull())
  2259. Stored = Inst;
  2260. else if (Stored.is<Decl *>()) {
  2261. assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
  2262. Stored = Inst;
  2263. } else
  2264. LocalDecls[D].get<DeclArgumentPack *>()->push_back(Inst);
  2265. }
  2266. void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
  2267. Decl *Inst) {
  2268. DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
  2269. Pack->push_back(Inst);
  2270. }
  2271. void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
  2272. llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
  2273. assert(Stored.isNull() && "Already instantiated this local");
  2274. DeclArgumentPack *Pack = new DeclArgumentPack;
  2275. Stored = Pack;
  2276. ArgumentPacks.push_back(Pack);
  2277. }
  2278. void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
  2279. const TemplateArgument *ExplicitArgs,
  2280. unsigned NumExplicitArgs) {
  2281. assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
  2282. "Already have a partially-substituted pack");
  2283. assert((!PartiallySubstitutedPack
  2284. || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
  2285. "Wrong number of arguments in partially-substituted pack");
  2286. PartiallySubstitutedPack = Pack;
  2287. ArgsInPartiallySubstitutedPack = ExplicitArgs;
  2288. NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
  2289. }
  2290. NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
  2291. const TemplateArgument **ExplicitArgs,
  2292. unsigned *NumExplicitArgs) const {
  2293. if (ExplicitArgs)
  2294. *ExplicitArgs = 0;
  2295. if (NumExplicitArgs)
  2296. *NumExplicitArgs = 0;
  2297. for (const LocalInstantiationScope *Current = this; Current;
  2298. Current = Current->Outer) {
  2299. if (Current->PartiallySubstitutedPack) {
  2300. if (ExplicitArgs)
  2301. *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
  2302. if (NumExplicitArgs)
  2303. *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
  2304. return Current->PartiallySubstitutedPack;
  2305. }
  2306. if (!Current->CombineWithOuterScope)
  2307. break;
  2308. }
  2309. return 0;
  2310. }