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