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