SemaTemplateInstantiateDecl.cpp revision 4ba3136b3eb9740a07bd61d0ab23ce9a8d894dee
1//===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl Instantiation ===/
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//===----------------------------------------------------------------------===/
8//
9//  This file implements C++ template instantiation for declarations.
10//
11//===----------------------------------------------------------------------===/
12#include "Sema.h"
13#include "Lookup.h"
14#include "clang/AST/ASTConsumer.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/DeclTemplate.h"
17#include "clang/AST/DeclVisitor.h"
18#include "clang/AST/Expr.h"
19#include "clang/Basic/PrettyStackTrace.h"
20#include "clang/Lex/Preprocessor.h"
21
22using namespace clang;
23
24namespace {
25  class TemplateDeclInstantiator
26    : public DeclVisitor<TemplateDeclInstantiator, Decl *> {
27    Sema &SemaRef;
28    DeclContext *Owner;
29    const MultiLevelTemplateArgumentList &TemplateArgs;
30
31    void InstantiateAttrs(Decl *Tmpl, Decl *New);
32
33  public:
34    typedef Sema::OwningExprResult OwningExprResult;
35
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.def.
43    Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
44    Decl *VisitNamespaceDecl(NamespaceDecl *D);
45    Decl *VisitTypedefDecl(TypedefDecl *D);
46    Decl *VisitVarDecl(VarDecl *D);
47    Decl *VisitFieldDecl(FieldDecl *D);
48    Decl *VisitStaticAssertDecl(StaticAssertDecl *D);
49    Decl *VisitEnumDecl(EnumDecl *D);
50    Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
51    Decl *VisitFriendDecl(FriendDecl *D);
52    Decl *VisitFunctionDecl(FunctionDecl *D,
53                            TemplateParameterList *TemplateParams = 0);
54    Decl *VisitCXXRecordDecl(CXXRecordDecl *D);
55    Decl *VisitCXXMethodDecl(CXXMethodDecl *D,
56                             TemplateParameterList *TemplateParams = 0);
57    Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
58    Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
59    Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
60    ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D);
61    Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
62    Decl *VisitClassTemplatePartialSpecializationDecl(
63                                    ClassTemplatePartialSpecializationDecl *D);
64    Decl *VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
65    Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
66    Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
67    Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
68    Decl *VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
69    Decl *VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
70    Decl *VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
71
72    // Base case. FIXME: Remove once we can instantiate everything.
73    Decl *VisitDecl(Decl *D) {
74      unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
75                                                            Diagnostic::Error,
76                                                   "cannot instantiate %0 yet");
77      SemaRef.Diag(D->getLocation(), DiagID)
78        << D->getDeclKindName();
79
80      return 0;
81    }
82
83    const LangOptions &getLangOptions() {
84      return SemaRef.getLangOptions();
85    }
86
87    // Helper functions for instantiating methods.
88    QualType 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 InstantiateClassTemplatePartialSpecialization(
97                                              ClassTemplateDecl *ClassTemplate,
98                           ClassTemplatePartialSpecializationDecl *PartialSpec);
99  };
100}
101
102// FIXME: Is this too simple?
103void TemplateDeclInstantiator::InstantiateAttrs(Decl *Tmpl, Decl *New) {
104  for (const Attr *TmplAttr = Tmpl->getAttrs(); TmplAttr;
105       TmplAttr = TmplAttr->getNext()) {
106
107    // FIXME: Is cloning correct for all attributes?
108    Attr *NewAttr = TmplAttr->clone(SemaRef.Context);
109
110    New->addAttr(NewAttr);
111  }
112}
113
114Decl *
115TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
116  assert(false && "Translation units cannot be instantiated");
117  return D;
118}
119
120Decl *
121TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
122  assert(false && "Namespaces cannot be instantiated");
123  return D;
124}
125
126Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
127  bool Invalid = false;
128  DeclaratorInfo *DI = D->getTypeDeclaratorInfo();
129  if (DI->getType()->isDependentType()) {
130    DI = SemaRef.SubstType(DI, TemplateArgs,
131                           D->getLocation(), D->getDeclName());
132    if (!DI) {
133      Invalid = true;
134      DI = SemaRef.Context.getTrivialDeclaratorInfo(SemaRef.Context.IntTy);
135    }
136  }
137
138  // Create the new typedef
139  TypedefDecl *Typedef
140    = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
141                          D->getIdentifier(), DI);
142  if (Invalid)
143    Typedef->setInvalidDecl();
144
145  Owner->addDecl(Typedef);
146
147  return Typedef;
148}
149
150Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
151  // Do substitution on the type of the declaration
152  DeclaratorInfo *DI = SemaRef.SubstType(D->getDeclaratorInfo(),
153                                         TemplateArgs,
154                                         D->getTypeSpecStartLoc(),
155                                         D->getDeclName());
156  if (!DI)
157    return 0;
158
159  // Build the instantiated declaration
160  VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
161                                 D->getLocation(), D->getIdentifier(),
162                                 DI->getType(), DI,
163                                 D->getStorageClass());
164  Var->setThreadSpecified(D->isThreadSpecified());
165  Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
166  Var->setDeclaredInCondition(D->isDeclaredInCondition());
167
168  // If we are instantiating a static data member defined
169  // out-of-line, the instantiation will have the same lexical
170  // context (which will be a namespace scope) as the template.
171  if (D->isOutOfLine())
172    Var->setLexicalDeclContext(D->getLexicalDeclContext());
173
174  // FIXME: In theory, we could have a previous declaration for variables that
175  // are not static data members.
176  bool Redeclaration = false;
177  // FIXME: having to fake up a LookupResult is dumb.
178  LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
179                        Sema::LookupOrdinaryName);
180  SemaRef.CheckVariableDeclaration(Var, Previous, Redeclaration);
181
182  if (D->isOutOfLine()) {
183    D->getLexicalDeclContext()->addDecl(Var);
184    Owner->makeDeclVisibleInContext(Var);
185  } else {
186    Owner->addDecl(Var);
187  }
188
189  // Link instantiations of static data members back to the template from
190  // which they were instantiated.
191  if (Var->isStaticDataMember())
192    SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
193                                                     TSK_ImplicitInstantiation);
194
195  if (D->getInit()) {
196    OwningExprResult Init
197      = SemaRef.SubstExpr(D->getInit(), TemplateArgs);
198    if (Init.isInvalid())
199      Var->setInvalidDecl();
200    else if (!D->getType()->isDependentType() &&
201             !D->getInit()->isTypeDependent() &&
202             !D->getInit()->isValueDependent()) {
203      // If neither the declaration's type nor its initializer are dependent,
204      // we don't want to redo all the checking, especially since the
205      // initializer might have been wrapped by a CXXConstructExpr since we did
206      // it the first time.
207      Var->setType(D->getType());
208      Var->setInit(SemaRef.Context, Init.takeAs<Expr>());
209    }
210    else if (ParenListExpr *PLE = dyn_cast<ParenListExpr>((Expr *)Init.get())) {
211      // FIXME: We're faking all of the comma locations, which is suboptimal.
212      // Do we even need these comma locations?
213      llvm::SmallVector<SourceLocation, 4> FakeCommaLocs;
214      if (PLE->getNumExprs() > 0) {
215        FakeCommaLocs.reserve(PLE->getNumExprs() - 1);
216        for (unsigned I = 0, N = PLE->getNumExprs() - 1; I != N; ++I) {
217          Expr *E = PLE->getExpr(I)->Retain();
218          FakeCommaLocs.push_back(
219                                SemaRef.PP.getLocForEndOfToken(E->getLocEnd()));
220        }
221        PLE->getExpr(PLE->getNumExprs() - 1)->Retain();
222      }
223
224      // Add the direct initializer to the declaration.
225      SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var),
226                                            PLE->getLParenLoc(),
227                                            Sema::MultiExprArg(SemaRef,
228                                                       (void**)PLE->getExprs(),
229                                                           PLE->getNumExprs()),
230                                            FakeCommaLocs.data(),
231                                            PLE->getRParenLoc());
232
233      // When Init is destroyed, it will destroy the instantiated ParenListExpr;
234      // we've explicitly retained all of its subexpressions already.
235    } else
236      SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var), move(Init),
237                                   D->hasCXXDirectInitializer());
238  } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
239    SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
240
241  return Var;
242}
243
244Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
245  bool Invalid = false;
246  DeclaratorInfo *DI = D->getDeclaratorInfo();
247  if (DI->getType()->isDependentType())  {
248    DI = SemaRef.SubstType(DI, TemplateArgs,
249                           D->getLocation(), D->getDeclName());
250    if (!DI) {
251      DI = D->getDeclaratorInfo();
252      Invalid = true;
253    } else if (DI->getType()->isFunctionType()) {
254      // C++ [temp.arg.type]p3:
255      //   If a declaration acquires a function type through a type
256      //   dependent on a template-parameter and this causes a
257      //   declaration that does not use the syntactic form of a
258      //   function declarator to have function type, the program is
259      //   ill-formed.
260      SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
261        << DI->getType();
262      Invalid = true;
263    }
264  }
265
266  Expr *BitWidth = D->getBitWidth();
267  if (Invalid)
268    BitWidth = 0;
269  else if (BitWidth) {
270    // The bit-width expression is not potentially evaluated.
271    EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
272
273    OwningExprResult InstantiatedBitWidth
274      = SemaRef.SubstExpr(BitWidth, TemplateArgs);
275    if (InstantiatedBitWidth.isInvalid()) {
276      Invalid = true;
277      BitWidth = 0;
278    } else
279      BitWidth = InstantiatedBitWidth.takeAs<Expr>();
280  }
281
282  FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
283                                            DI->getType(), DI,
284                                            cast<RecordDecl>(Owner),
285                                            D->getLocation(),
286                                            D->isMutable(),
287                                            BitWidth,
288                                            D->getTypeSpecStartLoc(),
289                                            D->getAccess(),
290                                            0);
291  if (!Field) {
292    cast<Decl>(Owner)->setInvalidDecl();
293    return 0;
294  }
295
296  InstantiateAttrs(D, Field);
297
298  if (Invalid)
299    Field->setInvalidDecl();
300
301  if (!Field->getDeclName()) {
302    // Keep track of where this decl came from.
303    SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
304  }
305
306  Field->setImplicit(D->isImplicit());
307  Owner->addDecl(Field);
308
309  return Field;
310}
311
312Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
313  FriendDecl::FriendUnion FU;
314
315  // Handle friend type expressions by simply substituting template
316  // parameters into the pattern type.
317  if (Type *Ty = D->getFriendType()) {
318    QualType T = SemaRef.SubstType(QualType(Ty,0), TemplateArgs,
319                                   D->getLocation(), DeclarationName());
320    if (T.isNull()) return 0;
321
322    assert(getLangOptions().CPlusPlus0x || T->isRecordType());
323    FU = T.getTypePtr();
324
325  // Handle everything else by appropriate substitution.
326  } else {
327    NamedDecl *ND = D->getFriendDecl();
328    assert(ND && "friend decl must be a decl or a type!");
329
330    // FIXME: We have a problem here, because the nested call to Visit(ND)
331    // will inject the thing that the friend references into the current
332    // owner, which is wrong.
333    Decl *NewND = Visit(ND);
334    if (!NewND) return 0;
335
336    FU = cast<NamedDecl>(NewND);
337  }
338
339  FriendDecl *FD =
340    FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(), FU,
341                       D->getFriendLoc());
342  FD->setAccess(AS_public);
343  Owner->addDecl(FD);
344  return FD;
345}
346
347Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
348  Expr *AssertExpr = D->getAssertExpr();
349
350  // The expression in a static assertion is not potentially evaluated.
351  EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
352
353  OwningExprResult InstantiatedAssertExpr
354    = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
355  if (InstantiatedAssertExpr.isInvalid())
356    return 0;
357
358  OwningExprResult Message(SemaRef, D->getMessage());
359  D->getMessage()->Retain();
360  Decl *StaticAssert
361    = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
362                                           move(InstantiatedAssertExpr),
363                                           move(Message)).getAs<Decl>();
364  return StaticAssert;
365}
366
367Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
368  EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
369                                    D->getLocation(), D->getIdentifier(),
370                                    D->getTagKeywordLoc(),
371                                    /*PrevDecl=*/0);
372  Enum->setInstantiationOfMemberEnum(D);
373  Enum->setAccess(D->getAccess());
374  Owner->addDecl(Enum);
375  Enum->startDefinition();
376
377  llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
378
379  EnumConstantDecl *LastEnumConst = 0;
380  for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
381         ECEnd = D->enumerator_end();
382       EC != ECEnd; ++EC) {
383    // The specified value for the enumerator.
384    OwningExprResult Value = SemaRef.Owned((Expr *)0);
385    if (Expr *UninstValue = EC->getInitExpr()) {
386      // The enumerator's value expression is not potentially evaluated.
387      EnterExpressionEvaluationContext Unevaluated(SemaRef,
388                                                   Action::Unevaluated);
389
390      Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
391    }
392
393    // Drop the initial value and continue.
394    bool isInvalid = false;
395    if (Value.isInvalid()) {
396      Value = SemaRef.Owned((Expr *)0);
397      isInvalid = true;
398    }
399
400    EnumConstantDecl *EnumConst
401      = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
402                                  EC->getLocation(), EC->getIdentifier(),
403                                  move(Value));
404
405    if (isInvalid) {
406      if (EnumConst)
407        EnumConst->setInvalidDecl();
408      Enum->setInvalidDecl();
409    }
410
411    if (EnumConst) {
412      Enum->addDecl(EnumConst);
413      Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
414      LastEnumConst = EnumConst;
415    }
416  }
417
418  // FIXME: Fixup LBraceLoc and RBraceLoc
419  // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
420  SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
421                        Sema::DeclPtrTy::make(Enum),
422                        &Enumerators[0], Enumerators.size(),
423                        0, 0);
424
425  return Enum;
426}
427
428Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
429  assert(false && "EnumConstantDecls can only occur within EnumDecls.");
430  return 0;
431}
432
433namespace {
434  class SortDeclByLocation {
435    SourceManager &SourceMgr;
436
437  public:
438    explicit SortDeclByLocation(SourceManager &SourceMgr)
439      : SourceMgr(SourceMgr) { }
440
441    bool operator()(const Decl *X, const Decl *Y) const {
442      return SourceMgr.isBeforeInTranslationUnit(X->getLocation(),
443                                                 Y->getLocation());
444    }
445  };
446}
447
448Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
449  // Create a local instantiation scope for this class template, which
450  // will contain the instantiations of the template parameters.
451  Sema::LocalInstantiationScope Scope(SemaRef);
452  TemplateParameterList *TempParams = D->getTemplateParameters();
453  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
454  if (!InstParams)
455    return NULL;
456
457  CXXRecordDecl *Pattern = D->getTemplatedDecl();
458  CXXRecordDecl *RecordInst
459    = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), Owner,
460                            Pattern->getLocation(), Pattern->getIdentifier(),
461                            Pattern->getTagKeywordLoc(), /*PrevDecl=*/ NULL,
462                            /*DelayTypeCreation=*/true);
463
464  ClassTemplateDecl *Inst
465    = ClassTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
466                                D->getIdentifier(), InstParams, RecordInst, 0);
467  RecordInst->setDescribedClassTemplate(Inst);
468  if (D->getFriendObjectKind())
469    Inst->setObjectOfFriendDecl(true);
470  else
471    Inst->setAccess(D->getAccess());
472  Inst->setInstantiatedFromMemberTemplate(D);
473
474  // Trigger creation of the type for the instantiation.
475  SemaRef.Context.getTypeDeclType(RecordInst);
476
477  // Finish handling of friends.
478  if (Inst->getFriendObjectKind()) {
479    return Inst;
480  }
481
482  Owner->addDecl(Inst);
483
484  // First, we sort the partial specializations by location, so
485  // that we instantiate them in the order they were declared.
486  llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
487  for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
488         P = D->getPartialSpecializations().begin(),
489         PEnd = D->getPartialSpecializations().end();
490       P != PEnd; ++P)
491    PartialSpecs.push_back(&*P);
492  std::sort(PartialSpecs.begin(), PartialSpecs.end(),
493            SortDeclByLocation(SemaRef.SourceMgr));
494
495  // Instantiate all of the partial specializations of this member class
496  // template.
497  for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
498    InstantiateClassTemplatePartialSpecialization(Inst, PartialSpecs[I]);
499
500  return Inst;
501}
502
503Decl *
504TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
505                                   ClassTemplatePartialSpecializationDecl *D) {
506  ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
507
508  // Lookup the already-instantiated declaration in the instantiation
509  // of the class template and return that.
510  DeclContext::lookup_result Found
511    = Owner->lookup(ClassTemplate->getDeclName());
512  if (Found.first == Found.second)
513    return 0;
514
515  ClassTemplateDecl *InstClassTemplate
516    = dyn_cast<ClassTemplateDecl>(*Found.first);
517  if (!InstClassTemplate)
518    return 0;
519
520  Decl *DCanon = D->getCanonicalDecl();
521  for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
522            P = InstClassTemplate->getPartialSpecializations().begin(),
523         PEnd = InstClassTemplate->getPartialSpecializations().end();
524       P != PEnd; ++P) {
525    if (P->getInstantiatedFromMember()->getCanonicalDecl() == DCanon)
526      return &*P;
527  }
528
529  return 0;
530}
531
532Decl *
533TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
534  // Create a local instantiation scope for this function template, which
535  // will contain the instantiations of the template parameters and then get
536  // merged with the local instantiation scope for the function template
537  // itself.
538  Sema::LocalInstantiationScope Scope(SemaRef);
539
540  TemplateParameterList *TempParams = D->getTemplateParameters();
541  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
542  if (!InstParams)
543    return NULL;
544
545  FunctionDecl *Instantiated = 0;
546  if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
547    Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
548                                                                 InstParams));
549  else
550    Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
551                                                          D->getTemplatedDecl(),
552                                                                InstParams));
553
554  if (!Instantiated)
555    return 0;
556
557  // Link the instantiated function template declaration to the function
558  // template from which it was instantiated.
559  FunctionTemplateDecl *InstTemplate
560    = Instantiated->getDescribedFunctionTemplate();
561  InstTemplate->setAccess(D->getAccess());
562  assert(InstTemplate &&
563         "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
564  if (!InstTemplate->getInstantiatedFromMemberTemplate())
565    InstTemplate->setInstantiatedFromMemberTemplate(D);
566
567  // Add non-friends into the owner.
568  if (!InstTemplate->getFriendObjectKind())
569    Owner->addDecl(InstTemplate);
570  return InstTemplate;
571}
572
573Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
574  CXXRecordDecl *PrevDecl = 0;
575  if (D->isInjectedClassName())
576    PrevDecl = cast<CXXRecordDecl>(Owner);
577
578  CXXRecordDecl *Record
579    = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
580                            D->getLocation(), D->getIdentifier(),
581                            D->getTagKeywordLoc(), PrevDecl);
582  Record->setImplicit(D->isImplicit());
583  // FIXME: Check against AS_none is an ugly hack to work around the issue that
584  // the tag decls introduced by friend class declarations don't have an access
585  // specifier. Remove once this area of the code gets sorted out.
586  if (D->getAccess() != AS_none)
587    Record->setAccess(D->getAccess());
588  if (!D->isInjectedClassName())
589    Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
590
591  // If the original function was part of a friend declaration,
592  // inherit its namespace state.
593  if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
594    Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
595
596  Record->setAnonymousStructOrUnion(D->isAnonymousStructOrUnion());
597
598  Owner->addDecl(Record);
599  return Record;
600}
601
602/// Normal class members are of more specific types and therefore
603/// don't make it here.  This function serves two purposes:
604///   1) instantiating function templates
605///   2) substituting friend declarations
606/// FIXME: preserve function definitions in case #2
607  Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
608                                       TemplateParameterList *TemplateParams) {
609  // Check whether there is already a function template specialization for
610  // this declaration.
611  FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
612  void *InsertPos = 0;
613  if (FunctionTemplate && !TemplateParams) {
614    llvm::FoldingSetNodeID ID;
615    FunctionTemplateSpecializationInfo::Profile(ID,
616                             TemplateArgs.getInnermost().getFlatArgumentList(),
617                                       TemplateArgs.getInnermost().flat_size(),
618                                                SemaRef.Context);
619
620    FunctionTemplateSpecializationInfo *Info
621      = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
622                                                                   InsertPos);
623
624    // If we already have a function template specialization, return it.
625    if (Info)
626      return Info->Function;
627  }
628
629  Sema::LocalInstantiationScope Scope(SemaRef, TemplateParams != 0);
630
631  llvm::SmallVector<ParmVarDecl *, 4> Params;
632  QualType T = SubstFunctionType(D, Params);
633  if (T.isNull())
634    return 0;
635
636  // Build the instantiated method declaration.
637  DeclContext *DC = SemaRef.FindInstantiatedContext(D->getDeclContext(),
638                                                    TemplateArgs);
639  FunctionDecl *Function =
640      FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
641                           D->getDeclName(), T, D->getDeclaratorInfo(),
642                           D->getStorageClass(),
643                           D->isInlineSpecified(), D->hasWrittenPrototype());
644  Function->setLexicalDeclContext(Owner);
645
646  // Attach the parameters
647  for (unsigned P = 0; P < Params.size(); ++P)
648    Params[P]->setOwningFunction(Function);
649  Function->setParams(SemaRef.Context, Params.data(), Params.size());
650
651  if (TemplateParams) {
652    // Our resulting instantiation is actually a function template, since we
653    // are substituting only the outer template parameters. For example, given
654    //
655    //   template<typename T>
656    //   struct X {
657    //     template<typename U> friend void f(T, U);
658    //   };
659    //
660    //   X<int> x;
661    //
662    // We are instantiating the friend function template "f" within X<int>,
663    // which means substituting int for T, but leaving "f" as a friend function
664    // template.
665    // Build the function template itself.
666    FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Owner,
667                                                    Function->getLocation(),
668                                                    Function->getDeclName(),
669                                                    TemplateParams, Function);
670    Function->setDescribedFunctionTemplate(FunctionTemplate);
671    FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
672  } else if (FunctionTemplate) {
673    // Record this function template specialization.
674    Function->setFunctionTemplateSpecialization(SemaRef.Context,
675                                                FunctionTemplate,
676                                                &TemplateArgs.getInnermost(),
677                                                InsertPos);
678  }
679
680  if (InitFunctionInstantiation(Function, D))
681    Function->setInvalidDecl();
682
683  bool Redeclaration = false;
684  bool OverloadableAttrRequired = false;
685
686  LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
687                        Sema::LookupOrdinaryName, Sema::ForRedeclaration);
688
689  if (TemplateParams || !FunctionTemplate) {
690    // Look only into the namespace where the friend would be declared to
691    // find a previous declaration. This is the innermost enclosing namespace,
692    // as described in ActOnFriendFunctionDecl.
693    SemaRef.LookupQualifiedName(Previous, DC);
694
695    // In C++, the previous declaration we find might be a tag type
696    // (class or enum). In this case, the new declaration will hide the
697    // tag type. Note that this does does not apply if we're declaring a
698    // typedef (C++ [dcl.typedef]p4).
699    if (Previous.isSingleTagDecl())
700      Previous.clear();
701  }
702
703  SemaRef.CheckFunctionDeclaration(Function, Previous, false, Redeclaration,
704                                   /*FIXME:*/OverloadableAttrRequired);
705
706  // If the original function was part of a friend declaration,
707  // inherit its namespace state and add it to the owner.
708  NamedDecl *FromFriendD
709      = TemplateParams? cast<NamedDecl>(D->getDescribedFunctionTemplate()) : D;
710  if (FromFriendD->getFriendObjectKind()) {
711    NamedDecl *ToFriendD = 0;
712    NamedDecl *PrevDecl;
713    if (TemplateParams) {
714      ToFriendD = cast<NamedDecl>(FunctionTemplate);
715      PrevDecl = FunctionTemplate->getPreviousDeclaration();
716    } else {
717      ToFriendD = Function;
718      PrevDecl = Function->getPreviousDeclaration();
719    }
720    ToFriendD->setObjectOfFriendDecl(PrevDecl != NULL);
721    if (!Owner->isDependentContext() && !PrevDecl)
722      DC->makeDeclVisibleInContext(ToFriendD, /* Recoverable = */ false);
723
724    if (!TemplateParams)
725      Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
726  }
727
728  return Function;
729}
730
731Decl *
732TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
733                                      TemplateParameterList *TemplateParams) {
734  FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
735  void *InsertPos = 0;
736  if (FunctionTemplate && !TemplateParams) {
737    // We are creating a function template specialization from a function
738    // template. Check whether there is already a function template
739    // specialization for this particular set of template arguments.
740    llvm::FoldingSetNodeID ID;
741    FunctionTemplateSpecializationInfo::Profile(ID,
742                            TemplateArgs.getInnermost().getFlatArgumentList(),
743                                      TemplateArgs.getInnermost().flat_size(),
744                                                SemaRef.Context);
745
746    FunctionTemplateSpecializationInfo *Info
747      = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
748                                                                   InsertPos);
749
750    // If we already have a function template specialization, return it.
751    if (Info)
752      return Info->Function;
753  }
754
755  Sema::LocalInstantiationScope Scope(SemaRef, TemplateParams != 0);
756
757  llvm::SmallVector<ParmVarDecl *, 4> Params;
758  QualType T = SubstFunctionType(D, Params);
759  if (T.isNull())
760    return 0;
761
762  // Build the instantiated method declaration.
763  CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
764  CXXMethodDecl *Method = 0;
765
766  DeclarationName Name = D->getDeclName();
767  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
768    QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
769    Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
770                                    SemaRef.Context.getCanonicalType(ClassTy));
771    Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
772                                        Constructor->getLocation(),
773                                        Name, T,
774                                        Constructor->getDeclaratorInfo(),
775                                        Constructor->isExplicit(),
776                                        Constructor->isInlineSpecified(), false);
777  } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
778    QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
779    Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
780                                   SemaRef.Context.getCanonicalType(ClassTy));
781    Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
782                                       Destructor->getLocation(), Name,
783                                       T, Destructor->isInlineSpecified(), false);
784  } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
785    CanQualType ConvTy
786      = SemaRef.Context.getCanonicalType(
787                                      T->getAs<FunctionType>()->getResultType());
788    Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
789                                                                      ConvTy);
790    Method = CXXConversionDecl::Create(SemaRef.Context, Record,
791                                       Conversion->getLocation(), Name,
792                                       T, Conversion->getDeclaratorInfo(),
793                                       Conversion->isInlineSpecified(),
794                                       Conversion->isExplicit());
795  } else {
796    Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
797                                   D->getDeclName(), T, D->getDeclaratorInfo(),
798                                   D->isStatic(), D->isInlineSpecified());
799  }
800
801  if (TemplateParams) {
802    // Our resulting instantiation is actually a function template, since we
803    // are substituting only the outer template parameters. For example, given
804    //
805    //   template<typename T>
806    //   struct X {
807    //     template<typename U> void f(T, U);
808    //   };
809    //
810    //   X<int> x;
811    //
812    // We are instantiating the member template "f" within X<int>, which means
813    // substituting int for T, but leaving "f" as a member function template.
814    // Build the function template itself.
815    FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
816                                                    Method->getLocation(),
817                                                    Method->getDeclName(),
818                                                    TemplateParams, Method);
819    if (D->isOutOfLine())
820      FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
821    Method->setDescribedFunctionTemplate(FunctionTemplate);
822  } else if (FunctionTemplate) {
823    // Record this function template specialization.
824    Method->setFunctionTemplateSpecialization(SemaRef.Context,
825                                              FunctionTemplate,
826                                              &TemplateArgs.getInnermost(),
827                                              InsertPos);
828  } else {
829    // Record that this is an instantiation of a member function.
830    Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
831  }
832
833  // If we are instantiating a member function defined
834  // out-of-line, the instantiation will have the same lexical
835  // context (which will be a namespace scope) as the template.
836  if (D->isOutOfLine())
837    Method->setLexicalDeclContext(D->getLexicalDeclContext());
838
839  // Attach the parameters
840  for (unsigned P = 0; P < Params.size(); ++P)
841    Params[P]->setOwningFunction(Method);
842  Method->setParams(SemaRef.Context, Params.data(), Params.size());
843
844  if (InitMethodInstantiation(Method, D))
845    Method->setInvalidDecl();
846
847  LookupResult Previous(SemaRef, Name, SourceLocation(),
848                        Sema::LookupOrdinaryName, Sema::ForRedeclaration);
849
850  if (!FunctionTemplate || TemplateParams) {
851    SemaRef.LookupQualifiedName(Previous, Owner);
852
853    // In C++, the previous declaration we find might be a tag type
854    // (class or enum). In this case, the new declaration will hide the
855    // tag type. Note that this does does not apply if we're declaring a
856    // typedef (C++ [dcl.typedef]p4).
857    if (Previous.isSingleTagDecl())
858      Previous.clear();
859  }
860
861  bool Redeclaration = false;
862  bool OverloadableAttrRequired = false;
863  SemaRef.CheckFunctionDeclaration(Method, Previous, false, Redeclaration,
864                                   /*FIXME:*/OverloadableAttrRequired);
865
866  if (D->isPure())
867    SemaRef.CheckPureMethod(Method, SourceRange());
868
869  if (!FunctionTemplate && (!Method->isInvalidDecl() || Previous.empty()) &&
870      !Method->getFriendObjectKind())
871    Owner->addDecl(Method);
872
873  SemaRef.AddOverriddenMethods(Record, Method);
874
875  return Method;
876}
877
878Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
879  return VisitCXXMethodDecl(D);
880}
881
882Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
883  return VisitCXXMethodDecl(D);
884}
885
886Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
887  return VisitCXXMethodDecl(D);
888}
889
890ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
891  QualType T;
892  DeclaratorInfo *DI = D->getDeclaratorInfo();
893  if (DI) {
894    DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
895                           D->getDeclName());
896    if (DI) T = DI->getType();
897  } else {
898    T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
899                          D->getDeclName());
900    DI = 0;
901  }
902
903  if (T.isNull())
904    return 0;
905
906  T = SemaRef.adjustParameterType(T);
907
908  // Allocate the parameter
909  ParmVarDecl *Param
910    = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(),
911                          D->getIdentifier(), T, DI, D->getStorageClass(), 0);
912
913  // Mark the default argument as being uninstantiated.
914  if (D->hasUninstantiatedDefaultArg())
915    Param->setUninstantiatedDefaultArg(D->getUninstantiatedDefaultArg());
916  else if (Expr *Arg = D->getDefaultArg())
917    Param->setUninstantiatedDefaultArg(Arg);
918
919  // Note: we don't try to instantiate function parameters until after
920  // we've instantiated the function's type. Therefore, we don't have
921  // to check for 'void' parameter types here.
922  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
923  return Param;
924}
925
926Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
927                                                    TemplateTypeParmDecl *D) {
928  // TODO: don't always clone when decls are refcounted.
929  const Type* T = D->getTypeForDecl();
930  assert(T->isTemplateTypeParmType());
931  const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
932
933  TemplateTypeParmDecl *Inst =
934    TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
935                                 TTPT->getDepth() - 1, TTPT->getIndex(),
936                                 TTPT->getName(),
937                                 D->wasDeclaredWithTypename(),
938                                 D->isParameterPack());
939
940  if (D->hasDefaultArgument())
941    Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
942
943  // Introduce this template parameter's instantiation into the instantiation
944  // scope.
945  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
946
947  return Inst;
948}
949
950Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
951                                                 NonTypeTemplateParmDecl *D) {
952  // Substitute into the type of the non-type template parameter.
953  QualType T;
954  DeclaratorInfo *DI = D->getDeclaratorInfo();
955  if (DI) {
956    DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
957                           D->getDeclName());
958    if (DI) T = DI->getType();
959  } else {
960    T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
961                          D->getDeclName());
962    DI = 0;
963  }
964  if (T.isNull())
965    return 0;
966
967  // Check that this type is acceptable for a non-type template parameter.
968  bool Invalid = false;
969  T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation());
970  if (T.isNull()) {
971    T = SemaRef.Context.IntTy;
972    Invalid = true;
973  }
974
975  NonTypeTemplateParmDecl *Param
976    = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
977                                      D->getDepth() - 1, D->getPosition(),
978                                      D->getIdentifier(), T, DI);
979  if (Invalid)
980    Param->setInvalidDecl();
981
982  Param->setDefaultArgument(D->getDefaultArgument());
983
984  // Introduce this template parameter's instantiation into the instantiation
985  // scope.
986  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
987  return Param;
988}
989
990Decl *
991TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
992                                                  TemplateTemplateParmDecl *D) {
993  // Instantiate the template parameter list of the template template parameter.
994  TemplateParameterList *TempParams = D->getTemplateParameters();
995  TemplateParameterList *InstParams;
996  {
997    // Perform the actual substitution of template parameters within a new,
998    // local instantiation scope.
999    Sema::LocalInstantiationScope Scope(SemaRef);
1000    InstParams = SubstTemplateParams(TempParams);
1001    if (!InstParams)
1002      return NULL;
1003  }
1004
1005  // Build the template template parameter.
1006  TemplateTemplateParmDecl *Param
1007    = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1008                                       D->getDepth() - 1, D->getPosition(),
1009                                       D->getIdentifier(), InstParams);
1010  Param->setDefaultArgument(D->getDefaultArgument());
1011
1012  // Introduce this template parameter's instantiation into the instantiation
1013  // scope.
1014  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1015
1016  return Param;
1017}
1018
1019Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1020  // Using directives are never dependent, so they require no explicit
1021
1022  UsingDirectiveDecl *Inst
1023    = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1024                                 D->getNamespaceKeyLocation(),
1025                                 D->getQualifierRange(), D->getQualifier(),
1026                                 D->getIdentLocation(),
1027                                 D->getNominatedNamespace(),
1028                                 D->getCommonAncestor());
1029  Owner->addDecl(Inst);
1030  return Inst;
1031}
1032
1033Decl * TemplateDeclInstantiator
1034    ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
1035  NestedNameSpecifier *NNS =
1036    SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1037                                     D->getTargetNestedNameRange(),
1038                                     TemplateArgs);
1039  if (!NNS)
1040    return 0;
1041
1042  CXXScopeSpec SS;
1043  SS.setRange(D->getTargetNestedNameRange());
1044  SS.setScopeRep(NNS);
1045
1046  NamedDecl *UD =
1047    SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1048                                  D->getUsingLoc(), SS, D->getLocation(),
1049                                  D->getDeclName(), 0,
1050                                  /*instantiation*/ true,
1051                                  /*typename*/ true, D->getTypenameLoc());
1052  if (UD)
1053    SemaRef.Context.setInstantiatedFromUnresolvedUsingDecl(cast<UsingDecl>(UD),
1054                                                           D);
1055  return UD;
1056}
1057
1058Decl * TemplateDeclInstantiator
1059    ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1060  NestedNameSpecifier *NNS =
1061    SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1062                                     D->getTargetNestedNameRange(),
1063                                     TemplateArgs);
1064  if (!NNS)
1065    return 0;
1066
1067  CXXScopeSpec SS;
1068  SS.setRange(D->getTargetNestedNameRange());
1069  SS.setScopeRep(NNS);
1070
1071  NamedDecl *UD =
1072    SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1073                                  D->getUsingLoc(), SS, D->getLocation(),
1074                                  D->getDeclName(), 0,
1075                                  /*instantiation*/ true,
1076                                  /*typename*/ false, SourceLocation());
1077  if (UD)
1078    SemaRef.Context.setInstantiatedFromUnresolvedUsingDecl(cast<UsingDecl>(UD),
1079                                                           D);
1080  return UD;
1081}
1082
1083Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
1084                      const MultiLevelTemplateArgumentList &TemplateArgs) {
1085  TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
1086  return Instantiator.Visit(D);
1087}
1088
1089/// \brief Instantiates a nested template parameter list in the current
1090/// instantiation context.
1091///
1092/// \param L The parameter list to instantiate
1093///
1094/// \returns NULL if there was an error
1095TemplateParameterList *
1096TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
1097  // Get errors for all the parameters before bailing out.
1098  bool Invalid = false;
1099
1100  unsigned N = L->size();
1101  typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
1102  ParamVector Params;
1103  Params.reserve(N);
1104  for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1105       PI != PE; ++PI) {
1106    NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
1107    Params.push_back(D);
1108    Invalid = Invalid || !D || D->isInvalidDecl();
1109  }
1110
1111  // Clean up if we had an error.
1112  if (Invalid) {
1113    for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
1114         PI != PE; ++PI)
1115      if (*PI)
1116        (*PI)->Destroy(SemaRef.Context);
1117    return NULL;
1118  }
1119
1120  TemplateParameterList *InstL
1121    = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1122                                    L->getLAngleLoc(), &Params.front(), N,
1123                                    L->getRAngleLoc());
1124  return InstL;
1125}
1126
1127/// \brief Instantiate the declaration of a class template partial
1128/// specialization.
1129///
1130/// \param ClassTemplate the (instantiated) class template that is partially
1131// specialized by the instantiation of \p PartialSpec.
1132///
1133/// \param PartialSpec the (uninstantiated) class template partial
1134/// specialization that we are instantiating.
1135///
1136/// \returns true if there was an error, false otherwise.
1137bool
1138TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1139                                            ClassTemplateDecl *ClassTemplate,
1140                          ClassTemplatePartialSpecializationDecl *PartialSpec) {
1141  // Create a local instantiation scope for this class template partial
1142  // specialization, which will contain the instantiations of the template
1143  // parameters.
1144  Sema::LocalInstantiationScope Scope(SemaRef);
1145
1146  // Substitute into the template parameters of the class template partial
1147  // specialization.
1148  TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1149  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1150  if (!InstParams)
1151    return true;
1152
1153  // Substitute into the template arguments of the class template partial
1154  // specialization.
1155  const TemplateArgumentLoc *PartialSpecTemplateArgs
1156    = PartialSpec->getTemplateArgsAsWritten();
1157  unsigned N = PartialSpec->getNumTemplateArgsAsWritten();
1158
1159  TemplateArgumentListInfo InstTemplateArgs; // no angle locations
1160  for (unsigned I = 0; I != N; ++I) {
1161    TemplateArgumentLoc Loc;
1162    if (SemaRef.Subst(PartialSpecTemplateArgs[I], Loc, TemplateArgs))
1163      return true;
1164    InstTemplateArgs.addArgument(Loc);
1165  }
1166
1167
1168  // Check that the template argument list is well-formed for this
1169  // class template.
1170  TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
1171                                        InstTemplateArgs.size());
1172  if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1173                                        PartialSpec->getLocation(),
1174                                        InstTemplateArgs,
1175                                        false,
1176                                        Converted))
1177    return true;
1178
1179  // Figure out where to insert this class template partial specialization
1180  // in the member template's set of class template partial specializations.
1181  llvm::FoldingSetNodeID ID;
1182  ClassTemplatePartialSpecializationDecl::Profile(ID,
1183                                                  Converted.getFlatArguments(),
1184                                                  Converted.flatSize(),
1185                                                  SemaRef.Context);
1186  void *InsertPos = 0;
1187  ClassTemplateSpecializationDecl *PrevDecl
1188    = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
1189                                                                     InsertPos);
1190
1191  // Build the canonical type that describes the converted template
1192  // arguments of the class template partial specialization.
1193  QualType CanonType
1194    = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
1195                                                  Converted.getFlatArguments(),
1196                                                    Converted.flatSize());
1197
1198  // Build the fully-sugared type for this class template
1199  // specialization as the user wrote in the specialization
1200  // itself. This means that we'll pretty-print the type retrieved
1201  // from the specialization's declaration the way that the user
1202  // actually wrote the specialization, rather than formatting the
1203  // name based on the "canonical" representation used to store the
1204  // template arguments in the specialization.
1205  QualType WrittenTy
1206    = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
1207                                                    InstTemplateArgs,
1208                                                    CanonType);
1209
1210  if (PrevDecl) {
1211    // We've already seen a partial specialization with the same template
1212    // parameters and template arguments. This can happen, for example, when
1213    // substituting the outer template arguments ends up causing two
1214    // class template partial specializations of a member class template
1215    // to have identical forms, e.g.,
1216    //
1217    //   template<typename T, typename U>
1218    //   struct Outer {
1219    //     template<typename X, typename Y> struct Inner;
1220    //     template<typename Y> struct Inner<T, Y>;
1221    //     template<typename Y> struct Inner<U, Y>;
1222    //   };
1223    //
1224    //   Outer<int, int> outer; // error: the partial specializations of Inner
1225    //                          // have the same signature.
1226    SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
1227      << WrittenTy;
1228    SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1229      << SemaRef.Context.getTypeDeclType(PrevDecl);
1230    return true;
1231  }
1232
1233
1234  // Create the class template partial specialization declaration.
1235  ClassTemplatePartialSpecializationDecl *InstPartialSpec
1236    = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context, Owner,
1237                                                     PartialSpec->getLocation(),
1238                                                     InstParams,
1239                                                     ClassTemplate,
1240                                                     Converted,
1241                                                     InstTemplateArgs,
1242                                                     0);
1243  InstPartialSpec->setInstantiatedFromMember(PartialSpec);
1244  InstPartialSpec->setTypeAsWritten(WrittenTy);
1245
1246  // Add this partial specialization to the set of class template partial
1247  // specializations.
1248  ClassTemplate->getPartialSpecializations().InsertNode(InstPartialSpec,
1249                                                        InsertPos);
1250  return false;
1251}
1252
1253/// \brief Does substitution on the type of the given function, including
1254/// all of the function parameters.
1255///
1256/// \param D The function whose type will be the basis of the substitution
1257///
1258/// \param Params the instantiated parameter declarations
1259
1260/// \returns the instantiated function's type if successful, a NULL
1261/// type if there was an error.
1262QualType
1263TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
1264                              llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
1265  bool InvalidDecl = false;
1266
1267  // Substitute all of the function's formal parameter types.
1268  TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs);
1269  llvm::SmallVector<QualType, 4> ParamTys;
1270  for (FunctionDecl::param_iterator P = D->param_begin(),
1271                                 PEnd = D->param_end();
1272       P != PEnd; ++P) {
1273    if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
1274      if (PInst->getType()->isVoidType()) {
1275        SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
1276        PInst->setInvalidDecl();
1277      } else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
1278                                                PInst->getType(),
1279                                                diag::err_abstract_type_in_decl,
1280                                                Sema::AbstractParamType))
1281        PInst->setInvalidDecl();
1282
1283      Params.push_back(PInst);
1284      ParamTys.push_back(PInst->getType());
1285
1286      if (PInst->isInvalidDecl())
1287        InvalidDecl = true;
1288    } else
1289      InvalidDecl = true;
1290  }
1291
1292  // FIXME: Deallocate dead declarations.
1293  if (InvalidDecl)
1294    return QualType();
1295
1296  const FunctionProtoType *Proto = D->getType()->getAs<FunctionProtoType>();
1297  assert(Proto && "Missing prototype?");
1298  QualType ResultType
1299    = SemaRef.SubstType(Proto->getResultType(), TemplateArgs,
1300                        D->getLocation(), D->getDeclName());
1301  if (ResultType.isNull())
1302    return QualType();
1303
1304  return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(),
1305                                   Proto->isVariadic(), Proto->getTypeQuals(),
1306                                   D->getLocation(), D->getDeclName());
1307}
1308
1309/// \brief Initializes the common fields of an instantiation function
1310/// declaration (New) from the corresponding fields of its template (Tmpl).
1311///
1312/// \returns true if there was an error
1313bool
1314TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
1315                                                    FunctionDecl *Tmpl) {
1316  if (Tmpl->isDeleted())
1317    New->setDeleted();
1318
1319  // If we are performing substituting explicitly-specified template arguments
1320  // or deduced template arguments into a function template and we reach this
1321  // point, we are now past the point where SFINAE applies and have committed
1322  // to keeping the new function template specialization. We therefore
1323  // convert the active template instantiation for the function template
1324  // into a template instantiation for this specific function template
1325  // specialization, which is not a SFINAE context, so that we diagnose any
1326  // further errors in the declaration itself.
1327  typedef Sema::ActiveTemplateInstantiation ActiveInstType;
1328  ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
1329  if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
1330      ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
1331    if (FunctionTemplateDecl *FunTmpl
1332          = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
1333      assert(FunTmpl->getTemplatedDecl() == Tmpl &&
1334             "Deduction from the wrong function template?");
1335      (void) FunTmpl;
1336      ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
1337      ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
1338      --SemaRef.NonInstantiationEntries;
1339    }
1340  }
1341
1342  return false;
1343}
1344
1345/// \brief Initializes common fields of an instantiated method
1346/// declaration (New) from the corresponding fields of its template
1347/// (Tmpl).
1348///
1349/// \returns true if there was an error
1350bool
1351TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
1352                                                  CXXMethodDecl *Tmpl) {
1353  if (InitFunctionInstantiation(New, Tmpl))
1354    return true;
1355
1356  CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
1357  New->setAccess(Tmpl->getAccess());
1358  if (Tmpl->isVirtualAsWritten()) {
1359    New->setVirtualAsWritten(true);
1360    Record->setAggregate(false);
1361    Record->setPOD(false);
1362    Record->setEmpty(false);
1363    Record->setPolymorphic(true);
1364  }
1365
1366  // FIXME: attributes
1367  // FIXME: New needs a pointer to Tmpl
1368  return false;
1369}
1370
1371/// \brief Instantiate the definition of the given function from its
1372/// template.
1373///
1374/// \param PointOfInstantiation the point at which the instantiation was
1375/// required. Note that this is not precisely a "point of instantiation"
1376/// for the function, but it's close.
1377///
1378/// \param Function the already-instantiated declaration of a
1379/// function template specialization or member function of a class template
1380/// specialization.
1381///
1382/// \param Recursive if true, recursively instantiates any functions that
1383/// are required by this instantiation.
1384///
1385/// \param DefinitionRequired if true, then we are performing an explicit
1386/// instantiation where the body of the function is required. Complain if
1387/// there is no such body.
1388void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
1389                                         FunctionDecl *Function,
1390                                         bool Recursive,
1391                                         bool DefinitionRequired) {
1392  if (Function->isInvalidDecl())
1393    return;
1394
1395  assert(!Function->getBody() && "Already instantiated!");
1396
1397  // Never instantiate an explicit specialization.
1398  if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1399    return;
1400
1401  // Find the function body that we'll be substituting.
1402  const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
1403  Stmt *Pattern = 0;
1404  if (PatternDecl)
1405    Pattern = PatternDecl->getBody(PatternDecl);
1406
1407  if (!Pattern) {
1408    if (DefinitionRequired) {
1409      if (Function->getPrimaryTemplate())
1410        Diag(PointOfInstantiation,
1411             diag::err_explicit_instantiation_undefined_func_template)
1412          << Function->getPrimaryTemplate();
1413      else
1414        Diag(PointOfInstantiation,
1415             diag::err_explicit_instantiation_undefined_member)
1416          << 1 << Function->getDeclName() << Function->getDeclContext();
1417
1418      if (PatternDecl)
1419        Diag(PatternDecl->getLocation(),
1420             diag::note_explicit_instantiation_here);
1421    }
1422
1423    return;
1424  }
1425
1426  // C++0x [temp.explicit]p9:
1427  //   Except for inline functions, other explicit instantiation declarations
1428  //   have the effect of suppressing the implicit instantiation of the entity
1429  //   to which they refer.
1430  if (Function->getTemplateSpecializationKind()
1431        == TSK_ExplicitInstantiationDeclaration &&
1432      !PatternDecl->isInlined())
1433    return;
1434
1435  InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
1436  if (Inst)
1437    return;
1438
1439  // If we're performing recursive template instantiation, create our own
1440  // queue of pending implicit instantiations that we will instantiate later,
1441  // while we're still within our own instantiation context.
1442  std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1443  if (Recursive)
1444    PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1445
1446  ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
1447
1448  // Introduce a new scope where local variable instantiations will be
1449  // recorded.
1450  LocalInstantiationScope Scope(*this);
1451
1452  // Introduce the instantiated function parameters into the local
1453  // instantiation scope.
1454  for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
1455    Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
1456                            Function->getParamDecl(I));
1457
1458  // Enter the scope of this instantiation. We don't use
1459  // PushDeclContext because we don't have a scope.
1460  DeclContext *PreviousContext = CurContext;
1461  CurContext = Function;
1462
1463  MultiLevelTemplateArgumentList TemplateArgs =
1464    getTemplateInstantiationArgs(Function);
1465
1466  // If this is a constructor, instantiate the member initializers.
1467  if (const CXXConstructorDecl *Ctor =
1468        dyn_cast<CXXConstructorDecl>(PatternDecl)) {
1469    InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
1470                               TemplateArgs);
1471  }
1472
1473  // Instantiate the function body.
1474  OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs);
1475
1476  if (Body.isInvalid())
1477    Function->setInvalidDecl();
1478
1479  ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
1480                          /*IsInstantiation=*/true);
1481
1482  CurContext = PreviousContext;
1483
1484  DeclGroupRef DG(Function);
1485  Consumer.HandleTopLevelDecl(DG);
1486
1487  if (Recursive) {
1488    // Instantiate any pending implicit instantiations found during the
1489    // instantiation of this template.
1490    PerformPendingImplicitInstantiations();
1491
1492    // Restore the set of pending implicit instantiations.
1493    PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1494  }
1495}
1496
1497/// \brief Instantiate the definition of the given variable from its
1498/// template.
1499///
1500/// \param PointOfInstantiation the point at which the instantiation was
1501/// required. Note that this is not precisely a "point of instantiation"
1502/// for the function, but it's close.
1503///
1504/// \param Var the already-instantiated declaration of a static member
1505/// variable of a class template specialization.
1506///
1507/// \param Recursive if true, recursively instantiates any functions that
1508/// are required by this instantiation.
1509///
1510/// \param DefinitionRequired if true, then we are performing an explicit
1511/// instantiation where an out-of-line definition of the member variable
1512/// is required. Complain if there is no such definition.
1513void Sema::InstantiateStaticDataMemberDefinition(
1514                                          SourceLocation PointOfInstantiation,
1515                                                 VarDecl *Var,
1516                                                 bool Recursive,
1517                                                 bool DefinitionRequired) {
1518  if (Var->isInvalidDecl())
1519    return;
1520
1521  // Find the out-of-line definition of this static data member.
1522  VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
1523  assert(Def && "This data member was not instantiated from a template?");
1524  assert(Def->isStaticDataMember() && "Not a static data member?");
1525  Def = Def->getOutOfLineDefinition();
1526
1527  if (!Def) {
1528    // We did not find an out-of-line definition of this static data member,
1529    // so we won't perform any instantiation. Rather, we rely on the user to
1530    // instantiate this definition (or provide a specialization for it) in
1531    // another translation unit.
1532    if (DefinitionRequired) {
1533      Def = Var->getInstantiatedFromStaticDataMember();
1534      Diag(PointOfInstantiation,
1535           diag::err_explicit_instantiation_undefined_member)
1536        << 2 << Var->getDeclName() << Var->getDeclContext();
1537      Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
1538    }
1539
1540    return;
1541  }
1542
1543  // Never instantiate an explicit specialization.
1544  if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1545    return;
1546
1547  // C++0x [temp.explicit]p9:
1548  //   Except for inline functions, other explicit instantiation declarations
1549  //   have the effect of suppressing the implicit instantiation of the entity
1550  //   to which they refer.
1551  if (Var->getTemplateSpecializationKind()
1552        == TSK_ExplicitInstantiationDeclaration)
1553    return;
1554
1555  InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
1556  if (Inst)
1557    return;
1558
1559  // If we're performing recursive template instantiation, create our own
1560  // queue of pending implicit instantiations that we will instantiate later,
1561  // while we're still within our own instantiation context.
1562  std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1563  if (Recursive)
1564    PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1565
1566  // Enter the scope of this instantiation. We don't use
1567  // PushDeclContext because we don't have a scope.
1568  DeclContext *PreviousContext = CurContext;
1569  CurContext = Var->getDeclContext();
1570
1571  VarDecl *OldVar = Var;
1572  Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
1573                                          getTemplateInstantiationArgs(Var)));
1574  CurContext = PreviousContext;
1575
1576  if (Var) {
1577    Var->setPreviousDeclaration(OldVar);
1578    MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
1579    assert(MSInfo && "Missing member specialization information?");
1580    Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
1581                                       MSInfo->getPointOfInstantiation());
1582    DeclGroupRef DG(Var);
1583    Consumer.HandleTopLevelDecl(DG);
1584  }
1585
1586  if (Recursive) {
1587    // Instantiate any pending implicit instantiations found during the
1588    // instantiation of this template.
1589    PerformPendingImplicitInstantiations();
1590
1591    // Restore the set of pending implicit instantiations.
1592    PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1593  }
1594}
1595
1596void
1597Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
1598                                 const CXXConstructorDecl *Tmpl,
1599                           const MultiLevelTemplateArgumentList &TemplateArgs) {
1600
1601  llvm::SmallVector<MemInitTy*, 4> NewInits;
1602
1603  // Instantiate all the initializers.
1604  for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
1605                                            InitsEnd = Tmpl->init_end();
1606       Inits != InitsEnd; ++Inits) {
1607    CXXBaseOrMemberInitializer *Init = *Inits;
1608
1609    ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this);
1610
1611    // Instantiate all the arguments.
1612    for (ExprIterator Args = Init->arg_begin(), ArgsEnd = Init->arg_end();
1613         Args != ArgsEnd; ++Args) {
1614      OwningExprResult NewArg = SubstExpr(*Args, TemplateArgs);
1615
1616      if (NewArg.isInvalid())
1617        New->setInvalidDecl();
1618      else
1619        NewArgs.push_back(NewArg.takeAs<Expr>());
1620    }
1621
1622    MemInitResult NewInit;
1623
1624    if (Init->isBaseInitializer()) {
1625      QualType BaseType(Init->getBaseClass(), 0);
1626      BaseType = SubstType(BaseType, TemplateArgs, Init->getSourceLocation(),
1627                           New->getDeclName());
1628
1629      NewInit = BuildBaseInitializer(BaseType,
1630                                     (Expr **)NewArgs.data(),
1631                                     NewArgs.size(),
1632                                     Init->getSourceLocation(),
1633                                     Init->getRParenLoc(),
1634                                     New->getParent());
1635    } else if (Init->isMemberInitializer()) {
1636      FieldDecl *Member;
1637
1638      // Is this an anonymous union?
1639      if (FieldDecl *UnionInit = Init->getAnonUnionMember())
1640        Member = cast<FieldDecl>(FindInstantiatedDecl(UnionInit, TemplateArgs));
1641      else
1642        Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMember(),
1643                                                      TemplateArgs));
1644
1645      NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
1646                                       NewArgs.size(),
1647                                       Init->getSourceLocation(),
1648                                       Init->getRParenLoc());
1649    }
1650
1651    if (NewInit.isInvalid())
1652      New->setInvalidDecl();
1653    else {
1654      // FIXME: It would be nice if ASTOwningVector had a release function.
1655      NewArgs.take();
1656
1657      NewInits.push_back((MemInitTy *)NewInit.get());
1658    }
1659  }
1660
1661  // Assign all the initializers to the new constructor.
1662  ActOnMemInitializers(DeclPtrTy::make(New),
1663                       /*FIXME: ColonLoc */
1664                       SourceLocation(),
1665                       NewInits.data(), NewInits.size());
1666}
1667
1668// TODO: this could be templated if the various decl types used the
1669// same method name.
1670static bool isInstantiationOf(ClassTemplateDecl *Pattern,
1671                              ClassTemplateDecl *Instance) {
1672  Pattern = Pattern->getCanonicalDecl();
1673
1674  do {
1675    Instance = Instance->getCanonicalDecl();
1676    if (Pattern == Instance) return true;
1677    Instance = Instance->getInstantiatedFromMemberTemplate();
1678  } while (Instance);
1679
1680  return false;
1681}
1682
1683static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
1684                              FunctionTemplateDecl *Instance) {
1685  Pattern = Pattern->getCanonicalDecl();
1686
1687  do {
1688    Instance = Instance->getCanonicalDecl();
1689    if (Pattern == Instance) return true;
1690    Instance = Instance->getInstantiatedFromMemberTemplate();
1691  } while (Instance);
1692
1693  return false;
1694}
1695
1696static bool
1697isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
1698                  ClassTemplatePartialSpecializationDecl *Instance) {
1699  Pattern
1700    = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
1701  do {
1702    Instance = cast<ClassTemplatePartialSpecializationDecl>(
1703                                                Instance->getCanonicalDecl());
1704    if (Pattern == Instance)
1705      return true;
1706    Instance = Instance->getInstantiatedFromMember();
1707  } while (Instance);
1708
1709  return false;
1710}
1711
1712static bool isInstantiationOf(CXXRecordDecl *Pattern,
1713                              CXXRecordDecl *Instance) {
1714  Pattern = Pattern->getCanonicalDecl();
1715
1716  do {
1717    Instance = Instance->getCanonicalDecl();
1718    if (Pattern == Instance) return true;
1719    Instance = Instance->getInstantiatedFromMemberClass();
1720  } while (Instance);
1721
1722  return false;
1723}
1724
1725static bool isInstantiationOf(FunctionDecl *Pattern,
1726                              FunctionDecl *Instance) {
1727  Pattern = Pattern->getCanonicalDecl();
1728
1729  do {
1730    Instance = Instance->getCanonicalDecl();
1731    if (Pattern == Instance) return true;
1732    Instance = Instance->getInstantiatedFromMemberFunction();
1733  } while (Instance);
1734
1735  return false;
1736}
1737
1738static bool isInstantiationOf(EnumDecl *Pattern,
1739                              EnumDecl *Instance) {
1740  Pattern = Pattern->getCanonicalDecl();
1741
1742  do {
1743    Instance = Instance->getCanonicalDecl();
1744    if (Pattern == Instance) return true;
1745    Instance = Instance->getInstantiatedFromMemberEnum();
1746  } while (Instance);
1747
1748  return false;
1749}
1750
1751static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
1752                              UsingDecl *Instance,
1753                              ASTContext &C) {
1754  return C.getInstantiatedFromUnresolvedUsingDecl(Instance) == Pattern;
1755}
1756
1757static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
1758                              UsingDecl *Instance,
1759                              ASTContext &C) {
1760  return C.getInstantiatedFromUnresolvedUsingDecl(Instance) == Pattern;
1761}
1762
1763static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
1764                                              VarDecl *Instance) {
1765  assert(Instance->isStaticDataMember());
1766
1767  Pattern = Pattern->getCanonicalDecl();
1768
1769  do {
1770    Instance = Instance->getCanonicalDecl();
1771    if (Pattern == Instance) return true;
1772    Instance = Instance->getInstantiatedFromStaticDataMember();
1773  } while (Instance);
1774
1775  return false;
1776}
1777
1778static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
1779  if (D->getKind() != Other->getKind()) {
1780    if (UnresolvedUsingTypenameDecl *UUD
1781          = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
1782      if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
1783        return isInstantiationOf(UUD, UD, Ctx);
1784      }
1785    }
1786
1787    if (UnresolvedUsingValueDecl *UUD
1788          = dyn_cast<UnresolvedUsingValueDecl>(D)) {
1789      if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
1790        return isInstantiationOf(UUD, UD, Ctx);
1791      }
1792    }
1793
1794    return false;
1795  }
1796
1797  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
1798    return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
1799
1800  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
1801    return isInstantiationOf(cast<FunctionDecl>(D), Function);
1802
1803  if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
1804    return isInstantiationOf(cast<EnumDecl>(D), Enum);
1805
1806  if (VarDecl *Var = dyn_cast<VarDecl>(Other))
1807    if (Var->isStaticDataMember())
1808      return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
1809
1810  if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
1811    return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
1812
1813  if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
1814    return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
1815
1816  if (ClassTemplatePartialSpecializationDecl *PartialSpec
1817        = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
1818    return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
1819                             PartialSpec);
1820
1821  if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
1822    if (!Field->getDeclName()) {
1823      // This is an unnamed field.
1824      return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
1825        cast<FieldDecl>(D);
1826    }
1827  }
1828
1829  return D->getDeclName() && isa<NamedDecl>(Other) &&
1830    D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
1831}
1832
1833template<typename ForwardIterator>
1834static NamedDecl *findInstantiationOf(ASTContext &Ctx,
1835                                      NamedDecl *D,
1836                                      ForwardIterator first,
1837                                      ForwardIterator last) {
1838  for (; first != last; ++first)
1839    if (isInstantiationOf(Ctx, D, *first))
1840      return cast<NamedDecl>(*first);
1841
1842  return 0;
1843}
1844
1845/// \brief Finds the instantiation of the given declaration context
1846/// within the current instantiation.
1847///
1848/// \returns NULL if there was an error
1849DeclContext *Sema::FindInstantiatedContext(DeclContext* DC,
1850                          const MultiLevelTemplateArgumentList &TemplateArgs) {
1851  if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
1852    Decl* ID = FindInstantiatedDecl(D, TemplateArgs);
1853    return cast_or_null<DeclContext>(ID);
1854  } else return DC;
1855}
1856
1857/// \brief Find the instantiation of the given declaration within the
1858/// current instantiation.
1859///
1860/// This routine is intended to be used when \p D is a declaration
1861/// referenced from within a template, that needs to mapped into the
1862/// corresponding declaration within an instantiation. For example,
1863/// given:
1864///
1865/// \code
1866/// template<typename T>
1867/// struct X {
1868///   enum Kind {
1869///     KnownValue = sizeof(T)
1870///   };
1871///
1872///   bool getKind() const { return KnownValue; }
1873/// };
1874///
1875/// template struct X<int>;
1876/// \endcode
1877///
1878/// In the instantiation of X<int>::getKind(), we need to map the
1879/// EnumConstantDecl for KnownValue (which refers to
1880/// X<T>::<Kind>::KnownValue) to its instantiation
1881/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
1882/// this mapping from within the instantiation of X<int>.
1883NamedDecl *Sema::FindInstantiatedDecl(NamedDecl *D,
1884                          const MultiLevelTemplateArgumentList &TemplateArgs) {
1885  DeclContext *ParentDC = D->getDeclContext();
1886  if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
1887      isa<TemplateTypeParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
1888      ParentDC->isFunctionOrMethod()) {
1889    // D is a local of some kind. Look into the map of local
1890    // declarations to their instantiations.
1891    return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
1892  }
1893
1894  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
1895    if (!Record->isDependentContext())
1896      return D;
1897
1898    // If the RecordDecl is actually the injected-class-name or a "templated"
1899    // declaration for a class template or class template partial
1900    // specialization, substitute into the injected-class-name of the
1901    // class template or partial specialization to find the new DeclContext.
1902    QualType T;
1903    ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
1904
1905    if (ClassTemplate) {
1906      T = ClassTemplate->getInjectedClassNameType(Context);
1907    } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1908                 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
1909      T = Context.getTypeDeclType(Record);
1910      ClassTemplate = PartialSpec->getSpecializedTemplate();
1911    }
1912
1913    if (!T.isNull()) {
1914      // Substitute into the injected-class-name to get the type corresponding
1915      // to the instantiation we want. This substitution should never fail,
1916      // since we know we can instantiate the injected-class-name or we wouldn't
1917      // have gotten to the injected-class-name!
1918      // FIXME: Can we use the CurrentInstantiationScope to avoid this extra
1919      // instantiation in the common case?
1920      T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
1921      assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
1922
1923      if (!T->isDependentType()) {
1924        assert(T->isRecordType() && "Instantiation must produce a record type");
1925        return T->getAs<RecordType>()->getDecl();
1926      }
1927
1928      // We are performing "partial" template instantiation to create the
1929      // member declarations for the members of a class template
1930      // specialization. Therefore, D is actually referring to something in
1931      // the current instantiation. Look through the current context,
1932      // which contains actual instantiations, to find the instantiation of
1933      // the "current instantiation" that D refers to.
1934      for (DeclContext *DC = CurContext; !DC->isFileContext();
1935           DC = DC->getParent()) {
1936        if (ClassTemplateSpecializationDecl *Spec
1937              = dyn_cast<ClassTemplateSpecializationDecl>(DC))
1938          if (isInstantiationOf(ClassTemplate,
1939                                Spec->getSpecializedTemplate()))
1940            return Spec;
1941      }
1942
1943      assert(false &&
1944             "Unable to find declaration for the current instantiation");
1945      return Record;
1946    }
1947
1948    // Fall through to deal with other dependent record types (e.g.,
1949    // anonymous unions in class templates).
1950  }
1951
1952  if (!ParentDC->isDependentContext())
1953    return D;
1954
1955  ParentDC = FindInstantiatedContext(ParentDC, TemplateArgs);
1956  if (!ParentDC)
1957    return 0;
1958
1959  if (ParentDC != D->getDeclContext()) {
1960    // We performed some kind of instantiation in the parent context,
1961    // so now we need to look into the instantiated parent context to
1962    // find the instantiation of the declaration D.
1963    NamedDecl *Result = 0;
1964    if (D->getDeclName()) {
1965      DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
1966      Result = findInstantiationOf(Context, D, Found.first, Found.second);
1967    } else {
1968      // Since we don't have a name for the entity we're looking for,
1969      // our only option is to walk through all of the declarations to
1970      // find that name. This will occur in a few cases:
1971      //
1972      //   - anonymous struct/union within a template
1973      //   - unnamed class/struct/union/enum within a template
1974      //
1975      // FIXME: Find a better way to find these instantiations!
1976      Result = findInstantiationOf(Context, D,
1977                                   ParentDC->decls_begin(),
1978                                   ParentDC->decls_end());
1979    }
1980
1981    assert(Result && "Unable to find instantiation of declaration!");
1982    D = Result;
1983  }
1984
1985  return D;
1986}
1987
1988/// \brief Performs template instantiation for all implicit template
1989/// instantiations we have seen until this point.
1990void Sema::PerformPendingImplicitInstantiations() {
1991  while (!PendingImplicitInstantiations.empty()) {
1992    PendingImplicitInstantiation Inst = PendingImplicitInstantiations.front();
1993    PendingImplicitInstantiations.pop_front();
1994
1995    // Instantiate function definitions
1996    if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
1997      PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function),
1998                                            Function->getLocation(), *this,
1999                                            Context.getSourceManager(),
2000                                           "instantiating function definition");
2001
2002      if (!Function->getBody())
2003        InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
2004      continue;
2005    }
2006
2007    // Instantiate static data member definitions.
2008    VarDecl *Var = cast<VarDecl>(Inst.first);
2009    assert(Var->isStaticDataMember() && "Not a static data member?");
2010
2011    PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var),
2012                                          Var->getLocation(), *this,
2013                                          Context.getSourceManager(),
2014                                          "instantiating static data member "
2015                                          "definition");
2016
2017    InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
2018  }
2019}
2020