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