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