SemaTemplateInstantiateDecl.cpp revision 5df37bd0242e838e465f0bd51a70af424d152053
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 "clang/Sema/SemaInternal.h"
13#include "clang/Sema/Lookup.h"
14#include "clang/Sema/PrettyDeclStackTrace.h"
15#include "clang/Sema/Template.h"
16#include "clang/AST/ASTConsumer.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/DeclTemplate.h"
19#include "clang/AST/DeclVisitor.h"
20#include "clang/AST/DependentDiagnostic.h"
21#include "clang/AST/Expr.h"
22#include "clang/AST/ExprCXX.h"
23#include "clang/AST/TypeLoc.h"
24#include "clang/Lex/Preprocessor.h"
25
26using namespace clang;
27
28bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
29                                              DeclaratorDecl *NewDecl) {
30  if (!OldDecl->getQualifierLoc())
31    return false;
32
33  NestedNameSpecifierLoc NewQualifierLoc
34    = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
35                                          TemplateArgs);
36
37  if (!NewQualifierLoc)
38    return true;
39
40  NewDecl->setQualifierInfo(NewQualifierLoc);
41  return false;
42}
43
44bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
45                                              TagDecl *NewDecl) {
46  if (!OldDecl->getQualifierLoc())
47    return false;
48
49  NestedNameSpecifierLoc NewQualifierLoc
50  = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
51                                        TemplateArgs);
52
53  if (!NewQualifierLoc)
54    return true;
55
56  NewDecl->setQualifierInfo(NewQualifierLoc);
57  return false;
58}
59
60// FIXME: Is this still too simple?
61void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
62                            const Decl *Tmpl, Decl *New) {
63  for (AttrVec::const_iterator i = Tmpl->attr_begin(), e = Tmpl->attr_end();
64       i != e; ++i) {
65    const Attr *TmplAttr = *i;
66    // FIXME: This should be generalized to more than just the AlignedAttr.
67    if (const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr)) {
68      if (Aligned->isAlignmentDependent()) {
69        if (Aligned->isAlignmentExpr()) {
70          // The alignment expression is a constant expression.
71          EnterExpressionEvaluationContext Unevaluated(*this,
72                                                       Sema::ConstantEvaluated);
73
74          ExprResult Result = SubstExpr(Aligned->getAlignmentExpr(),
75                                        TemplateArgs);
76          if (!Result.isInvalid())
77            AddAlignedAttr(Aligned->getLocation(), New, Result.takeAs<Expr>());
78        } else {
79          TypeSourceInfo *Result = SubstType(Aligned->getAlignmentType(),
80                                             TemplateArgs,
81                                             Aligned->getLocation(),
82                                             DeclarationName());
83          if (Result)
84            AddAlignedAttr(Aligned->getLocation(), New, Result);
85        }
86        continue;
87      }
88    }
89
90    // FIXME: Is cloning correct for all attributes?
91    Attr *NewAttr = TmplAttr->clone(Context);
92    New->addAttr(NewAttr);
93  }
94}
95
96Decl *
97TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
98  llvm_unreachable("Translation units cannot be instantiated");
99}
100
101Decl *
102TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
103  LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
104                                      D->getIdentifier());
105  Owner->addDecl(Inst);
106  return Inst;
107}
108
109Decl *
110TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
111  llvm_unreachable("Namespaces cannot be instantiated");
112}
113
114Decl *
115TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
116  NamespaceAliasDecl *Inst
117    = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
118                                 D->getNamespaceLoc(),
119                                 D->getAliasLoc(),
120                                 D->getIdentifier(),
121                                 D->getQualifierLoc(),
122                                 D->getTargetNameLoc(),
123                                 D->getNamespace());
124  Owner->addDecl(Inst);
125  return Inst;
126}
127
128Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
129                                                           bool IsTypeAlias) {
130  bool Invalid = false;
131  TypeSourceInfo *DI = D->getTypeSourceInfo();
132  if (DI->getType()->isInstantiationDependentType() ||
133      DI->getType()->isVariablyModifiedType()) {
134    DI = SemaRef.SubstType(DI, TemplateArgs,
135                           D->getLocation(), D->getDeclName());
136    if (!DI) {
137      Invalid = true;
138      DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
139    }
140  } else {
141    SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
142  }
143
144  // Create the new typedef
145  TypedefNameDecl *Typedef;
146  if (IsTypeAlias)
147    Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
148                                    D->getLocation(), D->getIdentifier(), DI);
149  else
150    Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
151                                  D->getLocation(), D->getIdentifier(), DI);
152  if (Invalid)
153    Typedef->setInvalidDecl();
154
155  // If the old typedef was the name for linkage purposes of an anonymous
156  // tag decl, re-establish that relationship for the new typedef.
157  if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
158    TagDecl *oldTag = oldTagType->getDecl();
159    if (oldTag->getTypedefNameForAnonDecl() == D) {
160      TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
161      assert(!newTag->getIdentifier() && !newTag->getTypedefNameForAnonDecl());
162      newTag->setTypedefNameForAnonDecl(Typedef);
163    }
164  }
165
166  if (TypedefNameDecl *Prev = D->getPreviousDeclaration()) {
167    NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
168                                                       TemplateArgs);
169    if (!InstPrev)
170      return 0;
171
172    TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
173
174    // If the typedef types are not identical, reject them.
175    SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
176
177    Typedef->setPreviousDeclaration(InstPrevTypedef);
178  }
179
180  SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
181
182  Typedef->setAccess(D->getAccess());
183
184  return Typedef;
185}
186
187Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
188  Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
189  Owner->addDecl(Typedef);
190  return Typedef;
191}
192
193Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
194  Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
195  Owner->addDecl(Typedef);
196  return Typedef;
197}
198
199Decl *
200TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
201  // Create a local instantiation scope for this type alias template, which
202  // will contain the instantiations of the template parameters.
203  LocalInstantiationScope Scope(SemaRef);
204
205  TemplateParameterList *TempParams = D->getTemplateParameters();
206  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
207  if (!InstParams)
208    return 0;
209
210  TypeAliasDecl *Pattern = D->getTemplatedDecl();
211
212  TypeAliasTemplateDecl *PrevAliasTemplate = 0;
213  if (Pattern->getPreviousDeclaration()) {
214    DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
215    if (Found.first != Found.second) {
216      PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(*Found.first);
217    }
218  }
219
220  TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
221    InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
222  if (!AliasInst)
223    return 0;
224
225  TypeAliasTemplateDecl *Inst
226    = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
227                                    D->getDeclName(), InstParams, AliasInst);
228  if (PrevAliasTemplate)
229    Inst->setPreviousDeclaration(PrevAliasTemplate);
230
231  Inst->setAccess(D->getAccess());
232
233  if (!PrevAliasTemplate)
234    Inst->setInstantiatedFromMemberTemplate(D);
235
236  Owner->addDecl(Inst);
237
238  return Inst;
239}
240
241/// \brief Instantiate an initializer, breaking it into separate
242/// initialization arguments.
243///
244/// \param Init The initializer to instantiate.
245///
246/// \param TemplateArgs Template arguments to be substituted into the
247/// initializer.
248///
249/// \param NewArgs Will be filled in with the instantiation arguments.
250///
251/// \returns true if an error occurred, false otherwise
252bool Sema::InstantiateInitializer(Expr *Init,
253                            const MultiLevelTemplateArgumentList &TemplateArgs,
254                                  SourceLocation &LParenLoc,
255                                  ASTOwningVector<Expr*> &NewArgs,
256                                  SourceLocation &RParenLoc) {
257  NewArgs.clear();
258  LParenLoc = SourceLocation();
259  RParenLoc = SourceLocation();
260
261  if (!Init)
262    return false;
263
264  if (ExprWithCleanups *ExprTemp = dyn_cast<ExprWithCleanups>(Init))
265    Init = ExprTemp->getSubExpr();
266
267  while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
268    Init = Binder->getSubExpr();
269
270  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
271    Init = ICE->getSubExprAsWritten();
272
273  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
274    LParenLoc = ParenList->getLParenLoc();
275    RParenLoc = ParenList->getRParenLoc();
276    return SubstExprs(ParenList->getExprs(), ParenList->getNumExprs(),
277                      true, TemplateArgs, NewArgs);
278  }
279
280  if (CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init)) {
281    if (!isa<CXXTemporaryObjectExpr>(Construct)) {
282      if (SubstExprs(Construct->getArgs(), Construct->getNumArgs(), true,
283                     TemplateArgs, NewArgs))
284        return true;
285
286      // FIXME: Fake locations!
287      LParenLoc = PP.getLocForEndOfToken(Init->getLocStart());
288      RParenLoc = LParenLoc;
289      return false;
290    }
291  }
292
293  ExprResult Result = SubstExpr(Init, TemplateArgs);
294  if (Result.isInvalid())
295    return true;
296
297  NewArgs.push_back(Result.takeAs<Expr>());
298  return false;
299}
300
301Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
302  // If this is the variable for an anonymous struct or union,
303  // instantiate the anonymous struct/union type first.
304  if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
305    if (RecordTy->getDecl()->isAnonymousStructOrUnion())
306      if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
307        return 0;
308
309  // Do substitution on the type of the declaration
310  TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
311                                         TemplateArgs,
312                                         D->getTypeSpecStartLoc(),
313                                         D->getDeclName());
314  if (!DI)
315    return 0;
316
317  if (DI->getType()->isFunctionType()) {
318    SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
319      << D->isStaticDataMember() << DI->getType();
320    return 0;
321  }
322
323  // Build the instantiated declaration
324  VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
325                                 D->getInnerLocStart(),
326                                 D->getLocation(), D->getIdentifier(),
327                                 DI->getType(), DI,
328                                 D->getStorageClass(),
329                                 D->getStorageClassAsWritten());
330  Var->setThreadSpecified(D->isThreadSpecified());
331  Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
332  Var->setCXXForRangeDecl(D->isCXXForRangeDecl());
333
334  // Substitute the nested name specifier, if any.
335  if (SubstQualifier(D, Var))
336    return 0;
337
338  // If we are instantiating a static data member defined
339  // out-of-line, the instantiation will have the same lexical
340  // context (which will be a namespace scope) as the template.
341  if (D->isOutOfLine())
342    Var->setLexicalDeclContext(D->getLexicalDeclContext());
343
344  Var->setAccess(D->getAccess());
345
346  if (!D->isStaticDataMember()) {
347    Var->setUsed(D->isUsed(false));
348    Var->setReferenced(D->isReferenced());
349  }
350
351  // FIXME: In theory, we could have a previous declaration for variables that
352  // are not static data members.
353  // FIXME: having to fake up a LookupResult is dumb.
354  LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
355                        Sema::LookupOrdinaryName, Sema::ForRedeclaration);
356  if (D->isStaticDataMember())
357    SemaRef.LookupQualifiedName(Previous, Owner, false);
358
359  // In ARC, infer 'retaining' for variables of retainable type.
360  if (SemaRef.getLangOptions().ObjCAutoRefCount &&
361      SemaRef.inferObjCARCLifetime(Var))
362    Var->setInvalidDecl();
363
364  SemaRef.CheckVariableDeclaration(Var, Previous);
365
366  if (D->isOutOfLine()) {
367    D->getLexicalDeclContext()->addDecl(Var);
368    Owner->makeDeclVisibleInContext(Var);
369  } else {
370    Owner->addDecl(Var);
371    if (Owner->isFunctionOrMethod())
372      SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Var);
373  }
374  SemaRef.InstantiateAttrs(TemplateArgs, D, Var);
375
376  // Link instantiations of static data members back to the template from
377  // which they were instantiated.
378  if (Var->isStaticDataMember())
379    SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
380                                                     TSK_ImplicitInstantiation);
381
382  if (Var->getAnyInitializer()) {
383    // We already have an initializer in the class.
384  } else if (D->getInit()) {
385    if (Var->isStaticDataMember() && !D->isOutOfLine())
386      SemaRef.PushExpressionEvaluationContext(Sema::ConstantEvaluated);
387    else
388      SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
389
390    // Instantiate the initializer.
391    SourceLocation LParenLoc, RParenLoc;
392    ASTOwningVector<Expr*> InitArgs(SemaRef);
393    if (!SemaRef.InstantiateInitializer(D->getInit(), TemplateArgs, LParenLoc,
394                                        InitArgs, RParenLoc)) {
395      bool TypeMayContainAuto = true;
396      // Attach the initializer to the declaration, if we have one.
397      if (InitArgs.size() == 0)
398        SemaRef.ActOnUninitializedDecl(Var, TypeMayContainAuto);
399      else if (D->hasCXXDirectInitializer()) {
400        // Add the direct initializer to the declaration.
401        SemaRef.AddCXXDirectInitializerToDecl(Var,
402                                              LParenLoc,
403                                              move_arg(InitArgs),
404                                              RParenLoc,
405                                              TypeMayContainAuto);
406      } else {
407        assert(InitArgs.size() == 1);
408        Expr *Init = InitArgs.take()[0];
409        SemaRef.AddInitializerToDecl(Var, Init, false, TypeMayContainAuto);
410      }
411    } else {
412      // FIXME: Not too happy about invalidating the declaration
413      // because of a bogus initializer.
414      Var->setInvalidDecl();
415    }
416
417    SemaRef.PopExpressionEvaluationContext();
418  } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) &&
419             !Var->isCXXForRangeDecl())
420    SemaRef.ActOnUninitializedDecl(Var, false);
421
422  // Diagnose unused local variables with dependent types, where the diagnostic
423  // will have been deferred.
424  if (!Var->isInvalidDecl() && Owner->isFunctionOrMethod() && !Var->isUsed() &&
425      D->getType()->isDependentType())
426    SemaRef.DiagnoseUnusedDecl(Var);
427
428  return Var;
429}
430
431Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
432  AccessSpecDecl* AD
433    = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
434                             D->getAccessSpecifierLoc(), D->getColonLoc());
435  Owner->addHiddenDecl(AD);
436  return AD;
437}
438
439Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
440  bool Invalid = false;
441  TypeSourceInfo *DI = D->getTypeSourceInfo();
442  if (DI->getType()->isInstantiationDependentType() ||
443      DI->getType()->isVariablyModifiedType())  {
444    DI = SemaRef.SubstType(DI, TemplateArgs,
445                           D->getLocation(), D->getDeclName());
446    if (!DI) {
447      DI = D->getTypeSourceInfo();
448      Invalid = true;
449    } else if (DI->getType()->isFunctionType()) {
450      // C++ [temp.arg.type]p3:
451      //   If a declaration acquires a function type through a type
452      //   dependent on a template-parameter and this causes a
453      //   declaration that does not use the syntactic form of a
454      //   function declarator to have function type, the program is
455      //   ill-formed.
456      SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
457        << DI->getType();
458      Invalid = true;
459    }
460  } else {
461    SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
462  }
463
464  Expr *BitWidth = D->getBitWidth();
465  if (Invalid)
466    BitWidth = 0;
467  else if (BitWidth) {
468    // The bit-width expression is a constant expression.
469    EnterExpressionEvaluationContext Unevaluated(SemaRef,
470                                                 Sema::ConstantEvaluated);
471
472    ExprResult InstantiatedBitWidth
473      = SemaRef.SubstExpr(BitWidth, TemplateArgs);
474    if (InstantiatedBitWidth.isInvalid()) {
475      Invalid = true;
476      BitWidth = 0;
477    } else
478      BitWidth = InstantiatedBitWidth.takeAs<Expr>();
479  }
480
481  FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
482                                            DI->getType(), DI,
483                                            cast<RecordDecl>(Owner),
484                                            D->getLocation(),
485                                            D->isMutable(),
486                                            BitWidth,
487                                            D->hasInClassInitializer(),
488                                            D->getTypeSpecStartLoc(),
489                                            D->getAccess(),
490                                            0);
491  if (!Field) {
492    cast<Decl>(Owner)->setInvalidDecl();
493    return 0;
494  }
495
496  SemaRef.InstantiateAttrs(TemplateArgs, D, Field);
497
498  if (Invalid)
499    Field->setInvalidDecl();
500
501  if (!Field->getDeclName()) {
502    // Keep track of where this decl came from.
503    SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
504  }
505  if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
506    if (Parent->isAnonymousStructOrUnion() &&
507        Parent->getRedeclContext()->isFunctionOrMethod())
508      SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
509  }
510
511  Field->setImplicit(D->isImplicit());
512  Field->setAccess(D->getAccess());
513  Owner->addDecl(Field);
514
515  return Field;
516}
517
518Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
519  NamedDecl **NamedChain =
520    new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
521
522  int i = 0;
523  for (IndirectFieldDecl::chain_iterator PI =
524       D->chain_begin(), PE = D->chain_end();
525       PI != PE; ++PI) {
526    NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), *PI,
527                                              TemplateArgs);
528    if (!Next)
529      return 0;
530
531    NamedChain[i++] = Next;
532  }
533
534  QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
535  IndirectFieldDecl* IndirectField
536    = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(),
537                                D->getIdentifier(), T,
538                                NamedChain, D->getChainingSize());
539
540
541  IndirectField->setImplicit(D->isImplicit());
542  IndirectField->setAccess(D->getAccess());
543  Owner->addDecl(IndirectField);
544  return IndirectField;
545}
546
547Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
548  // Handle friend type expressions by simply substituting template
549  // parameters into the pattern type and checking the result.
550  if (TypeSourceInfo *Ty = D->getFriendType()) {
551    TypeSourceInfo *InstTy;
552    // If this is an unsupported friend, don't bother substituting template
553    // arguments into it. The actual type referred to won't be used by any
554    // parts of Clang, and may not be valid for instantiating. Just use the
555    // same info for the instantiated friend.
556    if (D->isUnsupportedFriend()) {
557      InstTy = Ty;
558    } else {
559      InstTy = SemaRef.SubstType(Ty, TemplateArgs,
560                                 D->getLocation(), DeclarationName());
561    }
562    if (!InstTy)
563      return 0;
564
565    FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getLocation(),
566                                                 D->getFriendLoc(), InstTy);
567    if (!FD)
568      return 0;
569
570    FD->setAccess(AS_public);
571    FD->setUnsupportedFriend(D->isUnsupportedFriend());
572    Owner->addDecl(FD);
573    return FD;
574  }
575
576  NamedDecl *ND = D->getFriendDecl();
577  assert(ND && "friend decl must be a decl or a type!");
578
579  // All of the Visit implementations for the various potential friend
580  // declarations have to be carefully written to work for friend
581  // objects, with the most important detail being that the target
582  // decl should almost certainly not be placed in Owner.
583  Decl *NewND = Visit(ND);
584  if (!NewND) return 0;
585
586  FriendDecl *FD =
587    FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
588                       cast<NamedDecl>(NewND), D->getFriendLoc());
589  FD->setAccess(AS_public);
590  FD->setUnsupportedFriend(D->isUnsupportedFriend());
591  Owner->addDecl(FD);
592  return FD;
593}
594
595Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
596  Expr *AssertExpr = D->getAssertExpr();
597
598  // The expression in a static assertion is a constant expression.
599  EnterExpressionEvaluationContext Unevaluated(SemaRef,
600                                               Sema::ConstantEvaluated);
601
602  ExprResult InstantiatedAssertExpr
603    = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
604  if (InstantiatedAssertExpr.isInvalid())
605    return 0;
606
607  ExprResult Message(D->getMessage());
608  D->getMessage();
609  return SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
610                                              InstantiatedAssertExpr.get(),
611                                              Message.get(),
612                                              D->getRParenLoc());
613}
614
615Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
616  EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
617                                    D->getLocation(), D->getIdentifier(),
618                                    /*PrevDecl=*/0, D->isScoped(),
619                                    D->isScopedUsingClassTag(), D->isFixed());
620  if (D->isFixed()) {
621    if (TypeSourceInfo* TI = D->getIntegerTypeSourceInfo()) {
622      // If we have type source information for the underlying type, it means it
623      // has been explicitly set by the user. Perform substitution on it before
624      // moving on.
625      SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
626      Enum->setIntegerTypeSourceInfo(SemaRef.SubstType(TI,
627                                                       TemplateArgs,
628                                                       UnderlyingLoc,
629                                                       DeclarationName()));
630
631      if (!Enum->getIntegerTypeSourceInfo())
632        Enum->setIntegerType(SemaRef.Context.IntTy);
633    }
634    else {
635      assert(!D->getIntegerType()->isDependentType()
636             && "Dependent type without type source info");
637      Enum->setIntegerType(D->getIntegerType());
638    }
639  }
640
641  SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
642
643  Enum->setInstantiationOfMemberEnum(D);
644  Enum->setAccess(D->getAccess());
645  if (SubstQualifier(D, Enum)) return 0;
646  Owner->addDecl(Enum);
647  Enum->startDefinition();
648
649  if (D->getDeclContext()->isFunctionOrMethod())
650    SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
651
652  SmallVector<Decl*, 4> Enumerators;
653
654  EnumConstantDecl *LastEnumConst = 0;
655  for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
656         ECEnd = D->enumerator_end();
657       EC != ECEnd; ++EC) {
658    // The specified value for the enumerator.
659    ExprResult Value = SemaRef.Owned((Expr *)0);
660    if (Expr *UninstValue = EC->getInitExpr()) {
661      // The enumerator's value expression is a constant expression.
662      EnterExpressionEvaluationContext Unevaluated(SemaRef,
663                                                   Sema::ConstantEvaluated);
664
665      Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
666    }
667
668    // Drop the initial value and continue.
669    bool isInvalid = false;
670    if (Value.isInvalid()) {
671      Value = SemaRef.Owned((Expr *)0);
672      isInvalid = true;
673    }
674
675    EnumConstantDecl *EnumConst
676      = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
677                                  EC->getLocation(), EC->getIdentifier(),
678                                  Value.get());
679
680    if (isInvalid) {
681      if (EnumConst)
682        EnumConst->setInvalidDecl();
683      Enum->setInvalidDecl();
684    }
685
686    if (EnumConst) {
687      SemaRef.InstantiateAttrs(TemplateArgs, *EC, EnumConst);
688
689      EnumConst->setAccess(Enum->getAccess());
690      Enum->addDecl(EnumConst);
691      Enumerators.push_back(EnumConst);
692      LastEnumConst = EnumConst;
693
694      if (D->getDeclContext()->isFunctionOrMethod()) {
695        // If the enumeration is within a function or method, record the enum
696        // constant as a local.
697        SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
698      }
699    }
700  }
701
702  // FIXME: Fixup LBraceLoc and RBraceLoc
703  // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
704  SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
705                        Enum,
706                        Enumerators.data(), Enumerators.size(),
707                        0, 0);
708
709  return Enum;
710}
711
712Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
713  llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
714}
715
716Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
717  bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
718
719  // Create a local instantiation scope for this class template, which
720  // will contain the instantiations of the template parameters.
721  LocalInstantiationScope Scope(SemaRef);
722  TemplateParameterList *TempParams = D->getTemplateParameters();
723  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
724  if (!InstParams)
725    return NULL;
726
727  CXXRecordDecl *Pattern = D->getTemplatedDecl();
728
729  // Instantiate the qualifier.  We have to do this first in case
730  // we're a friend declaration, because if we are then we need to put
731  // the new declaration in the appropriate context.
732  NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
733  if (QualifierLoc) {
734    QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
735                                                       TemplateArgs);
736    if (!QualifierLoc)
737      return 0;
738  }
739
740  CXXRecordDecl *PrevDecl = 0;
741  ClassTemplateDecl *PrevClassTemplate = 0;
742
743  if (!isFriend && Pattern->getPreviousDeclaration()) {
744    DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
745    if (Found.first != Found.second) {
746      PrevClassTemplate = dyn_cast<ClassTemplateDecl>(*Found.first);
747      if (PrevClassTemplate)
748        PrevDecl = PrevClassTemplate->getTemplatedDecl();
749    }
750  }
751
752  // If this isn't a friend, then it's a member template, in which
753  // case we just want to build the instantiation in the
754  // specialization.  If it is a friend, we want to build it in
755  // the appropriate context.
756  DeclContext *DC = Owner;
757  if (isFriend) {
758    if (QualifierLoc) {
759      CXXScopeSpec SS;
760      SS.Adopt(QualifierLoc);
761      DC = SemaRef.computeDeclContext(SS);
762      if (!DC) return 0;
763    } else {
764      DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
765                                           Pattern->getDeclContext(),
766                                           TemplateArgs);
767    }
768
769    // Look for a previous declaration of the template in the owning
770    // context.
771    LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
772                   Sema::LookupOrdinaryName, Sema::ForRedeclaration);
773    SemaRef.LookupQualifiedName(R, DC);
774
775    if (R.isSingleResult()) {
776      PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
777      if (PrevClassTemplate)
778        PrevDecl = PrevClassTemplate->getTemplatedDecl();
779    }
780
781    if (!PrevClassTemplate && QualifierLoc) {
782      SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
783        << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
784        << QualifierLoc.getSourceRange();
785      return 0;
786    }
787
788    bool AdoptedPreviousTemplateParams = false;
789    if (PrevClassTemplate) {
790      bool Complain = true;
791
792      // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
793      // template for struct std::tr1::__detail::_Map_base, where the
794      // template parameters of the friend declaration don't match the
795      // template parameters of the original declaration. In this one
796      // case, we don't complain about the ill-formed friend
797      // declaration.
798      if (isFriend && Pattern->getIdentifier() &&
799          Pattern->getIdentifier()->isStr("_Map_base") &&
800          DC->isNamespace() &&
801          cast<NamespaceDecl>(DC)->getIdentifier() &&
802          cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
803        DeclContext *DCParent = DC->getParent();
804        if (DCParent->isNamespace() &&
805            cast<NamespaceDecl>(DCParent)->getIdentifier() &&
806            cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
807          DeclContext *DCParent2 = DCParent->getParent();
808          if (DCParent2->isNamespace() &&
809              cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
810              cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
811              DCParent2->getParent()->isTranslationUnit())
812            Complain = false;
813        }
814      }
815
816      TemplateParameterList *PrevParams
817        = PrevClassTemplate->getTemplateParameters();
818
819      // Make sure the parameter lists match.
820      if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
821                                                  Complain,
822                                                  Sema::TPL_TemplateMatch)) {
823        if (Complain)
824          return 0;
825
826        AdoptedPreviousTemplateParams = true;
827        InstParams = PrevParams;
828      }
829
830      // Do some additional validation, then merge default arguments
831      // from the existing declarations.
832      if (!AdoptedPreviousTemplateParams &&
833          SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
834                                             Sema::TPC_ClassTemplate))
835        return 0;
836    }
837  }
838
839  CXXRecordDecl *RecordInst
840    = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
841                            Pattern->getLocStart(), Pattern->getLocation(),
842                            Pattern->getIdentifier(), PrevDecl,
843                            /*DelayTypeCreation=*/true);
844
845  if (QualifierLoc)
846    RecordInst->setQualifierInfo(QualifierLoc);
847
848  ClassTemplateDecl *Inst
849    = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
850                                D->getIdentifier(), InstParams, RecordInst,
851                                PrevClassTemplate);
852  RecordInst->setDescribedClassTemplate(Inst);
853
854  if (isFriend) {
855    if (PrevClassTemplate)
856      Inst->setAccess(PrevClassTemplate->getAccess());
857    else
858      Inst->setAccess(D->getAccess());
859
860    Inst->setObjectOfFriendDecl(PrevClassTemplate != 0);
861    // TODO: do we want to track the instantiation progeny of this
862    // friend target decl?
863  } else {
864    Inst->setAccess(D->getAccess());
865    if (!PrevClassTemplate)
866      Inst->setInstantiatedFromMemberTemplate(D);
867  }
868
869  // Trigger creation of the type for the instantiation.
870  SemaRef.Context.getInjectedClassNameType(RecordInst,
871                                    Inst->getInjectedClassNameSpecialization());
872
873  // Finish handling of friends.
874  if (isFriend) {
875    DC->makeDeclVisibleInContext(Inst, /*Recoverable*/ false);
876    Inst->setLexicalDeclContext(Owner);
877    RecordInst->setLexicalDeclContext(Owner);
878    return Inst;
879  }
880
881  if (D->isOutOfLine()) {
882    Inst->setLexicalDeclContext(D->getLexicalDeclContext());
883    RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
884  }
885
886  Owner->addDecl(Inst);
887
888  if (!PrevClassTemplate) {
889    // Queue up any out-of-line partial specializations of this member
890    // class template; the client will force their instantiation once
891    // the enclosing class has been instantiated.
892    SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
893    D->getPartialSpecializations(PartialSpecs);
894    for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
895      if (PartialSpecs[I]->isOutOfLine())
896        OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
897  }
898
899  return Inst;
900}
901
902Decl *
903TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
904                                   ClassTemplatePartialSpecializationDecl *D) {
905  ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
906
907  // Lookup the already-instantiated declaration in the instantiation
908  // of the class template and return that.
909  DeclContext::lookup_result Found
910    = Owner->lookup(ClassTemplate->getDeclName());
911  if (Found.first == Found.second)
912    return 0;
913
914  ClassTemplateDecl *InstClassTemplate
915    = dyn_cast<ClassTemplateDecl>(*Found.first);
916  if (!InstClassTemplate)
917    return 0;
918
919  if (ClassTemplatePartialSpecializationDecl *Result
920        = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
921    return Result;
922
923  return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
924}
925
926Decl *
927TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
928  // Create a local instantiation scope for this function template, which
929  // will contain the instantiations of the template parameters and then get
930  // merged with the local instantiation scope for the function template
931  // itself.
932  LocalInstantiationScope Scope(SemaRef);
933
934  TemplateParameterList *TempParams = D->getTemplateParameters();
935  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
936  if (!InstParams)
937    return NULL;
938
939  FunctionDecl *Instantiated = 0;
940  if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
941    Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
942                                                                 InstParams));
943  else
944    Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
945                                                          D->getTemplatedDecl(),
946                                                                InstParams));
947
948  if (!Instantiated)
949    return 0;
950
951  Instantiated->setAccess(D->getAccess());
952
953  // Link the instantiated function template declaration to the function
954  // template from which it was instantiated.
955  FunctionTemplateDecl *InstTemplate
956    = Instantiated->getDescribedFunctionTemplate();
957  InstTemplate->setAccess(D->getAccess());
958  assert(InstTemplate &&
959         "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
960
961  bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
962
963  // Link the instantiation back to the pattern *unless* this is a
964  // non-definition friend declaration.
965  if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
966      !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
967    InstTemplate->setInstantiatedFromMemberTemplate(D);
968
969  // Make declarations visible in the appropriate context.
970  if (!isFriend)
971    Owner->addDecl(InstTemplate);
972
973  return InstTemplate;
974}
975
976Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
977  CXXRecordDecl *PrevDecl = 0;
978  if (D->isInjectedClassName())
979    PrevDecl = cast<CXXRecordDecl>(Owner);
980  else if (D->getPreviousDeclaration()) {
981    NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
982                                                   D->getPreviousDeclaration(),
983                                                   TemplateArgs);
984    if (!Prev) return 0;
985    PrevDecl = cast<CXXRecordDecl>(Prev);
986  }
987
988  CXXRecordDecl *Record
989    = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
990                            D->getLocStart(), D->getLocation(),
991                            D->getIdentifier(), PrevDecl);
992
993  // Substitute the nested name specifier, if any.
994  if (SubstQualifier(D, Record))
995    return 0;
996
997  Record->setImplicit(D->isImplicit());
998  // FIXME: Check against AS_none is an ugly hack to work around the issue that
999  // the tag decls introduced by friend class declarations don't have an access
1000  // specifier. Remove once this area of the code gets sorted out.
1001  if (D->getAccess() != AS_none)
1002    Record->setAccess(D->getAccess());
1003  if (!D->isInjectedClassName())
1004    Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
1005
1006  // If the original function was part of a friend declaration,
1007  // inherit its namespace state.
1008  if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
1009    Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
1010
1011  // Make sure that anonymous structs and unions are recorded.
1012  if (D->isAnonymousStructOrUnion()) {
1013    Record->setAnonymousStructOrUnion(true);
1014    if (Record->getDeclContext()->getRedeclContext()->isFunctionOrMethod())
1015      SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
1016  }
1017
1018  Owner->addDecl(Record);
1019  return Record;
1020}
1021
1022/// Normal class members are of more specific types and therefore
1023/// don't make it here.  This function serves two purposes:
1024///   1) instantiating function templates
1025///   2) substituting friend declarations
1026/// FIXME: preserve function definitions in case #2
1027Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
1028                                       TemplateParameterList *TemplateParams) {
1029  // Check whether there is already a function template specialization for
1030  // this declaration.
1031  FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1032  void *InsertPos = 0;
1033  if (FunctionTemplate && !TemplateParams) {
1034    std::pair<const TemplateArgument *, unsigned> Innermost
1035      = TemplateArgs.getInnermost();
1036
1037    FunctionDecl *SpecFunc
1038      = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
1039                                             InsertPos);
1040
1041    // If we already have a function template specialization, return it.
1042    if (SpecFunc)
1043      return SpecFunc;
1044  }
1045
1046  bool isFriend;
1047  if (FunctionTemplate)
1048    isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1049  else
1050    isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1051
1052  bool MergeWithParentScope = (TemplateParams != 0) ||
1053    Owner->isFunctionOrMethod() ||
1054    !(isa<Decl>(Owner) &&
1055      cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1056  LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
1057
1058  SmallVector<ParmVarDecl *, 4> Params;
1059  TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
1060  if (!TInfo)
1061    return 0;
1062  QualType T = TInfo->getType();
1063
1064  NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1065  if (QualifierLoc) {
1066    QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1067                                                       TemplateArgs);
1068    if (!QualifierLoc)
1069      return 0;
1070  }
1071
1072  // If we're instantiating a local function declaration, put the result
1073  // in the owner;  otherwise we need to find the instantiated context.
1074  DeclContext *DC;
1075  if (D->getDeclContext()->isFunctionOrMethod())
1076    DC = Owner;
1077  else if (isFriend && QualifierLoc) {
1078    CXXScopeSpec SS;
1079    SS.Adopt(QualifierLoc);
1080    DC = SemaRef.computeDeclContext(SS);
1081    if (!DC) return 0;
1082  } else {
1083    DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
1084                                         TemplateArgs);
1085  }
1086
1087  FunctionDecl *Function =
1088      FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1089                           D->getLocation(), D->getDeclName(), T, TInfo,
1090                           D->getStorageClass(), D->getStorageClassAsWritten(),
1091                           D->isInlineSpecified(), D->hasWrittenPrototype(),
1092                           /*isConstexpr*/ false);
1093
1094  if (QualifierLoc)
1095    Function->setQualifierInfo(QualifierLoc);
1096
1097  DeclContext *LexicalDC = Owner;
1098  if (!isFriend && D->isOutOfLine()) {
1099    assert(D->getDeclContext()->isFileContext());
1100    LexicalDC = D->getDeclContext();
1101  }
1102
1103  Function->setLexicalDeclContext(LexicalDC);
1104
1105  // Attach the parameters
1106  if (isa<FunctionProtoType>(Function->getType().IgnoreParens())) {
1107    // Adopt the already-instantiated parameters into our own context.
1108    for (unsigned P = 0; P < Params.size(); ++P)
1109      if (Params[P])
1110        Params[P]->setOwningFunction(Function);
1111  } else {
1112    // Since we were instantiated via a typedef of a function type, create
1113    // new parameters.
1114    const FunctionProtoType *Proto
1115      = Function->getType()->getAs<FunctionProtoType>();
1116    assert(Proto && "No function prototype in template instantiation?");
1117    for (FunctionProtoType::arg_type_iterator AI = Proto->arg_type_begin(),
1118         AE = Proto->arg_type_end(); AI != AE; ++AI) {
1119      ParmVarDecl *Param
1120        = SemaRef.BuildParmVarDeclForTypedef(Function, Function->getLocation(),
1121                                             *AI);
1122      Param->setScopeInfo(0, Params.size());
1123      Params.push_back(Param);
1124    }
1125  }
1126  Function->setParams(Params);
1127
1128  SourceLocation InstantiateAtPOI;
1129  if (TemplateParams) {
1130    // Our resulting instantiation is actually a function template, since we
1131    // are substituting only the outer template parameters. For example, given
1132    //
1133    //   template<typename T>
1134    //   struct X {
1135    //     template<typename U> friend void f(T, U);
1136    //   };
1137    //
1138    //   X<int> x;
1139    //
1140    // We are instantiating the friend function template "f" within X<int>,
1141    // which means substituting int for T, but leaving "f" as a friend function
1142    // template.
1143    // Build the function template itself.
1144    FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
1145                                                    Function->getLocation(),
1146                                                    Function->getDeclName(),
1147                                                    TemplateParams, Function);
1148    Function->setDescribedFunctionTemplate(FunctionTemplate);
1149
1150    FunctionTemplate->setLexicalDeclContext(LexicalDC);
1151
1152    if (isFriend && D->isThisDeclarationADefinition()) {
1153      // TODO: should we remember this connection regardless of whether
1154      // the friend declaration provided a body?
1155      FunctionTemplate->setInstantiatedFromMemberTemplate(
1156                                           D->getDescribedFunctionTemplate());
1157    }
1158  } else if (FunctionTemplate) {
1159    // Record this function template specialization.
1160    std::pair<const TemplateArgument *, unsigned> Innermost
1161      = TemplateArgs.getInnermost();
1162    Function->setFunctionTemplateSpecialization(FunctionTemplate,
1163                            TemplateArgumentList::CreateCopy(SemaRef.Context,
1164                                                             Innermost.first,
1165                                                             Innermost.second),
1166                                                InsertPos);
1167  } else if (isFriend) {
1168    // Note, we need this connection even if the friend doesn't have a body.
1169    // Its body may exist but not have been attached yet due to deferred
1170    // parsing.
1171    // FIXME: It might be cleaner to set this when attaching the body to the
1172    // friend function declaration, however that would require finding all the
1173    // instantiations and modifying them.
1174    Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
1175  }
1176
1177  if (InitFunctionInstantiation(Function, D))
1178    Function->setInvalidDecl();
1179
1180  bool isExplicitSpecialization = false;
1181
1182  LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
1183                        Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1184
1185  if (DependentFunctionTemplateSpecializationInfo *Info
1186        = D->getDependentSpecializationInfo()) {
1187    assert(isFriend && "non-friend has dependent specialization info?");
1188
1189    // This needs to be set now for future sanity.
1190    Function->setObjectOfFriendDecl(/*HasPrevious*/ true);
1191
1192    // Instantiate the explicit template arguments.
1193    TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1194                                          Info->getRAngleLoc());
1195    if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1196                      ExplicitArgs, TemplateArgs))
1197      return 0;
1198
1199    // Map the candidate templates to their instantiations.
1200    for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1201      Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1202                                                Info->getTemplate(I),
1203                                                TemplateArgs);
1204      if (!Temp) return 0;
1205
1206      Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1207    }
1208
1209    if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1210                                                    &ExplicitArgs,
1211                                                    Previous))
1212      Function->setInvalidDecl();
1213
1214    isExplicitSpecialization = true;
1215
1216  } else if (TemplateParams || !FunctionTemplate) {
1217    // Look only into the namespace where the friend would be declared to
1218    // find a previous declaration. This is the innermost enclosing namespace,
1219    // as described in ActOnFriendFunctionDecl.
1220    SemaRef.LookupQualifiedName(Previous, DC);
1221
1222    // In C++, the previous declaration we find might be a tag type
1223    // (class or enum). In this case, the new declaration will hide the
1224    // tag type. Note that this does does not apply if we're declaring a
1225    // typedef (C++ [dcl.typedef]p4).
1226    if (Previous.isSingleTagDecl())
1227      Previous.clear();
1228  }
1229
1230  SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
1231                                   isExplicitSpecialization);
1232
1233  NamedDecl *PrincipalDecl = (TemplateParams
1234                              ? cast<NamedDecl>(FunctionTemplate)
1235                              : Function);
1236
1237  // If the original function was part of a friend declaration,
1238  // inherit its namespace state and add it to the owner.
1239  if (isFriend) {
1240    NamedDecl *PrevDecl;
1241    if (TemplateParams)
1242      PrevDecl = FunctionTemplate->getPreviousDeclaration();
1243    else
1244      PrevDecl = Function->getPreviousDeclaration();
1245
1246    PrincipalDecl->setObjectOfFriendDecl(PrevDecl != 0);
1247    DC->makeDeclVisibleInContext(PrincipalDecl, /*Recoverable=*/ false);
1248
1249    bool queuedInstantiation = false;
1250
1251    // C++98 [temp.friend]p5: When a function is defined in a friend function
1252    //   declaration in a class template, the function is defined at each
1253    //   instantiation of the class template. The function is defined even if it
1254    //   is never used.
1255    // C++11 [temp.friend]p4: When a function is defined in a friend function
1256    //   declaration in a class template, the function is instantiated when the
1257    //   function is odr-used.
1258    //
1259    // If -Wc++98-compat is enabled, we go through the motions of checking for a
1260    // redefinition, but don't instantiate the function.
1261    if ((!SemaRef.getLangOptions().CPlusPlus0x ||
1262         SemaRef.Diags.getDiagnosticLevel(
1263             diag::warn_cxx98_compat_friend_redefinition,
1264             Function->getLocation())
1265           != DiagnosticsEngine::Ignored) &&
1266        D->isThisDeclarationADefinition()) {
1267      // Check for a function body.
1268      const FunctionDecl *Definition = 0;
1269      if (Function->isDefined(Definition) &&
1270          Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
1271        SemaRef.Diag(Function->getLocation(),
1272                     SemaRef.getLangOptions().CPlusPlus0x ?
1273                       diag::warn_cxx98_compat_friend_redefinition :
1274                       diag::err_redefinition) << Function->getDeclName();
1275        SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
1276        if (!SemaRef.getLangOptions().CPlusPlus0x)
1277          Function->setInvalidDecl();
1278      }
1279      // Check for redefinitions due to other instantiations of this or
1280      // a similar friend function.
1281      else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(),
1282                                           REnd = Function->redecls_end();
1283                R != REnd; ++R) {
1284        if (*R == Function)
1285          continue;
1286        switch (R->getFriendObjectKind()) {
1287        case Decl::FOK_None:
1288          if (!SemaRef.getLangOptions().CPlusPlus0x &&
1289              !queuedInstantiation && R->isUsed(false)) {
1290            if (MemberSpecializationInfo *MSInfo
1291                = Function->getMemberSpecializationInfo()) {
1292              if (MSInfo->getPointOfInstantiation().isInvalid()) {
1293                SourceLocation Loc = R->getLocation(); // FIXME
1294                MSInfo->setPointOfInstantiation(Loc);
1295                SemaRef.PendingLocalImplicitInstantiations.push_back(
1296                                                 std::make_pair(Function, Loc));
1297                queuedInstantiation = true;
1298              }
1299            }
1300          }
1301          break;
1302        default:
1303          if (const FunctionDecl *RPattern
1304              = R->getTemplateInstantiationPattern())
1305            if (RPattern->isDefined(RPattern)) {
1306              SemaRef.Diag(Function->getLocation(),
1307                           SemaRef.getLangOptions().CPlusPlus0x ?
1308                             diag::warn_cxx98_compat_friend_redefinition :
1309                             diag::err_redefinition)
1310                << Function->getDeclName();
1311              SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
1312              if (!SemaRef.getLangOptions().CPlusPlus0x)
1313                Function->setInvalidDecl();
1314              break;
1315            }
1316        }
1317      }
1318    }
1319  }
1320
1321  if (Function->isOverloadedOperator() && !DC->isRecord() &&
1322      PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1323    PrincipalDecl->setNonMemberOperator();
1324
1325  assert(!D->isDefaulted() && "only methods should be defaulted");
1326  return Function;
1327}
1328
1329Decl *
1330TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1331                                      TemplateParameterList *TemplateParams,
1332                                      bool IsClassScopeSpecialization) {
1333  FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1334  void *InsertPos = 0;
1335  if (FunctionTemplate && !TemplateParams) {
1336    // We are creating a function template specialization from a function
1337    // template. Check whether there is already a function template
1338    // specialization for this particular set of template arguments.
1339    std::pair<const TemplateArgument *, unsigned> Innermost
1340      = TemplateArgs.getInnermost();
1341
1342    FunctionDecl *SpecFunc
1343      = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
1344                                             InsertPos);
1345
1346    // If we already have a function template specialization, return it.
1347    if (SpecFunc)
1348      return SpecFunc;
1349  }
1350
1351  bool isFriend;
1352  if (FunctionTemplate)
1353    isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1354  else
1355    isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1356
1357  bool MergeWithParentScope = (TemplateParams != 0) ||
1358    !(isa<Decl>(Owner) &&
1359      cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1360  LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
1361
1362  // Instantiate enclosing template arguments for friends.
1363  SmallVector<TemplateParameterList *, 4> TempParamLists;
1364  unsigned NumTempParamLists = 0;
1365  if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1366    TempParamLists.set_size(NumTempParamLists);
1367    for (unsigned I = 0; I != NumTempParamLists; ++I) {
1368      TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1369      TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1370      if (!InstParams)
1371        return NULL;
1372      TempParamLists[I] = InstParams;
1373    }
1374  }
1375
1376  SmallVector<ParmVarDecl *, 4> Params;
1377  TypeSourceInfo *TInfo = D->getTypeSourceInfo();
1378  TInfo = SubstFunctionType(D, Params);
1379  if (!TInfo)
1380    return 0;
1381  QualType T = TInfo->getType();
1382
1383  // \brief If the type of this function, after ignoring parentheses,
1384  // is not *directly* a function type, then we're instantiating a function
1385  // that was declared via a typedef, e.g.,
1386  //
1387  //   typedef int functype(int, int);
1388  //   functype func;
1389  //
1390  // In this case, we'll just go instantiate the ParmVarDecls that we
1391  // synthesized in the method declaration.
1392  if (!isa<FunctionProtoType>(T.IgnoreParens())) {
1393    assert(!Params.size() && "Instantiating type could not yield parameters");
1394    SmallVector<QualType, 4> ParamTypes;
1395    if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(),
1396                               D->getNumParams(), TemplateArgs, ParamTypes,
1397                               &Params))
1398      return 0;
1399  }
1400
1401  NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1402  if (QualifierLoc) {
1403    QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1404                                                 TemplateArgs);
1405    if (!QualifierLoc)
1406      return 0;
1407  }
1408
1409  DeclContext *DC = Owner;
1410  if (isFriend) {
1411    if (QualifierLoc) {
1412      CXXScopeSpec SS;
1413      SS.Adopt(QualifierLoc);
1414      DC = SemaRef.computeDeclContext(SS);
1415
1416      if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
1417        return 0;
1418    } else {
1419      DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1420                                           D->getDeclContext(),
1421                                           TemplateArgs);
1422    }
1423    if (!DC) return 0;
1424  }
1425
1426  // Build the instantiated method declaration.
1427  CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1428  CXXMethodDecl *Method = 0;
1429
1430  SourceLocation StartLoc = D->getInnerLocStart();
1431  DeclarationNameInfo NameInfo
1432    = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1433  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
1434    Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
1435                                        StartLoc, NameInfo, T, TInfo,
1436                                        Constructor->isExplicit(),
1437                                        Constructor->isInlineSpecified(),
1438                                        false, /*isConstexpr*/ false);
1439  } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
1440    Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
1441                                       StartLoc, NameInfo, T, TInfo,
1442                                       Destructor->isInlineSpecified(),
1443                                       false);
1444  } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
1445    Method = CXXConversionDecl::Create(SemaRef.Context, Record,
1446                                       StartLoc, NameInfo, T, TInfo,
1447                                       Conversion->isInlineSpecified(),
1448                                       Conversion->isExplicit(),
1449                                       /*isConstexpr*/ false,
1450                                       Conversion->getLocEnd());
1451  } else {
1452    Method = CXXMethodDecl::Create(SemaRef.Context, Record,
1453                                   StartLoc, NameInfo, T, TInfo,
1454                                   D->isStatic(),
1455                                   D->getStorageClassAsWritten(),
1456                                   D->isInlineSpecified(),
1457                                   /*isConstexpr*/ false, D->getLocEnd());
1458  }
1459
1460  if (QualifierLoc)
1461    Method->setQualifierInfo(QualifierLoc);
1462
1463  if (TemplateParams) {
1464    // Our resulting instantiation is actually a function template, since we
1465    // are substituting only the outer template parameters. For example, given
1466    //
1467    //   template<typename T>
1468    //   struct X {
1469    //     template<typename U> void f(T, U);
1470    //   };
1471    //
1472    //   X<int> x;
1473    //
1474    // We are instantiating the member template "f" within X<int>, which means
1475    // substituting int for T, but leaving "f" as a member function template.
1476    // Build the function template itself.
1477    FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1478                                                    Method->getLocation(),
1479                                                    Method->getDeclName(),
1480                                                    TemplateParams, Method);
1481    if (isFriend) {
1482      FunctionTemplate->setLexicalDeclContext(Owner);
1483      FunctionTemplate->setObjectOfFriendDecl(true);
1484    } else if (D->isOutOfLine())
1485      FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
1486    Method->setDescribedFunctionTemplate(FunctionTemplate);
1487  } else if (FunctionTemplate) {
1488    // Record this function template specialization.
1489    std::pair<const TemplateArgument *, unsigned> Innermost
1490      = TemplateArgs.getInnermost();
1491    Method->setFunctionTemplateSpecialization(FunctionTemplate,
1492                         TemplateArgumentList::CreateCopy(SemaRef.Context,
1493                                                          Innermost.first,
1494                                                          Innermost.second),
1495                                              InsertPos);
1496  } else if (!isFriend) {
1497    // Record that this is an instantiation of a member function.
1498    Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
1499  }
1500
1501  // If we are instantiating a member function defined
1502  // out-of-line, the instantiation will have the same lexical
1503  // context (which will be a namespace scope) as the template.
1504  if (isFriend) {
1505    if (NumTempParamLists)
1506      Method->setTemplateParameterListsInfo(SemaRef.Context,
1507                                            NumTempParamLists,
1508                                            TempParamLists.data());
1509
1510    Method->setLexicalDeclContext(Owner);
1511    Method->setObjectOfFriendDecl(true);
1512  } else if (D->isOutOfLine())
1513    Method->setLexicalDeclContext(D->getLexicalDeclContext());
1514
1515  // Attach the parameters
1516  for (unsigned P = 0; P < Params.size(); ++P)
1517    Params[P]->setOwningFunction(Method);
1518  Method->setParams(Params);
1519
1520  if (InitMethodInstantiation(Method, D))
1521    Method->setInvalidDecl();
1522
1523  LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1524                        Sema::ForRedeclaration);
1525
1526  if (!FunctionTemplate || TemplateParams || isFriend) {
1527    SemaRef.LookupQualifiedName(Previous, Record);
1528
1529    // In C++, the previous declaration we find might be a tag type
1530    // (class or enum). In this case, the new declaration will hide the
1531    // tag type. Note that this does does not apply if we're declaring a
1532    // typedef (C++ [dcl.typedef]p4).
1533    if (Previous.isSingleTagDecl())
1534      Previous.clear();
1535  }
1536
1537  if (!IsClassScopeSpecialization)
1538    SemaRef.CheckFunctionDeclaration(0, Method, Previous, false);
1539
1540  if (D->isPure())
1541    SemaRef.CheckPureMethod(Method, SourceRange());
1542
1543  Method->setAccess(D->getAccess());
1544
1545  SemaRef.CheckOverrideControl(Method);
1546
1547  // If a function is defined as defaulted or deleted, mark it as such now.
1548  if (D->isDefaulted())
1549    Method->setDefaulted();
1550  if (D->isDeletedAsWritten())
1551    Method->setDeletedAsWritten();
1552
1553  if (FunctionTemplate) {
1554    // If there's a function template, let our caller handle it.
1555  } else if (Method->isInvalidDecl() && !Previous.empty()) {
1556    // Don't hide a (potentially) valid declaration with an invalid one.
1557  } else {
1558    NamedDecl *DeclToAdd = (TemplateParams
1559                            ? cast<NamedDecl>(FunctionTemplate)
1560                            : Method);
1561    if (isFriend)
1562      Record->makeDeclVisibleInContext(DeclToAdd);
1563    else if (!IsClassScopeSpecialization)
1564      Owner->addDecl(DeclToAdd);
1565  }
1566
1567  if (D->isExplicitlyDefaulted()) {
1568    SemaRef.SetDeclDefaulted(Method, Method->getLocation());
1569  } else {
1570    assert(!D->isDefaulted() &&
1571           "should not implicitly default uninstantiated function");
1572  }
1573
1574  return Method;
1575}
1576
1577Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
1578  return VisitCXXMethodDecl(D);
1579}
1580
1581Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
1582  return VisitCXXMethodDecl(D);
1583}
1584
1585Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
1586  return VisitCXXMethodDecl(D);
1587}
1588
1589ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
1590  return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0,
1591                                  llvm::Optional<unsigned>());
1592}
1593
1594Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1595                                                    TemplateTypeParmDecl *D) {
1596  // TODO: don't always clone when decls are refcounted.
1597  assert(D->getTypeForDecl()->isTemplateTypeParmType());
1598
1599  TemplateTypeParmDecl *Inst =
1600    TemplateTypeParmDecl::Create(SemaRef.Context, Owner,
1601                                 D->getLocStart(), D->getLocation(),
1602                                 D->getDepth() - TemplateArgs.getNumLevels(),
1603                                 D->getIndex(), D->getIdentifier(),
1604                                 D->wasDeclaredWithTypename(),
1605                                 D->isParameterPack());
1606  Inst->setAccess(AS_public);
1607
1608  if (D->hasDefaultArgument())
1609    Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
1610
1611  // Introduce this template parameter's instantiation into the instantiation
1612  // scope.
1613  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1614
1615  return Inst;
1616}
1617
1618Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1619                                                 NonTypeTemplateParmDecl *D) {
1620  // Substitute into the type of the non-type template parameter.
1621  TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
1622  SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
1623  SmallVector<QualType, 4> ExpandedParameterPackTypes;
1624  bool IsExpandedParameterPack = false;
1625  TypeSourceInfo *DI;
1626  QualType T;
1627  bool Invalid = false;
1628
1629  if (D->isExpandedParameterPack()) {
1630    // The non-type template parameter pack is an already-expanded pack
1631    // expansion of types. Substitute into each of the expanded types.
1632    ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
1633    ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
1634    for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1635      TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I),
1636                                               TemplateArgs,
1637                                               D->getLocation(),
1638                                               D->getDeclName());
1639      if (!NewDI)
1640        return 0;
1641
1642      ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1643      QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
1644                                                              D->getLocation());
1645      if (NewT.isNull())
1646        return 0;
1647      ExpandedParameterPackTypes.push_back(NewT);
1648    }
1649
1650    IsExpandedParameterPack = true;
1651    DI = D->getTypeSourceInfo();
1652    T = DI->getType();
1653  } else if (isa<PackExpansionTypeLoc>(TL)) {
1654    // The non-type template parameter pack's type is a pack expansion of types.
1655    // Determine whether we need to expand this parameter pack into separate
1656    // types.
1657    PackExpansionTypeLoc Expansion = cast<PackExpansionTypeLoc>(TL);
1658    TypeLoc Pattern = Expansion.getPatternLoc();
1659    SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1660    SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
1661
1662    // Determine whether the set of unexpanded parameter packs can and should
1663    // be expanded.
1664    bool Expand = true;
1665    bool RetainExpansion = false;
1666    llvm::Optional<unsigned> OrigNumExpansions
1667      = Expansion.getTypePtr()->getNumExpansions();
1668    llvm::Optional<unsigned> NumExpansions = OrigNumExpansions;
1669    if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
1670                                                Pattern.getSourceRange(),
1671                                                Unexpanded,
1672                                                TemplateArgs,
1673                                                Expand, RetainExpansion,
1674                                                NumExpansions))
1675      return 0;
1676
1677    if (Expand) {
1678      for (unsigned I = 0; I != *NumExpansions; ++I) {
1679        Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1680        TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
1681                                                  D->getLocation(),
1682                                                  D->getDeclName());
1683        if (!NewDI)
1684          return 0;
1685
1686        ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1687        QualType NewT = SemaRef.CheckNonTypeTemplateParameterType(
1688                                                              NewDI->getType(),
1689                                                              D->getLocation());
1690        if (NewT.isNull())
1691          return 0;
1692        ExpandedParameterPackTypes.push_back(NewT);
1693      }
1694
1695      // Note that we have an expanded parameter pack. The "type" of this
1696      // expanded parameter pack is the original expansion type, but callers
1697      // will end up using the expanded parameter pack types for type-checking.
1698      IsExpandedParameterPack = true;
1699      DI = D->getTypeSourceInfo();
1700      T = DI->getType();
1701    } else {
1702      // We cannot fully expand the pack expansion now, so substitute into the
1703      // pattern and create a new pack expansion type.
1704      Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1705      TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
1706                                                     D->getLocation(),
1707                                                     D->getDeclName());
1708      if (!NewPattern)
1709        return 0;
1710
1711      DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
1712                                      NumExpansions);
1713      if (!DI)
1714        return 0;
1715
1716      T = DI->getType();
1717    }
1718  } else {
1719    // Simple case: substitution into a parameter that is not a parameter pack.
1720    DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
1721                           D->getLocation(), D->getDeclName());
1722    if (!DI)
1723      return 0;
1724
1725    // Check that this type is acceptable for a non-type template parameter.
1726    T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
1727                                                  D->getLocation());
1728    if (T.isNull()) {
1729      T = SemaRef.Context.IntTy;
1730      Invalid = true;
1731    }
1732  }
1733
1734  NonTypeTemplateParmDecl *Param;
1735  if (IsExpandedParameterPack)
1736    Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
1737                                            D->getInnerLocStart(),
1738                                            D->getLocation(),
1739                                    D->getDepth() - TemplateArgs.getNumLevels(),
1740                                            D->getPosition(),
1741                                            D->getIdentifier(), T,
1742                                            DI,
1743                                            ExpandedParameterPackTypes.data(),
1744                                            ExpandedParameterPackTypes.size(),
1745                                    ExpandedParameterPackTypesAsWritten.data());
1746  else
1747    Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
1748                                            D->getInnerLocStart(),
1749                                            D->getLocation(),
1750                                    D->getDepth() - TemplateArgs.getNumLevels(),
1751                                            D->getPosition(),
1752                                            D->getIdentifier(), T,
1753                                            D->isParameterPack(), DI);
1754
1755  Param->setAccess(AS_public);
1756  if (Invalid)
1757    Param->setInvalidDecl();
1758
1759  Param->setDefaultArgument(D->getDefaultArgument(), false);
1760
1761  // Introduce this template parameter's instantiation into the instantiation
1762  // scope.
1763  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1764  return Param;
1765}
1766
1767Decl *
1768TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1769                                                  TemplateTemplateParmDecl *D) {
1770  // Instantiate the template parameter list of the template template parameter.
1771  TemplateParameterList *TempParams = D->getTemplateParameters();
1772  TemplateParameterList *InstParams;
1773  {
1774    // Perform the actual substitution of template parameters within a new,
1775    // local instantiation scope.
1776    LocalInstantiationScope Scope(SemaRef);
1777    InstParams = SubstTemplateParams(TempParams);
1778    if (!InstParams)
1779      return NULL;
1780  }
1781
1782  // Build the template template parameter.
1783  TemplateTemplateParmDecl *Param
1784    = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1785                                   D->getDepth() - TemplateArgs.getNumLevels(),
1786                                       D->getPosition(), D->isParameterPack(),
1787                                       D->getIdentifier(), InstParams);
1788  Param->setDefaultArgument(D->getDefaultArgument(), false);
1789  Param->setAccess(AS_public);
1790
1791  // Introduce this template parameter's instantiation into the instantiation
1792  // scope.
1793  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1794
1795  return Param;
1796}
1797
1798Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1799  // Using directives are never dependent (and never contain any types or
1800  // expressions), so they require no explicit instantiation work.
1801
1802  UsingDirectiveDecl *Inst
1803    = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1804                                 D->getNamespaceKeyLocation(),
1805                                 D->getQualifierLoc(),
1806                                 D->getIdentLocation(),
1807                                 D->getNominatedNamespace(),
1808                                 D->getCommonAncestor());
1809  Owner->addDecl(Inst);
1810  return Inst;
1811}
1812
1813Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
1814
1815  // The nested name specifier may be dependent, for example
1816  //     template <typename T> struct t {
1817  //       struct s1 { T f1(); };
1818  //       struct s2 : s1 { using s1::f1; };
1819  //     };
1820  //     template struct t<int>;
1821  // Here, in using s1::f1, s1 refers to t<T>::s1;
1822  // we need to substitute for t<int>::s1.
1823  NestedNameSpecifierLoc QualifierLoc
1824    = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
1825                                          TemplateArgs);
1826  if (!QualifierLoc)
1827    return 0;
1828
1829  // The name info is non-dependent, so no transformation
1830  // is required.
1831  DeclarationNameInfo NameInfo = D->getNameInfo();
1832
1833  // We only need to do redeclaration lookups if we're in a class
1834  // scope (in fact, it's not really even possible in non-class
1835  // scopes).
1836  bool CheckRedeclaration = Owner->isRecord();
1837
1838  LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
1839                    Sema::ForRedeclaration);
1840
1841  UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
1842                                       D->getUsingLocation(),
1843                                       QualifierLoc,
1844                                       NameInfo,
1845                                       D->isTypeName());
1846
1847  CXXScopeSpec SS;
1848  SS.Adopt(QualifierLoc);
1849  if (CheckRedeclaration) {
1850    Prev.setHideTags(false);
1851    SemaRef.LookupQualifiedName(Prev, Owner);
1852
1853    // Check for invalid redeclarations.
1854    if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1855                                            D->isTypeName(), SS,
1856                                            D->getLocation(), Prev))
1857      NewUD->setInvalidDecl();
1858
1859  }
1860
1861  if (!NewUD->isInvalidDecl() &&
1862      SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
1863                                      D->getLocation()))
1864    NewUD->setInvalidDecl();
1865
1866  SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1867  NewUD->setAccess(D->getAccess());
1868  Owner->addDecl(NewUD);
1869
1870  // Don't process the shadow decls for an invalid decl.
1871  if (NewUD->isInvalidDecl())
1872    return NewUD;
1873
1874  bool isFunctionScope = Owner->isFunctionOrMethod();
1875
1876  // Process the shadow decls.
1877  for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1878         I != E; ++I) {
1879    UsingShadowDecl *Shadow = *I;
1880    NamedDecl *InstTarget =
1881      cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
1882                                                          Shadow->getLocation(),
1883                                                        Shadow->getTargetDecl(),
1884                                                           TemplateArgs));
1885    if (!InstTarget)
1886      return 0;
1887
1888    if (CheckRedeclaration &&
1889        SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1890      continue;
1891
1892    UsingShadowDecl *InstShadow
1893      = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1894    SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
1895
1896    if (isFunctionScope)
1897      SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
1898  }
1899
1900  return NewUD;
1901}
1902
1903Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
1904  // Ignore these;  we handle them in bulk when processing the UsingDecl.
1905  return 0;
1906}
1907
1908Decl * TemplateDeclInstantiator
1909    ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
1910  NestedNameSpecifierLoc QualifierLoc
1911    = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
1912                                          TemplateArgs);
1913  if (!QualifierLoc)
1914    return 0;
1915
1916  CXXScopeSpec SS;
1917  SS.Adopt(QualifierLoc);
1918
1919  // Since NameInfo refers to a typename, it cannot be a C++ special name.
1920  // Hence, no tranformation is required for it.
1921  DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
1922  NamedDecl *UD =
1923    SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1924                                  D->getUsingLoc(), SS, NameInfo, 0,
1925                                  /*instantiation*/ true,
1926                                  /*typename*/ true, D->getTypenameLoc());
1927  if (UD)
1928    SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1929
1930  return UD;
1931}
1932
1933Decl * TemplateDeclInstantiator
1934    ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1935  NestedNameSpecifierLoc QualifierLoc
1936      = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs);
1937  if (!QualifierLoc)
1938    return 0;
1939
1940  CXXScopeSpec SS;
1941  SS.Adopt(QualifierLoc);
1942
1943  DeclarationNameInfo NameInfo
1944    = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1945
1946  NamedDecl *UD =
1947    SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1948                                  D->getUsingLoc(), SS, NameInfo, 0,
1949                                  /*instantiation*/ true,
1950                                  /*typename*/ false, SourceLocation());
1951  if (UD)
1952    SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1953
1954  return UD;
1955}
1956
1957
1958Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
1959                                     ClassScopeFunctionSpecializationDecl *Decl) {
1960  CXXMethodDecl *OldFD = Decl->getSpecialization();
1961  CXXMethodDecl *NewFD = cast<CXXMethodDecl>(VisitCXXMethodDecl(OldFD, 0, true));
1962
1963  LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName,
1964                        Sema::ForRedeclaration);
1965
1966  SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext);
1967  if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, 0, Previous)) {
1968    NewFD->setInvalidDecl();
1969    return NewFD;
1970  }
1971
1972  // Associate the specialization with the pattern.
1973  FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl());
1974  assert(Specialization && "Class scope Specialization is null");
1975  SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD);
1976
1977  return NewFD;
1978}
1979
1980Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
1981                      const MultiLevelTemplateArgumentList &TemplateArgs) {
1982  TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
1983  if (D->isInvalidDecl())
1984    return 0;
1985
1986  return Instantiator.Visit(D);
1987}
1988
1989/// \brief Instantiates a nested template parameter list in the current
1990/// instantiation context.
1991///
1992/// \param L The parameter list to instantiate
1993///
1994/// \returns NULL if there was an error
1995TemplateParameterList *
1996TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
1997  // Get errors for all the parameters before bailing out.
1998  bool Invalid = false;
1999
2000  unsigned N = L->size();
2001  typedef SmallVector<NamedDecl *, 8> ParamVector;
2002  ParamVector Params;
2003  Params.reserve(N);
2004  for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
2005       PI != PE; ++PI) {
2006    NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
2007    Params.push_back(D);
2008    Invalid = Invalid || !D || D->isInvalidDecl();
2009  }
2010
2011  // Clean up if we had an error.
2012  if (Invalid)
2013    return NULL;
2014
2015  TemplateParameterList *InstL
2016    = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
2017                                    L->getLAngleLoc(), &Params.front(), N,
2018                                    L->getRAngleLoc());
2019  return InstL;
2020}
2021
2022/// \brief Instantiate the declaration of a class template partial
2023/// specialization.
2024///
2025/// \param ClassTemplate the (instantiated) class template that is partially
2026// specialized by the instantiation of \p PartialSpec.
2027///
2028/// \param PartialSpec the (uninstantiated) class template partial
2029/// specialization that we are instantiating.
2030///
2031/// \returns The instantiated partial specialization, if successful; otherwise,
2032/// NULL to indicate an error.
2033ClassTemplatePartialSpecializationDecl *
2034TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
2035                                            ClassTemplateDecl *ClassTemplate,
2036                          ClassTemplatePartialSpecializationDecl *PartialSpec) {
2037  // Create a local instantiation scope for this class template partial
2038  // specialization, which will contain the instantiations of the template
2039  // parameters.
2040  LocalInstantiationScope Scope(SemaRef);
2041
2042  // Substitute into the template parameters of the class template partial
2043  // specialization.
2044  TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2045  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2046  if (!InstParams)
2047    return 0;
2048
2049  // Substitute into the template arguments of the class template partial
2050  // specialization.
2051  TemplateArgumentListInfo InstTemplateArgs; // no angle locations
2052  if (SemaRef.Subst(PartialSpec->getTemplateArgsAsWritten(),
2053                    PartialSpec->getNumTemplateArgsAsWritten(),
2054                    InstTemplateArgs, TemplateArgs))
2055    return 0;
2056
2057  // Check that the template argument list is well-formed for this
2058  // class template.
2059  SmallVector<TemplateArgument, 4> Converted;
2060  if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
2061                                        PartialSpec->getLocation(),
2062                                        InstTemplateArgs,
2063                                        false,
2064                                        Converted))
2065    return 0;
2066
2067  // Figure out where to insert this class template partial specialization
2068  // in the member template's set of class template partial specializations.
2069  void *InsertPos = 0;
2070  ClassTemplateSpecializationDecl *PrevDecl
2071    = ClassTemplate->findPartialSpecialization(Converted.data(),
2072                                               Converted.size(), InsertPos);
2073
2074  // Build the canonical type that describes the converted template
2075  // arguments of the class template partial specialization.
2076  QualType CanonType
2077    = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
2078                                                    Converted.data(),
2079                                                    Converted.size());
2080
2081  // Build the fully-sugared type for this class template
2082  // specialization as the user wrote in the specialization
2083  // itself. This means that we'll pretty-print the type retrieved
2084  // from the specialization's declaration the way that the user
2085  // actually wrote the specialization, rather than formatting the
2086  // name based on the "canonical" representation used to store the
2087  // template arguments in the specialization.
2088  TypeSourceInfo *WrittenTy
2089    = SemaRef.Context.getTemplateSpecializationTypeInfo(
2090                                                    TemplateName(ClassTemplate),
2091                                                    PartialSpec->getLocation(),
2092                                                    InstTemplateArgs,
2093                                                    CanonType);
2094
2095  if (PrevDecl) {
2096    // We've already seen a partial specialization with the same template
2097    // parameters and template arguments. This can happen, for example, when
2098    // substituting the outer template arguments ends up causing two
2099    // class template partial specializations of a member class template
2100    // to have identical forms, e.g.,
2101    //
2102    //   template<typename T, typename U>
2103    //   struct Outer {
2104    //     template<typename X, typename Y> struct Inner;
2105    //     template<typename Y> struct Inner<T, Y>;
2106    //     template<typename Y> struct Inner<U, Y>;
2107    //   };
2108    //
2109    //   Outer<int, int> outer; // error: the partial specializations of Inner
2110    //                          // have the same signature.
2111    SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
2112      << WrittenTy->getType();
2113    SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
2114      << SemaRef.Context.getTypeDeclType(PrevDecl);
2115    return 0;
2116  }
2117
2118
2119  // Create the class template partial specialization declaration.
2120  ClassTemplatePartialSpecializationDecl *InstPartialSpec
2121    = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
2122                                                     PartialSpec->getTagKind(),
2123                                                     Owner,
2124                                                     PartialSpec->getLocStart(),
2125                                                     PartialSpec->getLocation(),
2126                                                     InstParams,
2127                                                     ClassTemplate,
2128                                                     Converted.data(),
2129                                                     Converted.size(),
2130                                                     InstTemplateArgs,
2131                                                     CanonType,
2132                                                     0,
2133                             ClassTemplate->getNextPartialSpecSequenceNumber());
2134  // Substitute the nested name specifier, if any.
2135  if (SubstQualifier(PartialSpec, InstPartialSpec))
2136    return 0;
2137
2138  InstPartialSpec->setInstantiatedFromMember(PartialSpec);
2139  InstPartialSpec->setTypeAsWritten(WrittenTy);
2140
2141  // Add this partial specialization to the set of class template partial
2142  // specializations.
2143  ClassTemplate->AddPartialSpecialization(InstPartialSpec, InsertPos);
2144  return InstPartialSpec;
2145}
2146
2147TypeSourceInfo*
2148TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
2149                              SmallVectorImpl<ParmVarDecl *> &Params) {
2150  TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
2151  assert(OldTInfo && "substituting function without type source info");
2152  assert(Params.empty() && "parameter vector is non-empty at start");
2153  TypeSourceInfo *NewTInfo
2154    = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
2155                                    D->getTypeSpecStartLoc(),
2156                                    D->getDeclName());
2157  if (!NewTInfo)
2158    return 0;
2159
2160  if (NewTInfo != OldTInfo) {
2161    // Get parameters from the new type info.
2162    TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
2163    if (FunctionProtoTypeLoc *OldProtoLoc
2164                                  = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
2165      TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
2166      FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL);
2167      assert(NewProtoLoc && "Missing prototype?");
2168      unsigned NewIdx = 0, NumNewParams = NewProtoLoc->getNumArgs();
2169      for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc->getNumArgs();
2170           OldIdx != NumOldParams; ++OldIdx) {
2171        ParmVarDecl *OldParam = OldProtoLoc->getArg(OldIdx);
2172        if (!OldParam->isParameterPack() ||
2173            (NewIdx < NumNewParams &&
2174             NewProtoLoc->getArg(NewIdx)->isParameterPack())) {
2175          // Simple case: normal parameter, or a parameter pack that's
2176          // instantiated to a (still-dependent) parameter pack.
2177          ParmVarDecl *NewParam = NewProtoLoc->getArg(NewIdx++);
2178          Params.push_back(NewParam);
2179          SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam,
2180                                                               NewParam);
2181          continue;
2182        }
2183
2184        // Parameter pack: make the instantiation an argument pack.
2185        SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(
2186                                                                      OldParam);
2187        unsigned NumArgumentsInExpansion
2188          = SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
2189                                               TemplateArgs);
2190        while (NumArgumentsInExpansion--) {
2191          ParmVarDecl *NewParam = NewProtoLoc->getArg(NewIdx++);
2192          Params.push_back(NewParam);
2193          SemaRef.CurrentInstantiationScope->InstantiatedLocalPackArg(OldParam,
2194                                                                      NewParam);
2195        }
2196      }
2197    }
2198  } else {
2199    // The function type itself was not dependent and therefore no
2200    // substitution occurred. However, we still need to instantiate
2201    // the function parameters themselves.
2202    TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
2203    if (FunctionProtoTypeLoc *OldProtoLoc
2204                                    = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
2205      for (unsigned i = 0, i_end = OldProtoLoc->getNumArgs(); i != i_end; ++i) {
2206        ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc->getArg(i));
2207        if (!Parm)
2208          return 0;
2209        Params.push_back(Parm);
2210      }
2211    }
2212  }
2213  return NewTInfo;
2214}
2215
2216/// \brief Initializes the common fields of an instantiation function
2217/// declaration (New) from the corresponding fields of its template (Tmpl).
2218///
2219/// \returns true if there was an error
2220bool
2221TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
2222                                                    FunctionDecl *Tmpl) {
2223  if (Tmpl->isDeletedAsWritten())
2224    New->setDeletedAsWritten();
2225
2226  // If we are performing substituting explicitly-specified template arguments
2227  // or deduced template arguments into a function template and we reach this
2228  // point, we are now past the point where SFINAE applies and have committed
2229  // to keeping the new function template specialization. We therefore
2230  // convert the active template instantiation for the function template
2231  // into a template instantiation for this specific function template
2232  // specialization, which is not a SFINAE context, so that we diagnose any
2233  // further errors in the declaration itself.
2234  typedef Sema::ActiveTemplateInstantiation ActiveInstType;
2235  ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
2236  if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
2237      ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
2238    if (FunctionTemplateDecl *FunTmpl
2239          = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
2240      assert(FunTmpl->getTemplatedDecl() == Tmpl &&
2241             "Deduction from the wrong function template?");
2242      (void) FunTmpl;
2243      ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
2244      ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
2245      --SemaRef.NonInstantiationEntries;
2246    }
2247  }
2248
2249  const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
2250  assert(Proto && "Function template without prototype?");
2251
2252  if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
2253    // The function has an exception specification or a "noreturn"
2254    // attribute. Substitute into each of the exception types.
2255    SmallVector<QualType, 4> Exceptions;
2256    for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
2257      // FIXME: Poor location information!
2258      if (const PackExpansionType *PackExpansion
2259            = Proto->getExceptionType(I)->getAs<PackExpansionType>()) {
2260        // We have a pack expansion. Instantiate it.
2261        SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2262        SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
2263                                                Unexpanded);
2264        assert(!Unexpanded.empty() &&
2265               "Pack expansion without parameter packs?");
2266
2267        bool Expand = false;
2268        bool RetainExpansion = false;
2269        llvm::Optional<unsigned> NumExpansions
2270                                          = PackExpansion->getNumExpansions();
2271        if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(),
2272                                                    SourceRange(),
2273                                                    Unexpanded,
2274                                                    TemplateArgs,
2275                                                    Expand,
2276                                                    RetainExpansion,
2277                                                    NumExpansions))
2278          break;
2279
2280        if (!Expand) {
2281          // We can't expand this pack expansion into separate arguments yet;
2282          // just substitute into the pattern and create a new pack expansion
2283          // type.
2284          Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2285          QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2286                                         TemplateArgs,
2287                                       New->getLocation(), New->getDeclName());
2288          if (T.isNull())
2289            break;
2290
2291          T = SemaRef.Context.getPackExpansionType(T, NumExpansions);
2292          Exceptions.push_back(T);
2293          continue;
2294        }
2295
2296        // Substitute into the pack expansion pattern for each template
2297        bool Invalid = false;
2298        for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
2299          Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx);
2300
2301          QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2302                                         TemplateArgs,
2303                                       New->getLocation(), New->getDeclName());
2304          if (T.isNull()) {
2305            Invalid = true;
2306            break;
2307          }
2308
2309          Exceptions.push_back(T);
2310        }
2311
2312        if (Invalid)
2313          break;
2314
2315        continue;
2316      }
2317
2318      QualType T
2319        = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
2320                            New->getLocation(), New->getDeclName());
2321      if (T.isNull() ||
2322          SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
2323        continue;
2324
2325      Exceptions.push_back(T);
2326    }
2327    Expr *NoexceptExpr = 0;
2328    if (Expr *OldNoexceptExpr = Proto->getNoexceptExpr()) {
2329      EnterExpressionEvaluationContext Unevaluated(SemaRef,
2330                                                   Sema::ConstantEvaluated);
2331      ExprResult E = SemaRef.SubstExpr(OldNoexceptExpr, TemplateArgs);
2332      if (E.isUsable())
2333        E = SemaRef.CheckBooleanCondition(E.get(), E.get()->getLocStart());
2334
2335      if (E.isUsable()) {
2336        SourceLocation ErrLoc;
2337        llvm::APSInt NoexceptVal;
2338        NoexceptExpr = E.take();
2339        if (!NoexceptExpr->isTypeDependent() &&
2340            !NoexceptExpr->isValueDependent() &&
2341            !NoexceptExpr->isIntegerConstantExpr(NoexceptVal, SemaRef.Context,
2342                                                 &ErrLoc, /*evaluated=*/false)){
2343          SemaRef.Diag(ErrLoc, diag::err_noexcept_needs_constant_expression)
2344            << NoexceptExpr->getSourceRange();
2345          NoexceptExpr = 0;
2346        }
2347      }
2348    }
2349
2350    // Rebuild the function type
2351
2352    FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
2353    EPI.ExceptionSpecType = Proto->getExceptionSpecType();
2354    EPI.NumExceptions = Exceptions.size();
2355    EPI.Exceptions = Exceptions.data();
2356    EPI.NoexceptExpr = NoexceptExpr;
2357    EPI.ExtInfo = Proto->getExtInfo();
2358
2359    const FunctionProtoType *NewProto
2360      = New->getType()->getAs<FunctionProtoType>();
2361    assert(NewProto && "Template instantiation without function prototype?");
2362    New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
2363                                                 NewProto->arg_type_begin(),
2364                                                 NewProto->getNumArgs(),
2365                                                 EPI));
2366  }
2367
2368  // C++0x [dcl.constexpr]p6: If the instantiated template specialization of
2369  // a constexpr function template satisfies the requirements for a constexpr
2370  // function, then it is a constexpr function.
2371  if (Tmpl->isConstexpr() &&
2372      SemaRef.CheckConstexprFunctionDecl(New, Sema::CCK_Instantiation))
2373    New->setConstexpr(true);
2374
2375  const FunctionDecl* Definition = Tmpl;
2376
2377  // Get the definition. Leaves the variable unchanged if undefined.
2378  Tmpl->isDefined(Definition);
2379
2380  SemaRef.InstantiateAttrs(TemplateArgs, Definition, New);
2381
2382  return false;
2383}
2384
2385/// \brief Initializes common fields of an instantiated method
2386/// declaration (New) from the corresponding fields of its template
2387/// (Tmpl).
2388///
2389/// \returns true if there was an error
2390bool
2391TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
2392                                                  CXXMethodDecl *Tmpl) {
2393  if (InitFunctionInstantiation(New, Tmpl))
2394    return true;
2395
2396  New->setAccess(Tmpl->getAccess());
2397  if (Tmpl->isVirtualAsWritten())
2398    New->setVirtualAsWritten(true);
2399
2400  // FIXME: attributes
2401  // FIXME: New needs a pointer to Tmpl
2402  return false;
2403}
2404
2405/// \brief Instantiate the definition of the given function from its
2406/// template.
2407///
2408/// \param PointOfInstantiation the point at which the instantiation was
2409/// required. Note that this is not precisely a "point of instantiation"
2410/// for the function, but it's close.
2411///
2412/// \param Function the already-instantiated declaration of a
2413/// function template specialization or member function of a class template
2414/// specialization.
2415///
2416/// \param Recursive if true, recursively instantiates any functions that
2417/// are required by this instantiation.
2418///
2419/// \param DefinitionRequired if true, then we are performing an explicit
2420/// instantiation where the body of the function is required. Complain if
2421/// there is no such body.
2422void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
2423                                         FunctionDecl *Function,
2424                                         bool Recursive,
2425                                         bool DefinitionRequired) {
2426  if (Function->isInvalidDecl() || Function->isDefined())
2427    return;
2428
2429  // Never instantiate an explicit specialization except if it is a class scope
2430  // explicit specialization.
2431  if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
2432      !Function->getClassScopeSpecializationPattern())
2433    return;
2434
2435  // Find the function body that we'll be substituting.
2436  const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
2437  assert(PatternDecl && "instantiating a non-template");
2438
2439  Stmt *Pattern = PatternDecl->getBody(PatternDecl);
2440  assert(PatternDecl && "template definition is not a template");
2441  if (!Pattern) {
2442    // Try to find a defaulted definition
2443    PatternDecl->isDefined(PatternDecl);
2444  }
2445  assert(PatternDecl && "template definition is not a template");
2446
2447  // Postpone late parsed template instantiations.
2448  if (PatternDecl->isLateTemplateParsed() &&
2449      !LateTemplateParser) {
2450    PendingInstantiations.push_back(
2451      std::make_pair(Function, PointOfInstantiation));
2452    return;
2453  }
2454
2455  // Call the LateTemplateParser callback if there a need to late parse
2456  // a templated function definition.
2457  if (!Pattern && PatternDecl->isLateTemplateParsed() &&
2458      LateTemplateParser) {
2459    LateTemplateParser(OpaqueParser, PatternDecl);
2460    Pattern = PatternDecl->getBody(PatternDecl);
2461  }
2462
2463  if (!Pattern && !PatternDecl->isDefaulted()) {
2464    if (DefinitionRequired) {
2465      if (Function->getPrimaryTemplate())
2466        Diag(PointOfInstantiation,
2467             diag::err_explicit_instantiation_undefined_func_template)
2468          << Function->getPrimaryTemplate();
2469      else
2470        Diag(PointOfInstantiation,
2471             diag::err_explicit_instantiation_undefined_member)
2472          << 1 << Function->getDeclName() << Function->getDeclContext();
2473
2474      if (PatternDecl)
2475        Diag(PatternDecl->getLocation(),
2476             diag::note_explicit_instantiation_here);
2477      Function->setInvalidDecl();
2478    } else if (Function->getTemplateSpecializationKind()
2479                 == TSK_ExplicitInstantiationDefinition) {
2480      PendingInstantiations.push_back(
2481        std::make_pair(Function, PointOfInstantiation));
2482    }
2483
2484    return;
2485  }
2486
2487  // C++0x [temp.explicit]p9:
2488  //   Except for inline functions, other explicit instantiation declarations
2489  //   have the effect of suppressing the implicit instantiation of the entity
2490  //   to which they refer.
2491  if (Function->getTemplateSpecializationKind()
2492        == TSK_ExplicitInstantiationDeclaration &&
2493      !PatternDecl->isInlined())
2494    return;
2495
2496  InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
2497  if (Inst)
2498    return;
2499
2500  // Copy the inner loc start from the pattern.
2501  Function->setInnerLocStart(PatternDecl->getInnerLocStart());
2502
2503  // If we're performing recursive template instantiation, create our own
2504  // queue of pending implicit instantiations that we will instantiate later,
2505  // while we're still within our own instantiation context.
2506  SmallVector<VTableUse, 16> SavedVTableUses;
2507  std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
2508  if (Recursive) {
2509    VTableUses.swap(SavedVTableUses);
2510    PendingInstantiations.swap(SavedPendingInstantiations);
2511  }
2512
2513  EnterExpressionEvaluationContext EvalContext(*this,
2514                                               Sema::PotentiallyEvaluated);
2515  ActOnStartOfFunctionDef(0, Function);
2516
2517  // Introduce a new scope where local variable instantiations will be
2518  // recorded, unless we're actually a member function within a local
2519  // class, in which case we need to merge our results with the parent
2520  // scope (of the enclosing function).
2521  bool MergeWithParentScope = false;
2522  if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
2523    MergeWithParentScope = Rec->isLocalClass();
2524
2525  LocalInstantiationScope Scope(*this, MergeWithParentScope);
2526
2527  // Introduce the instantiated function parameters into the local
2528  // instantiation scope, and set the parameter names to those used
2529  // in the template.
2530  unsigned FParamIdx = 0;
2531  for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
2532    const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
2533    if (!PatternParam->isParameterPack()) {
2534      // Simple case: not a parameter pack.
2535      assert(FParamIdx < Function->getNumParams());
2536      ParmVarDecl *FunctionParam = Function->getParamDecl(I);
2537      FunctionParam->setDeclName(PatternParam->getDeclName());
2538      Scope.InstantiatedLocal(PatternParam, FunctionParam);
2539      ++FParamIdx;
2540      continue;
2541    }
2542
2543    // Expand the parameter pack.
2544    Scope.MakeInstantiatedLocalArgPack(PatternParam);
2545    for (unsigned NumFParams = Function->getNumParams();
2546         FParamIdx < NumFParams;
2547         ++FParamIdx) {
2548      ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2549      FunctionParam->setDeclName(PatternParam->getDeclName());
2550      Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
2551    }
2552  }
2553
2554  // Enter the scope of this instantiation. We don't use
2555  // PushDeclContext because we don't have a scope.
2556  Sema::ContextRAII savedContext(*this, Function);
2557
2558  MultiLevelTemplateArgumentList TemplateArgs =
2559    getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
2560
2561  if (PatternDecl->isDefaulted()) {
2562    ActOnFinishFunctionBody(Function, 0, /*IsInstantiation=*/true);
2563
2564    SetDeclDefaulted(Function, PatternDecl->getLocation());
2565  } else {
2566    // If this is a constructor, instantiate the member initializers.
2567    if (const CXXConstructorDecl *Ctor =
2568          dyn_cast<CXXConstructorDecl>(PatternDecl)) {
2569      InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
2570                                 TemplateArgs);
2571    }
2572
2573    // Instantiate the function body.
2574    StmtResult Body = SubstStmt(Pattern, TemplateArgs);
2575
2576    if (Body.isInvalid())
2577      Function->setInvalidDecl();
2578
2579    ActOnFinishFunctionBody(Function, Body.get(),
2580                            /*IsInstantiation=*/true);
2581  }
2582
2583  PerformDependentDiagnostics(PatternDecl, TemplateArgs);
2584
2585  savedContext.pop();
2586
2587  DeclGroupRef DG(Function);
2588  Consumer.HandleTopLevelDecl(DG);
2589
2590  // This class may have local implicit instantiations that need to be
2591  // instantiation within this scope.
2592  PerformPendingInstantiations(/*LocalOnly=*/true);
2593  Scope.Exit();
2594
2595  if (Recursive) {
2596    // Define any pending vtables.
2597    DefineUsedVTables();
2598
2599    // Instantiate any pending implicit instantiations found during the
2600    // instantiation of this template.
2601    PerformPendingInstantiations();
2602
2603    // Restore the set of pending vtables.
2604    assert(VTableUses.empty() &&
2605           "VTableUses should be empty before it is discarded.");
2606    VTableUses.swap(SavedVTableUses);
2607
2608    // Restore the set of pending implicit instantiations.
2609    assert(PendingInstantiations.empty() &&
2610           "PendingInstantiations should be empty before it is discarded.");
2611    PendingInstantiations.swap(SavedPendingInstantiations);
2612  }
2613}
2614
2615/// \brief Instantiate the definition of the given variable from its
2616/// template.
2617///
2618/// \param PointOfInstantiation the point at which the instantiation was
2619/// required. Note that this is not precisely a "point of instantiation"
2620/// for the function, but it's close.
2621///
2622/// \param Var the already-instantiated declaration of a static member
2623/// variable of a class template specialization.
2624///
2625/// \param Recursive if true, recursively instantiates any functions that
2626/// are required by this instantiation.
2627///
2628/// \param DefinitionRequired if true, then we are performing an explicit
2629/// instantiation where an out-of-line definition of the member variable
2630/// is required. Complain if there is no such definition.
2631void Sema::InstantiateStaticDataMemberDefinition(
2632                                          SourceLocation PointOfInstantiation,
2633                                                 VarDecl *Var,
2634                                                 bool Recursive,
2635                                                 bool DefinitionRequired) {
2636  if (Var->isInvalidDecl())
2637    return;
2638
2639  // Find the out-of-line definition of this static data member.
2640  VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
2641  assert(Def && "This data member was not instantiated from a template?");
2642  assert(Def->isStaticDataMember() && "Not a static data member?");
2643  Def = Def->getOutOfLineDefinition();
2644
2645  if (!Def) {
2646    // We did not find an out-of-line definition of this static data member,
2647    // so we won't perform any instantiation. Rather, we rely on the user to
2648    // instantiate this definition (or provide a specialization for it) in
2649    // another translation unit.
2650    if (DefinitionRequired) {
2651      Def = Var->getInstantiatedFromStaticDataMember();
2652      Diag(PointOfInstantiation,
2653           diag::err_explicit_instantiation_undefined_member)
2654        << 2 << Var->getDeclName() << Var->getDeclContext();
2655      Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
2656    } else if (Var->getTemplateSpecializationKind()
2657                 == TSK_ExplicitInstantiationDefinition) {
2658      PendingInstantiations.push_back(
2659        std::make_pair(Var, PointOfInstantiation));
2660    }
2661
2662    return;
2663  }
2664
2665  // Never instantiate an explicit specialization.
2666  if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2667    return;
2668
2669  // C++0x [temp.explicit]p9:
2670  //   Except for inline functions, other explicit instantiation declarations
2671  //   have the effect of suppressing the implicit instantiation of the entity
2672  //   to which they refer.
2673  if (Var->getTemplateSpecializationKind()
2674        == TSK_ExplicitInstantiationDeclaration)
2675    return;
2676
2677  // If we already have a definition, we're done.
2678  if (Var->getDefinition())
2679    return;
2680
2681  InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
2682  if (Inst)
2683    return;
2684
2685  // If we're performing recursive template instantiation, create our own
2686  // queue of pending implicit instantiations that we will instantiate later,
2687  // while we're still within our own instantiation context.
2688  SmallVector<VTableUse, 16> SavedVTableUses;
2689  std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
2690  if (Recursive) {
2691    VTableUses.swap(SavedVTableUses);
2692    PendingInstantiations.swap(SavedPendingInstantiations);
2693  }
2694
2695  // Enter the scope of this instantiation. We don't use
2696  // PushDeclContext because we don't have a scope.
2697  ContextRAII previousContext(*this, Var->getDeclContext());
2698
2699  VarDecl *OldVar = Var;
2700  Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
2701                                        getTemplateInstantiationArgs(Var)));
2702
2703  previousContext.pop();
2704
2705  if (Var) {
2706    MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
2707    assert(MSInfo && "Missing member specialization information?");
2708    Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
2709                                       MSInfo->getPointOfInstantiation());
2710    DeclGroupRef DG(Var);
2711    Consumer.HandleTopLevelDecl(DG);
2712  }
2713
2714  if (Recursive) {
2715    // Define any newly required vtables.
2716    DefineUsedVTables();
2717
2718    // Instantiate any pending implicit instantiations found during the
2719    // instantiation of this template.
2720    PerformPendingInstantiations();
2721
2722    // Restore the set of pending vtables.
2723    assert(VTableUses.empty() &&
2724           "VTableUses should be empty before it is discarded, "
2725           "while instantiating static data member.");
2726    VTableUses.swap(SavedVTableUses);
2727
2728    // Restore the set of pending implicit instantiations.
2729    assert(PendingInstantiations.empty() &&
2730           "PendingInstantiations should be empty before it is discarded, "
2731           "while instantiating static data member.");
2732    PendingInstantiations.swap(SavedPendingInstantiations);
2733  }
2734}
2735
2736static MultiInitializer CreateMultiInitializer(SmallVectorImpl<Expr*> &Args,
2737                                               const CXXCtorInitializer *Init) {
2738  // FIXME: This is a hack that will do slightly the wrong thing for an
2739  // initializer of the form foo({...}).
2740  // The right thing to do would be to modify InstantiateInitializer to create
2741  // the MultiInitializer.
2742  if (Args.size() == 1 && isa<InitListExpr>(Args[0]))
2743    return MultiInitializer(Args[0]);
2744  return MultiInitializer(Init->getLParenLoc(), Args.data(),
2745                          Args.size(), Init->getRParenLoc());
2746}
2747
2748void
2749Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
2750                                 const CXXConstructorDecl *Tmpl,
2751                           const MultiLevelTemplateArgumentList &TemplateArgs) {
2752
2753  SmallVector<CXXCtorInitializer*, 4> NewInits;
2754  bool AnyErrors = false;
2755
2756  // Instantiate all the initializers.
2757  for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
2758                                            InitsEnd = Tmpl->init_end();
2759       Inits != InitsEnd; ++Inits) {
2760    CXXCtorInitializer *Init = *Inits;
2761
2762    // Only instantiate written initializers, let Sema re-construct implicit
2763    // ones.
2764    if (!Init->isWritten())
2765      continue;
2766
2767    SourceLocation LParenLoc, RParenLoc;
2768    ASTOwningVector<Expr*> NewArgs(*this);
2769
2770    SourceLocation EllipsisLoc;
2771
2772    if (Init->isPackExpansion()) {
2773      // This is a pack expansion. We should expand it now.
2774      TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
2775      SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2776      collectUnexpandedParameterPacks(BaseTL, Unexpanded);
2777      bool ShouldExpand = false;
2778      bool RetainExpansion = false;
2779      llvm::Optional<unsigned> NumExpansions;
2780      if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
2781                                          BaseTL.getSourceRange(),
2782                                          Unexpanded,
2783                                          TemplateArgs, ShouldExpand,
2784                                          RetainExpansion,
2785                                          NumExpansions)) {
2786        AnyErrors = true;
2787        New->setInvalidDecl();
2788        continue;
2789      }
2790      assert(ShouldExpand && "Partial instantiation of base initializer?");
2791
2792      // Loop over all of the arguments in the argument pack(s),
2793      for (unsigned I = 0; I != *NumExpansions; ++I) {
2794        Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
2795
2796        // Instantiate the initializer.
2797        if (InstantiateInitializer(Init->getInit(), TemplateArgs,
2798                                   LParenLoc, NewArgs, RParenLoc)) {
2799          AnyErrors = true;
2800          break;
2801        }
2802
2803        // Instantiate the base type.
2804        TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
2805                                              TemplateArgs,
2806                                              Init->getSourceLocation(),
2807                                              New->getDeclName());
2808        if (!BaseTInfo) {
2809          AnyErrors = true;
2810          break;
2811        }
2812
2813        // Build the initializer.
2814        MultiInitializer MultiInit(CreateMultiInitializer(NewArgs, Init));
2815        MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
2816                                                     BaseTInfo, MultiInit,
2817                                                     New->getParent(),
2818                                                     SourceLocation());
2819        if (NewInit.isInvalid()) {
2820          AnyErrors = true;
2821          break;
2822        }
2823
2824        NewInits.push_back(NewInit.get());
2825        NewArgs.clear();
2826      }
2827
2828      continue;
2829    }
2830
2831    // Instantiate the initializer.
2832    if (InstantiateInitializer(Init->getInit(), TemplateArgs,
2833                               LParenLoc, NewArgs, RParenLoc)) {
2834      AnyErrors = true;
2835      continue;
2836    }
2837
2838    MemInitResult NewInit;
2839    if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
2840      TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
2841                                        TemplateArgs,
2842                                        Init->getSourceLocation(),
2843                                        New->getDeclName());
2844      if (!TInfo) {
2845        AnyErrors = true;
2846        New->setInvalidDecl();
2847        continue;
2848      }
2849
2850      MultiInitializer MultiInit(CreateMultiInitializer(NewArgs, Init));
2851
2852      if (Init->isBaseInitializer())
2853        NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, MultiInit,
2854                                       New->getParent(), EllipsisLoc);
2855      else
2856        NewInit = BuildDelegatingInitializer(TInfo, MultiInit,
2857                                  cast<CXXRecordDecl>(CurContext->getParent()));
2858    } else if (Init->isMemberInitializer()) {
2859      FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
2860                                                     Init->getMemberLocation(),
2861                                                     Init->getMember(),
2862                                                     TemplateArgs));
2863      if (!Member) {
2864        AnyErrors = true;
2865        New->setInvalidDecl();
2866        continue;
2867      }
2868
2869      MultiInitializer MultiInit(CreateMultiInitializer(NewArgs, Init));
2870      NewInit = BuildMemberInitializer(Member, MultiInit,
2871                                       Init->getSourceLocation());
2872    } else if (Init->isIndirectMemberInitializer()) {
2873      IndirectFieldDecl *IndirectMember =
2874         cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
2875                                 Init->getMemberLocation(),
2876                                 Init->getIndirectMember(), TemplateArgs));
2877
2878      if (!IndirectMember) {
2879        AnyErrors = true;
2880        New->setInvalidDecl();
2881        continue;
2882      }
2883
2884      MultiInitializer MultiInit(CreateMultiInitializer(NewArgs, Init));
2885      NewInit = BuildMemberInitializer(IndirectMember, MultiInit,
2886                                       Init->getSourceLocation());
2887    }
2888
2889    if (NewInit.isInvalid()) {
2890      AnyErrors = true;
2891      New->setInvalidDecl();
2892    } else {
2893      // FIXME: It would be nice if ASTOwningVector had a release function.
2894      NewArgs.take();
2895
2896      NewInits.push_back(NewInit.get());
2897    }
2898  }
2899
2900  // Assign all the initializers to the new constructor.
2901  ActOnMemInitializers(New,
2902                       /*FIXME: ColonLoc */
2903                       SourceLocation(),
2904                       NewInits.data(), NewInits.size(),
2905                       AnyErrors);
2906}
2907
2908// TODO: this could be templated if the various decl types used the
2909// same method name.
2910static bool isInstantiationOf(ClassTemplateDecl *Pattern,
2911                              ClassTemplateDecl *Instance) {
2912  Pattern = Pattern->getCanonicalDecl();
2913
2914  do {
2915    Instance = Instance->getCanonicalDecl();
2916    if (Pattern == Instance) return true;
2917    Instance = Instance->getInstantiatedFromMemberTemplate();
2918  } while (Instance);
2919
2920  return false;
2921}
2922
2923static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
2924                              FunctionTemplateDecl *Instance) {
2925  Pattern = Pattern->getCanonicalDecl();
2926
2927  do {
2928    Instance = Instance->getCanonicalDecl();
2929    if (Pattern == Instance) return true;
2930    Instance = Instance->getInstantiatedFromMemberTemplate();
2931  } while (Instance);
2932
2933  return false;
2934}
2935
2936static bool
2937isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
2938                  ClassTemplatePartialSpecializationDecl *Instance) {
2939  Pattern
2940    = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
2941  do {
2942    Instance = cast<ClassTemplatePartialSpecializationDecl>(
2943                                                Instance->getCanonicalDecl());
2944    if (Pattern == Instance)
2945      return true;
2946    Instance = Instance->getInstantiatedFromMember();
2947  } while (Instance);
2948
2949  return false;
2950}
2951
2952static bool isInstantiationOf(CXXRecordDecl *Pattern,
2953                              CXXRecordDecl *Instance) {
2954  Pattern = Pattern->getCanonicalDecl();
2955
2956  do {
2957    Instance = Instance->getCanonicalDecl();
2958    if (Pattern == Instance) return true;
2959    Instance = Instance->getInstantiatedFromMemberClass();
2960  } while (Instance);
2961
2962  return false;
2963}
2964
2965static bool isInstantiationOf(FunctionDecl *Pattern,
2966                              FunctionDecl *Instance) {
2967  Pattern = Pattern->getCanonicalDecl();
2968
2969  do {
2970    Instance = Instance->getCanonicalDecl();
2971    if (Pattern == Instance) return true;
2972    Instance = Instance->getInstantiatedFromMemberFunction();
2973  } while (Instance);
2974
2975  return false;
2976}
2977
2978static bool isInstantiationOf(EnumDecl *Pattern,
2979                              EnumDecl *Instance) {
2980  Pattern = Pattern->getCanonicalDecl();
2981
2982  do {
2983    Instance = Instance->getCanonicalDecl();
2984    if (Pattern == Instance) return true;
2985    Instance = Instance->getInstantiatedFromMemberEnum();
2986  } while (Instance);
2987
2988  return false;
2989}
2990
2991static bool isInstantiationOf(UsingShadowDecl *Pattern,
2992                              UsingShadowDecl *Instance,
2993                              ASTContext &C) {
2994  return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
2995}
2996
2997static bool isInstantiationOf(UsingDecl *Pattern,
2998                              UsingDecl *Instance,
2999                              ASTContext &C) {
3000  return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
3001}
3002
3003static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
3004                              UsingDecl *Instance,
3005                              ASTContext &C) {
3006  return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
3007}
3008
3009static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
3010                              UsingDecl *Instance,
3011                              ASTContext &C) {
3012  return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
3013}
3014
3015static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
3016                                              VarDecl *Instance) {
3017  assert(Instance->isStaticDataMember());
3018
3019  Pattern = Pattern->getCanonicalDecl();
3020
3021  do {
3022    Instance = Instance->getCanonicalDecl();
3023    if (Pattern == Instance) return true;
3024    Instance = Instance->getInstantiatedFromStaticDataMember();
3025  } while (Instance);
3026
3027  return false;
3028}
3029
3030// Other is the prospective instantiation
3031// D is the prospective pattern
3032static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
3033  if (D->getKind() != Other->getKind()) {
3034    if (UnresolvedUsingTypenameDecl *UUD
3035          = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3036      if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
3037        return isInstantiationOf(UUD, UD, Ctx);
3038      }
3039    }
3040
3041    if (UnresolvedUsingValueDecl *UUD
3042          = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3043      if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
3044        return isInstantiationOf(UUD, UD, Ctx);
3045      }
3046    }
3047
3048    return false;
3049  }
3050
3051  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
3052    return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
3053
3054  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
3055    return isInstantiationOf(cast<FunctionDecl>(D), Function);
3056
3057  if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
3058    return isInstantiationOf(cast<EnumDecl>(D), Enum);
3059
3060  if (VarDecl *Var = dyn_cast<VarDecl>(Other))
3061    if (Var->isStaticDataMember())
3062      return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
3063
3064  if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
3065    return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
3066
3067  if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
3068    return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
3069
3070  if (ClassTemplatePartialSpecializationDecl *PartialSpec
3071        = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
3072    return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
3073                             PartialSpec);
3074
3075  if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
3076    if (!Field->getDeclName()) {
3077      // This is an unnamed field.
3078      return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
3079        cast<FieldDecl>(D);
3080    }
3081  }
3082
3083  if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
3084    return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
3085
3086  if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
3087    return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
3088
3089  return D->getDeclName() && isa<NamedDecl>(Other) &&
3090    D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
3091}
3092
3093template<typename ForwardIterator>
3094static NamedDecl *findInstantiationOf(ASTContext &Ctx,
3095                                      NamedDecl *D,
3096                                      ForwardIterator first,
3097                                      ForwardIterator last) {
3098  for (; first != last; ++first)
3099    if (isInstantiationOf(Ctx, D, *first))
3100      return cast<NamedDecl>(*first);
3101
3102  return 0;
3103}
3104
3105/// \brief Finds the instantiation of the given declaration context
3106/// within the current instantiation.
3107///
3108/// \returns NULL if there was an error
3109DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
3110                          const MultiLevelTemplateArgumentList &TemplateArgs) {
3111  if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
3112    Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
3113    return cast_or_null<DeclContext>(ID);
3114  } else return DC;
3115}
3116
3117/// \brief Find the instantiation of the given declaration within the
3118/// current instantiation.
3119///
3120/// This routine is intended to be used when \p D is a declaration
3121/// referenced from within a template, that needs to mapped into the
3122/// corresponding declaration within an instantiation. For example,
3123/// given:
3124///
3125/// \code
3126/// template<typename T>
3127/// struct X {
3128///   enum Kind {
3129///     KnownValue = sizeof(T)
3130///   };
3131///
3132///   bool getKind() const { return KnownValue; }
3133/// };
3134///
3135/// template struct X<int>;
3136/// \endcode
3137///
3138/// In the instantiation of X<int>::getKind(), we need to map the
3139/// EnumConstantDecl for KnownValue (which refers to
3140/// X<T>::<Kind>::KnownValue) to its instantiation
3141/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
3142/// this mapping from within the instantiation of X<int>.
3143NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
3144                          const MultiLevelTemplateArgumentList &TemplateArgs) {
3145  DeclContext *ParentDC = D->getDeclContext();
3146  if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
3147      isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
3148      (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext())) {
3149    // D is a local of some kind. Look into the map of local
3150    // declarations to their instantiations.
3151    typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
3152    llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
3153      = CurrentInstantiationScope->findInstantiationOf(D);
3154
3155    if (Found) {
3156      if (Decl *FD = Found->dyn_cast<Decl *>())
3157        return cast<NamedDecl>(FD);
3158
3159      unsigned PackIdx = ArgumentPackSubstitutionIndex;
3160      return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
3161    }
3162
3163    // If we didn't find the decl, then we must have a label decl that hasn't
3164    // been found yet.  Lazily instantiate it and return it now.
3165    assert(isa<LabelDecl>(D));
3166
3167    Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
3168    assert(Inst && "Failed to instantiate label??");
3169
3170    CurrentInstantiationScope->InstantiatedLocal(D, Inst);
3171    return cast<LabelDecl>(Inst);
3172  }
3173
3174  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
3175    if (!Record->isDependentContext())
3176      return D;
3177
3178    // Determine whether this record is the "templated" declaration describing
3179    // a class template or class template partial specialization.
3180    ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
3181    if (ClassTemplate)
3182      ClassTemplate = ClassTemplate->getCanonicalDecl();
3183    else if (ClassTemplatePartialSpecializationDecl *PartialSpec
3184               = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
3185      ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
3186
3187    // Walk the current context to find either the record or an instantiation of
3188    // it.
3189    DeclContext *DC = CurContext;
3190    while (!DC->isFileContext()) {
3191      // If we're performing substitution while we're inside the template
3192      // definition, we'll find our own context. We're done.
3193      if (DC->Equals(Record))
3194        return Record;
3195
3196      if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
3197        // Check whether we're in the process of instantiating a class template
3198        // specialization of the template we're mapping.
3199        if (ClassTemplateSpecializationDecl *InstSpec
3200                      = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
3201          ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
3202          if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
3203            return InstRecord;
3204        }
3205
3206        // Check whether we're in the process of instantiating a member class.
3207        if (isInstantiationOf(Record, InstRecord))
3208          return InstRecord;
3209      }
3210
3211
3212      // Move to the outer template scope.
3213      if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
3214        if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
3215          DC = FD->getLexicalDeclContext();
3216          continue;
3217        }
3218      }
3219
3220      DC = DC->getParent();
3221    }
3222
3223    // Fall through to deal with other dependent record types (e.g.,
3224    // anonymous unions in class templates).
3225  }
3226
3227  if (!ParentDC->isDependentContext())
3228    return D;
3229
3230  ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
3231  if (!ParentDC)
3232    return 0;
3233
3234  if (ParentDC != D->getDeclContext()) {
3235    // We performed some kind of instantiation in the parent context,
3236    // so now we need to look into the instantiated parent context to
3237    // find the instantiation of the declaration D.
3238
3239    // If our context used to be dependent, we may need to instantiate
3240    // it before performing lookup into that context.
3241    bool IsBeingInstantiated = false;
3242    if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
3243      if (!Spec->isDependentContext()) {
3244        QualType T = Context.getTypeDeclType(Spec);
3245        const RecordType *Tag = T->getAs<RecordType>();
3246        assert(Tag && "type of non-dependent record is not a RecordType");
3247        if (Tag->isBeingDefined())
3248          IsBeingInstantiated = true;
3249        if (!Tag->isBeingDefined() &&
3250            RequireCompleteType(Loc, T, diag::err_incomplete_type))
3251          return 0;
3252
3253        ParentDC = Tag->getDecl();
3254      }
3255    }
3256
3257    NamedDecl *Result = 0;
3258    if (D->getDeclName()) {
3259      DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
3260      Result = findInstantiationOf(Context, D, Found.first, Found.second);
3261    } else {
3262      // Since we don't have a name for the entity we're looking for,
3263      // our only option is to walk through all of the declarations to
3264      // find that name. This will occur in a few cases:
3265      //
3266      //   - anonymous struct/union within a template
3267      //   - unnamed class/struct/union/enum within a template
3268      //
3269      // FIXME: Find a better way to find these instantiations!
3270      Result = findInstantiationOf(Context, D,
3271                                   ParentDC->decls_begin(),
3272                                   ParentDC->decls_end());
3273    }
3274
3275    if (!Result) {
3276      if (isa<UsingShadowDecl>(D)) {
3277        // UsingShadowDecls can instantiate to nothing because of using hiding.
3278      } else if (Diags.hasErrorOccurred()) {
3279        // We've already complained about something, so most likely this
3280        // declaration failed to instantiate. There's no point in complaining
3281        // further, since this is normal in invalid code.
3282      } else if (IsBeingInstantiated) {
3283        // The class in which this member exists is currently being
3284        // instantiated, and we haven't gotten around to instantiating this
3285        // member yet. This can happen when the code uses forward declarations
3286        // of member classes, and introduces ordering dependencies via
3287        // template instantiation.
3288        Diag(Loc, diag::err_member_not_yet_instantiated)
3289          << D->getDeclName()
3290          << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
3291        Diag(D->getLocation(), diag::note_non_instantiated_member_here);
3292      } else {
3293        // We should have found something, but didn't.
3294        llvm_unreachable("Unable to find instantiation of declaration!");
3295      }
3296    }
3297
3298    D = Result;
3299  }
3300
3301  return D;
3302}
3303
3304/// \brief Performs template instantiation for all implicit template
3305/// instantiations we have seen until this point.
3306void Sema::PerformPendingInstantiations(bool LocalOnly) {
3307  // Load pending instantiations from the external source.
3308  if (!LocalOnly && ExternalSource) {
3309    SmallVector<std::pair<ValueDecl *, SourceLocation>, 4> Pending;
3310    ExternalSource->ReadPendingInstantiations(Pending);
3311    PendingInstantiations.insert(PendingInstantiations.begin(),
3312                                 Pending.begin(), Pending.end());
3313  }
3314
3315  while (!PendingLocalImplicitInstantiations.empty() ||
3316         (!LocalOnly && !PendingInstantiations.empty())) {
3317    PendingImplicitInstantiation Inst;
3318
3319    if (PendingLocalImplicitInstantiations.empty()) {
3320      Inst = PendingInstantiations.front();
3321      PendingInstantiations.pop_front();
3322    } else {
3323      Inst = PendingLocalImplicitInstantiations.front();
3324      PendingLocalImplicitInstantiations.pop_front();
3325    }
3326
3327    // Instantiate function definitions
3328    if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
3329      PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
3330                                          "instantiating function definition");
3331      bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
3332                                TSK_ExplicitInstantiationDefinition;
3333      InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
3334                                    DefinitionRequired);
3335      continue;
3336    }
3337
3338    // Instantiate static data member definitions.
3339    VarDecl *Var = cast<VarDecl>(Inst.first);
3340    assert(Var->isStaticDataMember() && "Not a static data member?");
3341
3342    // Don't try to instantiate declarations if the most recent redeclaration
3343    // is invalid.
3344    if (Var->getMostRecentDeclaration()->isInvalidDecl())
3345      continue;
3346
3347    // Check if the most recent declaration has changed the specialization kind
3348    // and removed the need for implicit instantiation.
3349    switch (Var->getMostRecentDeclaration()->getTemplateSpecializationKind()) {
3350    case TSK_Undeclared:
3351      llvm_unreachable("Cannot instantitiate an undeclared specialization.");
3352    case TSK_ExplicitInstantiationDeclaration:
3353    case TSK_ExplicitSpecialization:
3354      continue;  // No longer need to instantiate this type.
3355    case TSK_ExplicitInstantiationDefinition:
3356      // We only need an instantiation if the pending instantiation *is* the
3357      // explicit instantiation.
3358      if (Var != Var->getMostRecentDeclaration()) continue;
3359    case TSK_ImplicitInstantiation:
3360      break;
3361    }
3362
3363    PrettyDeclStackTraceEntry CrashInfo(*this, Var, Var->getLocation(),
3364                                        "instantiating static data member "
3365                                        "definition");
3366
3367    bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
3368                              TSK_ExplicitInstantiationDefinition;
3369    InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true,
3370                                          DefinitionRequired);
3371  }
3372}
3373
3374void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
3375                       const MultiLevelTemplateArgumentList &TemplateArgs) {
3376  for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
3377         E = Pattern->ddiag_end(); I != E; ++I) {
3378    DependentDiagnostic *DD = *I;
3379
3380    switch (DD->getKind()) {
3381    case DependentDiagnostic::Access:
3382      HandleDependentAccessCheck(*DD, TemplateArgs);
3383      break;
3384    }
3385  }
3386}
3387