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