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