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