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