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