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