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