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/AST/ASTConsumer.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/ASTMutationListener.h"
16#include "clang/AST/DeclTemplate.h"
17#include "clang/AST/DeclVisitor.h"
18#include "clang/AST/DependentDiagnostic.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
21#include "clang/AST/TypeLoc.h"
22#include "clang/Sema/Lookup.h"
23#include "clang/Sema/PrettyDeclStackTrace.h"
24#include "clang/Sema/Template.h"
25
26using namespace clang;
27
28static bool isDeclWithinFunction(const Decl *D) {
29  const DeclContext *DC = D->getDeclContext();
30  if (DC->isFunctionOrMethod())
31    return true;
32
33  if (DC->isRecord())
34    return cast<CXXRecordDecl>(DC)->isLocalClass();
35
36  return false;
37}
38
39template<typename DeclT>
40static bool SubstQualifier(Sema &SemaRef, const DeclT *OldDecl, DeclT *NewDecl,
41                           const MultiLevelTemplateArgumentList &TemplateArgs) {
42  if (!OldDecl->getQualifierLoc())
43    return false;
44
45  assert((NewDecl->getFriendObjectKind() ||
46          !OldDecl->getLexicalDeclContext()->isDependentContext()) &&
47         "non-friend with qualified name defined in dependent context");
48  Sema::ContextRAII SavedContext(
49      SemaRef,
50      const_cast<DeclContext *>(NewDecl->getFriendObjectKind()
51                                    ? NewDecl->getLexicalDeclContext()
52                                    : OldDecl->getLexicalDeclContext()));
53
54  NestedNameSpecifierLoc NewQualifierLoc
55      = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
56                                            TemplateArgs);
57
58  if (!NewQualifierLoc)
59    return true;
60
61  NewDecl->setQualifierInfo(NewQualifierLoc);
62  return false;
63}
64
65bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
66                                              DeclaratorDecl *NewDecl) {
67  return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
68}
69
70bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
71                                              TagDecl *NewDecl) {
72  return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
73}
74
75// Include attribute instantiation code.
76#include "clang/Sema/AttrTemplateInstantiate.inc"
77
78static void instantiateDependentAlignedAttr(
79    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
80    const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
81  if (Aligned->isAlignmentExpr()) {
82    // The alignment expression is a constant expression.
83    EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated);
84    ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
85    if (!Result.isInvalid())
86      S.AddAlignedAttr(Aligned->getLocation(), New, Result.getAs<Expr>(),
87                       Aligned->getSpellingListIndex(), IsPackExpansion);
88  } else {
89    TypeSourceInfo *Result = S.SubstType(Aligned->getAlignmentType(),
90                                         TemplateArgs, Aligned->getLocation(),
91                                         DeclarationName());
92    if (Result)
93      S.AddAlignedAttr(Aligned->getLocation(), New, Result,
94                       Aligned->getSpellingListIndex(), IsPackExpansion);
95  }
96}
97
98static void instantiateDependentAlignedAttr(
99    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
100    const AlignedAttr *Aligned, Decl *New) {
101  if (!Aligned->isPackExpansion()) {
102    instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
103    return;
104  }
105
106  SmallVector<UnexpandedParameterPack, 2> Unexpanded;
107  if (Aligned->isAlignmentExpr())
108    S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
109                                      Unexpanded);
110  else
111    S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
112                                      Unexpanded);
113  assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
114
115  // Determine whether we can expand this attribute pack yet.
116  bool Expand = true, RetainExpansion = false;
117  Optional<unsigned> NumExpansions;
118  // FIXME: Use the actual location of the ellipsis.
119  SourceLocation EllipsisLoc = Aligned->getLocation();
120  if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
121                                        Unexpanded, TemplateArgs, Expand,
122                                        RetainExpansion, NumExpansions))
123    return;
124
125  if (!Expand) {
126    Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1);
127    instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
128  } else {
129    for (unsigned I = 0; I != *NumExpansions; ++I) {
130      Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I);
131      instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
132    }
133  }
134}
135
136static void instantiateDependentAssumeAlignedAttr(
137    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
138    const AssumeAlignedAttr *Aligned, Decl *New) {
139  // The alignment expression is a constant expression.
140  EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated);
141
142  Expr *E, *OE = nullptr;
143  ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
144  if (Result.isInvalid())
145    return;
146  E = Result.getAs<Expr>();
147
148  if (Aligned->getOffset()) {
149    Result = S.SubstExpr(Aligned->getOffset(), TemplateArgs);
150    if (Result.isInvalid())
151      return;
152    OE = Result.getAs<Expr>();
153  }
154
155  S.AddAssumeAlignedAttr(Aligned->getLocation(), New, E, OE,
156                         Aligned->getSpellingListIndex());
157}
158
159static void instantiateDependentAlignValueAttr(
160    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
161    const AlignValueAttr *Aligned, Decl *New) {
162  // The alignment expression is a constant expression.
163  EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated);
164  ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
165  if (!Result.isInvalid())
166    S.AddAlignValueAttr(Aligned->getLocation(), New, Result.getAs<Expr>(),
167                        Aligned->getSpellingListIndex());
168}
169
170static void instantiateDependentEnableIfAttr(
171    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
172    const EnableIfAttr *A, const Decl *Tmpl, Decl *New) {
173  Expr *Cond = nullptr;
174  {
175    EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
176    ExprResult Result = S.SubstExpr(A->getCond(), TemplateArgs);
177    if (Result.isInvalid())
178      return;
179    Cond = Result.getAs<Expr>();
180  }
181  if (A->getCond()->isTypeDependent() && !Cond->isTypeDependent()) {
182    ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
183    if (Converted.isInvalid())
184      return;
185    Cond = Converted.get();
186  }
187
188  SmallVector<PartialDiagnosticAt, 8> Diags;
189  if (A->getCond()->isValueDependent() && !Cond->isValueDependent() &&
190      !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(Tmpl),
191                                                Diags)) {
192    S.Diag(A->getLocation(), diag::err_enable_if_never_constant_expr);
193    for (int I = 0, N = Diags.size(); I != N; ++I)
194      S.Diag(Diags[I].first, Diags[I].second);
195    return;
196  }
197
198  EnableIfAttr *EIA = new (S.getASTContext())
199                        EnableIfAttr(A->getLocation(), S.getASTContext(), Cond,
200                                     A->getMessage(),
201                                     A->getSpellingListIndex());
202  New->addAttr(EIA);
203}
204
205void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
206                            const Decl *Tmpl, Decl *New,
207                            LateInstantiatedAttrVec *LateAttrs,
208                            LocalInstantiationScope *OuterMostScope) {
209  for (const auto *TmplAttr : Tmpl->attrs()) {
210    // FIXME: This should be generalized to more than just the AlignedAttr.
211    const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
212    if (Aligned && Aligned->isAlignmentDependent()) {
213      instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
214      continue;
215    }
216
217    const AssumeAlignedAttr *AssumeAligned = dyn_cast<AssumeAlignedAttr>(TmplAttr);
218    if (AssumeAligned) {
219      instantiateDependentAssumeAlignedAttr(*this, TemplateArgs, AssumeAligned, New);
220      continue;
221    }
222
223    const AlignValueAttr *AlignValue = dyn_cast<AlignValueAttr>(TmplAttr);
224    if (AlignValue) {
225      instantiateDependentAlignValueAttr(*this, TemplateArgs, AlignValue, New);
226      continue;
227    }
228
229    const EnableIfAttr *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr);
230    if (EnableIf && EnableIf->getCond()->isValueDependent()) {
231      instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl,
232                                       New);
233      continue;
234    }
235
236    // Existing DLL attribute on the instantiation takes precedence.
237    if (TmplAttr->getKind() == attr::DLLExport ||
238        TmplAttr->getKind() == attr::DLLImport) {
239      if (New->hasAttr<DLLExportAttr>() || New->hasAttr<DLLImportAttr>()) {
240        continue;
241      }
242    }
243
244    assert(!TmplAttr->isPackExpansion());
245    if (TmplAttr->isLateParsed() && LateAttrs) {
246      // Late parsed attributes must be instantiated and attached after the
247      // enclosing class has been instantiated.  See Sema::InstantiateClass.
248      LocalInstantiationScope *Saved = nullptr;
249      if (CurrentInstantiationScope)
250        Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
251      LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
252    } else {
253      // Allow 'this' within late-parsed attributes.
254      NamedDecl *ND = dyn_cast<NamedDecl>(New);
255      CXXRecordDecl *ThisContext =
256          dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
257      CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
258                                 ND && ND->isCXXInstanceMember());
259
260      Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
261                                                         *this, TemplateArgs);
262      if (NewAttr)
263        New->addAttr(NewAttr);
264    }
265  }
266}
267
268/// Get the previous declaration of a declaration for the purposes of template
269/// instantiation. If this finds a previous declaration, then the previous
270/// declaration of the instantiation of D should be an instantiation of the
271/// result of this function.
272template<typename DeclT>
273static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
274  DeclT *Result = D->getPreviousDecl();
275
276  // If the declaration is within a class, and the previous declaration was
277  // merged from a different definition of that class, then we don't have a
278  // previous declaration for the purpose of template instantiation.
279  if (Result && isa<CXXRecordDecl>(D->getDeclContext()) &&
280      D->getLexicalDeclContext() != Result->getLexicalDeclContext())
281    return nullptr;
282
283  return Result;
284}
285
286Decl *
287TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
288  llvm_unreachable("Translation units cannot be instantiated");
289}
290
291Decl *
292TemplateDeclInstantiator::VisitExternCContextDecl(ExternCContextDecl *D) {
293  llvm_unreachable("extern \"C\" context cannot be instantiated");
294}
295
296Decl *
297TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
298  LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
299                                      D->getIdentifier());
300  Owner->addDecl(Inst);
301  return Inst;
302}
303
304Decl *
305TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
306  llvm_unreachable("Namespaces cannot be instantiated");
307}
308
309Decl *
310TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
311  NamespaceAliasDecl *Inst
312    = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
313                                 D->getNamespaceLoc(),
314                                 D->getAliasLoc(),
315                                 D->getIdentifier(),
316                                 D->getQualifierLoc(),
317                                 D->getTargetNameLoc(),
318                                 D->getNamespace());
319  Owner->addDecl(Inst);
320  return Inst;
321}
322
323Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
324                                                           bool IsTypeAlias) {
325  bool Invalid = false;
326  TypeSourceInfo *DI = D->getTypeSourceInfo();
327  if (DI->getType()->isInstantiationDependentType() ||
328      DI->getType()->isVariablyModifiedType()) {
329    DI = SemaRef.SubstType(DI, TemplateArgs,
330                           D->getLocation(), D->getDeclName());
331    if (!DI) {
332      Invalid = true;
333      DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
334    }
335  } else {
336    SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
337  }
338
339  // HACK: g++ has a bug where it gets the value kind of ?: wrong.
340  // libstdc++ relies upon this bug in its implementation of common_type.
341  // If we happen to be processing that implementation, fake up the g++ ?:
342  // semantics. See LWG issue 2141 for more information on the bug.
343  const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
344  CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
345  if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
346      DT->isReferenceType() &&
347      RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
348      RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
349      D->getIdentifier() && D->getIdentifier()->isStr("type") &&
350      SemaRef.getSourceManager().isInSystemHeader(D->getLocStart()))
351    // Fold it to the (non-reference) type which g++ would have produced.
352    DI = SemaRef.Context.getTrivialTypeSourceInfo(
353      DI->getType().getNonReferenceType());
354
355  // Create the new typedef
356  TypedefNameDecl *Typedef;
357  if (IsTypeAlias)
358    Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
359                                    D->getLocation(), D->getIdentifier(), DI);
360  else
361    Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
362                                  D->getLocation(), D->getIdentifier(), DI);
363  if (Invalid)
364    Typedef->setInvalidDecl();
365
366  // If the old typedef was the name for linkage purposes of an anonymous
367  // tag decl, re-establish that relationship for the new typedef.
368  if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
369    TagDecl *oldTag = oldTagType->getDecl();
370    if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
371      TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
372      assert(!newTag->hasNameForLinkage());
373      newTag->setTypedefNameForAnonDecl(Typedef);
374    }
375  }
376
377  if (TypedefNameDecl *Prev = getPreviousDeclForInstantiation(D)) {
378    NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
379                                                       TemplateArgs);
380    if (!InstPrev)
381      return nullptr;
382
383    TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
384
385    // If the typedef types are not identical, reject them.
386    SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
387
388    Typedef->setPreviousDecl(InstPrevTypedef);
389  }
390
391  SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
392
393  Typedef->setAccess(D->getAccess());
394
395  return Typedef;
396}
397
398Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
399  Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
400  if (Typedef)
401    Owner->addDecl(Typedef);
402  return Typedef;
403}
404
405Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
406  Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
407  if (Typedef)
408    Owner->addDecl(Typedef);
409  return Typedef;
410}
411
412Decl *
413TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
414  // Create a local instantiation scope for this type alias template, which
415  // will contain the instantiations of the template parameters.
416  LocalInstantiationScope Scope(SemaRef);
417
418  TemplateParameterList *TempParams = D->getTemplateParameters();
419  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
420  if (!InstParams)
421    return nullptr;
422
423  TypeAliasDecl *Pattern = D->getTemplatedDecl();
424
425  TypeAliasTemplateDecl *PrevAliasTemplate = nullptr;
426  if (getPreviousDeclForInstantiation<TypedefNameDecl>(Pattern)) {
427    DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
428    if (!Found.empty()) {
429      PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
430    }
431  }
432
433  TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
434    InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
435  if (!AliasInst)
436    return nullptr;
437
438  TypeAliasTemplateDecl *Inst
439    = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
440                                    D->getDeclName(), InstParams, AliasInst);
441  AliasInst->setDescribedAliasTemplate(Inst);
442  if (PrevAliasTemplate)
443    Inst->setPreviousDecl(PrevAliasTemplate);
444
445  Inst->setAccess(D->getAccess());
446
447  if (!PrevAliasTemplate)
448    Inst->setInstantiatedFromMemberTemplate(D);
449
450  Owner->addDecl(Inst);
451
452  return Inst;
453}
454
455Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
456  return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
457}
458
459Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D,
460                                             bool InstantiatingVarTemplate) {
461
462  // If this is the variable for an anonymous struct or union,
463  // instantiate the anonymous struct/union type first.
464  if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
465    if (RecordTy->getDecl()->isAnonymousStructOrUnion())
466      if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
467        return nullptr;
468
469  // Do substitution on the type of the declaration
470  TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
471                                         TemplateArgs,
472                                         D->getTypeSpecStartLoc(),
473                                         D->getDeclName());
474  if (!DI)
475    return nullptr;
476
477  if (DI->getType()->isFunctionType()) {
478    SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
479      << D->isStaticDataMember() << DI->getType();
480    return nullptr;
481  }
482
483  DeclContext *DC = Owner;
484  if (D->isLocalExternDecl())
485    SemaRef.adjustContextForLocalExternDecl(DC);
486
487  // Build the instantiated declaration.
488  VarDecl *Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
489                                 D->getLocation(), D->getIdentifier(),
490                                 DI->getType(), DI, D->getStorageClass());
491
492  // In ARC, infer 'retaining' for variables of retainable type.
493  if (SemaRef.getLangOpts().ObjCAutoRefCount &&
494      SemaRef.inferObjCARCLifetime(Var))
495    Var->setInvalidDecl();
496
497  // Substitute the nested name specifier, if any.
498  if (SubstQualifier(D, Var))
499    return nullptr;
500
501  SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
502                                     StartingScope, InstantiatingVarTemplate);
503
504  if (D->isNRVOVariable()) {
505    QualType ReturnType = cast<FunctionDecl>(DC)->getReturnType();
506    if (SemaRef.isCopyElisionCandidate(ReturnType, Var, false))
507      Var->setNRVOVariable(true);
508  }
509
510  Var->setImplicit(D->isImplicit());
511
512  return Var;
513}
514
515Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
516  AccessSpecDecl* AD
517    = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
518                             D->getAccessSpecifierLoc(), D->getColonLoc());
519  Owner->addHiddenDecl(AD);
520  return AD;
521}
522
523Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
524  bool Invalid = false;
525  TypeSourceInfo *DI = D->getTypeSourceInfo();
526  if (DI->getType()->isInstantiationDependentType() ||
527      DI->getType()->isVariablyModifiedType())  {
528    DI = SemaRef.SubstType(DI, TemplateArgs,
529                           D->getLocation(), D->getDeclName());
530    if (!DI) {
531      DI = D->getTypeSourceInfo();
532      Invalid = true;
533    } else if (DI->getType()->isFunctionType()) {
534      // C++ [temp.arg.type]p3:
535      //   If a declaration acquires a function type through a type
536      //   dependent on a template-parameter and this causes a
537      //   declaration that does not use the syntactic form of a
538      //   function declarator to have function type, the program is
539      //   ill-formed.
540      SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
541        << DI->getType();
542      Invalid = true;
543    }
544  } else {
545    SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
546  }
547
548  Expr *BitWidth = D->getBitWidth();
549  if (Invalid)
550    BitWidth = nullptr;
551  else if (BitWidth) {
552    // The bit-width expression is a constant expression.
553    EnterExpressionEvaluationContext Unevaluated(SemaRef,
554                                                 Sema::ConstantEvaluated);
555
556    ExprResult InstantiatedBitWidth
557      = SemaRef.SubstExpr(BitWidth, TemplateArgs);
558    if (InstantiatedBitWidth.isInvalid()) {
559      Invalid = true;
560      BitWidth = nullptr;
561    } else
562      BitWidth = InstantiatedBitWidth.getAs<Expr>();
563  }
564
565  FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
566                                            DI->getType(), DI,
567                                            cast<RecordDecl>(Owner),
568                                            D->getLocation(),
569                                            D->isMutable(),
570                                            BitWidth,
571                                            D->getInClassInitStyle(),
572                                            D->getInnerLocStart(),
573                                            D->getAccess(),
574                                            nullptr);
575  if (!Field) {
576    cast<Decl>(Owner)->setInvalidDecl();
577    return nullptr;
578  }
579
580  SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
581
582  if (Field->hasAttrs())
583    SemaRef.CheckAlignasUnderalignment(Field);
584
585  if (Invalid)
586    Field->setInvalidDecl();
587
588  if (!Field->getDeclName()) {
589    // Keep track of where this decl came from.
590    SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
591  }
592  if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
593    if (Parent->isAnonymousStructOrUnion() &&
594        Parent->getRedeclContext()->isFunctionOrMethod())
595      SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
596  }
597
598  Field->setImplicit(D->isImplicit());
599  Field->setAccess(D->getAccess());
600  Owner->addDecl(Field);
601
602  return Field;
603}
604
605Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
606  bool Invalid = false;
607  TypeSourceInfo *DI = D->getTypeSourceInfo();
608
609  if (DI->getType()->isVariablyModifiedType()) {
610    SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
611      << D;
612    Invalid = true;
613  } else if (DI->getType()->isInstantiationDependentType())  {
614    DI = SemaRef.SubstType(DI, TemplateArgs,
615                           D->getLocation(), D->getDeclName());
616    if (!DI) {
617      DI = D->getTypeSourceInfo();
618      Invalid = true;
619    } else if (DI->getType()->isFunctionType()) {
620      // C++ [temp.arg.type]p3:
621      //   If a declaration acquires a function type through a type
622      //   dependent on a template-parameter and this causes a
623      //   declaration that does not use the syntactic form of a
624      //   function declarator to have function type, the program is
625      //   ill-formed.
626      SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
627      << DI->getType();
628      Invalid = true;
629    }
630  } else {
631    SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
632  }
633
634  MSPropertyDecl *Property = MSPropertyDecl::Create(
635      SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(),
636      DI, D->getLocStart(), D->getGetterId(), D->getSetterId());
637
638  SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
639                           StartingScope);
640
641  if (Invalid)
642    Property->setInvalidDecl();
643
644  Property->setAccess(D->getAccess());
645  Owner->addDecl(Property);
646
647  return Property;
648}
649
650Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
651  NamedDecl **NamedChain =
652    new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
653
654  int i = 0;
655  for (auto *PI : D->chain()) {
656    NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI,
657                                              TemplateArgs);
658    if (!Next)
659      return nullptr;
660
661    NamedChain[i++] = Next;
662  }
663
664  QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
665  IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
666      SemaRef.Context, Owner, D->getLocation(), D->getIdentifier(), T,
667      NamedChain, D->getChainingSize());
668
669  for (const auto *Attr : D->attrs())
670    IndirectField->addAttr(Attr->clone(SemaRef.Context));
671
672  IndirectField->setImplicit(D->isImplicit());
673  IndirectField->setAccess(D->getAccess());
674  Owner->addDecl(IndirectField);
675  return IndirectField;
676}
677
678Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
679  // Handle friend type expressions by simply substituting template
680  // parameters into the pattern type and checking the result.
681  if (TypeSourceInfo *Ty = D->getFriendType()) {
682    TypeSourceInfo *InstTy;
683    // If this is an unsupported friend, don't bother substituting template
684    // arguments into it. The actual type referred to won't be used by any
685    // parts of Clang, and may not be valid for instantiating. Just use the
686    // same info for the instantiated friend.
687    if (D->isUnsupportedFriend()) {
688      InstTy = Ty;
689    } else {
690      InstTy = SemaRef.SubstType(Ty, TemplateArgs,
691                                 D->getLocation(), DeclarationName());
692    }
693    if (!InstTy)
694      return nullptr;
695
696    FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getLocStart(),
697                                                 D->getFriendLoc(), InstTy);
698    if (!FD)
699      return nullptr;
700
701    FD->setAccess(AS_public);
702    FD->setUnsupportedFriend(D->isUnsupportedFriend());
703    Owner->addDecl(FD);
704    return FD;
705  }
706
707  NamedDecl *ND = D->getFriendDecl();
708  assert(ND && "friend decl must be a decl or a type!");
709
710  // All of the Visit implementations for the various potential friend
711  // declarations have to be carefully written to work for friend
712  // objects, with the most important detail being that the target
713  // decl should almost certainly not be placed in Owner.
714  Decl *NewND = Visit(ND);
715  if (!NewND) return nullptr;
716
717  FriendDecl *FD =
718    FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
719                       cast<NamedDecl>(NewND), D->getFriendLoc());
720  FD->setAccess(AS_public);
721  FD->setUnsupportedFriend(D->isUnsupportedFriend());
722  Owner->addDecl(FD);
723  return FD;
724}
725
726Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
727  Expr *AssertExpr = D->getAssertExpr();
728
729  // The expression in a static assertion is a constant expression.
730  EnterExpressionEvaluationContext Unevaluated(SemaRef,
731                                               Sema::ConstantEvaluated);
732
733  ExprResult InstantiatedAssertExpr
734    = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
735  if (InstantiatedAssertExpr.isInvalid())
736    return nullptr;
737
738  return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
739                                              InstantiatedAssertExpr.get(),
740                                              D->getMessage(),
741                                              D->getRParenLoc(),
742                                              D->isFailed());
743}
744
745Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
746  EnumDecl *PrevDecl = nullptr;
747  if (EnumDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
748    NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
749                                                   PatternPrev,
750                                                   TemplateArgs);
751    if (!Prev) return nullptr;
752    PrevDecl = cast<EnumDecl>(Prev);
753  }
754
755  EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
756                                    D->getLocation(), D->getIdentifier(),
757                                    PrevDecl, D->isScoped(),
758                                    D->isScopedUsingClassTag(), D->isFixed());
759  if (D->isFixed()) {
760    if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
761      // If we have type source information for the underlying type, it means it
762      // has been explicitly set by the user. Perform substitution on it before
763      // moving on.
764      SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
765      TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
766                                                DeclarationName());
767      if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
768        Enum->setIntegerType(SemaRef.Context.IntTy);
769      else
770        Enum->setIntegerTypeSourceInfo(NewTI);
771    } else {
772      assert(!D->getIntegerType()->isDependentType()
773             && "Dependent type without type source info");
774      Enum->setIntegerType(D->getIntegerType());
775    }
776  }
777
778  SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
779
780  Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
781  Enum->setAccess(D->getAccess());
782  // Forward the mangling number from the template to the instantiated decl.
783  SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D));
784  if (SubstQualifier(D, Enum)) return nullptr;
785  Owner->addDecl(Enum);
786
787  EnumDecl *Def = D->getDefinition();
788  if (Def && Def != D) {
789    // If this is an out-of-line definition of an enum member template, check
790    // that the underlying types match in the instantiation of both
791    // declarations.
792    if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
793      SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
794      QualType DefnUnderlying =
795        SemaRef.SubstType(TI->getType(), TemplateArgs,
796                          UnderlyingLoc, DeclarationName());
797      SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
798                                     DefnUnderlying, Enum);
799    }
800  }
801
802  // C++11 [temp.inst]p1: The implicit instantiation of a class template
803  // specialization causes the implicit instantiation of the declarations, but
804  // not the definitions of scoped member enumerations.
805  //
806  // DR1484 clarifies that enumeration definitions inside of a template
807  // declaration aren't considered entities that can be separately instantiated
808  // from the rest of the entity they are declared inside of.
809  if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
810    SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
811    InstantiateEnumDefinition(Enum, Def);
812  }
813
814  return Enum;
815}
816
817void TemplateDeclInstantiator::InstantiateEnumDefinition(
818    EnumDecl *Enum, EnumDecl *Pattern) {
819  Enum->startDefinition();
820
821  // Update the location to refer to the definition.
822  Enum->setLocation(Pattern->getLocation());
823
824  SmallVector<Decl*, 4> Enumerators;
825
826  EnumConstantDecl *LastEnumConst = nullptr;
827  for (auto *EC : Pattern->enumerators()) {
828    // The specified value for the enumerator.
829    ExprResult Value((Expr *)nullptr);
830    if (Expr *UninstValue = EC->getInitExpr()) {
831      // The enumerator's value expression is a constant expression.
832      EnterExpressionEvaluationContext Unevaluated(SemaRef,
833                                                   Sema::ConstantEvaluated);
834
835      Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
836    }
837
838    // Drop the initial value and continue.
839    bool isInvalid = false;
840    if (Value.isInvalid()) {
841      Value = nullptr;
842      isInvalid = true;
843    }
844
845    EnumConstantDecl *EnumConst
846      = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
847                                  EC->getLocation(), EC->getIdentifier(),
848                                  Value.get());
849
850    if (isInvalid) {
851      if (EnumConst)
852        EnumConst->setInvalidDecl();
853      Enum->setInvalidDecl();
854    }
855
856    if (EnumConst) {
857      SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst);
858
859      EnumConst->setAccess(Enum->getAccess());
860      Enum->addDecl(EnumConst);
861      Enumerators.push_back(EnumConst);
862      LastEnumConst = EnumConst;
863
864      if (Pattern->getDeclContext()->isFunctionOrMethod() &&
865          !Enum->isScoped()) {
866        // If the enumeration is within a function or method, record the enum
867        // constant as a local.
868        SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst);
869      }
870    }
871  }
872
873  // FIXME: Fixup LBraceLoc
874  SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(),
875                        Enum->getRBraceLoc(), Enum,
876                        Enumerators,
877                        nullptr, nullptr);
878}
879
880Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
881  llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
882}
883
884Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
885  bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
886
887  // Create a local instantiation scope for this class template, which
888  // will contain the instantiations of the template parameters.
889  LocalInstantiationScope Scope(SemaRef);
890  TemplateParameterList *TempParams = D->getTemplateParameters();
891  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
892  if (!InstParams)
893    return nullptr;
894
895  CXXRecordDecl *Pattern = D->getTemplatedDecl();
896
897  // Instantiate the qualifier.  We have to do this first in case
898  // we're a friend declaration, because if we are then we need to put
899  // the new declaration in the appropriate context.
900  NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
901  if (QualifierLoc) {
902    QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
903                                                       TemplateArgs);
904    if (!QualifierLoc)
905      return nullptr;
906  }
907
908  CXXRecordDecl *PrevDecl = nullptr;
909  ClassTemplateDecl *PrevClassTemplate = nullptr;
910
911  if (!isFriend && getPreviousDeclForInstantiation(Pattern)) {
912    DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
913    if (!Found.empty()) {
914      PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
915      if (PrevClassTemplate)
916        PrevDecl = PrevClassTemplate->getTemplatedDecl();
917    }
918  }
919
920  // If this isn't a friend, then it's a member template, in which
921  // case we just want to build the instantiation in the
922  // specialization.  If it is a friend, we want to build it in
923  // the appropriate context.
924  DeclContext *DC = Owner;
925  if (isFriend) {
926    if (QualifierLoc) {
927      CXXScopeSpec SS;
928      SS.Adopt(QualifierLoc);
929      DC = SemaRef.computeDeclContext(SS);
930      if (!DC) return nullptr;
931    } else {
932      DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
933                                           Pattern->getDeclContext(),
934                                           TemplateArgs);
935    }
936
937    // Look for a previous declaration of the template in the owning
938    // context.
939    LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
940                   Sema::LookupOrdinaryName, Sema::ForRedeclaration);
941    SemaRef.LookupQualifiedName(R, DC);
942
943    if (R.isSingleResult()) {
944      PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
945      if (PrevClassTemplate)
946        PrevDecl = PrevClassTemplate->getTemplatedDecl();
947    }
948
949    if (!PrevClassTemplate && QualifierLoc) {
950      SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
951        << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
952        << QualifierLoc.getSourceRange();
953      return nullptr;
954    }
955
956    bool AdoptedPreviousTemplateParams = false;
957    if (PrevClassTemplate) {
958      bool Complain = true;
959
960      // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
961      // template for struct std::tr1::__detail::_Map_base, where the
962      // template parameters of the friend declaration don't match the
963      // template parameters of the original declaration. In this one
964      // case, we don't complain about the ill-formed friend
965      // declaration.
966      if (isFriend && Pattern->getIdentifier() &&
967          Pattern->getIdentifier()->isStr("_Map_base") &&
968          DC->isNamespace() &&
969          cast<NamespaceDecl>(DC)->getIdentifier() &&
970          cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
971        DeclContext *DCParent = DC->getParent();
972        if (DCParent->isNamespace() &&
973            cast<NamespaceDecl>(DCParent)->getIdentifier() &&
974            cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
975          if (cast<Decl>(DCParent)->isInStdNamespace())
976            Complain = false;
977        }
978      }
979
980      TemplateParameterList *PrevParams
981        = PrevClassTemplate->getTemplateParameters();
982
983      // Make sure the parameter lists match.
984      if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
985                                                  Complain,
986                                                  Sema::TPL_TemplateMatch)) {
987        if (Complain)
988          return nullptr;
989
990        AdoptedPreviousTemplateParams = true;
991        InstParams = PrevParams;
992      }
993
994      // Do some additional validation, then merge default arguments
995      // from the existing declarations.
996      if (!AdoptedPreviousTemplateParams &&
997          SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
998                                             Sema::TPC_ClassTemplate))
999        return nullptr;
1000    }
1001  }
1002
1003  CXXRecordDecl *RecordInst
1004    = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
1005                            Pattern->getLocStart(), Pattern->getLocation(),
1006                            Pattern->getIdentifier(), PrevDecl,
1007                            /*DelayTypeCreation=*/true);
1008
1009  if (QualifierLoc)
1010    RecordInst->setQualifierInfo(QualifierLoc);
1011
1012  ClassTemplateDecl *Inst
1013    = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
1014                                D->getIdentifier(), InstParams, RecordInst,
1015                                PrevClassTemplate);
1016  RecordInst->setDescribedClassTemplate(Inst);
1017
1018  if (isFriend) {
1019    if (PrevClassTemplate)
1020      Inst->setAccess(PrevClassTemplate->getAccess());
1021    else
1022      Inst->setAccess(D->getAccess());
1023
1024    Inst->setObjectOfFriendDecl();
1025    // TODO: do we want to track the instantiation progeny of this
1026    // friend target decl?
1027  } else {
1028    Inst->setAccess(D->getAccess());
1029    if (!PrevClassTemplate)
1030      Inst->setInstantiatedFromMemberTemplate(D);
1031  }
1032
1033  // Trigger creation of the type for the instantiation.
1034  SemaRef.Context.getInjectedClassNameType(RecordInst,
1035                                    Inst->getInjectedClassNameSpecialization());
1036
1037  // Finish handling of friends.
1038  if (isFriend) {
1039    DC->makeDeclVisibleInContext(Inst);
1040    Inst->setLexicalDeclContext(Owner);
1041    RecordInst->setLexicalDeclContext(Owner);
1042    return Inst;
1043  }
1044
1045  if (D->isOutOfLine()) {
1046    Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1047    RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
1048  }
1049
1050  Owner->addDecl(Inst);
1051
1052  if (!PrevClassTemplate) {
1053    // Queue up any out-of-line partial specializations of this member
1054    // class template; the client will force their instantiation once
1055    // the enclosing class has been instantiated.
1056    SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1057    D->getPartialSpecializations(PartialSpecs);
1058    for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1059      if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1060        OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
1061  }
1062
1063  return Inst;
1064}
1065
1066Decl *
1067TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
1068                                   ClassTemplatePartialSpecializationDecl *D) {
1069  ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
1070
1071  // Lookup the already-instantiated declaration in the instantiation
1072  // of the class template and return that.
1073  DeclContext::lookup_result Found
1074    = Owner->lookup(ClassTemplate->getDeclName());
1075  if (Found.empty())
1076    return nullptr;
1077
1078  ClassTemplateDecl *InstClassTemplate
1079    = dyn_cast<ClassTemplateDecl>(Found.front());
1080  if (!InstClassTemplate)
1081    return nullptr;
1082
1083  if (ClassTemplatePartialSpecializationDecl *Result
1084        = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
1085    return Result;
1086
1087  return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
1088}
1089
1090Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
1091  assert(D->getTemplatedDecl()->isStaticDataMember() &&
1092         "Only static data member templates are allowed.");
1093
1094  // Create a local instantiation scope for this variable template, which
1095  // will contain the instantiations of the template parameters.
1096  LocalInstantiationScope Scope(SemaRef);
1097  TemplateParameterList *TempParams = D->getTemplateParameters();
1098  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1099  if (!InstParams)
1100    return nullptr;
1101
1102  VarDecl *Pattern = D->getTemplatedDecl();
1103  VarTemplateDecl *PrevVarTemplate = nullptr;
1104
1105  if (getPreviousDeclForInstantiation(Pattern)) {
1106    DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1107    if (!Found.empty())
1108      PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1109  }
1110
1111  VarDecl *VarInst =
1112      cast_or_null<VarDecl>(VisitVarDecl(Pattern,
1113                                         /*InstantiatingVarTemplate=*/true));
1114
1115  DeclContext *DC = Owner;
1116
1117  VarTemplateDecl *Inst = VarTemplateDecl::Create(
1118      SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
1119      VarInst);
1120  VarInst->setDescribedVarTemplate(Inst);
1121  Inst->setPreviousDecl(PrevVarTemplate);
1122
1123  Inst->setAccess(D->getAccess());
1124  if (!PrevVarTemplate)
1125    Inst->setInstantiatedFromMemberTemplate(D);
1126
1127  if (D->isOutOfLine()) {
1128    Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1129    VarInst->setLexicalDeclContext(D->getLexicalDeclContext());
1130  }
1131
1132  Owner->addDecl(Inst);
1133
1134  if (!PrevVarTemplate) {
1135    // Queue up any out-of-line partial specializations of this member
1136    // variable template; the client will force their instantiation once
1137    // the enclosing class has been instantiated.
1138    SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1139    D->getPartialSpecializations(PartialSpecs);
1140    for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1141      if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1142        OutOfLineVarPartialSpecs.push_back(
1143            std::make_pair(Inst, PartialSpecs[I]));
1144  }
1145
1146  return Inst;
1147}
1148
1149Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
1150    VarTemplatePartialSpecializationDecl *D) {
1151  assert(D->isStaticDataMember() &&
1152         "Only static data member templates are allowed.");
1153
1154  VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
1155
1156  // Lookup the already-instantiated declaration and return that.
1157  DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
1158  assert(!Found.empty() && "Instantiation found nothing?");
1159
1160  VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1161  assert(InstVarTemplate && "Instantiation did not find a variable template?");
1162
1163  if (VarTemplatePartialSpecializationDecl *Result =
1164          InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
1165    return Result;
1166
1167  return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
1168}
1169
1170Decl *
1171TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1172  // Create a local instantiation scope for this function template, which
1173  // will contain the instantiations of the template parameters and then get
1174  // merged with the local instantiation scope for the function template
1175  // itself.
1176  LocalInstantiationScope Scope(SemaRef);
1177
1178  TemplateParameterList *TempParams = D->getTemplateParameters();
1179  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1180  if (!InstParams)
1181    return nullptr;
1182
1183  FunctionDecl *Instantiated = nullptr;
1184  if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
1185    Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
1186                                                                 InstParams));
1187  else
1188    Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
1189                                                          D->getTemplatedDecl(),
1190                                                                InstParams));
1191
1192  if (!Instantiated)
1193    return nullptr;
1194
1195  // Link the instantiated function template declaration to the function
1196  // template from which it was instantiated.
1197  FunctionTemplateDecl *InstTemplate
1198    = Instantiated->getDescribedFunctionTemplate();
1199  InstTemplate->setAccess(D->getAccess());
1200  assert(InstTemplate &&
1201         "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
1202
1203  bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
1204
1205  // Link the instantiation back to the pattern *unless* this is a
1206  // non-definition friend declaration.
1207  if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
1208      !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
1209    InstTemplate->setInstantiatedFromMemberTemplate(D);
1210
1211  // Make declarations visible in the appropriate context.
1212  if (!isFriend) {
1213    Owner->addDecl(InstTemplate);
1214  } else if (InstTemplate->getDeclContext()->isRecord() &&
1215             !getPreviousDeclForInstantiation(D)) {
1216    SemaRef.CheckFriendAccess(InstTemplate);
1217  }
1218
1219  return InstTemplate;
1220}
1221
1222Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
1223  CXXRecordDecl *PrevDecl = nullptr;
1224  if (D->isInjectedClassName())
1225    PrevDecl = cast<CXXRecordDecl>(Owner);
1226  else if (CXXRecordDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
1227    NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
1228                                                   PatternPrev,
1229                                                   TemplateArgs);
1230    if (!Prev) return nullptr;
1231    PrevDecl = cast<CXXRecordDecl>(Prev);
1232  }
1233
1234  CXXRecordDecl *Record
1235    = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
1236                            D->getLocStart(), D->getLocation(),
1237                            D->getIdentifier(), PrevDecl);
1238
1239  // Substitute the nested name specifier, if any.
1240  if (SubstQualifier(D, Record))
1241    return nullptr;
1242
1243  Record->setImplicit(D->isImplicit());
1244  // FIXME: Check against AS_none is an ugly hack to work around the issue that
1245  // the tag decls introduced by friend class declarations don't have an access
1246  // specifier. Remove once this area of the code gets sorted out.
1247  if (D->getAccess() != AS_none)
1248    Record->setAccess(D->getAccess());
1249  if (!D->isInjectedClassName())
1250    Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
1251
1252  // If the original function was part of a friend declaration,
1253  // inherit its namespace state.
1254  if (D->getFriendObjectKind())
1255    Record->setObjectOfFriendDecl();
1256
1257  // Make sure that anonymous structs and unions are recorded.
1258  if (D->isAnonymousStructOrUnion())
1259    Record->setAnonymousStructOrUnion(true);
1260
1261  if (D->isLocalClass())
1262    SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
1263
1264  // Forward the mangling number from the template to the instantiated decl.
1265  SemaRef.Context.setManglingNumber(Record,
1266                                    SemaRef.Context.getManglingNumber(D));
1267
1268  Owner->addDecl(Record);
1269
1270  // DR1484 clarifies that the members of a local class are instantiated as part
1271  // of the instantiation of their enclosing entity.
1272  if (D->isCompleteDefinition() && D->isLocalClass()) {
1273    SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
1274                             TSK_ImplicitInstantiation,
1275                             /*Complain=*/true);
1276    SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
1277                                    TSK_ImplicitInstantiation);
1278  }
1279
1280  SemaRef.DiagnoseUnusedNestedTypedefs(Record);
1281
1282  return Record;
1283}
1284
1285/// \brief Adjust the given function type for an instantiation of the
1286/// given declaration, to cope with modifications to the function's type that
1287/// aren't reflected in the type-source information.
1288///
1289/// \param D The declaration we're instantiating.
1290/// \param TInfo The already-instantiated type.
1291static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
1292                                                   FunctionDecl *D,
1293                                                   TypeSourceInfo *TInfo) {
1294  const FunctionProtoType *OrigFunc
1295    = D->getType()->castAs<FunctionProtoType>();
1296  const FunctionProtoType *NewFunc
1297    = TInfo->getType()->castAs<FunctionProtoType>();
1298  if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
1299    return TInfo->getType();
1300
1301  FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
1302  NewEPI.ExtInfo = OrigFunc->getExtInfo();
1303  return Context.getFunctionType(NewFunc->getReturnType(),
1304                                 NewFunc->getParamTypes(), NewEPI);
1305}
1306
1307/// Normal class members are of more specific types and therefore
1308/// don't make it here.  This function serves two purposes:
1309///   1) instantiating function templates
1310///   2) substituting friend declarations
1311Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
1312                                       TemplateParameterList *TemplateParams) {
1313  // Check whether there is already a function template specialization for
1314  // this declaration.
1315  FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1316  if (FunctionTemplate && !TemplateParams) {
1317    ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1318
1319    void *InsertPos = nullptr;
1320    FunctionDecl *SpecFunc
1321      = FunctionTemplate->findSpecialization(Innermost, InsertPos);
1322
1323    // If we already have a function template specialization, return it.
1324    if (SpecFunc)
1325      return SpecFunc;
1326  }
1327
1328  bool isFriend;
1329  if (FunctionTemplate)
1330    isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1331  else
1332    isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1333
1334  bool MergeWithParentScope = (TemplateParams != nullptr) ||
1335    Owner->isFunctionOrMethod() ||
1336    !(isa<Decl>(Owner) &&
1337      cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1338  LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
1339
1340  SmallVector<ParmVarDecl *, 4> Params;
1341  TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
1342  if (!TInfo)
1343    return nullptr;
1344  QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
1345
1346  NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1347  if (QualifierLoc) {
1348    QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1349                                                       TemplateArgs);
1350    if (!QualifierLoc)
1351      return nullptr;
1352  }
1353
1354  // If we're instantiating a local function declaration, put the result
1355  // in the enclosing namespace; otherwise we need to find the instantiated
1356  // context.
1357  DeclContext *DC;
1358  if (D->isLocalExternDecl()) {
1359    DC = Owner;
1360    SemaRef.adjustContextForLocalExternDecl(DC);
1361  } else if (isFriend && QualifierLoc) {
1362    CXXScopeSpec SS;
1363    SS.Adopt(QualifierLoc);
1364    DC = SemaRef.computeDeclContext(SS);
1365    if (!DC) return nullptr;
1366  } else {
1367    DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
1368                                         TemplateArgs);
1369  }
1370
1371  FunctionDecl *Function =
1372      FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1373                           D->getNameInfo(), T, TInfo,
1374                           D->getCanonicalDecl()->getStorageClass(),
1375                           D->isInlineSpecified(), D->hasWrittenPrototype(),
1376                           D->isConstexpr());
1377  Function->setRangeEnd(D->getSourceRange().getEnd());
1378
1379  if (D->isInlined())
1380    Function->setImplicitlyInline();
1381
1382  if (QualifierLoc)
1383    Function->setQualifierInfo(QualifierLoc);
1384
1385  if (D->isLocalExternDecl())
1386    Function->setLocalExternDecl();
1387
1388  DeclContext *LexicalDC = Owner;
1389  if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
1390    assert(D->getDeclContext()->isFileContext());
1391    LexicalDC = D->getDeclContext();
1392  }
1393
1394  Function->setLexicalDeclContext(LexicalDC);
1395
1396  // Attach the parameters
1397  for (unsigned P = 0; P < Params.size(); ++P)
1398    if (Params[P])
1399      Params[P]->setOwningFunction(Function);
1400  Function->setParams(Params);
1401
1402  SourceLocation InstantiateAtPOI;
1403  if (TemplateParams) {
1404    // Our resulting instantiation is actually a function template, since we
1405    // are substituting only the outer template parameters. For example, given
1406    //
1407    //   template<typename T>
1408    //   struct X {
1409    //     template<typename U> friend void f(T, U);
1410    //   };
1411    //
1412    //   X<int> x;
1413    //
1414    // We are instantiating the friend function template "f" within X<int>,
1415    // which means substituting int for T, but leaving "f" as a friend function
1416    // template.
1417    // Build the function template itself.
1418    FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
1419                                                    Function->getLocation(),
1420                                                    Function->getDeclName(),
1421                                                    TemplateParams, Function);
1422    Function->setDescribedFunctionTemplate(FunctionTemplate);
1423
1424    FunctionTemplate->setLexicalDeclContext(LexicalDC);
1425
1426    if (isFriend && D->isThisDeclarationADefinition()) {
1427      // TODO: should we remember this connection regardless of whether
1428      // the friend declaration provided a body?
1429      FunctionTemplate->setInstantiatedFromMemberTemplate(
1430                                           D->getDescribedFunctionTemplate());
1431    }
1432  } else if (FunctionTemplate) {
1433    // Record this function template specialization.
1434    ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1435    Function->setFunctionTemplateSpecialization(FunctionTemplate,
1436                            TemplateArgumentList::CreateCopy(SemaRef.Context,
1437                                                             Innermost.begin(),
1438                                                             Innermost.size()),
1439                                                /*InsertPos=*/nullptr);
1440  } else if (isFriend) {
1441    // Note, we need this connection even if the friend doesn't have a body.
1442    // Its body may exist but not have been attached yet due to deferred
1443    // parsing.
1444    // FIXME: It might be cleaner to set this when attaching the body to the
1445    // friend function declaration, however that would require finding all the
1446    // instantiations and modifying them.
1447    Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
1448  }
1449
1450  if (InitFunctionInstantiation(Function, D))
1451    Function->setInvalidDecl();
1452
1453  bool isExplicitSpecialization = false;
1454
1455  LookupResult Previous(
1456      SemaRef, Function->getDeclName(), SourceLocation(),
1457      D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
1458                             : Sema::LookupOrdinaryName,
1459      Sema::ForRedeclaration);
1460
1461  if (DependentFunctionTemplateSpecializationInfo *Info
1462        = D->getDependentSpecializationInfo()) {
1463    assert(isFriend && "non-friend has dependent specialization info?");
1464
1465    // This needs to be set now for future sanity.
1466    Function->setObjectOfFriendDecl();
1467
1468    // Instantiate the explicit template arguments.
1469    TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1470                                          Info->getRAngleLoc());
1471    if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1472                      ExplicitArgs, TemplateArgs))
1473      return nullptr;
1474
1475    // Map the candidate templates to their instantiations.
1476    for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1477      Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1478                                                Info->getTemplate(I),
1479                                                TemplateArgs);
1480      if (!Temp) return nullptr;
1481
1482      Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1483    }
1484
1485    if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1486                                                    &ExplicitArgs,
1487                                                    Previous))
1488      Function->setInvalidDecl();
1489
1490    isExplicitSpecialization = true;
1491
1492  } else if (TemplateParams || !FunctionTemplate) {
1493    // Look only into the namespace where the friend would be declared to
1494    // find a previous declaration. This is the innermost enclosing namespace,
1495    // as described in ActOnFriendFunctionDecl.
1496    SemaRef.LookupQualifiedName(Previous, DC);
1497
1498    // In C++, the previous declaration we find might be a tag type
1499    // (class or enum). In this case, the new declaration will hide the
1500    // tag type. Note that this does does not apply if we're declaring a
1501    // typedef (C++ [dcl.typedef]p4).
1502    if (Previous.isSingleTagDecl())
1503      Previous.clear();
1504  }
1505
1506  SemaRef.CheckFunctionDeclaration(/*Scope*/ nullptr, Function, Previous,
1507                                   isExplicitSpecialization);
1508
1509  NamedDecl *PrincipalDecl = (TemplateParams
1510                              ? cast<NamedDecl>(FunctionTemplate)
1511                              : Function);
1512
1513  // If the original function was part of a friend declaration,
1514  // inherit its namespace state and add it to the owner.
1515  if (isFriend) {
1516    PrincipalDecl->setObjectOfFriendDecl();
1517    DC->makeDeclVisibleInContext(PrincipalDecl);
1518
1519    bool QueuedInstantiation = false;
1520
1521    // C++11 [temp.friend]p4 (DR329):
1522    //   When a function is defined in a friend function declaration in a class
1523    //   template, the function is instantiated when the function is odr-used.
1524    //   The same restrictions on multiple declarations and definitions that
1525    //   apply to non-template function declarations and definitions also apply
1526    //   to these implicit definitions.
1527    if (D->isThisDeclarationADefinition()) {
1528      // Check for a function body.
1529      const FunctionDecl *Definition = nullptr;
1530      if (Function->isDefined(Definition) &&
1531          Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
1532        SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1533            << Function->getDeclName();
1534        SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
1535      }
1536      // Check for redefinitions due to other instantiations of this or
1537      // a similar friend function.
1538      else for (auto R : Function->redecls()) {
1539        if (R == Function)
1540          continue;
1541
1542        // If some prior declaration of this function has been used, we need
1543        // to instantiate its definition.
1544        if (!QueuedInstantiation && R->isUsed(false)) {
1545          if (MemberSpecializationInfo *MSInfo =
1546                  Function->getMemberSpecializationInfo()) {
1547            if (MSInfo->getPointOfInstantiation().isInvalid()) {
1548              SourceLocation Loc = R->getLocation(); // FIXME
1549              MSInfo->setPointOfInstantiation(Loc);
1550              SemaRef.PendingLocalImplicitInstantiations.push_back(
1551                                               std::make_pair(Function, Loc));
1552              QueuedInstantiation = true;
1553            }
1554          }
1555        }
1556
1557        // If some prior declaration of this function was a friend with an
1558        // uninstantiated definition, reject it.
1559        if (R->getFriendObjectKind()) {
1560          if (const FunctionDecl *RPattern =
1561                  R->getTemplateInstantiationPattern()) {
1562            if (RPattern->isDefined(RPattern)) {
1563              SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1564                << Function->getDeclName();
1565              SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
1566              break;
1567            }
1568          }
1569        }
1570      }
1571    }
1572  }
1573
1574  if (Function->isLocalExternDecl() && !Function->getPreviousDecl())
1575    DC->makeDeclVisibleInContext(PrincipalDecl);
1576
1577  if (Function->isOverloadedOperator() && !DC->isRecord() &&
1578      PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1579    PrincipalDecl->setNonMemberOperator();
1580
1581  assert(!D->isDefaulted() && "only methods should be defaulted");
1582  return Function;
1583}
1584
1585Decl *
1586TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1587                                      TemplateParameterList *TemplateParams,
1588                                      bool IsClassScopeSpecialization) {
1589  FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1590  if (FunctionTemplate && !TemplateParams) {
1591    // We are creating a function template specialization from a function
1592    // template. Check whether there is already a function template
1593    // specialization for this particular set of template arguments.
1594    ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1595
1596    void *InsertPos = nullptr;
1597    FunctionDecl *SpecFunc
1598      = FunctionTemplate->findSpecialization(Innermost, InsertPos);
1599
1600    // If we already have a function template specialization, return it.
1601    if (SpecFunc)
1602      return SpecFunc;
1603  }
1604
1605  bool isFriend;
1606  if (FunctionTemplate)
1607    isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1608  else
1609    isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1610
1611  bool MergeWithParentScope = (TemplateParams != nullptr) ||
1612    !(isa<Decl>(Owner) &&
1613      cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1614  LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
1615
1616  // Instantiate enclosing template arguments for friends.
1617  SmallVector<TemplateParameterList *, 4> TempParamLists;
1618  unsigned NumTempParamLists = 0;
1619  if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1620    TempParamLists.set_size(NumTempParamLists);
1621    for (unsigned I = 0; I != NumTempParamLists; ++I) {
1622      TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1623      TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1624      if (!InstParams)
1625        return nullptr;
1626      TempParamLists[I] = InstParams;
1627    }
1628  }
1629
1630  SmallVector<ParmVarDecl *, 4> Params;
1631  TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
1632  if (!TInfo)
1633    return nullptr;
1634  QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
1635
1636  NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1637  if (QualifierLoc) {
1638    QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1639                                                 TemplateArgs);
1640    if (!QualifierLoc)
1641      return nullptr;
1642  }
1643
1644  DeclContext *DC = Owner;
1645  if (isFriend) {
1646    if (QualifierLoc) {
1647      CXXScopeSpec SS;
1648      SS.Adopt(QualifierLoc);
1649      DC = SemaRef.computeDeclContext(SS);
1650
1651      if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
1652        return nullptr;
1653    } else {
1654      DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1655                                           D->getDeclContext(),
1656                                           TemplateArgs);
1657    }
1658    if (!DC) return nullptr;
1659  }
1660
1661  // Build the instantiated method declaration.
1662  CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1663  CXXMethodDecl *Method = nullptr;
1664
1665  SourceLocation StartLoc = D->getInnerLocStart();
1666  DeclarationNameInfo NameInfo
1667    = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1668  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
1669    Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
1670                                        StartLoc, NameInfo, T, TInfo,
1671                                        Constructor->isExplicit(),
1672                                        Constructor->isInlineSpecified(),
1673                                        false, Constructor->isConstexpr());
1674
1675    // Claim that the instantiation of a constructor or constructor template
1676    // inherits the same constructor that the template does.
1677    if (CXXConstructorDecl *Inh = const_cast<CXXConstructorDecl *>(
1678            Constructor->getInheritedConstructor())) {
1679      // If we're instantiating a specialization of a function template, our
1680      // "inherited constructor" will actually itself be a function template.
1681      // Instantiate a declaration of it, too.
1682      if (FunctionTemplate) {
1683        assert(!TemplateParams && Inh->getDescribedFunctionTemplate() &&
1684               !Inh->getParent()->isDependentContext() &&
1685               "inheriting constructor template in dependent context?");
1686        Sema::InstantiatingTemplate Inst(SemaRef, Constructor->getLocation(),
1687                                         Inh);
1688        if (Inst.isInvalid())
1689          return nullptr;
1690        Sema::ContextRAII SavedContext(SemaRef, Inh->getDeclContext());
1691        LocalInstantiationScope LocalScope(SemaRef);
1692
1693        // Use the same template arguments that we deduced for the inheriting
1694        // constructor. There's no way they could be deduced differently.
1695        MultiLevelTemplateArgumentList InheritedArgs;
1696        InheritedArgs.addOuterTemplateArguments(TemplateArgs.getInnermost());
1697        Inh = cast_or_null<CXXConstructorDecl>(
1698            SemaRef.SubstDecl(Inh, Inh->getDeclContext(), InheritedArgs));
1699        if (!Inh)
1700          return nullptr;
1701      }
1702      cast<CXXConstructorDecl>(Method)->setInheritedConstructor(Inh);
1703    }
1704  } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
1705    Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
1706                                       StartLoc, NameInfo, T, TInfo,
1707                                       Destructor->isInlineSpecified(),
1708                                       false);
1709  } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
1710    Method = CXXConversionDecl::Create(SemaRef.Context, Record,
1711                                       StartLoc, NameInfo, T, TInfo,
1712                                       Conversion->isInlineSpecified(),
1713                                       Conversion->isExplicit(),
1714                                       Conversion->isConstexpr(),
1715                                       Conversion->getLocEnd());
1716  } else {
1717    StorageClass SC = D->isStatic() ? SC_Static : SC_None;
1718    Method = CXXMethodDecl::Create(SemaRef.Context, Record,
1719                                   StartLoc, NameInfo, T, TInfo,
1720                                   SC, D->isInlineSpecified(),
1721                                   D->isConstexpr(), D->getLocEnd());
1722  }
1723
1724  if (D->isInlined())
1725    Method->setImplicitlyInline();
1726
1727  if (QualifierLoc)
1728    Method->setQualifierInfo(QualifierLoc);
1729
1730  if (TemplateParams) {
1731    // Our resulting instantiation is actually a function template, since we
1732    // are substituting only the outer template parameters. For example, given
1733    //
1734    //   template<typename T>
1735    //   struct X {
1736    //     template<typename U> void f(T, U);
1737    //   };
1738    //
1739    //   X<int> x;
1740    //
1741    // We are instantiating the member template "f" within X<int>, which means
1742    // substituting int for T, but leaving "f" as a member function template.
1743    // Build the function template itself.
1744    FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1745                                                    Method->getLocation(),
1746                                                    Method->getDeclName(),
1747                                                    TemplateParams, Method);
1748    if (isFriend) {
1749      FunctionTemplate->setLexicalDeclContext(Owner);
1750      FunctionTemplate->setObjectOfFriendDecl();
1751    } else if (D->isOutOfLine())
1752      FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
1753    Method->setDescribedFunctionTemplate(FunctionTemplate);
1754  } else if (FunctionTemplate) {
1755    // Record this function template specialization.
1756    ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1757    Method->setFunctionTemplateSpecialization(FunctionTemplate,
1758                         TemplateArgumentList::CreateCopy(SemaRef.Context,
1759                                                          Innermost.begin(),
1760                                                          Innermost.size()),
1761                                              /*InsertPos=*/nullptr);
1762  } else if (!isFriend) {
1763    // Record that this is an instantiation of a member function.
1764    Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
1765  }
1766
1767  // If we are instantiating a member function defined
1768  // out-of-line, the instantiation will have the same lexical
1769  // context (which will be a namespace scope) as the template.
1770  if (isFriend) {
1771    if (NumTempParamLists)
1772      Method->setTemplateParameterListsInfo(SemaRef.Context,
1773                                            NumTempParamLists,
1774                                            TempParamLists.data());
1775
1776    Method->setLexicalDeclContext(Owner);
1777    Method->setObjectOfFriendDecl();
1778  } else if (D->isOutOfLine())
1779    Method->setLexicalDeclContext(D->getLexicalDeclContext());
1780
1781  // Attach the parameters
1782  for (unsigned P = 0; P < Params.size(); ++P)
1783    Params[P]->setOwningFunction(Method);
1784  Method->setParams(Params);
1785
1786  if (InitMethodInstantiation(Method, D))
1787    Method->setInvalidDecl();
1788
1789  LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1790                        Sema::ForRedeclaration);
1791
1792  if (!FunctionTemplate || TemplateParams || isFriend) {
1793    SemaRef.LookupQualifiedName(Previous, Record);
1794
1795    // In C++, the previous declaration we find might be a tag type
1796    // (class or enum). In this case, the new declaration will hide the
1797    // tag type. Note that this does does not apply if we're declaring a
1798    // typedef (C++ [dcl.typedef]p4).
1799    if (Previous.isSingleTagDecl())
1800      Previous.clear();
1801  }
1802
1803  if (!IsClassScopeSpecialization)
1804    SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous, false);
1805
1806  if (D->isPure())
1807    SemaRef.CheckPureMethod(Method, SourceRange());
1808
1809  // Propagate access.  For a non-friend declaration, the access is
1810  // whatever we're propagating from.  For a friend, it should be the
1811  // previous declaration we just found.
1812  if (isFriend && Method->getPreviousDecl())
1813    Method->setAccess(Method->getPreviousDecl()->getAccess());
1814  else
1815    Method->setAccess(D->getAccess());
1816  if (FunctionTemplate)
1817    FunctionTemplate->setAccess(Method->getAccess());
1818
1819  SemaRef.CheckOverrideControl(Method);
1820
1821  // If a function is defined as defaulted or deleted, mark it as such now.
1822  if (D->isExplicitlyDefaulted())
1823    SemaRef.SetDeclDefaulted(Method, Method->getLocation());
1824  if (D->isDeletedAsWritten())
1825    SemaRef.SetDeclDeleted(Method, Method->getLocation());
1826
1827  // If there's a function template, let our caller handle it.
1828  if (FunctionTemplate) {
1829    // do nothing
1830
1831  // Don't hide a (potentially) valid declaration with an invalid one.
1832  } else if (Method->isInvalidDecl() && !Previous.empty()) {
1833    // do nothing
1834
1835  // Otherwise, check access to friends and make them visible.
1836  } else if (isFriend) {
1837    // We only need to re-check access for methods which we didn't
1838    // manage to match during parsing.
1839    if (!D->getPreviousDecl())
1840      SemaRef.CheckFriendAccess(Method);
1841
1842    Record->makeDeclVisibleInContext(Method);
1843
1844  // Otherwise, add the declaration.  We don't need to do this for
1845  // class-scope specializations because we'll have matched them with
1846  // the appropriate template.
1847  } else if (!IsClassScopeSpecialization) {
1848    Owner->addDecl(Method);
1849  }
1850
1851  return Method;
1852}
1853
1854Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
1855  return VisitCXXMethodDecl(D);
1856}
1857
1858Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
1859  return VisitCXXMethodDecl(D);
1860}
1861
1862Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
1863  return VisitCXXMethodDecl(D);
1864}
1865
1866Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
1867  return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None,
1868                                  /*ExpectParameterPack=*/ false);
1869}
1870
1871Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1872                                                    TemplateTypeParmDecl *D) {
1873  // TODO: don't always clone when decls are refcounted.
1874  assert(D->getTypeForDecl()->isTemplateTypeParmType());
1875
1876  TemplateTypeParmDecl *Inst =
1877    TemplateTypeParmDecl::Create(SemaRef.Context, Owner,
1878                                 D->getLocStart(), D->getLocation(),
1879                                 D->getDepth() - TemplateArgs.getNumLevels(),
1880                                 D->getIndex(), D->getIdentifier(),
1881                                 D->wasDeclaredWithTypename(),
1882                                 D->isParameterPack());
1883  Inst->setAccess(AS_public);
1884
1885  if (D->hasDefaultArgument()) {
1886    TypeSourceInfo *InstantiatedDefaultArg =
1887        SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs,
1888                          D->getDefaultArgumentLoc(), D->getDeclName());
1889    if (InstantiatedDefaultArg)
1890      Inst->setDefaultArgument(InstantiatedDefaultArg, false);
1891  }
1892
1893  // Introduce this template parameter's instantiation into the instantiation
1894  // scope.
1895  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1896
1897  return Inst;
1898}
1899
1900Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1901                                                 NonTypeTemplateParmDecl *D) {
1902  // Substitute into the type of the non-type template parameter.
1903  TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
1904  SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
1905  SmallVector<QualType, 4> ExpandedParameterPackTypes;
1906  bool IsExpandedParameterPack = false;
1907  TypeSourceInfo *DI;
1908  QualType T;
1909  bool Invalid = false;
1910
1911  if (D->isExpandedParameterPack()) {
1912    // The non-type template parameter pack is an already-expanded pack
1913    // expansion of types. Substitute into each of the expanded types.
1914    ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
1915    ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
1916    for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1917      TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I),
1918                                               TemplateArgs,
1919                                               D->getLocation(),
1920                                               D->getDeclName());
1921      if (!NewDI)
1922        return nullptr;
1923
1924      ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1925      QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
1926                                                              D->getLocation());
1927      if (NewT.isNull())
1928        return nullptr;
1929      ExpandedParameterPackTypes.push_back(NewT);
1930    }
1931
1932    IsExpandedParameterPack = true;
1933    DI = D->getTypeSourceInfo();
1934    T = DI->getType();
1935  } else if (D->isPackExpansion()) {
1936    // The non-type template parameter pack's type is a pack expansion of types.
1937    // Determine whether we need to expand this parameter pack into separate
1938    // types.
1939    PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
1940    TypeLoc Pattern = Expansion.getPatternLoc();
1941    SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1942    SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
1943
1944    // Determine whether the set of unexpanded parameter packs can and should
1945    // be expanded.
1946    bool Expand = true;
1947    bool RetainExpansion = false;
1948    Optional<unsigned> OrigNumExpansions
1949      = Expansion.getTypePtr()->getNumExpansions();
1950    Optional<unsigned> NumExpansions = OrigNumExpansions;
1951    if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
1952                                                Pattern.getSourceRange(),
1953                                                Unexpanded,
1954                                                TemplateArgs,
1955                                                Expand, RetainExpansion,
1956                                                NumExpansions))
1957      return nullptr;
1958
1959    if (Expand) {
1960      for (unsigned I = 0; I != *NumExpansions; ++I) {
1961        Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1962        TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
1963                                                  D->getLocation(),
1964                                                  D->getDeclName());
1965        if (!NewDI)
1966          return nullptr;
1967
1968        ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1969        QualType NewT = SemaRef.CheckNonTypeTemplateParameterType(
1970                                                              NewDI->getType(),
1971                                                              D->getLocation());
1972        if (NewT.isNull())
1973          return nullptr;
1974        ExpandedParameterPackTypes.push_back(NewT);
1975      }
1976
1977      // Note that we have an expanded parameter pack. The "type" of this
1978      // expanded parameter pack is the original expansion type, but callers
1979      // will end up using the expanded parameter pack types for type-checking.
1980      IsExpandedParameterPack = true;
1981      DI = D->getTypeSourceInfo();
1982      T = DI->getType();
1983    } else {
1984      // We cannot fully expand the pack expansion now, so substitute into the
1985      // pattern and create a new pack expansion type.
1986      Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1987      TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
1988                                                     D->getLocation(),
1989                                                     D->getDeclName());
1990      if (!NewPattern)
1991        return nullptr;
1992
1993      DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
1994                                      NumExpansions);
1995      if (!DI)
1996        return nullptr;
1997
1998      T = DI->getType();
1999    }
2000  } else {
2001    // Simple case: substitution into a parameter that is not a parameter pack.
2002    DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
2003                           D->getLocation(), D->getDeclName());
2004    if (!DI)
2005      return nullptr;
2006
2007    // Check that this type is acceptable for a non-type template parameter.
2008    T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
2009                                                  D->getLocation());
2010    if (T.isNull()) {
2011      T = SemaRef.Context.IntTy;
2012      Invalid = true;
2013    }
2014  }
2015
2016  NonTypeTemplateParmDecl *Param;
2017  if (IsExpandedParameterPack)
2018    Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
2019                                            D->getInnerLocStart(),
2020                                            D->getLocation(),
2021                                    D->getDepth() - TemplateArgs.getNumLevels(),
2022                                            D->getPosition(),
2023                                            D->getIdentifier(), T,
2024                                            DI,
2025                                            ExpandedParameterPackTypes.data(),
2026                                            ExpandedParameterPackTypes.size(),
2027                                    ExpandedParameterPackTypesAsWritten.data());
2028  else
2029    Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
2030                                            D->getInnerLocStart(),
2031                                            D->getLocation(),
2032                                    D->getDepth() - TemplateArgs.getNumLevels(),
2033                                            D->getPosition(),
2034                                            D->getIdentifier(), T,
2035                                            D->isParameterPack(), DI);
2036
2037  Param->setAccess(AS_public);
2038  if (Invalid)
2039    Param->setInvalidDecl();
2040
2041  if (D->hasDefaultArgument()) {
2042    ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs);
2043    if (!Value.isInvalid())
2044      Param->setDefaultArgument(Value.get(), false);
2045  }
2046
2047  // Introduce this template parameter's instantiation into the instantiation
2048  // scope.
2049  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
2050  return Param;
2051}
2052
2053static void collectUnexpandedParameterPacks(
2054    Sema &S,
2055    TemplateParameterList *Params,
2056    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
2057  for (TemplateParameterList::const_iterator I = Params->begin(),
2058                                             E = Params->end(); I != E; ++I) {
2059    if ((*I)->isTemplateParameterPack())
2060      continue;
2061    if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*I))
2062      S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
2063                                        Unexpanded);
2064    if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(*I))
2065      collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
2066                                      Unexpanded);
2067  }
2068}
2069
2070Decl *
2071TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
2072                                                  TemplateTemplateParmDecl *D) {
2073  // Instantiate the template parameter list of the template template parameter.
2074  TemplateParameterList *TempParams = D->getTemplateParameters();
2075  TemplateParameterList *InstParams;
2076  SmallVector<TemplateParameterList*, 8> ExpandedParams;
2077
2078  bool IsExpandedParameterPack = false;
2079
2080  if (D->isExpandedParameterPack()) {
2081    // The template template parameter pack is an already-expanded pack
2082    // expansion of template parameters. Substitute into each of the expanded
2083    // parameters.
2084    ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
2085    for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
2086         I != N; ++I) {
2087      LocalInstantiationScope Scope(SemaRef);
2088      TemplateParameterList *Expansion =
2089        SubstTemplateParams(D->getExpansionTemplateParameters(I));
2090      if (!Expansion)
2091        return nullptr;
2092      ExpandedParams.push_back(Expansion);
2093    }
2094
2095    IsExpandedParameterPack = true;
2096    InstParams = TempParams;
2097  } else if (D->isPackExpansion()) {
2098    // The template template parameter pack expands to a pack of template
2099    // template parameters. Determine whether we need to expand this parameter
2100    // pack into separate parameters.
2101    SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2102    collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
2103                                    Unexpanded);
2104
2105    // Determine whether the set of unexpanded parameter packs can and should
2106    // be expanded.
2107    bool Expand = true;
2108    bool RetainExpansion = false;
2109    Optional<unsigned> NumExpansions;
2110    if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
2111                                                TempParams->getSourceRange(),
2112                                                Unexpanded,
2113                                                TemplateArgs,
2114                                                Expand, RetainExpansion,
2115                                                NumExpansions))
2116      return nullptr;
2117
2118    if (Expand) {
2119      for (unsigned I = 0; I != *NumExpansions; ++I) {
2120        Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2121        LocalInstantiationScope Scope(SemaRef);
2122        TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
2123        if (!Expansion)
2124          return nullptr;
2125        ExpandedParams.push_back(Expansion);
2126      }
2127
2128      // Note that we have an expanded parameter pack. The "type" of this
2129      // expanded parameter pack is the original expansion type, but callers
2130      // will end up using the expanded parameter pack types for type-checking.
2131      IsExpandedParameterPack = true;
2132      InstParams = TempParams;
2133    } else {
2134      // We cannot fully expand the pack expansion now, so just substitute
2135      // into the pattern.
2136      Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2137
2138      LocalInstantiationScope Scope(SemaRef);
2139      InstParams = SubstTemplateParams(TempParams);
2140      if (!InstParams)
2141        return nullptr;
2142    }
2143  } else {
2144    // Perform the actual substitution of template parameters within a new,
2145    // local instantiation scope.
2146    LocalInstantiationScope Scope(SemaRef);
2147    InstParams = SubstTemplateParams(TempParams);
2148    if (!InstParams)
2149      return nullptr;
2150  }
2151
2152  // Build the template template parameter.
2153  TemplateTemplateParmDecl *Param;
2154  if (IsExpandedParameterPack)
2155    Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2156                                             D->getLocation(),
2157                                   D->getDepth() - TemplateArgs.getNumLevels(),
2158                                             D->getPosition(),
2159                                             D->getIdentifier(), InstParams,
2160                                             ExpandedParams);
2161  else
2162    Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2163                                             D->getLocation(),
2164                                   D->getDepth() - TemplateArgs.getNumLevels(),
2165                                             D->getPosition(),
2166                                             D->isParameterPack(),
2167                                             D->getIdentifier(), InstParams);
2168  if (D->hasDefaultArgument()) {
2169    NestedNameSpecifierLoc QualifierLoc =
2170        D->getDefaultArgument().getTemplateQualifierLoc();
2171    QualifierLoc =
2172        SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
2173    TemplateName TName = SemaRef.SubstTemplateName(
2174        QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
2175        D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
2176    if (!TName.isNull())
2177      Param->setDefaultArgument(
2178          TemplateArgumentLoc(TemplateArgument(TName),
2179                              D->getDefaultArgument().getTemplateQualifierLoc(),
2180                              D->getDefaultArgument().getTemplateNameLoc()),
2181          false);
2182  }
2183  Param->setAccess(AS_public);
2184
2185  // Introduce this template parameter's instantiation into the instantiation
2186  // scope.
2187  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
2188
2189  return Param;
2190}
2191
2192Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
2193  // Using directives are never dependent (and never contain any types or
2194  // expressions), so they require no explicit instantiation work.
2195
2196  UsingDirectiveDecl *Inst
2197    = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
2198                                 D->getNamespaceKeyLocation(),
2199                                 D->getQualifierLoc(),
2200                                 D->getIdentLocation(),
2201                                 D->getNominatedNamespace(),
2202                                 D->getCommonAncestor());
2203
2204  // Add the using directive to its declaration context
2205  // only if this is not a function or method.
2206  if (!Owner->isFunctionOrMethod())
2207    Owner->addDecl(Inst);
2208
2209  return Inst;
2210}
2211
2212Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
2213
2214  // The nested name specifier may be dependent, for example
2215  //     template <typename T> struct t {
2216  //       struct s1 { T f1(); };
2217  //       struct s2 : s1 { using s1::f1; };
2218  //     };
2219  //     template struct t<int>;
2220  // Here, in using s1::f1, s1 refers to t<T>::s1;
2221  // we need to substitute for t<int>::s1.
2222  NestedNameSpecifierLoc QualifierLoc
2223    = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2224                                          TemplateArgs);
2225  if (!QualifierLoc)
2226    return nullptr;
2227
2228  // The name info is non-dependent, so no transformation
2229  // is required.
2230  DeclarationNameInfo NameInfo = D->getNameInfo();
2231
2232  // We only need to do redeclaration lookups if we're in a class
2233  // scope (in fact, it's not really even possible in non-class
2234  // scopes).
2235  bool CheckRedeclaration = Owner->isRecord();
2236
2237  LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
2238                    Sema::ForRedeclaration);
2239
2240  UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
2241                                       D->getUsingLoc(),
2242                                       QualifierLoc,
2243                                       NameInfo,
2244                                       D->hasTypename());
2245
2246  CXXScopeSpec SS;
2247  SS.Adopt(QualifierLoc);
2248  if (CheckRedeclaration) {
2249    Prev.setHideTags(false);
2250    SemaRef.LookupQualifiedName(Prev, Owner);
2251
2252    // Check for invalid redeclarations.
2253    if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
2254                                            D->hasTypename(), SS,
2255                                            D->getLocation(), Prev))
2256      NewUD->setInvalidDecl();
2257
2258  }
2259
2260  if (!NewUD->isInvalidDecl() &&
2261      SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), SS, NameInfo,
2262                                      D->getLocation()))
2263    NewUD->setInvalidDecl();
2264
2265  SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
2266  NewUD->setAccess(D->getAccess());
2267  Owner->addDecl(NewUD);
2268
2269  // Don't process the shadow decls for an invalid decl.
2270  if (NewUD->isInvalidDecl())
2271    return NewUD;
2272
2273  if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
2274    SemaRef.CheckInheritingConstructorUsingDecl(NewUD);
2275    return NewUD;
2276  }
2277
2278  bool isFunctionScope = Owner->isFunctionOrMethod();
2279
2280  // Process the shadow decls.
2281  for (auto *Shadow : D->shadows()) {
2282    NamedDecl *InstTarget =
2283        cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
2284            Shadow->getLocation(), Shadow->getTargetDecl(), TemplateArgs));
2285    if (!InstTarget)
2286      return nullptr;
2287
2288    UsingShadowDecl *PrevDecl = nullptr;
2289    if (CheckRedeclaration) {
2290      if (SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev, PrevDecl))
2291        continue;
2292    } else if (UsingShadowDecl *OldPrev =
2293                   getPreviousDeclForInstantiation(Shadow)) {
2294      PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
2295          Shadow->getLocation(), OldPrev, TemplateArgs));
2296    }
2297
2298    UsingShadowDecl *InstShadow =
2299        SemaRef.BuildUsingShadowDecl(/*Scope*/nullptr, NewUD, InstTarget,
2300                                     PrevDecl);
2301    SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
2302
2303    if (isFunctionScope)
2304      SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
2305  }
2306
2307  return NewUD;
2308}
2309
2310Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
2311  // Ignore these;  we handle them in bulk when processing the UsingDecl.
2312  return nullptr;
2313}
2314
2315Decl * TemplateDeclInstantiator
2316    ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
2317  NestedNameSpecifierLoc QualifierLoc
2318    = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2319                                          TemplateArgs);
2320  if (!QualifierLoc)
2321    return nullptr;
2322
2323  CXXScopeSpec SS;
2324  SS.Adopt(QualifierLoc);
2325
2326  // Since NameInfo refers to a typename, it cannot be a C++ special name.
2327  // Hence, no transformation is required for it.
2328  DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
2329  NamedDecl *UD =
2330    SemaRef.BuildUsingDeclaration(/*Scope*/ nullptr, D->getAccess(),
2331                                  D->getUsingLoc(), SS, NameInfo, nullptr,
2332                                  /*instantiation*/ true,
2333                                  /*typename*/ true, D->getTypenameLoc());
2334  if (UD)
2335    SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2336
2337  return UD;
2338}
2339
2340Decl * TemplateDeclInstantiator
2341    ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
2342  NestedNameSpecifierLoc QualifierLoc
2343      = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs);
2344  if (!QualifierLoc)
2345    return nullptr;
2346
2347  CXXScopeSpec SS;
2348  SS.Adopt(QualifierLoc);
2349
2350  DeclarationNameInfo NameInfo
2351    = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2352
2353  NamedDecl *UD =
2354    SemaRef.BuildUsingDeclaration(/*Scope*/ nullptr, D->getAccess(),
2355                                  D->getUsingLoc(), SS, NameInfo, nullptr,
2356                                  /*instantiation*/ true,
2357                                  /*typename*/ false, SourceLocation());
2358  if (UD)
2359    SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2360
2361  return UD;
2362}
2363
2364
2365Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
2366                                     ClassScopeFunctionSpecializationDecl *Decl) {
2367  CXXMethodDecl *OldFD = Decl->getSpecialization();
2368  CXXMethodDecl *NewFD =
2369    cast_or_null<CXXMethodDecl>(VisitCXXMethodDecl(OldFD, nullptr, true));
2370  if (!NewFD)
2371    return nullptr;
2372
2373  LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName,
2374                        Sema::ForRedeclaration);
2375
2376  TemplateArgumentListInfo TemplateArgs;
2377  TemplateArgumentListInfo *TemplateArgsPtr = nullptr;
2378  if (Decl->hasExplicitTemplateArgs()) {
2379    TemplateArgs = Decl->templateArgs();
2380    TemplateArgsPtr = &TemplateArgs;
2381  }
2382
2383  SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext);
2384  if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, TemplateArgsPtr,
2385                                                  Previous)) {
2386    NewFD->setInvalidDecl();
2387    return NewFD;
2388  }
2389
2390  // Associate the specialization with the pattern.
2391  FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl());
2392  assert(Specialization && "Class scope Specialization is null");
2393  SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD);
2394
2395  return NewFD;
2396}
2397
2398Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
2399                                     OMPThreadPrivateDecl *D) {
2400  SmallVector<Expr *, 5> Vars;
2401  for (auto *I : D->varlists()) {
2402    Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
2403    assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
2404    Vars.push_back(Var);
2405  }
2406
2407  OMPThreadPrivateDecl *TD =
2408    SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
2409
2410  TD->setAccess(AS_public);
2411  Owner->addDecl(TD);
2412
2413  return TD;
2414}
2415
2416Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
2417  return VisitFunctionDecl(D, nullptr);
2418}
2419
2420Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
2421  return VisitCXXMethodDecl(D, nullptr);
2422}
2423
2424Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
2425  llvm_unreachable("There are only CXXRecordDecls in C++");
2426}
2427
2428Decl *
2429TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
2430    ClassTemplateSpecializationDecl *D) {
2431  // As a MS extension, we permit class-scope explicit specialization
2432  // of member class templates.
2433  ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
2434  assert(ClassTemplate->getDeclContext()->isRecord() &&
2435         D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
2436         "can only instantiate an explicit specialization "
2437         "for a member class template");
2438
2439  // Lookup the already-instantiated declaration in the instantiation
2440  // of the class template. FIXME: Diagnose or assert if this fails?
2441  DeclContext::lookup_result Found
2442    = Owner->lookup(ClassTemplate->getDeclName());
2443  if (Found.empty())
2444    return nullptr;
2445  ClassTemplateDecl *InstClassTemplate
2446    = dyn_cast<ClassTemplateDecl>(Found.front());
2447  if (!InstClassTemplate)
2448    return nullptr;
2449
2450  // Substitute into the template arguments of the class template explicit
2451  // specialization.
2452  TemplateSpecializationTypeLoc Loc = D->getTypeAsWritten()->getTypeLoc().
2453                                        castAs<TemplateSpecializationTypeLoc>();
2454  TemplateArgumentListInfo InstTemplateArgs(Loc.getLAngleLoc(),
2455                                            Loc.getRAngleLoc());
2456  SmallVector<TemplateArgumentLoc, 4> ArgLocs;
2457  for (unsigned I = 0; I != Loc.getNumArgs(); ++I)
2458    ArgLocs.push_back(Loc.getArgLoc(I));
2459  if (SemaRef.Subst(ArgLocs.data(), ArgLocs.size(),
2460                    InstTemplateArgs, TemplateArgs))
2461    return nullptr;
2462
2463  // Check that the template argument list is well-formed for this
2464  // class template.
2465  SmallVector<TemplateArgument, 4> Converted;
2466  if (SemaRef.CheckTemplateArgumentList(InstClassTemplate,
2467                                        D->getLocation(),
2468                                        InstTemplateArgs,
2469                                        false,
2470                                        Converted))
2471    return nullptr;
2472
2473  // Figure out where to insert this class template explicit specialization
2474  // in the member template's set of class template explicit specializations.
2475  void *InsertPos = nullptr;
2476  ClassTemplateSpecializationDecl *PrevDecl =
2477      InstClassTemplate->findSpecialization(Converted, InsertPos);
2478
2479  // Check whether we've already seen a conflicting instantiation of this
2480  // declaration (for instance, if there was a prior implicit instantiation).
2481  bool Ignored;
2482  if (PrevDecl &&
2483      SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(),
2484                                                     D->getSpecializationKind(),
2485                                                     PrevDecl,
2486                                                     PrevDecl->getSpecializationKind(),
2487                                                     PrevDecl->getPointOfInstantiation(),
2488                                                     Ignored))
2489    return nullptr;
2490
2491  // If PrevDecl was a definition and D is also a definition, diagnose.
2492  // This happens in cases like:
2493  //
2494  //   template<typename T, typename U>
2495  //   struct Outer {
2496  //     template<typename X> struct Inner;
2497  //     template<> struct Inner<T> {};
2498  //     template<> struct Inner<U> {};
2499  //   };
2500  //
2501  //   Outer<int, int> outer; // error: the explicit specializations of Inner
2502  //                          // have the same signature.
2503  if (PrevDecl && PrevDecl->getDefinition() &&
2504      D->isThisDeclarationADefinition()) {
2505    SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
2506    SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
2507                 diag::note_previous_definition);
2508    return nullptr;
2509  }
2510
2511  // Create the class template partial specialization declaration.
2512  ClassTemplateSpecializationDecl *InstD
2513    = ClassTemplateSpecializationDecl::Create(SemaRef.Context,
2514                                              D->getTagKind(),
2515                                              Owner,
2516                                              D->getLocStart(),
2517                                              D->getLocation(),
2518                                              InstClassTemplate,
2519                                              Converted.data(),
2520                                              Converted.size(),
2521                                              PrevDecl);
2522
2523  // Add this partial specialization to the set of class template partial
2524  // specializations.
2525  if (!PrevDecl)
2526    InstClassTemplate->AddSpecialization(InstD, InsertPos);
2527
2528  // Substitute the nested name specifier, if any.
2529  if (SubstQualifier(D, InstD))
2530    return nullptr;
2531
2532  // Build the canonical type that describes the converted template
2533  // arguments of the class template explicit specialization.
2534  QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
2535      TemplateName(InstClassTemplate), Converted.data(), Converted.size(),
2536      SemaRef.Context.getRecordType(InstD));
2537
2538  // Build the fully-sugared type for this class template
2539  // specialization as the user wrote in the specialization
2540  // itself. This means that we'll pretty-print the type retrieved
2541  // from the specialization's declaration the way that the user
2542  // actually wrote the specialization, rather than formatting the
2543  // name based on the "canonical" representation used to store the
2544  // template arguments in the specialization.
2545  TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
2546      TemplateName(InstClassTemplate), D->getLocation(), InstTemplateArgs,
2547      CanonType);
2548
2549  InstD->setAccess(D->getAccess());
2550  InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
2551  InstD->setSpecializationKind(D->getSpecializationKind());
2552  InstD->setTypeAsWritten(WrittenTy);
2553  InstD->setExternLoc(D->getExternLoc());
2554  InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc());
2555
2556  Owner->addDecl(InstD);
2557
2558  // Instantiate the members of the class-scope explicit specialization eagerly.
2559  // We don't have support for lazy instantiation of an explicit specialization
2560  // yet, and MSVC eagerly instantiates in this case.
2561  if (D->isThisDeclarationADefinition() &&
2562      SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
2563                               TSK_ImplicitInstantiation,
2564                               /*Complain=*/true))
2565    return nullptr;
2566
2567  return InstD;
2568}
2569
2570Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
2571    VarTemplateSpecializationDecl *D) {
2572
2573  TemplateArgumentListInfo VarTemplateArgsInfo;
2574  VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
2575  assert(VarTemplate &&
2576         "A template specialization without specialized template?");
2577
2578  // Substitute the current template arguments.
2579  const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo();
2580  VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc());
2581  VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc());
2582
2583  if (SemaRef.Subst(TemplateArgsInfo.getArgumentArray(),
2584                    TemplateArgsInfo.size(), VarTemplateArgsInfo, TemplateArgs))
2585    return nullptr;
2586
2587  // Check that the template argument list is well-formed for this template.
2588  SmallVector<TemplateArgument, 4> Converted;
2589  if (SemaRef.CheckTemplateArgumentList(
2590          VarTemplate, VarTemplate->getLocStart(),
2591          const_cast<TemplateArgumentListInfo &>(VarTemplateArgsInfo), false,
2592          Converted))
2593    return nullptr;
2594
2595  // Find the variable template specialization declaration that
2596  // corresponds to these arguments.
2597  void *InsertPos = nullptr;
2598  if (VarTemplateSpecializationDecl *VarSpec = VarTemplate->findSpecialization(
2599          Converted, InsertPos))
2600    // If we already have a variable template specialization, return it.
2601    return VarSpec;
2602
2603  return VisitVarTemplateSpecializationDecl(VarTemplate, D, InsertPos,
2604                                            VarTemplateArgsInfo, Converted);
2605}
2606
2607Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
2608    VarTemplateDecl *VarTemplate, VarDecl *D, void *InsertPos,
2609    const TemplateArgumentListInfo &TemplateArgsInfo,
2610    ArrayRef<TemplateArgument> Converted) {
2611
2612  // If this is the variable for an anonymous struct or union,
2613  // instantiate the anonymous struct/union type first.
2614  if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
2615    if (RecordTy->getDecl()->isAnonymousStructOrUnion())
2616      if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
2617        return nullptr;
2618
2619  // Do substitution on the type of the declaration
2620  TypeSourceInfo *DI =
2621      SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
2622                        D->getTypeSpecStartLoc(), D->getDeclName());
2623  if (!DI)
2624    return nullptr;
2625
2626  if (DI->getType()->isFunctionType()) {
2627    SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
2628        << D->isStaticDataMember() << DI->getType();
2629    return nullptr;
2630  }
2631
2632  // Build the instantiated declaration
2633  VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create(
2634      SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
2635      VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted.data(),
2636      Converted.size());
2637  Var->setTemplateArgsInfo(TemplateArgsInfo);
2638  if (InsertPos)
2639    VarTemplate->AddSpecialization(Var, InsertPos);
2640
2641  // Substitute the nested name specifier, if any.
2642  if (SubstQualifier(D, Var))
2643    return nullptr;
2644
2645  SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs,
2646                                     Owner, StartingScope);
2647
2648  return Var;
2649}
2650
2651Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
2652  llvm_unreachable("@defs is not supported in Objective-C++");
2653}
2654
2655Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
2656  // FIXME: We need to be able to instantiate FriendTemplateDecls.
2657  unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
2658                                               DiagnosticsEngine::Error,
2659                                               "cannot instantiate %0 yet");
2660  SemaRef.Diag(D->getLocation(), DiagID)
2661    << D->getDeclKindName();
2662
2663  return nullptr;
2664}
2665
2666Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
2667  llvm_unreachable("Unexpected decl");
2668}
2669
2670Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
2671                      const MultiLevelTemplateArgumentList &TemplateArgs) {
2672  TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
2673  if (D->isInvalidDecl())
2674    return nullptr;
2675
2676  return Instantiator.Visit(D);
2677}
2678
2679/// \brief Instantiates a nested template parameter list in the current
2680/// instantiation context.
2681///
2682/// \param L The parameter list to instantiate
2683///
2684/// \returns NULL if there was an error
2685TemplateParameterList *
2686TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
2687  // Get errors for all the parameters before bailing out.
2688  bool Invalid = false;
2689
2690  unsigned N = L->size();
2691  typedef SmallVector<NamedDecl *, 8> ParamVector;
2692  ParamVector Params;
2693  Params.reserve(N);
2694  for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
2695       PI != PE; ++PI) {
2696    NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
2697    Params.push_back(D);
2698    Invalid = Invalid || !D || D->isInvalidDecl();
2699  }
2700
2701  // Clean up if we had an error.
2702  if (Invalid)
2703    return nullptr;
2704
2705  TemplateParameterList *InstL
2706    = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
2707                                    L->getLAngleLoc(), &Params.front(), N,
2708                                    L->getRAngleLoc());
2709  return InstL;
2710}
2711
2712/// \brief Instantiate the declaration of a class template partial
2713/// specialization.
2714///
2715/// \param ClassTemplate the (instantiated) class template that is partially
2716// specialized by the instantiation of \p PartialSpec.
2717///
2718/// \param PartialSpec the (uninstantiated) class template partial
2719/// specialization that we are instantiating.
2720///
2721/// \returns The instantiated partial specialization, if successful; otherwise,
2722/// NULL to indicate an error.
2723ClassTemplatePartialSpecializationDecl *
2724TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
2725                                            ClassTemplateDecl *ClassTemplate,
2726                          ClassTemplatePartialSpecializationDecl *PartialSpec) {
2727  // Create a local instantiation scope for this class template partial
2728  // specialization, which will contain the instantiations of the template
2729  // parameters.
2730  LocalInstantiationScope Scope(SemaRef);
2731
2732  // Substitute into the template parameters of the class template partial
2733  // specialization.
2734  TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2735  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2736  if (!InstParams)
2737    return nullptr;
2738
2739  // Substitute into the template arguments of the class template partial
2740  // specialization.
2741  const ASTTemplateArgumentListInfo *TemplArgInfo
2742    = PartialSpec->getTemplateArgsAsWritten();
2743  TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
2744                                            TemplArgInfo->RAngleLoc);
2745  if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
2746                    TemplArgInfo->NumTemplateArgs,
2747                    InstTemplateArgs, TemplateArgs))
2748    return nullptr;
2749
2750  // Check that the template argument list is well-formed for this
2751  // class template.
2752  SmallVector<TemplateArgument, 4> Converted;
2753  if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
2754                                        PartialSpec->getLocation(),
2755                                        InstTemplateArgs,
2756                                        false,
2757                                        Converted))
2758    return nullptr;
2759
2760  // Figure out where to insert this class template partial specialization
2761  // in the member template's set of class template partial specializations.
2762  void *InsertPos = nullptr;
2763  ClassTemplateSpecializationDecl *PrevDecl
2764    = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
2765
2766  // Build the canonical type that describes the converted template
2767  // arguments of the class template partial specialization.
2768  QualType CanonType
2769    = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
2770                                                    Converted.data(),
2771                                                    Converted.size());
2772
2773  // Build the fully-sugared type for this class template
2774  // specialization as the user wrote in the specialization
2775  // itself. This means that we'll pretty-print the type retrieved
2776  // from the specialization's declaration the way that the user
2777  // actually wrote the specialization, rather than formatting the
2778  // name based on the "canonical" representation used to store the
2779  // template arguments in the specialization.
2780  TypeSourceInfo *WrittenTy
2781    = SemaRef.Context.getTemplateSpecializationTypeInfo(
2782                                                    TemplateName(ClassTemplate),
2783                                                    PartialSpec->getLocation(),
2784                                                    InstTemplateArgs,
2785                                                    CanonType);
2786
2787  if (PrevDecl) {
2788    // We've already seen a partial specialization with the same template
2789    // parameters and template arguments. This can happen, for example, when
2790    // substituting the outer template arguments ends up causing two
2791    // class template partial specializations of a member class template
2792    // to have identical forms, e.g.,
2793    //
2794    //   template<typename T, typename U>
2795    //   struct Outer {
2796    //     template<typename X, typename Y> struct Inner;
2797    //     template<typename Y> struct Inner<T, Y>;
2798    //     template<typename Y> struct Inner<U, Y>;
2799    //   };
2800    //
2801    //   Outer<int, int> outer; // error: the partial specializations of Inner
2802    //                          // have the same signature.
2803    SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
2804      << WrittenTy->getType();
2805    SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
2806      << SemaRef.Context.getTypeDeclType(PrevDecl);
2807    return nullptr;
2808  }
2809
2810
2811  // Create the class template partial specialization declaration.
2812  ClassTemplatePartialSpecializationDecl *InstPartialSpec
2813    = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
2814                                                     PartialSpec->getTagKind(),
2815                                                     Owner,
2816                                                     PartialSpec->getLocStart(),
2817                                                     PartialSpec->getLocation(),
2818                                                     InstParams,
2819                                                     ClassTemplate,
2820                                                     Converted.data(),
2821                                                     Converted.size(),
2822                                                     InstTemplateArgs,
2823                                                     CanonType,
2824                                                     nullptr);
2825  // Substitute the nested name specifier, if any.
2826  if (SubstQualifier(PartialSpec, InstPartialSpec))
2827    return nullptr;
2828
2829  InstPartialSpec->setInstantiatedFromMember(PartialSpec);
2830  InstPartialSpec->setTypeAsWritten(WrittenTy);
2831
2832  // Add this partial specialization to the set of class template partial
2833  // specializations.
2834  ClassTemplate->AddPartialSpecialization(InstPartialSpec,
2835                                          /*InsertPos=*/nullptr);
2836  return InstPartialSpec;
2837}
2838
2839/// \brief Instantiate the declaration of a variable template partial
2840/// specialization.
2841///
2842/// \param VarTemplate the (instantiated) variable template that is partially
2843/// specialized by the instantiation of \p PartialSpec.
2844///
2845/// \param PartialSpec the (uninstantiated) variable template partial
2846/// specialization that we are instantiating.
2847///
2848/// \returns The instantiated partial specialization, if successful; otherwise,
2849/// NULL to indicate an error.
2850VarTemplatePartialSpecializationDecl *
2851TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
2852    VarTemplateDecl *VarTemplate,
2853    VarTemplatePartialSpecializationDecl *PartialSpec) {
2854  // Create a local instantiation scope for this variable template partial
2855  // specialization, which will contain the instantiations of the template
2856  // parameters.
2857  LocalInstantiationScope Scope(SemaRef);
2858
2859  // Substitute into the template parameters of the variable template partial
2860  // specialization.
2861  TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2862  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2863  if (!InstParams)
2864    return nullptr;
2865
2866  // Substitute into the template arguments of the variable template partial
2867  // specialization.
2868  const ASTTemplateArgumentListInfo *TemplArgInfo
2869    = PartialSpec->getTemplateArgsAsWritten();
2870  TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
2871                                            TemplArgInfo->RAngleLoc);
2872  if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
2873                    TemplArgInfo->NumTemplateArgs,
2874                    InstTemplateArgs, TemplateArgs))
2875    return nullptr;
2876
2877  // Check that the template argument list is well-formed for this
2878  // class template.
2879  SmallVector<TemplateArgument, 4> Converted;
2880  if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
2881                                        InstTemplateArgs, false, Converted))
2882    return nullptr;
2883
2884  // Figure out where to insert this variable template partial specialization
2885  // in the member template's set of variable template partial specializations.
2886  void *InsertPos = nullptr;
2887  VarTemplateSpecializationDecl *PrevDecl =
2888      VarTemplate->findPartialSpecialization(Converted, InsertPos);
2889
2890  // Build the canonical type that describes the converted template
2891  // arguments of the variable template partial specialization.
2892  QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
2893      TemplateName(VarTemplate), Converted.data(), Converted.size());
2894
2895  // Build the fully-sugared type for this variable template
2896  // specialization as the user wrote in the specialization
2897  // itself. This means that we'll pretty-print the type retrieved
2898  // from the specialization's declaration the way that the user
2899  // actually wrote the specialization, rather than formatting the
2900  // name based on the "canonical" representation used to store the
2901  // template arguments in the specialization.
2902  TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
2903      TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs,
2904      CanonType);
2905
2906  if (PrevDecl) {
2907    // We've already seen a partial specialization with the same template
2908    // parameters and template arguments. This can happen, for example, when
2909    // substituting the outer template arguments ends up causing two
2910    // variable template partial specializations of a member variable template
2911    // to have identical forms, e.g.,
2912    //
2913    //   template<typename T, typename U>
2914    //   struct Outer {
2915    //     template<typename X, typename Y> pair<X,Y> p;
2916    //     template<typename Y> pair<T, Y> p;
2917    //     template<typename Y> pair<U, Y> p;
2918    //   };
2919    //
2920    //   Outer<int, int> outer; // error: the partial specializations of Inner
2921    //                          // have the same signature.
2922    SemaRef.Diag(PartialSpec->getLocation(),
2923                 diag::err_var_partial_spec_redeclared)
2924        << WrittenTy->getType();
2925    SemaRef.Diag(PrevDecl->getLocation(),
2926                 diag::note_var_prev_partial_spec_here);
2927    return nullptr;
2928  }
2929
2930  // Do substitution on the type of the declaration
2931  TypeSourceInfo *DI = SemaRef.SubstType(
2932      PartialSpec->getTypeSourceInfo(), TemplateArgs,
2933      PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
2934  if (!DI)
2935    return nullptr;
2936
2937  if (DI->getType()->isFunctionType()) {
2938    SemaRef.Diag(PartialSpec->getLocation(),
2939                 diag::err_variable_instantiates_to_function)
2940        << PartialSpec->isStaticDataMember() << DI->getType();
2941    return nullptr;
2942  }
2943
2944  // Create the variable template partial specialization declaration.
2945  VarTemplatePartialSpecializationDecl *InstPartialSpec =
2946      VarTemplatePartialSpecializationDecl::Create(
2947          SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
2948          PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
2949          DI, PartialSpec->getStorageClass(), Converted.data(),
2950          Converted.size(), InstTemplateArgs);
2951
2952  // Substitute the nested name specifier, if any.
2953  if (SubstQualifier(PartialSpec, InstPartialSpec))
2954    return nullptr;
2955
2956  InstPartialSpec->setInstantiatedFromMember(PartialSpec);
2957  InstPartialSpec->setTypeAsWritten(WrittenTy);
2958
2959  // Add this partial specialization to the set of variable template partial
2960  // specializations. The instantiation of the initializer is not necessary.
2961  VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr);
2962
2963  SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
2964                                     LateAttrs, Owner, StartingScope);
2965
2966  return InstPartialSpec;
2967}
2968
2969TypeSourceInfo*
2970TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
2971                              SmallVectorImpl<ParmVarDecl *> &Params) {
2972  TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
2973  assert(OldTInfo && "substituting function without type source info");
2974  assert(Params.empty() && "parameter vector is non-empty at start");
2975
2976  CXXRecordDecl *ThisContext = nullptr;
2977  unsigned ThisTypeQuals = 0;
2978  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
2979    ThisContext = cast<CXXRecordDecl>(Owner);
2980    ThisTypeQuals = Method->getTypeQualifiers();
2981  }
2982
2983  TypeSourceInfo *NewTInfo
2984    = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
2985                                    D->getTypeSpecStartLoc(),
2986                                    D->getDeclName(),
2987                                    ThisContext, ThisTypeQuals);
2988  if (!NewTInfo)
2989    return nullptr;
2990
2991  TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
2992  if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
2993    if (NewTInfo != OldTInfo) {
2994      // Get parameters from the new type info.
2995      TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
2996      FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
2997      unsigned NewIdx = 0;
2998      for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
2999           OldIdx != NumOldParams; ++OldIdx) {
3000        ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
3001        LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
3002
3003        Optional<unsigned> NumArgumentsInExpansion;
3004        if (OldParam->isParameterPack())
3005          NumArgumentsInExpansion =
3006              SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
3007                                                 TemplateArgs);
3008        if (!NumArgumentsInExpansion) {
3009          // Simple case: normal parameter, or a parameter pack that's
3010          // instantiated to a (still-dependent) parameter pack.
3011          ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
3012          Params.push_back(NewParam);
3013          Scope->InstantiatedLocal(OldParam, NewParam);
3014        } else {
3015          // Parameter pack expansion: make the instantiation an argument pack.
3016          Scope->MakeInstantiatedLocalArgPack(OldParam);
3017          for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
3018            ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
3019            Params.push_back(NewParam);
3020            Scope->InstantiatedLocalPackArg(OldParam, NewParam);
3021          }
3022        }
3023      }
3024    } else {
3025      // The function type itself was not dependent and therefore no
3026      // substitution occurred. However, we still need to instantiate
3027      // the function parameters themselves.
3028      const FunctionProtoType *OldProto =
3029          cast<FunctionProtoType>(OldProtoLoc.getType());
3030      for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
3031           ++i) {
3032        ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
3033        if (!OldParam) {
3034          Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
3035              D, D->getLocation(), OldProto->getParamType(i)));
3036          continue;
3037        }
3038
3039        ParmVarDecl *Parm =
3040            cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
3041        if (!Parm)
3042          return nullptr;
3043        Params.push_back(Parm);
3044      }
3045    }
3046  } else {
3047    // If the type of this function, after ignoring parentheses, is not
3048    // *directly* a function type, then we're instantiating a function that
3049    // was declared via a typedef or with attributes, e.g.,
3050    //
3051    //   typedef int functype(int, int);
3052    //   functype func;
3053    //   int __cdecl meth(int, int);
3054    //
3055    // In this case, we'll just go instantiate the ParmVarDecls that we
3056    // synthesized in the method declaration.
3057    SmallVector<QualType, 4> ParamTypes;
3058    if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(),
3059                               D->getNumParams(), TemplateArgs, ParamTypes,
3060                               &Params))
3061      return nullptr;
3062  }
3063
3064  return NewTInfo;
3065}
3066
3067/// Introduce the instantiated function parameters into the local
3068/// instantiation scope, and set the parameter names to those used
3069/// in the template.
3070static bool addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
3071                                             const FunctionDecl *PatternDecl,
3072                                             LocalInstantiationScope &Scope,
3073                           const MultiLevelTemplateArgumentList &TemplateArgs) {
3074  unsigned FParamIdx = 0;
3075  for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
3076    const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
3077    if (!PatternParam->isParameterPack()) {
3078      // Simple case: not a parameter pack.
3079      assert(FParamIdx < Function->getNumParams());
3080      ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
3081      FunctionParam->setDeclName(PatternParam->getDeclName());
3082      // If the parameter's type is not dependent, update it to match the type
3083      // in the pattern. They can differ in top-level cv-qualifiers, and we want
3084      // the pattern's type here. If the type is dependent, they can't differ,
3085      // per core issue 1668. Substitute into the type from the pattern, in case
3086      // it's instantiation-dependent.
3087      // FIXME: Updating the type to work around this is at best fragile.
3088      if (!PatternDecl->getType()->isDependentType()) {
3089        QualType T = S.SubstType(PatternParam->getType(), TemplateArgs,
3090                                 FunctionParam->getLocation(),
3091                                 FunctionParam->getDeclName());
3092        if (T.isNull())
3093          return true;
3094        FunctionParam->setType(T);
3095      }
3096
3097      Scope.InstantiatedLocal(PatternParam, FunctionParam);
3098      ++FParamIdx;
3099      continue;
3100    }
3101
3102    // Expand the parameter pack.
3103    Scope.MakeInstantiatedLocalArgPack(PatternParam);
3104    Optional<unsigned> NumArgumentsInExpansion
3105      = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
3106    assert(NumArgumentsInExpansion &&
3107           "should only be called when all template arguments are known");
3108    QualType PatternType =
3109        PatternParam->getType()->castAs<PackExpansionType>()->getPattern();
3110    for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
3111      ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
3112      FunctionParam->setDeclName(PatternParam->getDeclName());
3113      if (!PatternDecl->getType()->isDependentType()) {
3114        Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, Arg);
3115        QualType T = S.SubstType(PatternType, TemplateArgs,
3116                                 FunctionParam->getLocation(),
3117                                 FunctionParam->getDeclName());
3118        if (T.isNull())
3119          return true;
3120        FunctionParam->setType(T);
3121      }
3122
3123      Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
3124      ++FParamIdx;
3125    }
3126  }
3127
3128  return false;
3129}
3130
3131void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
3132                                    FunctionDecl *Decl) {
3133  const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
3134  if (Proto->getExceptionSpecType() != EST_Uninstantiated)
3135    return;
3136
3137  InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
3138                             InstantiatingTemplate::ExceptionSpecification());
3139  if (Inst.isInvalid()) {
3140    // We hit the instantiation depth limit. Clear the exception specification
3141    // so that our callers don't have to cope with EST_Uninstantiated.
3142    UpdateExceptionSpec(Decl, EST_None);
3143    return;
3144  }
3145
3146  // Enter the scope of this instantiation. We don't use
3147  // PushDeclContext because we don't have a scope.
3148  Sema::ContextRAII savedContext(*this, Decl);
3149  LocalInstantiationScope Scope(*this);
3150
3151  MultiLevelTemplateArgumentList TemplateArgs =
3152    getTemplateInstantiationArgs(Decl, nullptr, /*RelativeToPrimary*/true);
3153
3154  FunctionDecl *Template = Proto->getExceptionSpecTemplate();
3155  if (addInstantiatedParametersToScope(*this, Decl, Template, Scope,
3156                                       TemplateArgs)) {
3157    UpdateExceptionSpec(Decl, EST_None);
3158    return;
3159  }
3160
3161  SubstExceptionSpec(Decl, Template->getType()->castAs<FunctionProtoType>(),
3162                     TemplateArgs);
3163}
3164
3165/// \brief Initializes the common fields of an instantiation function
3166/// declaration (New) from the corresponding fields of its template (Tmpl).
3167///
3168/// \returns true if there was an error
3169bool
3170TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
3171                                                    FunctionDecl *Tmpl) {
3172  if (Tmpl->isDeleted())
3173    New->setDeletedAsWritten();
3174
3175  // Forward the mangling number from the template to the instantiated decl.
3176  SemaRef.Context.setManglingNumber(New,
3177                                    SemaRef.Context.getManglingNumber(Tmpl));
3178
3179  // If we are performing substituting explicitly-specified template arguments
3180  // or deduced template arguments into a function template and we reach this
3181  // point, we are now past the point where SFINAE applies and have committed
3182  // to keeping the new function template specialization. We therefore
3183  // convert the active template instantiation for the function template
3184  // into a template instantiation for this specific function template
3185  // specialization, which is not a SFINAE context, so that we diagnose any
3186  // further errors in the declaration itself.
3187  typedef Sema::ActiveTemplateInstantiation ActiveInstType;
3188  ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
3189  if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
3190      ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
3191    if (FunctionTemplateDecl *FunTmpl
3192          = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
3193      assert(FunTmpl->getTemplatedDecl() == Tmpl &&
3194             "Deduction from the wrong function template?");
3195      (void) FunTmpl;
3196      ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
3197      ActiveInst.Entity = New;
3198    }
3199  }
3200
3201  const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
3202  assert(Proto && "Function template without prototype?");
3203
3204  if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
3205    FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3206
3207    // DR1330: In C++11, defer instantiation of a non-trivial
3208    // exception specification.
3209    if (SemaRef.getLangOpts().CPlusPlus11 &&
3210        EPI.ExceptionSpec.Type != EST_None &&
3211        EPI.ExceptionSpec.Type != EST_DynamicNone &&
3212        EPI.ExceptionSpec.Type != EST_BasicNoexcept) {
3213      FunctionDecl *ExceptionSpecTemplate = Tmpl;
3214      if (EPI.ExceptionSpec.Type == EST_Uninstantiated)
3215        ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate;
3216      ExceptionSpecificationType NewEST = EST_Uninstantiated;
3217      if (EPI.ExceptionSpec.Type == EST_Unevaluated)
3218        NewEST = EST_Unevaluated;
3219
3220      // Mark the function has having an uninstantiated exception specification.
3221      const FunctionProtoType *NewProto
3222        = New->getType()->getAs<FunctionProtoType>();
3223      assert(NewProto && "Template instantiation without function prototype?");
3224      EPI = NewProto->getExtProtoInfo();
3225      EPI.ExceptionSpec.Type = NewEST;
3226      EPI.ExceptionSpec.SourceDecl = New;
3227      EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate;
3228      New->setType(SemaRef.Context.getFunctionType(
3229          NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
3230    } else {
3231      SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs);
3232    }
3233  }
3234
3235  // Get the definition. Leaves the variable unchanged if undefined.
3236  const FunctionDecl *Definition = Tmpl;
3237  Tmpl->isDefined(Definition);
3238
3239  SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
3240                           LateAttrs, StartingScope);
3241
3242  return false;
3243}
3244
3245/// \brief Initializes common fields of an instantiated method
3246/// declaration (New) from the corresponding fields of its template
3247/// (Tmpl).
3248///
3249/// \returns true if there was an error
3250bool
3251TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
3252                                                  CXXMethodDecl *Tmpl) {
3253  if (InitFunctionInstantiation(New, Tmpl))
3254    return true;
3255
3256  New->setAccess(Tmpl->getAccess());
3257  if (Tmpl->isVirtualAsWritten())
3258    New->setVirtualAsWritten(true);
3259
3260  // FIXME: New needs a pointer to Tmpl
3261  return false;
3262}
3263
3264/// \brief Instantiate the definition of the given function from its
3265/// template.
3266///
3267/// \param PointOfInstantiation the point at which the instantiation was
3268/// required. Note that this is not precisely a "point of instantiation"
3269/// for the function, but it's close.
3270///
3271/// \param Function the already-instantiated declaration of a
3272/// function template specialization or member function of a class template
3273/// specialization.
3274///
3275/// \param Recursive if true, recursively instantiates any functions that
3276/// are required by this instantiation.
3277///
3278/// \param DefinitionRequired if true, then we are performing an explicit
3279/// instantiation where the body of the function is required. Complain if
3280/// there is no such body.
3281void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
3282                                         FunctionDecl *Function,
3283                                         bool Recursive,
3284                                         bool DefinitionRequired) {
3285  if (Function->isInvalidDecl() || Function->isDefined())
3286    return;
3287
3288  // Never instantiate an explicit specialization except if it is a class scope
3289  // explicit specialization.
3290  if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
3291      !Function->getClassScopeSpecializationPattern())
3292    return;
3293
3294  // Find the function body that we'll be substituting.
3295  const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
3296  assert(PatternDecl && "instantiating a non-template");
3297
3298  Stmt *Pattern = PatternDecl->getBody(PatternDecl);
3299  assert(PatternDecl && "template definition is not a template");
3300  if (!Pattern) {
3301    // Try to find a defaulted definition
3302    PatternDecl->isDefined(PatternDecl);
3303  }
3304  assert(PatternDecl && "template definition is not a template");
3305
3306  // Postpone late parsed template instantiations.
3307  if (PatternDecl->isLateTemplateParsed() &&
3308      !LateTemplateParser) {
3309    PendingInstantiations.push_back(
3310      std::make_pair(Function, PointOfInstantiation));
3311    return;
3312  }
3313
3314  // If we're performing recursive template instantiation, create our own
3315  // queue of pending implicit instantiations that we will instantiate later,
3316  // while we're still within our own instantiation context.
3317  // This has to happen before LateTemplateParser below is called, so that
3318  // it marks vtables used in late parsed templates as used.
3319  SavePendingLocalImplicitInstantiationsRAII
3320      SavedPendingLocalImplicitInstantiations(*this);
3321  SavePendingInstantiationsAndVTableUsesRAII
3322      SavePendingInstantiationsAndVTableUses(*this, /*Enabled=*/Recursive);
3323
3324  // Call the LateTemplateParser callback if there is a need to late parse
3325  // a templated function definition.
3326  if (!Pattern && PatternDecl->isLateTemplateParsed() &&
3327      LateTemplateParser) {
3328    // FIXME: Optimize to allow individual templates to be deserialized.
3329    if (PatternDecl->isFromASTFile())
3330      ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
3331
3332    LateParsedTemplate *LPT = LateParsedTemplateMap.lookup(PatternDecl);
3333    assert(LPT && "missing LateParsedTemplate");
3334    LateTemplateParser(OpaqueParser, *LPT);
3335    Pattern = PatternDecl->getBody(PatternDecl);
3336  }
3337
3338  if (!Pattern && !PatternDecl->isDefaulted()) {
3339    if (DefinitionRequired) {
3340      if (Function->getPrimaryTemplate())
3341        Diag(PointOfInstantiation,
3342             diag::err_explicit_instantiation_undefined_func_template)
3343          << Function->getPrimaryTemplate();
3344      else
3345        Diag(PointOfInstantiation,
3346             diag::err_explicit_instantiation_undefined_member)
3347          << 1 << Function->getDeclName() << Function->getDeclContext();
3348
3349      if (PatternDecl)
3350        Diag(PatternDecl->getLocation(),
3351             diag::note_explicit_instantiation_here);
3352      Function->setInvalidDecl();
3353    } else if (Function->getTemplateSpecializationKind()
3354                 == TSK_ExplicitInstantiationDefinition) {
3355      assert(!Recursive);
3356      PendingInstantiations.push_back(
3357        std::make_pair(Function, PointOfInstantiation));
3358    }
3359
3360    return;
3361  }
3362
3363  // C++1y [temp.explicit]p10:
3364  //   Except for inline functions, declarations with types deduced from their
3365  //   initializer or return value, and class template specializations, other
3366  //   explicit instantiation declarations have the effect of suppressing the
3367  //   implicit instantiation of the entity to which they refer.
3368  if (Function->getTemplateSpecializationKind() ==
3369          TSK_ExplicitInstantiationDeclaration &&
3370      !PatternDecl->isInlined() &&
3371      !PatternDecl->getReturnType()->getContainedAutoType())
3372    return;
3373
3374  if (PatternDecl->isInlined()) {
3375    // Function, and all later redeclarations of it (from imported modules,
3376    // for instance), are now implicitly inline.
3377    for (auto *D = Function->getMostRecentDecl(); /**/;
3378         D = D->getPreviousDecl()) {
3379      D->setImplicitlyInline();
3380      if (D == Function)
3381        break;
3382    }
3383  }
3384
3385  InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
3386  if (Inst.isInvalid())
3387    return;
3388
3389  // Copy the inner loc start from the pattern.
3390  Function->setInnerLocStart(PatternDecl->getInnerLocStart());
3391
3392  EnterExpressionEvaluationContext EvalContext(*this,
3393                                               Sema::PotentiallyEvaluated);
3394
3395  // Introduce a new scope where local variable instantiations will be
3396  // recorded, unless we're actually a member function within a local
3397  // class, in which case we need to merge our results with the parent
3398  // scope (of the enclosing function).
3399  bool MergeWithParentScope = false;
3400  if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
3401    MergeWithParentScope = Rec->isLocalClass();
3402
3403  LocalInstantiationScope Scope(*this, MergeWithParentScope);
3404
3405  if (PatternDecl->isDefaulted())
3406    SetDeclDefaulted(Function, PatternDecl->getLocation());
3407  else {
3408    MultiLevelTemplateArgumentList TemplateArgs =
3409      getTemplateInstantiationArgs(Function, nullptr, false, PatternDecl);
3410
3411    // Substitute into the qualifier; we can get a substitution failure here
3412    // through evil use of alias templates.
3413    // FIXME: Is CurContext correct for this? Should we go to the (instantiation
3414    // of the) lexical context of the pattern?
3415    SubstQualifier(*this, PatternDecl, Function, TemplateArgs);
3416
3417    ActOnStartOfFunctionDef(nullptr, Function);
3418
3419    // Enter the scope of this instantiation. We don't use
3420    // PushDeclContext because we don't have a scope.
3421    Sema::ContextRAII savedContext(*this, Function);
3422
3423    if (addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
3424                                         TemplateArgs))
3425      return;
3426
3427    // If this is a constructor, instantiate the member initializers.
3428    if (const CXXConstructorDecl *Ctor =
3429          dyn_cast<CXXConstructorDecl>(PatternDecl)) {
3430      InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
3431                                 TemplateArgs);
3432    }
3433
3434    // Instantiate the function body.
3435    StmtResult Body = SubstStmt(Pattern, TemplateArgs);
3436
3437    if (Body.isInvalid())
3438      Function->setInvalidDecl();
3439
3440    ActOnFinishFunctionBody(Function, Body.get(),
3441                            /*IsInstantiation=*/true);
3442
3443    PerformDependentDiagnostics(PatternDecl, TemplateArgs);
3444
3445    if (auto *Listener = getASTMutationListener())
3446      Listener->FunctionDefinitionInstantiated(Function);
3447
3448    savedContext.pop();
3449  }
3450
3451  DeclGroupRef DG(Function);
3452  Consumer.HandleTopLevelDecl(DG);
3453
3454  // This class may have local implicit instantiations that need to be
3455  // instantiation within this scope.
3456  PerformPendingInstantiations(/*LocalOnly=*/true);
3457  Scope.Exit();
3458
3459  if (Recursive) {
3460    // Define any pending vtables.
3461    DefineUsedVTables();
3462
3463    // Instantiate any pending implicit instantiations found during the
3464    // instantiation of this template.
3465    PerformPendingInstantiations();
3466
3467    // PendingInstantiations and VTableUses are restored through
3468    // SavePendingInstantiationsAndVTableUses's destructor.
3469  }
3470}
3471
3472VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation(
3473    VarTemplateDecl *VarTemplate, VarDecl *FromVar,
3474    const TemplateArgumentList &TemplateArgList,
3475    const TemplateArgumentListInfo &TemplateArgsInfo,
3476    SmallVectorImpl<TemplateArgument> &Converted,
3477    SourceLocation PointOfInstantiation, void *InsertPos,
3478    LateInstantiatedAttrVec *LateAttrs,
3479    LocalInstantiationScope *StartingScope) {
3480  if (FromVar->isInvalidDecl())
3481    return nullptr;
3482
3483  InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
3484  if (Inst.isInvalid())
3485    return nullptr;
3486
3487  MultiLevelTemplateArgumentList TemplateArgLists;
3488  TemplateArgLists.addOuterTemplateArguments(&TemplateArgList);
3489
3490  // Instantiate the first declaration of the variable template: for a partial
3491  // specialization of a static data member template, the first declaration may
3492  // or may not be the declaration in the class; if it's in the class, we want
3493  // to instantiate a member in the class (a declaration), and if it's outside,
3494  // we want to instantiate a definition.
3495  //
3496  // If we're instantiating an explicitly-specialized member template or member
3497  // partial specialization, don't do this. The member specialization completely
3498  // replaces the original declaration in this case.
3499  bool IsMemberSpec = false;
3500  if (VarTemplatePartialSpecializationDecl *PartialSpec =
3501          dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar))
3502    IsMemberSpec = PartialSpec->isMemberSpecialization();
3503  else if (VarTemplateDecl *FromTemplate = FromVar->getDescribedVarTemplate())
3504    IsMemberSpec = FromTemplate->isMemberSpecialization();
3505  if (!IsMemberSpec)
3506    FromVar = FromVar->getFirstDecl();
3507
3508  MultiLevelTemplateArgumentList MultiLevelList(TemplateArgList);
3509  TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
3510                                        MultiLevelList);
3511
3512  // TODO: Set LateAttrs and StartingScope ...
3513
3514  return cast_or_null<VarTemplateSpecializationDecl>(
3515      Instantiator.VisitVarTemplateSpecializationDecl(
3516          VarTemplate, FromVar, InsertPos, TemplateArgsInfo, Converted));
3517}
3518
3519/// \brief Instantiates a variable template specialization by completing it
3520/// with appropriate type information and initializer.
3521VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl(
3522    VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
3523    const MultiLevelTemplateArgumentList &TemplateArgs) {
3524
3525  // Do substitution on the type of the declaration
3526  TypeSourceInfo *DI =
3527      SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
3528                PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
3529  if (!DI)
3530    return nullptr;
3531
3532  // Update the type of this variable template specialization.
3533  VarSpec->setType(DI->getType());
3534
3535  // Instantiate the initializer.
3536  InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
3537
3538  return VarSpec;
3539}
3540
3541/// BuildVariableInstantiation - Used after a new variable has been created.
3542/// Sets basic variable data and decides whether to postpone the
3543/// variable instantiation.
3544void Sema::BuildVariableInstantiation(
3545    VarDecl *NewVar, VarDecl *OldVar,
3546    const MultiLevelTemplateArgumentList &TemplateArgs,
3547    LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
3548    LocalInstantiationScope *StartingScope,
3549    bool InstantiatingVarTemplate) {
3550
3551  // If we are instantiating a local extern declaration, the
3552  // instantiation belongs lexically to the containing function.
3553  // If we are instantiating a static data member defined
3554  // out-of-line, the instantiation will have the same lexical
3555  // context (which will be a namespace scope) as the template.
3556  if (OldVar->isLocalExternDecl()) {
3557    NewVar->setLocalExternDecl();
3558    NewVar->setLexicalDeclContext(Owner);
3559  } else if (OldVar->isOutOfLine())
3560    NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
3561  NewVar->setTSCSpec(OldVar->getTSCSpec());
3562  NewVar->setInitStyle(OldVar->getInitStyle());
3563  NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
3564  NewVar->setConstexpr(OldVar->isConstexpr());
3565  NewVar->setInitCapture(OldVar->isInitCapture());
3566  NewVar->setPreviousDeclInSameBlockScope(
3567      OldVar->isPreviousDeclInSameBlockScope());
3568  NewVar->setAccess(OldVar->getAccess());
3569
3570  if (!OldVar->isStaticDataMember()) {
3571    if (OldVar->isUsed(false))
3572      NewVar->setIsUsed();
3573    NewVar->setReferenced(OldVar->isReferenced());
3574  }
3575
3576  // See if the old variable had a type-specifier that defined an anonymous tag.
3577  // If it did, mark the new variable as being the declarator for the new
3578  // anonymous tag.
3579  if (const TagType *OldTagType = OldVar->getType()->getAs<TagType>()) {
3580    TagDecl *OldTag = OldTagType->getDecl();
3581    if (OldTag->getDeclaratorForAnonDecl() == OldVar) {
3582      TagDecl *NewTag = NewVar->getType()->castAs<TagType>()->getDecl();
3583      assert(!NewTag->hasNameForLinkage() &&
3584             !NewTag->hasDeclaratorForAnonDecl());
3585      NewTag->setDeclaratorForAnonDecl(NewVar);
3586    }
3587  }
3588
3589  InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
3590
3591  LookupResult Previous(
3592      *this, NewVar->getDeclName(), NewVar->getLocation(),
3593      NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
3594                                  : Sema::LookupOrdinaryName,
3595      Sema::ForRedeclaration);
3596
3597  if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
3598      (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() ||
3599       OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
3600    // We have a previous declaration. Use that one, so we merge with the
3601    // right type.
3602    if (NamedDecl *NewPrev = FindInstantiatedDecl(
3603            NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
3604      Previous.addDecl(NewPrev);
3605  } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
3606             OldVar->hasLinkage())
3607    LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
3608  CheckVariableDeclaration(NewVar, Previous);
3609
3610  if (!InstantiatingVarTemplate) {
3611    NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
3612    if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
3613      NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
3614  }
3615
3616  if (!OldVar->isOutOfLine()) {
3617    if (NewVar->getDeclContext()->isFunctionOrMethod())
3618      CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
3619  }
3620
3621  // Link instantiations of static data members back to the template from
3622  // which they were instantiated.
3623  if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate)
3624    NewVar->setInstantiationOfStaticDataMember(OldVar,
3625                                               TSK_ImplicitInstantiation);
3626
3627  // Forward the mangling number from the template to the instantiated decl.
3628  Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar));
3629  Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar));
3630
3631  // Delay instantiation of the initializer for variable templates until a
3632  // definition of the variable is needed. We need it right away if the type
3633  // contains 'auto'.
3634  if ((!isa<VarTemplateSpecializationDecl>(NewVar) &&
3635       !InstantiatingVarTemplate) ||
3636      NewVar->getType()->isUndeducedType())
3637    InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
3638
3639  // Diagnose unused local variables with dependent types, where the diagnostic
3640  // will have been deferred.
3641  if (!NewVar->isInvalidDecl() &&
3642      NewVar->getDeclContext()->isFunctionOrMethod() &&
3643      OldVar->getType()->isDependentType())
3644    DiagnoseUnusedDecl(NewVar);
3645}
3646
3647/// \brief Instantiate the initializer of a variable.
3648void Sema::InstantiateVariableInitializer(
3649    VarDecl *Var, VarDecl *OldVar,
3650    const MultiLevelTemplateArgumentList &TemplateArgs) {
3651
3652  if (Var->getAnyInitializer())
3653    // We already have an initializer in the class.
3654    return;
3655
3656  if (OldVar->getInit()) {
3657    if (Var->isStaticDataMember() && !OldVar->isOutOfLine())
3658      PushExpressionEvaluationContext(Sema::ConstantEvaluated, OldVar);
3659    else
3660      PushExpressionEvaluationContext(Sema::PotentiallyEvaluated, OldVar);
3661
3662    // Instantiate the initializer.
3663    ExprResult Init =
3664        SubstInitializer(OldVar->getInit(), TemplateArgs,
3665                         OldVar->getInitStyle() == VarDecl::CallInit);
3666    if (!Init.isInvalid()) {
3667      bool TypeMayContainAuto = true;
3668      Expr *InitExpr = Init.get();
3669
3670      if (Var->hasAttr<DLLImportAttr>() &&
3671          (!InitExpr ||
3672           !InitExpr->isConstantInitializer(getASTContext(), false))) {
3673        // Do not dynamically initialize dllimport variables.
3674      } else if (InitExpr) {
3675        bool DirectInit = OldVar->isDirectInit();
3676        AddInitializerToDecl(Var, InitExpr, DirectInit, TypeMayContainAuto);
3677      } else
3678        ActOnUninitializedDecl(Var, TypeMayContainAuto);
3679    } else {
3680      // FIXME: Not too happy about invalidating the declaration
3681      // because of a bogus initializer.
3682      Var->setInvalidDecl();
3683    }
3684
3685    PopExpressionEvaluationContext();
3686  } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) &&
3687             !Var->isCXXForRangeDecl())
3688    ActOnUninitializedDecl(Var, false);
3689}
3690
3691/// \brief Instantiate the definition of the given variable from its
3692/// template.
3693///
3694/// \param PointOfInstantiation the point at which the instantiation was
3695/// required. Note that this is not precisely a "point of instantiation"
3696/// for the function, but it's close.
3697///
3698/// \param Var the already-instantiated declaration of a static member
3699/// variable of a class template specialization.
3700///
3701/// \param Recursive if true, recursively instantiates any functions that
3702/// are required by this instantiation.
3703///
3704/// \param DefinitionRequired if true, then we are performing an explicit
3705/// instantiation where an out-of-line definition of the member variable
3706/// is required. Complain if there is no such definition.
3707void Sema::InstantiateStaticDataMemberDefinition(
3708                                          SourceLocation PointOfInstantiation,
3709                                                 VarDecl *Var,
3710                                                 bool Recursive,
3711                                                 bool DefinitionRequired) {
3712  InstantiateVariableDefinition(PointOfInstantiation, Var, Recursive,
3713                                DefinitionRequired);
3714}
3715
3716void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
3717                                         VarDecl *Var, bool Recursive,
3718                                         bool DefinitionRequired) {
3719  if (Var->isInvalidDecl())
3720    return;
3721
3722  VarTemplateSpecializationDecl *VarSpec =
3723      dyn_cast<VarTemplateSpecializationDecl>(Var);
3724  VarDecl *PatternDecl = nullptr, *Def = nullptr;
3725  MultiLevelTemplateArgumentList TemplateArgs =
3726      getTemplateInstantiationArgs(Var);
3727
3728  if (VarSpec) {
3729    // If this is a variable template specialization, make sure that it is
3730    // non-dependent, then find its instantiation pattern.
3731    bool InstantiationDependent = false;
3732    assert(!TemplateSpecializationType::anyDependentTemplateArguments(
3733               VarSpec->getTemplateArgsInfo(), InstantiationDependent) &&
3734           "Only instantiate variable template specializations that are "
3735           "not type-dependent");
3736    (void)InstantiationDependent;
3737
3738    // Find the variable initialization that we'll be substituting. If the
3739    // pattern was instantiated from a member template, look back further to
3740    // find the real pattern.
3741    assert(VarSpec->getSpecializedTemplate() &&
3742           "Specialization without specialized template?");
3743    llvm::PointerUnion<VarTemplateDecl *,
3744                       VarTemplatePartialSpecializationDecl *> PatternPtr =
3745        VarSpec->getSpecializedTemplateOrPartial();
3746    if (PatternPtr.is<VarTemplatePartialSpecializationDecl *>()) {
3747      VarTemplatePartialSpecializationDecl *Tmpl =
3748          PatternPtr.get<VarTemplatePartialSpecializationDecl *>();
3749      while (VarTemplatePartialSpecializationDecl *From =
3750                 Tmpl->getInstantiatedFromMember()) {
3751        if (Tmpl->isMemberSpecialization())
3752          break;
3753
3754        Tmpl = From;
3755      }
3756      PatternDecl = Tmpl;
3757    } else {
3758      VarTemplateDecl *Tmpl = PatternPtr.get<VarTemplateDecl *>();
3759      while (VarTemplateDecl *From =
3760                 Tmpl->getInstantiatedFromMemberTemplate()) {
3761        if (Tmpl->isMemberSpecialization())
3762          break;
3763
3764        Tmpl = From;
3765      }
3766      PatternDecl = Tmpl->getTemplatedDecl();
3767    }
3768
3769    // If this is a static data member template, there might be an
3770    // uninstantiated initializer on the declaration. If so, instantiate
3771    // it now.
3772    if (PatternDecl->isStaticDataMember() &&
3773        (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
3774        !Var->hasInit()) {
3775      // FIXME: Factor out the duplicated instantiation context setup/tear down
3776      // code here.
3777      InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
3778      if (Inst.isInvalid())
3779        return;
3780
3781      // If we're performing recursive template instantiation, create our own
3782      // queue of pending implicit instantiations that we will instantiate
3783      // later, while we're still within our own instantiation context.
3784      SavePendingInstantiationsAndVTableUsesRAII
3785          SavePendingInstantiationsAndVTableUses(*this, /*Enabled=*/Recursive);
3786
3787      LocalInstantiationScope Local(*this);
3788
3789      // Enter the scope of this instantiation. We don't use
3790      // PushDeclContext because we don't have a scope.
3791      ContextRAII PreviousContext(*this, Var->getDeclContext());
3792      InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
3793      PreviousContext.pop();
3794
3795      // FIXME: Need to inform the ASTConsumer that we instantiated the
3796      // initializer?
3797
3798      // This variable may have local implicit instantiations that need to be
3799      // instantiated within this scope.
3800      PerformPendingInstantiations(/*LocalOnly=*/true);
3801
3802      Local.Exit();
3803
3804      if (Recursive) {
3805        // Define any newly required vtables.
3806        DefineUsedVTables();
3807
3808        // Instantiate any pending implicit instantiations found during the
3809        // instantiation of this template.
3810        PerformPendingInstantiations();
3811
3812        // PendingInstantiations and VTableUses are restored through
3813        // SavePendingInstantiationsAndVTableUses's destructor.
3814      }
3815    }
3816
3817    // Find actual definition
3818    Def = PatternDecl->getDefinition(getASTContext());
3819  } else {
3820    // If this is a static data member, find its out-of-line definition.
3821    assert(Var->isStaticDataMember() && "not a static data member?");
3822    PatternDecl = Var->getInstantiatedFromStaticDataMember();
3823
3824    assert(PatternDecl && "data member was not instantiated from a template?");
3825    assert(PatternDecl->isStaticDataMember() && "not a static data member?");
3826    Def = PatternDecl->getOutOfLineDefinition();
3827  }
3828
3829  // If we don't have a definition of the variable template, we won't perform
3830  // any instantiation. Rather, we rely on the user to instantiate this
3831  // definition (or provide a specialization for it) in another translation
3832  // unit.
3833  if (!Def) {
3834    if (DefinitionRequired) {
3835      if (VarSpec)
3836        Diag(PointOfInstantiation,
3837             diag::err_explicit_instantiation_undefined_var_template) << Var;
3838      else
3839        Diag(PointOfInstantiation,
3840             diag::err_explicit_instantiation_undefined_member)
3841            << 2 << Var->getDeclName() << Var->getDeclContext();
3842      Diag(PatternDecl->getLocation(),
3843           diag::note_explicit_instantiation_here);
3844      if (VarSpec)
3845        Var->setInvalidDecl();
3846    } else if (Var->getTemplateSpecializationKind()
3847                 == TSK_ExplicitInstantiationDefinition) {
3848      PendingInstantiations.push_back(
3849        std::make_pair(Var, PointOfInstantiation));
3850    }
3851
3852    return;
3853  }
3854
3855  TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
3856
3857  // Never instantiate an explicit specialization.
3858  if (TSK == TSK_ExplicitSpecialization)
3859    return;
3860
3861  // C++11 [temp.explicit]p10:
3862  //   Except for inline functions, [...] explicit instantiation declarations
3863  //   have the effect of suppressing the implicit instantiation of the entity
3864  //   to which they refer.
3865  if (TSK == TSK_ExplicitInstantiationDeclaration)
3866    return;
3867
3868  // Make sure to pass the instantiated variable to the consumer at the end.
3869  struct PassToConsumerRAII {
3870    ASTConsumer &Consumer;
3871    VarDecl *Var;
3872
3873    PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
3874      : Consumer(Consumer), Var(Var) { }
3875
3876    ~PassToConsumerRAII() {
3877      Consumer.HandleCXXStaticMemberVarInstantiation(Var);
3878    }
3879  } PassToConsumerRAII(Consumer, Var);
3880
3881  // If we already have a definition, we're done.
3882  if (VarDecl *Def = Var->getDefinition()) {
3883    // We may be explicitly instantiating something we've already implicitly
3884    // instantiated.
3885    Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
3886                                       PointOfInstantiation);
3887    return;
3888  }
3889
3890  InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
3891  if (Inst.isInvalid())
3892    return;
3893
3894  // If we're performing recursive template instantiation, create our own
3895  // queue of pending implicit instantiations that we will instantiate later,
3896  // while we're still within our own instantiation context.
3897  SavePendingLocalImplicitInstantiationsRAII
3898      SavedPendingLocalImplicitInstantiations(*this);
3899  SavePendingInstantiationsAndVTableUsesRAII
3900      SavePendingInstantiationsAndVTableUses(*this, /*Enabled=*/Recursive);
3901
3902  // Enter the scope of this instantiation. We don't use
3903  // PushDeclContext because we don't have a scope.
3904  ContextRAII PreviousContext(*this, Var->getDeclContext());
3905  LocalInstantiationScope Local(*this);
3906
3907  VarDecl *OldVar = Var;
3908  if (!VarSpec)
3909    Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
3910                                          TemplateArgs));
3911  else if (Var->isStaticDataMember() &&
3912           Var->getLexicalDeclContext()->isRecord()) {
3913    // We need to instantiate the definition of a static data member template,
3914    // and all we have is the in-class declaration of it. Instantiate a separate
3915    // declaration of the definition.
3916    TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
3917                                          TemplateArgs);
3918    Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl(
3919        VarSpec->getSpecializedTemplate(), Def, nullptr,
3920        VarSpec->getTemplateArgsInfo(), VarSpec->getTemplateArgs().asArray()));
3921    if (Var) {
3922      llvm::PointerUnion<VarTemplateDecl *,
3923                         VarTemplatePartialSpecializationDecl *> PatternPtr =
3924          VarSpec->getSpecializedTemplateOrPartial();
3925      if (VarTemplatePartialSpecializationDecl *Partial =
3926          PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
3927        cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
3928            Partial, &VarSpec->getTemplateInstantiationArgs());
3929
3930      // Merge the definition with the declaration.
3931      LookupResult R(*this, Var->getDeclName(), Var->getLocation(),
3932                     LookupOrdinaryName, ForRedeclaration);
3933      R.addDecl(OldVar);
3934      MergeVarDecl(Var, R);
3935
3936      // Attach the initializer.
3937      InstantiateVariableInitializer(Var, Def, TemplateArgs);
3938    }
3939  } else
3940    // Complete the existing variable's definition with an appropriately
3941    // substituted type and initializer.
3942    Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
3943
3944  PreviousContext.pop();
3945
3946  if (Var) {
3947    PassToConsumerRAII.Var = Var;
3948    Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(),
3949                                       OldVar->getPointOfInstantiation());
3950  }
3951
3952  // This variable may have local implicit instantiations that need to be
3953  // instantiated within this scope.
3954  PerformPendingInstantiations(/*LocalOnly=*/true);
3955
3956  Local.Exit();
3957
3958  if (Recursive) {
3959    // Define any newly required vtables.
3960    DefineUsedVTables();
3961
3962    // Instantiate any pending implicit instantiations found during the
3963    // instantiation of this template.
3964    PerformPendingInstantiations();
3965
3966    // PendingInstantiations and VTableUses are restored through
3967    // SavePendingInstantiationsAndVTableUses's destructor.
3968  }
3969}
3970
3971void
3972Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
3973                                 const CXXConstructorDecl *Tmpl,
3974                           const MultiLevelTemplateArgumentList &TemplateArgs) {
3975
3976  SmallVector<CXXCtorInitializer*, 4> NewInits;
3977  bool AnyErrors = Tmpl->isInvalidDecl();
3978
3979  // Instantiate all the initializers.
3980  for (const auto *Init : Tmpl->inits()) {
3981    // Only instantiate written initializers, let Sema re-construct implicit
3982    // ones.
3983    if (!Init->isWritten())
3984      continue;
3985
3986    SourceLocation EllipsisLoc;
3987
3988    if (Init->isPackExpansion()) {
3989      // This is a pack expansion. We should expand it now.
3990      TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
3991      SmallVector<UnexpandedParameterPack, 4> Unexpanded;
3992      collectUnexpandedParameterPacks(BaseTL, Unexpanded);
3993      collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
3994      bool ShouldExpand = false;
3995      bool RetainExpansion = false;
3996      Optional<unsigned> NumExpansions;
3997      if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
3998                                          BaseTL.getSourceRange(),
3999                                          Unexpanded,
4000                                          TemplateArgs, ShouldExpand,
4001                                          RetainExpansion,
4002                                          NumExpansions)) {
4003        AnyErrors = true;
4004        New->setInvalidDecl();
4005        continue;
4006      }
4007      assert(ShouldExpand && "Partial instantiation of base initializer?");
4008
4009      // Loop over all of the arguments in the argument pack(s),
4010      for (unsigned I = 0; I != *NumExpansions; ++I) {
4011        Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
4012
4013        // Instantiate the initializer.
4014        ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
4015                                               /*CXXDirectInit=*/true);
4016        if (TempInit.isInvalid()) {
4017          AnyErrors = true;
4018          break;
4019        }
4020
4021        // Instantiate the base type.
4022        TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
4023                                              TemplateArgs,
4024                                              Init->getSourceLocation(),
4025                                              New->getDeclName());
4026        if (!BaseTInfo) {
4027          AnyErrors = true;
4028          break;
4029        }
4030
4031        // Build the initializer.
4032        MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
4033                                                     BaseTInfo, TempInit.get(),
4034                                                     New->getParent(),
4035                                                     SourceLocation());
4036        if (NewInit.isInvalid()) {
4037          AnyErrors = true;
4038          break;
4039        }
4040
4041        NewInits.push_back(NewInit.get());
4042      }
4043
4044      continue;
4045    }
4046
4047    // Instantiate the initializer.
4048    ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
4049                                           /*CXXDirectInit=*/true);
4050    if (TempInit.isInvalid()) {
4051      AnyErrors = true;
4052      continue;
4053    }
4054
4055    MemInitResult NewInit;
4056    if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
4057      TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
4058                                        TemplateArgs,
4059                                        Init->getSourceLocation(),
4060                                        New->getDeclName());
4061      if (!TInfo) {
4062        AnyErrors = true;
4063        New->setInvalidDecl();
4064        continue;
4065      }
4066
4067      if (Init->isBaseInitializer())
4068        NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.get(),
4069                                       New->getParent(), EllipsisLoc);
4070      else
4071        NewInit = BuildDelegatingInitializer(TInfo, TempInit.get(),
4072                                  cast<CXXRecordDecl>(CurContext->getParent()));
4073    } else if (Init->isMemberInitializer()) {
4074      FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
4075                                                     Init->getMemberLocation(),
4076                                                     Init->getMember(),
4077                                                     TemplateArgs));
4078      if (!Member) {
4079        AnyErrors = true;
4080        New->setInvalidDecl();
4081        continue;
4082      }
4083
4084      NewInit = BuildMemberInitializer(Member, TempInit.get(),
4085                                       Init->getSourceLocation());
4086    } else if (Init->isIndirectMemberInitializer()) {
4087      IndirectFieldDecl *IndirectMember =
4088         cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
4089                                 Init->getMemberLocation(),
4090                                 Init->getIndirectMember(), TemplateArgs));
4091
4092      if (!IndirectMember) {
4093        AnyErrors = true;
4094        New->setInvalidDecl();
4095        continue;
4096      }
4097
4098      NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(),
4099                                       Init->getSourceLocation());
4100    }
4101
4102    if (NewInit.isInvalid()) {
4103      AnyErrors = true;
4104      New->setInvalidDecl();
4105    } else {
4106      NewInits.push_back(NewInit.get());
4107    }
4108  }
4109
4110  // Assign all the initializers to the new constructor.
4111  ActOnMemInitializers(New,
4112                       /*FIXME: ColonLoc */
4113                       SourceLocation(),
4114                       NewInits,
4115                       AnyErrors);
4116}
4117
4118// TODO: this could be templated if the various decl types used the
4119// same method name.
4120static bool isInstantiationOf(ClassTemplateDecl *Pattern,
4121                              ClassTemplateDecl *Instance) {
4122  Pattern = Pattern->getCanonicalDecl();
4123
4124  do {
4125    Instance = Instance->getCanonicalDecl();
4126    if (Pattern == Instance) return true;
4127    Instance = Instance->getInstantiatedFromMemberTemplate();
4128  } while (Instance);
4129
4130  return false;
4131}
4132
4133static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
4134                              FunctionTemplateDecl *Instance) {
4135  Pattern = Pattern->getCanonicalDecl();
4136
4137  do {
4138    Instance = Instance->getCanonicalDecl();
4139    if (Pattern == Instance) return true;
4140    Instance = Instance->getInstantiatedFromMemberTemplate();
4141  } while (Instance);
4142
4143  return false;
4144}
4145
4146static bool
4147isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
4148                  ClassTemplatePartialSpecializationDecl *Instance) {
4149  Pattern
4150    = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
4151  do {
4152    Instance = cast<ClassTemplatePartialSpecializationDecl>(
4153                                                Instance->getCanonicalDecl());
4154    if (Pattern == Instance)
4155      return true;
4156    Instance = Instance->getInstantiatedFromMember();
4157  } while (Instance);
4158
4159  return false;
4160}
4161
4162static bool isInstantiationOf(CXXRecordDecl *Pattern,
4163                              CXXRecordDecl *Instance) {
4164  Pattern = Pattern->getCanonicalDecl();
4165
4166  do {
4167    Instance = Instance->getCanonicalDecl();
4168    if (Pattern == Instance) return true;
4169    Instance = Instance->getInstantiatedFromMemberClass();
4170  } while (Instance);
4171
4172  return false;
4173}
4174
4175static bool isInstantiationOf(FunctionDecl *Pattern,
4176                              FunctionDecl *Instance) {
4177  Pattern = Pattern->getCanonicalDecl();
4178
4179  do {
4180    Instance = Instance->getCanonicalDecl();
4181    if (Pattern == Instance) return true;
4182    Instance = Instance->getInstantiatedFromMemberFunction();
4183  } while (Instance);
4184
4185  return false;
4186}
4187
4188static bool isInstantiationOf(EnumDecl *Pattern,
4189                              EnumDecl *Instance) {
4190  Pattern = Pattern->getCanonicalDecl();
4191
4192  do {
4193    Instance = Instance->getCanonicalDecl();
4194    if (Pattern == Instance) return true;
4195    Instance = Instance->getInstantiatedFromMemberEnum();
4196  } while (Instance);
4197
4198  return false;
4199}
4200
4201static bool isInstantiationOf(UsingShadowDecl *Pattern,
4202                              UsingShadowDecl *Instance,
4203                              ASTContext &C) {
4204  return declaresSameEntity(C.getInstantiatedFromUsingShadowDecl(Instance),
4205                            Pattern);
4206}
4207
4208static bool isInstantiationOf(UsingDecl *Pattern,
4209                              UsingDecl *Instance,
4210                              ASTContext &C) {
4211  return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
4212}
4213
4214static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
4215                              UsingDecl *Instance,
4216                              ASTContext &C) {
4217  return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
4218}
4219
4220static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
4221                              UsingDecl *Instance,
4222                              ASTContext &C) {
4223  return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
4224}
4225
4226static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
4227                                              VarDecl *Instance) {
4228  assert(Instance->isStaticDataMember());
4229
4230  Pattern = Pattern->getCanonicalDecl();
4231
4232  do {
4233    Instance = Instance->getCanonicalDecl();
4234    if (Pattern == Instance) return true;
4235    Instance = Instance->getInstantiatedFromStaticDataMember();
4236  } while (Instance);
4237
4238  return false;
4239}
4240
4241// Other is the prospective instantiation
4242// D is the prospective pattern
4243static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
4244  if (D->getKind() != Other->getKind()) {
4245    if (UnresolvedUsingTypenameDecl *UUD
4246          = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4247      if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
4248        return isInstantiationOf(UUD, UD, Ctx);
4249      }
4250    }
4251
4252    if (UnresolvedUsingValueDecl *UUD
4253          = dyn_cast<UnresolvedUsingValueDecl>(D)) {
4254      if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
4255        return isInstantiationOf(UUD, UD, Ctx);
4256      }
4257    }
4258
4259    return false;
4260  }
4261
4262  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
4263    return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
4264
4265  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
4266    return isInstantiationOf(cast<FunctionDecl>(D), Function);
4267
4268  if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
4269    return isInstantiationOf(cast<EnumDecl>(D), Enum);
4270
4271  if (VarDecl *Var = dyn_cast<VarDecl>(Other))
4272    if (Var->isStaticDataMember())
4273      return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
4274
4275  if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
4276    return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
4277
4278  if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
4279    return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
4280
4281  if (ClassTemplatePartialSpecializationDecl *PartialSpec
4282        = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
4283    return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
4284                             PartialSpec);
4285
4286  if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
4287    if (!Field->getDeclName()) {
4288      // This is an unnamed field.
4289      return declaresSameEntity(Ctx.getInstantiatedFromUnnamedFieldDecl(Field),
4290                                cast<FieldDecl>(D));
4291    }
4292  }
4293
4294  if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
4295    return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
4296
4297  if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
4298    return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
4299
4300  return D->getDeclName() && isa<NamedDecl>(Other) &&
4301    D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
4302}
4303
4304template<typename ForwardIterator>
4305static NamedDecl *findInstantiationOf(ASTContext &Ctx,
4306                                      NamedDecl *D,
4307                                      ForwardIterator first,
4308                                      ForwardIterator last) {
4309  for (; first != last; ++first)
4310    if (isInstantiationOf(Ctx, D, *first))
4311      return cast<NamedDecl>(*first);
4312
4313  return nullptr;
4314}
4315
4316/// \brief Finds the instantiation of the given declaration context
4317/// within the current instantiation.
4318///
4319/// \returns NULL if there was an error
4320DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
4321                          const MultiLevelTemplateArgumentList &TemplateArgs) {
4322  if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
4323    Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
4324    return cast_or_null<DeclContext>(ID);
4325  } else return DC;
4326}
4327
4328/// \brief Find the instantiation of the given declaration within the
4329/// current instantiation.
4330///
4331/// This routine is intended to be used when \p D is a declaration
4332/// referenced from within a template, that needs to mapped into the
4333/// corresponding declaration within an instantiation. For example,
4334/// given:
4335///
4336/// \code
4337/// template<typename T>
4338/// struct X {
4339///   enum Kind {
4340///     KnownValue = sizeof(T)
4341///   };
4342///
4343///   bool getKind() const { return KnownValue; }
4344/// };
4345///
4346/// template struct X<int>;
4347/// \endcode
4348///
4349/// In the instantiation of <tt>X<int>::getKind()</tt>, we need to map the
4350/// \p EnumConstantDecl for \p KnownValue (which refers to
4351/// <tt>X<T>::<Kind>::KnownValue</tt>) to its instantiation
4352/// (<tt>X<int>::<Kind>::KnownValue</tt>). \p FindInstantiatedDecl performs
4353/// this mapping from within the instantiation of <tt>X<int></tt>.
4354NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
4355                          const MultiLevelTemplateArgumentList &TemplateArgs) {
4356  DeclContext *ParentDC = D->getDeclContext();
4357  // FIXME: Parmeters of pointer to functions (y below) that are themselves
4358  // parameters (p below) can have their ParentDC set to the translation-unit
4359  // - thus we can not consistently check if the ParentDC of such a parameter
4360  // is Dependent or/and a FunctionOrMethod.
4361  // For e.g. this code, during Template argument deduction tries to
4362  // find an instantiated decl for (T y) when the ParentDC for y is
4363  // the translation unit.
4364  //   e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
4365  //   float baz(float(*)()) { return 0.0; }
4366  //   Foo(baz);
4367  // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
4368  // it gets here, always has a FunctionOrMethod as its ParentDC??
4369  // For now:
4370  //  - as long as we have a ParmVarDecl whose parent is non-dependent and
4371  //    whose type is not instantiation dependent, do nothing to the decl
4372  //  - otherwise find its instantiated decl.
4373  if (isa<ParmVarDecl>(D) && !ParentDC->isDependentContext() &&
4374      !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
4375    return D;
4376  if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
4377      isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
4378      (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) ||
4379      (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
4380    // D is a local of some kind. Look into the map of local
4381    // declarations to their instantiations.
4382    if (CurrentInstantiationScope) {
4383      if (auto Found = CurrentInstantiationScope->findInstantiationOf(D)) {
4384        if (Decl *FD = Found->dyn_cast<Decl *>())
4385          return cast<NamedDecl>(FD);
4386
4387        int PackIdx = ArgumentPackSubstitutionIndex;
4388        assert(PackIdx != -1 &&
4389               "found declaration pack but not pack expanding");
4390        typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
4391        return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
4392      }
4393    }
4394
4395    // If we're performing a partial substitution during template argument
4396    // deduction, we may not have values for template parameters yet. They
4397    // just map to themselves.
4398    if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
4399        isa<TemplateTemplateParmDecl>(D))
4400      return D;
4401
4402    if (D->isInvalidDecl())
4403      return nullptr;
4404
4405    // If we didn't find the decl, then we must have a label decl that hasn't
4406    // been found yet.  Lazily instantiate it and return it now.
4407    assert(isa<LabelDecl>(D));
4408
4409    Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
4410    assert(Inst && "Failed to instantiate label??");
4411
4412    CurrentInstantiationScope->InstantiatedLocal(D, Inst);
4413    return cast<LabelDecl>(Inst);
4414  }
4415
4416  // For variable template specializations, update those that are still
4417  // type-dependent.
4418  if (VarTemplateSpecializationDecl *VarSpec =
4419          dyn_cast<VarTemplateSpecializationDecl>(D)) {
4420    bool InstantiationDependent = false;
4421    const TemplateArgumentListInfo &VarTemplateArgs =
4422        VarSpec->getTemplateArgsInfo();
4423    if (TemplateSpecializationType::anyDependentTemplateArguments(
4424            VarTemplateArgs, InstantiationDependent))
4425      D = cast<NamedDecl>(
4426          SubstDecl(D, VarSpec->getDeclContext(), TemplateArgs));
4427    return D;
4428  }
4429
4430  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
4431    if (!Record->isDependentContext())
4432      return D;
4433
4434    // Determine whether this record is the "templated" declaration describing
4435    // a class template or class template partial specialization.
4436    ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
4437    if (ClassTemplate)
4438      ClassTemplate = ClassTemplate->getCanonicalDecl();
4439    else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4440               = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
4441      ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
4442
4443    // Walk the current context to find either the record or an instantiation of
4444    // it.
4445    DeclContext *DC = CurContext;
4446    while (!DC->isFileContext()) {
4447      // If we're performing substitution while we're inside the template
4448      // definition, we'll find our own context. We're done.
4449      if (DC->Equals(Record))
4450        return Record;
4451
4452      if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
4453        // Check whether we're in the process of instantiating a class template
4454        // specialization of the template we're mapping.
4455        if (ClassTemplateSpecializationDecl *InstSpec
4456                      = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
4457          ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
4458          if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
4459            return InstRecord;
4460        }
4461
4462        // Check whether we're in the process of instantiating a member class.
4463        if (isInstantiationOf(Record, InstRecord))
4464          return InstRecord;
4465      }
4466
4467      // Move to the outer template scope.
4468      if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
4469        if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
4470          DC = FD->getLexicalDeclContext();
4471          continue;
4472        }
4473      }
4474
4475      DC = DC->getParent();
4476    }
4477
4478    // Fall through to deal with other dependent record types (e.g.,
4479    // anonymous unions in class templates).
4480  }
4481
4482  if (!ParentDC->isDependentContext())
4483    return D;
4484
4485  ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
4486  if (!ParentDC)
4487    return nullptr;
4488
4489  if (ParentDC != D->getDeclContext()) {
4490    // We performed some kind of instantiation in the parent context,
4491    // so now we need to look into the instantiated parent context to
4492    // find the instantiation of the declaration D.
4493
4494    // If our context used to be dependent, we may need to instantiate
4495    // it before performing lookup into that context.
4496    bool IsBeingInstantiated = false;
4497    if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
4498      if (!Spec->isDependentContext()) {
4499        QualType T = Context.getTypeDeclType(Spec);
4500        const RecordType *Tag = T->getAs<RecordType>();
4501        assert(Tag && "type of non-dependent record is not a RecordType");
4502        if (Tag->isBeingDefined())
4503          IsBeingInstantiated = true;
4504        if (!Tag->isBeingDefined() &&
4505            RequireCompleteType(Loc, T, diag::err_incomplete_type))
4506          return nullptr;
4507
4508        ParentDC = Tag->getDecl();
4509      }
4510    }
4511
4512    NamedDecl *Result = nullptr;
4513    if (D->getDeclName()) {
4514      DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
4515      Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
4516    } else {
4517      // Since we don't have a name for the entity we're looking for,
4518      // our only option is to walk through all of the declarations to
4519      // find that name. This will occur in a few cases:
4520      //
4521      //   - anonymous struct/union within a template
4522      //   - unnamed class/struct/union/enum within a template
4523      //
4524      // FIXME: Find a better way to find these instantiations!
4525      Result = findInstantiationOf(Context, D,
4526                                   ParentDC->decls_begin(),
4527                                   ParentDC->decls_end());
4528    }
4529
4530    if (!Result) {
4531      if (isa<UsingShadowDecl>(D)) {
4532        // UsingShadowDecls can instantiate to nothing because of using hiding.
4533      } else if (Diags.hasErrorOccurred()) {
4534        // We've already complained about something, so most likely this
4535        // declaration failed to instantiate. There's no point in complaining
4536        // further, since this is normal in invalid code.
4537      } else if (IsBeingInstantiated) {
4538        // The class in which this member exists is currently being
4539        // instantiated, and we haven't gotten around to instantiating this
4540        // member yet. This can happen when the code uses forward declarations
4541        // of member classes, and introduces ordering dependencies via
4542        // template instantiation.
4543        Diag(Loc, diag::err_member_not_yet_instantiated)
4544          << D->getDeclName()
4545          << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
4546        Diag(D->getLocation(), diag::note_non_instantiated_member_here);
4547      } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
4548        // This enumeration constant was found when the template was defined,
4549        // but can't be found in the instantiation. This can happen if an
4550        // unscoped enumeration member is explicitly specialized.
4551        EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
4552        EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
4553                                                             TemplateArgs));
4554        assert(Spec->getTemplateSpecializationKind() ==
4555                 TSK_ExplicitSpecialization);
4556        Diag(Loc, diag::err_enumerator_does_not_exist)
4557          << D->getDeclName()
4558          << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
4559        Diag(Spec->getLocation(), diag::note_enum_specialized_here)
4560          << Context.getTypeDeclType(Spec);
4561      } else {
4562        // We should have found something, but didn't.
4563        llvm_unreachable("Unable to find instantiation of declaration!");
4564      }
4565    }
4566
4567    D = Result;
4568  }
4569
4570  return D;
4571}
4572
4573/// \brief Performs template instantiation for all implicit template
4574/// instantiations we have seen until this point.
4575void Sema::PerformPendingInstantiations(bool LocalOnly) {
4576  while (!PendingLocalImplicitInstantiations.empty() ||
4577         (!LocalOnly && !PendingInstantiations.empty())) {
4578    PendingImplicitInstantiation Inst;
4579
4580    if (PendingLocalImplicitInstantiations.empty()) {
4581      Inst = PendingInstantiations.front();
4582      PendingInstantiations.pop_front();
4583    } else {
4584      Inst = PendingLocalImplicitInstantiations.front();
4585      PendingLocalImplicitInstantiations.pop_front();
4586    }
4587
4588    // Instantiate function definitions
4589    if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
4590      PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
4591                                          "instantiating function definition");
4592      bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
4593                                TSK_ExplicitInstantiationDefinition;
4594      InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
4595                                    DefinitionRequired);
4596      continue;
4597    }
4598
4599    // Instantiate variable definitions
4600    VarDecl *Var = cast<VarDecl>(Inst.first);
4601
4602    assert((Var->isStaticDataMember() ||
4603            isa<VarTemplateSpecializationDecl>(Var)) &&
4604           "Not a static data member, nor a variable template"
4605           " specialization?");
4606
4607    // Don't try to instantiate declarations if the most recent redeclaration
4608    // is invalid.
4609    if (Var->getMostRecentDecl()->isInvalidDecl())
4610      continue;
4611
4612    // Check if the most recent declaration has changed the specialization kind
4613    // and removed the need for implicit instantiation.
4614    switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) {
4615    case TSK_Undeclared:
4616      llvm_unreachable("Cannot instantitiate an undeclared specialization.");
4617    case TSK_ExplicitInstantiationDeclaration:
4618    case TSK_ExplicitSpecialization:
4619      continue;  // No longer need to instantiate this type.
4620    case TSK_ExplicitInstantiationDefinition:
4621      // We only need an instantiation if the pending instantiation *is* the
4622      // explicit instantiation.
4623      if (Var != Var->getMostRecentDecl()) continue;
4624    case TSK_ImplicitInstantiation:
4625      break;
4626    }
4627
4628    PrettyDeclStackTraceEntry CrashInfo(*this, Var, SourceLocation(),
4629                                        "instantiating variable definition");
4630    bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
4631                              TSK_ExplicitInstantiationDefinition;
4632
4633    // Instantiate static data member definitions or variable template
4634    // specializations.
4635    InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
4636                                  DefinitionRequired);
4637  }
4638}
4639
4640void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
4641                       const MultiLevelTemplateArgumentList &TemplateArgs) {
4642  for (auto DD : Pattern->ddiags()) {
4643    switch (DD->getKind()) {
4644    case DependentDiagnostic::Access:
4645      HandleDependentAccessCheck(*DD, TemplateArgs);
4646      break;
4647    }
4648  }
4649}
4650