blob: 18b6829744f00b7afd1d62c5ff439812ec54b6ba [file] [log] [blame]
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001//===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl Instantiation ===/
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//===----------------------------------------------------------------------===/
8//
9// This file implements C++ template instantiation for declarations.
10//
11//===----------------------------------------------------------------------===/
12#include "Sema.h"
John McCall7d384dd2009-11-18 07:57:50 +000013#include "Lookup.h"
Douglas Gregoraba43bb2009-05-26 20:50:29 +000014#include "clang/AST/ASTConsumer.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000015#include "clang/AST/ASTContext.h"
16#include "clang/AST/DeclTemplate.h"
17#include "clang/AST/DeclVisitor.h"
John McCall0c01d182010-03-24 05:22:00 +000018#include "clang/AST/DependentDiagnostic.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000019#include "clang/AST/Expr.h"
Douglas Gregora88cfbf2009-12-12 18:16:41 +000020#include "clang/AST/ExprCXX.h"
John McCall21ef0fa2010-03-11 09:03:00 +000021#include "clang/AST/TypeLoc.h"
Anders Carlssonc17fb7b2009-09-01 05:12:24 +000022#include "clang/Basic/PrettyStackTrace.h"
Douglas Gregor83ddad32009-08-26 21:14:46 +000023#include "clang/Lex/Preprocessor.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000024
25using namespace clang;
26
27namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +000028 class TemplateDeclInstantiator
Chris Lattnerb28317a2009-03-28 19:18:32 +000029 : public DeclVisitor<TemplateDeclInstantiator, Decl *> {
Douglas Gregor8dbc2692009-03-17 21:15:40 +000030 Sema &SemaRef;
31 DeclContext *Owner;
Douglas Gregord6350ae2009-08-28 20:31:08 +000032 const MultiLevelTemplateArgumentList &TemplateArgs;
Mike Stump1eb44332009-09-09 15:08:12 +000033
Anders Carlssond8fe2d52009-11-07 06:07:58 +000034 void InstantiateAttrs(Decl *Tmpl, Decl *New);
35
Douglas Gregor8dbc2692009-03-17 21:15:40 +000036 public:
37 typedef Sema::OwningExprResult OwningExprResult;
38
39 TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +000040 const MultiLevelTemplateArgumentList &TemplateArgs)
Douglas Gregor7e063902009-05-11 23:53:27 +000041 : SemaRef(SemaRef), Owner(Owner), TemplateArgs(TemplateArgs) { }
Mike Stump1eb44332009-09-09 15:08:12 +000042
Mike Stump390b4cc2009-05-16 07:39:55 +000043 // FIXME: Once we get closer to completion, replace these manually-written
44 // declarations with automatically-generated ones from
45 // clang/AST/DeclNodes.def.
Douglas Gregor4f722be2009-03-25 15:45:12 +000046 Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
47 Decl *VisitNamespaceDecl(NamespaceDecl *D);
John McCall3dbd3d52010-02-16 06:53:13 +000048 Decl *VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000049 Decl *VisitTypedefDecl(TypedefDecl *D);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +000050 Decl *VisitVarDecl(VarDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000051 Decl *VisitFieldDecl(FieldDecl *D);
52 Decl *VisitStaticAssertDecl(StaticAssertDecl *D);
53 Decl *VisitEnumDecl(EnumDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000054 Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
John McCall02cace72009-08-28 07:59:38 +000055 Decl *VisitFriendDecl(FriendDecl *D);
Douglas Gregora735b202009-10-13 14:39:41 +000056 Decl *VisitFunctionDecl(FunctionDecl *D,
57 TemplateParameterList *TemplateParams = 0);
Douglas Gregord475b8d2009-03-25 21:17:03 +000058 Decl *VisitCXXRecordDecl(CXXRecordDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000059 Decl *VisitCXXMethodDecl(CXXMethodDecl *D,
60 TemplateParameterList *TemplateParams = 0);
Douglas Gregor615c5d42009-03-24 16:43:20 +000061 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
Douglas Gregor03b2b072009-03-24 00:15:49 +000062 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +000063 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000064 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000065 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +000066 Decl *VisitClassTemplatePartialSpecializationDecl(
67 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000068 Decl *VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000069 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Douglas Gregor33642df2009-10-23 23:25:44 +000070 Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregor9106ef72009-11-11 16:58:32 +000071 Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Douglas Gregor48c32a72009-11-17 06:07:40 +000072 Decl *VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
John McCalled976492009-12-04 22:46:56 +000073 Decl *VisitUsingDecl(UsingDecl *D);
74 Decl *VisitUsingShadowDecl(UsingShadowDecl *D);
John McCall7ba107a2009-11-18 02:36:19 +000075 Decl *VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
76 Decl *VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Mike Stump1eb44332009-09-09 15:08:12 +000077
Douglas Gregor8dbc2692009-03-17 21:15:40 +000078 // Base case. FIXME: Remove once we can instantiate everything.
Douglas Gregor48c32a72009-11-17 06:07:40 +000079 Decl *VisitDecl(Decl *D) {
80 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
81 Diagnostic::Error,
82 "cannot instantiate %0 yet");
83 SemaRef.Diag(D->getLocation(), DiagID)
84 << D->getDeclKindName();
85
Douglas Gregor8dbc2692009-03-17 21:15:40 +000086 return 0;
87 }
Douglas Gregor5545e162009-03-24 00:38:23 +000088
John McCallfd810b12009-08-14 02:03:10 +000089 const LangOptions &getLangOptions() {
90 return SemaRef.getLangOptions();
91 }
92
Douglas Gregor5545e162009-03-24 00:38:23 +000093 // Helper functions for instantiating methods.
John McCall21ef0fa2010-03-11 09:03:00 +000094 TypeSourceInfo *SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +000095 llvm::SmallVectorImpl<ParmVarDecl *> &Params);
Douglas Gregore53060f2009-06-25 22:08:12 +000096 bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl);
Douglas Gregor5545e162009-03-24 00:38:23 +000097 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
John McCalle29ba202009-08-20 01:44:21 +000098
99 TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +0000100 SubstTemplateParams(TemplateParameterList *List);
John McCallb6217662010-03-15 10:12:16 +0000101
102 bool SubstQualifier(const DeclaratorDecl *OldDecl,
103 DeclaratorDecl *NewDecl);
104 bool SubstQualifier(const TagDecl *OldDecl,
105 TagDecl *NewDecl);
Douglas Gregored9c0f92009-10-29 00:04:11 +0000106
107 bool InstantiateClassTemplatePartialSpecialization(
108 ClassTemplateDecl *ClassTemplate,
109 ClassTemplatePartialSpecializationDecl *PartialSpec);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000110 };
111}
112
John McCallb6217662010-03-15 10:12:16 +0000113bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
114 DeclaratorDecl *NewDecl) {
115 NestedNameSpecifier *OldQual = OldDecl->getQualifier();
116 if (!OldQual) return false;
117
118 SourceRange QualRange = OldDecl->getQualifierRange();
119
120 NestedNameSpecifier *NewQual
121 = SemaRef.SubstNestedNameSpecifier(OldQual, QualRange, TemplateArgs);
122 if (!NewQual)
123 return true;
124
125 NewDecl->setQualifierInfo(NewQual, QualRange);
126 return false;
127}
128
129bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
130 TagDecl *NewDecl) {
131 NestedNameSpecifier *OldQual = OldDecl->getQualifier();
132 if (!OldQual) return false;
133
134 SourceRange QualRange = OldDecl->getQualifierRange();
135
136 NestedNameSpecifier *NewQual
137 = SemaRef.SubstNestedNameSpecifier(OldQual, QualRange, TemplateArgs);
138 if (!NewQual)
139 return true;
140
141 NewDecl->setQualifierInfo(NewQual, QualRange);
142 return false;
143}
144
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000145// FIXME: Is this too simple?
146void TemplateDeclInstantiator::InstantiateAttrs(Decl *Tmpl, Decl *New) {
147 for (const Attr *TmplAttr = Tmpl->getAttrs(); TmplAttr;
148 TmplAttr = TmplAttr->getNext()) {
149
150 // FIXME: Is cloning correct for all attributes?
151 Attr *NewAttr = TmplAttr->clone(SemaRef.Context);
152
153 New->addAttr(NewAttr);
154 }
155}
156
Douglas Gregor4f722be2009-03-25 15:45:12 +0000157Decl *
158TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
159 assert(false && "Translation units cannot be instantiated");
160 return D;
161}
162
163Decl *
164TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
165 assert(false && "Namespaces cannot be instantiated");
166 return D;
167}
168
John McCall3dbd3d52010-02-16 06:53:13 +0000169Decl *
170TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
171 NamespaceAliasDecl *Inst
172 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
173 D->getNamespaceLoc(),
174 D->getAliasLoc(),
175 D->getNamespace()->getIdentifier(),
176 D->getQualifierRange(),
177 D->getQualifier(),
178 D->getTargetNameLoc(),
179 D->getNamespace());
180 Owner->addDecl(Inst);
181 return Inst;
182}
183
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000184Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
185 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000186 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCallba6a9bd2009-10-24 08:00:42 +0000187 if (DI->getType()->isDependentType()) {
188 DI = SemaRef.SubstType(DI, TemplateArgs,
189 D->getLocation(), D->getDeclName());
190 if (!DI) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000191 Invalid = true;
John McCalla93c9342009-12-07 02:54:59 +0000192 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000193 }
194 }
Mike Stump1eb44332009-09-09 15:08:12 +0000195
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000196 // Create the new typedef
197 TypedefDecl *Typedef
198 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
John McCallba6a9bd2009-10-24 08:00:42 +0000199 D->getIdentifier(), DI);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000200 if (Invalid)
201 Typedef->setInvalidDecl();
202
John McCall5126fd02009-12-30 00:31:22 +0000203 if (TypedefDecl *Prev = D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000204 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
205 TemplateArgs);
John McCall5126fd02009-12-30 00:31:22 +0000206 Typedef->setPreviousDeclaration(cast<TypedefDecl>(InstPrev));
207 }
208
John McCall46460a62010-01-20 21:53:11 +0000209 Typedef->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000210 Owner->addDecl(Typedef);
Mike Stump1eb44332009-09-09 15:08:12 +0000211
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000212 return Typedef;
213}
214
Douglas Gregor6eef5192009-12-14 19:27:10 +0000215/// \brief Instantiate the arguments provided as part of initialization.
216///
217/// \returns true if an error occurred, false otherwise.
218static bool InstantiateInitializationArguments(Sema &SemaRef,
219 Expr **Args, unsigned NumArgs,
220 const MultiLevelTemplateArgumentList &TemplateArgs,
221 llvm::SmallVectorImpl<SourceLocation> &FakeCommaLocs,
222 ASTOwningVector<&ActionBase::DeleteExpr> &InitArgs) {
223 for (unsigned I = 0; I != NumArgs; ++I) {
224 // When we hit the first defaulted argument, break out of the loop:
225 // we don't pass those default arguments on.
226 if (Args[I]->isDefaultArgument())
227 break;
228
229 Sema::OwningExprResult Arg = SemaRef.SubstExpr(Args[I], TemplateArgs);
230 if (Arg.isInvalid())
231 return true;
232
233 Expr *ArgExpr = (Expr *)Arg.get();
234 InitArgs.push_back(Arg.release());
235
236 // FIXME: We're faking all of the comma locations. Do we need them?
237 FakeCommaLocs.push_back(
238 SemaRef.PP.getLocForEndOfToken(ArgExpr->getLocEnd()));
239 }
240
241 return false;
242}
243
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000244/// \brief Instantiate an initializer, breaking it into separate
245/// initialization arguments.
246///
247/// \param S The semantic analysis object.
248///
249/// \param Init The initializer to instantiate.
250///
251/// \param TemplateArgs Template arguments to be substituted into the
252/// initializer.
253///
254/// \param NewArgs Will be filled in with the instantiation arguments.
255///
256/// \returns true if an error occurred, false otherwise
257static bool InstantiateInitializer(Sema &S, Expr *Init,
258 const MultiLevelTemplateArgumentList &TemplateArgs,
259 SourceLocation &LParenLoc,
260 llvm::SmallVector<SourceLocation, 4> &CommaLocs,
261 ASTOwningVector<&ActionBase::DeleteExpr> &NewArgs,
262 SourceLocation &RParenLoc) {
263 NewArgs.clear();
264 LParenLoc = SourceLocation();
265 RParenLoc = SourceLocation();
266
267 if (!Init)
268 return false;
269
270 if (CXXExprWithTemporaries *ExprTemp = dyn_cast<CXXExprWithTemporaries>(Init))
271 Init = ExprTemp->getSubExpr();
272
273 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
274 Init = Binder->getSubExpr();
275
276 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
277 Init = ICE->getSubExprAsWritten();
278
279 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
280 LParenLoc = ParenList->getLParenLoc();
281 RParenLoc = ParenList->getRParenLoc();
282 return InstantiateInitializationArguments(S, ParenList->getExprs(),
283 ParenList->getNumExprs(),
284 TemplateArgs, CommaLocs,
285 NewArgs);
286 }
287
288 if (CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init)) {
Douglas Gregor28329e52010-03-24 21:22:47 +0000289 if (!isa<CXXTemporaryObjectExpr>(Construct)) {
290 if (InstantiateInitializationArguments(S,
291 Construct->getArgs(),
292 Construct->getNumArgs(),
293 TemplateArgs,
294 CommaLocs, NewArgs))
295 return true;
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000296
Douglas Gregor28329e52010-03-24 21:22:47 +0000297 // FIXME: Fake locations!
298 LParenLoc = S.PP.getLocForEndOfToken(Init->getLocStart());
299 RParenLoc = CommaLocs.empty()? LParenLoc : CommaLocs.back();
300 return false;
301 }
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000302 }
303
304 Sema::OwningExprResult Result = S.SubstExpr(Init, TemplateArgs);
305 if (Result.isInvalid())
306 return true;
307
308 NewArgs.push_back(Result.takeAs<Expr>());
309 return false;
310}
311
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000312Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000313 // Do substitution on the type of the declaration
John McCalla93c9342009-12-07 02:54:59 +0000314 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
John McCall0a5fa062009-10-21 02:39:02 +0000315 TemplateArgs,
316 D->getTypeSpecStartLoc(),
317 D->getDeclName());
318 if (!DI)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000319 return 0;
320
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000321 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000322 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
323 D->getLocation(), D->getIdentifier(),
John McCall0a5fa062009-10-21 02:39:02 +0000324 DI->getType(), DI,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000325 D->getStorageClass());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000326 Var->setThreadSpecified(D->isThreadSpecified());
327 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
328 Var->setDeclaredInCondition(D->isDeclaredInCondition());
Mike Stump1eb44332009-09-09 15:08:12 +0000329
John McCallb6217662010-03-15 10:12:16 +0000330 // Substitute the nested name specifier, if any.
331 if (SubstQualifier(D, Var))
332 return 0;
333
Mike Stump1eb44332009-09-09 15:08:12 +0000334 // If we are instantiating a static data member defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000335 // out-of-line, the instantiation will have the same lexical
336 // context (which will be a namespace scope) as the template.
337 if (D->isOutOfLine())
338 Var->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000339
John McCall46460a62010-01-20 21:53:11 +0000340 Var->setAccess(D->getAccess());
341
Mike Stump390b4cc2009-05-16 07:39:55 +0000342 // FIXME: In theory, we could have a previous declaration for variables that
343 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000344 bool Redeclaration = false;
John McCall68263142009-11-18 22:49:29 +0000345 // FIXME: having to fake up a LookupResult is dumb.
346 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
Douglas Gregor449d0a82010-03-01 19:11:54 +0000347 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Douglas Gregor60c93c92010-02-09 07:26:29 +0000348 if (D->isStaticDataMember())
349 SemaRef.LookupQualifiedName(Previous, Owner, false);
John McCall68263142009-11-18 22:49:29 +0000350 SemaRef.CheckVariableDeclaration(Var, Previous, Redeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000351
Douglas Gregor7caa6822009-07-24 20:34:43 +0000352 if (D->isOutOfLine()) {
353 D->getLexicalDeclContext()->addDecl(Var);
354 Owner->makeDeclVisibleInContext(Var);
355 } else {
356 Owner->addDecl(Var);
357 }
Mike Stump1eb44332009-09-09 15:08:12 +0000358
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000359 // Link instantiations of static data members back to the template from
360 // which they were instantiated.
361 if (Var->isStaticDataMember())
362 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000363 TSK_ImplicitInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000364
Douglas Gregor60c93c92010-02-09 07:26:29 +0000365 if (Var->getAnyInitializer()) {
366 // We already have an initializer in the class.
367 } else if (D->getInit()) {
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000368 if (Var->isStaticDataMember() && !D->isOutOfLine())
369 SemaRef.PushExpressionEvaluationContext(Sema::Unevaluated);
370 else
371 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
372
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000373 // Instantiate the initializer.
374 SourceLocation LParenLoc, RParenLoc;
375 llvm::SmallVector<SourceLocation, 4> CommaLocs;
376 ASTOwningVector<&ActionBase::DeleteExpr> InitArgs(SemaRef);
377 if (!InstantiateInitializer(SemaRef, D->getInit(), TemplateArgs, LParenLoc,
378 CommaLocs, InitArgs, RParenLoc)) {
379 // Attach the initializer to the declaration.
380 if (D->hasCXXDirectInitializer()) {
Douglas Gregor6eef5192009-12-14 19:27:10 +0000381 // Add the direct initializer to the declaration.
Douglas Gregora88cfbf2009-12-12 18:16:41 +0000382 SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var),
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000383 LParenLoc,
Douglas Gregor6eef5192009-12-14 19:27:10 +0000384 move_arg(InitArgs),
385 CommaLocs.data(),
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000386 RParenLoc);
387 } else if (InitArgs.size() == 1) {
388 Expr *Init = (Expr*)(InitArgs.take()[0]);
389 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var),
390 SemaRef.Owned(Init),
391 false);
392 } else {
393 assert(InitArgs.size() == 0);
394 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor6eef5192009-12-14 19:27:10 +0000395 }
Douglas Gregor6eef5192009-12-14 19:27:10 +0000396 } else {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000397 // FIXME: Not too happy about invalidating the declaration
398 // because of a bogus initializer.
399 Var->setInvalidDecl();
Douglas Gregor6eef5192009-12-14 19:27:10 +0000400 }
401
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000402 SemaRef.PopExpressionEvaluationContext();
Douglas Gregor65b90052009-07-27 17:43:39 +0000403 } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
404 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000405
406 return Var;
407}
408
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000409Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
410 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000411 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000412 if (DI->getType()->isDependentType()) {
413 DI = SemaRef.SubstType(DI, TemplateArgs,
414 D->getLocation(), D->getDeclName());
415 if (!DI) {
John McCalla93c9342009-12-07 02:54:59 +0000416 DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000417 Invalid = true;
418 } else if (DI->getType()->isFunctionType()) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000419 // C++ [temp.arg.type]p3:
420 // If a declaration acquires a function type through a type
421 // dependent on a template-parameter and this causes a
422 // declaration that does not use the syntactic form of a
423 // function declarator to have function type, the program is
424 // ill-formed.
425 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall07fb6be2009-10-22 23:33:21 +0000426 << DI->getType();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000427 Invalid = true;
428 }
429 }
430
431 Expr *BitWidth = D->getBitWidth();
432 if (Invalid)
433 BitWidth = 0;
434 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000435 // The bit-width expression is not potentially evaluated.
436 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000437
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000438 OwningExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000439 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000440 if (InstantiatedBitWidth.isInvalid()) {
441 Invalid = true;
442 BitWidth = 0;
443 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000444 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000445 }
446
John McCall07fb6be2009-10-22 23:33:21 +0000447 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
448 DI->getType(), DI,
Mike Stump1eb44332009-09-09 15:08:12 +0000449 cast<RecordDecl>(Owner),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000450 D->getLocation(),
451 D->isMutable(),
452 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000453 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000454 D->getAccess(),
455 0);
Douglas Gregor663b5a02009-10-14 20:14:33 +0000456 if (!Field) {
457 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000458 return 0;
Douglas Gregor663b5a02009-10-14 20:14:33 +0000459 }
Mike Stump1eb44332009-09-09 15:08:12 +0000460
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000461 InstantiateAttrs(D, Field);
462
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000463 if (Invalid)
464 Field->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000465
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000466 if (!Field->getDeclName()) {
467 // Keep track of where this decl came from.
468 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000469 }
Mike Stump1eb44332009-09-09 15:08:12 +0000470
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000471 Field->setImplicit(D->isImplicit());
John McCall46460a62010-01-20 21:53:11 +0000472 Field->setAccess(D->getAccess());
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000473 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000474
475 return Field;
476}
477
John McCall02cace72009-08-28 07:59:38 +0000478Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
John McCall02cace72009-08-28 07:59:38 +0000479 // Handle friend type expressions by simply substituting template
Douglas Gregor06245bf2010-04-07 17:57:12 +0000480 // parameters into the pattern type and checking the result.
John McCall32f2fb52010-03-25 18:04:51 +0000481 if (TypeSourceInfo *Ty = D->getFriendType()) {
482 TypeSourceInfo *InstTy =
483 SemaRef.SubstType(Ty, TemplateArgs,
484 D->getLocation(), DeclarationName());
Douglas Gregor06245bf2010-04-07 17:57:12 +0000485 if (!InstTy)
Douglas Gregor7557a132009-12-24 20:56:24 +0000486 return 0;
John McCall02cace72009-08-28 07:59:38 +0000487
Douglas Gregor06245bf2010-04-07 17:57:12 +0000488 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getFriendLoc(), InstTy);
489 if (!FD)
490 return 0;
491
492 FD->setAccess(AS_public);
493 Owner->addDecl(FD);
494 return FD;
495 }
496
497 NamedDecl *ND = D->getFriendDecl();
498 assert(ND && "friend decl must be a decl or a type!");
499
John McCallaf2094e2010-04-08 09:05:18 +0000500 // All of the Visit implementations for the various potential friend
501 // declarations have to be carefully written to work for friend
502 // objects, with the most important detail being that the target
503 // decl should almost certainly not be placed in Owner.
504 Decl *NewND = Visit(ND);
Douglas Gregor06245bf2010-04-07 17:57:12 +0000505 if (!NewND) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000506
John McCall02cace72009-08-28 07:59:38 +0000507 FriendDecl *FD =
Douglas Gregor06245bf2010-04-07 17:57:12 +0000508 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
509 cast<NamedDecl>(NewND), D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000510 FD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +0000511 Owner->addDecl(FD);
512 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000513}
514
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000515Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
516 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000517
Douglas Gregorac7610d2009-06-22 20:57:11 +0000518 // The expression in a static assertion is not potentially evaluated.
519 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000520
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000521 OwningExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000522 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000523 if (InstantiatedAssertExpr.isInvalid())
524 return 0;
525
Douglas Gregor43d9d922009-08-08 01:41:12 +0000526 OwningExprResult Message(SemaRef, D->getMessage());
527 D->getMessage()->Retain();
Mike Stump1eb44332009-09-09 15:08:12 +0000528 Decl *StaticAssert
529 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
Chris Lattnerb28317a2009-03-28 19:18:32 +0000530 move(InstantiatedAssertExpr),
531 move(Message)).getAs<Decl>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000532 return StaticAssert;
533}
534
535Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +0000536 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000537 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000538 D->getTagKeywordLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000539 /*PrevDecl=*/0);
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000540 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000541 Enum->setAccess(D->getAccess());
John McCallb6217662010-03-15 10:12:16 +0000542 if (SubstQualifier(D, Enum)) return 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000543 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000544 Enum->startDefinition();
545
Douglas Gregor96084f12010-03-01 19:00:07 +0000546 if (D->getDeclContext()->isFunctionOrMethod())
547 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
548
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000549 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000550
551 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000552 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
553 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000554 EC != ECEnd; ++EC) {
555 // The specified value for the enumerator.
556 OwningExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000557 if (Expr *UninstValue = EC->getInitExpr()) {
558 // The enumerator's value expression is not potentially evaluated.
Mike Stump1eb44332009-09-09 15:08:12 +0000559 EnterExpressionEvaluationContext Unevaluated(SemaRef,
Douglas Gregorac7610d2009-06-22 20:57:11 +0000560 Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000561
John McCallce3ff2b2009-08-25 22:02:44 +0000562 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000563 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000564
565 // Drop the initial value and continue.
566 bool isInvalid = false;
567 if (Value.isInvalid()) {
568 Value = SemaRef.Owned((Expr *)0);
569 isInvalid = true;
570 }
571
Mike Stump1eb44332009-09-09 15:08:12 +0000572 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000573 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
574 EC->getLocation(), EC->getIdentifier(),
575 move(Value));
576
577 if (isInvalid) {
578 if (EnumConst)
579 EnumConst->setInvalidDecl();
580 Enum->setInvalidDecl();
581 }
582
583 if (EnumConst) {
John McCall3b85ecf2010-01-23 22:37:59 +0000584 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000585 Enum->addDecl(EnumConst);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000586 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000587 LastEnumConst = EnumConst;
Douglas Gregor96084f12010-03-01 19:00:07 +0000588
589 if (D->getDeclContext()->isFunctionOrMethod()) {
590 // If the enumeration is within a function or method, record the enum
591 // constant as a local.
592 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
593 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000594 }
595 }
Mike Stump1eb44332009-09-09 15:08:12 +0000596
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000597 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000598 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000599 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
600 Sema::DeclPtrTy::make(Enum),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000601 &Enumerators[0], Enumerators.size(),
602 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000603
604 return Enum;
605}
606
Douglas Gregor6477b692009-03-25 15:04:13 +0000607Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
608 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
609 return 0;
610}
611
Douglas Gregored9c0f92009-10-29 00:04:11 +0000612namespace {
613 class SortDeclByLocation {
614 SourceManager &SourceMgr;
615
616 public:
617 explicit SortDeclByLocation(SourceManager &SourceMgr)
618 : SourceMgr(SourceMgr) { }
619
620 bool operator()(const Decl *X, const Decl *Y) const {
621 return SourceMgr.isBeforeInTranslationUnit(X->getLocation(),
622 Y->getLocation());
623 }
624 };
625}
626
John McCalle29ba202009-08-20 01:44:21 +0000627Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
John McCall93ba8572010-03-25 06:39:04 +0000628 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
629
Douglas Gregor550d9b22009-10-31 17:21:17 +0000630 // Create a local instantiation scope for this class template, which
631 // will contain the instantiations of the template parameters.
632 Sema::LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000633 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000634 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000635 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000636 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000637
638 CXXRecordDecl *Pattern = D->getTemplatedDecl();
John McCall93ba8572010-03-25 06:39:04 +0000639
640 // Instantiate the qualifier. We have to do this first in case
641 // we're a friend declaration, because if we are then we need to put
642 // the new declaration in the appropriate context.
643 NestedNameSpecifier *Qualifier = Pattern->getQualifier();
644 if (Qualifier) {
645 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
646 Pattern->getQualifierRange(),
647 TemplateArgs);
648 if (!Qualifier) return 0;
649 }
650
651 CXXRecordDecl *PrevDecl = 0;
652 ClassTemplateDecl *PrevClassTemplate = 0;
653
654 // If this isn't a friend, then it's a member template, in which
655 // case we just want to build the instantiation in the
656 // specialization. If it is a friend, we want to build it in
657 // the appropriate context.
658 DeclContext *DC = Owner;
659 if (isFriend) {
660 if (Qualifier) {
661 CXXScopeSpec SS;
662 SS.setScopeRep(Qualifier);
663 SS.setRange(Pattern->getQualifierRange());
664 DC = SemaRef.computeDeclContext(SS);
665 if (!DC) return 0;
666 } else {
667 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
668 Pattern->getDeclContext(),
669 TemplateArgs);
670 }
671
672 // Look for a previous declaration of the template in the owning
673 // context.
674 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
675 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
676 SemaRef.LookupQualifiedName(R, DC);
677
678 if (R.isSingleResult()) {
679 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
680 if (PrevClassTemplate)
681 PrevDecl = PrevClassTemplate->getTemplatedDecl();
682 }
683
684 if (!PrevClassTemplate && Qualifier) {
685 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
Douglas Gregor1eabb7d2010-03-31 23:17:41 +0000686 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
687 << Pattern->getQualifierRange();
John McCall93ba8572010-03-25 06:39:04 +0000688 return 0;
689 }
690
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000691 bool AdoptedPreviousTemplateParams = false;
John McCall93ba8572010-03-25 06:39:04 +0000692 if (PrevClassTemplate) {
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000693 bool Complain = true;
694
695 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
696 // template for struct std::tr1::__detail::_Map_base, where the
697 // template parameters of the friend declaration don't match the
698 // template parameters of the original declaration. In this one
699 // case, we don't complain about the ill-formed friend
700 // declaration.
701 if (isFriend && Pattern->getIdentifier() &&
702 Pattern->getIdentifier()->isStr("_Map_base") &&
703 DC->isNamespace() &&
704 cast<NamespaceDecl>(DC)->getIdentifier() &&
705 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
706 DeclContext *DCParent = DC->getParent();
707 if (DCParent->isNamespace() &&
708 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
709 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
710 DeclContext *DCParent2 = DCParent->getParent();
711 if (DCParent2->isNamespace() &&
712 cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
713 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
714 DCParent2->getParent()->isTranslationUnit())
715 Complain = false;
716 }
717 }
718
John McCall93ba8572010-03-25 06:39:04 +0000719 TemplateParameterList *PrevParams
720 = PrevClassTemplate->getTemplateParameters();
721
722 // Make sure the parameter lists match.
723 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000724 Complain,
725 Sema::TPL_TemplateMatch)) {
726 if (Complain)
727 return 0;
728
729 AdoptedPreviousTemplateParams = true;
730 InstParams = PrevParams;
731 }
John McCall93ba8572010-03-25 06:39:04 +0000732
733 // Do some additional validation, then merge default arguments
734 // from the existing declarations.
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000735 if (!AdoptedPreviousTemplateParams &&
736 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
John McCall93ba8572010-03-25 06:39:04 +0000737 Sema::TPC_ClassTemplate))
738 return 0;
739 }
740 }
741
John McCalle29ba202009-08-20 01:44:21 +0000742 CXXRecordDecl *RecordInst
John McCall93ba8572010-03-25 06:39:04 +0000743 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
John McCalle29ba202009-08-20 01:44:21 +0000744 Pattern->getLocation(), Pattern->getIdentifier(),
John McCall93ba8572010-03-25 06:39:04 +0000745 Pattern->getTagKeywordLoc(), PrevDecl,
Douglas Gregorf0510d42009-10-12 23:11:44 +0000746 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000747
John McCall93ba8572010-03-25 06:39:04 +0000748 if (Qualifier)
749 RecordInst->setQualifierInfo(Qualifier, Pattern->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +0000750
John McCalle29ba202009-08-20 01:44:21 +0000751 ClassTemplateDecl *Inst
John McCall93ba8572010-03-25 06:39:04 +0000752 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
753 D->getIdentifier(), InstParams, RecordInst,
754 PrevClassTemplate);
John McCalle29ba202009-08-20 01:44:21 +0000755 RecordInst->setDescribedClassTemplate(Inst);
John McCallea7390c2010-04-08 20:25:50 +0000756
John McCall93ba8572010-03-25 06:39:04 +0000757 if (isFriend) {
John McCallea7390c2010-04-08 20:25:50 +0000758 if (PrevClassTemplate)
759 Inst->setAccess(PrevClassTemplate->getAccess());
760 else
761 Inst->setAccess(D->getAccess());
762
John McCall93ba8572010-03-25 06:39:04 +0000763 Inst->setObjectOfFriendDecl(PrevClassTemplate != 0);
764 // TODO: do we want to track the instantiation progeny of this
765 // friend target decl?
766 } else {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000767 Inst->setAccess(D->getAccess());
John McCall93ba8572010-03-25 06:39:04 +0000768 Inst->setInstantiatedFromMemberTemplate(D);
769 }
Douglas Gregorf0510d42009-10-12 23:11:44 +0000770
771 // Trigger creation of the type for the instantiation.
John McCall3cb0ebd2010-03-10 03:28:59 +0000772 SemaRef.Context.getInjectedClassNameType(RecordInst,
773 Inst->getInjectedClassNameSpecialization(SemaRef.Context));
John McCallea7390c2010-04-08 20:25:50 +0000774
Douglas Gregor259571e2009-10-30 22:42:42 +0000775 // Finish handling of friends.
John McCall93ba8572010-03-25 06:39:04 +0000776 if (isFriend) {
777 DC->makeDeclVisibleInContext(Inst, /*Recoverable*/ false);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000778 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000779 }
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000780
John McCalle29ba202009-08-20 01:44:21 +0000781 Owner->addDecl(Inst);
Douglas Gregored9c0f92009-10-29 00:04:11 +0000782
783 // First, we sort the partial specializations by location, so
784 // that we instantiate them in the order they were declared.
785 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
786 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
787 P = D->getPartialSpecializations().begin(),
788 PEnd = D->getPartialSpecializations().end();
789 P != PEnd; ++P)
790 PartialSpecs.push_back(&*P);
791 std::sort(PartialSpecs.begin(), PartialSpecs.end(),
792 SortDeclByLocation(SemaRef.SourceMgr));
793
794 // Instantiate all of the partial specializations of this member class
795 // template.
796 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
797 InstantiateClassTemplatePartialSpecialization(Inst, PartialSpecs[I]);
798
John McCalle29ba202009-08-20 01:44:21 +0000799 return Inst;
800}
801
Douglas Gregord60e1052009-08-27 16:57:43 +0000802Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000803TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
804 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +0000805 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
806
807 // Lookup the already-instantiated declaration in the instantiation
808 // of the class template and return that.
809 DeclContext::lookup_result Found
810 = Owner->lookup(ClassTemplate->getDeclName());
811 if (Found.first == Found.second)
812 return 0;
813
814 ClassTemplateDecl *InstClassTemplate
815 = dyn_cast<ClassTemplateDecl>(*Found.first);
816 if (!InstClassTemplate)
817 return 0;
818
819 Decl *DCanon = D->getCanonicalDecl();
820 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
821 P = InstClassTemplate->getPartialSpecializations().begin(),
822 PEnd = InstClassTemplate->getPartialSpecializations().end();
823 P != PEnd; ++P) {
824 if (P->getInstantiatedFromMember()->getCanonicalDecl() == DCanon)
825 return &*P;
826 }
827
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000828 return 0;
829}
830
831Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +0000832TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000833 // Create a local instantiation scope for this function template, which
834 // will contain the instantiations of the template parameters and then get
835 // merged with the local instantiation scope for the function template
836 // itself.
837 Sema::LocalInstantiationScope Scope(SemaRef);
838
Douglas Gregord60e1052009-08-27 16:57:43 +0000839 TemplateParameterList *TempParams = D->getTemplateParameters();
840 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000841 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000842 return NULL;
Douglas Gregored9c0f92009-10-29 00:04:11 +0000843
Douglas Gregora735b202009-10-13 14:39:41 +0000844 FunctionDecl *Instantiated = 0;
845 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
846 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
847 InstParams));
848 else
849 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
850 D->getTemplatedDecl(),
851 InstParams));
852
853 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +0000854 return 0;
855
John McCall46460a62010-01-20 21:53:11 +0000856 Instantiated->setAccess(D->getAccess());
857
Mike Stump1eb44332009-09-09 15:08:12 +0000858 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +0000859 // template from which it was instantiated.
Douglas Gregor37d681852009-10-12 22:27:17 +0000860 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +0000861 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +0000862 InstTemplate->setAccess(D->getAccess());
Douglas Gregora735b202009-10-13 14:39:41 +0000863 assert(InstTemplate &&
864 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCalle976ffe2009-12-14 23:19:40 +0000865
John McCallb1a56e72010-03-26 23:10:15 +0000866 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
867
John McCalle976ffe2009-12-14 23:19:40 +0000868 // Link the instantiation back to the pattern *unless* this is a
869 // non-definition friend declaration.
870 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
John McCallb1a56e72010-03-26 23:10:15 +0000871 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregora735b202009-10-13 14:39:41 +0000872 InstTemplate->setInstantiatedFromMemberTemplate(D);
873
John McCallb1a56e72010-03-26 23:10:15 +0000874 // Make declarations visible in the appropriate context.
875 if (!isFriend)
Douglas Gregora735b202009-10-13 14:39:41 +0000876 Owner->addDecl(InstTemplate);
John McCallb1a56e72010-03-26 23:10:15 +0000877
Douglas Gregord60e1052009-08-27 16:57:43 +0000878 return InstTemplate;
879}
880
Douglas Gregord475b8d2009-03-25 21:17:03 +0000881Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
882 CXXRecordDecl *PrevDecl = 0;
883 if (D->isInjectedClassName())
884 PrevDecl = cast<CXXRecordDecl>(Owner);
John McCall6c1c1b82009-12-15 22:29:06 +0000885 else if (D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000886 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
887 D->getPreviousDeclaration(),
John McCall6c1c1b82009-12-15 22:29:06 +0000888 TemplateArgs);
889 if (!Prev) return 0;
890 PrevDecl = cast<CXXRecordDecl>(Prev);
891 }
Douglas Gregord475b8d2009-03-25 21:17:03 +0000892
893 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +0000894 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000895 D->getLocation(), D->getIdentifier(),
896 D->getTagKeywordLoc(), PrevDecl);
John McCallb6217662010-03-15 10:12:16 +0000897
898 // Substitute the nested name specifier, if any.
899 if (SubstQualifier(D, Record))
900 return 0;
901
Douglas Gregord475b8d2009-03-25 21:17:03 +0000902 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000903 // FIXME: Check against AS_none is an ugly hack to work around the issue that
904 // the tag decls introduced by friend class declarations don't have an access
905 // specifier. Remove once this area of the code gets sorted out.
906 if (D->getAccess() != AS_none)
907 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000908 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +0000909 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000910
John McCall02cace72009-08-28 07:59:38 +0000911 // If the original function was part of a friend declaration,
912 // inherit its namespace state.
913 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
914 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
915
Anders Carlssond8b285f2009-09-01 04:26:58 +0000916 Record->setAnonymousStructOrUnion(D->isAnonymousStructOrUnion());
917
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000918 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000919 return Record;
920}
921
John McCall02cace72009-08-28 07:59:38 +0000922/// Normal class members are of more specific types and therefore
923/// don't make it here. This function serves two purposes:
924/// 1) instantiating function templates
925/// 2) substituting friend declarations
926/// FIXME: preserve function definitions in case #2
Douglas Gregor7557a132009-12-24 20:56:24 +0000927Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregora735b202009-10-13 14:39:41 +0000928 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000929 // Check whether there is already a function template specialization for
930 // this declaration.
931 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
932 void *InsertPos = 0;
John McCallb0cb0222010-03-27 05:57:59 +0000933 if (FunctionTemplate && !TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000934 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000935 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000936 TemplateArgs.getInnermost().getFlatArgumentList(),
937 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor828e2262009-07-29 16:09:57 +0000938 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000939
940 FunctionTemplateSpecializationInfo *Info
941 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor127102b2009-06-29 20:59:39 +0000942 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000943
Douglas Gregor127102b2009-06-29 20:59:39 +0000944 // If we already have a function template specialization, return it.
945 if (Info)
946 return Info->Function;
947 }
Mike Stump1eb44332009-09-09 15:08:12 +0000948
John McCallb0cb0222010-03-27 05:57:59 +0000949 bool isFriend;
950 if (FunctionTemplate)
951 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
952 else
953 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
954
Douglas Gregor79c22782010-01-16 20:21:20 +0000955 bool MergeWithParentScope = (TemplateParams != 0) ||
956 !(isa<Decl>(Owner) &&
957 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
958 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +0000959
Douglas Gregore53060f2009-06-25 22:08:12 +0000960 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +0000961 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
962 TInfo = SubstFunctionType(D, Params);
963 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000964 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +0000965 QualType T = TInfo->getType();
John McCallfd810b12009-08-14 02:03:10 +0000966
John McCalld325daa2010-03-26 04:53:08 +0000967 NestedNameSpecifier *Qualifier = D->getQualifier();
968 if (Qualifier) {
969 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
970 D->getQualifierRange(),
971 TemplateArgs);
972 if (!Qualifier) return 0;
973 }
974
John McCall68b6b872010-02-06 01:50:47 +0000975 // If we're instantiating a local function declaration, put the result
976 // in the owner; otherwise we need to find the instantiated context.
977 DeclContext *DC;
978 if (D->getDeclContext()->isFunctionOrMethod())
979 DC = Owner;
John McCalld325daa2010-03-26 04:53:08 +0000980 else if (isFriend && Qualifier) {
981 CXXScopeSpec SS;
982 SS.setScopeRep(Qualifier);
983 SS.setRange(D->getQualifierRange());
984 DC = SemaRef.computeDeclContext(SS);
985 if (!DC) return 0;
986 } else {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000987 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
988 TemplateArgs);
John McCalld325daa2010-03-26 04:53:08 +0000989 }
John McCall68b6b872010-02-06 01:50:47 +0000990
John McCall02cace72009-08-28 07:59:38 +0000991 FunctionDecl *Function =
Mike Stump1eb44332009-09-09 15:08:12 +0000992 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +0000993 D->getDeclName(), T, TInfo,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000994 D->getStorageClass(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000995 D->isInlineSpecified(), D->hasWrittenPrototype());
John McCallb6217662010-03-15 10:12:16 +0000996
John McCalld325daa2010-03-26 04:53:08 +0000997 if (Qualifier)
998 Function->setQualifierInfo(Qualifier, D->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +0000999
John McCallb1a56e72010-03-26 23:10:15 +00001000 DeclContext *LexicalDC = Owner;
1001 if (!isFriend && D->isOutOfLine()) {
1002 assert(D->getDeclContext()->isFileContext());
1003 LexicalDC = D->getDeclContext();
1004 }
1005
1006 Function->setLexicalDeclContext(LexicalDC);
Mike Stump1eb44332009-09-09 15:08:12 +00001007
Douglas Gregore53060f2009-06-25 22:08:12 +00001008 // Attach the parameters
1009 for (unsigned P = 0; P < Params.size(); ++P)
1010 Params[P]->setOwningFunction(Function);
Douglas Gregor838db382010-02-11 01:19:42 +00001011 Function->setParams(Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +00001012
Douglas Gregora735b202009-10-13 14:39:41 +00001013 if (TemplateParams) {
1014 // Our resulting instantiation is actually a function template, since we
1015 // are substituting only the outer template parameters. For example, given
1016 //
1017 // template<typename T>
1018 // struct X {
1019 // template<typename U> friend void f(T, U);
1020 // };
1021 //
1022 // X<int> x;
1023 //
1024 // We are instantiating the friend function template "f" within X<int>,
1025 // which means substituting int for T, but leaving "f" as a friend function
1026 // template.
1027 // Build the function template itself.
John McCalld325daa2010-03-26 04:53:08 +00001028 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregora735b202009-10-13 14:39:41 +00001029 Function->getLocation(),
1030 Function->getDeclName(),
1031 TemplateParams, Function);
1032 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCallb1a56e72010-03-26 23:10:15 +00001033
1034 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalld325daa2010-03-26 04:53:08 +00001035
1036 if (isFriend && D->isThisDeclarationADefinition()) {
1037 // TODO: should we remember this connection regardless of whether
1038 // the friend declaration provided a body?
1039 FunctionTemplate->setInstantiatedFromMemberTemplate(
1040 D->getDescribedFunctionTemplate());
1041 }
Douglas Gregor66724ea2009-11-14 01:20:54 +00001042 } else if (FunctionTemplate) {
1043 // Record this function template specialization.
Douglas Gregor838db382010-02-11 01:19:42 +00001044 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor66724ea2009-11-14 01:20:54 +00001045 &TemplateArgs.getInnermost(),
1046 InsertPos);
John McCalld325daa2010-03-26 04:53:08 +00001047 } else if (isFriend && D->isThisDeclarationADefinition()) {
1048 // TODO: should we remember this connection regardless of whether
1049 // the friend declaration provided a body?
1050 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCall02cace72009-08-28 07:59:38 +00001051 }
Douglas Gregora735b202009-10-13 14:39:41 +00001052
Douglas Gregore53060f2009-06-25 22:08:12 +00001053 if (InitFunctionInstantiation(Function, D))
1054 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001055
Douglas Gregore53060f2009-06-25 22:08:12 +00001056 bool Redeclaration = false;
1057 bool OverloadableAttrRequired = false;
John McCallaf2094e2010-04-08 09:05:18 +00001058 bool isExplicitSpecialization = false;
Douglas Gregora735b202009-10-13 14:39:41 +00001059
John McCall68263142009-11-18 22:49:29 +00001060 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
1061 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1062
John McCallaf2094e2010-04-08 09:05:18 +00001063 if (DependentFunctionTemplateSpecializationInfo *Info
1064 = D->getDependentSpecializationInfo()) {
1065 assert(isFriend && "non-friend has dependent specialization info?");
1066
1067 // This needs to be set now for future sanity.
1068 Function->setObjectOfFriendDecl(/*HasPrevious*/ true);
1069
1070 // Instantiate the explicit template arguments.
1071 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1072 Info->getRAngleLoc());
1073 for (unsigned I = 0, E = Info->getNumTemplateArgs(); I != E; ++I) {
1074 TemplateArgumentLoc Loc;
1075 if (SemaRef.Subst(Info->getTemplateArg(I), Loc, TemplateArgs))
1076 return 0;
1077
1078 ExplicitArgs.addArgument(Loc);
1079 }
1080
1081 // Map the candidate templates to their instantiations.
1082 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1083 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1084 Info->getTemplate(I),
1085 TemplateArgs);
1086 if (!Temp) return 0;
1087
1088 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1089 }
1090
1091 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1092 &ExplicitArgs,
1093 Previous))
1094 Function->setInvalidDecl();
1095
1096 isExplicitSpecialization = true;
1097
1098 } else if (TemplateParams || !FunctionTemplate) {
Douglas Gregora735b202009-10-13 14:39:41 +00001099 // Look only into the namespace where the friend would be declared to
1100 // find a previous declaration. This is the innermost enclosing namespace,
1101 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +00001102 SemaRef.LookupQualifiedName(Previous, DC);
Douglas Gregora735b202009-10-13 14:39:41 +00001103
Douglas Gregora735b202009-10-13 14:39:41 +00001104 // In C++, the previous declaration we find might be a tag type
1105 // (class or enum). In this case, the new declaration will hide the
1106 // tag type. Note that this does does not apply if we're declaring a
1107 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001108 if (Previous.isSingleTagDecl())
1109 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +00001110 }
1111
John McCall9f54ad42009-12-10 09:41:52 +00001112 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
John McCallaf2094e2010-04-08 09:05:18 +00001113 isExplicitSpecialization, Redeclaration,
Douglas Gregore53060f2009-06-25 22:08:12 +00001114 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001115
Douglas Gregora735b202009-10-13 14:39:41 +00001116 // If the original function was part of a friend declaration,
1117 // inherit its namespace state and add it to the owner.
John McCalld325daa2010-03-26 04:53:08 +00001118 if (isFriend) {
Douglas Gregora735b202009-10-13 14:39:41 +00001119 NamedDecl *ToFriendD = 0;
John McCall68263142009-11-18 22:49:29 +00001120 NamedDecl *PrevDecl;
Douglas Gregora735b202009-10-13 14:39:41 +00001121 if (TemplateParams) {
1122 ToFriendD = cast<NamedDecl>(FunctionTemplate);
1123 PrevDecl = FunctionTemplate->getPreviousDeclaration();
1124 } else {
1125 ToFriendD = Function;
1126 PrevDecl = Function->getPreviousDeclaration();
1127 }
1128 ToFriendD->setObjectOfFriendDecl(PrevDecl != NULL);
John McCalld325daa2010-03-26 04:53:08 +00001129 DC->makeDeclVisibleInContext(ToFriendD, /*Recoverable=*/ false);
Douglas Gregora735b202009-10-13 14:39:41 +00001130 }
1131
Douglas Gregore53060f2009-06-25 22:08:12 +00001132 return Function;
1133}
1134
Douglas Gregord60e1052009-08-27 16:57:43 +00001135Decl *
1136TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1137 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +00001138 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1139 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +00001140 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +00001141 // We are creating a function template specialization from a function
1142 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +00001143 // specialization for this particular set of template arguments.
Douglas Gregor6b906862009-08-21 00:16:32 +00001144 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001145 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001146 TemplateArgs.getInnermost().getFlatArgumentList(),
1147 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor6b906862009-08-21 00:16:32 +00001148 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001149
1150 FunctionTemplateSpecializationInfo *Info
1151 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor6b906862009-08-21 00:16:32 +00001152 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001153
Douglas Gregor6b906862009-08-21 00:16:32 +00001154 // If we already have a function template specialization, return it.
1155 if (Info)
1156 return Info->Function;
1157 }
1158
John McCallb0cb0222010-03-27 05:57:59 +00001159 bool isFriend;
1160 if (FunctionTemplate)
1161 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1162 else
1163 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1164
Douglas Gregor79c22782010-01-16 20:21:20 +00001165 bool MergeWithParentScope = (TemplateParams != 0) ||
1166 !(isa<Decl>(Owner) &&
1167 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1168 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001169
Douglas Gregor0ca20ac2009-05-29 18:27:38 +00001170 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +00001171 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
1172 TInfo = SubstFunctionType(D, Params);
1173 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001174 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +00001175 QualType T = TInfo->getType();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001176
John McCallb0cb0222010-03-27 05:57:59 +00001177 NestedNameSpecifier *Qualifier = D->getQualifier();
1178 if (Qualifier) {
1179 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
1180 D->getQualifierRange(),
1181 TemplateArgs);
1182 if (!Qualifier) return 0;
1183 }
1184
1185 DeclContext *DC = Owner;
1186 if (isFriend) {
1187 if (Qualifier) {
1188 CXXScopeSpec SS;
1189 SS.setScopeRep(Qualifier);
1190 SS.setRange(D->getQualifierRange());
1191 DC = SemaRef.computeDeclContext(SS);
1192 } else {
1193 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1194 D->getDeclContext(),
1195 TemplateArgs);
1196 }
1197 if (!DC) return 0;
1198 }
1199
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001200 // Build the instantiated method declaration.
John McCallb0cb0222010-03-27 05:57:59 +00001201 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Douglas Gregordec06662009-08-21 18:42:58 +00001202 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001203
Douglas Gregordec06662009-08-21 18:42:58 +00001204 DeclarationName Name = D->getDeclName();
Douglas Gregor17e32f32009-08-21 22:43:28 +00001205 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Douglas Gregordec06662009-08-21 18:42:58 +00001206 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
1207 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
1208 SemaRef.Context.getCanonicalType(ClassTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001209 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
1210 Constructor->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +00001211 Name, T, TInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001212 Constructor->isExplicit(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001213 Constructor->isInlineSpecified(), false);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001214 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
1215 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
1216 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
1217 SemaRef.Context.getCanonicalType(ClassTy));
1218 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
1219 Destructor->getLocation(), Name,
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001220 T, Destructor->isInlineSpecified(), false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001221 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001222 CanQualType ConvTy
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001223 = SemaRef.Context.getCanonicalType(
John McCall183700f2009-09-21 23:43:11 +00001224 T->getAs<FunctionType>()->getResultType());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001225 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
1226 ConvTy);
1227 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
1228 Conversion->getLocation(), Name,
John McCall21ef0fa2010-03-11 09:03:00 +00001229 T, TInfo,
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001230 Conversion->isInlineSpecified(),
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001231 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +00001232 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001233 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +00001234 D->getDeclName(), T, TInfo,
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001235 D->isStatic(), D->isInlineSpecified());
Douglas Gregordec06662009-08-21 18:42:58 +00001236 }
Douglas Gregor6b906862009-08-21 00:16:32 +00001237
John McCallb0cb0222010-03-27 05:57:59 +00001238 if (Qualifier)
1239 Method->setQualifierInfo(Qualifier, D->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +00001240
Douglas Gregord60e1052009-08-27 16:57:43 +00001241 if (TemplateParams) {
1242 // Our resulting instantiation is actually a function template, since we
1243 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +00001244 //
Douglas Gregord60e1052009-08-27 16:57:43 +00001245 // template<typename T>
1246 // struct X {
1247 // template<typename U> void f(T, U);
1248 // };
1249 //
1250 // X<int> x;
1251 //
1252 // We are instantiating the member template "f" within X<int>, which means
1253 // substituting int for T, but leaving "f" as a member function template.
1254 // Build the function template itself.
1255 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1256 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001257 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +00001258 TemplateParams, Method);
John McCallb0cb0222010-03-27 05:57:59 +00001259 if (isFriend) {
1260 FunctionTemplate->setLexicalDeclContext(Owner);
1261 FunctionTemplate->setObjectOfFriendDecl(true);
1262 } else if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +00001263 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +00001264 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001265 } else if (FunctionTemplate) {
1266 // Record this function template specialization.
Douglas Gregor838db382010-02-11 01:19:42 +00001267 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor66724ea2009-11-14 01:20:54 +00001268 &TemplateArgs.getInnermost(),
1269 InsertPos);
John McCallb0cb0222010-03-27 05:57:59 +00001270 } else if (!isFriend) {
Douglas Gregor66724ea2009-11-14 01:20:54 +00001271 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +00001272 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001273 }
1274
Mike Stump1eb44332009-09-09 15:08:12 +00001275 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +00001276 // out-of-line, the instantiation will have the same lexical
1277 // context (which will be a namespace scope) as the template.
John McCallb0cb0222010-03-27 05:57:59 +00001278 if (isFriend) {
1279 Method->setLexicalDeclContext(Owner);
1280 Method->setObjectOfFriendDecl(true);
1281 } else if (D->isOutOfLine())
Douglas Gregor7caa6822009-07-24 20:34:43 +00001282 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00001283
Douglas Gregor5545e162009-03-24 00:38:23 +00001284 // Attach the parameters
1285 for (unsigned P = 0; P < Params.size(); ++P)
1286 Params[P]->setOwningFunction(Method);
Douglas Gregor838db382010-02-11 01:19:42 +00001287 Method->setParams(Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +00001288
1289 if (InitMethodInstantiation(Method, D))
1290 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001291
John McCall68263142009-11-18 22:49:29 +00001292 LookupResult Previous(SemaRef, Name, SourceLocation(),
1293 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00001294
John McCallb0cb0222010-03-27 05:57:59 +00001295 if (!FunctionTemplate || TemplateParams || isFriend) {
1296 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001297
Douglas Gregordec06662009-08-21 18:42:58 +00001298 // In C++, the previous declaration we find might be a tag type
1299 // (class or enum). In this case, the new declaration will hide the
1300 // tag type. Note that this does does not apply if we're declaring a
1301 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001302 if (Previous.isSingleTagDecl())
1303 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +00001304 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001305
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001306 bool Redeclaration = false;
1307 bool OverloadableAttrRequired = false;
John McCall9f54ad42009-12-10 09:41:52 +00001308 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001309 /*FIXME:*/OverloadableAttrRequired);
1310
Douglas Gregor4ba31362009-12-01 17:24:26 +00001311 if (D->isPure())
1312 SemaRef.CheckPureMethod(Method, SourceRange());
1313
John McCall46460a62010-01-20 21:53:11 +00001314 Method->setAccess(D->getAccess());
1315
John McCallb0cb0222010-03-27 05:57:59 +00001316 if (FunctionTemplate) {
1317 // If there's a function template, let our caller handle it.
1318 } else if (Method->isInvalidDecl() && !Previous.empty()) {
1319 // Don't hide a (potentially) valid declaration with an invalid one.
1320 } else {
1321 NamedDecl *DeclToAdd = (TemplateParams
1322 ? cast<NamedDecl>(FunctionTemplate)
1323 : Method);
1324 if (isFriend)
1325 Record->makeDeclVisibleInContext(DeclToAdd);
1326 else
1327 Owner->addDecl(DeclToAdd);
1328 }
Mike Stump1eb44332009-09-09 15:08:12 +00001329
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001330 return Method;
1331}
1332
Douglas Gregor615c5d42009-03-24 16:43:20 +00001333Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +00001334 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +00001335}
1336
Douglas Gregor03b2b072009-03-24 00:15:49 +00001337Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001338 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +00001339}
1340
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001341Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001342 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001343}
1344
Douglas Gregor6477b692009-03-25 15:04:13 +00001345ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001346 return SemaRef.SubstParmVarDecl(D, TemplateArgs);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001347}
1348
John McCalle29ba202009-08-20 01:44:21 +00001349Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1350 TemplateTypeParmDecl *D) {
1351 // TODO: don't always clone when decls are refcounted.
1352 const Type* T = D->getTypeForDecl();
1353 assert(T->isTemplateTypeParmType());
1354 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001355
John McCalle29ba202009-08-20 01:44:21 +00001356 TemplateTypeParmDecl *Inst =
1357 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor550d9b22009-10-31 17:21:17 +00001358 TTPT->getDepth() - 1, TTPT->getIndex(),
John McCalle29ba202009-08-20 01:44:21 +00001359 TTPT->getName(),
1360 D->wasDeclaredWithTypename(),
1361 D->isParameterPack());
1362
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001363 if (D->hasDefaultArgument())
1364 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
John McCalle29ba202009-08-20 01:44:21 +00001365
Douglas Gregor550d9b22009-10-31 17:21:17 +00001366 // Introduce this template parameter's instantiation into the instantiation
1367 // scope.
1368 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1369
John McCalle29ba202009-08-20 01:44:21 +00001370 return Inst;
1371}
1372
Douglas Gregor33642df2009-10-23 23:25:44 +00001373Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1374 NonTypeTemplateParmDecl *D) {
1375 // Substitute into the type of the non-type template parameter.
1376 QualType T;
John McCalla93c9342009-12-07 02:54:59 +00001377 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor33642df2009-10-23 23:25:44 +00001378 if (DI) {
1379 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
1380 D->getDeclName());
1381 if (DI) T = DI->getType();
1382 } else {
1383 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
1384 D->getDeclName());
1385 DI = 0;
1386 }
1387 if (T.isNull())
1388 return 0;
1389
1390 // Check that this type is acceptable for a non-type template parameter.
1391 bool Invalid = false;
1392 T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation());
1393 if (T.isNull()) {
1394 T = SemaRef.Context.IntTy;
1395 Invalid = true;
1396 }
1397
1398 NonTypeTemplateParmDecl *Param
1399 = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1400 D->getDepth() - 1, D->getPosition(),
1401 D->getIdentifier(), T, DI);
1402 if (Invalid)
1403 Param->setInvalidDecl();
1404
1405 Param->setDefaultArgument(D->getDefaultArgument());
Douglas Gregor550d9b22009-10-31 17:21:17 +00001406
1407 // Introduce this template parameter's instantiation into the instantiation
1408 // scope.
1409 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001410 return Param;
1411}
1412
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001413Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001414TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1415 TemplateTemplateParmDecl *D) {
1416 // Instantiate the template parameter list of the template template parameter.
1417 TemplateParameterList *TempParams = D->getTemplateParameters();
1418 TemplateParameterList *InstParams;
1419 {
1420 // Perform the actual substitution of template parameters within a new,
1421 // local instantiation scope.
1422 Sema::LocalInstantiationScope Scope(SemaRef);
1423 InstParams = SubstTemplateParams(TempParams);
1424 if (!InstParams)
1425 return NULL;
1426 }
1427
1428 // Build the template template parameter.
1429 TemplateTemplateParmDecl *Param
1430 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1431 D->getDepth() - 1, D->getPosition(),
1432 D->getIdentifier(), InstParams);
1433 Param->setDefaultArgument(D->getDefaultArgument());
1434
1435 // Introduce this template parameter's instantiation into the instantiation
1436 // scope.
1437 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1438
1439 return Param;
1440}
1441
Douglas Gregor48c32a72009-11-17 06:07:40 +00001442Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1443 // Using directives are never dependent, so they require no explicit
1444
1445 UsingDirectiveDecl *Inst
1446 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1447 D->getNamespaceKeyLocation(),
1448 D->getQualifierRange(), D->getQualifier(),
1449 D->getIdentLocation(),
1450 D->getNominatedNamespace(),
1451 D->getCommonAncestor());
1452 Owner->addDecl(Inst);
1453 return Inst;
1454}
1455
John McCalled976492009-12-04 22:46:56 +00001456Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
1457 // The nested name specifier is non-dependent, so no transformation
1458 // is required.
1459
John McCall9f54ad42009-12-10 09:41:52 +00001460 // We only need to do redeclaration lookups if we're in a class
1461 // scope (in fact, it's not really even possible in non-class
1462 // scopes).
1463 bool CheckRedeclaration = Owner->isRecord();
1464
1465 LookupResult Prev(SemaRef, D->getDeclName(), D->getLocation(),
1466 Sema::LookupUsingDeclName, Sema::ForRedeclaration);
1467
John McCalled976492009-12-04 22:46:56 +00001468 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
1469 D->getLocation(),
1470 D->getNestedNameRange(),
1471 D->getUsingLocation(),
1472 D->getTargetNestedNameDecl(),
1473 D->getDeclName(),
1474 D->isTypeName());
1475
1476 CXXScopeSpec SS;
1477 SS.setScopeRep(D->getTargetNestedNameDecl());
1478 SS.setRange(D->getNestedNameRange());
John McCall9f54ad42009-12-10 09:41:52 +00001479
1480 if (CheckRedeclaration) {
1481 Prev.setHideTags(false);
1482 SemaRef.LookupQualifiedName(Prev, Owner);
1483
1484 // Check for invalid redeclarations.
1485 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1486 D->isTypeName(), SS,
1487 D->getLocation(), Prev))
1488 NewUD->setInvalidDecl();
1489
1490 }
1491
1492 if (!NewUD->isInvalidDecl() &&
1493 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
John McCalled976492009-12-04 22:46:56 +00001494 D->getLocation()))
1495 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00001496
John McCalled976492009-12-04 22:46:56 +00001497 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1498 NewUD->setAccess(D->getAccess());
1499 Owner->addDecl(NewUD);
1500
John McCall9f54ad42009-12-10 09:41:52 +00001501 // Don't process the shadow decls for an invalid decl.
1502 if (NewUD->isInvalidDecl())
1503 return NewUD;
1504
John McCall323c3102009-12-22 22:26:37 +00001505 bool isFunctionScope = Owner->isFunctionOrMethod();
1506
John McCall9f54ad42009-12-10 09:41:52 +00001507 // Process the shadow decls.
1508 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1509 I != E; ++I) {
1510 UsingShadowDecl *Shadow = *I;
1511 NamedDecl *InstTarget =
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001512 cast<NamedDecl>(SemaRef.FindInstantiatedDecl(Shadow->getLocation(),
1513 Shadow->getTargetDecl(),
John McCall9f54ad42009-12-10 09:41:52 +00001514 TemplateArgs));
1515
1516 if (CheckRedeclaration &&
1517 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1518 continue;
1519
1520 UsingShadowDecl *InstShadow
1521 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1522 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCall323c3102009-12-22 22:26:37 +00001523
1524 if (isFunctionScope)
1525 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall9f54ad42009-12-10 09:41:52 +00001526 }
John McCalled976492009-12-04 22:46:56 +00001527
1528 return NewUD;
1529}
1530
1531Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00001532 // Ignore these; we handle them in bulk when processing the UsingDecl.
1533 return 0;
John McCalled976492009-12-04 22:46:56 +00001534}
1535
John McCall7ba107a2009-11-18 02:36:19 +00001536Decl * TemplateDeclInstantiator
1537 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00001538 NestedNameSpecifier *NNS =
1539 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1540 D->getTargetNestedNameRange(),
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001541 TemplateArgs);
1542 if (!NNS)
1543 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001544
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001545 CXXScopeSpec SS;
1546 SS.setRange(D->getTargetNestedNameRange());
1547 SS.setScopeRep(NNS);
Mike Stump1eb44332009-09-09 15:08:12 +00001548
1549 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001550 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
John McCall7ba107a2009-11-18 02:36:19 +00001551 D->getUsingLoc(), SS, D->getLocation(),
1552 D->getDeclName(), 0,
1553 /*instantiation*/ true,
1554 /*typename*/ true, D->getTypenameLoc());
1555 if (UD)
John McCalled976492009-12-04 22:46:56 +00001556 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1557
John McCall7ba107a2009-11-18 02:36:19 +00001558 return UD;
1559}
1560
1561Decl * TemplateDeclInstantiator
1562 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1563 NestedNameSpecifier *NNS =
1564 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1565 D->getTargetNestedNameRange(),
1566 TemplateArgs);
1567 if (!NNS)
1568 return 0;
1569
1570 CXXScopeSpec SS;
1571 SS.setRange(D->getTargetNestedNameRange());
1572 SS.setScopeRep(NNS);
1573
1574 NamedDecl *UD =
1575 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1576 D->getUsingLoc(), SS, D->getLocation(),
1577 D->getDeclName(), 0,
1578 /*instantiation*/ true,
1579 /*typename*/ false, SourceLocation());
Anders Carlsson0d8df782009-08-29 19:37:28 +00001580 if (UD)
John McCalled976492009-12-04 22:46:56 +00001581 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1582
Anders Carlsson0d8df782009-08-29 19:37:28 +00001583 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001584}
1585
John McCallce3ff2b2009-08-25 22:02:44 +00001586Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001587 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001588 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor2fa98002010-02-16 19:28:15 +00001589 if (D->isInvalidDecl())
1590 return 0;
1591
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001592 return Instantiator.Visit(D);
1593}
1594
John McCalle29ba202009-08-20 01:44:21 +00001595/// \brief Instantiates a nested template parameter list in the current
1596/// instantiation context.
1597///
1598/// \param L The parameter list to instantiate
1599///
1600/// \returns NULL if there was an error
1601TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001602TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001603 // Get errors for all the parameters before bailing out.
1604 bool Invalid = false;
1605
1606 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001607 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001608 ParamVector Params;
1609 Params.reserve(N);
1610 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1611 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001612 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00001613 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00001614 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00001615 }
1616
1617 // Clean up if we had an error.
1618 if (Invalid) {
1619 for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
1620 PI != PE; ++PI)
1621 if (*PI)
1622 (*PI)->Destroy(SemaRef.Context);
1623 return NULL;
1624 }
1625
1626 TemplateParameterList *InstL
1627 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1628 L->getLAngleLoc(), &Params.front(), N,
1629 L->getRAngleLoc());
1630 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00001631}
John McCalle29ba202009-08-20 01:44:21 +00001632
Douglas Gregored9c0f92009-10-29 00:04:11 +00001633/// \brief Instantiate the declaration of a class template partial
1634/// specialization.
1635///
1636/// \param ClassTemplate the (instantiated) class template that is partially
1637// specialized by the instantiation of \p PartialSpec.
1638///
1639/// \param PartialSpec the (uninstantiated) class template partial
1640/// specialization that we are instantiating.
1641///
1642/// \returns true if there was an error, false otherwise.
1643bool
1644TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1645 ClassTemplateDecl *ClassTemplate,
1646 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001647 // Create a local instantiation scope for this class template partial
1648 // specialization, which will contain the instantiations of the template
1649 // parameters.
1650 Sema::LocalInstantiationScope Scope(SemaRef);
1651
Douglas Gregored9c0f92009-10-29 00:04:11 +00001652 // Substitute into the template parameters of the class template partial
1653 // specialization.
1654 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1655 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1656 if (!InstParams)
1657 return true;
1658
1659 // Substitute into the template arguments of the class template partial
1660 // specialization.
John McCall833ca992009-10-29 08:12:44 +00001661 const TemplateArgumentLoc *PartialSpecTemplateArgs
1662 = PartialSpec->getTemplateArgsAsWritten();
1663 unsigned N = PartialSpec->getNumTemplateArgsAsWritten();
1664
John McCalld5532b62009-11-23 01:53:49 +00001665 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
John McCall833ca992009-10-29 08:12:44 +00001666 for (unsigned I = 0; I != N; ++I) {
John McCalld5532b62009-11-23 01:53:49 +00001667 TemplateArgumentLoc Loc;
1668 if (SemaRef.Subst(PartialSpecTemplateArgs[I], Loc, TemplateArgs))
Douglas Gregored9c0f92009-10-29 00:04:11 +00001669 return true;
John McCalld5532b62009-11-23 01:53:49 +00001670 InstTemplateArgs.addArgument(Loc);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001671 }
1672
1673
1674 // Check that the template argument list is well-formed for this
1675 // class template.
1676 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
1677 InstTemplateArgs.size());
1678 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1679 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001680 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001681 false,
1682 Converted))
1683 return true;
1684
1685 // Figure out where to insert this class template partial specialization
1686 // in the member template's set of class template partial specializations.
1687 llvm::FoldingSetNodeID ID;
1688 ClassTemplatePartialSpecializationDecl::Profile(ID,
1689 Converted.getFlatArguments(),
1690 Converted.flatSize(),
1691 SemaRef.Context);
1692 void *InsertPos = 0;
1693 ClassTemplateSpecializationDecl *PrevDecl
1694 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
1695 InsertPos);
1696
1697 // Build the canonical type that describes the converted template
1698 // arguments of the class template partial specialization.
1699 QualType CanonType
1700 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
1701 Converted.getFlatArguments(),
1702 Converted.flatSize());
1703
1704 // Build the fully-sugared type for this class template
1705 // specialization as the user wrote in the specialization
1706 // itself. This means that we'll pretty-print the type retrieved
1707 // from the specialization's declaration the way that the user
1708 // actually wrote the specialization, rather than formatting the
1709 // name based on the "canonical" representation used to store the
1710 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00001711 TypeSourceInfo *WrittenTy
1712 = SemaRef.Context.getTemplateSpecializationTypeInfo(
1713 TemplateName(ClassTemplate),
1714 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001715 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001716 CanonType);
1717
1718 if (PrevDecl) {
1719 // We've already seen a partial specialization with the same template
1720 // parameters and template arguments. This can happen, for example, when
1721 // substituting the outer template arguments ends up causing two
1722 // class template partial specializations of a member class template
1723 // to have identical forms, e.g.,
1724 //
1725 // template<typename T, typename U>
1726 // struct Outer {
1727 // template<typename X, typename Y> struct Inner;
1728 // template<typename Y> struct Inner<T, Y>;
1729 // template<typename Y> struct Inner<U, Y>;
1730 // };
1731 //
1732 // Outer<int, int> outer; // error: the partial specializations of Inner
1733 // // have the same signature.
1734 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
1735 << WrittenTy;
1736 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1737 << SemaRef.Context.getTypeDeclType(PrevDecl);
1738 return true;
1739 }
1740
1741
1742 // Create the class template partial specialization declaration.
1743 ClassTemplatePartialSpecializationDecl *InstPartialSpec
1744 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context, Owner,
1745 PartialSpec->getLocation(),
1746 InstParams,
1747 ClassTemplate,
1748 Converted,
John McCalld5532b62009-11-23 01:53:49 +00001749 InstTemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00001750 CanonType,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001751 0);
John McCallb6217662010-03-15 10:12:16 +00001752 // Substitute the nested name specifier, if any.
1753 if (SubstQualifier(PartialSpec, InstPartialSpec))
1754 return 0;
1755
Douglas Gregored9c0f92009-10-29 00:04:11 +00001756 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
1757 InstPartialSpec->setTypeAsWritten(WrittenTy);
1758
1759 // Add this partial specialization to the set of class template partial
1760 // specializations.
1761 ClassTemplate->getPartialSpecializations().InsertNode(InstPartialSpec,
1762 InsertPos);
1763 return false;
1764}
1765
John McCall21ef0fa2010-03-11 09:03:00 +00001766TypeSourceInfo*
John McCallce3ff2b2009-08-25 22:02:44 +00001767TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00001768 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall21ef0fa2010-03-11 09:03:00 +00001769 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
1770 assert(OldTInfo && "substituting function without type source info");
1771 assert(Params.empty() && "parameter vector is non-empty at start");
John McCall6cd3b9f2010-04-09 17:38:44 +00001772 TypeSourceInfo *NewTInfo
1773 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
1774 D->getTypeSpecStartLoc(),
1775 D->getDeclName());
John McCall21ef0fa2010-03-11 09:03:00 +00001776 if (!NewTInfo)
1777 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +00001778
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001779 if (NewTInfo != OldTInfo) {
1780 // Get parameters from the new type info.
1781 TypeLoc NewTL = NewTInfo->getTypeLoc();
1782 FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL);
1783 assert(NewProtoLoc && "Missing prototype?");
1784 for (unsigned i = 0, i_end = NewProtoLoc->getNumArgs(); i != i_end; ++i)
1785 Params.push_back(NewProtoLoc->getArg(i));
1786 } else {
1787 // The function type itself was not dependent and therefore no
1788 // substitution occurred. However, we still need to instantiate
1789 // the function parameters themselves.
1790 TypeLoc OldTL = OldTInfo->getTypeLoc();
1791 FunctionProtoTypeLoc *OldProtoLoc = cast<FunctionProtoTypeLoc>(&OldTL);
1792 for (unsigned i = 0, i_end = OldProtoLoc->getNumArgs(); i != i_end; ++i) {
1793 ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc->getArg(i));
1794 if (!Parm)
1795 return 0;
1796 Params.push_back(Parm);
1797 }
1798 }
John McCall21ef0fa2010-03-11 09:03:00 +00001799 return NewTInfo;
Douglas Gregor5545e162009-03-24 00:38:23 +00001800}
1801
Mike Stump1eb44332009-09-09 15:08:12 +00001802/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00001803/// declaration (New) from the corresponding fields of its template (Tmpl).
1804///
1805/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001806bool
1807TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00001808 FunctionDecl *Tmpl) {
1809 if (Tmpl->isDeleted())
1810 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00001811
Douglas Gregorcca9e962009-07-01 22:01:06 +00001812 // If we are performing substituting explicitly-specified template arguments
1813 // or deduced template arguments into a function template and we reach this
1814 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00001815 // to keeping the new function template specialization. We therefore
1816 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00001817 // into a template instantiation for this specific function template
1818 // specialization, which is not a SFINAE context, so that we diagnose any
1819 // further errors in the declaration itself.
1820 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
1821 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
1822 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
1823 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00001824 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00001825 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001826 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00001827 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00001828 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001829 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
1830 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00001831 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001832 }
1833 }
Mike Stump1eb44332009-09-09 15:08:12 +00001834
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001835 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
1836 assert(Proto && "Function template without prototype?");
1837
1838 if (Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec() ||
1839 Proto->getNoReturnAttr()) {
1840 // The function has an exception specification or a "noreturn"
1841 // attribute. Substitute into each of the exception types.
1842 llvm::SmallVector<QualType, 4> Exceptions;
1843 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
1844 // FIXME: Poor location information!
1845 QualType T
1846 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
1847 New->getLocation(), New->getDeclName());
1848 if (T.isNull() ||
1849 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
1850 continue;
1851
1852 Exceptions.push_back(T);
1853 }
1854
1855 // Rebuild the function type
1856
1857 const FunctionProtoType *NewProto
1858 = New->getType()->getAs<FunctionProtoType>();
1859 assert(NewProto && "Template instantiation without function prototype?");
1860 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
1861 NewProto->arg_type_begin(),
1862 NewProto->getNumArgs(),
1863 NewProto->isVariadic(),
1864 NewProto->getTypeQuals(),
1865 Proto->hasExceptionSpec(),
1866 Proto->hasAnyExceptionSpec(),
1867 Exceptions.size(),
1868 Exceptions.data(),
Rafael Espindola264ba482010-03-30 20:24:48 +00001869 Proto->getExtInfo()));
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001870 }
1871
Douglas Gregore53060f2009-06-25 22:08:12 +00001872 return false;
1873}
1874
Douglas Gregor5545e162009-03-24 00:38:23 +00001875/// \brief Initializes common fields of an instantiated method
1876/// declaration (New) from the corresponding fields of its template
1877/// (Tmpl).
1878///
1879/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001880bool
1881TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00001882 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00001883 if (InitFunctionInstantiation(New, Tmpl))
1884 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001885
Douglas Gregor5545e162009-03-24 00:38:23 +00001886 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
1887 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00001888 if (Tmpl->isVirtualAsWritten())
1889 Record->setMethodAsVirtual(New);
Douglas Gregor5545e162009-03-24 00:38:23 +00001890
1891 // FIXME: attributes
1892 // FIXME: New needs a pointer to Tmpl
1893 return false;
1894}
Douglas Gregora58861f2009-05-13 20:28:22 +00001895
1896/// \brief Instantiate the definition of the given function from its
1897/// template.
1898///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001899/// \param PointOfInstantiation the point at which the instantiation was
1900/// required. Note that this is not precisely a "point of instantiation"
1901/// for the function, but it's close.
1902///
Douglas Gregora58861f2009-05-13 20:28:22 +00001903/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001904/// function template specialization or member function of a class template
1905/// specialization.
1906///
1907/// \param Recursive if true, recursively instantiates any functions that
1908/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001909///
1910/// \param DefinitionRequired if true, then we are performing an explicit
1911/// instantiation where the body of the function is required. Complain if
1912/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001913void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001914 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001915 bool Recursive,
1916 bool DefinitionRequired) {
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001917 if (Function->isInvalidDecl())
1918 return;
1919
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001920 assert(!Function->getBody() && "Already instantiated!");
Mike Stump1eb44332009-09-09 15:08:12 +00001921
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001922 // Never instantiate an explicit specialization.
1923 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1924 return;
1925
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001926 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00001927 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001928 Stmt *Pattern = 0;
1929 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001930 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001931
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001932 if (!Pattern) {
1933 if (DefinitionRequired) {
1934 if (Function->getPrimaryTemplate())
1935 Diag(PointOfInstantiation,
1936 diag::err_explicit_instantiation_undefined_func_template)
1937 << Function->getPrimaryTemplate();
1938 else
1939 Diag(PointOfInstantiation,
1940 diag::err_explicit_instantiation_undefined_member)
1941 << 1 << Function->getDeclName() << Function->getDeclContext();
1942
1943 if (PatternDecl)
1944 Diag(PatternDecl->getLocation(),
1945 diag::note_explicit_instantiation_here);
1946 }
1947
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001948 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001949 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001950
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001951 // C++0x [temp.explicit]p9:
1952 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00001953 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001954 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00001955 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001956 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00001957 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001958 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001959
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001960 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
1961 if (Inst)
1962 return;
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001963
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001964 // If we're performing recursive template instantiation, create our own
1965 // queue of pending implicit instantiations that we will instantiate later,
1966 // while we're still within our own instantiation context.
1967 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1968 if (Recursive)
1969 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001970
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001971 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
1972
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001973 // Introduce a new scope where local variable instantiations will be
Douglas Gregor60406be2010-01-16 22:29:39 +00001974 // recorded, unless we're actually a member function within a local
1975 // class, in which case we need to merge our results with the parent
1976 // scope (of the enclosing function).
1977 bool MergeWithParentScope = false;
1978 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
1979 MergeWithParentScope = Rec->isLocalClass();
1980
1981 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00001982
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001983 // Introduce the instantiated function parameters into the local
1984 // instantiation scope.
1985 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
1986 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
1987 Function->getParamDecl(I));
1988
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001989 // Enter the scope of this instantiation. We don't use
1990 // PushDeclContext because we don't have a scope.
1991 DeclContext *PreviousContext = CurContext;
1992 CurContext = Function;
1993
Mike Stump1eb44332009-09-09 15:08:12 +00001994 MultiLevelTemplateArgumentList TemplateArgs =
Anders Carlsson09025312009-08-29 05:16:22 +00001995 getTemplateInstantiationArgs(Function);
1996
1997 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001998 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00001999 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
2000 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
2001 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002002 }
2003
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002004 // Instantiate the function body.
Anders Carlsson09025312009-08-29 05:16:22 +00002005 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002006
Douglas Gregor52604ab2009-09-11 21:19:12 +00002007 if (Body.isInvalid())
2008 Function->setInvalidDecl();
2009
Mike Stump1eb44332009-09-09 15:08:12 +00002010 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002011 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002012
John McCall0c01d182010-03-24 05:22:00 +00002013 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
2014
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002015 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +00002016
2017 DeclGroupRef DG(Function);
2018 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00002019
Douglas Gregor60406be2010-01-16 22:29:39 +00002020 // This class may have local implicit instantiations that need to be
2021 // instantiation within this scope.
2022 PerformPendingImplicitInstantiations(/*LocalOnly=*/true);
2023 Scope.Exit();
2024
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002025 if (Recursive) {
2026 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002027 // instantiation of this template.
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002028 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002029
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002030 // Restore the set of pending implicit instantiations.
2031 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
2032 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002033}
2034
2035/// \brief Instantiate the definition of the given variable from its
2036/// template.
2037///
Douglas Gregor7caa6822009-07-24 20:34:43 +00002038/// \param PointOfInstantiation the point at which the instantiation was
2039/// required. Note that this is not precisely a "point of instantiation"
2040/// for the function, but it's close.
2041///
2042/// \param Var the already-instantiated declaration of a static member
2043/// variable of a class template specialization.
2044///
2045/// \param Recursive if true, recursively instantiates any functions that
2046/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002047///
2048/// \param DefinitionRequired if true, then we are performing an explicit
2049/// instantiation where an out-of-line definition of the member variable
2050/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002051void Sema::InstantiateStaticDataMemberDefinition(
2052 SourceLocation PointOfInstantiation,
2053 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002054 bool Recursive,
2055 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002056 if (Var->isInvalidDecl())
2057 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002058
Douglas Gregor7caa6822009-07-24 20:34:43 +00002059 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002060 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00002061 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00002062 assert(Def->isStaticDataMember() && "Not a static data member?");
2063 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00002064
Douglas Gregor0d035142009-10-27 18:42:08 +00002065 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002066 // We did not find an out-of-line definition of this static data member,
2067 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00002068 // instantiate this definition (or provide a specialization for it) in
2069 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002070 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002071 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002072 Diag(PointOfInstantiation,
2073 diag::err_explicit_instantiation_undefined_member)
2074 << 2 << Var->getDeclName() << Var->getDeclContext();
2075 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
2076 }
2077
Douglas Gregor7caa6822009-07-24 20:34:43 +00002078 return;
2079 }
2080
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002081 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002082 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002083 return;
2084
2085 // C++0x [temp.explicit]p9:
2086 // Except for inline functions, other explicit instantiation declarations
2087 // have the effect of suppressing the implicit instantiation of the entity
2088 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002089 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002090 == TSK_ExplicitInstantiationDeclaration)
2091 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002092
Douglas Gregor7caa6822009-07-24 20:34:43 +00002093 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
2094 if (Inst)
2095 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002096
Douglas Gregor7caa6822009-07-24 20:34:43 +00002097 // If we're performing recursive template instantiation, create our own
2098 // queue of pending implicit instantiations that we will instantiate later,
2099 // while we're still within our own instantiation context.
2100 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
2101 if (Recursive)
2102 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002103
Douglas Gregor7caa6822009-07-24 20:34:43 +00002104 // Enter the scope of this instantiation. We don't use
2105 // PushDeclContext because we don't have a scope.
2106 DeclContext *PreviousContext = CurContext;
2107 CurContext = Var->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002108
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002109 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00002110 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Douglas Gregor7caa6822009-07-24 20:34:43 +00002111 getTemplateInstantiationArgs(Var)));
Douglas Gregor7caa6822009-07-24 20:34:43 +00002112 CurContext = PreviousContext;
2113
2114 if (Var) {
Douglas Gregor583f33b2009-10-15 18:07:02 +00002115 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
2116 assert(MSInfo && "Missing member specialization information?");
2117 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
2118 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00002119 DeclGroupRef DG(Var);
2120 Consumer.HandleTopLevelDecl(DG);
2121 }
Mike Stump1eb44332009-09-09 15:08:12 +00002122
Douglas Gregor7caa6822009-07-24 20:34:43 +00002123 if (Recursive) {
2124 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002125 // instantiation of this template.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002126 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002127
Douglas Gregor7caa6822009-07-24 20:34:43 +00002128 // Restore the set of pending implicit instantiations.
2129 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002130 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002131}
Douglas Gregor815215d2009-05-27 05:35:12 +00002132
Anders Carlsson09025312009-08-29 05:16:22 +00002133void
2134Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
2135 const CXXConstructorDecl *Tmpl,
2136 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002137
Anders Carlsson09025312009-08-29 05:16:22 +00002138 llvm::SmallVector<MemInitTy*, 4> NewInits;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002139 bool AnyErrors = false;
2140
Anders Carlsson09025312009-08-29 05:16:22 +00002141 // Instantiate all the initializers.
2142 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00002143 InitsEnd = Tmpl->init_end();
2144 Inits != InitsEnd; ++Inits) {
Anders Carlsson09025312009-08-29 05:16:22 +00002145 CXXBaseOrMemberInitializer *Init = *Inits;
2146
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002147 SourceLocation LParenLoc, RParenLoc;
Anders Carlsson09025312009-08-29 05:16:22 +00002148 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002149 llvm::SmallVector<SourceLocation, 4> CommaLocs;
Mike Stump1eb44332009-09-09 15:08:12 +00002150
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002151 // Instantiate the initializer.
2152 if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs,
2153 LParenLoc, CommaLocs, NewArgs, RParenLoc)) {
2154 AnyErrors = true;
2155 continue;
Anders Carlsson09025312009-08-29 05:16:22 +00002156 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002157
Anders Carlsson09025312009-08-29 05:16:22 +00002158 MemInitResult NewInit;
Anders Carlsson09025312009-08-29 05:16:22 +00002159 if (Init->isBaseInitializer()) {
John McCalla93c9342009-12-07 02:54:59 +00002160 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002161 TemplateArgs,
2162 Init->getSourceLocation(),
2163 New->getDeclName());
John McCalla93c9342009-12-07 02:54:59 +00002164 if (!BaseTInfo) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002165 AnyErrors = true;
Douglas Gregor802ab452009-12-02 22:36:29 +00002166 New->setInvalidDecl();
2167 continue;
2168 }
2169
John McCalla93c9342009-12-07 02:54:59 +00002170 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00002171 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002172 NewArgs.size(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002173 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002174 Init->getRParenLoc(),
2175 New->getParent());
2176 } else if (Init->isMemberInitializer()) {
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002177 FieldDecl *Member;
Mike Stump1eb44332009-09-09 15:08:12 +00002178
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002179 // Is this an anonymous union?
2180 if (FieldDecl *UnionInit = Init->getAnonUnionMember())
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002181 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(),
2182 UnionInit, TemplateArgs));
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002183 else
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002184 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(),
2185 Init->getMember(),
Douglas Gregore95b4092009-09-16 18:34:49 +00002186 TemplateArgs));
Mike Stump1eb44332009-09-09 15:08:12 +00002187
2188 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002189 NewArgs.size(),
2190 Init->getSourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002191 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002192 Init->getRParenLoc());
2193 }
2194
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002195 if (NewInit.isInvalid()) {
2196 AnyErrors = true;
Anders Carlsson09025312009-08-29 05:16:22 +00002197 New->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002198 } else {
Anders Carlsson09025312009-08-29 05:16:22 +00002199 // FIXME: It would be nice if ASTOwningVector had a release function.
2200 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00002201
Anders Carlsson09025312009-08-29 05:16:22 +00002202 NewInits.push_back((MemInitTy *)NewInit.get());
2203 }
2204 }
Mike Stump1eb44332009-09-09 15:08:12 +00002205
Anders Carlsson09025312009-08-29 05:16:22 +00002206 // Assign all the initializers to the new constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00002207 ActOnMemInitializers(DeclPtrTy::make(New),
Anders Carlsson09025312009-08-29 05:16:22 +00002208 /*FIXME: ColonLoc */
2209 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002210 NewInits.data(), NewInits.size(),
2211 AnyErrors);
Anders Carlsson09025312009-08-29 05:16:22 +00002212}
2213
John McCall52a575a2009-08-29 08:11:13 +00002214// TODO: this could be templated if the various decl types used the
2215// same method name.
2216static bool isInstantiationOf(ClassTemplateDecl *Pattern,
2217 ClassTemplateDecl *Instance) {
2218 Pattern = Pattern->getCanonicalDecl();
2219
2220 do {
2221 Instance = Instance->getCanonicalDecl();
2222 if (Pattern == Instance) return true;
2223 Instance = Instance->getInstantiatedFromMemberTemplate();
2224 } while (Instance);
2225
2226 return false;
2227}
2228
Douglas Gregor0d696532009-09-28 06:34:35 +00002229static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
2230 FunctionTemplateDecl *Instance) {
2231 Pattern = Pattern->getCanonicalDecl();
2232
2233 do {
2234 Instance = Instance->getCanonicalDecl();
2235 if (Pattern == Instance) return true;
2236 Instance = Instance->getInstantiatedFromMemberTemplate();
2237 } while (Instance);
2238
2239 return false;
2240}
2241
Douglas Gregored9c0f92009-10-29 00:04:11 +00002242static bool
2243isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
2244 ClassTemplatePartialSpecializationDecl *Instance) {
2245 Pattern
2246 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
2247 do {
2248 Instance = cast<ClassTemplatePartialSpecializationDecl>(
2249 Instance->getCanonicalDecl());
2250 if (Pattern == Instance)
2251 return true;
2252 Instance = Instance->getInstantiatedFromMember();
2253 } while (Instance);
2254
2255 return false;
2256}
2257
John McCall52a575a2009-08-29 08:11:13 +00002258static bool isInstantiationOf(CXXRecordDecl *Pattern,
2259 CXXRecordDecl *Instance) {
2260 Pattern = Pattern->getCanonicalDecl();
2261
2262 do {
2263 Instance = Instance->getCanonicalDecl();
2264 if (Pattern == Instance) return true;
2265 Instance = Instance->getInstantiatedFromMemberClass();
2266 } while (Instance);
2267
2268 return false;
2269}
2270
2271static bool isInstantiationOf(FunctionDecl *Pattern,
2272 FunctionDecl *Instance) {
2273 Pattern = Pattern->getCanonicalDecl();
2274
2275 do {
2276 Instance = Instance->getCanonicalDecl();
2277 if (Pattern == Instance) return true;
2278 Instance = Instance->getInstantiatedFromMemberFunction();
2279 } while (Instance);
2280
2281 return false;
2282}
2283
2284static bool isInstantiationOf(EnumDecl *Pattern,
2285 EnumDecl *Instance) {
2286 Pattern = Pattern->getCanonicalDecl();
2287
2288 do {
2289 Instance = Instance->getCanonicalDecl();
2290 if (Pattern == Instance) return true;
2291 Instance = Instance->getInstantiatedFromMemberEnum();
2292 } while (Instance);
2293
2294 return false;
2295}
2296
John McCalled976492009-12-04 22:46:56 +00002297static bool isInstantiationOf(UsingShadowDecl *Pattern,
2298 UsingShadowDecl *Instance,
2299 ASTContext &C) {
2300 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
2301}
2302
2303static bool isInstantiationOf(UsingDecl *Pattern,
2304 UsingDecl *Instance,
2305 ASTContext &C) {
2306 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
2307}
2308
John McCall7ba107a2009-11-18 02:36:19 +00002309static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
2310 UsingDecl *Instance,
2311 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002312 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00002313}
2314
2315static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00002316 UsingDecl *Instance,
2317 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002318 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00002319}
2320
John McCall52a575a2009-08-29 08:11:13 +00002321static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
2322 VarDecl *Instance) {
2323 assert(Instance->isStaticDataMember());
2324
2325 Pattern = Pattern->getCanonicalDecl();
2326
2327 do {
2328 Instance = Instance->getCanonicalDecl();
2329 if (Pattern == Instance) return true;
2330 Instance = Instance->getInstantiatedFromStaticDataMember();
2331 } while (Instance);
2332
2333 return false;
2334}
2335
John McCalled976492009-12-04 22:46:56 +00002336// Other is the prospective instantiation
2337// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00002338static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002339 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00002340 if (UnresolvedUsingTypenameDecl *UUD
2341 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
2342 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2343 return isInstantiationOf(UUD, UD, Ctx);
2344 }
2345 }
2346
2347 if (UnresolvedUsingValueDecl *UUD
2348 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002349 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2350 return isInstantiationOf(UUD, UD, Ctx);
2351 }
2352 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002353
Anders Carlsson0d8df782009-08-29 19:37:28 +00002354 return false;
2355 }
Mike Stump1eb44332009-09-09 15:08:12 +00002356
John McCall52a575a2009-08-29 08:11:13 +00002357 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
2358 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00002359
John McCall52a575a2009-08-29 08:11:13 +00002360 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
2361 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00002362
John McCall52a575a2009-08-29 08:11:13 +00002363 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
2364 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00002365
Douglas Gregor7caa6822009-07-24 20:34:43 +00002366 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00002367 if (Var->isStaticDataMember())
2368 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
2369
2370 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
2371 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00002372
Douglas Gregor0d696532009-09-28 06:34:35 +00002373 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
2374 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
2375
Douglas Gregored9c0f92009-10-29 00:04:11 +00002376 if (ClassTemplatePartialSpecializationDecl *PartialSpec
2377 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
2378 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
2379 PartialSpec);
2380
Anders Carlssond8b285f2009-09-01 04:26:58 +00002381 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
2382 if (!Field->getDeclName()) {
2383 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00002384 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00002385 cast<FieldDecl>(D);
2386 }
2387 }
Mike Stump1eb44332009-09-09 15:08:12 +00002388
John McCalled976492009-12-04 22:46:56 +00002389 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
2390 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
2391
2392 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
2393 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
2394
Douglas Gregor815215d2009-05-27 05:35:12 +00002395 return D->getDeclName() && isa<NamedDecl>(Other) &&
2396 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
2397}
2398
2399template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00002400static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00002401 NamedDecl *D,
2402 ForwardIterator first,
2403 ForwardIterator last) {
2404 for (; first != last; ++first)
2405 if (isInstantiationOf(Ctx, D, *first))
2406 return cast<NamedDecl>(*first);
2407
2408 return 0;
2409}
2410
John McCall02cace72009-08-28 07:59:38 +00002411/// \brief Finds the instantiation of the given declaration context
2412/// within the current instantiation.
2413///
2414/// \returns NULL if there was an error
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002415DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregore95b4092009-09-16 18:34:49 +00002416 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00002417 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002418 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00002419 return cast_or_null<DeclContext>(ID);
2420 } else return DC;
2421}
2422
Douglas Gregored961e72009-05-27 17:54:46 +00002423/// \brief Find the instantiation of the given declaration within the
2424/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00002425///
2426/// This routine is intended to be used when \p D is a declaration
2427/// referenced from within a template, that needs to mapped into the
2428/// corresponding declaration within an instantiation. For example,
2429/// given:
2430///
2431/// \code
2432/// template<typename T>
2433/// struct X {
2434/// enum Kind {
2435/// KnownValue = sizeof(T)
2436/// };
2437///
2438/// bool getKind() const { return KnownValue; }
2439/// };
2440///
2441/// template struct X<int>;
2442/// \endcode
2443///
2444/// In the instantiation of X<int>::getKind(), we need to map the
2445/// EnumConstantDecl for KnownValue (which refers to
2446/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00002447/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2448/// this mapping from within the instantiation of X<int>.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002449NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregore95b4092009-09-16 18:34:49 +00002450 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00002451 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00002452 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregor6d3e6272010-02-05 19:54:12 +00002453 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
Douglas Gregor550d9b22009-10-31 17:21:17 +00002454 ParentDC->isFunctionOrMethod()) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002455 // D is a local of some kind. Look into the map of local
2456 // declarations to their instantiations.
2457 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
2458 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002459
Douglas Gregore95b4092009-09-16 18:34:49 +00002460 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
2461 if (!Record->isDependentContext())
2462 return D;
2463
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002464 // If the RecordDecl is actually the injected-class-name or a
2465 // "templated" declaration for a class template, class template
2466 // partial specialization, or a member class of a class template,
2467 // substitute into the injected-class-name of the class template
2468 // or partial specialization to find the new DeclContext.
Douglas Gregore95b4092009-09-16 18:34:49 +00002469 QualType T;
2470 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
2471
2472 if (ClassTemplate) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002473 T = ClassTemplate->getInjectedClassNameSpecialization(Context);
Douglas Gregore95b4092009-09-16 18:34:49 +00002474 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2475 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
Douglas Gregore95b4092009-09-16 18:34:49 +00002476 ClassTemplate = PartialSpec->getSpecializedTemplate();
John McCall3cb0ebd2010-03-10 03:28:59 +00002477
2478 // If we call SubstType with an InjectedClassNameType here we
2479 // can end up in an infinite loop.
2480 T = Context.getTypeDeclType(Record);
2481 assert(isa<InjectedClassNameType>(T) &&
2482 "type of partial specialization is not an InjectedClassNameType");
2483 T = cast<InjectedClassNameType>(T)->getUnderlyingType();
2484 }
Douglas Gregore95b4092009-09-16 18:34:49 +00002485
2486 if (!T.isNull()) {
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002487 // Substitute into the injected-class-name to get the type
2488 // corresponding to the instantiation we want, which may also be
2489 // the current instantiation (if we're in a template
2490 // definition). This substitution should never fail, since we
2491 // know we can instantiate the injected-class-name or we
2492 // wouldn't have gotten to the injected-class-name!
2493
2494 // FIXME: Can we use the CurrentInstantiationScope to avoid this
2495 // extra instantiation in the common case?
Douglas Gregore95b4092009-09-16 18:34:49 +00002496 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
2497 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
2498
2499 if (!T->isDependentType()) {
2500 assert(T->isRecordType() && "Instantiation must produce a record type");
2501 return T->getAs<RecordType>()->getDecl();
2502 }
2503
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002504 // We are performing "partial" template instantiation to create
2505 // the member declarations for the members of a class template
2506 // specialization. Therefore, D is actually referring to something
2507 // in the current instantiation. Look through the current
2508 // context, which contains actual instantiations, to find the
2509 // instantiation of the "current instantiation" that D refers
2510 // to.
2511 bool SawNonDependentContext = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002512 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00002513 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002514 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002515 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00002516 if (isInstantiationOf(ClassTemplate,
2517 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00002518 return Spec;
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002519
2520 if (!DC->isDependentContext())
2521 SawNonDependentContext = true;
John McCall52a575a2009-08-29 08:11:13 +00002522 }
2523
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002524 // We're performing "instantiation" of a member of the current
2525 // instantiation while we are type-checking the
2526 // definition. Compute the declaration context and return that.
2527 assert(!SawNonDependentContext &&
2528 "No dependent context while instantiating record");
2529 DeclContext *DC = computeDeclContext(T);
2530 assert(DC &&
John McCall52a575a2009-08-29 08:11:13 +00002531 "Unable to find declaration for the current instantiation");
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002532 return cast<CXXRecordDecl>(DC);
John McCall52a575a2009-08-29 08:11:13 +00002533 }
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002534
Douglas Gregore95b4092009-09-16 18:34:49 +00002535 // Fall through to deal with other dependent record types (e.g.,
2536 // anonymous unions in class templates).
2537 }
John McCall52a575a2009-08-29 08:11:13 +00002538
Douglas Gregore95b4092009-09-16 18:34:49 +00002539 if (!ParentDC->isDependentContext())
2540 return D;
2541
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002542 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002543 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00002544 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002545
Douglas Gregor815215d2009-05-27 05:35:12 +00002546 if (ParentDC != D->getDeclContext()) {
2547 // We performed some kind of instantiation in the parent context,
2548 // so now we need to look into the instantiated parent context to
2549 // find the instantiation of the declaration D.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002550
John McCall3cb0ebd2010-03-10 03:28:59 +00002551 // If our context used to be dependent, we may need to instantiate
2552 // it before performing lookup into that context.
2553 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002554 if (!Spec->isDependentContext()) {
2555 QualType T = Context.getTypeDeclType(Spec);
John McCall3cb0ebd2010-03-10 03:28:59 +00002556 const RecordType *Tag = T->getAs<RecordType>();
2557 assert(Tag && "type of non-dependent record is not a RecordType");
2558 if (!Tag->isBeingDefined() &&
2559 RequireCompleteType(Loc, T, diag::err_incomplete_type))
2560 return 0;
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002561 }
2562 }
2563
Douglas Gregor815215d2009-05-27 05:35:12 +00002564 NamedDecl *Result = 0;
2565 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002566 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00002567 Result = findInstantiationOf(Context, D, Found.first, Found.second);
2568 } else {
2569 // Since we don't have a name for the entity we're looking for,
2570 // our only option is to walk through all of the declarations to
2571 // find that name. This will occur in a few cases:
2572 //
2573 // - anonymous struct/union within a template
2574 // - unnamed class/struct/union/enum within a template
2575 //
2576 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00002577 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002578 ParentDC->decls_begin(),
2579 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00002580 }
Mike Stump1eb44332009-09-09 15:08:12 +00002581
John McCall9f54ad42009-12-10 09:41:52 +00002582 // UsingShadowDecls can instantiate to nothing because of using hiding.
Douglas Gregor00225542010-03-01 18:27:54 +00002583 assert((Result || isa<UsingShadowDecl>(D) || D->isInvalidDecl() ||
2584 cast<Decl>(ParentDC)->isInvalidDecl())
John McCall9f54ad42009-12-10 09:41:52 +00002585 && "Unable to find instantiation of declaration!");
2586
Douglas Gregor815215d2009-05-27 05:35:12 +00002587 D = Result;
2588 }
2589
Douglas Gregor815215d2009-05-27 05:35:12 +00002590 return D;
2591}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002592
Mike Stump1eb44332009-09-09 15:08:12 +00002593/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002594/// instantiations we have seen until this point.
Douglas Gregor60406be2010-01-16 22:29:39 +00002595void Sema::PerformPendingImplicitInstantiations(bool LocalOnly) {
2596 while (!PendingLocalImplicitInstantiations.empty() ||
2597 (!LocalOnly && !PendingImplicitInstantiations.empty())) {
2598 PendingImplicitInstantiation Inst;
2599
2600 if (PendingLocalImplicitInstantiations.empty()) {
2601 Inst = PendingImplicitInstantiations.front();
2602 PendingImplicitInstantiations.pop_front();
2603 } else {
2604 Inst = PendingLocalImplicitInstantiations.front();
2605 PendingLocalImplicitInstantiations.pop_front();
2606 }
Mike Stump1eb44332009-09-09 15:08:12 +00002607
Douglas Gregor7caa6822009-07-24 20:34:43 +00002608 // Instantiate function definitions
2609 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002610 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002611 Function->getLocation(), *this,
2612 Context.getSourceManager(),
2613 "instantiating function definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002614
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002615 if (!Function->getBody())
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002616 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00002617 continue;
2618 }
Mike Stump1eb44332009-09-09 15:08:12 +00002619
Douglas Gregor7caa6822009-07-24 20:34:43 +00002620 // Instantiate static data member definitions.
2621 VarDecl *Var = cast<VarDecl>(Inst.first);
2622 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002623
Chandler Carruth291b4412010-02-13 10:17:50 +00002624 // Don't try to instantiate declarations if the most recent redeclaration
2625 // is invalid.
2626 if (Var->getMostRecentDeclaration()->isInvalidDecl())
2627 continue;
2628
2629 // Check if the most recent declaration has changed the specialization kind
2630 // and removed the need for implicit instantiation.
2631 switch (Var->getMostRecentDeclaration()->getTemplateSpecializationKind()) {
2632 case TSK_Undeclared:
2633 assert(false && "Cannot instantitiate an undeclared specialization.");
2634 case TSK_ExplicitInstantiationDeclaration:
2635 case TSK_ExplicitInstantiationDefinition:
2636 case TSK_ExplicitSpecialization:
2637 continue; // No longer need implicit instantiation.
2638 case TSK_ImplicitInstantiation:
2639 break;
2640 }
2641
Mike Stump1eb44332009-09-09 15:08:12 +00002642 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002643 Var->getLocation(), *this,
2644 Context.getSourceManager(),
2645 "instantiating static data member "
2646 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002647
Douglas Gregor7caa6822009-07-24 20:34:43 +00002648 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002649 }
2650}
John McCall0c01d182010-03-24 05:22:00 +00002651
2652void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
2653 const MultiLevelTemplateArgumentList &TemplateArgs) {
2654 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
2655 E = Pattern->ddiag_end(); I != E; ++I) {
2656 DependentDiagnostic *DD = *I;
2657
2658 switch (DD->getKind()) {
2659 case DependentDiagnostic::Access:
2660 HandleDependentAccessCheck(*DD, TemplateArgs);
2661 break;
2662 }
2663 }
2664}