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