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