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