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