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