SemaTemplateInstantiateDecl.cpp revision c5c54f2c7bbc000dbcaee5e0acec2dbb0c0f0cf8
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 "clang/AST/ASTConsumer.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/DeclTemplate.h"
16#include "clang/AST/DeclVisitor.h"
17#include "clang/AST/Expr.h"
18#include "clang/Lex/Preprocessor.h"
19#include "llvm/Support/Compiler.h"
20
21using namespace clang;
22
23namespace {
24  class VISIBILITY_HIDDEN TemplateDeclInstantiator
25    : public DeclVisitor<TemplateDeclInstantiator, Decl *> {
26    Sema &SemaRef;
27    DeclContext *Owner;
28    const TemplateArgumentList &TemplateArgs;
29
30  public:
31    typedef Sema::OwningExprResult OwningExprResult;
32
33    TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner,
34                             const TemplateArgumentList &TemplateArgs)
35      : SemaRef(SemaRef), Owner(Owner), TemplateArgs(TemplateArgs) { }
36
37    // FIXME: Once we get closer to completion, replace these manually-written
38    // declarations with automatically-generated ones from
39    // clang/AST/DeclNodes.def.
40    Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
41    Decl *VisitNamespaceDecl(NamespaceDecl *D);
42    Decl *VisitTypedefDecl(TypedefDecl *D);
43    Decl *VisitVarDecl(VarDecl *D);
44    Decl *VisitFieldDecl(FieldDecl *D);
45    Decl *VisitStaticAssertDecl(StaticAssertDecl *D);
46    Decl *VisitEnumDecl(EnumDecl *D);
47    Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
48    Decl *VisitFriendClassDecl(FriendClassDecl *D);
49    Decl *VisitFunctionDecl(FunctionDecl *D);
50    Decl *VisitCXXRecordDecl(CXXRecordDecl *D);
51    Decl *VisitCXXMethodDecl(CXXMethodDecl *D,
52                             TemplateParameterList *TemplateParams = 0);
53    Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
54    Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
55    Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
56    ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D);
57    Decl *VisitOriginalParmVarDecl(OriginalParmVarDecl *D);
58    Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
59    Decl *VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
60    Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
61
62    // Base case. FIXME: Remove once we can instantiate everything.
63    Decl *VisitDecl(Decl *) {
64      assert(false && "Template instantiation of unknown declaration kind!");
65      return 0;
66    }
67
68    const LangOptions &getLangOptions() {
69      return SemaRef.getLangOptions();
70    }
71
72    // Helper functions for instantiating methods.
73    QualType SubstFunctionType(FunctionDecl *D,
74                             llvm::SmallVectorImpl<ParmVarDecl *> &Params);
75    bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl);
76    bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
77
78    TemplateParameterList *
79      SubstTemplateParams(TemplateParameterList *List);
80  };
81}
82
83Decl *
84TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
85  assert(false && "Translation units cannot be instantiated");
86  return D;
87}
88
89Decl *
90TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
91  assert(false && "Namespaces cannot be instantiated");
92  return D;
93}
94
95Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
96  bool Invalid = false;
97  QualType T = D->getUnderlyingType();
98  if (T->isDependentType()) {
99    T = SemaRef.SubstType(T, TemplateArgs,
100                          D->getLocation(), D->getDeclName());
101    if (T.isNull()) {
102      Invalid = true;
103      T = SemaRef.Context.IntTy;
104    }
105  }
106
107  // Create the new typedef
108  TypedefDecl *Typedef
109    = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
110                          D->getIdentifier(), T);
111  if (Invalid)
112    Typedef->setInvalidDecl();
113
114  Owner->addDecl(Typedef);
115
116  return Typedef;
117}
118
119Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
120  // Do substitution on the type of the declaration
121  QualType T = SemaRef.SubstType(D->getType(), TemplateArgs,
122                                 D->getTypeSpecStartLoc(),
123                                 D->getDeclName());
124  if (T.isNull())
125    return 0;
126
127  // Build the instantiated declaration
128  VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
129                                 D->getLocation(), D->getIdentifier(),
130                                 T, D->getDeclaratorInfo(),
131                                 D->getStorageClass());
132  Var->setThreadSpecified(D->isThreadSpecified());
133  Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
134  Var->setDeclaredInCondition(D->isDeclaredInCondition());
135
136  // If we are instantiating a static data member defined
137  // out-of-line, the instantiation will have the same lexical
138  // context (which will be a namespace scope) as the template.
139  if (D->isOutOfLine())
140    Var->setLexicalDeclContext(D->getLexicalDeclContext());
141
142  // FIXME: In theory, we could have a previous declaration for variables that
143  // are not static data members.
144  bool Redeclaration = false;
145  SemaRef.CheckVariableDeclaration(Var, 0, Redeclaration);
146
147  if (D->isOutOfLine()) {
148    D->getLexicalDeclContext()->addDecl(Var);
149    Owner->makeDeclVisibleInContext(Var);
150  } else {
151    Owner->addDecl(Var);
152  }
153
154  if (D->getInit()) {
155    OwningExprResult Init
156      = SemaRef.SubstExpr(D->getInit(), TemplateArgs);
157    if (Init.isInvalid())
158      Var->setInvalidDecl();
159    else if (ParenListExpr *PLE = dyn_cast<ParenListExpr>((Expr *)Init.get())) {
160      // FIXME: We're faking all of the comma locations, which is suboptimal.
161      // Do we even need these comma locations?
162      llvm::SmallVector<SourceLocation, 4> FakeCommaLocs;
163      if (PLE->getNumExprs() > 0) {
164        FakeCommaLocs.reserve(PLE->getNumExprs() - 1);
165        for (unsigned I = 0, N = PLE->getNumExprs() - 1; I != N; ++I) {
166          Expr *E = PLE->getExpr(I)->Retain();
167          FakeCommaLocs.push_back(
168                                SemaRef.PP.getLocForEndOfToken(E->getLocEnd()));
169        }
170        PLE->getExpr(PLE->getNumExprs() - 1)->Retain();
171      }
172
173      // Add the direct initializer to the declaration.
174      SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var),
175                                            PLE->getLParenLoc(),
176                                            Sema::MultiExprArg(SemaRef,
177                                                       (void**)PLE->getExprs(),
178                                                           PLE->getNumExprs()),
179                                            FakeCommaLocs.data(),
180                                            PLE->getRParenLoc());
181
182      // When Init is destroyed, it will destroy the instantiated ParenListExpr;
183      // we've explicitly retained all of its subexpressions already.
184    } else
185      SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var), move(Init),
186                                   D->hasCXXDirectInitializer());
187  } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
188    SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
189
190  // Link instantiations of static data members back to the template from
191  // which they were instantiated.
192  if (Var->isStaticDataMember())
193    SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D);
194
195  return Var;
196}
197
198Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
199  bool Invalid = false;
200  QualType T = D->getType();
201  if (T->isDependentType())  {
202    T = SemaRef.SubstType(T, TemplateArgs,
203                          D->getLocation(), D->getDeclName());
204    if (!T.isNull() && T->isFunctionType()) {
205      // C++ [temp.arg.type]p3:
206      //   If a declaration acquires a function type through a type
207      //   dependent on a template-parameter and this causes a
208      //   declaration that does not use the syntactic form of a
209      //   function declarator to have function type, the program is
210      //   ill-formed.
211      SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
212        << T;
213      T = QualType();
214      Invalid = true;
215    }
216  }
217
218  Expr *BitWidth = D->getBitWidth();
219  if (Invalid)
220    BitWidth = 0;
221  else if (BitWidth) {
222    // The bit-width expression is not potentially evaluated.
223    EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
224
225    OwningExprResult InstantiatedBitWidth
226      = SemaRef.SubstExpr(BitWidth, TemplateArgs);
227    if (InstantiatedBitWidth.isInvalid()) {
228      Invalid = true;
229      BitWidth = 0;
230    } else
231      BitWidth = InstantiatedBitWidth.takeAs<Expr>();
232  }
233
234  FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(), T,
235                                            D->getDeclaratorInfo(),
236                                            cast<RecordDecl>(Owner),
237                                            D->getLocation(),
238                                            D->isMutable(),
239                                            BitWidth,
240                                            D->getTypeSpecStartLoc(),
241                                            D->getAccess(),
242                                            0);
243  if (Field) {
244    if (Invalid)
245      Field->setInvalidDecl();
246
247    Owner->addDecl(Field);
248  }
249
250  return Field;
251}
252
253Decl *TemplateDeclInstantiator::VisitFriendClassDecl(FriendClassDecl *D) {
254  QualType T = D->getFriendType();
255  if (T->isDependentType())  {
256    T = SemaRef.SubstType(T, TemplateArgs, D->getLocation(),
257                          DeclarationName());
258    assert(T.isNull() || getLangOptions().CPlusPlus0x || T->isRecordType());
259  }
260
261  // FIXME: the target context might be dependent.
262  DeclContext *DC = D->getDeclContext();
263  assert(DC->isFileContext());
264
265  FriendClassDecl *NewD =
266    FriendClassDecl::Create(SemaRef.Context, DC, D->getLocation(), T,
267                            D->getFriendLoc());
268  NewD->setLexicalDeclContext(Owner);
269
270  Owner->addDecl(NewD);
271  return NewD;
272}
273
274Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
275  Expr *AssertExpr = D->getAssertExpr();
276
277  // The expression in a static assertion is not potentially evaluated.
278  EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
279
280  OwningExprResult InstantiatedAssertExpr
281    = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
282  if (InstantiatedAssertExpr.isInvalid())
283    return 0;
284
285  OwningExprResult Message(SemaRef, D->getMessage());
286  D->getMessage()->Retain();
287  Decl *StaticAssert
288    = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
289                                           move(InstantiatedAssertExpr),
290                                           move(Message)).getAs<Decl>();
291  return StaticAssert;
292}
293
294Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
295  EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
296                                    D->getLocation(), D->getIdentifier(),
297                                    D->getTagKeywordLoc(),
298                                    /*PrevDecl=*/0);
299  Enum->setInstantiationOfMemberEnum(D);
300  Enum->setAccess(D->getAccess());
301  Owner->addDecl(Enum);
302  Enum->startDefinition();
303
304  llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
305
306  EnumConstantDecl *LastEnumConst = 0;
307  for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
308         ECEnd = D->enumerator_end();
309       EC != ECEnd; ++EC) {
310    // The specified value for the enumerator.
311    OwningExprResult Value = SemaRef.Owned((Expr *)0);
312    if (Expr *UninstValue = EC->getInitExpr()) {
313      // The enumerator's value expression is not potentially evaluated.
314      EnterExpressionEvaluationContext Unevaluated(SemaRef,
315                                                   Action::Unevaluated);
316
317      Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
318    }
319
320    // Drop the initial value and continue.
321    bool isInvalid = false;
322    if (Value.isInvalid()) {
323      Value = SemaRef.Owned((Expr *)0);
324      isInvalid = true;
325    }
326
327    EnumConstantDecl *EnumConst
328      = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
329                                  EC->getLocation(), EC->getIdentifier(),
330                                  move(Value));
331
332    if (isInvalid) {
333      if (EnumConst)
334        EnumConst->setInvalidDecl();
335      Enum->setInvalidDecl();
336    }
337
338    if (EnumConst) {
339      Enum->addDecl(EnumConst);
340      Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
341      LastEnumConst = EnumConst;
342    }
343  }
344
345  // FIXME: Fixup LBraceLoc and RBraceLoc
346  // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
347  SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
348                        Sema::DeclPtrTy::make(Enum),
349                        &Enumerators[0], Enumerators.size(),
350                        0, 0);
351
352  return Enum;
353}
354
355Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
356  assert(false && "EnumConstantDecls can only occur within EnumDecls.");
357  return 0;
358}
359
360Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
361  TemplateParameterList *TempParams = D->getTemplateParameters();
362  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
363  if (!InstParams)
364    return NULL;
365
366  CXXRecordDecl *Pattern = D->getTemplatedDecl();
367  CXXRecordDecl *RecordInst
368    = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), Owner,
369                            Pattern->getLocation(), Pattern->getIdentifier(),
370                            Pattern->getTagKeywordLoc(), /*PrevDecl=*/ NULL);
371
372  ClassTemplateDecl *Inst
373    = ClassTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
374                                D->getIdentifier(), InstParams, RecordInst, 0);
375  RecordInst->setDescribedClassTemplate(Inst);
376  Inst->setAccess(D->getAccess());
377  Inst->setInstantiatedFromMemberTemplate(D);
378
379  Owner->addDecl(Inst);
380  return Inst;
381}
382
383Decl *
384TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
385  TemplateParameterList *TempParams = D->getTemplateParameters();
386  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
387  if (!InstParams)
388    return NULL;
389
390  // FIXME: Handle instantiation of nested function templates that aren't
391  // member function templates. This could happen inside a FriendDecl.
392  assert(isa<CXXMethodDecl>(D->getTemplatedDecl()));
393  CXXMethodDecl *InstMethod
394    = cast_or_null<CXXMethodDecl>(
395                 VisitCXXMethodDecl(cast<CXXMethodDecl>(D->getTemplatedDecl()),
396                                    InstParams));
397  if (!InstMethod)
398    return 0;
399
400  // Link the instantiated function template declaration to the function
401  // template from which it was instantiated.
402  FunctionTemplateDecl *InstTemplate = InstMethod->getDescribedFunctionTemplate();
403  assert(InstTemplate && "VisitCXXMethodDecl didn't create a template!");
404  InstTemplate->setInstantiatedFromMemberTemplate(D);
405  Owner->addDecl(InstTemplate);
406  return InstTemplate;
407}
408
409Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
410  CXXRecordDecl *PrevDecl = 0;
411  if (D->isInjectedClassName())
412    PrevDecl = cast<CXXRecordDecl>(Owner);
413
414  CXXRecordDecl *Record
415    = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
416                            D->getLocation(), D->getIdentifier(),
417                            D->getTagKeywordLoc(), PrevDecl);
418  Record->setImplicit(D->isImplicit());
419  Record->setAccess(D->getAccess());
420  if (!D->isInjectedClassName())
421    Record->setInstantiationOfMemberClass(D);
422
423  Owner->addDecl(Record);
424  return Record;
425}
426
427Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
428  // Check whether there is already a function template specialization for
429  // this declaration.
430  FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
431  void *InsertPos = 0;
432  if (FunctionTemplate) {
433    llvm::FoldingSetNodeID ID;
434    FunctionTemplateSpecializationInfo::Profile(ID,
435                                          TemplateArgs.getFlatArgumentList(),
436                                                TemplateArgs.flat_size(),
437                                                SemaRef.Context);
438
439    FunctionTemplateSpecializationInfo *Info
440      = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
441                                                                   InsertPos);
442
443    // If we already have a function template specialization, return it.
444    if (Info)
445      return Info->Function;
446  }
447
448  Sema::LocalInstantiationScope Scope(SemaRef);
449
450  llvm::SmallVector<ParmVarDecl *, 4> Params;
451  QualType T = SubstFunctionType(D, Params);
452  if (T.isNull())
453    return 0;
454
455  // Build the instantiated method declaration.
456  FunctionDecl *Function;
457  if (FriendFunctionDecl* FFD = dyn_cast<FriendFunctionDecl>(D)) {
458    // The new decl's semantic context.  FIXME:  this might need
459    // to be instantiated.
460    DeclContext *DC = D->getDeclContext();
461
462    // This assert is bogus and exists only to catch cases we don't
463    // handle yet.
464    assert(!DC->isDependentContext());
465
466    Function =
467      FriendFunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
468                                 D->getDeclName(), T, D->getDeclaratorInfo(),
469                                 D->isInline(), FFD->getFriendLoc());
470    Function->setLexicalDeclContext(Owner);
471  } else {
472    Function =
473      FunctionDecl::Create(SemaRef.Context, Owner, D->getLocation(),
474                           D->getDeclName(), T, D->getDeclaratorInfo(),
475                           D->getStorageClass(),
476                           D->isInline(), D->hasWrittenPrototype());
477  }
478
479  // Attach the parameters
480  for (unsigned P = 0; P < Params.size(); ++P)
481    Params[P]->setOwningFunction(Function);
482  Function->setParams(SemaRef.Context, Params.data(), Params.size());
483
484  if (InitFunctionInstantiation(Function, D))
485    Function->setInvalidDecl();
486
487  bool Redeclaration = false;
488  bool OverloadableAttrRequired = false;
489  NamedDecl *PrevDecl = 0;
490  SemaRef.CheckFunctionDeclaration(Function, PrevDecl, Redeclaration,
491                                   /*FIXME:*/OverloadableAttrRequired);
492
493  if (FunctionTemplate) {
494    // Record this function template specialization.
495    Function->setFunctionTemplateSpecialization(SemaRef.Context,
496                                                FunctionTemplate,
497                                                &TemplateArgs,
498                                                InsertPos);
499  }
500
501  // If this was a friend function decl, it's a member which
502  // needs to be added.
503  if (isa<FriendFunctionDecl>(Function)) {
504    // If the new context is still dependent, this declaration
505    // needs to remain hidden.
506    if (Owner->isDependentContext())
507      Owner->addHiddenDecl(Function);
508    else
509      Owner->addDecl(Function);
510  }
511
512  return Function;
513}
514
515Decl *
516TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
517                                      TemplateParameterList *TemplateParams) {
518  FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
519  void *InsertPos = 0;
520  if (FunctionTemplate && !TemplateParams) {
521    // We are creating a function template specialization from a function
522    // template. Check whether there is already a function template
523    // specialization for this particular set of template arguments.
524    llvm::FoldingSetNodeID ID;
525    FunctionTemplateSpecializationInfo::Profile(ID,
526                                          TemplateArgs.getFlatArgumentList(),
527                                                TemplateArgs.flat_size(),
528                                                SemaRef.Context);
529
530    FunctionTemplateSpecializationInfo *Info
531      = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
532                                                                   InsertPos);
533
534    // If we already have a function template specialization, return it.
535    if (Info)
536      return Info->Function;
537  }
538
539  Sema::LocalInstantiationScope Scope(SemaRef);
540
541  llvm::SmallVector<ParmVarDecl *, 4> Params;
542  QualType T = SubstFunctionType(D, Params);
543  if (T.isNull())
544    return 0;
545
546  // Build the instantiated method declaration.
547  CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
548  CXXMethodDecl *Method = 0;
549
550  DeclarationName Name = D->getDeclName();
551  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
552    QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
553    Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
554                                    SemaRef.Context.getCanonicalType(ClassTy));
555    Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
556                                        Constructor->getLocation(),
557                                        Name, T,
558                                        Constructor->getDeclaratorInfo(),
559                                        Constructor->isExplicit(),
560                                        Constructor->isInline(), false);
561  } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
562    QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
563    Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
564                                   SemaRef.Context.getCanonicalType(ClassTy));
565    Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
566                                       Destructor->getLocation(), Name,
567                                       T, Destructor->isInline(), false);
568  } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
569    CanQualType ConvTy
570      = SemaRef.Context.getCanonicalType(
571                                      T->getAsFunctionType()->getResultType());
572    Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
573                                                                      ConvTy);
574    Method = CXXConversionDecl::Create(SemaRef.Context, Record,
575                                       Conversion->getLocation(), Name,
576                                       T, Conversion->getDeclaratorInfo(),
577                                       Conversion->isInline(),
578                                       Conversion->isExplicit());
579  } else {
580    Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
581                                   D->getDeclName(), T, D->getDeclaratorInfo(),
582                                   D->isStatic(), D->isInline());
583  }
584
585  if (TemplateParams) {
586    // Our resulting instantiation is actually a function template, since we
587    // are substituting only the outer template parameters. For example, given
588    //
589    //   template<typename T>
590    //   struct X {
591    //     template<typename U> void f(T, U);
592    //   };
593    //
594    //   X<int> x;
595    //
596    // We are instantiating the member template "f" within X<int>, which means
597    // substituting int for T, but leaving "f" as a member function template.
598    // Build the function template itself.
599    FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
600                                                    Method->getLocation(),
601                                                    Method->getDeclName(),
602                                                    TemplateParams, Method);
603    if (D->isOutOfLine())
604      FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
605    Method->setDescribedFunctionTemplate(FunctionTemplate);
606  } else if (!FunctionTemplate)
607    Method->setInstantiationOfMemberFunction(D);
608
609  // If we are instantiating a member function defined
610  // out-of-line, the instantiation will have the same lexical
611  // context (which will be a namespace scope) as the template.
612  if (D->isOutOfLine())
613    Method->setLexicalDeclContext(D->getLexicalDeclContext());
614
615  // Attach the parameters
616  for (unsigned P = 0; P < Params.size(); ++P)
617    Params[P]->setOwningFunction(Method);
618  Method->setParams(SemaRef.Context, Params.data(), Params.size());
619
620  if (InitMethodInstantiation(Method, D))
621    Method->setInvalidDecl();
622
623  NamedDecl *PrevDecl = 0;
624
625  if (!FunctionTemplate || TemplateParams) {
626    PrevDecl = SemaRef.LookupQualifiedName(Owner, Name,
627                                           Sema::LookupOrdinaryName, true);
628
629    // In C++, the previous declaration we find might be a tag type
630    // (class or enum). In this case, the new declaration will hide the
631    // tag type. Note that this does does not apply if we're declaring a
632    // typedef (C++ [dcl.typedef]p4).
633    if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
634      PrevDecl = 0;
635  }
636
637  if (FunctionTemplate && !TemplateParams)
638    // Record this function template specialization.
639    Method->setFunctionTemplateSpecialization(SemaRef.Context,
640                                              FunctionTemplate,
641                                              &TemplateArgs,
642                                              InsertPos);
643
644  bool Redeclaration = false;
645  bool OverloadableAttrRequired = false;
646  SemaRef.CheckFunctionDeclaration(Method, PrevDecl, Redeclaration,
647                                   /*FIXME:*/OverloadableAttrRequired);
648
649  if (!FunctionTemplate && (!Method->isInvalidDecl() || !PrevDecl))
650    Owner->addDecl(Method);
651
652  return Method;
653}
654
655Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
656  return VisitCXXMethodDecl(D);
657}
658
659Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
660  return VisitCXXMethodDecl(D);
661}
662
663Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
664  return VisitCXXMethodDecl(D);
665}
666
667ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
668  QualType OrigT = SemaRef.SubstType(D->getOriginalType(), TemplateArgs,
669                                           D->getLocation(), D->getDeclName());
670  if (OrigT.isNull())
671    return 0;
672
673  QualType T = SemaRef.adjustParameterType(OrigT);
674
675  // Allocate the parameter
676  ParmVarDecl *Param = 0;
677  if (T == OrigT)
678    Param = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(),
679                                D->getIdentifier(), T, D->getDeclaratorInfo(),
680                                D->getStorageClass(), 0);
681  else
682    Param = OriginalParmVarDecl::Create(SemaRef.Context, Owner,
683                                        D->getLocation(), D->getIdentifier(),
684                                        T, D->getDeclaratorInfo(), OrigT,
685                                        D->getStorageClass(), 0);
686
687  // Mark the default argument as being uninstantiated.
688  if (Expr *Arg = D->getDefaultArg())
689    Param->setUninstantiatedDefaultArg(Arg);
690
691  // Note: we don't try to instantiate function parameters until after
692  // we've instantiated the function's type. Therefore, we don't have
693  // to check for 'void' parameter types here.
694  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
695  return Param;
696}
697
698Decl *
699TemplateDeclInstantiator::VisitOriginalParmVarDecl(OriginalParmVarDecl *D) {
700  // Since parameter types can decay either before or after
701  // instantiation, we simply treat OriginalParmVarDecls as
702  // ParmVarDecls the same way, and create one or the other depending
703  // on what happens after template instantiation.
704  return VisitParmVarDecl(D);
705}
706
707Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
708                                                    TemplateTypeParmDecl *D) {
709  // TODO: don't always clone when decls are refcounted.
710  const Type* T = D->getTypeForDecl();
711  assert(T->isTemplateTypeParmType());
712  const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
713
714  TemplateTypeParmDecl *Inst =
715    TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
716                                 TTPT->getDepth(), TTPT->getIndex(),
717                                 TTPT->getName(),
718                                 D->wasDeclaredWithTypename(),
719                                 D->isParameterPack());
720
721  if (D->hasDefaultArgument()) {
722    QualType DefaultPattern = D->getDefaultArgument();
723    QualType DefaultInst
724      = SemaRef.SubstType(DefaultPattern, TemplateArgs,
725                          D->getDefaultArgumentLoc(),
726                          D->getDeclName());
727
728    Inst->setDefaultArgument(DefaultInst,
729                             D->getDefaultArgumentLoc(),
730                             D->defaultArgumentWasInherited() /* preserve? */);
731  }
732
733  return Inst;
734}
735
736Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
737                      const TemplateArgumentList &TemplateArgs) {
738  TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
739  return Instantiator.Visit(D);
740}
741
742/// \brief Instantiates a nested template parameter list in the current
743/// instantiation context.
744///
745/// \param L The parameter list to instantiate
746///
747/// \returns NULL if there was an error
748TemplateParameterList *
749TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
750  // Get errors for all the parameters before bailing out.
751  bool Invalid = false;
752
753  unsigned N = L->size();
754  typedef llvm::SmallVector<Decl*,8> ParamVector;
755  ParamVector Params;
756  Params.reserve(N);
757  for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
758       PI != PE; ++PI) {
759    Decl *D = Visit(*PI);
760    Params.push_back(D);
761    Invalid = Invalid || !D;
762  }
763
764  // Clean up if we had an error.
765  if (Invalid) {
766    for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
767         PI != PE; ++PI)
768      if (*PI)
769        (*PI)->Destroy(SemaRef.Context);
770    return NULL;
771  }
772
773  TemplateParameterList *InstL
774    = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
775                                    L->getLAngleLoc(), &Params.front(), N,
776                                    L->getRAngleLoc());
777  return InstL;
778}
779
780/// \brief Does substitution on the type of the given function, including
781/// all of the function parameters.
782///
783/// \param D The function whose type will be the basis of the substitution
784///
785/// \param Params the instantiated parameter declarations
786
787/// \returns the instantiated function's type if successful, a NULL
788/// type if there was an error.
789QualType
790TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
791                              llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
792  bool InvalidDecl = false;
793
794  // Substitute all of the function's formal parameter types.
795  TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs);
796  llvm::SmallVector<QualType, 4> ParamTys;
797  for (FunctionDecl::param_iterator P = D->param_begin(),
798                                 PEnd = D->param_end();
799       P != PEnd; ++P) {
800    if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
801      if (PInst->getType()->isVoidType()) {
802        SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
803        PInst->setInvalidDecl();
804      } else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
805                                                PInst->getType(),
806                                                diag::err_abstract_type_in_decl,
807                                                Sema::AbstractParamType))
808        PInst->setInvalidDecl();
809
810      Params.push_back(PInst);
811      ParamTys.push_back(PInst->getType());
812
813      if (PInst->isInvalidDecl())
814        InvalidDecl = true;
815    } else
816      InvalidDecl = true;
817  }
818
819  // FIXME: Deallocate dead declarations.
820  if (InvalidDecl)
821    return QualType();
822
823  const FunctionProtoType *Proto = D->getType()->getAsFunctionProtoType();
824  assert(Proto && "Missing prototype?");
825  QualType ResultType
826    = SemaRef.SubstType(Proto->getResultType(), TemplateArgs,
827                        D->getLocation(), D->getDeclName());
828  if (ResultType.isNull())
829    return QualType();
830
831  return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(),
832                                   Proto->isVariadic(), Proto->getTypeQuals(),
833                                   D->getLocation(), D->getDeclName());
834}
835
836/// \brief Initializes the common fields of an instantiation function
837/// declaration (New) from the corresponding fields of its template (Tmpl).
838///
839/// \returns true if there was an error
840bool
841TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
842                                                    FunctionDecl *Tmpl) {
843  if (Tmpl->isDeleted())
844    New->setDeleted();
845
846  // If we are performing substituting explicitly-specified template arguments
847  // or deduced template arguments into a function template and we reach this
848  // point, we are now past the point where SFINAE applies and have committed
849  // to keeping the new function template specialization. We therefore
850  // convert the active template instantiation for the function template
851  // into a template instantiation for this specific function template
852  // specialization, which is not a SFINAE context, so that we diagnose any
853  // further errors in the declaration itself.
854  typedef Sema::ActiveTemplateInstantiation ActiveInstType;
855  ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
856  if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
857      ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
858    if (FunctionTemplateDecl *FunTmpl
859          = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
860      assert(FunTmpl->getTemplatedDecl() == Tmpl &&
861             "Deduction from the wrong function template?");
862      (void) FunTmpl;
863      ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
864      ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
865    }
866  }
867
868  return false;
869}
870
871/// \brief Initializes common fields of an instantiated method
872/// declaration (New) from the corresponding fields of its template
873/// (Tmpl).
874///
875/// \returns true if there was an error
876bool
877TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
878                                                  CXXMethodDecl *Tmpl) {
879  if (InitFunctionInstantiation(New, Tmpl))
880    return true;
881
882  CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
883  New->setAccess(Tmpl->getAccess());
884  if (Tmpl->isVirtualAsWritten()) {
885    New->setVirtualAsWritten(true);
886    Record->setAggregate(false);
887    Record->setPOD(false);
888    Record->setEmpty(false);
889    Record->setPolymorphic(true);
890  }
891  if (Tmpl->isPure()) {
892    New->setPure();
893    Record->setAbstract(true);
894  }
895
896  // FIXME: attributes
897  // FIXME: New needs a pointer to Tmpl
898  return false;
899}
900
901/// \brief Instantiate the definition of the given function from its
902/// template.
903///
904/// \param PointOfInstantiation the point at which the instantiation was
905/// required. Note that this is not precisely a "point of instantiation"
906/// for the function, but it's close.
907///
908/// \param Function the already-instantiated declaration of a
909/// function template specialization or member function of a class template
910/// specialization.
911///
912/// \param Recursive if true, recursively instantiates any functions that
913/// are required by this instantiation.
914void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
915                                         FunctionDecl *Function,
916                                         bool Recursive) {
917  if (Function->isInvalidDecl())
918    return;
919
920  assert(!Function->getBody() && "Already instantiated!");
921
922  // Find the function body that we'll be substituting.
923  const FunctionDecl *PatternDecl = 0;
924  if (FunctionTemplateDecl *Primary = Function->getPrimaryTemplate())
925    PatternDecl = Primary->getTemplatedDecl();
926  else
927    PatternDecl = Function->getInstantiatedFromMemberFunction();
928  Stmt *Pattern = 0;
929  if (PatternDecl)
930    Pattern = PatternDecl->getBody(PatternDecl);
931
932  if (!Pattern)
933    return;
934
935  InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
936  if (Inst)
937    return;
938
939  // If we're performing recursive template instantiation, create our own
940  // queue of pending implicit instantiations that we will instantiate later,
941  // while we're still within our own instantiation context.
942  std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
943  if (Recursive)
944    PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
945
946  ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
947
948  // Introduce a new scope where local variable instantiations will be
949  // recorded.
950  LocalInstantiationScope Scope(*this);
951
952  // Introduce the instantiated function parameters into the local
953  // instantiation scope.
954  for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
955    Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
956                            Function->getParamDecl(I));
957
958  // Enter the scope of this instantiation. We don't use
959  // PushDeclContext because we don't have a scope.
960  DeclContext *PreviousContext = CurContext;
961  CurContext = Function;
962
963  // Instantiate the function body.
964  OwningStmtResult Body
965    = SubstStmt(Pattern, getTemplateInstantiationArgs(Function));
966
967  ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
968                          /*IsInstantiation=*/true);
969
970  CurContext = PreviousContext;
971
972  DeclGroupRef DG(Function);
973  Consumer.HandleTopLevelDecl(DG);
974
975  if (Recursive) {
976    // Instantiate any pending implicit instantiations found during the
977    // instantiation of this template.
978    PerformPendingImplicitInstantiations();
979
980    // Restore the set of pending implicit instantiations.
981    PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
982  }
983}
984
985/// \brief Instantiate the definition of the given variable from its
986/// template.
987///
988/// \param PointOfInstantiation the point at which the instantiation was
989/// required. Note that this is not precisely a "point of instantiation"
990/// for the function, but it's close.
991///
992/// \param Var the already-instantiated declaration of a static member
993/// variable of a class template specialization.
994///
995/// \param Recursive if true, recursively instantiates any functions that
996/// are required by this instantiation.
997void Sema::InstantiateStaticDataMemberDefinition(
998                                          SourceLocation PointOfInstantiation,
999                                                 VarDecl *Var,
1000                                                 bool Recursive) {
1001  if (Var->isInvalidDecl())
1002    return;
1003
1004  // Find the out-of-line definition of this static data member.
1005  // FIXME: Do we have to look for specializations separately?
1006  VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
1007  bool FoundOutOfLineDef = false;
1008  assert(Def && "This data member was not instantiated from a template?");
1009  assert(Def->isStaticDataMember() && "Not a static data member?");
1010  for (VarDecl::redecl_iterator RD = Def->redecls_begin(),
1011                             RDEnd = Def->redecls_end();
1012       RD != RDEnd; ++RD) {
1013    if (RD->getLexicalDeclContext()->isFileContext()) {
1014      Def = *RD;
1015      FoundOutOfLineDef = true;
1016    }
1017  }
1018
1019  if (!FoundOutOfLineDef) {
1020    // We did not find an out-of-line definition of this static data member,
1021    // so we won't perform any instantiation. Rather, we rely on the user to
1022    // instantiate this definition (or provide a specialization for it) in
1023    // another translation unit.
1024    return;
1025  }
1026
1027  InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
1028  if (Inst)
1029    return;
1030
1031  // If we're performing recursive template instantiation, create our own
1032  // queue of pending implicit instantiations that we will instantiate later,
1033  // while we're still within our own instantiation context.
1034  std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1035  if (Recursive)
1036    PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1037
1038  // Enter the scope of this instantiation. We don't use
1039  // PushDeclContext because we don't have a scope.
1040  DeclContext *PreviousContext = CurContext;
1041  CurContext = Var->getDeclContext();
1042
1043#if 0
1044  // Instantiate the initializer of this static data member.
1045  OwningExprResult Init
1046    = InstantiateExpr(Def->getInit(), getTemplateInstantiationArgs(Var));
1047  if (Init.isInvalid()) {
1048    // If instantiation of the initializer failed, mark the declaration invalid
1049    // and don't instantiate anything else that was triggered by this
1050    // instantiation.
1051    Var->setInvalidDecl();
1052
1053    // Restore the set of pending implicit instantiations.
1054    PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1055
1056    return;
1057  }
1058
1059  // Type-check the initializer.
1060  if (Init.get())
1061    AddInitializerToDecl(DeclPtrTy::make(Var), move(Init),
1062                         Def->hasCXXDirectInitializer());
1063  else
1064    ActOnUninitializedDecl(DeclPtrTy::make(Var), false);
1065#else
1066  Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
1067                                          getTemplateInstantiationArgs(Var)));
1068#endif
1069
1070  CurContext = PreviousContext;
1071
1072  if (Var) {
1073    DeclGroupRef DG(Var);
1074    Consumer.HandleTopLevelDecl(DG);
1075  }
1076
1077  if (Recursive) {
1078    // Instantiate any pending implicit instantiations found during the
1079    // instantiation of this template.
1080    PerformPendingImplicitInstantiations();
1081
1082    // Restore the set of pending implicit instantiations.
1083    PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
1084  }
1085}
1086
1087static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
1088  if (D->getKind() != Other->getKind())
1089    return false;
1090
1091  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
1092    return Record->getInstantiatedFromMemberClass()->getCanonicalDecl()
1093             == D->getCanonicalDecl();
1094
1095  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
1096    return Function->getInstantiatedFromMemberFunction()->getCanonicalDecl()
1097             == D->getCanonicalDecl();
1098
1099  if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
1100    return Enum->getInstantiatedFromMemberEnum()->getCanonicalDecl()
1101             == D->getCanonicalDecl();
1102
1103  if (VarDecl *Var = dyn_cast<VarDecl>(Other))
1104    if (Var->isStaticDataMember())
1105      return Var->getInstantiatedFromStaticDataMember()->getCanonicalDecl()
1106               == D->getCanonicalDecl();
1107
1108  // FIXME: How can we find instantiations of anonymous unions?
1109
1110  return D->getDeclName() && isa<NamedDecl>(Other) &&
1111    D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
1112}
1113
1114template<typename ForwardIterator>
1115static NamedDecl *findInstantiationOf(ASTContext &Ctx,
1116                                      NamedDecl *D,
1117                                      ForwardIterator first,
1118                                      ForwardIterator last) {
1119  for (; first != last; ++first)
1120    if (isInstantiationOf(Ctx, D, *first))
1121      return cast<NamedDecl>(*first);
1122
1123  return 0;
1124}
1125
1126/// \brief Find the instantiation of the given declaration within the
1127/// current instantiation.
1128///
1129/// This routine is intended to be used when \p D is a declaration
1130/// referenced from within a template, that needs to mapped into the
1131/// corresponding declaration within an instantiation. For example,
1132/// given:
1133///
1134/// \code
1135/// template<typename T>
1136/// struct X {
1137///   enum Kind {
1138///     KnownValue = sizeof(T)
1139///   };
1140///
1141///   bool getKind() const { return KnownValue; }
1142/// };
1143///
1144/// template struct X<int>;
1145/// \endcode
1146///
1147/// In the instantiation of X<int>::getKind(), we need to map the
1148/// EnumConstantDecl for KnownValue (which refers to
1149/// X<T>::<Kind>::KnownValue) to its instantiation
1150/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
1151/// this mapping from within the instantiation of X<int>.
1152NamedDecl * Sema::FindInstantiatedDecl(NamedDecl *D) {
1153  DeclContext *ParentDC = D->getDeclContext();
1154  if (isa<ParmVarDecl>(D) || ParentDC->isFunctionOrMethod()) {
1155    // D is a local of some kind. Look into the map of local
1156    // declarations to their instantiations.
1157    return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
1158  }
1159
1160  if (NamedDecl *ParentDecl = dyn_cast<NamedDecl>(ParentDC)) {
1161    ParentDecl = FindInstantiatedDecl(ParentDecl);
1162    if (!ParentDecl)
1163      return 0;
1164
1165    ParentDC = cast<DeclContext>(ParentDecl);
1166  }
1167
1168  if (ParentDC != D->getDeclContext()) {
1169    // We performed some kind of instantiation in the parent context,
1170    // so now we need to look into the instantiated parent context to
1171    // find the instantiation of the declaration D.
1172    NamedDecl *Result = 0;
1173    if (D->getDeclName()) {
1174      DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
1175      Result = findInstantiationOf(Context, D, Found.first, Found.second);
1176    } else {
1177      // Since we don't have a name for the entity we're looking for,
1178      // our only option is to walk through all of the declarations to
1179      // find that name. This will occur in a few cases:
1180      //
1181      //   - anonymous struct/union within a template
1182      //   - unnamed class/struct/union/enum within a template
1183      //
1184      // FIXME: Find a better way to find these instantiations!
1185      Result = findInstantiationOf(Context, D,
1186                                   ParentDC->decls_begin(),
1187                                   ParentDC->decls_end());
1188    }
1189    assert(Result && "Unable to find instantiation of declaration!");
1190    D = Result;
1191  }
1192
1193  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
1194    if (ClassTemplateDecl *ClassTemplate
1195          = Record->getDescribedClassTemplate()) {
1196      // When the declaration D was parsed, it referred to the current
1197      // instantiation. Therefore, look through the current context,
1198      // which contains actual instantiations, to find the
1199      // instantiation of the "current instantiation" that D refers
1200      // to. Alternatively, we could just instantiate the
1201      // injected-class-name with the current template arguments, but
1202      // such an instantiation is far more expensive.
1203      for (DeclContext *DC = CurContext; !DC->isFileContext();
1204           DC = DC->getParent()) {
1205        if (ClassTemplateSpecializationDecl *Spec
1206              = dyn_cast<ClassTemplateSpecializationDecl>(DC))
1207          if (Spec->getSpecializedTemplate()->getCanonicalDecl()
1208              == ClassTemplate->getCanonicalDecl())
1209            return Spec;
1210      }
1211
1212      assert(false &&
1213             "Unable to find declaration for the current instantiation");
1214    }
1215
1216  return D;
1217}
1218
1219/// \brief Performs template instantiation for all implicit template
1220/// instantiations we have seen until this point.
1221void Sema::PerformPendingImplicitInstantiations() {
1222  while (!PendingImplicitInstantiations.empty()) {
1223    PendingImplicitInstantiation Inst = PendingImplicitInstantiations.front();
1224    PendingImplicitInstantiations.pop_front();
1225
1226    // Instantiate function definitions
1227    if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
1228      if (!Function->getBody())
1229        InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
1230      continue;
1231    }
1232
1233    // Instantiate static data member definitions.
1234    VarDecl *Var = cast<VarDecl>(Inst.first);
1235    assert(Var->isStaticDataMember() && "Not a static data member?");
1236    InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
1237  }
1238}
1239