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