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