blob: 10fe176148f0aeb44ee7718702d5c4f4cb43beeb [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,
Douglas Gregor16573fa2010-04-19 22:54:31 +0000325 D->getStorageClass(),
326 D->getStorageClassAsWritten());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000327 Var->setThreadSpecified(D->isThreadSpecified());
328 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
329 Var->setDeclaredInCondition(D->isDeclaredInCondition());
Mike Stump1eb44332009-09-09 15:08:12 +0000330
John McCallb6217662010-03-15 10:12:16 +0000331 // Substitute the nested name specifier, if any.
332 if (SubstQualifier(D, Var))
333 return 0;
334
Mike Stump1eb44332009-09-09 15:08:12 +0000335 // If we are instantiating a static data member defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000336 // out-of-line, the instantiation will have the same lexical
337 // context (which will be a namespace scope) as the template.
338 if (D->isOutOfLine())
339 Var->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000340
John McCall46460a62010-01-20 21:53:11 +0000341 Var->setAccess(D->getAccess());
342
Mike Stump390b4cc2009-05-16 07:39:55 +0000343 // FIXME: In theory, we could have a previous declaration for variables that
344 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000345 bool Redeclaration = false;
John McCall68263142009-11-18 22:49:29 +0000346 // FIXME: having to fake up a LookupResult is dumb.
347 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
Douglas Gregor449d0a82010-03-01 19:11:54 +0000348 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Douglas Gregor60c93c92010-02-09 07:26:29 +0000349 if (D->isStaticDataMember())
350 SemaRef.LookupQualifiedName(Previous, Owner, false);
John McCall68263142009-11-18 22:49:29 +0000351 SemaRef.CheckVariableDeclaration(Var, Previous, Redeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000352
Douglas Gregor7caa6822009-07-24 20:34:43 +0000353 if (D->isOutOfLine()) {
354 D->getLexicalDeclContext()->addDecl(Var);
355 Owner->makeDeclVisibleInContext(Var);
356 } else {
357 Owner->addDecl(Var);
358 }
Mike Stump1eb44332009-09-09 15:08:12 +0000359
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000360 // Link instantiations of static data members back to the template from
361 // which they were instantiated.
362 if (Var->isStaticDataMember())
363 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000364 TSK_ImplicitInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000365
Douglas Gregor60c93c92010-02-09 07:26:29 +0000366 if (Var->getAnyInitializer()) {
367 // We already have an initializer in the class.
368 } else if (D->getInit()) {
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000369 if (Var->isStaticDataMember() && !D->isOutOfLine())
370 SemaRef.PushExpressionEvaluationContext(Sema::Unevaluated);
371 else
372 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
373
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000374 // Instantiate the initializer.
375 SourceLocation LParenLoc, RParenLoc;
376 llvm::SmallVector<SourceLocation, 4> CommaLocs;
377 ASTOwningVector<&ActionBase::DeleteExpr> InitArgs(SemaRef);
378 if (!InstantiateInitializer(SemaRef, D->getInit(), TemplateArgs, LParenLoc,
379 CommaLocs, InitArgs, RParenLoc)) {
380 // Attach the initializer to the declaration.
381 if (D->hasCXXDirectInitializer()) {
Douglas Gregor6eef5192009-12-14 19:27:10 +0000382 // Add the direct initializer to the declaration.
Douglas Gregora88cfbf2009-12-12 18:16:41 +0000383 SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var),
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000384 LParenLoc,
Douglas Gregor6eef5192009-12-14 19:27:10 +0000385 move_arg(InitArgs),
386 CommaLocs.data(),
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000387 RParenLoc);
388 } else if (InitArgs.size() == 1) {
389 Expr *Init = (Expr*)(InitArgs.take()[0]);
390 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var),
391 SemaRef.Owned(Init),
392 false);
393 } else {
394 assert(InitArgs.size() == 0);
395 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor6eef5192009-12-14 19:27:10 +0000396 }
Douglas Gregor6eef5192009-12-14 19:27:10 +0000397 } else {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000398 // FIXME: Not too happy about invalidating the declaration
399 // because of a bogus initializer.
400 Var->setInvalidDecl();
Douglas Gregor6eef5192009-12-14 19:27:10 +0000401 }
402
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000403 SemaRef.PopExpressionEvaluationContext();
Douglas Gregor65b90052009-07-27 17:43:39 +0000404 } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
405 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000406
407 return Var;
408}
409
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000410Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
411 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000412 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000413 if (DI->getType()->isDependentType()) {
414 DI = SemaRef.SubstType(DI, TemplateArgs,
415 D->getLocation(), D->getDeclName());
416 if (!DI) {
John McCalla93c9342009-12-07 02:54:59 +0000417 DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000418 Invalid = true;
419 } else if (DI->getType()->isFunctionType()) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000420 // C++ [temp.arg.type]p3:
421 // If a declaration acquires a function type through a type
422 // dependent on a template-parameter and this causes a
423 // declaration that does not use the syntactic form of a
424 // function declarator to have function type, the program is
425 // ill-formed.
426 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall07fb6be2009-10-22 23:33:21 +0000427 << DI->getType();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000428 Invalid = true;
429 }
430 }
431
432 Expr *BitWidth = D->getBitWidth();
433 if (Invalid)
434 BitWidth = 0;
435 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000436 // The bit-width expression is not potentially evaluated.
437 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000438
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000439 OwningExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000440 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000441 if (InstantiatedBitWidth.isInvalid()) {
442 Invalid = true;
443 BitWidth = 0;
444 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000445 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000446 }
447
John McCall07fb6be2009-10-22 23:33:21 +0000448 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
449 DI->getType(), DI,
Mike Stump1eb44332009-09-09 15:08:12 +0000450 cast<RecordDecl>(Owner),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000451 D->getLocation(),
452 D->isMutable(),
453 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000454 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000455 D->getAccess(),
456 0);
Douglas Gregor663b5a02009-10-14 20:14:33 +0000457 if (!Field) {
458 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000459 return 0;
Douglas Gregor663b5a02009-10-14 20:14:33 +0000460 }
Mike Stump1eb44332009-09-09 15:08:12 +0000461
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000462 InstantiateAttrs(D, Field);
463
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000464 if (Invalid)
465 Field->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000466
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000467 if (!Field->getDeclName()) {
468 // Keep track of where this decl came from.
469 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000470 }
Mike Stump1eb44332009-09-09 15:08:12 +0000471
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000472 Field->setImplicit(D->isImplicit());
John McCall46460a62010-01-20 21:53:11 +0000473 Field->setAccess(D->getAccess());
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000474 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000475
476 return Field;
477}
478
John McCall02cace72009-08-28 07:59:38 +0000479Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
John McCall02cace72009-08-28 07:59:38 +0000480 // Handle friend type expressions by simply substituting template
Douglas Gregor06245bf2010-04-07 17:57:12 +0000481 // parameters into the pattern type and checking the result.
John McCall32f2fb52010-03-25 18:04:51 +0000482 if (TypeSourceInfo *Ty = D->getFriendType()) {
483 TypeSourceInfo *InstTy =
484 SemaRef.SubstType(Ty, TemplateArgs,
485 D->getLocation(), DeclarationName());
Douglas Gregor06245bf2010-04-07 17:57:12 +0000486 if (!InstTy)
Douglas Gregor7557a132009-12-24 20:56:24 +0000487 return 0;
John McCall02cace72009-08-28 07:59:38 +0000488
Douglas Gregor06245bf2010-04-07 17:57:12 +0000489 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getFriendLoc(), InstTy);
490 if (!FD)
491 return 0;
492
493 FD->setAccess(AS_public);
494 Owner->addDecl(FD);
495 return FD;
496 }
497
498 NamedDecl *ND = D->getFriendDecl();
499 assert(ND && "friend decl must be a decl or a type!");
500
John McCallaf2094e2010-04-08 09:05:18 +0000501 // All of the Visit implementations for the various potential friend
502 // declarations have to be carefully written to work for friend
503 // objects, with the most important detail being that the target
504 // decl should almost certainly not be placed in Owner.
505 Decl *NewND = Visit(ND);
Douglas Gregor06245bf2010-04-07 17:57:12 +0000506 if (!NewND) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000507
John McCall02cace72009-08-28 07:59:38 +0000508 FriendDecl *FD =
Douglas Gregor06245bf2010-04-07 17:57:12 +0000509 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
510 cast<NamedDecl>(NewND), D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000511 FD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +0000512 Owner->addDecl(FD);
513 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000514}
515
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000516Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
517 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000518
Douglas Gregorac7610d2009-06-22 20:57:11 +0000519 // The expression in a static assertion is not potentially evaluated.
520 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000521
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000522 OwningExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000523 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000524 if (InstantiatedAssertExpr.isInvalid())
525 return 0;
526
Douglas Gregor43d9d922009-08-08 01:41:12 +0000527 OwningExprResult Message(SemaRef, D->getMessage());
528 D->getMessage()->Retain();
Mike Stump1eb44332009-09-09 15:08:12 +0000529 Decl *StaticAssert
530 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
Chris Lattnerb28317a2009-03-28 19:18:32 +0000531 move(InstantiatedAssertExpr),
532 move(Message)).getAs<Decl>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000533 return StaticAssert;
534}
535
536Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +0000537 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000538 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000539 D->getTagKeywordLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000540 /*PrevDecl=*/0);
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000541 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000542 Enum->setAccess(D->getAccess());
John McCallb6217662010-03-15 10:12:16 +0000543 if (SubstQualifier(D, Enum)) return 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000544 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000545 Enum->startDefinition();
546
Douglas Gregor96084f12010-03-01 19:00:07 +0000547 if (D->getDeclContext()->isFunctionOrMethod())
548 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
549
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000550 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000551
552 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000553 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
554 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000555 EC != ECEnd; ++EC) {
556 // The specified value for the enumerator.
557 OwningExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000558 if (Expr *UninstValue = EC->getInitExpr()) {
559 // The enumerator's value expression is not potentially evaluated.
Mike Stump1eb44332009-09-09 15:08:12 +0000560 EnterExpressionEvaluationContext Unevaluated(SemaRef,
Douglas Gregorac7610d2009-06-22 20:57:11 +0000561 Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000562
John McCallce3ff2b2009-08-25 22:02:44 +0000563 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000564 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000565
566 // Drop the initial value and continue.
567 bool isInvalid = false;
568 if (Value.isInvalid()) {
569 Value = SemaRef.Owned((Expr *)0);
570 isInvalid = true;
571 }
572
Mike Stump1eb44332009-09-09 15:08:12 +0000573 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000574 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
575 EC->getLocation(), EC->getIdentifier(),
576 move(Value));
577
578 if (isInvalid) {
579 if (EnumConst)
580 EnumConst->setInvalidDecl();
581 Enum->setInvalidDecl();
582 }
583
584 if (EnumConst) {
John McCall3b85ecf2010-01-23 22:37:59 +0000585 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000586 Enum->addDecl(EnumConst);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000587 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000588 LastEnumConst = EnumConst;
Douglas Gregor96084f12010-03-01 19:00:07 +0000589
590 if (D->getDeclContext()->isFunctionOrMethod()) {
591 // If the enumeration is within a function or method, record the enum
592 // constant as a local.
593 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
594 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000595 }
596 }
Mike Stump1eb44332009-09-09 15:08:12 +0000597
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000598 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000599 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000600 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
601 Sema::DeclPtrTy::make(Enum),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000602 &Enumerators[0], Enumerators.size(),
603 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000604
605 return Enum;
606}
607
Douglas Gregor6477b692009-03-25 15:04:13 +0000608Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
609 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
610 return 0;
611}
612
Douglas Gregored9c0f92009-10-29 00:04:11 +0000613namespace {
614 class SortDeclByLocation {
615 SourceManager &SourceMgr;
616
617 public:
618 explicit SortDeclByLocation(SourceManager &SourceMgr)
619 : SourceMgr(SourceMgr) { }
620
621 bool operator()(const Decl *X, const Decl *Y) const {
622 return SourceMgr.isBeforeInTranslationUnit(X->getLocation(),
623 Y->getLocation());
624 }
625 };
626}
627
John McCalle29ba202009-08-20 01:44:21 +0000628Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
John McCall93ba8572010-03-25 06:39:04 +0000629 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
630
Douglas Gregor550d9b22009-10-31 17:21:17 +0000631 // Create a local instantiation scope for this class template, which
632 // will contain the instantiations of the template parameters.
633 Sema::LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000634 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000635 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000636 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000637 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000638
639 CXXRecordDecl *Pattern = D->getTemplatedDecl();
John McCall93ba8572010-03-25 06:39:04 +0000640
641 // Instantiate the qualifier. We have to do this first in case
642 // we're a friend declaration, because if we are then we need to put
643 // the new declaration in the appropriate context.
644 NestedNameSpecifier *Qualifier = Pattern->getQualifier();
645 if (Qualifier) {
646 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
647 Pattern->getQualifierRange(),
648 TemplateArgs);
649 if (!Qualifier) return 0;
650 }
651
652 CXXRecordDecl *PrevDecl = 0;
653 ClassTemplateDecl *PrevClassTemplate = 0;
654
655 // If this isn't a friend, then it's a member template, in which
656 // case we just want to build the instantiation in the
657 // specialization. If it is a friend, we want to build it in
658 // the appropriate context.
659 DeclContext *DC = Owner;
660 if (isFriend) {
661 if (Qualifier) {
662 CXXScopeSpec SS;
663 SS.setScopeRep(Qualifier);
664 SS.setRange(Pattern->getQualifierRange());
665 DC = SemaRef.computeDeclContext(SS);
666 if (!DC) return 0;
667 } else {
668 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
669 Pattern->getDeclContext(),
670 TemplateArgs);
671 }
672
673 // Look for a previous declaration of the template in the owning
674 // context.
675 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
676 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
677 SemaRef.LookupQualifiedName(R, DC);
678
679 if (R.isSingleResult()) {
680 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
681 if (PrevClassTemplate)
682 PrevDecl = PrevClassTemplate->getTemplatedDecl();
683 }
684
685 if (!PrevClassTemplate && Qualifier) {
686 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
Douglas Gregor1eabb7d2010-03-31 23:17:41 +0000687 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
688 << Pattern->getQualifierRange();
John McCall93ba8572010-03-25 06:39:04 +0000689 return 0;
690 }
691
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000692 bool AdoptedPreviousTemplateParams = false;
John McCall93ba8572010-03-25 06:39:04 +0000693 if (PrevClassTemplate) {
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000694 bool Complain = true;
695
696 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
697 // template for struct std::tr1::__detail::_Map_base, where the
698 // template parameters of the friend declaration don't match the
699 // template parameters of the original declaration. In this one
700 // case, we don't complain about the ill-formed friend
701 // declaration.
702 if (isFriend && Pattern->getIdentifier() &&
703 Pattern->getIdentifier()->isStr("_Map_base") &&
704 DC->isNamespace() &&
705 cast<NamespaceDecl>(DC)->getIdentifier() &&
706 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
707 DeclContext *DCParent = DC->getParent();
708 if (DCParent->isNamespace() &&
709 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
710 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
711 DeclContext *DCParent2 = DCParent->getParent();
712 if (DCParent2->isNamespace() &&
713 cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
714 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
715 DCParent2->getParent()->isTranslationUnit())
716 Complain = false;
717 }
718 }
719
John McCall93ba8572010-03-25 06:39:04 +0000720 TemplateParameterList *PrevParams
721 = PrevClassTemplate->getTemplateParameters();
722
723 // Make sure the parameter lists match.
724 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000725 Complain,
726 Sema::TPL_TemplateMatch)) {
727 if (Complain)
728 return 0;
729
730 AdoptedPreviousTemplateParams = true;
731 InstParams = PrevParams;
732 }
John McCall93ba8572010-03-25 06:39:04 +0000733
734 // Do some additional validation, then merge default arguments
735 // from the existing declarations.
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000736 if (!AdoptedPreviousTemplateParams &&
737 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
John McCall93ba8572010-03-25 06:39:04 +0000738 Sema::TPC_ClassTemplate))
739 return 0;
740 }
741 }
742
John McCalle29ba202009-08-20 01:44:21 +0000743 CXXRecordDecl *RecordInst
John McCall93ba8572010-03-25 06:39:04 +0000744 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
John McCalle29ba202009-08-20 01:44:21 +0000745 Pattern->getLocation(), Pattern->getIdentifier(),
John McCall93ba8572010-03-25 06:39:04 +0000746 Pattern->getTagKeywordLoc(), PrevDecl,
Douglas Gregorf0510d42009-10-12 23:11:44 +0000747 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000748
John McCall93ba8572010-03-25 06:39:04 +0000749 if (Qualifier)
750 RecordInst->setQualifierInfo(Qualifier, Pattern->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +0000751
John McCalle29ba202009-08-20 01:44:21 +0000752 ClassTemplateDecl *Inst
John McCall93ba8572010-03-25 06:39:04 +0000753 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
754 D->getIdentifier(), InstParams, RecordInst,
755 PrevClassTemplate);
John McCalle29ba202009-08-20 01:44:21 +0000756 RecordInst->setDescribedClassTemplate(Inst);
John McCallea7390c2010-04-08 20:25:50 +0000757
John McCall93ba8572010-03-25 06:39:04 +0000758 if (isFriend) {
John McCallea7390c2010-04-08 20:25:50 +0000759 if (PrevClassTemplate)
760 Inst->setAccess(PrevClassTemplate->getAccess());
761 else
762 Inst->setAccess(D->getAccess());
763
John McCall93ba8572010-03-25 06:39:04 +0000764 Inst->setObjectOfFriendDecl(PrevClassTemplate != 0);
765 // TODO: do we want to track the instantiation progeny of this
766 // friend target decl?
767 } else {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000768 Inst->setAccess(D->getAccess());
John McCall93ba8572010-03-25 06:39:04 +0000769 Inst->setInstantiatedFromMemberTemplate(D);
770 }
Douglas Gregorf0510d42009-10-12 23:11:44 +0000771
772 // Trigger creation of the type for the instantiation.
John McCall3cb0ebd2010-03-10 03:28:59 +0000773 SemaRef.Context.getInjectedClassNameType(RecordInst,
774 Inst->getInjectedClassNameSpecialization(SemaRef.Context));
John McCallea7390c2010-04-08 20:25:50 +0000775
Douglas Gregor259571e2009-10-30 22:42:42 +0000776 // Finish handling of friends.
John McCall93ba8572010-03-25 06:39:04 +0000777 if (isFriend) {
778 DC->makeDeclVisibleInContext(Inst, /*Recoverable*/ false);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000779 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000780 }
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000781
John McCalle29ba202009-08-20 01:44:21 +0000782 Owner->addDecl(Inst);
Douglas Gregored9c0f92009-10-29 00:04:11 +0000783
784 // First, we sort the partial specializations by location, so
785 // that we instantiate them in the order they were declared.
786 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
787 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
788 P = D->getPartialSpecializations().begin(),
789 PEnd = D->getPartialSpecializations().end();
790 P != PEnd; ++P)
791 PartialSpecs.push_back(&*P);
792 std::sort(PartialSpecs.begin(), PartialSpecs.end(),
793 SortDeclByLocation(SemaRef.SourceMgr));
794
795 // Instantiate all of the partial specializations of this member class
796 // template.
797 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
798 InstantiateClassTemplatePartialSpecialization(Inst, PartialSpecs[I]);
799
John McCalle29ba202009-08-20 01:44:21 +0000800 return Inst;
801}
802
Douglas Gregord60e1052009-08-27 16:57:43 +0000803Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000804TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
805 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +0000806 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
807
808 // Lookup the already-instantiated declaration in the instantiation
809 // of the class template and return that.
810 DeclContext::lookup_result Found
811 = Owner->lookup(ClassTemplate->getDeclName());
812 if (Found.first == Found.second)
813 return 0;
814
815 ClassTemplateDecl *InstClassTemplate
816 = dyn_cast<ClassTemplateDecl>(*Found.first);
817 if (!InstClassTemplate)
818 return 0;
819
820 Decl *DCanon = D->getCanonicalDecl();
821 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
822 P = InstClassTemplate->getPartialSpecializations().begin(),
823 PEnd = InstClassTemplate->getPartialSpecializations().end();
824 P != PEnd; ++P) {
825 if (P->getInstantiatedFromMember()->getCanonicalDecl() == DCanon)
826 return &*P;
827 }
828
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000829 return 0;
830}
831
832Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +0000833TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000834 // Create a local instantiation scope for this function template, which
835 // will contain the instantiations of the template parameters and then get
836 // merged with the local instantiation scope for the function template
837 // itself.
838 Sema::LocalInstantiationScope Scope(SemaRef);
839
Douglas Gregord60e1052009-08-27 16:57:43 +0000840 TemplateParameterList *TempParams = D->getTemplateParameters();
841 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000842 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000843 return NULL;
Douglas Gregored9c0f92009-10-29 00:04:11 +0000844
Douglas Gregora735b202009-10-13 14:39:41 +0000845 FunctionDecl *Instantiated = 0;
846 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
847 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
848 InstParams));
849 else
850 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
851 D->getTemplatedDecl(),
852 InstParams));
853
854 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +0000855 return 0;
856
John McCall46460a62010-01-20 21:53:11 +0000857 Instantiated->setAccess(D->getAccess());
858
Mike Stump1eb44332009-09-09 15:08:12 +0000859 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +0000860 // template from which it was instantiated.
Douglas Gregor37d681852009-10-12 22:27:17 +0000861 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +0000862 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +0000863 InstTemplate->setAccess(D->getAccess());
Douglas Gregora735b202009-10-13 14:39:41 +0000864 assert(InstTemplate &&
865 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCalle976ffe2009-12-14 23:19:40 +0000866
John McCallb1a56e72010-03-26 23:10:15 +0000867 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
868
John McCalle976ffe2009-12-14 23:19:40 +0000869 // Link the instantiation back to the pattern *unless* this is a
870 // non-definition friend declaration.
871 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
John McCallb1a56e72010-03-26 23:10:15 +0000872 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregora735b202009-10-13 14:39:41 +0000873 InstTemplate->setInstantiatedFromMemberTemplate(D);
874
John McCallb1a56e72010-03-26 23:10:15 +0000875 // Make declarations visible in the appropriate context.
876 if (!isFriend)
Douglas Gregora735b202009-10-13 14:39:41 +0000877 Owner->addDecl(InstTemplate);
John McCallb1a56e72010-03-26 23:10:15 +0000878
Douglas Gregord60e1052009-08-27 16:57:43 +0000879 return InstTemplate;
880}
881
Douglas Gregord475b8d2009-03-25 21:17:03 +0000882Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
883 CXXRecordDecl *PrevDecl = 0;
884 if (D->isInjectedClassName())
885 PrevDecl = cast<CXXRecordDecl>(Owner);
John McCall6c1c1b82009-12-15 22:29:06 +0000886 else if (D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000887 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
888 D->getPreviousDeclaration(),
John McCall6c1c1b82009-12-15 22:29:06 +0000889 TemplateArgs);
890 if (!Prev) return 0;
891 PrevDecl = cast<CXXRecordDecl>(Prev);
892 }
Douglas Gregord475b8d2009-03-25 21:17:03 +0000893
894 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +0000895 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000896 D->getLocation(), D->getIdentifier(),
897 D->getTagKeywordLoc(), PrevDecl);
John McCallb6217662010-03-15 10:12:16 +0000898
899 // Substitute the nested name specifier, if any.
900 if (SubstQualifier(D, Record))
901 return 0;
902
Douglas Gregord475b8d2009-03-25 21:17:03 +0000903 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000904 // FIXME: Check against AS_none is an ugly hack to work around the issue that
905 // the tag decls introduced by friend class declarations don't have an access
906 // specifier. Remove once this area of the code gets sorted out.
907 if (D->getAccess() != AS_none)
908 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000909 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +0000910 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000911
John McCall02cace72009-08-28 07:59:38 +0000912 // If the original function was part of a friend declaration,
913 // inherit its namespace state.
914 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
915 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
916
Anders Carlssond8b285f2009-09-01 04:26:58 +0000917 Record->setAnonymousStructOrUnion(D->isAnonymousStructOrUnion());
918
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000919 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000920 return Record;
921}
922
John McCall02cace72009-08-28 07:59:38 +0000923/// Normal class members are of more specific types and therefore
924/// don't make it here. This function serves two purposes:
925/// 1) instantiating function templates
926/// 2) substituting friend declarations
927/// FIXME: preserve function definitions in case #2
Douglas Gregor7557a132009-12-24 20:56:24 +0000928Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregora735b202009-10-13 14:39:41 +0000929 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000930 // Check whether there is already a function template specialization for
931 // this declaration.
932 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
933 void *InsertPos = 0;
John McCallb0cb0222010-03-27 05:57:59 +0000934 if (FunctionTemplate && !TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000935 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000936 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000937 TemplateArgs.getInnermost().getFlatArgumentList(),
938 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor828e2262009-07-29 16:09:57 +0000939 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000940
941 FunctionTemplateSpecializationInfo *Info
942 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor127102b2009-06-29 20:59:39 +0000943 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000944
Douglas Gregor127102b2009-06-29 20:59:39 +0000945 // If we already have a function template specialization, return it.
946 if (Info)
947 return Info->Function;
948 }
Mike Stump1eb44332009-09-09 15:08:12 +0000949
John McCallb0cb0222010-03-27 05:57:59 +0000950 bool isFriend;
951 if (FunctionTemplate)
952 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
953 else
954 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
955
Douglas Gregor79c22782010-01-16 20:21:20 +0000956 bool MergeWithParentScope = (TemplateParams != 0) ||
957 !(isa<Decl>(Owner) &&
958 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
959 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +0000960
Douglas Gregore53060f2009-06-25 22:08:12 +0000961 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +0000962 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
963 TInfo = SubstFunctionType(D, Params);
964 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000965 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +0000966 QualType T = TInfo->getType();
John McCallfd810b12009-08-14 02:03:10 +0000967
John McCalld325daa2010-03-26 04:53:08 +0000968 NestedNameSpecifier *Qualifier = D->getQualifier();
969 if (Qualifier) {
970 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
971 D->getQualifierRange(),
972 TemplateArgs);
973 if (!Qualifier) return 0;
974 }
975
John McCall68b6b872010-02-06 01:50:47 +0000976 // If we're instantiating a local function declaration, put the result
977 // in the owner; otherwise we need to find the instantiated context.
978 DeclContext *DC;
979 if (D->getDeclContext()->isFunctionOrMethod())
980 DC = Owner;
John McCalld325daa2010-03-26 04:53:08 +0000981 else if (isFriend && Qualifier) {
982 CXXScopeSpec SS;
983 SS.setScopeRep(Qualifier);
984 SS.setRange(D->getQualifierRange());
985 DC = SemaRef.computeDeclContext(SS);
986 if (!DC) return 0;
987 } else {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000988 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
989 TemplateArgs);
John McCalld325daa2010-03-26 04:53:08 +0000990 }
John McCall68b6b872010-02-06 01:50:47 +0000991
John McCall02cace72009-08-28 07:59:38 +0000992 FunctionDecl *Function =
Mike Stump1eb44332009-09-09 15:08:12 +0000993 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +0000994 D->getDeclName(), T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +0000995 D->getStorageClass(), D->getStorageClassAsWritten(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000996 D->isInlineSpecified(), D->hasWrittenPrototype());
John McCallb6217662010-03-15 10:12:16 +0000997
John McCalld325daa2010-03-26 04:53:08 +0000998 if (Qualifier)
999 Function->setQualifierInfo(Qualifier, D->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +00001000
John McCallb1a56e72010-03-26 23:10:15 +00001001 DeclContext *LexicalDC = Owner;
1002 if (!isFriend && D->isOutOfLine()) {
1003 assert(D->getDeclContext()->isFileContext());
1004 LexicalDC = D->getDeclContext();
1005 }
1006
1007 Function->setLexicalDeclContext(LexicalDC);
Mike Stump1eb44332009-09-09 15:08:12 +00001008
Douglas Gregore53060f2009-06-25 22:08:12 +00001009 // Attach the parameters
1010 for (unsigned P = 0; P < Params.size(); ++P)
1011 Params[P]->setOwningFunction(Function);
Douglas Gregor838db382010-02-11 01:19:42 +00001012 Function->setParams(Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +00001013
Douglas Gregora735b202009-10-13 14:39:41 +00001014 if (TemplateParams) {
1015 // Our resulting instantiation is actually a function template, since we
1016 // are substituting only the outer template parameters. For example, given
1017 //
1018 // template<typename T>
1019 // struct X {
1020 // template<typename U> friend void f(T, U);
1021 // };
1022 //
1023 // X<int> x;
1024 //
1025 // We are instantiating the friend function template "f" within X<int>,
1026 // which means substituting int for T, but leaving "f" as a friend function
1027 // template.
1028 // Build the function template itself.
John McCalld325daa2010-03-26 04:53:08 +00001029 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregora735b202009-10-13 14:39:41 +00001030 Function->getLocation(),
1031 Function->getDeclName(),
1032 TemplateParams, Function);
1033 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCallb1a56e72010-03-26 23:10:15 +00001034
1035 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalld325daa2010-03-26 04:53:08 +00001036
1037 if (isFriend && D->isThisDeclarationADefinition()) {
1038 // TODO: should we remember this connection regardless of whether
1039 // the friend declaration provided a body?
1040 FunctionTemplate->setInstantiatedFromMemberTemplate(
1041 D->getDescribedFunctionTemplate());
1042 }
Douglas Gregor66724ea2009-11-14 01:20:54 +00001043 } else if (FunctionTemplate) {
1044 // Record this function template specialization.
Douglas Gregor838db382010-02-11 01:19:42 +00001045 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor66724ea2009-11-14 01:20:54 +00001046 &TemplateArgs.getInnermost(),
1047 InsertPos);
John McCalld325daa2010-03-26 04:53:08 +00001048 } else if (isFriend && D->isThisDeclarationADefinition()) {
1049 // TODO: should we remember this connection regardless of whether
1050 // the friend declaration provided a body?
1051 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCall02cace72009-08-28 07:59:38 +00001052 }
Douglas Gregora735b202009-10-13 14:39:41 +00001053
Douglas Gregore53060f2009-06-25 22:08:12 +00001054 if (InitFunctionInstantiation(Function, D))
1055 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001056
Douglas Gregore53060f2009-06-25 22:08:12 +00001057 bool Redeclaration = false;
1058 bool OverloadableAttrRequired = false;
John McCallaf2094e2010-04-08 09:05:18 +00001059 bool isExplicitSpecialization = false;
Douglas Gregora735b202009-10-13 14:39:41 +00001060
John McCall68263142009-11-18 22:49:29 +00001061 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
1062 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1063
John McCallaf2094e2010-04-08 09:05:18 +00001064 if (DependentFunctionTemplateSpecializationInfo *Info
1065 = D->getDependentSpecializationInfo()) {
1066 assert(isFriend && "non-friend has dependent specialization info?");
1067
1068 // This needs to be set now for future sanity.
1069 Function->setObjectOfFriendDecl(/*HasPrevious*/ true);
1070
1071 // Instantiate the explicit template arguments.
1072 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1073 Info->getRAngleLoc());
1074 for (unsigned I = 0, E = Info->getNumTemplateArgs(); I != E; ++I) {
1075 TemplateArgumentLoc Loc;
1076 if (SemaRef.Subst(Info->getTemplateArg(I), Loc, TemplateArgs))
1077 return 0;
1078
1079 ExplicitArgs.addArgument(Loc);
1080 }
1081
1082 // Map the candidate templates to their instantiations.
1083 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1084 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1085 Info->getTemplate(I),
1086 TemplateArgs);
1087 if (!Temp) return 0;
1088
1089 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1090 }
1091
1092 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1093 &ExplicitArgs,
1094 Previous))
1095 Function->setInvalidDecl();
1096
1097 isExplicitSpecialization = true;
1098
1099 } else if (TemplateParams || !FunctionTemplate) {
Douglas Gregora735b202009-10-13 14:39:41 +00001100 // Look only into the namespace where the friend would be declared to
1101 // find a previous declaration. This is the innermost enclosing namespace,
1102 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +00001103 SemaRef.LookupQualifiedName(Previous, DC);
Douglas Gregora735b202009-10-13 14:39:41 +00001104
Douglas Gregora735b202009-10-13 14:39:41 +00001105 // In C++, the previous declaration we find might be a tag type
1106 // (class or enum). In this case, the new declaration will hide the
1107 // tag type. Note that this does does not apply if we're declaring a
1108 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001109 if (Previous.isSingleTagDecl())
1110 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +00001111 }
1112
John McCall9f54ad42009-12-10 09:41:52 +00001113 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
John McCallaf2094e2010-04-08 09:05:18 +00001114 isExplicitSpecialization, Redeclaration,
Douglas Gregore53060f2009-06-25 22:08:12 +00001115 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001116
Douglas Gregora735b202009-10-13 14:39:41 +00001117 // If the original function was part of a friend declaration,
1118 // inherit its namespace state and add it to the owner.
John McCalld325daa2010-03-26 04:53:08 +00001119 if (isFriend) {
Douglas Gregora735b202009-10-13 14:39:41 +00001120 NamedDecl *ToFriendD = 0;
John McCall68263142009-11-18 22:49:29 +00001121 NamedDecl *PrevDecl;
Douglas Gregora735b202009-10-13 14:39:41 +00001122 if (TemplateParams) {
1123 ToFriendD = cast<NamedDecl>(FunctionTemplate);
1124 PrevDecl = FunctionTemplate->getPreviousDeclaration();
1125 } else {
1126 ToFriendD = Function;
1127 PrevDecl = Function->getPreviousDeclaration();
1128 }
1129 ToFriendD->setObjectOfFriendDecl(PrevDecl != NULL);
John McCalld325daa2010-03-26 04:53:08 +00001130 DC->makeDeclVisibleInContext(ToFriendD, /*Recoverable=*/ false);
Douglas Gregora735b202009-10-13 14:39:41 +00001131 }
1132
Douglas Gregore53060f2009-06-25 22:08:12 +00001133 return Function;
1134}
1135
Douglas Gregord60e1052009-08-27 16:57:43 +00001136Decl *
1137TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1138 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +00001139 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1140 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +00001141 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +00001142 // We are creating a function template specialization from a function
1143 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +00001144 // specialization for this particular set of template arguments.
Douglas Gregor6b906862009-08-21 00:16:32 +00001145 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001146 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001147 TemplateArgs.getInnermost().getFlatArgumentList(),
1148 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor6b906862009-08-21 00:16:32 +00001149 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001150
1151 FunctionTemplateSpecializationInfo *Info
1152 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor6b906862009-08-21 00:16:32 +00001153 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001154
Douglas Gregor6b906862009-08-21 00:16:32 +00001155 // If we already have a function template specialization, return it.
1156 if (Info)
1157 return Info->Function;
1158 }
1159
John McCallb0cb0222010-03-27 05:57:59 +00001160 bool isFriend;
1161 if (FunctionTemplate)
1162 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1163 else
1164 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1165
Douglas Gregor79c22782010-01-16 20:21:20 +00001166 bool MergeWithParentScope = (TemplateParams != 0) ||
1167 !(isa<Decl>(Owner) &&
1168 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1169 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001170
Douglas Gregor0ca20ac2009-05-29 18:27:38 +00001171 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +00001172 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
1173 TInfo = SubstFunctionType(D, Params);
1174 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001175 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +00001176 QualType T = TInfo->getType();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001177
John McCallb0cb0222010-03-27 05:57:59 +00001178 NestedNameSpecifier *Qualifier = D->getQualifier();
1179 if (Qualifier) {
1180 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
1181 D->getQualifierRange(),
1182 TemplateArgs);
1183 if (!Qualifier) return 0;
1184 }
1185
1186 DeclContext *DC = Owner;
1187 if (isFriend) {
1188 if (Qualifier) {
1189 CXXScopeSpec SS;
1190 SS.setScopeRep(Qualifier);
1191 SS.setRange(D->getQualifierRange());
1192 DC = SemaRef.computeDeclContext(SS);
1193 } else {
1194 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1195 D->getDeclContext(),
1196 TemplateArgs);
1197 }
1198 if (!DC) return 0;
1199 }
1200
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001201 // Build the instantiated method declaration.
John McCallb0cb0222010-03-27 05:57:59 +00001202 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Douglas Gregordec06662009-08-21 18:42:58 +00001203 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001204
Douglas Gregordec06662009-08-21 18:42:58 +00001205 DeclarationName Name = D->getDeclName();
Douglas Gregor17e32f32009-08-21 22:43:28 +00001206 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Douglas Gregordec06662009-08-21 18:42:58 +00001207 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
1208 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
1209 SemaRef.Context.getCanonicalType(ClassTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001210 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
1211 Constructor->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +00001212 Name, T, TInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001213 Constructor->isExplicit(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001214 Constructor->isInlineSpecified(),
1215 false);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001216 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
1217 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
1218 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
1219 SemaRef.Context.getCanonicalType(ClassTy));
1220 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
1221 Destructor->getLocation(), Name,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001222 T, Destructor->isInlineSpecified(),
1223 false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001224 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001225 CanQualType ConvTy
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001226 = SemaRef.Context.getCanonicalType(
John McCall183700f2009-09-21 23:43:11 +00001227 T->getAs<FunctionType>()->getResultType());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001228 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
1229 ConvTy);
1230 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
1231 Conversion->getLocation(), Name,
John McCall21ef0fa2010-03-11 09:03:00 +00001232 T, TInfo,
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001233 Conversion->isInlineSpecified(),
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001234 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +00001235 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001236 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +00001237 D->getDeclName(), T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001238 D->isStatic(),
1239 D->getStorageClassAsWritten(),
1240 D->isInlineSpecified());
Douglas Gregordec06662009-08-21 18:42:58 +00001241 }
Douglas Gregor6b906862009-08-21 00:16:32 +00001242
John McCallb0cb0222010-03-27 05:57:59 +00001243 if (Qualifier)
1244 Method->setQualifierInfo(Qualifier, D->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +00001245
Douglas Gregord60e1052009-08-27 16:57:43 +00001246 if (TemplateParams) {
1247 // Our resulting instantiation is actually a function template, since we
1248 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +00001249 //
Douglas Gregord60e1052009-08-27 16:57:43 +00001250 // template<typename T>
1251 // struct X {
1252 // template<typename U> void f(T, U);
1253 // };
1254 //
1255 // X<int> x;
1256 //
1257 // We are instantiating the member template "f" within X<int>, which means
1258 // substituting int for T, but leaving "f" as a member function template.
1259 // Build the function template itself.
1260 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1261 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001262 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +00001263 TemplateParams, Method);
John McCallb0cb0222010-03-27 05:57:59 +00001264 if (isFriend) {
1265 FunctionTemplate->setLexicalDeclContext(Owner);
1266 FunctionTemplate->setObjectOfFriendDecl(true);
1267 } else if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +00001268 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +00001269 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001270 } else if (FunctionTemplate) {
1271 // Record this function template specialization.
Douglas Gregor838db382010-02-11 01:19:42 +00001272 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor66724ea2009-11-14 01:20:54 +00001273 &TemplateArgs.getInnermost(),
1274 InsertPos);
John McCallb0cb0222010-03-27 05:57:59 +00001275 } else if (!isFriend) {
Douglas Gregor66724ea2009-11-14 01:20:54 +00001276 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +00001277 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001278 }
1279
Mike Stump1eb44332009-09-09 15:08:12 +00001280 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +00001281 // out-of-line, the instantiation will have the same lexical
1282 // context (which will be a namespace scope) as the template.
John McCallb0cb0222010-03-27 05:57:59 +00001283 if (isFriend) {
1284 Method->setLexicalDeclContext(Owner);
1285 Method->setObjectOfFriendDecl(true);
1286 } else if (D->isOutOfLine())
Douglas Gregor7caa6822009-07-24 20:34:43 +00001287 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00001288
Douglas Gregor5545e162009-03-24 00:38:23 +00001289 // Attach the parameters
1290 for (unsigned P = 0; P < Params.size(); ++P)
1291 Params[P]->setOwningFunction(Method);
Douglas Gregor838db382010-02-11 01:19:42 +00001292 Method->setParams(Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +00001293
1294 if (InitMethodInstantiation(Method, D))
1295 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001296
John McCall68263142009-11-18 22:49:29 +00001297 LookupResult Previous(SemaRef, Name, SourceLocation(),
1298 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00001299
John McCallb0cb0222010-03-27 05:57:59 +00001300 if (!FunctionTemplate || TemplateParams || isFriend) {
1301 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001302
Douglas Gregordec06662009-08-21 18:42:58 +00001303 // In C++, the previous declaration we find might be a tag type
1304 // (class or enum). In this case, the new declaration will hide the
1305 // tag type. Note that this does does not apply if we're declaring a
1306 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001307 if (Previous.isSingleTagDecl())
1308 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +00001309 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001310
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001311 bool Redeclaration = false;
1312 bool OverloadableAttrRequired = false;
John McCall9f54ad42009-12-10 09:41:52 +00001313 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001314 /*FIXME:*/OverloadableAttrRequired);
1315
Douglas Gregor4ba31362009-12-01 17:24:26 +00001316 if (D->isPure())
1317 SemaRef.CheckPureMethod(Method, SourceRange());
1318
John McCall46460a62010-01-20 21:53:11 +00001319 Method->setAccess(D->getAccess());
1320
John McCallb0cb0222010-03-27 05:57:59 +00001321 if (FunctionTemplate) {
1322 // If there's a function template, let our caller handle it.
1323 } else if (Method->isInvalidDecl() && !Previous.empty()) {
1324 // Don't hide a (potentially) valid declaration with an invalid one.
1325 } else {
1326 NamedDecl *DeclToAdd = (TemplateParams
1327 ? cast<NamedDecl>(FunctionTemplate)
1328 : Method);
1329 if (isFriend)
1330 Record->makeDeclVisibleInContext(DeclToAdd);
1331 else
1332 Owner->addDecl(DeclToAdd);
1333 }
Mike Stump1eb44332009-09-09 15:08:12 +00001334
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001335 return Method;
1336}
1337
Douglas Gregor615c5d42009-03-24 16:43:20 +00001338Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +00001339 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +00001340}
1341
Douglas Gregor03b2b072009-03-24 00:15:49 +00001342Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001343 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +00001344}
1345
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001346Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001347 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001348}
1349
Douglas Gregor6477b692009-03-25 15:04:13 +00001350ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001351 return SemaRef.SubstParmVarDecl(D, TemplateArgs);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001352}
1353
John McCalle29ba202009-08-20 01:44:21 +00001354Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1355 TemplateTypeParmDecl *D) {
1356 // TODO: don't always clone when decls are refcounted.
1357 const Type* T = D->getTypeForDecl();
1358 assert(T->isTemplateTypeParmType());
1359 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001360
John McCalle29ba202009-08-20 01:44:21 +00001361 TemplateTypeParmDecl *Inst =
1362 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor550d9b22009-10-31 17:21:17 +00001363 TTPT->getDepth() - 1, TTPT->getIndex(),
John McCalle29ba202009-08-20 01:44:21 +00001364 TTPT->getName(),
1365 D->wasDeclaredWithTypename(),
1366 D->isParameterPack());
1367
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001368 if (D->hasDefaultArgument())
1369 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
John McCalle29ba202009-08-20 01:44:21 +00001370
Douglas Gregor550d9b22009-10-31 17:21:17 +00001371 // Introduce this template parameter's instantiation into the instantiation
1372 // scope.
1373 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1374
John McCalle29ba202009-08-20 01:44:21 +00001375 return Inst;
1376}
1377
Douglas Gregor33642df2009-10-23 23:25:44 +00001378Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1379 NonTypeTemplateParmDecl *D) {
1380 // Substitute into the type of the non-type template parameter.
1381 QualType T;
John McCalla93c9342009-12-07 02:54:59 +00001382 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor33642df2009-10-23 23:25:44 +00001383 if (DI) {
1384 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
1385 D->getDeclName());
1386 if (DI) T = DI->getType();
1387 } else {
1388 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
1389 D->getDeclName());
1390 DI = 0;
1391 }
1392 if (T.isNull())
1393 return 0;
1394
1395 // Check that this type is acceptable for a non-type template parameter.
1396 bool Invalid = false;
1397 T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation());
1398 if (T.isNull()) {
1399 T = SemaRef.Context.IntTy;
1400 Invalid = true;
1401 }
1402
1403 NonTypeTemplateParmDecl *Param
1404 = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1405 D->getDepth() - 1, D->getPosition(),
1406 D->getIdentifier(), T, DI);
1407 if (Invalid)
1408 Param->setInvalidDecl();
1409
1410 Param->setDefaultArgument(D->getDefaultArgument());
Douglas Gregor550d9b22009-10-31 17:21:17 +00001411
1412 // Introduce this template parameter's instantiation into the instantiation
1413 // scope.
1414 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001415 return Param;
1416}
1417
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001418Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001419TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1420 TemplateTemplateParmDecl *D) {
1421 // Instantiate the template parameter list of the template template parameter.
1422 TemplateParameterList *TempParams = D->getTemplateParameters();
1423 TemplateParameterList *InstParams;
1424 {
1425 // Perform the actual substitution of template parameters within a new,
1426 // local instantiation scope.
1427 Sema::LocalInstantiationScope Scope(SemaRef);
1428 InstParams = SubstTemplateParams(TempParams);
1429 if (!InstParams)
1430 return NULL;
1431 }
1432
1433 // Build the template template parameter.
1434 TemplateTemplateParmDecl *Param
1435 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1436 D->getDepth() - 1, D->getPosition(),
1437 D->getIdentifier(), InstParams);
1438 Param->setDefaultArgument(D->getDefaultArgument());
1439
1440 // Introduce this template parameter's instantiation into the instantiation
1441 // scope.
1442 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1443
1444 return Param;
1445}
1446
Douglas Gregor48c32a72009-11-17 06:07:40 +00001447Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1448 // Using directives are never dependent, so they require no explicit
1449
1450 UsingDirectiveDecl *Inst
1451 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1452 D->getNamespaceKeyLocation(),
1453 D->getQualifierRange(), D->getQualifier(),
1454 D->getIdentLocation(),
1455 D->getNominatedNamespace(),
1456 D->getCommonAncestor());
1457 Owner->addDecl(Inst);
1458 return Inst;
1459}
1460
John McCalled976492009-12-04 22:46:56 +00001461Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
1462 // The nested name specifier is non-dependent, so no transformation
1463 // is required.
1464
John McCall9f54ad42009-12-10 09:41:52 +00001465 // We only need to do redeclaration lookups if we're in a class
1466 // scope (in fact, it's not really even possible in non-class
1467 // scopes).
1468 bool CheckRedeclaration = Owner->isRecord();
1469
1470 LookupResult Prev(SemaRef, D->getDeclName(), D->getLocation(),
1471 Sema::LookupUsingDeclName, Sema::ForRedeclaration);
1472
John McCalled976492009-12-04 22:46:56 +00001473 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
1474 D->getLocation(),
1475 D->getNestedNameRange(),
1476 D->getUsingLocation(),
1477 D->getTargetNestedNameDecl(),
1478 D->getDeclName(),
1479 D->isTypeName());
1480
1481 CXXScopeSpec SS;
1482 SS.setScopeRep(D->getTargetNestedNameDecl());
1483 SS.setRange(D->getNestedNameRange());
John McCall9f54ad42009-12-10 09:41:52 +00001484
1485 if (CheckRedeclaration) {
1486 Prev.setHideTags(false);
1487 SemaRef.LookupQualifiedName(Prev, Owner);
1488
1489 // Check for invalid redeclarations.
1490 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1491 D->isTypeName(), SS,
1492 D->getLocation(), Prev))
1493 NewUD->setInvalidDecl();
1494
1495 }
1496
1497 if (!NewUD->isInvalidDecl() &&
1498 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
John McCalled976492009-12-04 22:46:56 +00001499 D->getLocation()))
1500 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00001501
John McCalled976492009-12-04 22:46:56 +00001502 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1503 NewUD->setAccess(D->getAccess());
1504 Owner->addDecl(NewUD);
1505
John McCall9f54ad42009-12-10 09:41:52 +00001506 // Don't process the shadow decls for an invalid decl.
1507 if (NewUD->isInvalidDecl())
1508 return NewUD;
1509
John McCall323c3102009-12-22 22:26:37 +00001510 bool isFunctionScope = Owner->isFunctionOrMethod();
1511
John McCall9f54ad42009-12-10 09:41:52 +00001512 // Process the shadow decls.
1513 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1514 I != E; ++I) {
1515 UsingShadowDecl *Shadow = *I;
1516 NamedDecl *InstTarget =
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001517 cast<NamedDecl>(SemaRef.FindInstantiatedDecl(Shadow->getLocation(),
1518 Shadow->getTargetDecl(),
John McCall9f54ad42009-12-10 09:41:52 +00001519 TemplateArgs));
1520
1521 if (CheckRedeclaration &&
1522 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1523 continue;
1524
1525 UsingShadowDecl *InstShadow
1526 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1527 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCall323c3102009-12-22 22:26:37 +00001528
1529 if (isFunctionScope)
1530 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall9f54ad42009-12-10 09:41:52 +00001531 }
John McCalled976492009-12-04 22:46:56 +00001532
1533 return NewUD;
1534}
1535
1536Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00001537 // Ignore these; we handle them in bulk when processing the UsingDecl.
1538 return 0;
John McCalled976492009-12-04 22:46:56 +00001539}
1540
John McCall7ba107a2009-11-18 02:36:19 +00001541Decl * TemplateDeclInstantiator
1542 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00001543 NestedNameSpecifier *NNS =
1544 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1545 D->getTargetNestedNameRange(),
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001546 TemplateArgs);
1547 if (!NNS)
1548 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001549
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001550 CXXScopeSpec SS;
1551 SS.setRange(D->getTargetNestedNameRange());
1552 SS.setScopeRep(NNS);
Mike Stump1eb44332009-09-09 15:08:12 +00001553
1554 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001555 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
John McCall7ba107a2009-11-18 02:36:19 +00001556 D->getUsingLoc(), SS, D->getLocation(),
1557 D->getDeclName(), 0,
1558 /*instantiation*/ true,
1559 /*typename*/ true, D->getTypenameLoc());
1560 if (UD)
John McCalled976492009-12-04 22:46:56 +00001561 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1562
John McCall7ba107a2009-11-18 02:36:19 +00001563 return UD;
1564}
1565
1566Decl * TemplateDeclInstantiator
1567 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1568 NestedNameSpecifier *NNS =
1569 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1570 D->getTargetNestedNameRange(),
1571 TemplateArgs);
1572 if (!NNS)
1573 return 0;
1574
1575 CXXScopeSpec SS;
1576 SS.setRange(D->getTargetNestedNameRange());
1577 SS.setScopeRep(NNS);
1578
1579 NamedDecl *UD =
1580 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1581 D->getUsingLoc(), SS, D->getLocation(),
1582 D->getDeclName(), 0,
1583 /*instantiation*/ true,
1584 /*typename*/ false, SourceLocation());
Anders Carlsson0d8df782009-08-29 19:37:28 +00001585 if (UD)
John McCalled976492009-12-04 22:46:56 +00001586 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1587
Anders Carlsson0d8df782009-08-29 19:37:28 +00001588 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001589}
1590
John McCallce3ff2b2009-08-25 22:02:44 +00001591Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001592 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001593 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor2fa98002010-02-16 19:28:15 +00001594 if (D->isInvalidDecl())
1595 return 0;
1596
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001597 return Instantiator.Visit(D);
1598}
1599
John McCalle29ba202009-08-20 01:44:21 +00001600/// \brief Instantiates a nested template parameter list in the current
1601/// instantiation context.
1602///
1603/// \param L The parameter list to instantiate
1604///
1605/// \returns NULL if there was an error
1606TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001607TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001608 // Get errors for all the parameters before bailing out.
1609 bool Invalid = false;
1610
1611 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001612 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001613 ParamVector Params;
1614 Params.reserve(N);
1615 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1616 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001617 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00001618 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00001619 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00001620 }
1621
1622 // Clean up if we had an error.
1623 if (Invalid) {
1624 for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
1625 PI != PE; ++PI)
1626 if (*PI)
1627 (*PI)->Destroy(SemaRef.Context);
1628 return NULL;
1629 }
1630
1631 TemplateParameterList *InstL
1632 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1633 L->getLAngleLoc(), &Params.front(), N,
1634 L->getRAngleLoc());
1635 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00001636}
John McCalle29ba202009-08-20 01:44:21 +00001637
Douglas Gregored9c0f92009-10-29 00:04:11 +00001638/// \brief Instantiate the declaration of a class template partial
1639/// specialization.
1640///
1641/// \param ClassTemplate the (instantiated) class template that is partially
1642// specialized by the instantiation of \p PartialSpec.
1643///
1644/// \param PartialSpec the (uninstantiated) class template partial
1645/// specialization that we are instantiating.
1646///
1647/// \returns true if there was an error, false otherwise.
1648bool
1649TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1650 ClassTemplateDecl *ClassTemplate,
1651 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001652 // Create a local instantiation scope for this class template partial
1653 // specialization, which will contain the instantiations of the template
1654 // parameters.
1655 Sema::LocalInstantiationScope Scope(SemaRef);
1656
Douglas Gregored9c0f92009-10-29 00:04:11 +00001657 // Substitute into the template parameters of the class template partial
1658 // specialization.
1659 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1660 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1661 if (!InstParams)
1662 return true;
1663
1664 // Substitute into the template arguments of the class template partial
1665 // specialization.
John McCall833ca992009-10-29 08:12:44 +00001666 const TemplateArgumentLoc *PartialSpecTemplateArgs
1667 = PartialSpec->getTemplateArgsAsWritten();
1668 unsigned N = PartialSpec->getNumTemplateArgsAsWritten();
1669
John McCalld5532b62009-11-23 01:53:49 +00001670 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
John McCall833ca992009-10-29 08:12:44 +00001671 for (unsigned I = 0; I != N; ++I) {
John McCalld5532b62009-11-23 01:53:49 +00001672 TemplateArgumentLoc Loc;
1673 if (SemaRef.Subst(PartialSpecTemplateArgs[I], Loc, TemplateArgs))
Douglas Gregored9c0f92009-10-29 00:04:11 +00001674 return true;
John McCalld5532b62009-11-23 01:53:49 +00001675 InstTemplateArgs.addArgument(Loc);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001676 }
1677
1678
1679 // Check that the template argument list is well-formed for this
1680 // class template.
1681 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
1682 InstTemplateArgs.size());
1683 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1684 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001685 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001686 false,
1687 Converted))
1688 return true;
1689
1690 // Figure out where to insert this class template partial specialization
1691 // in the member template's set of class template partial specializations.
1692 llvm::FoldingSetNodeID ID;
1693 ClassTemplatePartialSpecializationDecl::Profile(ID,
1694 Converted.getFlatArguments(),
1695 Converted.flatSize(),
1696 SemaRef.Context);
1697 void *InsertPos = 0;
1698 ClassTemplateSpecializationDecl *PrevDecl
1699 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
1700 InsertPos);
1701
1702 // Build the canonical type that describes the converted template
1703 // arguments of the class template partial specialization.
1704 QualType CanonType
1705 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
1706 Converted.getFlatArguments(),
1707 Converted.flatSize());
1708
1709 // Build the fully-sugared type for this class template
1710 // specialization as the user wrote in the specialization
1711 // itself. This means that we'll pretty-print the type retrieved
1712 // from the specialization's declaration the way that the user
1713 // actually wrote the specialization, rather than formatting the
1714 // name based on the "canonical" representation used to store the
1715 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00001716 TypeSourceInfo *WrittenTy
1717 = SemaRef.Context.getTemplateSpecializationTypeInfo(
1718 TemplateName(ClassTemplate),
1719 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001720 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001721 CanonType);
1722
1723 if (PrevDecl) {
1724 // We've already seen a partial specialization with the same template
1725 // parameters and template arguments. This can happen, for example, when
1726 // substituting the outer template arguments ends up causing two
1727 // class template partial specializations of a member class template
1728 // to have identical forms, e.g.,
1729 //
1730 // template<typename T, typename U>
1731 // struct Outer {
1732 // template<typename X, typename Y> struct Inner;
1733 // template<typename Y> struct Inner<T, Y>;
1734 // template<typename Y> struct Inner<U, Y>;
1735 // };
1736 //
1737 // Outer<int, int> outer; // error: the partial specializations of Inner
1738 // // have the same signature.
1739 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
1740 << WrittenTy;
1741 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1742 << SemaRef.Context.getTypeDeclType(PrevDecl);
1743 return true;
1744 }
1745
1746
1747 // Create the class template partial specialization declaration.
1748 ClassTemplatePartialSpecializationDecl *InstPartialSpec
1749 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context, Owner,
1750 PartialSpec->getLocation(),
1751 InstParams,
1752 ClassTemplate,
1753 Converted,
John McCalld5532b62009-11-23 01:53:49 +00001754 InstTemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00001755 CanonType,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001756 0);
John McCallb6217662010-03-15 10:12:16 +00001757 // Substitute the nested name specifier, if any.
1758 if (SubstQualifier(PartialSpec, InstPartialSpec))
1759 return 0;
1760
Douglas Gregored9c0f92009-10-29 00:04:11 +00001761 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
1762 InstPartialSpec->setTypeAsWritten(WrittenTy);
1763
1764 // Add this partial specialization to the set of class template partial
1765 // specializations.
1766 ClassTemplate->getPartialSpecializations().InsertNode(InstPartialSpec,
1767 InsertPos);
1768 return false;
1769}
1770
John McCall21ef0fa2010-03-11 09:03:00 +00001771TypeSourceInfo*
John McCallce3ff2b2009-08-25 22:02:44 +00001772TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00001773 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall21ef0fa2010-03-11 09:03:00 +00001774 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
1775 assert(OldTInfo && "substituting function without type source info");
1776 assert(Params.empty() && "parameter vector is non-empty at start");
John McCall6cd3b9f2010-04-09 17:38:44 +00001777 TypeSourceInfo *NewTInfo
1778 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
1779 D->getTypeSpecStartLoc(),
1780 D->getDeclName());
John McCall21ef0fa2010-03-11 09:03:00 +00001781 if (!NewTInfo)
1782 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +00001783
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001784 if (NewTInfo != OldTInfo) {
1785 // Get parameters from the new type info.
1786 TypeLoc NewTL = NewTInfo->getTypeLoc();
1787 FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL);
1788 assert(NewProtoLoc && "Missing prototype?");
1789 for (unsigned i = 0, i_end = NewProtoLoc->getNumArgs(); i != i_end; ++i)
1790 Params.push_back(NewProtoLoc->getArg(i));
1791 } else {
1792 // The function type itself was not dependent and therefore no
1793 // substitution occurred. However, we still need to instantiate
1794 // the function parameters themselves.
1795 TypeLoc OldTL = OldTInfo->getTypeLoc();
1796 FunctionProtoTypeLoc *OldProtoLoc = cast<FunctionProtoTypeLoc>(&OldTL);
1797 for (unsigned i = 0, i_end = OldProtoLoc->getNumArgs(); i != i_end; ++i) {
1798 ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc->getArg(i));
1799 if (!Parm)
1800 return 0;
1801 Params.push_back(Parm);
1802 }
1803 }
John McCall21ef0fa2010-03-11 09:03:00 +00001804 return NewTInfo;
Douglas Gregor5545e162009-03-24 00:38:23 +00001805}
1806
Mike Stump1eb44332009-09-09 15:08:12 +00001807/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00001808/// declaration (New) from the corresponding fields of its template (Tmpl).
1809///
1810/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001811bool
1812TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00001813 FunctionDecl *Tmpl) {
1814 if (Tmpl->isDeleted())
1815 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00001816
Douglas Gregorcca9e962009-07-01 22:01:06 +00001817 // If we are performing substituting explicitly-specified template arguments
1818 // or deduced template arguments into a function template and we reach this
1819 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00001820 // to keeping the new function template specialization. We therefore
1821 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00001822 // into a template instantiation for this specific function template
1823 // specialization, which is not a SFINAE context, so that we diagnose any
1824 // further errors in the declaration itself.
1825 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
1826 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
1827 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
1828 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00001829 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00001830 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001831 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00001832 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00001833 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001834 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
1835 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00001836 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001837 }
1838 }
Mike Stump1eb44332009-09-09 15:08:12 +00001839
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001840 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
1841 assert(Proto && "Function template without prototype?");
1842
1843 if (Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec() ||
1844 Proto->getNoReturnAttr()) {
1845 // The function has an exception specification or a "noreturn"
1846 // attribute. Substitute into each of the exception types.
1847 llvm::SmallVector<QualType, 4> Exceptions;
1848 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
1849 // FIXME: Poor location information!
1850 QualType T
1851 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
1852 New->getLocation(), New->getDeclName());
1853 if (T.isNull() ||
1854 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
1855 continue;
1856
1857 Exceptions.push_back(T);
1858 }
1859
1860 // Rebuild the function type
1861
1862 const FunctionProtoType *NewProto
1863 = New->getType()->getAs<FunctionProtoType>();
1864 assert(NewProto && "Template instantiation without function prototype?");
1865 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
1866 NewProto->arg_type_begin(),
1867 NewProto->getNumArgs(),
1868 NewProto->isVariadic(),
1869 NewProto->getTypeQuals(),
1870 Proto->hasExceptionSpec(),
1871 Proto->hasAnyExceptionSpec(),
1872 Exceptions.size(),
1873 Exceptions.data(),
Rafael Espindola264ba482010-03-30 20:24:48 +00001874 Proto->getExtInfo()));
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001875 }
1876
Douglas Gregore53060f2009-06-25 22:08:12 +00001877 return false;
1878}
1879
Douglas Gregor5545e162009-03-24 00:38:23 +00001880/// \brief Initializes common fields of an instantiated method
1881/// declaration (New) from the corresponding fields of its template
1882/// (Tmpl).
1883///
1884/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001885bool
1886TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00001887 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00001888 if (InitFunctionInstantiation(New, Tmpl))
1889 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001890
Douglas Gregor5545e162009-03-24 00:38:23 +00001891 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
1892 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00001893 if (Tmpl->isVirtualAsWritten())
1894 Record->setMethodAsVirtual(New);
Douglas Gregor5545e162009-03-24 00:38:23 +00001895
1896 // FIXME: attributes
1897 // FIXME: New needs a pointer to Tmpl
1898 return false;
1899}
Douglas Gregora58861f2009-05-13 20:28:22 +00001900
1901/// \brief Instantiate the definition of the given function from its
1902/// template.
1903///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001904/// \param PointOfInstantiation the point at which the instantiation was
1905/// required. Note that this is not precisely a "point of instantiation"
1906/// for the function, but it's close.
1907///
Douglas Gregora58861f2009-05-13 20:28:22 +00001908/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001909/// function template specialization or member function of a class template
1910/// specialization.
1911///
1912/// \param Recursive if true, recursively instantiates any functions that
1913/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001914///
1915/// \param DefinitionRequired if true, then we are performing an explicit
1916/// instantiation where the body of the function is required. Complain if
1917/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001918void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001919 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001920 bool Recursive,
1921 bool DefinitionRequired) {
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001922 if (Function->isInvalidDecl())
1923 return;
1924
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001925 assert(!Function->getBody() && "Already instantiated!");
Mike Stump1eb44332009-09-09 15:08:12 +00001926
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001927 // Never instantiate an explicit specialization.
1928 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1929 return;
1930
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001931 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00001932 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001933 Stmt *Pattern = 0;
1934 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001935 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001936
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001937 if (!Pattern) {
1938 if (DefinitionRequired) {
1939 if (Function->getPrimaryTemplate())
1940 Diag(PointOfInstantiation,
1941 diag::err_explicit_instantiation_undefined_func_template)
1942 << Function->getPrimaryTemplate();
1943 else
1944 Diag(PointOfInstantiation,
1945 diag::err_explicit_instantiation_undefined_member)
1946 << 1 << Function->getDeclName() << Function->getDeclContext();
1947
1948 if (PatternDecl)
1949 Diag(PatternDecl->getLocation(),
1950 diag::note_explicit_instantiation_here);
1951 }
1952
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001953 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001954 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001955
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001956 // C++0x [temp.explicit]p9:
1957 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00001958 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001959 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00001960 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001961 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00001962 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001963 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001964
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001965 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
1966 if (Inst)
1967 return;
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001968
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001969 // If we're performing recursive template instantiation, create our own
1970 // queue of pending implicit instantiations that we will instantiate later,
1971 // while we're still within our own instantiation context.
1972 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1973 if (Recursive)
1974 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001975
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001976 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
1977
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001978 // Introduce a new scope where local variable instantiations will be
Douglas Gregor60406be2010-01-16 22:29:39 +00001979 // recorded, unless we're actually a member function within a local
1980 // class, in which case we need to merge our results with the parent
1981 // scope (of the enclosing function).
1982 bool MergeWithParentScope = false;
1983 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
1984 MergeWithParentScope = Rec->isLocalClass();
1985
1986 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00001987
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001988 // Introduce the instantiated function parameters into the local
1989 // instantiation scope.
1990 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
1991 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
1992 Function->getParamDecl(I));
1993
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001994 // Enter the scope of this instantiation. We don't use
1995 // PushDeclContext because we don't have a scope.
1996 DeclContext *PreviousContext = CurContext;
1997 CurContext = Function;
1998
Mike Stump1eb44332009-09-09 15:08:12 +00001999 MultiLevelTemplateArgumentList TemplateArgs =
Anders Carlsson09025312009-08-29 05:16:22 +00002000 getTemplateInstantiationArgs(Function);
2001
2002 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00002003 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00002004 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
2005 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
2006 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002007 }
2008
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002009 // Instantiate the function body.
Anders Carlsson09025312009-08-29 05:16:22 +00002010 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002011
Douglas Gregor52604ab2009-09-11 21:19:12 +00002012 if (Body.isInvalid())
2013 Function->setInvalidDecl();
2014
Mike Stump1eb44332009-09-09 15:08:12 +00002015 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002016 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002017
John McCall0c01d182010-03-24 05:22:00 +00002018 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
2019
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002020 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +00002021
2022 DeclGroupRef DG(Function);
2023 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00002024
Douglas Gregor60406be2010-01-16 22:29:39 +00002025 // This class may have local implicit instantiations that need to be
2026 // instantiation within this scope.
2027 PerformPendingImplicitInstantiations(/*LocalOnly=*/true);
2028 Scope.Exit();
2029
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002030 if (Recursive) {
2031 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002032 // instantiation of this template.
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002033 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002034
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002035 // Restore the set of pending implicit instantiations.
2036 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
2037 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002038}
2039
2040/// \brief Instantiate the definition of the given variable from its
2041/// template.
2042///
Douglas Gregor7caa6822009-07-24 20:34:43 +00002043/// \param PointOfInstantiation the point at which the instantiation was
2044/// required. Note that this is not precisely a "point of instantiation"
2045/// for the function, but it's close.
2046///
2047/// \param Var the already-instantiated declaration of a static member
2048/// variable of a class template specialization.
2049///
2050/// \param Recursive if true, recursively instantiates any functions that
2051/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002052///
2053/// \param DefinitionRequired if true, then we are performing an explicit
2054/// instantiation where an out-of-line definition of the member variable
2055/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002056void Sema::InstantiateStaticDataMemberDefinition(
2057 SourceLocation PointOfInstantiation,
2058 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002059 bool Recursive,
2060 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002061 if (Var->isInvalidDecl())
2062 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002063
Douglas Gregor7caa6822009-07-24 20:34:43 +00002064 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002065 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00002066 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00002067 assert(Def->isStaticDataMember() && "Not a static data member?");
2068 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00002069
Douglas Gregor0d035142009-10-27 18:42:08 +00002070 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002071 // We did not find an out-of-line definition of this static data member,
2072 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00002073 // instantiate this definition (or provide a specialization for it) in
2074 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002075 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002076 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002077 Diag(PointOfInstantiation,
2078 diag::err_explicit_instantiation_undefined_member)
2079 << 2 << Var->getDeclName() << Var->getDeclContext();
2080 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
2081 }
2082
Douglas Gregor7caa6822009-07-24 20:34:43 +00002083 return;
2084 }
2085
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002086 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002087 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002088 return;
2089
2090 // C++0x [temp.explicit]p9:
2091 // Except for inline functions, other explicit instantiation declarations
2092 // have the effect of suppressing the implicit instantiation of the entity
2093 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002094 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002095 == TSK_ExplicitInstantiationDeclaration)
2096 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002097
Douglas Gregor7caa6822009-07-24 20:34:43 +00002098 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
2099 if (Inst)
2100 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002101
Douglas Gregor7caa6822009-07-24 20:34:43 +00002102 // If we're performing recursive template instantiation, create our own
2103 // queue of pending implicit instantiations that we will instantiate later,
2104 // while we're still within our own instantiation context.
2105 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
2106 if (Recursive)
2107 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002108
Douglas Gregor7caa6822009-07-24 20:34:43 +00002109 // Enter the scope of this instantiation. We don't use
2110 // PushDeclContext because we don't have a scope.
2111 DeclContext *PreviousContext = CurContext;
2112 CurContext = Var->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002113
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002114 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00002115 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Douglas Gregor7caa6822009-07-24 20:34:43 +00002116 getTemplateInstantiationArgs(Var)));
Douglas Gregor7caa6822009-07-24 20:34:43 +00002117 CurContext = PreviousContext;
2118
2119 if (Var) {
Douglas Gregor583f33b2009-10-15 18:07:02 +00002120 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
2121 assert(MSInfo && "Missing member specialization information?");
2122 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
2123 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00002124 DeclGroupRef DG(Var);
2125 Consumer.HandleTopLevelDecl(DG);
2126 }
Mike Stump1eb44332009-09-09 15:08:12 +00002127
Douglas Gregor7caa6822009-07-24 20:34:43 +00002128 if (Recursive) {
2129 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002130 // instantiation of this template.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002131 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002132
Douglas Gregor7caa6822009-07-24 20:34:43 +00002133 // Restore the set of pending implicit instantiations.
2134 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002135 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002136}
Douglas Gregor815215d2009-05-27 05:35:12 +00002137
Anders Carlsson09025312009-08-29 05:16:22 +00002138void
2139Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
2140 const CXXConstructorDecl *Tmpl,
2141 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002142
Anders Carlsson09025312009-08-29 05:16:22 +00002143 llvm::SmallVector<MemInitTy*, 4> NewInits;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002144 bool AnyErrors = false;
2145
Anders Carlsson09025312009-08-29 05:16:22 +00002146 // Instantiate all the initializers.
2147 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00002148 InitsEnd = Tmpl->init_end();
2149 Inits != InitsEnd; ++Inits) {
Anders Carlsson09025312009-08-29 05:16:22 +00002150 CXXBaseOrMemberInitializer *Init = *Inits;
2151
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002152 SourceLocation LParenLoc, RParenLoc;
Anders Carlsson09025312009-08-29 05:16:22 +00002153 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002154 llvm::SmallVector<SourceLocation, 4> CommaLocs;
Mike Stump1eb44332009-09-09 15:08:12 +00002155
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002156 // Instantiate the initializer.
2157 if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs,
2158 LParenLoc, CommaLocs, NewArgs, RParenLoc)) {
2159 AnyErrors = true;
2160 continue;
Anders Carlsson09025312009-08-29 05:16:22 +00002161 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002162
Anders Carlsson09025312009-08-29 05:16:22 +00002163 MemInitResult NewInit;
Anders Carlsson09025312009-08-29 05:16:22 +00002164 if (Init->isBaseInitializer()) {
John McCalla93c9342009-12-07 02:54:59 +00002165 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002166 TemplateArgs,
2167 Init->getSourceLocation(),
2168 New->getDeclName());
John McCalla93c9342009-12-07 02:54:59 +00002169 if (!BaseTInfo) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002170 AnyErrors = true;
Douglas Gregor802ab452009-12-02 22:36:29 +00002171 New->setInvalidDecl();
2172 continue;
2173 }
2174
John McCalla93c9342009-12-07 02:54:59 +00002175 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00002176 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002177 NewArgs.size(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002178 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002179 Init->getRParenLoc(),
2180 New->getParent());
2181 } else if (Init->isMemberInitializer()) {
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002182 FieldDecl *Member;
Mike Stump1eb44332009-09-09 15:08:12 +00002183
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002184 // Is this an anonymous union?
2185 if (FieldDecl *UnionInit = Init->getAnonUnionMember())
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002186 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(),
2187 UnionInit, TemplateArgs));
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002188 else
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002189 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(),
2190 Init->getMember(),
Douglas Gregore95b4092009-09-16 18:34:49 +00002191 TemplateArgs));
Mike Stump1eb44332009-09-09 15:08:12 +00002192
2193 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002194 NewArgs.size(),
2195 Init->getSourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002196 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002197 Init->getRParenLoc());
2198 }
2199
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002200 if (NewInit.isInvalid()) {
2201 AnyErrors = true;
Anders Carlsson09025312009-08-29 05:16:22 +00002202 New->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002203 } else {
Anders Carlsson09025312009-08-29 05:16:22 +00002204 // FIXME: It would be nice if ASTOwningVector had a release function.
2205 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00002206
Anders Carlsson09025312009-08-29 05:16:22 +00002207 NewInits.push_back((MemInitTy *)NewInit.get());
2208 }
2209 }
Mike Stump1eb44332009-09-09 15:08:12 +00002210
Anders Carlsson09025312009-08-29 05:16:22 +00002211 // Assign all the initializers to the new constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00002212 ActOnMemInitializers(DeclPtrTy::make(New),
Anders Carlsson09025312009-08-29 05:16:22 +00002213 /*FIXME: ColonLoc */
2214 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002215 NewInits.data(), NewInits.size(),
2216 AnyErrors);
Anders Carlsson09025312009-08-29 05:16:22 +00002217}
2218
John McCall52a575a2009-08-29 08:11:13 +00002219// TODO: this could be templated if the various decl types used the
2220// same method name.
2221static bool isInstantiationOf(ClassTemplateDecl *Pattern,
2222 ClassTemplateDecl *Instance) {
2223 Pattern = Pattern->getCanonicalDecl();
2224
2225 do {
2226 Instance = Instance->getCanonicalDecl();
2227 if (Pattern == Instance) return true;
2228 Instance = Instance->getInstantiatedFromMemberTemplate();
2229 } while (Instance);
2230
2231 return false;
2232}
2233
Douglas Gregor0d696532009-09-28 06:34:35 +00002234static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
2235 FunctionTemplateDecl *Instance) {
2236 Pattern = Pattern->getCanonicalDecl();
2237
2238 do {
2239 Instance = Instance->getCanonicalDecl();
2240 if (Pattern == Instance) return true;
2241 Instance = Instance->getInstantiatedFromMemberTemplate();
2242 } while (Instance);
2243
2244 return false;
2245}
2246
Douglas Gregored9c0f92009-10-29 00:04:11 +00002247static bool
2248isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
2249 ClassTemplatePartialSpecializationDecl *Instance) {
2250 Pattern
2251 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
2252 do {
2253 Instance = cast<ClassTemplatePartialSpecializationDecl>(
2254 Instance->getCanonicalDecl());
2255 if (Pattern == Instance)
2256 return true;
2257 Instance = Instance->getInstantiatedFromMember();
2258 } while (Instance);
2259
2260 return false;
2261}
2262
John McCall52a575a2009-08-29 08:11:13 +00002263static bool isInstantiationOf(CXXRecordDecl *Pattern,
2264 CXXRecordDecl *Instance) {
2265 Pattern = Pattern->getCanonicalDecl();
2266
2267 do {
2268 Instance = Instance->getCanonicalDecl();
2269 if (Pattern == Instance) return true;
2270 Instance = Instance->getInstantiatedFromMemberClass();
2271 } while (Instance);
2272
2273 return false;
2274}
2275
2276static bool isInstantiationOf(FunctionDecl *Pattern,
2277 FunctionDecl *Instance) {
2278 Pattern = Pattern->getCanonicalDecl();
2279
2280 do {
2281 Instance = Instance->getCanonicalDecl();
2282 if (Pattern == Instance) return true;
2283 Instance = Instance->getInstantiatedFromMemberFunction();
2284 } while (Instance);
2285
2286 return false;
2287}
2288
2289static bool isInstantiationOf(EnumDecl *Pattern,
2290 EnumDecl *Instance) {
2291 Pattern = Pattern->getCanonicalDecl();
2292
2293 do {
2294 Instance = Instance->getCanonicalDecl();
2295 if (Pattern == Instance) return true;
2296 Instance = Instance->getInstantiatedFromMemberEnum();
2297 } while (Instance);
2298
2299 return false;
2300}
2301
John McCalled976492009-12-04 22:46:56 +00002302static bool isInstantiationOf(UsingShadowDecl *Pattern,
2303 UsingShadowDecl *Instance,
2304 ASTContext &C) {
2305 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
2306}
2307
2308static bool isInstantiationOf(UsingDecl *Pattern,
2309 UsingDecl *Instance,
2310 ASTContext &C) {
2311 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
2312}
2313
John McCall7ba107a2009-11-18 02:36:19 +00002314static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
2315 UsingDecl *Instance,
2316 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002317 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00002318}
2319
2320static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00002321 UsingDecl *Instance,
2322 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002323 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00002324}
2325
John McCall52a575a2009-08-29 08:11:13 +00002326static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
2327 VarDecl *Instance) {
2328 assert(Instance->isStaticDataMember());
2329
2330 Pattern = Pattern->getCanonicalDecl();
2331
2332 do {
2333 Instance = Instance->getCanonicalDecl();
2334 if (Pattern == Instance) return true;
2335 Instance = Instance->getInstantiatedFromStaticDataMember();
2336 } while (Instance);
2337
2338 return false;
2339}
2340
John McCalled976492009-12-04 22:46:56 +00002341// Other is the prospective instantiation
2342// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00002343static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002344 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00002345 if (UnresolvedUsingTypenameDecl *UUD
2346 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
2347 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2348 return isInstantiationOf(UUD, UD, Ctx);
2349 }
2350 }
2351
2352 if (UnresolvedUsingValueDecl *UUD
2353 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002354 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2355 return isInstantiationOf(UUD, UD, Ctx);
2356 }
2357 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002358
Anders Carlsson0d8df782009-08-29 19:37:28 +00002359 return false;
2360 }
Mike Stump1eb44332009-09-09 15:08:12 +00002361
John McCall52a575a2009-08-29 08:11:13 +00002362 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
2363 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00002364
John McCall52a575a2009-08-29 08:11:13 +00002365 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
2366 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00002367
John McCall52a575a2009-08-29 08:11:13 +00002368 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
2369 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00002370
Douglas Gregor7caa6822009-07-24 20:34:43 +00002371 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00002372 if (Var->isStaticDataMember())
2373 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
2374
2375 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
2376 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00002377
Douglas Gregor0d696532009-09-28 06:34:35 +00002378 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
2379 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
2380
Douglas Gregored9c0f92009-10-29 00:04:11 +00002381 if (ClassTemplatePartialSpecializationDecl *PartialSpec
2382 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
2383 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
2384 PartialSpec);
2385
Anders Carlssond8b285f2009-09-01 04:26:58 +00002386 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
2387 if (!Field->getDeclName()) {
2388 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00002389 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00002390 cast<FieldDecl>(D);
2391 }
2392 }
Mike Stump1eb44332009-09-09 15:08:12 +00002393
John McCalled976492009-12-04 22:46:56 +00002394 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
2395 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
2396
2397 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
2398 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
2399
Douglas Gregor815215d2009-05-27 05:35:12 +00002400 return D->getDeclName() && isa<NamedDecl>(Other) &&
2401 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
2402}
2403
2404template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00002405static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00002406 NamedDecl *D,
2407 ForwardIterator first,
2408 ForwardIterator last) {
2409 for (; first != last; ++first)
2410 if (isInstantiationOf(Ctx, D, *first))
2411 return cast<NamedDecl>(*first);
2412
2413 return 0;
2414}
2415
John McCall02cace72009-08-28 07:59:38 +00002416/// \brief Finds the instantiation of the given declaration context
2417/// within the current instantiation.
2418///
2419/// \returns NULL if there was an error
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002420DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregore95b4092009-09-16 18:34:49 +00002421 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00002422 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002423 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00002424 return cast_or_null<DeclContext>(ID);
2425 } else return DC;
2426}
2427
Douglas Gregored961e72009-05-27 17:54:46 +00002428/// \brief Find the instantiation of the given declaration within the
2429/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00002430///
2431/// This routine is intended to be used when \p D is a declaration
2432/// referenced from within a template, that needs to mapped into the
2433/// corresponding declaration within an instantiation. For example,
2434/// given:
2435///
2436/// \code
2437/// template<typename T>
2438/// struct X {
2439/// enum Kind {
2440/// KnownValue = sizeof(T)
2441/// };
2442///
2443/// bool getKind() const { return KnownValue; }
2444/// };
2445///
2446/// template struct X<int>;
2447/// \endcode
2448///
2449/// In the instantiation of X<int>::getKind(), we need to map the
2450/// EnumConstantDecl for KnownValue (which refers to
2451/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00002452/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2453/// this mapping from within the instantiation of X<int>.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002454NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregore95b4092009-09-16 18:34:49 +00002455 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00002456 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00002457 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregor6d3e6272010-02-05 19:54:12 +00002458 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
Douglas Gregor550d9b22009-10-31 17:21:17 +00002459 ParentDC->isFunctionOrMethod()) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002460 // D is a local of some kind. Look into the map of local
2461 // declarations to their instantiations.
2462 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
2463 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002464
Douglas Gregore95b4092009-09-16 18:34:49 +00002465 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
2466 if (!Record->isDependentContext())
2467 return D;
2468
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002469 // If the RecordDecl is actually the injected-class-name or a
2470 // "templated" declaration for a class template, class template
2471 // partial specialization, or a member class of a class template,
2472 // substitute into the injected-class-name of the class template
2473 // or partial specialization to find the new DeclContext.
Douglas Gregore95b4092009-09-16 18:34:49 +00002474 QualType T;
2475 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
2476
2477 if (ClassTemplate) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002478 T = ClassTemplate->getInjectedClassNameSpecialization(Context);
Douglas Gregore95b4092009-09-16 18:34:49 +00002479 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2480 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
Douglas Gregore95b4092009-09-16 18:34:49 +00002481 ClassTemplate = PartialSpec->getSpecializedTemplate();
John McCall3cb0ebd2010-03-10 03:28:59 +00002482
2483 // If we call SubstType with an InjectedClassNameType here we
2484 // can end up in an infinite loop.
2485 T = Context.getTypeDeclType(Record);
2486 assert(isa<InjectedClassNameType>(T) &&
2487 "type of partial specialization is not an InjectedClassNameType");
2488 T = cast<InjectedClassNameType>(T)->getUnderlyingType();
2489 }
Douglas Gregore95b4092009-09-16 18:34:49 +00002490
2491 if (!T.isNull()) {
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002492 // Substitute into the injected-class-name to get the type
2493 // corresponding to the instantiation we want, which may also be
2494 // the current instantiation (if we're in a template
2495 // definition). This substitution should never fail, since we
2496 // know we can instantiate the injected-class-name or we
2497 // wouldn't have gotten to the injected-class-name!
2498
2499 // FIXME: Can we use the CurrentInstantiationScope to avoid this
2500 // extra instantiation in the common case?
Douglas Gregore95b4092009-09-16 18:34:49 +00002501 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
2502 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
2503
2504 if (!T->isDependentType()) {
2505 assert(T->isRecordType() && "Instantiation must produce a record type");
2506 return T->getAs<RecordType>()->getDecl();
2507 }
2508
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002509 // We are performing "partial" template instantiation to create
2510 // the member declarations for the members of a class template
2511 // specialization. Therefore, D is actually referring to something
2512 // in the current instantiation. Look through the current
2513 // context, which contains actual instantiations, to find the
2514 // instantiation of the "current instantiation" that D refers
2515 // to.
2516 bool SawNonDependentContext = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002517 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00002518 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002519 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002520 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00002521 if (isInstantiationOf(ClassTemplate,
2522 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00002523 return Spec;
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002524
2525 if (!DC->isDependentContext())
2526 SawNonDependentContext = true;
John McCall52a575a2009-08-29 08:11:13 +00002527 }
2528
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002529 // We're performing "instantiation" of a member of the current
2530 // instantiation while we are type-checking the
2531 // definition. Compute the declaration context and return that.
2532 assert(!SawNonDependentContext &&
2533 "No dependent context while instantiating record");
2534 DeclContext *DC = computeDeclContext(T);
2535 assert(DC &&
John McCall52a575a2009-08-29 08:11:13 +00002536 "Unable to find declaration for the current instantiation");
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002537 return cast<CXXRecordDecl>(DC);
John McCall52a575a2009-08-29 08:11:13 +00002538 }
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002539
Douglas Gregore95b4092009-09-16 18:34:49 +00002540 // Fall through to deal with other dependent record types (e.g.,
2541 // anonymous unions in class templates).
2542 }
John McCall52a575a2009-08-29 08:11:13 +00002543
Douglas Gregore95b4092009-09-16 18:34:49 +00002544 if (!ParentDC->isDependentContext())
2545 return D;
2546
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002547 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002548 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00002549 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002550
Douglas Gregor815215d2009-05-27 05:35:12 +00002551 if (ParentDC != D->getDeclContext()) {
2552 // We performed some kind of instantiation in the parent context,
2553 // so now we need to look into the instantiated parent context to
2554 // find the instantiation of the declaration D.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002555
John McCall3cb0ebd2010-03-10 03:28:59 +00002556 // If our context used to be dependent, we may need to instantiate
2557 // it before performing lookup into that context.
2558 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002559 if (!Spec->isDependentContext()) {
2560 QualType T = Context.getTypeDeclType(Spec);
John McCall3cb0ebd2010-03-10 03:28:59 +00002561 const RecordType *Tag = T->getAs<RecordType>();
2562 assert(Tag && "type of non-dependent record is not a RecordType");
2563 if (!Tag->isBeingDefined() &&
2564 RequireCompleteType(Loc, T, diag::err_incomplete_type))
2565 return 0;
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002566 }
2567 }
2568
Douglas Gregor815215d2009-05-27 05:35:12 +00002569 NamedDecl *Result = 0;
2570 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002571 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00002572 Result = findInstantiationOf(Context, D, Found.first, Found.second);
2573 } else {
2574 // Since we don't have a name for the entity we're looking for,
2575 // our only option is to walk through all of the declarations to
2576 // find that name. This will occur in a few cases:
2577 //
2578 // - anonymous struct/union within a template
2579 // - unnamed class/struct/union/enum within a template
2580 //
2581 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00002582 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002583 ParentDC->decls_begin(),
2584 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00002585 }
Mike Stump1eb44332009-09-09 15:08:12 +00002586
John McCall9f54ad42009-12-10 09:41:52 +00002587 // UsingShadowDecls can instantiate to nothing because of using hiding.
Douglas Gregor00225542010-03-01 18:27:54 +00002588 assert((Result || isa<UsingShadowDecl>(D) || D->isInvalidDecl() ||
2589 cast<Decl>(ParentDC)->isInvalidDecl())
John McCall9f54ad42009-12-10 09:41:52 +00002590 && "Unable to find instantiation of declaration!");
2591
Douglas Gregor815215d2009-05-27 05:35:12 +00002592 D = Result;
2593 }
2594
Douglas Gregor815215d2009-05-27 05:35:12 +00002595 return D;
2596}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002597
Mike Stump1eb44332009-09-09 15:08:12 +00002598/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002599/// instantiations we have seen until this point.
Douglas Gregor60406be2010-01-16 22:29:39 +00002600void Sema::PerformPendingImplicitInstantiations(bool LocalOnly) {
2601 while (!PendingLocalImplicitInstantiations.empty() ||
2602 (!LocalOnly && !PendingImplicitInstantiations.empty())) {
2603 PendingImplicitInstantiation Inst;
2604
2605 if (PendingLocalImplicitInstantiations.empty()) {
2606 Inst = PendingImplicitInstantiations.front();
2607 PendingImplicitInstantiations.pop_front();
2608 } else {
2609 Inst = PendingLocalImplicitInstantiations.front();
2610 PendingLocalImplicitInstantiations.pop_front();
2611 }
Mike Stump1eb44332009-09-09 15:08:12 +00002612
Douglas Gregor7caa6822009-07-24 20:34:43 +00002613 // Instantiate function definitions
2614 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002615 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002616 Function->getLocation(), *this,
2617 Context.getSourceManager(),
2618 "instantiating function definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002619
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002620 if (!Function->getBody())
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002621 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00002622 continue;
2623 }
Mike Stump1eb44332009-09-09 15:08:12 +00002624
Douglas Gregor7caa6822009-07-24 20:34:43 +00002625 // Instantiate static data member definitions.
2626 VarDecl *Var = cast<VarDecl>(Inst.first);
2627 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002628
Chandler Carruth291b4412010-02-13 10:17:50 +00002629 // Don't try to instantiate declarations if the most recent redeclaration
2630 // is invalid.
2631 if (Var->getMostRecentDeclaration()->isInvalidDecl())
2632 continue;
2633
2634 // Check if the most recent declaration has changed the specialization kind
2635 // and removed the need for implicit instantiation.
2636 switch (Var->getMostRecentDeclaration()->getTemplateSpecializationKind()) {
2637 case TSK_Undeclared:
2638 assert(false && "Cannot instantitiate an undeclared specialization.");
2639 case TSK_ExplicitInstantiationDeclaration:
2640 case TSK_ExplicitInstantiationDefinition:
2641 case TSK_ExplicitSpecialization:
2642 continue; // No longer need implicit instantiation.
2643 case TSK_ImplicitInstantiation:
2644 break;
2645 }
2646
Mike Stump1eb44332009-09-09 15:08:12 +00002647 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002648 Var->getLocation(), *this,
2649 Context.getSourceManager(),
2650 "instantiating static data member "
2651 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002652
Douglas Gregor7caa6822009-07-24 20:34:43 +00002653 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002654 }
2655}
John McCall0c01d182010-03-24 05:22:00 +00002656
2657void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
2658 const MultiLevelTemplateArgumentList &TemplateArgs) {
2659 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
2660 E = Pattern->ddiag_end(); I != E; ++I) {
2661 DependentDiagnostic *DD = *I;
2662
2663 switch (DD->getKind()) {
2664 case DependentDiagnostic::Access:
2665 HandleDependentAccessCheck(*DD, TemplateArgs);
2666 break;
2667 }
2668 }
2669}