SemaTemplateInstantiateDecl.cpp revision f0bf4d554f2513cbb4bec952c81ced59279ad91e
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
623namespace {
624  class SortDeclByLocation {
625    SourceManager &SourceMgr;
626
627  public:
628    explicit SortDeclByLocation(SourceManager &SourceMgr)
629      : SourceMgr(SourceMgr) { }
630
631    bool operator()(const Decl *X, const Decl *Y) const {
632      return SourceMgr.isBeforeInTranslationUnit(X->getLocation(),
633                                                 Y->getLocation());
634    }
635  };
636}
637
638Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
639  bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
640
641  // Create a local instantiation scope for this class template, which
642  // will contain the instantiations of the template parameters.
643  Sema::LocalInstantiationScope Scope(SemaRef);
644  TemplateParameterList *TempParams = D->getTemplateParameters();
645  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
646  if (!InstParams)
647    return NULL;
648
649  CXXRecordDecl *Pattern = D->getTemplatedDecl();
650
651  // Instantiate the qualifier.  We have to do this first in case
652  // we're a friend declaration, because if we are then we need to put
653  // the new declaration in the appropriate context.
654  NestedNameSpecifier *Qualifier = Pattern->getQualifier();
655  if (Qualifier) {
656    Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
657                                                 Pattern->getQualifierRange(),
658                                                 TemplateArgs);
659    if (!Qualifier) return 0;
660  }
661
662  CXXRecordDecl *PrevDecl = 0;
663  ClassTemplateDecl *PrevClassTemplate = 0;
664
665  // If this isn't a friend, then it's a member template, in which
666  // case we just want to build the instantiation in the
667  // specialization.  If it is a friend, we want to build it in
668  // the appropriate context.
669  DeclContext *DC = Owner;
670  if (isFriend) {
671    if (Qualifier) {
672      CXXScopeSpec SS;
673      SS.setScopeRep(Qualifier);
674      SS.setRange(Pattern->getQualifierRange());
675      DC = SemaRef.computeDeclContext(SS);
676      if (!DC) return 0;
677    } else {
678      DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
679                                           Pattern->getDeclContext(),
680                                           TemplateArgs);
681    }
682
683    // Look for a previous declaration of the template in the owning
684    // context.
685    LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
686                   Sema::LookupOrdinaryName, Sema::ForRedeclaration);
687    SemaRef.LookupQualifiedName(R, DC);
688
689    if (R.isSingleResult()) {
690      PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
691      if (PrevClassTemplate)
692        PrevDecl = PrevClassTemplate->getTemplatedDecl();
693    }
694
695    if (!PrevClassTemplate && Qualifier) {
696      SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
697        << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
698        << Pattern->getQualifierRange();
699      return 0;
700    }
701
702    bool AdoptedPreviousTemplateParams = false;
703    if (PrevClassTemplate) {
704      bool Complain = true;
705
706      // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
707      // template for struct std::tr1::__detail::_Map_base, where the
708      // template parameters of the friend declaration don't match the
709      // template parameters of the original declaration. In this one
710      // case, we don't complain about the ill-formed friend
711      // declaration.
712      if (isFriend && Pattern->getIdentifier() &&
713          Pattern->getIdentifier()->isStr("_Map_base") &&
714          DC->isNamespace() &&
715          cast<NamespaceDecl>(DC)->getIdentifier() &&
716          cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
717        DeclContext *DCParent = DC->getParent();
718        if (DCParent->isNamespace() &&
719            cast<NamespaceDecl>(DCParent)->getIdentifier() &&
720            cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
721          DeclContext *DCParent2 = DCParent->getParent();
722          if (DCParent2->isNamespace() &&
723              cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
724              cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
725              DCParent2->getParent()->isTranslationUnit())
726            Complain = false;
727        }
728      }
729
730      TemplateParameterList *PrevParams
731        = PrevClassTemplate->getTemplateParameters();
732
733      // Make sure the parameter lists match.
734      if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
735                                                  Complain,
736                                                  Sema::TPL_TemplateMatch)) {
737        if (Complain)
738          return 0;
739
740        AdoptedPreviousTemplateParams = true;
741        InstParams = PrevParams;
742      }
743
744      // Do some additional validation, then merge default arguments
745      // from the existing declarations.
746      if (!AdoptedPreviousTemplateParams &&
747          SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
748                                             Sema::TPC_ClassTemplate))
749        return 0;
750    }
751  }
752
753  CXXRecordDecl *RecordInst
754    = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
755                            Pattern->getLocation(), Pattern->getIdentifier(),
756                            Pattern->getTagKeywordLoc(), PrevDecl,
757                            /*DelayTypeCreation=*/true);
758
759  if (Qualifier)
760    RecordInst->setQualifierInfo(Qualifier, Pattern->getQualifierRange());
761
762  ClassTemplateDecl *Inst
763    = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
764                                D->getIdentifier(), InstParams, RecordInst,
765                                PrevClassTemplate);
766  RecordInst->setDescribedClassTemplate(Inst);
767
768  if (isFriend) {
769    if (PrevClassTemplate)
770      Inst->setAccess(PrevClassTemplate->getAccess());
771    else
772      Inst->setAccess(D->getAccess());
773
774    Inst->setObjectOfFriendDecl(PrevClassTemplate != 0);
775    // TODO: do we want to track the instantiation progeny of this
776    // friend target decl?
777  } else {
778    Inst->setAccess(D->getAccess());
779    Inst->setInstantiatedFromMemberTemplate(D);
780  }
781
782  // Trigger creation of the type for the instantiation.
783  SemaRef.Context.getInjectedClassNameType(RecordInst,
784                  Inst->getInjectedClassNameSpecialization(SemaRef.Context));
785
786  // Finish handling of friends.
787  if (isFriend) {
788    DC->makeDeclVisibleInContext(Inst, /*Recoverable*/ false);
789    return Inst;
790  }
791
792  Owner->addDecl(Inst);
793
794  // First, we sort the partial specializations by location, so
795  // that we instantiate them in the order they were declared.
796  llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
797  for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
798         P = D->getPartialSpecializations().begin(),
799         PEnd = D->getPartialSpecializations().end();
800       P != PEnd; ++P)
801    PartialSpecs.push_back(&*P);
802  std::sort(PartialSpecs.begin(), PartialSpecs.end(),
803            SortDeclByLocation(SemaRef.SourceMgr));
804
805  // Instantiate all of the partial specializations of this member class
806  // template.
807  for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
808    InstantiateClassTemplatePartialSpecialization(Inst, PartialSpecs[I]);
809
810  return Inst;
811}
812
813Decl *
814TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
815                                   ClassTemplatePartialSpecializationDecl *D) {
816  ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
817
818  // Lookup the already-instantiated declaration in the instantiation
819  // of the class template and return that.
820  DeclContext::lookup_result Found
821    = Owner->lookup(ClassTemplate->getDeclName());
822  if (Found.first == Found.second)
823    return 0;
824
825  ClassTemplateDecl *InstClassTemplate
826    = dyn_cast<ClassTemplateDecl>(*Found.first);
827  if (!InstClassTemplate)
828    return 0;
829
830  Decl *DCanon = D->getCanonicalDecl();
831  for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
832            P = InstClassTemplate->getPartialSpecializations().begin(),
833         PEnd = InstClassTemplate->getPartialSpecializations().end();
834       P != PEnd; ++P) {
835    if (P->getInstantiatedFromMember()->getCanonicalDecl() == DCanon)
836      return &*P;
837  }
838
839  return 0;
840}
841
842Decl *
843TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
844  // Create a local instantiation scope for this function template, which
845  // will contain the instantiations of the template parameters and then get
846  // merged with the local instantiation scope for the function template
847  // itself.
848  Sema::LocalInstantiationScope Scope(SemaRef);
849
850  TemplateParameterList *TempParams = D->getTemplateParameters();
851  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
852  if (!InstParams)
853    return NULL;
854
855  FunctionDecl *Instantiated = 0;
856  if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
857    Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
858                                                                 InstParams));
859  else
860    Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
861                                                          D->getTemplatedDecl(),
862                                                                InstParams));
863
864  if (!Instantiated)
865    return 0;
866
867  Instantiated->setAccess(D->getAccess());
868
869  // Link the instantiated function template declaration to the function
870  // template from which it was instantiated.
871  FunctionTemplateDecl *InstTemplate
872    = Instantiated->getDescribedFunctionTemplate();
873  InstTemplate->setAccess(D->getAccess());
874  assert(InstTemplate &&
875         "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
876
877  bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
878
879  // Link the instantiation back to the pattern *unless* this is a
880  // non-definition friend declaration.
881  if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
882      !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
883    InstTemplate->setInstantiatedFromMemberTemplate(D);
884
885  // Make declarations visible in the appropriate context.
886  if (!isFriend)
887    Owner->addDecl(InstTemplate);
888
889  return InstTemplate;
890}
891
892Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
893  CXXRecordDecl *PrevDecl = 0;
894  if (D->isInjectedClassName())
895    PrevDecl = cast<CXXRecordDecl>(Owner);
896  else if (D->getPreviousDeclaration()) {
897    NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
898                                                   D->getPreviousDeclaration(),
899                                                   TemplateArgs);
900    if (!Prev) return 0;
901    PrevDecl = cast<CXXRecordDecl>(Prev);
902  }
903
904  CXXRecordDecl *Record
905    = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
906                            D->getLocation(), D->getIdentifier(),
907                            D->getTagKeywordLoc(), PrevDecl);
908
909  // Substitute the nested name specifier, if any.
910  if (SubstQualifier(D, Record))
911    return 0;
912
913  Record->setImplicit(D->isImplicit());
914  // FIXME: Check against AS_none is an ugly hack to work around the issue that
915  // the tag decls introduced by friend class declarations don't have an access
916  // specifier. Remove once this area of the code gets sorted out.
917  if (D->getAccess() != AS_none)
918    Record->setAccess(D->getAccess());
919  if (!D->isInjectedClassName())
920    Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
921
922  // If the original function was part of a friend declaration,
923  // inherit its namespace state.
924  if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
925    Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
926
927  Record->setAnonymousStructOrUnion(D->isAnonymousStructOrUnion());
928
929  Owner->addDecl(Record);
930  return Record;
931}
932
933/// Normal class members are of more specific types and therefore
934/// don't make it here.  This function serves two purposes:
935///   1) instantiating function templates
936///   2) substituting friend declarations
937/// FIXME: preserve function definitions in case #2
938Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
939                                       TemplateParameterList *TemplateParams) {
940  // Check whether there is already a function template specialization for
941  // this declaration.
942  FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
943  void *InsertPos = 0;
944  if (FunctionTemplate && !TemplateParams) {
945    llvm::FoldingSetNodeID ID;
946    FunctionTemplateSpecializationInfo::Profile(ID,
947                             TemplateArgs.getInnermost().getFlatArgumentList(),
948                                       TemplateArgs.getInnermost().flat_size(),
949                                                SemaRef.Context);
950
951    FunctionTemplateSpecializationInfo *Info
952      = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
953                                                                   InsertPos);
954
955    // If we already have a function template specialization, return it.
956    if (Info)
957      return Info->Function;
958  }
959
960  bool isFriend;
961  if (FunctionTemplate)
962    isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
963  else
964    isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
965
966  bool MergeWithParentScope = (TemplateParams != 0) ||
967    !(isa<Decl>(Owner) &&
968      cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
969  Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
970
971  llvm::SmallVector<ParmVarDecl *, 4> Params;
972  TypeSourceInfo *TInfo = D->getTypeSourceInfo();
973  TInfo = SubstFunctionType(D, Params);
974  if (!TInfo)
975    return 0;
976  QualType T = TInfo->getType();
977
978  NestedNameSpecifier *Qualifier = D->getQualifier();
979  if (Qualifier) {
980    Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
981                                                 D->getQualifierRange(),
982                                                 TemplateArgs);
983    if (!Qualifier) return 0;
984  }
985
986  // If we're instantiating a local function declaration, put the result
987  // in the owner;  otherwise we need to find the instantiated context.
988  DeclContext *DC;
989  if (D->getDeclContext()->isFunctionOrMethod())
990    DC = Owner;
991  else if (isFriend && Qualifier) {
992    CXXScopeSpec SS;
993    SS.setScopeRep(Qualifier);
994    SS.setRange(D->getQualifierRange());
995    DC = SemaRef.computeDeclContext(SS);
996    if (!DC) return 0;
997  } else {
998    DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
999                                         TemplateArgs);
1000  }
1001
1002  FunctionDecl *Function =
1003      FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
1004                           D->getDeclName(), T, TInfo,
1005                           D->getStorageClass(), D->getStorageClassAsWritten(),
1006                           D->isInlineSpecified(), D->hasWrittenPrototype());
1007
1008  if (Qualifier)
1009    Function->setQualifierInfo(Qualifier, D->getQualifierRange());
1010
1011  DeclContext *LexicalDC = Owner;
1012  if (!isFriend && D->isOutOfLine()) {
1013    assert(D->getDeclContext()->isFileContext());
1014    LexicalDC = D->getDeclContext();
1015  }
1016
1017  Function->setLexicalDeclContext(LexicalDC);
1018
1019  // Attach the parameters
1020  for (unsigned P = 0; P < Params.size(); ++P)
1021    Params[P]->setOwningFunction(Function);
1022  Function->setParams(Params.data(), Params.size());
1023
1024  if (TemplateParams) {
1025    // Our resulting instantiation is actually a function template, since we
1026    // are substituting only the outer template parameters. For example, given
1027    //
1028    //   template<typename T>
1029    //   struct X {
1030    //     template<typename U> friend void f(T, U);
1031    //   };
1032    //
1033    //   X<int> x;
1034    //
1035    // We are instantiating the friend function template "f" within X<int>,
1036    // which means substituting int for T, but leaving "f" as a friend function
1037    // template.
1038    // Build the function template itself.
1039    FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
1040                                                    Function->getLocation(),
1041                                                    Function->getDeclName(),
1042                                                    TemplateParams, Function);
1043    Function->setDescribedFunctionTemplate(FunctionTemplate);
1044
1045    FunctionTemplate->setLexicalDeclContext(LexicalDC);
1046
1047    if (isFriend && D->isThisDeclarationADefinition()) {
1048      // TODO: should we remember this connection regardless of whether
1049      // the friend declaration provided a body?
1050      FunctionTemplate->setInstantiatedFromMemberTemplate(
1051                                           D->getDescribedFunctionTemplate());
1052    }
1053  } else if (FunctionTemplate) {
1054    // Record this function template specialization.
1055    Function->setFunctionTemplateSpecialization(FunctionTemplate,
1056                                                &TemplateArgs.getInnermost(),
1057                                                InsertPos);
1058  } else if (isFriend && D->isThisDeclarationADefinition()) {
1059    // TODO: should we remember this connection regardless of whether
1060    // the friend declaration provided a body?
1061    Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
1062  }
1063
1064  if (InitFunctionInstantiation(Function, D))
1065    Function->setInvalidDecl();
1066
1067  bool Redeclaration = false;
1068  bool OverloadableAttrRequired = false;
1069  bool isExplicitSpecialization = false;
1070
1071  LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
1072                        Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1073
1074  if (DependentFunctionTemplateSpecializationInfo *Info
1075        = D->getDependentSpecializationInfo()) {
1076    assert(isFriend && "non-friend has dependent specialization info?");
1077
1078    // This needs to be set now for future sanity.
1079    Function->setObjectOfFriendDecl(/*HasPrevious*/ true);
1080
1081    // Instantiate the explicit template arguments.
1082    TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1083                                          Info->getRAngleLoc());
1084    for (unsigned I = 0, E = Info->getNumTemplateArgs(); I != E; ++I) {
1085      TemplateArgumentLoc Loc;
1086      if (SemaRef.Subst(Info->getTemplateArg(I), Loc, TemplateArgs))
1087        return 0;
1088
1089      ExplicitArgs.addArgument(Loc);
1090    }
1091
1092    // Map the candidate templates to their instantiations.
1093    for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1094      Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1095                                                Info->getTemplate(I),
1096                                                TemplateArgs);
1097      if (!Temp) return 0;
1098
1099      Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1100    }
1101
1102    if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1103                                                    &ExplicitArgs,
1104                                                    Previous))
1105      Function->setInvalidDecl();
1106
1107    isExplicitSpecialization = true;
1108
1109  } else if (TemplateParams || !FunctionTemplate) {
1110    // Look only into the namespace where the friend would be declared to
1111    // find a previous declaration. This is the innermost enclosing namespace,
1112    // as described in ActOnFriendFunctionDecl.
1113    SemaRef.LookupQualifiedName(Previous, DC);
1114
1115    // In C++, the previous declaration we find might be a tag type
1116    // (class or enum). In this case, the new declaration will hide the
1117    // tag type. Note that this does does not apply if we're declaring a
1118    // typedef (C++ [dcl.typedef]p4).
1119    if (Previous.isSingleTagDecl())
1120      Previous.clear();
1121  }
1122
1123  SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
1124                                   isExplicitSpecialization, Redeclaration,
1125                                   /*FIXME:*/OverloadableAttrRequired);
1126
1127  // If the original function was part of a friend declaration,
1128  // inherit its namespace state and add it to the owner.
1129  if (isFriend) {
1130    NamedDecl *ToFriendD = 0;
1131    NamedDecl *PrevDecl;
1132    if (TemplateParams) {
1133      ToFriendD = cast<NamedDecl>(FunctionTemplate);
1134      PrevDecl = FunctionTemplate->getPreviousDeclaration();
1135    } else {
1136      ToFriendD = Function;
1137      PrevDecl = Function->getPreviousDeclaration();
1138    }
1139    ToFriendD->setObjectOfFriendDecl(PrevDecl != NULL);
1140    DC->makeDeclVisibleInContext(ToFriendD, /*Recoverable=*/ false);
1141  }
1142
1143  return Function;
1144}
1145
1146Decl *
1147TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1148                                      TemplateParameterList *TemplateParams) {
1149  FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1150  void *InsertPos = 0;
1151  if (FunctionTemplate && !TemplateParams) {
1152    // We are creating a function template specialization from a function
1153    // template. Check whether there is already a function template
1154    // specialization for this particular set of template arguments.
1155    llvm::FoldingSetNodeID ID;
1156    FunctionTemplateSpecializationInfo::Profile(ID,
1157                            TemplateArgs.getInnermost().getFlatArgumentList(),
1158                                      TemplateArgs.getInnermost().flat_size(),
1159                                                SemaRef.Context);
1160
1161    FunctionTemplateSpecializationInfo *Info
1162      = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
1163                                                                   InsertPos);
1164
1165    // If we already have a function template specialization, return it.
1166    if (Info)
1167      return Info->Function;
1168  }
1169
1170  bool isFriend;
1171  if (FunctionTemplate)
1172    isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1173  else
1174    isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1175
1176  bool MergeWithParentScope = (TemplateParams != 0) ||
1177    !(isa<Decl>(Owner) &&
1178      cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1179  Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
1180
1181  llvm::SmallVector<ParmVarDecl *, 4> Params;
1182  TypeSourceInfo *TInfo = D->getTypeSourceInfo();
1183  TInfo = SubstFunctionType(D, Params);
1184  if (!TInfo)
1185    return 0;
1186  QualType T = TInfo->getType();
1187
1188  NestedNameSpecifier *Qualifier = D->getQualifier();
1189  if (Qualifier) {
1190    Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
1191                                                 D->getQualifierRange(),
1192                                                 TemplateArgs);
1193    if (!Qualifier) return 0;
1194  }
1195
1196  DeclContext *DC = Owner;
1197  if (isFriend) {
1198    if (Qualifier) {
1199      CXXScopeSpec SS;
1200      SS.setScopeRep(Qualifier);
1201      SS.setRange(D->getQualifierRange());
1202      DC = SemaRef.computeDeclContext(SS);
1203    } else {
1204      DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1205                                           D->getDeclContext(),
1206                                           TemplateArgs);
1207    }
1208    if (!DC) return 0;
1209  }
1210
1211  // Build the instantiated method declaration.
1212  CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1213  CXXMethodDecl *Method = 0;
1214
1215  DeclarationName Name = D->getDeclName();
1216  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
1217    QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
1218    Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
1219                                    SemaRef.Context.getCanonicalType(ClassTy));
1220    Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
1221                                        Constructor->getLocation(),
1222                                        Name, T, TInfo,
1223                                        Constructor->isExplicit(),
1224                                        Constructor->isInlineSpecified(),
1225                                        false);
1226  } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
1227    QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
1228    Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
1229                                   SemaRef.Context.getCanonicalType(ClassTy));
1230    Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
1231                                       Destructor->getLocation(), Name,
1232                                       T, Destructor->isInlineSpecified(),
1233                                       false);
1234  } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
1235    CanQualType ConvTy
1236      = SemaRef.Context.getCanonicalType(
1237                                      T->getAs<FunctionType>()->getResultType());
1238    Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
1239                                                                      ConvTy);
1240    Method = CXXConversionDecl::Create(SemaRef.Context, Record,
1241                                       Conversion->getLocation(), Name,
1242                                       T, TInfo,
1243                                       Conversion->isInlineSpecified(),
1244                                       Conversion->isExplicit());
1245  } else {
1246    Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
1247                                   D->getDeclName(), T, TInfo,
1248                                   D->isStatic(),
1249                                   D->getStorageClassAsWritten(),
1250                                   D->isInlineSpecified());
1251  }
1252
1253  if (Qualifier)
1254    Method->setQualifierInfo(Qualifier, D->getQualifierRange());
1255
1256  if (TemplateParams) {
1257    // Our resulting instantiation is actually a function template, since we
1258    // are substituting only the outer template parameters. For example, given
1259    //
1260    //   template<typename T>
1261    //   struct X {
1262    //     template<typename U> void f(T, U);
1263    //   };
1264    //
1265    //   X<int> x;
1266    //
1267    // We are instantiating the member template "f" within X<int>, which means
1268    // substituting int for T, but leaving "f" as a member function template.
1269    // Build the function template itself.
1270    FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1271                                                    Method->getLocation(),
1272                                                    Method->getDeclName(),
1273                                                    TemplateParams, Method);
1274    if (isFriend) {
1275      FunctionTemplate->setLexicalDeclContext(Owner);
1276      FunctionTemplate->setObjectOfFriendDecl(true);
1277    } else if (D->isOutOfLine())
1278      FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
1279    Method->setDescribedFunctionTemplate(FunctionTemplate);
1280  } else if (FunctionTemplate) {
1281    // Record this function template specialization.
1282    Method->setFunctionTemplateSpecialization(FunctionTemplate,
1283                                              &TemplateArgs.getInnermost(),
1284                                              InsertPos);
1285  } else if (!isFriend) {
1286    // Record that this is an instantiation of a member function.
1287    Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
1288  }
1289
1290  // If we are instantiating a member function defined
1291  // out-of-line, the instantiation will have the same lexical
1292  // context (which will be a namespace scope) as the template.
1293  if (isFriend) {
1294    Method->setLexicalDeclContext(Owner);
1295    Method->setObjectOfFriendDecl(true);
1296  } else if (D->isOutOfLine())
1297    Method->setLexicalDeclContext(D->getLexicalDeclContext());
1298
1299  // Attach the parameters
1300  for (unsigned P = 0; P < Params.size(); ++P)
1301    Params[P]->setOwningFunction(Method);
1302  Method->setParams(Params.data(), Params.size());
1303
1304  if (InitMethodInstantiation(Method, D))
1305    Method->setInvalidDecl();
1306
1307  LookupResult Previous(SemaRef, Name, SourceLocation(),
1308                        Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1309
1310  if (!FunctionTemplate || TemplateParams || isFriend) {
1311    SemaRef.LookupQualifiedName(Previous, Record);
1312
1313    // In C++, the previous declaration we find might be a tag type
1314    // (class or enum). In this case, the new declaration will hide the
1315    // tag type. Note that this does does not apply if we're declaring a
1316    // typedef (C++ [dcl.typedef]p4).
1317    if (Previous.isSingleTagDecl())
1318      Previous.clear();
1319  }
1320
1321  bool Redeclaration = false;
1322  bool OverloadableAttrRequired = false;
1323  SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration,
1324                                   /*FIXME:*/OverloadableAttrRequired);
1325
1326  if (D->isPure())
1327    SemaRef.CheckPureMethod(Method, SourceRange());
1328
1329  Method->setAccess(D->getAccess());
1330
1331  if (FunctionTemplate) {
1332    // If there's a function template, let our caller handle it.
1333  } else if (Method->isInvalidDecl() && !Previous.empty()) {
1334    // Don't hide a (potentially) valid declaration with an invalid one.
1335  } else {
1336    NamedDecl *DeclToAdd = (TemplateParams
1337                            ? cast<NamedDecl>(FunctionTemplate)
1338                            : Method);
1339    if (isFriend)
1340      Record->makeDeclVisibleInContext(DeclToAdd);
1341    else
1342      Owner->addDecl(DeclToAdd);
1343  }
1344
1345  return Method;
1346}
1347
1348Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
1349  return VisitCXXMethodDecl(D);
1350}
1351
1352Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
1353  return VisitCXXMethodDecl(D);
1354}
1355
1356Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
1357  return VisitCXXMethodDecl(D);
1358}
1359
1360ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
1361  return SemaRef.SubstParmVarDecl(D, TemplateArgs);
1362}
1363
1364Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1365                                                    TemplateTypeParmDecl *D) {
1366  // TODO: don't always clone when decls are refcounted.
1367  const Type* T = D->getTypeForDecl();
1368  assert(T->isTemplateTypeParmType());
1369  const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
1370
1371  TemplateTypeParmDecl *Inst =
1372    TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1373                                 TTPT->getDepth() - 1, TTPT->getIndex(),
1374                                 TTPT->getName(),
1375                                 D->wasDeclaredWithTypename(),
1376                                 D->isParameterPack());
1377
1378  if (D->hasDefaultArgument())
1379    Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
1380
1381  // Introduce this template parameter's instantiation into the instantiation
1382  // scope.
1383  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1384
1385  return Inst;
1386}
1387
1388Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1389                                                 NonTypeTemplateParmDecl *D) {
1390  // Substitute into the type of the non-type template parameter.
1391  QualType T;
1392  TypeSourceInfo *DI = D->getTypeSourceInfo();
1393  if (DI) {
1394    DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
1395                           D->getDeclName());
1396    if (DI) T = DI->getType();
1397  } else {
1398    T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
1399                          D->getDeclName());
1400    DI = 0;
1401  }
1402  if (T.isNull())
1403    return 0;
1404
1405  // Check that this type is acceptable for a non-type template parameter.
1406  bool Invalid = false;
1407  T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation());
1408  if (T.isNull()) {
1409    T = SemaRef.Context.IntTy;
1410    Invalid = true;
1411  }
1412
1413  NonTypeTemplateParmDecl *Param
1414    = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1415                                      D->getDepth() - 1, D->getPosition(),
1416                                      D->getIdentifier(), T, DI);
1417  if (Invalid)
1418    Param->setInvalidDecl();
1419
1420  Param->setDefaultArgument(D->getDefaultArgument());
1421
1422  // Introduce this template parameter's instantiation into the instantiation
1423  // scope.
1424  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1425  return Param;
1426}
1427
1428Decl *
1429TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1430                                                  TemplateTemplateParmDecl *D) {
1431  // Instantiate the template parameter list of the template template parameter.
1432  TemplateParameterList *TempParams = D->getTemplateParameters();
1433  TemplateParameterList *InstParams;
1434  {
1435    // Perform the actual substitution of template parameters within a new,
1436    // local instantiation scope.
1437    Sema::LocalInstantiationScope Scope(SemaRef);
1438    InstParams = SubstTemplateParams(TempParams);
1439    if (!InstParams)
1440      return NULL;
1441  }
1442
1443  // Build the template template parameter.
1444  TemplateTemplateParmDecl *Param
1445    = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1446                                       D->getDepth() - 1, D->getPosition(),
1447                                       D->getIdentifier(), InstParams);
1448  Param->setDefaultArgument(D->getDefaultArgument());
1449
1450  // Introduce this template parameter's instantiation into the instantiation
1451  // scope.
1452  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1453
1454  return Param;
1455}
1456
1457Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1458  // Using directives are never dependent, so they require no explicit
1459
1460  UsingDirectiveDecl *Inst
1461    = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1462                                 D->getNamespaceKeyLocation(),
1463                                 D->getQualifierRange(), D->getQualifier(),
1464                                 D->getIdentLocation(),
1465                                 D->getNominatedNamespace(),
1466                                 D->getCommonAncestor());
1467  Owner->addDecl(Inst);
1468  return Inst;
1469}
1470
1471Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
1472  // The nested name specifier is non-dependent, so no transformation
1473  // is required.
1474
1475  // We only need to do redeclaration lookups if we're in a class
1476  // scope (in fact, it's not really even possible in non-class
1477  // scopes).
1478  bool CheckRedeclaration = Owner->isRecord();
1479
1480  LookupResult Prev(SemaRef, D->getDeclName(), D->getLocation(),
1481                    Sema::LookupUsingDeclName, Sema::ForRedeclaration);
1482
1483  UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
1484                                       D->getLocation(),
1485                                       D->getNestedNameRange(),
1486                                       D->getUsingLocation(),
1487                                       D->getTargetNestedNameDecl(),
1488                                       D->getDeclName(),
1489                                       D->isTypeName());
1490
1491  CXXScopeSpec SS;
1492  SS.setScopeRep(D->getTargetNestedNameDecl());
1493  SS.setRange(D->getNestedNameRange());
1494
1495  if (CheckRedeclaration) {
1496    Prev.setHideTags(false);
1497    SemaRef.LookupQualifiedName(Prev, Owner);
1498
1499    // Check for invalid redeclarations.
1500    if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1501                                            D->isTypeName(), SS,
1502                                            D->getLocation(), Prev))
1503      NewUD->setInvalidDecl();
1504
1505  }
1506
1507  if (!NewUD->isInvalidDecl() &&
1508      SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
1509                                      D->getLocation()))
1510    NewUD->setInvalidDecl();
1511
1512  SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1513  NewUD->setAccess(D->getAccess());
1514  Owner->addDecl(NewUD);
1515
1516  // Don't process the shadow decls for an invalid decl.
1517  if (NewUD->isInvalidDecl())
1518    return NewUD;
1519
1520  bool isFunctionScope = Owner->isFunctionOrMethod();
1521
1522  // Process the shadow decls.
1523  for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1524         I != E; ++I) {
1525    UsingShadowDecl *Shadow = *I;
1526    NamedDecl *InstTarget =
1527      cast<NamedDecl>(SemaRef.FindInstantiatedDecl(Shadow->getLocation(),
1528                                                   Shadow->getTargetDecl(),
1529                                                   TemplateArgs));
1530
1531    if (CheckRedeclaration &&
1532        SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1533      continue;
1534
1535    UsingShadowDecl *InstShadow
1536      = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1537    SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
1538
1539    if (isFunctionScope)
1540      SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
1541  }
1542
1543  return NewUD;
1544}
1545
1546Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
1547  // Ignore these;  we handle them in bulk when processing the UsingDecl.
1548  return 0;
1549}
1550
1551Decl * TemplateDeclInstantiator
1552    ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
1553  NestedNameSpecifier *NNS =
1554    SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1555                                     D->getTargetNestedNameRange(),
1556                                     TemplateArgs);
1557  if (!NNS)
1558    return 0;
1559
1560  CXXScopeSpec SS;
1561  SS.setRange(D->getTargetNestedNameRange());
1562  SS.setScopeRep(NNS);
1563
1564  NamedDecl *UD =
1565    SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1566                                  D->getUsingLoc(), SS, D->getLocation(),
1567                                  D->getDeclName(), 0,
1568                                  /*instantiation*/ true,
1569                                  /*typename*/ true, D->getTypenameLoc());
1570  if (UD)
1571    SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1572
1573  return UD;
1574}
1575
1576Decl * TemplateDeclInstantiator
1577    ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1578  NestedNameSpecifier *NNS =
1579    SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1580                                     D->getTargetNestedNameRange(),
1581                                     TemplateArgs);
1582  if (!NNS)
1583    return 0;
1584
1585  CXXScopeSpec SS;
1586  SS.setRange(D->getTargetNestedNameRange());
1587  SS.setScopeRep(NNS);
1588
1589  NamedDecl *UD =
1590    SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1591                                  D->getUsingLoc(), SS, D->getLocation(),
1592                                  D->getDeclName(), 0,
1593                                  /*instantiation*/ true,
1594                                  /*typename*/ false, SourceLocation());
1595  if (UD)
1596    SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1597
1598  return UD;
1599}
1600
1601Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
1602                      const MultiLevelTemplateArgumentList &TemplateArgs) {
1603  TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
1604  if (D->isInvalidDecl())
1605    return 0;
1606
1607  return Instantiator.Visit(D);
1608}
1609
1610/// \brief Instantiates a nested template parameter list in the current
1611/// instantiation context.
1612///
1613/// \param L The parameter list to instantiate
1614///
1615/// \returns NULL if there was an error
1616TemplateParameterList *
1617TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
1618  // Get errors for all the parameters before bailing out.
1619  bool Invalid = false;
1620
1621  unsigned N = L->size();
1622  typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
1623  ParamVector Params;
1624  Params.reserve(N);
1625  for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1626       PI != PE; ++PI) {
1627    NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
1628    Params.push_back(D);
1629    Invalid = Invalid || !D || D->isInvalidDecl();
1630  }
1631
1632  // Clean up if we had an error.
1633  if (Invalid) {
1634    for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
1635         PI != PE; ++PI)
1636      if (*PI)
1637        (*PI)->Destroy(SemaRef.Context);
1638    return NULL;
1639  }
1640
1641  TemplateParameterList *InstL
1642    = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1643                                    L->getLAngleLoc(), &Params.front(), N,
1644                                    L->getRAngleLoc());
1645  return InstL;
1646}
1647
1648/// \brief Instantiate the declaration of a class template partial
1649/// specialization.
1650///
1651/// \param ClassTemplate the (instantiated) class template that is partially
1652// specialized by the instantiation of \p PartialSpec.
1653///
1654/// \param PartialSpec the (uninstantiated) class template partial
1655/// specialization that we are instantiating.
1656///
1657/// \returns true if there was an error, false otherwise.
1658bool
1659TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1660                                            ClassTemplateDecl *ClassTemplate,
1661                          ClassTemplatePartialSpecializationDecl *PartialSpec) {
1662  // Create a local instantiation scope for this class template partial
1663  // specialization, which will contain the instantiations of the template
1664  // parameters.
1665  Sema::LocalInstantiationScope Scope(SemaRef);
1666
1667  // Substitute into the template parameters of the class template partial
1668  // specialization.
1669  TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1670  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1671  if (!InstParams)
1672    return true;
1673
1674  // Substitute into the template arguments of the class template partial
1675  // specialization.
1676  const TemplateArgumentLoc *PartialSpecTemplateArgs
1677    = PartialSpec->getTemplateArgsAsWritten();
1678  unsigned N = PartialSpec->getNumTemplateArgsAsWritten();
1679
1680  TemplateArgumentListInfo InstTemplateArgs; // no angle locations
1681  for (unsigned I = 0; I != N; ++I) {
1682    TemplateArgumentLoc Loc;
1683    if (SemaRef.Subst(PartialSpecTemplateArgs[I], Loc, TemplateArgs))
1684      return true;
1685    InstTemplateArgs.addArgument(Loc);
1686  }
1687
1688
1689  // Check that the template argument list is well-formed for this
1690  // class template.
1691  TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
1692                                        InstTemplateArgs.size());
1693  if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1694                                        PartialSpec->getLocation(),
1695                                        InstTemplateArgs,
1696                                        false,
1697                                        Converted))
1698    return true;
1699
1700  // Figure out where to insert this class template partial specialization
1701  // in the member template's set of class template partial specializations.
1702  llvm::FoldingSetNodeID ID;
1703  ClassTemplatePartialSpecializationDecl::Profile(ID,
1704                                                  Converted.getFlatArguments(),
1705                                                  Converted.flatSize(),
1706                                                  SemaRef.Context);
1707  void *InsertPos = 0;
1708  ClassTemplateSpecializationDecl *PrevDecl
1709    = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
1710                                                                     InsertPos);
1711
1712  // Build the canonical type that describes the converted template
1713  // arguments of the class template partial specialization.
1714  QualType CanonType
1715    = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
1716                                                  Converted.getFlatArguments(),
1717                                                    Converted.flatSize());
1718
1719  // Build the fully-sugared type for this class template
1720  // specialization as the user wrote in the specialization
1721  // itself. This means that we'll pretty-print the type retrieved
1722  // from the specialization's declaration the way that the user
1723  // actually wrote the specialization, rather than formatting the
1724  // name based on the "canonical" representation used to store the
1725  // template arguments in the specialization.
1726  TypeSourceInfo *WrittenTy
1727    = SemaRef.Context.getTemplateSpecializationTypeInfo(
1728                                                    TemplateName(ClassTemplate),
1729                                                    PartialSpec->getLocation(),
1730                                                    InstTemplateArgs,
1731                                                    CanonType);
1732
1733  if (PrevDecl) {
1734    // We've already seen a partial specialization with the same template
1735    // parameters and template arguments. This can happen, for example, when
1736    // substituting the outer template arguments ends up causing two
1737    // class template partial specializations of a member class template
1738    // to have identical forms, e.g.,
1739    //
1740    //   template<typename T, typename U>
1741    //   struct Outer {
1742    //     template<typename X, typename Y> struct Inner;
1743    //     template<typename Y> struct Inner<T, Y>;
1744    //     template<typename Y> struct Inner<U, Y>;
1745    //   };
1746    //
1747    //   Outer<int, int> outer; // error: the partial specializations of Inner
1748    //                          // have the same signature.
1749    SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
1750      << WrittenTy;
1751    SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1752      << SemaRef.Context.getTypeDeclType(PrevDecl);
1753    return true;
1754  }
1755
1756
1757  // Create the class template partial specialization declaration.
1758  ClassTemplatePartialSpecializationDecl *InstPartialSpec
1759    = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context, Owner,
1760                                                     PartialSpec->getLocation(),
1761                                                     InstParams,
1762                                                     ClassTemplate,
1763                                                     Converted,
1764                                                     InstTemplateArgs,
1765                                                     CanonType,
1766                                                     0);
1767  // Substitute the nested name specifier, if any.
1768  if (SubstQualifier(PartialSpec, InstPartialSpec))
1769    return 0;
1770
1771  InstPartialSpec->setInstantiatedFromMember(PartialSpec);
1772  InstPartialSpec->setTypeAsWritten(WrittenTy);
1773
1774  // Add this partial specialization to the set of class template partial
1775  // specializations.
1776  ClassTemplate->getPartialSpecializations().InsertNode(InstPartialSpec,
1777                                                        InsertPos);
1778  return false;
1779}
1780
1781TypeSourceInfo*
1782TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
1783                              llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
1784  TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
1785  assert(OldTInfo && "substituting function without type source info");
1786  assert(Params.empty() && "parameter vector is non-empty at start");
1787  TypeSourceInfo *NewTInfo
1788    = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
1789                                    D->getTypeSpecStartLoc(),
1790                                    D->getDeclName());
1791  if (!NewTInfo)
1792    return 0;
1793
1794  if (NewTInfo != OldTInfo) {
1795    // Get parameters from the new type info.
1796    TypeLoc NewTL = NewTInfo->getTypeLoc();
1797    FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL);
1798    assert(NewProtoLoc && "Missing prototype?");
1799    for (unsigned i = 0, i_end = NewProtoLoc->getNumArgs(); i != i_end; ++i)
1800      Params.push_back(NewProtoLoc->getArg(i));
1801  } else {
1802    // The function type itself was not dependent and therefore no
1803    // substitution occurred. However, we still need to instantiate
1804    // the function parameters themselves.
1805    TypeLoc OldTL = OldTInfo->getTypeLoc();
1806    FunctionProtoTypeLoc *OldProtoLoc = cast<FunctionProtoTypeLoc>(&OldTL);
1807    for (unsigned i = 0, i_end = OldProtoLoc->getNumArgs(); i != i_end; ++i) {
1808      ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc->getArg(i));
1809      if (!Parm)
1810        return 0;
1811      Params.push_back(Parm);
1812    }
1813  }
1814  return NewTInfo;
1815}
1816
1817/// \brief Initializes the common fields of an instantiation function
1818/// declaration (New) from the corresponding fields of its template (Tmpl).
1819///
1820/// \returns true if there was an error
1821bool
1822TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
1823                                                    FunctionDecl *Tmpl) {
1824  if (Tmpl->isDeleted())
1825    New->setDeleted();
1826
1827  // If we are performing substituting explicitly-specified template arguments
1828  // or deduced template arguments into a function template and we reach this
1829  // point, we are now past the point where SFINAE applies and have committed
1830  // to keeping the new function template specialization. We therefore
1831  // convert the active template instantiation for the function template
1832  // into a template instantiation for this specific function template
1833  // specialization, which is not a SFINAE context, so that we diagnose any
1834  // further errors in the declaration itself.
1835  typedef Sema::ActiveTemplateInstantiation ActiveInstType;
1836  ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
1837  if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
1838      ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
1839    if (FunctionTemplateDecl *FunTmpl
1840          = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
1841      assert(FunTmpl->getTemplatedDecl() == Tmpl &&
1842             "Deduction from the wrong function template?");
1843      (void) FunTmpl;
1844      ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
1845      ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
1846      --SemaRef.NonInstantiationEntries;
1847    }
1848  }
1849
1850  const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
1851  assert(Proto && "Function template without prototype?");
1852
1853  if (Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec() ||
1854      Proto->getNoReturnAttr()) {
1855    // The function has an exception specification or a "noreturn"
1856    // attribute. Substitute into each of the exception types.
1857    llvm::SmallVector<QualType, 4> Exceptions;
1858    for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
1859      // FIXME: Poor location information!
1860      QualType T
1861        = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
1862                            New->getLocation(), New->getDeclName());
1863      if (T.isNull() ||
1864          SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
1865        continue;
1866
1867      Exceptions.push_back(T);
1868    }
1869
1870    // Rebuild the function type
1871
1872    const FunctionProtoType *NewProto
1873      = New->getType()->getAs<FunctionProtoType>();
1874    assert(NewProto && "Template instantiation without function prototype?");
1875    New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
1876                                                 NewProto->arg_type_begin(),
1877                                                 NewProto->getNumArgs(),
1878                                                 NewProto->isVariadic(),
1879                                                 NewProto->getTypeQuals(),
1880                                                 Proto->hasExceptionSpec(),
1881                                                 Proto->hasAnyExceptionSpec(),
1882                                                 Exceptions.size(),
1883                                                 Exceptions.data(),
1884                                                 Proto->getExtInfo()));
1885  }
1886
1887  return false;
1888}
1889
1890/// \brief Initializes common fields of an instantiated method
1891/// declaration (New) from the corresponding fields of its template
1892/// (Tmpl).
1893///
1894/// \returns true if there was an error
1895bool
1896TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
1897                                                  CXXMethodDecl *Tmpl) {
1898  if (InitFunctionInstantiation(New, Tmpl))
1899    return true;
1900
1901  CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
1902  New->setAccess(Tmpl->getAccess());
1903  if (Tmpl->isVirtualAsWritten())
1904    Record->setMethodAsVirtual(New);
1905
1906  // FIXME: attributes
1907  // FIXME: New needs a pointer to Tmpl
1908  return false;
1909}
1910
1911/// \brief Instantiate the definition of the given function from its
1912/// template.
1913///
1914/// \param PointOfInstantiation the point at which the instantiation was
1915/// required. Note that this is not precisely a "point of instantiation"
1916/// for the function, but it's close.
1917///
1918/// \param Function the already-instantiated declaration of a
1919/// function template specialization or member function of a class template
1920/// specialization.
1921///
1922/// \param Recursive if true, recursively instantiates any functions that
1923/// are required by this instantiation.
1924///
1925/// \param DefinitionRequired if true, then we are performing an explicit
1926/// instantiation where the body of the function is required. Complain if
1927/// there is no such body.
1928void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
1929                                         FunctionDecl *Function,
1930                                         bool Recursive,
1931                                         bool DefinitionRequired) {
1932  if (Function->isInvalidDecl())
1933    return;
1934
1935  assert(!Function->getBody() && "Already instantiated!");
1936
1937  // Never instantiate an explicit specialization.
1938  if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1939    return;
1940
1941  // Find the function body that we'll be substituting.
1942  const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
1943  Stmt *Pattern = 0;
1944  if (PatternDecl)
1945    Pattern = PatternDecl->getBody(PatternDecl);
1946
1947  if (!Pattern) {
1948    if (DefinitionRequired) {
1949      if (Function->getPrimaryTemplate())
1950        Diag(PointOfInstantiation,
1951             diag::err_explicit_instantiation_undefined_func_template)
1952          << Function->getPrimaryTemplate();
1953      else
1954        Diag(PointOfInstantiation,
1955             diag::err_explicit_instantiation_undefined_member)
1956          << 1 << Function->getDeclName() << Function->getDeclContext();
1957
1958      if (PatternDecl)
1959        Diag(PatternDecl->getLocation(),
1960             diag::note_explicit_instantiation_here);
1961    }
1962
1963    return;
1964  }
1965
1966  // C++0x [temp.explicit]p9:
1967  //   Except for inline functions, other explicit instantiation declarations
1968  //   have the effect of suppressing the implicit instantiation of the entity
1969  //   to which they refer.
1970  if (Function->getTemplateSpecializationKind()
1971        == TSK_ExplicitInstantiationDeclaration &&
1972      !PatternDecl->isInlined())
1973    return;
1974
1975  InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
1976  if (Inst)
1977    return;
1978
1979  // If we're performing recursive template instantiation, create our own
1980  // queue of pending implicit instantiations that we will instantiate later,
1981  // while we're still within our own instantiation context.
1982  std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1983  if (Recursive)
1984    PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1985
1986  ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
1987
1988  // Introduce a new scope where local variable instantiations will be
1989  // recorded, unless we're actually a member function within a local
1990  // class, in which case we need to merge our results with the parent
1991  // scope (of the enclosing function).
1992  bool MergeWithParentScope = false;
1993  if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
1994    MergeWithParentScope = Rec->isLocalClass();
1995
1996  LocalInstantiationScope Scope(*this, MergeWithParentScope);
1997
1998  // Introduce the instantiated function parameters into the local
1999  // instantiation scope.
2000  for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
2001    Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
2002                            Function->getParamDecl(I));
2003
2004  // Enter the scope of this instantiation. We don't use
2005  // PushDeclContext because we don't have a scope.
2006  DeclContext *PreviousContext = CurContext;
2007  CurContext = Function;
2008
2009  MultiLevelTemplateArgumentList TemplateArgs =
2010    getTemplateInstantiationArgs(Function);
2011
2012  // If this is a constructor, instantiate the member initializers.
2013  if (const CXXConstructorDecl *Ctor =
2014        dyn_cast<CXXConstructorDecl>(PatternDecl)) {
2015    InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
2016                               TemplateArgs);
2017  }
2018
2019  // Instantiate the function body.
2020  OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs);
2021
2022  if (Body.isInvalid())
2023    Function->setInvalidDecl();
2024
2025  ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
2026                          /*IsInstantiation=*/true);
2027
2028  PerformDependentDiagnostics(PatternDecl, TemplateArgs);
2029
2030  CurContext = PreviousContext;
2031
2032  DeclGroupRef DG(Function);
2033  Consumer.HandleTopLevelDecl(DG);
2034
2035  // This class may have local implicit instantiations that need to be
2036  // instantiation within this scope.
2037  PerformPendingImplicitInstantiations(/*LocalOnly=*/true);
2038  Scope.Exit();
2039
2040  if (Recursive) {
2041    // Instantiate any pending implicit instantiations found during the
2042    // instantiation of this template.
2043    PerformPendingImplicitInstantiations();
2044
2045    // Restore the set of pending implicit instantiations.
2046    PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
2047  }
2048}
2049
2050/// \brief Instantiate the definition of the given variable from its
2051/// template.
2052///
2053/// \param PointOfInstantiation the point at which the instantiation was
2054/// required. Note that this is not precisely a "point of instantiation"
2055/// for the function, but it's close.
2056///
2057/// \param Var the already-instantiated declaration of a static member
2058/// variable of a class template specialization.
2059///
2060/// \param Recursive if true, recursively instantiates any functions that
2061/// are required by this instantiation.
2062///
2063/// \param DefinitionRequired if true, then we are performing an explicit
2064/// instantiation where an out-of-line definition of the member variable
2065/// is required. Complain if there is no such definition.
2066void Sema::InstantiateStaticDataMemberDefinition(
2067                                          SourceLocation PointOfInstantiation,
2068                                                 VarDecl *Var,
2069                                                 bool Recursive,
2070                                                 bool DefinitionRequired) {
2071  if (Var->isInvalidDecl())
2072    return;
2073
2074  // Find the out-of-line definition of this static data member.
2075  VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
2076  assert(Def && "This data member was not instantiated from a template?");
2077  assert(Def->isStaticDataMember() && "Not a static data member?");
2078  Def = Def->getOutOfLineDefinition();
2079
2080  if (!Def) {
2081    // We did not find an out-of-line definition of this static data member,
2082    // so we won't perform any instantiation. Rather, we rely on the user to
2083    // instantiate this definition (or provide a specialization for it) in
2084    // another translation unit.
2085    if (DefinitionRequired) {
2086      Def = Var->getInstantiatedFromStaticDataMember();
2087      Diag(PointOfInstantiation,
2088           diag::err_explicit_instantiation_undefined_member)
2089        << 2 << Var->getDeclName() << Var->getDeclContext();
2090      Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
2091    }
2092
2093    return;
2094  }
2095
2096  // Never instantiate an explicit specialization.
2097  if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2098    return;
2099
2100  // C++0x [temp.explicit]p9:
2101  //   Except for inline functions, other explicit instantiation declarations
2102  //   have the effect of suppressing the implicit instantiation of the entity
2103  //   to which they refer.
2104  if (Var->getTemplateSpecializationKind()
2105        == TSK_ExplicitInstantiationDeclaration)
2106    return;
2107
2108  InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
2109  if (Inst)
2110    return;
2111
2112  // If we're performing recursive template instantiation, create our own
2113  // queue of pending implicit instantiations that we will instantiate later,
2114  // while we're still within our own instantiation context.
2115  std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
2116  if (Recursive)
2117    PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
2118
2119  // Enter the scope of this instantiation. We don't use
2120  // PushDeclContext because we don't have a scope.
2121  DeclContext *PreviousContext = CurContext;
2122  CurContext = Var->getDeclContext();
2123
2124  VarDecl *OldVar = Var;
2125  Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
2126                                          getTemplateInstantiationArgs(Var)));
2127  CurContext = PreviousContext;
2128
2129  if (Var) {
2130    MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
2131    assert(MSInfo && "Missing member specialization information?");
2132    Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
2133                                       MSInfo->getPointOfInstantiation());
2134    DeclGroupRef DG(Var);
2135    Consumer.HandleTopLevelDecl(DG);
2136  }
2137
2138  if (Recursive) {
2139    // Instantiate any pending implicit instantiations found during the
2140    // instantiation of this template.
2141    PerformPendingImplicitInstantiations();
2142
2143    // Restore the set of pending implicit instantiations.
2144    PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
2145  }
2146}
2147
2148void
2149Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
2150                                 const CXXConstructorDecl *Tmpl,
2151                           const MultiLevelTemplateArgumentList &TemplateArgs) {
2152
2153  llvm::SmallVector<MemInitTy*, 4> NewInits;
2154  bool AnyErrors = false;
2155
2156  // Instantiate all the initializers.
2157  for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
2158                                            InitsEnd = Tmpl->init_end();
2159       Inits != InitsEnd; ++Inits) {
2160    CXXBaseOrMemberInitializer *Init = *Inits;
2161
2162    SourceLocation LParenLoc, RParenLoc;
2163    ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this);
2164    llvm::SmallVector<SourceLocation, 4> CommaLocs;
2165
2166    // Instantiate the initializer.
2167    if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs,
2168                               LParenLoc, CommaLocs, NewArgs, RParenLoc)) {
2169      AnyErrors = true;
2170      continue;
2171    }
2172
2173    MemInitResult NewInit;
2174    if (Init->isBaseInitializer()) {
2175      TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
2176                                            TemplateArgs,
2177                                            Init->getSourceLocation(),
2178                                            New->getDeclName());
2179      if (!BaseTInfo) {
2180        AnyErrors = true;
2181        New->setInvalidDecl();
2182        continue;
2183      }
2184
2185      NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
2186                                     (Expr **)NewArgs.data(),
2187                                     NewArgs.size(),
2188                                     Init->getLParenLoc(),
2189                                     Init->getRParenLoc(),
2190                                     New->getParent());
2191    } else if (Init->isMemberInitializer()) {
2192      FieldDecl *Member;
2193
2194      // Is this an anonymous union?
2195      if (FieldDecl *UnionInit = Init->getAnonUnionMember())
2196        Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(),
2197                                                      UnionInit, TemplateArgs));
2198      else
2199        Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(),
2200                                                      Init->getMember(),
2201                                                      TemplateArgs));
2202
2203      NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
2204                                       NewArgs.size(),
2205                                       Init->getSourceLocation(),
2206                                       Init->getLParenLoc(),
2207                                       Init->getRParenLoc());
2208    }
2209
2210    if (NewInit.isInvalid()) {
2211      AnyErrors = true;
2212      New->setInvalidDecl();
2213    } else {
2214      // FIXME: It would be nice if ASTOwningVector had a release function.
2215      NewArgs.take();
2216
2217      NewInits.push_back((MemInitTy *)NewInit.get());
2218    }
2219  }
2220
2221  // Assign all the initializers to the new constructor.
2222  ActOnMemInitializers(DeclPtrTy::make(New),
2223                       /*FIXME: ColonLoc */
2224                       SourceLocation(),
2225                       NewInits.data(), NewInits.size(),
2226                       AnyErrors);
2227}
2228
2229// TODO: this could be templated if the various decl types used the
2230// same method name.
2231static bool isInstantiationOf(ClassTemplateDecl *Pattern,
2232                              ClassTemplateDecl *Instance) {
2233  Pattern = Pattern->getCanonicalDecl();
2234
2235  do {
2236    Instance = Instance->getCanonicalDecl();
2237    if (Pattern == Instance) return true;
2238    Instance = Instance->getInstantiatedFromMemberTemplate();
2239  } while (Instance);
2240
2241  return false;
2242}
2243
2244static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
2245                              FunctionTemplateDecl *Instance) {
2246  Pattern = Pattern->getCanonicalDecl();
2247
2248  do {
2249    Instance = Instance->getCanonicalDecl();
2250    if (Pattern == Instance) return true;
2251    Instance = Instance->getInstantiatedFromMemberTemplate();
2252  } while (Instance);
2253
2254  return false;
2255}
2256
2257static bool
2258isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
2259                  ClassTemplatePartialSpecializationDecl *Instance) {
2260  Pattern
2261    = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
2262  do {
2263    Instance = cast<ClassTemplatePartialSpecializationDecl>(
2264                                                Instance->getCanonicalDecl());
2265    if (Pattern == Instance)
2266      return true;
2267    Instance = Instance->getInstantiatedFromMember();
2268  } while (Instance);
2269
2270  return false;
2271}
2272
2273static bool isInstantiationOf(CXXRecordDecl *Pattern,
2274                              CXXRecordDecl *Instance) {
2275  Pattern = Pattern->getCanonicalDecl();
2276
2277  do {
2278    Instance = Instance->getCanonicalDecl();
2279    if (Pattern == Instance) return true;
2280    Instance = Instance->getInstantiatedFromMemberClass();
2281  } while (Instance);
2282
2283  return false;
2284}
2285
2286static bool isInstantiationOf(FunctionDecl *Pattern,
2287                              FunctionDecl *Instance) {
2288  Pattern = Pattern->getCanonicalDecl();
2289
2290  do {
2291    Instance = Instance->getCanonicalDecl();
2292    if (Pattern == Instance) return true;
2293    Instance = Instance->getInstantiatedFromMemberFunction();
2294  } while (Instance);
2295
2296  return false;
2297}
2298
2299static bool isInstantiationOf(EnumDecl *Pattern,
2300                              EnumDecl *Instance) {
2301  Pattern = Pattern->getCanonicalDecl();
2302
2303  do {
2304    Instance = Instance->getCanonicalDecl();
2305    if (Pattern == Instance) return true;
2306    Instance = Instance->getInstantiatedFromMemberEnum();
2307  } while (Instance);
2308
2309  return false;
2310}
2311
2312static bool isInstantiationOf(UsingShadowDecl *Pattern,
2313                              UsingShadowDecl *Instance,
2314                              ASTContext &C) {
2315  return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
2316}
2317
2318static bool isInstantiationOf(UsingDecl *Pattern,
2319                              UsingDecl *Instance,
2320                              ASTContext &C) {
2321  return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
2322}
2323
2324static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
2325                              UsingDecl *Instance,
2326                              ASTContext &C) {
2327  return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
2328}
2329
2330static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
2331                              UsingDecl *Instance,
2332                              ASTContext &C) {
2333  return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
2334}
2335
2336static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
2337                                              VarDecl *Instance) {
2338  assert(Instance->isStaticDataMember());
2339
2340  Pattern = Pattern->getCanonicalDecl();
2341
2342  do {
2343    Instance = Instance->getCanonicalDecl();
2344    if (Pattern == Instance) return true;
2345    Instance = Instance->getInstantiatedFromStaticDataMember();
2346  } while (Instance);
2347
2348  return false;
2349}
2350
2351// Other is the prospective instantiation
2352// D is the prospective pattern
2353static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
2354  if (D->getKind() != Other->getKind()) {
2355    if (UnresolvedUsingTypenameDecl *UUD
2356          = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
2357      if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2358        return isInstantiationOf(UUD, UD, Ctx);
2359      }
2360    }
2361
2362    if (UnresolvedUsingValueDecl *UUD
2363          = dyn_cast<UnresolvedUsingValueDecl>(D)) {
2364      if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2365        return isInstantiationOf(UUD, UD, Ctx);
2366      }
2367    }
2368
2369    return false;
2370  }
2371
2372  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
2373    return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
2374
2375  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
2376    return isInstantiationOf(cast<FunctionDecl>(D), Function);
2377
2378  if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
2379    return isInstantiationOf(cast<EnumDecl>(D), Enum);
2380
2381  if (VarDecl *Var = dyn_cast<VarDecl>(Other))
2382    if (Var->isStaticDataMember())
2383      return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
2384
2385  if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
2386    return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
2387
2388  if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
2389    return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
2390
2391  if (ClassTemplatePartialSpecializationDecl *PartialSpec
2392        = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
2393    return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
2394                             PartialSpec);
2395
2396  if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
2397    if (!Field->getDeclName()) {
2398      // This is an unnamed field.
2399      return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
2400        cast<FieldDecl>(D);
2401    }
2402  }
2403
2404  if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
2405    return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
2406
2407  if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
2408    return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
2409
2410  return D->getDeclName() && isa<NamedDecl>(Other) &&
2411    D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
2412}
2413
2414template<typename ForwardIterator>
2415static NamedDecl *findInstantiationOf(ASTContext &Ctx,
2416                                      NamedDecl *D,
2417                                      ForwardIterator first,
2418                                      ForwardIterator last) {
2419  for (; first != last; ++first)
2420    if (isInstantiationOf(Ctx, D, *first))
2421      return cast<NamedDecl>(*first);
2422
2423  return 0;
2424}
2425
2426/// \brief Finds the instantiation of the given declaration context
2427/// within the current instantiation.
2428///
2429/// \returns NULL if there was an error
2430DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
2431                          const MultiLevelTemplateArgumentList &TemplateArgs) {
2432  if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
2433    Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
2434    return cast_or_null<DeclContext>(ID);
2435  } else return DC;
2436}
2437
2438/// \brief Find the instantiation of the given declaration within the
2439/// current instantiation.
2440///
2441/// This routine is intended to be used when \p D is a declaration
2442/// referenced from within a template, that needs to mapped into the
2443/// corresponding declaration within an instantiation. For example,
2444/// given:
2445///
2446/// \code
2447/// template<typename T>
2448/// struct X {
2449///   enum Kind {
2450///     KnownValue = sizeof(T)
2451///   };
2452///
2453///   bool getKind() const { return KnownValue; }
2454/// };
2455///
2456/// template struct X<int>;
2457/// \endcode
2458///
2459/// In the instantiation of X<int>::getKind(), we need to map the
2460/// EnumConstantDecl for KnownValue (which refers to
2461/// X<T>::<Kind>::KnownValue) to its instantiation
2462/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2463/// this mapping from within the instantiation of X<int>.
2464NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
2465                          const MultiLevelTemplateArgumentList &TemplateArgs) {
2466  DeclContext *ParentDC = D->getDeclContext();
2467  if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
2468      isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
2469      ParentDC->isFunctionOrMethod()) {
2470    // D is a local of some kind. Look into the map of local
2471    // declarations to their instantiations.
2472    return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
2473  }
2474
2475  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
2476    if (!Record->isDependentContext())
2477      return D;
2478
2479    // If the RecordDecl is actually the injected-class-name or a
2480    // "templated" declaration for a class template, class template
2481    // partial specialization, or a member class of a class template,
2482    // substitute into the injected-class-name of the class template
2483    // or partial specialization to find the new DeclContext.
2484    QualType T;
2485    ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
2486
2487    if (ClassTemplate) {
2488      T = ClassTemplate->getInjectedClassNameSpecialization(Context);
2489    } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2490                 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2491      ClassTemplate = PartialSpec->getSpecializedTemplate();
2492
2493      // If we call SubstType with an InjectedClassNameType here we
2494      // can end up in an infinite loop.
2495      T = Context.getTypeDeclType(Record);
2496      assert(isa<InjectedClassNameType>(T) &&
2497             "type of partial specialization is not an InjectedClassNameType");
2498      T = cast<InjectedClassNameType>(T)->getUnderlyingType();
2499    }
2500
2501    if (!T.isNull()) {
2502      // Substitute into the injected-class-name to get the type
2503      // corresponding to the instantiation we want, which may also be
2504      // the current instantiation (if we're in a template
2505      // definition). This substitution should never fail, since we
2506      // know we can instantiate the injected-class-name or we
2507      // wouldn't have gotten to the injected-class-name!
2508
2509      // FIXME: Can we use the CurrentInstantiationScope to avoid this
2510      // extra instantiation in the common case?
2511      T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
2512      assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
2513
2514      if (!T->isDependentType()) {
2515        assert(T->isRecordType() && "Instantiation must produce a record type");
2516        return T->getAs<RecordType>()->getDecl();
2517      }
2518
2519      // We are performing "partial" template instantiation to create
2520      // the member declarations for the members of a class template
2521      // specialization. Therefore, D is actually referring to something
2522      // in the current instantiation. Look through the current
2523      // context, which contains actual instantiations, to find the
2524      // instantiation of the "current instantiation" that D refers
2525      // to.
2526      bool SawNonDependentContext = false;
2527      for (DeclContext *DC = CurContext; !DC->isFileContext();
2528           DC = DC->getParent()) {
2529        if (ClassTemplateSpecializationDecl *Spec
2530                          = dyn_cast<ClassTemplateSpecializationDecl>(DC))
2531          if (isInstantiationOf(ClassTemplate,
2532                                Spec->getSpecializedTemplate()))
2533            return Spec;
2534
2535        if (!DC->isDependentContext())
2536          SawNonDependentContext = true;
2537      }
2538
2539      // We're performing "instantiation" of a member of the current
2540      // instantiation while we are type-checking the
2541      // definition. Compute the declaration context and return that.
2542      assert(!SawNonDependentContext &&
2543             "No dependent context while instantiating record");
2544      DeclContext *DC = computeDeclContext(T);
2545      assert(DC &&
2546             "Unable to find declaration for the current instantiation");
2547      return cast<CXXRecordDecl>(DC);
2548    }
2549
2550    // Fall through to deal with other dependent record types (e.g.,
2551    // anonymous unions in class templates).
2552  }
2553
2554  if (!ParentDC->isDependentContext())
2555    return D;
2556
2557  ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
2558  if (!ParentDC)
2559    return 0;
2560
2561  if (ParentDC != D->getDeclContext()) {
2562    // We performed some kind of instantiation in the parent context,
2563    // so now we need to look into the instantiated parent context to
2564    // find the instantiation of the declaration D.
2565
2566    // If our context used to be dependent, we may need to instantiate
2567    // it before performing lookup into that context.
2568    if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
2569      if (!Spec->isDependentContext()) {
2570        QualType T = Context.getTypeDeclType(Spec);
2571        const RecordType *Tag = T->getAs<RecordType>();
2572        assert(Tag && "type of non-dependent record is not a RecordType");
2573        if (!Tag->isBeingDefined() &&
2574            RequireCompleteType(Loc, T, diag::err_incomplete_type))
2575          return 0;
2576      }
2577    }
2578
2579    NamedDecl *Result = 0;
2580    if (D->getDeclName()) {
2581      DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
2582      Result = findInstantiationOf(Context, D, Found.first, Found.second);
2583    } else {
2584      // Since we don't have a name for the entity we're looking for,
2585      // our only option is to walk through all of the declarations to
2586      // find that name. This will occur in a few cases:
2587      //
2588      //   - anonymous struct/union within a template
2589      //   - unnamed class/struct/union/enum within a template
2590      //
2591      // FIXME: Find a better way to find these instantiations!
2592      Result = findInstantiationOf(Context, D,
2593                                   ParentDC->decls_begin(),
2594                                   ParentDC->decls_end());
2595    }
2596
2597    // UsingShadowDecls can instantiate to nothing because of using hiding.
2598    assert((Result || isa<UsingShadowDecl>(D) || D->isInvalidDecl() ||
2599            cast<Decl>(ParentDC)->isInvalidDecl())
2600           && "Unable to find instantiation of declaration!");
2601
2602    D = Result;
2603  }
2604
2605  return D;
2606}
2607
2608/// \brief Performs template instantiation for all implicit template
2609/// instantiations we have seen until this point.
2610void Sema::PerformPendingImplicitInstantiations(bool LocalOnly) {
2611  while (!PendingLocalImplicitInstantiations.empty() ||
2612         (!LocalOnly && !PendingImplicitInstantiations.empty())) {
2613    PendingImplicitInstantiation Inst;
2614
2615    if (PendingLocalImplicitInstantiations.empty()) {
2616      Inst = PendingImplicitInstantiations.front();
2617      PendingImplicitInstantiations.pop_front();
2618    } else {
2619      Inst = PendingLocalImplicitInstantiations.front();
2620      PendingLocalImplicitInstantiations.pop_front();
2621    }
2622
2623    // Instantiate function definitions
2624    if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
2625      PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function),
2626                                            Function->getLocation(), *this,
2627                                            Context.getSourceManager(),
2628                                           "instantiating function definition");
2629
2630      if (!Function->getBody())
2631        InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
2632      continue;
2633    }
2634
2635    // Instantiate static data member definitions.
2636    VarDecl *Var = cast<VarDecl>(Inst.first);
2637    assert(Var->isStaticDataMember() && "Not a static data member?");
2638
2639    // Don't try to instantiate declarations if the most recent redeclaration
2640    // is invalid.
2641    if (Var->getMostRecentDeclaration()->isInvalidDecl())
2642      continue;
2643
2644    // Check if the most recent declaration has changed the specialization kind
2645    // and removed the need for implicit instantiation.
2646    switch (Var->getMostRecentDeclaration()->getTemplateSpecializationKind()) {
2647    case TSK_Undeclared:
2648      assert(false && "Cannot instantitiate an undeclared specialization.");
2649    case TSK_ExplicitInstantiationDeclaration:
2650    case TSK_ExplicitInstantiationDefinition:
2651    case TSK_ExplicitSpecialization:
2652      continue;  // No longer need implicit instantiation.
2653    case TSK_ImplicitInstantiation:
2654      break;
2655    }
2656
2657    PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var),
2658                                          Var->getLocation(), *this,
2659                                          Context.getSourceManager(),
2660                                          "instantiating static data member "
2661                                          "definition");
2662
2663    InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
2664  }
2665}
2666
2667void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
2668                       const MultiLevelTemplateArgumentList &TemplateArgs) {
2669  for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
2670         E = Pattern->ddiag_end(); I != E; ++I) {
2671    DependentDiagnostic *DD = *I;
2672
2673    switch (DD->getKind()) {
2674    case DependentDiagnostic::Access:
2675      HandleDependentAccessCheck(*DD, TemplateArgs);
2676      break;
2677    }
2678  }
2679}
2680