clang  16.0.0git
SemaDeclCXX.cpp
Go to the documentation of this file.
1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements semantic analysis for C++ declarations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/AST/ASTConsumer.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/RecordLayout.h"
26 #include "clang/AST/StmtVisitor.h"
27 #include "clang/AST/TypeLoc.h"
28 #include "clang/AST/TypeOrdering.h"
31 #include "clang/Basic/Specifiers.h"
32 #include "clang/Basic/TargetInfo.h"
34 #include "clang/Lex/Preprocessor.h"
36 #include "clang/Sema/DeclSpec.h"
38 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/Scope.h"
41 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/Template.h"
44 #include "llvm/ADT/ScopeExit.h"
45 #include "llvm/ADT/SmallString.h"
46 #include "llvm/ADT/STLExtras.h"
47 #include "llvm/ADT/StringExtras.h"
48 #include <map>
49 #include <set>
50 
51 using namespace clang;
52 
53 //===----------------------------------------------------------------------===//
54 // CheckDefaultArgumentVisitor
55 //===----------------------------------------------------------------------===//
56 
57 namespace {
58 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
59 /// the default argument of a parameter to determine whether it
60 /// contains any ill-formed subexpressions. For example, this will
61 /// diagnose the use of local variables or parameters within the
62 /// default argument expression.
63 class CheckDefaultArgumentVisitor
64  : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
65  Sema &S;
66  const Expr *DefaultArg;
67 
68 public:
69  CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
70  : S(S), DefaultArg(DefaultArg) {}
71 
72  bool VisitExpr(const Expr *Node);
73  bool VisitDeclRefExpr(const DeclRefExpr *DRE);
74  bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
75  bool VisitLambdaExpr(const LambdaExpr *Lambda);
76  bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
77 };
78 
79 /// VisitExpr - Visit all of the children of this expression.
80 bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
81  bool IsInvalid = false;
82  for (const Stmt *SubStmt : Node->children())
83  IsInvalid |= Visit(SubStmt);
84  return IsInvalid;
85 }
86 
87 /// VisitDeclRefExpr - Visit a reference to a declaration, to
88 /// determine whether this declaration can be used in the default
89 /// argument expression.
90 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
91  const NamedDecl *Decl = DRE->getDecl();
92  if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {
93  // C++ [dcl.fct.default]p9:
94  // [...] parameters of a function shall not be used in default
95  // argument expressions, even if they are not evaluated. [...]
96  //
97  // C++17 [dcl.fct.default]p9 (by CWG 2082):
98  // [...] A parameter shall not appear as a potentially-evaluated
99  // expression in a default argument. [...]
100  //
101  if (DRE->isNonOdrUse() != NOUR_Unevaluated)
102  return S.Diag(DRE->getBeginLoc(),
103  diag::err_param_default_argument_references_param)
104  << Param->getDeclName() << DefaultArg->getSourceRange();
105  } else {
106  const VarDecl *VD = nullptr;
107  if (const auto *BD = dyn_cast<BindingDecl>(Decl))
108  VD = dyn_cast_if_present<VarDecl>(BD->getDecomposedDecl());
109  else
110  VD = dyn_cast<VarDecl>(Decl);
111  if (VD) {
112  // C++ [dcl.fct.default]p7:
113  // Local variables shall not be used in default argument
114  // expressions.
115  //
116  // C++17 [dcl.fct.default]p7 (by CWG 2082):
117  // A local variable shall not appear as a potentially-evaluated
118  // expression in a default argument.
119  //
120  // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
121  // Note: A local variable cannot be odr-used (6.3) in a default
122  // argument.
123  //
124  if (VD->isLocalVarDecl() && !DRE->isNonOdrUse())
125  return S.Diag(DRE->getBeginLoc(),
126  diag::err_param_default_argument_references_local)
127  << Decl->getDeclName() << DefaultArg->getSourceRange();
128  }
129  }
130  return false;
131 }
132 
133 /// VisitCXXThisExpr - Visit a C++ "this" expression.
134 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
135  // C++ [dcl.fct.default]p8:
136  // The keyword this shall not be used in a default argument of a
137  // member function.
138  return S.Diag(ThisE->getBeginLoc(),
139  diag::err_param_default_argument_references_this)
140  << ThisE->getSourceRange();
141 }
142 
143 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
144  const PseudoObjectExpr *POE) {
145  bool Invalid = false;
146  for (const Expr *E : POE->semantics()) {
147  // Look through bindings.
148  if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
149  E = OVE->getSourceExpr();
150  assert(E && "pseudo-object binding without source expression?");
151  }
152 
153  Invalid |= Visit(E);
154  }
155  return Invalid;
156 }
157 
158 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
159  // [expr.prim.lambda.capture]p9
160  // a lambda-expression appearing in a default argument cannot implicitly or
161  // explicitly capture any local entity. Such a lambda-expression can still
162  // have an init-capture if any full-expression in its initializer satisfies
163  // the constraints of an expression appearing in a default argument.
164  bool Invalid = false;
165  for (const LambdaCapture &LC : Lambda->captures()) {
166  if (!Lambda->isInitCapture(&LC))
167  return S.Diag(LC.getLocation(), diag::err_lambda_capture_default_arg);
168  // Init captures are always VarDecl.
169  auto *D = cast<VarDecl>(LC.getCapturedVar());
170  Invalid |= Visit(D->getInit());
171  }
172  return Invalid;
173 }
174 } // namespace
175 
176 void
178  const CXXMethodDecl *Method) {
179  // If we have an MSAny spec already, don't bother.
180  if (!Method || ComputedEST == EST_MSAny)
181  return;
182 
183  const FunctionProtoType *Proto
184  = Method->getType()->getAs<FunctionProtoType>();
185  Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
186  if (!Proto)
187  return;
188 
190 
191  // If we have a throw-all spec at this point, ignore the function.
192  if (ComputedEST == EST_None)
193  return;
194 
195  if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
196  EST = EST_BasicNoexcept;
197 
198  switch (EST) {
199  case EST_Unparsed:
200  case EST_Uninstantiated:
201  case EST_Unevaluated:
202  llvm_unreachable("should not see unresolved exception specs here");
203 
204  // If this function can throw any exceptions, make a note of that.
205  case EST_MSAny:
206  case EST_None:
207  // FIXME: Whichever we see last of MSAny and None determines our result.
208  // We should make a consistent, order-independent choice here.
209  ClearExceptions();
210  ComputedEST = EST;
211  return;
212  case EST_NoexceptFalse:
213  ClearExceptions();
214  ComputedEST = EST_None;
215  return;
216  // FIXME: If the call to this decl is using any of its default arguments, we
217  // need to search them for potentially-throwing calls.
218  // If this function has a basic noexcept, it doesn't affect the outcome.
219  case EST_BasicNoexcept:
220  case EST_NoexceptTrue:
221  case EST_NoThrow:
222  return;
223  // If we're still at noexcept(true) and there's a throw() callee,
224  // change to that specification.
225  case EST_DynamicNone:
226  if (ComputedEST == EST_BasicNoexcept)
227  ComputedEST = EST_DynamicNone;
228  return;
230  llvm_unreachable(
231  "should not generate implicit declarations for dependent cases");
232  case EST_Dynamic:
233  break;
234  }
235  assert(EST == EST_Dynamic && "EST case not considered earlier.");
236  assert(ComputedEST != EST_None &&
237  "Shouldn't collect exceptions when throw-all is guaranteed.");
238  ComputedEST = EST_Dynamic;
239  // Record the exceptions in this function's exception specification.
240  for (const auto &E : Proto->exceptions())
241  if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
242  Exceptions.push_back(E);
243 }
244 
246  if (!S || ComputedEST == EST_MSAny)
247  return;
248 
249  // FIXME:
250  //
251  // C++0x [except.spec]p14:
252  // [An] implicit exception-specification specifies the type-id T if and
253  // only if T is allowed by the exception-specification of a function directly
254  // invoked by f's implicit definition; f shall allow all exceptions if any
255  // function it directly invokes allows all exceptions, and f shall allow no
256  // exceptions if every function it directly invokes allows no exceptions.
257  //
258  // Note in particular that if an implicit exception-specification is generated
259  // for a function containing a throw-expression, that specification can still
260  // be noexcept(true).
261  //
262  // Note also that 'directly invoked' is not defined in the standard, and there
263  // is no indication that we should only consider potentially-evaluated calls.
264  //
265  // Ultimately we should implement the intent of the standard: the exception
266  // specification should be the set of exceptions which can be thrown by the
267  // implicit definition. For now, we assume that any non-nothrow expression can
268  // throw any exception.
269 
270  if (Self->canThrow(S))
271  ComputedEST = EST_None;
272 }
273 
275  SourceLocation EqualLoc) {
276  if (RequireCompleteType(Param->getLocation(), Param->getType(),
277  diag::err_typecheck_decl_incomplete_type))
278  return true;
279 
280  // C++ [dcl.fct.default]p5
281  // A default argument expression is implicitly converted (clause
282  // 4) to the parameter type. The default argument expression has
283  // the same semantic constraints as the initializer expression in
284  // a declaration of a variable of the parameter type, using the
285  // copy-initialization semantics (8.5).
287  Param);
289  EqualLoc);
290  InitializationSequence InitSeq(*this, Entity, Kind, Arg);
291  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
292  if (Result.isInvalid())
293  return true;
294  Arg = Result.getAs<Expr>();
295 
296  CheckCompletedExpr(Arg, EqualLoc);
297  Arg = MaybeCreateExprWithCleanups(Arg);
298 
299  return Arg;
300 }
301 
303  SourceLocation EqualLoc) {
304  // Add the default argument to the parameter
305  Param->setDefaultArg(Arg);
306 
307  // We have already instantiated this parameter; provide each of the
308  // instantiations with the uninstantiated default argument.
309  UnparsedDefaultArgInstantiationsMap::iterator InstPos
310  = UnparsedDefaultArgInstantiations.find(Param);
311  if (InstPos != UnparsedDefaultArgInstantiations.end()) {
312  for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
313  InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
314 
315  // We're done tracking this parameter's instantiations.
316  UnparsedDefaultArgInstantiations.erase(InstPos);
317  }
318 }
319 
320 /// ActOnParamDefaultArgument - Check whether the default argument
321 /// provided for a function parameter is well-formed. If so, attach it
322 /// to the parameter declaration.
323 void
325  Expr *DefaultArg) {
326  if (!param || !DefaultArg)
327  return;
328 
329  ParmVarDecl *Param = cast<ParmVarDecl>(param);
330  UnparsedDefaultArgLocs.erase(Param);
331 
332  auto Fail = [&] {
333  Param->setInvalidDecl();
335  EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue));
336  };
337 
338  // Default arguments are only permitted in C++
339  if (!getLangOpts().CPlusPlus) {
340  Diag(EqualLoc, diag::err_param_default_argument)
341  << DefaultArg->getSourceRange();
342  return Fail();
343  }
344 
345  // Check for unexpanded parameter packs.
347  return Fail();
348  }
349 
350  // C++11 [dcl.fct.default]p3
351  // A default argument expression [...] shall not be specified for a
352  // parameter pack.
353  if (Param->isParameterPack()) {
354  Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
355  << DefaultArg->getSourceRange();
356  // Recover by discarding the default argument.
357  Param->setDefaultArg(nullptr);
358  return;
359  }
360 
361  ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);
362  if (Result.isInvalid())
363  return Fail();
364 
365  DefaultArg = Result.getAs<Expr>();
366 
367  // Check that the default argument is well-formed
368  CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
369  if (DefaultArgChecker.Visit(DefaultArg))
370  return Fail();
371 
372  SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
373 }
374 
375 /// ActOnParamUnparsedDefaultArgument - We've seen a default
376 /// argument for a function parameter, but we can't parse it yet
377 /// because we're inside a class definition. Note that this default
378 /// argument will be parsed later.
380  SourceLocation EqualLoc,
381  SourceLocation ArgLoc) {
382  if (!param)
383  return;
384 
385  ParmVarDecl *Param = cast<ParmVarDecl>(param);
386  Param->setUnparsedDefaultArg();
387  UnparsedDefaultArgLocs[Param] = ArgLoc;
388 }
389 
390 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
391 /// the default argument for the parameter param failed.
393  SourceLocation EqualLoc) {
394  if (!param)
395  return;
396 
397  ParmVarDecl *Param = cast<ParmVarDecl>(param);
398  Param->setInvalidDecl();
399  UnparsedDefaultArgLocs.erase(Param);
401  EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue));
402 }
403 
404 /// CheckExtraCXXDefaultArguments - Check for any extra default
405 /// arguments in the declarator, which is not a function declaration
406 /// or definition and therefore is not permitted to have default
407 /// arguments. This routine should be invoked for every declarator
408 /// that is not a function declaration or definition.
410  // C++ [dcl.fct.default]p3
411  // A default argument expression shall be specified only in the
412  // parameter-declaration-clause of a function declaration or in a
413  // template-parameter (14.1). It shall not be specified for a
414  // parameter pack. If it is specified in a
415  // parameter-declaration-clause, it shall not occur within a
416  // declarator or abstract-declarator of a parameter-declaration.
417  bool MightBeFunction = D.isFunctionDeclarationContext();
418  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
419  DeclaratorChunk &chunk = D.getTypeObject(i);
420  if (chunk.Kind == DeclaratorChunk::Function) {
421  if (MightBeFunction) {
422  // This is a function declaration. It can have default arguments, but
423  // keep looking in case its return type is a function type with default
424  // arguments.
425  MightBeFunction = false;
426  continue;
427  }
428  for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
429  ++argIdx) {
430  ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
431  if (Param->hasUnparsedDefaultArg()) {
432  std::unique_ptr<CachedTokens> Toks =
433  std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
434  SourceRange SR;
435  if (Toks->size() > 1)
436  SR = SourceRange((*Toks)[1].getLocation(),
437  Toks->back().getLocation());
438  else
439  SR = UnparsedDefaultArgLocs[Param];
440  Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
441  << SR;
442  } else if (Param->getDefaultArg()) {
443  Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
444  << Param->getDefaultArg()->getSourceRange();
445  Param->setDefaultArg(nullptr);
446  }
447  }
448  } else if (chunk.Kind != DeclaratorChunk::Paren) {
449  MightBeFunction = false;
450  }
451  }
452 }
453 
455  return llvm::any_of(FD->parameters(), [](ParmVarDecl *P) {
456  return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
457  });
458 }
459 
460 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
461 /// function, once we already know that they have the same
462 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
463 /// error, false otherwise.
465  Scope *S) {
466  bool Invalid = false;
467 
468  // The declaration context corresponding to the scope is the semantic
469  // parent, unless this is a local function declaration, in which case
470  // it is that surrounding function.
471  DeclContext *ScopeDC = New->isLocalExternDecl()
472  ? New->getLexicalDeclContext()
473  : New->getDeclContext();
474 
475  // Find the previous declaration for the purpose of default arguments.
476  FunctionDecl *PrevForDefaultArgs = Old;
477  for (/**/; PrevForDefaultArgs;
478  // Don't bother looking back past the latest decl if this is a local
479  // extern declaration; nothing else could work.
480  PrevForDefaultArgs = New->isLocalExternDecl()
481  ? nullptr
482  : PrevForDefaultArgs->getPreviousDecl()) {
483  // Ignore hidden declarations.
484  if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
485  continue;
486 
487  if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
488  !New->isCXXClassMember()) {
489  // Ignore default arguments of old decl if they are not in
490  // the same scope and this is not an out-of-line definition of
491  // a member function.
492  continue;
493  }
494 
495  if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
496  // If only one of these is a local function declaration, then they are
497  // declared in different scopes, even though isDeclInScope may think
498  // they're in the same scope. (If both are local, the scope check is
499  // sufficient, and if neither is local, then they are in the same scope.)
500  continue;
501  }
502 
503  // We found the right previous declaration.
504  break;
505  }
506 
507  // C++ [dcl.fct.default]p4:
508  // For non-template functions, default arguments can be added in
509  // later declarations of a function in the same
510  // scope. Declarations in different scopes have completely
511  // distinct sets of default arguments. That is, declarations in
512  // inner scopes do not acquire default arguments from
513  // declarations in outer scopes, and vice versa. In a given
514  // function declaration, all parameters subsequent to a
515  // parameter with a default argument shall have default
516  // arguments supplied in this or previous declarations. A
517  // default argument shall not be redefined by a later
518  // declaration (not even to the same value).
519  //
520  // C++ [dcl.fct.default]p6:
521  // Except for member functions of class templates, the default arguments
522  // in a member function definition that appears outside of the class
523  // definition are added to the set of default arguments provided by the
524  // member function declaration in the class definition.
525  for (unsigned p = 0, NumParams = PrevForDefaultArgs
526  ? PrevForDefaultArgs->getNumParams()
527  : 0;
528  p < NumParams; ++p) {
529  ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
530  ParmVarDecl *NewParam = New->getParamDecl(p);
531 
532  bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
533  bool NewParamHasDfl = NewParam->hasDefaultArg();
534 
535  if (OldParamHasDfl && NewParamHasDfl) {
536  unsigned DiagDefaultParamID =
537  diag::err_param_default_argument_redefinition;
538 
539  // MSVC accepts that default parameters be redefined for member functions
540  // of template class. The new default parameter's value is ignored.
541  Invalid = true;
542  if (getLangOpts().MicrosoftExt) {
543  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
544  if (MD && MD->getParent()->getDescribedClassTemplate()) {
545  // Merge the old default argument into the new parameter.
546  NewParam->setHasInheritedDefaultArg();
547  if (OldParam->hasUninstantiatedDefaultArg())
548  NewParam->setUninstantiatedDefaultArg(
549  OldParam->getUninstantiatedDefaultArg());
550  else
551  NewParam->setDefaultArg(OldParam->getInit());
552  DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
553  Invalid = false;
554  }
555  }
556 
557  // FIXME: If we knew where the '=' was, we could easily provide a fix-it
558  // hint here. Alternatively, we could walk the type-source information
559  // for NewParam to find the last source location in the type... but it
560  // isn't worth the effort right now. This is the kind of test case that
561  // is hard to get right:
562  // int f(int);
563  // void g(int (*fp)(int) = f);
564  // void g(int (*fp)(int) = &f);
565  Diag(NewParam->getLocation(), DiagDefaultParamID)
566  << NewParam->getDefaultArgRange();
567 
568  // Look for the function declaration where the default argument was
569  // actually written, which may be a declaration prior to Old.
570  for (auto Older = PrevForDefaultArgs;
571  OldParam->hasInheritedDefaultArg(); /**/) {
572  Older = Older->getPreviousDecl();
573  OldParam = Older->getParamDecl(p);
574  }
575 
576  Diag(OldParam->getLocation(), diag::note_previous_definition)
577  << OldParam->getDefaultArgRange();
578  } else if (OldParamHasDfl) {
579  // Merge the old default argument into the new parameter unless the new
580  // function is a friend declaration in a template class. In the latter
581  // case the default arguments will be inherited when the friend
582  // declaration will be instantiated.
583  if (New->getFriendObjectKind() == Decl::FOK_None ||
585  // It's important to use getInit() here; getDefaultArg()
586  // strips off any top-level ExprWithCleanups.
587  NewParam->setHasInheritedDefaultArg();
588  if (OldParam->hasUnparsedDefaultArg())
589  NewParam->setUnparsedDefaultArg();
590  else if (OldParam->hasUninstantiatedDefaultArg())
591  NewParam->setUninstantiatedDefaultArg(
592  OldParam->getUninstantiatedDefaultArg());
593  else
594  NewParam->setDefaultArg(OldParam->getInit());
595  }
596  } else if (NewParamHasDfl) {
597  if (New->getDescribedFunctionTemplate()) {
598  // Paragraph 4, quoted above, only applies to non-template functions.
599  Diag(NewParam->getLocation(),
600  diag::err_param_default_argument_template_redecl)
601  << NewParam->getDefaultArgRange();
602  Diag(PrevForDefaultArgs->getLocation(),
603  diag::note_template_prev_declaration)
604  << false;
605  } else if (New->getTemplateSpecializationKind()
608  // C++ [temp.expr.spec]p21:
609  // Default function arguments shall not be specified in a declaration
610  // or a definition for one of the following explicit specializations:
611  // - the explicit specialization of a function template;
612  // - the explicit specialization of a member function template;
613  // - the explicit specialization of a member function of a class
614  // template where the class template specialization to which the
615  // member function specialization belongs is implicitly
616  // instantiated.
617  Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
619  << New->getDeclName()
620  << NewParam->getDefaultArgRange();
621  } else if (New->getDeclContext()->isDependentContext()) {
622  // C++ [dcl.fct.default]p6 (DR217):
623  // Default arguments for a member function of a class template shall
624  // be specified on the initial declaration of the member function
625  // within the class template.
626  //
627  // Reading the tea leaves a bit in DR217 and its reference to DR205
628  // leads me to the conclusion that one cannot add default function
629  // arguments for an out-of-line definition of a member function of a
630  // dependent type.
631  int WhichKind = 2;
632  if (CXXRecordDecl *Record
633  = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
634  if (Record->getDescribedClassTemplate())
635  WhichKind = 0;
636  else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
637  WhichKind = 1;
638  else
639  WhichKind = 2;
640  }
641 
642  Diag(NewParam->getLocation(),
643  diag::err_param_default_argument_member_template_redecl)
644  << WhichKind
645  << NewParam->getDefaultArgRange();
646  }
647  }
648  }
649 
650  // DR1344: If a default argument is added outside a class definition and that
651  // default argument makes the function a special member function, the program
652  // is ill-formed. This can only happen for constructors.
653  if (isa<CXXConstructorDecl>(New) &&
655  CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
656  OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
657  if (NewSM != OldSM) {
658  ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
659  assert(NewParam->hasDefaultArg());
660  Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
661  << NewParam->getDefaultArgRange() << NewSM;
662  Diag(Old->getLocation(), diag::note_previous_declaration);
663  }
664  }
665 
666  const FunctionDecl *Def;
667  // C++11 [dcl.constexpr]p1: If any declaration of a function or function
668  // template has a constexpr specifier then all its declarations shall
669  // contain the constexpr specifier.
670  if (New->getConstexprKind() != Old->getConstexprKind()) {
671  Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
672  << New << static_cast<int>(New->getConstexprKind())
673  << static_cast<int>(Old->getConstexprKind());
674  Diag(Old->getLocation(), diag::note_previous_declaration);
675  Invalid = true;
676  } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
677  Old->isDefined(Def) &&
678  // If a friend function is inlined but does not have 'inline'
679  // specifier, it is a definition. Do not report attribute conflict
680  // in this case, redefinition will be diagnosed later.
681  (New->isInlineSpecified() ||
682  New->getFriendObjectKind() == Decl::FOK_None)) {
683  // C++11 [dcl.fcn.spec]p4:
684  // If the definition of a function appears in a translation unit before its
685  // first declaration as inline, the program is ill-formed.
686  Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
687  Diag(Def->getLocation(), diag::note_previous_definition);
688  Invalid = true;
689  }
690 
691  // C++17 [temp.deduct.guide]p3:
692  // Two deduction guide declarations in the same translation unit
693  // for the same class template shall not have equivalent
694  // parameter-declaration-clauses.
695  if (isa<CXXDeductionGuideDecl>(New) &&
697  Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
698  Diag(Old->getLocation(), diag::note_previous_declaration);
699  }
700 
701  // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
702  // argument expression, that declaration shall be a definition and shall be
703  // the only declaration of the function or function template in the
704  // translation unit.
707  Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
708  Diag(Old->getLocation(), diag::note_previous_declaration);
709  Invalid = true;
710  }
711 
712  // C++11 [temp.friend]p4 (DR329):
713  // When a function is defined in a friend function declaration in a class
714  // template, the function is instantiated when the function is odr-used.
715  // The same restrictions on multiple declarations and definitions that
716  // apply to non-template function declarations and definitions also apply
717  // to these implicit definitions.
718  const FunctionDecl *OldDefinition = nullptr;
720  Old->isDefined(OldDefinition, true))
721  CheckForFunctionRedefinition(New, OldDefinition);
722 
723  return Invalid;
724 }
725 
726 NamedDecl *
728  MultiTemplateParamsArg TemplateParamLists) {
729  assert(D.isDecompositionDeclarator());
731 
732  // The syntax only allows a decomposition declarator as a simple-declaration,
733  // a for-range-declaration, or a condition in Clang, but we parse it in more
734  // cases than that.
736  Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
737  << Decomp.getSourceRange();
738  return nullptr;
739  }
740 
741  if (!TemplateParamLists.empty()) {
742  // FIXME: There's no rule against this, but there are also no rules that
743  // would actually make it usable, so we reject it for now.
744  Diag(TemplateParamLists.front()->getTemplateLoc(),
745  diag::err_decomp_decl_template);
746  return nullptr;
747  }
748 
749  Diag(Decomp.getLSquareLoc(),
751  ? diag::ext_decomp_decl
753  ? diag::ext_decomp_decl_cond
754  : diag::warn_cxx14_compat_decomp_decl)
755  << Decomp.getSourceRange();
756 
757  // The semantic context is always just the current context.
758  DeclContext *const DC = CurContext;
759 
760  // C++17 [dcl.dcl]/8:
761  // The decl-specifier-seq shall contain only the type-specifier auto
762  // and cv-qualifiers.
763  // C++2a [dcl.dcl]/8:
764  // If decl-specifier-seq contains any decl-specifier other than static,
765  // thread_local, auto, or cv-qualifiers, the program is ill-formed.
766  auto &DS = D.getDeclSpec();
767  {
768  SmallVector<StringRef, 8> BadSpecifiers;
769  SmallVector<SourceLocation, 8> BadSpecifierLocs;
770  SmallVector<StringRef, 8> CPlusPlus20Specifiers;
771  SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
772  if (auto SCS = DS.getStorageClassSpec()) {
773  if (SCS == DeclSpec::SCS_static) {
774  CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
775  CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
776  } else {
777  BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
778  BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
779  }
780  }
781  if (auto TSCS = DS.getThreadStorageClassSpec()) {
782  CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
783  CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
784  }
785  if (DS.hasConstexprSpecifier()) {
786  BadSpecifiers.push_back(
787  DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
788  BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
789  }
790  if (DS.isInlineSpecified()) {
791  BadSpecifiers.push_back("inline");
792  BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
793  }
794  if (!BadSpecifiers.empty()) {
795  auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
796  Err << (int)BadSpecifiers.size()
797  << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
798  // Don't add FixItHints to remove the specifiers; we do still respect
799  // them when building the underlying variable.
800  for (auto Loc : BadSpecifierLocs)
801  Err << SourceRange(Loc, Loc);
802  } else if (!CPlusPlus20Specifiers.empty()) {
803  auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
805  ? diag::warn_cxx17_compat_decomp_decl_spec
806  : diag::ext_decomp_decl_spec);
807  Warn << (int)CPlusPlus20Specifiers.size()
808  << llvm::join(CPlusPlus20Specifiers.begin(),
809  CPlusPlus20Specifiers.end(), " ");
810  for (auto Loc : CPlusPlus20SpecifierLocs)
811  Warn << SourceRange(Loc, Loc);
812  }
813  // We can't recover from it being declared as a typedef.
814  if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
815  return nullptr;
816  }
817 
818  // C++2a [dcl.struct.bind]p1:
819  // A cv that includes volatile is deprecated
820  if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
822  Diag(DS.getVolatileSpecLoc(),
823  diag::warn_deprecated_volatile_structured_binding);
824 
825  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
826  QualType R = TInfo->getType();
827 
830  D.setInvalidType();
831 
832  // The syntax only allows a single ref-qualifier prior to the decomposition
833  // declarator. No other declarator chunks are permitted. Also check the type
834  // specifier here.
835  if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
836  D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
837  (D.getNumTypeObjects() == 1 &&
839  Diag(Decomp.getLSquareLoc(),
840  (D.hasGroupingParens() ||
841  (D.getNumTypeObjects() &&
843  ? diag::err_decomp_decl_parens
844  : diag::err_decomp_decl_type)
845  << R;
846 
847  // In most cases, there's no actual problem with an explicitly-specified
848  // type, but a function type won't work here, and ActOnVariableDeclarator
849  // shouldn't be called for such a type.
850  if (R->isFunctionType())
851  D.setInvalidType();
852  }
853 
854  // Build the BindingDecls.
856 
857  // Build the BindingDecls.
858  for (auto &B : D.getDecompositionDeclarator().bindings()) {
859  // Check for name conflicts.
860  DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
861  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
863  LookupName(Previous, S,
864  /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
865 
866  // It's not permitted to shadow a template parameter name.
867  if (Previous.isSingleResult() &&
868  Previous.getFoundDecl()->isTemplateParameter()) {
870  Previous.getFoundDecl());
871  Previous.clear();
872  }
873 
874  auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
875 
876  // Find the shadowed declaration before filtering for scope.
877  NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
879  : nullptr;
880 
881  bool ConsiderLinkage = DC->isFunctionOrMethod() &&
882  DS.getStorageClassSpec() == DeclSpec::SCS_extern;
883  FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
884  /*AllowInlineNamespace*/false);
885 
886  if (!Previous.empty()) {
887  auto *Old = Previous.getRepresentativeDecl();
888  Diag(B.NameLoc, diag::err_redefinition) << B.Name;
889  Diag(Old->getLocation(), diag::note_previous_definition);
890  } else if (ShadowedDecl && !D.isRedeclaration()) {
891  CheckShadow(BD, ShadowedDecl, Previous);
892  }
893  PushOnScopeChains(BD, S, true);
894  Bindings.push_back(BD);
895  ParsingInitForAutoVars.insert(BD);
896  }
897 
898  // There are no prior lookup results for the variable itself, because it
899  // is unnamed.
900  DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
901  Decomp.getLSquareLoc());
902  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
904 
905  // Build the variable that holds the non-decomposed object.
906  bool AddToScope = true;
907  NamedDecl *New =
908  ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
909  MultiTemplateParamsArg(), AddToScope, Bindings);
910  if (AddToScope) {
911  S->AddDecl(New);
913  }
914 
916  checkDeclIsAllowedInOpenMPTarget(nullptr, New);
917 
918  return New;
919 }
920 
923  QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
924  llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
925  if ((int64_t)Bindings.size() != NumElems) {
926  S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
927  << DecompType << (unsigned)Bindings.size()
928  << (unsigned)NumElems.getLimitedValue(UINT_MAX)
929  << toString(NumElems, 10) << (NumElems < Bindings.size());
930  return true;
931  }
932 
933  unsigned I = 0;
934  for (auto *B : Bindings) {
935  SourceLocation Loc = B->getLocation();
936  ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
937  if (E.isInvalid())
938  return true;
939  E = GetInit(Loc, E.get(), I++);
940  if (E.isInvalid())
941  return true;
942  B->setBinding(ElemType, E.get());
943  }
944 
945  return false;
946 }
947 
950  ValueDecl *Src, QualType DecompType,
951  const llvm::APSInt &NumElems,
952  QualType ElemType) {
954  S, Bindings, Src, DecompType, NumElems, ElemType,
955  [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
956  ExprResult E = S.ActOnIntegerConstant(Loc, I);
957  if (E.isInvalid())
958  return ExprError();
959  return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
960  });
961 }
962 
964  ValueDecl *Src, QualType DecompType,
965  const ConstantArrayType *CAT) {
966  return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
967  llvm::APSInt(CAT->getSize()),
968  CAT->getElementType());
969 }
970 
972  ValueDecl *Src, QualType DecompType,
973  const VectorType *VT) {
975  S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
977  DecompType.getQualifiers()));
978 }
979 
982  ValueDecl *Src, QualType DecompType,
983  const ComplexType *CT) {
985  S, Bindings, Src, DecompType, llvm::APSInt::get(2),
987  DecompType.getQualifiers()),
988  [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
989  return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
990  });
991 }
992 
995  const TemplateParameterList *Params) {
996  SmallString<128> SS;
997  llvm::raw_svector_ostream OS(SS);
998  bool First = true;
999  unsigned I = 0;
1000  for (auto &Arg : Args.arguments()) {
1001  if (!First)
1002  OS << ", ";
1003  Arg.getArgument().print(PrintingPolicy, OS,
1005  PrintingPolicy, Params, I));
1006  First = false;
1007  I++;
1008  }
1009  return std::string(OS.str());
1010 }
1011 
1012 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
1013  SourceLocation Loc, StringRef Trait,
1015  unsigned DiagID) {
1016  auto DiagnoseMissing = [&] {
1017  if (DiagID)
1018  S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
1019  Args, /*Params*/ nullptr);
1020  return true;
1021  };
1022 
1023  // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1025  if (!Std)
1026  return DiagnoseMissing();
1027 
1028  // Look up the trait itself, within namespace std. We can diagnose various
1029  // problems with this lookup even if we've been asked to not diagnose a
1030  // missing specialization, because this can only fail if the user has been
1031  // declaring their own names in namespace std or we don't support the
1032  // standard library implementation in use.
1033  LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
1035  if (!S.LookupQualifiedName(Result, Std))
1036  return DiagnoseMissing();
1037  if (Result.isAmbiguous())
1038  return true;
1039 
1040  ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1041  if (!TraitTD) {
1042  Result.suppressDiagnostics();
1043  NamedDecl *Found = *Result.begin();
1044  S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1045  S.Diag(Found->getLocation(), diag::note_declared_at);
1046  return true;
1047  }
1048 
1049  // Build the template-id.
1050  QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
1051  if (TraitTy.isNull())
1052  return true;
1053  if (!S.isCompleteType(Loc, TraitTy)) {
1054  if (DiagID)
1056  Loc, TraitTy, DiagID,
1058  TraitTD->getTemplateParameters()));
1059  return true;
1060  }
1061 
1062  CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1063  assert(RD && "specialization of class template is not a class?");
1064 
1065  // Look up the member of the trait type.
1066  S.LookupQualifiedName(TraitMemberLookup, RD);
1067  return TraitMemberLookup.isAmbiguous();
1068 }
1069 
1070 static TemplateArgumentLoc
1072  uint64_t I) {
1073  TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
1074  return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1075 }
1076 
1077 static TemplateArgumentLoc
1080 }
1081 
1082 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1083 
1084 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1085  llvm::APSInt &Size) {
1088 
1091 
1092  // Form template argument list for tuple_size<T>.
1093  TemplateArgumentListInfo Args(Loc, Loc);
1095 
1096  // If there's no tuple_size specialization or the lookup of 'value' is empty,
1097  // it's not tuple-like.
1098  if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1099  R.empty())
1100  return IsTupleLike::NotTupleLike;
1101 
1102  // If we get this far, we've committed to the tuple interpretation, but
1103  // we can still fail if there actually isn't a usable ::value.
1104 
1105  struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1106  LookupResult &R;
1108  ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1109  : R(R), Args(Args) {}
1110  Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1111  SourceLocation Loc) override {
1112  return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1114  /*Params*/ nullptr);
1115  }
1116  } Diagnoser(R, Args);
1117 
1118  ExprResult E =
1119  S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1120  if (E.isInvalid())
1121  return IsTupleLike::Error;
1122 
1123  E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
1124  if (E.isInvalid())
1125  return IsTupleLike::Error;
1126 
1127  return IsTupleLike::TupleLike;
1128 }
1129 
1130 /// \return std::tuple_element<I, T>::type.
1132  unsigned I, QualType T) {
1133  // Form template argument list for tuple_element<I, T>.
1134  TemplateArgumentListInfo Args(Loc, Loc);
1135  Args.addArgument(
1138 
1139  DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1140  LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1142  S, R, Loc, "tuple_element", Args,
1143  diag::err_decomp_decl_std_tuple_element_not_specialized))
1144  return QualType();
1145 
1146  auto *TD = R.getAsSingle<TypeDecl>();
1147  if (!TD) {
1148  R.suppressDiagnostics();
1149  S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1151  /*Params*/ nullptr);
1152  if (!R.empty())
1153  S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1154  return QualType();
1155  }
1156 
1157  return S.Context.getTypeDeclType(TD);
1158 }
1159 
1160 namespace {
1161 struct InitializingBinding {
1162  Sema &S;
1163  InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1166  Ctx.PointOfInstantiation = BD->getLocation();
1167  Ctx.Entity = BD;
1168  S.pushCodeSynthesisContext(Ctx);
1169  }
1170  ~InitializingBinding() {
1172  }
1173 };
1174 }
1175 
1178  VarDecl *Src, QualType DecompType,
1179  const llvm::APSInt &TupleSize) {
1180  if ((int64_t)Bindings.size() != TupleSize) {
1181  S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1182  << DecompType << (unsigned)Bindings.size()
1183  << (unsigned)TupleSize.getLimitedValue(UINT_MAX)
1184  << toString(TupleSize, 10) << (TupleSize < Bindings.size());
1185  return true;
1186  }
1187 
1188  if (Bindings.empty())
1189  return false;
1190 
1191  DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1192 
1193  // [dcl.decomp]p3:
1194  // The unqualified-id get is looked up in the scope of E by class member
1195  // access lookup ...
1196  LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1197  bool UseMemberGet = false;
1198  if (S.isCompleteType(Src->getLocation(), DecompType)) {
1199  if (auto *RD = DecompType->getAsCXXRecordDecl())
1200  S.LookupQualifiedName(MemberGet, RD);
1201  if (MemberGet.isAmbiguous())
1202  return true;
1203  // ... and if that finds at least one declaration that is a function
1204  // template whose first template parameter is a non-type parameter ...
1205  for (NamedDecl *D : MemberGet) {
1206  if (FunctionTemplateDecl *FTD =
1207  dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1208  TemplateParameterList *TPL = FTD->getTemplateParameters();
1209  if (TPL->size() != 0 &&
1210  isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1211  // ... the initializer is e.get<i>().
1212  UseMemberGet = true;
1213  break;
1214  }
1215  }
1216  }
1217  }
1218 
1219  unsigned I = 0;
1220  for (auto *B : Bindings) {
1221  InitializingBinding InitContext(S, B);
1222  SourceLocation Loc = B->getLocation();
1223 
1224  ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1225  if (E.isInvalid())
1226  return true;
1227 
1228  // e is an lvalue if the type of the entity is an lvalue reference and
1229  // an xvalue otherwise
1230  if (!Src->getType()->isLValueReferenceType())
1231  E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1232  E.get(), nullptr, VK_XValue,
1233  FPOptionsOverride());
1234 
1235  TemplateArgumentListInfo Args(Loc, Loc);
1236  Args.addArgument(
1238 
1239  if (UseMemberGet) {
1240  // if [lookup of member get] finds at least one declaration, the
1241  // initializer is e.get<i-1>().
1242  E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1243  CXXScopeSpec(), SourceLocation(), nullptr,
1244  MemberGet, &Args, nullptr);
1245  if (E.isInvalid())
1246  return true;
1247 
1248  E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc);
1249  } else {
1250  // Otherwise, the initializer is get<i-1>(e), where get is looked up
1251  // in the associated namespaces.
1254  DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1256 
1257  Expr *Arg = E.get();
1258  E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1259  }
1260  if (E.isInvalid())
1261  return true;
1262  Expr *Init = E.get();
1263 
1264  // Given the type T designated by std::tuple_element<i - 1, E>::type,
1265  QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1266  if (T.isNull())
1267  return true;
1268 
1269  // each vi is a variable of type "reference to T" initialized with the
1270  // initializer, where the reference is an lvalue reference if the
1271  // initializer is an lvalue and an rvalue reference otherwise
1272  QualType RefType =
1273  S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1274  if (RefType.isNull())
1275  return true;
1276  auto *RefVD = VarDecl::Create(
1277  S.Context, Src->getDeclContext(), Loc, Loc,
1278  B->getDeclName().getAsIdentifierInfo(), RefType,
1280  RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1281  RefVD->setTSCSpec(Src->getTSCSpec());
1282  RefVD->setImplicit();
1283  if (Src->isInlineSpecified())
1284  RefVD->setInlineSpecified();
1285  RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1286 
1289  InitializationSequence Seq(S, Entity, Kind, Init);
1290  E = Seq.Perform(S, Entity, Kind, Init);
1291  if (E.isInvalid())
1292  return true;
1293  E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1294  if (E.isInvalid())
1295  return true;
1296  RefVD->setInit(E.get());
1298 
1300  DeclarationNameInfo(B->getDeclName(), Loc),
1301  RefVD);
1302  if (E.isInvalid())
1303  return true;
1304 
1305  B->setBinding(T, E.get());
1306  I++;
1307  }
1308 
1309  return false;
1310 }
1311 
1312 /// Find the base class to decompose in a built-in decomposition of a class type.
1313 /// This base class search is, unfortunately, not quite like any other that we
1314 /// perform anywhere else in C++.
1316  const CXXRecordDecl *RD,
1317  CXXCastPath &BasePath) {
1318  auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1319  CXXBasePath &Path) {
1320  return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1321  };
1322 
1323  const CXXRecordDecl *ClassWithFields = nullptr;
1325  if (RD->hasDirectFields())
1326  // [dcl.decomp]p4:
1327  // Otherwise, all of E's non-static data members shall be public direct
1328  // members of E ...
1329  ClassWithFields = RD;
1330  else {
1331  // ... or of ...
1332  CXXBasePaths Paths;
1333  Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1334  if (!RD->lookupInBases(BaseHasFields, Paths)) {
1335  // If no classes have fields, just decompose RD itself. (This will work
1336  // if and only if zero bindings were provided.)
1337  return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1338  }
1339 
1340  CXXBasePath *BestPath = nullptr;
1341  for (auto &P : Paths) {
1342  if (!BestPath)
1343  BestPath = &P;
1344  else if (!S.Context.hasSameType(P.back().Base->getType(),
1345  BestPath->back().Base->getType())) {
1346  // ... the same ...
1347  S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1348  << false << RD << BestPath->back().Base->getType()
1349  << P.back().Base->getType();
1350  return DeclAccessPair();
1351  } else if (P.Access < BestPath->Access) {
1352  BestPath = &P;
1353  }
1354  }
1355 
1356  // ... unambiguous ...
1357  QualType BaseType = BestPath->back().Base->getType();
1358  if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1359  S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1360  << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1361  return DeclAccessPair();
1362  }
1363 
1364  // ... [accessible, implied by other rules] base class of E.
1365  S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1366  *BestPath, diag::err_decomp_decl_inaccessible_base);
1367  AS = BestPath->Access;
1368 
1369  ClassWithFields = BaseType->getAsCXXRecordDecl();
1370  S.BuildBasePathArray(Paths, BasePath);
1371  }
1372 
1373  // The above search did not check whether the selected class itself has base
1374  // classes with fields, so check that now.
1375  CXXBasePaths Paths;
1376  if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1377  S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1378  << (ClassWithFields == RD) << RD << ClassWithFields
1379  << Paths.front().back().Base->getType();
1380  return DeclAccessPair();
1381  }
1382 
1383  return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1384 }
1385 
1387  ValueDecl *Src, QualType DecompType,
1388  const CXXRecordDecl *OrigRD) {
1389  if (S.RequireCompleteType(Src->getLocation(), DecompType,
1390  diag::err_incomplete_type))
1391  return true;
1392 
1393  CXXCastPath BasePath;
1394  DeclAccessPair BasePair =
1395  findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1396  const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1397  if (!RD)
1398  return true;
1400  DecompType.getQualifiers());
1401 
1402  auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1403  unsigned NumFields = llvm::count_if(
1404  RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1405  assert(Bindings.size() != NumFields);
1406  S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1407  << DecompType << (unsigned)Bindings.size() << NumFields << NumFields
1408  << (NumFields < Bindings.size());
1409  return true;
1410  };
1411 
1412  // all of E's non-static data members shall be [...] well-formed
1413  // when named as e.name in the context of the structured binding,
1414  // E shall not have an anonymous union member, ...
1415  unsigned I = 0;
1416  for (auto *FD : RD->fields()) {
1417  if (FD->isUnnamedBitfield())
1418  continue;
1419 
1420  // All the non-static data members are required to be nameable, so they
1421  // must all have names.
1422  if (!FD->getDeclName()) {
1423  if (RD->isLambda()) {
1424  S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda);
1425  S.Diag(RD->getLocation(), diag::note_lambda_decl);
1426  return true;
1427  }
1428 
1429  if (FD->isAnonymousStructOrUnion()) {
1430  S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1431  << DecompType << FD->getType()->isUnionType();
1432  S.Diag(FD->getLocation(), diag::note_declared_at);
1433  return true;
1434  }
1435 
1436  // FIXME: Are there any other ways we could have an anonymous member?
1437  }
1438 
1439  // We have a real field to bind.
1440  if (I >= Bindings.size())
1441  return DiagnoseBadNumberOfBindings();
1442  auto *B = Bindings[I++];
1443  SourceLocation Loc = B->getLocation();
1444 
1445  // The field must be accessible in the context of the structured binding.
1446  // We already checked that the base class is accessible.
1447  // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1448  // const_cast here.
1450  Loc, const_cast<CXXRecordDecl *>(OrigRD),
1452  BasePair.getAccess(), FD->getAccess())));
1453 
1454  // Initialize the binding to Src.FD.
1455  ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1456  if (E.isInvalid())
1457  return true;
1458  E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1459  VK_LValue, &BasePath);
1460  if (E.isInvalid())
1461  return true;
1462  E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1463  CXXScopeSpec(), FD,
1464  DeclAccessPair::make(FD, FD->getAccess()),
1465  DeclarationNameInfo(FD->getDeclName(), Loc));
1466  if (E.isInvalid())
1467  return true;
1468 
1469  // If the type of the member is T, the referenced type is cv T, where cv is
1470  // the cv-qualification of the decomposition expression.
1471  //
1472  // FIXME: We resolve a defect here: if the field is mutable, we do not add
1473  // 'const' to the type of the field.
1474  Qualifiers Q = DecompType.getQualifiers();
1475  if (FD->isMutable())
1476  Q.removeConst();
1477  B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1478  }
1479 
1480  if (I != Bindings.size())
1481  return DiagnoseBadNumberOfBindings();
1482 
1483  return false;
1484 }
1485 
1487  QualType DecompType = DD->getType();
1488 
1489  // If the type of the decomposition is dependent, then so is the type of
1490  // each binding.
1491  if (DecompType->isDependentType()) {
1492  for (auto *B : DD->bindings())
1493  B->setType(Context.DependentTy);
1494  return;
1495  }
1496 
1497  DecompType = DecompType.getNonReferenceType();
1499 
1500  // C++1z [dcl.decomp]/2:
1501  // If E is an array type [...]
1502  // As an extension, we also support decomposition of built-in complex and
1503  // vector types.
1504  if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1505  if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1506  DD->setInvalidDecl();
1507  return;
1508  }
1509  if (auto *VT = DecompType->getAs<VectorType>()) {
1510  if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1511  DD->setInvalidDecl();
1512  return;
1513  }
1514  if (auto *CT = DecompType->getAs<ComplexType>()) {
1515  if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1516  DD->setInvalidDecl();
1517  return;
1518  }
1519 
1520  // C++1z [dcl.decomp]/3:
1521  // if the expression std::tuple_size<E>::value is a well-formed integral
1522  // constant expression, [...]
1523  llvm::APSInt TupleSize(32);
1524  switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1525  case IsTupleLike::Error:
1526  DD->setInvalidDecl();
1527  return;
1528 
1529  case IsTupleLike::TupleLike:
1530  if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1531  DD->setInvalidDecl();
1532  return;
1533 
1534  case IsTupleLike::NotTupleLike:
1535  break;
1536  }
1537 
1538  // C++1z [dcl.dcl]/8:
1539  // [E shall be of array or non-union class type]
1540  CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1541  if (!RD || RD->isUnion()) {
1542  Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1543  << DD << !RD << DecompType;
1544  DD->setInvalidDecl();
1545  return;
1546  }
1547 
1548  // C++1z [dcl.decomp]/4:
1549  // all of E's non-static data members shall be [...] direct members of
1550  // E or of the same unambiguous public base class of E, ...
1551  if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1552  DD->setInvalidDecl();
1553 }
1554 
1555 /// Merge the exception specifications of two variable declarations.
1556 ///
1557 /// This is called when there's a redeclaration of a VarDecl. The function
1558 /// checks if the redeclaration might have an exception specification and
1559 /// validates compatibility and merges the specs if necessary.
1561  // Shortcut if exceptions are disabled.
1562  if (!getLangOpts().CXXExceptions)
1563  return;
1564 
1565  assert(Context.hasSameType(New->getType(), Old->getType()) &&
1566  "Should only be called if types are otherwise the same.");
1567 
1568  QualType NewType = New->getType();
1569  QualType OldType = Old->getType();
1570 
1571  // We're only interested in pointers and references to functions, as well
1572  // as pointers to member functions.
1573  if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1574  NewType = R->getPointeeType();
1575  OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1576  } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1577  NewType = P->getPointeeType();
1578  OldType = OldType->castAs<PointerType>()->getPointeeType();
1579  } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1580  NewType = M->getPointeeType();
1581  OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1582  }
1583 
1584  if (!NewType->isFunctionProtoType())
1585  return;
1586 
1587  // There's lots of special cases for functions. For function pointers, system
1588  // libraries are hopefully not as broken so that we don't need these
1589  // workarounds.
1591  OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1592  NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1593  New->setInvalidDecl();
1594  }
1595 }
1596 
1597 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1598 /// function declaration are well-formed according to C++
1599 /// [dcl.fct.default].
1601  unsigned NumParams = FD->getNumParams();
1602  unsigned ParamIdx = 0;
1603 
1604  // This checking doesn't make sense for explicit specializations; their
1605  // default arguments are determined by the declaration we're specializing,
1606  // not by FD.
1608  return;
1609  if (auto *FTD = FD->getDescribedFunctionTemplate())
1610  if (FTD->isMemberSpecialization())
1611  return;
1612 
1613  // Find first parameter with a default argument
1614  for (; ParamIdx < NumParams; ++ParamIdx) {
1615  ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1616  if (Param->hasDefaultArg())
1617  break;
1618  }
1619 
1620  // C++20 [dcl.fct.default]p4:
1621  // In a given function declaration, each parameter subsequent to a parameter
1622  // with a default argument shall have a default argument supplied in this or
1623  // a previous declaration, unless the parameter was expanded from a
1624  // parameter pack, or shall be a function parameter pack.
1625  for (; ParamIdx < NumParams; ++ParamIdx) {
1626  ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1627  if (!Param->hasDefaultArg() && !Param->isParameterPack() &&
1630  if (Param->isInvalidDecl())
1631  /* We already complained about this parameter. */;
1632  else if (Param->getIdentifier())
1633  Diag(Param->getLocation(),
1634  diag::err_param_default_argument_missing_name)
1635  << Param->getIdentifier();
1636  else
1637  Diag(Param->getLocation(),
1638  diag::err_param_default_argument_missing);
1639  }
1640  }
1641 }
1642 
1643 /// Check that the given type is a literal type. Issue a diagnostic if not,
1644 /// if Kind is Diagnose.
1645 /// \return \c true if a problem has been found (and optionally diagnosed).
1646 template <typename... Ts>
1648  SourceLocation Loc, QualType T, unsigned DiagID,
1649  Ts &&...DiagArgs) {
1650  if (T->isDependentType())
1651  return false;
1652 
1653  switch (Kind) {
1655  return SemaRef.RequireLiteralType(Loc, T, DiagID,
1656  std::forward<Ts>(DiagArgs)...);
1657 
1659  return !T->isLiteralType(SemaRef.Context);
1660  }
1661 
1662  llvm_unreachable("unknown CheckConstexprKind");
1663 }
1664 
1665 /// Determine whether a destructor cannot be constexpr due to
1667  const CXXDestructorDecl *DD,
1669  auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1670  const CXXRecordDecl *RD =
1671  T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1672  if (!RD || RD->hasConstexprDestructor())
1673  return true;
1674 
1676  SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1677  << static_cast<int>(DD->getConstexprKind()) << !FD
1678  << (FD ? FD->getDeclName() : DeclarationName()) << T;
1679  SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1680  << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1681  }
1682  return false;
1683  };
1684 
1685  const CXXRecordDecl *RD = DD->getParent();
1686  for (const CXXBaseSpecifier &B : RD->bases())
1687  if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1688  return false;
1689  for (const FieldDecl *FD : RD->fields())
1690  if (!Check(FD->getLocation(), FD->getType(), FD))
1691  return false;
1692  return true;
1693 }
1694 
1695 /// Check whether a function's parameter types are all literal types. If so,
1696 /// return true. If not, produce a suitable diagnostic and return false.
1697 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1698  const FunctionDecl *FD,
1700  unsigned ArgIndex = 0;
1701  const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1702  for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1703  e = FT->param_type_end();
1704  i != e; ++i, ++ArgIndex) {
1705  const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1706  SourceLocation ParamLoc = PD->getLocation();
1707  if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1708  diag::err_constexpr_non_literal_param, ArgIndex + 1,
1709  PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1710  FD->isConsteval()))
1711  return false;
1712  }
1713  return true;
1714 }
1715 
1716 /// Check whether a function's return type is a literal type. If so, return
1717 /// true. If not, produce a suitable diagnostic and return false.
1718 static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1720  if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1721  diag::err_constexpr_non_literal_return,
1722  FD->isConsteval()))
1723  return false;
1724  return true;
1725 }
1726 
1727 /// Get diagnostic %select index for tag kind for
1728 /// record diagnostic message.
1729 /// WARNING: Indexes apply to particular diagnostics only!
1730 ///
1731 /// \returns diagnostic %select index.
1733  switch (Tag) {
1734  case TTK_Struct: return 0;
1735  case TTK_Interface: return 1;
1736  case TTK_Class: return 2;
1737  default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1738  }
1739 }
1740 
1741 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1742  Stmt *Body,
1744 
1745 // Check whether a function declaration satisfies the requirements of a
1746 // constexpr function definition or a constexpr constructor definition. If so,
1747 // return true. If not, produce appropriate diagnostics (unless asked not to by
1748 // Kind) and return false.
1749 //
1750 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1753  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1754  if (MD && MD->isInstance()) {
1755  // C++11 [dcl.constexpr]p4:
1756  // The definition of a constexpr constructor shall satisfy the following
1757  // constraints:
1758  // - the class shall not have any virtual base classes;
1759  //
1760  // FIXME: This only applies to constructors and destructors, not arbitrary
1761  // member functions.
1762  const CXXRecordDecl *RD = MD->getParent();
1763  if (RD->getNumVBases()) {
1765  return false;
1766 
1767  Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1768  << isa<CXXConstructorDecl>(NewFD)
1770  for (const auto &I : RD->vbases())
1771  Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1772  << I.getSourceRange();
1773  return false;
1774  }
1775  }
1776 
1777  if (!isa<CXXConstructorDecl>(NewFD)) {
1778  // C++11 [dcl.constexpr]p3:
1779  // The definition of a constexpr function shall satisfy the following
1780  // constraints:
1781  // - it shall not be virtual; (removed in C++20)
1782  const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1783  if (Method && Method->isVirtual()) {
1784  if (getLangOpts().CPlusPlus20) {
1786  Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1787  } else {
1789  return false;
1790 
1791  Method = Method->getCanonicalDecl();
1792  Diag(Method->getLocation(), diag::err_constexpr_virtual);
1793 
1794  // If it's not obvious why this function is virtual, find an overridden
1795  // function which uses the 'virtual' keyword.
1796  const CXXMethodDecl *WrittenVirtual = Method;
1797  while (!WrittenVirtual->isVirtualAsWritten())
1798  WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1799  if (WrittenVirtual != Method)
1800  Diag(WrittenVirtual->getLocation(),
1801  diag::note_overridden_virtual_function);
1802  return false;
1803  }
1804  }
1805 
1806  // - its return type shall be a literal type;
1807  if (!CheckConstexprReturnType(*this, NewFD, Kind))
1808  return false;
1809  }
1810 
1811  if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1812  // A destructor can be constexpr only if the defaulted destructor could be;
1813  // we don't need to check the members and bases if we already know they all
1814  // have constexpr destructors.
1815  if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1817  return false;
1818  if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1819  return false;
1820  }
1821  }
1822 
1823  // - each of its parameter types shall be a literal type;
1824  if (!CheckConstexprParameterTypes(*this, NewFD, Kind))
1825  return false;
1826 
1827  Stmt *Body = NewFD->getBody();
1828  assert(Body &&
1829  "CheckConstexprFunctionDefinition called on function with no body");
1830  return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1831 }
1832 
1833 /// Check the given declaration statement is legal within a constexpr function
1834 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1835 ///
1836 /// \return true if the body is OK (maybe only as an extension), false if we
1837 /// have diagnosed a problem.
1838 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1839  DeclStmt *DS, SourceLocation &Cxx1yLoc,
1841  // C++11 [dcl.constexpr]p3 and p4:
1842  // The definition of a constexpr function(p3) or constructor(p4) [...] shall
1843  // contain only
1844  for (const auto *DclIt : DS->decls()) {
1845  switch (DclIt->getKind()) {
1846  case Decl::StaticAssert:
1847  case Decl::Using:
1848  case Decl::UsingShadow:
1849  case Decl::UsingDirective:
1850  case Decl::UnresolvedUsingTypename:
1851  case Decl::UnresolvedUsingValue:
1852  case Decl::UsingEnum:
1853  // - static_assert-declarations
1854  // - using-declarations,
1855  // - using-directives,
1856  // - using-enum-declaration
1857  continue;
1858 
1859  case Decl::Typedef:
1860  case Decl::TypeAlias: {
1861  // - typedef declarations and alias-declarations that do not define
1862  // classes or enumerations,
1863  const auto *TN = cast<TypedefNameDecl>(DclIt);
1864  if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1865  // Don't allow variably-modified types in constexpr functions.
1867  TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1868  SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1869  << TL.getSourceRange() << TL.getType()
1870  << isa<CXXConstructorDecl>(Dcl);
1871  }
1872  return false;
1873  }
1874  continue;
1875  }
1876 
1877  case Decl::Enum:
1878  case Decl::CXXRecord:
1879  // C++1y allows types to be defined, not just declared.
1880  if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1882  SemaRef.Diag(DS->getBeginLoc(),
1883  SemaRef.getLangOpts().CPlusPlus14
1884  ? diag::warn_cxx11_compat_constexpr_type_definition
1885  : diag::ext_constexpr_type_definition)
1886  << isa<CXXConstructorDecl>(Dcl);
1887  } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1888  return false;
1889  }
1890  }
1891  continue;
1892 
1893  case Decl::EnumConstant:
1894  case Decl::IndirectField:
1895  case Decl::ParmVar:
1896  // These can only appear with other declarations which are banned in
1897  // C++11 and permitted in C++1y, so ignore them.
1898  continue;
1899 
1900  case Decl::Var:
1901  case Decl::Decomposition: {
1902  // C++1y [dcl.constexpr]p3 allows anything except:
1903  // a definition of a variable of non-literal type or of static or
1904  // thread storage duration or [before C++2a] for which no
1905  // initialization is performed.
1906  const auto *VD = cast<VarDecl>(DclIt);
1907  if (VD->isThisDeclarationADefinition()) {
1908  if (VD->isStaticLocal()) {
1910  SemaRef.Diag(VD->getLocation(),
1911  SemaRef.getLangOpts().CPlusPlus2b
1912  ? diag::warn_cxx20_compat_constexpr_var
1913  : diag::ext_constexpr_static_var)
1914  << isa<CXXConstructorDecl>(Dcl)
1915  << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1916  } else if (!SemaRef.getLangOpts().CPlusPlus2b) {
1917  return false;
1918  }
1919  }
1920  if (SemaRef.LangOpts.CPlusPlus2b) {
1921  CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1922  diag::warn_cxx20_compat_constexpr_var,
1923  isa<CXXConstructorDecl>(Dcl),
1924  /*variable of non-literal type*/ 2);
1925  } else if (CheckLiteralType(
1926  SemaRef, Kind, VD->getLocation(), VD->getType(),
1927  diag::err_constexpr_local_var_non_literal_type,
1928  isa<CXXConstructorDecl>(Dcl))) {
1929  return false;
1930  }
1931  if (!VD->getType()->isDependentType() &&
1932  !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1934  SemaRef.Diag(
1935  VD->getLocation(),
1936  SemaRef.getLangOpts().CPlusPlus20
1937  ? diag::warn_cxx17_compat_constexpr_local_var_no_init
1938  : diag::ext_constexpr_local_var_no_init)
1939  << isa<CXXConstructorDecl>(Dcl);
1940  } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1941  return false;
1942  }
1943  continue;
1944  }
1945  }
1947  SemaRef.Diag(VD->getLocation(),
1948  SemaRef.getLangOpts().CPlusPlus14
1949  ? diag::warn_cxx11_compat_constexpr_local_var
1950  : diag::ext_constexpr_local_var)
1951  << isa<CXXConstructorDecl>(Dcl);
1952  } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1953  return false;
1954  }
1955  continue;
1956  }
1957 
1958  case Decl::NamespaceAlias:
1959  case Decl::Function:
1960  // These are disallowed in C++11 and permitted in C++1y. Allow them
1961  // everywhere as an extension.
1962  if (!Cxx1yLoc.isValid())
1963  Cxx1yLoc = DS->getBeginLoc();
1964  continue;
1965 
1966  default:
1968  SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1969  << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
1970  }
1971  return false;
1972  }
1973  }
1974 
1975  return true;
1976 }
1977 
1978 /// Check that the given field is initialized within a constexpr constructor.
1979 ///
1980 /// \param Dcl The constexpr constructor being checked.
1981 /// \param Field The field being checked. This may be a member of an anonymous
1982 /// struct or union nested within the class being checked.
1983 /// \param Inits All declarations, including anonymous struct/union members and
1984 /// indirect members, for which any initialization was provided.
1985 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach
1986 /// multiple notes for different members to the same error.
1987 /// \param Kind Whether we're diagnosing a constructor as written or determining
1988 /// whether the formal requirements are satisfied.
1989 /// \return \c false if we're checking for validity and the constructor does
1990 /// not satisfy the requirements on a constexpr constructor.
1992  const FunctionDecl *Dcl,
1993  FieldDecl *Field,
1994  llvm::SmallSet<Decl*, 16> &Inits,
1995  bool &Diagnosed,
1997  // In C++20 onwards, there's nothing to check for validity.
1999  SemaRef.getLangOpts().CPlusPlus20)
2000  return true;
2001 
2002  if (Field->isInvalidDecl())
2003  return true;
2004 
2005  if (Field->isUnnamedBitfield())
2006  return true;
2007 
2008  // Anonymous unions with no variant members and empty anonymous structs do not
2009  // need to be explicitly initialized. FIXME: Anonymous structs that contain no
2010  // indirect fields don't need initializing.
2011  if (Field->isAnonymousStructOrUnion() &&
2012  (Field->getType()->isUnionType()
2013  ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
2014  : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
2015  return true;
2016 
2017  if (!Inits.count(Field)) {
2019  if (!Diagnosed) {
2020  SemaRef.Diag(Dcl->getLocation(),
2021  SemaRef.getLangOpts().CPlusPlus20
2022  ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
2023  : diag::ext_constexpr_ctor_missing_init);
2024  Diagnosed = true;
2025  }
2026  SemaRef.Diag(Field->getLocation(),
2027  diag::note_constexpr_ctor_missing_init);
2028  } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2029  return false;
2030  }
2031  } else if (Field->isAnonymousStructOrUnion()) {
2032  const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
2033  for (auto *I : RD->fields())
2034  // If an anonymous union contains an anonymous struct of which any member
2035  // is initialized, all members must be initialized.
2036  if (!RD->isUnion() || Inits.count(I))
2037  if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2038  Kind))
2039  return false;
2040  }
2041  return true;
2042 }
2043 
2044 /// Check the provided statement is allowed in a constexpr function
2045 /// definition.
2046 static bool
2048  SmallVectorImpl<SourceLocation> &ReturnStmts,
2049  SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2050  SourceLocation &Cxx2bLoc,
2052  // - its function-body shall be [...] a compound-statement that contains only
2053  switch (S->getStmtClass()) {
2054  case Stmt::NullStmtClass:
2055  // - null statements,
2056  return true;
2057 
2058  case Stmt::DeclStmtClass:
2059  // - static_assert-declarations
2060  // - using-declarations,
2061  // - using-directives,
2062  // - typedef declarations and alias-declarations that do not define
2063  // classes or enumerations,
2064  if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
2065  return false;
2066  return true;
2067 
2068  case Stmt::ReturnStmtClass:
2069  // - and exactly one return statement;
2070  if (isa<CXXConstructorDecl>(Dcl)) {
2071  // C++1y allows return statements in constexpr constructors.
2072  if (!Cxx1yLoc.isValid())
2073  Cxx1yLoc = S->getBeginLoc();
2074  return true;
2075  }
2076 
2077  ReturnStmts.push_back(S->getBeginLoc());
2078  return true;
2079 
2080  case Stmt::AttributedStmtClass:
2081  // Attributes on a statement don't affect its formal kind and hence don't
2082  // affect its validity in a constexpr function.
2084  SemaRef, Dcl, cast<AttributedStmt>(S)->getSubStmt(), ReturnStmts,
2085  Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);
2086 
2087  case Stmt::CompoundStmtClass: {
2088  // C++1y allows compound-statements.
2089  if (!Cxx1yLoc.isValid())
2090  Cxx1yLoc = S->getBeginLoc();
2091 
2092  CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2093  for (auto *BodyIt : CompStmt->body()) {
2094  if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2095  Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2096  return false;
2097  }
2098  return true;
2099  }
2100 
2101  case Stmt::IfStmtClass: {
2102  // C++1y allows if-statements.
2103  if (!Cxx1yLoc.isValid())
2104  Cxx1yLoc = S->getBeginLoc();
2105 
2106  IfStmt *If = cast<IfStmt>(S);
2107  if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2108  Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2109  return false;
2110  if (If->getElse() &&
2111  !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2112  Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2113  return false;
2114  return true;
2115  }
2116 
2117  case Stmt::WhileStmtClass:
2118  case Stmt::DoStmtClass:
2119  case Stmt::ForStmtClass:
2120  case Stmt::CXXForRangeStmtClass:
2121  case Stmt::ContinueStmtClass:
2122  // C++1y allows all of these. We don't allow them as extensions in C++11,
2123  // because they don't make sense without variable mutation.
2124  if (!SemaRef.getLangOpts().CPlusPlus14)
2125  break;
2126  if (!Cxx1yLoc.isValid())
2127  Cxx1yLoc = S->getBeginLoc();
2128  for (Stmt *SubStmt : S->children()) {
2129  if (SubStmt &&
2130  !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2131  Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2132  return false;
2133  }
2134  return true;
2135 
2136  case Stmt::SwitchStmtClass:
2137  case Stmt::CaseStmtClass:
2138  case Stmt::DefaultStmtClass:
2139  case Stmt::BreakStmtClass:
2140  // C++1y allows switch-statements, and since they don't need variable
2141  // mutation, we can reasonably allow them in C++11 as an extension.
2142  if (!Cxx1yLoc.isValid())
2143  Cxx1yLoc = S->getBeginLoc();
2144  for (Stmt *SubStmt : S->children()) {
2145  if (SubStmt &&
2146  !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2147  Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2148  return false;
2149  }
2150  return true;
2151 
2152  case Stmt::LabelStmtClass:
2153  case Stmt::GotoStmtClass:
2154  if (Cxx2bLoc.isInvalid())
2155  Cxx2bLoc = S->getBeginLoc();
2156  for (Stmt *SubStmt : S->children()) {
2157  if (SubStmt &&
2158  !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2159  Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2160  return false;
2161  }
2162  return true;
2163 
2164  case Stmt::GCCAsmStmtClass:
2165  case Stmt::MSAsmStmtClass:
2166  // C++2a allows inline assembly statements.
2167  case Stmt::CXXTryStmtClass:
2168  if (Cxx2aLoc.isInvalid())
2169  Cxx2aLoc = S->getBeginLoc();
2170  for (Stmt *SubStmt : S->children()) {
2171  if (SubStmt &&
2172  !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2173  Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2174  return false;
2175  }
2176  return true;
2177 
2178  case Stmt::CXXCatchStmtClass:
2179  // Do not bother checking the language mode (already covered by the
2180  // try block check).
2182  SemaRef, Dcl, cast<CXXCatchStmt>(S)->getHandlerBlock(), ReturnStmts,
2183  Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2184  return false;
2185  return true;
2186 
2187  default:
2188  if (!isa<Expr>(S))
2189  break;
2190 
2191  // C++1y allows expression-statements.
2192  if (!Cxx1yLoc.isValid())
2193  Cxx1yLoc = S->getBeginLoc();
2194  return true;
2195  }
2196 
2198  SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2199  << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2200  }
2201  return false;
2202 }
2203 
2204 /// Check the body for the given constexpr function declaration only contains
2205 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2206 ///
2207 /// \return true if the body is OK, false if we have found or diagnosed a
2208 /// problem.
2209 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2210  Stmt *Body,
2212  SmallVector<SourceLocation, 4> ReturnStmts;
2213 
2214  if (isa<CXXTryStmt>(Body)) {
2215  // C++11 [dcl.constexpr]p3:
2216  // The definition of a constexpr function shall satisfy the following
2217  // constraints: [...]
2218  // - its function-body shall be = delete, = default, or a
2219  // compound-statement
2220  //
2221  // C++11 [dcl.constexpr]p4:
2222  // In the definition of a constexpr constructor, [...]
2223  // - its function-body shall not be a function-try-block;
2224  //
2225  // This restriction is lifted in C++2a, as long as inner statements also
2226  // apply the general constexpr rules.
2227  switch (Kind) {
2229  if (!SemaRef.getLangOpts().CPlusPlus20)
2230  return false;
2231  break;
2232 
2234  SemaRef.Diag(Body->getBeginLoc(),
2235  !SemaRef.getLangOpts().CPlusPlus20
2236  ? diag::ext_constexpr_function_try_block_cxx20
2237  : diag::warn_cxx17_compat_constexpr_function_try_block)
2238  << isa<CXXConstructorDecl>(Dcl);
2239  break;
2240  }
2241  }
2242 
2243  // - its function-body shall be [...] a compound-statement that contains only
2244  // [... list of cases ...]
2245  //
2246  // Note that walking the children here is enough to properly check for
2247  // CompoundStmt and CXXTryStmt body.
2248  SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc;
2249  for (Stmt *SubStmt : Body->children()) {
2250  if (SubStmt &&
2251  !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2252  Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2253  return false;
2254  }
2255 
2257  // If this is only valid as an extension, report that we don't satisfy the
2258  // constraints of the current language.
2259  if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus2b) ||
2260  (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2261  (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2262  return false;
2263  } else if (Cxx2bLoc.isValid()) {
2264  SemaRef.Diag(Cxx2bLoc,
2265  SemaRef.getLangOpts().CPlusPlus2b
2266  ? diag::warn_cxx20_compat_constexpr_body_invalid_stmt
2267  : diag::ext_constexpr_body_invalid_stmt_cxx2b)
2268  << isa<CXXConstructorDecl>(Dcl);
2269  } else if (Cxx2aLoc.isValid()) {
2270  SemaRef.Diag(Cxx2aLoc,
2271  SemaRef.getLangOpts().CPlusPlus20
2272  ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2273  : diag::ext_constexpr_body_invalid_stmt_cxx20)
2274  << isa<CXXConstructorDecl>(Dcl);
2275  } else if (Cxx1yLoc.isValid()) {
2276  SemaRef.Diag(Cxx1yLoc,
2277  SemaRef.getLangOpts().CPlusPlus14
2278  ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2279  : diag::ext_constexpr_body_invalid_stmt)
2280  << isa<CXXConstructorDecl>(Dcl);
2281  }
2282 
2283  if (const CXXConstructorDecl *Constructor
2284  = dyn_cast<CXXConstructorDecl>(Dcl)) {
2285  const CXXRecordDecl *RD = Constructor->getParent();
2286  // DR1359:
2287  // - every non-variant non-static data member and base class sub-object
2288  // shall be initialized;
2289  // DR1460:
2290  // - if the class is a union having variant members, exactly one of them
2291  // shall be initialized;
2292  if (RD->isUnion()) {
2293  if (Constructor->getNumCtorInitializers() == 0 &&
2294  RD->hasVariantMembers()) {
2296  SemaRef.Diag(
2297  Dcl->getLocation(),
2298  SemaRef.getLangOpts().CPlusPlus20
2299  ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2300  : diag::ext_constexpr_union_ctor_no_init);
2301  } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2302  return false;
2303  }
2304  }
2305  } else if (!Constructor->isDependentContext() &&
2306  !Constructor->isDelegatingConstructor()) {
2307  assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2308 
2309  // Skip detailed checking if we have enough initializers, and we would
2310  // allow at most one initializer per member.
2311  bool AnyAnonStructUnionMembers = false;
2312  unsigned Fields = 0;
2314  E = RD->field_end(); I != E; ++I, ++Fields) {
2315  if (I->isAnonymousStructOrUnion()) {
2316  AnyAnonStructUnionMembers = true;
2317  break;
2318  }
2319  }
2320  // DR1460:
2321  // - if the class is a union-like class, but is not a union, for each of
2322  // its anonymous union members having variant members, exactly one of
2323  // them shall be initialized;
2324  if (AnyAnonStructUnionMembers ||
2325  Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2326  // Check initialization of non-static data members. Base classes are
2327  // always initialized so do not need to be checked. Dependent bases
2328  // might not have initializers in the member initializer list.
2329  llvm::SmallSet<Decl*, 16> Inits;
2330  for (const auto *I: Constructor->inits()) {
2331  if (FieldDecl *FD = I->getMember())
2332  Inits.insert(FD);
2333  else if (IndirectFieldDecl *ID = I->getIndirectMember())
2334  Inits.insert(ID->chain_begin(), ID->chain_end());
2335  }
2336 
2337  bool Diagnosed = false;
2338  for (auto *I : RD->fields())
2339  if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2340  Kind))
2341  return false;
2342  }
2343  }
2344  } else {
2345  if (ReturnStmts.empty()) {
2346  // C++1y doesn't require constexpr functions to contain a 'return'
2347  // statement. We still do, unless the return type might be void, because
2348  // otherwise if there's no return statement, the function cannot
2349  // be used in a core constant expression.
2350  bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
2351  (Dcl->getReturnType()->isVoidType() ||
2352  Dcl->getReturnType()->isDependentType());
2353  switch (Kind) {
2355  SemaRef.Diag(Dcl->getLocation(),
2356  OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2357  : diag::err_constexpr_body_no_return)
2358  << Dcl->isConsteval();
2359  if (!OK)
2360  return false;
2361  break;
2362 
2364  // The formal requirements don't include this rule in C++14, even
2365  // though the "must be able to produce a constant expression" rules
2366  // still imply it in some cases.
2367  if (!SemaRef.getLangOpts().CPlusPlus14)
2368  return false;
2369  break;
2370  }
2371  } else if (ReturnStmts.size() > 1) {
2372  switch (Kind) {
2374  SemaRef.Diag(
2375  ReturnStmts.back(),
2376  SemaRef.getLangOpts().CPlusPlus14
2377  ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2378  : diag::ext_constexpr_body_multiple_return);
2379  for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2380  SemaRef.Diag(ReturnStmts[I],
2381  diag::note_constexpr_body_previous_return);
2382  break;
2383 
2385  if (!SemaRef.getLangOpts().CPlusPlus14)
2386  return false;
2387  break;
2388  }
2389  }
2390  }
2391 
2392  // C++11 [dcl.constexpr]p5:
2393  // if no function argument values exist such that the function invocation
2394  // substitution would produce a constant expression, the program is
2395  // ill-formed; no diagnostic required.
2396  // C++11 [dcl.constexpr]p3:
2397  // - every constructor call and implicit conversion used in initializing the
2398  // return value shall be one of those allowed in a constant expression.
2399  // C++11 [dcl.constexpr]p4:
2400  // - every constructor involved in initializing non-static data members and
2401  // base class sub-objects shall be a constexpr constructor.
2402  //
2403  // Note that this rule is distinct from the "requirements for a constexpr
2404  // function", so is not checked in CheckValid mode.
2408  SemaRef.Diag(Dcl->getLocation(),
2409  diag::ext_constexpr_function_never_constant_expr)
2410  << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2411  for (size_t I = 0, N = Diags.size(); I != N; ++I)
2412  SemaRef.Diag(Diags[I].first, Diags[I].second);
2413  // Don't return false here: we allow this for compatibility in
2414  // system headers.
2415  }
2416 
2417  return true;
2418 }
2419 
2420 /// Get the class that is directly named by the current context. This is the
2421 /// class for which an unqualified-id in this scope could name a constructor
2422 /// or destructor.
2423 ///
2424 /// If the scope specifier denotes a class, this will be that class.
2425 /// If the scope specifier is empty, this will be the class whose
2426 /// member-specification we are currently within. Otherwise, there
2427 /// is no such class.
2429  assert(getLangOpts().CPlusPlus && "No class names in C!");
2430 
2431  if (SS && SS->isInvalid())
2432  return nullptr;
2433 
2434  if (SS && SS->isNotEmpty()) {
2435  DeclContext *DC = computeDeclContext(*SS, true);
2436  return dyn_cast_or_null<CXXRecordDecl>(DC);
2437  }
2438 
2439  return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2440 }
2441 
2442 /// isCurrentClassName - Determine whether the identifier II is the
2443 /// name of the class type currently being defined. In the case of
2444 /// nested classes, this will only return true if II is the name of
2445 /// the innermost class.
2447  const CXXScopeSpec *SS) {
2448  CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2449  return CurDecl && &II == CurDecl->getIdentifier();
2450 }
2451 
2452 /// Determine whether the identifier II is a typo for the name of
2453 /// the class type currently being defined. If so, update it to the identifier
2454 /// that should have been used.
2456  assert(getLangOpts().CPlusPlus && "No class names in C!");
2457 
2458  if (!getLangOpts().SpellChecking)
2459  return false;
2460 
2461  CXXRecordDecl *CurDecl;
2462  if (SS && SS->isSet() && !SS->isInvalid()) {
2463  DeclContext *DC = computeDeclContext(*SS, true);
2464  CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2465  } else
2466  CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2467 
2468  if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2469  3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2470  < II->getLength()) {
2471  II = CurDecl->getIdentifier();
2472  return true;
2473  }
2474 
2475  return false;
2476 }
2477 
2478 /// Determine whether the given class is a base class of the given
2479 /// class, including looking at dependent bases.
2480 static bool findCircularInheritance(const CXXRecordDecl *Class,
2481  const CXXRecordDecl *Current) {
2483 
2484  Class = Class->getCanonicalDecl();
2485  while (true) {
2486  for (const auto &I : Current->bases()) {
2487  CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2488  if (!Base)
2489  continue;
2490 
2491  Base = Base->getDefinition();
2492  if (!Base)
2493  continue;
2494 
2495  if (Base->getCanonicalDecl() == Class)
2496  return true;
2497 
2498  Queue.push_back(Base);
2499  }
2500 
2501  if (Queue.empty())
2502  return false;
2503 
2504  Current = Queue.pop_back_val();
2505  }
2506 
2507  return false;
2508 }
2509 
2510 /// Check the validity of a C++ base class specifier.
2511 ///
2512 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2513 /// and returns NULL otherwise.
2516  SourceRange SpecifierRange,
2517  bool Virtual, AccessSpecifier Access,
2518  TypeSourceInfo *TInfo,
2519  SourceLocation EllipsisLoc) {
2520  // In HLSL, unspecified class access is public rather than private.
2521  if (getLangOpts().HLSL && Class->getTagKind() == TTK_Class &&
2522  Access == AS_none)
2523  Access = AS_public;
2524 
2525  QualType BaseType = TInfo->getType();
2526  if (BaseType->containsErrors()) {
2527  // Already emitted a diagnostic when parsing the error type.
2528  return nullptr;
2529  }
2530  // C++ [class.union]p1:
2531  // A union shall not have base classes.
2532  if (Class->isUnion()) {
2533  Diag(Class->getLocation(), diag::err_base_clause_on_union)
2534  << SpecifierRange;
2535  return nullptr;
2536  }
2537 
2538  if (EllipsisLoc.isValid() &&
2540  Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2541  << TInfo->getTypeLoc().getSourceRange();
2542  EllipsisLoc = SourceLocation();
2543  }
2544 
2545  SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2546 
2547  if (BaseType->isDependentType()) {
2548  // Make sure that we don't have circular inheritance among our dependent
2549  // bases. For non-dependent bases, the check for completeness below handles
2550  // this.
2551  if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2552  if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2553  ((BaseDecl = BaseDecl->getDefinition()) &&
2554  findCircularInheritance(Class, BaseDecl))) {
2555  Diag(BaseLoc, diag::err_circular_inheritance)
2556  << BaseType << Context.getTypeDeclType(Class);
2557 
2558  if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2559  Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2560  << BaseType;
2561 
2562  return nullptr;
2563  }
2564  }
2565 
2566  // Make sure that we don't make an ill-formed AST where the type of the
2567  // Class is non-dependent and its attached base class specifier is an
2568  // dependent type, which violates invariants in many clang code paths (e.g.
2569  // constexpr evaluator). If this case happens (in errory-recovery mode), we
2570  // explicitly mark the Class decl invalid. The diagnostic was already
2571  // emitted.
2572  if (!Class->getTypeForDecl()->isDependentType())
2573  Class->setInvalidDecl();
2574  return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2575  Class->getTagKind() == TTK_Class,
2576  Access, TInfo, EllipsisLoc);
2577  }
2578 
2579  // Base specifiers must be record types.
2580  if (!BaseType->isRecordType()) {
2581  Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2582  return nullptr;
2583  }
2584 
2585  // C++ [class.union]p1:
2586  // A union shall not be used as a base class.
2587  if (BaseType->isUnionType()) {
2588  Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2589  return nullptr;
2590  }
2591 
2592  // For the MS ABI, propagate DLL attributes to base class templates.
2594  if (Attr *ClassAttr = getDLLAttr(Class)) {
2595  if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2596  BaseType->getAsCXXRecordDecl())) {
2597  propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2598  BaseLoc);
2599  }
2600  }
2601  }
2602 
2603  // C++ [class.derived]p2:
2604  // The class-name in a base-specifier shall not be an incompletely
2605  // defined class.
2606  if (RequireCompleteType(BaseLoc, BaseType,
2607  diag::err_incomplete_base_class, SpecifierRange)) {
2608  Class->setInvalidDecl();
2609  return nullptr;
2610  }
2611 
2612  // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2613  RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl();
2614  assert(BaseDecl && "Record type has no declaration");
2615  BaseDecl = BaseDecl->getDefinition();
2616  assert(BaseDecl && "Base type is not incomplete, but has no definition");
2617  CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2618  assert(CXXBaseDecl && "Base type is not a C++ type");
2619 
2620  // Microsoft docs say:
2621  // "If a base-class has a code_seg attribute, derived classes must have the
2622  // same attribute."
2623  const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2624  const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2625  if ((DerivedCSA || BaseCSA) &&
2626  (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2627  Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2628  Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2629  << CXXBaseDecl;
2630  return nullptr;
2631  }
2632 
2633  // A class which contains a flexible array member is not suitable for use as a
2634  // base class:
2635  // - If the layout determines that a base comes before another base,
2636  // the flexible array member would index into the subsequent base.
2637  // - If the layout determines that base comes before the derived class,
2638  // the flexible array member would index into the derived class.
2639  if (CXXBaseDecl->hasFlexibleArrayMember()) {
2640  Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2641  << CXXBaseDecl->getDeclName();
2642  return nullptr;
2643  }
2644 
2645  // C++ [class]p3:
2646  // If a class is marked final and it appears as a base-type-specifier in
2647  // base-clause, the program is ill-formed.
2648  if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2649  Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2650  << CXXBaseDecl->getDeclName()
2651  << FA->isSpelledAsSealed();
2652  Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2653  << CXXBaseDecl->getDeclName() << FA->getRange();
2654  return nullptr;
2655  }
2656 
2657  if (BaseDecl->isInvalidDecl())
2658  Class->setInvalidDecl();
2659 
2660  // Create the base specifier.
2661  return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2662  Class->getTagKind() == TTK_Class,
2663  Access, TInfo, EllipsisLoc);
2664 }
2665 
2666 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2667 /// one entry in the base class list of a class specifier, for
2668 /// example:
2669 /// class foo : public bar, virtual private baz {
2670 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2672  const ParsedAttributesView &Attributes,
2673  bool Virtual, AccessSpecifier Access,
2674  ParsedType basetype, SourceLocation BaseLoc,
2675  SourceLocation EllipsisLoc) {
2676  if (!classdecl)
2677  return true;
2678 
2679  AdjustDeclIfTemplate(classdecl);
2680  CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2681  if (!Class)
2682  return true;
2683 
2684  // We haven't yet attached the base specifiers.
2685  Class->setIsParsingBaseSpecifiers();
2686 
2687  // We do not support any C++11 attributes on base-specifiers yet.
2688  // Diagnose any attributes we see.
2689  for (const ParsedAttr &AL : Attributes) {
2690  if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2691  continue;
2692  Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2693  ? (unsigned)diag::warn_unknown_attribute_ignored
2694  : (unsigned)diag::err_base_specifier_attribute)
2695  << AL << AL.getRange();
2696  }
2697 
2698  TypeSourceInfo *TInfo = nullptr;
2699  GetTypeFromParser(basetype, &TInfo);
2700 
2701  if (EllipsisLoc.isInvalid() &&
2702  DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2703  UPPC_BaseType))
2704  return true;
2705 
2706  if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2707  Virtual, Access, TInfo,
2708  EllipsisLoc))
2709  return BaseSpec;
2710  else
2711  Class->setInvalidDecl();
2712 
2713  return true;
2714 }
2715 
2716 /// Use small set to collect indirect bases. As this is only used
2717 /// locally, there's no need to abstract the small size parameter.
2719 
2720 /// Recursively add the bases of Type. Don't add Type itself.
2721 static void
2723  const QualType &Type)
2724 {
2725  // Even though the incoming type is a base, it might not be
2726  // a class -- it could be a template parm, for instance.
2727  if (auto Rec = Type->getAs<RecordType>()) {
2728  auto Decl = Rec->getAsCXXRecordDecl();
2729 
2730  // Iterate over its bases.
2731  for (const auto &BaseSpec : Decl->bases()) {
2732  QualType Base = Context.getCanonicalType(BaseSpec.getType())
2733  .getUnqualifiedType();
2734  if (Set.insert(Base).second)
2735  // If we've not already seen it, recurse.
2737  }
2738  }
2739 }
2740 
2741 /// Performs the actual work of attaching the given base class
2742 /// specifiers to a C++ class.
2745  if (Bases.empty())
2746  return false;
2747 
2748  // Used to keep track of which base types we have already seen, so
2749  // that we can properly diagnose redundant direct base types. Note
2750  // that the key is always the unqualified canonical type of the base
2751  // class.
2752  std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2753 
2754  // Used to track indirect bases so we can see if a direct base is
2755  // ambiguous.
2756  IndirectBaseSet IndirectBaseTypes;
2757 
2758  // Copy non-redundant base specifiers into permanent storage.
2759  unsigned NumGoodBases = 0;
2760  bool Invalid = false;
2761  for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2762  QualType NewBaseType
2763  = Context.getCanonicalType(Bases[idx]->getType());
2764  NewBaseType = NewBaseType.getLocalUnqualifiedType();
2765 
2766  CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2767  if (KnownBase) {
2768  // C++ [class.mi]p3:
2769  // A class shall not be specified as a direct base class of a
2770  // derived class more than once.
2771  Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2772  << KnownBase->getType() << Bases[idx]->getSourceRange();
2773 
2774  // Delete the duplicate base class specifier; we're going to
2775  // overwrite its pointer later.
2776  Context.Deallocate(Bases[idx]);
2777 
2778  Invalid = true;
2779  } else {
2780  // Okay, add this new base class.
2781  KnownBase = Bases[idx];
2782  Bases[NumGoodBases++] = Bases[idx];
2783 
2784  if (NewBaseType->isDependentType())
2785  continue;
2786  // Note this base's direct & indirect bases, if there could be ambiguity.
2787  if (Bases.size() > 1)
2788  NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2789 
2790  if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2791  const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2792  if (Class->isInterface() &&
2793  (!RD->isInterfaceLike() ||
2794  KnownBase->getAccessSpecifier() != AS_public)) {
2795  // The Microsoft extension __interface does not permit bases that
2796  // are not themselves public interfaces.
2797  Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2798  << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2799  << RD->getSourceRange();
2800  Invalid = true;
2801  }
2802  if (RD->hasAttr<WeakAttr>())
2803  Class->addAttr(WeakAttr::CreateImplicit(Context));
2804  }
2805  }
2806  }
2807 
2808  // Attach the remaining base class specifiers to the derived class.
2809  Class->setBases(Bases.data(), NumGoodBases);
2810 
2811  // Check that the only base classes that are duplicate are virtual.
2812  for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2813  // Check whether this direct base is inaccessible due to ambiguity.
2814  QualType BaseType = Bases[idx]->getType();
2815 
2816  // Skip all dependent types in templates being used as base specifiers.
2817  // Checks below assume that the base specifier is a CXXRecord.
2818  if (BaseType->isDependentType())
2819  continue;
2820 
2821  CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2822  .getUnqualifiedType();
2823 
2824  if (IndirectBaseTypes.count(CanonicalBase)) {
2825  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2826  /*DetectVirtual=*/true);
2827  bool found
2828  = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2829  assert(found);
2830  (void)found;
2831 
2832  if (Paths.isAmbiguous(CanonicalBase))
2833  Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2834  << BaseType << getAmbiguousPathsDisplayString(Paths)
2835  << Bases[idx]->getSourceRange();
2836  else
2837  assert(Bases[idx]->isVirtual());
2838  }
2839 
2840  // Delete the base class specifier, since its data has been copied
2841  // into the CXXRecordDecl.
2842  Context.Deallocate(Bases[idx]);
2843  }
2844 
2845  return Invalid;
2846 }
2847 
2848 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2849 /// class, after checking whether there are any duplicate base
2850 /// classes.
2853  if (!ClassDecl || Bases.empty())
2854  return;
2855 
2856  AdjustDeclIfTemplate(ClassDecl);
2857  AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2858 }
2859 
2860 /// Determine whether the type \p Derived is a C++ class that is
2861 /// derived from the type \p Base.
2863  if (!getLangOpts().CPlusPlus)
2864  return false;
2865 
2866  CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2867  if (!DerivedRD)
2868  return false;
2869 
2870  CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2871  if (!BaseRD)
2872  return false;
2873 
2874  // If either the base or the derived type is invalid, don't try to
2875  // check whether one is derived from the other.
2876  if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2877  return false;
2878 
2879  // FIXME: In a modules build, do we need the entire path to be visible for us
2880  // to be able to use the inheritance relationship?
2881  if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2882  return false;
2883 
2884  return DerivedRD->isDerivedFrom(BaseRD);
2885 }
2886 
2887 /// Determine whether the type \p Derived is a C++ class that is
2888 /// derived from the type \p Base.
2890  CXXBasePaths &Paths) {
2891  if (!getLangOpts().CPlusPlus)
2892  return false;
2893 
2894  CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2895  if (!DerivedRD)
2896  return false;
2897 
2898  CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2899  if (!BaseRD)
2900  return false;
2901 
2902  if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2903  return false;
2904 
2905  return DerivedRD->isDerivedFrom(BaseRD, Paths);
2906 }
2907 
2908 static void BuildBasePathArray(const CXXBasePath &Path,
2909  CXXCastPath &BasePathArray) {
2910  // We first go backward and check if we have a virtual base.
2911  // FIXME: It would be better if CXXBasePath had the base specifier for
2912  // the nearest virtual base.
2913  unsigned Start = 0;
2914  for (unsigned I = Path.size(); I != 0; --I) {
2915  if (Path[I - 1].Base->isVirtual()) {
2916  Start = I - 1;
2917  break;
2918  }
2919  }
2920 
2921  // Now add all bases.
2922  for (unsigned I = Start, E = Path.size(); I != E; ++I)
2923  BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2924 }
2925 
2926 
2928  CXXCastPath &BasePathArray) {
2929  assert(BasePathArray.empty() && "Base path array must be empty!");
2930  assert(Paths.isRecordingPaths() && "Must record paths!");
2931  return ::BuildBasePathArray(Paths.front(), BasePathArray);
2932 }
2933 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2934 /// conversion (where Derived and Base are class types) is
2935 /// well-formed, meaning that the conversion is unambiguous (and
2936 /// that all of the base classes are accessible). Returns true
2937 /// and emits a diagnostic if the code is ill-formed, returns false
2938 /// otherwise. Loc is the location where this routine should point to
2939 /// if there is an error, and Range is the source range to highlight
2940 /// if there is an error.
2941 ///
2942 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
2943 /// diagnostic for the respective type of error will be suppressed, but the
2944 /// check for ill-formed code will still be performed.
2945 bool
2947  unsigned InaccessibleBaseID,
2948  unsigned AmbiguousBaseConvID,
2949  SourceLocation Loc, SourceRange Range,
2950  DeclarationName Name,
2951  CXXCastPath *BasePath,
2952  bool IgnoreAccess) {
2953  // First, determine whether the path from Derived to Base is
2954  // ambiguous. This is slightly more expensive than checking whether
2955  // the Derived to Base conversion exists, because here we need to
2956  // explore multiple paths to determine if there is an ambiguity.
2957  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2958  /*DetectVirtual=*/false);
2959  bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2960  if (!DerivationOkay)
2961  return true;
2962 
2963  const CXXBasePath *Path = nullptr;
2964  if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2965  Path = &Paths.front();
2966 
2967  // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2968  // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2969  // user to access such bases.
2970  if (!Path && getLangOpts().MSVCCompat) {
2971  for (const CXXBasePath &PossiblePath : Paths) {
2972  if (PossiblePath.size() == 1) {
2973  Path = &PossiblePath;
2974  if (AmbiguousBaseConvID)
2975  Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2976  << Base << Derived << Range;
2977  break;
2978  }
2979  }
2980  }
2981 
2982  if (Path) {
2983  if (!IgnoreAccess) {
2984  // Check that the base class can be accessed.
2985  switch (
2986  CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2987  case AR_inaccessible:
2988  return true;
2989  case AR_accessible:
2990  case AR_dependent:
2991  case AR_delayed:
2992  break;
2993  }
2994  }
2995 
2996  // Build a base path if necessary.
2997  if (BasePath)
2998  ::BuildBasePathArray(*Path, *BasePath);
2999  return false;
3000  }
3001 
3002  if (AmbiguousBaseConvID) {
3003  // We know that the derived-to-base conversion is ambiguous, and
3004  // we're going to produce a diagnostic. Perform the derived-to-base
3005  // search just one more time to compute all of the possible paths so
3006  // that we can print them out. This is more expensive than any of
3007  // the previous derived-to-base checks we've done, but at this point
3008  // performance isn't as much of an issue.
3009  Paths.clear();
3010  Paths.setRecordingPaths(true);
3011  bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3012  assert(StillOkay && "Can only be used with a derived-to-base conversion");
3013  (void)StillOkay;
3014 
3015  // Build up a textual representation of the ambiguous paths, e.g.,
3016  // D -> B -> A, that will be used to illustrate the ambiguous
3017  // conversions in the diagnostic. We only print one of the paths
3018  // to each base class subobject.
3019  std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3020 
3021  Diag(Loc, AmbiguousBaseConvID)
3022  << Derived << Base << PathDisplayStr << Range << Name;
3023  }
3024  return true;
3025 }
3026 
3027 bool
3029  SourceLocation Loc, SourceRange Range,
3030  CXXCastPath *BasePath,
3031  bool IgnoreAccess) {
3033  Derived, Base, diag::err_upcast_to_inaccessible_base,
3034  diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
3035  BasePath, IgnoreAccess);
3036 }
3037 
3038 
3039 /// Builds a string representing ambiguous paths from a
3040 /// specific derived class to different subobjects of the same base
3041 /// class.
3042 ///
3043 /// This function builds a string that can be used in error messages
3044 /// to show the different paths that one can take through the
3045 /// inheritance hierarchy to go from the derived class to different
3046 /// subobjects of a base class. The result looks something like this:
3047 /// @code
3048 /// struct D -> struct B -> struct A
3049 /// struct D -> struct C -> struct A
3050 /// @endcode
3052  std::string PathDisplayStr;
3053  std::set<unsigned> DisplayedPaths;
3054  for (CXXBasePaths::paths_iterator Path = Paths.begin();
3055  Path != Paths.end(); ++Path) {
3056  if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
3057  // We haven't displayed a path to this particular base
3058  // class subobject yet.
3059  PathDisplayStr += "\n ";
3060  PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
3061  for (CXXBasePath::const_iterator Element = Path->begin();
3062  Element != Path->end(); ++Element)
3063  PathDisplayStr += " -> " + Element->Base->getType().getAsString();
3064  }
3065  }
3066 
3067  return PathDisplayStr;
3068 }
3069 
3070 //===----------------------------------------------------------------------===//
3071 // C++ class member Handling
3072 //===----------------------------------------------------------------------===//
3073 
3074 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
3076  SourceLocation ColonLoc,
3077  const ParsedAttributesView &Attrs) {
3078  assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
3080  ASLoc, ColonLoc);
3081  CurContext->addHiddenDecl(ASDecl);
3082  return ProcessAccessDeclAttributeList(ASDecl, Attrs);
3083 }
3084 
3085 /// CheckOverrideControl - Check C++11 override control semantics.
3087  if (D->isInvalidDecl())
3088  return;
3089 
3090  // We only care about "override" and "final" declarations.
3091  if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3092  return;
3093 
3094  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3095 
3096  // We can't check dependent instance methods.
3097  if (MD && MD->isInstance() &&
3098  (MD->getParent()->hasAnyDependentBases() ||
3099  MD->getType()->isDependentType()))
3100  return;
3101 
3102  if (MD && !MD->isVirtual()) {
3103  // If we have a non-virtual method, check if it hides a virtual method.
3104  // (In that case, it's most likely the method has the wrong type.)
3105  SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3106  FindHiddenVirtualMethods(MD, OverloadedMethods);
3107 
3108  if (!OverloadedMethods.empty()) {
3109  if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3110  Diag(OA->getLocation(),
3111  diag::override_keyword_hides_virtual_member_function)
3112  << "override" << (OverloadedMethods.size() > 1);
3113  } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3114  Diag(FA->getLocation(),
3115  diag::override_keyword_hides_virtual_member_function)
3116  << (FA->isSpelledAsSealed() ? "sealed" : "final")
3117  << (OverloadedMethods.size() > 1);
3118  }
3119  NoteHiddenVirtualMethods(MD, OverloadedMethods);
3120  MD->setInvalidDecl();
3121  return;
3122  }
3123  // Fall through into the general case diagnostic.
3124  // FIXME: We might want to attempt typo correction here.
3125  }
3126 
3127  if (!MD || !MD->isVirtual()) {
3128  if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3129  Diag(OA->getLocation(),
3130  diag::override_keyword_only_allowed_on_virtual_member_functions)
3131  << "override" << FixItHint::CreateRemoval(OA->getLocation());
3132  D->dropAttr<OverrideAttr>();
3133  }
3134  if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3135  Diag(FA->getLocation(),
3136  diag::override_keyword_only_allowed_on_virtual_member_functions)
3137  << (FA->isSpelledAsSealed() ? "sealed" : "final")
3138  << FixItHint::CreateRemoval(FA->getLocation());
3139  D->dropAttr<FinalAttr>();
3140  }
3141  return;
3142  }
3143 
3144  // C++11 [class.virtual]p5:
3145  // If a function is marked with the virt-specifier override and
3146  // does not override a member function of a base class, the program is
3147  // ill-formed.
3148  bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3149  if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3150  Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3151  << MD->getDeclName();
3152 }
3153 
3155  if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3156  return;
3157  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3158  if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3159  return;
3160 
3161  SourceLocation Loc = MD->getLocation();
3162  SourceLocation SpellingLoc = Loc;
3163  if (getSourceManager().isMacroArgExpansion(Loc))
3164  SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3165  SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3166  if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3167  return;
3168 
3169  if (MD->size_overridden_methods() > 0) {
3170  auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3171  unsigned DiagID =
3172  Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3173  ? DiagInconsistent
3174  : DiagSuggest;
3175  Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3176  const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3177  Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3178  };
3179  if (isa<CXXDestructorDecl>(MD))
3180  EmitDiag(
3181  diag::warn_inconsistent_destructor_marked_not_override_overriding,
3182  diag::warn_suggest_destructor_marked_not_override_overriding);
3183  else
3184  EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3185  diag::warn_suggest_function_marked_not_override_overriding);
3186  }
3187 }
3188 
3189 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
3190 /// function overrides a virtual member function marked 'final', according to
3191 /// C++11 [class.virtual]p4.
3193  const CXXMethodDecl *Old) {
3194  FinalAttr *FA = Old->getAttr<FinalAttr>();
3195  if (!FA)
3196  return false;
3197 
3198  Diag(New->getLocation(), diag::err_final_function_overridden)
3199  << New->getDeclName()
3200  << FA->isSpelledAsSealed();
3201  Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3202  return true;
3203 }
3204 
3205 static bool InitializationHasSideEffects(const FieldDecl &FD) {
3206  const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3207  // FIXME: Destruction of ObjC lifetime types has side-effects.
3208  if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3209  return !RD->isCompleteDefinition() ||
3210  !RD->hasTrivialDefaultConstructor() ||
3211  !RD->hasTrivialDestructor();
3212  return false;
3213 }
3214 
3217  llvm::find_if(list, [](const ParsedAttr &AL) {
3218  return AL.isDeclspecPropertyAttribute();
3219  });
3220  if (Itr != list.end())
3221  return &*Itr;
3222  return nullptr;
3223 }
3224 
3225 // Check if there is a field shadowing.
3226 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3227  DeclarationName FieldName,
3228  const CXXRecordDecl *RD,
3229  bool DeclIsField) {
3230  if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3231  return;
3232 
3233  // To record a shadowed field in a base
3234  std::map<CXXRecordDecl*, NamedDecl*> Bases;
3235  auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3236  CXXBasePath &Path) {
3237  const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3238  // Record an ambiguous path directly
3239  if (Bases.find(Base) != Bases.end())
3240  return true;
3241  for (const auto Field : Base->lookup(FieldName)) {
3242  if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3243  Field->getAccess() != AS_private) {
3244  assert(Field->getAccess() != AS_none);
3245  assert(Bases.find(Base) == Bases.end());
3246  Bases[Base] = Field;
3247  return true;
3248  }
3249  }
3250  return false;
3251  };
3252 
3253  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3254  /*DetectVirtual=*/true);
3255  if (!RD->lookupInBases(FieldShadowed, Paths))
3256  return;
3257 
3258  for (const auto &P : Paths) {
3259  auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3260  auto It = Bases.find(Base);
3261  // Skip duplicated bases
3262  if (It == Bases.end())
3263  continue;
3264  auto BaseField = It->second;
3265  assert(BaseField->getAccess() != AS_private);
3266  if (AS_none !=
3267  CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3268  Diag(Loc, diag::warn_shadow_field)
3269  << FieldName << RD << Base << DeclIsField;
3270  Diag(BaseField->getLocation(), diag::note_shadow_field);
3271  Bases.erase(It);
3272  }
3273  }
3274 }
3275 
3276 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
3277 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
3278 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
3279 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
3280 /// present (but parsing it has been deferred).
3281 NamedDecl *
3283  MultiTemplateParamsArg TemplateParameterLists,
3284  Expr *BW, const VirtSpecifiers &VS,
3285  InClassInitStyle InitStyle) {
3286  const DeclSpec &DS = D.getDeclSpec();
3288  DeclarationName Name = NameInfo.getName();
3289  SourceLocation Loc = NameInfo.getLoc();
3290 
3291  // For anonymous bitfields, the location should point to the type.
3292  if (Loc.isInvalid())
3293  Loc = D.getBeginLoc();
3294 
3295  Expr *BitWidth = static_cast<Expr*>(BW);
3296 
3297  assert(isa<CXXRecordDecl>(CurContext));
3298  assert(!DS.isFriendSpecified());
3299 
3300  bool isFunc = D.isDeclarationOfFunction();
3301  const ParsedAttr *MSPropertyAttr =
3303 
3304  if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3305  // The Microsoft extension __interface only permits public member functions
3306  // and prohibits constructors, destructors, operators, non-public member
3307  // functions, static methods and data members.
3308  unsigned InvalidDecl;
3309  bool ShowDeclName = true;
3310  if (!isFunc &&
3311  (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3312  InvalidDecl = 0;
3313  else if (!isFunc)
3314  InvalidDecl = 1;
3315  else if (AS != AS_public)
3316  InvalidDecl = 2;
3317  else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3318  InvalidDecl = 3;
3319  else switch (Name.getNameKind()) {
3321  InvalidDecl = 4;
3322  ShowDeclName = false;
3323  break;
3324 
3326  InvalidDecl = 5;
3327  ShowDeclName = false;
3328  break;
3329 
3332  InvalidDecl = 6;
3333  break;
3334 
3335  default:
3336  InvalidDecl = 0;
3337  break;
3338  }
3339 
3340  if (InvalidDecl) {
3341  if (ShowDeclName)
3342  Diag(Loc, diag::err_invalid_member_in_interface)
3343  << (InvalidDecl-1) << Name;
3344  else
3345  Diag(Loc, diag::err_invalid_member_in_interface)
3346  << (InvalidDecl-1) << "";
3347  return nullptr;
3348  }
3349  }
3350 
3351  // C++ 9.2p6: A member shall not be declared to have automatic storage
3352  // duration (auto, register) or with the extern storage-class-specifier.
3353  // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3354  // data members and cannot be applied to names declared const or static,
3355  // and cannot be applied to reference members.
3356  switch (DS.getStorageClassSpec()) {
3358  case DeclSpec::SCS_typedef:
3359  case DeclSpec::SCS_static:
3360  break;
3361  case DeclSpec::SCS_mutable:
3362  if (isFunc) {
3363  Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3364 
3365  // FIXME: It would be nicer if the keyword was ignored only for this
3366  // declarator. Otherwise we could get follow-up errors.
3368  }
3369  break;
3370  default:
3372  diag::err_storageclass_invalid_for_member);
3374  break;
3375  }
3376 
3377  bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3379  !isFunc);
3380 
3381  if (DS.hasConstexprSpecifier() && isInstField) {
3383  Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3384  SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3385  if (InitStyle == ICIS_NoInit) {
3386  B << 0 << 0;
3388  B << FixItHint::CreateRemoval(ConstexprLoc);
3389  else {
3390  B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3392  const char *PrevSpec;
3393  unsigned DiagID;
3394  bool Failed = D.getMutableDeclSpec().SetTypeQual(
3395  DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3396  (void)Failed;
3397  assert(!Failed && "Making a constexpr member const shouldn't fail");
3398  }
3399  } else {
3400  B << 1;
3401  const char *PrevSpec;
3402  unsigned DiagID;
3404  *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3406  assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3407  "This is the only DeclSpec that should fail to be applied");
3408  B << 1;
3409  } else {
3410  B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3411  isInstField = false;
3412  }
3413  }
3414  }
3415 
3416  NamedDecl *Member;
3417  if (isInstField) {
3418  CXXScopeSpec &SS = D.getCXXScopeSpec();
3419 
3420  // Data members must have identifiers for names.
3421  if (!Name.isIdentifier()) {
3422  Diag(Loc, diag::err_bad_variable_name)
3423  << Name;
3424  return nullptr;
3425  }
3426 
3427  IdentifierInfo *II = Name.getAsIdentifierInfo();
3428 
3429  // Member field could not be with "template" keyword.
3430  // So TemplateParameterLists should be empty in this case.
3431  if (TemplateParameterLists.size()) {
3432  TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3433  if (TemplateParams->size()) {
3434  // There is no such thing as a member field template.
3435  Diag(D.getIdentifierLoc(), diag::err_template_member)
3436  << II
3437  << SourceRange(TemplateParams->getTemplateLoc(),
3438  TemplateParams->getRAngleLoc());
3439  } else {
3440  // There is an extraneous 'template<>' for this member.
3441  Diag(TemplateParams->getTemplateLoc(),
3442  diag::err_template_member_noparams)
3443  << II
3444  << SourceRange(TemplateParams->getTemplateLoc(),
3445  TemplateParams->getRAngleLoc());
3446  }
3447  return nullptr;
3448  }
3449 
3451  Diag(D.getIdentifierLoc(), diag::err_member_with_template_arguments)
3452  << II
3455  << D.getName().TemplateId->LAngleLoc;
3456  D.SetIdentifier(II, Loc);
3457  }
3458 
3459  if (SS.isSet() && !SS.isInvalid()) {
3460  // The user provided a superfluous scope specifier inside a class
3461  // definition:
3462  //
3463  // class X {
3464  // int X::member;
3465  // };
3466  if (DeclContext *DC = computeDeclContext(SS, false))
3468  D.getName().getKind() ==
3470  else
3471  Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3472  << Name << SS.getRange();
3473 
3474  SS.clear();
3475  }
3476 
3477  if (MSPropertyAttr) {
3478  Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3479  BitWidth, InitStyle, AS, *MSPropertyAttr);
3480  if (!Member)
3481  return nullptr;
3482  isInstField = false;
3483  } else {
3484  Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3485  BitWidth, InitStyle, AS);
3486  if (!Member)
3487  return nullptr;
3488  }
3489 
3490  CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3491  } else {
3492  Member = HandleDeclarator(S, D, TemplateParameterLists);
3493  if (!Member)
3494  return nullptr;
3495 
3496  // Non-instance-fields can't have a bitfield.
3497  if (BitWidth) {
3498  if (Member->isInvalidDecl()) {
3499  // don't emit another diagnostic.
3500  } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3501  // C++ 9.6p3: A bit-field shall not be a static member.
3502  // "static member 'A' cannot be a bit-field"
3503  Diag(Loc, diag::err_static_not_bitfield)
3504  << Name << BitWidth->getSourceRange();
3505  } else if (isa<TypedefDecl>(Member)) {
3506  // "typedef member 'x' cannot be a bit-field"
3507  Diag(Loc, diag::err_typedef_not_bitfield)
3508  << Name << BitWidth->getSourceRange();
3509  } else {
3510  // A function typedef ("typedef int f(); f a;").
3511  // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3512  Diag(Loc, diag::err_not_integral_type_bitfield)
3513  << Name << cast<ValueDecl>(Member)->getType()
3514  << BitWidth->getSourceRange();
3515  }
3516 
3517  BitWidth = nullptr;
3518  Member->setInvalidDecl();
3519  }
3520 
3521  NamedDecl *NonTemplateMember = Member;
3522  if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3523  NonTemplateMember = FunTmpl->getTemplatedDecl();
3524  else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3525  NonTemplateMember = VarTmpl->getTemplatedDecl();
3526 
3527  Member->setAccess(AS);
3528 
3529  // If we have declared a member function template or static data member
3530  // template, set the access of the templated declaration as well.
3531  if (NonTemplateMember != Member)
3532  NonTemplateMember->setAccess(AS);
3533 
3534  // C++ [temp.deduct.guide]p3:
3535  // A deduction guide [...] for a member class template [shall be
3536  // declared] with the same access [as the template].
3537  if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3538  auto *TD = DG->getDeducedTemplate();
3539  // Access specifiers are only meaningful if both the template and the
3540  // deduction guide are from the same scope.
3541  if (AS != TD->getAccess() &&
3542  TD->getDeclContext()->getRedeclContext()->Equals(
3543  DG->getDeclContext()->getRedeclContext())) {
3544  Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3545  Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3546  << TD->getAccess();
3547  const AccessSpecDecl *LastAccessSpec = nullptr;
3548  for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3549  if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3550  LastAccessSpec = AccessSpec;
3551  }
3552  assert(LastAccessSpec && "differing access with no access specifier");
3553  Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3554  << AS;
3555  }
3556  }
3557  }
3558 
3559  if (VS.isOverrideSpecified())
3560  Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(),
3562  if (VS.isFinalSpecified())
3563  Member->addAttr(FinalAttr::Create(
3565  static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed())));
3566 
3567  if (VS.getLastLocation().isValid()) {
3568  // Update the end location of a method that has a virt-specifiers.
3569  if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3570  MD->setRangeEnd(VS.getLastLocation());
3571  }
3572 
3574 
3575  assert((Name || isInstField) && "No identifier for non-field ?");
3576 
3577  if (isInstField) {
3578  FieldDecl *FD = cast<FieldDecl>(Member);
3579  FieldCollector->Add(FD);
3580 
3581  if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3582  // Remember all explicit private FieldDecls that have a name, no side
3583  // effects and are not part of a dependent type declaration.
3584  if (!FD->isImplicit() && FD->getDeclName() &&
3585  FD->getAccess() == AS_private &&
3586  !FD->hasAttr<UnusedAttr>() &&
3587  !FD->getParent()->isDependentContext() &&
3589  UnusedPrivateFields.insert(FD);
3590  }
3591  }
3592 
3593  return Member;
3594 }
3595 
3596 namespace {
3597  class UninitializedFieldVisitor
3598  : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3599  Sema &S;
3600  // List of Decls to generate a warning on. Also remove Decls that become
3601  // initialized.
3602  llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3603  // List of base classes of the record. Classes are removed after their
3604  // initializers.
3605  llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3606  // Vector of decls to be removed from the Decl set prior to visiting the
3607  // nodes. These Decls may have been initialized in the prior initializer.
3608  llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3609  // If non-null, add a note to the warning pointing back to the constructor.
3610  const CXXConstructorDecl *Constructor;
3611  // Variables to hold state when processing an initializer list. When
3612  // InitList is true, special case initialization of FieldDecls matching
3613  // InitListFieldDecl.
3614  bool InitList;
3615  FieldDecl *InitListFieldDecl;
3616  llvm::SmallVector<unsigned, 4> InitFieldIndex;
3617 
3618  public:
3620  UninitializedFieldVisitor(Sema &S,
3621  llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3622  llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3623  : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3624  Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3625 
3626  // Returns true if the use of ME is not an uninitialized use.
3627  bool IsInitListMemberExprInitialized(MemberExpr *ME,
3628  bool CheckReferenceOnly) {
3630  bool ReferenceField = false;
3631  while (ME) {
3632  FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3633  if (!FD)
3634  return false;
3635  Fields.push_back(FD);
3636  if (FD->getType()->isReferenceType())
3637  ReferenceField = true;
3638  ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3639  }
3640 
3641  // Binding a reference to an uninitialized field is not an
3642  // uninitialized use.
3643  if (CheckReferenceOnly && !ReferenceField)
3644  return true;
3645 
3646  llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3647  // Discard the first field since it is the field decl that is being
3648  // initialized.
3649  for (const FieldDecl *FD : llvm::drop_begin(llvm::reverse(Fields)))
3650  UsedFieldIndex.push_back(FD->getFieldIndex());
3651 
3652  for (auto UsedIter = UsedFieldIndex.begin(),
3653  UsedEnd = UsedFieldIndex.end(),
3654  OrigIter = InitFieldIndex.begin(),
3655  OrigEnd = InitFieldIndex.end();
3656  UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3657  if (*UsedIter < *OrigIter)
3658  return true;
3659  if (*UsedIter > *OrigIter)
3660  break;
3661  }
3662 
3663  return false;
3664  }
3665 
3666  void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3667  bool AddressOf) {
3668  if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3669  return;
3670 
3671  // FieldME is the inner-most MemberExpr that is not an anonymous struct
3672  // or union.
3673  MemberExpr *FieldME = ME;
3674 
3675  bool AllPODFields = FieldME->getType().isPODType(S.Context);
3676 
3677  Expr *Base = ME;
3678  while (MemberExpr *SubME =
3679  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3680 
3681  if (isa<VarDecl>(SubME->getMemberDecl()))
3682  return;
3683 
3684  if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3685  if (!FD->isAnonymousStructOrUnion())
3686  FieldME = SubME;
3687 
3688  if (!FieldME->getType().isPODType(S.Context))
3689  AllPODFields = false;
3690 
3691  Base = SubME->getBase();
3692  }
3693 
3694  if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3695  Visit(Base);
3696  return;
3697  }
3698 
3699  if (AddressOf && AllPODFields)
3700  return;
3701 
3702  ValueDecl* FoundVD = FieldME->getMemberDecl();
3703 
3704  if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3705  while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3706  BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3707  }
3708 
3709  if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3710  QualType T = BaseCast->getType();
3711  if (T->isPointerType() &&
3712  BaseClasses.count(T->getPointeeType())) {
3713  S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3714  << T->getPointeeType() << FoundVD;
3715  }
3716  }
3717  }
3718 
3719  if (!Decls.count(FoundVD))
3720  return;
3721 
3722  const bool IsReference = FoundVD->getType()->isReferenceType();
3723 
3724  if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3725  // Special checking for initializer lists.
3726  if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3727  return;
3728  }
3729  } else {
3730  // Prevent double warnings on use of unbounded references.
3731  if (CheckReferenceOnly && !IsReference)
3732  return;
3733  }
3734 
3735  unsigned diag = IsReference
3736  ? diag::warn_reference_field_is_uninit
3737  : diag::warn_field_is_uninit;
3738  S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3739  if (Constructor)
3740  S.Diag(Constructor->getLocation(),
3741  diag::note_uninit_in_this_constructor)
3742  << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3743 
3744  }
3745 
3746  void HandleValue(Expr *E, bool AddressOf) {
3747  E = E->IgnoreParens();
3748 
3749  if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3750  HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3751  AddressOf /*AddressOf*/);
3752  return;
3753  }
3754 
3755  if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3756  Visit(CO->getCond());
3757  HandleValue(CO->getTrueExpr(), AddressOf);
3758  HandleValue(CO->getFalseExpr(), AddressOf);
3759  return;
3760  }
3761 
3762  if (BinaryConditionalOperator *BCO =
3763  dyn_cast<BinaryConditionalOperator>(E)) {
3764  Visit(BCO->getCond());
3765  HandleValue(BCO->getFalseExpr(), AddressOf);
3766  return;
3767  }
3768 
3769  if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3770  HandleValue(OVE->getSourceExpr(), AddressOf);
3771  return;
3772  }
3773 
3774  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3775  switch (BO->getOpcode()) {
3776  default:
3777  break;
3778  case(BO_PtrMemD):
3779  case(BO_PtrMemI):
3780  HandleValue(BO->getLHS(), AddressOf);
3781  Visit(BO->getRHS());
3782  return;
3783  case(BO_Comma):
3784  Visit(BO->getLHS());
3785  HandleValue(BO->getRHS(), AddressOf);
3786  return;
3787  }
3788  }
3789 
3790  Visit(E);
3791  }
3792 
3793  void CheckInitListExpr(InitListExpr *ILE) {
3794  InitFieldIndex.push_back(0);
3795  for (auto *Child : ILE->children()) {
3796  if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3797  CheckInitListExpr(SubList);
3798  } else {
3799  Visit(Child);
3800  }
3801  ++InitFieldIndex.back();
3802  }
3803  InitFieldIndex.pop_back();
3804  }
3805 
3806  void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3807  FieldDecl *Field, const Type *BaseClass) {
3808  // Remove Decls that may have been initialized in the previous
3809  // initializer.
3810  for (ValueDecl* VD : DeclsToRemove)
3811  Decls.erase(VD);
3812  DeclsToRemove.clear();
3813 
3814  Constructor = FieldConstructor;
3815  InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3816 
3817  if (ILE && Field) {
3818  InitList = true;
3819  InitListFieldDecl = Field;
3820  InitFieldIndex.clear();
3821  CheckInitListExpr(ILE);
3822  } else {
3823  InitList = false;
3824  Visit(E);
3825  }
3826 
3827  if (Field)
3828  Decls.erase(Field);
3829  if (BaseClass)
3830  BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3831  }
3832 
3833  void VisitMemberExpr(MemberExpr *ME) {
3834  // All uses of unbounded reference fields will warn.
3835  HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3836  }
3837 
3838  void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3839  if (E->getCastKind() == CK_LValueToRValue) {
3840  HandleValue(E->getSubExpr(), false /*AddressOf*/);
3841  return;
3842  }
3843 
3844  Inherited::VisitImplicitCastExpr(E);
3845  }
3846 
3847  void VisitCXXConstructExpr(CXXConstructExpr *E) {
3848  if (E->getConstructor()->isCopyConstructor()) {
3849  Expr *ArgExpr = E->getArg(0);
3850  if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3851  if (ILE->getNumInits() == 1)
3852  ArgExpr = ILE->getInit(0);
3853  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3854  if (ICE->getCastKind() == CK_NoOp)
3855  ArgExpr = ICE->getSubExpr();
3856  HandleValue(ArgExpr, false /*AddressOf*/);
3857  return;
3858  }
3859  Inherited::VisitCXXConstructExpr(E);
3860  }
3861 
3862  void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3863  Expr *Callee = E->getCallee();
3864  if (isa<MemberExpr>(Callee)) {
3865  HandleValue(Callee, false /*AddressOf*/);
3866  for (auto *Arg : E->arguments())
3867  Visit(Arg);
3868  return;
3869  }
3870 
3871  Inherited::VisitCXXMemberCallExpr(E);
3872  }
3873 
3874  void VisitCallExpr(CallExpr *E) {
3875  // Treat std::move as a use.
3876  if (E->isCallToStdMove()) {
3877  HandleValue(E->getArg(0), /*AddressOf=*/false);
3878  return;
3879  }
3880 
3881  Inherited::VisitCallExpr(E);
3882  }
3883 
3884  void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3885  Expr *Callee = E->getCallee();
3886 
3887  if (isa<UnresolvedLookupExpr>(Callee))
3888  return Inherited::VisitCXXOperatorCallExpr(E);
3889 
3890  Visit(Callee);
3891  for (auto *Arg : E->arguments())
3892  HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3893  }
3894 
3895  void VisitBinaryOperator(BinaryOperator *E) {
3896  // If a field assignment is detected, remove the field from the
3897  // uninitiailized field set.
3898  if (E->getOpcode() == BO_Assign)
3899  if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3900  if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3901  if (!FD->getType()->isReferenceType())
3902  DeclsToRemove.push_back(FD);
3903 
3904  if (E->isCompoundAssignmentOp()) {
3905  HandleValue(E->getLHS(), false /*AddressOf*/);
3906  Visit(E->getRHS());
3907  return;
3908  }
3909 
3910  Inherited::VisitBinaryOperator(E);
3911  }
3912 
3913  void VisitUnaryOperator(UnaryOperator *E) {
3914  if (E->isIncrementDecrementOp()) {
3915  HandleValue(E->getSubExpr(), false /*AddressOf*/);
3916  return;
3917  }
3918  if (E->getOpcode() == UO_AddrOf) {
3919  if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3920  HandleValue(ME->getBase(), true /*AddressOf*/);
3921  return;
3922  }
3923  }
3924 
3925  Inherited::VisitUnaryOperator(E);
3926  }
3927  };
3928 
3929  // Diagnose value-uses of fields to initialize themselves, e.g.
3930  // foo(foo)
3931  // where foo is not also a parameter to the constructor.
3932  // Also diagnose across field uninitialized use such as
3933  // x(y), y(x)
3934  // TODO: implement -Wuninitialized and fold this into that framework.
3935  static void DiagnoseUninitializedFields(
3936  Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3937 
3938  if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3939  Constructor->getLocation())) {
3940  return;
3941  }
3942 
3943  if (Constructor->isInvalidDecl())
3944  return;
3945 
3946  const CXXRecordDecl *RD = Constructor->getParent();
3947 
3948  if (RD->isDependentContext())
3949  return;
3950 
3951  // Holds fields that are uninitialized.
3952  llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3953 
3954  // At the beginning, all fields are uninitialized.
3955  for (auto *I : RD->decls()) {
3956  if (auto *FD = dyn_cast<FieldDecl>(I)) {
3957  UninitializedFields.insert(FD);
3958  } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3959  UninitializedFields.insert(IFD->getAnonField());
3960  }
3961  }
3962 
3963  llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3964  for (auto I : RD->bases())
3965  UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3966 
3967  if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3968  return;
3969 
3970  UninitializedFieldVisitor UninitializedChecker(SemaRef,
3971  UninitializedFields,
3972  UninitializedBaseClasses);
3973 
3974  for (const auto *FieldInit : Constructor->inits()) {
3975  if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3976  break;
3977 
3978  Expr *InitExpr = FieldInit->getInit();
3979  if (!InitExpr)
3980  continue;
3981 
3982  if (CXXDefaultInitExpr *Default =
3983  dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3984  InitExpr = Default->getExpr();
3985  if (!InitExpr)
3986  continue;
3987  // In class initializers will point to the constructor.
3988  UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3989  FieldInit->getAnyMember(),
3990  FieldInit->getBaseClass());
3991  } else {
3992  UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3993  FieldInit->getAnyMember(),
3994  FieldInit->getBaseClass());
3995  }
3996  }
3997  }
3998 } // namespace
3999 
4000 /// Enter a new C++ default initializer scope. After calling this, the
4001 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
4002 /// parsing or instantiating the initializer failed.
4004  // Create a synthetic function scope to represent the call to the constructor
4005  // that notionally surrounds a use of this initializer.
4007 }
4008 
4010  if (!D.isFunctionDeclarator())
4011  return;
4012  auto &FTI = D.getFunctionTypeInfo();
4013  if (!FTI.Params)
4014  return;
4015  for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
4016  FTI.NumParams)) {
4017  auto *ParamDecl = cast<NamedDecl>(Param.Param);
4018  if (ParamDecl->getDeclName())
4019  PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
4020  }
4021 }
4022 
4024  return ActOnRequiresClause(ConstraintExpr);
4025 }
4026 
4028  if (ConstraintExpr.isInvalid())
4029  return ExprError();
4030 
4031  ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr);
4032  if (ConstraintExpr.isInvalid())
4033  return ExprError();
4034 
4035  if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),
4037  return ExprError();
4038 
4039  return ConstraintExpr;
4040 }
4041 
4042 /// This is invoked after parsing an in-class initializer for a
4043 /// non-static C++ class member, and after instantiating an in-class initializer
4044 /// in a class template. Such actions are deferred until the class is complete.
4046  SourceLocation InitLoc,
4047  Expr *InitExpr) {
4048  // Pop the notional constructor scope we created earlier.
4049  PopFunctionScopeInfo(nullptr, D);
4050 
4051  FieldDecl *FD = dyn_cast<FieldDecl>(D);
4052  assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
4053  "must set init style when field is created");
4054 
4055  if (!InitExpr) {
4056  D->setInvalidDecl();
4057  if (FD)
4059  return;
4060  }
4061 
4063  FD->setInvalidDecl();
4065  return;
4066  }
4067 
4068  ExprResult Init = InitExpr;
4069  if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
4070  InitializedEntity Entity =
4075  InitExpr->getBeginLoc(),
4076  InitExpr->getEndLoc())
4077  : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
4078  InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4079  Init = Seq.Perform(*this, Entity, Kind, InitExpr);
4080  if (Init.isInvalid()) {
4081  FD->setInvalidDecl();
4082  return;
4083  }
4084  }
4085 
4086  // C++11 [class.base.init]p7:
4087  // The initialization of each base and member constitutes a
4088  // full-expression.
4089  Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
4090  if (Init.isInvalid()) {
4091  FD->setInvalidDecl();
4092  return;
4093  }
4094 
4095  InitExpr = Init.get();
4096 
4097  FD->setInClassInitializer(InitExpr);
4098 }
4099 
4100 /// Find the direct and/or virtual base specifiers that
4101 /// correspond to the given base type, for use in base initialization
4102 /// within a constructor.
4103 static bool FindBaseInitializer(Sema &SemaRef,
4104  CXXRecordDecl *ClassDecl,
4105  QualType BaseType,
4106  const CXXBaseSpecifier *&DirectBaseSpec,
4107  const CXXBaseSpecifier *&VirtualBaseSpec) {
4108  // First, check for a direct base class.
4109  DirectBaseSpec = nullptr;
4110  for (const auto &Base : ClassDecl->bases()) {
4111  if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
4112  // We found a direct base of this type. That's what we're
4113  // initializing.
4114  DirectBaseSpec = &Base;
4115  break;
4116  }
4117  }
4118 
4119  // Check for a virtual base class.
4120  // FIXME: We might be able to short-circuit this if we know in advance that
4121  // there are no virtual bases.
4122  VirtualBaseSpec = nullptr;
4123  if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4124  // We haven't found a base yet; search the class hierarchy for a
4125  // virtual base class.
4126  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4127  /*DetectVirtual=*/false);
4128  if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4129  SemaRef.Context.getTypeDeclType(ClassDecl),
4130  BaseType, Paths)) {
4131  for (CXXBasePaths::paths_iterator Path = Paths.begin();
4132  Path != Paths.end(); ++Path) {
4133  if (Path->back().Base->isVirtual()) {
4134  VirtualBaseSpec = Path->back().Base;
4135  break;
4136  }
4137  }
4138  }
4139  }
4140 
4141  return DirectBaseSpec || VirtualBaseSpec;
4142 }
4143 
4144 /// Handle a C++ member initializer using braced-init-list syntax.
4147  Scope *S,
4148  CXXScopeSpec &SS,
4149  IdentifierInfo *MemberOrBase,
4150  ParsedType TemplateTypeTy,
4151  const DeclSpec &DS,
4152  SourceLocation IdLoc,
4153  Expr *InitList,
4154  SourceLocation EllipsisLoc) {
4155  return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4156  DS, IdLoc, InitList,
4157  EllipsisLoc);
4158 }
4159 
4160 /// Handle a C++ member initializer using parentheses syntax.
4163  Scope *S,
4164  CXXScopeSpec &SS,
4165  IdentifierInfo *MemberOrBase,
4166  ParsedType TemplateTypeTy,
4167  const DeclSpec &DS,
4168  SourceLocation IdLoc,
4169  SourceLocation LParenLoc,
4170  ArrayRef<Expr *> Args,
4171  SourceLocation RParenLoc,
4172  SourceLocation EllipsisLoc) {
4173  Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4174  return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4175  DS, IdLoc, List, EllipsisLoc);
4176 }
4177 
4178 namespace {
4179 
4180 // Callback to only accept typo corrections that can be a valid C++ member
4181 // initializer: either a non-static field member or a base class.
4182 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4183 public:
4184  explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4185  : ClassDecl(ClassDecl) {}
4186 
4187  bool ValidateCandidate(const TypoCorrection &candidate) override {
4188  if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4189  if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4190  return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4191  return isa<TypeDecl>(ND);
4192  }
4193  return false;
4194  }
4195 
4196  std::unique_ptr<CorrectionCandidateCallback> clone() override {
4197  return std::make_unique<MemInitializerValidatorCCC>(*this);
4198  }
4199 
4200 private:
4201  CXXRecordDecl *ClassDecl;
4202 };
4203 
4204 }
4205 
4206 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4207  CXXScopeSpec &SS,
4208  ParsedType TemplateTypeTy,
4209  IdentifierInfo *MemberOrBase) {
4210  if (SS.getScopeRep() || TemplateTypeTy)
4211  return nullptr;
4212  for (auto *D : ClassDecl->lookup(MemberOrBase))
4213  if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D))
4214  return cast<ValueDecl>(D);
4215  return nullptr;
4216 }
4217 
4218 /// Handle a C++ member initializer.
4221  Scope *S,
4222  CXXScopeSpec &SS,
4223  IdentifierInfo *MemberOrBase,
4224  ParsedType TemplateTypeTy,
4225  const DeclSpec &DS,
4226  SourceLocation IdLoc,
4227  Expr *Init,
4228  SourceLocation EllipsisLoc) {
4229  ExprResult Res = CorrectDelayedTyposInExpr(Init, /*InitDecl=*/nullptr,
4230  /*RecoverUncorrectedTypos=*/true);
4231  if (!Res.isUsable())
4232  return true;
4233  Init = Res.get();
4234 
4235  if (!ConstructorD)
4236  return true;
4237 
4238  AdjustDeclIfTemplate(ConstructorD);
4239 
4240  CXXConstructorDecl *Constructor
4241  = dyn_cast<CXXConstructorDecl>(ConstructorD);
4242  if (!Constructor) {
4243  // The user wrote a constructor initializer on a function that is
4244  // not a C++ constructor. Ignore the error for now, because we may
4245  // have more member initializers coming; we'll diagnose it just
4246  // once in ActOnMemInitializers.
4247  return true;
4248  }
4249 
4250  CXXRecordDecl *ClassDecl = Constructor->getParent();
4251 
4252  // C++ [class.base.init]p2:
4253  // Names in a mem-initializer-id are looked up in the scope of the
4254  // constructor's class and, if not found in that scope, are looked
4255  // up in the scope containing the constructor's definition.
4256  // [Note: if the constructor's class contains a member with the
4257  // same name as a direct or virtual base class of the class, a
4258  // mem-initializer-id naming the member or base class and composed
4259  // of a single identifier refers to the class member. A
4260  // mem-initializer-id for the hidden base class may be specified
4261  // using a qualified name. ]
4262 
4263  // Look for a member, first.
4264  if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4265  ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4266  if (EllipsisLoc.isValid())
4267  Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4268  << MemberOrBase
4269  << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4270 
4271  return BuildMemberInitializer(Member, Init, IdLoc);
4272  }
4273  // It didn't name a member, so see if it names a class.
4274  QualType BaseType;
4275  TypeSourceInfo *TInfo = nullptr;
4276 
4277  if (TemplateTypeTy) {
4278  BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4279  if (BaseType.isNull())
4280  return true;
4281  } else if (DS.getTypeSpecType() == TST_decltype) {
4282  BaseType = BuildDecltypeType(DS.getRepAsExpr());
4283  } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4284  Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4285  return true;
4286  } else {
4287  LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4288  LookupParsedName(R, S, &SS);
4289 
4290  TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4291  if (!TyD) {
4292  if (R.isAmbiguous()) return true;
4293 
4294  // We don't want access-control diagnostics here.
4295  R.suppressDiagnostics();
4296 
4297  if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4298  bool NotUnknownSpecialization = false;
4299  DeclContext *DC = computeDeclContext(SS, false);
4300  if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4301  NotUnknownSpecialization = !Record->hasAnyDependentBases();
4302 
4303  if (!NotUnknownSpecialization) {
4304  // When the scope specifier can refer to a member of an unknown
4305  // specialization, we take it as a type name.
4308  *MemberOrBase, IdLoc);
4309  if (BaseType.isNull())
4310  return true;
4311 
4312  TInfo = Context.CreateTypeSourceInfo(BaseType);
4315  if (!TL.isNull()) {
4316  TL.setNameLoc(IdLoc);
4319  }
4320 
4321  R.clear();
4322  R.setLookupName(MemberOrBase);
4323  }
4324  }
4325 
4326  if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) {
4327  if (auto UnqualifiedBase = R.getAsSingle<ClassTemplateDecl>()) {
4328  auto *TempSpec = cast<TemplateSpecializationType>(
4329  UnqualifiedBase->getInjectedClassNameSpecialization());
4330  TemplateName TN = TempSpec->getTemplateName();
4331  for (auto const &Base : ClassDecl->bases()) {
4332  auto BaseTemplate =
4333  Base.getType()->getAs<TemplateSpecializationType>();
4334  if (BaseTemplate && Context.hasSameTemplateName(
4335  BaseTemplate->getTemplateName(), TN)) {
4336  Diag(IdLoc, diag::ext_unqualified_base_class)
4337  << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4338  BaseType = Base.getType();
4339  break;
4340  }
4341  }
4342  }
4343  }
4344 
4345  // If no results were found, try to correct typos.
4346  TypoCorrection Corr;
4347  MemInitializerValidatorCCC CCC(ClassDecl);
4348  if (R.empty() && BaseType.isNull() &&
4349  (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4350  CCC, CTK_ErrorRecovery, ClassDecl))) {
4351  if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4352  // We have found a non-static data member with a similar
4353  // name to what was typed; complain and initialize that
4354  // member.
4355  diagnoseTypo(Corr,
4356  PDiag(diag::err_mem_init_not_member_or_class_suggest)
4357  << MemberOrBase << true);
4358  return BuildMemberInitializer(Member, Init, IdLoc);
4359  } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4360  const CXXBaseSpecifier *DirectBaseSpec;
4361  const CXXBaseSpecifier *VirtualBaseSpec;
4362  if (FindBaseInitializer(*this, ClassDecl,
4364  DirectBaseSpec, VirtualBaseSpec)) {
4365  // We have found a direct or virtual base class with a
4366  // similar name to what was typed; complain and initialize
4367  // that base class.
4368  diagnoseTypo(Corr,
4369  PDiag(diag::err_mem_init_not_member_or_class_suggest)
4370  << MemberOrBase << false,
4371  PDiag() /*Suppress note, we provide our own.*/);
4372 
4373  const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4374  : VirtualBaseSpec;
4375  Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4376  << BaseSpec->getType() << BaseSpec->getSourceRange();
4377 
4378  TyD = Type;
4379  }
4380  }
4381  }
4382 
4383  if (!TyD && BaseType.isNull()) {
4384  Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4385  << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4386  return true;
4387  }
4388  }
4389 
4390  if (BaseType.isNull()) {
4391  BaseType = getElaboratedType(ETK_None, SS, Context.getTypeDeclType(TyD));
4392  MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4393  TInfo = Context.CreateTypeSourceInfo(BaseType);
4395  TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4398  }
4399  }
4400 
4401  if (!TInfo)
4402  TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4403 
4404  return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4405 }
4406 
4409  SourceLocation IdLoc) {
4410  FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4411  IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4412  assert((DirectMember || IndirectMember) &&
4413  "Member must be a FieldDecl or IndirectFieldDecl");
4414 
4416  return true;
4417 
4418  if (Member->isInvalidDecl())
4419  return true;
4420 
4421  MultiExprArg Args;
4422  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4423  Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4424  } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4425  Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4426  } else {
4427  // Template instantiation doesn't reconstruct ParenListExprs for us.
4428  Args = Init;
4429  }
4430 
4431  SourceRange InitRange = Init->getSourceRange();
4432 
4433  if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4434  // Can't check initialization for a member of dependent type or when
4435  // any of the arguments are type-dependent expressions.
4437  } else {
4438  bool InitList = false;
4439  if (isa<InitListExpr>(Init)) {
4440  InitList = true;
4441  Args = Init;
4442  }
4443 
4444  // Initialize the member.
4445  InitializedEntity MemberEntity =
4446  DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4447  : InitializedEntity::InitializeMember(IndirectMember,
4448  nullptr);
4451  IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4452  : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4453  InitRange.getEnd());
4454 
4455  InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4456  ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4457  nullptr);
4458  if (!MemberInit.isInvalid()) {
4459  // C++11 [class.base.init]p7:
4460  // The initialization of each base and member constitutes a
4461  // full-expression.
4462  MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4463  /*DiscardedValue*/ false);
4464  }
4465 
4466  if (MemberInit.isInvalid()) {
4467  // Args were sensible expressions but we couldn't initialize the member
4468  // from them. Preserve them in a RecoveryExpr instead.
4469  Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4470  Member->getType())
4471  .get();
4472  if (!Init)
4473  return true;
4474  } else {
4475  Init = MemberInit.get();
4476  }
4477  }
4478 
4479  if (DirectMember) {
4480  return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4481  InitRange.getBegin(), Init,
4482  InitRange.getEnd());
4483  } else {
4484  return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4485  InitRange.getBegin(), Init,
4486  InitRange.getEnd());
4487  }
4488 }
4489 
4492  CXXRecordDecl *ClassDecl) {
4493  SourceLocation NameLoc = TInfo->getTypeLoc().getSourceRange().getBegin();
4494  if (!LangOpts.CPlusPlus11)
4495  return Diag(NameLoc, diag::err_delegating_ctor)
4496  << TInfo->getTypeLoc().getSourceRange();
4497  Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4498 
4499  bool InitList = true;
4500  MultiExprArg Args = Init;
4501  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4502  InitList = false;
4503  Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4504  }
4505 
4506  SourceRange InitRange = Init->getSourceRange();
4507  // Initialize the object.
4509  QualType(ClassDecl->getTypeForDecl(), 0));
4512  NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4513  : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4514  InitRange.getEnd());
4515  InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4516  ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4517  Args, nullptr);
4518  if (!DelegationInit.isInvalid()) {
4519  assert((DelegationInit.get()->containsErrors() ||
4520  cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&
4521  "Delegating constructor with no target?");
4522 
4523  // C++11 [class.base.init]p7:
4524  // The initialization of each base and member constitutes a
4525  // full-expression.
4526  DelegationInit = ActOnFinishFullExpr(
4527  DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4528  }
4529 
4530  if (DelegationInit.isInvalid()) {
4531  DelegationInit =
4532  CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4533  QualType(ClassDecl->getTypeForDecl(), 0));
4534  if (DelegationInit.isInvalid())
4535  return true;
4536  } else {
4537  // If we are in a dependent context, template instantiation will
4538  // perform this type-checking again. Just save the arguments that we
4539  // received in a ParenListExpr.
4540  // FIXME: This isn't quite ideal, since our ASTs don't capture all
4541  // of the information that we have about the base
4542  // initializer. However, deconstructing the ASTs is a dicey process,
4543  // and this approach is far more likely to get the corner cases right.
4545  DelegationInit = Init;
4546  }
4547 
4548  return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4549  DelegationInit.getAs<Expr>(),
4550  InitRange.getEnd());
4551 }
4552 
4555  Expr *Init, CXXRecordDecl *ClassDecl,
4556  SourceLocation EllipsisLoc) {
4557  SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getBeginLoc();
4558 
4559  if (!BaseType->isDependentType() && !BaseType->isRecordType())
4560  return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4561  << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
4562 
4563  // C++ [class.base.init]p2:
4564  // [...] Unless the mem-initializer-id names a nonstatic data
4565  // member of the constructor's class or a direct or virtual base
4566  // of that class, the mem-initializer is ill-formed. A
4567  // mem-initializer-list can initialize a base class using any
4568  // name that denotes that base class type.
4569 
4570  // We can store the initializers in "as-written" form and delay analysis until
4571  // instantiation if the constructor is dependent. But not for dependent
4572  // (broken) code in a non-template! SetCtorInitializers does not expect this.
4573  bool Dependent = CurContext->isDependentContext() &&
4574  (BaseType->isDependentType() || Init->isTypeDependent());
4575 
4576  SourceRange InitRange = Init->getSourceRange();
4577  if (EllipsisLoc.isValid()) {
4578  // This is a pack expansion.
4579  if (!BaseType->containsUnexpandedParameterPack()) {
4580  Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4581  << SourceRange(BaseLoc, InitRange.getEnd());
4582 
4583  EllipsisLoc = SourceLocation();
4584  }
4585  } else {
4586  // Check for any unexpanded parameter packs.
4587  if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4588  return true;
4589 
4591  return true;
4592  }
4593 
4594  // Check for direct and virtual base classes.
4595  const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4596  const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4597  if (!Dependent) {
4599  BaseType))
4600  return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4601 
4602  FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4603  VirtualBaseSpec);
4604 
4605  // C++ [base.class.init]p2:
4606  // Unless the mem-initializer-id names a nonstatic data member of the
4607  // constructor's class or a direct or virtual base of that class, the
4608  // mem-initializer is ill-formed.
4609  if (!DirectBaseSpec && !VirtualBaseSpec) {
4610  // If the class has any dependent bases, then it's possible that
4611  // one of those types will resolve to the same type as
4612  // BaseType. Therefore, just treat this as a dependent base
4613  // class initialization. FIXME: Should we try to check the
4614  // initialization anyway? It seems odd.
4615  if (ClassDecl->hasAnyDependentBases())
4616  Dependent = true;
4617  else
4618  return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4619  << BaseType << Context.getTypeDeclType(ClassDecl)
4620  << BaseTInfo->getTypeLoc().getSourceRange();
4621  }
4622  }
4623 
4624  if (Dependent) {
4626 
4627  return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4628  /*IsVirtual=*/false,
4629  InitRange.getBegin(), Init,
4630  InitRange.getEnd(), EllipsisLoc);
4631  }
4632 
4633  // C++ [base.class.init]p2:
4634  // If a mem-initializer-id is ambiguous because it designates both
4635  // a direct non-virtual base class and an inherited virtual base
4636  // class, the mem-initializer is ill-formed.
4637  if (DirectBaseSpec && VirtualBaseSpec)
4638  return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4639  << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4640 
4641  const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4642  if (!BaseSpec)
4643  BaseSpec = VirtualBaseSpec;
4644 
4645  // Initialize the base.
4646  bool InitList = true;
4647  MultiExprArg Args = Init;
4648  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4649  InitList = false;
4650  Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4651  }
4652 
4653  InitializedEntity BaseEntity =
4654  InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4656  InitList ? InitializationKind::CreateDirectList(BaseLoc)
4657  : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4658  InitRange.getEnd());
4659  InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4660  ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4661  if (!BaseInit.isInvalid()) {
4662  // C++11 [class.base.init]p7:
4663  // The initialization of each base and member constitutes a
4664  // full-expression.
4665  BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4666  /*DiscardedValue*/ false);
4667  }
4668 
4669  if (BaseInit.isInvalid()) {
4670  BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(),
4671  Args, BaseType);
4672  if (BaseInit.isInvalid())
4673  return true;
4674  } else {
4675  // If we are in a dependent context, template instantiation will
4676  // perform this type-checking again. Just save the arguments that we
4677  // received in a ParenListExpr.
4678  // FIXME: This isn't quite ideal, since our ASTs don't capture all
4679  // of the information that we have about the base
4680  // initializer. However, deconstructing the ASTs is a dicey process,
4681  // and this approach is far more likely to get the corner cases right.
4683  BaseInit = Init;
4684  }
4685 
4686  return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4687  BaseSpec->isVirtual(),
4688  InitRange.getBegin(),
4689  BaseInit.getAs<Expr>(),
4690  InitRange.getEnd(), EllipsisLoc);
4691 }
4692 
4693 // Create a static_cast<T&&>(expr).
4694 static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
4695  QualType TargetType =
4696  SemaRef.BuildReferenceType(E->getType(), /*SpelledAsLValue*/ false,
4698  SourceLocation ExprLoc = E->getBeginLoc();
4699  TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4700  TargetType, ExprLoc);
4701 
4702  return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4703  SourceRange(ExprLoc, ExprLoc),
4704  E->getSourceRange()).get();
4705 }
4706 
4707 /// ImplicitInitializerKind - How an implicit base or member initializer should
4708 /// initialize its base or member.
4714 };
4715 
4716 static bool
4718  ImplicitInitializerKind ImplicitInitKind,
4719  CXXBaseSpecifier *BaseSpec,
4720  bool IsInheritedVirtualBase,
4721  CXXCtorInitializer *&CXXBaseInit) {
4722  InitializedEntity InitEntity
4723  = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4724  IsInheritedVirtualBase);
4725 
4726  ExprResult BaseInit;
4727 
4728  switch (ImplicitInitKind) {
4729  case IIK_Inherit:
4730  case IIK_Default: {
4731  InitializationKind InitKind
4732  = InitializationKind::CreateDefault(Constructor->getLocation());
4733  InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4734  BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4735  break;
4736  }
4737 
4738  case IIK_Move:
4739  case IIK_Copy: {
4740  bool Moving = ImplicitInitKind == IIK_Move;
4741  ParmVarDecl *Param = Constructor->getParamDecl(0);
4742  QualType ParamType = Param->getType().getNonReferenceType();
4743 
4744  Expr *CopyCtorArg =
4746  SourceLocation(), Param, false,
4747  Constructor->getLocation(), ParamType,
4748  VK_LValue, nullptr);
4749 
4750  SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4751 
4752  // Cast to the base class to avoid ambiguities.
4753  QualType ArgTy =
4754  SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4755  ParamType.getQualifiers());
4756 
4757  if (Moving) {
4758  CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4759  }
4760 
4761  CXXCastPath BasePath;
4762  BasePath.push_back(BaseSpec);
4763  CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4764  CK_UncheckedDerivedToBase,
4765  Moving ? VK_XValue : VK_LValue,
4766  &BasePath).get();
4767 
4768  InitializationKind InitKind
4769  = InitializationKind::CreateDirect(Constructor->getLocation(),
4771  InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4772  BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4773  break;
4774  }
4775  }
4776 
4777  BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4778  if (BaseInit.isInvalid())
4779  return true;
4780 
4781  CXXBaseInit =
4782  new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4783  SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4784  SourceLocation()),
4785  BaseSpec->isVirtual(),
4786  SourceLocation(),
4787  BaseInit.getAs<Expr>(),
4788  SourceLocation(),
4789  SourceLocation());
4790 
4791  return false;
4792 }
4793 
4794 static bool RefersToRValueRef(Expr *MemRef) {
4795  ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4796  return Referenced->getType()->isRValueReferenceType();
4797 }
4798 
4799 static bool
4801  ImplicitInitializerKind ImplicitInitKind,
4802  FieldDecl *Field, IndirectFieldDecl *Indirect,
4803  CXXCtorInitializer *&CXXMemberInit) {
4804  if (Field->isInvalidDecl())
4805  return true;
4806 
4807  SourceLocation Loc = Constructor->getLocation();
4808 
4809  if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4810  bool Moving = ImplicitInitKind == IIK_Move;
4811  ParmVarDecl *Param = Constructor->getParamDecl(0);
4812  QualType ParamType = Param->getType().getNonReferenceType();
4813 
4814  // Suppress copying zero-width bitfields.
4815  if (Field->isZeroLengthBitField(SemaRef.Context))
4816  return false;
4817 
4818  Expr *MemberExprBase =
4820  SourceLocation(), Param, false,
4821  Loc, ParamType, VK_LValue, nullptr);
4822 
4823  SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4824 
4825  if (Moving) {
4826  MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4827  }
4828 
4829  // Build a reference to this field within the parameter.
4830  CXXScopeSpec SS;
4831  LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4833  MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4834  : cast<ValueDecl>(Field), AS_public);
4835  MemberLookup.resolveKind();
4836  ExprResult CtorArg
4837  = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4838  ParamType, Loc,
4839  /*IsArrow=*/false,
4840  SS,
4841  /*TemplateKWLoc=*/SourceLocation(),
4842  /*FirstQualifierInScope=*/nullptr,
4843  MemberLookup,
4844  /*TemplateArgs=*/nullptr,
4845  /*S*/nullptr);
4846  if (CtorArg.isInvalid())
4847  return true;
4848 
4849  // C++11 [class.copy]p15:
4850  // - if a member m has rvalue reference type T&&, it is direct-initialized
4851  // with static_cast<T&&>(x.m);
4852  if (RefersToRValueRef(CtorArg.get())) {
4853  CtorArg = CastForMoving(SemaRef, CtorArg.get());
4854  }
4855 
4856  InitializedEntity Entity =
4857  Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4858  /*Implicit*/ true)
4859  : InitializedEntity::InitializeMember(Field, nullptr,
4860  /*Implicit*/ true);
4861 
4862  // Direct-initialize to use the copy constructor.
4863  InitializationKind InitKind =
4865 
4866  Expr *CtorArgE = CtorArg.getAs<Expr>();
4867  InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4868  ExprResult MemberInit =
4869  InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4870  MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4871  if (MemberInit.isInvalid())
4872  return true;
4873 
4874  if (Indirect)
4875  CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4876  SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4877  else
4878  CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4879  SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4880  return false;
4881  }
4882 
4883  assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4884  "Unhandled implicit init kind!");
4885 
4886  QualType FieldBaseElementType =
4887  SemaRef.Context.getBaseElementType(Field->getType());
4888 
4889  if (FieldBaseElementType->isRecordType()) {
4890  InitializedEntity InitEntity =
4891  Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4892  /*Implicit*/ true)
4893  : InitializedEntity::InitializeMember(Field, nullptr,
4894  /*Implicit*/ true);
4895  InitializationKind InitKind =
4897 
4898  InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4899  ExprResult MemberInit =
4900  InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4901 
4902  MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4903  if (MemberInit.isInvalid())
4904  return true;
4905 
4906  if (Indirect)
4907  CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4908  Indirect, Loc,
4909  Loc,
4910  MemberInit.get(),
4911  Loc);
4912  else
4913  CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4914  Field, Loc, Loc,
4915  MemberInit.get(),
4916  Loc);
4917  return false;
4918  }
4919 
4920  if (!Field->getParent()->isUnion()) {
4921  if (FieldBaseElementType->isReferenceType()) {
4922  SemaRef.Diag(Constructor->getLocation(),
4923  diag::err_uninitialized_member_in_ctor)
4924  << (int)Constructor->isImplicit()
4925  << SemaRef.Context.getTagDeclType(Constructor->getParent())
4926  << 0 << Field->getDeclName();
4927  SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4928  return true;
4929  }
4930 
4931  if (FieldBaseElementType.isConstQualified()) {
4932  SemaRef.Diag(Constructor->getLocation(),
4933  diag::err_uninitialized_member_in_ctor)
4934  << (int)Constructor->isImplicit()
4935  << SemaRef.Context.getTagDeclType(Constructor->getParent())
4936  << 1 << Field->getDeclName();
4937  SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4938  return true;
4939  }
4940  }
4941 
4942  if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4943  // ARC and Weak:
4944  // Default-initialize Objective-C pointers to NULL.
4945  CXXMemberInit
4946  = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4947  Loc, Loc,
4948  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4949  Loc);
4950  return false;
4951  }
4952 
4953  // Nothing to initialize.
4954  CXXMemberInit = nullptr;
4955  return false;
4956 }
4957 
4958 namespace {
4959 struct BaseAndFieldInfo {
4960  Sema &S;
4961  CXXConstructorDecl *Ctor;
4962  bool AnyErrorsInInits;
4964  llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4966  llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4967 
4968  BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4969  : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4970  bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4971  if (Ctor->getInheritedConstructor())
4972  IIK = IIK_Inherit;
4973  else if (Generated && Ctor->isCopyConstructor())
4974  IIK = IIK_Copy;
4975  else if (Generated && Ctor->isMoveConstructor())
4976  IIK = IIK_Move;
4977  else
4978  IIK = IIK_Default;
4979  }
4980 
4981  bool isImplicitCopyOrMove() const {
4982  switch (IIK) {
4983  case IIK_Copy:
4984  case IIK_Move:
4985  return true;
4986 
4987  case IIK_Default:
4988  case IIK_Inherit:
4989  return false;
4990  }
4991 
4992  llvm_unreachable("Invalid ImplicitInitializerKind!");
4993  }
4994 
4995  bool addFieldInitializer(CXXCtorInitializer *Init) {
4996  AllToInit.push_back(Init);
4997 
4998  // Check whether this initializer makes the field "used".
4999  if (Init->getInit()->HasSideEffects(S.Context))
5000  S.UnusedPrivateFields.remove(Init->getAnyMember());
5001 
5002  return false;
5003  }
5004 
5005  bool isInactiveUnionMember(FieldDecl *Field) {
5006  RecordDecl *Record = Field->getParent();
5007  if (!Record->isUnion())
5008  return false;
5009 
5010  if (FieldDecl *Active =
5011  ActiveUnionMember.lookup(Record->getCanonicalDecl()))
5012  return Active != Field->getCanonicalDecl();
5013 
5014  // In an implicit copy or move constructor, ignore any in-class initializer.
5015  if (isImplicitCopyOrMove())
5016  return true;
5017 
5018  // If there's no explicit initialization, the field is active only if it
5019  // has an in-class initializer...
5020  if (Field->hasInClassInitializer())
5021  return false;
5022  // ... or it's an anonymous struct or union whose class has an in-class
5023  // initializer.
5024  if (!Field->isAnonymousStructOrUnion())
5025  return true;
5026  CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
5027  return !FieldRD->hasInClassInitializer();
5028  }
5029 
5030  /// Determine whether the given field is, or is within, a union member
5031  /// that is inactive (because there was an initializer given for a different
5032  /// member of the union, or because the union was not initialized at all).
5033  bool isWithinInactiveUnionMember(FieldDecl *Field,
5034  IndirectFieldDecl *Indirect) {
5035  if (!Indirect)
5036  return isInactiveUnionMember(Field);
5037 
5038  for (auto *C : Indirect->chain()) {
5039  FieldDecl *Field = dyn_cast<FieldDecl>(C);
5040  if (Field && isInactiveUnionMember(Field))
5041  return true;
5042  }
5043  return false;
5044  }
5045 };
5046 }
5047 
5048 /// Determine whether the given type is an incomplete or zero-lenfgth
5049 /// array type.
5051  if (T->isIncompleteArrayType())
5052  return true;
5053 
5054  while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
5055  if (!ArrayT->getSize())
5056  return true;
5057 
5058  T = ArrayT->getElementType();
5059  }
5060 
5061  return false;
5062 }
5063 
5064 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
5065  FieldDecl *Field,
5066  IndirectFieldDecl *Indirect = nullptr) {
5067  if (Field->isInvalidDecl())
5068  return false;
5069 
5070  // Overwhelmingly common case: we have a direct initializer for this field.
5071  if (CXXCtorInitializer *Init =
5072  Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
5073  return Info.addFieldInitializer(Init);
5074 
5075  // C++11 [class.base.init]p8:
5076  // if the entity is a non-static data member that has a
5077  // brace-or-equal-initializer and either
5078  // -- the constructor's class is a union and no other variant member of that
5079  // union is designated by a mem-initializer-id or
5080  // -- the constructor's class is not a union, and, if the entity is a member
5081  // of an anonymous union, no other member of that union is designated by
5082  // a mem-initializer-id,
5083  // the entity is initialized as specified in [dcl.init].
5084  //
5085  // We also apply the same rules to handle anonymous structs within anonymous
5086  // unions.
5087  if (Info.isWithinInactiveUnionMember(Field, Indirect))
5088  return false;
5089 
5090  if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
5091  ExprResult DIE =
5092  SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
5093  if (DIE.isInvalid())
5094  return true;
5095 
5096  auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
5097  SemaRef.checkInitializerLifetime(Entity, DIE.get());
5098 
5099  CXXCtorInitializer *Init;
5100  if (Indirect)
5101  Init = new (SemaRef.Context)
5102  CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
5103  SourceLocation(), DIE.get(), SourceLocation());
5104  else
5105  Init = new (SemaRef.Context)
5106  CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
5107  SourceLocation(), DIE.get(), SourceLocation());
5108  return Info.addFieldInitializer(Init);
5109  }
5110 
5111  // Don't initialize incomplete or zero-length arrays.
5112  if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
5113  return false;
5114 
5115  // Don't try to build an implicit initializer if there were semantic
5116  // errors in any of the initializers (and therefore we might be
5117  // missing some that the user actually wrote).
5118  if (Info.AnyErrorsInInits)
5119  return false;
5120 
5121  CXXCtorInitializer *Init = nullptr;
5122  if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
5123  Indirect, Init))
5124  return true;
5125 
5126  if (!Init)
5127  return false;
5128 
5129  return Info.addFieldInitializer(Init);
5130 }
5131 
5132 bool
5134  CXXCtorInitializer *Initializer) {
5135  assert(Initializer->isDelegatingInitializer());
5136  Constructor->setNumCtorInitializers(1);
5137  CXXCtorInitializer **initializer =
5138  new (Context) CXXCtorInitializer*[1];
5139  memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
5140  Constructor->setCtorInitializers(initializer);
5141 
5142  if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
5143  MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5144  DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5145  }
5146 
5147  DelegatingCtorDecls.push_back(Constructor);
5148 
5149  DiagnoseUninitializedFields(*this, Constructor);
5150 
5151  return false;
5152 }
5153 
5154 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5155  ArrayRef<CXXCtorInitializer *> Initializers) {
5156  if (Constructor->isDependentContext()) {
5157  // Just store the initializers as written, they will be checked during
5158  // instantiation.
5159  if (!Initializers.empty()) {
5160  Constructor->setNumCtorInitializers(Initializers.size());
5161  CXXCtorInitializer **baseOrMemberInitializers =
5162  new (Context) CXXCtorInitializer*[Initializers.size()];
5163  memcpy(baseOrMemberInitializers, Initializers.data(),
5164  Initializers.size() * sizeof(CXXCtorInitializer*));
5165  Constructor->setCtorInitializers(baseOrMemberInitializers);
5166  }
5167 
5168  // Let template instantiation know whether we had errors.
5169  if (AnyErrors)
5170  Constructor->setInvalidDecl();
5171 
5172  return false;
5173  }
5174 
5175  BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5176 
5177  // We need to build the initializer AST according to order of construction
5178  // and not what user specified in the Initializers list.
5179  CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5180  if (!ClassDecl)
5181  return true;
5182 
5183  bool HadError = false;
5184 
5185  for (unsigned i = 0; i < Initializers.size(); i++) {
5186  CXXCtorInitializer *Member = Initializers[i];
5187 
5188  if (Member->isBaseInitializer())
5189  Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
5190  else {
5191  Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5192 
5193  if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5194  for (auto *C : F->chain()) {
5195  FieldDecl *FD = dyn_cast<FieldDecl>(C);
5196  if (FD && FD->getParent()->isUnion())
5197  Info.ActiveUnionMember.insert(std::make_pair(
5198  FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5199  }
5200  } else if (FieldDecl *FD = Member->getMember()) {
5201  if (FD->getParent()->isUnion())
5202  Info.ActiveUnionMember.insert(std::make_pair(
5203  FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5204  }
5205  }
5206  }
5207 
5208  // Keep track of the direct virtual bases.
5210  for (auto &I : ClassDecl->bases()) {
5211  if (I.isVirtual())
5212  DirectVBases.insert(&I);
5213  }
5214 
5215  // Push virtual bases before others.
5216  for (auto &VBase : ClassDecl->vbases()) {
5218  = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
5219  // [class.base.init]p7, per DR257:
5220  // A mem-initializer where the mem-initializer-id names a virtual base
5221  // class is ignored during execution of a constructor of any class that
5222  // is not the most derived class.
5223  if (ClassDecl->isAbstract()) {
5224  // FIXME: Provide a fixit to remove the base specifier. This requires
5225  // tracking the location of the associated comma for a base specifier.
5226  Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5227  << VBase.getType() << ClassDecl;
5228  DiagnoseAbstractType(ClassDecl);
5229  }
5230 
5231  Info.AllToInit.push_back(Value);
5232  } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5233  // [class.base.init]p8, per DR257:
5234  // If a given [...] base class is not named by a mem-initializer-id
5235  // [...] and the entity is not a virtual base class of an abstract
5236  // class, then [...] the entity is default-initialized.
5237  bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5238  CXXCtorInitializer *CXXBaseInit;
5239  if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5240  &VBase, IsInheritedVirtualBase,
5241  CXXBaseInit)) {
5242  HadError = true;
5243  continue;
5244  }
5245 
5246  Info.AllToInit.push_back(CXXBaseInit);
5247  }
5248  }
5249 
5250  // Non-virtual bases.
5251  for (auto &Base : ClassDecl->bases()) {
5252  // Virtuals are in the virtual base list and already constructed.
5253  if (Base.isVirtual())
5254  continue;
5255 
5257  = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
5258  Info.AllToInit.push_back(Value);
5259  } else if (!AnyErrors) {
5260  CXXCtorInitializer *CXXBaseInit;
5261  if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5262  &Base, /*IsInheritedVirtualBase=*/false,
5263  CXXBaseInit)) {
5264  HadError = true;
5265  continue;
5266  }
5267 
5268  Info.AllToInit.push_back(CXXBaseInit);
5269  }
5270  }
5271 
5272  // Fields.
5273  for (auto *Mem : ClassDecl->decls()) {
5274  if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5275  // C++ [class.bit]p2:
5276  // A declaration for a bit-field that omits the identifier declares an
5277  // unnamed bit-field. Unnamed bit-fields are not members and cannot be
5278  // initialized.
5279  if (F->isUnnamedBitfield())
5280  continue;
5281 
5282  // If we're not generating the implicit copy/move constructor, then we'll
5283  // handle anonymous struct/union fields based on their individual
5284  // indirect fields.
5285  if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5286  continue;
5287 
5288  if (CollectFieldInitializer(*this, Info, F))
5289  HadError = true;
5290  continue;
5291  }
5292 
5293  // Beyond this point, we only consider default initialization.
5294  if (Info.isImplicitCopyOrMove())
5295  continue;
5296 
5297  if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5298  if (F->getType()->isIncompleteArrayType()) {
5299  assert(ClassDecl->hasFlexibleArrayMember() &&
5300  "Incomplete array type is not valid");
5301  continue;
5302  }
5303 
5304  // Initialize each field of an anonymous struct individually.
5305  if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5306  HadError = true;
5307 
5308  continue;
5309  }
5310  }
5311 
5312  unsigned NumInitializers = Info.AllToInit.size();
5313  if (NumInitializers > 0) {
5314  Constructor->setNumCtorInitializers(NumInitializers);
5315  CXXCtorInitializer **baseOrMemberInitializers =
5316  new (Context) CXXCtorInitializer*[NumInitializers];
5317  memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5318  NumInitializers * sizeof(CXXCtorInitializer*));
5319  Constructor->setCtorInitializers(baseOrMemberInitializers);
5320 
5321  // Constructors implicitly reference the base and member
5322  // destructors.
5323  MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
5324  Constructor->getParent());
5325  }
5326 
5327  return HadError;
5328 }
5329 
5331  if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5332  const RecordDecl *RD = RT->getDecl();
5333  if (RD->isAnonymousStructOrUnion()) {
5334  for (auto *Field : RD->fields())
5335  PopulateKeysForFields(Field, IdealInits);
5336  return;
5337  }
5338  }
5339  IdealInits.push_back(Field->getCanonicalDecl());
5340 }
5341 
5342 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5343  return Context.getCanonicalType(BaseType).getTypePtr();
5344 }
5345 
5346 static const void *GetKeyForMember(ASTContext &Context,
5347  CXXCtorInitializer *Member) {
5348  if (!Member->isAnyMemberInitializer())
5349  return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5350 
5351  return Member->getAnyMember()->getCanonicalDecl();
5352 }
5353 
5356  const CXXCtorInitializer *Current) {
5357  if (Previous->isAnyMemberInitializer())
5358  Diag << 0 << Previous->getAnyMember();
5359  else
5360  Diag << 1 << Previous->getTypeSourceInfo()->getType();
5361 
5362  if (Current->isAnyMemberInitializer())
5363  Diag << 0 << Current->getAnyMember();
5364  else
5365  Diag << 1 << Current->getTypeSourceInfo()->getType();
5366 }
5367 
5369  Sema &SemaRef, const CXXConstructorDecl *Constructor,
5371  if (Constructor->getDeclContext()->isDependentContext())
5372  return;
5373 
5374  // Don't check initializers order unless the warning is enabled at the
5375  // location of at least one initializer.
5376  bool ShouldCheckOrder = false;
5377  for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5378  CXXCtorInitializer *Init = Inits[InitIndex];
5379  if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5380  Init->getSourceLocation())) {
5381  ShouldCheckOrder = true;
5382  break;
5383  }
5384  }
5385  if (!ShouldCheckOrder)
5386  return;
5387 
5388  // Build the list of bases and members in the order that they'll
5389  // actually be initialized. The explicit initializers should be in
5390  // this same order but may be missing things.
5391  SmallVector<const void*, 32> IdealInitKeys;
5392 
5393  const CXXRecordDecl *ClassDecl = Constructor->getParent();
5394 
5395  // 1. Virtual bases.
5396  for (const auto &VBase : ClassDecl->vbases())
5397  IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5398 
5399  // 2. Non-virtual bases.
5400  for (const auto &Base : ClassDecl->bases()) {
5401  if (Base.isVirtual())
5402  continue;
5403  IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5404  }
5405 
5406  // 3. Direct fields.
5407  for (auto *Field : ClassDecl->fields()) {
5408  if (Field->isUnnamedBitfield())
5409  continue;
5410 
5411  PopulateKeysForFields(Field, IdealInitKeys);
5412  }
5413 
5414  unsigned NumIdealInits = IdealInitKeys.size();
5415  unsigned IdealIndex = 0;
5416 
5417  // Track initializers that are in an incorrect order for either a warning or
5418  // note if multiple ones occur.
5419  SmallVector<unsigned> WarnIndexes;
5420  // Correlates the index of an initializer in the init-list to the index of
5421  // the field/base in the class.
5422  SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5423 
5424  for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5425  const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]);
5426 
5427  // Scan forward to try to find this initializer in the idealized
5428  // initializers list.
5429  for (; IdealIndex != NumIdealInits; ++IdealIndex)
5430  if (InitKey == IdealInitKeys[IdealIndex])
5431  break;
5432 
5433  // If we didn't find this initializer, it must be because we
5434  // scanned past it on a previous iteration. That can only
5435  // happen if we're out of order; emit a warning.
5436  if (IdealIndex == NumIdealInits && InitIndex) {
5437  WarnIndexes.push_back(InitIndex);
5438 
5439  // Move back to the initializer's location in the ideal list.
5440  for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIn