clang  8.0.0
SemaDeclCXX.cpp
Go to the documentation of this file.
1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements semantic analysis for C++ declarations.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
19 #include "clang/AST/CharUnits.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/RecordLayout.h"
25 #include "clang/AST/StmtVisitor.h"
26 #include "clang/AST/TypeLoc.h"
27 #include "clang/AST/TypeOrdering.h"
29 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/Preprocessor.h"
33 #include "clang/Sema/DeclSpec.h"
35 #include "clang/Sema/Lookup.h"
37 #include "clang/Sema/Scope.h"
38 #include "clang/Sema/ScopeInfo.h"
40 #include "clang/Sema/Template.h"
41 #include "llvm/ADT/STLExtras.h"
42 #include "llvm/ADT/SmallString.h"
43 #include "llvm/ADT/StringExtras.h"
44 #include <map>
45 #include <set>
46 
47 using namespace clang;
48 
49 //===----------------------------------------------------------------------===//
50 // CheckDefaultArgumentVisitor
51 //===----------------------------------------------------------------------===//
52 
53 namespace {
54  /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
55  /// the default argument of a parameter to determine whether it
56  /// contains any ill-formed subexpressions. For example, this will
57  /// diagnose the use of local variables or parameters within the
58  /// default argument expression.
59  class CheckDefaultArgumentVisitor
60  : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
61  Expr *DefaultArg;
62  Sema *S;
63 
64  public:
65  CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
66  : DefaultArg(defarg), S(s) {}
67 
68  bool VisitExpr(Expr *Node);
69  bool VisitDeclRefExpr(DeclRefExpr *DRE);
70  bool VisitCXXThisExpr(CXXThisExpr *ThisE);
71  bool VisitLambdaExpr(LambdaExpr *Lambda);
72  bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
73  };
74 
75  /// VisitExpr - Visit all of the children of this expression.
76  bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
77  bool IsInvalid = false;
78  for (Stmt *SubStmt : Node->children())
79  IsInvalid |= Visit(SubStmt);
80  return IsInvalid;
81  }
82 
83  /// VisitDeclRefExpr - Visit a reference to a declaration, to
84  /// determine whether this declaration can be used in the default
85  /// argument expression.
86  bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
87  NamedDecl *Decl = DRE->getDecl();
88  if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
89  // C++ [dcl.fct.default]p9
90  // Default arguments are evaluated each time the function is
91  // called. The order of evaluation of function arguments is
92  // unspecified. Consequently, parameters of a function shall not
93  // be used in default argument expressions, even if they are not
94  // evaluated. Parameters of a function declared before a default
95  // argument expression are in scope and can hide namespace and
96  // class member names.
97  return S->Diag(DRE->getBeginLoc(),
98  diag::err_param_default_argument_references_param)
99  << Param->getDeclName() << DefaultArg->getSourceRange();
100  } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
101  // C++ [dcl.fct.default]p7
102  // Local variables shall not be used in default argument
103  // expressions.
104  if (VDecl->isLocalVarDecl())
105  return S->Diag(DRE->getBeginLoc(),
106  diag::err_param_default_argument_references_local)
107  << VDecl->getDeclName() << DefaultArg->getSourceRange();
108  }
109 
110  return false;
111  }
112 
113  /// VisitCXXThisExpr - Visit a C++ "this" expression.
114  bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
115  // C++ [dcl.fct.default]p8:
116  // The keyword this shall not be used in a default argument of a
117  // member function.
118  return S->Diag(ThisE->getBeginLoc(),
119  diag::err_param_default_argument_references_this)
120  << ThisE->getSourceRange();
121  }
122 
123  bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
124  bool Invalid = false;
126  i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
127  Expr *E = *i;
128 
129  // Look through bindings.
130  if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
131  E = OVE->getSourceExpr();
132  assert(E && "pseudo-object binding without source expression?");
133  }
134 
135  Invalid |= Visit(E);
136  }
137  return Invalid;
138  }
139 
140  bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
141  // C++11 [expr.lambda.prim]p13:
142  // A lambda-expression appearing in a default argument shall not
143  // implicitly or explicitly capture any entity.
144  if (Lambda->capture_begin() == Lambda->capture_end())
145  return false;
146 
147  return S->Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg);
148  }
149 }
150 
151 void
153  const CXXMethodDecl *Method) {
154  // If we have an MSAny spec already, don't bother.
155  if (!Method || ComputedEST == EST_MSAny)
156  return;
157 
158  const FunctionProtoType *Proto
159  = Method->getType()->getAs<FunctionProtoType>();
160  Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
161  if (!Proto)
162  return;
163 
165 
166  // If we have a throw-all spec at this point, ignore the function.
167  if (ComputedEST == EST_None)
168  return;
169 
170  if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
171  EST = EST_BasicNoexcept;
172 
173  switch (EST) {
174  case EST_Unparsed:
175  case EST_Uninstantiated:
176  case EST_Unevaluated:
177  llvm_unreachable("should not see unresolved exception specs here");
178 
179  // If this function can throw any exceptions, make a note of that.
180  case EST_MSAny:
181  case EST_None:
182  // FIXME: Whichever we see last of MSAny and None determines our result.
183  // We should make a consistent, order-independent choice here.
184  ClearExceptions();
185  ComputedEST = EST;
186  return;
187  case EST_NoexceptFalse:
188  ClearExceptions();
189  ComputedEST = EST_None;
190  return;
191  // FIXME: If the call to this decl is using any of its default arguments, we
192  // need to search them for potentially-throwing calls.
193  // If this function has a basic noexcept, it doesn't affect the outcome.
194  case EST_BasicNoexcept:
195  case EST_NoexceptTrue:
196  return;
197  // If we're still at noexcept(true) and there's a throw() callee,
198  // change to that specification.
199  case EST_DynamicNone:
200  if (ComputedEST == EST_BasicNoexcept)
201  ComputedEST = EST_DynamicNone;
202  return;
204  llvm_unreachable(
205  "should not generate implicit declarations for dependent cases");
206  case EST_Dynamic:
207  break;
208  }
209  assert(EST == EST_Dynamic && "EST case not considered earlier.");
210  assert(ComputedEST != EST_None &&
211  "Shouldn't collect exceptions when throw-all is guaranteed.");
212  ComputedEST = EST_Dynamic;
213  // Record the exceptions in this function's exception specification.
214  for (const auto &E : Proto->exceptions())
215  if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
216  Exceptions.push_back(E);
217 }
218 
220  if (!E || ComputedEST == EST_MSAny)
221  return;
222 
223  // FIXME:
224  //
225  // C++0x [except.spec]p14:
226  // [An] implicit exception-specification specifies the type-id T if and
227  // only if T is allowed by the exception-specification of a function directly
228  // invoked by f's implicit definition; f shall allow all exceptions if any
229  // function it directly invokes allows all exceptions, and f shall allow no
230  // exceptions if every function it directly invokes allows no exceptions.
231  //
232  // Note in particular that if an implicit exception-specification is generated
233  // for a function containing a throw-expression, that specification can still
234  // be noexcept(true).
235  //
236  // Note also that 'directly invoked' is not defined in the standard, and there
237  // is no indication that we should only consider potentially-evaluated calls.
238  //
239  // Ultimately we should implement the intent of the standard: the exception
240  // specification should be the set of exceptions which can be thrown by the
241  // implicit definition. For now, we assume that any non-nothrow expression can
242  // throw any exception.
243 
244  if (Self->canThrow(E))
245  ComputedEST = EST_None;
246 }
247 
248 bool
250  SourceLocation EqualLoc) {
251  if (RequireCompleteType(Param->getLocation(), Param->getType(),
252  diag::err_typecheck_decl_incomplete_type)) {
253  Param->setInvalidDecl();
254  return true;
255  }
256 
257  // C++ [dcl.fct.default]p5
258  // A default argument expression is implicitly converted (clause
259  // 4) to the parameter type. The default argument expression has
260  // the same semantic constraints as the initializer expression in
261  // a declaration of a variable of the parameter type, using the
262  // copy-initialization semantics (8.5).
264  Param);
266  EqualLoc);
267  InitializationSequence InitSeq(*this, Entity, Kind, Arg);
268  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
269  if (Result.isInvalid())
270  return true;
271  Arg = Result.getAs<Expr>();
272 
273  CheckCompletedExpr(Arg, EqualLoc);
274  Arg = MaybeCreateExprWithCleanups(Arg);
275 
276  // Okay: add the default argument to the parameter
277  Param->setDefaultArg(Arg);
278 
279  // We have already instantiated this parameter; provide each of the
280  // instantiations with the uninstantiated default argument.
281  UnparsedDefaultArgInstantiationsMap::iterator InstPos
282  = UnparsedDefaultArgInstantiations.find(Param);
283  if (InstPos != UnparsedDefaultArgInstantiations.end()) {
284  for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
285  InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
286 
287  // We're done tracking this parameter's instantiations.
288  UnparsedDefaultArgInstantiations.erase(InstPos);
289  }
290 
291  return false;
292 }
293 
294 /// ActOnParamDefaultArgument - Check whether the default argument
295 /// provided for a function parameter is well-formed. If so, attach it
296 /// to the parameter declaration.
297 void
299  Expr *DefaultArg) {
300  if (!param || !DefaultArg)
301  return;
302 
303  ParmVarDecl *Param = cast<ParmVarDecl>(param);
304  UnparsedDefaultArgLocs.erase(Param);
305 
306  // Default arguments are only permitted in C++
307  if (!getLangOpts().CPlusPlus) {
308  Diag(EqualLoc, diag::err_param_default_argument)
309  << DefaultArg->getSourceRange();
310  Param->setInvalidDecl();
311  return;
312  }
313 
314  // Check for unexpanded parameter packs.
315  if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
316  Param->setInvalidDecl();
317  return;
318  }
319 
320  // C++11 [dcl.fct.default]p3
321  // A default argument expression [...] shall not be specified for a
322  // parameter pack.
323  if (Param->isParameterPack()) {
324  Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
325  << DefaultArg->getSourceRange();
326  return;
327  }
328 
329  // Check that the default argument is well-formed
330  CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
331  if (DefaultArgChecker.Visit(DefaultArg)) {
332  Param->setInvalidDecl();
333  return;
334  }
335 
336  SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
337 }
338 
339 /// ActOnParamUnparsedDefaultArgument - We've seen a default
340 /// argument for a function parameter, but we can't parse it yet
341 /// because we're inside a class definition. Note that this default
342 /// argument will be parsed later.
344  SourceLocation EqualLoc,
345  SourceLocation ArgLoc) {
346  if (!param)
347  return;
348 
349  ParmVarDecl *Param = cast<ParmVarDecl>(param);
350  Param->setUnparsedDefaultArg();
351  UnparsedDefaultArgLocs[Param] = ArgLoc;
352 }
353 
354 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
355 /// the default argument for the parameter param failed.
357  SourceLocation EqualLoc) {
358  if (!param)
359  return;
360 
361  ParmVarDecl *Param = cast<ParmVarDecl>(param);
362  Param->setInvalidDecl();
363  UnparsedDefaultArgLocs.erase(Param);
364  Param->setDefaultArg(new(Context)
365  OpaqueValueExpr(EqualLoc,
366  Param->getType().getNonReferenceType(),
367  VK_RValue));
368 }
369 
370 /// CheckExtraCXXDefaultArguments - Check for any extra default
371 /// arguments in the declarator, which is not a function declaration
372 /// or definition and therefore is not permitted to have default
373 /// arguments. This routine should be invoked for every declarator
374 /// that is not a function declaration or definition.
376  // C++ [dcl.fct.default]p3
377  // A default argument expression shall be specified only in the
378  // parameter-declaration-clause of a function declaration or in a
379  // template-parameter (14.1). It shall not be specified for a
380  // parameter pack. If it is specified in a
381  // parameter-declaration-clause, it shall not occur within a
382  // declarator or abstract-declarator of a parameter-declaration.
383  bool MightBeFunction = D.isFunctionDeclarationContext();
384  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
385  DeclaratorChunk &chunk = D.getTypeObject(i);
386  if (chunk.Kind == DeclaratorChunk::Function) {
387  if (MightBeFunction) {
388  // This is a function declaration. It can have default arguments, but
389  // keep looking in case its return type is a function type with default
390  // arguments.
391  MightBeFunction = false;
392  continue;
393  }
394  for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
395  ++argIdx) {
396  ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
397  if (Param->hasUnparsedDefaultArg()) {
398  std::unique_ptr<CachedTokens> Toks =
399  std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
400  SourceRange SR;
401  if (Toks->size() > 1)
402  SR = SourceRange((*Toks)[1].getLocation(),
403  Toks->back().getLocation());
404  else
405  SR = UnparsedDefaultArgLocs[Param];
406  Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
407  << SR;
408  } else if (Param->getDefaultArg()) {
409  Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
410  << Param->getDefaultArg()->getSourceRange();
411  Param->setDefaultArg(nullptr);
412  }
413  }
414  } else if (chunk.Kind != DeclaratorChunk::Paren) {
415  MightBeFunction = false;
416  }
417  }
418 }
419 
421  for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
422  const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
423  if (!PVD->hasDefaultArg())
424  return false;
425  if (!PVD->hasInheritedDefaultArg())
426  return true;
427  }
428  return false;
429 }
430 
431 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
432 /// function, once we already know that they have the same
433 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
434 /// error, false otherwise.
436  Scope *S) {
437  bool Invalid = false;
438 
439  // The declaration context corresponding to the scope is the semantic
440  // parent, unless this is a local function declaration, in which case
441  // it is that surrounding function.
442  DeclContext *ScopeDC = New->isLocalExternDecl()
443  ? New->getLexicalDeclContext()
444  : New->getDeclContext();
445 
446  // Find the previous declaration for the purpose of default arguments.
447  FunctionDecl *PrevForDefaultArgs = Old;
448  for (/**/; PrevForDefaultArgs;
449  // Don't bother looking back past the latest decl if this is a local
450  // extern declaration; nothing else could work.
451  PrevForDefaultArgs = New->isLocalExternDecl()
452  ? nullptr
453  : PrevForDefaultArgs->getPreviousDecl()) {
454  // Ignore hidden declarations.
455  if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
456  continue;
457 
458  if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
459  !New->isCXXClassMember()) {
460  // Ignore default arguments of old decl if they are not in
461  // the same scope and this is not an out-of-line definition of
462  // a member function.
463  continue;
464  }
465 
466  if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
467  // If only one of these is a local function declaration, then they are
468  // declared in different scopes, even though isDeclInScope may think
469  // they're in the same scope. (If both are local, the scope check is
470  // sufficient, and if neither is local, then they are in the same scope.)
471  continue;
472  }
473 
474  // We found the right previous declaration.
475  break;
476  }
477 
478  // C++ [dcl.fct.default]p4:
479  // For non-template functions, default arguments can be added in
480  // later declarations of a function in the same
481  // scope. Declarations in different scopes have completely
482  // distinct sets of default arguments. That is, declarations in
483  // inner scopes do not acquire default arguments from
484  // declarations in outer scopes, and vice versa. In a given
485  // function declaration, all parameters subsequent to a
486  // parameter with a default argument shall have default
487  // arguments supplied in this or previous declarations. A
488  // default argument shall not be redefined by a later
489  // declaration (not even to the same value).
490  //
491  // C++ [dcl.fct.default]p6:
492  // Except for member functions of class templates, the default arguments
493  // in a member function definition that appears outside of the class
494  // definition are added to the set of default arguments provided by the
495  // member function declaration in the class definition.
496  for (unsigned p = 0, NumParams = PrevForDefaultArgs
497  ? PrevForDefaultArgs->getNumParams()
498  : 0;
499  p < NumParams; ++p) {
500  ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
501  ParmVarDecl *NewParam = New->getParamDecl(p);
502 
503  bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
504  bool NewParamHasDfl = NewParam->hasDefaultArg();
505 
506  if (OldParamHasDfl && NewParamHasDfl) {
507  unsigned DiagDefaultParamID =
508  diag::err_param_default_argument_redefinition;
509 
510  // MSVC accepts that default parameters be redefined for member functions
511  // of template class. The new default parameter's value is ignored.
512  Invalid = true;
513  if (getLangOpts().MicrosoftExt) {
514  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
515  if (MD && MD->getParent()->getDescribedClassTemplate()) {
516  // Merge the old default argument into the new parameter.
517  NewParam->setHasInheritedDefaultArg();
518  if (OldParam->hasUninstantiatedDefaultArg())
519  NewParam->setUninstantiatedDefaultArg(
520  OldParam->getUninstantiatedDefaultArg());
521  else
522  NewParam->setDefaultArg(OldParam->getInit());
523  DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
524  Invalid = false;
525  }
526  }
527 
528  // FIXME: If we knew where the '=' was, we could easily provide a fix-it
529  // hint here. Alternatively, we could walk the type-source information
530  // for NewParam to find the last source location in the type... but it
531  // isn't worth the effort right now. This is the kind of test case that
532  // is hard to get right:
533  // int f(int);
534  // void g(int (*fp)(int) = f);
535  // void g(int (*fp)(int) = &f);
536  Diag(NewParam->getLocation(), DiagDefaultParamID)
537  << NewParam->getDefaultArgRange();
538 
539  // Look for the function declaration where the default argument was
540  // actually written, which may be a declaration prior to Old.
541  for (auto Older = PrevForDefaultArgs;
542  OldParam->hasInheritedDefaultArg(); /**/) {
543  Older = Older->getPreviousDecl();
544  OldParam = Older->getParamDecl(p);
545  }
546 
547  Diag(OldParam->getLocation(), diag::note_previous_definition)
548  << OldParam->getDefaultArgRange();
549  } else if (OldParamHasDfl) {
550  // Merge the old default argument into the new parameter unless the new
551  // function is a friend declaration in a template class. In the latter
552  // case the default arguments will be inherited when the friend
553  // declaration will be instantiated.
554  if (New->getFriendObjectKind() == Decl::FOK_None ||
556  // It's important to use getInit() here; getDefaultArg()
557  // strips off any top-level ExprWithCleanups.
558  NewParam->setHasInheritedDefaultArg();
559  if (OldParam->hasUnparsedDefaultArg())
560  NewParam->setUnparsedDefaultArg();
561  else if (OldParam->hasUninstantiatedDefaultArg())
562  NewParam->setUninstantiatedDefaultArg(
563  OldParam->getUninstantiatedDefaultArg());
564  else
565  NewParam->setDefaultArg(OldParam->getInit());
566  }
567  } else if (NewParamHasDfl) {
568  if (New->getDescribedFunctionTemplate()) {
569  // Paragraph 4, quoted above, only applies to non-template functions.
570  Diag(NewParam->getLocation(),
571  diag::err_param_default_argument_template_redecl)
572  << NewParam->getDefaultArgRange();
573  Diag(PrevForDefaultArgs->getLocation(),
574  diag::note_template_prev_declaration)
575  << false;
576  } else if (New->getTemplateSpecializationKind()
579  // C++ [temp.expr.spec]p21:
580  // Default function arguments shall not be specified in a declaration
581  // or a definition for one of the following explicit specializations:
582  // - the explicit specialization of a function template;
583  // - the explicit specialization of a member function template;
584  // - the explicit specialization of a member function of a class
585  // template where the class template specialization to which the
586  // member function specialization belongs is implicitly
587  // instantiated.
588  Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
590  << New->getDeclName()
591  << NewParam->getDefaultArgRange();
592  } else if (New->getDeclContext()->isDependentContext()) {
593  // C++ [dcl.fct.default]p6 (DR217):
594  // Default arguments for a member function of a class template shall
595  // be specified on the initial declaration of the member function
596  // within the class template.
597  //
598  // Reading the tea leaves a bit in DR217 and its reference to DR205
599  // leads me to the conclusion that one cannot add default function
600  // arguments for an out-of-line definition of a member function of a
601  // dependent type.
602  int WhichKind = 2;
603  if (CXXRecordDecl *Record
604  = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
605  if (Record->getDescribedClassTemplate())
606  WhichKind = 0;
607  else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
608  WhichKind = 1;
609  else
610  WhichKind = 2;
611  }
612 
613  Diag(NewParam->getLocation(),
614  diag::err_param_default_argument_member_template_redecl)
615  << WhichKind
616  << NewParam->getDefaultArgRange();
617  }
618  }
619  }
620 
621  // DR1344: If a default argument is added outside a class definition and that
622  // default argument makes the function a special member function, the program
623  // is ill-formed. This can only happen for constructors.
624  if (isa<CXXConstructorDecl>(New) &&
626  CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
627  OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
628  if (NewSM != OldSM) {
629  ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
630  assert(NewParam->hasDefaultArg());
631  Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
632  << NewParam->getDefaultArgRange() << NewSM;
633  Diag(Old->getLocation(), diag::note_previous_declaration);
634  }
635  }
636 
637  const FunctionDecl *Def;
638  // C++11 [dcl.constexpr]p1: If any declaration of a function or function
639  // template has a constexpr specifier then all its declarations shall
640  // contain the constexpr specifier.
641  if (New->isConstexpr() != Old->isConstexpr()) {
642  Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
643  << New << New->isConstexpr();
644  Diag(Old->getLocation(), diag::note_previous_declaration);
645  Invalid = true;
646  } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
647  Old->isDefined(Def) &&
648  // If a friend function is inlined but does not have 'inline'
649  // specifier, it is a definition. Do not report attribute conflict
650  // in this case, redefinition will be diagnosed later.
651  (New->isInlineSpecified() ||
652  New->getFriendObjectKind() == Decl::FOK_None)) {
653  // C++11 [dcl.fcn.spec]p4:
654  // If the definition of a function appears in a translation unit before its
655  // first declaration as inline, the program is ill-formed.
656  Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
657  Diag(Def->getLocation(), diag::note_previous_definition);
658  Invalid = true;
659  }
660 
661  // FIXME: It's not clear what should happen if multiple declarations of a
662  // deduction guide have different explicitness. For now at least we simply
663  // reject any case where the explicitness changes.
664  auto *NewGuide = dyn_cast<CXXDeductionGuideDecl>(New);
665  if (NewGuide && NewGuide->isExplicitSpecified() !=
666  cast<CXXDeductionGuideDecl>(Old)->isExplicitSpecified()) {
667  Diag(New->getLocation(), diag::err_deduction_guide_explicit_mismatch)
668  << NewGuide->isExplicitSpecified();
669  Diag(Old->getLocation(), diag::note_previous_declaration);
670  }
671 
672  // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
673  // argument expression, that declaration shall be a definition and shall be
674  // the only declaration of the function or function template in the
675  // translation unit.
678  Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
679  Diag(Old->getLocation(), diag::note_previous_declaration);
680  Invalid = true;
681  }
682 
683  return Invalid;
684 }
685 
686 NamedDecl *
688  MultiTemplateParamsArg TemplateParamLists) {
689  assert(D.isDecompositionDeclarator());
691 
692  // The syntax only allows a decomposition declarator as a simple-declaration,
693  // a for-range-declaration, or a condition in Clang, but we parse it in more
694  // cases than that.
696  Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
697  << Decomp.getSourceRange();
698  return nullptr;
699  }
700 
701  if (!TemplateParamLists.empty()) {
702  // FIXME: There's no rule against this, but there are also no rules that
703  // would actually make it usable, so we reject it for now.
704  Diag(TemplateParamLists.front()->getTemplateLoc(),
705  diag::err_decomp_decl_template);
706  return nullptr;
707  }
708 
709  Diag(Decomp.getLSquareLoc(),
710  !getLangOpts().CPlusPlus17
711  ? diag::ext_decomp_decl
713  ? diag::ext_decomp_decl_cond
714  : diag::warn_cxx14_compat_decomp_decl)
715  << Decomp.getSourceRange();
716 
717  // The semantic context is always just the current context.
718  DeclContext *const DC = CurContext;
719 
720  // C++1z [dcl.dcl]/8:
721  // The decl-specifier-seq shall contain only the type-specifier auto
722  // and cv-qualifiers.
723  auto &DS = D.getDeclSpec();
724  {
725  SmallVector<StringRef, 8> BadSpecifiers;
726  SmallVector<SourceLocation, 8> BadSpecifierLocs;
727  if (auto SCS = DS.getStorageClassSpec()) {
728  BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
729  BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
730  }
731  if (auto TSCS = DS.getThreadStorageClassSpec()) {
732  BadSpecifiers.push_back(DeclSpec::getSpecifierName(TSCS));
733  BadSpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
734  }
735  if (DS.isConstexprSpecified()) {
736  BadSpecifiers.push_back("constexpr");
737  BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
738  }
739  if (DS.isInlineSpecified()) {
740  BadSpecifiers.push_back("inline");
741  BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
742  }
743  if (!BadSpecifiers.empty()) {
744  auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
745  Err << (int)BadSpecifiers.size()
746  << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
747  // Don't add FixItHints to remove the specifiers; we do still respect
748  // them when building the underlying variable.
749  for (auto Loc : BadSpecifierLocs)
750  Err << SourceRange(Loc, Loc);
751  }
752  // We can't recover from it being declared as a typedef.
753  if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
754  return nullptr;
755  }
756 
757  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
758  QualType R = TInfo->getType();
759 
760  if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
761  UPPC_DeclarationType))
762  D.setInvalidType();
763 
764  // The syntax only allows a single ref-qualifier prior to the decomposition
765  // declarator. No other declarator chunks are permitted. Also check the type
766  // specifier here.
767  if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
768  D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
769  (D.getNumTypeObjects() == 1 &&
771  Diag(Decomp.getLSquareLoc(),
772  (D.hasGroupingParens() ||
773  (D.getNumTypeObjects() &&
775  ? diag::err_decomp_decl_parens
776  : diag::err_decomp_decl_type)
777  << R;
778 
779  // In most cases, there's no actual problem with an explicitly-specified
780  // type, but a function type won't work here, and ActOnVariableDeclarator
781  // shouldn't be called for such a type.
782  if (R->isFunctionType())
783  D.setInvalidType();
784  }
785 
786  // Build the BindingDecls.
788 
789  // Build the BindingDecls.
790  for (auto &B : D.getDecompositionDeclarator().bindings()) {
791  // Check for name conflicts.
792  DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
793  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
794  ForVisibleRedeclaration);
795  LookupName(Previous, S,
796  /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
797 
798  // It's not permitted to shadow a template parameter name.
799  if (Previous.isSingleResult() &&
800  Previous.getFoundDecl()->isTemplateParameter()) {
801  DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
802  Previous.getFoundDecl());
803  Previous.clear();
804  }
805 
806  bool ConsiderLinkage = DC->isFunctionOrMethod() &&
807  DS.getStorageClassSpec() == DeclSpec::SCS_extern;
808  FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
809  /*AllowInlineNamespace*/false);
810  if (!Previous.empty()) {
811  auto *Old = Previous.getRepresentativeDecl();
812  Diag(B.NameLoc, diag::err_redefinition) << B.Name;
813  Diag(Old->getLocation(), diag::note_previous_definition);
814  }
815 
816  auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
817  PushOnScopeChains(BD, S, true);
818  Bindings.push_back(BD);
819  ParsingInitForAutoVars.insert(BD);
820  }
821 
822  // There are no prior lookup results for the variable itself, because it
823  // is unnamed.
824  DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
825  Decomp.getLSquareLoc());
826  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
827  ForVisibleRedeclaration);
828 
829  // Build the variable that holds the non-decomposed object.
830  bool AddToScope = true;
831  NamedDecl *New =
832  ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
833  MultiTemplateParamsArg(), AddToScope, Bindings);
834  if (AddToScope) {
835  S->AddDecl(New);
836  CurContext->addHiddenDecl(New);
837  }
838 
839  if (isInOpenMPDeclareTargetContext())
840  checkDeclIsAllowedInOpenMPTarget(nullptr, New);
841 
842  return New;
843 }
844 
846  Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
847  QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
848  llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
849  if ((int64_t)Bindings.size() != NumElems) {
850  S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
851  << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
852  << (NumElems < Bindings.size());
853  return true;
854  }
855 
856  unsigned I = 0;
857  for (auto *B : Bindings) {
858  SourceLocation Loc = B->getLocation();
859  ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
860  if (E.isInvalid())
861  return true;
862  E = GetInit(Loc, E.get(), I++);
863  if (E.isInvalid())
864  return true;
865  B->setBinding(ElemType, E.get());
866  }
867 
868  return false;
869 }
870 
872  ArrayRef<BindingDecl *> Bindings,
873  ValueDecl *Src, QualType DecompType,
874  const llvm::APSInt &NumElems,
875  QualType ElemType) {
877  S, Bindings, Src, DecompType, NumElems, ElemType,
878  [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
879  ExprResult E = S.ActOnIntegerConstant(Loc, I);
880  if (E.isInvalid())
881  return ExprError();
882  return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
883  });
884 }
885 
887  ValueDecl *Src, QualType DecompType,
888  const ConstantArrayType *CAT) {
889  return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
890  llvm::APSInt(CAT->getSize()),
891  CAT->getElementType());
892 }
893 
895  ValueDecl *Src, QualType DecompType,
896  const VectorType *VT) {
898  S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
900  DecompType.getQualifiers()));
901 }
902 
904  ArrayRef<BindingDecl *> Bindings,
905  ValueDecl *Src, QualType DecompType,
906  const ComplexType *CT) {
908  S, Bindings, Src, DecompType, llvm::APSInt::get(2),
910  DecompType.getQualifiers()),
911  [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
912  return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
913  });
914 }
915 
917  TemplateArgumentListInfo &Args) {
918  SmallString<128> SS;
919  llvm::raw_svector_ostream OS(SS);
920  bool First = true;
921  for (auto &Arg : Args.arguments()) {
922  if (!First)
923  OS << ", ";
924  Arg.getArgument().print(PrintingPolicy, OS);
925  First = false;
926  }
927  return OS.str();
928 }
929 
930 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
931  SourceLocation Loc, StringRef Trait,
933  unsigned DiagID) {
934  auto DiagnoseMissing = [&] {
935  if (DiagID)
936  S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
937  Args);
938  return true;
939  };
940 
941  // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
943  if (!Std)
944  return DiagnoseMissing();
945 
946  // Look up the trait itself, within namespace std. We can diagnose various
947  // problems with this lookup even if we've been asked to not diagnose a
948  // missing specialization, because this can only fail if the user has been
949  // declaring their own names in namespace std or we don't support the
950  // standard library implementation in use.
953  if (!S.LookupQualifiedName(Result, Std))
954  return DiagnoseMissing();
955  if (Result.isAmbiguous())
956  return true;
957 
958  ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
959  if (!TraitTD) {
960  Result.suppressDiagnostics();
961  NamedDecl *Found = *Result.begin();
962  S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
963  S.Diag(Found->getLocation(), diag::note_declared_at);
964  return true;
965  }
966 
967  // Build the template-id.
968  QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
969  if (TraitTy.isNull())
970  return true;
971  if (!S.isCompleteType(Loc, TraitTy)) {
972  if (DiagID)
974  Loc, TraitTy, DiagID,
976  return true;
977  }
978 
979  CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
980  assert(RD && "specialization of class template is not a class?");
981 
982  // Look up the member of the trait type.
983  S.LookupQualifiedName(TraitMemberLookup, RD);
984  return TraitMemberLookup.isAmbiguous();
985 }
986 
987 static TemplateArgumentLoc
989  uint64_t I) {
990  TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
991  return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
992 }
993 
994 static TemplateArgumentLoc
997 }
998 
999 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1000 
1002  llvm::APSInt &Size) {
1005 
1007  LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1008 
1009  // Form template argument list for tuple_size<T>.
1010  TemplateArgumentListInfo Args(Loc, Loc);
1012 
1013  // If there's no tuple_size specialization, it's not tuple-like.
1014  if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0))
1015  return IsTupleLike::NotTupleLike;
1016 
1017  // If we get this far, we've committed to the tuple interpretation, but
1018  // we can still fail if there actually isn't a usable ::value.
1019 
1020  struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1021  LookupResult &R;
1023  ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1024  : R(R), Args(Args) {}
1025  void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
1026  S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1028  }
1029  } Diagnoser(R, Args);
1030 
1031  if (R.empty()) {
1032  Diagnoser.diagnoseNotICE(S, Loc, SourceRange());
1033  return IsTupleLike::Error;
1034  }
1035 
1036  ExprResult E =
1037  S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1038  if (E.isInvalid())
1039  return IsTupleLike::Error;
1040 
1041  E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
1042  if (E.isInvalid())
1043  return IsTupleLike::Error;
1044 
1045  return IsTupleLike::TupleLike;
1046 }
1047 
1048 /// \return std::tuple_element<I, T>::type.
1050  unsigned I, QualType T) {
1051  // Form template argument list for tuple_element<I, T>.
1052  TemplateArgumentListInfo Args(Loc, Loc);
1053  Args.addArgument(
1056 
1057  DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1058  LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1060  S, R, Loc, "tuple_element", Args,
1061  diag::err_decomp_decl_std_tuple_element_not_specialized))
1062  return QualType();
1063 
1064  auto *TD = R.getAsSingle<TypeDecl>();
1065  if (!TD) {
1066  R.suppressDiagnostics();
1067  S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1069  if (!R.empty())
1070  S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1071  return QualType();
1072  }
1073 
1074  return S.Context.getTypeDeclType(TD);
1075 }
1076 
1077 namespace {
1078 struct BindingDiagnosticTrap {
1079  Sema &S;
1080  DiagnosticErrorTrap Trap;
1081  BindingDecl *BD;
1082 
1083  BindingDiagnosticTrap(Sema &S, BindingDecl *BD)
1084  : S(S), Trap(S.Diags), BD(BD) {}
1085  ~BindingDiagnosticTrap() {
1086  if (Trap.hasErrorOccurred())
1087  S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD;
1088  }
1089 };
1090 }
1091 
1093  ArrayRef<BindingDecl *> Bindings,
1094  VarDecl *Src, QualType DecompType,
1095  const llvm::APSInt &TupleSize) {
1096  if ((int64_t)Bindings.size() != TupleSize) {
1097  S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1098  << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1099  << (TupleSize < Bindings.size());
1100  return true;
1101  }
1102 
1103  if (Bindings.empty())
1104  return false;
1105 
1106  DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1107 
1108  // [dcl.decomp]p3:
1109  // The unqualified-id get is looked up in the scope of E by class member
1110  // access lookup ...
1111  LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1112  bool UseMemberGet = false;
1113  if (S.isCompleteType(Src->getLocation(), DecompType)) {
1114  if (auto *RD = DecompType->getAsCXXRecordDecl())
1115  S.LookupQualifiedName(MemberGet, RD);
1116  if (MemberGet.isAmbiguous())
1117  return true;
1118  // ... and if that finds at least one declaration that is a function
1119  // template whose first template parameter is a non-type parameter ...
1120  for (NamedDecl *D : MemberGet) {
1121  if (FunctionTemplateDecl *FTD =
1122  dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1123  TemplateParameterList *TPL = FTD->getTemplateParameters();
1124  if (TPL->size() != 0 &&
1125  isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1126  // ... the initializer is e.get<i>().
1127  UseMemberGet = true;
1128  break;
1129  }
1130  }
1131  }
1132  S.FilterAcceptableTemplateNames(MemberGet);
1133  }
1134 
1135  unsigned I = 0;
1136  for (auto *B : Bindings) {
1137  BindingDiagnosticTrap Trap(S, B);
1138  SourceLocation Loc = B->getLocation();
1139 
1140  ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1141  if (E.isInvalid())
1142  return true;
1143 
1144  // e is an lvalue if the type of the entity is an lvalue reference and
1145  // an xvalue otherwise
1146  if (!Src->getType()->isLValueReferenceType())
1147  E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1148  E.get(), nullptr, VK_XValue);
1149 
1150  TemplateArgumentListInfo Args(Loc, Loc);
1151  Args.addArgument(
1153 
1154  if (UseMemberGet) {
1155  // if [lookup of member get] finds at least one declaration, the
1156  // initializer is e.get<i-1>().
1157  E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1158  CXXScopeSpec(), SourceLocation(), nullptr,
1159  MemberGet, &Args, nullptr);
1160  if (E.isInvalid())
1161  return true;
1162 
1163  E = S.ActOnCallExpr(nullptr, E.get(), Loc, None, Loc);
1164  } else {
1165  // Otherwise, the initializer is get<i-1>(e), where get is looked up
1166  // in the associated namespaces.
1169  DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1171 
1172  Expr *Arg = E.get();
1173  E = S.ActOnCallExpr(nullptr, Get, Loc, Arg, Loc);
1174  }
1175  if (E.isInvalid())
1176  return true;
1177  Expr *Init = E.get();
1178 
1179  // Given the type T designated by std::tuple_element<i - 1, E>::type,
1180  QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1181  if (T.isNull())
1182  return true;
1183 
1184  // each vi is a variable of type "reference to T" initialized with the
1185  // initializer, where the reference is an lvalue reference if the
1186  // initializer is an lvalue and an rvalue reference otherwise
1187  QualType RefType =
1188  S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1189  if (RefType.isNull())
1190  return true;
1191  auto *RefVD = VarDecl::Create(
1192  S.Context, Src->getDeclContext(), Loc, Loc,
1193  B->getDeclName().getAsIdentifierInfo(), RefType,
1196  RefVD->setTSCSpec(Src->getTSCSpec());
1197  RefVD->setImplicit();
1198  if (Src->isInlineSpecified())
1199  RefVD->setInlineSpecified();
1200  RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1201 
1204  InitializationSequence Seq(S, Entity, Kind, Init);
1205  E = Seq.Perform(S, Entity, Kind, Init);
1206  if (E.isInvalid())
1207  return true;
1208  E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1209  if (E.isInvalid())
1210  return true;
1211  RefVD->setInit(E.get());
1212  RefVD->checkInitIsICE();
1213 
1215  DeclarationNameInfo(B->getDeclName(), Loc),
1216  RefVD);
1217  if (E.isInvalid())
1218  return true;
1219 
1220  B->setBinding(T, E.get());
1221  I++;
1222  }
1223 
1224  return false;
1225 }
1226 
1227 /// Find the base class to decompose in a built-in decomposition of a class type.
1228 /// This base class search is, unfortunately, not quite like any other that we
1229 /// perform anywhere else in C++.
1231  const CXXRecordDecl *RD,
1232  CXXCastPath &BasePath) {
1233  auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1234  CXXBasePath &Path) {
1235  return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1236  };
1237 
1238  const CXXRecordDecl *ClassWithFields = nullptr;
1240  if (RD->hasDirectFields())
1241  // [dcl.decomp]p4:
1242  // Otherwise, all of E's non-static data members shall be public direct
1243  // members of E ...
1244  ClassWithFields = RD;
1245  else {
1246  // ... or of ...
1247  CXXBasePaths Paths;
1248  Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1249  if (!RD->lookupInBases(BaseHasFields, Paths)) {
1250  // If no classes have fields, just decompose RD itself. (This will work
1251  // if and only if zero bindings were provided.)
1252  return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1253  }
1254 
1255  CXXBasePath *BestPath = nullptr;
1256  for (auto &P : Paths) {
1257  if (!BestPath)
1258  BestPath = &P;
1259  else if (!S.Context.hasSameType(P.back().Base->getType(),
1260  BestPath->back().Base->getType())) {
1261  // ... the same ...
1262  S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1263  << false << RD << BestPath->back().Base->getType()
1264  << P.back().Base->getType();
1265  return DeclAccessPair();
1266  } else if (P.Access < BestPath->Access) {
1267  BestPath = &P;
1268  }
1269  }
1270 
1271  // ... unambiguous ...
1272  QualType BaseType = BestPath->back().Base->getType();
1273  if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1274  S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1275  << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1276  return DeclAccessPair();
1277  }
1278 
1279  // ... [accessible, implied by other rules] base class of E.
1280  S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1281  *BestPath, diag::err_decomp_decl_inaccessible_base);
1282  AS = BestPath->Access;
1283 
1284  ClassWithFields = BaseType->getAsCXXRecordDecl();
1285  S.BuildBasePathArray(Paths, BasePath);
1286  }
1287 
1288  // The above search did not check whether the selected class itself has base
1289  // classes with fields, so check that now.
1290  CXXBasePaths Paths;
1291  if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1292  S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1293  << (ClassWithFields == RD) << RD << ClassWithFields
1294  << Paths.front().back().Base->getType();
1295  return DeclAccessPair();
1296  }
1297 
1298  return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1299 }
1300 
1302  ValueDecl *Src, QualType DecompType,
1303  const CXXRecordDecl *OrigRD) {
1304  if (S.RequireCompleteType(Src->getLocation(), DecompType,
1305  diag::err_incomplete_type))
1306  return true;
1307 
1308  CXXCastPath BasePath;
1309  DeclAccessPair BasePair =
1310  findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1311  const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1312  if (!RD)
1313  return true;
1315  DecompType.getQualifiers());
1316 
1317  auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1318  unsigned NumFields =
1319  std::count_if(RD->field_begin(), RD->field_end(),
1320  [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1321  assert(Bindings.size() != NumFields);
1322  S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1323  << DecompType << (unsigned)Bindings.size() << NumFields
1324  << (NumFields < Bindings.size());
1325  return true;
1326  };
1327 
1328  // all of E's non-static data members shall be [...] well-formed
1329  // when named as e.name in the context of the structured binding,
1330  // E shall not have an anonymous union member, ...
1331  unsigned I = 0;
1332  for (auto *FD : RD->fields()) {
1333  if (FD->isUnnamedBitfield())
1334  continue;
1335 
1336  if (FD->isAnonymousStructOrUnion()) {
1337  S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1338  << DecompType << FD->getType()->isUnionType();
1339  S.Diag(FD->getLocation(), diag::note_declared_at);
1340  return true;
1341  }
1342 
1343  // We have a real field to bind.
1344  if (I >= Bindings.size())
1345  return DiagnoseBadNumberOfBindings();
1346  auto *B = Bindings[I++];
1347  SourceLocation Loc = B->getLocation();
1348 
1349  // The field must be accessible in the context of the structured binding.
1350  // We already checked that the base class is accessible.
1351  // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1352  // const_cast here.
1354  Loc, const_cast<CXXRecordDecl *>(OrigRD),
1356  BasePair.getAccess(), FD->getAccess())));
1357 
1358  // Initialize the binding to Src.FD.
1359  ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1360  if (E.isInvalid())
1361  return true;
1362  E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1363  VK_LValue, &BasePath);
1364  if (E.isInvalid())
1365  return true;
1366  E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1367  CXXScopeSpec(), FD,
1368  DeclAccessPair::make(FD, FD->getAccess()),
1369  DeclarationNameInfo(FD->getDeclName(), Loc));
1370  if (E.isInvalid())
1371  return true;
1372 
1373  // If the type of the member is T, the referenced type is cv T, where cv is
1374  // the cv-qualification of the decomposition expression.
1375  //
1376  // FIXME: We resolve a defect here: if the field is mutable, we do not add
1377  // 'const' to the type of the field.
1378  Qualifiers Q = DecompType.getQualifiers();
1379  if (FD->isMutable())
1380  Q.removeConst();
1381  B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1382  }
1383 
1384  if (I != Bindings.size())
1385  return DiagnoseBadNumberOfBindings();
1386 
1387  return false;
1388 }
1389 
1391  QualType DecompType = DD->getType();
1392 
1393  // If the type of the decomposition is dependent, then so is the type of
1394  // each binding.
1395  if (DecompType->isDependentType()) {
1396  for (auto *B : DD->bindings())
1397  B->setType(Context.DependentTy);
1398  return;
1399  }
1400 
1401  DecompType = DecompType.getNonReferenceType();
1402  ArrayRef<BindingDecl*> Bindings = DD->bindings();
1403 
1404  // C++1z [dcl.decomp]/2:
1405  // If E is an array type [...]
1406  // As an extension, we also support decomposition of built-in complex and
1407  // vector types.
1408  if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1409  if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1410  DD->setInvalidDecl();
1411  return;
1412  }
1413  if (auto *VT = DecompType->getAs<VectorType>()) {
1414  if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1415  DD->setInvalidDecl();
1416  return;
1417  }
1418  if (auto *CT = DecompType->getAs<ComplexType>()) {
1419  if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1420  DD->setInvalidDecl();
1421  return;
1422  }
1423 
1424  // C++1z [dcl.decomp]/3:
1425  // if the expression std::tuple_size<E>::value is a well-formed integral
1426  // constant expression, [...]
1427  llvm::APSInt TupleSize(32);
1428  switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1429  case IsTupleLike::Error:
1430  DD->setInvalidDecl();
1431  return;
1432 
1433  case IsTupleLike::TupleLike:
1434  if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1435  DD->setInvalidDecl();
1436  return;
1437 
1438  case IsTupleLike::NotTupleLike:
1439  break;
1440  }
1441 
1442  // C++1z [dcl.dcl]/8:
1443  // [E shall be of array or non-union class type]
1444  CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1445  if (!RD || RD->isUnion()) {
1446  Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1447  << DD << !RD << DecompType;
1448  DD->setInvalidDecl();
1449  return;
1450  }
1451 
1452  // C++1z [dcl.decomp]/4:
1453  // all of E's non-static data members shall be [...] direct members of
1454  // E or of the same unambiguous public base class of E, ...
1455  if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1456  DD->setInvalidDecl();
1457 }
1458 
1459 /// Merge the exception specifications of two variable declarations.
1460 ///
1461 /// This is called when there's a redeclaration of a VarDecl. The function
1462 /// checks if the redeclaration might have an exception specification and
1463 /// validates compatibility and merges the specs if necessary.
1465  // Shortcut if exceptions are disabled.
1466  if (!getLangOpts().CXXExceptions)
1467  return;
1468 
1469  assert(Context.hasSameType(New->getType(), Old->getType()) &&
1470  "Should only be called if types are otherwise the same.");
1471 
1472  QualType NewType = New->getType();
1473  QualType OldType = Old->getType();
1474 
1475  // We're only interested in pointers and references to functions, as well
1476  // as pointers to member functions.
1477  if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1478  NewType = R->getPointeeType();
1479  OldType = OldType->getAs<ReferenceType>()->getPointeeType();
1480  } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1481  NewType = P->getPointeeType();
1482  OldType = OldType->getAs<PointerType>()->getPointeeType();
1483  } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1484  NewType = M->getPointeeType();
1485  OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
1486  }
1487 
1488  if (!NewType->isFunctionProtoType())
1489  return;
1490 
1491  // There's lots of special cases for functions. For function pointers, system
1492  // libraries are hopefully not as broken so that we don't need these
1493  // workarounds.
1494  if (CheckEquivalentExceptionSpec(
1495  OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1496  NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1497  New->setInvalidDecl();
1498  }
1499 }
1500 
1501 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1502 /// function declaration are well-formed according to C++
1503 /// [dcl.fct.default].
1505  unsigned NumParams = FD->getNumParams();
1506  unsigned p;
1507 
1508  // Find first parameter with a default argument
1509  for (p = 0; p < NumParams; ++p) {
1510  ParmVarDecl *Param = FD->getParamDecl(p);
1511  if (Param->hasDefaultArg())
1512  break;
1513  }
1514 
1515  // C++11 [dcl.fct.default]p4:
1516  // In a given function declaration, each parameter subsequent to a parameter
1517  // with a default argument shall have a default argument supplied in this or
1518  // a previous declaration or shall be a function parameter pack. A default
1519  // argument shall not be redefined by a later declaration (not even to the
1520  // same value).
1521  unsigned LastMissingDefaultArg = 0;
1522  for (; p < NumParams; ++p) {
1523  ParmVarDecl *Param = FD->getParamDecl(p);
1524  if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
1525  if (Param->isInvalidDecl())
1526  /* We already complained about this parameter. */;
1527  else if (Param->getIdentifier())
1528  Diag(Param->getLocation(),
1529  diag::err_param_default_argument_missing_name)
1530  << Param->getIdentifier();
1531  else
1532  Diag(Param->getLocation(),
1533  diag::err_param_default_argument_missing);
1534 
1535  LastMissingDefaultArg = p;
1536  }
1537  }
1538 
1539  if (LastMissingDefaultArg > 0) {
1540  // Some default arguments were missing. Clear out all of the
1541  // default arguments up to (and including) the last missing
1542  // default argument, so that we leave the function parameters
1543  // in a semantically valid state.
1544  for (p = 0; p <= LastMissingDefaultArg; ++p) {
1545  ParmVarDecl *Param = FD->getParamDecl(p);
1546  if (Param->hasDefaultArg()) {
1547  Param->setDefaultArg(nullptr);
1548  }
1549  }
1550  }
1551 }
1552 
1553 // CheckConstexprParameterTypes - Check whether a function's parameter types
1554 // are all literal types. If so, return true. If not, produce a suitable
1555 // diagnostic and return false.
1556 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1557  const FunctionDecl *FD) {
1558  unsigned ArgIndex = 0;
1559  const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
1561  e = FT->param_type_end();
1562  i != e; ++i, ++ArgIndex) {
1563  const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1564  SourceLocation ParamLoc = PD->getLocation();
1565  if (!(*i)->isDependentType() &&
1566  SemaRef.RequireLiteralType(ParamLoc, *i,
1567  diag::err_constexpr_non_literal_param,
1568  ArgIndex+1, PD->getSourceRange(),
1569  isa<CXXConstructorDecl>(FD)))
1570  return false;
1571  }
1572  return true;
1573 }
1574 
1575 /// Get diagnostic %select index for tag kind for
1576 /// record diagnostic message.
1577 /// WARNING: Indexes apply to particular diagnostics only!
1578 ///
1579 /// \returns diagnostic %select index.
1581  switch (Tag) {
1582  case TTK_Struct: return 0;
1583  case TTK_Interface: return 1;
1584  case TTK_Class: return 2;
1585  default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1586  }
1587 }
1588 
1589 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
1590 // the requirements of a constexpr function definition or a constexpr
1591 // constructor definition. If so, return true. If not, produce appropriate
1592 // diagnostics and return false.
1593 //
1594 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1596  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1597  if (MD && MD->isInstance()) {
1598  // C++11 [dcl.constexpr]p4:
1599  // The definition of a constexpr constructor shall satisfy the following
1600  // constraints:
1601  // - the class shall not have any virtual base classes;
1602  const CXXRecordDecl *RD = MD->getParent();
1603  if (RD->getNumVBases()) {
1604  Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1605  << isa<CXXConstructorDecl>(NewFD)
1607  for (const auto &I : RD->vbases())
1608  Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1609  << I.getSourceRange();
1610  return false;
1611  }
1612  }
1613 
1614  if (!isa<CXXConstructorDecl>(NewFD)) {
1615  // C++11 [dcl.constexpr]p3:
1616  // The definition of a constexpr function shall satisfy the following
1617  // constraints:
1618  // - it shall not be virtual;
1619  const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1620  if (Method && Method->isVirtual()) {
1621  Method = Method->getCanonicalDecl();
1622  Diag(Method->getLocation(), diag::err_constexpr_virtual);
1623 
1624  // If it's not obvious why this function is virtual, find an overridden
1625  // function which uses the 'virtual' keyword.
1626  const CXXMethodDecl *WrittenVirtual = Method;
1627  while (!WrittenVirtual->isVirtualAsWritten())
1628  WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1629  if (WrittenVirtual != Method)
1630  Diag(WrittenVirtual->getLocation(),
1631  diag::note_overridden_virtual_function);
1632  return false;
1633  }
1634 
1635  // - its return type shall be a literal type;
1636  QualType RT = NewFD->getReturnType();
1637  if (!RT->isDependentType() &&
1638  RequireLiteralType(NewFD->getLocation(), RT,
1639  diag::err_constexpr_non_literal_return))
1640  return false;
1641  }
1642 
1643  // - each of its parameter types shall be a literal type;
1644  if (!CheckConstexprParameterTypes(*this, NewFD))
1645  return false;
1646 
1647  return true;
1648 }
1649 
1650 /// Check the given declaration statement is legal within a constexpr function
1651 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1652 ///
1653 /// \return true if the body is OK (maybe only as an extension), false if we
1654 /// have diagnosed a problem.
1655 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1656  DeclStmt *DS, SourceLocation &Cxx1yLoc) {
1657  // C++11 [dcl.constexpr]p3 and p4:
1658  // The definition of a constexpr function(p3) or constructor(p4) [...] shall
1659  // contain only
1660  for (const auto *DclIt : DS->decls()) {
1661  switch (DclIt->getKind()) {
1662  case Decl::StaticAssert:
1663  case Decl::Using:
1664  case Decl::UsingShadow:
1665  case Decl::UsingDirective:
1666  case Decl::UnresolvedUsingTypename:
1667  case Decl::UnresolvedUsingValue:
1668  // - static_assert-declarations
1669  // - using-declarations,
1670  // - using-directives,
1671  continue;
1672 
1673  case Decl::Typedef:
1674  case Decl::TypeAlias: {
1675  // - typedef declarations and alias-declarations that do not define
1676  // classes or enumerations,
1677  const auto *TN = cast<TypedefNameDecl>(DclIt);
1678  if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1679  // Don't allow variably-modified types in constexpr functions.
1680  TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1681  SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1682  << TL.getSourceRange() << TL.getType()
1683  << isa<CXXConstructorDecl>(Dcl);
1684  return false;
1685  }
1686  continue;
1687  }
1688 
1689  case Decl::Enum:
1690  case Decl::CXXRecord:
1691  // C++1y allows types to be defined, not just declared.
1692  if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
1693  SemaRef.Diag(DS->getBeginLoc(),
1694  SemaRef.getLangOpts().CPlusPlus14
1695  ? diag::warn_cxx11_compat_constexpr_type_definition
1696  : diag::ext_constexpr_type_definition)
1697  << isa<CXXConstructorDecl>(Dcl);
1698  continue;
1699 
1700  case Decl::EnumConstant:
1701  case Decl::IndirectField:
1702  case Decl::ParmVar:
1703  // These can only appear with other declarations which are banned in
1704  // C++11 and permitted in C++1y, so ignore them.
1705  continue;
1706 
1707  case Decl::Var:
1708  case Decl::Decomposition: {
1709  // C++1y [dcl.constexpr]p3 allows anything except:
1710  // a definition of a variable of non-literal type or of static or
1711  // thread storage duration or for which no initialization is performed.
1712  const auto *VD = cast<VarDecl>(DclIt);
1713  if (VD->isThisDeclarationADefinition()) {
1714  if (VD->isStaticLocal()) {
1715  SemaRef.Diag(VD->getLocation(),
1716  diag::err_constexpr_local_var_static)
1717  << isa<CXXConstructorDecl>(Dcl)
1718  << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1719  return false;
1720  }
1721  if (!VD->getType()->isDependentType() &&
1722  SemaRef.RequireLiteralType(
1723  VD->getLocation(), VD->getType(),
1724  diag::err_constexpr_local_var_non_literal_type,
1725  isa<CXXConstructorDecl>(Dcl)))
1726  return false;
1727  if (!VD->getType()->isDependentType() &&
1728  !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1729  SemaRef.Diag(VD->getLocation(),
1730  diag::err_constexpr_local_var_no_init)
1731  << isa<CXXConstructorDecl>(Dcl);
1732  return false;
1733  }
1734  }
1735  SemaRef.Diag(VD->getLocation(),
1736  SemaRef.getLangOpts().CPlusPlus14
1737  ? diag::warn_cxx11_compat_constexpr_local_var
1738  : diag::ext_constexpr_local_var)
1739  << isa<CXXConstructorDecl>(Dcl);
1740  continue;
1741  }
1742 
1743  case Decl::NamespaceAlias:
1744  case Decl::Function:
1745  // These are disallowed in C++11 and permitted in C++1y. Allow them
1746  // everywhere as an extension.
1747  if (!Cxx1yLoc.isValid())
1748  Cxx1yLoc = DS->getBeginLoc();
1749  continue;
1750 
1751  default:
1752  SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1753  << isa<CXXConstructorDecl>(Dcl);
1754  return false;
1755  }
1756  }
1757 
1758  return true;
1759 }
1760 
1761 /// Check that the given field is initialized within a constexpr constructor.
1762 ///
1763 /// \param Dcl The constexpr constructor being checked.
1764 /// \param Field The field being checked. This may be a member of an anonymous
1765 /// struct or union nested within the class being checked.
1766 /// \param Inits All declarations, including anonymous struct/union members and
1767 /// indirect members, for which any initialization was provided.
1768 /// \param Diagnosed Set to true if an error is produced.
1770  const FunctionDecl *Dcl,
1771  FieldDecl *Field,
1772  llvm::SmallSet<Decl*, 16> &Inits,
1773  bool &Diagnosed) {
1774  if (Field->isInvalidDecl())
1775  return;
1776 
1777  if (Field->isUnnamedBitfield())
1778  return;
1779 
1780  // Anonymous unions with no variant members and empty anonymous structs do not
1781  // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1782  // indirect fields don't need initializing.
1783  if (Field->isAnonymousStructOrUnion() &&
1784  (Field->getType()->isUnionType()
1785  ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1786  : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1787  return;
1788 
1789  if (!Inits.count(Field)) {
1790  if (!Diagnosed) {
1791  SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
1792  Diagnosed = true;
1793  }
1794  SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
1795  } else if (Field->isAnonymousStructOrUnion()) {
1796  const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1797  for (auto *I : RD->fields())
1798  // If an anonymous union contains an anonymous struct of which any member
1799  // is initialized, all members must be initialized.
1800  if (!RD->isUnion() || Inits.count(I))
1801  CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
1802  }
1803 }
1804 
1805 /// Check the provided statement is allowed in a constexpr function
1806 /// definition.
1807 static bool
1809  SmallVectorImpl<SourceLocation> &ReturnStmts,
1810  SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc) {
1811  // - its function-body shall be [...] a compound-statement that contains only
1812  switch (S->getStmtClass()) {
1813  case Stmt::NullStmtClass:
1814  // - null statements,
1815  return true;
1816 
1817  case Stmt::DeclStmtClass:
1818  // - static_assert-declarations
1819  // - using-declarations,
1820  // - using-directives,
1821  // - typedef declarations and alias-declarations that do not define
1822  // classes or enumerations,
1823  if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1824  return false;
1825  return true;
1826 
1827  case Stmt::ReturnStmtClass:
1828  // - and exactly one return statement;
1829  if (isa<CXXConstructorDecl>(Dcl)) {
1830  // C++1y allows return statements in constexpr constructors.
1831  if (!Cxx1yLoc.isValid())
1832  Cxx1yLoc = S->getBeginLoc();
1833  return true;
1834  }
1835 
1836  ReturnStmts.push_back(S->getBeginLoc());
1837  return true;
1838 
1839  case Stmt::CompoundStmtClass: {
1840  // C++1y allows compound-statements.
1841  if (!Cxx1yLoc.isValid())
1842  Cxx1yLoc = S->getBeginLoc();
1843 
1844  CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1845  for (auto *BodyIt : CompStmt->body()) {
1846  if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1847  Cxx1yLoc, Cxx2aLoc))
1848  return false;
1849  }
1850  return true;
1851  }
1852 
1853  case Stmt::AttributedStmtClass:
1854  if (!Cxx1yLoc.isValid())
1855  Cxx1yLoc = S->getBeginLoc();
1856  return true;
1857 
1858  case Stmt::IfStmtClass: {
1859  // C++1y allows if-statements.
1860  if (!Cxx1yLoc.isValid())
1861  Cxx1yLoc = S->getBeginLoc();
1862 
1863  IfStmt *If = cast<IfStmt>(S);
1864  if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1865  Cxx1yLoc, Cxx2aLoc))
1866  return false;
1867  if (If->getElse() &&
1868  !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1869  Cxx1yLoc, Cxx2aLoc))
1870  return false;
1871  return true;
1872  }
1873 
1874  case Stmt::WhileStmtClass:
1875  case Stmt::DoStmtClass:
1876  case Stmt::ForStmtClass:
1877  case Stmt::CXXForRangeStmtClass:
1878  case Stmt::ContinueStmtClass:
1879  // C++1y allows all of these. We don't allow them as extensions in C++11,
1880  // because they don't make sense without variable mutation.
1881  if (!SemaRef.getLangOpts().CPlusPlus14)
1882  break;
1883  if (!Cxx1yLoc.isValid())
1884  Cxx1yLoc = S->getBeginLoc();
1885  for (Stmt *SubStmt : S->children())
1886  if (SubStmt &&
1887  !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1888  Cxx1yLoc, Cxx2aLoc))
1889  return false;
1890  return true;
1891 
1892  case Stmt::SwitchStmtClass:
1893  case Stmt::CaseStmtClass:
1894  case Stmt::DefaultStmtClass:
1895  case Stmt::BreakStmtClass:
1896  // C++1y allows switch-statements, and since they don't need variable
1897  // mutation, we can reasonably allow them in C++11 as an extension.
1898  if (!Cxx1yLoc.isValid())
1899  Cxx1yLoc = S->getBeginLoc();
1900  for (Stmt *SubStmt : S->children())
1901  if (SubStmt &&
1902  !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1903  Cxx1yLoc, Cxx2aLoc))
1904  return false;
1905  return true;
1906 
1907  case Stmt::CXXTryStmtClass:
1908  if (Cxx2aLoc.isInvalid())
1909  Cxx2aLoc = S->getBeginLoc();
1910  for (Stmt *SubStmt : S->children()) {
1911  if (SubStmt &&
1912  !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1913  Cxx1yLoc, Cxx2aLoc))
1914  return false;
1915  }
1916  return true;
1917 
1918  case Stmt::CXXCatchStmtClass:
1919  // Do not bother checking the language mode (already covered by the
1920  // try block check).
1921  if (!CheckConstexprFunctionStmt(SemaRef, Dcl,
1922  cast<CXXCatchStmt>(S)->getHandlerBlock(),
1923  ReturnStmts, Cxx1yLoc, Cxx2aLoc))
1924  return false;
1925  return true;
1926 
1927  default:
1928  if (!isa<Expr>(S))
1929  break;
1930 
1931  // C++1y allows expression-statements.
1932  if (!Cxx1yLoc.isValid())
1933  Cxx1yLoc = S->getBeginLoc();
1934  return true;
1935  }
1936 
1937  SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1938  << isa<CXXConstructorDecl>(Dcl);
1939  return false;
1940 }
1941 
1942 /// Check the body for the given constexpr function declaration only contains
1943 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1944 ///
1945 /// \return true if the body is OK, false if we have diagnosed a problem.
1947  SmallVector<SourceLocation, 4> ReturnStmts;
1948 
1949  if (isa<CXXTryStmt>(Body)) {
1950  // C++11 [dcl.constexpr]p3:
1951  // The definition of a constexpr function shall satisfy the following
1952  // constraints: [...]
1953  // - its function-body shall be = delete, = default, or a
1954  // compound-statement
1955  //
1956  // C++11 [dcl.constexpr]p4:
1957  // In the definition of a constexpr constructor, [...]
1958  // - its function-body shall not be a function-try-block;
1959  //
1960  // This restriction is lifted in C++2a, as long as inner statements also
1961  // apply the general constexpr rules.
1962  Diag(Body->getBeginLoc(),
1963  !getLangOpts().CPlusPlus2a
1964  ? diag::ext_constexpr_function_try_block_cxx2a
1965  : diag::warn_cxx17_compat_constexpr_function_try_block)
1966  << isa<CXXConstructorDecl>(Dcl);
1967  }
1968 
1969  // - its function-body shall be [...] a compound-statement that contains only
1970  // [... list of cases ...]
1971  //
1972  // Note that walking the children here is enough to properly check for
1973  // CompoundStmt and CXXTryStmt body.
1974  SourceLocation Cxx1yLoc, Cxx2aLoc;
1975  for (Stmt *SubStmt : Body->children()) {
1976  if (SubStmt &&
1977  !CheckConstexprFunctionStmt(*this, Dcl, SubStmt, ReturnStmts,
1978  Cxx1yLoc, Cxx2aLoc))
1979  return false;
1980  }
1981 
1982  if (Cxx2aLoc.isValid())
1983  Diag(Cxx2aLoc,
1984  getLangOpts().CPlusPlus2a
1985  ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
1986  : diag::ext_constexpr_body_invalid_stmt_cxx2a)
1987  << isa<CXXConstructorDecl>(Dcl);
1988  if (Cxx1yLoc.isValid())
1989  Diag(Cxx1yLoc,
1990  getLangOpts().CPlusPlus14
1991  ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1992  : diag::ext_constexpr_body_invalid_stmt)
1993  << isa<CXXConstructorDecl>(Dcl);
1994 
1995  if (const CXXConstructorDecl *Constructor
1996  = dyn_cast<CXXConstructorDecl>(Dcl)) {
1997  const CXXRecordDecl *RD = Constructor->getParent();
1998  // DR1359:
1999  // - every non-variant non-static data member and base class sub-object
2000  // shall be initialized;
2001  // DR1460:
2002  // - if the class is a union having variant members, exactly one of them
2003  // shall be initialized;
2004  if (RD->isUnion()) {
2005  if (Constructor->getNumCtorInitializers() == 0 &&
2006  RD->hasVariantMembers()) {
2007  Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
2008  return false;
2009  }
2010  } else if (!Constructor->isDependentContext() &&
2011  !Constructor->isDelegatingConstructor()) {
2012  assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2013 
2014  // Skip detailed checking if we have enough initializers, and we would
2015  // allow at most one initializer per member.
2016  bool AnyAnonStructUnionMembers = false;
2017  unsigned Fields = 0;
2019  E = RD->field_end(); I != E; ++I, ++Fields) {
2020  if (I->isAnonymousStructOrUnion()) {
2021  AnyAnonStructUnionMembers = true;
2022  break;
2023  }
2024  }
2025  // DR1460:
2026  // - if the class is a union-like class, but is not a union, for each of
2027  // its anonymous union members having variant members, exactly one of
2028  // them shall be initialized;
2029  if (AnyAnonStructUnionMembers ||
2030  Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2031  // Check initialization of non-static data members. Base classes are
2032  // always initialized so do not need to be checked. Dependent bases
2033  // might not have initializers in the member initializer list.
2034  llvm::SmallSet<Decl*, 16> Inits;
2035  for (const auto *I: Constructor->inits()) {
2036  if (FieldDecl *FD = I->getMember())
2037  Inits.insert(FD);
2038  else if (IndirectFieldDecl *ID = I->getIndirectMember())
2039  Inits.insert(ID->chain_begin(), ID->chain_end());
2040  }
2041 
2042  bool Diagnosed = false;
2043  for (auto *I : RD->fields())
2044  CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
2045  if (Diagnosed)
2046  return false;
2047  }
2048  }
2049  } else {
2050  if (ReturnStmts.empty()) {
2051  // C++1y doesn't require constexpr functions to contain a 'return'
2052  // statement. We still do, unless the return type might be void, because
2053  // otherwise if there's no return statement, the function cannot
2054  // be used in a core constant expression.
2055  bool OK = getLangOpts().CPlusPlus14 &&
2056  (Dcl->getReturnType()->isVoidType() ||
2057  Dcl->getReturnType()->isDependentType());
2058  Diag(Dcl->getLocation(),
2059  OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2060  : diag::err_constexpr_body_no_return);
2061  if (!OK)
2062  return false;
2063  } else if (ReturnStmts.size() > 1) {
2064  Diag(ReturnStmts.back(),
2065  getLangOpts().CPlusPlus14
2066  ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2067  : diag::ext_constexpr_body_multiple_return);
2068  for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2069  Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
2070  }
2071  }
2072 
2073  // C++11 [dcl.constexpr]p5:
2074  // if no function argument values exist such that the function invocation
2075  // substitution would produce a constant expression, the program is
2076  // ill-formed; no diagnostic required.
2077  // C++11 [dcl.constexpr]p3:
2078  // - every constructor call and implicit conversion used in initializing the
2079  // return value shall be one of those allowed in a constant expression.
2080  // C++11 [dcl.constexpr]p4:
2081  // - every constructor involved in initializing non-static data members and
2082  // base class sub-objects shall be a constexpr constructor.
2084  if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
2085  Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
2086  << isa<CXXConstructorDecl>(Dcl);
2087  for (size_t I = 0, N = Diags.size(); I != N; ++I)
2088  Diag(Diags[I].first, Diags[I].second);
2089  // Don't return false here: we allow this for compatibility in
2090  // system headers.
2091  }
2092 
2093  return true;
2094 }
2095 
2096 /// Get the class that is directly named by the current context. This is the
2097 /// class for which an unqualified-id in this scope could name a constructor
2098 /// or destructor.
2099 ///
2100 /// If the scope specifier denotes a class, this will be that class.
2101 /// If the scope specifier is empty, this will be the class whose
2102 /// member-specification we are currently within. Otherwise, there
2103 /// is no such class.
2105  assert(getLangOpts().CPlusPlus && "No class names in C!");
2106 
2107  if (SS && SS->isInvalid())
2108  return nullptr;
2109 
2110  if (SS && SS->isNotEmpty()) {
2111  DeclContext *DC = computeDeclContext(*SS, true);
2112  return dyn_cast_or_null<CXXRecordDecl>(DC);
2113  }
2114 
2115  return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2116 }
2117 
2118 /// isCurrentClassName - Determine whether the identifier II is the
2119 /// name of the class type currently being defined. In the case of
2120 /// nested classes, this will only return true if II is the name of
2121 /// the innermost class.
2123  const CXXScopeSpec *SS) {
2124  CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2125  return CurDecl && &II == CurDecl->getIdentifier();
2126 }
2127 
2128 /// Determine whether the identifier II is a typo for the name of
2129 /// the class type currently being defined. If so, update it to the identifier
2130 /// that should have been used.
2132  assert(getLangOpts().CPlusPlus && "No class names in C!");
2133 
2134  if (!getLangOpts().SpellChecking)
2135  return false;
2136 
2137  CXXRecordDecl *CurDecl;
2138  if (SS && SS->isSet() && !SS->isInvalid()) {
2139  DeclContext *DC = computeDeclContext(*SS, true);
2140  CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2141  } else
2142  CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2143 
2144  if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2145  3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2146  < II->getLength()) {
2147  II = CurDecl->getIdentifier();
2148  return true;
2149  }
2150 
2151  return false;
2152 }
2153 
2154 /// Determine whether the given class is a base class of the given
2155 /// class, including looking at dependent bases.
2156 static bool findCircularInheritance(const CXXRecordDecl *Class,
2157  const CXXRecordDecl *Current) {
2159 
2160  Class = Class->getCanonicalDecl();
2161  while (true) {
2162  for (const auto &I : Current->bases()) {
2163  CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2164  if (!Base)
2165  continue;
2166 
2167  Base = Base->getDefinition();
2168  if (!Base)
2169  continue;
2170 
2171  if (Base->getCanonicalDecl() == Class)
2172  return true;
2173 
2174  Queue.push_back(Base);
2175  }
2176 
2177  if (Queue.empty())
2178  return false;
2179 
2180  Current = Queue.pop_back_val();
2181  }
2182 
2183  return false;
2184 }
2185 
2186 /// Check the validity of a C++ base class specifier.
2187 ///
2188 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2189 /// and returns NULL otherwise.
2192  SourceRange SpecifierRange,
2193  bool Virtual, AccessSpecifier Access,
2194  TypeSourceInfo *TInfo,
2195  SourceLocation EllipsisLoc) {
2196  QualType BaseType = TInfo->getType();
2197 
2198  // C++ [class.union]p1:
2199  // A union shall not have base classes.
2200  if (Class->isUnion()) {
2201  Diag(Class->getLocation(), diag::err_base_clause_on_union)
2202  << SpecifierRange;
2203  return nullptr;
2204  }
2205 
2206  if (EllipsisLoc.isValid() &&
2208  Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2209  << TInfo->getTypeLoc().getSourceRange();
2210  EllipsisLoc = SourceLocation();
2211  }
2212 
2213  SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2214 
2215  if (BaseType->isDependentType()) {
2216  // Make sure that we don't have circular inheritance among our dependent
2217  // bases. For non-dependent bases, the check for completeness below handles
2218  // this.
2219  if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2220  if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2221  ((BaseDecl = BaseDecl->getDefinition()) &&
2222  findCircularInheritance(Class, BaseDecl))) {
2223  Diag(BaseLoc, diag::err_circular_inheritance)
2224  << BaseType << Context.getTypeDeclType(Class);
2225 
2226  if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2227  Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2228  << BaseType;
2229 
2230  return nullptr;
2231  }
2232  }
2233 
2234  return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2235  Class->getTagKind() == TTK_Class,
2236  Access, TInfo, EllipsisLoc);
2237  }
2238 
2239  // Base specifiers must be record types.
2240  if (!BaseType->isRecordType()) {
2241  Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2242  return nullptr;
2243  }
2244 
2245  // C++ [class.union]p1:
2246  // A union shall not be used as a base class.
2247  if (BaseType->isUnionType()) {
2248  Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2249  return nullptr;
2250  }
2251 
2252  // For the MS ABI, propagate DLL attributes to base class templates.
2253  if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2254  if (Attr *ClassAttr = getDLLAttr(Class)) {
2255  if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2256  BaseType->getAsCXXRecordDecl())) {
2257  propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2258  BaseLoc);
2259  }
2260  }
2261  }
2262 
2263  // C++ [class.derived]p2:
2264  // The class-name in a base-specifier shall not be an incompletely
2265  // defined class.
2266  if (RequireCompleteType(BaseLoc, BaseType,
2267  diag::err_incomplete_base_class, SpecifierRange)) {
2268  Class->setInvalidDecl();
2269  return nullptr;
2270  }
2271 
2272  // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2273  RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
2274  assert(BaseDecl && "Record type has no declaration");
2275  BaseDecl = BaseDecl->getDefinition();
2276  assert(BaseDecl && "Base type is not incomplete, but has no definition");
2277  CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2278  assert(CXXBaseDecl && "Base type is not a C++ type");
2279 
2280  // Microsoft docs say:
2281  // "If a base-class has a code_seg attribute, derived classes must have the
2282  // same attribute."
2283  const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2284  const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2285  if ((DerivedCSA || BaseCSA) &&
2286  (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2287  Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2288  Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2289  << CXXBaseDecl;
2290  return nullptr;
2291  }
2292 
2293  // A class which contains a flexible array member is not suitable for use as a
2294  // base class:
2295  // - If the layout determines that a base comes before another base,
2296  // the flexible array member would index into the subsequent base.
2297  // - If the layout determines that base comes before the derived class,
2298  // the flexible array member would index into the derived class.
2299  if (CXXBaseDecl->hasFlexibleArrayMember()) {
2300  Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2301  << CXXBaseDecl->getDeclName();
2302  return nullptr;
2303  }
2304 
2305  // C++ [class]p3:
2306  // If a class is marked final and it appears as a base-type-specifier in
2307  // base-clause, the program is ill-formed.
2308  if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2309  Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2310  << CXXBaseDecl->getDeclName()
2311  << FA->isSpelledAsSealed();
2312  Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2313  << CXXBaseDecl->getDeclName() << FA->getRange();
2314  return nullptr;
2315  }
2316 
2317  if (BaseDecl->isInvalidDecl())
2318  Class->setInvalidDecl();
2319 
2320  // Create the base specifier.
2321  return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2322  Class->getTagKind() == TTK_Class,
2323  Access, TInfo, EllipsisLoc);
2324 }
2325 
2326 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2327 /// one entry in the base class list of a class specifier, for
2328 /// example:
2329 /// class foo : public bar, virtual private baz {
2330 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2331 BaseResult
2332 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2333  ParsedAttributes &Attributes,
2334  bool Virtual, AccessSpecifier Access,
2335  ParsedType basetype, SourceLocation BaseLoc,
2336  SourceLocation EllipsisLoc) {
2337  if (!classdecl)
2338  return true;
2339 
2340  AdjustDeclIfTemplate(classdecl);
2341  CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2342  if (!Class)
2343  return true;
2344 
2345  // We haven't yet attached the base specifiers.
2346  Class->setIsParsingBaseSpecifiers();
2347 
2348  // We do not support any C++11 attributes on base-specifiers yet.
2349  // Diagnose any attributes we see.
2350  for (const ParsedAttr &AL : Attributes) {
2351  if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2352  continue;
2353  Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2354  ? (unsigned)diag::warn_unknown_attribute_ignored
2355  : (unsigned)diag::err_base_specifier_attribute)
2356  << AL.getName();
2357  }
2358 
2359  TypeSourceInfo *TInfo = nullptr;
2360  GetTypeFromParser(basetype, &TInfo);
2361 
2362  if (EllipsisLoc.isInvalid() &&
2363  DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2364  UPPC_BaseType))
2365  return true;
2366 
2367  if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2368  Virtual, Access, TInfo,
2369  EllipsisLoc))
2370  return BaseSpec;
2371  else
2372  Class->setInvalidDecl();
2373 
2374  return true;
2375 }
2376 
2377 /// Use small set to collect indirect bases. As this is only used
2378 /// locally, there's no need to abstract the small size parameter.
2379 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2380 
2381 /// Recursively add the bases of Type. Don't add Type itself.
2382 static void
2383 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2384  const QualType &Type)
2385 {
2386  // Even though the incoming type is a base, it might not be
2387  // a class -- it could be a template parm, for instance.
2388  if (auto Rec = Type->getAs<RecordType>()) {
2389  auto Decl = Rec->getAsCXXRecordDecl();
2390 
2391  // Iterate over its bases.
2392  for (const auto &BaseSpec : Decl->bases()) {
2393  QualType Base = Context.getCanonicalType(BaseSpec.getType())
2394  .getUnqualifiedType();
2395  if (Set.insert(Base).second)
2396  // If we've not already seen it, recurse.
2397  NoteIndirectBases(Context, Set, Base);
2398  }
2399  }
2400 }
2401 
2402 /// Performs the actual work of attaching the given base class
2403 /// specifiers to a C++ class.
2406  if (Bases.empty())
2407  return false;
2408 
2409  // Used to keep track of which base types we have already seen, so
2410  // that we can properly diagnose redundant direct base types. Note
2411  // that the key is always the unqualified canonical type of the base
2412  // class.
2413  std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2414 
2415  // Used to track indirect bases so we can see if a direct base is
2416  // ambiguous.
2417  IndirectBaseSet IndirectBaseTypes;
2418 
2419  // Copy non-redundant base specifiers into permanent storage.
2420  unsigned NumGoodBases = 0;
2421  bool Invalid = false;
2422  for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2423  QualType NewBaseType
2424  = Context.getCanonicalType(Bases[idx]->getType());
2425  NewBaseType = NewBaseType.getLocalUnqualifiedType();
2426 
2427  CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2428  if (KnownBase) {
2429  // C++ [class.mi]p3:
2430  // A class shall not be specified as a direct base class of a
2431  // derived class more than once.
2432  Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2433  << KnownBase->getType() << Bases[idx]->getSourceRange();
2434 
2435  // Delete the duplicate base class specifier; we're going to
2436  // overwrite its pointer later.
2437  Context.Deallocate(Bases[idx]);
2438 
2439  Invalid = true;
2440  } else {
2441  // Okay, add this new base class.
2442  KnownBase = Bases[idx];
2443  Bases[NumGoodBases++] = Bases[idx];
2444 
2445  // Note this base's direct & indirect bases, if there could be ambiguity.
2446  if (Bases.size() > 1)
2447  NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2448 
2449  if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2450  const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2451  if (Class->isInterface() &&
2452  (!RD->isInterfaceLike() ||
2453  KnownBase->getAccessSpecifier() != AS_public)) {
2454  // The Microsoft extension __interface does not permit bases that
2455  // are not themselves public interfaces.
2456  Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2457  << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2458  << RD->getSourceRange();
2459  Invalid = true;
2460  }
2461  if (RD->hasAttr<WeakAttr>())
2462  Class->addAttr(WeakAttr::CreateImplicit(Context));
2463  }
2464  }
2465  }
2466 
2467  // Attach the remaining base class specifiers to the derived class.
2468  Class->setBases(Bases.data(), NumGoodBases);
2469 
2470  // Check that the only base classes that are duplicate are virtual.
2471  for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2472  // Check whether this direct base is inaccessible due to ambiguity.
2473  QualType BaseType = Bases[idx]->getType();
2474 
2475  // Skip all dependent types in templates being used as base specifiers.
2476  // Checks below assume that the base specifier is a CXXRecord.
2477  if (BaseType->isDependentType())
2478  continue;
2479 
2480  CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2481  .getUnqualifiedType();
2482 
2483  if (IndirectBaseTypes.count(CanonicalBase)) {
2484  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2485  /*DetectVirtual=*/true);
2486  bool found
2487  = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2488  assert(found);
2489  (void)found;
2490 
2491  if (Paths.isAmbiguous(CanonicalBase))
2492  Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2493  << BaseType << getAmbiguousPathsDisplayString(Paths)
2494  << Bases[idx]->getSourceRange();
2495  else
2496  assert(Bases[idx]->isVirtual());
2497  }
2498 
2499  // Delete the base class specifier, since its data has been copied
2500  // into the CXXRecordDecl.
2501  Context.Deallocate(Bases[idx]);
2502  }
2503 
2504  return Invalid;
2505 }
2506 
2507 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2508 /// class, after checking whether there are any duplicate base
2509 /// classes.
2510 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2512  if (!ClassDecl || Bases.empty())
2513  return;
2514 
2515  AdjustDeclIfTemplate(ClassDecl);
2516  AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2517 }
2518 
2519 /// Determine whether the type \p Derived is a C++ class that is
2520 /// derived from the type \p Base.
2522  if (!getLangOpts().CPlusPlus)
2523  return false;
2524 
2525  CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2526  if (!DerivedRD)
2527  return false;
2528 
2529  CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2530  if (!BaseRD)
2531  return false;
2532 
2533  // If either the base or the derived type is invalid, don't try to
2534  // check whether one is derived from the other.
2535  if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2536  return false;
2537 
2538  // FIXME: In a modules build, do we need the entire path to be visible for us
2539  // to be able to use the inheritance relationship?
2540  if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2541  return false;
2542 
2543  return DerivedRD->isDerivedFrom(BaseRD);
2544 }
2545 
2546 /// Determine whether the type \p Derived is a C++ class that is
2547 /// derived from the type \p Base.
2549  CXXBasePaths &Paths) {
2550  if (!getLangOpts().CPlusPlus)
2551  return false;
2552 
2553  CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2554  if (!DerivedRD)
2555  return false;
2556 
2557  CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2558  if (!BaseRD)
2559  return false;
2560 
2561  if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2562  return false;
2563 
2564  return DerivedRD->isDerivedFrom(BaseRD, Paths);
2565 }
2566 
2567 static void BuildBasePathArray(const CXXBasePath &Path,
2568  CXXCastPath &BasePathArray) {
2569  // We first go backward and check if we have a virtual base.
2570  // FIXME: It would be better if CXXBasePath had the base specifier for
2571  // the nearest virtual base.
2572  unsigned Start = 0;
2573  for (unsigned I = Path.size(); I != 0; --I) {
2574  if (Path[I - 1].Base->isVirtual()) {
2575  Start = I - 1;
2576  break;
2577  }
2578  }
2579 
2580  // Now add all bases.
2581  for (unsigned I = Start, E = Path.size(); I != E; ++I)
2582  BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2583 }
2584 
2585 
2587  CXXCastPath &BasePathArray) {
2588  assert(BasePathArray.empty() && "Base path array must be empty!");
2589  assert(Paths.isRecordingPaths() && "Must record paths!");
2590  return ::BuildBasePathArray(Paths.front(), BasePathArray);
2591 }
2592 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2593 /// conversion (where Derived and Base are class types) is
2594 /// well-formed, meaning that the conversion is unambiguous (and
2595 /// that all of the base classes are accessible). Returns true
2596 /// and emits a diagnostic if the code is ill-formed, returns false
2597 /// otherwise. Loc is the location where this routine should point to
2598 /// if there is an error, and Range is the source range to highlight
2599 /// if there is an error.
2600 ///
2601 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
2602 /// diagnostic for the respective type of error will be suppressed, but the
2603 /// check for ill-formed code will still be performed.
2604 bool
2606  unsigned InaccessibleBaseID,
2607  unsigned AmbigiousBaseConvID,
2608  SourceLocation Loc, SourceRange Range,
2609  DeclarationName Name,
2610  CXXCastPath *BasePath,
2611  bool IgnoreAccess) {
2612  // First, determine whether the path from Derived to Base is
2613  // ambiguous. This is slightly more expensive than checking whether
2614  // the Derived to Base conversion exists, because here we need to
2615  // explore multiple paths to determine if there is an ambiguity.
2616  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2617  /*DetectVirtual=*/false);
2618  bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2619  if (!DerivationOkay)
2620  return true;
2621 
2622  const CXXBasePath *Path = nullptr;
2623  if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2624  Path = &Paths.front();
2625 
2626  // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2627  // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2628  // user to access such bases.
2629  if (!Path && getLangOpts().MSVCCompat) {
2630  for (const CXXBasePath &PossiblePath : Paths) {
2631  if (PossiblePath.size() == 1) {
2632  Path = &PossiblePath;
2633  if (AmbigiousBaseConvID)
2634  Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2635  << Base << Derived << Range;
2636  break;
2637  }
2638  }
2639  }
2640 
2641  if (Path) {
2642  if (!IgnoreAccess) {
2643  // Check that the base class can be accessed.
2644  switch (
2645  CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2646  case AR_inaccessible:
2647  return true;
2648  case AR_accessible:
2649  case AR_dependent:
2650  case AR_delayed:
2651  break;
2652  }
2653  }
2654 
2655  // Build a base path if necessary.
2656  if (BasePath)
2657  ::BuildBasePathArray(*Path, *BasePath);
2658  return false;
2659  }
2660 
2661  if (AmbigiousBaseConvID) {
2662  // We know that the derived-to-base conversion is ambiguous, and
2663  // we're going to produce a diagnostic. Perform the derived-to-base
2664  // search just one more time to compute all of the possible paths so
2665  // that we can print them out. This is more expensive than any of
2666  // the previous derived-to-base checks we've done, but at this point
2667  // performance isn't as much of an issue.
2668  Paths.clear();
2669  Paths.setRecordingPaths(true);
2670  bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2671  assert(StillOkay && "Can only be used with a derived-to-base conversion");
2672  (void)StillOkay;
2673 
2674  // Build up a textual representation of the ambiguous paths, e.g.,
2675  // D -> B -> A, that will be used to illustrate the ambiguous
2676  // conversions in the diagnostic. We only print one of the paths
2677  // to each base class subobject.
2678  std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2679 
2680  Diag(Loc, AmbigiousBaseConvID)
2681  << Derived << Base << PathDisplayStr << Range << Name;
2682  }
2683  return true;
2684 }
2685 
2686 bool
2688  SourceLocation Loc, SourceRange Range,
2689  CXXCastPath *BasePath,
2690  bool IgnoreAccess) {
2691  return CheckDerivedToBaseConversion(
2692  Derived, Base, diag::err_upcast_to_inaccessible_base,
2693  diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2694  BasePath, IgnoreAccess);
2695 }
2696 
2697 
2698 /// Builds a string representing ambiguous paths from a
2699 /// specific derived class to different subobjects of the same base
2700 /// class.
2701 ///
2702 /// This function builds a string that can be used in error messages
2703 /// to show the different paths that one can take through the
2704 /// inheritance hierarchy to go from the derived class to different
2705 /// subobjects of a base class. The result looks something like this:
2706 /// @code
2707 /// struct D -> struct B -> struct A
2708 /// struct D -> struct C -> struct A
2709 /// @endcode
2711  std::string PathDisplayStr;
2712  std::set<unsigned> DisplayedPaths;
2713  for (CXXBasePaths::paths_iterator Path = Paths.begin();
2714  Path != Paths.end(); ++Path) {
2715  if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2716  // We haven't displayed a path to this particular base
2717  // class subobject yet.
2718  PathDisplayStr += "\n ";
2719  PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2720  for (CXXBasePath::const_iterator Element = Path->begin();
2721  Element != Path->end(); ++Element)
2722  PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2723  }
2724  }
2725 
2726  return PathDisplayStr;
2727 }
2728 
2729 //===----------------------------------------------------------------------===//
2730 // C++ class member Handling
2731 //===----------------------------------------------------------------------===//
2732 
2733 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2736  const ParsedAttributesView &Attrs) {
2737  assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
2738  AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2739  ASLoc, ColonLoc);
2740  CurContext->addHiddenDecl(ASDecl);
2741  return ProcessAccessDeclAttributeList(ASDecl, Attrs);
2742 }
2743 
2744 /// CheckOverrideControl - Check C++11 override control semantics.
2746  if (D->isInvalidDecl())
2747  return;
2748 
2749  // We only care about "override" and "final" declarations.
2750  if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2751  return;
2752 
2753  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2754 
2755  // We can't check dependent instance methods.
2756  if (MD && MD->isInstance() &&
2757  (MD->getParent()->hasAnyDependentBases() ||
2758  MD->getType()->isDependentType()))
2759  return;
2760 
2761  if (MD && !MD->isVirtual()) {
2762  // If we have a non-virtual method, check if if hides a virtual method.
2763  // (In that case, it's most likely the method has the wrong type.)
2764  SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2765  FindHiddenVirtualMethods(MD, OverloadedMethods);
2766 
2767  if (!OverloadedMethods.empty()) {
2768  if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2769  Diag(OA->getLocation(),
2770  diag::override_keyword_hides_virtual_member_function)
2771  << "override" << (OverloadedMethods.size() > 1);
2772  } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2773  Diag(FA->getLocation(),
2774  diag::override_keyword_hides_virtual_member_function)
2775  << (FA->isSpelledAsSealed() ? "sealed" : "final")
2776  << (OverloadedMethods.size() > 1);
2777  }
2778  NoteHiddenVirtualMethods(MD, OverloadedMethods);
2779  MD->setInvalidDecl();
2780  return;
2781  }
2782  // Fall through into the general case diagnostic.
2783  // FIXME: We might want to attempt typo correction here.
2784  }
2785 
2786  if (!MD || !MD->isVirtual()) {
2787  if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2788  Diag(OA->getLocation(),
2789  diag::override_keyword_only_allowed_on_virtual_member_functions)
2790  << "override" << FixItHint::CreateRemoval(OA->getLocation());
2791  D->dropAttr<OverrideAttr>();
2792  }
2793  if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2794  Diag(FA->getLocation(),
2795  diag::override_keyword_only_allowed_on_virtual_member_functions)
2796  << (FA->isSpelledAsSealed() ? "sealed" : "final")
2797  << FixItHint::CreateRemoval(FA->getLocation());
2798  D->dropAttr<FinalAttr>();
2799  }
2800  return;
2801  }
2802 
2803  // C++11 [class.virtual]p5:
2804  // If a function is marked with the virt-specifier override and
2805  // does not override a member function of a base class, the program is
2806  // ill-formed.
2807  bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
2808  if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
2809  Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
2810  << MD->getDeclName();
2811 }
2812 
2814  if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
2815  return;
2816  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2817  if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
2818  return;
2819 
2820  SourceLocation Loc = MD->getLocation();
2821  SourceLocation SpellingLoc = Loc;
2822  if (getSourceManager().isMacroArgExpansion(Loc))
2823  SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
2824  SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
2825  if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
2826  return;
2827 
2828  if (MD->size_overridden_methods() > 0) {
2829  unsigned DiagID = isa<CXXDestructorDecl>(MD)
2830  ? diag::warn_destructor_marked_not_override_overriding
2831  : diag::warn_function_marked_not_override_overriding;
2832  Diag(MD->getLocation(), DiagID) << MD->getDeclName();
2833  const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
2834  Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
2835  }
2836 }
2837 
2838 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
2839 /// function overrides a virtual member function marked 'final', according to
2840 /// C++11 [class.virtual]p4.
2842  const CXXMethodDecl *Old) {
2843  FinalAttr *FA = Old->getAttr<FinalAttr>();
2844  if (!FA)
2845  return false;
2846 
2847  Diag(New->getLocation(), diag::err_final_function_overridden)
2848  << New->getDeclName()
2849  << FA->isSpelledAsSealed();
2850  Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2851  return true;
2852 }
2853 
2854 static bool InitializationHasSideEffects(const FieldDecl &FD) {
2855  const Type *T = FD.getType()->getBaseElementTypeUnsafe();
2856  // FIXME: Destruction of ObjC lifetime types has side-effects.
2857  if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2858  return !RD->isCompleteDefinition() ||
2859  !RD->hasTrivialDefaultConstructor() ||
2860  !RD->hasTrivialDestructor();
2861  return false;
2862 }
2863 
2866  llvm::find_if(list, [](const ParsedAttr &AL) {
2867  return AL.isDeclspecPropertyAttribute();
2868  });
2869  if (Itr != list.end())
2870  return &*Itr;
2871  return nullptr;
2872 }
2873 
2874 // Check if there is a field shadowing.
2875 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
2876  DeclarationName FieldName,
2877  const CXXRecordDecl *RD,
2878  bool DeclIsField) {
2879  if (Diags.isIgnored(diag::warn_shadow_field, Loc))
2880  return;
2881 
2882  // To record a shadowed field in a base
2883  std::map<CXXRecordDecl*, NamedDecl*> Bases;
2884  auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
2885  CXXBasePath &Path) {
2886  const auto Base = Specifier->getType()->getAsCXXRecordDecl();
2887  // Record an ambiguous path directly
2888  if (Bases.find(Base) != Bases.end())
2889  return true;
2890  for (const auto Field : Base->lookup(FieldName)) {
2891  if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
2892  Field->getAccess() != AS_private) {
2893  assert(Field->getAccess() != AS_none);
2894  assert(Bases.find(Base) == Bases.end());
2895  Bases[Base] = Field;
2896  return true;
2897  }
2898  }
2899  return false;
2900  };
2901 
2902  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2903  /*DetectVirtual=*/true);
2904  if (!RD->lookupInBases(FieldShadowed, Paths))
2905  return;
2906 
2907  for (const auto &P : Paths) {
2908  auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
2909  auto It = Bases.find(Base);
2910  // Skip duplicated bases
2911  if (It == Bases.end())
2912  continue;
2913  auto BaseField = It->second;
2914  assert(BaseField->getAccess() != AS_private);
2915  if (AS_none !=
2916  CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
2917  Diag(Loc, diag::warn_shadow_field)
2918  << FieldName << RD << Base << DeclIsField;
2919  Diag(BaseField->getLocation(), diag::note_shadow_field);
2920  Bases.erase(It);
2921  }
2922  }
2923 }
2924 
2925 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2926 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
2927 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
2928 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2929 /// present (but parsing it has been deferred).
2930 NamedDecl *
2932  MultiTemplateParamsArg TemplateParameterLists,
2933  Expr *BW, const VirtSpecifiers &VS,
2934  InClassInitStyle InitStyle) {
2935  const DeclSpec &DS = D.getDeclSpec();
2936  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2937  DeclarationName Name = NameInfo.getName();
2938  SourceLocation Loc = NameInfo.getLoc();
2939 
2940  // For anonymous bitfields, the location should point to the type.
2941  if (Loc.isInvalid())
2942  Loc = D.getBeginLoc();
2943 
2944  Expr *BitWidth = static_cast<Expr*>(BW);
2945 
2946  assert(isa<CXXRecordDecl>(CurContext));
2947  assert(!DS.isFriendSpecified());
2948 
2949  bool isFunc = D.isDeclarationOfFunction();
2950  const ParsedAttr *MSPropertyAttr =
2952 
2953  if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2954  // The Microsoft extension __interface only permits public member functions
2955  // and prohibits constructors, destructors, operators, non-public member
2956  // functions, static methods and data members.
2957  unsigned InvalidDecl;
2958  bool ShowDeclName = true;
2959  if (!isFunc &&
2960  (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
2961  InvalidDecl = 0;
2962  else if (!isFunc)
2963  InvalidDecl = 1;
2964  else if (AS != AS_public)
2965  InvalidDecl = 2;
2966  else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2967  InvalidDecl = 3;
2968  else switch (Name.getNameKind()) {
2970  InvalidDecl = 4;
2971  ShowDeclName = false;
2972  break;
2973 
2975  InvalidDecl = 5;
2976  ShowDeclName = false;
2977  break;
2978 
2981  InvalidDecl = 6;
2982  break;
2983 
2984  default:
2985  InvalidDecl = 0;
2986  break;
2987  }
2988 
2989  if (InvalidDecl) {
2990  if (ShowDeclName)
2991  Diag(Loc, diag::err_invalid_member_in_interface)
2992  << (InvalidDecl-1) << Name;
2993  else
2994  Diag(Loc, diag::err_invalid_member_in_interface)
2995  << (InvalidDecl-1) << "";
2996  return nullptr;
2997  }
2998  }
2999 
3000  // C++ 9.2p6: A member shall not be declared to have automatic storage
3001  // duration (auto, register) or with the extern storage-class-specifier.
3002  // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3003  // data members and cannot be applied to names declared const or static,
3004  // and cannot be applied to reference members.
3005  switch (DS.getStorageClassSpec()) {
3007  case DeclSpec::SCS_typedef:
3008  case DeclSpec::SCS_static:
3009  break;
3010  case DeclSpec::SCS_mutable:
3011  if (isFunc) {
3012  Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3013 
3014  // FIXME: It would be nicer if the keyword was ignored only for this
3015  // declarator. Otherwise we could get follow-up errors.
3017  }
3018  break;
3019  default:
3021  diag::err_storageclass_invalid_for_member);
3023  break;
3024  }
3025 
3026  bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3028  !isFunc);
3029 
3030  if (DS.isConstexprSpecified() && isInstField) {
3032  Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3033  SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3034  if (InitStyle == ICIS_NoInit) {
3035  B << 0 << 0;
3037  B << FixItHint::CreateRemoval(ConstexprLoc);
3038  else {
3039  B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3041  const char *PrevSpec;
3042  unsigned DiagID;
3043  bool Failed = D.getMutableDeclSpec().SetTypeQual(
3044  DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3045  (void)Failed;
3046  assert(!Failed && "Making a constexpr member const shouldn't fail");
3047  }
3048  } else {
3049  B << 1;
3050  const char *PrevSpec;
3051  unsigned DiagID;
3053  *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3054  Context.getPrintingPolicy())) {
3055  assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3056  "This is the only DeclSpec that should fail to be applied");
3057  B << 1;
3058  } else {
3059  B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3060  isInstField = false;
3061  }
3062  }
3063  }
3064 
3065  NamedDecl *Member;
3066  if (isInstField) {
3067  CXXScopeSpec &SS = D.getCXXScopeSpec();
3068 
3069  // Data members must have identifiers for names.
3070  if (!Name.isIdentifier()) {
3071  Diag(Loc, diag::err_bad_variable_name)
3072  << Name;
3073  return nullptr;
3074  }
3075 
3076  IdentifierInfo *II = Name.getAsIdentifierInfo();
3077 
3078  // Member field could not be with "template" keyword.
3079  // So TemplateParameterLists should be empty in this case.
3080  if (TemplateParameterLists.size()) {
3081  TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3082  if (TemplateParams->size()) {
3083  // There is no such thing as a member field template.
3084  Diag(D.getIdentifierLoc(), diag::err_template_member)
3085  << II
3086  << SourceRange(TemplateParams->getTemplateLoc(),
3087  TemplateParams->getRAngleLoc());
3088  } else {
3089  // There is an extraneous 'template<>' for this member.
3090  Diag(TemplateParams->getTemplateLoc(),
3091  diag::err_template_member_noparams)
3092  << II
3093  << SourceRange(TemplateParams->getTemplateLoc(),
3094  TemplateParams->getRAngleLoc());
3095  }
3096  return nullptr;
3097  }
3098 
3099  if (SS.isSet() && !SS.isInvalid()) {
3100  // The user provided a superfluous scope specifier inside a class
3101  // definition:
3102  //
3103  // class X {
3104  // int X::member;
3105  // };
3106  if (DeclContext *DC = computeDeclContext(SS, false))
3107  diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3108  D.getName().getKind() ==
3110  else
3111  Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3112  << Name << SS.getRange();
3113 
3114  SS.clear();
3115  }
3116 
3117  if (MSPropertyAttr) {
3118  Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3119  BitWidth, InitStyle, AS, *MSPropertyAttr);
3120  if (!Member)
3121  return nullptr;
3122  isInstField = false;
3123  } else {
3124  Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3125  BitWidth, InitStyle, AS);
3126  if (!Member)
3127  return nullptr;
3128  }
3129 
3130  CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3131  } else {
3132  Member = HandleDeclarator(S, D, TemplateParameterLists);
3133  if (!Member)
3134  return nullptr;
3135 
3136  // Non-instance-fields can't have a bitfield.
3137  if (BitWidth) {
3138  if (Member->isInvalidDecl()) {
3139  // don't emit another diagnostic.
3140  } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3141  // C++ 9.6p3: A bit-field shall not be a static member.
3142  // "static member 'A' cannot be a bit-field"
3143  Diag(Loc, diag::err_static_not_bitfield)
3144  << Name << BitWidth->getSourceRange();
3145  } else if (isa<TypedefDecl>(Member)) {
3146  // "typedef member 'x' cannot be a bit-field"
3147  Diag(Loc, diag::err_typedef_not_bitfield)
3148  << Name << BitWidth->getSourceRange();
3149  } else {
3150  // A function typedef ("typedef int f(); f a;").
3151  // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3152  Diag(Loc, diag::err_not_integral_type_bitfield)
3153  << Name << cast<ValueDecl>(Member)->getType()
3154  << BitWidth->getSourceRange();
3155  }
3156 
3157  BitWidth = nullptr;
3158  Member->setInvalidDecl();
3159  }
3160 
3161  NamedDecl *NonTemplateMember = Member;
3162  if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3163  NonTemplateMember = FunTmpl->getTemplatedDecl();
3164  else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3165  NonTemplateMember = VarTmpl->getTemplatedDecl();
3166 
3167  Member->setAccess(AS);
3168 
3169  // If we have declared a member function template or static data member
3170  // template, set the access of the templated declaration as well.
3171  if (NonTemplateMember != Member)
3172  NonTemplateMember->setAccess(AS);
3173 
3174  // C++ [temp.deduct.guide]p3:
3175  // A deduction guide [...] for a member class template [shall be
3176  // declared] with the same access [as the template].
3177  if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3178  auto *TD = DG->getDeducedTemplate();
3179  if (AS != TD->getAccess()) {
3180  Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3181  Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3182  << TD->getAccess();
3183  const AccessSpecDecl *LastAccessSpec = nullptr;
3184  for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3185  if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3186  LastAccessSpec = AccessSpec;
3187  }
3188  assert(LastAccessSpec && "differing access with no access specifier");
3189  Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3190  << AS;
3191  }
3192  }
3193  }
3194 
3195  if (VS.isOverrideSpecified())
3196  Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
3197  if (VS.isFinalSpecified())
3198  Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
3199  VS.isFinalSpelledSealed()));
3200 
3201  if (VS.getLastLocation().isValid()) {
3202  // Update the end location of a method that has a virt-specifiers.
3203  if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3204  MD->setRangeEnd(VS.getLastLocation());
3205  }
3206 
3207  CheckOverrideControl(Member);
3208 
3209  assert((Name || isInstField) && "No identifier for non-field ?");
3210 
3211  if (isInstField) {
3212  FieldDecl *FD = cast<FieldDecl>(Member);
3213  FieldCollector->Add(FD);
3214 
3215  if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3216  // Remember all explicit private FieldDecls that have a name, no side
3217  // effects and are not part of a dependent type declaration.
3218  if (!FD->isImplicit() && FD->getDeclName() &&
3219  FD->getAccess() == AS_private &&
3220  !FD->hasAttr<UnusedAttr>() &&
3221  !FD->getParent()->isDependentContext() &&
3223  UnusedPrivateFields.insert(FD);
3224  }
3225  }
3226 
3227  return Member;
3228 }
3229 
3230 namespace {
3231  class UninitializedFieldVisitor
3232  : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3233  Sema &S;
3234  // List of Decls to generate a warning on. Also remove Decls that become
3235  // initialized.
3236  llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3237  // List of base classes of the record. Classes are removed after their
3238  // initializers.
3239  llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3240  // Vector of decls to be removed from the Decl set prior to visiting the
3241  // nodes. These Decls may have been initialized in the prior initializer.
3242  llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3243  // If non-null, add a note to the warning pointing back to the constructor.
3244  const CXXConstructorDecl *Constructor;
3245  // Variables to hold state when processing an initializer list. When
3246  // InitList is true, special case initialization of FieldDecls matching
3247  // InitListFieldDecl.
3248  bool InitList;
3249  FieldDecl *InitListFieldDecl;
3250  llvm::SmallVector<unsigned, 4> InitFieldIndex;
3251 
3252  public:
3254  UninitializedFieldVisitor(Sema &S,
3255  llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3256  llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3257  : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3258  Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3259 
3260  // Returns true if the use of ME is not an uninitialized use.
3261  bool IsInitListMemberExprInitialized(MemberExpr *ME,
3262  bool CheckReferenceOnly) {
3264  bool ReferenceField = false;
3265  while (ME) {
3266  FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3267  if (!FD)
3268  return false;
3269  Fields.push_back(FD);
3270  if (FD->getType()->isReferenceType())
3271  ReferenceField = true;
3272  ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3273  }
3274 
3275  // Binding a reference to an uninitialized field is not an
3276  // uninitialized use.
3277  if (CheckReferenceOnly && !ReferenceField)
3278  return true;
3279 
3280  llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3281  // Discard the first field since it is the field decl that is being
3282  // initialized.
3283  for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3284  UsedFieldIndex.push_back((*I)->getFieldIndex());
3285  }
3286 
3287  for (auto UsedIter = UsedFieldIndex.begin(),
3288  UsedEnd = UsedFieldIndex.end(),
3289  OrigIter = InitFieldIndex.begin(),
3290  OrigEnd = InitFieldIndex.end();
3291  UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3292  if (*UsedIter < *OrigIter)
3293  return true;
3294  if (*UsedIter > *OrigIter)
3295  break;
3296  }
3297 
3298  return false;
3299  }
3300 
3301  void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3302  bool AddressOf) {
3303  if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3304  return;
3305 
3306  // FieldME is the inner-most MemberExpr that is not an anonymous struct
3307  // or union.
3308  MemberExpr *FieldME = ME;
3309 
3310  bool AllPODFields = FieldME->getType().isPODType(S.Context);
3311 
3312  Expr *Base = ME;
3313  while (MemberExpr *SubME =
3314  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3315 
3316  if (isa<VarDecl>(SubME->getMemberDecl()))
3317  return;
3318 
3319  if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3320  if (!FD->isAnonymousStructOrUnion())
3321  FieldME = SubME;
3322 
3323  if (!FieldME->getType().isPODType(S.Context))
3324  AllPODFields = false;
3325 
3326  Base = SubME->getBase();
3327  }
3328 
3329  if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
3330  return;
3331 
3332  if (AddressOf && AllPODFields)
3333  return;
3334 
3335  ValueDecl* FoundVD = FieldME->getMemberDecl();
3336 
3337  if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3338  while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3339  BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3340  }
3341 
3342  if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3343  QualType T = BaseCast->getType();
3344  if (T->isPointerType() &&
3345  BaseClasses.count(T->getPointeeType())) {
3346  S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3347  << T->getPointeeType() << FoundVD;
3348  }
3349  }
3350  }
3351 
3352  if (!Decls.count(FoundVD))
3353  return;
3354 
3355  const bool IsReference = FoundVD->getType()->isReferenceType();
3356 
3357  if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3358  // Special checking for initializer lists.
3359  if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3360  return;
3361  }
3362  } else {
3363  // Prevent double warnings on use of unbounded references.
3364  if (CheckReferenceOnly && !IsReference)
3365  return;
3366  }
3367 
3368  unsigned diag = IsReference
3369  ? diag::warn_reference_field_is_uninit
3370  : diag::warn_field_is_uninit;
3371  S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3372  if (Constructor)
3373  S.Diag(Constructor->getLocation(),
3374  diag::note_uninit_in_this_constructor)
3375  << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3376 
3377  }
3378 
3379  void HandleValue(Expr *E, bool AddressOf) {
3380  E = E->IgnoreParens();
3381 
3382  if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3383  HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3384  AddressOf /*AddressOf*/);
3385  return;
3386  }
3387 
3388  if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3389  Visit(CO->getCond());
3390  HandleValue(CO->getTrueExpr(), AddressOf);
3391  HandleValue(CO->getFalseExpr(), AddressOf);
3392  return;
3393  }
3394 
3395  if (BinaryConditionalOperator *BCO =
3396  dyn_cast<BinaryConditionalOperator>(E)) {
3397  Visit(BCO->getCond());
3398  HandleValue(BCO->getFalseExpr(), AddressOf);
3399  return;
3400  }
3401 
3402  if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3403  HandleValue(OVE->getSourceExpr(), AddressOf);
3404  return;
3405  }
3406 
3407  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3408  switch (BO->getOpcode()) {
3409  default:
3410  break;
3411  case(BO_PtrMemD):
3412  case(BO_PtrMemI):
3413  HandleValue(BO->getLHS(), AddressOf);
3414  Visit(BO->getRHS());
3415  return;
3416  case(BO_Comma):
3417  Visit(BO->getLHS());
3418  HandleValue(BO->getRHS(), AddressOf);
3419  return;
3420  }
3421  }
3422 
3423  Visit(E);
3424  }
3425 
3426  void CheckInitListExpr(InitListExpr *ILE) {
3427  InitFieldIndex.push_back(0);
3428  for (auto Child : ILE->children()) {
3429  if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3430  CheckInitListExpr(SubList);
3431  } else {
3432  Visit(Child);
3433  }
3434  ++InitFieldIndex.back();
3435  }
3436  InitFieldIndex.pop_back();
3437  }
3438 
3439  void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3440  FieldDecl *Field, const Type *BaseClass) {
3441  // Remove Decls that may have been initialized in the previous
3442  // initializer.
3443  for (ValueDecl* VD : DeclsToRemove)
3444  Decls.erase(VD);
3445  DeclsToRemove.clear();
3446 
3447  Constructor = FieldConstructor;
3448  InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3449 
3450  if (ILE && Field) {
3451  InitList = true;
3452  InitListFieldDecl = Field;
3453  InitFieldIndex.clear();
3454  CheckInitListExpr(ILE);
3455  } else {
3456  InitList = false;
3457  Visit(E);
3458  }
3459 
3460  if (Field)
3461  Decls.erase(Field);
3462  if (BaseClass)
3463  BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3464  }
3465 
3466  void VisitMemberExpr(MemberExpr *ME) {
3467  // All uses of unbounded reference fields will warn.
3468  HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3469  }
3470 
3471  void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3472  if (E->getCastKind() == CK_LValueToRValue) {
3473  HandleValue(E->getSubExpr(), false /*AddressOf*/);
3474  return;
3475  }
3476 
3477  Inherited::VisitImplicitCastExpr(E);
3478  }
3479 
3480  void VisitCXXConstructExpr(CXXConstructExpr *E) {
3481  if (E->getConstructor()->isCopyConstructor()) {
3482  Expr *ArgExpr = E->getArg(0);
3483  if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3484  if (ILE->getNumInits() == 1)
3485  ArgExpr = ILE->getInit(0);
3486  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3487  if (ICE->getCastKind() == CK_NoOp)
3488  ArgExpr = ICE->getSubExpr();
3489  HandleValue(ArgExpr, false /*AddressOf*/);
3490  return;
3491  }
3492  Inherited::VisitCXXConstructExpr(E);
3493  }
3494 
3495  void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3496  Expr *Callee = E->getCallee();
3497  if (isa<MemberExpr>(Callee)) {
3498  HandleValue(Callee, false /*AddressOf*/);
3499  for (auto Arg : E->arguments())
3500  Visit(Arg);
3501  return;
3502  }
3503 
3504  Inherited::VisitCXXMemberCallExpr(E);
3505  }
3506 
3507  void VisitCallExpr(CallExpr *E) {
3508  // Treat std::move as a use.
3509  if (E->isCallToStdMove()) {
3510  HandleValue(E->getArg(0), /*AddressOf=*/false);
3511  return;
3512  }
3513 
3514  Inherited::VisitCallExpr(E);
3515  }
3516 
3517  void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3518  Expr *Callee = E->getCallee();
3519 
3520  if (isa<UnresolvedLookupExpr>(Callee))
3521  return Inherited::VisitCXXOperatorCallExpr(E);
3522 
3523  Visit(Callee);
3524  for (auto Arg : E->arguments())
3525  HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3526  }
3527 
3528  void VisitBinaryOperator(BinaryOperator *E) {
3529  // If a field assignment is detected, remove the field from the
3530  // uninitiailized field set.
3531  if (E->getOpcode() == BO_Assign)
3532  if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3533  if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3534  if (!FD->getType()->isReferenceType())
3535  DeclsToRemove.push_back(FD);
3536 
3537  if (E->isCompoundAssignmentOp()) {
3538  HandleValue(E->getLHS(), false /*AddressOf*/);
3539  Visit(E->getRHS());
3540  return;
3541  }
3542 
3543  Inherited::VisitBinaryOperator(E);
3544  }
3545 
3546  void VisitUnaryOperator(UnaryOperator *E) {
3547  if (E->isIncrementDecrementOp()) {
3548  HandleValue(E->getSubExpr(), false /*AddressOf*/);
3549  return;
3550  }
3551  if (E->getOpcode() == UO_AddrOf) {
3552  if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3553  HandleValue(ME->getBase(), true /*AddressOf*/);
3554  return;
3555  }
3556  }
3557 
3558  Inherited::VisitUnaryOperator(E);
3559  }
3560  };
3561 
3562  // Diagnose value-uses of fields to initialize themselves, e.g.
3563  // foo(foo)
3564  // where foo is not also a parameter to the constructor.
3565  // Also diagnose across field uninitialized use such as
3566  // x(y), y(x)
3567  // TODO: implement -Wuninitialized and fold this into that framework.
3568  static void DiagnoseUninitializedFields(
3569  Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3570 
3571  if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3572  Constructor->getLocation())) {
3573  return;
3574  }
3575 
3576  if (Constructor->isInvalidDecl())
3577  return;
3578 
3579  const CXXRecordDecl *RD = Constructor->getParent();
3580 
3581  if (RD->getDescribedClassTemplate())
3582  return;
3583 
3584  // Holds fields that are uninitialized.
3585  llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3586 
3587  // At the beginning, all fields are uninitialized.
3588  for (auto *I : RD->decls()) {
3589  if (auto *FD = dyn_cast<FieldDecl>(I)) {
3590  UninitializedFields.insert(FD);
3591  } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3592  UninitializedFields.insert(IFD->getAnonField());
3593  }
3594  }
3595 
3596  llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3597  for (auto I : RD->bases())
3598  UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3599 
3600  if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3601  return;
3602 
3603  UninitializedFieldVisitor UninitializedChecker(SemaRef,
3604  UninitializedFields,
3605  UninitializedBaseClasses);
3606 
3607  for (const auto *FieldInit : Constructor->inits()) {
3608  if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3609  break;
3610 
3611  Expr *InitExpr = FieldInit->getInit();
3612  if (!InitExpr)
3613  continue;
3614 
3616  dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3617  InitExpr = Default->getExpr();
3618  if (!InitExpr)
3619  continue;
3620  // In class initializers will point to the constructor.
3621  UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3622  FieldInit->getAnyMember(),
3623  FieldInit->getBaseClass());
3624  } else {
3625  UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3626  FieldInit->getAnyMember(),
3627  FieldInit->getBaseClass());
3628  }
3629  }
3630  }
3631 } // namespace
3632 
3633 /// Enter a new C++ default initializer scope. After calling this, the
3634 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3635 /// parsing or instantiating the initializer failed.
3637  // Create a synthetic function scope to represent the call to the constructor
3638  // that notionally surrounds a use of this initializer.
3639  PushFunctionScope();
3640 }
3641 
3642 /// This is invoked after parsing an in-class initializer for a
3643 /// non-static C++ class member, and after instantiating an in-class initializer
3644 /// in a class template. Such actions are deferred until the class is complete.
3646  SourceLocation InitLoc,
3647  Expr *InitExpr) {
3648  // Pop the notional constructor scope we created earlier.
3649  PopFunctionScopeInfo(nullptr, D);
3650 
3651  FieldDecl *FD = dyn_cast<FieldDecl>(D);
3652  assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3653  "must set init style when field is created");
3654 
3655  if (!InitExpr) {
3656  D->setInvalidDecl();
3657  if (FD)
3659  return;
3660  }
3661 
3662  if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3663  FD->setInvalidDecl();
3665  return;
3666  }
3667 
3668  ExprResult Init = InitExpr;
3669  if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3670  InitializedEntity Entity =
3675  InitExpr->getBeginLoc(),
3676  InitExpr->getEndLoc())
3677  : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
3678  InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3679  Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3680  if (Init.isInvalid()) {
3681  FD->setInvalidDecl();
3682  return;
3683  }
3684  }
3685 
3686  // C++11 [class.base.init]p7:
3687  // The initialization of each base and member constitutes a
3688  // full-expression.
3689  Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
3690  if (Init.isInvalid()) {
3691  FD->setInvalidDecl();
3692  return;
3693  }
3694 
3695  InitExpr = Init.get();
3696 
3697  FD->setInClassInitializer(InitExpr);
3698 }
3699 
3700 /// Find the direct and/or virtual base specifiers that
3701 /// correspond to the given base type, for use in base initialization
3702 /// within a constructor.
3703 static bool FindBaseInitializer(Sema &SemaRef,
3704  CXXRecordDecl *ClassDecl,
3705  QualType BaseType,
3706  const CXXBaseSpecifier *&DirectBaseSpec,
3707  const CXXBaseSpecifier *&VirtualBaseSpec) {
3708  // First, check for a direct base class.
3709  DirectBaseSpec = nullptr;
3710  for (const auto &Base : ClassDecl->bases()) {
3711  if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
3712  // We found a direct base of this type. That's what we're
3713  // initializing.
3714  DirectBaseSpec = &Base;
3715  break;
3716  }
3717  }
3718 
3719  // Check for a virtual base class.
3720  // FIXME: We might be able to short-circuit this if we know in advance that
3721  // there are no virtual bases.
3722  VirtualBaseSpec = nullptr;
3723  if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3724  // We haven't found a base yet; search the class hierarchy for a
3725  // virtual base class.
3726  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3727  /*DetectVirtual=*/false);
3728  if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
3729  SemaRef.Context.getTypeDeclType(ClassDecl),
3730  BaseType, Paths)) {
3731  for (CXXBasePaths::paths_iterator Path = Paths.begin();
3732  Path != Paths.end(); ++Path) {
3733  if (Path->back().Base->isVirtual()) {
3734  VirtualBaseSpec = Path->back().Base;
3735  break;
3736  }
3737  }
3738  }
3739  }
3740 
3741  return DirectBaseSpec || VirtualBaseSpec;
3742 }
3743 
3744 /// Handle a C++ member initializer using braced-init-list syntax.
3746 Sema::ActOnMemInitializer(Decl *ConstructorD,
3747  Scope *S,
3748  CXXScopeSpec &SS,
3749  IdentifierInfo *MemberOrBase,
3750  ParsedType TemplateTypeTy,
3751  const DeclSpec &DS,
3752  SourceLocation IdLoc,
3753  Expr *InitList,
3754  SourceLocation EllipsisLoc) {
3755  return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3756  DS, IdLoc, InitList,
3757  EllipsisLoc);
3758 }
3759 
3760 /// Handle a C++ member initializer using parentheses syntax.
3762 Sema::ActOnMemInitializer(Decl *ConstructorD,
3763  Scope *S,
3764  CXXScopeSpec &SS,
3765  IdentifierInfo *MemberOrBase,
3766  ParsedType TemplateTypeTy,
3767  const DeclSpec &DS,
3768  SourceLocation IdLoc,
3769  SourceLocation LParenLoc,
3770  ArrayRef<Expr *> Args,
3771  SourceLocation RParenLoc,
3772  SourceLocation EllipsisLoc) {
3773  Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
3774  return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3775  DS, IdLoc, List, EllipsisLoc);
3776 }
3777 
3778 namespace {
3779 
3780 // Callback to only accept typo corrections that can be a valid C++ member
3781 // intializer: either a non-static field member or a base class.
3782 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
3783 public:
3784  explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
3785  : ClassDecl(ClassDecl) {}
3786 
3787  bool ValidateCandidate(const TypoCorrection &candidate) override {
3788  if (NamedDecl *ND = candidate.getCorrectionDecl()) {
3789  if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
3790  return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
3791  return isa<TypeDecl>(ND);
3792  }
3793  return false;
3794  }
3795 
3796 private:
3797  CXXRecordDecl *ClassDecl;
3798 };
3799 
3800 }
3801 
3802 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
3803  CXXScopeSpec &SS,
3804  ParsedType TemplateTypeTy,
3805  IdentifierInfo *MemberOrBase) {
3806  if (SS.getScopeRep() || TemplateTypeTy)
3807  return nullptr;
3808  DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
3809  if (Result.empty())
3810  return nullptr;
3811  ValueDecl *Member;
3812  if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
3813  (Member = dyn_cast<IndirectFieldDecl>(Result.front())))
3814  return Member;
3815  return nullptr;
3816 }
3817 
3818 /// Handle a C++ member initializer.
3820 Sema::BuildMemInitializer(Decl *ConstructorD,
3821  Scope *S,
3822  CXXScopeSpec &SS,
3823  IdentifierInfo *MemberOrBase,
3824  ParsedType TemplateTypeTy,
3825  const DeclSpec &DS,
3826  SourceLocation IdLoc,
3827  Expr *Init,
3828  SourceLocation EllipsisLoc) {
3829  ExprResult Res = CorrectDelayedTyposInExpr(Init);
3830  if (!Res.isUsable())
3831  return true;
3832  Init = Res.get();
3833 
3834  if (!ConstructorD)
3835  return true;
3836 
3837  AdjustDeclIfTemplate(ConstructorD);
3838 
3839  CXXConstructorDecl *Constructor
3840  = dyn_cast<CXXConstructorDecl>(ConstructorD);
3841  if (!Constructor) {
3842  // The user wrote a constructor initializer on a function that is
3843  // not a C++ constructor. Ignore the error for now, because we may
3844  // have more member initializers coming; we'll diagnose it just
3845  // once in ActOnMemInitializers.
3846  return true;
3847  }
3848 
3849  CXXRecordDecl *ClassDecl = Constructor->getParent();
3850 
3851  // C++ [class.base.init]p2:
3852  // Names in a mem-initializer-id are looked up in the scope of the
3853  // constructor's class and, if not found in that scope, are looked
3854  // up in the scope containing the constructor's definition.
3855  // [Note: if the constructor's class contains a member with the
3856  // same name as a direct or virtual base class of the class, a
3857  // mem-initializer-id naming the member or base class and composed
3858  // of a single identifier refers to the class member. A
3859  // mem-initializer-id for the hidden base class may be specified
3860  // using a qualified name. ]
3861 
3862  // Look for a member, first.
3863  if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
3864  ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
3865  if (EllipsisLoc.isValid())
3866  Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
3867  << MemberOrBase
3868  << SourceRange(IdLoc, Init->getSourceRange().getEnd());
3869 
3870  return BuildMemberInitializer(Member, Init, IdLoc);
3871  }
3872  // It didn't name a member, so see if it names a class.
3873  QualType BaseType;
3874  TypeSourceInfo *TInfo = nullptr;
3875 
3876  if (TemplateTypeTy) {
3877  BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
3878  } else if (DS.getTypeSpecType() == TST_decltype) {
3879  BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
3880  } else if (DS.getTypeSpecType() == TST_decltype_auto) {
3881  Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
3882  return true;
3883  } else {
3884  LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
3885  LookupParsedName(R, S, &SS);
3886 
3887  TypeDecl *TyD = R.getAsSingle<TypeDecl>();
3888  if (!TyD) {
3889  if (R.isAmbiguous()) return true;
3890 
3891  // We don't want access-control diagnostics here.
3892  R.suppressDiagnostics();
3893 
3894  if (SS.isSet() && isDependentScopeSpecifier(SS)) {
3895  bool NotUnknownSpecialization = false;
3896  DeclContext *DC = computeDeclContext(SS, false);
3897  if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
3898  NotUnknownSpecialization = !Record->hasAnyDependentBases();
3899 
3900  if (!NotUnknownSpecialization) {
3901  // When the scope specifier can refer to a member of an unknown
3902  // specialization, we take it as a type name.
3903  BaseType = CheckTypenameType(ETK_None, SourceLocation(),
3904  SS.getWithLocInContext(Context),
3905  *MemberOrBase, IdLoc);
3906  if (BaseType.isNull())
3907  return true;
3908 
3909  TInfo = Context.CreateTypeSourceInfo(BaseType);
3912  if (!TL.isNull()) {
3913  TL.setNameLoc(IdLoc);
3915  TL.setQualifierLoc(SS.getWithLocInContext(Context));
3916  }
3917 
3918  R.clear();
3919  R.setLookupName(MemberOrBase);
3920  }
3921  }
3922 
3923  // If no results were found, try to correct typos.
3924  TypoCorrection Corr;
3925  if (R.empty() && BaseType.isNull() &&
3926  (Corr = CorrectTypo(
3927  R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
3928  llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
3929  CTK_ErrorRecovery, ClassDecl))) {
3930  if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
3931  // We have found a non-static data member with a similar
3932  // name to what was typed; complain and initialize that
3933  // member.
3934  diagnoseTypo(Corr,
3935  PDiag(diag::err_mem_init_not_member_or_class_suggest)
3936  << MemberOrBase << true);
3937  return BuildMemberInitializer(Member, Init, IdLoc);
3938  } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
3939  const CXXBaseSpecifier *DirectBaseSpec;
3940  const CXXBaseSpecifier *VirtualBaseSpec;
3941  if (FindBaseInitializer(*this, ClassDecl,
3942  Context.getTypeDeclType(Type),
3943  DirectBaseSpec, VirtualBaseSpec)) {
3944  // We have found a direct or virtual base class with a
3945  // similar name to what was typed; complain and initialize
3946  // that base class.
3947  diagnoseTypo(Corr,
3948  PDiag(diag::err_mem_init_not_member_or_class_suggest)
3949  << MemberOrBase << false,
3950  PDiag() /*Suppress note, we provide our own.*/);
3951 
3952  const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
3953  : VirtualBaseSpec;
3954  Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
3955  << BaseSpec->getType() << BaseSpec->getSourceRange();
3956 
3957  TyD = Type;
3958  }
3959  }
3960  }
3961 
3962  if (!TyD && BaseType.isNull()) {
3963  Diag(IdLoc, diag::err_mem_init_not_member_or_class)
3964  << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
3965  return true;
3966  }
3967  }
3968 
3969  if (BaseType.isNull()) {
3970  BaseType = Context.getTypeDeclType(TyD);
3971  MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
3972  if (SS.isSet()) {
3973  BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
3974  BaseType);
3975  TInfo = Context.CreateTypeSourceInfo(BaseType);
3977  TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
3979  TL.setQualifierLoc(SS.getWithLocInContext(Context));
3980  }
3981  }
3982  }
3983 
3984  if (!TInfo)
3985  TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
3986 
3987  return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
3988 }
3989 
3992  SourceLocation IdLoc) {
3993  FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3994  IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3995  assert((DirectMember || IndirectMember) &&
3996  "Member must be a FieldDecl or IndirectFieldDecl");
3997 
3998  if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3999  return true;
4000 
4001  if (Member->isInvalidDecl())
4002  return true;
4003 
4004  MultiExprArg Args;
4005  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4006  Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4007  } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4008  Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4009  } else {
4010  // Template instantiation doesn't reconstruct ParenListExprs for us.
4011  Args = Init;
4012  }
4013 
4014  SourceRange InitRange = Init->getSourceRange();
4015 
4016  if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4017  // Can't check initialization for a member of dependent type or when
4018  // any of the arguments are type-dependent expressions.
4019  DiscardCleanupsInEvaluationContext();
4020  } else {
4021  bool InitList = false;
4022  if (isa<InitListExpr>(Init)) {
4023  InitList = true;
4024  Args = Init;
4025  }
4026 
4027  // Initialize the member.
4028  InitializedEntity MemberEntity =
4029  DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4030  : InitializedEntity::InitializeMember(IndirectMember,
4031  nullptr);
4034  IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4035  : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4036  InitRange.getEnd());
4037 
4038  InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4039  ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4040  nullptr);
4041  if (MemberInit.isInvalid())
4042  return true;
4043 
4044  // C++11 [class.base.init]p7:
4045  // The initialization of each base and member constitutes a
4046  // full-expression.
4047  MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4048  /*DiscardedValue*/ false);
4049  if (MemberInit.isInvalid())
4050  return true;
4051 
4052  Init = MemberInit.get();
4053  }
4054 
4055  if (DirectMember) {
4056  return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4057  InitRange.getBegin(), Init,
4058  InitRange.getEnd());
4059  } else {
4060  return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4061  InitRange.getBegin(), Init,
4062  InitRange.getEnd());
4063  }
4064 }
4065 
4068  CXXRecordDecl *ClassDecl) {
4069  SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4070  if (!LangOpts.CPlusPlus11)
4071  return Diag(NameLoc, diag::err_delegating_ctor)
4072  << TInfo->getTypeLoc().getLocalSourceRange();
4073  Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4074 
4075  bool InitList = true;
4076  MultiExprArg Args = Init;
4077  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4078  InitList = false;
4079  Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4080  }
4081 
4082  SourceRange InitRange = Init->getSourceRange();
4083  // Initialize the object.
4085  QualType(ClassDecl->getTypeForDecl(), 0));
4088  NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4089  : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4090  InitRange.getEnd());
4091  InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4092  ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4093  Args, nullptr);
4094  if (DelegationInit.isInvalid())
4095  return true;
4096 
4097  assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
4098  "Delegating constructor with no target?");
4099 
4100  // C++11 [class.base.init]p7:
4101  // The initialization of each base and member constitutes a
4102  // full-expression.
4103  DelegationInit = ActOnFinishFullExpr(
4104  DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4105  if (DelegationInit.isInvalid())
4106  return true;
4107 
4108  // If we are in a dependent context, template instantiation will
4109  // perform this type-checking again. Just save the arguments that we
4110  // received in a ParenListExpr.
4111  // FIXME: This isn't quite ideal, since our ASTs don't capture all
4112  // of the information that we have about the base
4113  // initializer. However, deconstructing the ASTs is a dicey process,
4114  // and this approach is far more likely to get the corner cases right.
4115  if (CurContext->isDependentContext())
4116  DelegationInit = Init;
4117 
4118  return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4119  DelegationInit.getAs<Expr>(),
4120  InitRange.getEnd());
4121 }
4122 
4125  Expr *Init, CXXRecordDecl *ClassDecl,
4126  SourceLocation EllipsisLoc) {
4127  SourceLocation BaseLoc
4128  = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4129 
4130  if (!BaseType->isDependentType() && !BaseType->isRecordType())
4131  return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4132  << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4133 
4134  // C++ [class.base.init]p2:
4135  // [...] Unless the mem-initializer-id names a nonstatic data
4136  // member of the constructor's class or a direct or virtual base
4137  // of that class, the mem-initializer is ill-formed. A
4138  // mem-initializer-list can initialize a base class using any
4139  // name that denotes that base class type.
4140  bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4141 
4142  SourceRange InitRange = Init->getSourceRange();
4143  if (EllipsisLoc.isValid()) {
4144  // This is a pack expansion.
4145  if (!BaseType->containsUnexpandedParameterPack()) {
4146  Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4147  << SourceRange(BaseLoc, InitRange.getEnd());
4148 
4149  EllipsisLoc = SourceLocation();
4150  }
4151  } else {
4152  // Check for any unexpanded parameter packs.
4153  if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4154  return true;
4155 
4156  if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4157  return true;
4158  }
4159 
4160  // Check for direct and virtual base classes.
4161  const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4162  const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4163  if (!Dependent) {
4164  if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4165  BaseType))
4166  return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4167 
4168  FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4169  VirtualBaseSpec);
4170 
4171  // C++ [base.class.init]p2:
4172  // Unless the mem-initializer-id names a nonstatic data member of the
4173  // constructor's class or a direct or virtual base of that class, the
4174  // mem-initializer is ill-formed.
4175  if (!DirectBaseSpec && !VirtualBaseSpec) {
4176  // If the class has any dependent bases, then it's possible that
4177  // one of those types will resolve to the same type as
4178  // BaseType. Therefore, just treat this as a dependent base
4179  // class initialization. FIXME: Should we try to check the
4180  // initialization anyway? It seems odd.
4181  if (ClassDecl->hasAnyDependentBases())
4182  Dependent = true;
4183  else
4184  return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4185  << BaseType << Context.getTypeDeclType(ClassDecl)
4186  << BaseTInfo->getTypeLoc().getLocalSourceRange();
4187  }
4188  }
4189 
4190  if (Dependent) {
4191  DiscardCleanupsInEvaluationContext();
4192 
4193  return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4194  /*IsVirtual=*/false,
4195  InitRange.getBegin(), Init,
4196  InitRange.getEnd(), EllipsisLoc);
4197  }
4198 
4199  // C++ [base.class.init]p2:
4200  // If a mem-initializer-id is ambiguous because it designates both
4201  // a direct non-virtual base class and an inherited virtual base
4202  // class, the mem-initializer is ill-formed.
4203  if (DirectBaseSpec && VirtualBaseSpec)
4204  return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4205  << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4206 
4207  const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4208  if (!BaseSpec)
4209  BaseSpec = VirtualBaseSpec;
4210 
4211  // Initialize the base.
4212  bool InitList = true;
4213  MultiExprArg Args = Init;
4214  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4215  InitList = false;
4216  Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4217  }
4218 
4219  InitializedEntity BaseEntity =
4220  InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4222  InitList ? InitializationKind::CreateDirectList(BaseLoc)
4223  : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4224  InitRange.getEnd());
4225  InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4226  ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4227  if (BaseInit.isInvalid())
4228  return true;
4229 
4230  // C++11 [class.base.init]p7:
4231  // The initialization of each base and member constitutes a
4232  // full-expression.
4233  BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4234  /*DiscardedValue*/ false);
4235  if (BaseInit.isInvalid())
4236  return true;
4237 
4238  // If we are in a dependent context, template instantiation will
4239  // perform this type-checking again. Just save the arguments that we
4240  // received in a ParenListExpr.
4241  // FIXME: This isn't quite ideal, since our ASTs don't capture all
4242  // of the information that we have about the base
4243  // initializer. However, deconstructing the ASTs is a dicey process,
4244  // and this approach is far more likely to get the corner cases right.
4245  if (CurContext->isDependentContext())
4246  BaseInit = Init;
4247 
4248  return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4249  BaseSpec->isVirtual(),
4250  InitRange.getBegin(),
4251  BaseInit.getAs<Expr>(),
4252  InitRange.getEnd(), EllipsisLoc);
4253 }
4254 
4255 // Create a static_cast<T&&>(expr).
4256 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4257  if (T.isNull()) T = E->getType();
4258  QualType TargetType = SemaRef.BuildReferenceType(
4259  T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4260  SourceLocation ExprLoc = E->getBeginLoc();
4261  TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4262  TargetType, ExprLoc);
4263 
4264  return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4265  SourceRange(ExprLoc, ExprLoc),
4266  E->getSourceRange()).get();
4267 }
4268 
4269 /// ImplicitInitializerKind - How an implicit base or member initializer should
4270 /// initialize its base or member.
4276 };
4277 
4278 static bool
4280  ImplicitInitializerKind ImplicitInitKind,
4281  CXXBaseSpecifier *BaseSpec,
4282  bool IsInheritedVirtualBase,
4283  CXXCtorInitializer *&CXXBaseInit) {
4284  InitializedEntity InitEntity
4285  = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4286  IsInheritedVirtualBase);
4287 
4288  ExprResult BaseInit;
4289 
4290  switch (ImplicitInitKind) {
4291  case IIK_Inherit:
4292  case IIK_Default: {
4293  InitializationKind InitKind
4295  InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4296  BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4297  break;
4298  }
4299 
4300  case IIK_Move:
4301  case IIK_Copy: {
4302  bool Moving = ImplicitInitKind == IIK_Move;
4303  ParmVarDecl *Param = Constructor->getParamDecl(0);
4304  QualType ParamType = Param->getType().getNonReferenceType();
4305 
4306  Expr *CopyCtorArg =
4308  SourceLocation(), Param, false,
4309  Constructor->getLocation(), ParamType,
4310  VK_LValue, nullptr);
4311 
4312  SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4313 
4314  // Cast to the base class to avoid ambiguities.
4315  QualType ArgTy =
4316  SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4317  ParamType.getQualifiers());
4318 
4319  if (Moving) {
4320  CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4321  }
4322 
4323  CXXCastPath BasePath;
4324  BasePath.push_back(BaseSpec);
4325  CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4326  CK_UncheckedDerivedToBase,
4327  Moving ? VK_XValue : VK_LValue,
4328  &BasePath).get();
4329 
4330  InitializationKind InitKind
4333  InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4334  BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4335  break;
4336  }
4337  }
4338 
4339  BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4340  if (BaseInit.isInvalid())
4341  return true;
4342 
4343  CXXBaseInit =
4344  new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4345  SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4346  SourceLocation()),
4347  BaseSpec->isVirtual(),
4348  SourceLocation(),
4349  BaseInit.getAs<Expr>(),
4350  SourceLocation(),
4351  SourceLocation());
4352 
4353  return false;
4354 }
4355 
4356 static bool RefersToRValueRef(Expr *MemRef) {
4357  ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4358  return Referenced->getType()->isRValueReferenceType();
4359 }
4360 
4361 static bool
4363  ImplicitInitializerKind ImplicitInitKind,
4364  FieldDecl *Field, IndirectFieldDecl *Indirect,
4365  CXXCtorInitializer *&CXXMemberInit) {
4366  if (Field->isInvalidDecl())
4367  return true;
4368 
4369  SourceLocation Loc = Constructor->getLocation();
4370 
4371  if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4372  bool Moving = ImplicitInitKind == IIK_Move;
4373  ParmVarDecl *Param = Constructor->getParamDecl(0);
4374  QualType ParamType = Param->getType().getNonReferenceType();
4375 
4376  // Suppress copying zero-width bitfields.
4377  if (Field->isZeroLengthBitField(SemaRef.Context))
4378  return false;
4379 
4380  Expr *MemberExprBase =
4382  SourceLocation(), Param, false,
4383  Loc, ParamType, VK_LValue, nullptr);
4384 
4385  SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4386 
4387  if (Moving) {
4388  MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4389  }
4390 
4391  // Build a reference to this field within the parameter.
4392  CXXScopeSpec SS;
4393  LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4395  MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4396  : cast<ValueDecl>(Field), AS_public);
4397  MemberLookup.resolveKind();
4398  ExprResult CtorArg
4399  = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4400  ParamType, Loc,
4401  /*IsArrow=*/false,
4402  SS,
4403  /*TemplateKWLoc=*/SourceLocation(),
4404  /*FirstQualifierInScope=*/nullptr,
4405  MemberLookup,
4406  /*TemplateArgs=*/nullptr,
4407  /*S*/nullptr);
4408  if (CtorArg.isInvalid())
4409  return true;
4410 
4411  // C++11 [class.copy]p15:
4412  // - if a member m has rvalue reference type T&&, it is direct-initialized
4413  // with static_cast<T&&>(x.m);
4414  if (RefersToRValueRef(CtorArg.get())) {
4415  CtorArg = CastForMoving(SemaRef, CtorArg.get());
4416  }
4417 
4418  InitializedEntity Entity =
4419  Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4420  /*Implicit*/ true)
4421  : InitializedEntity::InitializeMember(Field, nullptr,
4422  /*Implicit*/ true);
4423 
4424  // Direct-initialize to use the copy constructor.
4425  InitializationKind InitKind =
4427 
4428  Expr *CtorArgE = CtorArg.getAs<Expr>();
4429  InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4430  ExprResult MemberInit =
4431  InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4432  MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4433  if (MemberInit.isInvalid())
4434  return true;
4435 
4436  if (Indirect)
4437  CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4438  SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4439  else
4440  CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4441  SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4442  return false;
4443  }
4444 
4445  assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4446  "Unhandled implicit init kind!");
4447 
4448  QualType FieldBaseElementType =
4449  SemaRef.Context.getBaseElementType(Field->getType());
4450 
4451  if (FieldBaseElementType->isRecordType()) {
4452  InitializedEntity InitEntity =
4453  Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4454  /*Implicit*/ true)
4455  : InitializedEntity::InitializeMember(Field, nullptr,
4456  /*Implicit*/ true);
4457  InitializationKind InitKind =
4459 
4460  InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4461  ExprResult MemberInit =
4462  InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4463 
4464  MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4465  if (MemberInit.isInvalid())
4466  return true;
4467 
4468  if (Indirect)
4469  CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4470  Indirect, Loc,
4471  Loc,
4472  MemberInit.get(),
4473  Loc);
4474  else
4475  CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4476  Field, Loc, Loc,
4477  MemberInit.get(),
4478  Loc);
4479  return false;
4480  }
4481 
4482  if (!Field->getParent()->isUnion()) {
4483  if (FieldBaseElementType->isReferenceType()) {
4484  SemaRef.Diag(Constructor->getLocation(),
4485  diag::err_uninitialized_member_in_ctor)
4486  << (int)Constructor->isImplicit()
4487  << SemaRef.Context.getTagDeclType(Constructor->getParent())
4488  << 0 << Field->getDeclName();
4489  SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4490  return true;
4491  }
4492 
4493  if (FieldBaseElementType.isConstQualified()) {
4494  SemaRef.Diag(Constructor->getLocation(),
4495  diag::err_uninitialized_member_in_ctor)
4496  << (int)Constructor->isImplicit()
4497  << SemaRef.Context.getTagDeclType(Constructor->getParent())
4498  << 1 << Field->getDeclName();
4499  SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4500  return true;
4501  }
4502  }
4503 
4504  if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4505  // ARC and Weak:
4506  // Default-initialize Objective-C pointers to NULL.
4507  CXXMemberInit
4508  = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4509  Loc, Loc,
4510  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4511  Loc);
4512  return false;
4513  }
4514 
4515  // Nothing to initialize.
4516  CXXMemberInit = nullptr;
4517  return false;
4518 }
4519 
4520 namespace {
4521 struct BaseAndFieldInfo {
4522  Sema &S;
4523  CXXConstructorDecl *Ctor;
4524  bool AnyErrorsInInits;
4526  llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4528  llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4529 
4530  BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4531  : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4532  bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4533  if (Ctor->getInheritedConstructor())
4534  IIK = IIK_Inherit;
4535  else if (Generated && Ctor->isCopyConstructor())
4536  IIK = IIK_Copy;
4537  else if (Generated && Ctor->isMoveConstructor())
4538  IIK = IIK_Move;
4539  else
4540  IIK = IIK_Default;
4541  }
4542 
4543  bool isImplicitCopyOrMove() const {
4544  switch (IIK) {
4545  case IIK_Copy:
4546  case IIK_Move:
4547  return true;
4548 
4549  case IIK_Default:
4550  case IIK_Inherit:
4551  return false;
4552  }
4553 
4554  llvm_unreachable("Invalid ImplicitInitializerKind!");
4555  }
4556 
4557  bool addFieldInitializer(CXXCtorInitializer *Init) {
4558  AllToInit.push_back(Init);
4559 
4560  // Check whether this initializer makes the field "used".
4561  if (Init->getInit()->HasSideEffects(S.Context))
4562  S.UnusedPrivateFields.remove(Init->getAnyMember());
4563 
4564  return false;
4565  }
4566 
4567  bool isInactiveUnionMember(FieldDecl *Field) {
4568  RecordDecl *Record = Field->getParent();
4569  if (!Record->isUnion())
4570  return false;
4571 
4572  if (FieldDecl *Active =
4573  ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4574  return Active != Field->getCanonicalDecl();
4575 
4576  // In an implicit copy or move constructor, ignore any in-class initializer.
4577  if (isImplicitCopyOrMove())
4578  return true;
4579 
4580  // If there's no explicit initialization, the field is active only if it
4581  // has an in-class initializer...
4582  if (Field->hasInClassInitializer())
4583  return false;
4584  // ... or it's an anonymous struct or union whose class has an in-class
4585  // initializer.
4586  if (!Field->isAnonymousStructOrUnion())
4587  return true;
4588  CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4589  return !FieldRD->hasInClassInitializer();
4590  }
4591 
4592  /// Determine whether the given field is, or is within, a union member
4593  /// that is inactive (because there was an initializer given for a different
4594  /// member of the union, or because the union was not initialized at all).
4595  bool isWithinInactiveUnionMember(FieldDecl *Field,
4596  IndirectFieldDecl *Indirect) {
4597  if (!Indirect)
4598  return isInactiveUnionMember(Field);
4599 
4600  for (auto *C : Indirect->chain()) {
4601  FieldDecl *Field = dyn_cast<FieldDecl>(C);
4602  if (Field && isInactiveUnionMember(Field))
4603  return true;
4604  }
4605  return false;
4606  }
4607 };
4608 }
4609 
4610 /// Determine whether the given type is an incomplete or zero-lenfgth
4611 /// array type.
4613  if (T->isIncompleteArrayType())
4614  return true;
4615 
4616  while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4617  if (!ArrayT->getSize())
4618  return true;
4619 
4620  T = ArrayT->getElementType();
4621  }
4622 
4623  return false;
4624 }
4625 
4626 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4627  FieldDecl *Field,
4628  IndirectFieldDecl *Indirect = nullptr) {
4629  if (Field->isInvalidDecl())
4630  return false;
4631 
4632  // Overwhelmingly common case: we have a direct initializer for this field.
4633  if (CXXCtorInitializer *Init =
4634  Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4635  return Info.addFieldInitializer(Init);
4636 
4637  // C++11 [class.base.init]p8:
4638  // if the entity is a non-static data member that has a
4639  // brace-or-equal-initializer and either
4640  // -- the constructor's class is a union and no other variant member of that
4641  // union is designated by a mem-initializer-id or
4642  // -- the constructor's class is not a union, and, if the entity is a member
4643  // of an anonymous union, no other member of that union is designated by
4644  // a mem-initializer-id,
4645  // the entity is initialized as specified in [dcl.init].
4646  //
4647  // We also apply the same rules to handle anonymous structs within anonymous
4648  // unions.
4649  if (Info.isWithinInactiveUnionMember(Field, Indirect))
4650  return false;
4651 
4652  if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4653  ExprResult DIE =
4654  SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4655  if (DIE.isInvalid())
4656  return true;
4657 
4658  auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
4659  SemaRef.checkInitializerLifetime(Entity, DIE.get());
4660 
4661  CXXCtorInitializer *Init;
4662  if (Indirect)
4663  Init = new (SemaRef.Context)
4664  CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4665  SourceLocation(), DIE.get(), SourceLocation());
4666  else
4667  Init = new (SemaRef.Context)
4668  CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4669  SourceLocation(), DIE.get(), SourceLocation());
4670  return Info.addFieldInitializer(Init);
4671  }
4672 
4673  // Don't initialize incomplete or zero-length arrays.
4674  if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4675  return false;
4676 
4677  // Don't try to build an implicit initializer if there were semantic
4678  // errors in any of the initializers (and therefore we might be
4679  // missing some that the user actually wrote).
4680  if (Info.AnyErrorsInInits)
4681  return false;
4682 
4683  CXXCtorInitializer *Init = nullptr;
4684  if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4685  Indirect, Init))
4686  return true;
4687 
4688  if (!Init)
4689  return false;
4690 
4691  return Info.addFieldInitializer(Init);
4692 }
4693 
4694 bool
4696  CXXCtorInitializer *Initializer) {
4697  assert(Initializer->isDelegatingInitializer());
4698  Constructor->setNumCtorInitializers(1);
4699  CXXCtorInitializer **initializer =
4700  new (Context) CXXCtorInitializer*[1];
4701  memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4702  Constructor->setCtorInitializers(initializer);
4703 
4704  if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
4705  MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
4706  DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4707  }
4708 
4709  DelegatingCtorDecls.push_back(Constructor);
4710 
4711  DiagnoseUninitializedFields(*this, Constructor);
4712 
4713  return false;
4714 }
4715 
4716 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4717  ArrayRef<CXXCtorInitializer *> Initializers) {
4718  if (Constructor->isDependentContext()) {
4719  // Just store the initializers as written, they will be checked during
4720  // instantiation.
4721  if (!Initializers.empty()) {
4722  Constructor->setNumCtorInitializers(Initializers.size());
4723  CXXCtorInitializer **baseOrMemberInitializers =
4724  new (Context) CXXCtorInitializer*[Initializers.size()];
4725  memcpy(baseOrMemberInitializers, Initializers.data(),
4726  Initializers.size() * sizeof(CXXCtorInitializer*));
4727  Constructor->setCtorInitializers(baseOrMemberInitializers);
4728  }
4729 
4730  // Let template instantiation know whether we had errors.
4731  if (AnyErrors)
4732  Constructor->setInvalidDecl();
4733 
4734  return false;
4735  }
4736 
4737  BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
4738 
4739  // We need to build the initializer AST according to order of construction
4740  // and not what user specified in the Initializers list.
4741  CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
4742  if (!ClassDecl)
4743  return true;
4744 
4745  bool HadError = false;
4746 
4747  for (unsigned i = 0; i < Initializers.size(); i++) {
4748  CXXCtorInitializer *Member = Initializers[i];
4749 
4750  if (Member->isBaseInitializer())
4751  Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
4752  else {
4753  Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
4754 
4755  if (IndirectFieldDecl *F = Member->getIndirectMember()) {
4756  for (auto *C : F->chain()) {
4757  FieldDecl *FD = dyn_cast<FieldDecl>(C);
4758  if (FD && FD->getParent()->isUnion())
4759  Info.ActiveUnionMember.insert(std::make_pair(
4760  FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4761  }
4762  } else if (FieldDecl *FD = Member->getMember()) {
4763  if (FD->getParent()->isUnion())
4764  Info.ActiveUnionMember.insert(std::make_pair(
4765  FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4766  }
4767  }
4768  }
4769 
4770  // Keep track of the direct virtual bases.
4771  llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
4772  for (auto &I : ClassDecl->bases()) {
4773  if (I.isVirtual())
4774  DirectVBases.insert(&I);
4775  }
4776 
4777  // Push virtual bases before others.
4778  for (auto &VBase : ClassDecl->vbases()) {
4780  = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
4781  // [class.base.init]p7, per DR257:
4782  // A mem-initializer where the mem-initializer-id names a virtual base
4783  // class is ignored during execution of a constructor of any class that
4784  // is not the most derived class.
4785  if (ClassDecl->isAbstract()) {
4786  // FIXME: Provide a fixit to remove the base specifier. This requires
4787  // tracking the location of the associated comma for a base specifier.
4788  Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
4789  << VBase.getType() << ClassDecl;
4790  DiagnoseAbstractType(ClassDecl);
4791  }
4792 
4793  Info.AllToInit.push_back(Value);
4794  } else if (!AnyErrors && !ClassDecl->isAbstract()) {
4795  // [class.base.init]p8, per DR257:
4796  // If a given [...] base class is not named by a mem-initializer-id
4797  // [...] and the entity is not a virtual base class of an abstract
4798  // class, then [...] the entity is default-initialized.
4799  bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
4800  CXXCtorInitializer *CXXBaseInit;
4801  if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4802  &VBase, IsInheritedVirtualBase,
4803  CXXBaseInit)) {
4804  HadError = true;
4805  continue;
4806  }
4807 
4808  Info.AllToInit.push_back(CXXBaseInit);
4809  }
4810  }
4811 
4812  // Non-virtual bases.
4813  for (auto &Base : ClassDecl->bases()) {
4814  // Virtuals are in the virtual base list and already constructed.
4815  if (Base.isVirtual())
4816  continue;
4817 
4819  = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
4820  Info.AllToInit.push_back(Value);
4821  } else if (!AnyErrors) {
4822  CXXCtorInitializer *CXXBaseInit;
4823  if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4824  &Base, /*IsInheritedVirtualBase=*/false,
4825  CXXBaseInit)) {
4826  HadError = true;
4827  continue;
4828  }
4829 
4830  Info.AllToInit.push_back(CXXBaseInit);
4831  }
4832  }
4833 
4834  // Fields.
4835  for (auto *Mem : ClassDecl->decls()) {
4836  if (auto *F = dyn_cast<FieldDecl>(Mem)) {
4837  // C++ [class.bit]p2:
4838  // A declaration for a bit-field that omits the identifier declares an
4839  // unnamed bit-field. Unnamed bit-fields are not members and cannot be
4840  // initialized.
4841  if (F->isUnnamedBitfield())
4842  continue;
4843 
4844  // If we're not generating the implicit copy/move constructor, then we'll
4845  // handle anonymous struct/union fields based on their individual
4846  // indirect fields.
4847  if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
4848  continue;
4849 
4850  if (CollectFieldInitializer(*this, Info, F))
4851  HadError = true;
4852  continue;
4853  }
4854 
4855  // Beyond this point, we only consider default initialization.
4856  if (Info.isImplicitCopyOrMove())
4857  continue;
4858 
4859  if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
4860  if (F->getType()->isIncompleteArrayType()) {
4861  assert(ClassDecl->hasFlexibleArrayMember() &&
4862  "Incomplete array type is not valid");
4863  continue;
4864  }
4865 
4866  // Initialize each field of an anonymous struct individually.
4867  if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4868  HadError = true;
4869 
4870  continue;
4871  }
4872  }
4873 
4874  unsigned NumInitializers = Info.AllToInit.size();
4875  if (NumInitializers > 0) {
4876  Constructor->setNumCtorInitializers(NumInitializers);
4877  CXXCtorInitializer **baseOrMemberInitializers =
4878  new (Context) CXXCtorInitializer*[NumInitializers];
4879  memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
4880  NumInitializers * sizeof(CXXCtorInitializer*));
4881  Constructor->setCtorInitializers(baseOrMemberInitializers);
4882 
4883  // Constructors implicitly reference the base and member
4884  // destructors.
4885  MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4886  Constructor->getParent());
4887  }
4888 
4889  return HadError;
4890 }
4891 
4893  if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
4894  const RecordDecl *RD = RT->getDecl();
4895  if (RD->isAnonymousStructOrUnion()) {
4896  for (auto *Field : RD->fields())
4897  PopulateKeysForFields(Field, IdealInits);
4898  return;
4899  }
4900  }
4901  IdealInits.push_back(Field->getCanonicalDecl());
4902 }
4903 
4904 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4905  return Context.getCanonicalType(BaseType).getTypePtr();
4906 }
4907 
4908 static const void *GetKeyForMember(ASTContext &Context,
4909  CXXCtorInitializer *Member) {
4910  if (!Member->isAnyMemberInitializer())
4911  return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
4912 
4913  return Member->getAnyMember()->getCanonicalDecl();
4914 }
4915 
4917  Sema &SemaRef, const CXXConstructorDecl *Constructor,
4919  if (Constructor->getDeclContext()->isDependentContext())
4920  return;
4921 
4922  // Don't check initializers order unless the warning is enabled at the
4923  // location of at least one initializer.
4924  bool ShouldCheckOrder = false;
4925  for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4926  CXXCtorInitializer *Init = Inits[InitIndex];
4927  if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4928  Init->getSourceLocation())) {
4929  ShouldCheckOrder = true;
4930  break;
4931  }
4932  }
4933  if (!ShouldCheckOrder)
4934  return;
4935 
4936  // Build the list of bases and members in the order that they'll
4937  // actually be initialized. The explicit initializers should be in
4938  // this same order but may be missing things.
4939  SmallVector<const void*, 32> IdealInitKeys;
4940 
4941  const CXXRecordDecl *ClassDecl = Constructor->getParent();
4942 
4943  // 1. Virtual bases.
4944  for (const auto &VBase : ClassDecl->vbases())
4945  IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
4946 
4947  // 2. Non-virtual bases.
4948  for (const auto &Base : ClassDecl->bases()) {
4949  if (Base.isVirtual())
4950  continue;
4951  IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
4952  }
4953 
4954  // 3. Direct fields.
4955  for (auto *Field : ClassDecl->fields()) {
4956  if (Field->isUnnamedBitfield())
4957  continue;
4958 
4959  PopulateKeysForFields(Field, IdealInitKeys);
4960  }
4961 
4962  unsigned NumIdealInits = IdealInitKeys.size();
4963  unsigned IdealIndex = 0;
4964 
4965  CXXCtorInitializer *PrevInit = nullptr;
4966  for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4967  CXXCtorInitializer *Init = Inits[InitIndex];
4968  const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
4969 
4970  // Scan forward to try to find this initializer in the idealized
4971  // initializers list.
4972  for (; IdealIndex != NumIdealInits; ++IdealIndex)
4973  if (InitKey == IdealInitKeys[IdealIndex])
4974  break;
4975 
4976  // If we didn't find this initializer, it must be because we
4977  // scanned past it on a previous iteration. That can only
4978  // happen if we're out of order; emit a warning.
4979  if (IdealIndex == NumIdealInits && PrevInit) {
4981  SemaRef.Diag(PrevInit->getSourceLocation(),
4982  diag::warn_initializer_out_of_order);
4983 
4984  if (PrevInit->isAnyMemberInitializer())
4985  D << 0 << PrevInit->getAnyMember()->getDeclName();
4986  else
4987  D << 1 << PrevInit->getTypeSourceInfo()->getType();
4988 
4989  if (Init->isAnyMemberInitializer())
4990  D << 0 << Init->getAnyMember()->getDeclName();
4991  else
4992  D << 1 << Init->getTypeSourceInfo()->getType();
4993 
4994  // Move back to the initializer's location in the ideal list.
4995  for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4996  if (InitKey == IdealInitKeys[IdealIndex])
4997  break;
4998 
4999  assert(IdealIndex < NumIdealInits &&
5000  "initializer not found in initializer list");
5001  }
5002 
5003  PrevInit = Init;
5004  }
5005 }
5006 
5007 namespace {
5008 bool CheckRedundantInit(Sema &S,
5009  CXXCtorInitializer *Init,
5010  CXXCtorInitializer *&PrevInit) {
5011  if (!PrevInit) {
5012  PrevInit = Init;
5013  return false;
5014  }
5015 
5016  if (FieldDecl *Field = Init->getAnyMember())
5017  S.Diag(Init->getSourceLocation(),
5018  diag::err_multiple_mem_initialization)
5019  << Field->getDeclName()
5020  << Init->getSourceRange();
5021  else {
5022  const Type *BaseClass = Init->getBaseClass();
5023  assert(BaseClass && "neither field nor base");
5024  S.Diag(Init->getSourceLocation(),
5025  diag::err_multiple_base_initialization)
5026  << QualType(BaseClass, 0)
5027  << Init->getSourceRange();
5028  }
5029  S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5030  << 0 << PrevInit->getSourceRange();
5031 
5032  return true;
5033 }
5034 
5035 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5036 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5037 
5038 bool CheckRedundantUnionInit(Sema &S,
5039  CXXCtorInitializer *Init,
5040  RedundantUnionMap &Unions) {
5041  FieldDecl *Field = Init->getAnyMember();
5042  RecordDecl *Parent = Field->getParent();
5043  NamedDecl *Child = Field;
5044 
5045  while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5046  if (Parent->isUnion()) {
5047  UnionEntry &En = Unions[Parent];
5048  if (En.first && En.first != Child) {
5049  S.Diag(Init->getSourceLocation(),
5050  diag::err_multiple_mem_union_initialization)
5051  << Field->getDeclName()
5052  << Init->getSourceRange();
5053  S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5054  << 0 << En.second->getSourceRange();
5055  return true;
5056  }
5057  if (!En.first) {
5058  En.first = Child;
5059  En.second = Init;
5060  }
5061  if (!Parent->isAnonymousStructOrUnion())
5062  return false;
5063  }
5064 
5065  Child = Parent;
5066  Parent = cast<RecordDecl>(Parent->getDeclContext());
5067  }
5068 
5069  return false;
5070 }
5071 }
5072 
5073 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5074 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5077  bool AnyErrors) {
5078  if (!ConstructorDecl)
5079  return;
5080 
5081  AdjustDeclIfTemplate(ConstructorDecl);
5082 
5083  CXXConstructorDecl *Constructor
5084  = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5085 
5086  if (!Constructor) {
5087  Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5088  return;
5089  }
5090 
5091  // Mapping for the duplicate initializers check.
5092  // For member initializers, this is keyed with a FieldDecl*.
5093  // For base initializers, this is keyed with a Type*.
5094  llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5095 
5096  // Mapping for the inconsistent anonymous-union initializers check.
5097  RedundantUnionMap MemberUnions;
5098 
5099  bool HadError = false;
5100  for (unsigned i = 0; i < MemInits.size(); i++) {
5101  CXXCtorInitializer *Init = MemInits[i];
5102 
5103  // Set the source order index.
5104  Init->setSourceOrder(i);
5105 
5106  if (Init->isAnyMemberInitializer()) {
5107  const void *Key = GetKeyForMember(Context, Init);
5108  if (CheckRedundantInit(*this, Init, Members[Key]) ||
5109  CheckRedundantUnionInit(*this, Init, MemberUnions))
5110  HadError = true;
5111  } else if (Init->isBaseInitializer()) {
5112  const void *Key = GetKeyForMember(Context, Init);
5113  if (CheckRedundantInit(*this, Init, Members[Key]))
5114  HadError = true;
5115  } else {
5116  assert(Init->isDelegatingInitializer());
5117  // This must be the only initializer
5118  if (MemInits.size() != 1) {
5119  Diag(Init->getSourceLocation(),
5120  diag::err_delegating_initializer_alone)
5121  << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5122  // We will treat this as being the only initializer.
5123  }
5124  SetDelegatingInitializer(Constructor, MemInits[i]);
5125  // Return immediately as the initializer is set.
5126  return;
5127  }
5128  }
5129 
5130  if (HadError)
5131  return;
5132 
5133  DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5134 
5135  SetCtorInitializers(Constructor, AnyErrors, MemInits);
5136 
5137  DiagnoseUninitializedFields(*this, Constructor);
5138 }
5139 
5140 void
5142  CXXRecordDecl *ClassDecl) {
5143  // Ignore dependent contexts. Also ignore unions, since their members never
5144  // have destructors implicitly called.
5145  if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5146  return;
5147 
5148  // FIXME: all the access-control diagnostics are positioned on the
5149  // field/base declaration. That's probably good; that said, the
5150  // user might reasonably want to know why the destructor is being
5151  // emitted, and we currently don't say.
5152 
5153  // Non-static data members.
5154  for (auto *Field : ClassDecl->fields()) {
5155  if (Field->isInvalidDecl())
5156  continue;
5157 
5158  // Don't destroy incomplete or zero-length arrays.
5159  if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5160  continue;
5161 
5162  QualType FieldType = Context.getBaseElementType(Field->getType());
5163 
5164  const RecordType* RT = FieldType->getAs<RecordType>();
5165  if (!RT)
5166  continue;
5167 
5168  CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5169  if (FieldClassDecl->isInvalidDecl())
5170  continue;
5171  if (FieldClassDecl->hasIrrelevantDestructor())
5172  continue;
5173  // The destructor for an implicit anonymous union member is never invoked.
5174  if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5175  continue;
5176 
5177  CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5178  assert(Dtor && "No dtor found for FieldClassDecl!");
5179  CheckDestructorAccess(Field->getLocation(), Dtor,
5180  PDiag(diag::err_access_dtor_field)
5181  << Field->getDeclName()
5182  << FieldType);
5183 
5184  MarkFunctionReferenced(Location, Dtor);
5185  DiagnoseUseOfDecl(Dtor, Location);
5186  }
5187 
5188  // We only potentially invoke the destructors of potentially constructed
5189  // subobjects.
5190  bool VisitVirtualBases = !ClassDecl->isAbstract();
5191 
5192  llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5193 
5194  // Bases.
5195  for (const auto &Base : ClassDecl->bases()) {
5196  // Bases are always records in a well-formed non-dependent class.
5197  const RecordType *RT = Base.getType()->getAs<RecordType>();
5198 
5199  // Remember direct virtual bases.
5200  if (Base.isVirtual()) {
5201  if (!VisitVirtualBases)
5202  continue;
5203  DirectVirtualBases.insert(RT);
5204  }
5205 
5206  CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5207  // If our base class is invalid, we probably can't get its dtor anyway.
5208  if (BaseClassDecl->isInvalidDecl())
5209  continue;
5210  if (BaseClassDecl->hasIrrelevantDestructor())
5211  continue;
5212 
5213  CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5214  assert(Dtor && "No dtor found for BaseClassDecl!");
5215 
5216  // FIXME: caret should be on the start of the class name
5217  CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5218  PDiag(diag::err_access_dtor_base)
5219  << Base.getType() << Base.getSourceRange(),
5220  Context.getTypeDeclType(ClassDecl));
5221 
5222  MarkFunctionReferenced(Location, Dtor);
5223  DiagnoseUseOfDecl(Dtor, Location);
5224  }
5225 
5226  if (!VisitVirtualBases)
5227  return;
5228 
5229  // Virtual bases.
5230  for (const auto &VBase : ClassDecl->vbases()) {
5231  // Bases are always records in a well-formed non-dependent class.
5232  const RecordType *RT = VBase.getType()->castAs<RecordType>();
5233 
5234  // Ignore direct virtual bases.
5235  if (DirectVirtualBases.count(RT))
5236  continue;
5237 
5238  CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5239  // If our base class is invalid, we probably can't get its dtor anyway.
5240  if (BaseClassDecl->isInvalidDecl())
5241  continue;
5242  if (BaseClassDecl->hasIrrelevantDestructor())
5243  continue;
5244 
5245  CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5246  assert(Dtor && "No dtor found for BaseClassDecl!");
5247  if (CheckDestructorAccess(
5248  ClassDecl->getLocation(), Dtor,
5249  PDiag(diag::err_access_dtor_vbase)
5250  << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5251  Context.getTypeDeclType(ClassDecl)) ==
5252  AR_accessible) {
5253  CheckDerivedToBaseConversion(
5254  Context.getTypeDeclType(ClassDecl), VBase.getType(),
5255  diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5256  SourceRange(), DeclarationName(), nullptr);
5257  }
5258 
5259  MarkFunctionReferenced(Location, Dtor);
5260  DiagnoseUseOfDecl(Dtor, Location);
5261  }
5262 }
5263 
5264 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5265  if (!CDtorDecl)
5266  return;
5267 
5268  if (CXXConstructorDecl *Constructor
5269  = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5270  SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5271  DiagnoseUninitializedFields(*this, Constructor);
5272  }
5273 }
5274 
5276  if (!getLangOpts().CPlusPlus)
5277  return false;
5278 
5279  const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5280  if (!RD)
5281  return false;
5282 
5283  // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5284  // class template specialization here, but doing so breaks a lot of code.
5285 
5286  // We can't answer whether something is abstract until it has a
5287  // definition. If it's currently being defined, we'll walk back
5288  // over all the declarations when we have a full definition.
5289  const CXXRecordDecl *Def = RD->getDefinition();
5290  if (!Def || Def->isBeingDefined())
5291  return false;
5292 
5293  return RD->isAbstract();
5294 }
5295 
5297  TypeDiagnoser &Diagnoser) {
5298  if (!isAbstractType(Loc, T))
5299  return false;
5300 
5301  T = Context.getBaseElementType(T);
5302  Diagnoser.diagnose(*this, Loc, T);
5303  DiagnoseAbstractType(T->getAsCXXRecordDecl());
5304  return true;
5305 }
5306 
5308  // Check if we've already emitted the list of pure virtual functions
5309  // for this class.
5310  if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5311  return;
5312 
5313  // If the diagnostic is suppressed, don't emit the notes. We're only
5314  // going to emit them once, so try to attach them to a diagnostic we're
5315  // actually going to show.
5316  if (Diags.isLastDiagnosticIgnored())
5317  return;
5318 
5319  CXXFinalOverriderMap FinalOverriders;
5320  RD->getFinalOverriders(FinalOverriders);
5321 
5322  // Keep a set of seen pure methods so we won't diagnose the same method
5323  // more than once.
5324  llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5325 
5326  for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5327  MEnd = FinalOverriders.end();
5328  M != MEnd;
5329  ++M) {
5330  for (OverridingMethods::iterator SO = M->second.begin(),
5331  SOEnd = M->second.end();
5332  SO != SOEnd; ++SO) {
5333  // C++ [class.abstract]p4:
5334  // A class is abstract if it contains or inherits at least one
5335  // pure virtual function for which the final overrider is pure
5336  // virtual.
5337 
5338  //
5339  if (SO->second.size() != 1)
5340  continue;
5341 
5342  if (!SO->second.front().Method->isPure())
5343  continue;
5344 
5345  if (!SeenPureMethods.insert(SO->second.front().Method).second)
5346  continue;
5347 
5348  Diag(SO->second.front().Method->getLocation(),
5349  diag::note_pure_virtual_function)
5350  << SO->second.front().Method->getDeclName() << RD->getDeclName();
5351  }
5352  }
5353 
5354  if (!PureVirtualClassDiagSet)
5355  PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5356  PureVirtualClassDiagSet->insert(RD);
5357 }
5358 
5359 namespace {
5360 struct AbstractUsageInfo {
5361  Sema &S;
5362  CXXRecordDecl *Record;
5363  CanQualType AbstractType;
5364  bool Invalid;
5365 
5366  AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5367  : S(S), Record(Record),
5368  AbstractType(S.Context.getCanonicalType(
5369  S.Context.getTypeDeclType(Record))),
5370  Invalid(false) {}
5371 
5372  void DiagnoseAbstractType() {
5373  if (Invalid) return;
5374  S.DiagnoseAbstractType(Record);
5375  Invalid = true;
5376  }
5377 
5378  void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5379 };
5380 
5381 struct CheckAbstractUsage {
5382  AbstractUsageInfo &Info;
5383  const NamedDecl *Ctx;
5384 
5385  CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5386  : Info(Info), Ctx(Ctx) {}
5387 
5388  void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5389  switch (TL.getTypeLocClass()) {
5390 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5391 #define TYPELOC(CLASS, PARENT) \
5392  case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5393 #include "clang/AST/TypeLocNodes.def"
5394  }
5395  }
5396 
5397  void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5399  for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5400  if (!TL.getParam(I))
5401  continue;
5402 
5403  TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5404  if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5405  }
5406  }
5407 
5408  void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5410  }
5411 
5413  // Visit the type parameters from a permissive context.
5414  for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5415  TemplateArgumentLoc TAL = TL.getArgLoc(I);
5417  if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5418  Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5419  // TODO: other template argument types?
5420  }
5421  }
5422 
5423  // Visit pointee types from a permissive context.
5424 #define CheckPolymorphic(Type) \
5425  void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5426  Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5427  }
5433 
5434  /// Handle all the types we haven't given a more specific
5435  /// implementation for above.
5436  void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5437  // Every other kind of type that we haven't called out already
5438  // that has an inner type is either (1) sugar or (2) contains that
5439  // inner type in some way as a subobject.
5440  if (TypeLoc Next = TL.getNextTypeLoc())
5441  return Visit(Next, Sel);
5442 
5443  // If there's no inner type and we're in a permissive context,
5444  // don't diagnose.
5445  if (Sel == Sema::AbstractNone) return;
5446 
5447  // Check whether the type matches the abstract type.
5448  QualType T = TL.getType();
5449  if (T->isArrayType()) {
5451  T = Info.S.Context.getBaseElementType(T);
5452  }
5454  if (CT != Info.AbstractType) return;
5455 
5456  // It matched; do some magic.
5457  if (Sel == Sema::AbstractArrayType) {
5458  Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5459  << T << TL.getSourceRange();
5460  } else {
5461  Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5462  << Sel << T << TL.getSourceRange();
5463  }
5464  Info.DiagnoseAbstractType();
5465  }
5466 };
5467 
5468 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5470  CheckAbstractUsage(*this, D).Visit(TL, Sel);
5471 }
5472 
5473 }
5474 
5475 /// Check for invalid uses of an abstract type in a method declaration.
5476 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5477  CXXMethodDecl *MD) {
5478  // No need to do the check on definitions, which require that
5479  // the return/param types be complete.
5480  if (MD->doesThisDeclarationHaveABody())
5481  return;
5482 
5483  // For safety's sake, just ignore it if we don't have type source
5484  // information. This should never happen for non-implicit methods,
5485  // but...
5486  if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5487  Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5488 }
5489 
5490 /// Check for invalid uses of an abstract type within a class definition.
5491 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5492  CXXRecordDecl *RD) {
5493  for (auto *D : RD->decls()) {
5494  if (D->isImplicit()) continue;
5495 
5496  // Methods and method templates.
5497  if (isa<CXXMethodDecl>(D)) {
5498  CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5499  } else if (isa<FunctionTemplateDecl>(D)) {
5500  FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5501  CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5502 
5503  // Fields and static variables.
5504  } else if (isa<FieldDecl>(D)) {
5505  FieldDecl *FD = cast<FieldDecl>(D);
5506  if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5507  Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5508  } else if (isa<VarDecl>(D)) {
5509  VarDecl *VD = cast<VarDecl>(D);
5510  if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5511  Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5512 
5513  // Nested classes and class templates.
5514  } else if (isa<CXXRecordDecl>(D)) {
5515  CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5516  } else if (isa<ClassTemplateDecl>(D)) {
5518  cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5519  }
5520  }
5521 }
5522 
5524  Attr *ClassAttr = getDLLAttr(Class);
5525  if (!ClassAttr)
5526  return;
5527 
5528  assert(ClassAttr->getKind() == attr::DLLExport);
5529 
5531 
5533  // Don't go any further if this is just an explicit instantiation
5534  // declaration.
5535  return;
5536 
5537  if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
5538  S.MarkVTableUsed(Class->getLocation(), Class, true);
5539 
5540  for (Decl *Member : Class->decls()) {
5541  // Defined static variables that are members of an exported base
5542  // class must be marked export too.
5543  auto *VD = dyn_cast<VarDecl>(Member);
5544  if (VD && Member->getAttr<DLLExportAttr>() &&
5545  VD->getStorageClass() == SC_Static &&
5547  S.MarkVariableReferenced(VD->getLocation(), VD);
5548 
5549  auto *MD = dyn_cast<CXXMethodDecl>(Member);
5550  if (!MD)
5551  continue;
5552 
5553  if (Member->getAttr<DLLExportAttr>()) {
5554  if (MD->isUserProvided()) {
5555  // Instantiate non-default class member functions ...
5556 
5557  // .. except for certain kinds of template specializations.
5558  if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5559  continue;
5560 
5561  S.MarkFunctionReferenced(Class->getLocation(), MD);
5562 
5563  // The function will be passed to the consumer when its definition is
5564  // encountered.
5565  } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5566  MD->isCopyAssignmentOperator() ||
5567  MD->isMoveAssignmentOperator()) {
5568  // Synthesize and instantiate non-trivial implicit methods, explicitly
5569  // defaulted methods, and the copy and move assignment operators. The
5570  // latter are exported even if they are trivial, because the address of
5571  // an operator can be taken and should compare equal across libraries.
5572  DiagnosticErrorTrap Trap(S.Diags);
5573  S.MarkFunctionReferenced(Class->getLocation(), MD);
5574  if (Trap.hasErrorOccurred()) {
5575  S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
5576  << Class << !S.getLangOpts().CPlusPlus11;
5577  break;
5578  }
5579 
5580  // There is no later point when we will see the definition of this
5581  // function, so pass it to the consumer now.
5583  }
5584  }
5585  }
5586 }
5587 
5589  CXXRecordDecl *Class) {
5590  // Only the MS ABI has default constructor closures, so we don't need to do
5591  // this semantic checking anywhere else.
5593  return;
5594 
5595  CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5596  for (Decl *Member : Class->decls()) {
5597  // Look for exported default constructors.
5598  auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5599  if (!CD || !CD->isDefaultConstructor())
5600  continue;
5601  auto *Attr = CD->getAttr<DLLExportAttr>();
5602  if (!Attr)
5603  continue;
5604 
5605  // If the class is non-dependent, mark the default arguments as ODR-used so
5606  // that we can properly codegen the constructor closure.
5607  if (!Class->isDependentContext()) {
5608  for (ParmVarDecl *PD : CD->parameters()) {
5609  (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5611  }
5612  }
5613 
5614  if (LastExportedDefaultCtor) {
5615  S.Diag(LastExportedDefaultCtor->getLocation(),
5616  diag::err_attribute_dll_ambiguous_default_ctor)
5617  << Class;
5618  S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5619  << CD->getDeclName();
5620  return;
5621  }
5622  LastExportedDefaultCtor = CD;
5623  }
5624 }
5625 
5627  // Mark any compiler-generated routines with the implicit code_seg attribute.
5628  for (auto *Method : Class->methods()) {
5629  if (Method->isUserProvided())
5630  continue;
5631  if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
5632  Method->addAttr(A);
5633  }
5634 }
5635 
5636 /// Check class-level dllimport/dllexport attribute.
5638  Attr *ClassAttr = getDLLAttr(Class);
5639 
5640  // MSVC inherits DLL attributes to partial class template specializations.
5641  if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
5642  if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
5643  if (Attr *TemplateAttr =
5644  getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
5645  auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
5646  A->setInherited(true);
5647  ClassAttr = A;
5648  }
5649  }
5650  }
5651 
5652  if (!ClassAttr)
5653  return;
5654 
5655  if (!Class->isExternallyVisible()) {
5656  Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
5657  << Class << ClassAttr;
5658  return;
5659  }
5660 
5661  if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5662  !ClassAttr->isInherited()) {
5663  // Diagnose dll attributes on members of class with dll attribute.
5664  for (Decl *Member : Class->decls()) {
5665  if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
5666  continue;
5667  InheritableAttr *MemberAttr = getDLLAttr(Member);
5668  if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
5669  continue;
5670 
5671  Diag(MemberAttr->getLocation(),
5672  diag::err_attribute_dll_member_of_dll_class)
5673  << MemberAttr << ClassAttr;
5674  Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
5675  Member->setInvalidDecl();
5676  }
5677  }
5678 
5679  if (Class->getDescribedClassTemplate())
5680  // Don't inherit dll attribute until the template is instantiated.
5681  return;
5682 
5683  // The class is either imported or exported.
5684  const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
5685 
5686  // Check if this was a dllimport attribute propagated from a derived class to
5687  // a base class template specialization. We don't apply these attributes to
5688  // static data members.
5689  const bool PropagatedImport =
5690  !ClassExported &&
5691  cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
5692 
5694 
5695  // Ignore explicit dllexport on explicit class template instantiation declarations.
5696  if (ClassExported && !ClassAttr->isInherited() &&
5698  Class->dropAttr<DLLExportAttr>();
5699  return;
5700  }
5701 
5702  // Force declaration of implicit members so they can inherit the attribute.
5703  ForceDeclarationOfImplicitMembers(Class);
5704 
5705  // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
5706  // seem to be true in practice?
5707 
5708  for (Decl *Member : Class->decls()) {
5709  VarDecl *VD = dyn_cast<VarDecl>(Member);
5710  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
5711 
5712  // Only methods and static fields inherit the attributes.
5713  if (!VD && !MD)
5714  continue;
5715 
5716  if (MD) {
5717  // Don't process deleted methods.
5718  if (MD->isDeleted())
5719  continue;
5720 
5721  if (MD->isInlined()) {
5722  // MinGW does not import or export inline methods.
5723  if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5724  !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())
5725  continue;
5726 
5727  // MSVC versions before 2015 don't export the move assignment operators
5728  // and move constructor, so don't attempt to import/export them if
5729  // we have a definition.
5730  auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
5731  if ((MD->isMoveAssignmentOperator() ||
5732  (Ctor && Ctor->isMoveConstructor())) &&
5733  !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
5734  continue;
5735 
5736  // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
5737  // operator is exported anyway.
5738  if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5739  (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
5740  continue;
5741  }
5742  }
5743 
5744  // Don't apply dllimport attributes to static data members of class template
5745  // instantiations when the attribute is propagated from a derived class.
5746  if (VD && PropagatedImport)
5747  continue;
5748 
5749  if (!cast<NamedDecl>(Member)->isExternallyVisible())
5750  continue;
5751 
5752  if (!getDLLAttr(Member)) {
5753  InheritableAttr *NewAttr = nullptr;
5754 
5755  // Do not export/import inline function when -fno-dllexport-inlines is
5756  // passed. But add attribute for later local static var check.
5757  if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
5760  if (ClassExported) {
5761  NewAttr = ::new (getASTContext())
5762  DLLExportStaticLocalAttr(ClassAttr->getRange(),
5763  getASTContext(),
5764  ClassAttr->getSpellingListIndex());
5765  } else {
5766  NewAttr = ::new (getASTContext())
5767  DLLImportStaticLocalAttr(ClassAttr->getRange(),
5768  getASTContext(),
5769  ClassAttr->getSpellingListIndex());
5770  }
5771  } else {
5772  NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5773  }
5774 
5775  NewAttr->setInherited(true);
5776  Member->addAttr(NewAttr);
5777 
5778  if (MD) {
5779  // Propagate DLLAttr to friend re-declarations of MD that have already
5780  // been constructed.
5781  for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
5782  FD = FD->getPreviousDecl()) {
5783  if (FD->getFriendObjectKind() == Decl::FOK_None)
5784  continue;
5785  assert(!getDLLAttr(FD) &&
5786  "friend re-decl should not already have a DLLAttr");
5787  NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5788  NewAttr->setInherited(true);
5789  FD->addAttr(NewAttr);
5790  }
5791  }
5792  }
5793  }
5794 
5795  if (ClassExported)
5796  DelayedDllExportClasses.push_back(Class);
5797 }
5798 
5799 /// Perform propagation of DLL attributes from a derived class to a
5800 /// templated base class for MS compatibility.
5802  CXXRecordDecl *Class, Attr *ClassAttr,
5803  ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
5804  if (getDLLAttr(
5805  BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
5806  // If the base class template has a DLL attribute, don't try to change it.
5807  return;
5808  }
5809 
5810  auto TSK = BaseTemplateSpec->getSpecializationKind();
5811  if (!getDLLAttr(BaseTemplateSpec) &&
5813  TSK == TSK_ImplicitInstantiation)) {
5814  // The template hasn't been instantiated yet (or it has, but only as an
5815  // explicit instantiation declaration or implicit instantiation, which means
5816  // we haven't codegenned any members yet), so propagate the attribute.
5817  auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5818  NewAttr->setInherited(true);
5819  BaseTemplateSpec->addAttr(NewAttr);
5820 
5821  // If this was an import, mark that we propagated it from a derived class to
5822  // a base class template specialization.
5823  if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
5824  ImportAttr->setPropagatedToBaseTemplate();
5825 
5826  // If the template is already instantiated, checkDLLAttributeRedeclaration()
5827  // needs to be run again to work see the new attribute. Otherwise this will
5828  // get run whenever the template is instantiated.
5829  if (TSK != TSK_Undeclared)
5830  checkClassLevelDLLAttribute(BaseTemplateSpec);
5831 
5832  return;
5833  }
5834 
5835  if (getDLLAttr(BaseTemplateSpec)) {
5836  // The template has already been specialized or instantiated with an
5837  // attribute, explicitly or through propagation. We should not try to change
5838  // it.
5839  return;
5840  }
5841 
5842  // The template was previously instantiated or explicitly specialized without
5843  // a dll attribute, It's too late for us to add an attribute, so warn that
5844  // this is unsupported.
5845  Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
5846  << BaseTemplateSpec->isExplicitSpecialization();
5847  Diag(ClassAttr->getLocation(), diag::note_attribute);
5848  if (BaseTemplateSpec->isExplicitSpecialization()) {
5849  Diag(BaseTemplateSpec->getLocation(),
5850  diag::note_template_class_explicit_specialization_was_here)
5851  << BaseTemplateSpec;
5852  } else {
5853  Diag(BaseTemplateSpec->getPointOfInstantiation(),
5854  diag::note_template_class_instantiation_was_here)
5855  << BaseTemplateSpec;
5856  }
5857 }
5858 
5860  SourceLocation DefaultLoc) {
5861  switch (S.getSpecialMember(MD)) {
5863  S.DefineImplicitDefaultConstructor(DefaultLoc,
5864  cast<CXXConstructorDecl>(MD));
5865  break;
5867  S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5868  break;
5870  S.DefineImplicitCopyAssignment(DefaultLoc, MD);
5871  break;
5872  case Sema::CXXDestructor:
5873  S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
5874  break;
5876  S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5877  break;
5879  S.DefineImplicitMoveAssignment(DefaultLoc, MD);
5880  break;
5881  case Sema::CXXInvalid:
5882  llvm_unreachable("Invalid special member.");
5883  }
5884 }
5885 
5886 /// Determine whether a type is permitted to be passed or returned in
5887 /// registers, per C++ [class.temporary]p3.
5890  if (D->isDependentType() || D->isInvalidDecl())
5891  return false;
5892 
5893  // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
5894  // The PS4 platform ABI follows the behavior of Clang 3.2.
5895  if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
5896  return !D->hasNonTrivialDestructorForCall() &&
5898 
5899  if (CCK == TargetInfo::CCK_MicrosoftWin64) {
5900  bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
5901  bool DtorIsTrivialForCall = false;
5902 
5903  // If a class has at least one non-deleted, trivial copy constructor, it
5904  // is passed according to the C ABI. Otherwise, it is passed indirectly.
5905  //
5906  // Note: This permits classes with non-trivial copy or move ctors to be
5907  // passed in registers, so long as they *also* have a trivial copy ctor,
5908  // which is non-conforming.
5909  if (D->needsImplicitCopyConstructor()) {
5911  if (D->hasTrivialCopyConstructor())
5912  CopyCtorIsTrivial = true;
5914  CopyCtorIsTrivialForCall = true;
5915  }
5916  } else {
5917  for (const CXXConstructorDecl *CD : D->ctors()) {
5918  if (CD->isCopyConstructor() && !CD->isDeleted()) {
5919  if (CD->isTrivial())
5920  CopyCtorIsTrivial = true;
5921  if (CD->isTrivialForCall())
5922  CopyCtorIsTrivialForCall = true;
5923  }
5924  }
5925  }
5926 
5927  if (D->needsImplicitDestructor()) {
5928  if (!D->defaultedDestructorIsDeleted() &&
5930  DtorIsTrivialForCall = true;
5931  } else if (const auto *DD = D->getDestructor()) {
5932  if (!DD->isDeleted() && DD->isTrivialForCall())
5933  DtorIsTrivialForCall = true;
5934  }
5935 
5936  // If the copy ctor and dtor are both trivial-for-calls, pass direct.
5937  if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
5938  return true;
5939 
5940  // If a class has a destructor, we'd really like to pass it indirectly
5941  // because it allows us to elide copies. Unfortunately, MSVC makes that
5942  // impossible for small types, which it will pass in a single register or
5943  // stack slot. Most objects with dtors are large-ish, so handle that early.
5944  // We can't call out all large objects as being indirect because there are
5945  // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
5946  // how we pass large POD types.
5947 
5948  // Note: This permits small classes with nontrivial destructors to be
5949  // passed in registers, which is non-conforming.
5950  if (CopyCtorIsTrivial &&
5951  S.getASTContext().getTypeSize(D->getTypeForDecl()) <= 64)
5952  return true;
5953  return false;
5954  }
5955 
5956  // Per C++ [class.temporary]p3, the relevant condition is:
5957  // each copy constructor, move constructor, and destructor of X is
5958  // either trivial or deleted, and X has at least one non-deleted copy
5959  // or move constructor
5960  bool HasNonDeletedCopyOrMove = false;
5961 
5962  if (D->needsImplicitCopyConstructor() &&
5965  return false;
5966  HasNonDeletedCopyOrMove = true;
5967  }
5968 
5969  if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
5972  return false;
5973  HasNonDeletedCopyOrMove = true;
5974  }
5975 
5978  return false;
5979 
5980  for (const CXXMethodDecl *MD : D->methods()) {
5981  if (MD->isDeleted())
5982  continue;
5983 
5984  auto *CD = dyn_cast<CXXConstructorDecl>(MD);
5985  if (CD && CD->isCopyOrMoveConstructor())
5986  HasNonDeletedCopyOrMove = true;
5987  else if (!isa<CXXDestructorDecl>(MD))
5988  continue;
5989 
5990  if (!MD->isTrivialForCall())
5991  return false;
5992  }
5993 
5994  return HasNonDeletedCopyOrMove;
5995 }
5996 
5997 /// Perform semantic checks on a class definition that has been
5998 /// completing, introducing implicitly-declared members, checking for
5999 /// abstract types, etc.
6001  if (!Record)
6002  return;
6003 
6004  if (Record->isAbstract() && !Record->isInvalidDecl()) {
6005  AbstractUsageInfo Info(*this, Record);
6006  CheckAbstractClassUsage(Info, Record);
6007  }
6008 
6009  // If this is not an aggregate type and has no user-declared constructor,
6010  // complain about any non-static data members of reference or const scalar
6011  // type, since they will never get initializers.
6012  if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6013  !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6014  !Record->isLambda()) {
6015  bool Complained = false;
6016  for (const auto *F : Record->fields()) {
6017  if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6018  continue;
6019 
6020  if (F->getType()->isReferenceType() ||
6021  (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6022  if (!Complained) {
6023  Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6024  << Record->getTagKind() << Record;
6025  Complained = true;
6026  }
6027 
6028  Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6029  << F->getType()->isReferenceType()
6030  << F->getDeclName();
6031  }
6032  }
6033  }
6034 
6035  if (Record->getIdentifier()) {
6036  // C++ [class.mem]p13:
6037  // If T is the name of a class, then each of the following shall have a
6038  // name different from T:
6039  // - every member of every anonymous union that is a member of class T.
6040  //
6041  // C++ [class.mem]p14:
6042  // In addition, if class T has a user-declared constructor (12.1), every
6043  // non-static data member of class T shall have a name different from T.
6044  DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6045  for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6046  ++I) {
6047  NamedDecl *D = (*I)->getUnderlyingDecl();
6048  if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6049  Record->hasUserDeclaredConstructor()) ||
6050  isa<IndirectFieldDecl>(D)) {
6051  Diag((*I)->getLocation(), diag::err_member_name_of_class)
6052  << D->getDeclName();
6053  break;
6054  }
6055  }
6056  }
6057 
6058  // Warn if the class has virtual methods but non-virtual public destructor.
6059  if (Record->isPolymorphic() && !Record->isDependentType()) {
6060  CXXDestructorDecl *dtor = Record->getDestructor();
6061  if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6062  !Record->hasAttr<FinalAttr>())
6063  Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6064  diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6065  }
6066 
6067  if (Record->isAbstract()) {
6068  if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6069  Diag(Record->getLocation(), diag::warn_abstract_final_class)
6070  << FA->isSpelledAsSealed();
6071  DiagnoseAbstractType(Record);
6072  }
6073  }
6074 
6075  // See if trivial_abi has to be dropped.
6076  if (Record->hasAttr<TrivialABIAttr>())
6077  checkIllFormedTrivialABIStruct(*Record);
6078 
6079  // Set HasTrivialSpecialMemberForCall if the record has attribute
6080  // "trivial_abi".
6081  bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6082 
6083  if (HasTrivialABI)
6085 
6086  bool HasMethodWithOverrideControl = false,
6087  HasOverridingMethodWithoutOverrideControl = false;
6088  if (!Record->isDependentType()) {
6089  for (auto *M : Record->methods()) {
6090  // See if a method overloads virtual methods in a base
6091  // class without overriding any.
6092  if (!M->isStatic())
6093  DiagnoseHiddenVirtualMethods(M);
6094  if (M->hasAttr<OverrideAttr>())
6095  HasMethodWithOverrideControl = true;
6096  else if (M->size_overridden_methods() > 0)
6097  HasOverridingMethodWithoutOverrideControl = true;
6098  // Check whether the explicitly-defaulted special members are valid.
6099  if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
6100  CheckExplicitlyDefaultedSpecialMember(M);
6101 
6102  // For an explicitly defaulted or deleted special member, we defer
6103  // determining triviality until the class is complete. That time is now!
6104  CXXSpecialMember CSM = getSpecialMember(M);
6105  if (!M->isImplicit() && !M->isUserProvided()) {
6106  if (CSM != CXXInvalid) {
6107  M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6108  // Inform the class that we've finished declaring this member.
6110  M->setTrivialForCall(
6111  HasTrivialABI ||
6112  SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6113  Record->setTrivialForCallFlags(M);
6114  }
6115  }
6116 
6117  // Set triviality for the purpose of calls if this is a user-provided
6118  // copy/move constructor or destructor.
6119  if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6120  CSM == CXXDestructor) && M->isUserProvided()) {
6121  M->setTrivialForCall(HasTrivialABI);
6122  Record->setTrivialForCallFlags(M);
6123  }
6124 
6125  if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6126  M->hasAttr<DLLExportAttr>()) {
6127  if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6128  M->isTrivial() &&
6129  (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6130  CSM == CXXDestructor))
6131  M->dropAttr<DLLExportAttr>();
6132 
6133  if (M->hasAttr<DLLExportAttr>()) {
6134  DefineImplicitSpecialMember(*this, M, M->getLocation());
6135  ActOnFinishInlineFunctionDef(M);
6136  }
6137  }
6138  }
6139  }
6140 
6141  if (HasMethodWithOverrideControl &&
6142  HasOverridingMethodWithoutOverrideControl) {
6143  // At least one method has the 'override' control declared.
6144  // Diagnose all other overridden methods which do not have 'override' specified on them.
6145  for (auto *M : Record->methods())
6146  DiagnoseAbsenceOfOverrideControl(M);
6147  }
6148 
6149  // ms_struct is a request to use the same ABI rules as MSVC. Check
6150  // whether this class uses any C++ features that are implemented
6151  // completely differently in MSVC, and if so, emit a diagnostic.
6152  // That diagnostic defaults to an error, but we allow projects to
6153  // map it down to a warning (or ignore it). It's a fairly common
6154  // practice among users of the ms_struct pragma to mass-annotate
6155  // headers, sweeping up a bunch of types that the project doesn't
6156  // really rely on MSVC-compatible layout for. We must therefore
6157  // support "ms_struct except for C++ stuff" as a secondary ABI.
6158  if (Record->isMsStruct(Context) &&
6159  (Record->isPolymorphic() || Record->getNumBases())) {
6160  Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
6161  }
6162 
6163  checkClassLevelDLLAttribute(Record);
6164  checkClassLevelCodeSegAttribute(Record);
6165 
6166  bool ClangABICompat4 =
6167  Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
6169  Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
6170  bool CanPass = canPassInRegisters(*this, Record, CCK);
6171 
6172  // Do not change ArgPassingRestrictions if it has already been set to
6173  // APK_CanNeverPassInRegs.
6175  Record->setArgPassingRestrictions(CanPass
6178 
6179  // If canPassInRegisters returns true despite the record having a non-trivial
6180  // destructor, the record is destructed in the callee. This happens only when
6181  // the record or one of its subobjects has a field annotated with trivial_abi
6182  // or a field qualified with ObjC __strong/__weak.
6184  Record->setParamDestroyedInCallee(true);
6185  else if (Record->hasNonTrivialDestructor())
6186  Record->setParamDestroyedInCallee(CanPass);
6187 
6188  if (getLangOpts().ForceEmitVTables) {
6189  // If we want to emit all the vtables, we need to mark it as used. This
6190  // is especially required for cases like vtable assumption loads.
6191  MarkVTableUsed(Record->getInnerLocStart(), Record);
6192  }
6193 }
6194 
6195 /// Look up the special member function that would be called by a special
6196 /// member function for a subobject of class type.
6197 ///
6198 /// \param Class The class type of the subobject.
6199 /// \param CSM The kind of special member function.
6200 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
6201 /// \param ConstRHS True if this is a copy operation with a const object
6202 /// on its RHS, that is, if the argument to the outer special member
6203 /// function is 'const' and this is not a field marked 'mutable'.
6205  Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
6206  unsigned FieldQuals, bool ConstRHS) {
6207  unsigned LHSQuals = 0;
6208  if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
6209  LHSQuals = FieldQuals;
6210 
6211  unsigned RHSQuals = FieldQuals;
6212  if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
6213  RHSQuals = 0;
6214  else if (ConstRHS)
6215  RHSQuals |= Qualifiers::Const;
6216 
6217  return S.LookupSpecialMember(Class, CSM,
6218  RHSQuals & Qualifiers::Const,
6219  RHSQuals & Qualifiers::Volatile,
6220  false,
6221  LHSQuals & Qualifiers::Const,
6222  LHSQuals & Qualifiers::Volatile);
6223 }
6224 
6226  Sema &S;
6227  SourceLocation UseLoc;
6228 
6229  /// A mapping from the base classes through which the constructor was
6230  /// inherited to the using shadow declaration in that base class (or a null
6231  /// pointer if the constructor was declared in that base class).
6232  llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
6233  InheritedFromBases;
6234 
6235 public:
6238  : S(S), UseLoc(UseLoc) {
6239  bool DiagnosedMultipleConstructedBases = false;
6240  CXXRecordDecl *ConstructedBase = nullptr;
6241  UsingDecl *ConstructedBaseUsing = nullptr;
6242 
6243  // Find the set of such base class subobjects and check that there's a
6244  // unique constructed subobject.
6245  for (auto *D : Shadow->redecls()) {
6246  auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
6247  auto *DNominatedBase = DShadow->getNominatedBaseClass();
6248  auto *DConstructedBase = DShadow->getConstructedBaseClass();
6249 
6250  InheritedFromBases.insert(
6251  std::make_pair(DNominatedBase->getCanonicalDecl(),
6252  DShadow->getNominatedBaseClassShadowDecl()));
6253  if (DShadow->constructsVirtualBase())
6254  InheritedFromBases.insert(
6255  std::make_pair(DConstructedBase->getCanonicalDecl(),
6256  DShadow->getConstructedBaseClassShadowDecl()));
6257  else
6258  assert(DNominatedBase == DConstructedBase);
6259 
6260  // [class.inhctor.init]p2:
6261  // If the constructor was inherited from multiple base class subobjects
6262  // of type B, the program is ill-formed.
6263  if (!ConstructedBase) {
6264  ConstructedBase = DConstructedBase;
6265  ConstructedBaseUsing = D->getUsingDecl();
6266  } else if (ConstructedBase != DConstructedBase &&
6267  !Shadow->isInvalidDecl()) {
6268  if (!DiagnosedMultipleConstructedBases) {
6269  S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
6270  << Shadow->getTargetDecl();
6271  S.Diag(ConstructedBaseUsing->getLocation(),
6272  diag::note_ambiguous_inherited_constructor_using)
6273  << ConstructedBase;
6274  DiagnosedMultipleConstructedBases = true;
6275  }
6276  S.Diag(D->getUsingDecl()->getLocation(),
6277  diag::note_ambiguous_inherited_constructor_using)
6278  << DConstructedBase;
6279  }
6280  }
6281 
6282  if (DiagnosedMultipleConstructedBases)
6283  Shadow->setInvalidDecl();
6284  }
6285 
6286  /// Find the constructor to use for inherited construction of a base class,
6287  /// and whether that base class constructor inherits the constructor from a
6288  /// virtual base class (in which case it won't actually invoke it).
6289  std::pair<CXXConstructorDecl *, bool>
6291  auto It = InheritedFromBases.find(Base->getCanonicalDecl());
6292  if (It == InheritedFromBases.end())
6293  return std::make_pair(nullptr, false);
6294 
6295  // This is an intermediary class.
6296  if (It->second)
6297  return std::make_pair(
6298  S.findInheritingConstructor(UseLoc, Ctor, It->second),
6299  It->second->constructsVirtualBase());
6300 
6301  // This is the base class from which the constructor was inherited.
6302  return std::make_pair(Ctor, false);
6303  }
6304 };
6305 
6306 /// Is the special member function which would be selected to perform the
6307 /// specified operation on the specified class type a constexpr constructor?
6308 static bool
6310  Sema::CXXSpecialMember CSM, unsigned Quals,
6311  bool ConstRHS,
6312  CXXConstructorDecl *InheritedCtor = nullptr,
6313  Sema::InheritedConstructorInfo *Inherited = nullptr) {
6314  // If we're inheriting a constructor, see if we need to call it for this base
6315  // class.
6316  if (InheritedCtor) {
6317  assert(CSM == Sema::CXXDefaultConstructor);
6318  auto BaseCtor =
6319  Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
6320  if (BaseCtor)
6321  return BaseCtor->isConstexpr();
6322  }
6323 
6324  if (CSM == Sema::CXXDefaultConstructor)
6325  return ClassDecl->hasConstexprDefaultConstructor();
6326 
6328  lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
6329  if (!SMOR.getMethod())
6330  // A constructor we wouldn't select can't be "involved in initializing"
6331  // anything.
6332  return true;
6333  return SMOR.getMethod()->isConstexpr();
6334 }
6335 
6336 /// Determine whether the specified special member function would be constexpr
6337 /// if it were implicitly defined.
6339  Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
6340  bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
6341  Sema::InheritedConstructorInfo *Inherited = nullptr) {
6342  if (!S.getLangOpts().CPlusPlus11)
6343  return false;
6344 
6345  // C++11 [dcl.constexpr]p4:
6346  // In the definition of a constexpr constructor [...]
6347  bool Ctor = true;
6348  switch (CSM) {
6350  if (Inherited)
6351  break;
6352  // Since default constructor lookup is essentially trivial (and cannot
6353  // involve, for instance, template instantiation), we compute whether a
6354  // defaulted default constructor is constexpr directly within CXXRecordDecl.
6355  //
6356  // This is important for performance; we need to know whether the default
6357  // constructor is constexpr to determine whether the type is a literal type.
6358  return ClassDecl->defaultedDefaultConstructorIsConstexpr();
6359 
6362  // For copy or move constructors, we need to perform overload resolution.
6363  break;
6364 
6367  if (!S.getLangOpts().CPlusPlus14)
6368  return false;
6369  // In C++1y, we need to perform overload resolution.
6370  Ctor = false;
6371  break;
6372 
6373  case Sema::CXXDestructor:
6374  case Sema::CXXInvalid:
6375  return false;
6376  }
6377 
6378  // -- if the class is a non-empty union, or for each non-empty anonymous
6379  // union member of a non-union class, exactly one non-static data member
6380  // shall be initialized; [DR1359]
6381  //
6382  // If we squint, this is guaranteed, since exactly one non-static data member
6383  // will be initialized (if the constructor isn't deleted), we just don't know
6384  // which one.
6385  if (Ctor && ClassDecl->isUnion())
6386  return CSM == Sema::CXXDefaultConstructor
6387  ? ClassDecl->hasInClassInitializer() ||
6388  !ClassDecl->hasVariantMembers()
6389  : true;
6390 
6391  // -- the class shall not have any virtual base classes;
6392  if (Ctor && ClassDecl->getNumVBases())
6393  return false;
6394 
6395  // C++1y [class.copy]p26:
6396  // -- [the class] is a literal type, and
6397  if (!Ctor && !ClassDecl->isLiteral())
6398  return false;
6399 
6400  // -- every constructor involved in initializing [...] base class
6401  // sub-objects shall be a constexpr constructor;
6402  // -- the assignment operator selected to copy/move each direct base
6403  // class is a constexpr function, and
6404  for (const auto &B : ClassDecl->bases()) {
6405  const RecordType *BaseType = B.getType()->getAs<RecordType>();
6406  if (!BaseType) continue;
6407 
6408  CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6409  if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
6410  InheritedCtor, Inherited))
6411  return false;
6412  }
6413 
6414  // -- every constructor involved in initializing non-static data members
6415  // [...] shall be a constexpr constructor;
6416  // -- every non-static data member and base class sub-object shall be
6417  // initialized
6418  // -- for each non-static data member of X that is of class type (or array
6419  // thereof), the assignment operator selected to copy/move that member is
6420  // a constexpr function
6421  for (const auto *F : ClassDecl->fields()) {
6422  if (F->isInvalidDecl())
6423  continue;
6424  if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
6425  continue;
6426  QualType BaseType = S.Context.getBaseElementType(F->getType());
6427  if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
6428  CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6429  if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
6430  BaseType.getCVRQualifiers(),
6431  ConstArg && !F->isMutable()))
6432  return false;
6433  } else if (CSM == Sema::CXXDefaultConstructor) {
6434  return false;
6435  }
6436  }
6437 
6438  // All OK, it's constexpr!
6439  return true;
6440 }
6441 
6446 
6449  auto CSM = S.getSpecialMember(MD);
6450  if (CSM != Sema::CXXInvalid)
6451  return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr);
6452 
6453  auto *CD = cast<CXXConstructorDecl>(MD);
6454  assert(CD->getInheritedConstructor() &&
6455  "only special members have implicit exception specs");
6457  S, Loc, CD->getInheritedConstructor().getShadowDecl());
6459  S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
6460 }
6461 
6463  CXXMethodDecl *MD) {
6465 
6466  // Build an exception specification pointing back at this member.
6468  EPI.ExceptionSpec.SourceDecl = MD;
6469 
6470  // Set the calling convention to the default for C++ instance methods.
6471  EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
6472  S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6473  /*IsCXXMethod=*/true));
6474  return EPI;
6475 }
6476 
6478  const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
6479  if (FPT->getExceptionSpecType() != EST_Unevaluated)
6480  return;
6481 
6482  // Evaluate the exception specification.
6483  auto IES = computeImplicitExceptionSpec(*this, Loc, MD);
6484  auto ESI = IES.getExceptionSpec();
6485 
6486  // Update the type of the special member to use it.
6487  UpdateExceptionSpec(MD, ESI);
6488 
6489  // A user-provided destructor can be defined outside the class. When that
6490  // happens, be sure to update the exception specification on both
6491  // declarations.
6492  const FunctionProtoType *CanonicalFPT =
6494  if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
6495  UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
6496 }
6497 
6499  CXXRecordDecl *RD = MD->getParent();
6500  CXXSpecialMember CSM = getSpecialMember(MD);
6501 
6502  assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
6503  "not an explicitly-defaulted special member");
6504 
6505  // Whether this was the first-declared instance of the constructor.
6506  // This affects whether we implicitly add an exception spec and constexpr.
6507  bool First = MD == MD->getCanonicalDecl();
6508 
6509  bool HadError = false;
6510 
6511  // C++11 [dcl.fct.def.default]p1:
6512  // A function that is explicitly defaulted shall
6513  // -- be a special member function (checked elsewhere),
6514  // -- have the same type (except for ref-qualifiers, and except that a
6515  // copy operation can take a non-const reference) as an implicit
6516  // declaration, and
6517  // -- not have default arguments.
6518  // C++2a changes the second bullet to instead delete the function if it's
6519  // defaulted on its first declaration, unless it's "an assignment operator,
6520  // and its return type differs or its parameter type is not a reference".
6521  bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus2a && First;
6522  bool ShouldDeleteForTypeMismatch = false;
6523  unsigned ExpectedParams = 1;
6524  if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
6525  ExpectedParams = 0;
6526  if (MD->getNumParams() != ExpectedParams) {
6527  // This checks for default arguments: a copy or move constructor with a
6528  // default argument is classified as a default constructor, and assignment
6529  // operations and destructors can't have default arguments.
6530  Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
6531  << CSM << MD->getSourceRange();
6532  HadError = true;
6533  } else if (MD->isVariadic()) {
6534  if (DeleteOnTypeMismatch)
6535  ShouldDeleteForTypeMismatch = true;
6536  else {
6537  Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
6538  << CSM << MD->getSourceRange();
6539  HadError = true;
6540  }
6541  }
6542 
6544 
6545  bool CanHaveConstParam = false;
6546  if (CSM == CXXCopyConstructor)
6547  CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
6548  else if (CSM == CXXCopyAssignment)
6549  CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
6550 
6551  QualType ReturnType = Context.VoidTy;
6552  if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
6553  // Check for return type matching.
6554  ReturnType = Type->getReturnType();
6555 
6556  QualType DeclType = Context.getTypeDeclType(RD);
6557  DeclType = Context.getAddrSpaceQualType(DeclType, MD->getTypeQualifiers().getAddressSpace());
6558  QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
6559 
6560  if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
6561  Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
6562  << (CSM == CXXMoveAssignment) << ExpectedReturnType;
6563  HadError = true;
6564  }
6565 
6566  // A defaulted special member cannot have cv-qualifiers.
6567  if (Type->getTypeQuals().hasConst() || Type->getTypeQuals().hasVolatile()) {
6568  if (DeleteOnTypeMismatch)
6569  ShouldDeleteForTypeMismatch = true;
6570  else {
6571  Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
6572  << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
6573  HadError = true;
6574  }
6575  }
6576  }
6577 
6578  // Check for parameter type matching.
6579  QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
6580  bool HasConstParam = false;
6581  if (ExpectedParams && ArgType->isReferenceType()) {
6582  // Argument must be reference to possibly-const T.
6583  QualType ReferentType = ArgType->getPointeeType();
6584  HasConstParam = ReferentType.isConstQualified();
6585 
6586  if (ReferentType.isVolatileQualified()) {
6587  if (DeleteOnTypeMismatch)
6588  ShouldDeleteForTypeMismatch = true;
6589  else {
6590  Diag(MD->getLocation(),
6591  diag::err_defaulted_special_member_volatile_param) << CSM;
6592  HadError = true;
6593  }
6594  }
6595 
6596  if (HasConstParam && !CanHaveConstParam) {
6597  if (DeleteOnTypeMismatch)
6598  ShouldDeleteForTypeMismatch = true;
6599  else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
6600  Diag(MD->getLocation(),
6601  diag::err_defaulted_special_member_copy_const_param)
6602  << (CSM == CXXCopyAssignment);
6603  // FIXME: Explain why this special member can't be const.
6604  HadError = true;
6605  } else {
6606  Diag(MD->getLocation(),
6607  diag::err_defaulted_special_member_move_const_param)
6608  << (CSM == CXXMoveAssignment);
6609  HadError = true;
6610  }
6611  }
6612  } else if (ExpectedParams) {
6613  // A copy assignment operator can take its argument by value, but a
6614  // defaulted one cannot.
6615  assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
6616  Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
6617  HadError = true;
6618  }
6619 
6620  // C++11 [dcl.fct.def.default]p2:
6621  // An explicitly-defaulted function may be declared constexpr only if it
6622  // would have been implicitly declared as constexpr,
6623  // Do not apply this rule to members of class templates, since core issue 1358
6624  // makes such functions always instantiate to constexpr functions. For
6625  // functions which cannot be constexpr (for non-constructors in C++11 and for
6626  // destructors in C++1y), this is checked elsewhere.
6627  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
6628  HasConstParam);
6629  if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
6630  : isa<CXXConstructorDecl>(MD)) &&
6631  MD->isConstexpr() && !Constexpr &&
6633  Diag(MD->getBeginLoc(), diag::err_incorrect_defaulted_constexpr) << CSM;
6634  // FIXME: Explain why the special member can't be constexpr.
6635  HadError = true;
6636  }
6637 
6638  // and may have an explicit exception-specification only if it is compatible
6639  // with the exception-specification on the implicit declaration.
6640  if (Type->hasExceptionSpec()) {
6641  // Delay the check if this is the first declaration of the special member,
6642  // since we may not have parsed some necessary in-class initializers yet.
6643  if (First) {
6644  // If the exception specification needs to be instantiated, do so now,
6645  // before we clobber it with an EST_Unevaluated specification below.
6646  if (Type->getExceptionSpecType() == EST_Uninstantiated) {
6647  InstantiateExceptionSpec(MD->getBeginLoc(), MD);
6648  Type = MD->getType()->getAs<FunctionProtoType>();
6649  }
6650  DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
6651  } else
6652  CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
6653  }
6654 
6655  // If a function is explicitly defaulted on its first declaration,
6656  if (First) {
6657  // -- it is implicitly considered to be constexpr if the implicit
6658  // definition would be,
6659  MD->setConstexpr(Constexpr);
6660 
6661  // -- it is implicitly considered to have the same exception-specification
6662  // as if it had been implicitly declared,
6665  EPI.ExceptionSpec.SourceDecl = MD;
6666  MD->setType(Context.getFunctionType(ReturnType,
6667  llvm::makeArrayRef(&ArgType,
6668  ExpectedParams),
6669  EPI));
6670  }
6671 
6672  if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
6673  if (First) {
6674  SetDeclDeleted(MD, MD->getLocation());
6675  if (!inTemplateInstantiation() && !HadError) {
6676  Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
6677  if (ShouldDeleteForTypeMismatch) {
6678  Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
6679  } else {
6680  ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6681  }
6682  }
6683  if (ShouldDeleteForTypeMismatch && !HadError) {
6684  Diag(MD->getLocation(),
6685  diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
6686  }
6687  } else {
6688  // C++11 [dcl.fct.def.default]p4:
6689  // [For a] user-provided explicitly-defaulted function [...] if such a
6690  // function is implicitly defined as deleted, the program is ill-formed.
6691  Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
6692  assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
6693  ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6694  HadError = true;
6695  }
6696  }
6697 
6698  if (HadError)
6699  MD->setInvalidDecl();
6700 }
6701 
6702 /// Check whether the exception specification provided for an
6703 /// explicitly-defaulted special member matches the exception specification
6704 /// that would have been generated for an implicit special member, per
6705 /// C++11 [dcl.fct.def.default]p2.
6707  CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
6708  // If the exception specification was explicitly specified but hadn't been
6709  // parsed when the method was defaulted, grab it now.
6710  if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
6711  SpecifiedType =
6713 
6714  // Compute the implicit exception specification.
6715  CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6716  /*IsCXXMethod=*/true);
6718  auto IES = computeImplicitExceptionSpec(*this, MD->getLocation(), MD);
6719  EPI.ExceptionSpec = IES.getExceptionSpec();
6720  const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
6721  Context.getFunctionType(Context.VoidTy, None, EPI));
6722 
6723  // Ensure that it matches.
6724  CheckEquivalentExceptionSpec(
6725  PDiag(diag::err_incorrect_defaulted_exception_spec)
6726  << getSpecialMember(MD), PDiag(),
6727  ImplicitType, SourceLocation(),
6728  SpecifiedType, MD->getLocation());
6729 }
6730 
6732  decltype(DelayedOverridingExceptionSpecChecks) Overriding;
6733  decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
6734  decltype(DelayedDefaultedMemberExceptionSpecs) Defaulted;
6735 
6736  std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
6737  std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
6738  std::swap(Defaulted, DelayedDefaultedMemberExceptionSpecs);
6739 
6740  // Perform any deferred checking of exception specifications for virtual
6741  // destructors.
6742  for (auto &Check : Overriding)
6743  CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
6744 
6745  // Perform any deferred checking of exception specifications for befriended
6746  // special members.
6747  for (auto &Check : Equivalent)
6748  CheckEquivalentExceptionSpec(Check.second, Check.first);
6749 
6750  // Check that any explicitly-defaulted methods have exception specifications
6751  // compatible with their implicit exception specifications.
6752  for (auto &Spec : Defaulted)
6753  CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
6754 }
6755 
6756 namespace {
6757 /// CRTP base class for visiting operations performed by a special member
6758 /// function (or inherited constructor).
6759 template<typename Derived>
6760 struct SpecialMemberVisitor {
6761  Sema &S;
6762  CXXMethodDecl *MD;
6765 
6766  // Properties of the special member, computed for convenience.
6767  bool IsConstructor = false, IsAssignment = false, ConstArg = false;
6768 
6769  SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6771  : S(S), MD(MD), CSM(CSM), ICI(ICI) {
6772  switch (CSM) {
6776  IsConstructor = true;
6777  break;
6780  IsAssignment = true;
6781  break;
6782  case Sema::CXXDestructor:
6783  break;
6784  case Sema::CXXInvalid:
6785  llvm_unreachable("invalid special member kind");
6786  }
6787 
6788  if (MD->getNumParams()) {
6789  if (const ReferenceType *RT =
6790  MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
6791  ConstArg = RT->getPointeeType().isConstQualified();
6792  }
6793  }
6794 
6795  Derived &getDerived() { return static_cast<Derived&>(*this); }
6796 
6797  /// Is this a "move" special member?
6798  bool isMove() const {
6799  return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
6800  }
6801 
6802  /// Look up the corresponding special member in the given class.
6804  unsigned Quals, bool IsMutable) {
6805  return lookupCallFromSpecialMember(S, Class, CSM, Quals,
6806  ConstArg && !IsMutable);
6807  }
6808 
6809  /// Look up the constructor for the specified base class to see if it's
6810  /// overridden due to this being an inherited constructor.
6811  Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
6812  if (!ICI)
6813  return {};
6814  assert(CSM == Sema::CXXDefaultConstructor);
6815  auto *BaseCtor =
6816  cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
6817  if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
6818  return MD;
6819  return {};
6820  }
6821 
6822  /// A base or member subobject.
6823  typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
6824 
6825  /// Get the location to use for a subobject in diagnostics.
6826  static SourceLocation getSubobjectLoc(Subobject Subobj) {
6827  // FIXME: For an indirect virtual base, the direct base leading to
6828  // the indirect virtual base would be a more useful choice.
6829  if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
6830  return B->getBaseTypeLoc();
6831  else
6832  return Subobj.get<FieldDecl*>()->getLocation();
6833  }
6834 
6835  enum BasesToVisit {
6836  /// Visit all non-virtual (direct) bases.
6837  VisitNonVirtualBases,
6838  /// Visit all direct bases, virtual or not.
6839  VisitDirectBases,
6840  /// Visit all non-virtual bases, and all virtual bases if the class
6841  /// is not abstract.
6842  VisitPotentiallyConstructedBases,
6843  /// Visit all direct or virtual bases.
6844  VisitAllBases
6845  };
6846 
6847  // Visit the bases and members of the class.
6848  bool visit(BasesToVisit Bases) {
6849  CXXRecordDecl *RD = MD->getParent();
6850 
6851  if (Bases == VisitPotentiallyConstructedBases)
6852  Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
6853 
6854  for (auto &B : RD->bases())
6855  if ((Bases == VisitDirectBases || !B.isVirtual()) &&
6856  getDerived().visitBase(&B))
6857  return true;
6858 
6859  if (Bases == VisitAllBases)
6860  for (auto &B : RD->vbases())
6861  if (getDerived().visitBase(&B))
6862  return true;
6863 
6864  for (auto *F : RD->fields())
6865  if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
6866  getDerived().visitField(F))
6867  return true;
6868 
6869  return false;
6870  }
6871 };
6872 }
6873 
6874 namespace {
6875 struct SpecialMemberDeletionInfo
6876  : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
6877  bool Diagnose;
6878 
6879  SourceLocation Loc;
6880 
6881  bool AllFieldsAreConst;
6882 
6883  SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
6885  Sema::InheritedConstructorInfo *ICI, bool Diagnose)
6886  : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
6887  Loc(MD->getLocation()), AllFieldsAreConst(true) {}
6888 
6889  bool inUnion() const { return MD->getParent()->isUnion(); }
6890 
6891  Sema::CXXSpecialMember getEffectiveCSM() {
6892  return ICI ? Sema::CXXInvalid : CSM;
6893  }
6894 
6895  bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
6896  bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
6897 
6898  bool shouldDeleteForBase(CXXBaseSpecifier *Base);
6899  bool shouldDeleteForField(FieldDecl *FD);
6900  bool shouldDeleteForAllConstMembers();
6901 
6902  bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
6903  unsigned Quals);
6904  bool shouldDeleteForSubobjectCall(Subobject Subobj,
6906  bool IsDtorCallInCtor);
6907 
6908  bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
6909 };
6910 }
6911 
6912 /// Is the given special member inaccessible when used on the given
6913 /// sub-object.
6914 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
6915  CXXMethodDecl *target) {
6916  /// If we're operating on a base class, the object type is the
6917  /// type of this special member.
6918  QualType objectTy;
6919  AccessSpecifier access = target->getAccess();
6920  if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
6921  objectTy = S.Context.getTypeDeclType(MD->getParent());
6922  access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
6923 
6924  // If we're operating on a field, the object type is the type of the field.
6925  } else {
6926  objectTy = S.Context.getTypeDeclType(target->getParent());
6927  }
6928 
6929  return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
6930 }
6931 
6932 /// Check whether we should delete a special member due to the implicit
6933 /// definition containing a call to a special member of a subobject.
6934 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
6935  Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
6936  bool IsDtorCallInCtor) {
6937  CXXMethodDecl *Decl = SMOR.getMethod();
6938  FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6939 
6940  int DiagKind = -1;
6941 
6943  DiagKind = !Decl ? 0 : 1;
6945  DiagKind = 2;
6946  else if (!isAccessible(Subobj, Decl))
6947  DiagKind = 3;
6948  else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
6949  !Decl->isTrivial()) {
6950  // A member of a union must have a trivial corresponding special member.
6951  // As a weird special case, a destructor call from a union's constructor
6952  // must be accessible and non-deleted, but need not be trivial. Such a
6953  // destructor is never actually called, but is semantically checked as
6954  // if it were.
6955  DiagKind = 4;
6956  }
6957 
6958  if (DiagKind == -1)
6959  return false;
6960 
6961  if (Diagnose) {
6962  if (Field) {
6963  S.Diag(Field->getLocation(),
6964  diag::note_deleted_special_member_class_subobject)
6965  << getEffectiveCSM() << MD->getParent() << /*IsField*/true
6966  << Field << DiagKind << IsDtorCallInCtor;
6967  } else {
6968  CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
6969  S.Diag(Base->getBeginLoc(),
6970  diag::note_deleted_special_member_class_subobject)
6971  << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
6972  << Base->getType() << DiagKind << IsDtorCallInCtor;
6973  }
6974 
6975  if (DiagKind == 1)
6976  S.NoteDeletedFunction(Decl);
6977  // FIXME: Explain inaccessibility if DiagKind == 3.
6978  }
6979 
6980  return true;
6981 }
6982 
6983 /// Check whether we should delete a special member function due to having a
6984 /// direct or virtual base class or non-static data member of class type M.
6985 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
6986  CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
6987  FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6988  bool IsMutable = Field && Field->isMutable();
6989 
6990  // C++11 [class.ctor]p5:
6991  // -- any direct or virtual base class, or non-static data member with no
6992  // brace-or-equal-initializer, has class type M (or array thereof) and
6993  // either M has no default constructor or overload resolution as applied
6994  // to M's default constructor results in an ambiguity or in a function
6995  // that is deleted or inaccessible
6996  // C++11 [class.copy]p11, C++11 [class.copy]p23:
6997  // -- a direct or virtual base class B that cannot be copied/moved because
6998  // overload resolution, as applied to B's corresponding special member,
6999  // results in an ambiguity or a function that is deleted or inaccessible
7000  // from the defaulted special member
7001  // C++11 [class.dtor]p5:
7002  // -- any direct or virtual base class [...] has a type with a destructor
7003  // that is deleted or inaccessible
7004  if (!(CSM == Sema::CXXDefaultConstructor &&
7005  Field && Field->hasInClassInitializer()) &&
7006  shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
7007  false))
7008  return true;
7009 
7010  // C++11 [class.ctor]p5, C++11 [class.copy]p11:
7011  // -- any direct or virtual base class or non-static data member has a
7012  // type with a destructor that is deleted or inaccessible
7013  if (IsConstructor) {
7016  false, false, false, false, false);
7017  if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
7018  return true;
7019  }
7020 
7021  return false;
7022 }
7023 
7024 /// Check whether we should delete a special member function due to the class
7025 /// having a particular direct or virtual base class.
7026 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
7027  CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
7028  // If program is correct, BaseClass cannot be null, but if it is, the error
7029  // must be reported elsewhere.
7030  if (!BaseClass)
7031  return false;
7032  // If we have an inheriting constructor, check whether we're calling an
7033  // inherited constructor instead of a default constructor.
7034  Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
7035  if (auto *BaseCtor = SMOR.getMethod()) {
7036  // Note that we do not check access along this path; other than that,
7037  // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
7038  // FIXME: Check that the base has a usable destructor! Sink this into
7039  // shouldDeleteForClassSubobject.
7040  if (BaseCtor->isDeleted() && Diagnose) {
7041  S.Diag(Base->getBeginLoc(),
7042  diag::note_deleted_special_member_class_subobject)
7043  << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
7044  << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false;
7045  S.NoteDeletedFunction(BaseCtor);
7046  }
7047  return BaseCtor->isDeleted();
7048  }
7049  return shouldDeleteForClassSubobject(BaseClass, Base, 0);
7050 }
7051 
7052 /// Check whether we should delete a special member function due to the class
7053 /// having a particular non-static data member.
7054 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
7055  QualType FieldType = S.Context.getBaseElementType(FD->getType());
7056  CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
7057 
7058  if (CSM == Sema::CXXDefaultConstructor) {
7059  // For a default constructor, all references must be initialized in-class
7060  // and, if a union, it must have a non-const member.
7061  if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
7062  if (Diagnose)
7063  S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
7064  << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
7065  return true;
7066  }
7067  // C++11 [class.ctor]p5: any non-variant non-static data member of
7068  // const-qualified type (or array thereof) with no
7069  // brace-or-equal-initializer does not have a user-provided default
7070  // constructor.
7071  if (!inUnion() && FieldType.isConstQualified() &&
7072  !FD->hasInClassInitializer() &&
7073  (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
7074  if (Diagnose)
7075  S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
7076  << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
7077  return true;
7078  }
7079 
7080  if (inUnion() && !FieldType.isConstQualified())
7081  AllFieldsAreConst = false;
7082  } else if (CSM == Sema::CXXCopyConstructor) {
7083  // For a copy constructor, data members must not be of rvalue reference
7084  // type.
7085  if (FieldType->isRValueReferenceType()) {
7086  if (Diagnose)
7087  S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
7088  << MD->getParent() << FD << FieldType;
7089  return true;
7090  }
7091  } else if (IsAssignment) {
7092  // For an assignment operator, data members must not be of reference type.
7093  if (FieldType->isReferenceType()) {
7094  if (Diagnose)
7095  S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
7096  << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
7097  return true;
7098  }
7099  if (!FieldRecord && FieldType.isConstQualified()) {
7100  // C++11 [class.copy]p23:
7101  // -- a non-static data member of const non-class type (or array thereof)
7102  if (Diagnose)
7103  S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
7104  << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
7105  return true;
7106  }
7107  }
7108 
7109  if (FieldRecord) {
7110  // Some additional restrictions exist on the variant members.
7111  if (!inUnion() && FieldRecord->isUnion() &&
7112  FieldRecord->isAnonymousStructOrUnion()) {
7113  bool AllVariantFieldsAreConst = true;
7114 
7115  // FIXME: Handle anonymous unions declared within anonymous unions.
7116  for (auto *UI : FieldRecord->fields()) {
7117  QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
7118 
7119  if (!UnionFieldType.isConstQualified())
7120  AllVariantFieldsAreConst = false;
7121 
7122  CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
7123  if (UnionFieldRecord &&
7124  shouldDeleteForClassSubobject(UnionFieldRecord, UI,
7125  UnionFieldType.getCVRQualifiers()))
7126  return true;
7127  }
7128 
7129  // At least one member in each anonymous union must be non-const
7130  if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
7131  !FieldRecord->field_empty()) {
7132  if (Diagnose)
7133  S.Diag(FieldRecord->getLocation(),
7134  diag::note_deleted_default_ctor_all_const)
7135  << !!ICI << MD->getParent() << /*anonymous union*/1;
7136  return true;
7137  }
7138 
7139  // Don't check the implicit member of the anonymous union type.
7140  // This is technically non-conformant, but sanity demands it.
7141  return false;
7142  }
7143 
7144  if (shouldDeleteForClassSubobject(FieldRecord, FD,
7145  FieldType.getCVRQualifiers()))
7146  return true;
7147  }
7148 
7149  return false;
7150 }
7151 
7152 /// C++11 [class.ctor] p5:
7153 /// A defaulted default constructor for a class X is defined as deleted if
7154 /// X is a union and all of its variant members are of const-qualified type.
7155 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
7156  // This is a silly definition, because it gives an empty union a deleted
7157  // default constructor. Don't do that.
7158  if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
7159  bool AnyFields = false;
7160  for (auto *F : MD->getParent()->fields())
7161  if ((AnyFields = !F->isUnnamedBitfield()))
7162  break;
7163  if (!AnyFields)
7164  return false;
7165  if (Diagnose)
7166  S.Diag(MD->getParent()->getLocation(),
7167  diag::note_deleted_default_ctor_all_const)
7168  << !!ICI << MD->getParent() << /*not anonymous union*/0;
7169  return true;
7170  }
7171  return false;
7172 }
7173 
7174 /// Determine whether a defaulted special member function should be defined as
7175 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
7176 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
7179  bool Diagnose) {
7180  if (MD->isInvalidDecl())
7181  return false;
7182  CXXRecordDecl *RD = MD->getParent();
7183  assert(!RD->isDependentType() && "do deletion after instantiation");
7184  if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
7185  return false;
7186 
7187  // C++11 [expr.lambda.prim]p19:
7188  // The closure type associated with a lambda-expression has a
7189  // deleted (8.4.3) default constructor and a deleted copy
7190  // assignment operator.
7191  // C++2a adds back these operators if the lambda has no capture-default.
7193  (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
7194  if (Diagnose)
7195  Diag(RD->getLocation(), diag::note_lambda_decl);
7196  return true;
7197  }
7198 
7199  // For an anonymous struct or union, the copy and assignment special members
7200  // will never be used, so skip the check. For an anonymous union declared at
7201  // namespace scope, the constructor and destructor are used.
7202  if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
7204  return false;
7205 
7206  // C++11 [class.copy]p7, p18:
7207  // If the class definition declares a move constructor or move assignment
7208  // operator, an implicitly declared copy constructor or copy assignment
7209  // operator is defined as deleted.
7210  if (MD->isImplicit() &&
7211  (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
7212  CXXMethodDecl *UserDeclaredMove = nullptr;
7213 
7214  // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
7215  // deletion of the corresponding copy operation, not both copy operations.
7216  // MSVC 2015 has adopted the standards conforming behavior.
7217  bool DeletesOnlyMatchingCopy =
7218  getLangOpts().MSVCCompat &&
7219  !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
7220 
7221  if (RD->hasUserDeclaredMoveConstructor() &&
7222  (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
7223  if (!Diagnose) return true;
7224 
7225  // Find any user-declared move constructor.
7226  for (auto *I : RD->ctors()) {
7227  if (I->isMoveConstructor()) {
7228  UserDeclaredMove = I;
7229  break;
7230  }
7231  }
7232  assert(UserDeclaredMove);
7233  } else if (RD->hasUserDeclaredMoveAssignment() &&
7234  (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
7235  if (!Diagnose) return true;
7236 
7237  // Find any user-declared move assignment operator.
7238  for (auto *I : RD->methods()) {
7239  if (I->isMoveAssignmentOperator()) {
7240  UserDeclaredMove = I;
7241  break;
7242  }
7243  }
7244  assert(UserDeclaredMove);
7245  }
7246 
7247  if (UserDeclaredMove) {
7248  Diag(UserDeclaredMove->getLocation(),
7249  diag::note_deleted_copy_user_declared_move)
7250  << (CSM == CXXCopyAssignment) << RD
7251  << UserDeclaredMove->isMoveAssignmentOperator();
7252  return true;
7253  }
7254  }
7255 
7256  // Do access control from the special member function
7257  ContextRAII MethodContext(*this, MD);
7258 
7259  // C++11 [class.dtor]p5:
7260  // -- for a virtual destructor, lookup of the non-array deallocation function
7261  // results in an ambiguity or in a function that is deleted or inaccessible
7262  if (CSM == CXXDestructor && MD->isVirtual()) {
7263  FunctionDecl *OperatorDelete = nullptr;
7264  DeclarationName Name =
7265  Context.DeclarationNames.getCXXOperatorName(OO_Delete);
7266  if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
7267  OperatorDelete, /*Diagnose*/false)) {
7268  if (Diagnose)
7269  Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
7270  return true;
7271  }
7272  }
7273 
7274  SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
7275 
7276  // Per DR1611, do not consider virtual bases of constructors of abstract
7277  // classes, since we are not going to construct them.
7278  // Per DR1658, do not consider virtual bases of destructors of abstract
7279  // classes either.
7280  // Per DR2180, for assignment operators we only assign (and thus only
7281  // consider) direct bases.
7282  if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
7283  : SMI.VisitPotentiallyConstructedBases))
7284  return true;
7285 
7286  if (SMI.shouldDeleteForAllConstMembers())
7287  return true;
7288 
7289  if (getLangOpts().CUDA) {
7290  // We should delete the special member in CUDA mode if target inference
7291  // failed.
7292  // For inherited constructors (non-null ICI), CSM may be passed so that MD
7293  // is treated as certain special member, which may not reflect what special
7294  // member MD really is. However inferCUDATargetForImplicitSpecialMember
7295  // expects CSM to match MD, therefore recalculate CSM.
7296  assert(ICI || CSM == getSpecialMember(MD));
7297  auto RealCSM = CSM;
7298  if (ICI)
7299  RealCSM = getSpecialMember(MD);
7300 
7301  return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
7302  SMI.ConstArg, Diagnose);
7303  }
7304 
7305  return false;
7306 }
7307 
7308 /// Perform lookup for a special member of the specified kind, and determine
7309 /// whether it is trivial. If the triviality can be determined without the
7310 /// lookup, skip it. This is intended for use when determining whether a
7311 /// special member of a containing object is trivial, and thus does not ever
7312 /// perform overload resolution for default constructors.
7313 ///
7314 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
7315 /// member that was most likely to be intended to be trivial, if any.
7316 ///
7317 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
7318 /// determine whether the special member is trivial.
7320  Sema::CXXSpecialMember CSM, unsigned Quals,
7321  bool ConstRHS,
7323  CXXMethodDecl **Selected) {
7324  if (Selected)
7325  *Selected = nullptr;
7326 
7327  switch (CSM) {
7328  case Sema::CXXInvalid:
7329  llvm_unreachable("not a special member");
7330 
7332  // C++11 [class.ctor]p5:
7333  // A default constructor is trivial if:
7334  // - all the [direct subobjects] have trivial default constructors
7335  //
7336  // Note, no overload resolution is performed in this case.
7337  if (RD->hasTrivialDefaultConstructor())
7338  return true;
7339 
7340  if (Selected) {
7341  // If there's a default constructor which could have been trivial, dig it
7342  // out. Otherwise, if there's any user-provided default constructor, point
7343  // to that as an example of why there's not a trivial one.
7344  CXXConstructorDecl *DefCtor = nullptr;
7347  for (auto *CI : RD->ctors()) {
7348  if (!CI->isDefaultConstructor())
7349  continue;
7350  DefCtor = CI;
7351  if (!DefCtor->isUserProvided())
7352  break;
7353  }
7354 
7355  *Selected = DefCtor;
7356  }
7357 
7358  return false;
7359 
7360  case Sema::CXXDestructor:
7361  // C++11 [class.dtor]p5:
7362  // A destructor is trivial if:
7363  // - all the direct [subobjects] have trivial destructors
7364  if (RD->hasTrivialDestructor() ||
7365  (TAH == Sema::TAH_ConsiderTrivialABI &&
7367  return true;
7368 
7369  if (Selected) {
7370  if (RD->needsImplicitDestructor())
7372  *Selected = RD->getDestructor();
7373  }
7374 
7375  return false;
7376 
7378  // C++11 [class.copy]p12:
7379  // A copy constructor is trivial if:
7380  // - the constructor selected to copy each direct [subobject] is trivial
7381  if (RD->hasTrivialCopyConstructor() ||
7382  (TAH == Sema::TAH_ConsiderTrivialABI &&
7384  if (Quals == Qualifiers::Const)
7385  // We must either select the trivial copy constructor or reach an
7386  // ambiguity; no need to actually perform overload resolution.
7387  return true;
7388  } else if (!Selected) {
7389  return false;
7390  }
7391  // In C++98, we are not supposed to perform overload resolution here, but we
7392  // treat that as a language defect, as suggested on cxx-abi-dev, to treat
7393  // cases like B as having a non-trivial copy constructor:
7394  // struct A { template<typename T> A(T&); };
7395  // struct B { mutable A a; };
7396  goto NeedOverloadResolution;
7397 
7399  // C++11 [class.copy]p25:
7400  // A copy assignment operator is trivial if:
7401  // - the assignment operator selected to copy each direct [subobject] is
7402  // trivial
7403  if (RD->hasTrivialCopyAssignment()) {
7404  if (Quals == Qualifiers::Const)
7405  return true;
7406  } else if (!Selected) {
7407  return false;
7408  }
7409  // In C++98, we are not supposed to perform overload resolution here, but we
7410  // treat that as a language defect.
7411  goto NeedOverloadResolution;
7412 
7415  NeedOverloadResolution:
7417  lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
7418 
7419  // The standard doesn't describe how to behave if the lookup is ambiguous.
7420  // We treat it as not making the member non-trivial, just like the standard
7421  // mandates for the default constructor. This should rarely matter, because
7422  // the member will also be deleted.
7424  return true;
7425 
7426  if (!SMOR.getMethod()) {
7427  assert(SMOR.getKind() ==
7429  return false;
7430  }
7431 
7432  // We deliberately don't check if we found a deleted special member. We're
7433  // not supposed to!
7434  if (Selected)
7435  *Selected = SMOR.getMethod();
7436 
7437  if (TAH == Sema::TAH_ConsiderTrivialABI &&
7439  return SMOR.getMethod()->isTrivialForCall();
7440  return SMOR.getMethod()->isTrivial();
7441  }
7442 
7443  llvm_unreachable("unknown special method kind");
7444 }
7445 
7447  for (auto *CI : RD->ctors())
7448  if (!CI->isImplicit())
7449  return CI;
7450 
7451  // Look for constructor templates.
7452  typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
7453  for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
7454  if (CXXConstructorDecl *CD =
7455  dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
7456  return CD;
7457  }
7458 
7459  return nullptr;
7460 }
7461 
7462 /// The kind of subobject we are checking for triviality. The values of this
7463 /// enumeration are used in diagnostics.
7465  /// The subobject is a base class.
7467  /// The subobject is a non-static data member.
7469  /// The object is actually the complete object.
7471 };
7472 
7473 /// Check whether the special member selected for a given type would be trivial.
7475  QualType SubType, bool ConstRHS,
7478  Sema::TrivialABIHandling TAH, bool Diagnose) {
7479  CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
7480  if (!SubRD)
7481  return true;
7482 
7483  CXXMethodDecl *Selected;
7484  if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
7485  ConstRHS, TAH, Diagnose ? &Selected : nullptr))
7486  return true;
7487 
7488  if (Diagnose) {
7489  if (ConstRHS)
7490  SubType.addConst();
7491 
7492  if (!Selected && CSM == Sema::CXXDefaultConstructor) {
7493  S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
7494  << Kind << SubType.getUnqualifiedType();
7495  if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
7496  S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
7497  } else if (!Selected)
7498  S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
7499  << Kind << SubType.getUnqualifiedType() << CSM << SubType;
7500  else if (Selected->isUserProvided()) {
7501  if (Kind == TSK_CompleteObject)
7502  S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
7503  << Kind << SubType.getUnqualifiedType() << CSM;
7504  else {
7505  S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
7506  << Kind << SubType.getUnqualifiedType() << CSM;
7507  S.Diag(Selected->getLocation(), diag::note_declared_at);
7508  }
7509  } else {
7510  if (Kind != TSK_CompleteObject)
7511  S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
7512  << Kind << SubType.getUnqualifiedType() << CSM;
7513 
7514  // Explain why the defaulted or deleted special member isn't trivial.
7516  Diagnose);
7517  }
7518  }
7519 
7520  return false;
7521 }
7522 
7523 /// Check whether the members of a class type allow a special member to be
7524 /// trivial.
7527  bool ConstArg,
7529  bool Diagnose) {
7530  for (const auto *FI : RD->fields()) {
7531  if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
7532  continue;
7533 
7534  QualType FieldType = S.Context.getBaseElementType(FI->getType());
7535 
7536  // Pretend anonymous struct or union members are members of this class.
7537  if (FI->isAnonymousStructOrUnion()) {
7538  if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
7539  CSM, ConstArg, TAH, Diagnose))
7540  return false;
7541  continue;
7542  }
7543 
7544  // C++11 [class.ctor]p5:
7545  // A default constructor is trivial if [...]
7546  // -- no non-static data member of its class has a
7547  // brace-or-equal-initializer
7548  if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
7549  if (Diagnose)
7550  S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
7551  return false;
7552  }
7553 
7554  // Objective C ARC 4.3.5:
7555  // [...] nontrivally ownership-qualified types are [...] not trivially
7556  // default constructible, copy constructible, move constructible, copy
7557  // assignable, move assignable, or destructible [...]
7558  if (FieldType.hasNonTrivialObjCLifetime()) {
7559  if (Diagnose)
7560  S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
7561  << RD << FieldType.getObjCLifetime();
7562  return false;
7563  }
7564 
7565  bool ConstRHS = ConstArg && !FI->isMutable();
7566  if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
7567  CSM, TSK_Field, TAH, Diagnose))
7568  return false;
7569  }
7570 
7571  return true;
7572 }
7573 
7574 /// Diagnose why the specified class does not have a trivial special member of
7575 /// the given kind.
7577  QualType Ty = Context.getRecordType(RD);
7578 
7579  bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
7580  checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
7581  TSK_CompleteObject, TAH_IgnoreTrivialABI,
7582  /*Diagnose*/true);
7583 }
7584 
7585 /// Determine whether a defaulted or deleted special member function is trivial,
7586 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
7587 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
7589  TrivialABIHandling TAH, bool Diagnose) {
7590  assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
7591 
7592  CXXRecordDecl *RD = MD->getParent();
7593 
7594  bool ConstArg = false;
7595 
7596  // C++11 [class.copy]p12, p25: [DR1593]
7597  // A [special member] is trivial if [...] its parameter-type-list is
7598  // equivalent to the parameter-type-list of an implicit declaration [...]
7599  switch (CSM) {
7600  case CXXDefaultConstructor:
7601  case CXXDestructor:
7602  // Trivial default constructors and destructors cannot have parameters.
7603  break;
7604 
7605  case CXXCopyConstructor:
7606  case CXXCopyAssignment: {
7607  // Trivial copy operations always have const, non-volatile parameter types.
7608  ConstArg = true;
7609  const ParmVarDecl *Param0 = MD->getParamDecl(0);
7610  const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
7611  if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
7612  if (Diagnose)
7613  Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7614  << Param0->getSourceRange() << Param0->getType()
7615  << Context.getLValueReferenceType(
7616  Context.getRecordType(RD).withConst());
7617  return false;
7618  }
7619  break;
7620  }
7621 
7622  case CXXMoveConstructor:
7623  case CXXMoveAssignment: {
7624  // Trivial move operations always have non-cv-qualified parameters.
7625  const ParmVarDecl *Param0 = MD->getParamDecl(0);
7626  const RValueReferenceType *RT =
7627  Param0->getType()->getAs<RValueReferenceType>();
7628  if (!RT || RT->getPointeeType().getCVRQualifiers()) {
7629  if (Diagnose)
7630  Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7631  << Param0->getSourceRange() << Param0->getType()
7632  << Context.getRValueReferenceType(Context.getRecordType(RD));
7633  return false;
7634  }
7635  break;
7636  }
7637 
7638  case CXXInvalid:
7639  llvm_unreachable("not a special member");
7640  }
7641 
7642  if (MD->getMinRequiredArguments() < MD->getNumParams()) {
7643  if (Diagnose)
7644  Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
7645  diag::note_nontrivial_default_arg)
7647  return false;
7648  }
7649  if (MD->isVariadic()) {
7650  if (Diagnose)
7651  Diag(MD->getLocation(), diag::note_nontrivial_variadic);
7652  return false;
7653  }
7654 
7655  // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7656  // A copy/move [constructor or assignment operator] is trivial if
7657  // -- the [member] selected to copy/move each direct base class subobject
7658  // is trivial
7659  //
7660  // C++11 [class.copy]p12, C++11 [class.copy]p25:
7661  // A [default constructor or destructor] is trivial if
7662  // -- all the direct base classes have trivial [default constructors or
7663  // destructors]
7664  for (const auto &BI : RD->bases())
7665  if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
7666  ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
7667  return false;
7668 
7669  // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7670  // A copy/move [constructor or assignment operator] for a class X is
7671  // trivial if
7672  // -- for each non-static data member of X that is of class type (or array
7673  // thereof), the constructor selected to copy/move that member is
7674  // trivial
7675  //
7676  // C++11 [class.copy]p12, C++11 [class.copy]p25:
7677  // A [default constructor or destructor] is trivial if
7678  // -- for all of the non-static data members of its class that are of class
7679  // type (or array thereof), each such class has a trivial [default
7680  // constructor or destructor]
7681  if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
7682  return false;
7683 
7684  // C++11 [class.dtor]p5:
7685  // A destructor is trivial if [...]
7686  // -- the destructor is not virtual
7687  if (CSM == CXXDestructor && MD->isVirtual()) {
7688  if (Diagnose)
7689  Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
7690  return false;
7691  }
7692 
7693  // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
7694  // A [special member] for class X is trivial if [...]
7695  // -- class X has no virtual functions and no virtual base classes
7696  if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
7697  if (!Diagnose)
7698  return false;
7699 
7700  if (RD->getNumVBases()) {
7701  // Check for virtual bases. We already know that the corresponding
7702  // member in all bases is trivial, so vbases must all be direct.
7703  CXXBaseSpecifier &BS = *RD->vbases_begin();
7704  assert(BS.isVirtual());
7705  Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
7706  return false;
7707  }
7708 
7709  // Must have a virtual method.
7710  for (const auto *MI : RD->methods()) {
7711  if (MI->isVirtual()) {
7712  SourceLocation MLoc = MI->getBeginLoc();
7713  Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
7714  return false;
7715  }
7716  }
7717 
7718  llvm_unreachable("dynamic class with no vbases and no virtual functions");
7719  }
7720 
7721  // Looks like it's trivial!
7722  return true;
7723 }
7724 
7725 namespace {
7726 struct FindHiddenVirtualMethod {
7727  Sema *S;
7728  CXXMethodDecl *Method;
7729  llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
7730  SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7731 
7732 private:
7733  /// Check whether any most overridden method from MD in Methods
7734  static bool CheckMostOverridenMethods(
7735  const CXXMethodDecl *MD,
7736  const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
7737  if (MD->size_overridden_methods() == 0)
7738  return Methods.count(MD->getCanonicalDecl());
7739  for (const CXXMethodDecl *O : MD->overridden_methods())
7740  if (CheckMostOverridenMethods(O, Methods))
7741  return true;
7742  return false;
7743  }
7744 
7745 public:
7746  /// Member lookup function that determines whether a given C++
7747  /// method overloads virtual methods in a base class without overriding any,
7748  /// to be used with CXXRecordDecl::lookupInBases().
7749  bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7750  RecordDecl *BaseRecord =
7751  Specifier->getType()->getAs<RecordType>()->getDecl();
7752 
7753  DeclarationName Name = Method->getDeclName();
7754  assert(Name.getNameKind() == DeclarationName::Identifier);
7755 
7756  bool foundSameNameMethod = false;
7757  SmallVector<CXXMethodDecl *, 8> overloadedMethods;
7758  for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7759  Path.Decls = Path.Decls.slice(1)) {
7760  NamedDecl *D = Path.Decls.front();
7761  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7762  MD = MD->getCanonicalDecl();
7763  foundSameNameMethod = true;
7764  // Interested only in hidden virtual methods.
7765  if (!MD->isVirtual())
7766  continue;
7767  // If the method we are checking overrides a method from its base
7768  // don't warn about the other overloaded methods. Clang deviates from
7769  // GCC by only diagnosing overloads of inherited virtual functions that
7770  // do not override any other virtual functions in the base. GCC's
7771  // -Woverloaded-virtual diagnoses any derived function hiding a virtual
7772  // function from a base class. These cases may be better served by a
7773  // warning (not specific to virtual functions) on call sites when the
7774  // call would select a different function from the base class, were it
7775  // visible.
7776  // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
7777  if (!S->IsOverload(Method, MD, false))
7778  return true;
7779  // Collect the overload only if its hidden.
7780  if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
7781  overloadedMethods.push_back(MD);
7782  }
7783  }
7784 
7785  if (foundSameNameMethod)
7786  OverloadedMethods.append(overloadedMethods.begin(),
7787  overloadedMethods.end());
7788  return foundSameNameMethod;
7789  }
7790 };
7791 } // end anonymous namespace
7792 
7793 /// Add the most overriden methods from MD to Methods
7795  llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
7796  if (MD->size_overridden_methods() == 0)
7797  Methods.insert(MD->getCanonicalDecl());
7798  else
7799  for (const CXXMethodDecl *O : MD->overridden_methods())
7800  AddMostOverridenMethods(O, Methods);
7801 }
7802 
7803 /// Check if a method overloads virtual methods in a base class without
7804 /// overriding any.
7806  SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7807  if (!MD->getDeclName().isIdentifier())
7808  return;
7809 
7810  CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
7811  /*bool RecordPaths=*/false,
7812  /*bool DetectVirtual=*/false);
7813  FindHiddenVirtualMethod FHVM;
7814  FHVM.Method = MD;
7815  FHVM.S = this;
7816 
7817  // Keep the base methods that were overridden or introduced in the subclass
7818  // by 'using' in a set. A base method not in this set is hidden.
7819  CXXRecordDecl *DC = MD->getParent();
7821  for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
7822  NamedDecl *ND = *I;
7823  if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
7824  ND = shad->getTargetDecl();
7825  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7826  AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
7827  }
7828 
7829  if (DC->lookupInBases(FHVM, Paths))
7830  OverloadedMethods = FHVM.OverloadedMethods;
7831 }
7832 
7834  SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7835  for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
7836  CXXMethodDecl *overloadedMD = OverloadedMethods[i];
7837  PartialDiagnostic PD = PDiag(
7838  diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
7839  HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
7840  Diag(overloadedMD->getLocation(), PD);
7841  }
7842 }
7843 
7844 /// Diagnose methods which overload virtual methods in a base class
7845 /// without overriding any.
7847  if (MD->isInvalidDecl())
7848  return;
7849 
7850  if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
7851  return;
7852 
7853  SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7854  FindHiddenVirtualMethods(MD, OverloadedMethods);
7855  if (!OverloadedMethods.empty()) {
7856  Diag(MD->getLocation(), diag::warn_overloaded_virtual)
7857  << MD << (OverloadedMethods.size() > 1);
7858 
7859  NoteHiddenVirtualMethods(MD, OverloadedMethods);
7860  }
7861 }
7862 
7864  auto PrintDiagAndRemoveAttr = [&]() {
7865  // No diagnostics if this is a template instantiation.
7867  Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
7868  diag::ext_cannot_use_trivial_abi) << &RD;
7869  RD.dropAttr<TrivialABIAttr>();
7870  };
7871 
7872  // Ill-formed if the struct has virtual functions.
7873  if (RD.isPolymorphic()) {
7874  PrintDiagAndRemoveAttr();
7875  return;
7876  }
7877 
7878  for (const auto &B : RD.bases()) {
7879  // Ill-formed if the base class is non-trivial for the purpose of calls or a
7880  // virtual base.
7881  if ((!B.getType()->isDependentType() &&
7882  !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) ||
7883  B.isVirtual()) {
7884  PrintDiagAndRemoveAttr();
7885  return;
7886  }
7887  }
7888 
7889  for (const auto *FD : RD.fields()) {
7890  // Ill-formed if the field is an ObjectiveC pointer or of a type that is
7891  // non-trivial for the purpose of calls.
7892  QualType FT = FD->getType();
7893  if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
7894  PrintDiagAndRemoveAttr();
7895  return;
7896  }
7897 
7898  if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
7899  if (!RT->isDependentType() &&
7900  !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
7901  PrintDiagAndRemoveAttr();
7902  return;
7903  }
7904  }
7905 }
7906 
7908  Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
7909  SourceLocation RBrac, const ParsedAttributesView &AttrList) {
7910  if (!TagDecl)
7911  return;
7912 
7913  AdjustDeclIfTemplate(TagDecl);
7914 
7915  for (const ParsedAttr &AL : AttrList) {
7916  if (AL.getKind() != ParsedAttr::AT_Visibility)
7917  continue;
7918  AL.setInvalid();
7919  Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored)
7920  << AL.getName();
7921  }
7922 
7923  ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
7924  // strict aliasing violation!
7925  reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
7926  FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
7927 
7928  CheckCompletedCXXClass(cast<CXXRecordDecl>(TagDecl));
7929 }
7930 
7931 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
7932 /// special functions, such as the default constructor, copy
7933 /// constructor, or destructor, to the given C++ class (C++
7934 /// [special]p1). This routine can only be executed just before the
7935 /// definition of the class is complete.
7937  if (ClassDecl->needsImplicitDefaultConstructor()) {
7939 
7940  if (ClassDecl->hasInheritedConstructor())
7941  DeclareImplicitDefaultConstructor(ClassDecl);
7942  }
7943 
7944  if (ClassDecl->needsImplicitCopyConstructor()) {
7946 
7947  // If the properties or semantics of the copy constructor couldn't be
7948  // determined while the class was being declared, force a declaration
7949  // of it now.
7950  if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
7951  ClassDecl->hasInheritedConstructor())
7952  DeclareImplicitCopyConstructor(ClassDecl);
7953  // For the MS ABI we need to know whether the copy ctor is deleted. A
7954  // prerequisite for deleting the implicit copy ctor is that the class has a
7955  // move ctor or move assignment that is either user-declared or whose
7956  // semantics are inherited from a subobject. FIXME: We should provide a more
7957  // direct way for CodeGen to ask whether the constructor was deleted.
7958  else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
7959  (ClassDecl->hasUserDeclaredMoveConstructor() ||
7961  ClassDecl->hasUserDeclaredMoveAssignment() ||
7963  DeclareImplicitCopyConstructor(ClassDecl);
7964  }
7965 
7966  if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
7968 
7969  if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7970  ClassDecl->hasInheritedConstructor())
7971  DeclareImplicitMoveConstructor(ClassDecl);
7972  }
7973 
7974  if (ClassDecl->needsImplicitCopyAssignment()) {
7976 
7977  // If we have a dynamic class, then the copy assignment operator may be
7978  // virtual, so we have to declare it immediately. This ensures that, e.g.,
7979  // it shows up in the right place in the vtable and that we diagnose
7980  // problems with the implicit exception specification.
7981  if (ClassDecl->isDynamicClass() ||
7983  ClassDecl->hasInheritedAssignment())
7984  DeclareImplicitCopyAssignment(ClassDecl);
7985  }
7986 
7987  if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
7989 
7990  // Likewise for the move assignment operator.
7991  if (ClassDecl->isDynamicClass() ||
7993  ClassDecl->hasInheritedAssignment())
7994  DeclareImplicitMoveAssignment(ClassDecl);
7995  }
7996 
7997  if (ClassDecl->needsImplicitDestructor()) {
7999 
8000  // If we have a dynamic class, then the destructor may be virtual, so we
8001  // have to declare the destructor immediately. This ensures that, e.g., it
8002  // shows up in the right place in the vtable and that we diagnose problems
8003  // with the implicit exception specification.
8004  if (ClassDecl->isDynamicClass() ||
8006  DeclareImplicitDestructor(ClassDecl);
8007  }
8008 }
8009 
8011  if (!D)
8012  return 0;
8013 
8014  // The order of template parameters is not important here. All names
8015  // get added to the same scope.
8017 
8018  if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
8019  D = TD->getTemplatedDecl();
8020 
8021  if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
8022  ParameterLists.push_back(PSD->getTemplateParameters());
8023 
8024  if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
8025  for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
8026  ParameterLists.push_back(DD->getTemplateParameterList(i));
8027 
8028  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8029  if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
8030  ParameterLists.push_back(FTD->getTemplateParameters());
8031  }
8032  }
8033 
8034  if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
8035  for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
8036  ParameterLists.push_back(TD->getTemplateParameterList(i));
8037 
8038  if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
8040  ParameterLists.push_back(CTD->getTemplateParameters());
8041  }
8042  }
8043 
8044  unsigned Count = 0;
8045  for (TemplateParameterList *Params : ParameterLists) {
8046  if (Params->size() > 0)
8047  // Ignore explicit specializations; they don't contribute to the template
8048  // depth.
8049  ++Count;
8050  for (NamedDecl *Param : *Params) {
8051  if (Param->getDeclName()) {
8052  S->AddDecl(Param);
8053  IdResolver.AddDecl(Param);
8054  }
8055  }
8056  }
8057 
8058  return Count;
8059 }
8060 
8062  if (!RecordD) return;
8063  AdjustDeclIfTemplate(RecordD);
8064  CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
8065  PushDeclContext(S, Record);
8066 }
8067 
8069  if (!RecordD) return;
8070  PopDeclContext();
8071 }
8072 
8073 /// This is used to implement the constant expression evaluation part of the
8074 /// attribute enable_if extension. There is nothing in standard C++ which would
8075 /// require reentering parameters.
8077  if (!Param)
8078  return;
8079 
8080  S->AddDecl(Param);
8081  if (Param->getDeclName())
8082  IdResolver.AddDecl(Param);
8083 }
8084 
8085 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
8086 /// parsing a top-level (non-nested) C++ class, and we are now
8087 /// parsing those parts of the given Method declaration that could
8088 /// not be parsed earlier (C++ [class.mem]p2), such as default
8089 /// arguments. This action should enter the scope of the given
8090 /// Method declaration as if we had just parsed the qualified method
8091 /// name. However, it should not bring the parameters into scope;
8092 /// that will be performed by ActOnDelayedCXXMethodParameter.
8094 }
8095 
8096 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
8097 /// C++ method declaration. We're (re-)introducing the given
8098 /// function parameter into scope for use in parsing later parts of
8099 /// the method declaration. For example, we could see an
8100 /// ActOnParamDefaultArgument event for this parameter.
8102  if (!ParamD)
8103  return;
8104 
8105  ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
8106 
8107  // If this parameter has an unparsed default argument, clear it out
8108  // to make way for the parsed default argument.
8109  if (Param->hasUnparsedDefaultArg())
8110  Param->setDefaultArg(nullptr);
8111 
8112  S->AddDecl(Param);
8113  if (Param->getDeclName())
8114  IdResolver.AddDecl(Param);
8115 }
8116 
8117 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
8118 /// processing the delayed method declaration for Method. The method
8119 /// declaration is now considered finished. There may be a separate
8120 /// ActOnStartOfFunctionDef action later (not necessarily
8121 /// immediately!) for this method, if it was also defined inside the
8122 /// class body.
8124  if (!MethodD)
8125  return;
8126 
8127  AdjustDeclIfTemplate(MethodD);
8128 
8129  FunctionDecl *Method = cast<FunctionDecl>(MethodD);
8130 
8131  // Now that we have our default arguments, check the constructor
8132  // again. It could produce additional diagnostics or affect whether
8133  // the class has implicitly-declared destructors, among other
8134  // things.
8135  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
8136  CheckConstructor(Constructor);
8137 
8138  // Check the default arguments, which we may have added.
8139  if (!Method->isInvalidDecl())
8140  CheckCXXDefaultArguments(Method);
8141 }
8142 
8143 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
8144 /// the well-formedness of the constructor declarator @p D with type @p
8145 /// R. If there are any errors in the declarator, this routine will
8146 /// emit diagnostics and set the invalid bit to true. In any case, the type
8147 /// will be updated to reflect a well-formed type for the constructor and
8148 /// returned.
8150  StorageClass &SC) {
8151  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8152 
8153  // C++ [class.ctor]p3:
8154  // A constructor shall not be virtual (10.3) or static (9.4). A
8155  // constructor can be invoked for a const, volatile or const
8156  // volatile object. A constructor shall not be declared const,
8157  // volatile, or const volatile (9.3.2).
8158  if (isVirtual) {
8159  if (!D.isInvalidType())
8160  Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8161  << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
8162  << SourceRange(D.getIdentifierLoc());
8163  D.setInvalidType();
8164  }
8165  if (SC == SC_Static) {
8166  if (!D.isInvalidType())
8167  Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8168  << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8169  << SourceRange(D.getIdentifierLoc());
8170  D.setInvalidType();
8171  SC = SC_None;
8172  }
8173 
8174  if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8175  diagnoseIgnoredQualifiers(
8176  diag::err_constructor_return_type, TypeQuals, SourceLocation(),
8180  D.setInvalidType();
8181  }
8182 
8184  if (FTI.hasMethodTypeQualifiers()) {
8186  [&](DeclSpec::TQ TypeQual, StringRef QualName, SourceLocation SL) {
8187  Diag(SL, diag::err_invalid_qualified_constructor)
8188  << QualName << SourceRange(SL);
8189  });
8190  D.setInvalidType();
8191  }
8192 
8193  // C++0x [class.ctor]p4:
8194  // A constructor shall not be declared with a ref-qualifier.
8195  if (FTI.hasRefQualifier()) {
8196  Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
8199  D.setInvalidType();
8200  }
8201 
8202  // Rebuild the function type "R" without any type qualifiers (in
8203  // case any of the errors above fired) and with "void" as the
8204  // return type, since constructors don't have return types.
8205  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8206  if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
8207  return R;
8208 
8210  EPI.TypeQuals = Qualifiers();
8211  EPI.RefQualifier = RQ_None;
8212 
8213  return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
8214 }
8215 
8216 /// CheckConstructor - Checks a fully-formed constructor for
8217 /// well-formedness, issuing any diagnostics required. Returns true if
8218 /// the constructor declarator is invalid.
8220  CXXRecordDecl *ClassDecl
8221  = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
8222  if (!ClassDecl)
8223  return Constructor->setInvalidDecl();
8224 
8225  // C++ [class.copy]p3:
8226  // A declaration of a constructor for a class X is ill-formed if
8227  // its first parameter is of type (optionally cv-qualified) X and
8228  // either there are no other parameters or else all other
8229  // parameters have default arguments.
8230  if (!Constructor->isInvalidDecl() &&
8231  ((Constructor->getNumParams() == 1) ||
8232  (Constructor->getNumParams() > 1 &&
8233  Constructor->getParamDecl(1)->hasDefaultArg())) &&
8234  Constructor->getTemplateSpecializationKind()
8236  QualType ParamType = Constructor->getParamDecl(0)->getType();
8237  QualType ClassTy = Context.getTagDeclType(ClassDecl);
8238  if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
8239  SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
8240  const char *ConstRef
8241  = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
8242  : " const &";
8243  Diag(ParamLoc, diag::err_constructor_byvalue_arg)
8244  << FixItHint::CreateInsertion(ParamLoc, ConstRef);
8245 
8246  // FIXME: Rather that making the constructor invalid, we should endeavor
8247  // to fix the type.
8248  Constructor->setInvalidDecl();
8249  }
8250  }
8251 }
8252 
8253 /// CheckDestructor - Checks a fully-formed destructor definition for
8254 /// well-formedness, issuing any diagnostics required. Returns true
8255 /// on error.
8257  CXXRecordDecl *RD = Destructor->getParent();
8258 
8259  if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
8260  SourceLocation Loc;
8261 
8262  if (!Destructor->isImplicit())
8263  Loc = Destructor->getLocation();
8264  else
8265  Loc = RD->getLocation();
8266 
8267  // If we have a virtual destructor, look up the deallocation function
8268  if (FunctionDecl *OperatorDelete =
8269  FindDeallocationFunctionForDestructor(Loc, RD)) {
8270  Expr *ThisArg = nullptr;
8271 
8272  // If the notional 'delete this' expression requires a non-trivial
8273  // conversion from 'this' to the type of a destroying operator delete's
8274  // first parameter, perform that conversion now.
8275  if (OperatorDelete->isDestroyingOperatorDelete()) {
8276  QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
8277  if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
8278  // C++ [class.dtor]p13:
8279  // ... as if for the expression 'delete this' appearing in a
8280  // non-virtual destructor of the destructor's class.
8281  ContextRAII SwitchContext(*this, Destructor);
8282  ExprResult This =
8283  ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
8284  assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
8285  This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
8286  if (This.isInvalid()) {
8287  // FIXME: Register this as a context note so that it comes out
8288  // in the right order.
8289  Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
8290  return true;
8291  }
8292  ThisArg = This.get();
8293  }
8294  }
8295 
8296  DiagnoseUseOfDecl(OperatorDelete, Loc);
8297  MarkFunctionReferenced(Loc, OperatorDelete);
8298  Destructor->setOperatorDelete(OperatorDelete, ThisArg);
8299  }
8300  }
8301 
8302  return false;
8303 }
8304 
8305 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
8306 /// the well-formednes of the destructor declarator @p D with type @p
8307 /// R. If there are any errors in the declarator, this routine will
8308 /// emit diagnostics and set the declarator to invalid. Even if this happens,
8309 /// will be updated to reflect a well-formed type for the destructor and
8310 /// returned.
8312  StorageClass& SC) {
8313  // C++ [class.dtor]p1:
8314  // [...] A typedef-name that names a class is a class-name
8315  // (7.1.3); however, a typedef-name that names a class shall not
8316  // be used as the identifier in the declarator for a destructor
8317  // declaration.
8318  QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
8319  if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
8320  Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8321  << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
8322  else if (const TemplateSpecializationType *TST =
8323  DeclaratorType->getAs<TemplateSpecializationType>())
8324  if (TST->isTypeAlias())
8325  Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8326  << DeclaratorType << 1;
8327 
8328  // C++ [class.dtor]p2:
8329  // A destructor is used to destroy objects of its class type. A
8330  // destructor takes no parameters, and no return type can be
8331  // specified for it (not even void). The address of a destructor
8332  // shall not be taken. A destructor shall not be static. A
8333  // destructor can be invoked for a const, volatile or const
8334  // volatile object. A destructor shall not be declared const,
8335  // volatile or const volatile (9.3.2).
8336  if (SC == SC_Static) {
8337  if (!D.isInvalidType())
8338  Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
8339  << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8342 
8343  SC = SC_None;
8344  }
8345  if (!D.isInvalidType()) {
8346  // Destructors don't have return types, but the parser will
8347  // happily parse something like:
8348  //
8349  // class X {
8350  // float ~X();
8351  // };
8352  //
8353  // The return type will be eliminated later.
8354  if (D.getDeclSpec().hasTypeSpecifier())
8355  Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
8357  << SourceRange(D.getIdentifierLoc());
8358  else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8359  diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
8360  SourceLocation(),
8365  D.setInvalidType();
8366  }
8367  }
8368 
8370  if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
8372  [&](DeclSpec::TQ TypeQual, StringRef QualName, SourceLocation SL) {
8373  Diag(SL, diag::err_invalid_qualified_destructor)
8374  << QualName << SourceRange(SL);
8375  });
8376  D.setInvalidType();
8377  }
8378 
8379  // C++0x [class.dtor]p2:
8380  // A destructor shall not be declared with a ref-qualifier.
8381  if (FTI.hasRefQualifier()) {
8382  Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
8385  D.setInvalidType();
8386  }
8387 
8388  // Make sure we don't have any parameters.
8389  if (FTIHasNonVoidParameters(FTI)) {
8390  Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
8391 
8392  // Delete the parameters.
8393  FTI.freeParams();
8394  D.setInvalidType();
8395  }
8396 
8397  // Make sure the destructor isn't variadic.
8398  if (FTI.isVariadic) {
8399  Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
8400  D.setInvalidType();
8401  }
8402 
8403  // Rebuild the function type "R" without any type qualifiers or
8404  // parameters (in case any of the errors above fired) and with
8405  // "void" as the return type, since destructors don't have return
8406  // types.
8407  if (!D.isInvalidType())
8408  return R;
8409 
8410  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8412  EPI.Variadic = false;
8413  EPI.TypeQuals = Qualifiers();
8414  EPI.RefQualifier = RQ_None;
8415  return Context.getFunctionType(Context.VoidTy, None, EPI);
8416 }
8417 
8418 static void extendLeft(SourceRange &R, SourceRange Before) {
8419  if (Before.isInvalid())
8420  return;
8421  R.setBegin(Before.getBegin());
8422  if (R.getEnd().isInvalid())
8423  R.setEnd(Before.getEnd());
8424 }
8425 
8427  if (After.isInvalid())
8428  return;
8429  if (R.getBegin().isInvalid())
8430  R.setBegin(After.getBegin());
8431  R.setEnd(After.getEnd());
8432 }
8433 
8434 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
8435 /// well-formednes of the conversion function declarator @p D with
8436 /// type @p R. If there are any errors in the declarator, this routine
8437 /// will emit diagnostics and return true. Otherwise, it will return
8438 /// false. Either way, the type @p R will be updated to reflect a
8439 /// well-formed type for the conversion operator.
8441  StorageClass& SC) {
8442  // C++ [class.conv.fct]p1:
8443  // Neither parameter types nor return type can be specified. The
8444  // type of a conversion function (8.3.5) is "function taking no
8445  // parameter returning conversion-type-id."
8446  if (SC == SC_Static) {
8447  if (!D.isInvalidType())
8448  Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
8450  << D.getName().getSourceRange();
8451  D.setInvalidType();
8452  SC = SC_None;
8453  }
8454 
8455  TypeSourceInfo *ConvTSI = nullptr;
8456  QualType ConvType =
8457  GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
8458 
8459  const DeclSpec &DS = D.getDeclSpec();
8460  if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
8461  // Conversion functions don't have return types, but the parser will
8462  // happily parse something like:
8463  //
8464  // class X {
8465  // float operator bool();
8466  // };
8467  //
8468  // The return type will be changed later anyway.
8469  Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
8470  << SourceRange(DS.getTypeSpecTypeLoc())
8471  << SourceRange(D.getIdentifierLoc());
8472  D.setInvalidType();
8473  } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
8474  // It's also plausible that the user writes type qualifiers in the wrong
8475  // place, such as:
8476  // struct S { const operator int(); };
8477  // FIXME: we could provide a fixit to move the qualifiers onto the
8478  // conversion type.
8479  Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
8480  << SourceRange(D.getIdentifierLoc()) << 0;
8481  D.setInvalidType();
8482  }
8483 
8484  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8485 
8486  // Make sure we don't have any parameters.
8487  if (Proto->getNumParams() > 0) {
8488  Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
8489 
8490  // Delete the parameters.
8492  D.setInvalidType();
8493  } else if (Proto->isVariadic()) {
8494  Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
8495  D.setInvalidType();
8496  }
8497 
8498  // Diagnose "&operator bool()" and other such nonsense. This
8499  // is actually a gcc extension which we don't support.
8500  if (Proto->getReturnType() != ConvType) {
8501  bool NeedsTypedef = false;
8502  SourceRange Before, After;
8503 
8504  // Walk the chunks and extract information on them for our diagnostic.
8505  bool PastFunctionChunk = false;
8506  for (auto &Chunk : D.type_objects()) {
8507  switch (Chunk.Kind) {
8509  if (!PastFunctionChunk) {
8510  if (Chunk.Fun.HasTrailingReturnType) {
8511  TypeSourceInfo *TRT = nullptr;
8512  GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
8513  if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
8514  }
8515  PastFunctionChunk = true;
8516  break;
8517  }
8518  LLVM_FALLTHROUGH;
8520  NeedsTypedef = true;
8521  extendRight(After, Chunk.getSourceRange());
8522  break;
8523 
8528  case DeclaratorChunk::Pipe:
8529  extendLeft(Before, Chunk.getSourceRange());
8530  break;
8531 
8533  extendLeft(Before, Chunk.Loc);
8534  extendRight(After, Chunk.EndLoc);
8535  break;
8536  }
8537  }
8538 
8539  SourceLocation Loc = Before.isValid() ? Before.getBegin() :
8540  After.isValid() ? After.getBegin() :
8541  D.getIdentifierLoc();
8542  auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
8543  DB << Before << After;
8544 
8545  if (!NeedsTypedef) {
8546  DB << /*don't need a typedef*/0;
8547 
8548  // If we can provide a correct fix-it hint, do so.
8549  if (After.isInvalid() && ConvTSI) {
8550  SourceLocation InsertLoc =
8551  getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
8552  DB << FixItHint::CreateInsertion(InsertLoc, " ")
8554  InsertLoc, CharSourceRange::getTokenRange(Before))
8555  << FixItHint::CreateRemoval(Before);
8556  }
8557  } else if (!Proto->getReturnType()->isDependentType()) {
8558  DB << /*typedef*/1 << Proto->getReturnType();
8559  } else if (getLangOpts().CPlusPlus11) {
8560  DB << /*alias template*/2 << Proto->getReturnType();
8561  } else {
8562  DB << /*might not be fixable*/3;
8563  }
8564 
8565  // Recover by incorporating the other type chunks into the result type.
8566  // Note, this does *not* change the name of the function. This is compatible
8567  // with the GCC extension:
8568  // struct S { &operator int(); } s;
8569  // int &r = s.operator int(); // ok in GCC
8570  // S::operator int&() {} // error in GCC, function name is 'operator int'.
8571  ConvType = Proto->getReturnType();
8572  }
8573 
8574  // C++ [class.conv.fct]p4:
8575  // The conversion-type-id shall not represent a function type nor
8576  // an array type.
8577  if (ConvType->isArrayType()) {
8578  Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
8579  ConvType = Context.getPointerType(ConvType);
8580  D.setInvalidType();
8581  } else if (ConvType->isFunctionType()) {
8582  Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
8583  ConvType = Context.getPointerType(ConvType);
8584  D.setInvalidType();
8585  }
8586 
8587  // Rebuild the function type "R" without any parameters (in case any
8588  // of the errors above fired) and with the conversion type as the
8589  // return type.
8590  if (D.isInvalidType())
8591  R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
8592 
8593  // C++0x explicit conversion operators.
8594  if (DS.isExplicitSpecified())
8595  Diag(DS.getExplicitSpecLoc(),
8596  getLangOpts().CPlusPlus11
8597  ? diag::warn_cxx98_compat_explicit_conversion_functions
8598  : diag::ext_explicit_conversion_functions)
8599  << SourceRange(DS.getExplicitSpecLoc());
8600 }
8601 
8602 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
8603 /// the declaration of the given C++ conversion function. This routine
8604 /// is responsible for recording the conversion function in the C++
8605 /// class, if possible.
8607  assert(Conversion && "Expected to receive a conversion function declaration");
8608 
8609  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
8610 
8611  // Make sure we aren't redeclaring the conversion function.
8612  QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
8613 
8614  // C++ [class.conv.fct]p1:
8615  // [...] A conversion function is never used to convert a
8616  // (possibly cv-qualified) object to the (possibly cv-qualified)
8617  // same object type (or a reference to it), to a (possibly
8618  // cv-qualified) base class of that type (or a reference to it),
8619  // or to (possibly cv-qualified) void.
8620  // FIXME: Suppress this warning if the conversion function ends up being a
8621  // virtual function that overrides a virtual function in a base class.
8622  QualType ClassType
8623  = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8624  if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
8625  ConvType = ConvTypeRef->getPointeeType();
8626  if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
8628  /* Suppress diagnostics for instantiations. */;
8629  else if (ConvType->isRecordType()) {
8630  ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
8631  if (ConvType == ClassType)
8632  Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
8633  << ClassType;
8634  else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
8635  Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
8636  << ClassType << ConvType;
8637  } else if (ConvType->isVoidType()) {
8638  Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
8639  << ClassType << ConvType;
8640  }
8641 
8642  if (FunctionTemplateDecl *ConversionTemplate
8643  = Conversion->getDescribedFunctionTemplate())
8644  return ConversionTemplate;
8645 
8646  return Conversion;
8647 }
8648 
8649 namespace {
8650 /// Utility class to accumulate and print a diagnostic listing the invalid
8651 /// specifier(s) on a declaration.
8652 struct BadSpecifierDiagnoser {
8653  BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
8654  : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
8655  ~BadSpecifierDiagnoser() {
8656  Diagnostic << Specifiers;
8657  }
8658 
8659  template<typename T> void check(SourceLocation SpecLoc, T Spec) {
8660  return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
8661  }
8662  void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
8663  return check(SpecLoc,
8665  }
8666  void check(SourceLocation SpecLoc, const char *Spec) {
8667  if (SpecLoc.isInvalid()) return;
8668  Diagnostic << SourceRange(SpecLoc, SpecLoc);
8669  if (!Specifiers.empty()) Specifiers += " ";
8670  Specifiers += Spec;
8671  }
8672 
8673  Sema &S;
8675  std::string Specifiers;
8676 };
8677 }
8678 
8679 /// Check the validity of a declarator that we parsed for a deduction-guide.
8680 /// These aren't actually declarators in the grammar, so we need to check that
8681 /// the user didn't specify any pieces that are not part of the deduction-guide
8682 /// grammar.
8684  StorageClass &SC) {
8685  TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
8686  TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
8687  assert(GuidedTemplateDecl && "missing template decl for deduction guide");
8688 
8689  // C++ [temp.deduct.guide]p3:
8690  // A deduction-gide shall be declared in the same scope as the
8691  // corresponding class template.
8692  if (!CurContext->getRedeclContext()->Equals(
8693  GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
8694  Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
8695  << GuidedTemplateDecl;
8696  Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
8697  }
8698 
8699  auto &DS = D.getMutableDeclSpec();
8700  // We leave 'friend' and 'virtual' to be rejected in the normal way.
8701  if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
8702  DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
8703  DS.isNoreturnSpecified() || DS.isConstexprSpecified()) {
8704  BadSpecifierDiagnoser Diagnoser(
8705  *this, D.getIdentifierLoc(),
8706  diag::err_deduction_guide_invalid_specifier);
8707 
8708  Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
8710  SC = SC_None;
8711 
8712  // 'explicit' is permitted.
8713  Diagnoser.check(DS.getInlineSpecLoc(), "inline");
8714  Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
8715  Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
8716  DS.ClearConstexprSpec();
8717 
8718  Diagnoser.check(DS.getConstSpecLoc(), "const");
8719  Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
8720  Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
8721  Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
8722  Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
8723  DS.ClearTypeQualifiers();
8724 
8725  Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
8726  Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
8727  Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
8728  Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
8729  DS.ClearTypeSpecType();
8730  }
8731 
8732  if (D.isInvalidType())
8733  return;
8734 
8735  // Check the declarator is simple enough.
8736  bool FoundFunction = false;
8737  for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
8738  if (Chunk.Kind == DeclaratorChunk::Paren)
8739  continue;
8740  if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
8742  diag::err_deduction_guide_with_complex_decl)
8743  << D.getSourceRange();
8744  break;
8745  }
8746  if (!Chunk.Fun.hasTrailingReturnType()) {
8747  Diag(D.getName().getBeginLoc(),
8748  diag::err_deduction_guide_no_trailing_return_type);
8749  break;
8750  }
8751 
8752  // Check that the return type is written as a specialization of
8753  // the template specified as the deduction-guide's name.
8754  ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
8755  TypeSourceInfo *TSI = nullptr;
8756  QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
8757  assert(TSI && "deduction guide has valid type but invalid return type?");
8758  bool AcceptableReturnType = false;
8759  bool MightInstantiateToSpecialization = false;
8760  if (auto RetTST =
8762  TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
8763  bool TemplateMatches =
8764  Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
8765  if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
8766  AcceptableReturnType = true;
8767  else {
8768  // This could still instantiate to the right type, unless we know it
8769  // names the wrong class template.
8770  auto *TD = SpecifiedName.getAsTemplateDecl();
8771  MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
8772  !TemplateMatches);
8773  }
8774  } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
8775  MightInstantiateToSpecialization = true;
8776  }
8777 
8778  if (!AcceptableReturnType) {
8779  Diag(TSI->getTypeLoc().getBeginLoc(),
8780  diag::err_deduction_guide_bad_trailing_return_type)
8781  << GuidedTemplate << TSI->getType()
8782  << MightInstantiateToSpecialization
8783  << TSI->getTypeLoc().getSourceRange();
8784  }
8785 
8786  // Keep going to check that we don't have any inner declarator pieces (we
8787  // could still have a function returning a pointer to a function).
8788  FoundFunction = true;
8789  }
8790 
8791  if (D.isFunctionDefinition())
8792  Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
8793 }
8794 
8795 //===----------------------------------------------------------------------===//
8796 // Namespace Handling
8797 //===----------------------------------------------------------------------===//
8798 
8799 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
8800 /// reopened.
8802  SourceLocation Loc,
8803  IdentifierInfo *II, bool *IsInline,
8804  NamespaceDecl *PrevNS) {
8805  assert(*IsInline != PrevNS->isInline());
8806 
8807  // HACK: Work around a bug in libstdc++4.6's <atomic>, where
8808  // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
8809  // inline namespaces, with the intention of bringing names into namespace std.
8810  //
8811  // We support this just well enough to get that case working; this is not
8812  // sufficient to support reopening namespaces as inline in general.
8813  if (*IsInline && II && II->getName().startswith("__atomic") &&
8815  // Mark all prior declarations of the namespace as inline.
8816  for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
8817  NS = NS->getPreviousDecl())
8818  NS->setInline(*IsInline);
8819  // Patch up the lookup table for the containing namespace. This isn't really
8820  // correct, but it's good enough for this particular case.
8821  for (auto *I : PrevNS->decls())
8822  if (auto *ND = dyn_cast<NamedDecl>(I))
8823  PrevNS->getParent()->makeDeclVisibleInContext(ND);
8824  return;
8825  }
8826 
8827  if (PrevNS->isInline())
8828  // The user probably just forgot the 'inline', so suggest that it
8829  // be added back.
8830  S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
8831  << FixItHint::CreateInsertion(KeywordLoc, "inline ");
8832  else
8833  S.Diag(Loc, diag::err_inline_namespace_mismatch);
8834 
8835  S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
8836  *IsInline = PrevNS->isInline();
8837 }
8838 
8839 /// ActOnStartNamespaceDef - This is called at the start of a namespace
8840 /// definition.
8842  Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
8843  SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
8844  const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
8845  SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
8846  // For anonymous namespace, take the location of the left brace.
8847  SourceLocation Loc = II ? IdentLoc : LBrace;
8848  bool IsInline = InlineLoc.isValid();
8849  bool IsInvalid = false;
8850  bool IsStd = false;
8851  bool AddToKnown = false;
8852  Scope *DeclRegionScope = NamespcScope->getParent();
8853 
8854  NamespaceDecl *PrevNS = nullptr;
8855  if (II) {
8856  // C++ [namespace.def]p2:
8857  // The identifier in an original-namespace-definition shall not
8858  // have been previously defined in the declarative region in
8859  // which the original-namespace-definition appears. The
8860  // identifier in an original-namespace-definition is the name of
8861  // the namespace. Subsequently in that declarative region, it is
8862  // treated as an original-namespace-name.
8863  //
8864  // Since namespace names are unique in their scope, and we don't
8865  // look through using directives, just look for any ordinary names
8866  // as if by qualified name lookup.
8867  LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
8868  ForExternalRedeclaration);
8869  LookupQualifiedName(R, CurContext->getRedeclContext());
8870  NamedDecl *PrevDecl =
8871  R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
8872  PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
8873 
8874  if (PrevNS) {
8875  // This is an extended namespace definition.
8876  if (IsInline != PrevNS->isInline())
8877  DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
8878  &IsInline, PrevNS);
8879  } else if (PrevDecl) {
8880  // This is an invalid name redefinition.
8881  Diag(Loc, diag::err_redefinition_different_kind)
8882  << II;
8883  Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8884  IsInvalid = true;
8885  // Continue on to push Namespc as current DeclContext and return it.
8886  } else if (II->isStr("std") &&
8887  CurContext->getRedeclContext()->isTranslationUnit()) {
8888  // This is the first "real" definition of the namespace "std", so update
8889  // our cache of the "std" namespace to point at this definition.
8890  PrevNS = getStdNamespace();
8891  IsStd = true;
8892  AddToKnown = !IsInline;
8893  } else {
8894  // We've seen this namespace for the first time.
8895  AddToKnown = !IsInline;
8896  }
8897  } else {
8898  // Anonymous namespaces.
8899 
8900  // Determine whether the parent already has an anonymous namespace.
8901  DeclContext *Parent = CurContext->getRedeclContext();
8902  if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8903  PrevNS = TU->getAnonymousNamespace();
8904  } else {
8905  NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
8906  PrevNS = ND->getAnonymousNamespace();
8907  }
8908 
8909  if (PrevNS && IsInline != PrevNS->isInline())
8910  DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
8911  &IsInline, PrevNS);
8912  }
8913 
8914  NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
8915  StartLoc, Loc, II, PrevNS);
8916  if (IsInvalid)
8917  Namespc->setInvalidDecl();
8918 
8919  ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
8920  AddPragmaAttributes(DeclRegionScope, Namespc);
8921 
8922  // FIXME: Should we be merging attributes?
8923  if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
8924  PushNamespaceVisibilityAttr(Attr, Loc);
8925 
8926  if (IsStd)
8927  StdNamespace = Namespc;
8928  if (AddToKnown)
8929  KnownNamespaces[Namespc] = false;
8930 
8931  if (II) {
8932  PushOnScopeChains(Namespc, DeclRegionScope);
8933  } else {
8934  // Link the anonymous namespace into its parent.
8935  DeclContext *Parent = CurContext->getRedeclContext();
8936  if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8937  TU->setAnonymousNamespace(Namespc);
8938  } else {
8939  cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
8940  }
8941 
8942  CurContext->addDecl(Namespc);
8943 
8944  // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
8945  // behaves as if it were replaced by
8946  // namespace unique { /* empty body */ }
8947  // using namespace unique;
8948  // namespace unique { namespace-body }
8949  // where all occurrences of 'unique' in a translation unit are
8950  // replaced by the same identifier and this identifier differs
8951  // from all other identifiers in the entire program.
8952 
8953  // We just create the namespace with an empty name and then add an
8954  // implicit using declaration, just like the standard suggests.
8955  //
8956  // CodeGen enforces the "universally unique" aspect by giving all
8957  // declarations semantically contained within an anonymous
8958  // namespace internal linkage.
8959 
8960  if (!PrevNS) {
8961  UD = UsingDirectiveDecl::Create(Context, Parent,
8962  /* 'using' */ LBrace,
8963  /* 'namespace' */ SourceLocation(),
8964  /* qualifier */ NestedNameSpecifierLoc(),
8965  /* identifier */ SourceLocation(),
8966  Namespc,
8967  /* Ancestor */ Parent);
8968  UD->setImplicit();
8969  Parent->addDecl(UD);
8970  }
8971  }
8972 
8973  ActOnDocumentableDecl(Namespc);
8974 
8975  // Although we could have an invalid decl (i.e. the namespace name is a
8976  // redefinition), push it as current DeclContext and try to continue parsing.
8977  // FIXME: We should be able to push Namespc here, so that the each DeclContext
8978  // for the namespace has the declarations that showed up in that particular
8979  // namespace definition.
8980  PushDeclContext(NamespcScope, Namespc);
8981  return Namespc;
8982 }
8983 
8984 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
8985 /// is a namespace alias, returns the namespace it points to.
8987  if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
8988  return AD->getNamespace();
8989  return dyn_cast_or_null<NamespaceDecl>(D);
8990 }
8991 
8992 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
8993 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
8995  NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
8996  assert(Namespc && "Invalid parameter, expected NamespaceDecl");
8997  Namespc->setRBraceLoc(RBrace);
8998  PopDeclContext();
8999  if (Namespc->hasAttr<VisibilityAttr>())
9000  PopPragmaVisibility(true, RBrace);
9001 }
9002 
9004  return cast_or_null<CXXRecordDecl>(
9005  StdBadAlloc.get(Context.getExternalSource()));
9006 }
9007 
9009  return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
9010 }
9011 
9013  return cast_or_null<NamespaceDecl>(
9014  StdNamespace.get(Context.getExternalSource()));
9015 }
9016 
9018  if (!StdExperimentalNamespaceCache) {
9019  if (auto Std = getStdNamespace()) {
9020  LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
9021  SourceLocation(), LookupNamespaceName);
9022  if (!LookupQualifiedName(Result, Std) ||
9023  !(StdExperimentalNamespaceCache =
9024  Result.getAsSingle<NamespaceDecl>()))
9025  Result.suppressDiagnostics();
9026  }
9027  }
9028  return StdExperimentalNamespaceCache;
9029 }
9030 
9031 namespace {
9032 
9034  USS_InvalidMember,
9035  USS_MissingMember,
9036  USS_NonTrivial,
9037  USS_Other
9038 };
9039 
9040 struct InvalidSTLDiagnoser {
9041  Sema &S;
9042  SourceLocation Loc;
9043  QualType TyForDiags;
9044 
9045  QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
9046  const VarDecl *VD = nullptr) {
9047  {
9048  auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
9049  << TyForDiags << ((int)Sel);
9050  if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
9051  assert(!Name.empty());
9052  D << Name;
9053  }
9054  }
9055  if (Sel == USS_InvalidMember) {
9056  S.Diag(VD->getLocation(), diag::note_var_declared_here)
9057  << VD << VD->getSourceRange();
9058  }
9059  return QualType();
9060  }
9061 };
9062 } // namespace
9063 
9065  SourceLocation Loc) {
9066  assert(getLangOpts().CPlusPlus &&
9067  "Looking for comparison category type outside of C++.");
9068 
9069  // Check if we've already successfully checked the comparison category type
9070  // before. If so, skip checking it again.
9071  ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
9072  if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)])
9073  return Info->getType();
9074 
9075  // If lookup failed
9076  if (!Info) {
9077  std::string NameForDiags = "std::";
9078  NameForDiags += ComparisonCategories::getCategoryString(Kind);
9079  Diag(Loc, diag::err_implied_comparison_category_type_not_found)
9080  << NameForDiags;
9081  return QualType();
9082  }
9083 
9084  assert(Info->Kind == Kind);
9085  assert(Info->Record);
9086 
9087  // Update the Record decl in case we encountered a forward declaration on our
9088  // first pass. FIXME: This is a bit of a hack.
9089  if (Info->Record->hasDefinition())
9090  Info->Record = Info->Record->getDefinition();
9091 
9092  // Use an elaborated type for diagnostics which has a name containing the
9093  // prepended 'std' namespace but not any inline namespace names.
9094  QualType TyForDiags = [&]() {
9095  auto *NNS =
9096  NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
9097  return Context.getElaboratedType(ETK_None, NNS, Info->getType());
9098  }();
9099 
9100  if (RequireCompleteType(Loc, TyForDiags, diag::err_incomplete_type))
9101  return QualType();
9102 
9103  InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags};
9104 
9105  if (!Info->Record->isTriviallyCopyable())
9106  return UnsupportedSTLError(USS_NonTrivial);
9107 
9108  for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
9109  CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
9110  // Tolerate empty base classes.
9111  if (Base->isEmpty())
9112  continue;
9113  // Reject STL implementations which have at least one non-empty base.
9114  return UnsupportedSTLError();
9115  }
9116 
9117  // Check that the STL has implemented the types using a single integer field.
9118  // This expectation allows better codegen for builtin operators. We require:
9119  // (1) The class has exactly one field.
9120  // (2) The field is an integral or enumeration type.
9121  auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
9122  if (std::distance(FIt, FEnd) != 1 ||
9123  !FIt->getType()->isIntegralOrEnumerationType()) {
9124  return UnsupportedSTLError();
9125  }
9126 
9127  // Build each of the require values and store them in Info.
9128  for (ComparisonCategoryResult CCR :
9130  StringRef MemName = ComparisonCategories::getResultString(CCR);
9131  ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
9132 
9133  if (!ValInfo)
9134  return UnsupportedSTLError(USS_MissingMember, MemName);
9135 
9136  VarDecl *VD = ValInfo->VD;
9137  assert(VD && "should not be null!");
9138 
9139  // Attempt to diagnose reasons why the STL definition of this type
9140  // might be foobar, including it failing to be a constant expression.
9141  // TODO Handle more ways the lookup or result can be invalid.
9142  if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() ||
9143  !VD->checkInitIsICE())
9144  return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
9145 
9146  // Attempt to evaluate the var decl as a constant expression and extract
9147  // the value of its first field as a ICE. If this fails, the STL
9148  // implementation is not supported.
9149  if (!ValInfo->hasValidIntValue())
9150  return UnsupportedSTLError();
9151 
9152  MarkVariableReferenced(Loc, VD);
9153  }
9154 
9155  // We've successfully built the required types and expressions. Update
9156  // the cache and return the newly cached value.
9157  FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
9158  return Info->getType();
9159 }
9160 
9161 /// Retrieve the special "std" namespace, which may require us to
9162 /// implicitly define the namespace.
9164  if (!StdNamespace) {
9165  // The "std" namespace has not yet been defined, so build one implicitly.
9166  StdNamespace = NamespaceDecl::Create(Context,
9167  Context.getTranslationUnitDecl(),
9168  /*Inline=*/false,
9170  &PP.getIdentifierTable().get("std"),
9171  /*PrevDecl=*/nullptr);
9172  getStdNamespace()->setImplicit(true);
9173  }
9174 
9175  return getStdNamespace();
9176 }
9177 
9179  assert(getLangOpts().CPlusPlus &&
9180  "Looking for std::initializer_list outside of C++.");
9181 
9182  // We're looking for implicit instantiations of
9183  // template <typename E> class std::initializer_list.
9184 
9185  if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
9186  return false;
9187 
9188  ClassTemplateDecl *Template = nullptr;
9189  const TemplateArgument *Arguments = nullptr;
9190 
9191  if (const RecordType *RT = Ty->getAs<RecordType>()) {
9192 
9193  ClassTemplateSpecializationDecl *Specialization =
9194  dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
9195  if (!Specialization)
9196  return false;
9197 
9198  Template = Specialization->getSpecializedTemplate();
9199  Arguments = Specialization->getTemplateArgs().data();
9200  } else if (const TemplateSpecializationType *TST =
9202  Template = dyn_cast_or_null<ClassTemplateDecl>(
9203  TST->getTemplateName().getAsTemplateDecl());
9204  Arguments = TST->getArgs();
9205  }
9206  if (!Template)
9207  return false;
9208 
9209  if (!StdInitializerList) {
9210  // Haven't recognized std::initializer_list yet, maybe this is it.
9211  CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
9212  if (TemplateClass->getIdentifier() !=
9213  &PP.getIdentifierTable().get("initializer_list") ||
9214  !getStdNamespace()->InEnclosingNamespaceSetOf(
9215  TemplateClass->getDeclContext()))
9216  return false;
9217  // This is a template called std::initializer_list, but is it the right
9218  // template?
9219  TemplateParameterList *Params = Template->getTemplateParameters();
9220  if (Params->getMinRequiredArguments() != 1)
9221  return false;
9222  if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
9223  return false;
9224 
9225  // It's the right template.
9226  StdInitializerList = Template;
9227  }
9228 
9229  if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
9230  return false;
9231 
9232  // This is an instance of std::initializer_list. Find the argument type.
9233  if (Element)
9234  *Element = Arguments[0].getAsType();
9235  return true;
9236 }
9237 
9240  if (!Std) {
9241  S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9242  return nullptr;
9243  }
9244 
9245  LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
9247  if (!S.LookupQualifiedName(Result, Std)) {
9248  S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9249  return nullptr;
9250  }
9251  ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
9252  if (!Template) {
9253  Result.suppressDiagnostics();
9254  // We found something weird. Complain about the first thing we found.
9255  NamedDecl *Found = *Result.begin();
9256  S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
9257  return nullptr;
9258  }
9259 
9260  // We found some template called std::initializer_list. Now verify that it's
9261  // correct.
9262  TemplateParameterList *Params = Template->getTemplateParameters();
9263  if (Params->getMinRequiredArguments() != 1 ||
9264  !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
9265  S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
9266  return nullptr;
9267  }
9268 
9269  return Template;
9270 }
9271 
9273  if (!StdInitializerList) {
9274  StdInitializerList = LookupStdInitializerList(*this, Loc);
9275  if (!StdInitializerList)
9276  return QualType();
9277  }
9278 
9279  TemplateArgumentListInfo Args(Loc, Loc);
9281  Context.getTrivialTypeSourceInfo(Element,
9282  Loc)));
9283  return Context.getCanonicalType(
9284  CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
9285 }
9286 
9288  // C++ [dcl.init.list]p2:
9289  // A constructor is an initializer-list constructor if its first parameter
9290  // is of type std::initializer_list<E> or reference to possibly cv-qualified
9291  // std::initializer_list<E> for some type E, and either there are no other
9292  // parameters or else all other parameters have default arguments.
9293  if (Ctor->getNumParams() < 1 ||
9294  (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
9295  return false;
9296 
9297  QualType ArgType = Ctor->getParamDecl(0)->getType();
9298  if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
9299  ArgType = RT->getPointeeType().getUnqualifiedType();
9300 
9301  return isStdInitializerList(ArgType, nullptr);
9302 }
9303 
9304 /// Determine whether a using statement is in a context where it will be
9305 /// apply in all contexts.
9307  switch (CurContext->getDeclKind()) {
9308  case Decl::TranslationUnit:
9309  return true;
9310  case Decl::LinkageSpec:
9311  return IsUsingDirectiveInToplevelContext(CurContext->getParent());
9312  default:
9313  return false;
9314  }
9315 }
9316 
9317 namespace {
9318 
9319 // Callback to only accept typo corrections that are namespaces.
9320 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
9321 public:
9322  bool ValidateCandidate(const TypoCorrection &candidate) override {
9323  if (NamedDecl *ND = candidate.getCorrectionDecl())
9324  return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
9325  return false;
9326  }
9327 };
9328 
9329 }
9330 
9332  CXXScopeSpec &SS,
9333  SourceLocation IdentLoc,
9334  IdentifierInfo *Ident) {
9335  R.clear();
9336  if (TypoCorrection Corrected =
9337  S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
9338  llvm::make_unique<NamespaceValidatorCCC>(),
9340  if (DeclContext *DC = S.computeDeclContext(SS, false)) {
9341  std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
9342  bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
9343  Ident->getName().equals(CorrectedStr);
9344  S.diagnoseTypo(Corrected,
9345  S.PDiag(diag::err_using_directive_member_suggest)
9346  << Ident << DC << DroppedSpecifier << SS.getRange(),
9347  S.PDiag(diag::note_namespace_defined_here));
9348  } else {
9349  S.diagnoseTypo(Corrected,
9350  S.PDiag(diag::err_using_directive_suggest) << Ident,
9351  S.PDiag(diag::note_namespace_defined_here));
9352  }
9353  R.addDecl(Corrected.getFoundDecl());
9354  return true;
9355  }
9356  return false;
9357 }
9358 
9360  SourceLocation NamespcLoc, CXXScopeSpec &SS,
9361  SourceLocation IdentLoc,
9362  IdentifierInfo *NamespcName,
9363  const ParsedAttributesView &AttrList) {
9364  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9365  assert(NamespcName && "Invalid NamespcName.");
9366  assert(IdentLoc.isValid() && "Invalid NamespceName location.");
9367 
9368  // This can only happen along a recovery path.
9369  while (S->isTemplateParamScope())
9370  S = S->getParent();
9371  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
9372 
9373  UsingDirectiveDecl *UDir = nullptr;
9374  NestedNameSpecifier *Qualifier = nullptr;
9375  if (SS.isSet())
9376  Qualifier = SS.getScopeRep();
9377 
9378  // Lookup namespace name.
9379  LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
9380  LookupParsedName(R, S, &SS);
9381  if (R.isAmbiguous())
9382  return nullptr;
9383 
9384  if (R.empty()) {
9385  R.clear();
9386  // Allow "using namespace std;" or "using namespace ::std;" even if
9387  // "std" hasn't been defined yet, for GCC compatibility.
9388  if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
9389  NamespcName->isStr("std")) {
9390  Diag(IdentLoc, diag::ext_using_undefined_std);
9391  R.addDecl(getOrCreateStdNamespace());
9392  R.resolveKind();
9393  }
9394  // Otherwise, attempt typo correction.
9395  else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
9396  }
9397 
9398  if (!R.empty()) {
9399  NamedDecl *Named = R.getRepresentativeDecl();
9401  assert(NS && "expected namespace decl");
9402 
9403  // The use of a nested name specifier may trigger deprecation warnings.
9404  DiagnoseUseOfDecl(Named, IdentLoc);
9405 
9406  // C++ [namespace.udir]p1:
9407  // A using-directive specifies that the names in the nominated
9408  // namespace can be used in the scope in which the
9409  // using-directive appears after the using-directive. During
9410  // unqualified name lookup (3.4.1), the names appear as if they
9411  // were declared in the nearest enclosing namespace which
9412  // contains both the using-directive and the nominated
9413  // namespace. [Note: in this context, "contains" means "contains
9414  // directly or indirectly". ]
9415 
9416  // Find enclosing context containing both using-directive and
9417  // nominated namespace.
9418  DeclContext *CommonAncestor = NS;
9419  while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
9420  CommonAncestor = CommonAncestor->getParent();
9421 
9422  UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
9423  SS.getWithLocInContext(Context),
9424  IdentLoc, Named, CommonAncestor);
9425 
9426  if (IsUsingDirectiveInToplevelContext(CurContext) &&
9427  !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
9428  Diag(IdentLoc, diag::warn_using_directive_in_header);
9429  }
9430 
9431  PushUsingDirective(S, UDir);
9432  } else {
9433  Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
9434  }
9435 
9436  if (UDir)
9437  ProcessDeclAttributeList(S, UDir, AttrList);
9438 
9439  return UDir;
9440 }
9441 
9443  // If the scope has an associated entity and the using directive is at
9444  // namespace or translation unit scope, add the UsingDirectiveDecl into
9445  // its lookup structure so qualified name lookup can find it.
9446  DeclContext *Ctx = S->getEntity();
9447  if (Ctx && !Ctx->isFunctionOrMethod())
9448  Ctx->addDecl(UDir);
9449  else
9450  // Otherwise, it is at block scope. The using-directives will affect lookup
9451  // only to the end of the scope.
9452  S->PushUsingDirective(UDir);
9453 }
9454 
9456  SourceLocation UsingLoc,
9457  SourceLocation TypenameLoc, CXXScopeSpec &SS,
9458  UnqualifiedId &Name,
9459  SourceLocation EllipsisLoc,
9460  const ParsedAttributesView &AttrList) {
9461  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
9462 
9463  if (SS.isEmpty()) {
9464  Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
9465  return nullptr;
9466  }
9467 
9468  switch (Name.getKind()) {
9474  break;
9475 
9478  // C++11 inheriting constructors.
9479  Diag(Name.getBeginLoc(),
9480  getLangOpts().CPlusPlus11
9481  ? diag::warn_cxx98_compat_using_decl_constructor
9482  : diag::err_using_decl_constructor)
9483  << SS.getRange();
9484 
9485  if (getLangOpts().CPlusPlus11) break;
9486 
9487  return nullptr;
9488 
9490  Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
9491  return nullptr;
9492 
9494  Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
9496  return nullptr;
9497 
9499  llvm_unreachable("cannot parse qualified deduction guide name");
9500  }
9501 
9502  DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
9503  DeclarationName TargetName = TargetNameInfo.getName();
9504  if (!TargetName)
9505  return nullptr;
9506 
9507  // Warn about access declarations.
9508  if (UsingLoc.isInvalid()) {
9509  Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
9510  ? diag::err_access_decl
9511  : diag::warn_access_decl_deprecated)
9512  << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
9513  }
9514 
9515  if (EllipsisLoc.isInvalid()) {
9516  if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
9517  DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
9518  return nullptr;
9519  } else {
9521  !TargetNameInfo.containsUnexpandedParameterPack()) {
9522  Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
9523  << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
9524  EllipsisLoc = SourceLocation();
9525  }
9526  }
9527 
9528  NamedDecl *UD =
9529  BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
9530  SS, TargetNameInfo, EllipsisLoc, AttrList,
9531  /*IsInstantiation*/false);
9532  if (UD)
9533  PushOnScopeChains(UD, S, /*AddToContext*/ false);
9534 
9535  return UD;
9536 }
9537 
9538 /// Determine whether a using declaration considers the given
9539 /// declarations as "equivalent", e.g., if they are redeclarations of
9540 /// the same entity or are both typedefs of the same type.
9541 static bool
9543  if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
9544  return true;
9545 
9546  if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
9547  if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
9548  return Context.hasSameType(TD1->getUnderlyingType(),
9549  TD2->getUnderlyingType());
9550 
9551  return false;
9552 }
9553 
9554 
9555 /// Determines whether to create a using shadow decl for a particular
9556 /// decl, given the set of decls existing prior to this using lookup.
9558  const LookupResult &Previous,
9559  UsingShadowDecl *&PrevShadow) {
9560  // Diagnose finding a decl which is not from a base class of the
9561  // current class. We do this now because there are cases where this
9562  // function will silently decide not to build a shadow decl, which
9563  // will pre-empt further diagnostics.
9564  //
9565  // We don't need to do this in C++11 because we do the check once on
9566  // the qualifier.
9567  //
9568  // FIXME: diagnose the following if we care enough:
9569  // struct A { int foo; };
9570  // struct B : A { using A::foo; };
9571  // template <class T> struct C : A {};
9572  // template <class T> struct D : C<T> { using B::foo; } // <---
9573  // This is invalid (during instantiation) in C++03 because B::foo
9574  // resolves to the using decl in B, which is not a base class of D<T>.
9575  // We can't diagnose it immediately because C<T> is an unknown
9576  // specialization. The UsingShadowDecl in D<T> then points directly
9577  // to A::foo, which will look well-formed when we instantiate.
9578  // The right solution is to not collapse the shadow-decl chain.
9579  if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
9580  DeclContext *OrigDC = Orig->getDeclContext();
9581 
9582  // Handle enums and anonymous structs.
9583  if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
9584  CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
9585  while (OrigRec->isAnonymousStructOrUnion())
9586  OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
9587 
9588  if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
9589  if (OrigDC == CurContext) {
9590  Diag(Using->getLocation(),
9591  diag::err_using_decl_nested_name_specifier_is_current_class)
9592  << Using->getQualifierLoc().getSourceRange();
9593  Diag(Orig->getLocation(), diag::note_using_decl_target);
9594  Using->setInvalidDecl();
9595  return true;
9596  }
9597 
9598  Diag(Using->getQualifierLoc().getBeginLoc(),
9599  diag::err_using_decl_nested_name_specifier_is_not_base_class)
9600  << Using->getQualifier()
9601  << cast<CXXRecordDecl>(CurContext)
9602  << Using->getQualifierLoc().getSourceRange();
9603  Diag(Orig->getLocation(), diag::note_using_decl_target);
9604  Using->setInvalidDecl();
9605  return true;
9606  }
9607  }
9608 
9609  if (Previous.empty()) return false;
9610 
9611  NamedDecl *Target = Orig;
9612  if (isa<UsingShadowDecl>(Target))
9613  Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9614 
9615  // If the target happens to be one of the previous declarations, we
9616  // don't have a conflict.
9617  //
9618  // FIXME: but we might be increasing its access, in which case we
9619  // should redeclare it.
9620  NamedDecl *NonTag = nullptr, *Tag = nullptr;
9621  bool FoundEquivalentDecl = false;
9622  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9623  I != E; ++I) {
9624  NamedDecl *D = (*I)->getUnderlyingDecl();
9625  // We can have UsingDecls in our Previous results because we use the same
9626  // LookupResult for checking whether the UsingDecl itself is a valid
9627  // redeclaration.
9628  if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
9629  continue;
9630 
9631  if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
9632  // C++ [class.mem]p19:
9633  // If T is the name of a class, then [every named member other than
9634  // a non-static data member] shall have a name different from T
9635  if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
9636  !isa<IndirectFieldDecl>(Target) &&
9637  !isa<UnresolvedUsingValueDecl>(Target) &&
9638  DiagnoseClassNameShadow(
9639  CurContext,
9640  DeclarationNameInfo(Using->getDeclName(), Using->getLocation())))
9641  return true;
9642  }
9643 
9644  if (IsEquivalentForUsingDecl(Context, D, Target)) {
9645  if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
9646  PrevShadow = Shadow;
9647  FoundEquivalentDecl = true;
9648  } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
9649  // We don't conflict with an existing using shadow decl of an equivalent
9650  // declaration, but we're not a redeclaration of it.
9651  FoundEquivalentDecl = true;
9652  }
9653 
9654  if (isVisible(D))
9655  (isa<TagDecl>(D) ? Tag : NonTag) = D;
9656  }
9657 
9658  if (FoundEquivalentDecl)
9659  return false;
9660 
9661  if (FunctionDecl *FD = Target->getAsFunction()) {
9662  NamedDecl *OldDecl = nullptr;
9663  switch (CheckOverload(nullptr, FD, Previous, OldDecl,
9664  /*IsForUsingDecl*/ true)) {
9665  case Ovl_Overload:
9666  return false;
9667 
9668  case Ovl_NonFunction:
9669  Diag(Using->getLocation(), diag::err_using_decl_conflict);
9670  break;
9671 
9672  // We found a decl with the exact signature.
9673  case Ovl_Match:
9674  // If we're in a record, we want to hide the target, so we
9675  // return true (without a diagnostic) to tell the caller not to
9676  // build a shadow decl.
9677  if (CurContext->isRecord())
9678  return true;
9679 
9680  // If we're not in a record, this is an error.
9681  Diag(Using->getLocation(), diag::err_using_decl_conflict);
9682  break;
9683  }
9684 
9685  Diag(Target->getLocation(), diag::note_using_decl_target);
9686  Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
9687  Using->setInvalidDecl();
9688  return true;
9689  }
9690 
9691  // Target is not a function.
9692 
9693  if (isa<TagDecl>(Target)) {
9694  // No conflict between a tag and a non-tag.
9695  if (!Tag) return false;
9696 
9697  Diag(Using->getLocation(), diag::err_using_decl_conflict);
9698  Diag(Target->getLocation(), diag::note_using_decl_target);
9699  Diag(Tag->getLocation(), diag::note_using_decl_conflict);
9700  Using->setInvalidDecl();
9701  return true;
9702  }
9703 
9704  // No conflict between a tag and a non-tag.
9705  if (!NonTag) return false;
9706 
9707  Diag(Using->getLocation(), diag::err_using_decl_conflict);
9708  Diag(Target->getLocation(), diag::note_using_decl_target);
9709  Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
9710  Using->setInvalidDecl();
9711  return true;
9712 }
9713 
9714 /// Determine whether a direct base class is a virtual base class.
9715 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
9716  if (!Derived->getNumVBases())
9717  return false;
9718  for (auto &B : Derived->bases())
9719  if (B.getType()->getAsCXXRecordDecl() == Base)
9720  return B.isVirtual();
9721  llvm_unreachable("not a direct base class");
9722 }
9723 
9724 /// Builds a shadow declaration corresponding to a 'using' declaration.
9726  UsingDecl *UD,
9727  NamedDecl *Orig,
9728  UsingShadowDecl *PrevDecl) {
9729  // If we resolved to another shadow declaration, just coalesce them.
9730  NamedDecl *Target = Orig;
9731  if (isa<UsingShadowDecl>(Target)) {
9732  Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9733  assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
9734  }
9735 
9736  NamedDecl *NonTemplateTarget = Target;
9737  if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
9738  NonTemplateTarget = TargetTD->getTemplatedDecl();
9739 
9740  UsingShadowDecl *Shadow;
9741  if (isa<CXXConstructorDecl>(NonTemplateTarget)) {
9742  bool IsVirtualBase =
9743  isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
9744  UD->getQualifier()->getAsRecordDecl());
9746  Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
9747  } else {
9748  Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
9749  Target);
9750  }
9751  UD->addShadowDecl(Shadow);
9752 
9753  Shadow->setAccess(UD->getAccess());
9754  if (Orig->isInvalidDecl() || UD->isInvalidDecl())
9755  Shadow->setInvalidDecl();
9756 
9757  Shadow->setPreviousDecl(PrevDecl);
9758 
9759  if (S)
9760  PushOnScopeChains(Shadow, S);
9761  else
9762  CurContext->addDecl(Shadow);
9763 
9764 
9765  return Shadow;
9766 }
9767 
9768 /// Hides a using shadow declaration. This is required by the current
9769 /// using-decl implementation when a resolvable using declaration in a
9770 /// class is followed by a declaration which would hide or override
9771 /// one or more of the using decl's targets; for example:
9772 ///
9773 /// struct Base { void foo(int); };
9774 /// struct Derived : Base {
9775 /// using Base::foo;
9776 /// void foo(int);
9777 /// };
9778 ///
9779 /// The governing language is C++03 [namespace.udecl]p12:
9780 ///
9781 /// When a using-declaration brings names from a base class into a
9782 /// derived class scope, member functions in the derived class
9783 /// override and/or hide member functions with the same name and
9784 /// parameter types in a base class (rather than conflicting).
9785 ///
9786 /// There are two ways to implement this:
9787 /// (1) optimistically create shadow decls when they're not hidden
9788 /// by existing declarations, or
9789 /// (2) don't create any shadow decls (or at least don't make them
9790 /// visible) until we've fully parsed/instantiated the class.
9791 /// The problem with (1) is that we might have to retroactively remove
9792 /// a shadow decl, which requires several O(n) operations because the
9793 /// decl structures are (very reasonably) not designed for removal.
9794 /// (2) avoids this but is very fiddly and phase-dependent.
9796  if (Shadow->getDeclName().getNameKind() ==
9798  cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
9799 
9800  // Remove it from the DeclContext...
9801  Shadow->getDeclContext()->removeDecl(Shadow);
9802 
9803  // ...and the scope, if applicable...
9804  if (S) {
9805  S->RemoveDecl(Shadow);
9806  IdResolver.RemoveDecl(Shadow);
9807  }
9808 
9809  // ...and the using decl.
9810  Shadow->getUsingDecl()->removeShadowDecl(Shadow);
9811 
9812  // TODO: complain somehow if Shadow was used. It shouldn't
9813  // be possible for this to happen, because...?
9814 }
9815 
9816 /// Find the base specifier for a base class with the given type.
9818  QualType DesiredBase,
9819  bool &AnyDependentBases) {
9820  // Check whether the named type is a direct base class.
9821  CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
9822  for (auto &Base : Derived->bases()) {
9823  CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
9824  if (CanonicalDesiredBase == BaseType)
9825  return &Base;
9826  if (BaseType->isDependentType())
9827  AnyDependentBases = true;
9828  }
9829  return nullptr;
9830 }
9831 
9832 namespace {
9833 class UsingValidatorCCC : public CorrectionCandidateCallback {
9834 public:
9835  UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
9836  NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
9837  : HasTypenameKeyword(HasTypenameKeyword),
9838  IsInstantiation(IsInstantiation), OldNNS(NNS),
9839  RequireMemberOf(RequireMemberOf) {}
9840 
9841  bool ValidateCandidate(const TypoCorrection &Candidate) override {
9842  NamedDecl *ND = Candidate.getCorrectionDecl();
9843 
9844  // Keywords are not valid here.
9845  if (!ND || isa<NamespaceDecl>(ND))
9846  return false;
9847 
9848  // Completely unqualified names are invalid for a 'using' declaration.
9849  if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
9850  return false;
9851 
9852  // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
9853  // reject.
9854 
9855  if (RequireMemberOf) {
9856  auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9857  if (FoundRecord && FoundRecord->isInjectedClassName()) {
9858  // No-one ever wants a using-declaration to name an injected-class-name
9859  // of a base class, unless they're declaring an inheriting constructor.
9860  ASTContext &Ctx = ND->getASTContext();
9861  if (!Ctx.getLangOpts().CPlusPlus11)
9862  return false;
9863  QualType FoundType = Ctx.getRecordType(FoundRecord);
9864 
9865  // Check that the injected-class-name is named as a member of its own
9866  // type; we don't want to suggest 'using Derived::Base;', since that
9867  // means something else.
9869  Candidate.WillReplaceSpecifier()
9870  ? Candidate.getCorrectionSpecifier()
9871  : OldNNS;
9872  if (!Specifier->getAsType() ||
9873  !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
9874  return false;
9875 
9876  // Check that this inheriting constructor declaration actually names a
9877  // direct base class of the current class.
9878  bool AnyDependentBases = false;
9879  if (!findDirectBaseWithType(RequireMemberOf,
9880  Ctx.getRecordType(FoundRecord),
9881  AnyDependentBases) &&
9882  !AnyDependentBases)
9883  return false;
9884  } else {
9885  auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
9886  if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
9887  return false;
9888 
9889  // FIXME: Check that the base class member is accessible?
9890  }
9891  } else {
9892  auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9893  if (FoundRecord && FoundRecord->isInjectedClassName())
9894  return false;
9895  }
9896 
9897  if (isa<TypeDecl>(ND))
9898  return HasTypenameKeyword || !IsInstantiation;
9899 
9900  return !HasTypenameKeyword;
9901  }
9902 
9903 private:
9904  bool HasTypenameKeyword;
9905  bool IsInstantiation;
9906  NestedNameSpecifier *OldNNS;
9907  CXXRecordDecl *RequireMemberOf;
9908 };
9909 } // end anonymous namespace
9910 
9911 /// Builds a using declaration.
9912 ///
9913 /// \param IsInstantiation - Whether this call arises from an
9914 /// instantiation of an unresolved using declaration. We treat
9915 /// the lookup differently for these declarations.
9917  Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
9918  bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
9919  DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
9920  const ParsedAttributesView &AttrList, bool IsInstantiation) {
9921  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9922  SourceLocation IdentLoc = NameInfo.getLoc();
9923  assert(IdentLoc.isValid() && "Invalid TargetName location.");
9924 
9925  // FIXME: We ignore attributes for now.
9926 
9927  // For an inheriting constructor declaration, the name of the using
9928  // declaration is the name of a constructor in this class, not in the
9929  // base class.
9930  DeclarationNameInfo UsingName = NameInfo;
9931  if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
9932  if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
9934  Context.getCanonicalType(Context.getRecordType(RD))));
9935 
9936  // Do the redeclaration lookup in the current scope.
9937  LookupResult Previous(*this, UsingName, LookupUsingDeclName,
9938  ForVisibleRedeclaration);
9939  Previous.setHideTags(false);
9940  if (S) {
9941  LookupName(Previous, S);
9942 
9943  // It is really dumb that we have to do this.
9944  LookupResult::Filter F = Previous.makeFilter();
9945  while (F.hasNext()) {
9946  NamedDecl *D = F.next();
9947  if (!isDeclInScope(D, CurContext, S))
9948  F.erase();
9949  // If we found a local extern declaration that's not ordinarily visible,
9950  // and this declaration is being added to a non-block scope, ignore it.
9951  // We're only checking for scope conflicts here, not also for violations
9952  // of the linkage rules.
9953  else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
9955  F.erase();
9956  }
9957  F.done();
9958  } else {
9959  assert(IsInstantiation && "no scope in non-instantiation");
9960  if (CurContext->isRecord())
9961  LookupQualifiedName(Previous, CurContext);
9962  else {
9963  // No redeclaration check is needed here; in non-member contexts we
9964  // diagnosed all possible conflicts with other using-declarations when
9965  // building the template:
9966  //
9967  // For a dependent non-type using declaration, the only valid case is
9968  // if we instantiate to a single enumerator. We check for conflicts
9969  // between shadow declarations we introduce, and we check in the template
9970  // definition for conflicts between a non-type using declaration and any
9971  // other declaration, which together covers all cases.
9972  //
9973  // A dependent typename using declaration will never successfully
9974  // instantiate, since it will always name a class member, so we reject
9975  // that in the template definition.
9976  }
9977  }
9978 
9979  // Check for invalid redeclarations.
9980  if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
9981  SS, IdentLoc, Previous))
9982  return nullptr;
9983 
9984  // Check for bad qualifiers.
9985  if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
9986  IdentLoc))
9987  return nullptr;
9988 
9989  DeclContext *LookupContext = computeDeclContext(SS);
9990  NamedDecl *D;
9991  NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9992  if (!LookupContext || EllipsisLoc.isValid()) {
9993  if (HasTypenameKeyword) {
9994  // FIXME: not all declaration name kinds are legal here
9995  D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
9996  UsingLoc, TypenameLoc,
9997  QualifierLoc,
9998  IdentLoc, NameInfo.getName(),
9999  EllipsisLoc);
10000  } else {
10001  D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
10002  QualifierLoc, NameInfo, EllipsisLoc);
10003  }
10004  D->setAccess(AS);
10005  CurContext->addDecl(D);
10006  return D;
10007  }
10008 
10009  auto Build = [&](bool Invalid) {
10010  UsingDecl *UD =
10011  UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
10012  UsingName, HasTypenameKeyword);
10013  UD->setAccess(AS);
10014  CurContext->addDecl(UD);
10015  UD->setInvalidDecl(Invalid);
10016  return UD;
10017  };
10018  auto BuildInvalid = [&]{ return Build(true); };
10019  auto BuildValid = [&]{ return Build(false); };
10020 
10021  if (RequireCompleteDeclContext(SS, LookupContext))
10022  return BuildInvalid();
10023 
10024  // Look up the target name.
10025  LookupResult R(*this, NameInfo, LookupOrdinaryName);
10026 
10027  // Unlike most lookups, we don't always want to hide tag
10028  // declarations: tag names are visible through the using declaration
10029  // even if hidden by ordinary names, *except* in a dependent context
10030  // where it's important for the sanity of two-phase lookup.
10031  if (!IsInstantiation)
10032  R.setHideTags(false);
10033 
10034  // For the purposes of this lookup, we have a base object type
10035  // equal to that of the current context.
10036  if (CurContext->isRecord()) {
10038  Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
10039  }
10040 
10041  LookupQualifiedName(R, LookupContext);
10042 
10043  // Try to correct typos if possible. If constructor name lookup finds no
10044  // results, that means the named class has no explicit constructors, and we
10045  // suppressed declaring implicit ones (probably because it's dependent or
10046  // invalid).
10047  if (R.empty() &&
10049  // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
10050  // it will believe that glibc provides a ::gets in cases where it does not,
10051  // and will try to pull it into namespace std with a using-declaration.
10052  // Just ignore the using-declaration in that case.
10053  auto *II = NameInfo.getName().getAsIdentifierInfo();
10054  if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
10055  CurContext->isStdNamespace() &&
10056  isa<TranslationUnitDecl>(LookupContext) &&
10057  getSourceManager().isInSystemHeader(UsingLoc))
10058  return nullptr;
10059  if (TypoCorrection Corrected = CorrectTypo(
10060  R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
10061  llvm::make_unique<UsingValidatorCCC>(
10062  HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
10063  dyn_cast<CXXRecordDecl>(CurContext)),
10064  CTK_ErrorRecovery)) {
10065  // We reject candidates where DroppedSpecifier == true, hence the
10066  // literal '0' below.
10067  diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
10068  << NameInfo.getName() << LookupContext << 0
10069  << SS.getRange());
10070 
10071  // If we picked a correction with no attached Decl we can't do anything
10072  // useful with it, bail out.
10073  NamedDecl *ND = Corrected.getCorrectionDecl();
10074  if (!ND)
10075  return BuildInvalid();
10076 
10077  // If we corrected to an inheriting constructor, handle it as one.
10078  auto *RD = dyn_cast<CXXRecordDecl>(ND);
10079  if (RD && RD->isInjectedClassName()) {
10080  // The parent of the injected class name is the class itself.
10081  RD = cast<CXXRecordDecl>(RD->getParent());
10082 
10083  // Fix up the information we'll use to build the using declaration.
10084  if (Corrected.WillReplaceSpecifier()) {
10086  Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
10087  QualifierLoc.getSourceRange());
10088  QualifierLoc = Builder.getWithLocInContext(Context);
10089  }
10090 
10091  // In this case, the name we introduce is the name of a derived class
10092  // constructor.
10093  auto *CurClass = cast<CXXRecordDecl>(CurContext);
10094  UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
10095  Context.getCanonicalType(Context.getRecordType(CurClass))));
10096  UsingName.setNamedTypeInfo(nullptr);
10097  for (auto *Ctor : LookupConstructors(RD))
10098  R.addDecl(Ctor);
10099  R.resolveKind();
10100  } else {
10101  // FIXME: Pick up all the declarations if we found an overloaded
10102  // function.
10103  UsingName.setName(ND->getDeclName());
10104  R.addDecl(ND);
10105  }
10106  } else {
10107  Diag(IdentLoc, diag::err_no_member)
10108  << NameInfo.getName() << LookupContext << SS.getRange();
10109  return BuildInvalid();
10110  }
10111  }
10112 
10113  if (R.isAmbiguous())
10114  return BuildInvalid();
10115 
10116  if (HasTypenameKeyword) {
10117  // If we asked for a typename and got a non-type decl, error out.
10118  if (!R.getAsSingle<TypeDecl>()) {
10119  Diag(IdentLoc, diag::err_using_typename_non_type);
10120  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10121  Diag((*I)->getUnderlyingDecl()->getLocation(),
10122  diag::note_using_decl_target);
10123  return BuildInvalid();
10124  }
10125  } else {
10126  // If we asked for a non-typename and we got a type, error out,
10127  // but only if this is an instantiation of an unresolved using
10128  // decl. Otherwise just silently find the type name.
10129  if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
10130  Diag(IdentLoc, diag::err_using_dependent_value_is_type);
10131  Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
10132  return BuildInvalid();
10133  }
10134  }
10135 
10136  // C++14 [namespace.udecl]p6:
10137  // A using-declaration shall not name a namespace.
10138  if (R.getAsSingle<NamespaceDecl>()) {
10139  Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
10140  << SS.getRange();
10141  return BuildInvalid();
10142  }
10143 
10144  // C++14 [namespace.udecl]p7:
10145  // A using-declaration shall not name a scoped enumerator.
10146  if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
10147  if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
10148  Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
10149  << SS.getRange();
10150  return BuildInvalid();
10151  }
10152  }
10153 
10154  UsingDecl *UD = BuildValid();
10155 
10156  // Some additional rules apply to inheriting constructors.
10157  if (UsingName.getName().getNameKind() ==
10159  // Suppress access diagnostics; the access check is instead performed at the
10160  // point of use for an inheriting constructor.
10161  R.suppressDiagnostics();
10162  if (CheckInheritingConstructorUsingDecl(UD))
10163  return UD;
10164  }
10165 
10166  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
10167  UsingShadowDecl *PrevDecl = nullptr;
10168  if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
10169  BuildUsingShadowDecl(S, UD, *I, PrevDecl);
10170  }
10171 
10172  return UD;
10173 }
10174 
10176  ArrayRef<NamedDecl *> Expansions) {
10177  assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
10178  isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
10179  isa<UsingPackDecl>(InstantiatedFrom));
10180 
10181  auto *UPD =
10182  UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
10183  UPD->setAccess(InstantiatedFrom->getAccess());
10184  CurContext->addDecl(UPD);
10185  return UPD;
10186 }
10187 
10188 /// Additional checks for a using declaration referring to a constructor name.
10190  assert(!UD->hasTypename() && "expecting a constructor name");
10191 
10192  const Type *SourceType = UD->getQualifier()->getAsType();
10193  assert(SourceType &&
10194  "Using decl naming constructor doesn't have type in scope spec.");
10195  CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
10196 
10197  // Check whether the named type is a direct base class.
10198  bool AnyDependentBases = false;
10199  auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
10200  AnyDependentBases);
10201  if (!Base && !AnyDependentBases) {
10202  Diag(UD->getUsingLoc(),
10203  diag::err_using_decl_constructor_not_in_direct_base)
10204  << UD->getNameInfo().getSourceRange()
10205  << QualType(SourceType, 0) << TargetClass;
10206  UD->setInvalidDecl();
10207  return true;
10208  }
10209 
10210  if (Base)
10211  Base->setInheritConstructors();
10212 
10213  return false;
10214 }
10215 
10216 /// Checks that the given using declaration is not an invalid
10217 /// redeclaration. Note that this is checking only for the using decl
10218 /// itself, not for any ill-formedness among the UsingShadowDecls.
10220  bool HasTypenameKeyword,
10221  const CXXScopeSpec &SS,
10222  SourceLocation NameLoc,
10223  const LookupResult &Prev) {
10224  NestedNameSpecifier *Qual = SS.getScopeRep();
10225 
10226  // C++03 [namespace.udecl]p8:
10227  // C++0x [namespace.udecl]p10:
10228  // A using-declaration is a declaration and can therefore be used
10229  // repeatedly where (and only where) multiple declarations are
10230  // allowed.
10231  //
10232  // That's in non-member contexts.
10233  if (!CurContext->getRedeclContext()->isRecord()) {
10234  // A dependent qualifier outside a class can only ever resolve to an
10235  // enumeration type. Therefore it conflicts with any other non-type
10236  // declaration in the same scope.
10237  // FIXME: How should we check for dependent type-type conflicts at block
10238  // scope?
10239  if (Qual->isDependent() && !HasTypenameKeyword) {
10240  for (auto *D : Prev) {
10241  if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
10242  bool OldCouldBeEnumerator =
10243  isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
10244  Diag(NameLoc,
10245  OldCouldBeEnumerator ? diag::err_redefinition
10246  : diag::err_redefinition_different_kind)
10247  << Prev.getLookupName();
10248  Diag(D->getLocation(), diag::note_previous_definition);
10249  return true;
10250  }
10251  }
10252  }
10253  return false;
10254  }
10255 
10256  for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
10257  NamedDecl *D = *I;
10258 
10259  bool DTypename;
10260  NestedNameSpecifier *DQual;
10261  if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
10262  DTypename = UD->hasTypename();
10263  DQual = UD->getQualifier();
10264  } else if (UnresolvedUsingValueDecl *UD
10265  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
10266  DTypename = false;
10267  DQual = UD->getQualifier();
10268  } else if (UnresolvedUsingTypenameDecl *UD
10269  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
10270  DTypename = true;
10271  DQual = UD->getQualifier();
10272  } else continue;
10273 
10274  // using decls differ if one says 'typename' and the other doesn't.
10275  // FIXME: non-dependent using decls?
10276  if (HasTypenameKeyword != DTypename) continue;
10277 
10278  // using decls differ if they name different scopes (but note that
10279  // template instantiation can cause this check to trigger when it
10280  // didn't before instantiation).
10281  if (Context.getCanonicalNestedNameSpecifier(Qual) !=
10282  Context.getCanonicalNestedNameSpecifier(DQual))
10283  continue;
10284 
10285  Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
10286  Diag(D->getLocation(), diag::note_using_decl) << 1;
10287  return true;
10288  }
10289 
10290  return false;
10291 }
10292 
10293 
10294 /// Checks that the given nested-name qualifier used in a using decl
10295 /// in the current context is appropriately related to the current
10296 /// scope. If an error is found, diagnoses it and returns true.
10298  bool HasTypename,
10299  const CXXScopeSpec &SS,
10300  const DeclarationNameInfo &NameInfo,
10301  SourceLocation NameLoc) {
10302  DeclContext *NamedContext = computeDeclContext(SS);
10303 
10304  if (!CurContext->isRecord()) {
10305  // C++03 [namespace.udecl]p3:
10306  // C++0x [namespace.udecl]p8:
10307  // A using-declaration for a class member shall be a member-declaration.
10308 
10309  // If we weren't able to compute a valid scope, it might validly be a
10310  // dependent class scope or a dependent enumeration unscoped scope. If
10311  // we have a 'typename' keyword, the scope must resolve to a class type.
10312  if ((HasTypename && !NamedContext) ||
10313  (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
10314  auto *RD = NamedContext
10315  ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
10316  : nullptr;
10317  if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
10318  RD = nullptr;
10319 
10320  Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
10321  << SS.getRange();
10322 
10323  // If we have a complete, non-dependent source type, try to suggest a
10324  // way to get the same effect.
10325  if (!RD)
10326  return true;
10327 
10328  // Find what this using-declaration was referring to.
10329  LookupResult R(*this, NameInfo, LookupOrdinaryName);
10330  R.setHideTags(false);
10331  R.suppressDiagnostics();
10332  LookupQualifiedName(R, RD);
10333 
10334  if (R.getAsSingle<TypeDecl>()) {
10335  if (getLangOpts().CPlusPlus11) {
10336  // Convert 'using X::Y;' to 'using Y = X::Y;'.
10337  Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
10338  << 0 // alias declaration
10340  NameInfo.getName().getAsString() +
10341  " = ");
10342  } else {
10343  // Convert 'using X::Y;' to 'typedef X::Y Y;'.
10344  SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
10345  Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
10346  << 1 // typedef declaration
10347  << FixItHint::CreateReplacement(UsingLoc, "typedef")
10349  InsertLoc, " " + NameInfo.getName().getAsString());
10350  }
10351  } else if (R.getAsSingle<VarDecl>()) {
10352  // Don't provide a fixit outside C++11 mode; we don't want to suggest
10353  // repeating the type of the static data member here.
10354  FixItHint FixIt;
10355  if (getLangOpts().CPlusPlus11) {
10356  // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10358  UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
10359  }
10360 
10361  Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10362  << 2 // reference declaration
10363  << FixIt;
10364  } else if (R.getAsSingle<EnumConstantDecl>()) {
10365  // Don't provide a fixit outside C++11 mode; we don't want to suggest
10366  // repeating the type of the enumeration here, and we can't do so if
10367  // the type is anonymous.
10368  FixItHint FixIt;
10369  if (getLangOpts().CPlusPlus11) {
10370  // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10372  UsingLoc,
10373  "constexpr auto " + NameInfo.getName().getAsString() + " = ");
10374  }
10375 
10376  Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10377  << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
10378  << FixIt;
10379  }
10380  return true;
10381  }
10382 
10383  // Otherwise, this might be valid.
10384  return false;
10385  }
10386 
10387  // The current scope is a record.
10388 
10389  // If the named context is dependent, we can't decide much.
10390  if (!NamedContext) {
10391  // FIXME: in C++0x, we can diagnose if we can prove that the
10392  // nested-name-specifier does not refer to a base class, which is
10393  // still possible in some cases.
10394 
10395  // Otherwise we have to conservatively report that things might be
10396  // okay.
10397  return false;
10398  }
10399 
10400  if (!NamedContext->isRecord()) {
10401  // Ideally this would point at the last name in the specifier,
10402  // but we don't have that level of source info.
10403  Diag(SS.getRange().getBegin(),
10404  diag::err_using_decl_nested_name_specifier_is_not_class)
10405  << SS.getScopeRep() << SS.getRange();
10406  return true;
10407  }
10408 
10409  if (!NamedContext->isDependentContext() &&
10410  RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
10411  return true;
10412 
10413  if (getLangOpts().CPlusPlus11) {
10414  // C++11 [namespace.udecl]p3:
10415  // In a using-declaration used as a member-declaration, the
10416  // nested-name-specifier shall name a base class of the class
10417  // being defined.
10418 
10419  if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
10420  cast<CXXRecordDecl>(NamedContext))) {
10421  if (CurContext == NamedContext) {
10422  Diag(NameLoc,
10423  diag::err_using_decl_nested_name_specifier_is_current_class)
10424  << SS.getRange();
10425  return true;
10426  }
10427 
10428  if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
10429  Diag(SS.getRange().getBegin(),
10430  diag::err_using_decl_nested_name_specifier_is_not_base_class)
10431  << SS.getScopeRep()
10432  << cast<CXXRecordDecl>(CurContext)
10433  << SS.getRange();
10434  }
10435  return true;
10436  }
10437 
10438  return false;
10439  }
10440 
10441  // C++03 [namespace.udecl]p4:
10442  // A using-declaration used as a member-declaration shall refer
10443  // to a member of a base class of the class being defined [etc.].
10444 
10445  // Salient point: SS doesn't have to name a base class as long as
10446  // lookup only finds members from base classes. Therefore we can
10447  // diagnose here only if we can prove that that can't happen,
10448  // i.e. if the class hierarchies provably don't intersect.
10449 
10450  // TODO: it would be nice if "definitely valid" results were cached
10451  // in the UsingDecl and UsingShadowDecl so that these checks didn't
10452  // need to be repeated.
10453 
10454  llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
10455  auto Collect = [&Bases](const CXXRecordDecl *Base) {
10456  Bases.insert(Base);
10457  return true;
10458  };
10459 
10460  // Collect all bases. Return false if we find a dependent base.
10461  if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
10462  return false;
10463 
10464  // Returns true if the base is dependent or is one of the accumulated base
10465  // classes.
10466  auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
10467  return !Bases.count(Base);
10468  };
10469 
10470  // Return false if the class has a dependent base or if it or one
10471  // of its bases is present in the base set of the current context.
10472  if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
10473  !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
10474  return false;
10475 
10476  Diag(SS.getRange().getBegin(),
10477  diag::err_using_decl_nested_name_specifier_is_not_base_class)
10478  << SS.getScopeRep()
10479  << cast<CXXRecordDecl>(CurContext)
10480  << SS.getRange();
10481 
10482  return true;
10483 }
10484 
10486  MultiTemplateParamsArg TemplateParamLists,
10487  SourceLocation UsingLoc, UnqualifiedId &Name,
10488  const ParsedAttributesView &AttrList,
10489  TypeResult Type, Decl *DeclFromDeclSpec) {
10490  // Skip up to the relevant declaration scope.
10491  while (S->isTemplateParamScope())
10492  S = S->getParent();
10493  assert((S->getFlags() & Scope::DeclScope) &&
10494  "got alias-declaration outside of declaration scope");
10495 
10496  if (Type.isInvalid())
10497  return nullptr;
10498 
10499  bool Invalid = false;
10500  DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
10501  TypeSourceInfo *TInfo = nullptr;
10502  GetTypeFromParser(Type.get(), &TInfo);
10503 
10504  if (DiagnoseClassNameShadow(CurContext, NameInfo))
10505  return nullptr;
10506 
10507  if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
10508  UPPC_DeclarationType)) {
10509  Invalid = true;
10510  TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10511  TInfo->getTypeLoc().getBeginLoc());
10512  }
10513 
10514  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
10515  TemplateParamLists.size()
10516  ? forRedeclarationInCurContext()
10517  : ForVisibleRedeclaration);
10518  LookupName(Previous, S);
10519 
10520  // Warn about shadowing the name of a template parameter.
10521  if (Previous.isSingleResult() &&
10522  Previous.getFoundDecl()->isTemplateParameter()) {
10523  DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
10524  Previous.clear();
10525  }
10526 
10527  assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
10528  "name in alias declaration must be an identifier");
10529  TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
10530  Name.StartLocation,
10531  Name.Identifier, TInfo);
10532 
10533  NewTD->setAccess(AS);
10534 
10535  if (Invalid)
10536  NewTD->setInvalidDecl();
10537 
10538  ProcessDeclAttributeList(S, NewTD, AttrList);
10539  AddPragmaAttributes(S, NewTD);
10540 
10541  CheckTypedefForVariablyModifiedType(S, NewTD);
10542  Invalid |= NewTD->isInvalidDecl();
10543 
10544  bool Redeclaration = false;
10545 
10546  NamedDecl *NewND;
10547  if (TemplateParamLists.size()) {
10548  TypeAliasTemplateDecl *OldDecl = nullptr;
10549  TemplateParameterList *OldTemplateParams = nullptr;
10550 
10551  if (TemplateParamLists.size() != 1) {
10552  Diag(UsingLoc, diag::err_alias_template_extra_headers)
10553  << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
10554  TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
10555  }
10556  TemplateParameterList *TemplateParams = TemplateParamLists[0];
10557 
10558  // Check that we can declare a template here.
10559  if (CheckTemplateDeclScope(S, TemplateParams))
10560  return nullptr;
10561 
10562  // Only consider previous declarations in the same scope.
10563  FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
10564  /*ExplicitInstantiationOrSpecialization*/false);
10565  if (!Previous.empty()) {
10566  Redeclaration = true;
10567 
10568  OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
10569  if (!OldDecl && !Invalid) {
10570  Diag(UsingLoc, diag::err_redefinition_different_kind)
10571  << Name.Identifier;
10572 
10573  NamedDecl *OldD = Previous.getRepresentativeDecl();
10574  if (OldD->getLocation().isValid())
10575  Diag(OldD->getLocation(), diag::note_previous_definition);
10576 
10577  Invalid = true;
10578  }
10579 
10580  if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
10581  if (TemplateParameterListsAreEqual(TemplateParams,
10582  OldDecl->getTemplateParameters(),
10583  /*Complain=*/true,
10584  TPL_TemplateMatch))
10585  OldTemplateParams =
10587  else
10588  Invalid = true;
10589 
10590  TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
10591  if (!Invalid &&
10592  !Context.hasSameType(OldTD->getUnderlyingType(),
10593  NewTD->getUnderlyingType())) {
10594  // FIXME: The C++0x standard does not clearly say this is ill-formed,
10595  // but we can't reasonably accept it.
10596  Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
10597  << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
10598  if (OldTD->getLocation().isValid())
10599  Diag(OldTD->getLocation(), diag::note_previous_definition);
10600  Invalid = true;
10601  }
10602  }
10603  }
10604 
10605  // Merge any previous default template arguments into our parameters,
10606  // and check the parameter list.
10607  if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
10608  TPC_TypeAliasTemplate))
10609  return nullptr;
10610 
10611  TypeAliasTemplateDecl *NewDecl =
10612  TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
10613  Name.Identifier, TemplateParams,
10614  NewTD);
10615  NewTD->setDescribedAliasTemplate(NewDecl);
10616 
10617  NewDecl->setAccess(AS);
10618 
10619  if (Invalid)
10620  NewDecl->setInvalidDecl();
10621  else if (OldDecl) {
10622  NewDecl->setPreviousDecl(OldDecl);
10623  CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
10624  }
10625 
10626  NewND = NewDecl;
10627  } else {
10628  if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
10629  setTagNameForLinkagePurposes(TD, NewTD);
10630  handleTagNumbering(TD, S);
10631  }
10632  ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
10633  NewND = NewTD;
10634  }
10635 
10636  PushOnScopeChains(NewND, S);
10637  ActOnDocumentableDecl(NewND);
10638  return NewND;
10639 }
10640 
10642  SourceLocation AliasLoc,
10643  IdentifierInfo *Alias, CXXScopeSpec &SS,
10644  SourceLocation IdentLoc,
10645  IdentifierInfo *Ident) {
10646 
10647  // Lookup the namespace name.
10648  LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
10649  LookupParsedName(R, S, &SS);
10650 
10651  if (R.isAmbiguous())
10652  return nullptr;
10653 
10654  if (R.empty()) {
10655  if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
10656  Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
10657  return nullptr;
10658  }
10659  }
10660  assert(!R.isAmbiguous() && !R.empty());
10661  NamedDecl *ND = R.getRepresentativeDecl();
10662 
10663  // Check if we have a previous declaration with the same name.
10664  LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
10665  ForVisibleRedeclaration);
10666  LookupName(PrevR, S);
10667 
10668  // Check we're not shadowing a template parameter.
10669  if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
10670  DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
10671  PrevR.clear();
10672  }
10673 
10674  // Filter out any other lookup result from an enclosing scope.
10675  FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
10676  /*AllowInlineNamespace*/false);
10677 
10678  // Find the previous declaration and check that we can redeclare it.
10679  NamespaceAliasDecl *Prev = nullptr;
10680  if (PrevR.isSingleResult()) {
10681  NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
10682  if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
10683  // We already have an alias with the same name that points to the same
10684  // namespace; check that it matches.
10685  if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
10686  Prev = AD;
10687  } else if (isVisible(PrevDecl)) {
10688  Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
10689  << Alias;
10690  Diag(AD->getLocation(), diag::note_previous_namespace_alias)
10691  << AD->getNamespace();
10692  return nullptr;
10693  }
10694  } else if (isVisible(PrevDecl)) {
10695  unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
10696  ? diag::err_redefinition
10697  : diag::err_redefinition_different_kind;
10698  Diag(AliasLoc, DiagID) << Alias;
10699  Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10700  return nullptr;
10701  }
10702  }
10703 
10704  // The use of a nested name specifier may trigger deprecation warnings.
10705  DiagnoseUseOfDecl(ND, IdentLoc);
10706 
10707  NamespaceAliasDecl *AliasDecl =
10708  NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
10709  Alias, SS.getWithLocInContext(Context),
10710  IdentLoc, ND);
10711  if (Prev)
10712  AliasDecl->setPreviousDecl(Prev);
10713 
10714  PushOnScopeChains(AliasDecl, S);
10715  return AliasDecl;
10716 }
10717 
10718 namespace {
10719 struct SpecialMemberExceptionSpecInfo
10720  : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
10721  SourceLocation Loc;
10723 
10724  SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
10727  SourceLocation Loc)
10728  : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
10729 
10730  bool visitBase(CXXBaseSpecifier *Base);
10731  bool visitField(FieldDecl *FD);
10732 
10733  void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
10734  unsigned Quals);
10735 
10736  void visitSubobjectCall(Subobject Subobj,
10738 };
10739 }
10740 
10741 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
10742  auto *RT = Base->getType()->getAs<RecordType>();
10743  if (!RT)
10744  return false;
10745 
10746  auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
10747  Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
10748  if (auto *BaseCtor = SMOR.getMethod()) {
10749  visitSubobjectCall(Base, BaseCtor);
10750  return false;
10751  }
10752 
10753  visitClassSubobject(BaseClass, Base, 0);
10754  return false;
10755 }
10756 
10757 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
10758  if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
10759  Expr *E = FD->getInClassInitializer();
10760  if (!E)
10761  // FIXME: It's a little wasteful to build and throw away a
10762  // CXXDefaultInitExpr here.
10763  // FIXME: We should have a single context note pointing at Loc, and
10764  // this location should be MD->getLocation() instead, since that's
10765  // the location where we actually use the default init expression.
10766  E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
10767  if (E)
10768  ExceptSpec.CalledExpr(E);
10769  } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
10770  ->getAs<RecordType>()) {
10771  visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
10772  FD->getType().getCVRQualifiers());
10773  }
10774  return false;
10775 }
10776 
10777 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
10778  Subobject Subobj,
10779  unsigned Quals) {
10780  FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
10781  bool IsMutable = Field && Field->isMutable();
10782  visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
10783 }
10784 
10785 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
10786  Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
10787  // Note, if lookup fails, it doesn't matter what exception specification we
10788  // choose because the special member will be deleted.
10789  if (CXXMethodDecl *MD = SMOR.getMethod())
10790  ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
10791 }
10792 
10793 namespace {
10794 /// RAII object to register a special member as being currently declared.
10795 struct ComputingExceptionSpec {
10796  Sema &S;
10797 
10798  ComputingExceptionSpec(Sema &S, CXXMethodDecl *MD, SourceLocation Loc)
10799  : S(S) {
10802  Ctx.PointOfInstantiation = Loc;
10803  Ctx.Entity = MD;
10804  S.pushCodeSynthesisContext(Ctx);
10805  }
10806  ~ComputingExceptionSpec() {
10808  }
10809 };
10810 }
10811 
10816  ComputingExceptionSpec CES(S, MD, Loc);
10817 
10818  CXXRecordDecl *ClassDecl = MD->getParent();
10819 
10820  // C++ [except.spec]p14:
10821  // An implicitly declared special member function (Clause 12) shall have an
10822  // exception-specification. [...]
10823  SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
10824  if (ClassDecl->isInvalidDecl())
10825  return Info.ExceptSpec;
10826 
10827  // FIXME: If this diagnostic fires, we're probably missing a check for
10828  // attempting to resolve an exception specification before it's known
10829  // at a higher level.
10831  S.Context.getRecordType(ClassDecl),
10832  diag::err_exception_spec_incomplete_type))
10833  return Info.ExceptSpec;
10834 
10835  // C++1z [except.spec]p7:
10836  // [Look for exceptions thrown by] a constructor selected [...] to
10837  // initialize a potentially constructed subobject,
10838  // C++1z [except.spec]p8:
10839  // The exception specification for an implicitly-declared destructor, or a
10840  // destructor without a noexcept-specifier, is potentially-throwing if and
10841  // only if any of the destructors for any of its potentially constructed
10842  // subojects is potentially throwing.
10843  // FIXME: We respect the first rule but ignore the "potentially constructed"
10844  // in the second rule to resolve a core issue (no number yet) that would have
10845  // us reject:
10846  // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
10847  // struct B : A {};
10848  // struct C : B { void f(); };
10849  // ... due to giving B::~B() a non-throwing exception specification.
10850  Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
10851  : Info.VisitAllBases);
10852 
10853  return Info.ExceptSpec;
10854 }
10855 
10856 namespace {
10857 /// RAII object to register a special member as being currently declared.
10858 struct DeclaringSpecialMember {
10859  Sema &S;
10861  Sema::ContextRAII SavedContext;
10862  bool WasAlreadyBeingDeclared;
10863 
10864  DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
10865  : S(S), D(RD, CSM), SavedContext(S, RD) {
10866  WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
10867  if (WasAlreadyBeingDeclared)
10868  // This almost never happens, but if it does, ensure that our cache
10869  // doesn't contain a stale result.
10870  S.SpecialMemberCache.clear();
10871  else {
10872  // Register a note to be produced if we encounter an error while
10873  // declaring the special member.
10876  // FIXME: We don't have a location to use here. Using the class's
10877  // location maintains the fiction that we declare all special members
10878  // with the class, but (1) it's not clear that lying about that helps our
10879  // users understand what's going on, and (2) there may be outer contexts
10880  // on the stack (some of which are relevant) and printing them exposes
10881  // our lies.
10882  Ctx.PointOfInstantiation = RD->getLocation();
10883  Ctx.Entity = RD;
10884  Ctx.SpecialMember = CSM;
10885  S.pushCodeSynthesisContext(Ctx);
10886  }
10887  }
10888  ~DeclaringSpecialMember() {
10889  if (!WasAlreadyBeingDeclared) {
10890  S.SpecialMembersBeingDeclared.erase(D);
10892  }
10893  }
10894 
10895  /// Are we already trying to declare this special member?
10896  bool isAlreadyBeingDeclared() const {
10897  return WasAlreadyBeingDeclared;
10898  }
10899 };
10900 }
10901 
10903  // Look up any existing declarations, but don't trigger declaration of all
10904  // implicit special members with this name.
10905  DeclarationName Name = FD->getDeclName();
10906  LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
10907  ForExternalRedeclaration);
10908  for (auto *D : FD->getParent()->lookup(Name))
10909  if (auto *Acceptable = R.getAcceptableDecl(D))
10910  R.addDecl(Acceptable);
10911  R.resolveKind();
10912  R.suppressDiagnostics();
10913 
10914  CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
10915 }
10916 
10917 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
10918  QualType ResultTy,
10919  ArrayRef<QualType> Args) {
10920  // Build an exception specification pointing back at this constructor.
10921  FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
10922 
10923  if (getLangOpts().OpenCLCPlusPlus) {
10924  // OpenCL: Implicitly defaulted special member are of the generic address
10925  // space.
10927  }
10928 
10929  auto QT = Context.getFunctionType(ResultTy, Args, EPI);
10930  SpecialMem->setType(QT);
10931 }
10932 
10934  CXXRecordDecl *ClassDecl) {
10935  // C++ [class.ctor]p5:
10936  // A default constructor for a class X is a constructor of class X
10937  // that can be called without an argument. If there is no
10938  // user-declared constructor for class X, a default constructor is
10939  // implicitly declared. An implicitly-declared default constructor
10940  // is an inline public member of its class.
10941  assert(ClassDecl->needsImplicitDefaultConstructor() &&
10942  "Should not build implicit default constructor!");
10943 
10944  DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
10945  if (DSM.isAlreadyBeingDeclared())
10946  return nullptr;
10947 
10948  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10949  CXXDefaultConstructor,
10950  false);
10951 
10952  // Create the actual constructor declaration.
10953  CanQualType ClassType
10954  = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10955  SourceLocation ClassLoc = ClassDecl->getLocation();
10956  DeclarationName Name
10957  = Context.DeclarationNames.getCXXConstructorName(ClassType);
10958  DeclarationNameInfo NameInfo(Name, ClassLoc);
10960  Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
10961  /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
10962  /*isImplicitlyDeclared=*/true, Constexpr);
10963  DefaultCon->setAccess(AS_public);
10964  DefaultCon->setDefaulted();
10965 
10966  if (getLangOpts().CUDA) {
10967  inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
10968  DefaultCon,
10969  /* ConstRHS */ false,
10970  /* Diagnose */ false);
10971  }
10972 
10973  setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
10974 
10975  // We don't need to use SpecialMemberIsTrivial here; triviality for default
10976  // constructors is easy to compute.
10977  DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
10978 
10979  // Note that we have declared this constructor.
10981 
10982  Scope *S = getScopeForContext(ClassDecl);
10983  CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
10984 
10985  if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
10986  SetDeclDeleted(DefaultCon, ClassLoc);
10987 
10988  if (S)
10989  PushOnScopeChains(DefaultCon, S, false);
10990  ClassDecl->addDecl(DefaultCon);
10991 
10992  return DefaultCon;
10993 }
10994 
10996  CXXConstructorDecl *Constructor) {
10997  assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
10998  !Constructor->doesThisDeclarationHaveABody() &&
10999  !Constructor->isDeleted()) &&
11000  "DefineImplicitDefaultConstructor - call it for implicit default ctor");
11001  if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
11002  return;
11003 
11004  CXXRecordDecl *ClassDecl = Constructor->getParent();
11005  assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
11006 
11007  SynthesizedFunctionScope Scope(*this, Constructor);
11008 
11009  // The exception specification is needed because we are defining the
11010  // function.
11011  ResolveExceptionSpec(CurrentLocation,
11012  Constructor->getType()->castAs<FunctionProtoType>());
11013  MarkVTableUsed(CurrentLocation, ClassDecl);
11014 
11015  // Add a context note for diagnostics produced after this point.
11016  Scope.addContextNote(CurrentLocation);
11017 
11018  if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
11019  Constructor->setInvalidDecl();
11020  return;
11021  }
11022 
11023  SourceLocation Loc = Constructor->getEndLoc().isValid()
11024  ? Constructor->getEndLoc()
11025  : Constructor->getLocation();
11026  Constructor->setBody(new (Context) CompoundStmt(Loc));
11027  Constructor->markUsed(Context);
11028 
11029  if (ASTMutationListener *L = getASTMutationListener()) {
11030  L->CompletedImplicitDefinition(Constructor);
11031  }
11032 
11033  DiagnoseUninitializedFields(*this, Constructor);
11034 }
11035 
11037  // Perform any delayed checks on exception specifications.
11038  CheckDelayedMemberExceptionSpecs();
11039 }
11040 
11041 /// Find or create the fake constructor we synthesize to model constructing an
11042 /// object of a derived class via a constructor of a base class.
11045  CXXConstructorDecl *BaseCtor,
11046  ConstructorUsingShadowDecl *Shadow) {
11047  CXXRecordDecl *Derived = Shadow->getParent();
11048  SourceLocation UsingLoc = Shadow->getLocation();
11049 
11050  // FIXME: Add a new kind of DeclarationName for an inherited constructor.
11051  // For now we use the name of the base class constructor as a member of the
11052  // derived class to indicate a (fake) inherited constructor name.
11053  DeclarationName Name = BaseCtor->getDeclName();
11054 
11055  // Check to see if we already have a fake constructor for this inherited
11056  // constructor call.
11057  for (NamedDecl *Ctor : Derived->lookup(Name))
11058  if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
11059  ->getInheritedConstructor()
11060  .getConstructor(),
11061  BaseCtor))
11062  return cast<CXXConstructorDecl>(Ctor);
11063 
11064  DeclarationNameInfo NameInfo(Name, UsingLoc);
11065  TypeSourceInfo *TInfo =
11066  Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
11067  FunctionProtoTypeLoc ProtoLoc =
11069 
11070  // Check the inherited constructor is valid and find the list of base classes
11071  // from which it was inherited.
11072  InheritedConstructorInfo ICI(*this, Loc, Shadow);
11073 
11074  bool Constexpr =
11075  BaseCtor->isConstexpr() &&
11076  defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
11077  false, BaseCtor, &ICI);
11078 
11080  Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
11081  BaseCtor->isExplicit(), /*Inline=*/true,
11082  /*ImplicitlyDeclared=*/true, Constexpr,
11083  InheritedConstructor(Shadow, BaseCtor));
11084  if (Shadow->isInvalidDecl())
11085  DerivedCtor->setInvalidDecl();
11086 
11087  // Build an unevaluated exception specification for this fake constructor.
11088  const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
11091  EPI.ExceptionSpec.SourceDecl = DerivedCtor;
11092  DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
11093  FPT->getParamTypes(), EPI));
11094 
11095  // Build the parameter declarations.
11096  SmallVector<ParmVarDecl *, 16> ParamDecls;
11097  for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
11098  TypeSourceInfo *TInfo =
11099  Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
11101  Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
11102  FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
11103  PD->setScopeInfo(0, I);
11104  PD->setImplicit();
11105  // Ensure attributes are propagated onto parameters (this matters for
11106  // format, pass_object_size, ...).
11107  mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
11108  ParamDecls.push_back(PD);
11109  ProtoLoc.setParam(I, PD);
11110  }
11111 
11112  // Set up the new constructor.
11113  assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
11114  DerivedCtor->setAccess(BaseCtor->getAccess());
11115  DerivedCtor->setParams(ParamDecls);
11116  Derived->addDecl(DerivedCtor);
11117 
11118  if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
11119  SetDeclDeleted(DerivedCtor, UsingLoc);
11120 
11121  return DerivedCtor;
11122 }
11123 
11125  InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
11127  ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
11128  /*Diagnose*/true);
11129 }
11130 
11132  CXXConstructorDecl *Constructor) {
11133  CXXRecordDecl *ClassDecl = Constructor->getParent();
11134  assert(Constructor->getInheritedConstructor() &&
11135  !Constructor->doesThisDeclarationHaveABody() &&
11136  !Constructor->isDeleted());
11137  if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
11138  return;
11139 
11140  // Initializations are performed "as if by a defaulted default constructor",
11141  // so enter the appropriate scope.
11142  SynthesizedFunctionScope Scope(*this, Constructor);
11143 
11144  // The exception specification is needed because we are defining the
11145  // function.
11146  ResolveExceptionSpec(CurrentLocation,
11147  Constructor->getType()->castAs<FunctionProtoType>());
11148  MarkVTableUsed(CurrentLocation, ClassDecl);
11149 
11150  // Add a context note for diagnostics produced after this point.
11151  Scope.addContextNote(CurrentLocation);
11152 
11153  ConstructorUsingShadowDecl *Shadow =
11154  Constructor->getInheritedConstructor().getShadowDecl();
11155  CXXConstructorDecl *InheritedCtor =
11156  Constructor->getInheritedConstructor().getConstructor();
11157 
11158  // [class.inhctor.init]p1:
11159  // initialization proceeds as if a defaulted default constructor is used to
11160  // initialize the D object and each base class subobject from which the
11161  // constructor was inherited
11162 
11163  InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
11164  CXXRecordDecl *RD = Shadow->getParent();
11165  SourceLocation InitLoc = Shadow->getLocation();
11166 
11167  // Build explicit initializers for all base classes from which the
11168  // constructor was inherited.
11170  for (bool VBase : {false, true}) {
11171  for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
11172  if (B.isVirtual() != VBase)
11173  continue;
11174 
11175  auto *BaseRD = B.getType()->getAsCXXRecordDecl();
11176  if (!BaseRD)
11177  continue;
11178 
11179  auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
11180  if (!BaseCtor.first)
11181  continue;
11182 
11183  MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
11184  ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
11185  InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
11186 
11187  auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
11188  Inits.push_back(new (Context) CXXCtorInitializer(
11189  Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
11190  SourceLocation()));
11191  }
11192  }
11193 
11194  // We now proceed as if for a defaulted default constructor, with the relevant
11195  // initializers replaced.
11196 
11197  if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
11198  Constructor->setInvalidDecl();
11199  return;
11200  }
11201 
11202  Constructor->setBody(new (Context) CompoundStmt(InitLoc));
11203  Constructor->markUsed(Context);
11204 
11205  if (ASTMutationListener *L = getASTMutationListener()) {
11206  L->CompletedImplicitDefinition(Constructor);
11207  }
11208 
11209  DiagnoseUninitializedFields(*this, Constructor);
11210 }
11211 
11213  // C++ [class.dtor]p2:
11214  // If a class has no user-declared destructor, a destructor is
11215  // declared implicitly. An implicitly-declared destructor is an
11216  // inline public member of its class.
11217  assert(ClassDecl->needsImplicitDestructor());
11218 
11219  DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
11220  if (DSM.isAlreadyBeingDeclared())
11221  return nullptr;
11222 
11223  // Create the actual destructor declaration.
11224  CanQualType ClassType
11225  = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
11226  SourceLocation ClassLoc = ClassDecl->getLocation();
11227  DeclarationName Name
11228  = Context.DeclarationNames.getCXXDestructorName(ClassType);
11229  DeclarationNameInfo NameInfo(Name, ClassLoc);
11230  CXXDestructorDecl *Destructor
11231  = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
11232  QualType(), nullptr, /*isInline=*/true,
11233  /*isImplicitlyDeclared=*/true);
11234  Destructor->setAccess(AS_public);
11235  Destructor->setDefaulted();
11236 
11237  if (getLangOpts().CUDA) {
11238  inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
11239  Destructor,
11240  /* ConstRHS */ false,
11241  /* Diagnose */ false);
11242  }
11243 
11244  setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
11245 
11246  // We don't need to use SpecialMemberIsTrivial here; triviality for
11247  // destructors is easy to compute.
11248  Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
11249  Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
11250  ClassDecl->hasTrivialDestructorForCall());
11251 
11252  // Note that we have declared this destructor.
11254 
11255  Scope *S = getScopeForContext(ClassDecl);
11256  CheckImplicitSpecialMemberDeclaration(S, Destructor);
11257 
11258  // We can't check whether an implicit destructor is deleted before we complete
11259  // the definition of the class, because its validity depends on the alignment
11260  // of the class. We'll check this from ActOnFields once the class is complete.
11261  if (ClassDecl->isCompleteDefinition() &&
11262  ShouldDeleteSpecialMember(Destructor, CXXDestructor))
11263  SetDeclDeleted(Destructor, ClassLoc);
11264 
11265  // Introduce this destructor into its scope.
11266  if (S)
11267  PushOnScopeChains(Destructor, S, false);
11268  ClassDecl->addDecl(Destructor);
11269 
11270  return Destructor;
11271 }
11272 
11274  CXXDestructorDecl *Destructor) {
11275  assert((Destructor->isDefaulted() &&
11276  !Destructor->doesThisDeclarationHaveABody() &&
11277  !Destructor->isDeleted()) &&
11278  "DefineImplicitDestructor - call it for implicit default dtor");
11279  if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
11280  return;
11281 
11282  CXXRecordDecl *ClassDecl = Destructor->getParent();
11283  assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
11284 
11285  SynthesizedFunctionScope Scope(*this, Destructor);
11286 
11287  // The exception specification is needed because we are defining the
11288  // function.
11289  ResolveExceptionSpec(CurrentLocation,
11290  Destructor->getType()->castAs<FunctionProtoType>());
11291  MarkVTableUsed(CurrentLocation, ClassDecl);
11292 
11293  // Add a context note for diagnostics produced after this point.
11294  Scope.addContextNote(CurrentLocation);
11295 
11296  MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
11297  Destructor->getParent());
11298 
11299  if (CheckDestructor(Destructor)) {
11300  Destructor->setInvalidDecl();
11301  return;
11302  }
11303 
11304  SourceLocation Loc = Destructor->getEndLoc().isValid()
11305  ? Destructor->getEndLoc()
11306  : Destructor->getLocation();
11307  Destructor->setBody(new (Context) CompoundStmt(Loc));
11308  Destructor->markUsed(Context);
11309 
11310  if (ASTMutationListener *L = getASTMutationListener()) {
11311  L->CompletedImplicitDefinition(Destructor);
11312  }
11313 }
11314 
11315 /// Perform any semantic analysis which needs to be delayed until all
11316 /// pending class member declarations have been parsed.
11318  // If the context is an invalid C++ class, just suppress these checks.
11319  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
11320  if (Record->isInvalidDecl()) {
11321  DelayedOverridingExceptionSpecChecks.clear();
11322  DelayedEquivalentExceptionSpecChecks.clear();
11323  DelayedDefaultedMemberExceptionSpecs.clear();
11324  return;
11325  }
11327  }
11328 }
11329 
11331  referenceDLLExportedClassMethods();
11332 }
11333 
11335  if (!DelayedDllExportClasses.empty()) {
11336  // Calling ReferenceDllExportedMembers might cause the current function to
11337  // be called again, so use a local copy of DelayedDllExportClasses.
11339  std::swap(DelayedDllExportClasses, WorkList);
11340  for (CXXRecordDecl *Class : WorkList)
11341  ReferenceDllExportedMembers(*this, Class);
11342  }
11343 }
11344 
11346  assert(getLangOpts().CPlusPlus11 &&
11347  "adjusting dtor exception specs was introduced in c++11");
11348 
11349  if (Destructor->isDependentContext())
11350  return;
11351 
11352  // C++11 [class.dtor]p3:
11353  // A declaration of a destructor that does not have an exception-
11354  // specification is implicitly considered to have the same exception-
11355  // specification as an implicit declaration.
11356  const FunctionProtoType *DtorType = Destructor->getType()->
11357  getAs<FunctionProtoType>();
11358  if (DtorType->hasExceptionSpec())
11359  return;
11360 
11361  // Replace the destructor's type, building off the existing one. Fortunately,
11362  // the only thing of interest in the destructor type is its extended info.
11363  // The return and arguments are fixed.
11366  EPI.ExceptionSpec.SourceDecl = Destructor;
11367  Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
11368 
11369  // FIXME: If the destructor has a body that could throw, and the newly created
11370  // spec doesn't allow exceptions, we should emit a warning, because this
11371  // change in behavior can break conforming C++03 programs at runtime.
11372  // However, we don't have a body or an exception specification yet, so it
11373  // needs to be done somewhere else.
11374 }
11375 
11376 namespace {
11377 /// An abstract base class for all helper classes used in building the
11378 // copy/move operators. These classes serve as factory functions and help us
11379 // avoid using the same Expr* in the AST twice.
11380 class ExprBuilder {
11381  ExprBuilder(const ExprBuilder&) = delete;
11382  ExprBuilder &operator=(const ExprBuilder&) = delete;
11383 
11384 protected:
11385  static Expr *assertNotNull(Expr *E) {
11386  assert(E && "Expression construction must not fail.");
11387  return E;
11388  }
11389 
11390 public:
11391  ExprBuilder() {}
11392  virtual ~ExprBuilder() {}
11393 
11394  virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
11395 };
11396 
11397 class RefBuilder: public ExprBuilder {
11398  VarDecl *Var;
11399  QualType VarType;
11400 
11401 public:
11402  Expr *build(Sema &S, SourceLocation Loc) const override {
11403  return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
11404  }
11405 
11406  RefBuilder(VarDecl *Var, QualType VarType)
11407  : Var(Var), VarType(VarType) {}
11408 };
11409 
11410 class ThisBuilder: public ExprBuilder {
11411 public:
11412  Expr *build(Sema &S, SourceLocation Loc) const override {
11413  return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
11414  }
11415 };
11416 
11417 class CastBuilder: public ExprBuilder {
11418  const ExprBuilder &Builder;
11419  QualType Type;
11421  const CXXCastPath &Path;
11422 
11423 public:
11424  Expr *build(Sema &S, SourceLocation Loc) const override {
11425  return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
11426  CK_UncheckedDerivedToBase, Kind,
11427  &Path).get());
11428  }
11429 
11430  CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
11431  const CXXCastPath &Path)
11432  : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
11433 };
11434 
11435 class DerefBuilder: public ExprBuilder {
11436  const ExprBuilder &Builder;
11437 
11438 public:
11439  Expr *build(Sema &S, SourceLocation Loc) const override {
11440  return assertNotNull(
11441  S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
11442  }
11443 
11444  DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11445 };
11446 
11447 class MemberBuilder: public ExprBuilder {
11448  const ExprBuilder &Builder;
11449  QualType Type;
11450  CXXScopeSpec SS;
11451  bool IsArrow;
11452  LookupResult &MemberLookup;
11453 
11454 public:
11455  Expr *build(Sema &S, SourceLocation Loc) const override {
11456  return assertNotNull(S.BuildMemberReferenceExpr(
11457  Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
11458  nullptr, MemberLookup, nullptr, nullptr).get());
11459  }
11460 
11461  MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
11462  LookupResult &MemberLookup)
11463  : Builder(Builder), Type(Type), IsArrow(IsArrow),
11464  MemberLookup(MemberLookup) {}
11465 };
11466 
11467 class MoveCastBuilder: public ExprBuilder {
11468  const ExprBuilder &Builder;
11469 
11470 public:
11471  Expr *build(Sema &S, SourceLocation Loc) const override {
11472  return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
11473  }
11474 
11475  MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11476 };
11477 
11478 class LvalueConvBuilder: public ExprBuilder {
11479  const ExprBuilder &Builder;
11480 
11481 public:
11482  Expr *build(Sema &S, SourceLocation Loc) const override {
11483  return assertNotNull(
11484  S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
11485  }
11486 
11487  LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11488 };
11489 
11490 class SubscriptBuilder: public ExprBuilder {
11491  const ExprBuilder &Base;
11492  const ExprBuilder &Index;
11493 
11494 public:
11495  Expr *build(Sema &S, SourceLocation Loc) const override {
11496  return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
11497  Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
11498  }
11499 
11500  SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
11501  : Base(Base), Index(Index) {}
11502 };
11503 
11504 } // end anonymous namespace
11505 
11506 /// When generating a defaulted copy or move assignment operator, if a field
11507 /// should be copied with __builtin_memcpy rather than via explicit assignments,
11508 /// do so. This optimization only applies for arrays of scalars, and for arrays
11509 /// of class type where the selected copy/move-assignment operator is trivial.
11510 static StmtResult
11512  const ExprBuilder &ToB, const ExprBuilder &FromB) {
11513  // Compute the size of the memory buffer to be copied.
11514  QualType SizeType = S.Context.getSizeType();
11515  llvm::APInt Size(S.Context.getTypeSize(SizeType),
11517 
11518  // Take the address of the field references for "from" and "to". We
11519  // directly construct UnaryOperators here because semantic analysis
11520  // does not permit us to take the address of an xvalue.
11521  Expr *From = FromB.build(S, Loc);
11522  From = new (S.Context) UnaryOperator(From, UO_AddrOf,
11523  S.Context.getPointerType(From->getType()),
11524  VK_RValue, OK_Ordinary, Loc, false);
11525  Expr *To = ToB.build(S, Loc);
11526  To = new (S.Context) UnaryOperator(To, UO_AddrOf,
11527  S.Context.getPointerType(To->getType()),
11528  VK_RValue, OK_Ordinary, Loc, false);
11529 
11530  const Type *E = T->getBaseElementTypeUnsafe();
11531  bool NeedsCollectableMemCpy =
11532  E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
11533 
11534  // Create a reference to the __builtin_objc_memmove_collectable function
11535  StringRef MemCpyName = NeedsCollectableMemCpy ?
11536  "__builtin_objc_memmove_collectable" :
11537  "__builtin_memcpy";
11538  LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
11540  S.LookupName(R, S.TUScope, true);
11541 
11542  FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
11543  if (!MemCpy)
11544  // Something went horribly wrong earlier, and we will have complained
11545  // about it.
11546  return StmtError();
11547 
11548  ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
11549  VK_RValue, Loc, nullptr);
11550  assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
11551 
11552  Expr *CallArgs[] = {
11553  To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
11554  };
11555  ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
11556  Loc, CallArgs, Loc);
11557 
11558  assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
11559  return Call.getAs<Stmt>();
11560 }
11561 
11562 /// Builds a statement that copies/moves the given entity from \p From to
11563 /// \c To.
11564 ///
11565 /// This routine is used to copy/move the members of a class with an
11566 /// implicitly-declared copy/move assignment operator. When the entities being
11567 /// copied are arrays, this routine builds for loops to copy them.
11568 ///
11569 /// \param S The Sema object used for type-checking.
11570 ///
11571 /// \param Loc The location where the implicit copy/move is being generated.
11572 ///
11573 /// \param T The type of the expressions being copied/moved. Both expressions
11574 /// must have this type.
11575 ///
11576 /// \param To The expression we are copying/moving to.
11577 ///
11578 /// \param From The expression we are copying/moving from.
11579 ///
11580 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
11581 /// Otherwise, it's a non-static member subobject.
11582 ///
11583 /// \param Copying Whether we're copying or moving.
11584 ///
11585 /// \param Depth Internal parameter recording the depth of the recursion.
11586 ///
11587 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
11588 /// if a memcpy should be used instead.
11589 static StmtResult
11591  const ExprBuilder &To, const ExprBuilder &From,
11592  bool CopyingBaseSubobject, bool Copying,
11593  unsigned Depth = 0) {
11594  // C++11 [class.copy]p28:
11595  // Each subobject is assigned in the manner appropriate to its type:
11596  //
11597  // - if the subobject is of class type, as if by a call to operator= with
11598  // the subobject as the object expression and the corresponding
11599  // subobject of x as a single function argument (as if by explicit
11600  // qualification; that is, ignoring any possible virtual overriding
11601  // functions in more derived classes);
11602  //
11603  // C++03 [class.copy]p13:
11604  // - if the subobject is of class type, the copy assignment operator for
11605  // the class is used (as if by explicit qualification; that is,
11606  // ignoring any possible virtual overriding functions in more derived
11607  // classes);
11608  if (const RecordType *RecordTy = T->getAs<RecordType>()) {
11609  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
11610 
11611  // Look for operator=.
11612  DeclarationName Name
11614  LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
11615  S.LookupQualifiedName(OpLookup, ClassDecl, false);
11616 
11617  // Prior to C++11, filter out any result that isn't a copy/move-assignment
11618  // operator.
11619  if (!S.getLangOpts().CPlusPlus11) {
11620  LookupResult::Filter F = OpLookup.makeFilter();
11621  while (F.hasNext()) {
11622  NamedDecl *D = F.next();
11623  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
11624  if (Method->isCopyAssignmentOperator() ||
11625  (!Copying && Method->isMoveAssignmentOperator()))
11626  continue;
11627 
11628  F.erase();
11629  }
11630  F.done();
11631  }
11632 
11633  // Suppress the protected check (C++ [class.protected]) for each of the
11634  // assignment operators we found. This strange dance is required when
11635  // we're assigning via a base classes's copy-assignment operator. To
11636  // ensure that we're getting the right base class subobject (without
11637  // ambiguities), we need to cast "this" to that subobject type; to
11638  // ensure that we don't go through the virtual call mechanism, we need
11639  // to qualify the operator= name with the base class (see below). However,
11640  // this means that if the base class has a protected copy assignment
11641  // operator, the protected member access check will fail. So, we
11642  // rewrite "protected" access to "public" access in this case, since we
11643  // know by construction that we're calling from a derived class.
11644  if (CopyingBaseSubobject) {
11645  for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
11646  L != LEnd; ++L) {
11647  if (L.getAccess() == AS_protected)
11648  L.setAccess(AS_public);
11649  }
11650  }
11651 
11652  // Create the nested-name-specifier that will be used to qualify the
11653  // reference to operator=; this is required to suppress the virtual
11654  // call mechanism.
11655  CXXScopeSpec SS;
11656  const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
11657  SS.MakeTrivial(S.Context,
11658  NestedNameSpecifier::Create(S.Context, nullptr, false,
11659  CanonicalT),
11660  Loc);
11661 
11662  // Create the reference to operator=.
11663  ExprResult OpEqualRef
11664  = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
11665  SS, /*TemplateKWLoc=*/SourceLocation(),
11666  /*FirstQualifierInScope=*/nullptr,
11667  OpLookup,
11668  /*TemplateArgs=*/nullptr, /*S*/nullptr,
11669  /*SuppressQualifierCheck=*/true);
11670  if (OpEqualRef.isInvalid())
11671  return StmtError();
11672 
11673  // Build the call to the assignment operator.
11674 
11675  Expr *FromInst = From.build(S, Loc);
11676  ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
11677  OpEqualRef.getAs<Expr>(),
11678  Loc, FromInst, Loc);
11679  if (Call.isInvalid())
11680  return StmtError();
11681 
11682  // If we built a call to a trivial 'operator=' while copying an array,
11683  // bail out. We'll replace the whole shebang with a memcpy.
11684  CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
11685  if (CE && CE->getMethodDecl()->isTrivial() && Depth)
11686  return StmtResult((Stmt*)nullptr);
11687 
11688  // Convert to an expression-statement, and clean up any produced
11689  // temporaries.
11690  return S.ActOnExprStmt(Call);
11691  }
11692 
11693  // - if the subobject is of scalar type, the built-in assignment
11694  // operator is used.
11695  const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
11696  if (!ArrayTy) {
11698  Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
11699  if (Assignment.isInvalid())
11700  return StmtError();
11701  return S.ActOnExprStmt(Assignment);
11702  }
11703 
11704  // - if the subobject is an array, each element is assigned, in the
11705  // manner appropriate to the element type;
11706 
11707  // Construct a loop over the array bounds, e.g.,
11708  //
11709  // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
11710  //
11711  // that will copy each of the array elements.
11712  QualType SizeType = S.Context.getSizeType();
11713 
11714  // Create the iteration variable.
11715  IdentifierInfo *IterationVarName = nullptr;
11716  {
11717  SmallString<8> Str;
11718  llvm::raw_svector_ostream OS(Str);
11719  OS << "__i" << Depth;
11720  IterationVarName = &S.Context.Idents.get(OS.str());
11721  }
11722  VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11723  IterationVarName, SizeType,
11724  S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
11725  SC_None);
11726 
11727  // Initialize the iteration variable to zero.
11728  llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
11729  IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
11730 
11731  // Creates a reference to the iteration variable.
11732  RefBuilder IterationVarRef(IterationVar, SizeType);
11733  LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
11734 
11735  // Create the DeclStmt that holds the iteration variable.
11736  Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
11737 
11738  // Subscript the "from" and "to" expressions with the iteration variable.
11739  SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
11740  MoveCastBuilder FromIndexMove(FromIndexCopy);
11741  const ExprBuilder *FromIndex;
11742  if (Copying)
11743  FromIndex = &FromIndexCopy;
11744  else
11745  FromIndex = &FromIndexMove;
11746 
11747  SubscriptBuilder ToIndex(To, IterationVarRefRVal);
11748 
11749  // Build the copy/move for an individual element of the array.
11750  StmtResult Copy =
11752  ToIndex, *FromIndex, CopyingBaseSubobject,
11753  Copying, Depth + 1);
11754  // Bail out if copying fails or if we determined that we should use memcpy.
11755  if (Copy.isInvalid() || !Copy.get())
11756  return Copy;
11757 
11758  // Create the comparison against the array bound.
11759  llvm::APInt Upper
11760  = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
11761  Expr *Comparison
11762  = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
11763  IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
11764  BO_NE, S.Context.BoolTy,
11765  VK_RValue, OK_Ordinary, Loc, FPOptions());
11766 
11767  // Create the pre-increment of the iteration variable. We can determine
11768  // whether the increment will overflow based on the value of the array
11769  // bound.
11770  Expr *Increment = new (S.Context)
11771  UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType,
11772  VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue());
11773 
11774  // Construct the loop that copies all elements of this array.
11775  return S.ActOnForStmt(
11776  Loc, Loc, InitStmt,
11777  S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
11778  S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
11779 }
11780 
11781 static StmtResult
11783  const ExprBuilder &To, const ExprBuilder &From,
11784  bool CopyingBaseSubobject, bool Copying) {
11785  // Maybe we should use a memcpy?
11786  if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
11788  return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11789 
11791  CopyingBaseSubobject,
11792  Copying, 0));
11793 
11794  // If we ended up picking a trivial assignment operator for an array of a
11795  // non-trivially-copyable class type, just emit a memcpy.
11796  if (!Result.isInvalid() && !Result.get())
11797  return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11798 
11799  return Result;
11800 }
11801 
11803  // Note: The following rules are largely analoguous to the copy
11804  // constructor rules. Note that virtual bases are not taken into account
11805  // for determining the argument type of the operator. Note also that
11806  // operators taking an object instead of a reference are allowed.
11807  assert(ClassDecl->needsImplicitCopyAssignment());
11808 
11809  DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
11810  if (DSM.isAlreadyBeingDeclared())
11811  return nullptr;
11812 
11813  QualType ArgType = Context.getTypeDeclType(ClassDecl);
11814  QualType RetType = Context.getLValueReferenceType(ArgType);
11815  bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
11816  if (Const)
11817  ArgType = ArgType.withConst();
11818 
11819  if (Context.getLangOpts().OpenCLCPlusPlus)
11820  ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
11821 
11822  ArgType = Context.getLValueReferenceType(ArgType);
11823 
11824  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11825  CXXCopyAssignment,
11826  Const);
11827 
11828  // An implicitly-declared copy assignment operator is an inline public
11829  // member of its class.
11830  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11831  SourceLocation ClassLoc = ClassDecl->getLocation();
11832  DeclarationNameInfo NameInfo(Name, ClassLoc);
11833  CXXMethodDecl *CopyAssignment =
11834  CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
11835  /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
11836  /*isInline=*/true, Constexpr, SourceLocation());
11837  CopyAssignment->setAccess(AS_public);
11838  CopyAssignment->setDefaulted();
11839  CopyAssignment->setImplicit();
11840 
11841  if (getLangOpts().CUDA) {
11842  inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
11843  CopyAssignment,
11844  /* ConstRHS */ Const,
11845  /* Diagnose */ false);
11846  }
11847 
11848  setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
11849 
11850  // Add the parameter to the operator.
11851  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
11852  ClassLoc, ClassLoc,
11853  /*Id=*/nullptr, ArgType,
11854  /*TInfo=*/nullptr, SC_None,
11855  nullptr);
11856  CopyAssignment->setParams(FromParam);
11857 
11858  CopyAssignment->setTrivial(
11860  ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
11861  : ClassDecl->hasTrivialCopyAssignment());
11862 
11863  // Note that we have added this copy-assignment operator.
11865 
11866  Scope *S = getScopeForContext(ClassDecl);
11867  CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
11868 
11869  if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
11870  SetDeclDeleted(CopyAssignment, ClassLoc);
11871 
11872  if (S)
11873  PushOnScopeChains(CopyAssignment, S, false);
11874  ClassDecl->addDecl(CopyAssignment);
11875 
11876  return CopyAssignment;
11877 }
11878 
11879 /// Diagnose an implicit copy operation for a class which is odr-used, but
11880 /// which is deprecated because the class has a user-declared copy constructor,
11881 /// copy assignment operator, or destructor.
11883  assert(CopyOp->isImplicit());
11884 
11885  CXXRecordDecl *RD = CopyOp->getParent();
11886  CXXMethodDecl *UserDeclaredOperation = nullptr;
11887 
11888  // In Microsoft mode, assignment operations don't affect constructors and
11889  // vice versa.
11890  if (RD->hasUserDeclaredDestructor()) {
11891  UserDeclaredOperation = RD->getDestructor();
11892  } else if (!isa<CXXConstructorDecl>(CopyOp) &&
11893  RD->hasUserDeclaredCopyConstructor() &&
11894  !S.getLangOpts().MSVCCompat) {
11895  // Find any user-declared copy constructor.
11896  for (auto *I : RD->ctors()) {
11897  if (I->isCopyConstructor()) {
11898  UserDeclaredOperation = I;
11899  break;
11900  }
11901  }
11902  assert(UserDeclaredOperation);
11903  } else if (isa<CXXConstructorDecl>(CopyOp) &&
11904  RD->hasUserDeclaredCopyAssignment() &&
11905  !S.getLangOpts().MSVCCompat) {
11906  // Find any user-declared move assignment operator.
11907  for (auto *I : RD->methods()) {
11908  if (I->isCopyAssignmentOperator()) {
11909  UserDeclaredOperation = I;
11910  break;
11911  }
11912  }
11913  assert(UserDeclaredOperation);
11914  }
11915 
11916  if (UserDeclaredOperation) {
11917  S.Diag(UserDeclaredOperation->getLocation(),
11918  diag::warn_deprecated_copy_operation)
11919  << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
11920  << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
11921  }
11922 }
11923 
11925  CXXMethodDecl *CopyAssignOperator) {
11926  assert((CopyAssignOperator->isDefaulted() &&
11927  CopyAssignOperator->isOverloadedOperator() &&
11928  CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
11929  !CopyAssignOperator->doesThisDeclarationHaveABody() &&
11930  !CopyAssignOperator->isDeleted()) &&
11931  "DefineImplicitCopyAssignment called for wrong function");
11932  if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
11933  return;
11934 
11935  CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
11936  if (ClassDecl->isInvalidDecl()) {
11937  CopyAssignOperator->setInvalidDecl();
11938  return;
11939  }
11940 
11941  SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
11942 
11943  // The exception specification is needed because we are defining the
11944  // function.
11945  ResolveExceptionSpec(CurrentLocation,
11946  CopyAssignOperator->getType()->castAs<FunctionProtoType>());
11947 
11948  // Add a context note for diagnostics produced after this point.
11949  Scope.addContextNote(CurrentLocation);
11950 
11951  // C++11 [class.copy]p18:
11952  // The [definition of an implicitly declared copy assignment operator] is
11953  // deprecated if the class has a user-declared copy constructor or a
11954  // user-declared destructor.
11955  if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
11956  diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
11957 
11958  // C++0x [class.copy]p30:
11959  // The implicitly-defined or explicitly-defaulted copy assignment operator
11960  // for a non-union class X performs memberwise copy assignment of its
11961  // subobjects. The direct base classes of X are assigned first, in the
11962  // order of their declaration in the base-specifier-list, and then the
11963  // immediate non-static data members of X are assigned, in the order in
11964  // which they were declared in the class definition.
11965 
11966  // The statements that form the synthesized function body.
11967  SmallVector<Stmt*, 8> Statements;
11968 
11969  // The parameter for the "other" object, which we are copying from.
11970  ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
11971  Qualifiers OtherQuals = Other->getType().getQualifiers();
11972  QualType OtherRefType = Other->getType();
11973  if (const LValueReferenceType *OtherRef
11974  = OtherRefType->getAs<LValueReferenceType>()) {
11975  OtherRefType = OtherRef->getPointeeType();
11976  OtherQuals = OtherRefType.getQualifiers();
11977  }
11978 
11979  // Our location for everything implicitly-generated.
11980  SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
11981  ? CopyAssignOperator->getEndLoc()
11982  : CopyAssignOperator->getLocation();
11983 
11984  // Builds a DeclRefExpr for the "other" object.
11985  RefBuilder OtherRef(Other, OtherRefType);
11986 
11987  // Builds the "this" pointer.
11988  ThisBuilder This;
11989 
11990  // Assign base classes.
11991  bool Invalid = false;
11992  for (auto &Base : ClassDecl->bases()) {
11993  // Form the assignment:
11994  // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
11995  QualType BaseType = Base.getType().getUnqualifiedType();
11996  if (!BaseType->isRecordType()) {
11997  Invalid = true;
11998  continue;
11999  }
12000 
12001  CXXCastPath BasePath;
12002  BasePath.push_back(&Base);
12003 
12004  // Construct the "from" expression, which is an implicit cast to the
12005  // appropriately-qualified base type.
12006  CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
12007  VK_LValue, BasePath);
12008 
12009  // Dereference "this".
12010  DerefBuilder DerefThis(This);
12011  CastBuilder To(DerefThis,
12012  Context.getQualifiedType(
12013  BaseType, CopyAssignOperator->getTypeQualifiers()),
12014  VK_LValue, BasePath);
12015 
12016  // Build the copy.
12017  StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
12018  To, From,
12019  /*CopyingBaseSubobject=*/true,
12020  /*Copying=*/true);
12021  if (Copy.isInvalid()) {
12022  CopyAssignOperator->setInvalidDecl();
12023  return;
12024  }
12025 
12026  // Success! Record the copy.
12027  Statements.push_back(Copy.getAs<Expr>());
12028  }
12029 
12030  // Assign non-static members.
12031  for (auto *Field : ClassDecl->fields()) {
12032  // FIXME: We should form some kind of AST representation for the implied
12033  // memcpy in a union copy operation.
12034  if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
12035  continue;
12036 
12037  if (Field->isInvalidDecl()) {
12038  Invalid = true;
12039  continue;
12040  }
12041 
12042  // Check for members of reference type; we can't copy those.
12043  if (Field->getType()->isReferenceType()) {
12044  Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12045  << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
12046  Diag(Field->getLocation(), diag::note_declared_at);
12047  Invalid = true;
12048  continue;
12049  }
12050 
12051  // Check for members of const-qualified, non-class type.
12052  QualType BaseType = Context.getBaseElementType(Field->getType());
12053  if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
12054  Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12055  << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
12056  Diag(Field->getLocation(), diag::note_declared_at);
12057  Invalid = true;
12058  continue;
12059  }
12060 
12061  // Suppress assigning zero-width bitfields.
12062  if (Field->isZeroLengthBitField(Context))
12063  continue;
12064 
12065  QualType FieldType = Field->getType().getNonReferenceType();
12066  if (FieldType->isIncompleteArrayType()) {
12067  assert(ClassDecl->hasFlexibleArrayMember() &&
12068  "Incomplete array type is not valid");
12069  continue;
12070  }
12071 
12072  // Build references to the field in the object we're copying from and to.
12073  CXXScopeSpec SS; // Intentionally empty
12074  LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
12075  LookupMemberName);
12076  MemberLookup.addDecl(Field);
12077  MemberLookup.resolveKind();
12078 
12079  MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
12080 
12081  MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
12082 
12083  // Build the copy of this field.
12084  StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
12085  To, From,
12086  /*CopyingBaseSubobject=*/false,
12087  /*Copying=*/true);
12088  if (Copy.isInvalid()) {
12089  CopyAssignOperator->setInvalidDecl();
12090  return;
12091  }
12092 
12093  // Success! Record the copy.
12094  Statements.push_back(Copy.getAs<Stmt>());
12095  }
12096 
12097  if (!Invalid) {
12098  // Add a "return *this;"
12099  ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
12100 
12101  StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
12102  if (Return.isInvalid())
12103  Invalid = true;
12104  else
12105  Statements.push_back(Return.getAs<Stmt>());
12106  }
12107 
12108  if (Invalid) {
12109  CopyAssignOperator->setInvalidDecl();
12110  return;
12111  }
12112 
12113  StmtResult Body;
12114  {
12115  CompoundScopeRAII CompoundScope(*this);
12116  Body = ActOnCompoundStmt(Loc, Loc, Statements,
12117  /*isStmtExpr=*/false);
12118  assert(!Body.isInvalid() && "Compound statement creation cannot fail");
12119  }
12120  CopyAssignOperator->setBody(Body.getAs<Stmt>());
12121  CopyAssignOperator->markUsed(Context);
12122 
12123  if (ASTMutationListener *L = getASTMutationListener()) {
12124  L->CompletedImplicitDefinition(CopyAssignOperator);
12125  }
12126 }
12127 
12129  assert(ClassDecl->needsImplicitMoveAssignment());
12130 
12131  DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
12132  if (DSM.isAlreadyBeingDeclared())
12133  return nullptr;
12134 
12135  // Note: The following rules are largely analoguous to the move
12136  // constructor rules.
12137 
12138  QualType ArgType = Context.getTypeDeclType(ClassDecl);
12139  QualType RetType = Context.getLValueReferenceType(ArgType);
12140  ArgType = Context.getRValueReferenceType(ArgType);
12141 
12142  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12143  CXXMoveAssignment,
12144  false);
12145 
12146  // An implicitly-declared move assignment operator is an inline public
12147  // member of its class.
12148  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
12149  SourceLocation ClassLoc = ClassDecl->getLocation();
12150  DeclarationNameInfo NameInfo(Name, ClassLoc);
12151  CXXMethodDecl *MoveAssignment =
12152  CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
12153  /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
12154  /*isInline=*/true, Constexpr, SourceLocation());
12155  MoveAssignment->setAccess(AS_public);
12156  MoveAssignment->setDefaulted();
12157  MoveAssignment->setImplicit();
12158 
12159  if (getLangOpts().CUDA) {
12160  inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
12161  MoveAssignment,
12162  /* ConstRHS */ false,
12163  /* Diagnose */ false);
12164  }
12165 
12166  // Build an exception specification pointing back at this member.
12168  getImplicitMethodEPI(*this, MoveAssignment);
12169  MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
12170 
12171  // Add the parameter to the operator.
12172  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
12173  ClassLoc, ClassLoc,
12174  /*Id=*/nullptr, ArgType,
12175  /*TInfo=*/nullptr, SC_None,
12176  nullptr);
12177  MoveAssignment->setParams(FromParam);
12178 
12179  MoveAssignment->setTrivial(
12181  ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
12182  : ClassDecl->hasTrivialMoveAssignment());
12183 
12184  // Note that we have added this copy-assignment operator.
12186 
12187  Scope *S = getScopeForContext(ClassDecl);
12188  CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
12189 
12190  if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
12192  SetDeclDeleted(MoveAssignment, ClassLoc);
12193  }
12194 
12195  if (S)
12196  PushOnScopeChains(MoveAssignment, S, false);
12197  ClassDecl->addDecl(MoveAssignment);
12198 
12199  return MoveAssignment;
12200 }
12201 
12202 /// Check if we're implicitly defining a move assignment operator for a class
12203 /// with virtual bases. Such a move assignment might move-assign the virtual
12204 /// base multiple times.
12206  SourceLocation CurrentLocation) {
12207  assert(!Class->isDependentContext() && "should not define dependent move");
12208 
12209  // Only a virtual base could get implicitly move-assigned multiple times.
12210  // Only a non-trivial move assignment can observe this. We only want to
12211  // diagnose if we implicitly define an assignment operator that assigns
12212  // two base classes, both of which move-assign the same virtual base.
12213  if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
12214  Class->getNumBases() < 2)
12215  return;
12216 
12218  typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
12219  VBaseMap VBases;
12220 
12221  for (auto &BI : Class->bases()) {
12222  Worklist.push_back(&BI);
12223  while (!Worklist.empty()) {
12224  CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
12225  CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
12226 
12227  // If the base has no non-trivial move assignment operators,
12228  // we don't care about moves from it.
12229  if (!Base->hasNonTrivialMoveAssignment())
12230  continue;
12231 
12232  // If there's nothing virtual here, skip it.
12233  if (!BaseSpec->isVirtual() && !Base->getNumVBases())
12234  continue;
12235 
12236  // If we're not actually going to call a move assignment for this base,
12237  // or the selected move assignment is trivial, skip it.
12240  /*ConstArg*/false, /*VolatileArg*/false,
12241  /*RValueThis*/true, /*ConstThis*/false,
12242  /*VolatileThis*/false);
12243  if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
12245  continue;
12246 
12247  if (BaseSpec->isVirtual()) {
12248  // We're going to move-assign this virtual base, and its move
12249  // assignment operator is not trivial. If this can happen for
12250  // multiple distinct direct bases of Class, diagnose it. (If it
12251  // only happens in one base, we'll diagnose it when synthesizing
12252  // that base class's move assignment operator.)
12253  CXXBaseSpecifier *&Existing =
12254  VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
12255  .first->second;
12256  if (Existing && Existing != &BI) {
12257  S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
12258  << Class << Base;
12259  S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
12260  << (Base->getCanonicalDecl() ==
12261  Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12262  << Base << Existing->getType() << Existing->getSourceRange();
12263  S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
12264  << (Base->getCanonicalDecl() ==
12265  BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12266  << Base << BI.getType() << BaseSpec->getSourceRange();
12267 
12268  // Only diagnose each vbase once.
12269  Existing = nullptr;
12270  }
12271  } else {
12272  // Only walk over bases that have defaulted move assignment operators.
12273  // We assume that any user-provided move assignment operator handles
12274  // the multiple-moves-of-vbase case itself somehow.
12275  if (!SMOR.getMethod()->isDefaulted())
12276  continue;
12277 
12278  // We're going to move the base classes of Base. Add them to the list.
12279  for (auto &BI : Base->bases())
12280  Worklist.push_back(&BI);
12281  }
12282  }
12283  }
12284 }
12285 
12287  CXXMethodDecl *MoveAssignOperator) {
12288  assert((MoveAssignOperator->isDefaulted() &&
12289  MoveAssignOperator->isOverloadedOperator() &&
12290  MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
12291  !MoveAssignOperator->doesThisDeclarationHaveABody() &&
12292  !MoveAssignOperator->isDeleted()) &&
12293  "DefineImplicitMoveAssignment called for wrong function");
12294  if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
12295  return;
12296 
12297  CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
12298  if (ClassDecl->isInvalidDecl()) {
12299  MoveAssignOperator->setInvalidDecl();
12300  return;
12301  }
12302 
12303  // C++0x [class.copy]p28:
12304  // The implicitly-defined or move assignment operator for a non-union class
12305  // X performs memberwise move assignment of its subobjects. The direct base
12306  // classes of X are assigned first, in the order of their declaration in the
12307  // base-specifier-list, and then the immediate non-static data members of X
12308  // are assigned, in the order in which they were declared in the class
12309  // definition.
12310 
12311  // Issue a warning if our implicit move assignment operator will move
12312  // from a virtual base more than once.
12313  checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
12314 
12315  SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
12316 
12317  // The exception specification is needed because we are defining the
12318  // function.
12319  ResolveExceptionSpec(CurrentLocation,
12320  MoveAssignOperator->getType()->castAs<FunctionProtoType>());
12321 
12322  // Add a context note for diagnostics produced after this point.
12323  Scope.addContextNote(CurrentLocation);
12324 
12325  // The statements that form the synthesized function body.
12326  SmallVector<Stmt*, 8> Statements;
12327 
12328  // The parameter for the "other" object, which we are move from.
12329  ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
12330  QualType OtherRefType = Other->getType()->
12331  getAs<RValueReferenceType>()->getPointeeType();
12332 
12333  // Our location for everything implicitly-generated.
12334  SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
12335  ? MoveAssignOperator->getEndLoc()
12336  : MoveAssignOperator->getLocation();
12337 
12338  // Builds a reference to the "other" object.
12339  RefBuilder OtherRef(Other, OtherRefType);
12340  // Cast to rvalue.
12341  MoveCastBuilder MoveOther(OtherRef);
12342 
12343  // Builds the "this" pointer.
12344  ThisBuilder This;
12345 
12346  // Assign base classes.
12347  bool Invalid = false;
12348  for (auto &Base : ClassDecl->bases()) {
12349  // C++11 [class.copy]p28:
12350  // It is unspecified whether subobjects representing virtual base classes
12351  // are assigned more than once by the implicitly-defined copy assignment
12352  // operator.
12353  // FIXME: Do not assign to a vbase that will be assigned by some other base
12354  // class. For a move-assignment, this can result in the vbase being moved
12355  // multiple times.
12356 
12357  // Form the assignment:
12358  // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
12359  QualType BaseType = Base.getType().getUnqualifiedType();
12360  if (!BaseType->isRecordType()) {
12361  Invalid = true;
12362  continue;
12363  }
12364 
12365  CXXCastPath BasePath;
12366  BasePath.push_back(&Base);
12367 
12368  // Construct the "from" expression, which is an implicit cast to the
12369  // appropriately-qualified base type.
12370  CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
12371 
12372  // Dereference "this".
12373  DerefBuilder DerefThis(This);
12374 
12375  // Implicitly cast "this" to the appropriately-qualified base type.
12376  CastBuilder To(DerefThis,
12377  Context.getQualifiedType(
12378  BaseType, MoveAssignOperator->getTypeQualifiers()),
12379  VK_LValue, BasePath);
12380 
12381  // Build the move.
12382  StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
12383  To, From,
12384  /*CopyingBaseSubobject=*/true,
12385  /*Copying=*/false);
12386  if (Move.isInvalid()) {
12387  MoveAssignOperator->setInvalidDecl();
12388  return;
12389  }
12390 
12391  // Success! Record the move.
12392  Statements.push_back(Move.getAs<Expr>());
12393  }
12394 
12395  // Assign non-static members.
12396  for (auto *Field : ClassDecl->fields()) {
12397  // FIXME: We should form some kind of AST representation for the implied
12398  // memcpy in a union copy operation.
12399  if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
12400  continue;
12401 
12402  if (Field->isInvalidDecl()) {
12403  Invalid = true;
12404  continue;
12405  }
12406 
12407  // Check for members of reference type; we can't move those.
12408  if (Field->getType()->isReferenceType()) {
12409  Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12410  << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
12411  Diag(Field->getLocation(), diag::note_declared_at);
12412  Invalid = true;
12413  continue;
12414  }
12415 
12416  // Check for members of const-qualified, non-class type.
12417  QualType BaseType = Context.getBaseElementType(Field->getType());
12418  if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
12419  Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12420  << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
12421  Diag(Field->getLocation(), diag::note_declared_at);
12422  Invalid = true;
12423  continue;
12424  }
12425 
12426  // Suppress assigning zero-width bitfields.
12427  if (Field->isZeroLengthBitField(Context))
12428  continue;
12429 
12430  QualType FieldType = Field->getType().getNonReferenceType();
12431  if (FieldType->isIncompleteArrayType()) {
12432  assert(ClassDecl->hasFlexibleArrayMember() &&
12433  "Incomplete array type is not valid");
12434  continue;
12435  }
12436 
12437  // Build references to the field in the object we're copying from and to.
12438  LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
12439  LookupMemberName);
12440  MemberLookup.addDecl(Field);
12441  MemberLookup.resolveKind();
12442  MemberBuilder From(MoveOther, OtherRefType,
12443  /*IsArrow=*/false, MemberLookup);
12444  MemberBuilder To(This, getCurrentThisType(),
12445  /*IsArrow=*/true, MemberLookup);
12446 
12447  assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
12448  "Member reference with rvalue base must be rvalue except for reference "
12449  "members, which aren't allowed for move assignment.");
12450 
12451  // Build the move of this field.
12452  StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
12453  To, From,
12454  /*CopyingBaseSubobject=*/false,
12455  /*Copying=*/false);
12456  if (Move.isInvalid()) {
12457  MoveAssignOperator->setInvalidDecl();
12458  return;
12459  }
12460 
12461  // Success! Record the copy.
12462  Statements.push_back(Move.getAs<Stmt>());
12463  }
12464 
12465  if (!Invalid) {
12466  // Add a "return *this;"
12467  ExprResult ThisObj =
12468  CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
12469 
12470  StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
12471  if (Return.isInvalid())
12472  Invalid = true;
12473  else
12474  Statements.push_back(Return.getAs<Stmt>());
12475  }
12476 
12477  if (Invalid) {
12478  MoveAssignOperator->setInvalidDecl();
12479  return;
12480  }
12481 
12482  StmtResult Body;
12483  {
12484  CompoundScopeRAII CompoundScope(*this);
12485  Body = ActOnCompoundStmt(Loc, Loc, Statements,
12486  /*isStmtExpr=*/false);
12487  assert(!Body.isInvalid() && "Compound statement creation cannot fail");
12488  }
12489  MoveAssignOperator->setBody(Body.getAs<Stmt>());
12490  MoveAssignOperator->markUsed(Context);
12491 
12492  if (ASTMutationListener *L = getASTMutationListener()) {
12493  L->CompletedImplicitDefinition(MoveAssignOperator);
12494  }
12495 }
12496 
12498  CXXRecordDecl *ClassDecl) {
12499  // C++ [class.copy]p4:
12500  // If the class definition does not explicitly declare a copy
12501  // constructor, one is declared implicitly.
12502  assert(ClassDecl->needsImplicitCopyConstructor());
12503 
12504  DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
12505  if (DSM.isAlreadyBeingDeclared())
12506  return nullptr;
12507 
12508  QualType ClassType = Context.getTypeDeclType(ClassDecl);
12509  QualType ArgType = ClassType;
12510  bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
12511  if (Const)
12512  ArgType = ArgType.withConst();
12513 
12514  if (Context.getLangOpts().OpenCLCPlusPlus)
12515  ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
12516 
12517  ArgType = Context.getLValueReferenceType(ArgType);
12518 
12519  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12520  CXXCopyConstructor,
12521  Const);
12522 
12523  DeclarationName Name
12525  Context.getCanonicalType(ClassType));
12526  SourceLocation ClassLoc = ClassDecl->getLocation();
12527  DeclarationNameInfo NameInfo(Name, ClassLoc);
12528 
12529  // An implicitly-declared copy constructor is an inline public
12530  // member of its class.
12532  Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12533  /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12534  Constexpr);
12535  CopyConstructor->setAccess(AS_public);
12536  CopyConstructor->setDefaulted();
12537 
12538  if (getLangOpts().CUDA) {
12539  inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
12540  CopyConstructor,
12541  /* ConstRHS */ Const,
12542  /* Diagnose */ false);
12543  }
12544 
12545  setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
12546 
12547  // Add the parameter to the constructor.
12548  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
12549  ClassLoc, ClassLoc,
12550  /*IdentifierInfo=*/nullptr,
12551  ArgType, /*TInfo=*/nullptr,
12552  SC_None, nullptr);
12553  CopyConstructor->setParams(FromParam);
12554 
12555  CopyConstructor->setTrivial(
12557  ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
12558  : ClassDecl->hasTrivialCopyConstructor());
12559 
12560  CopyConstructor->setTrivialForCall(
12561  ClassDecl->hasAttr<TrivialABIAttr>() ||
12563  ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
12564  TAH_ConsiderTrivialABI)
12565  : ClassDecl->hasTrivialCopyConstructorForCall()));
12566 
12567  // Note that we have declared this constructor.
12569 
12570  Scope *S = getScopeForContext(ClassDecl);
12571  CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
12572 
12573  if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
12575  SetDeclDeleted(CopyConstructor, ClassLoc);
12576  }
12577 
12578  if (S)
12579  PushOnScopeChains(CopyConstructor, S, false);
12580  ClassDecl->addDecl(CopyConstructor);
12581 
12582  return CopyConstructor;
12583 }
12584 
12586  CXXConstructorDecl *CopyConstructor) {
12587  assert((CopyConstructor->isDefaulted() &&
12588  CopyConstructor->isCopyConstructor() &&
12589  !CopyConstructor->doesThisDeclarationHaveABody() &&
12590  !CopyConstructor->isDeleted()) &&
12591  "DefineImplicitCopyConstructor - call it for implicit copy ctor");
12592  if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
12593  return;
12594 
12595  CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
12596  assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
12597 
12598  SynthesizedFunctionScope Scope(*this, CopyConstructor);
12599 
12600  // The exception specification is needed because we are defining the
12601  // function.
12602  ResolveExceptionSpec(CurrentLocation,
12603  CopyConstructor->getType()->castAs<FunctionProtoType>());
12604  MarkVTableUsed(CurrentLocation, ClassDecl);
12605 
12606  // Add a context note for diagnostics produced after this point.
12607  Scope.addContextNote(CurrentLocation);
12608 
12609  // C++11 [class.copy]p7:
12610  // The [definition of an implicitly declared copy constructor] is
12611  // deprecated if the class has a user-declared copy assignment operator
12612  // or a user-declared destructor.
12613  if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
12614  diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
12615 
12616  if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
12617  CopyConstructor->setInvalidDecl();
12618  } else {
12619  SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
12620  ? CopyConstructor->getEndLoc()
12621  : CopyConstructor->getLocation();
12622  Sema::CompoundScopeRAII CompoundScope(*this);
12623  CopyConstructor->setBody(
12624  ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
12625  CopyConstructor->markUsed(Context);
12626  }
12627 
12628  if (ASTMutationListener *L = getASTMutationListener()) {
12629  L->CompletedImplicitDefinition(CopyConstructor);
12630  }
12631 }
12632 
12634  CXXRecordDecl *ClassDecl) {
12635  assert(ClassDecl->needsImplicitMoveConstructor());
12636 
12637  DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
12638  if (DSM.isAlreadyBeingDeclared())
12639  return nullptr;
12640 
12641  QualType ClassType = Context.getTypeDeclType(ClassDecl);
12642 
12643  QualType ArgType = ClassType;
12644  if (Context.getLangOpts().OpenCLCPlusPlus)
12645  ArgType = Context.getAddrSpaceQualType(ClassType, LangAS::opencl_generic);
12646  ArgType = Context.getRValueReferenceType(ArgType);
12647 
12648  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12649  CXXMoveConstructor,
12650  false);
12651 
12652  DeclarationName Name
12654  Context.getCanonicalType(ClassType));
12655  SourceLocation ClassLoc = ClassDecl->getLocation();
12656  DeclarationNameInfo NameInfo(Name, ClassLoc);
12657 
12658  // C++11 [class.copy]p11:
12659  // An implicitly-declared copy/move constructor is an inline public
12660  // member of its class.
12662  Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12663  /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12664  Constexpr);
12665  MoveConstructor->setAccess(AS_public);
12666  MoveConstructor->setDefaulted();
12667 
12668  if (getLangOpts().CUDA) {
12669  inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
12670  MoveConstructor,
12671  /* ConstRHS */ false,
12672  /* Diagnose */ false);
12673  }
12674 
12675  setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
12676 
12677  // Add the parameter to the constructor.
12678  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
12679  ClassLoc, ClassLoc,
12680  /*IdentifierInfo=*/nullptr,
12681  ArgType, /*TInfo=*/nullptr,
12682  SC_None, nullptr);
12683  MoveConstructor->setParams(FromParam);
12684 
12685  MoveConstructor->setTrivial(
12687  ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
12688  : ClassDecl->hasTrivialMoveConstructor());
12689 
12690  MoveConstructor->setTrivialForCall(
12691  ClassDecl->hasAttr<TrivialABIAttr>() ||
12693  ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
12694  TAH_ConsiderTrivialABI)
12695  : ClassDecl->hasTrivialMoveConstructorForCall()));
12696 
12697  // Note that we have declared this constructor.
12699 
12700  Scope *S = getScopeForContext(ClassDecl);
12701  CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
12702 
12703  if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
12705  SetDeclDeleted(MoveConstructor, ClassLoc);
12706  }
12707 
12708  if (S)
12709  PushOnScopeChains(MoveConstructor, S, false);
12710  ClassDecl->addDecl(MoveConstructor);
12711 
12712  return MoveConstructor;
12713 }
12714 
12716  CXXConstructorDecl *MoveConstructor) {
12717  assert((MoveConstructor->isDefaulted() &&
12718  MoveConstructor->isMoveConstructor() &&
12719  !MoveConstructor->doesThisDeclarationHaveABody() &&
12720  !MoveConstructor->isDeleted()) &&
12721  "DefineImplicitMoveConstructor - call it for implicit move ctor");
12722  if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
12723  return;
12724 
12725  CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
12726  assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
12727 
12728  SynthesizedFunctionScope Scope(*this, MoveConstructor);
12729 
12730  // The exception specification is needed because we are defining the
12731  // function.
12732  ResolveExceptionSpec(CurrentLocation,
12733  MoveConstructor->getType()->castAs<FunctionProtoType>());
12734  MarkVTableUsed(CurrentLocation, ClassDecl);
12735 
12736  // Add a context note for diagnostics produced after this point.
12737  Scope.addContextNote(CurrentLocation);
12738 
12739  if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
12740  MoveConstructor->setInvalidDecl();
12741  } else {
12742  SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
12743  ? MoveConstructor->getEndLoc()
12744  : MoveConstructor->getLocation();
12745  Sema::CompoundScopeRAII CompoundScope(*this);
12746  MoveConstructor->setBody(ActOnCompoundStmt(
12747  Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
12748  MoveConstructor->markUsed(Context);
12749  }
12750 
12751  if (ASTMutationListener *L = getASTMutationListener()) {
12752  L->CompletedImplicitDefinition(MoveConstructor);
12753  }
12754 }
12755 
12757  return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
12758 }
12759 
12761  SourceLocation CurrentLocation,
12762  CXXConversionDecl *Conv) {
12763  SynthesizedFunctionScope Scope(*this, Conv);
12764  assert(!Conv->getReturnType()->isUndeducedType());
12765 
12766  CXXRecordDecl *Lambda = Conv->getParent();
12767  FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
12768  FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker();
12769 
12770  if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
12771  CallOp = InstantiateFunctionDeclaration(
12772  CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
12773  if (!CallOp)
12774  return;
12775 
12776  Invoker = InstantiateFunctionDeclaration(
12777  Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
12778  if (!Invoker)
12779  return;
12780  }
12781 
12782  if (CallOp->isInvalidDecl())
12783  return;
12784 
12785  // Mark the call operator referenced (and add to pending instantiations
12786  // if necessary).
12787  // For both the conversion and static-invoker template specializations
12788  // we construct their body's in this function, so no need to add them
12789  // to the PendingInstantiations.
12790  MarkFunctionReferenced(CurrentLocation, CallOp);
12791 
12792  // Fill in the __invoke function with a dummy implementation. IR generation
12793  // will fill in the actual details. Update its type in case it contained
12794  // an 'auto'.
12795  Invoker->markUsed(Context);
12796  Invoker->setReferenced();
12797  Invoker->setType(Conv->getReturnType()->getPointeeType());
12798  Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
12799 
12800  // Construct the body of the conversion function { return __invoke; }.
12801  Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
12802  VK_LValue, Conv->getLocation()).get();
12803  assert(FunctionRef && "Can't refer to __invoke function?");
12804  Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
12805  Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
12806  Conv->getLocation()));
12807  Conv->markUsed(Context);
12808  Conv->setReferenced();
12809 
12810  if (ASTMutationListener *L = getASTMutationListener()) {
12811  L->CompletedImplicitDefinition(Conv);
12812  L->CompletedImplicitDefinition(Invoker);
12813  }
12814 }
12815 
12816 
12817 
12819  SourceLocation CurrentLocation,
12820  CXXConversionDecl *Conv)
12821 {
12822  assert(!Conv->getParent()->isGenericLambda());
12823 
12824  SynthesizedFunctionScope Scope(*this, Conv);
12825 
12826  // Copy-initialize the lambda object as needed to capture it.
12827  Expr *This = ActOnCXXThis(CurrentLocation).get();
12828  Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
12829 
12830  ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
12831  Conv->getLocation(),
12832  Conv, DerefThis);
12833 
12834  // If we're not under ARC, make sure we still get the _Block_copy/autorelease
12835  // behavior. Note that only the general conversion function does this
12836  // (since it's unusable otherwise); in the case where we inline the
12837  // block literal, it has block literal lifetime semantics.
12838  if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
12839  BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
12840  CK_CopyAndAutoreleaseBlockObject,
12841  BuildBlock.get(), nullptr, VK_RValue);
12842 
12843  if (BuildBlock.isInvalid()) {
12844  Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12845  Conv->setInvalidDecl();
12846  return;
12847  }
12848 
12849  // Create the return statement that returns the block from the conversion
12850  // function.
12851  StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
12852  if (Return.isInvalid()) {
12853  Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12854  Conv->setInvalidDecl();
12855  return;
12856  }
12857 
12858  // Set the body of the conversion function.
12859  Stmt *ReturnS = Return.get();
12860  Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
12861  Conv->getLocation()));
12862  Conv->markUsed(Context);
12863 
12864  // We're done; notify the mutation listener, if any.
12865  if (ASTMutationListener *L = getASTMutationListener()) {
12866  L->CompletedImplicitDefinition(Conv);
12867  }
12868 }
12869 
12870 /// Determine whether the given list arguments contains exactly one
12871 /// "real" (non-default) argument.
12873  switch (Args.size()) {
12874  case 0:
12875  return false;
12876 
12877  default:
12878  if (!Args[1]->isDefaultArgument())
12879  return false;
12880 
12881  LLVM_FALLTHROUGH;
12882  case 1:
12883  return !Args[0]->isDefaultArgument();
12884  }
12885 
12886  return false;
12887 }
12888 
12889 ExprResult
12891  NamedDecl *FoundDecl,
12892  CXXConstructorDecl *Constructor,
12893  MultiExprArg ExprArgs,
12894  bool HadMultipleCandidates,
12895  bool IsListInitialization,
12896  bool IsStdInitListInitialization,
12897  bool RequiresZeroInit,
12898  unsigned ConstructKind,
12899  SourceRange ParenRange) {
12900  bool Elidable = false;
12901 
12902  // C++0x [class.copy]p34:
12903  // When certain criteria are met, an implementation is allowed to
12904  // omit the copy/move construction of a class object, even if the
12905  // copy/move constructor and/or destructor for the object have
12906  // side effects. [...]
12907  // - when a temporary class object that has not been bound to a
12908  // reference (12.2) would be copied/moved to a class object
12909  // with the same cv-unqualified type, the copy/move operation
12910  // can be omitted by constructing the temporary object
12911  // directly into the target of the omitted copy/move
12912  if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
12913  Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
12914  Expr *SubExpr = ExprArgs[0];
12915  Elidable = SubExpr->isTemporaryObject(
12916  Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
12917  }
12918 
12919  return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
12920  FoundDecl, Constructor,
12921  Elidable, ExprArgs, HadMultipleCandidates,
12922  IsListInitialization,
12923  IsStdInitListInitialization, RequiresZeroInit,
12924  ConstructKind, ParenRange);
12925 }
12926 
12927 ExprResult
12929  NamedDecl *FoundDecl,
12930  CXXConstructorDecl *Constructor,
12931  bool Elidable,
12932  MultiExprArg ExprArgs,
12933  bool HadMultipleCandidates,
12934  bool IsListInitialization,
12935  bool IsStdInitListInitialization,
12936  bool RequiresZeroInit,
12937  unsigned ConstructKind,
12938  SourceRange ParenRange) {
12939  if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
12940  Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
12941  if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
12942  return ExprError();
12943  }
12944 
12945  return BuildCXXConstructExpr(
12946  ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
12947  HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
12948  RequiresZeroInit, ConstructKind, ParenRange);
12949 }
12950 
12951 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
12952 /// including handling of its default argument expressions.
12953 ExprResult
12955  CXXConstructorDecl *Constructor,
12956  bool Elidable,
12957  MultiExprArg ExprArgs,
12958  bool HadMultipleCandidates,
12959  bool IsListInitialization,
12960  bool IsStdInitListInitialization,
12961  bool RequiresZeroInit,
12962  unsigned ConstructKind,
12963  SourceRange ParenRange) {
12964  assert(declaresSameEntity(
12965  Constructor->getParent(),
12966  DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
12967  "given constructor for wrong type");
12968  MarkFunctionReferenced(ConstructLoc, Constructor);
12969  if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
12970  return ExprError();
12971 
12972  return CXXConstructExpr::Create(
12973  Context, DeclInitType, ConstructLoc, Constructor, Elidable,
12974  ExprArgs, HadMultipleCandidates, IsListInitialization,
12975  IsStdInitListInitialization, RequiresZeroInit,
12976  static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
12977  ParenRange);
12978 }
12979 
12981  assert(Field->hasInClassInitializer());
12982 
12983  // If we already have the in-class initializer nothing needs to be done.
12984  if (Field->getInClassInitializer())
12985  return CXXDefaultInitExpr::Create(Context, Loc, Field);
12986 
12987  // If we might have already tried and failed to instantiate, don't try again.
12988  if (Field->isInvalidDecl())
12989  return ExprError();
12990 
12991  // Maybe we haven't instantiated the in-class initializer. Go check the
12992  // pattern FieldDecl to see if it has one.
12993  CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
12994 
12996  CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
12998  ClassPattern->lookup(Field->getDeclName());
12999 
13000  // Lookup can return at most two results: the pattern for the field, or the
13001  // injected class name of the parent record. No other member can have the
13002  // same name as the field.
13003  // In modules mode, lookup can return multiple results (coming from
13004  // different modules).
13005  assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
13006  "more than two lookup results for field name");
13007  FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
13008  if (!Pattern) {
13009  assert(isa<CXXRecordDecl>(Lookup[0]) &&
13010  "cannot have other non-field member with same name");
13011  for (auto L : Lookup)
13012  if (isa<FieldDecl>(L)) {
13013  Pattern = cast<FieldDecl>(L);
13014  break;
13015  }
13016  assert(Pattern && "We must have set the Pattern!");
13017  }
13018 
13019  if (!Pattern->hasInClassInitializer() ||
13020  InstantiateInClassInitializer(Loc, Field, Pattern,
13021  getTemplateInstantiationArgs(Field))) {
13022  // Don't diagnose this again.
13023  Field->setInvalidDecl();
13024  return ExprError();
13025  }
13026  return CXXDefaultInitExpr::Create(Context, Loc, Field);
13027  }
13028 
13029  // DR1351:
13030  // If the brace-or-equal-initializer of a non-static data member
13031  // invokes a defaulted default constructor of its class or of an
13032  // enclosing class in a potentially evaluated subexpression, the
13033  // program is ill-formed.
13034  //
13035  // This resolution is unworkable: the exception specification of the
13036  // default constructor can be needed in an unevaluated context, in
13037  // particular, in the operand of a noexcept-expression, and we can be
13038  // unable to compute an exception specification for an enclosed class.
13039  //
13040  // Any attempt to resolve the exception specification of a defaulted default
13041  // constructor before the initializer is lexically complete will ultimately
13042  // come here at which point we can diagnose it.
13043  RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
13044  Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
13045  << OutermostClass << Field;
13046  Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed);
13047  // Recover by marking the field invalid, unless we're in a SFINAE context.
13048  if (!isSFINAEContext())
13049  Field->setInvalidDecl();
13050  return ExprError();
13051 }
13052 
13054  if (VD->isInvalidDecl()) return;
13055 
13056  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
13057  if (ClassDecl->isInvalidDecl()) return;
13058  if (ClassDecl->hasIrrelevantDestructor()) return;
13059  if (ClassDecl->isDependentContext()) return;
13060 
13061  if (VD->isNoDestroy(getASTContext()))
13062  return;
13063 
13064  CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
13065  MarkFunctionReferenced(VD->getLocation(), Destructor);
13066  CheckDestructorAccess(VD->getLocation(), Destructor,
13067  PDiag(diag::err_access_dtor_var)
13068  << VD->getDeclName()
13069  << VD->getType());
13070  DiagnoseUseOfDecl(Destructor, VD->getLocation());
13071 
13072  if (Destructor->isTrivial()) return;
13073  if (!VD->hasGlobalStorage()) return;
13074 
13075  // Emit warning for non-trivial dtor in global scope (a real global,
13076  // class-static, function-static).
13077  Diag(VD->getLocation(), diag::warn_exit_time_destructor);
13078 
13079  // TODO: this should be re-enabled for static locals by !CXAAtExit
13080  if (!VD->isStaticLocal())
13081  Diag(VD->getLocation(), diag::warn_global_destructor);
13082 }
13083 
13084 /// Given a constructor and the set of arguments provided for the
13085 /// constructor, convert the arguments and add any required default arguments
13086 /// to form a proper call to this constructor.
13087 ///
13088 /// \returns true if an error occurred, false otherwise.
13089 bool
13091  MultiExprArg ArgsPtr,
13092  SourceLocation Loc,
13093  SmallVectorImpl<Expr*> &ConvertedArgs,
13094  bool AllowExplicit,
13095  bool IsListInitialization) {
13096  // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
13097  unsigned NumArgs = ArgsPtr.size();
13098  Expr **Args = ArgsPtr.data();
13099 
13100  const FunctionProtoType *Proto
13101  = Constructor->getType()->getAs<FunctionProtoType>();
13102  assert(Proto && "Constructor without a prototype?");
13103  unsigned NumParams = Proto->getNumParams();
13104 
13105  // If too few arguments are available, we'll fill in the rest with defaults.
13106  if (NumArgs < NumParams)
13107  ConvertedArgs.reserve(NumParams);
13108  else
13109  ConvertedArgs.reserve(NumArgs);
13110 
13111  VariadicCallType CallType =
13112  Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
13113  SmallVector<Expr *, 8> AllArgs;
13114  bool Invalid = GatherArgumentsForCall(Loc, Constructor,
13115  Proto, 0,
13116  llvm::makeArrayRef(Args, NumArgs),
13117  AllArgs,
13118  CallType, AllowExplicit,
13119  IsListInitialization);
13120  ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
13121 
13122  DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
13123 
13124  CheckConstructorCall(Constructor,
13125  llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
13126  Proto, Loc);
13127 
13128  return Invalid;
13129 }
13130 
13131 static inline bool
13133  const FunctionDecl *FnDecl) {
13134  const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
13135  if (isa<NamespaceDecl>(DC)) {
13136  return SemaRef.Diag(FnDecl->getLocation(),
13137  diag::err_operator_new_delete_declared_in_namespace)
13138  << FnDecl->getDeclName();
13139  }
13140 
13141  if (isa<TranslationUnitDecl>(DC) &&
13142  FnDecl->getStorageClass() == SC_Static) {
13143  return SemaRef.Diag(FnDecl->getLocation(),
13144  diag::err_operator_new_delete_declared_static)
13145  << FnDecl->getDeclName();
13146  }
13147 
13148  return false;
13149 }
13150 
13151 static QualType
13152 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) {
13153  QualType QTy = PtrTy->getPointeeType();
13154  QTy = SemaRef.Context.removeAddrSpaceQualType(QTy);
13155  return SemaRef.Context.getPointerType(QTy);
13156 }
13157 
13158 static inline bool
13160  CanQualType ExpectedResultType,
13161  CanQualType ExpectedFirstParamType,
13162  unsigned DependentParamTypeDiag,
13163  unsigned InvalidParamTypeDiag) {
13164  QualType ResultType =
13165  FnDecl->getType()->getAs<FunctionType>()->getReturnType();
13166 
13167  // Check that the result type is not dependent.
13168  if (ResultType->isDependentType())
13169  return SemaRef.Diag(FnDecl->getLocation(),
13170  diag::err_operator_new_delete_dependent_result_type)
13171  << FnDecl->getDeclName() << ExpectedResultType;
13172 
13173  // OpenCL C++: the operator is valid on any address space.
13174  if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
13175  if (auto *PtrTy = ResultType->getAs<PointerType>()) {
13176  ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
13177  }
13178  }
13179 
13180  // Check that the result type is what we expect.
13181  if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
13182  return SemaRef.Diag(FnDecl->getLocation(),
13183  diag::err_operator_new_delete_invalid_result_type)
13184  << FnDecl->getDeclName() << ExpectedResultType;
13185 
13186  // A function template must have at least 2 parameters.
13187  if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
13188  return SemaRef.Diag(FnDecl->getLocation(),
13189  diag::err_operator_new_delete_template_too_few_parameters)
13190  << FnDecl->getDeclName();
13191 
13192  // The function decl must have at least 1 parameter.
13193  if (FnDecl->getNumParams() == 0)
13194  return SemaRef.Diag(FnDecl->getLocation(),
13195  diag::err_operator_new_delete_too_few_parameters)
13196  << FnDecl->getDeclName();
13197 
13198  // Check the first parameter type is not dependent.
13199  QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
13200  if (FirstParamType->isDependentType())
13201  return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
13202  << FnDecl->getDeclName() << ExpectedFirstParamType;
13203 
13204  // Check that the first parameter type is what we expect.
13205  if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
13206  // OpenCL C++: the operator is valid on any address space.
13207  if (auto *PtrTy =
13208  FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) {
13209  FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
13210  }
13211  }
13212  if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
13213  ExpectedFirstParamType)
13214  return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
13215  << FnDecl->getDeclName() << ExpectedFirstParamType;
13216 
13217  return false;
13218 }
13219 
13220 static bool
13222  // C++ [basic.stc.dynamic.allocation]p1:
13223  // A program is ill-formed if an allocation function is declared in a
13224  // namespace scope other than global scope or declared static in global
13225  // scope.
13226  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13227  return true;
13228 
13229  CanQualType SizeTy =
13230  SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
13231 
13232  // C++ [basic.stc.dynamic.allocation]p1:
13233  // The return type shall be void*. The first parameter shall have type
13234  // std::size_t.
13235  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
13236  SizeTy,
13237  diag::err_operator_new_dependent_param_type,
13238  diag::err_operator_new_param_type))
13239  return true;
13240 
13241  // C++ [basic.stc.dynamic.allocation]p1:
13242  // The first parameter shall not have an associated default argument.
13243  if (FnDecl->getParamDecl(0)->hasDefaultArg())
13244  return SemaRef.Diag(FnDecl->getLocation(),
13245  diag::err_operator_new_default_arg)
13246  << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
13247 
13248  return false;
13249 }
13250 
13251 static bool
13253  // C++ [basic.stc.dynamic.deallocation]p1:
13254  // A program is ill-formed if deallocation functions are declared in a
13255  // namespace scope other than global scope or declared static in global
13256  // scope.
13257  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13258  return true;
13259 
13260  auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
13261 
13262  // C++ P0722:
13263  // Within a class C, the first parameter of a destroying operator delete
13264  // shall be of type C *. The first parameter of any other deallocation
13265  // function shall be of type void *.
13266  CanQualType ExpectedFirstParamType =
13267  MD && MD->isDestroyingOperatorDelete()
13268  ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
13269  SemaRef.Context.getRecordType(MD->getParent())))
13270  : SemaRef.Context.VoidPtrTy;
13271 
13272  // C++ [basic.stc.dynamic.deallocation]p2:
13273  // Each deallocation function shall return void
13275  SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
13276  diag::err_operator_delete_dependent_param_type,
13277  diag::err_operator_delete_param_type))
13278  return true;
13279 
13280  // C++ P0722:
13281  // A destroying operator delete shall be a usual deallocation function.
13282  if (MD && !MD->getParent()->isDependentContext() &&
13284  !SemaRef.isUsualDeallocationFunction(MD)) {
13285  SemaRef.Diag(MD->getLocation(),
13286  diag::err_destroying_operator_delete_not_usual);
13287  return true;
13288  }
13289 
13290  return false;
13291 }
13292 
13293 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
13294 /// of this overloaded operator is well-formed. If so, returns false;
13295 /// otherwise, emits appropriate diagnostics and returns true.
13297  assert(FnDecl && FnDecl->isOverloadedOperator() &&
13298  "Expected an overloaded operator declaration");
13299 
13301 
13302  // C++ [over.oper]p5:
13303  // The allocation and deallocation functions, operator new,
13304  // operator new[], operator delete and operator delete[], are
13305  // described completely in 3.7.3. The attributes and restrictions
13306  // found in the rest of this subclause do not apply to them unless
13307  // explicitly stated in 3.7.3.
13308  if (Op == OO_Delete || Op == OO_Array_Delete)
13309  return CheckOperatorDeleteDeclaration(*this, FnDecl);
13310 
13311  if (Op == OO_New || Op == OO_Array_New)
13312  return CheckOperatorNewDeclaration(*this, FnDecl);
13313 
13314  // C++ [over.oper]p6:
13315  // An operator function shall either be a non-static member
13316  // function or be a non-member function and have at least one
13317  // parameter whose type is a class, a reference to a class, an
13318  // enumeration, or a reference to an enumeration.
13319  if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
13320  if (MethodDecl->isStatic())
13321  return Diag(FnDecl->getLocation(),
13322  diag::err_operator_overload_static) << FnDecl->getDeclName();
13323  } else {
13324  bool ClassOrEnumParam = false;
13325  for (auto Param : FnDecl->parameters()) {
13326  QualType ParamType = Param->getType().getNonReferenceType();
13327  if (ParamType->isDependentType() || ParamType->isRecordType() ||
13328  ParamType->isEnumeralType()) {
13329  ClassOrEnumParam = true;
13330  break;
13331  }
13332  }
13333 
13334  if (!ClassOrEnumParam)
13335  return Diag(FnDecl->getLocation(),
13336  diag::err_operator_overload_needs_class_or_enum)
13337  << FnDecl->getDeclName();
13338  }
13339 
13340  // C++ [over.oper]p8:
13341  // An operator function cannot have default arguments (8.3.6),
13342  // except where explicitly stated below.
13343  //
13344  // Only the function-call operator allows default arguments
13345  // (C++ [over.call]p1).
13346  if (Op != OO_Call) {
13347  for (auto Param : FnDecl->parameters()) {
13348  if (Param->hasDefaultArg())
13349  return Diag(Param->getLocation(),
13350  diag::err_operator_overload_default_arg)
13351  << FnDecl->getDeclName() << Param->getDefaultArgRange();
13352  }
13353  }
13354 
13355  static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
13356  { false, false, false }
13357 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
13358  , { Unary, Binary, MemberOnly }
13359 #include "clang/Basic/OperatorKinds.def"
13360  };
13361 
13362  bool CanBeUnaryOperator = OperatorUses[Op][0];
13363  bool CanBeBinaryOperator = OperatorUses[Op][1];
13364  bool MustBeMemberOperator = OperatorUses[Op][2];
13365 
13366  // C++ [over.oper]p8:
13367  // [...] Operator functions cannot have more or fewer parameters
13368  // than the number required for the corresponding operator, as
13369  // described in the rest of this subclause.
13370  unsigned NumParams = FnDecl->getNumParams()
13371  + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
13372  if (Op != OO_Call &&
13373  ((NumParams == 1 && !CanBeUnaryOperator) ||
13374  (NumParams == 2 && !CanBeBinaryOperator) ||
13375  (NumParams < 1) || (NumParams > 2))) {
13376  // We have the wrong number of parameters.
13377  unsigned ErrorKind;
13378  if (CanBeUnaryOperator && CanBeBinaryOperator) {
13379  ErrorKind = 2; // 2 -> unary or binary.
13380  } else if (CanBeUnaryOperator) {
13381  ErrorKind = 0; // 0 -> unary
13382  } else {
13383  assert(CanBeBinaryOperator &&
13384  "All non-call overloaded operators are unary or binary!");
13385  ErrorKind = 1; // 1 -> binary
13386  }
13387 
13388  return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
13389  << FnDecl->getDeclName() << NumParams << ErrorKind;
13390  }
13391 
13392  // Overloaded operators other than operator() cannot be variadic.
13393  if (Op != OO_Call &&
13394  FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
13395  return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
13396  << FnDecl->getDeclName();
13397  }
13398 
13399  // Some operators must be non-static member functions.
13400  if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
13401  return Diag(FnDecl->getLocation(),
13402  diag::err_operator_overload_must_be_member)
13403  << FnDecl->getDeclName();
13404  }
13405 
13406  // C++ [over.inc]p1:
13407  // The user-defined function called operator++ implements the
13408  // prefix and postfix ++ operator. If this function is a member
13409  // function with no parameters, or a non-member function with one
13410  // parameter of class or enumeration type, it defines the prefix
13411  // increment operator ++ for objects of that type. If the function
13412  // is a member function with one parameter (which shall be of type
13413  // int) or a non-member function with two parameters (the second
13414  // of which shall be of type int), it defines the postfix
13415  // increment operator ++ for objects of that type.
13416  if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
13417  ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
13418  QualType ParamType = LastParam->getType();
13419 
13420  if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
13421  !ParamType->isDependentType())
13422  return Diag(LastParam->getLocation(),
13423  diag::err_operator_overload_post_incdec_must_be_int)
13424  << LastParam->getType() << (Op == OO_MinusMinus);
13425  }
13426 
13427  return false;
13428 }
13429 
13430 static bool
13432  FunctionTemplateDecl *TpDecl) {
13433  TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
13434 
13435  // Must have one or two template parameters.
13436  if (TemplateParams->size() == 1) {
13437  NonTypeTemplateParmDecl *PmDecl =
13438  dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
13439 
13440  // The template parameter must be a char parameter pack.
13441  if (PmDecl && PmDecl->isTemplateParameterPack() &&
13442  SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
13443  return false;
13444 
13445  } else if (TemplateParams->size() == 2) {
13446  TemplateTypeParmDecl *PmType =
13447  dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
13448  NonTypeTemplateParmDecl *PmArgs =
13449  dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
13450 
13451  // The second template parameter must be a parameter pack with the
13452  // first template parameter as its type.
13453  if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
13454  PmArgs->isTemplateParameterPack()) {
13455  const TemplateTypeParmType *TArgs =
13456  PmArgs->getType()->getAs<TemplateTypeParmType>();
13457  if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
13458  TArgs->getIndex() == PmType->getIndex()) {
13459  if (!SemaRef.inTemplateInstantiation())
13460  SemaRef.Diag(TpDecl->getLocation(),
13461  diag::ext_string_literal_operator_template);
13462  return false;
13463  }
13464  }
13465  }
13466 
13467  SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
13468  diag::err_literal_operator_template)
13469  << TpDecl->getTemplateParameters()->getSourceRange();
13470  return true;
13471 }
13472 
13473 /// CheckLiteralOperatorDeclaration - Check whether the declaration
13474 /// of this literal operator function is well-formed. If so, returns
13475 /// false; otherwise, emits appropriate diagnostics and returns true.
13477  if (isa<CXXMethodDecl>(FnDecl)) {
13478  Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
13479  << FnDecl->getDeclName();
13480  return true;
13481  }
13482 
13483  if (FnDecl->isExternC()) {
13484  Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
13485  if (const LinkageSpecDecl *LSD =
13486  FnDecl->getDeclContext()->getExternCContext())
13487  Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
13488  return true;
13489  }
13490 
13491  // This might be the definition of a literal operator template.
13493 
13494  // This might be a specialization of a literal operator template.
13495  if (!TpDecl)
13496  TpDecl = FnDecl->getPrimaryTemplate();
13497 
13498  // template <char...> type operator "" name() and
13499  // template <class T, T...> type operator "" name() are the only valid
13500  // template signatures, and the only valid signatures with no parameters.
13501  if (TpDecl) {
13502  if (FnDecl->param_size() != 0) {
13503  Diag(FnDecl->getLocation(),
13504  diag::err_literal_operator_template_with_params);
13505  return true;
13506  }
13507 
13508  if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
13509  return true;
13510 
13511  } else if (FnDecl->param_size() == 1) {
13512  const ParmVarDecl *Param = FnDecl->getParamDecl(0);
13513 
13514  QualType ParamType = Param->getType().getUnqualifiedType();
13515 
13516  // Only unsigned long long int, long double, any character type, and const
13517  // char * are allowed as the only parameters.
13518  if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
13519  ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
13520  Context.hasSameType(ParamType, Context.CharTy) ||
13521  Context.hasSameType(ParamType, Context.WideCharTy) ||
13522  Context.hasSameType(ParamType, Context.Char8Ty) ||
13523  Context.hasSameType(ParamType, Context.Char16Ty) ||
13524  Context.hasSameType(ParamType, Context.Char32Ty)) {
13525  } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
13526  QualType InnerType = Ptr->getPointeeType();
13527 
13528  // Pointer parameter must be a const char *.
13529  if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
13530  Context.CharTy) &&
13531  InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
13532  Diag(Param->getSourceRange().getBegin(),
13533  diag::err_literal_operator_param)
13534  << ParamType << "'const char *'" << Param->getSourceRange();
13535  return true;
13536  }
13537 
13538  } else if (ParamType->isRealFloatingType()) {
13539  Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13540  << ParamType << Context.LongDoubleTy << Param->getSourceRange();
13541  return true;
13542 
13543  } else if (ParamType->isIntegerType()) {
13544  Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13545  << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
13546  return true;
13547 
13548  } else {
13549  Diag(Param->getSourceRange().getBegin(),
13550  diag::err_literal_operator_invalid_param)
13551  << ParamType << Param->getSourceRange();
13552  return true;
13553  }
13554 
13555  } else if (FnDecl->param_size() == 2) {
13556  FunctionDecl::param_iterator Param = FnDecl->param_begin();
13557 
13558  // First, verify that the first parameter is correct.
13559 
13560  QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
13561 
13562  // Two parameter function must have a pointer to const as a
13563  // first parameter; let's strip those qualifiers.
13564  const PointerType *PT = FirstParamType->getAs<PointerType>();
13565 
13566  if (!PT) {
13567  Diag((*Param)->getSourceRange().getBegin(),
13568  diag::err_literal_operator_param)
13569  << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13570  return true;
13571  }
13572 
13573  QualType PointeeType = PT->getPointeeType();
13574  // First parameter must be const
13575  if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
13576  Diag((*Param)->getSourceRange().getBegin(),
13577  diag::err_literal_operator_param)
13578  << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13579  return true;
13580  }
13581 
13582  QualType InnerType = PointeeType.getUnqualifiedType();
13583  // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
13584  // const char32_t* are allowed as the first parameter to a two-parameter
13585  // function
13586  if (!(Context.hasSameType(InnerType, Context.CharTy) ||
13587  Context.hasSameType(InnerType, Context.WideCharTy) ||
13588  Context.hasSameType(InnerType, Context.Char8Ty) ||
13589  Context.hasSameType(InnerType, Context.Char16Ty) ||
13590  Context.hasSameType(InnerType, Context.Char32Ty))) {
13591  Diag((*Param)->getSourceRange().getBegin(),
13592  diag::err_literal_operator_param)
13593  << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13594  return true;
13595  }
13596 
13597  // Move on to the second and final parameter.
13598  ++Param;
13599 
13600  // The second parameter must be a std::size_t.
13601  QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
13602  if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
13603  Diag((*Param)->getSourceRange().getBegin(),
13604  diag::err_literal_operator_param)
13605  << SecondParamType << Context.getSizeType()
13606  << (*Param)->getSourceRange();
13607  return true;
13608  }
13609  } else {
13610  Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
13611  return true;
13612  }
13613 
13614  // Parameters are good.
13615 
13616  // A parameter-declaration-clause containing a default argument is not
13617  // equivalent to any of the permitted forms.
13618  for (auto Param : FnDecl->parameters()) {
13619  if (Param->hasDefaultArg()) {
13620  Diag(Param->getDefaultArgRange().getBegin(),
13621  diag::err_literal_operator_default_argument)
13622  << Param->getDefaultArgRange();
13623  break;
13624  }
13625  }
13626 
13627  StringRef LiteralName
13628  = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
13629  if (LiteralName[0] != '_' &&
13630  !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
13631  // C++11 [usrlit.suffix]p1:
13632  // Literal suffix identifiers that do not start with an underscore
13633  // are reserved for future standardization.
13634  Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
13635  << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
13636  }
13637 
13638  return false;
13639 }
13640 
13641 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
13642 /// linkage specification, including the language and (if present)
13643 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
13644 /// language string literal. LBraceLoc, if valid, provides the location of
13645 /// the '{' brace. Otherwise, this linkage specification does not
13646 /// have any braces.
13648  Expr *LangStr,
13649  SourceLocation LBraceLoc) {
13650  StringLiteral *Lit = cast<StringLiteral>(LangStr);
13651  if (!Lit->isAscii()) {
13652  Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
13653  << LangStr->getSourceRange();
13654  return nullptr;
13655  }
13656 
13657  StringRef Lang = Lit->getString();
13659  if (Lang == "C")
13660  Language = LinkageSpecDecl::lang_c;
13661  else if (Lang == "C++")
13662  Language = LinkageSpecDecl::lang_cxx;
13663  else {
13664  Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
13665  << LangStr->getSourceRange();
13666  return nullptr;
13667  }
13668 
13669  // FIXME: Add all the various semantics of linkage specifications
13670 
13671  LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
13672  LangStr->getExprLoc(), Language,
13673  LBraceLoc.isValid());
13674  CurContext->addDecl(D);
13675  PushDeclContext(S, D);
13676  return D;
13677 }
13678 
13679 /// ActOnFinishLinkageSpecification - Complete the definition of
13680 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
13681 /// valid, it's the position of the closing '}' brace in a linkage
13682 /// specification that uses braces.
13684  Decl *LinkageSpec,
13685  SourceLocation RBraceLoc) {
13686  if (RBraceLoc.isValid()) {
13687  LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
13688  LSDecl->setRBraceLoc(RBraceLoc);
13689  }
13690  PopDeclContext();
13691  return LinkageSpec;
13692 }
13693 
13695  const ParsedAttributesView &AttrList,
13696  SourceLocation SemiLoc) {
13697  Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
13698  // Attribute declarations appertain to empty declaration so we handle
13699  // them here.
13700  ProcessDeclAttributeList(S, ED, AttrList);
13701 
13702  CurContext->addDecl(ED);
13703  return ED;
13704 }
13705 
13706 /// Perform semantic analysis for the variable declaration that
13707 /// occurs within a C++ catch clause, returning the newly-created
13708 /// variable.
13710  TypeSourceInfo *TInfo,
13711  SourceLocation StartLoc,
13712  SourceLocation Loc,
13713  IdentifierInfo *Name) {
13714  bool Invalid = false;
13715  QualType ExDeclType = TInfo->getType();
13716 
13717  // Arrays and functions decay.
13718  if (ExDeclType->isArrayType())
13719  ExDeclType = Context.getArrayDecayedType(ExDeclType);
13720  else if (ExDeclType->isFunctionType())
13721  ExDeclType = Context.getPointerType(ExDeclType);
13722 
13723  // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
13724  // The exception-declaration shall not denote a pointer or reference to an
13725  // incomplete type, other than [cv] void*.
13726  // N2844 forbids rvalue references.
13727  if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
13728  Diag(Loc, diag::err_catch_rvalue_ref);
13729  Invalid = true;
13730  }
13731 
13732  if (ExDeclType->isVariablyModifiedType()) {
13733  Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
13734  Invalid = true;
13735  }
13736 
13737  QualType BaseType = ExDeclType;
13738  int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
13739  unsigned DK = diag::err_catch_incomplete;
13740  if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
13741  BaseType = Ptr->getPointeeType();
13742  Mode = 1;
13743  DK = diag::err_catch_incomplete_ptr;
13744  } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
13745  // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
13746  BaseType = Ref->getPointeeType();
13747  Mode = 2;
13748  DK = diag::err_catch_incomplete_ref;
13749  }
13750  if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
13751  !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
13752  Invalid = true;
13753 
13754  if (!Invalid && !ExDeclType->isDependentType() &&
13755  RequireNonAbstractType(Loc, ExDeclType,
13756  diag::err_abstract_type_in_decl,
13757  AbstractVariableType))
13758  Invalid = true;
13759 
13760  // Only the non-fragile NeXT runtime currently supports C++ catches
13761  // of ObjC types, and no runtime supports catching ObjC types by value.
13762  if (!Invalid && getLangOpts().ObjC) {
13763  QualType T = ExDeclType;
13764  if (const ReferenceType *RT = T->getAs<ReferenceType>())
13765  T = RT->getPointeeType();
13766 
13767  if (T->isObjCObjectType()) {
13768  Diag(Loc, diag::err_objc_object_catch);
13769  Invalid = true;
13770  } else if (T->isObjCObjectPointerType()) {
13771  // FIXME: should this be a test for macosx-fragile specifically?
13772  if (getLangOpts().ObjCRuntime.isFragile())
13773  Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
13774  }
13775  }
13776 
13777  VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
13778  ExDeclType, TInfo, SC_None);
13779  ExDecl->setExceptionVariable(true);
13780 
13781  // In ARC, infer 'retaining' for variables of retainable type.
13782  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
13783  Invalid = true;
13784 
13785  if (!Invalid && !ExDeclType->isDependentType()) {
13786  if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
13787  // Insulate this from anything else we might currently be parsing.
13789  *this, ExpressionEvaluationContext::PotentiallyEvaluated);
13790 
13791  // C++ [except.handle]p16:
13792  // The object declared in an exception-declaration or, if the
13793  // exception-declaration does not specify a name, a temporary (12.2) is
13794  // copy-initialized (8.5) from the exception object. [...]
13795  // The object is destroyed when the handler exits, after the destruction
13796  // of any automatic objects initialized within the handler.
13797  //
13798  // We just pretend to initialize the object with itself, then make sure
13799  // it can be destroyed later.
13800  QualType initType = Context.getExceptionObjectType(ExDeclType);
13801 
13802  InitializedEntity entity =
13804  InitializationKind initKind =
13806 
13807  Expr *opaqueValue =
13808  new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
13809  InitializationSequence sequence(*this, entity, initKind, opaqueValue);
13810  ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
13811  if (result.isInvalid())
13812  Invalid = true;
13813  else {
13814  // If the constructor used was non-trivial, set this as the
13815  // "initializer".
13816  CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
13817  if (!construct->getConstructor()->isTrivial()) {
13818  Expr *init = MaybeCreateExprWithCleanups(construct);
13819  ExDecl->setInit(init);
13820  }
13821 
13822  // And make sure it's destructable.
13823  FinalizeVarWithDestructor(ExDecl, recordType);
13824  }
13825  }
13826  }
13827 
13828  if (Invalid)
13829  ExDecl->setInvalidDecl();
13830 
13831  return ExDecl;
13832 }
13833 
13834 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
13835 /// handler.
13837  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13838  bool Invalid = D.isInvalidType();
13839 
13840  // Check for unexpanded parameter packs.
13841  if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13842  UPPC_ExceptionType)) {
13843  TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13844  D.getIdentifierLoc());
13845  Invalid = true;
13846  }
13847 
13848  IdentifierInfo *II = D.getIdentifier();
13849  if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
13850  LookupOrdinaryName,
13851  ForVisibleRedeclaration)) {
13852  // The scope should be freshly made just for us. There is just no way
13853  // it contains any previous declaration, except for function parameters in
13854  // a function-try-block's catch statement.
13855  assert(!S->isDeclScope(PrevDecl));
13856  if (isDeclInScope(PrevDecl, CurContext, S)) {
13857  Diag(D.getIdentifierLoc(), diag::err_redefinition)
13858  << D.getIdentifier();
13859  Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13860  Invalid = true;
13861  } else if (PrevDecl->isTemplateParameter())
13862  // Maybe we will complain about the shadowed template parameter.
13863  DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13864  }
13865 
13866  if (D.getCXXScopeSpec().isSet() && !Invalid) {
13867  Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
13868  << D.getCXXScopeSpec().getRange();
13869  Invalid = true;
13870  }
13871 
13872  VarDecl *ExDecl = BuildExceptionDeclaration(
13873  S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
13874  if (Invalid)
13875  ExDecl->setInvalidDecl();
13876 
13877  // Add the exception declaration into this scope.
13878  if (II)
13879  PushOnScopeChains(ExDecl, S);
13880  else
13881  CurContext->addDecl(ExDecl);
13882 
13883  ProcessDeclAttributes(S, ExDecl, D);
13884  return ExDecl;
13885 }
13886 
13888  Expr *AssertExpr,
13889  Expr *AssertMessageExpr,
13890  SourceLocation RParenLoc) {
13891  StringLiteral *AssertMessage =
13892  AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
13893 
13894  if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
13895  return nullptr;
13896 
13897  return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
13898  AssertMessage, RParenLoc, false);
13899 }
13900 
13902  Expr *AssertExpr,
13903  StringLiteral *AssertMessage,
13904  SourceLocation RParenLoc,
13905  bool Failed) {
13906  assert(AssertExpr != nullptr && "Expected non-null condition");
13907  if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
13908  !Failed) {
13909  // In a static_assert-declaration, the constant-expression shall be a
13910  // constant expression that can be contextually converted to bool.
13911  ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
13912  if (Converted.isInvalid())
13913  Failed = true;
13914  else
13915  Converted = ConstantExpr::Create(Context, Converted.get());
13916 
13917  llvm::APSInt Cond;
13918  if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
13919  diag::err_static_assert_expression_is_not_constant,
13920  /*AllowFold=*/false).isInvalid())
13921  Failed = true;
13922 
13923  if (!Failed && !Cond) {
13924  SmallString<256> MsgBuffer;
13925  llvm::raw_svector_ostream Msg(MsgBuffer);
13926  if (AssertMessage)
13927  AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
13928 
13929  Expr *InnerCond = nullptr;
13930  std::string InnerCondDescription;
13931  std::tie(InnerCond, InnerCondDescription) =
13932  findFailedBooleanCondition(Converted.get());
13933  if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
13934  && !isa<IntegerLiteral>(InnerCond)) {
13935  Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
13936  << InnerCondDescription << !AssertMessage
13937  << Msg.str() << InnerCond->getSourceRange();
13938  } else {
13939  Diag(StaticAssertLoc, diag::err_static_assert_failed)
13940  << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
13941  }
13942  Failed = true;
13943  }
13944  }
13945 
13946  ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
13947  /*DiscardedValue*/false,
13948  /*IsConstexpr*/true);
13949  if (FullAssertExpr.isInvalid())
13950  Failed = true;
13951  else
13952  AssertExpr = FullAssertExpr.get();
13953 
13954  Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
13955  AssertExpr, AssertMessage, RParenLoc,
13956  Failed);
13957 
13958  CurContext->addDecl(Decl);
13959  return Decl;
13960 }
13961 
13962 /// Perform semantic analysis of the given friend type declaration.
13963 ///
13964 /// \returns A friend declaration that.
13966  SourceLocation FriendLoc,
13967  TypeSourceInfo *TSInfo) {
13968  assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
13969 
13970  QualType T = TSInfo->getType();
13971  SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
13972 
13973  // C++03 [class.friend]p2:
13974  // An elaborated-type-specifier shall be used in a friend declaration
13975  // for a class.*
13976  //
13977  // * The class-key of the elaborated-type-specifier is required.
13978  if (!CodeSynthesisContexts.empty()) {
13979  // Do not complain about the form of friend template types during any kind
13980  // of code synthesis. For template instantiation, we will have complained
13981  // when the template was defined.
13982  } else {
13983  if (!T->isElaboratedTypeSpecifier()) {
13984  // If we evaluated the type to a record type, suggest putting
13985  // a tag in front.
13986  if (const RecordType *RT = T->getAs<RecordType>()) {
13987  RecordDecl *RD = RT->getDecl();
13988 
13989  SmallString<16> InsertionText(" ");
13990  InsertionText += RD->getKindName();
13991 
13992  Diag(TypeRange.getBegin(),
13993  getLangOpts().CPlusPlus11 ?
13994  diag::warn_cxx98_compat_unelaborated_friend_type :
13995  diag::ext_unelaborated_friend_type)
13996  << (unsigned) RD->getTagKind()
13997  << T
13998  << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
13999  InsertionText);
14000  } else {
14001  Diag(FriendLoc,
14002  getLangOpts().CPlusPlus11 ?
14003  diag::warn_cxx98_compat_nonclass_type_friend :
14004  diag::ext_nonclass_type_friend)
14005  << T
14006  << TypeRange;
14007  }
14008  } else if (T->getAs<EnumType>()) {
14009  Diag(FriendLoc,
14010  getLangOpts().CPlusPlus11 ?
14011  diag::warn_cxx98_compat_enum_friend :
14012  diag::ext_enum_friend)
14013  << T
14014  << TypeRange;
14015  }
14016 
14017  // C++11 [class.friend]p3:
14018  // A friend declaration that does not declare a function shall have one
14019  // of the following forms:
14020  // friend elaborated-type-specifier ;
14021  // friend simple-type-specifier ;
14022  // friend typename-specifier ;
14023  if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
14024  Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
14025  }
14026 
14027  // If the type specifier in a friend declaration designates a (possibly
14028  // cv-qualified) class type, that class is declared as a friend; otherwise,
14029  // the friend declaration is ignored.
14030  return FriendDecl::Create(Context, CurContext,
14031  TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
14032  FriendLoc);
14033 }
14034 
14035 /// Handle a friend tag declaration where the scope specifier was
14036 /// templated.
14038  unsigned TagSpec, SourceLocation TagLoc,
14039  CXXScopeSpec &SS, IdentifierInfo *Name,
14040  SourceLocation NameLoc,
14041  const ParsedAttributesView &Attr,
14042  MultiTemplateParamsArg TempParamLists) {
14044 
14045  bool IsMemberSpecialization = false;
14046  bool Invalid = false;
14047 
14048  if (TemplateParameterList *TemplateParams =
14049  MatchTemplateParametersToScopeSpecifier(
14050  TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
14051  IsMemberSpecialization, Invalid)) {
14052  if (TemplateParams->size() > 0) {
14053  // This is a declaration of a class template.
14054  if (Invalid)
14055  return nullptr;
14056 
14057  return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
14058  NameLoc, Attr, TemplateParams, AS_public,
14059  /*ModulePrivateLoc=*/SourceLocation(),
14060  FriendLoc, TempParamLists.size() - 1,
14061  TempParamLists.data()).get();
14062  } else {
14063  // The "template<>" header is extraneous.
14064  Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
14065  << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
14066  IsMemberSpecialization = true;
14067  }
14068  }
14069 
14070  if (Invalid) return nullptr;
14071 
14072  bool isAllExplicitSpecializations = true;
14073  for (unsigned I = TempParamLists.size(); I-- > 0; ) {
14074  if (TempParamLists[I]->size()) {
14075  isAllExplicitSpecializations = false;
14076  break;
14077  }
14078  }
14079 
14080  // FIXME: don't ignore attributes.
14081 
14082  // If it's explicit specializations all the way down, just forget
14083  // about the template header and build an appropriate non-templated
14084  // friend. TODO: for source fidelity, remember the headers.
14085  if (isAllExplicitSpecializations) {
14086  if (SS.isEmpty()) {
14087  bool Owned = false;
14088  bool IsDependent = false;
14089  return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
14090  Attr, AS_public,
14091  /*ModulePrivateLoc=*/SourceLocation(),
14092  MultiTemplateParamsArg(), Owned, IsDependent,
14093  /*ScopedEnumKWLoc=*/SourceLocation(),
14094  /*ScopedEnumUsesClassTag=*/false,
14095  /*UnderlyingType=*/TypeResult(),
14096  /*IsTypeSpecifier=*/false,
14097  /*IsTemplateParamOrArg=*/false);
14098  }
14099 
14100  NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
14101  ElaboratedTypeKeyword Keyword
14103  QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
14104  *Name, NameLoc);
14105  if (T.isNull())
14106  return nullptr;
14107 
14108  TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
14109  if (isa<DependentNameType>(T)) {
14112  TL.setElaboratedKeywordLoc(TagLoc);
14113  TL.setQualifierLoc(QualifierLoc);
14114  TL.setNameLoc(NameLoc);
14115  } else {
14117  TL.setElaboratedKeywordLoc(TagLoc);
14118  TL.setQualifierLoc(QualifierLoc);
14119  TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
14120  }
14121 
14122  FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
14123  TSI, FriendLoc, TempParamLists);
14124  Friend->setAccess(AS_public);
14125  CurContext->addDecl(Friend);
14126  return Friend;
14127  }
14128 
14129  assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
14130 
14131 
14132 
14133  // Handle the case of a templated-scope friend class. e.g.
14134  // template <class T> class A<T>::B;
14135  // FIXME: we don't support these right now.
14136  Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
14137  << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
14139  QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
14140  TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
14142  TL.setElaboratedKeywordLoc(TagLoc);
14143  TL.setQualifierLoc(SS.getWithLocInContext(Context));
14144  TL.setNameLoc(NameLoc);
14145 
14146  FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
14147  TSI, FriendLoc, TempParamLists);
14148  Friend->setAccess(AS_public);
14149  Friend->setUnsupportedFriend(true);
14150  CurContext->addDecl(Friend);
14151  return Friend;
14152 }
14153 
14154 /// Handle a friend type declaration. This works in tandem with
14155 /// ActOnTag.
14156 ///
14157 /// Notes on friend class templates:
14158 ///
14159 /// We generally treat friend class declarations as if they were
14160 /// declaring a class. So, for example, the elaborated type specifier
14161 /// in a friend declaration is required to obey the restrictions of a
14162 /// class-head (i.e. no typedefs in the scope chain), template
14163 /// parameters are required to match up with simple template-ids, &c.
14164 /// However, unlike when declaring a template specialization, it's
14165 /// okay to refer to a template specialization without an empty
14166 /// template parameter declaration, e.g.
14167 /// friend class A<T>::B<unsigned>;
14168 /// We permit this as a special case; if there are any template
14169 /// parameters present at all, require proper matching, i.e.
14170 /// template <> template <class T> friend class A<int>::B;
14172  MultiTemplateParamsArg TempParams) {
14173  SourceLocation Loc = DS.getBeginLoc();
14174 
14175  assert(DS.isFriendSpecified());
14177 
14178  // C++ [class.friend]p3:
14179  // A friend declaration that does not declare a function shall have one of
14180  // the following forms:
14181  // friend elaborated-type-specifier ;
14182  // friend simple-type-specifier ;
14183  // friend typename-specifier ;
14184  //
14185  // Any declaration with a type qualifier does not have that form. (It's
14186  // legal to specify a qualified type as a friend, you just can't write the
14187  // keywords.)
14188  if (DS.getTypeQualifiers()) {
14190  Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
14192  Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
14194  Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
14196  Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
14198  Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
14199  }
14200 
14201  // Try to convert the decl specifier to a type. This works for
14202  // friend templates because ActOnTag never produces a ClassTemplateDecl
14203  // for a TUK_Friend.
14204  Declarator TheDeclarator(DS, DeclaratorContext::MemberContext);
14205  TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
14206  QualType T = TSI->getType();
14207  if (TheDeclarator.isInvalidType())
14208  return nullptr;
14209 
14210  if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
14211  return nullptr;
14212 
14213  // This is definitely an error in C++98. It's probably meant to
14214  // be forbidden in C++0x, too, but the specification is just
14215  // poorly written.
14216  //
14217  // The problem is with declarations like the following:
14218  // template <T> friend A<T>::foo;
14219  // where deciding whether a class C is a friend or not now hinges
14220  // on whether there exists an instantiation of A that causes
14221  // 'foo' to equal C. There are restrictions on class-heads
14222  // (which we declare (by fiat) elaborated friend declarations to
14223  // be) that makes this tractable.
14224  //
14225  // FIXME: handle "template <> friend class A<T>;", which
14226  // is possibly well-formed? Who even knows?
14227  if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
14228  Diag(Loc, diag::err_tagless_friend_type_template)
14229  << DS.getSourceRange();
14230  return nullptr;
14231  }
14232 
14233  // C++98 [class.friend]p1: A friend of a class is a function
14234  // or class that is not a member of the class . . .
14235  // This is fixed in DR77, which just barely didn't make the C++03
14236  // deadline. It's also a very silly restriction that seriously
14237  // affects inner classes and which nobody else seems to implement;
14238  // thus we never diagnose it, not even in -pedantic.
14239  //
14240  // But note that we could warn about it: it's always useless to
14241  // friend one of your own members (it's not, however, worthless to
14242  // friend a member of an arbitrary specialization of your template).
14243 
14244  Decl *D;
14245  if (!TempParams.empty())
14246  D = FriendTemplateDecl::Create(Context, CurContext, Loc,
14247  TempParams,
14248  TSI,
14249  DS.getFriendSpecLoc());
14250  else
14251  D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
14252 
14253  if (!D)
14254  return nullptr;
14255 
14256  D->setAccess(AS_public);
14257  CurContext->addDecl(D);
14258 
14259  return D;
14260 }
14261 
14263  MultiTemplateParamsArg TemplateParams) {
14264  const DeclSpec &DS = D.getDeclSpec();
14265 
14266  assert(DS.isFriendSpecified());
14268 
14269  SourceLocation Loc = D.getIdentifierLoc();
14270  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14271 
14272  // C++ [class.friend]p1
14273  // A friend of a class is a function or class....
14274  // Note that this sees through typedefs, which is intended.
14275  // It *doesn't* see through dependent types, which is correct
14276  // according to [temp.arg.type]p3:
14277  // If a declaration acquires a function type through a
14278  // type dependent on a template-parameter and this causes
14279  // a declaration that does not use the syntactic form of a
14280  // function declarator to have a function type, the program
14281  // is ill-formed.
14282  if (!TInfo->getType()->isFunctionType()) {
14283  Diag(Loc, diag::err_unexpected_friend);
14284 
14285  // It might be worthwhile to try to recover by creating an
14286  // appropriate declaration.
14287  return nullptr;
14288  }
14289 
14290  // C++ [namespace.memdef]p3
14291  // - If a friend declaration in a non-local class first declares a
14292  // class or function, the friend class or function is a member
14293  // of the innermost enclosing namespace.
14294  // - The name of the friend is not found by simple name lookup
14295  // until a matching declaration is provided in that namespace
14296  // scope (either before or after the class declaration granting
14297  // friendship).
14298  // - If a friend function is called, its name may be found by the
14299  // name lookup that considers functions from namespaces and
14300  // classes associated with the types of the function arguments.
14301  // - When looking for a prior declaration of a class or a function
14302  // declared as a friend, scopes outside the innermost enclosing
14303  // namespace scope are not considered.
14304 
14305  CXXScopeSpec &SS = D.getCXXScopeSpec();
14306  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
14307  assert(NameInfo.getName());
14308 
14309  // Check for unexpanded parameter packs.
14310  if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
14311  DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
14312  DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
14313  return nullptr;
14314 
14315  // The context we found the declaration in, or in which we should
14316  // create the declaration.
14317  DeclContext *DC;
14318  Scope *DCScope = S;
14319  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
14320  ForExternalRedeclaration);
14321 
14322  // There are five cases here.
14323  // - There's no scope specifier and we're in a local class. Only look
14324  // for functions declared in the immediately-enclosing block scope.
14325  // We recover from invalid scope qualifiers as if they just weren't there.
14326  FunctionDecl *FunctionContainingLocalClass = nullptr;
14327  if ((SS.isInvalid() || !SS.isSet()) &&
14328  (FunctionContainingLocalClass =
14329  cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
14330  // C++11 [class.friend]p11:
14331  // If a friend declaration appears in a local class and the name
14332  // specified is an unqualified name, a prior declaration is
14333  // looked up without considering scopes that are outside the
14334  // innermost enclosing non-class scope. For a friend function
14335  // declaration, if there is no prior declaration, the program is
14336  // ill-formed.
14337 
14338  // Find the innermost enclosing non-class scope. This is the block
14339  // scope containing the local class definition (or for a nested class,
14340  // the outer local class).
14341  DCScope = S->getFnParent();
14342 
14343  // Look up the function name in the scope.
14344  Previous.clear(LookupLocalFriendName);
14345  LookupName(Previous, S, /*AllowBuiltinCreation*/false);
14346 
14347  if (!Previous.empty()) {
14348  // All possible previous declarations must have the same context:
14349  // either they were declared at block scope or they are members of
14350  // one of the enclosing local classes.
14351  DC = Previous.getRepresentativeDecl()->getDeclContext();
14352  } else {
14353  // This is ill-formed, but provide the context that we would have
14354  // declared the function in, if we were permitted to, for error recovery.
14355  DC = FunctionContainingLocalClass;
14356  }
14357  adjustContextForLocalExternDecl(DC);
14358 
14359  // C++ [class.friend]p6:
14360  // A function can be defined in a friend declaration of a class if and
14361  // only if the class is a non-local class (9.8), the function name is
14362  // unqualified, and the function has namespace scope.
14363  if (D.isFunctionDefinition()) {
14364  Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
14365  }
14366 
14367  // - There's no scope specifier, in which case we just go to the
14368  // appropriate scope and look for a function or function template
14369  // there as appropriate.
14370  } else if (SS.isInvalid() || !SS.isSet()) {
14371  // C++11 [namespace.memdef]p3:
14372  // If the name in a friend declaration is neither qualified nor
14373  // a template-id and the declaration is a function or an
14374  // elaborated-type-specifier, the lookup to determine whether
14375  // the entity has been previously declared shall not consider
14376  // any scopes outside the innermost enclosing namespace.
14377  bool isTemplateId =
14379 
14380  // Find the appropriate context according to the above.
14381  DC = CurContext;
14382 
14383  // Skip class contexts. If someone can cite chapter and verse
14384  // for this behavior, that would be nice --- it's what GCC and
14385  // EDG do, and it seems like a reasonable intent, but the spec
14386  // really only says that checks for unqualified existing
14387  // declarations should stop at the nearest enclosing namespace,
14388  // not that they should only consider the nearest enclosing
14389  // namespace.
14390  while (DC->isRecord())
14391  DC = DC->getParent();
14392 
14393  DeclContext *LookupDC = DC;
14394  while (LookupDC->isTransparentContext())
14395  LookupDC = LookupDC->getParent();
14396 
14397  while (true) {
14398  LookupQualifiedName(Previous, LookupDC);
14399 
14400  if (!Previous.empty()) {
14401  DC = LookupDC;
14402  break;
14403  }
14404 
14405  if (isTemplateId) {
14406  if (isa<TranslationUnitDecl>(LookupDC)) break;
14407  } else {
14408  if (LookupDC->isFileContext()) break;
14409  }
14410  LookupDC = LookupDC->getParent();
14411  }
14412 
14413  DCScope = getScopeForDeclContext(S, DC);
14414 
14415  // - There's a non-dependent scope specifier, in which case we
14416  // compute it and do a previous lookup there for a function
14417  // or function template.
14418  } else if (!SS.getScopeRep()->isDependent()) {
14419  DC = computeDeclContext(SS);
14420  if (!DC) return nullptr;
14421 
14422  if (RequireCompleteDeclContext(SS, DC)) return nullptr;
14423 
14424  LookupQualifiedName(Previous, DC);
14425 
14426  // C++ [class.friend]p1: A friend of a class is a function or
14427  // class that is not a member of the class . . .
14428  if (DC->Equals(CurContext))
14429  Diag(DS.getFriendSpecLoc(),
14430  getLangOpts().CPlusPlus11 ?
14431  diag::warn_cxx98_compat_friend_is_member :
14432  diag::err_friend_is_member);
14433 
14434  if (D.isFunctionDefinition()) {
14435  // C++ [class.friend]p6:
14436  // A function can be defined in a friend declaration of a class if and
14437  // only if the class is a non-local class (9.8), the function name is
14438  // unqualified, and the function has namespace scope.
14439  //
14440  // FIXME: We should only do this if the scope specifier names the
14441  // innermost enclosing namespace; otherwise the fixit changes the
14442  // meaning of the code.
14444  = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
14445 
14446  DB << SS.getScopeRep();
14447  if (DC->isFileContext())
14448  DB << FixItHint::CreateRemoval(SS.getRange());
14449  SS.clear();
14450  }
14451 
14452  // - There's a scope specifier that does not match any template
14453  // parameter lists, in which case we use some arbitrary context,
14454  // create a method or method template, and wait for instantiation.
14455  // - There's a scope specifier that does match some template
14456  // parameter lists, which we don't handle right now.
14457  } else {
14458  if (D.isFunctionDefinition()) {
14459  // C++ [class.friend]p6:
14460  // A function can be defined in a friend declaration of a class if and
14461  // only if the class is a non-local class (9.8), the function name is
14462  // unqualified, and the function has namespace scope.
14463  Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
14464  << SS.getScopeRep();
14465  }
14466 
14467  DC = CurContext;
14468  assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
14469  }
14470 
14471  if (!DC->isRecord()) {
14472  int DiagArg = -1;
14473  switch (D.getName().getKind()) {
14476  DiagArg = 0;
14477  break;
14479  DiagArg = 1;
14480  break;
14482  DiagArg = 2;
14483  break;
14485  DiagArg = 3;
14486  break;
14492  break;
14493  }
14494  // This implies that it has to be an operator or function.
14495  if (DiagArg >= 0) {
14496  Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
14497  return nullptr;
14498  }
14499  }
14500 
14501  // FIXME: This is an egregious hack to cope with cases where the scope stack
14502  // does not contain the declaration context, i.e., in an out-of-line
14503  // definition of a class.
14504  Scope FakeDCScope(S, Scope::DeclScope, Diags);
14505  if (!DCScope) {
14506  FakeDCScope.setEntity(DC);
14507  DCScope = &FakeDCScope;
14508  }
14509 
14510  bool AddToScope = true;
14511  NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
14512  TemplateParams, AddToScope);
14513  if (!ND) return nullptr;
14514 
14515  assert(ND->getLexicalDeclContext() == CurContext);
14516 
14517  // If we performed typo correction, we might have added a scope specifier
14518  // and changed the decl context.
14519  DC = ND->getDeclContext();
14520 
14521  // Add the function declaration to the appropriate lookup tables,
14522  // adjusting the redeclarations list as necessary. We don't
14523  // want to do this yet if the friending class is dependent.
14524  //
14525  // Also update the scope-based lookup if the target context's
14526  // lookup context is in lexical scope.
14527  if (!CurContext->isDependentContext()) {
14528  DC = DC->getRedeclContext();
14529  DC->makeDeclVisibleInContext(ND);
14530  if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14531  PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
14532  }
14533 
14534  FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
14535  D.getIdentifierLoc(), ND,
14536  DS.getFriendSpecLoc());
14537  FrD->setAccess(AS_public);
14538  CurContext->addDecl(FrD);
14539 
14540  if (ND->isInvalidDecl()) {
14541  FrD->setInvalidDecl();
14542  } else {
14543  if (DC->isRecord()) CheckFriendAccess(ND);
14544 
14545  FunctionDecl *FD;
14546  if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
14547  FD = FTD->getTemplatedDecl();
14548  else
14549  FD = cast<FunctionDecl>(ND);
14550 
14551  // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
14552  // default argument expression, that declaration shall be a definition
14553  // and shall be the only declaration of the function or function
14554  // template in the translation unit.
14556  // We can't look at FD->getPreviousDecl() because it may not have been set
14557  // if we're in a dependent context. If the function is known to be a
14558  // redeclaration, we will have narrowed Previous down to the right decl.
14559  if (D.isRedeclaration()) {
14560  Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
14561  Diag(Previous.getRepresentativeDecl()->getLocation(),
14562  diag::note_previous_declaration);
14563  } else if (!D.isFunctionDefinition())
14564  Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
14565  }
14566 
14567  // Mark templated-scope function declarations as unsupported.
14568  if (FD->getNumTemplateParameterLists() && SS.isValid()) {
14569  Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
14570  << SS.getScopeRep() << SS.getRange()
14571  << cast<CXXRecordDecl>(CurContext);
14572  FrD->setUnsupportedFriend(true);
14573  }
14574  }
14575 
14576  return ND;
14577 }
14578 
14579 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
14580  AdjustDeclIfTemplate(Dcl);
14581 
14582  FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
14583  if (!Fn) {
14584  Diag(DelLoc, diag::err_deleted_non_function);
14585  return;
14586  }
14587 
14588  // Deleted function does not have a body.
14589  Fn->setWillHaveBody(false);
14590 
14591  if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
14592  // Don't consider the implicit declaration we generate for explicit
14593  // specializations. FIXME: Do not generate these implicit declarations.
14594  if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
14595  Prev->getPreviousDecl()) &&
14596  !Prev->isDefined()) {
14597  Diag(DelLoc, diag::err_deleted_decl_not_first);
14598  Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
14599  Prev->isImplicit() ? diag::note_previous_implicit_declaration
14600  : diag::note_previous_declaration);
14601  }
14602  // If the declaration wasn't the first, we delete the function anyway for
14603  // recovery.
14604  Fn = Fn->getCanonicalDecl();
14605  }
14606 
14607  // dllimport/dllexport cannot be deleted.
14608  if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
14609  Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
14610  Fn->setInvalidDecl();
14611  }
14612 
14613  if (Fn->isDeleted())
14614  return;
14615 
14616  // See if we're deleting a function which is already known to override a
14617  // non-deleted virtual function.
14618  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
14619  bool IssuedDiagnostic = false;
14620  for (const CXXMethodDecl *O : MD->overridden_methods()) {
14621  if (!(*MD->begin_overridden_methods())->isDeleted()) {
14622  if (!IssuedDiagnostic) {
14623  Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
14624  IssuedDiagnostic = true;
14625  }
14626  Diag(O->getLocation(), diag::note_overridden_virtual_function);
14627  }
14628  }
14629  // If this function was implicitly deleted because it was defaulted,
14630  // explain why it was deleted.
14631  if (IssuedDiagnostic && MD->isDefaulted())
14632  ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr,
14633  /*Diagnose*/true);
14634  }
14635 
14636  // C++11 [basic.start.main]p3:
14637  // A program that defines main as deleted [...] is ill-formed.
14638  if (Fn->isMain())
14639  Diag(DelLoc, diag::err_deleted_main);
14640 
14641  // C++11 [dcl.fct.def.delete]p4:
14642  // A deleted function is implicitly inline.
14643  Fn->setImplicitlyInline();
14644  Fn->setDeletedAsWritten();
14645 }
14646 
14647 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
14648  CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
14649 
14650  if (MD) {
14651  if (MD->getParent()->isDependentType()) {
14652  MD->setDefaulted();
14653  MD->setExplicitlyDefaulted();
14654  return;
14655  }
14656 
14657  CXXSpecialMember Member = getSpecialMember(MD);
14658  if (Member == CXXInvalid) {
14659  if (!MD->isInvalidDecl())
14660  Diag(DefaultLoc, diag::err_default_special_members);
14661  return;
14662  }
14663 
14664  MD->setDefaulted();
14665  MD->setExplicitlyDefaulted();
14666 
14667  // Unset that we will have a body for this function. We might not,
14668  // if it turns out to be trivial, and we don't need this marking now
14669  // that we've marked it as defaulted.
14670  MD->setWillHaveBody(false);
14671 
14672  // If this definition appears within the record, do the checking when
14673  // the record is complete.
14674  const FunctionDecl *Primary = MD;
14675  if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
14676  // Ask the template instantiation pattern that actually had the
14677  // '= default' on it.
14678  Primary = Pattern;
14679 
14680  // If the method was defaulted on its first declaration, we will have
14681  // already performed the checking in CheckCompletedCXXClass. Such a
14682  // declaration doesn't trigger an implicit definition.
14683  if (Primary->getCanonicalDecl()->isDefaulted())
14684  return;
14685 
14686  CheckExplicitlyDefaultedSpecialMember(MD);
14687 
14688  if (!MD->isInvalidDecl())
14689  DefineImplicitSpecialMember(*this, MD, DefaultLoc);
14690  } else {
14691  Diag(DefaultLoc, diag::err_default_special_members);
14692  }
14693 }
14694 
14695 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
14696  for (Stmt *SubStmt : S->children()) {
14697  if (!SubStmt)
14698  continue;
14699  if (isa<ReturnStmt>(SubStmt))
14700  Self.Diag(SubStmt->getBeginLoc(),
14701  diag::err_return_in_constructor_handler);
14702  if (!isa<Expr>(SubStmt))
14703  SearchForReturnInStmt(Self, SubStmt);
14704  }
14705 }
14706 
14708  for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
14709  CXXCatchStmt *Handler = TryBlock->getHandler(I);
14710  SearchForReturnInStmt(*this, Handler);
14711  }
14712 }
14713 
14715  const CXXMethodDecl *Old) {
14716  const auto *NewFT = New->getType()->getAs<FunctionProtoType>();
14717  const auto *OldFT = Old->getType()->getAs<FunctionProtoType>();
14718 
14719  if (OldFT->hasExtParameterInfos()) {
14720  for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
14721  // A parameter of the overriding method should be annotated with noescape
14722  // if the corresponding parameter of the overridden method is annotated.
14723  if (OldFT->getExtParameterInfo(I).isNoEscape() &&
14724  !NewFT->getExtParameterInfo(I).isNoEscape()) {
14725  Diag(New->getParamDecl(I)->getLocation(),
14726  diag::warn_overriding_method_missing_noescape);
14727  Diag(Old->getParamDecl(I)->getLocation(),
14728  diag::note_overridden_marked_noescape);
14729  }
14730  }
14731 
14732  // Virtual overrides must have the same code_seg.
14733  const auto *OldCSA = Old->getAttr<CodeSegAttr>();
14734  const auto *NewCSA = New->getAttr<CodeSegAttr>();
14735  if ((NewCSA || OldCSA) &&
14736  (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
14737  Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
14738  Diag(Old->getLocation(), diag::note_previous_declaration);
14739  return true;
14740  }
14741 
14742  CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
14743 
14744  // If the calling conventions match, everything is fine
14745  if (NewCC == OldCC)
14746  return false;
14747 
14748  // If the calling conventions mismatch because the new function is static,
14749  // suppress the calling convention mismatch error; the error about static
14750  // function override (err_static_overrides_virtual from
14751  // Sema::CheckFunctionDeclaration) is more clear.
14752  if (New->getStorageClass() == SC_Static)
14753  return false;
14754 
14755  Diag(New->getLocation(),
14756  diag::err_conflicting_overriding_cc_attributes)
14757  << New->getDeclName() << New->getType() << Old->getType();
14758  Diag(Old->getLocation(), diag::note_overridden_virtual_function);
14759  return true;
14760 }
14761 
14763  const CXXMethodDecl *Old) {
14764  QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
14765  QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
14766 
14767  if (Context.hasSameType(NewTy, OldTy) ||
14768  NewTy->isDependentType() || OldTy->isDependentType())
14769  return false;
14770 
14771  // Check if the return types are covariant
14772  QualType NewClassTy, OldClassTy;
14773 
14774  /// Both types must be pointers or references to classes.
14775  if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
14776  if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
14777  NewClassTy = NewPT->getPointeeType();
14778  OldClassTy = OldPT->getPointeeType();
14779  }
14780  } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
14781  if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
14782  if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
14783  NewClassTy = NewRT->getPointeeType();
14784  OldClassTy = OldRT->getPointeeType();
14785  }
14786  }
14787  }
14788 
14789  // The return types aren't either both pointers or references to a class type.
14790  if (NewClassTy.isNull()) {
14791  Diag(New->getLocation(),
14792  diag::err_different_return_type_for_overriding_virtual_function)
14793  << New->getDeclName() << NewTy << OldTy
14794  << New->getReturnTypeSourceRange();
14795  Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14796  << Old->getReturnTypeSourceRange();
14797 
14798  return true;
14799  }
14800 
14801  if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
14802  // C++14 [class.virtual]p8:
14803  // If the class type in the covariant return type of D::f differs from
14804  // that of B::f, the class type in the return type of D::f shall be
14805  // complete at the point of declaration of D::f or shall be the class
14806  // type D.
14807  if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
14808  if (!RT->isBeingDefined() &&
14809  RequireCompleteType(New->getLocation(), NewClassTy,
14810  diag::err_covariant_return_incomplete,
14811  New->getDeclName()))
14812  return true;
14813  }
14814 
14815  // Check if the new class derives from the old class.
14816  if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
14817  Diag(New->getLocation(), diag::err_covariant_return_not_derived)
14818  << New->getDeclName() << NewTy << OldTy
14819  << New->getReturnTypeSourceRange();
14820  Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14821  << Old->getReturnTypeSourceRange();
14822  return true;
14823  }
14824 
14825  // Check if we the conversion from derived to base is valid.
14826  if (CheckDerivedToBaseConversion(
14827  NewClassTy, OldClassTy,
14828  diag::err_covariant_return_inaccessible_base,
14829  diag::err_covariant_return_ambiguous_derived_to_base_conv,
14830  New->getLocation(), New->getReturnTypeSourceRange(),
14831  New->getDeclName(), nullptr)) {
14832  // FIXME: this note won't trigger for delayed access control
14833  // diagnostics, and it's impossible to get an undelayed error
14834  // here from access control during the original parse because
14835  // the ParsingDeclSpec/ParsingDeclarator are still in scope.
14836  Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14837  << Old->getReturnTypeSourceRange();
14838  return true;
14839  }
14840  }
14841 
14842  // The qualifiers of the return types must be the same.
14843  if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
14844  Diag(New->getLocation(),
14845  diag::err_covariant_return_type_different_qualifications)
14846  << New->getDeclName() << NewTy << OldTy
14847  << New->getReturnTypeSourceRange();
14848  Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14849  << Old->getReturnTypeSourceRange();
14850  return true;
14851  }
14852 
14853 
14854  // The new class type must have the same or less qualifiers as the old type.
14855  if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
14856  Diag(New->getLocation(),
14857  diag::err_covariant_return_type_class_type_more_qualified)
14858  << New->getDeclName() << NewTy << OldTy
14859  << New->getReturnTypeSourceRange();
14860  Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14861  << Old->getReturnTypeSourceRange();
14862  return true;
14863  }
14864 
14865  return false;
14866 }
14867 
14868 /// Mark the given method pure.
14869 ///
14870 /// \param Method the method to be marked pure.
14871 ///
14872 /// \param InitRange the source range that covers the "0" initializer.
14874  SourceLocation EndLoc = InitRange.getEnd();
14875  if (EndLoc.isValid())
14876  Method->setRangeEnd(EndLoc);
14877 
14878  if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
14879  Method->setPure();
14880  return false;
14881  }
14882 
14883  if (!Method->isInvalidDecl())
14884  Diag(Method->getLocation(), diag::err_non_virtual_pure)
14885  << Method->getDeclName() << InitRange;
14886  return true;
14887 }
14888 
14890  if (D->getFriendObjectKind())
14891  Diag(D->getLocation(), diag::err_pure_friend);
14892  else if (auto *M = dyn_cast<CXXMethodDecl>(D))
14893  CheckPureMethod(M, ZeroLoc);
14894  else
14895  Diag(D->getLocation(), diag::err_illegal_initializer);
14896 }
14897 
14898 /// Determine whether the given declaration is a global variable or
14899 /// static data member.
14900 static bool isNonlocalVariable(const Decl *D) {
14901  if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
14902  return Var->hasGlobalStorage();
14903 
14904  return false;
14905 }
14906 
14907 /// Invoked when we are about to parse an initializer for the declaration
14908 /// 'Dcl'.
14909 ///
14910 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
14911 /// static data member of class X, names should be looked up in the scope of
14912 /// class X. If the declaration had a scope specifier, a scope will have
14913 /// been created and passed in for this purpose. Otherwise, S will be null.
14915  // If there is no declaration, there was an error parsing it.
14916  if (!D || D->isInvalidDecl())
14917  return;
14918 
14919  // We will always have a nested name specifier here, but this declaration
14920  // might not be out of line if the specifier names the current namespace:
14921  // extern int n;
14922  // int ::n = 0;
14923  if (S && D->isOutOfLine())
14924  EnterDeclaratorContext(S, D->getDeclContext());
14925 
14926  // If we are parsing the initializer for a static data member, push a
14927  // new expression evaluation context that is associated with this static
14928  // data member.
14929  if (isNonlocalVariable(D))
14930  PushExpressionEvaluationContext(
14931  ExpressionEvaluationContext::PotentiallyEvaluated, D);
14932 }
14933 
14934 /// Invoked after we are finished parsing an initializer for the declaration D.
14936  // If there is no declaration, there was an error parsing it.
14937  if (!D || D->isInvalidDecl())
14938  return;
14939 
14940  if (isNonlocalVariable(D))
14941  PopExpressionEvaluationContext();
14942 
14943  if (S && D->isOutOfLine())
14944  ExitDeclaratorContext(S);
14945 }
14946 
14947 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
14948 /// C++ if/switch/while/for statement.
14949 /// e.g: "if (int x = f()) {...}"
14951  // C++ 6.4p2:
14952  // The declarator shall not specify a function or an array.
14953  // The type-specifier-seq shall not contain typedef and shall not declare a
14954  // new class or enumeration.
14956  "Parser allowed 'typedef' as storage class of condition decl.");
14957 
14958  Decl *Dcl = ActOnDeclarator(S, D);
14959  if (!Dcl)
14960  return true;
14961 
14962  if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
14963  Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
14964  << D.getSourceRange();
14965  return true;
14966  }
14967 
14968  return Dcl;
14969 }
14970 
14972  if (!ExternalSource)
14973  return;
14974 
14976  ExternalSource->ReadUsedVTables(VTables);
14977  SmallVector<VTableUse, 4> NewUses;
14978  for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
14979  llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
14980  = VTablesUsed.find(VTables[I].Record);
14981  // Even if a definition wasn't required before, it may be required now.
14982  if (Pos != VTablesUsed.end()) {
14983  if (!Pos->second && VTables[I].DefinitionRequired)
14984  Pos->second = true;
14985  continue;
14986  }
14987 
14988  VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
14989  NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
14990  }
14991 
14992  VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
14993 }
14994 
14996  bool DefinitionRequired) {
14997  // Ignore any vtable uses in unevaluated operands or for classes that do
14998  // not have a vtable.
14999  if (!Class->isDynamicClass() || Class->isDependentContext() ||
15000  CurContext->isDependentContext() || isUnevaluatedContext())
15001  return;
15002  // Do not mark as used if compiling for the device outside of the target
15003  // region.
15004  if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
15005  !isInOpenMPDeclareTargetContext() &&
15006  !isInOpenMPTargetExecutionDirective()) {
15007  if (!DefinitionRequired)
15008  MarkVirtualMembersReferenced(Loc, Class);
15009  return;
15010  }
15011 
15012  // Try to insert this class into the map.
15013  LoadExternalVTableUses();
15014  Class = Class->getCanonicalDecl();
15015  std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
15016  Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
15017  if (!Pos.second) {
15018  // If we already had an entry, check to see if we are promoting this vtable
15019  // to require a definition. If so, we need to reappend to the VTableUses
15020  // list, since we may have already processed the first entry.
15021  if (DefinitionRequired && !Pos.first->second) {
15022  Pos.first->second = true;
15023  } else {
15024  // Otherwise, we can early exit.
15025  return;
15026  }
15027  } else {
15028  // The Microsoft ABI requires that we perform the destructor body
15029  // checks (i.e. operator delete() lookup) when the vtable is marked used, as
15030  // the deleting destructor is emitted with the vtable, not with the
15031  // destructor definition as in the Itanium ABI.
15032  if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
15033  CXXDestructorDecl *DD = Class->getDestructor();
15034  if (DD && DD->isVirtual() && !DD->isDeleted()) {
15035  if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
15036  // If this is an out-of-line declaration, marking it referenced will
15037  // not do anything. Manually call CheckDestructor to look up operator
15038  // delete().
15039  ContextRAII SavedContext(*this, DD);
15040  CheckDestructor(DD);
15041  } else {
15042  MarkFunctionReferenced(Loc, Class->getDestructor());
15043  }
15044  }
15045  }
15046  }
15047 
15048  // Local classes need to have their virtual members marked
15049  // immediately. For all other classes, we mark their virtual members
15050  // at the end of the translation unit.
15051  if (Class->isLocalClass())
15052  MarkVirtualMembersReferenced(Loc, Class);
15053  else
15054  VTableUses.push_back(std::make_pair(Class, Loc));
15055 }
15056 
15058  LoadExternalVTableUses();
15059  if (VTableUses.empty())
15060  return false;
15061 
15062  // Note: The VTableUses vector could grow as a result of marking
15063  // the members of a class as "used", so we check the size each
15064  // time through the loop and prefer indices (which are stable) to
15065  // iterators (which are not).
15066  bool DefinedAnything = false;
15067  for (unsigned I = 0; I != VTableUses.size(); ++I) {
15068  CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
15069  if (!Class)
15070  continue;
15071  TemplateSpecializationKind ClassTSK =
15073 
15074  SourceLocation Loc = VTableUses[I].second;
15075 
15076  bool DefineVTable = true;
15077 
15078  // If this class has a key function, but that key function is
15079  // defined in another translation unit, we don't need to emit the
15080  // vtable even though we're using it.
15081  const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
15082  if (KeyFunction && !KeyFunction->hasBody()) {
15083  // The key function is in another translation unit.
15084  DefineVTable = false;
15086  KeyFunction->getTemplateSpecializationKind();
15087  assert(TSK != TSK_ExplicitInstantiationDefinition &&
15088  TSK != TSK_ImplicitInstantiation &&
15089  "Instantiations don't have key functions");
15090  (void)TSK;
15091  } else if (!KeyFunction) {
15092  // If we have a class with no key function that is the subject
15093  // of an explicit instantiation declaration, suppress the
15094  // vtable; it will live with the explicit instantiation
15095  // definition.
15096  bool IsExplicitInstantiationDeclaration =
15098  for (auto R : Class->redecls()) {
15100  = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
15102  IsExplicitInstantiationDeclaration = true;
15103  else if (TSK == TSK_ExplicitInstantiationDefinition) {
15104  IsExplicitInstantiationDeclaration = false;
15105  break;
15106  }
15107  }
15108 
15109  if (IsExplicitInstantiationDeclaration)
15110  DefineVTable = false;
15111  }
15112 
15113  // The exception specifications for all virtual members may be needed even
15114  // if we are not providing an authoritative form of the vtable in this TU.
15115  // We may choose to emit it available_externally anyway.
15116  if (!DefineVTable) {
15117  MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
15118  continue;
15119  }
15120 
15121  // Mark all of the virtual members of this class as referenced, so
15122  // that we can build a vtable. Then, tell the AST consumer that a
15123  // vtable for this class is required.
15124  DefinedAnything = true;
15125  MarkVirtualMembersReferenced(Loc, Class);
15126  CXXRecordDecl *Canonical = Class->getCanonicalDecl();
15127  if (VTablesUsed[Canonical])
15128  Consumer.HandleVTable(Class);
15129 
15130  // Warn if we're emitting a weak vtable. The vtable will be weak if there is
15131  // no key function or the key function is inlined. Don't warn in C++ ABIs
15132  // that lack key functions, since the user won't be able to make one.
15133  if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
15134  Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
15135  const FunctionDecl *KeyFunctionDef = nullptr;
15136  if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
15137  KeyFunctionDef->isInlined())) {
15138  Diag(Class->getLocation(),
15140  ? diag::warn_weak_template_vtable
15141  : diag::warn_weak_vtable)
15142  << Class;
15143  }
15144  }
15145  }
15146  VTableUses.clear();
15147 
15148  return DefinedAnything;
15149 }
15150 
15152  const CXXRecordDecl *RD) {
15153  for (const auto *I : RD->methods())
15154  if (I->isVirtual() && !I->isPure())
15155  ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
15156 }
15157 
15159  const CXXRecordDecl *RD) {
15160  // Mark all functions which will appear in RD's vtable as used.
15161  CXXFinalOverriderMap FinalOverriders;
15162  RD->getFinalOverriders(FinalOverriders);
15163  for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
15164  E = FinalOverriders.end();
15165  I != E; ++I) {
15166  for (OverridingMethods::const_iterator OI = I->second.begin(),
15167  OE = I->second.end();
15168  OI != OE; ++OI) {
15169  assert(OI->second.size() > 0 && "no final overrider");
15170  CXXMethodDecl *Overrider = OI->second.front().Method;
15171 
15172  // C++ [basic.def.odr]p2:
15173  // [...] A virtual member function is used if it is not pure. [...]
15174  if (!Overrider->isPure())
15175  MarkFunctionReferenced(Loc, Overrider);
15176  }
15177  }
15178 
15179  // Only classes that have virtual bases need a VTT.
15180  if (RD->getNumVBases() == 0)
15181  return;
15182 
15183  for (const auto &I : RD->bases()) {
15184  const CXXRecordDecl *Base =
15185  cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
15186  if (Base->getNumVBases() == 0)
15187  continue;
15188  MarkVirtualMembersReferenced(Loc, Base);
15189  }
15190 }
15191 
15192 /// SetIvarInitializers - This routine builds initialization ASTs for the
15193 /// Objective-C implementation whose ivars need be initialized.
15195  if (!getLangOpts().CPlusPlus)
15196  return;
15197  if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
15199  CollectIvarsToConstructOrDestruct(OID, ivars);
15200  if (ivars.empty())
15201  return;
15203  for (unsigned i = 0; i < ivars.size(); i++) {
15204  FieldDecl *Field = ivars[i];
15205  if (Field->isInvalidDecl())
15206  continue;
15207 
15208  CXXCtorInitializer *Member;
15210  InitializationKind InitKind =
15211  InitializationKind::CreateDefault(ObjCImplementation->getLocation());
15212 
15213  InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
15214  ExprResult MemberInit =
15215  InitSeq.Perform(*this, InitEntity, InitKind, None);
15216  MemberInit = MaybeCreateExprWithCleanups(MemberInit);
15217  // Note, MemberInit could actually come back empty if no initialization
15218  // is required (e.g., because it would call a trivial default constructor)
15219  if (!MemberInit.get() || MemberInit.isInvalid())
15220  continue;
15221 
15222  Member =
15223  new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
15224  SourceLocation(),
15225  MemberInit.getAs<Expr>(),
15226  SourceLocation());
15227  AllToInit.push_back(Member);
15228 
15229  // Be sure that the destructor is accessible and is marked as referenced.
15230  if (const RecordType *RecordTy =
15231  Context.getBaseElementType(Field->getType())
15232  ->getAs<RecordType>()) {
15233  CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
15234  if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
15235  MarkFunctionReferenced(Field->getLocation(), Destructor);
15236  CheckDestructorAccess(Field->getLocation(), Destructor,
15237  PDiag(diag::err_access_dtor_ivar)
15238  << Context.getBaseElementType(Field->getType()));
15239  }
15240  }
15241  }
15242  ObjCImplementation->setIvarInitializers(Context,
15243  AllToInit.data(), AllToInit.size());
15244  }
15245 }
15246 
15247 static
15249  llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
15250  llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
15251  llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
15252  Sema &S) {
15253  if (Ctor->isInvalidDecl())
15254  return;
15255 
15257 
15258  // Target may not be determinable yet, for instance if this is a dependent
15259  // call in an uninstantiated template.
15260  if (Target) {
15261  const FunctionDecl *FNTarget = nullptr;
15262  (void)Target->hasBody(FNTarget);
15263  Target = const_cast<CXXConstructorDecl*>(
15264  cast_or_null<CXXConstructorDecl>(FNTarget));
15265  }
15266 
15267  CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
15268  // Avoid dereferencing a null pointer here.
15269  *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
15270 
15271  if (!Current.insert(Canonical).second)
15272  return;
15273 
15274  // We know that beyond here, we aren't chaining into a cycle.
15275  if (!Target || !Target->isDelegatingConstructor() ||
15276  Target->isInvalidDecl() || Valid.count(TCanonical)) {
15277  Valid.insert(Current.begin(), Current.end());
15278  Current.clear();
15279  // We've hit a cycle.
15280  } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
15281  Current.count(TCanonical)) {
15282  // If we haven't diagnosed this cycle yet, do so now.
15283  if (!Invalid.count(TCanonical)) {
15284  S.Diag((*Ctor->init_begin())->getSourceLocation(),
15285  diag::warn_delegating_ctor_cycle)
15286  << Ctor;
15287 
15288  // Don't add a note for a function delegating directly to itself.
15289  if (TCanonical != Canonical)
15290  S.Diag(Target->getLocation(), diag::note_it_delegates_to);
15291 
15293  while (C->getCanonicalDecl() != Canonical) {
15294  const FunctionDecl *FNTarget = nullptr;
15295  (void)C->getTargetConstructor()->hasBody(FNTarget);
15296  assert(FNTarget && "Ctor cycle through bodiless function");
15297 
15298  C = const_cast<CXXConstructorDecl*>(
15299  cast<CXXConstructorDecl>(FNTarget));
15300  S.Diag(C->getLocation(), diag::note_which_delegates_to);
15301  }
15302  }
15303 
15304  Invalid.insert(Current.begin(), Current.end());
15305  Current.clear();
15306  } else {
15307  DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
15308  }
15309 }
15310 
15311 
15313  llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
15314 
15315  for (DelegatingCtorDeclsType::iterator
15316  I = DelegatingCtorDecls.begin(ExternalSource),
15317  E = DelegatingCtorDecls.end();
15318  I != E; ++I)
15319  DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
15320 
15321  for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
15322  (*CI)->setInvalidDecl();
15323 }
15324 
15325 namespace {
15326  /// AST visitor that finds references to the 'this' expression.
15327  class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
15328  Sema &S;
15329 
15330  public:
15331  explicit FindCXXThisExpr(Sema &S) : S(S) { }
15332 
15333  bool VisitCXXThisExpr(CXXThisExpr *E) {
15334  S.Diag(E->getLocation(), diag::err_this_static_member_func)
15335  << E->isImplicit();
15336  return false;
15337  }
15338  };
15339 }
15340 
15342  TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15343  if (!TSInfo)
15344  return false;
15345 
15346  TypeLoc TL = TSInfo->getTypeLoc();
15348  if (!ProtoTL)
15349  return false;
15350 
15351  // C++11 [expr.prim.general]p3:
15352  // [The expression this] shall not appear before the optional
15353  // cv-qualifier-seq and it shall not appear within the declaration of a
15354  // static member function (although its type and value category are defined
15355  // within a static member function as they are within a non-static member
15356  // function). [ Note: this is because declaration matching does not occur
15357  // until the complete declarator is known. - end note ]
15358  const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15359  FindCXXThisExpr Finder(*this);
15360 
15361  // If the return type came after the cv-qualifier-seq, check it now.
15362  if (Proto->hasTrailingReturn() &&
15363  !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
15364  return true;
15365 
15366  // Check the exception specification.
15367  if (checkThisInStaticMemberFunctionExceptionSpec(Method))
15368  return true;
15369 
15370  return checkThisInStaticMemberFunctionAttributes(Method);
15371 }
15372 
15374  TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15375  if (!TSInfo)
15376  return false;
15377 
15378  TypeLoc TL = TSInfo->getTypeLoc();
15380  if (!ProtoTL)
15381  return false;
15382 
15383  const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15384  FindCXXThisExpr Finder(*this);
15385 
15386  switch (Proto->getExceptionSpecType()) {
15387  case EST_Unparsed:
15388  case EST_Uninstantiated:
15389  case EST_Unevaluated:
15390  case EST_BasicNoexcept:
15391  case EST_DynamicNone:
15392  case EST_MSAny:
15393  case EST_None:
15394  break;
15395 
15396  case EST_DependentNoexcept:
15397  case EST_NoexceptFalse:
15398  case EST_NoexceptTrue:
15399  if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
15400  return true;
15401  LLVM_FALLTHROUGH;
15402 
15403  case EST_Dynamic:
15404  for (const auto &E : Proto->exceptions()) {
15405  if (!Finder.TraverseType(E))
15406  return true;
15407  }
15408  break;
15409  }
15410 
15411  return false;
15412 }
15413 
15415  FindCXXThisExpr Finder(*this);
15416 
15417  // Check attributes.
15418  for (const auto *A : Method->attrs()) {
15419  // FIXME: This should be emitted by tblgen.
15420  Expr *Arg = nullptr;
15421  ArrayRef<Expr *> Args;
15422  if (const auto *G = dyn_cast<GuardedByAttr>(A))
15423  Arg = G->getArg();
15424  else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
15425  Arg = G->getArg();
15426  else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
15427  Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
15428  else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
15429  Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
15430  else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
15431  Arg = ETLF->getSuccessValue();
15432  Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
15433  } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
15434  Arg = STLF->getSuccessValue();
15435  Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
15436  } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
15437  Arg = LR->getArg();
15438  else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
15439  Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
15440  else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
15441  Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15442  else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
15443  Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15444  else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
15445  Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15446  else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
15447  Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15448 
15449  if (Arg && !Finder.TraverseStmt(Arg))
15450  return true;
15451 
15452  for (unsigned I = 0, N = Args.size(); I != N; ++I) {
15453  if (!Finder.TraverseStmt(Args[I]))
15454  return true;
15455  }
15456  }
15457 
15458  return false;
15459 }
15460 
15462  bool IsTopLevel, ExceptionSpecificationType EST,
15463  ArrayRef<ParsedType> DynamicExceptions,
15464  ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
15465  SmallVectorImpl<QualType> &Exceptions,
15467  Exceptions.clear();
15468  ESI.Type = EST;
15469  if (EST == EST_Dynamic) {
15470  Exceptions.reserve(DynamicExceptions.size());
15471  for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
15472  // FIXME: Preserve type source info.
15473  QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
15474 
15475  if (IsTopLevel) {
15477  collectUnexpandedParameterPacks(ET, Unexpanded);
15478  if (!Unexpanded.empty()) {
15480  DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
15481  Unexpanded);
15482  continue;
15483  }
15484  }
15485 
15486  // Check that the type is valid for an exception spec, and
15487  // drop it if not.
15488  if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
15489  Exceptions.push_back(ET);
15490  }
15491  ESI.Exceptions = Exceptions;
15492  return;
15493  }
15494 
15495  if (isComputedNoexcept(EST)) {
15496  assert((NoexceptExpr->isTypeDependent() ||
15497  NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
15498  Context.BoolTy) &&
15499  "Parser should have made sure that the expression is boolean");
15500  if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
15501  ESI.Type = EST_BasicNoexcept;
15502  return;
15503  }
15504 
15505  ESI.NoexceptExpr = NoexceptExpr;
15506  return;
15507  }
15508 }
15509 
15512  SourceRange SpecificationRange,
15513  ArrayRef<ParsedType> DynamicExceptions,
15514  ArrayRef<SourceRange> DynamicExceptionRanges,
15515  Expr *NoexceptExpr) {
15516  if (!MethodD)
15517  return;
15518 
15519  // Dig out the method we're referring to.
15520  if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
15521  MethodD = FunTmpl->getTemplatedDecl();
15522 
15523  CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
15524  if (!Method)
15525  return;
15526 
15527  // Check the exception specification.
15528  llvm::SmallVector<QualType, 4> Exceptions;
15530  checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
15531  DynamicExceptionRanges, NoexceptExpr, Exceptions,
15532  ESI);
15533 
15534  // Update the exception specification on the function type.
15535  Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
15536 
15537  if (Method->isStatic())
15538  checkThisInStaticMemberFunctionExceptionSpec(Method);
15539 
15540  if (Method->isVirtual()) {
15541  // Check overrides, which we previously had to delay.
15542  for (const CXXMethodDecl *O : Method->overridden_methods())
15543  CheckOverridingFunctionExceptionSpec(Method, O);
15544  }
15545 }
15546 
15547 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
15548 ///
15550  SourceLocation DeclStart, Declarator &D,
15551  Expr *BitWidth,
15552  InClassInitStyle InitStyle,
15553  AccessSpecifier AS,
15554  const ParsedAttr &MSPropertyAttr) {
15555  IdentifierInfo *II = D.getIdentifier();
15556  if (!II) {
15557  Diag(DeclStart, diag::err_anonymous_property);
15558  return nullptr;
15559  }
15560  SourceLocation Loc = D.getIdentifierLoc();
15561 
15562  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15563  QualType T = TInfo->getType();
15564  if (getLangOpts().CPlusPlus) {
15565  CheckExtraCXXDefaultArguments(D);
15566 
15567  if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15568  UPPC_DataMemberType)) {
15569  D.setInvalidType();
15570  T = Context.IntTy;
15571  TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15572  }
15573  }
15574 
15575  DiagnoseFunctionSpecifiers(D.getDeclSpec());
15576 
15577  if (D.getDeclSpec().isInlineSpecified())
15578  Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15579  << getLangOpts().CPlusPlus17;
15582  diag::err_invalid_thread)
15583  << DeclSpec::getSpecifierName(TSCS);
15584 
15585  // Check to see if this name was declared as a member previously
15586  NamedDecl *PrevDecl = nullptr;
15587  LookupResult Previous(*this, II, Loc, LookupMemberName,
15588  ForVisibleRedeclaration);
15589  LookupName(Previous, S);
15590  switch (Previous.getResultKind()) {
15591  case LookupResult::Found:
15593  PrevDecl = Previous.getAsSingle<NamedDecl>();
15594  break;
15595 
15597  PrevDecl = Previous.getRepresentativeDecl();
15598  break;
15599 
15603  break;
15604  }
15605 
15606  if (PrevDecl && PrevDecl->isTemplateParameter()) {
15607  // Maybe we will complain about the shadowed template parameter.
15608  DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15609  // Just pretend that we didn't see the previous declaration.
15610  PrevDecl = nullptr;
15611  }
15612 
15613  if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15614  PrevDecl = nullptr;
15615 
15616  SourceLocation TSSL = D.getBeginLoc();
15617  MSPropertyDecl *NewPD =
15618  MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
15619  MSPropertyAttr.getPropertyDataGetter(),
15620  MSPropertyAttr.getPropertyDataSetter());
15621  ProcessDeclAttributes(TUScope, NewPD, D);
15622  NewPD->setAccess(AS);
15623 
15624  if (NewPD->isInvalidDecl())
15625  Record->setInvalidDecl();
15626 
15628  NewPD->setModulePrivate();
15629 
15630  if (NewPD->isInvalidDecl() && PrevDecl) {
15631  // Don't introduce NewFD into scope; there's already something
15632  // with the same name in the same scope.
15633  } else if (II) {
15634  PushOnScopeChains(NewPD, S);
15635  } else
15636  Record->addDecl(NewPD);
15637 
15638  return NewPD;
15639 }
QualType BuildStdInitializerList(QualType Element, SourceLocation Loc)
Looks for the std::initializer_list template and instantiates it with Element, or emits an error if i...
Abstract class used to diagnose incomplete types.
Definition: Sema.h:1510
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:78
bool isBaseInitializer() const
Determine whether this initializer is initializing a base class.
Definition: DeclCXX.h:2325
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
static NamespaceDecl * Create(ASTContext &C, DeclContext *DC, bool Inline, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, NamespaceDecl *PrevDecl)
Definition: DeclCXX.cpp:2584
NamespaceDecl * lookupStdExperimentalNamespace()
void setSourceOrder(int Pos)
Set the source order of this initializer.
Definition: DeclCXX.h:2439
Defines the clang::ASTContext interface.
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
void ActOnFinishDelayedMemberInitializers(Decl *Record)
static CXXDefaultInitExpr * Create(const ASTContext &Ctx, SourceLocation Loc, FieldDecl *Field)
Field is the non-static data member whose default initializer is used by this expression.
Definition: ExprCXX.h:1152
VariadicCallType
Definition: Sema.h:9462
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:465
bool isCallToStdMove() const
Definition: Expr.h:2645
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1583
static void collectUnexpandedParameterPacks(Sema &S, TemplateParameterList *Params, SmallVectorImpl< UnexpandedParameterPack > &Unexpanded)
ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK)
Definition: SemaExpr.cpp:16131
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition: DeclCXX.h:3201
SourceLocation getBeginLoc() const
Definition: ExprCXX.h:994
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
void setImplicit(bool I=true)
Definition: DeclBase.h:548
Represents a function declaration or definition.
Definition: Decl.h:1738
static StmtResult buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, const ExprBuilder &To, const ExprBuilder &From, bool CopyingBaseSubobject, bool Copying, unsigned Depth=0)
Builds a statement that copies/moves the given entity from From to To.
Name lookup found a set of overloaded functions that met the criteria.
Definition: Lookup.h:64
NamespaceDecl * getStdNamespace() const
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition: DeclSpec.h:2268
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
Expr * getInit() const
Get the initializer.
Definition: DeclCXX.h:2454
unsigned RefQualifierIsLValueRef
Whether the ref-qualifier (if any) is an lvalue reference.
Definition: DeclSpec.h:1265
void CheckConstructor(CXXConstructorDecl *Constructor)
CheckConstructor - Checks a fully-formed constructor for well-formedness, issuing any diagnostics req...
void setOrigin(CXXRecordDecl *Rec)
CXXMethodDecl * getMethod() const
Definition: Sema.h:1079
no exception specification
static bool checkMemberDecomposition(Sema &S, ArrayRef< BindingDecl *> Bindings, ValueDecl *Src, QualType DecompType, const CXXRecordDecl *OrigRD)
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:496
PtrTy get() const
Definition: Ownership.h:81
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T -> getSizeExpr()))
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2537
EvaluatedExprVisitor - This class visits &#39;Expr *&#39;s.
CanQualType VoidPtrTy
Definition: ASTContext.h:1044
QualType getPointeeType() const
Definition: Type.h:2550
A (possibly-)qualified type.
Definition: Type.h:638
ASTConsumer & Consumer
Definition: Sema.h:325
Simple class containing the result of Sema::CorrectTypo.
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition: Type.cpp:2101
base_class_range bases()
Definition: DeclCXX.h:823
bool isArrayType() const
Definition: Type.h:6345
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:2773
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition: Decl.h:2376
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:2553
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:817
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition: DeclSpec.h:1134
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition: Decl.cpp:2902
void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace)
ActOnFinishNamespaceDef - This callback is called after a namespace is exited.
capture_iterator capture_end() const
Retrieve an iterator pointing past the end of the sequence of lambda captures.
Definition: ExprCXX.cpp:1162
ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val)
Definition: SemaExpr.cpp:3197
SourceLocation StartLocation
The location of the first token that describes this unqualified-id, which will be the location of the...
Definition: DeclSpec.h:992
static unsigned NumImplicitMoveAssignmentOperatorsDeclared
The number of implicitly-declared move assignment operators for which declarations were built...
Definition: ASTContext.h:2820
SourceRange getSourceRange() const LLVM_READONLY
Retrieve the source range covering the entirety of this nested-name-specifier.
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition: DeclSpec.h:2179
static TypeAliasTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a function template node.
bool SetTypeQual(TQ T, SourceLocation Loc)
Definition: DeclSpec.cpp:891
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc...
Definition: Sema.h:3055
bool willHaveBody() const
True if this function will eventually have a body, once it&#39;s fully parsed.
Definition: Decl.h:2221
DeclarationName getCXXConstructorName(CanQualType Ty)
Returns the name of a C++ constructor for the given Type.
static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM, unsigned Quals, bool ConstRHS, Sema::TrivialABIHandling TAH, CXXMethodDecl **Selected)
Perform lookup for a special member of the specified kind, and determine whether it is trivial...
static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc, const CXXRecordDecl *RD, CXXCastPath &BasePath)
Find the base class to decompose in a built-in decomposition of a class type.
InClassInitStyle getInClassInitStyle() const
Get the kind of (C++11) default member initializer that this field has.
Definition: Decl.h:2707
const Expr * getInit(unsigned Init) const
Definition: Expr.h:4233
CanQualType Char32Ty
Definition: ASTContext.h:1024
The subobject is a base class.
void setLookupName(DeclarationName Name)
Sets the name to look up.
Definition: Lookup.h:246
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false)
Perform unqualified name lookup starting from a given scope.
static UsingPackDecl * Create(ASTContext &C, DeclContext *DC, NamedDecl *InstantiatedFrom, ArrayRef< NamedDecl *> UsingDecls)
Definition: DeclCXX.cpp:2763
static unsigned NumImplicitDefaultConstructors
The number of implicitly-declared default constructors.
Definition: ASTContext.h:2788
TypeLoc getNextTypeLoc() const
Get the next TypeLoc pointed by this TypeLoc, e.g for "int*" the TypeLoc is a PointerLoc and next Typ...
Definition: TypeLoc.h:168
Decl * Entity
The entity that is being synthesized.
Definition: Sema.h:7238
Expr *const * semantics_iterator
Definition: Expr.h:5365
static ClassTemplateDecl * LookupStdInitializerList(Sema &S, SourceLocation Loc)
Stmt - This represents one statement.
Definition: Stmt.h:66
IdentifierInfo * Identifier
When Kind == IK_Identifier, the parsed identifier, or when Kind == IK_UserLiteralId, the identifier suffix.
Definition: DeclSpec.h:962
CXXRecordDecl * getCurrentClass(Scope *S, const CXXScopeSpec *SS)
Get the class that is directly named by the current context.
Filter makeFilter()
Create a filter for this result set.
Definition: Lookup.h:671
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition: Decl.h:4289
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3355
CXXCatchStmt * getHandler(unsigned i)
Definition: StmtCXX.h:104
IfStmt - This represents an if/then/else.
Definition: Stmt.h:1687
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Definition: Type.cpp:505
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program...
Definition: Decl.cpp:2760
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:953
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type...
Definition: Type.h:4059
void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD)
Check a completed declaration of an implicit special member.
bool isElaboratedTypeSpecifier() const
Determine wither this type is a C++ elaborated-type-specifier.
Definition: Type.cpp:2631
An instance of this object exists for each enum constant that is defined.
Definition: Decl.h:2786
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:1937
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition: DeclCXX.h:838
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1020
void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method)
ActOnStartDelayedCXXMethodDeclaration - We have completed parsing a top-level (non-nested) C++ class...
static CharSourceRange getTokenRange(SourceRange R)
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:807
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2094
static unsigned NumImplicitMoveAssignmentOperators
The number of implicitly-declared move assignment operators.
Definition: ASTContext.h:2816
Decl * ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc, SourceLocation NamespcLoc, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *NamespcName, const ParsedAttributesView &AttrList)
bool isAscii() const
Definition: Expr.h:1685
bool isRecordType() const
Definition: Type.h:6369
static TemplateArgumentLoc getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T)
Expr * getBase() const
Definition: Expr.h:2767
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:189
DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D)
ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a C++ if/switch/while/for statem...
void erase()
Erase the last element returned from this iterator.
Definition: Lookup.h:643
static InitializedEntity InitializeMember(FieldDecl *Member, const InitializedEntity *Parent=nullptr, bool Implicit=false)
Create the initialization entity for a member subobject.
static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D)
Determine what kind of template specialization the given declaration is.
NamedDecl * BuildUsingDeclaration(Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList, bool IsInstantiation)
Builds a using declaration.
static InitializedEntity InitializeParameter(ASTContext &Context, const ParmVarDecl *Parm)
Create the initialization entity for a parameter.
void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, const CXXRecordDecl *RD)
Mark the exception specifications of all virtual member functions in the given class as needed...
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:1933
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type...
const Type * getTypeForDecl() const
Definition: Decl.h:2898
bool hasIrrelevantDestructor() const
Determine whether this class has a destructor which has no semantic effect.
Definition: DeclCXX.h:1514
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition: Sema.h:1308
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:87
void setRangeEnd(SourceLocation E)
Definition: Decl.h:1908
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:4002
bool needsOverloadResolutionForDestructor() const
Determine whether we need to eagerly declare a destructor for this class.
Definition: DeclCXX.h:1191
ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc)
BuildCallToMemberFunction - Build a call to a member function.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:410
bool isVirtual() const
Definition: DeclCXX.h:2086
static bool FindBaseInitializer(Sema &SemaRef, CXXRecordDecl *ClassDecl, QualType BaseType, const CXXBaseSpecifier *&DirectBaseSpec, const CXXBaseSpecifier *&VirtualBaseSpec)
Find the direct and/or virtual base specifiers that correspond to the given base type, for use in base initialization within a constructor.
void setArgPassingRestrictions(ArgPassingKind Kind)
Definition: Decl.h:3727
ComparisonCategoryType Kind
The Kind of the comparison category type.
bool isVirtual() const
Determines whether the base class is a virtual base class (or not).
Definition: DeclCXX.h:245
ThreadStorageClassSpecifier getTSCSpec() const
Definition: Decl.h:1029
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl, bool ConsiderCudaAttrs=true)
Opcode getOpcode() const
Definition: Expr.h:3322
StringRef P
bool isTemplateParamScope() const
isTemplateParamScope - Return true if this scope is a C++ template parameter scope.
Definition: Scope.h:376
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:828
void setPure(bool P=true)
Definition: Decl.cpp:2747
static QualType RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy)
void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD)
MarkVirtualMembersReferenced - Will mark all members of the given CXXRecordDecl referenced.
bool isOverrideSpecified() const
Definition: DeclSpec.h:2517
Not a friend object.
Definition: DeclBase.h:1095
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration, or NULL if there is no previous declaration.
Definition: DeclBase.h:953
NamedDecl * getDecl() const
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:6245
void AddDecl(Decl *D)
Definition: Scope.h:287
static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base)
Determine whether a direct base class is a virtual base class.
void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD)
Evaluate the implicit exception specification for a defaulted special member function.
A constructor named via a template-id.
static InitializationKind CreateDirect(SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
Create a direct initialization.
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
Definition: SemaExpr.cpp:4487
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined...
Definition: Decl.h:2763
static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, SourceLocation Loc, StringRef Trait, TemplateArgumentListInfo &Args, unsigned DiagID)
static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag)
Converts a TagTypeKind into an elaborated type keyword.
Definition: Type.cpp:2540
The base class of the type hierarchy.
Definition: Type.h:1407
static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, QualType SubType, bool ConstRHS, Sema::CXXSpecialMember CSM, TrivialSubobjectKind Kind, Sema::TrivialABIHandling TAH, bool Diagnose)
Check whether the special member selected for a given type would be trivial.
SourceLocation getBeginLoc() const
getBeginLoc - Retrieve the location of the first token.
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method)
ActOnFinishDelayedCXXMethodDeclaration - We have finished processing the delayed method declaration f...
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:1890
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
One instance of this struct is used for each type in a declarator that is parsed. ...
Definition: DeclSpec.h:1148
Declaration of a variable template.
static InitializationKind CreateDefault(SourceLocation InitLoc)
Create a default initialization.
Represent a C++ namespace.
Definition: Decl.h:515
static bool isNonlocalVariable(const Decl *D)
Determine whether the given declaration is a global variable or static data member.
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1262
static FixItHint CreateInsertionFromRange(SourceLocation InsertionLoc, CharSourceRange FromRange, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code from FromRange at a specific location...
Definition: Diagnostic.h:105
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.h:1169
SourceLocation getEndLoc() const LLVM_READONLY
static const char * getSpecifierName(DeclSpec::TST T, const PrintingPolicy &Policy)
Turn a type-specifier-type into a string like "_Bool" or "union".
Definition: DeclSpec.cpp:521
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclBase.h:414
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:133
bool hasTrivialMoveConstructor() const
Determine whether this class has a trivial move constructor (C++11 [class.copy]p12) ...
Definition: DeclCXX.h:1423
QualType withConst() const
Definition: Type.h:810
std::unique_ptr< CachedTokens > DefaultArgTokens
DefaultArgTokens - When the parameter&#39;s default argument cannot be parsed immediately (because it occ...
Definition: DeclSpec.h:1234
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:690
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition: Specifiers.h:98
const NestedNameSpecifier * Specifier
A container of type source information.
Definition: Decl.h:87
Floating point control options.
Definition: LangOptions.h:307
constexpr XRayInstrMask Function
Definition: XRayInstr.h:39
static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, TemplateArgumentListInfo &Args)
An overloaded operator name, e.g., operator+.
bool isDefined(const FunctionDecl *&Definition) const
Returns true if the function has a definition that does not need to be instantiated.
Definition: Decl.cpp:2720
TSCS getThreadStorageClassSpec() const
Definition: DeclSpec.h:452
bool needsImplicitMoveAssignment() const
Determine whether this class should get an implicit move assignment operator or if any existing speci...
Definition: DeclCXX.h:1161
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition: DeclCXX.h:2800
static InitializedEntity InitializeMemberFromDefaultMemberInitializer(FieldDecl *Member)
Create the initialization entity for a default member initializer.
bool hasNext() const
Definition: Lookup.h:628
Abstract base class used for diagnosing integer constant expression violations.
Definition: Sema.h:9977
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
unsigned getIdentifierNamespace() const
Definition: DeclBase.h:792
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2484
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition: Lookup.h:543
IdentifierInfo * getPropertyDataGetter() const
Definition: ParsedAttr.h:530
CanQualType WideCharTy
Definition: ASTContext.h:1020
bool implicitCopyAssignmentHasConstParam() const
Determine whether an implicit copy assignment operator for this type would have a parameter with a co...
Definition: DeclCXX.h:1124
bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param)
Instantiate or parse a C++ default argument expression as necessary.
Definition: SemaExpr.cpp:4652
float __ovld __cnfn distance(float p0, float p1)
Returns the distance between p0 and p1.
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse=true)
Mark a function referenced, and check whether it is odr-used (C++ [basic.def.odr]p2, C99 6.9p3)
Definition: SemaExpr.cpp:14615
bool needsOverloadResolutionForCopyConstructor() const
Determine whether we need to eagerly declare a defaulted copy constructor for this class...
Definition: DeclCXX.h:1008
size_t param_size() const
Definition: Decl.h:2278
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition: Decl.h:2714
SourceLocation getEndLoc() const
Get the end source location.
Definition: TypeLoc.cpp:227
bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S)
MergeCXXFunctionDecl - Merge two declarations of the same C++ function, once we already know that the...
SourceLocation getOverrideLoc() const
Definition: DeclSpec.h:2518
QualType getElementType() const
Definition: Type.h:2847
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3169
void CheckCXXDefaultArguments(FunctionDecl *FD)
CheckCXXDefaultArguments - Verify that the default arguments for a function declaration are well-form...
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition: DeclCXX.cpp:2356
RAII object to handle the state changes required to synthesize a function body.
Definition: Sema.h:762
IdentifierInfo * getPropertyDataSetter() const
Definition: ParsedAttr.h:536
NamedDecl * BuildUsingPackDecl(NamedDecl *InstantiatedFrom, ArrayRef< NamedDecl *> Expansions)
static InitializedEntity InitializeBase(ASTContext &Context, const CXXBaseSpecifier *Base, bool IsInheritedVirtualBase, const InitializedEntity *Parent=nullptr)
Create the initialization entity for a base class subobject.
Definition: SemaInit.cpp:3066
CXXMethodDecl * DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl)
Declare the implicit move assignment operator for the given class.
void ActOnFinishCXXNonNestedClass(Decl *D)
This file provides some common utility functions for processing Lambda related AST Constructs...
std::list< CXXBasePath >::iterator paths_iterator
static std::vector< ComparisonCategoryResult > getPossibleResultsForType(ComparisonCategoryType Type)
Return the list of results which are valid for the specified comparison category type.
void ActOnDefaultCtorInitializers(Decl *CDtorDecl)
DeclContext::lookup_result Decls
The set of declarations found inside this base class subobject.
bool isFunctionDeclarationContext() const
Return true if this declaration appears in a context where a function declarator would be a function ...
Definition: DeclSpec.h:2291
FriendDecl - Represents the declaration of a friend entity, which can be a function, a type, or a templated function or type.
Definition: DeclFriend.h:54
bool isInterface() const
Definition: Decl.h:3250
static CXXConstructExpr * Create(const ASTContext &Ctx, QualType Ty, SourceLocation Loc, CXXConstructorDecl *Ctor, bool Elidable, ArrayRef< Expr *> Args, bool HadMultipleCandidates, bool ListInitialization, bool StdInitListInitialization, bool ZeroInitialization, ConstructionKind ConstructKind, SourceRange ParenOrBraceRange)
Create a C++ construction expression.
Definition: ExprCXX.cpp:984
RAII object that enters a new expression evaluation context.
Definition: Sema.h:10853
void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record)
Represents a variable declaration or definition.
Definition: Decl.h:813
ActionResult< Stmt * > StmtResult
Definition: Ownership.h:268
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:25
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1765
QualType getReturnType() const
Definition: Decl.h:2302
DiagnosticsEngine & Diags
Definition: Sema.h:326
Wrapper for source info for member pointers.
Definition: TypeLoc.h:1232
unsigned getNumParams() const
Definition: Type.h:3888
bool isEnumeralType() const
Definition: Type.h:6373
void finishedDefaultedOrDeletedMember(CXXMethodDecl *MD)
Indicates that the declaration of a defaulted or deleted special member function is now complete...
Definition: DeclCXX.cpp:1285
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6748
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition: Decl.cpp:2621
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:2178
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
Extra information about a function prototype.
Definition: Type.h:3767
bool hasInheritedDefaultArg() const
Definition: Decl.h:1676
void clear()
Clear the base-paths results.
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:1997
TypeSpecifierType
Specifies the kind of type.
Definition: Specifiers.h:45
bool needsImplicitCopyAssignment() const
Determine whether this class needs an implicit copy assignment operator to be lazily declared...
Definition: DeclCXX.h:1112
static MSPropertyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName N, QualType T, TypeSourceInfo *TInfo, SourceLocation StartL, IdentifierInfo *Getter, IdentifierInfo *Setter)
Definition: DeclCXX.cpp:2915
The "__interface" keyword.
Definition: Type.h:5036
void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD)
Check that the C++ class annoated with "trivial_abi" satisfies all the conditions that are needed for...
RAII class that determines when any errors have occurred between the time the instance was created an...
Definition: Diagnostic.h:999
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:432
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:5349
SourceLocation getFinalLoc() const
Definition: DeclSpec.h:2522
bool field_empty() const
Definition: Decl.h:3792
bool isZeroLengthBitField(const ASTContext &Ctx) const
Is this a zero-length bit-field? Such bit-fields aren&#39;t really bit-fields at all and instead act as a...
Definition: Decl.cpp:3792
bool isAmbiguous() const
Definition: Lookup.h:290
NestedNameSpecifier * getCorrectionSpecifier() const
Gets the NestedNameSpecifier needed to use the typo correction.
DeclClass * getCorrectionDeclAs() const
reference front() const
Definition: DeclBase.h:1234
bool hasTrivialDefaultConstructor() const
Determine whether this class has a trivial default constructor (C++11 [class.ctor]p5).
Definition: DeclCXX.h:1363
TypeLoc getNamedTypeLoc() const
Definition: TypeLoc.h:1972
bool isInvalidDecl() const
Definition: DeclBase.h:542
Stmt * getThen()
Definition: Stmt.h:1774
Like System, but searched after the system directories.
static StmtResult buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, const ExprBuilder &ToB, const ExprBuilder &FromB)
When generating a defaulted copy or move assignment operator, if a field should be copied with __buil...
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:68
void setBegin(SourceLocation b)
static StringRef getTagTypeKindName(TagTypeKind Kind)
Definition: Type.h:5113
bool hasTypeSpecifier() const
Return true if any type-specifier has been found.
Definition: DeclSpec.h:609
static InitializationKind CreateDirectList(SourceLocation InitLoc)
bool isInterfaceLike() const
Definition: DeclCXX.cpp:1742
Describes how types, statements, expressions, and declarations should be printed. ...
Definition: PrettyPrinter.h:38
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition: Sema.h:7170
void DefineImplicitLambdaToFunctionPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv)
Define the "body" of the conversion from a lambda object to a function pointer.
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
bool hasMethodTypeQualifiers() const
Determine whether this method has qualifiers.
Definition: DeclSpec.h:1452
bool isStatic() const
Definition: DeclCXX.cpp:1872
bool hasDefinition() const
Definition: DeclCXX.h:776
static StringRef getResultString(ComparisonCategoryResult Kind)
Decl * ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, MultiTemplateParamsArg TemplateParams)
Handle a friend type declaration.
static AccessSpecDecl * Create(ASTContext &C, AccessSpecifier AS, DeclContext *DC, SourceLocation ASLoc, SourceLocation ColonLoc)
Definition: DeclCXX.h:163
Represents a parameter to a function.
Definition: Decl.h:1550
QualType CheckComparisonCategoryType(ComparisonCategoryType Kind, SourceLocation Loc)
Lookup the specified comparison category types in the standard library, an check the VarDecls possibl...
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition: Type.h:877
MutableArrayRef< ParmVarDecl * >::iterator param_iterator
Definition: Decl.h:2270
Defines the clang::Expr interface and subclasses for C++ expressions.
Parse and apply any fixits to the source.
void removeDecl(Decl *D)
Removes a declaration from this context.
Definition: DeclBase.cpp:1427
noexcept(expression), value-dependent
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:1952
void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old)
Merge the exception specifications of two variable declarations.
A reasonable base class for TypeLocs that correspond to types that are written as a type-specifier...
Definition: TypeLoc.h:507
CXXConstructorDecl * getTargetConstructor() const
When this constructor delegates to another, retrieve the target.
Definition: DeclCXX.cpp:2347
The collection of all-type qualifiers we support.
Definition: Type.h:141
bool isAnonymousStructOrUnion() const
Determines whether this field is a representative for an anonymous struct or union.
Definition: Decl.cpp:3777
bool isRecordingPaths() const
Whether we are recording paths.
ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false)
ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Definition: SemaExpr.cpp:5408
const FunctionDecl * isLocalClass() const
If the class is a local class [class.local], returns the enclosing function declaration.
Definition: DeclCXX.h:1647
void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitMoveConstructor - Checks for feasibility of defining this constructor as the move const...
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type. ...
Definition: Decl.cpp:3202
bool FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI)
Definition: SemaInternal.h:37
QualType CheckConstructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
CheckConstructorDeclarator - Called by ActOnDeclarator to check the well-formedness of the constructo...
static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T)
Determine whether the given type is an incomplete or zero-lenfgth array type.
void CheckDelayedMemberExceptionSpecs()
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:57
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:2124
SourceLocation getFriendSpecLoc() const
Definition: DeclSpec.h:722
const AstTypeMatcher< RecordType > recordType
Matches record types (e.g.
bool isRedeclaration() const
Definition: DeclSpec.h:2485
void ActOnMemInitializers(Decl *ConstructorDecl, SourceLocation ColonLoc, ArrayRef< CXXCtorInitializer *> MemInits, bool AnyErrors)
ActOnMemInitializers - Handle the member initializers for a constructor.
Represents a struct/union/class.
Definition: Decl.h:3593
bool hasTrivialCopyConstructorForCall() const
Definition: DeclCXX.h:1404
bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, InheritedConstructorInfo *ICI=nullptr, bool Diagnose=false)
Determine if a special member function should have a deleted definition when it is defaulted...
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
void LoadExternalVTableUses()
Load any externally-stored vtable uses.
bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename, const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, SourceLocation NameLoc)
Checks that the given nested-name qualifier used in a using decl in the current context is appropriat...
static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, unsigned I, QualType T)
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition: DeclCXX.h:1327
const TemplateArgumentList & getTemplateArgs() const
Retrieve the template arguments of the class template specialization.
Description of a constructor that was inherited from a base class.
Definition: DeclCXX.h:2458
static bool IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2)
Determine whether a using declaration considers the given declarations as "equivalent", e.g., if they are redeclarations of the same entity or are both typedefs of the same type.
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition: DeclSpec.h:986
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:298
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1148
FunctionType::ExtInfo ExtInfo
Definition: Type.h:3768
Represents a class template specialization, which refers to a class template with a given set of temp...
One of these records is kept for each identifier that is lexed.
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1022
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition: Lookup.h:74
unsigned getDepth() const
Retrieve the depth of the template parameter.
Decl * ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc, SourceLocation NamespaceLoc, SourceLocation IdentLoc, IdentifierInfo *Ident, SourceLocation LBrace, const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UsingDecl)
ActOnStartNamespaceDef - This is called at the start of a namespace definition.
static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext)
Determine whether a using statement is in a context where it will be apply in all contexts...
Decl * ActOnNamespaceAliasDef(Scope *CurScope, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *Ident)
void setRecordingPaths(bool RP)
Specify whether we should be recording paths or not.
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition: Decl.h:2774
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue=true)
Definition: SemaStmt.cpp:45
UnionParsedType ConversionFunctionId
When Kind == IK_ConversionFunctionId, the type that the conversion function names.
Definition: DeclSpec.h:970
void setUninstantiatedDefaultArg(Expr *arg)
Definition: Decl.cpp:2610
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:155
static unsigned NumImplicitMoveConstructorsDeclared
The number of implicitly-declared move constructors for which declarations were built.
Definition: ASTContext.h:2806
A C++ nested-name-specifier augmented with source location information.
bool isInline() const
Returns true if this is an inline namespace declaration.
Definition: Decl.h:576
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:7520
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:3895
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1187
SourceLocation getTypeSpecTypeLoc() const
Definition: DeclSpec.h:515
TypeSourceInfo * getTypeSourceInfo() const
Definition: TemplateBase.h:507
ImplicitInitializerKind
ImplicitInitializerKind - How an implicit base or member initializer should initialize its base or me...
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known...
bool defaultedDefaultConstructorIsConstexpr() const
Determine whether a defaulted default constructor for this class would be constexpr.
Definition: DeclCXX.h:1386
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:3774
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base)
Determine whether the type Derived is a C++ class that is derived from the type Base.
field_range fields() const
Definition: Decl.h:3784
BaseResult ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, ParsedAttributes &Attrs, bool Virtual, AccessSpecifier Access, ParsedType basetype, SourceLocation BaseLoc, SourceLocation EllipsisLoc)
ActOnBaseSpecifier - Parsed a base specifier.
static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, FieldDecl *Field, IndirectFieldDecl *Indirect=nullptr)
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon=QualType()) const
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:288
NameKind getNameKind() const
Determine what kind of name this is.
void checkExceptionSpecification(bool IsTopLevel, ExceptionSpecificationType EST, ArrayRef< ParsedType > DynamicExceptions, ArrayRef< SourceRange > DynamicExceptionRanges, Expr *NoexceptExpr, SmallVectorImpl< QualType > &Exceptions, FunctionProtoType::ExceptionSpecInfo &ESI)
Check the given exception-specification and update the exception specification information with the r...
UnionParsedTemplateTy TemplateName
When Kind == IK_DeductionGuideName, the parsed template-name.
Definition: DeclSpec.h:981
VarDecl * BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id)
Perform semantic analysis for the variable declaration that occurs within a C++ catch clause...
Represents a member of a struct/union/class.
Definition: Decl.h:2579
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
TypeSourceInfo * getTypeSourceInfo() const
Returns the declarator information for a base class or delegating initializer.
Definition: DeclCXX.h:2386
void removeConst()
Definition: Type.h:260
bool isAbstractType(SourceLocation Loc, QualType T)
static bool isIncrementDecrementOp(Opcode Op)
Definition: Expr.h:1969
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition: Lookup.h:231
bool isFunctionDefinition() const
Definition: DeclSpec.h:2462
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2127
SourceLocation getExprLoc() const LLVM_READONLY
Definition: Expr.h:2885
void setName(DeclarationName N)
setName - Sets the embedded declaration name.
bool isReferenceType() const
Definition: Type.h:6308
CXXRecordDecl * getStdBadAlloc() const
bool hasTrivialMoveAssignment() const
Determine whether this class has a trivial move assignment operator (C++11 [class.copy]p25)
Definition: DeclCXX.h:1463
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2002
InheritedConstructor getInheritedConstructor() const
Get the constructor that this inheriting constructor is based on.
Definition: DeclCXX.h:2679
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:32
static UnresolvedUsingTypenameDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, SourceLocation TypenameLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TargetNameLoc, DeclarationName TargetName, SourceLocation EllipsisLoc)
Definition: DeclCXX.cpp:2812
static void extendLeft(SourceRange &R, SourceRange Before)
bool hasUserDeclaredDestructor() const
Determine whether this class has a user-declared destructor.
Definition: DeclCXX.h:1179
DeclarationName getCXXDestructorName(CanQualType Ty)
Returns the name of a C++ destructor for the given Type.
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr)
Definition: Expr.cpp:406
ParmVarDecl * getParam(unsigned i) const
Definition: TypeLoc.h:1408
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:6511
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC...
Definition: DeclBase.h:1872
llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const
Make an APSInt of the appropriate width and signedness for the given Value and integer Type...
Definition: ASTContext.h:2633
LookupResultKind getResultKind() const
Definition: Lookup.h:310
bool DefineUsedVTables()
Define all of the vtables that have been used in this translation unit and reference any virtual memb...
void setParams(ArrayRef< ParmVarDecl *> NewParamInfo)
Definition: Decl.h:2293
Expr * getSubExpr()
Definition: Expr.h:3050
Represents an access specifier followed by colon &#39;:&#39;.
Definition: DeclCXX.h:132
void ClearStorageClassSpecs()
Definition: DeclSpec.h:465
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:739
void addShadowDecl(UsingShadowDecl *S)
Definition: DeclCXX.cpp:2711
ComparisonCategoryResult
An enumeration representing the possible results of a three-way comparison.
void CheckDeductionGuideDeclarator(Declarator &D, QualType &R, StorageClass &SC)
Check the validity of a declarator that we parsed for a deduction-guide.
SourceLocation getTemplateLoc() const
Definition: DeclTemplate.h:172
void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType)
FinalizeVarWithDestructor - Prepare for calling destructor on the constructed variable.
void CheckExtraCXXDefaultArguments(Declarator &D)
CheckExtraCXXDefaultArguments - Check for any extra default arguments in the declarator, which is not a function declaration or definition and therefore is not permitted to have default arguments.
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition: Lookup.h:56
A user-defined literal name, e.g., operator "" _i.
IdentifierTable & Idents
Definition: ASTContext.h:566
SpecialMemberOverloadResult - The overloading result for a special member function.
Definition: Sema.h:1063
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition: SemaExpr.cpp:100
void setImplicitCopyConstructorIsDeleted()
Set that we attempted to declare an implicit copy constructor, but overload resolution failed so we d...
Definition: DeclCXX.h:1061
An r-value expression (a pr-value in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:110
bool isInvalidType() const
Definition: DeclSpec.h:2443
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2262
UnsupportedSTLSelect
DeclClass * getAsSingle() const
Definition: Lookup.h:496
void FindHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl< CXXMethodDecl *> &OverloadedMethods)
Check if a method overloads virtual methods in a base class without overriding any.
bool isFinalSpelledSealed() const
Definition: DeclSpec.h:2521
TypeAliasDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
static ParenListExpr * Create(const ASTContext &Ctx, SourceLocation LParenLoc, ArrayRef< Expr *> Exprs, SourceLocation RParenLoc)
Create a paren list.
Definition: Expr.cpp:4051
static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, DeclStmt *DS, SourceLocation &Cxx1yLoc)
Check the given declaration statement is legal within a constexpr function body.
UnionParsedType DestructorName
When Kind == IK_DestructorName, the type referred to by the class-name.
Definition: DeclSpec.h:978
Describes an C or C++ initializer list.
Definition: Expr.h:4185
Represents a C++ using-declaration.
Definition: DeclCXX.h:3352
The argument of this type can be passed directly in registers.
Definition: Decl.h:3604
ArrayRef< BindingDecl * > bindings() const
Definition: DeclCXX.h:3875
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:934
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:2738
bool isCompleteType(SourceLocation Loc, QualType T)
Definition: Sema.h:1655
CXXRecordDecl * getAsRecordDecl() const
Retrieve the record declaration stored in this nested name specifier.
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to form a template specialization. ...
void resolveKind()
Resolves the result kind of the lookup, possibly hiding decls.
Definition: SemaLookup.cpp:469
NamespaceDecl * getOrCreateStdNamespace()
Retrieve the special "std" namespace, which may require us to implicitly define the namespace...
static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class)
Represents the results of name lookup.
Definition: Lookup.h:47
PtrTy get() const
Definition: Ownership.h:174
bool isDelegatingConstructor() const
Determine whether this constructor is a delegating constructor.
Definition: DeclCXX.h:2594
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
void CalledExpr(Expr *E)
Integrate an invoked expression into the collected data.
static InitializedEntity InitializeDelegation(QualType Type)
Create the initialization entity for a delegated constructor.
TagKind getTagKind() const
Definition: Decl.h:3243
Microsoft throw(...) extension.
A convenient class for passing around template argument information.
Definition: TemplateBase.h:555
void setParamDestroyedInCallee(bool V)
Definition: Decl.h:3735
AccessSpecifier getAccessSpecifier() const
Returns the access specifier for this base specifier.
Definition: DeclCXX.h:272
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition: Type.cpp:2205
CXXConstructorDecl * DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit move constructor for the given class.
bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl, AccessSpecifier access, QualType objectType)
Is the given special member function accessible for the purposes of deciding whether to define a spec...
bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method)
Check whether &#39;this&#39; shows up in the type of a static member function after the (naturally empty) cv-...
bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target, const LookupResult &PreviousDecls, UsingShadowDecl *&PrevShadow)
Determines whether to create a using shadow decl for a particular decl, given the set of decls existi...
bool needsOverloadResolutionForCopyAssignment() const
Determine whether we need to eagerly declare a defaulted copy assignment operator for this class...
Definition: DeclCXX.h:1118
void FilterAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true)
bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS)
Determine whether the identifier II is a typo for the name of the class type currently being defined...
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:3354
bool CheckConstexprFunctionDecl(const FunctionDecl *FD)
void DefineInheritingConstructor(SourceLocation UseLoc, CXXConstructorDecl *Constructor)
Define the specified inheriting constructor.
ArrayRef< NamedDecl * > chain() const
Definition: Decl.h:2847
An x-value expression is a reference to an object with independent storage but which can be "moved"...
Definition: Specifiers.h:119
A friend of a previously-undeclared entity.
Definition: DeclBase.h:1097
bool hasNonTrivialDestructorForCall() const
Definition: DeclCXX.h:1492
child_range children()
Definition: Stmt.cpp:237
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition: DeclSpec.h:2175
static bool BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, ImplicitInitializerKind ImplicitInitKind, FieldDecl *Field, IndirectFieldDecl *Indirect, CXXCtorInitializer *&CXXMemberInit)
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base=nullptr)
Perform reference-marking and odr-use handling for a DeclRefExpr.
Definition: SemaExpr.cpp:15736
StmtResult StmtError()
Definition: Ownership.h:284
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:654
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:1831
static void NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, const QualType &Type)
Recursively add the bases of Type. Don&#39;t add Type itself.
semantics_iterator semantics_end()
Definition: Expr.h:5373
void ActOnBaseSpecifiers(Decl *ClassDecl, MutableArrayRef< CXXBaseSpecifier *> Bases)
ActOnBaseSpecifiers - Attach the given base specifiers to the class, after checking whether there are...
Represents a declaration of a type.
Definition: Decl.h:2874
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3287
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:6142
LangAS getAddressSpace() const
Definition: Type.h:352
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition: Sema.h:7235
static CompoundStmt * Create(const ASTContext &C, ArrayRef< Stmt *> Stmts, SourceLocation LB, SourceLocation RB)
Definition: Stmt.cpp:332
void CheckDelegatingCtorCycles()
QualType getExceptionObjectType(QualType T) const
QualType CheckDestructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
CheckDestructorDeclarator - Called by ActOnDeclarator to check the well-formednes of the destructor d...
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition: Ownership.h:281
bool isRValueReferenceType() const
Definition: Type.h:6316
static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, SourceLocation CurrentLocation)
Check if we&#39;re implicitly defining a move assignment operator for a class with virtual bases...
bool isNull() const
Definition: TypeLoc.h:119
child_range children()
Definition: Expr.h:4368
void setExceptionVariable(bool EV)
Definition: Decl.h:1310
The argument of this type cannot be passed directly in registers.
Definition: Decl.h:3618
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition: Decl.h:1382
ActionResult< ParsedType > TypeResult
Definition: Ownership.h:269
DeclContextLookupResult slice(size_t N) const
Definition: DeclBase.h:1239
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition: DeclCXX.h:1196
CanQualType LongDoubleTy
Definition: ASTContext.h:1028
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence...
Definition: SemaInit.cpp:7284
bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc)
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:6072
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:728
field_iterator field_begin() const
Definition: Decl.cpp:4145
param_type_iterator param_type_begin() const
Definition: Type.h:4034
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1158
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition: Decl.h:1660
CXXBaseSpecifier * CheckBaseSpecifier(CXXRecordDecl *Class, SourceRange SpecifierRange, bool Virtual, AccessSpecifier Access, TypeSourceInfo *TInfo, SourceLocation EllipsisLoc)
ActOnBaseSpecifier - Parsed a base specifier.
void setTrivial(bool IT)
Definition: Decl.h:2027
ExprResult ActOnCXXThis(SourceLocation loc)
bool isAnyMemberInitializer() const
Definition: DeclCXX.h:2333
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:63
static unsigned NumImplicitDefaultConstructorsDeclared
The number of implicitly-declared default constructors for which declarations were built...
Definition: ASTContext.h:2792
void setNumCtorInitializers(unsigned numCtorInitializers)
Definition: DeclCXX.h:2575
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC)...
Definition: DeclBase.h:821
FieldDecl * getAnyMember() const
Definition: DeclCXX.h:2398
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1649
Preprocessor & PP
Definition: Sema.h:323
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1478
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition: Decl.cpp:1918
const LangOptions & getLangOpts() const
Definition: Sema.h:1231
static NamespaceAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamedDecl *Namespace)
Definition: DeclCXX.cpp:2639
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value &#39;V&#39; and type &#39;type&#39;.
Definition: Expr.cpp:792
TemplateArgumentLoc getArgLoc(unsigned i) const
Definition: TypeLoc.h:1592
void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor)
Build an exception spec for destructors that don&#39;t have one.
bool isInstance() const
Definition: DeclCXX.h:2069
SourceLocation getConstSpecLoc() const
Definition: DeclSpec.h:548
bool isTypeDependent() const
isTypeDependent - Determines whether this expression is type-dependent (C++ [temp.dep.expr]), which means that its type could change from one template instantiation to the next.
Definition: Expr.h:167
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition: DeclSpec.h:1869
static bool findCircularInheritance(const CXXRecordDecl *Class, const CXXRecordDecl *Current)
Determine whether the given class is a base class of the given class, including looking at dependent ...
const TemplateArgument * data() const
Retrieve a pointer to the template argument list.
Definition: DeclTemplate.h:273
An ordinary object is located at an address in memory.
Definition: Specifiers.h:126
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition: DeclCXX.cpp:1697
Decl * ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, Expr *LangStr, SourceLocation LBraceLoc)
ActOnStartLinkageSpecification - Parsed the beginning of a C++ linkage specification, including the language and (if present) the &#39;{&#39;.
Represents an ObjC class declaration.
Definition: DeclObjC.h:1172
FieldDecl * getMember() const
If this is a member initializer, returns the declaration of the non-static data member being initiali...
Definition: DeclCXX.h:2392
Represents a linkage specification.
Definition: DeclCXX.h:2826
ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, ActOnMemberAccessExtraArgs *ExtraArgs=nullptr)
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition: Lookup.h:415
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:3063
bool containsUnexpandedParameterPack() const
Determine whether this name contains an unexpanded parameter pack.
bool hasConstexprDefaultConstructor() const
Determine whether this class has a constexpr default constructor.
Definition: DeclCXX.h:1392
CXXRecordDecl * getTemplatedDecl() const
Get the underlying class declarations of the template.
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclSpec.h:507
bool isAbstract() const
Determine whether this class has a pure virtual function.
Definition: DeclCXX.h:1344
void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:2784
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Definition: CanonicalType.h:84
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, bool Overloaded, UnresolvedSetIterator Begin, UnresolvedSetIterator End)
Definition: ExprCXX.cpp:325
FunctionDecl * SourceDecl
The function whose exception specification this is, for EST_Unevaluated and EST_Uninstantiated.
Definition: Type.h:3753
void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init)
Check that the lifetime of the initializer (and its subobjects) is sufficient for initializing the en...
Definition: SemaInit.cpp:6918
A binding in a decomposition declaration.
Definition: DeclCXX.h:3795
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
Qualifiers getTypeQuals() const
Definition: Type.h:4015
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context...
Definition: DeclSpec.cpp:143
bool hasConst() const
Definition: Type.h:258
init_iterator init_begin()
Retrieve an iterator to the first initializer.
Definition: DeclCXX.h:2533
IdentifierInfo * getIdentifier() const
Definition: DeclSpec.h:2127
void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var)
Mark a variable referenced, and check whether it is odr-used (C++ [basic.def.odr]p2, C99 6.9p3).
Definition: SemaExpr.cpp:15697
Ordinary names.
Definition: DeclBase.h:145
unsigned getLength() const
Efficiently return the length of this identifier info.
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:870
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location...
static TemplateArgumentLoc getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, uint64_t I)
ArgPassingKind getArgPassingRestrictions() const
Definition: Decl.h:3723
bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, TrivialABIHandling TAH=TAH_IgnoreTrivialABI, bool Diagnose=false)
Determine whether a defaulted or deleted special member function is trivial, as specified in C++11 [c...
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition: Decl.h:3666
param_iterator param_begin()
Definition: Decl.h:2274
Represents the this expression in C++.
Definition: ExprCXX.h:976
UsingShadowDecl * BuildUsingShadowDecl(Scope *S, UsingDecl *UD, NamedDecl *Target, UsingShadowDecl *PrevDecl)
Builds a shadow declaration corresponding to a &#39;using&#39; declaration.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: ExprCXX.h:1857
static bool isValidUDSuffix(const LangOptions &LangOpts, StringRef Suffix)
Determine whether a suffix is a valid ud-suffix.
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1595
Class that aids in the construction of nested-name-specifiers along with source-location information ...
ExtInfo withCallingConv(CallingConv cc) const
Definition: Type.h:3571
static StmtResult buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, const ExprBuilder &To, const ExprBuilder &From, bool CopyingBaseSubobject, bool Copying)
SourceLocation LAngleLoc
The location of the &#39;<&#39; before the template argument list.
void removeInClassInitializer()
Remove the C++11 in-class initializer from this member.
Definition: Decl.h:2740
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:3455
static bool canPassInRegisters(Sema &S, CXXRecordDecl *D, TargetInfo::CallingConvKind CCK)
Determine whether a type is permitted to be passed or returned in registers, per C++ [class...
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:1235
static bool checkArrayDecomposition(Sema &S, ArrayRef< BindingDecl *> Bindings, ValueDecl *Src, QualType DecompType, const ConstantArrayType *CAT)
bool isFinalSpecified() const
Definition: DeclSpec.h:2520
void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl)
ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an initializer for the declaratio...
CXXSpecialMember
Kinds of C++ special members.
Definition: Sema.h:1167
NodeId Parent
Definition: ASTDiff.cpp:192
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition: Scope.h:218
QualType CheckTemplateIdType(TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs)
MemInitResult BuildMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, Expr *Init, SourceLocation EllipsisLoc)
Handle a C++ member initializer.
CXXConstructorDecl * findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor, ConstructorUsingShadowDecl *DerivedShadow)
Given a derived-class using shadow declaration for a constructor and the correspnding base class cons...
void setBases(CXXBaseSpecifier const *const *Bases, unsigned NumBases)
Sets the base classes of this struct or class.
Definition: DeclCXX.cpp:185
bool isDeclspecPropertyAttribute() const
Is this the Microsoft __declspec(property) attribute?
Definition: ParsedAttr.h:394
bool hasAttr() const
Definition: DeclBase.h:531
CXXConstructorDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2684
bool hasUserProvidedDefaultConstructor() const
Whether this class has a user-provided default constructor per C++11.
Definition: DeclCXX.h:989
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:3582
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition: DeclSpec.h:1861
bool isTriviallyCopyable() const
Determine whether this class is considered trivially copyable per (C++11 [class]p6).
Definition: DeclCXX.cpp:533
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:278
StringRef getString() const
Definition: Expr.h:1649
enum clang::DeclaratorChunk::@215 Kind
Represents the declaration of a typedef-name via a C++11 alias-declaration.
Definition: Decl.h:3038
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1241
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1613
SourceLocation getUnalignedSpecLoc() const
Definition: DeclSpec.h:552
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3687
virtual CallingConvKind getCallingConvKind(bool ClangABICompat4) const
Definition: TargetInfo.cpp:399
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition: DeclSpec.cpp:119
bool isDynamicClass() const
Definition: DeclCXX.h:789
void ClearConstexprSpec()
Definition: DeclSpec.h:730
void setImplicitlyInline(bool I=true)
Flag that this function is implicitly inline.
Definition: Decl.h:2351
ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
CreateBuiltinBinOp - Creates a new built-in binary operation with operator Opc at location TokLoc...
Definition: SemaExpr.cpp:12242
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:1137
void ActOnFinishCXXMemberDecls()
Perform any semantic analysis which needs to be delayed until all pending class member declarations h...
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any...
Definition: Decl.cpp:3300
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition: ExprCXX.h:1334
void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl)
Defines an implicitly-declared copy assignment operator.
static unsigned NumImplicitCopyConstructors
The number of implicitly-declared copy constructors.
Definition: ASTContext.h:2795
bool isDeclarationOfFunction() const
Determine whether the declaration that will be produced from this declaration will be a function...
Definition: DeclSpec.cpp:313
A RAII object to enter scope of a compound statement.
Definition: Sema.h:3715
bool isMoreQualifiedThan(QualType Other) const
Determine whether this type is more qualified than the other given type, requiring exact equality for...
Definition: Type.h:6216
bool isStdInitializerList(QualType Ty, QualType *Element)
Tests whether Ty is an instance of std::initializer_list and, if it is and Element is not NULL...
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition: DeclCXX.cpp:1627
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:689
SourceRange getLocalSourceRange() const
Get the local source range.
Definition: TypeLoc.h:157
static StringRef getCategoryString(ComparisonCategoryType Kind)
static Sema::ImplicitExceptionSpecification ComputeDefaultedSpecialMemberExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, Sema::InheritedConstructorInfo *ICI)
bool isDelegatingInitializer() const
Determine whether this initializer is creating a delegating constructor.
Definition: DeclCXX.h:2353
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat)
Definition: Expr.cpp:1844
DeclSpec * MethodQualifiers
DeclSpec for the function with the qualifier related info.
Definition: DeclSpec.h:1316
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:569
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition: DeclSpec.h:1288
llvm::FoldingSet< SpecialMemberOverloadResultEntry > SpecialMemberCache
A cache of special member function overload resolution results for C++ records.
Definition: Sema.h:1097
bool hasTrivialMoveConstructorForCall() const
Definition: DeclCXX.h:1428
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:6147
void NoteHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl< CXXMethodDecl *> &OverloadedMethods)
bool mayHaveDecompositionDeclarator() const
Return true if the context permits a C++17 decomposition declarator.
Definition: DeclSpec.h:2012
static EmptyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition: Decl.cpp:4616
A conversion function name, e.g., operator int.
SourceRange getRange() const
Definition: DeclSpec.h:68
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:179
bool isInlineSpecified() const
Definition: Decl.h:1367
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location, which defaults to the empty location.
static StaticAssertDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StaticAssertLoc, Expr *AssertExpr, StringLiteral *Message, SourceLocation RParenLoc, bool Failed)
Definition: DeclCXX.cpp:2833
bool isLiteral() const
Determine whether this class is a literal type.
Definition: DeclCXX.h:1566
void setInClassInitializer(Expr *Init)
Set the C++11 in-class initializer for this member.
Definition: Decl.h:2731
const CXXRecordDecl * getParent() const
Returns the parent of this using shadow declaration, which is the class in which this is declared...
Definition: DeclCXX.h:3296
void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param)
This is used to implement the constant expression evaluation part of the attribute enable_if extensio...
MemInitResult BuildMemberInitializer(ValueDecl *Member, Expr *Init, SourceLocation IdLoc)
TST getTypeSpecType() const
Definition: DeclSpec.h:483
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclCXX.h:236
static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp)
Diagnose an implicit copy operation for a class which is odr-used, but which is deprecated because th...
bool hasKeyFunctions() const
Does this ABI use key functions? If so, class data such as the vtable is emitted with strong linkage ...
Definition: TargetCXXABI.h:227
bool hasInheritedConstructor() const
Determine whether this class has a using-declaration that names a user-declared base class constructo...
Definition: DeclCXX.h:1526
static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, unsigned FieldQuals, bool ConstRHS)
Look up the special member function that would be called by a special member function for a subobject...
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition: Expr.cpp:3101
static CXXDestructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool isInline, bool isImplicitlyDeclared)
Definition: DeclCXX.cpp:2465
llvm::PointerIntPair< CXXRecordDecl *, 3, CXXSpecialMember > SpecialMemberDecl
Definition: Sema.h:1178
bool isMsStruct(const ASTContext &C) const
Get whether or not this is an ms_struct which can be turned on with an attribute, pragma...
Definition: Decl.cpp:4162
bool isUsualDeallocationFunction(const CXXMethodDecl *FD)
void setTrivialForCall(bool IT)
Definition: Decl.h:2030
static bool checkComplexDecomposition(Sema &S, ArrayRef< BindingDecl *> Bindings, ValueDecl *Src, QualType DecompType, const ComplexType *CT)
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:190
static bool checkArrayLikeDecomposition(Sema &S, ArrayRef< BindingDecl *> Bindings, ValueDecl *Src, QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType)
Allows QualTypes to be sorted and hence used in maps and sets.
Decl * ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, Expr *AssertMessageExpr, SourceLocation RParenLoc)
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:432
QualType getElementType() const
Definition: Type.h:2490
bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method)
Whether this&#39; shows up in the exception specification of a static member function.
bool isInlineSpecified() const
Determine whether the "inline" keyword was specified for this function.
Definition: Decl.h:2342
Represents a shadow constructor declaration introduced into a class by a C++11 using-declaration that...
Definition: DeclCXX.h:3240
bool isDependentType() const
Whether this declaration declares a type that is dependent, i.e., a type that somehow depends on temp...
Definition: Decl.h:3220
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:637
This represents one expression.
Definition: Expr.h:106
bool isCopyOrMoveConstructor(unsigned &TypeQuals) const
Determine whether this is a copy or move constructor.
Definition: DeclCXX.cpp:2376
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier that qualifies the name, with source-location information.
Definition: DeclCXX.h:3392
StringRef getKindName() const
Definition: Decl.h:3239
QualType getPointeeType() const
Definition: Type.h:2694
void DefineImplicitCopyConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitCopyConstructor - Checks for feasibility of defining this constructor as the copy const...
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:107
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:2689
bool isDefaulted() const
Whether this function is defaulted per C++0x.
Definition: Decl.h:2034
llvm::StringRef getAsString(SyncScope S)
Definition: SyncScope.h:51
bool isDeclScope(Decl *D)
isDeclScope - Return true if this is the scope that the specified decl is declared in...
Definition: Scope.h:321
Helper class that collects exception specifications for implicitly-declared special member functions...
Definition: Sema.h:4751
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
static void DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef, const CXXConstructorDecl *Constructor, ArrayRef< CXXCtorInitializer *> Inits)
bool isDecompositionDeclarator() const
Return whether this declarator is a decomposition declarator.
Definition: DeclSpec.h:2123
void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath)
StateNode * Previous
Declaration of a template type parameter.
unsigned getIndex() const
Definition: Type.h:4566
DeclContext * getEntity() const
Definition: Scope.h:325
bool defaultedMoveConstructorIsDeleted() const
true if a defaulted move constructor for this class would be deleted.
Definition: DeclCXX.h:921
DeclarationNameInfo getNameInfo() const
Definition: DeclCXX.h:3399
void setHideTags(bool Hide)
Sets whether tag declarations should be hidden by non-tag declarations during resolution.
Definition: Lookup.h:286
This file defines the classes used to store parsed information about declaration-specifiers and decla...
IsTupleLike
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:6811
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition: Type.h:5050
void getFinalOverriders(CXXFinalOverriderMap &FinaOverriders) const
Retrieve the final overriders for each virtual member function in the class hierarchy where this clas...
SourceLocation getBeginLoc() const
Retrieve the location of the beginning of this nested-name-specifier.
void setRBraceLoc(SourceLocation L)
Definition: Decl.h:621
Inits[]
Definition: OpenMPClause.h:151
static bool checkVectorDecomposition(Sema &S, ArrayRef< BindingDecl *> Bindings, ValueDecl *Src, QualType DecompType, const VectorType *VT)
static InitializedEntity InitializeVariable(VarDecl *Var)
Create the initialization entity for a variable.
OpaquePtr< T > get() const
Definition: Ownership.h:105
static UnresolvedUsingValueDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, SourceLocation EllipsisLoc)
Definition: DeclCXX.cpp:2784
SourceLocation getLocation() const
Definition: ExprCXX.h:991
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:87
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2706
void freeParams()
Reset the parameter list to having zero parameters.
Definition: DeclSpec.h:1348
void setInit(Expr *I)
Definition: Decl.cpp:2205
Expr * getCallee()
Definition: Expr.h:2514
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
std::string getAsString() const
Retrieve the human-readable string for this name.
unsigned getNumInits() const
Definition: Expr.h:4215
static unsigned NumImplicitMoveConstructors
The number of implicitly-declared move constructors.
Definition: ASTContext.h:2802
AccessResult CheckStructuredBindingMemberAccess(SourceLocation UseLoc, CXXRecordDecl *DecomposedClass, DeclAccessPair Field)
Checks implicit access to a member in a structured binding.
SourceLocation getVolatileSpecLoc() const
Definition: DeclSpec.h:550
SourceLocation getThreadStorageClassSpecLoc() const
Definition: DeclSpec.h:461
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:547
const CXXRecordDecl * getTemplateInstantiationPattern() const
Retrieve the record declaration from which this record could be instantiated.
Definition: DeclCXX.cpp:1652
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:3475
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl...
void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir)
void setRBraceLoc(SourceLocation L)
Definition: DeclCXX.h:2877
Defines the clang::Preprocessor interface.
bool CheckInheritingConstructorUsingDecl(UsingDecl *UD)
Additional checks for a using declaration referring to a constructor name.
bool hasUserDeclaredMoveAssignment() const
Determine whether this class has had a move assignment declared by the user.
Definition: DeclCXX.h:1139
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, bool AllowFold=true)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
Definition: SemaExpr.cpp:14220
field_iterator field_end() const
Definition: Decl.h:3787
ClassTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD)
overridden_method_range overridden_methods() const
Definition: DeclCXX.cpp:2170
bool isLocalExternDecl()
Determine whether this is a block-scope declaration with linkage.
Definition: DeclBase.h:1053
bool isFileContext() const
Definition: DeclBase.h:1818
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:72
DeclContext * getDeclContext()
Definition: DeclBase.h:427
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:769
bool isConstexprSpecified() const
Definition: DeclSpec.h:727
A parsed C++17 decomposition declarator of the form &#39;[&#39; identifier-list &#39;]&#39;.
Definition: DeclSpec.h:1664
ExprResult BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, TypeSourceInfo *Ty, Expr *E, SourceRange AngleBrackets, SourceRange Parens)
Definition: SemaCast.cpp:258
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition: Type.cpp:2527
void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc, Expr *Init)
This is invoked after parsing an in-class initializer for a non-static C++ class member, and after instantiating an in-class initializer in a class template.
bool hasAnyDependentBases() const
Determine whether this class has any dependent base classes which are not the current instantiation...
Definition: DeclCXX.cpp:526
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
Decl * ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList, SourceLocation SemiLoc)
Handle a C++11 empty-declaration and attribute-declaration.
CXXTryStmt - A C++ try block, including all handlers.
Definition: StmtCXX.h:65
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:2331
static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD, SourceLocation DefaultLoc)
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition: DeclBase.h:2422
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack...
Definition: DeclBase.cpp:201
void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param)
ActOnDelayedCXXMethodParameter - We&#39;ve already started a delayed C++ method declaration.
Represents a C++ template name within the type system.
Definition: TemplateName.h:179
bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, SourceLocation ColonLoc, const ParsedAttributesView &Attrs)
ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
bool needsImplicitDestructor() const
Determine whether this class needs an implicit destructor to be lazily declared.
Definition: DeclCXX.h:1185
bool RequireCompleteType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:7603
SourceLocation getStorageClassSpecLoc() const
Definition: DeclSpec.h:460
Defines the clang::TypeLoc interface and its subclasses.
int Depth
Definition: ASTDiff.cpp:191
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition: DeclSpec.h:1016
void DiscardCleanupsInEvaluationContext()
Definition: SemaExpr.cpp:14538
The argument of this type cannot be passed directly in registers.
Definition: Decl.h:3613
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn&#39;t...
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined...
Definition: DeclBase.h:614
void propagateDLLAttrToBaseClassTemplate(CXXRecordDecl *Class, Attr *ClassAttr, ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc)
Perform propagation of DLL attributes from a derived class to a templated base class for MS compatibi...
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition: DeclCXX.h:1337
bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const
Determine whether the result of this expression is a temporary object of the given class type...
Definition: Expr.cpp:2800
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition: Decl.cpp:2695
void setInheritConstructors(bool Inherit=true)
Set that this base class&#39;s constructors should be inherited.
Definition: DeclCXX.h:258
bool isInvalid() const
QualType getType() const
Definition: Expr.h:128
bool isFunctionOrMethod() const
Definition: DeclBase.h:1800
static bool isPotentialConstantExpr(const FunctionDecl *FD, SmallVectorImpl< PartialDiagnosticAt > &Diags)
isPotentialConstantExpr - Return true if this function&#39;s definition might be usable in a constant exp...
StorageClass
Storage classes.
Definition: Specifiers.h:206
bool hasNonTrivialDestructor() const
Determine whether this class has a non-trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1488
void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl)
Defines an implicitly-declared move assignment operator.
void CheckCompletedCXXClass(CXXRecordDecl *Record)
Perform semantic checks on a class definition that has been completing, introducing implicitly-declar...
Qualifiers getTypeQualifiers() const
Definition: DeclCXX.h:2188
bool isIdentifier() const
Predicate functions for querying what type of name this is.
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition: Lookup.h:297
InClassInitStyle
In-class initialization styles for non-static data members.
Definition: Specifiers.h:229
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
Declaration of an alias template.
static unsigned getRecordDiagFromTagKind(TagTypeKind Tag)
Get diagnostic select index for tag kind for record diagnostic message.
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1752
static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM, bool ConstArg, Sema::TrivialABIHandling TAH, bool Diagnose)
Check whether the members of a class type allow a special member to be trivial.
A boolean condition, from &#39;if&#39;, &#39;while&#39;, &#39;for&#39;, or &#39;do&#39;.
void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc)
static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, unsigned Quals, bool ConstRHS, CXXConstructorDecl *InheritedCtor=nullptr, Sema::InheritedConstructorInfo *Inherited=nullptr)
Is the special member function which would be selected to perform the specified operation on the spec...
QualType getRecordType(const RecordDecl *Decl) const
bool isInvalid() const
Definition: Ownership.h:170
SourceLocation getEnd() const
UnaryOperator - This represents the unary-expression&#39;s (except sizeof and alignof), the postinc/postdec operators from postfix-expression, and various extensions.
Definition: Expr.h:1896
void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method)
Integrate another called method into the collected data.
CXXMethodDecl * getMethodDecl() const
Retrieves the declaration of the called method.
Definition: ExprCXX.cpp:652
void setHasTrivialSpecialMemberForCall()
Definition: DeclCXX.h:1496
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1380
bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a literal type.
Definition: SemaType.cpp:7953
Represents a GCC generic vector type.
Definition: Type.h:3168
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:2720
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1078
bool isFriendSpecified() const
Definition: DeclSpec.h:721
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:6688
void addContextNote(SourceLocation UseLoc)
Definition: Sema.h:779
bool hasTrivialCopyConstructor() const
Determine whether this class has a trivial copy constructor (C++ [class.copy]p6, C++11 [class...
Definition: DeclCXX.h:1400
void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl)
ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an initializer for the declaration ...
void setOperatorDelete(FunctionDecl *OD, Expr *ThisArg)
Definition: DeclCXX.cpp:2477
ValueDecl * getDecl()
Definition: Expr.h:1114
Represents a C++ deduction guide declaration.
Definition: DeclCXX.h:1988
bool needsImplicitDefaultConstructor() const
Determine if we need to declare a default constructor for this class.
Definition: DeclCXX.h:974
bool isUsable() const
Definition: Ownership.h:171
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2768
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1396
The result type of a method or function.
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:152
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2026
bool isUnionType() const
Definition: Type.cpp:475
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2011
static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl< const void *> &IdealInits)
bool isNull() const
Return true if this QualType doesn&#39;t point to a type yet.
Definition: Type.h:703
bool hasNonTrivialMoveAssignment() const
Determine whether this class has a non-trivial move assignment operator (C++11 [class.copy]p25)
Definition: DeclCXX.h:1470
bool isProvablyNotDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is provably not derived from the type Base.
void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM)
Diagnose why the specified class does not have a trivial special member of the given kind...
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition: Specifiers.h:170
bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New, const CXXMethodDecl *Old)
The triviality of a method affected by "trivial_abi".
Definition: Sema.h:2294
static bool CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, SmallVectorImpl< SourceLocation > &ReturnStmts, SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc)
Check the provided statement is allowed in a constexpr function definition.
void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitDefaultConstructor - Checks for feasibility of defining this constructor as the default...
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:236
TypeLoc getReturnLoc() const
Definition: TypeLoc.h:1411
static bool RefersToRValueRef(Expr *MemRef)
bool hasValidIntValue() const
True iff we&#39;ve successfully evaluated the variable as a constant expression and extracted its integer...
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so...
Definition: DeclBase.h:1104
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:301
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:6105
static InitializationKind CreateCopy(SourceLocation InitLoc, SourceLocation EqualLoc, bool AllowExplicitConvs=false)
Create a copy initialization.
bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body)
Check the body for the given constexpr function declaration only contains the permitted types of stat...
#define CheckPolymorphic(Type)
CanQualType getCanonicalTypeUnqualified() const
SourceLocation getRefQualifierLoc() const
Retrieve the location of the ref-qualifier, if any.
Definition: DeclSpec.h:1416
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:6131
bool hasGroupingParens() const
Definition: DeclSpec.h:2448
void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow)
Hides a using shadow declaration.
bool hasTrailingReturn() const
Whether this function prototype has a trailing return type.
Definition: Type.h:4013
RecordDecl * getDecl() const
Definition: Type.h:4380
bool hasVariantMembers() const
Determine whether this class has any variant members.
Definition: DeclCXX.h:1359
noexcept(expression), evals to &#39;false&#39;
NestedNameSpecifier * getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:76
bool isInjectedClassName() const
Determines whether this declaration represents the injected class name.
Definition: Decl.cpp:4126
unsigned size_overridden_methods() const
Definition: DeclCXX.cpp:2164
static void SearchForReturnInStmt(Sema &Self, Stmt *S)
Wrapper for source info for arrays.
Definition: TypeLoc.h:1460
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
static bool DiagnoseUnexpandedParameterPacks(Sema &S, TemplateTemplateParmDecl *TTP)
Check for unexpanded parameter packs within the template parameters of a template template parameter...
void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class)
ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, CXXConstructorDecl *Constructor, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, unsigned ConstructKind, SourceRange ParenRange)
BuildCXXConstructExpr - Creates a complete call to a constructor, including handling of its default a...
bool containsUnexpandedParameterPack() const
Whether this nested-name-specifier contains an unexpanded parameter pack (for C++11 variadic template...
Decl::Kind getDeclKind() const
Definition: DeclBase.h:1745
void ActOnStartCXXInClassMemberInitializer()
Enter a new C++ default initializer scope.
static bool CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, const FunctionDecl *FnDecl)
UnqualifiedIdKind Kind
Describes the kind of unqualified-id parsed.
Definition: DeclSpec.h:941
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class...
Definition: Expr.h:945
static unsigned NumImplicitDestructorsDeclared
The number of implicitly-declared destructors for which declarations were built.
Definition: ASTContext.h:2827
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:1785
void pushCodeSynthesisContext(CodeSynthesisContext Ctx)
We are declaring an implicit special member function.
Definition: Sema.h:7218
CXXSpecialMember SpecialMember
The special member being declared or defined.
Definition: Sema.h:7256
CanQualType BuiltinFnTy
Definition: ASTContext.h:1046
The "struct" keyword.
Definition: Type.h:5033
Kind
static CXXConstructorDecl * findUserDeclaredCtor(CXXRecordDecl *RD)
Represents a call to an inherited base class constructor from an inheriting constructor.
Definition: ExprCXX.h:1448
ActionResult - This structure is used while parsing/acting on expressions, stmts, etc...
Definition: Ownership.h:157
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:3743
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:5299
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType, TagDecl *OwnedTagDecl=nullptr) const
TypeLoc IgnoreParens() const
Definition: TypeLoc.h:1127
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2558
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:204
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition: Type.h:4078
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:3899
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:218
SCS getStorageClassSpec() const
Definition: DeclSpec.h:451
ASTContext & getASTContext() const
Definition: Sema.h:1238
SourceRange getSourceRange() const LLVM_READONLY
Determine the source range covering the entire initializer.
Definition: DeclCXX.cpp:2286
static FriendDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, FriendUnion Friend_, SourceLocation FriendL, ArrayRef< TemplateParameterList *> FriendTypeTPLists=None)
Definition: DeclFriend.cpp:35
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:295
llvm::SmallPtrSet< QualType, 4 > IndirectBaseSet
Use small set to collect indirect bases.
bool hasTrivialCopyAssignment() const
Determine whether this class has a trivial copy assignment operator (C++ [class.copy]p11, C++11 [class.copy]p25)
Definition: DeclCXX.h:1450
Encodes a location in the source.
void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record)
body_range body()
Definition: Stmt.h:1274
QualType getReturnType() const
Definition: Type.h:3613
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
We are computing the exception specification for a defaulted special member function.
Definition: Sema.h:7211
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums...
Definition: Type.h:4396
bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange)
Mark the given method pure.
bool hasSameTemplateName(TemplateName X, TemplateName Y)
Determine whether the given template names refer to the same template.
Decl * ActOnFinishLinkageSpecification(Scope *S, Decl *LinkageSpec, SourceLocation RBraceLoc)
ActOnFinishLinkageSpecification - Complete the definition of the C++ linkage specification LinkageSpe...
unsigned getNumHandlers() const
Definition: StmtCXX.h:103
decl_iterator decls_begin() const
Definition: DeclBase.cpp:1371
Expr * getSubExpr() const
Definition: Expr.h:1926
bool hasErrorOccurred() const
Determine whether any errors have occurred since this object instance was created.
Definition: Diagnostic.h:1010
Decl * BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, StringLiteral *AssertMessageExpr, SourceLocation RParenLoc, bool Failed)
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2095
void setTrivialForCallFlags(CXXMethodDecl *MD)
Definition: DeclCXX.cpp:1321
Attr * clone(ASTContext &C) const
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition: DeclSpec.h:1873
CastKind getCastKind() const
Definition: Expr.h:3044
static void CheckConstexprCtorInitializer(Sema &SemaRef, const FunctionDecl *Dcl, FieldDecl *Field, llvm::SmallSet< Decl *, 16 > &Inits, bool &Diagnosed)
Check that the given field is initialized within a constexpr constructor.
bool isUnnamedBitfield() const
Determines whether this is an unnamed bitfield.
Definition: Decl.h:2660
static unsigned NumImplicitCopyAssignmentOperatorsDeclared
The number of implicitly-declared copy assignment operators for which declarations were built...
Definition: ASTContext.h:2813
bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method)
Check whether &#39;this&#39; shows up in the attributes of the given static member function.
DeclarationName getName() const
getName - Returns the embedded declaration name.
static ConstantExpr * Create(const ASTContext &Context, Expr *E)
Definition: Expr.h:909
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3064
SourceLocation getUsingLoc() const
Return the source location of the &#39;using&#39; keyword.
Definition: DeclCXX.h:3385
void referenceDLLExportedClassMethods()
MutableArrayRef< Expr * > MultiExprArg
Definition: Ownership.h:277
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
Represents a call to a member function that may be written either with member call syntax (e...
Definition: ExprCXX.h:171
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:376
FunctionTypeInfo Fun
Definition: DeclSpec.h:1520
bool isModulePrivateSpecified() const
Definition: DeclSpec.h:724
InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, ConstructorUsingShadowDecl *Shadow)
Attempt to be ABI-compatible with code generated by Clang 4.0.x (SVN r291814).
static bool CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, CanQualType ExpectedResultType, CanQualType ExpectedFirstParamType, unsigned DependentParamTypeDiag, unsigned InvalidParamTypeDiag)
Stmt * getElse()
Definition: Stmt.h:1783
QualType getElementType() const
Definition: Type.h:3203
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
Definition: SemaInternal.h:94
DeclStmt - Adaptor class for mixing declarations with statements and expressions. ...
Definition: Stmt.h:1143
void setReferenced(bool R=true)
Definition: DeclBase.h:577
unsigned getSpellingListIndex() const
Definition: Attr.h:91
IdentifierTable & getIdentifierTable()
Definition: Preprocessor.h:823
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:117
bool SetStorageClassSpec(Sema &S, SCS SC, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
These methods set the specified attribute of the DeclSpec and return false if there was no error...
Definition: DeclSpec.cpp:580
void DefineImplicitDestructor(SourceLocation CurrentLocation, CXXDestructorDecl *Destructor)
DefineImplicitDestructor - Checks for feasibility of defining this destructor as the default destruct...
Represents a dependent using declaration which was not marked with typename.
Definition: DeclCXX.h:3571
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:3866
Expr * getInClassInitializer() const
Get the C++11 default member initializer for this member, or null if one has not been set...
Definition: Decl.h:2721
unsigned getLocalCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers local to this particular QualType instan...
Definition: Type.h:765
const DecompositionDeclarator & getDecompositionDeclarator() const
Definition: DeclSpec.h:1875
void removeShadowDecl(UsingShadowDecl *S)
Definition: DeclCXX.cpp:2721
void setCtorInitializers(CXXCtorInitializer **Initializers)
Definition: DeclCXX.h:2584
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2041
void setDefaulted(bool D=true)
Definition: Decl.h:2035
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2413
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition: Type.h:3928
paths_iterator begin()
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:183
void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc)
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition: Decl.h:1078
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:553
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
No ref-qualifier was provided.
Definition: Type.h:1360
void setEntity(DeclContext *E)
Definition: Scope.h:326
bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckForFunctionMarkedFinal - Checks whether a virtual member function overrides a virtual member fun...
llvm::SmallPtrSet< const CXXRecordDecl *, 8 > RecordDeclSetTy
Definition: Sema.h:584
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2285
std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths)
Builds a string representing ambiguous paths from a specific derived class to different subobjects of...
void setImplicitMoveConstructorIsDeleted()
Set that we attempted to declare an implicit move constructor, but overload resolution failed so we d...
Definition: DeclCXX.h:1070
SourceLocation getLocation() const
Definition: Attr.h:94
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:3860
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition: Lookup.h:69
Expr * getNoexceptExpr() const
Return the expression inside noexcept(expression), or a null pointer if there is none (because the ex...
Definition: Type.h:3963
static CXXBaseSpecifier * findDirectBaseWithType(CXXRecordDecl *Derived, QualType DesiredBase, bool &AnyDependentBases)
Find the base specifier for a base class with the given type.
CanQualType VoidTy
Definition: ASTContext.h:1016
void actOnDelayedExceptionSpecification(Decl *Method, ExceptionSpecificationType EST, SourceRange SpecificationRange, ArrayRef< ParsedType > DynamicExceptions, ArrayRef< SourceRange > DynamicExceptionRanges, Expr *NoexceptExpr)
Add an exception-specification to the given member function (or member function template).
bool isGenericLambda() const
Determine whether this class describes a generic lambda function object (i.e.
Definition: DeclCXX.cpp:1348
Describes the kind of initialization being performed, along with location information for tokens rela...
bool isValueDependent() const
isValueDependent - Determines whether this expression is value-dependent (C++ [temp.dep.constexpr]).
Definition: Expr.h:149
static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *Ident)
AbstractDiagSelID
Definition: Sema.h:6113
arg_range arguments()
Definition: Expr.h:2585
AccessSpecifier getAccess() const
QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, const DeclSpec *DS=nullptr)
Definition: SemaType.cpp:1727
bool isObjCObjectPointerType() const
Definition: Type.h:6393
A class for iterating through a result set and possibly filtering out results.
Definition: Lookup.h:606
Direct list-initialization.
Definition: Specifiers.h:232
Represents a C++11 virt-specifier-seq.
Definition: DeclSpec.h:2499
static ConstructorUsingShadowDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, UsingDecl *Using, NamedDecl *Target, bool IsVirtual)
Definition: DeclCXX.cpp:2693
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3115
bool isFunctionProtoType() const
Definition: Type.h:1947
void CheckExplicitlyDefaultedMemberExceptionSpec(CXXMethodDecl *MD, const FunctionProtoType *T)
Check whether the exception specification provided for an explicitly-defaulted special member matches...
static bool checkSimpleDecomposition(Sema &S, ArrayRef< BindingDecl *> Bindings, ValueDecl *Src, QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType, llvm::function_ref< ExprResult(SourceLocation, Expr *, unsigned)> GetInit)
void setIsParsingBaseSpecifiers()
Definition: DeclCXX.h:805
bool hasUninstantiatedDefaultArg() const
Definition: Decl.h:1664
static FriendTemplateDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation Loc, MutableArrayRef< TemplateParameterList *> Params, FriendUnion Friend, SourceLocation FriendLoc)
CXXRecordDecl * getOrigin() const
Retrieve the type from which this base-paths search began.
static bool BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, ImplicitInitializerKind ImplicitInitKind, CXXBaseSpecifier *BaseSpec, bool IsInheritedVirtualBase, CXXCtorInitializer *&CXXBaseInit)
No entity found met the criteria.
Definition: Lookup.h:51
static bool CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl)
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired=false)
Note that the vtable for the given class was used at the given location.
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition: Decl.cpp:3076
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition: Specifiers.h:164
This template specialization was formed from a template-id but has not yet been declared, defined, or instantiated.
Definition: Specifiers.h:149
bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc, bool HasTypenameKeyword, const CXXScopeSpec &SS, SourceLocation NameLoc, const LookupResult &Previous)
Checks that the given using declaration is not an invalid redeclaration.
QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc, DeclarationName Entity)
Build a reference type.
Definition: SemaType.cpp:1980
SourceLocation getRAngleLoc() const
Definition: DeclTemplate.h:174
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted per C++0x.
Definition: Decl.h:2039
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
SourceLocation getInlineSpecLoc() const
Definition: DeclSpec.h:570
NamedDecl * next()
Definition: Lookup.h:632
void setExplicitlyDefaulted(bool ED=true)
State that this function is explicitly defaulted per C++0x.
Definition: Decl.h:2045
void setHasInheritedDefaultArg(bool I=true)
Definition: Decl.h:1680
bool hasFlexibleArrayMember() const
Definition: Decl.h:3647
bool defaultedCopyConstructorIsDeleted() const
true if a defaulted copy constructor for this class would be deleted.
Definition: DeclCXX.h:912
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:194
static bool checkTupleLikeDecomposition(Sema &S, ArrayRef< BindingDecl *> Bindings, VarDecl *Src, QualType DecompType, const llvm::APSInt &TupleSize)
static Sema::ImplicitExceptionSpecification computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD)
bool isTrivialForCall() const
Definition: Decl.h:2029
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2293
void addArgument(const TemplateArgumentLoc &Loc)
Definition: TemplateBase.h:595
virtual bool isOutOfLine() const
Determine whether this declaration is declared out of line (outside its semantic context).
Definition: Decl.cpp:99
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:3922
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:215
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
TypeLoc getElementLoc() const
Definition: TypeLoc.h:1493
bool hasInClassInitializer() const
Whether this class has any in-class initializers for non-static data members (including those in anon...
Definition: DeclCXX.h:1289
CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD)
getSpecialMember - get the special member enum for a method.
Definition: SemaDecl.cpp:2807
SourceLocation getLastLocation() const
Definition: DeclSpec.h:2529
CXXDestructorDecl * DeclareImplicitDestructor(CXXRecordDecl *ClassDecl)
Declare the implicit destructor for the given class.
Expr * getLHS() const
Definition: Expr.h:3327
static TypeAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:4571
A POD class for pairing a NamedDecl* with an access specifier.
CXXConstructorDecl * getConstructor() const
Definition: DeclCXX.h:2471
StringRef getName() const
Return the actual identifier string.
MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, CXXRecordDecl *ClassDecl)
SourceRange getRange() const
Definition: Attr.h:95
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition: DeclSpec.h:1889
static void checkForMultipleExportedDefaultConstructors(Sema &S, CXXRecordDecl *Class)
Decl * ActOnExceptionDeclarator(Scope *S, Declarator &D)
ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch handler.
void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery=true)
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod) const
Retrieves the default calling convention for the current target.
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:2916
const ComparisonCategoryInfo * lookupInfo(ComparisonCategoryType Kind) const
Return the cached comparison category information for the specified &#39;Kind&#39;.
ast_type_traits::DynTypedNode Node
CanQualType CharTy
Definition: ASTContext.h:1018
TLS with a dynamic initializer.
Definition: Decl.h:836
Represents a template argument.
Definition: TemplateBase.h:51
void setBody(Stmt *B)
Definition: Decl.cpp:2741
TagTypeKind
The kind of a tag type.
Definition: Type.h:5031
static bool isInvalid(LocType Loc, bool *Invalid)
const ObjCInterfaceDecl * getClassInterface() const
Definition: DeclObjC.h:2440
bool hasNonTrivialCopyConstructorForCall() const
Definition: DeclCXX.h:1415
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition: Decl.cpp:2535
static LinkageSpecDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExternLoc, SourceLocation LangLoc, LanguageIDs Lang, bool HasBraces)
Definition: DeclCXX.cpp:2528
Dataflow Directional Tag Classes.
void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT)
Definition: Decl.h:3056
bool isExplicit() const
Whether this function is explicit.
Definition: DeclCXX.h:2589
static void DelegatingCycleHelper(CXXConstructorDecl *Ctor, llvm::SmallPtrSet< CXXConstructorDecl *, 4 > &Valid, llvm::SmallPtrSet< CXXConstructorDecl *, 4 > &Invalid, llvm::SmallPtrSet< CXXConstructorDecl *, 4 > &Current, Sema &S)
bool isValid() const
Return true if this is a valid SourceLocation object.
CXXConstructorDecl * DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit copy constructor for the given class.
MSPropertyDecl * HandleMSProperty(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS, const ParsedAttr &MSPropertyAttr)
HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
const TemplateArgument & getArgument() const
Definition: TemplateBase.h:499
not evaluated yet, for special member function
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1262
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:399
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:22
static const TST TST_auto
Definition: DeclSpec.h:303
method_iterator begin_overridden_methods() const
Definition: DeclCXX.cpp:2154
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition: Scope.h:226
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_RValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CCK_ImplicitConversion)
ImpCastExprToType - If Expr is not of type &#39;Type&#39;, insert an implicit cast.
Definition: Sema.cpp:474
static void AddMostOverridenMethods(const CXXMethodDecl *MD, llvm::SmallPtrSetImpl< const CXXMethodDecl *> &Methods)
Add the most overriden methods from MD to Methods.
QualType getType() const
Get the type for which this source info wrapper provides information.
Definition: TypeLoc.h:131
StmtResult ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, Stmt *First, ConditionResult Second, FullExprArg Third, SourceLocation RParenLoc, Stmt *Body)
Definition: SemaStmt.cpp:1728
unsigned isVariadic
isVariadic - If this function has a prototype, and if that proto ends with &#39;,...)&#39;, this is true.
Definition: DeclSpec.h:1258
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:3558
bool isImplicit() const
Definition: ExprCXX.h:997
SourceRange getSourceRange(const SourceRange &Range)
Returns the SourceRange of a SourceRange.
Definition: FixIt.h:34
bool isRecord() const
Definition: DeclBase.h:1827
attr_range attrs() const
Definition: DeclBase.h:490
SourceLocation RAngleLoc
The location of the &#39;>&#39; after the template argument list.
static bool InitializationHasSideEffects(const FieldDecl &FD)
bool hasTrivialDestructorForCall() const
Definition: DeclCXX.h:1482
Represents a field injected from an anonymous union/struct into the parent scope. ...
Definition: Decl.h:2825
void ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, Expr *defarg)
ActOnParamDefaultArgument - Check whether the default argument provided for a function parameter is w...
bool isCopyConstructor(unsigned &TypeQuals) const
Whether this constructor is a copy constructor (C++ [class.copy]p2, which can be used to copy the cla...
Definition: DeclCXX.cpp:2365
SourceLocation getSourceLocation() const
Determine the source location of the initializer.
Definition: DeclCXX.cpp:2273
QualType getUnderlyingType() const
Definition: Decl.h:2971
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1027
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:118
AccessSpecifier getAccess() const
Definition: DeclBase.h:462
const Expr * getInit() const
Definition: Decl.h:1220
A decomposition declaration.
Definition: DeclCXX.h:3843
MapType::iterator iterator
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
Definition: DeclBase.cpp:1756
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:160
static NamespaceDecl * getNamespaceDecl(NamedDecl *D)
getNamespaceDecl - Returns the namespace a decl represents.
bool hasUserDeclaredConstructor() const
Determine whether this class has any user-declared constructors.
Definition: DeclCXX.h:983
unsigned getIndex() const
Retrieve the index of the template parameter.
void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD)
Represents a dependent using declaration which was marked with typename.
Definition: DeclCXX.h:3667
FunctionDecl * getTemplateInstantiationPattern() const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
Definition: Decl.cpp:3414
static UsingDirectiveDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, SourceLocation NamespaceLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc, NamedDecl *Nominated, DeclContext *CommonAncestor)
Definition: DeclCXX.cpp:2545
bool areArgsDestroyedLeftToRightInCallee() const
Are arguments to a call destroyed left to right in the callee? This is a fundamental language change...
Definition: TargetCXXABI.h:209
void setWillHaveBody(bool V=true)
Definition: Decl.h:2222
NamedDecl * getCorrectionDecl() const
Gets the pointer to the declaration of the typo correction.
The name of a declaration.
StmtClass getStmtClass() const
Definition: Stmt.h:1029
ArrayRef< QualType > exceptions() const
Definition: Type.h:4044
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition: Lookup.h:506
Expr * getDefaultArg()
Definition: Decl.cpp:2573
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition: Decl.h:346
const CXXRecordDecl * getParent() const
Returns the parent of this method declaration, which is the class in which this method is defined...
Definition: DeclCXX.h:2166
bool isMoveConstructor(unsigned &TypeQuals) const
Determine whether this constructor is a move constructor (C++11 [class.copy]p3), which can be used to...
Definition: DeclCXX.cpp:2370
llvm::SmallPtrSet< SpecialMemberDecl, 4 > SpecialMembersBeingDeclared
The C++ special members which we are currently in the process of declaring.
Definition: Sema.h:1183
const Type * getBaseClass() const
If this is a base class initializer, returns the type of the base class.
Definition: DeclCXX.cpp:2266
std::pair< CXXRecordDecl *, SourceLocation > VTableUse
The list of classes whose vtables have been used within this translation unit, and the source locatio...
Definition: Sema.h:5844
A mapping from each virtual member function to its set of final overriders.
unsigned getNumTemplateParameterLists() const
Definition: Decl.h:760
Represents an enum.
Definition: Decl.h:3326
CXXRecordDecl * Record
The declaration for the comparison category type from the standard library.
bool isAmbiguous(CanQualType BaseType)
Determine whether the path from the most-derived type to the given base type is ambiguous (i...
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:2756
bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl)
CheckOverloadedOperatorDeclaration - Check whether the declaration of this overloaded operator is wel...
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:146
semantics_iterator semantics_begin()
Definition: Expr.h:5367
bool isDestroyingOperatorDelete() const
Determine whether this is a destroying operator delete.
Definition: Decl.cpp:2884
Expr * get() const
Definition: Sema.h:3673
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration...
Definition: DeclCXX.h:2144
llvm::ArrayRef< TemplateArgumentLoc > arguments() const
Definition: TemplateBase.h:583
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspnd...
MemInitResult BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, Expr *Init, CXXRecordDecl *ClassDecl, SourceLocation EllipsisLoc)
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any...
Definition: ASTContext.h:1083
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:508
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext, providing only those that are of type SpecificDecl (or a class derived from it).
Definition: DeclBase.h:2017
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 &#39;auto&#39; typ...
Definition: Type.h:6663
static unsigned NumImplicitCopyAssignmentOperators
The number of implicitly-declared copy assignment operators.
Definition: ASTContext.h:2809
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:196
Expr * IgnoreParenImpCasts() LLVM_READONLY
IgnoreParenImpCasts - Ignore parentheses and implicit casts.
Definition: Expr.cpp:2693
void PushUsingDirective(UsingDirectiveDecl *UDir)
Definition: Scope.h:458
CXXConstructorDecl * DeclareImplicitDefaultConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit default constructor for the given class.
std::pair< CXXConstructorDecl *, bool > findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const
Find the constructor to use for inherited construction of a base class, and whether that base class c...
void forEachQualifier(llvm::function_ref< void(TQ, StringRef, SourceLocation)> Handle)
This method calls the passed in handler on each qual being set.
Definition: DeclSpec.cpp:422
unsigned getNumParams() const
Definition: TypeLoc.h:1402
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2022
SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D, CXXSpecialMember SM, bool ConstArg, bool VolatileArg, bool RValueThis, bool ConstThis, bool VolatileThis)
const FunctionDecl * getOperatorDelete() const
Definition: DeclCXX.h:2738
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:151
static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, CXXMethodDecl *MD)
UsingDecl * getUsingDecl() const
Gets the using declaration to which this declaration is tied.
Definition: DeclCXX.cpp:2682
void RemoveDecl(Decl *D)
Definition: Scope.h:291
Name lookup found a single declaration that met the criteria.
Definition: Lookup.h:60
bool needsOverloadResolutionForMoveConstructor() const
Determine whether we need to eagerly declare a defaulted move constructor for this class...
Definition: DeclCXX.h:1098
bool isCurrentClassName(const IdentifierInfo &II, Scope *S, const CXXScopeSpec *SS=nullptr)
isCurrentClassName - Determine whether the identifier II is the name of the class type currently bein...
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2552
static AccessSpecifier MergeAccess(AccessSpecifier PathAccess, AccessSpecifier DeclAccess)
Calculates the access of a decl that is reached along a path.
Definition: DeclCXX.h:1864
bool isIncompleteArrayType() const
Definition: Type.h:6353
bool lookupInBases(BaseMatchesCallback BaseMatches, CXXBasePaths &Paths, bool LookupInDependent=false) const
Look for entities within the base classes of this C++ class, transitively searching all base class su...
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:4370
Complex values, per C99 6.2.5p11.
Definition: Type.h:2477
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:450
static bool CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl)
MapType::const_iterator const_iterator
void setUnparsedDefaultArg()
Specify that this parameter has an unparsed default argument.
Definition: Decl.h:1672
Expr * getUninstantiatedDefaultArg()
Definition: Decl.cpp:2615
bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl)
CheckLiteralOperatorDeclaration - Check whether the declaration of this literal operator function is ...
bool checkInitIsICE() const
Determine whether the value of the initializer attached to this declaration is an integral constant e...
Definition: Decl.cpp:2330
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition: DeclSpec.h:547
static void extendRight(SourceRange &R, SourceRange After)
QualType getCanonicalTypeInternal() const
Definition: Type.h:2355
SourceLocation getVirtualSpecLoc() const
Definition: DeclSpec.h:575
Represents a C++ base or member initializer.
Definition: DeclCXX.h:2256
LanguageIDs
Represents the language in a linkage specification.
Definition: DeclCXX.h:2837
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:6578
This template specialization was declared or defined by an explicit specialization (C++ [temp...
Definition: Specifiers.h:156
SourceRange getSourceRange() const LLVM_READONLY
getSourceRange - The range of the declaration name.
bool needsOverloadResolutionForMoveAssignment() const
Determine whether we need to eagerly declare a move assignment operator for this class.
Definition: DeclCXX.h:1172
bool hasNonTrivialObjCLifetime() const
Definition: Type.h:1062
IndirectFieldDecl * getIndirectMember() const
Definition: DeclCXX.h:2406
T * getAttr() const
Definition: DeclBase.h:527
type_object_range type_objects() const
Returns the range of type objects, from the identifier outwards.
Definition: DeclSpec.h:2192
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
const llvm::APInt & getSize() const
Definition: Type.h:2890
CanQualType DependentTy
Definition: ASTContext.h:1045
bool isFunctionType() const
Definition: Type.h:6292
TrivialSubobjectKind
The kind of subobject we are checking for triviality.
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition: Decl.h:1060
NamedDecl * ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, MultiTemplateParamsArg TemplateParameterLists, Expr *BitfieldWidth, const VirtSpecifiers &VS, InClassInitStyle InitStyle)
ActOnCXXMemberDeclarator - This is invoked when a C++ class member declarator is parsed.
static const void * GetKeyForBase(ASTContext &Context, QualType BaseType)
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:716
ClassTemplateDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this template.
CXXBasePath & front()
Opcode getOpcode() const
Definition: Expr.h:1921
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition: ExprCXX.h:1413
bool isImplicitlyDeleted(FunctionDecl *FD)
Determine whether the given function is an implicitly-deleted special member function.
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:2673
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1730
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2269
decl_range decls()
Definition: Stmt.h:1186
static UsingShadowDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, UsingDecl *Using, NamedDecl *Target)
Definition: DeclCXX.h:3174
TypeLocClass getTypeLocClass() const
Definition: TypeLoc.h:114
ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, FieldDecl *Field, DeclAccessPair FoundDecl, const DeclarationNameInfo &MemberNameInfo)
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr)
Definition: SemaExpr.cpp:12854
static CXXMethodDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool isInline, bool isConstexpr, SourceLocation EndLocation)
Definition: DeclCXX.cpp:1935
The template argument is a type.
Definition: TemplateBase.h:60
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
Holds information about the various types of exception specification.
Definition: Type.h:3741
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:92
const LinkageSpecDecl * getExternCContext() const
Retrieve the nearest enclosing C linkage specification context.
Definition: DeclBase.cpp:1133
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1507
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream...
void setInherited(bool I)
Definition: Attr.h:152
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition: Lookup.h:251
The "class" keyword.
Definition: Type.h:5042
Represents a base class of a C++ class.
Definition: DeclCXX.h:192
bool hasTypename() const
Return true if the using declaration has &#39;typename&#39;.
Definition: DeclCXX.h:3407
bool isInitListConstructor(const FunctionDecl *Ctor)
Determine whether Ctor is an initializer-list constructor, as defined in [dcl.init.list]p2.
void checkClassLevelDLLAttribute(CXXRecordDecl *Class)
Check class-level dllimport/dllexport attribute.
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition: DeclBase.cpp:412
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2070
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition: Type.h:3746
This is a scope that can contain a declaration.
Definition: Scope.h:60
bool isObjCObjectType() const
Definition: Type.h:6397
static BindingDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, IdentifierInfo *Id)
Definition: DeclCXX.cpp:2851
CanQualType Char8Ty
Definition: ASTContext.h:1022
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2356
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
SourceLocation getIdentifierLoc() const
Definition: DeclSpec.h:2133
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2253
TrivialABIHandling
Definition: Sema.h:2289
static const void * GetKeyForMember(ASTContext &Context, CXXCtorInitializer *Member)
A use of a default initializer in a constructor or in aggregate initialization.
Definition: ExprCXX.h:1137
EnumDecl * getStdAlignValT() const
bool isSet() const
Deprecated.
Definition: DeclSpec.h:209
bool isLValueReferenceType() const
Definition: Type.h:6312
bool needsImplicitCopyConstructor() const
Determine whether this class needs an implicit copy constructor to be lazily declared.
Definition: DeclCXX.h:1002
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:238
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition: DeclCXX.cpp:1619
void setInvalidType(bool Val=true)
Definition: DeclSpec.h:2442
Reading or writing from this object requires a barrier call.
Definition: Type.h:172
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition: Type.h:3749
void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc)
ActOnParamDefaultArgumentError - Parsing or semantic analysis of the default argument for the paramet...
void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv)
Define the "body" of the conversion from a lambda object to a block pointer.
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:235
unsigned getDepth() const
Definition: Type.h:4565
static void BuildBasePathArray(const CXXBasePath &Path, CXXCastPath &BasePathArray)
QualType getParamType(unsigned i) const
Definition: Type.h:3890
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups, surround it with a ExprWithCleanups node.
ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
Definition: SemaExpr.cpp:1687
void printPretty(raw_ostream &OS, PrinterHelper *Helper, const PrintingPolicy &Policy, unsigned Indentation=0, StringRef NewlineSymbol="\, const ASTContext *Context=nullptr) const
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1009
void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, CXXRecordDecl *Record)
MarkBaseAndMemberDestructorsReferenced - Given a record decl, mark all the non-trivial destructors of...
void Deallocate(void *Ptr) const
Definition: ASTContext.h:675
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:2682
static bool functionDeclHasDefaultArgument(const FunctionDecl *FD)
void CheckOverrideControl(NamedDecl *D)
CheckOverrideControl - Check C++11 override control semantics.
CallingConv getCallConv() const
Definition: Type.h:3623
ThreadStorageClassSpecifier
Thread storage-class-specifier.
Definition: Specifiers.h:193
void setImplicitMoveAssignmentIsDeleted()
Set that we attempted to declare an implicit move assignment operator, but overload resolution failed...
Definition: DeclCXX.h:1151
Describes the sequence of initializations required to initialize a given object or reference with a s...
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context...
Captures information about "declaration specifiers".
Definition: DeclSpec.h:228
ActionResult< Expr * > ExprResult
Definition: Ownership.h:267
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:6152
SourceLocation getRestrictSpecLoc() const
Definition: DeclSpec.h:549
static bool CheckConstexprParameterTypes(Sema &SemaRef, const FunctionDecl *FD)
void setDefaultArg(Expr *defarg)
Definition: Decl.cpp:2585
bool isMutable() const
Determines whether this field is mutable (C++ only).
Definition: Decl.h:2654
void setEnd(SourceLocation e)
const CXXMethodDecl * getCurrentKeyFunction(const CXXRecordDecl *RD)
Get our current best idea for the key function of the given record decl, or nullptr if there isn&#39;t on...
Represents a C++ struct/union/class.
Definition: DeclCXX.h:300
static bool isCompoundAssignmentOp(Opcode Opc)
Definition: Expr.h:3415
void setIvarInitializers(ASTContext &C, CXXCtorInitializer **initializers, unsigned numInitializers)
Definition: DeclObjC.cpp:2170
bool isValid() const
bool hasUserDeclaredMoveConstructor() const
Determine whether this class has had a move constructor declared by the user.
Definition: DeclCXX.h:1049
bool CompleteConstructorCall(CXXConstructorDecl *Constructor, MultiExprArg ArgsPtr, SourceLocation Loc, SmallVectorImpl< Expr *> &ConvertedArgs, bool AllowExplicit=false, bool IsListInitialization=false)
Given a constructor and the set of arguments provided for the constructor, convert the arguments and ...
void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc)
bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, ArrayRef< CXXCtorInitializer *> Initializers=None)
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type...
bool isVoidType() const
Definition: Type.h:6544
bool AttachBaseSpecifiers(CXXRecordDecl *Class, MutableArrayRef< CXXBaseSpecifier *> Bases)
Performs the actual work of attaching the given base class specifiers to a C++ class.
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:3655
CXXCatchStmt - This represents a C++ catch block.
Definition: StmtCXX.h:29
void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD)
void setConstexpr(bool IC)
Definition: Decl.h:2095
void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock)
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:6099
void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc, SourceLocation ArgLoc)
ActOnParamUnparsedDefaultArgument - We&#39;ve seen a default argument for a function parameter, but we can&#39;t parse it yet because we&#39;re inside a class definition.
static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, llvm::APSInt &Size)
void setParam(unsigned i, ParmVarDecl *VD)
Definition: TypeLoc.h:1409
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition: DeclSpec.h:191
CanQualType Char16Ty
Definition: ASTContext.h:1023
QualType removeAddrSpaceQualType(QualType T) const
Remove any existing address space on the type and returns the type with qualifiers intact (or that&#39;s ...
bool isInherited() const
Definition: Attr.h:98
static bool hasOneRealArgument(MultiExprArg Args)
Determine whether the given list arguments contains exactly one "real" (non-default) argument...
AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, QualType Base, QualType Derived, const CXXBasePath &Path, unsigned DiagID, bool ForceCheck=false, bool ForceUnprivileged=false)
Checks access for a hierarchy conversion.
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition: DeclSpec.h:1854
static unsigned NumImplicitCopyConstructorsDeclared
The number of implicitly-declared copy constructors for which declarations were built.
Definition: ASTContext.h:2799
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:336
void setUnsupportedFriend(bool Unsupported)
Definition: DeclFriend.h:178
static UsingDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation UsingL, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool HasTypenameKeyword)
Definition: DeclCXX.cpp:2742
Declaration of a class template.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
bool isVirtualSpecified() const
Definition: DeclSpec.h:574
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string...
Definition: Diagnostic.h:129
void addAttr(Attr *A)
Definition: DeclBase.cpp:840
bool lambdaIsDefaultConstructibleAndAssignable() const
Determine whether this lambda should have an implicit default constructor and copy and move assignmen...
Definition: DeclCXX.cpp:631
NamedDecl * getAcceptableDecl(NamedDecl *D) const
Retrieve the accepted (re)declaration of the given declaration, if there is one.
Definition: Lookup.h:350
SourceManager & getSourceManager() const
Definition: Sema.h:1236
SourceRange getDefaultArgRange() const
Retrieve the source range that covers the entire default argument.
Definition: Decl.cpp:2590
iterator end() const
Definition: Lookup.h:325
A template-id, e.g., f<int>.
bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckOverridingFunctionReturnType - Checks whether the return types are covariant, according to C++ [class.virtual]p5.
bool hasInheritedAssignment() const
Determine whether this class has a using-declaration that names a base class assignment operator...
Definition: DeclCXX.h:1532
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:276
A little helper class (which is basically a smart pointer that forwards info from DiagnosticsEngine) ...
Definition: Diagnostic.h:1316
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1566
Defines the clang::TargetInfo interface.
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2396
AccessSpecifier Access
The access along this inheritance path.
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:154
bool isInlineSpecified() const
Definition: DeclSpec.h:567
static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, bool ConstArg, CXXConstructorDecl *InheritedCtor=nullptr, Sema::InheritedConstructorInfo *Inherited=nullptr)
Determine whether the specified special member function would be constexpr if it were implicitly defi...
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:3637
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition: Decl.h:1989
SourceLocation getAtomicSpecLoc() const
Definition: DeclSpec.h:551
ExprResult ExprError()
Definition: Ownership.h:283
bool hasVolatile() const
Definition: Type.h:263
void adjustExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI, bool AsWritten=false)
Change the exception specification on a function once it is delay-parsed, instantiated, or computed.
FriendDecl * CheckFriendTypeDecl(SourceLocation LocStart, SourceLocation FriendLoc, TypeSourceInfo *TSInfo)
Perform semantic analysis of the given friend type declaration.
capture_iterator capture_begin() const
Retrieve an iterator pointing to the first lambda capture.
Definition: ExprCXX.cpp:1158
static void CheckAbstractClassUsage(AbstractUsageInfo &Info, CXXMethodDecl *MD)
Check for invalid uses of an abstract type in a method declaration.
NestedNameSpecifier * getQualifier() const
Retrieve the nested-name-specifier that qualifies the name.
Definition: DeclCXX.h:3395
NameKind getKind() const
CanQualType IntTy
Definition: ASTContext.h:1025
unsigned getNumElements() const
Definition: Type.h:3204
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Definition: Redeclarable.h:226
The top declaration context.
Definition: Decl.h:108
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2079
SourceLocation getConstexprSpecLoc() const
Definition: DeclSpec.h:728
QualType getAsType() const
Retrieve the type for a type template argument.
Definition: TemplateBase.h:257
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1041
void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass &SC)
CheckConversionDeclarator - Called by ActOnDeclarator to check the well-formednes of the conversion f...
const Scope * getFnParent() const
getFnParent - Return the closest scope that is a function body.
Definition: Scope.h:230
bool hasRefQualifier() const
Determine whether this function declaration contains a ref-qualifier.
Definition: DeclSpec.h:1445
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:819
bool isUnion() const
Definition: Decl.h:3252
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:4841
NamedDecl * getMostRecentDecl()
Definition: Decl.h:446
Expr * getRHS() const
Definition: Expr.h:3329
void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD)
Diagnose methods which overload virtual methods in a base class without overriding any...
CXXMethodDecl * DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl)
Declare the implicit copy assignment operator for the given class.
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2136
bool isPointerType() const
Definition: Type.h:6296
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:3316
bool implicitCopyConstructorHasConstParam() const
Determine whether an implicit copy constructor for this type would have a parameter with a const-qual...
Definition: DeclCXX.h:1023
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
virtual bool HandleTopLevelDecl(DeclGroupRef D)
HandleTopLevelDecl - Handle the specified top-level declaration.
Definition: ASTConsumer.cpp:19
void addAddressSpace(LangAS space)
Definition: Type.h:378
void setBaseObjectType(QualType T)
Sets the base object type for this lookup.
Definition: Lookup.h:409
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:66
bool needsImplicitMoveConstructor() const
Determine whether this class should get an implicit move constructor or if any existing special membe...
Definition: DeclCXX.h:1088
ArrayRef< Binding > bindings() const
Definition: DeclSpec.h:1701
bool CheckDestructor(CXXDestructorDecl *Destructor)
CheckDestructor - Checks a fully-formed destructor definition for well-formedness, issuing any diagnostics required.
DeclaratorContext getContext() const
Definition: DeclSpec.h:1879
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1135
SourceLocation getInnerLocStart() const
Return SourceLocation representing start of source range ignoring outer template declarations.
Definition: Decl.h:3150
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:572
NamespaceDecl * getAnonymousNamespace() const
Retrieve the anonymous namespace nested inside this namespace, if any.
Definition: Decl.h:598
bool hasDirectFields() const
Determine whether this class has direct non-static data members.
Definition: DeclCXX.h:1330
An instance of this class represents the declaration of a property member.
Definition: DeclCXX.h:3912
IdentifierInfo * getCXXLiteralIdentifier() const
If this name is the name of a literal operator, retrieve the identifier associated with it...
QualType getType() const
Definition: Decl.h:648
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:114
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:328
A trivial tuple used to represent a source range.
void setLexicalDeclContext(DeclContext *DC)
Definition: DeclBase.cpp:299
ASTContext & Context
Definition: Sema.h:324
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, std::unique_ptr< CorrectionCandidateCallback > CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2983
paths_iterator end()
This represents a decl that may have a name.
Definition: Decl.h:249
virtual void diagnose(Sema &S, SourceLocation Loc, QualType T)=0
void dropAttr()
Definition: DeclBase.h:502
bool isTranslationUnit() const
Definition: DeclBase.h:1823
Expr * getRepAsExpr() const
Definition: DeclSpec.h:500
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type...
Definition: TypeLoc.h:76
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:457
CanQualType BoolTy
Definition: ASTContext.h:1017
Represents a C++ namespace alias.
Definition: DeclCXX.h:3020
Decl * ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, MultiTemplateParamsArg TempParamLists)
Handle a friend tag declaration where the scope specifier was templated.
No keyword precedes the qualified type name.
Definition: Type.h:5071
SourceRange getSourceRange() const LLVM_READONLY
Retrieves the source range that contains the entire base specifier.
Definition: DeclCXX.h:235
FullExprArg MakeFullDiscardedValueExpr(Expr *Arg)
Definition: Sema.h:3696
iterator begin() const
Definition: Lookup.h:324
Represents C++ using-directive.
Definition: DeclCXX.h:2916
void DiagnoseAbstractType(const CXXRecordDecl *RD)
static Expr * CastForMoving(Sema &SemaRef, Expr *E, QualType T=QualType())
bool isAggregate() const
Determine whether this class is an aggregate (C++ [dcl.init.aggr]), which is a class with no user-dec...
Definition: DeclCXX.h:1284
Describes an entity that is being initialized.
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
attr::Kind getKind() const
Definition: Attr.h:87
MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, SourceLocation LParenLoc, ArrayRef< Expr *> Args, SourceLocation RParenLoc, SourceLocation EllipsisLoc)
Handle a C++ member initializer using parentheses syntax.
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition: Lookup.h:513
ComparisonCategoryType
An enumeration representing the different comparison categories types.
The global specifier &#39;::&#39;. There is no stored value.
NestedNameSpecifier * getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const
Retrieves the "canonical" nested name specifier for a given nested name specifier.
NamedDecl * ActOnDecompositionDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists)
The object is actually the complete object.
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3055
void setType(QualType newType)
Definition: Decl.h:649
static CXXConstructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool isExplicit, bool isInline, bool isImplicitlyDeclared, bool isConstexpr, InheritedConstructor Inherited=InheritedConstructor())
Definition: DeclCXX.cpp:2326
ctor_range ctors() const
Definition: DeclCXX.h:885
Decl * ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS, MultiTemplateParamsArg TemplateParams, SourceLocation UsingLoc, UnqualifiedId &Name, const ParsedAttributesView &AttrList, TypeResult Type, Decl *DeclFromDeclSpec)
bool hasInit() const
Definition: Decl.cpp:2164
Wrapper for source info for pointers.
Definition: TypeLoc.h:1202
SourceLocation getBegin() const
ParsedAttributes - A collection of parsed attributes.
Definition: ParsedAttr.h:855
SourceLocation ColonLoc
Location of &#39;:&#39;.
Definition: OpenMPClause.h:108
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclTemplate.h:176
const LangOptions & getLangOpts() const
Definition: ASTContext.h:707
void WillReplaceSpecifier(bool ForceReplacement)
bool isParameterPack() const
Determine whether this parameter is actually a function parameter pack.
Definition: Decl.cpp:2629
Wrapper for source info for block pointers.
Definition: TypeLoc.h:1215
void setDeletedAsWritten(bool D=true)
Definition: Decl.h:2144
void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl)
AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared special functions, such as the default constructor, copy constructor, or destructor, to the given C++ class (C++ [special]p1).
An implicit &#39;self&#39; parameter.
void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation)
SetIvarInitializers - This routine builds initialization ASTs for the Objective-C implementation whos...
No in-class initializer.
Definition: Specifiers.h:230
base_class_range vbases()
Definition: DeclCXX.h:840
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:2872
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:3773
static InitializedEntity InitializeBinding(VarDecl *Binding)
Create the initialization entity for a structured binding.
A deduction-guide name (a template-name)
Declaration of a template function.
Definition: DeclTemplate.h:969
Decl * ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation TypenameLoc, CXXScopeSpec &SS, UnqualifiedId &Name, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList)
Represents an implicitly-generated value initialization of an object of a given type.
Definition: Expr.h:4893
bool SetDelegatingInitializer(CXXConstructorDecl *Constructor, CXXCtorInitializer *Initializer)
void DiagnoseAbsenceOfOverrideControl(NamedDecl *D)
DiagnoseAbsenceOfOverrideControl - Diagnose if &#39;override&#39; keyword was not used in the declaration of ...
ParamInfo * Params
Params - This is a pointer to a new[]&#39;d array of ParamInfo objects that describe the parameters speci...
Definition: DeclSpec.h:1313
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:1943
Comparison
NamedDeclSetType UnusedPrivateFields
Set containing all declared private fields that are not used.
Definition: Sema.h:569
static bool checkLiteralOperatorTemplateParameterList(Sema &SemaRef, FunctionTemplateDecl *TpDecl)
static const ParsedAttr * getMSPropertyAttr(const ParsedAttributesView &list)
Attr - This represents one attribute.
Definition: Attr.h:44
ParsedAttributes & getAttributes()
Definition: DeclSpec.h:762
SourceLocation getLocation() const
Definition: DeclBase.h:418
Represents a shadow declaration introduced into a scope by a (resolved) using declaration.
Definition: DeclCXX.h:3139
bool isExternallyVisible() const
Definition: Decl.h:380
LangStandard::Kind Std
QualType getType() const
Return the type wrapped by this type source info.
Definition: Decl.h:98
A single template declaration.
Definition: TemplateName.h:192
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition: Decl.h:3189
ConstructorUsingShadowDecl * getShadowDecl() const
Definition: DeclCXX.h:2470
noexcept(expression), evals to &#39;true&#39;
Helper class that creates diagnostics with optional template instantiation stacks.
Definition: Sema.h:1261
Expr * IgnoreParens() LLVM_READONLY
IgnoreParens - Ignore parentheses.
Definition: Expr.cpp:2560
Decl * ActOnConversionDeclarator(CXXConversionDecl *Conversion)
ActOnConversionDeclarator - Called by ActOnDeclarator to complete the declaration of the given C++ co...
decl_iterator decls_end() const
Definition: DeclBase.h:1999
The triviality of a method unaffected by "trivial_abi".
Definition: Sema.h:2291
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1058
static unsigned NumImplicitDestructors
The number of implicitly-declared destructors.
Definition: ASTContext.h:2823
static bool isVisible(Sema &SemaRef, NamedDecl *D)
Determine whether the given declaration is visible to the program.
Definition: Lookup.h:338
NamedDecl * ActOnFriendFunctionDecl(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParams)
bool isTransparentContext() const
isTransparentContext - Determines whether this context is a "transparent" context, meaning that the members declared in this context are semantically declared in the nearest enclosing non-transparent (opaque) context but are lexically declared in this context.
Definition: DeclBase.cpp:1110
param_type_iterator param_type_end() const
Definition: Type.h:4038
unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template)
static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, SourceLocation Loc, IdentifierInfo *II, bool *IsInline, NamespaceDecl *PrevNS)
Diagnose a mismatch in &#39;inline&#39; qualifiers when a namespace is reopened.
A RAII object to temporarily push a declaration context.
Definition: Sema.h:728
method_range methods() const
Definition: DeclCXX.h:865
The subobject is a non-static data member.
bool isNoDestroy(const ASTContext &) const
Do we need to emit an exit-time destructor for this variable?
Definition: Decl.cpp:2480
QualType getType() const
Retrieves the type of the base class.
Definition: DeclCXX.h:291
ComparisonCategories CompCategories
Types and expressions required to build C++2a three-way comparisons using operator<=>, including the values return by builtin <=> operators.
Definition: ASTContext.h:2026
bool defaultedDestructorIsDeleted() const
true if a defaulted destructor for this class would be deleted.
Definition: DeclCXX.h:929