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