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