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