xref: /freebsd/contrib/llvm-project/clang/lib/Sema/SemaDeclCXX.cpp (revision 734e82fe33aa764367791a7d603b383996c6b40b)
1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for C++ declarations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/AST/ASTConsumer.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/ASTLambda.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/ComparisonCategories.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/RecordLayout.h"
25 #include "clang/AST/RecursiveASTVisitor.h"
26 #include "clang/AST/StmtVisitor.h"
27 #include "clang/AST/TypeLoc.h"
28 #include "clang/AST/TypeOrdering.h"
29 #include "clang/Basic/AttributeCommonInfo.h"
30 #include "clang/Basic/PartialDiagnostic.h"
31 #include "clang/Basic/Specifiers.h"
32 #include "clang/Basic/TargetInfo.h"
33 #include "clang/Lex/LiteralSupport.h"
34 #include "clang/Lex/Preprocessor.h"
35 #include "clang/Sema/CXXFieldCollector.h"
36 #include "clang/Sema/DeclSpec.h"
37 #include "clang/Sema/Initialization.h"
38 #include "clang/Sema/Lookup.h"
39 #include "clang/Sema/ParsedTemplate.h"
40 #include "clang/Sema/Scope.h"
41 #include "clang/Sema/ScopeInfo.h"
42 #include "clang/Sema/SemaInternal.h"
43 #include "clang/Sema/Template.h"
44 #include "llvm/ADT/ScopeExit.h"
45 #include "llvm/ADT/SmallString.h"
46 #include "llvm/ADT/STLExtras.h"
47 #include "llvm/ADT/StringExtras.h"
48 #include <map>
49 #include <optional>
50 #include <set>
51 
52 using namespace clang;
53 
54 //===----------------------------------------------------------------------===//
55 // CheckDefaultArgumentVisitor
56 //===----------------------------------------------------------------------===//
57 
58 namespace {
59 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
60 /// the default argument of a parameter to determine whether it
61 /// contains any ill-formed subexpressions. For example, this will
62 /// diagnose the use of local variables or parameters within the
63 /// default argument expression.
64 class CheckDefaultArgumentVisitor
65     : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
66   Sema &S;
67   const Expr *DefaultArg;
68 
69 public:
70   CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
71       : S(S), DefaultArg(DefaultArg) {}
72 
73   bool VisitExpr(const Expr *Node);
74   bool VisitDeclRefExpr(const DeclRefExpr *DRE);
75   bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
76   bool VisitLambdaExpr(const LambdaExpr *Lambda);
77   bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
78 };
79 
80 /// VisitExpr - Visit all of the children of this expression.
81 bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
82   bool IsInvalid = false;
83   for (const Stmt *SubStmt : Node->children())
84     IsInvalid |= Visit(SubStmt);
85   return IsInvalid;
86 }
87 
88 /// VisitDeclRefExpr - Visit a reference to a declaration, to
89 /// determine whether this declaration can be used in the default
90 /// argument expression.
91 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
92   const ValueDecl *Decl = dyn_cast<ValueDecl>(DRE->getDecl());
93 
94   if (!isa<VarDecl, BindingDecl>(Decl))
95     return false;
96 
97   if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {
98     // C++ [dcl.fct.default]p9:
99     //   [...] parameters of a function shall not be used in default
100     //   argument expressions, even if they are not evaluated. [...]
101     //
102     // C++17 [dcl.fct.default]p9 (by CWG 2082):
103     //   [...] A parameter shall not appear as a potentially-evaluated
104     //   expression in a default argument. [...]
105     //
106     if (DRE->isNonOdrUse() != NOUR_Unevaluated)
107       return S.Diag(DRE->getBeginLoc(),
108                     diag::err_param_default_argument_references_param)
109              << Param->getDeclName() << DefaultArg->getSourceRange();
110   } else if (auto *VD = Decl->getPotentiallyDecomposedVarDecl()) {
111     // C++ [dcl.fct.default]p7:
112     //   Local variables shall not be used in default argument
113     //   expressions.
114     //
115     // C++17 [dcl.fct.default]p7 (by CWG 2082):
116     //   A local variable shall not appear as a potentially-evaluated
117     //   expression in a default argument.
118     //
119     // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
120     //   Note: A local variable cannot be odr-used (6.3) in a default
121     //   argument.
122     //
123     if (VD->isLocalVarDecl() && !DRE->isNonOdrUse())
124       return S.Diag(DRE->getBeginLoc(),
125                     diag::err_param_default_argument_references_local)
126              << Decl << DefaultArg->getSourceRange();
127   }
128   return false;
129 }
130 
131 /// VisitCXXThisExpr - Visit a C++ "this" expression.
132 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
133   // C++ [dcl.fct.default]p8:
134   //   The keyword this shall not be used in a default argument of a
135   //   member function.
136   return S.Diag(ThisE->getBeginLoc(),
137                 diag::err_param_default_argument_references_this)
138          << ThisE->getSourceRange();
139 }
140 
141 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
142     const PseudoObjectExpr *POE) {
143   bool Invalid = false;
144   for (const Expr *E : POE->semantics()) {
145     // Look through bindings.
146     if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
147       E = OVE->getSourceExpr();
148       assert(E && "pseudo-object binding without source expression?");
149     }
150 
151     Invalid |= Visit(E);
152   }
153   return Invalid;
154 }
155 
156 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
157   // [expr.prim.lambda.capture]p9
158   // a lambda-expression appearing in a default argument cannot implicitly or
159   // explicitly capture any local entity. Such a lambda-expression can still
160   // have an init-capture if any full-expression in its initializer satisfies
161   // the constraints of an expression appearing in a default argument.
162   bool Invalid = false;
163   for (const LambdaCapture &LC : Lambda->captures()) {
164     if (!Lambda->isInitCapture(&LC))
165       return S.Diag(LC.getLocation(), diag::err_lambda_capture_default_arg);
166     // Init captures are always VarDecl.
167     auto *D = cast<VarDecl>(LC.getCapturedVar());
168     Invalid |= Visit(D->getInit());
169   }
170   return Invalid;
171 }
172 } // namespace
173 
174 void
175 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
176                                                  const CXXMethodDecl *Method) {
177   // If we have an MSAny spec already, don't bother.
178   if (!Method || ComputedEST == EST_MSAny)
179     return;
180 
181   const FunctionProtoType *Proto
182     = Method->getType()->getAs<FunctionProtoType>();
183   Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
184   if (!Proto)
185     return;
186 
187   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
188 
189   // If we have a throw-all spec at this point, ignore the function.
190   if (ComputedEST == EST_None)
191     return;
192 
193   if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
194     EST = EST_BasicNoexcept;
195 
196   switch (EST) {
197   case EST_Unparsed:
198   case EST_Uninstantiated:
199   case EST_Unevaluated:
200     llvm_unreachable("should not see unresolved exception specs here");
201 
202   // If this function can throw any exceptions, make a note of that.
203   case EST_MSAny:
204   case EST_None:
205     // FIXME: Whichever we see last of MSAny and None determines our result.
206     // We should make a consistent, order-independent choice here.
207     ClearExceptions();
208     ComputedEST = EST;
209     return;
210   case EST_NoexceptFalse:
211     ClearExceptions();
212     ComputedEST = EST_None;
213     return;
214   // FIXME: If the call to this decl is using any of its default arguments, we
215   // need to search them for potentially-throwing calls.
216   // If this function has a basic noexcept, it doesn't affect the outcome.
217   case EST_BasicNoexcept:
218   case EST_NoexceptTrue:
219   case EST_NoThrow:
220     return;
221   // If we're still at noexcept(true) and there's a throw() callee,
222   // change to that specification.
223   case EST_DynamicNone:
224     if (ComputedEST == EST_BasicNoexcept)
225       ComputedEST = EST_DynamicNone;
226     return;
227   case EST_DependentNoexcept:
228     llvm_unreachable(
229         "should not generate implicit declarations for dependent cases");
230   case EST_Dynamic:
231     break;
232   }
233   assert(EST == EST_Dynamic && "EST case not considered earlier.");
234   assert(ComputedEST != EST_None &&
235          "Shouldn't collect exceptions when throw-all is guaranteed.");
236   ComputedEST = EST_Dynamic;
237   // Record the exceptions in this function's exception specification.
238   for (const auto &E : Proto->exceptions())
239     if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
240       Exceptions.push_back(E);
241 }
242 
243 void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) {
244   if (!S || ComputedEST == EST_MSAny)
245     return;
246 
247   // FIXME:
248   //
249   // C++0x [except.spec]p14:
250   //   [An] implicit exception-specification specifies the type-id T if and
251   // only if T is allowed by the exception-specification of a function directly
252   // invoked by f's implicit definition; f shall allow all exceptions if any
253   // function it directly invokes allows all exceptions, and f shall allow no
254   // exceptions if every function it directly invokes allows no exceptions.
255   //
256   // Note in particular that if an implicit exception-specification is generated
257   // for a function containing a throw-expression, that specification can still
258   // be noexcept(true).
259   //
260   // Note also that 'directly invoked' is not defined in the standard, and there
261   // is no indication that we should only consider potentially-evaluated calls.
262   //
263   // Ultimately we should implement the intent of the standard: the exception
264   // specification should be the set of exceptions which can be thrown by the
265   // implicit definition. For now, we assume that any non-nothrow expression can
266   // throw any exception.
267 
268   if (Self->canThrow(S))
269     ComputedEST = EST_None;
270 }
271 
272 ExprResult Sema::ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
273                                              SourceLocation EqualLoc) {
274   if (RequireCompleteType(Param->getLocation(), Param->getType(),
275                           diag::err_typecheck_decl_incomplete_type))
276     return true;
277 
278   // C++ [dcl.fct.default]p5
279   //   A default argument expression is implicitly converted (clause
280   //   4) to the parameter type. The default argument expression has
281   //   the same semantic constraints as the initializer expression in
282   //   a declaration of a variable of the parameter type, using the
283   //   copy-initialization semantics (8.5).
284   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
285                                                                     Param);
286   InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
287                                                            EqualLoc);
288   InitializationSequence InitSeq(*this, Entity, Kind, Arg);
289   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
290   if (Result.isInvalid())
291     return true;
292   Arg = Result.getAs<Expr>();
293 
294   CheckCompletedExpr(Arg, EqualLoc);
295   Arg = MaybeCreateExprWithCleanups(Arg);
296 
297   return Arg;
298 }
299 
300 void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
301                                    SourceLocation EqualLoc) {
302   // Add the default argument to the parameter
303   Param->setDefaultArg(Arg);
304 
305   // We have already instantiated this parameter; provide each of the
306   // instantiations with the uninstantiated default argument.
307   UnparsedDefaultArgInstantiationsMap::iterator InstPos
308     = UnparsedDefaultArgInstantiations.find(Param);
309   if (InstPos != UnparsedDefaultArgInstantiations.end()) {
310     for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
311       InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
312 
313     // We're done tracking this parameter's instantiations.
314     UnparsedDefaultArgInstantiations.erase(InstPos);
315   }
316 }
317 
318 /// ActOnParamDefaultArgument - Check whether the default argument
319 /// provided for a function parameter is well-formed. If so, attach it
320 /// to the parameter declaration.
321 void
322 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
323                                 Expr *DefaultArg) {
324   if (!param || !DefaultArg)
325     return;
326 
327   ParmVarDecl *Param = cast<ParmVarDecl>(param);
328   UnparsedDefaultArgLocs.erase(Param);
329 
330   auto Fail = [&] {
331     Param->setInvalidDecl();
332     Param->setDefaultArg(new (Context) OpaqueValueExpr(
333         EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue));
334   };
335 
336   // Default arguments are only permitted in C++
337   if (!getLangOpts().CPlusPlus) {
338     Diag(EqualLoc, diag::err_param_default_argument)
339       << DefaultArg->getSourceRange();
340     return Fail();
341   }
342 
343   // Check for unexpanded parameter packs.
344   if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
345     return Fail();
346   }
347 
348   // C++11 [dcl.fct.default]p3
349   //   A default argument expression [...] shall not be specified for a
350   //   parameter pack.
351   if (Param->isParameterPack()) {
352     Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
353         << DefaultArg->getSourceRange();
354     // Recover by discarding the default argument.
355     Param->setDefaultArg(nullptr);
356     return;
357   }
358 
359   ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);
360   if (Result.isInvalid())
361     return Fail();
362 
363   DefaultArg = Result.getAs<Expr>();
364 
365   // Check that the default argument is well-formed
366   CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
367   if (DefaultArgChecker.Visit(DefaultArg))
368     return Fail();
369 
370   SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
371 }
372 
373 /// ActOnParamUnparsedDefaultArgument - We've seen a default
374 /// argument for a function parameter, but we can't parse it yet
375 /// because we're inside a class definition. Note that this default
376 /// argument will be parsed later.
377 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
378                                              SourceLocation EqualLoc,
379                                              SourceLocation ArgLoc) {
380   if (!param)
381     return;
382 
383   ParmVarDecl *Param = cast<ParmVarDecl>(param);
384   Param->setUnparsedDefaultArg();
385   UnparsedDefaultArgLocs[Param] = ArgLoc;
386 }
387 
388 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
389 /// the default argument for the parameter param failed.
390 void Sema::ActOnParamDefaultArgumentError(Decl *param,
391                                           SourceLocation EqualLoc) {
392   if (!param)
393     return;
394 
395   ParmVarDecl *Param = cast<ParmVarDecl>(param);
396   Param->setInvalidDecl();
397   UnparsedDefaultArgLocs.erase(Param);
398   Param->setDefaultArg(new (Context) OpaqueValueExpr(
399       EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue));
400 }
401 
402 /// CheckExtraCXXDefaultArguments - Check for any extra default
403 /// arguments in the declarator, which is not a function declaration
404 /// or definition and therefore is not permitted to have default
405 /// arguments. This routine should be invoked for every declarator
406 /// that is not a function declaration or definition.
407 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
408   // C++ [dcl.fct.default]p3
409   //   A default argument expression shall be specified only in the
410   //   parameter-declaration-clause of a function declaration or in a
411   //   template-parameter (14.1). It shall not be specified for a
412   //   parameter pack. If it is specified in a
413   //   parameter-declaration-clause, it shall not occur within a
414   //   declarator or abstract-declarator of a parameter-declaration.
415   bool MightBeFunction = D.isFunctionDeclarationContext();
416   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
417     DeclaratorChunk &chunk = D.getTypeObject(i);
418     if (chunk.Kind == DeclaratorChunk::Function) {
419       if (MightBeFunction) {
420         // This is a function declaration. It can have default arguments, but
421         // keep looking in case its return type is a function type with default
422         // arguments.
423         MightBeFunction = false;
424         continue;
425       }
426       for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
427            ++argIdx) {
428         ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
429         if (Param->hasUnparsedDefaultArg()) {
430           std::unique_ptr<CachedTokens> Toks =
431               std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
432           SourceRange SR;
433           if (Toks->size() > 1)
434             SR = SourceRange((*Toks)[1].getLocation(),
435                              Toks->back().getLocation());
436           else
437             SR = UnparsedDefaultArgLocs[Param];
438           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
439             << SR;
440         } else if (Param->getDefaultArg()) {
441           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
442             << Param->getDefaultArg()->getSourceRange();
443           Param->setDefaultArg(nullptr);
444         }
445       }
446     } else if (chunk.Kind != DeclaratorChunk::Paren) {
447       MightBeFunction = false;
448     }
449   }
450 }
451 
452 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
453   return llvm::any_of(FD->parameters(), [](ParmVarDecl *P) {
454     return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
455   });
456 }
457 
458 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
459 /// function, once we already know that they have the same
460 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
461 /// error, false otherwise.
462 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
463                                 Scope *S) {
464   bool Invalid = false;
465 
466   // The declaration context corresponding to the scope is the semantic
467   // parent, unless this is a local function declaration, in which case
468   // it is that surrounding function.
469   DeclContext *ScopeDC = New->isLocalExternDecl()
470                              ? New->getLexicalDeclContext()
471                              : New->getDeclContext();
472 
473   // Find the previous declaration for the purpose of default arguments.
474   FunctionDecl *PrevForDefaultArgs = Old;
475   for (/**/; PrevForDefaultArgs;
476        // Don't bother looking back past the latest decl if this is a local
477        // extern declaration; nothing else could work.
478        PrevForDefaultArgs = New->isLocalExternDecl()
479                                 ? nullptr
480                                 : PrevForDefaultArgs->getPreviousDecl()) {
481     // Ignore hidden declarations.
482     if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
483       continue;
484 
485     if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
486         !New->isCXXClassMember()) {
487       // Ignore default arguments of old decl if they are not in
488       // the same scope and this is not an out-of-line definition of
489       // a member function.
490       continue;
491     }
492 
493     if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
494       // If only one of these is a local function declaration, then they are
495       // declared in different scopes, even though isDeclInScope may think
496       // they're in the same scope. (If both are local, the scope check is
497       // sufficient, and if neither is local, then they are in the same scope.)
498       continue;
499     }
500 
501     // We found the right previous declaration.
502     break;
503   }
504 
505   // C++ [dcl.fct.default]p4:
506   //   For non-template functions, default arguments can be added in
507   //   later declarations of a function in the same
508   //   scope. Declarations in different scopes have completely
509   //   distinct sets of default arguments. That is, declarations in
510   //   inner scopes do not acquire default arguments from
511   //   declarations in outer scopes, and vice versa. In a given
512   //   function declaration, all parameters subsequent to a
513   //   parameter with a default argument shall have default
514   //   arguments supplied in this or previous declarations. A
515   //   default argument shall not be redefined by a later
516   //   declaration (not even to the same value).
517   //
518   // C++ [dcl.fct.default]p6:
519   //   Except for member functions of class templates, the default arguments
520   //   in a member function definition that appears outside of the class
521   //   definition are added to the set of default arguments provided by the
522   //   member function declaration in the class definition.
523   for (unsigned p = 0, NumParams = PrevForDefaultArgs
524                                        ? PrevForDefaultArgs->getNumParams()
525                                        : 0;
526        p < NumParams; ++p) {
527     ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
528     ParmVarDecl *NewParam = New->getParamDecl(p);
529 
530     bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
531     bool NewParamHasDfl = NewParam->hasDefaultArg();
532 
533     if (OldParamHasDfl && NewParamHasDfl) {
534       unsigned DiagDefaultParamID =
535         diag::err_param_default_argument_redefinition;
536 
537       // MSVC accepts that default parameters be redefined for member functions
538       // of template class. The new default parameter's value is ignored.
539       Invalid = true;
540       if (getLangOpts().MicrosoftExt) {
541         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
542         if (MD && MD->getParent()->getDescribedClassTemplate()) {
543           // Merge the old default argument into the new parameter.
544           NewParam->setHasInheritedDefaultArg();
545           if (OldParam->hasUninstantiatedDefaultArg())
546             NewParam->setUninstantiatedDefaultArg(
547                                       OldParam->getUninstantiatedDefaultArg());
548           else
549             NewParam->setDefaultArg(OldParam->getInit());
550           DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
551           Invalid = false;
552         }
553       }
554 
555       // FIXME: If we knew where the '=' was, we could easily provide a fix-it
556       // hint here. Alternatively, we could walk the type-source information
557       // for NewParam to find the last source location in the type... but it
558       // isn't worth the effort right now. This is the kind of test case that
559       // is hard to get right:
560       //   int f(int);
561       //   void g(int (*fp)(int) = f);
562       //   void g(int (*fp)(int) = &f);
563       Diag(NewParam->getLocation(), DiagDefaultParamID)
564         << NewParam->getDefaultArgRange();
565 
566       // Look for the function declaration where the default argument was
567       // actually written, which may be a declaration prior to Old.
568       for (auto Older = PrevForDefaultArgs;
569            OldParam->hasInheritedDefaultArg(); /**/) {
570         Older = Older->getPreviousDecl();
571         OldParam = Older->getParamDecl(p);
572       }
573 
574       Diag(OldParam->getLocation(), diag::note_previous_definition)
575         << OldParam->getDefaultArgRange();
576     } else if (OldParamHasDfl) {
577       // Merge the old default argument into the new parameter unless the new
578       // function is a friend declaration in a template class. In the latter
579       // case the default arguments will be inherited when the friend
580       // declaration will be instantiated.
581       if (New->getFriendObjectKind() == Decl::FOK_None ||
582           !New->getLexicalDeclContext()->isDependentContext()) {
583         // It's important to use getInit() here;  getDefaultArg()
584         // strips off any top-level ExprWithCleanups.
585         NewParam->setHasInheritedDefaultArg();
586         if (OldParam->hasUnparsedDefaultArg())
587           NewParam->setUnparsedDefaultArg();
588         else if (OldParam->hasUninstantiatedDefaultArg())
589           NewParam->setUninstantiatedDefaultArg(
590                                        OldParam->getUninstantiatedDefaultArg());
591         else
592           NewParam->setDefaultArg(OldParam->getInit());
593       }
594     } else if (NewParamHasDfl) {
595       if (New->getDescribedFunctionTemplate()) {
596         // Paragraph 4, quoted above, only applies to non-template functions.
597         Diag(NewParam->getLocation(),
598              diag::err_param_default_argument_template_redecl)
599           << NewParam->getDefaultArgRange();
600         Diag(PrevForDefaultArgs->getLocation(),
601              diag::note_template_prev_declaration)
602             << false;
603       } else if (New->getTemplateSpecializationKind()
604                    != TSK_ImplicitInstantiation &&
605                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
606         // C++ [temp.expr.spec]p21:
607         //   Default function arguments shall not be specified in a declaration
608         //   or a definition for one of the following explicit specializations:
609         //     - the explicit specialization of a function template;
610         //     - the explicit specialization of a member function template;
611         //     - the explicit specialization of a member function of a class
612         //       template where the class template specialization to which the
613         //       member function specialization belongs is implicitly
614         //       instantiated.
615         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
616           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
617           << New->getDeclName()
618           << NewParam->getDefaultArgRange();
619       } else if (New->getDeclContext()->isDependentContext()) {
620         // C++ [dcl.fct.default]p6 (DR217):
621         //   Default arguments for a member function of a class template shall
622         //   be specified on the initial declaration of the member function
623         //   within the class template.
624         //
625         // Reading the tea leaves a bit in DR217 and its reference to DR205
626         // leads me to the conclusion that one cannot add default function
627         // arguments for an out-of-line definition of a member function of a
628         // dependent type.
629         int WhichKind = 2;
630         if (CXXRecordDecl *Record
631               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
632           if (Record->getDescribedClassTemplate())
633             WhichKind = 0;
634           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
635             WhichKind = 1;
636           else
637             WhichKind = 2;
638         }
639 
640         Diag(NewParam->getLocation(),
641              diag::err_param_default_argument_member_template_redecl)
642           << WhichKind
643           << NewParam->getDefaultArgRange();
644       }
645     }
646   }
647 
648   // DR1344: If a default argument is added outside a class definition and that
649   // default argument makes the function a special member function, the program
650   // is ill-formed. This can only happen for constructors.
651   if (isa<CXXConstructorDecl>(New) &&
652       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
653     CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
654                      OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
655     if (NewSM != OldSM) {
656       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
657       assert(NewParam->hasDefaultArg());
658       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
659         << NewParam->getDefaultArgRange() << NewSM;
660       Diag(Old->getLocation(), diag::note_previous_declaration);
661     }
662   }
663 
664   const FunctionDecl *Def;
665   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
666   // template has a constexpr specifier then all its declarations shall
667   // contain the constexpr specifier.
668   if (New->getConstexprKind() != Old->getConstexprKind()) {
669     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
670         << New << static_cast<int>(New->getConstexprKind())
671         << static_cast<int>(Old->getConstexprKind());
672     Diag(Old->getLocation(), diag::note_previous_declaration);
673     Invalid = true;
674   } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
675              Old->isDefined(Def) &&
676              // If a friend function is inlined but does not have 'inline'
677              // specifier, it is a definition. Do not report attribute conflict
678              // in this case, redefinition will be diagnosed later.
679              (New->isInlineSpecified() ||
680               New->getFriendObjectKind() == Decl::FOK_None)) {
681     // C++11 [dcl.fcn.spec]p4:
682     //   If the definition of a function appears in a translation unit before its
683     //   first declaration as inline, the program is ill-formed.
684     Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
685     Diag(Def->getLocation(), diag::note_previous_definition);
686     Invalid = true;
687   }
688 
689   // C++17 [temp.deduct.guide]p3:
690   //   Two deduction guide declarations in the same translation unit
691   //   for the same class template shall not have equivalent
692   //   parameter-declaration-clauses.
693   if (isa<CXXDeductionGuideDecl>(New) &&
694       !New->isFunctionTemplateSpecialization() && isVisible(Old)) {
695     Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
696     Diag(Old->getLocation(), diag::note_previous_declaration);
697   }
698 
699   // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
700   // argument expression, that declaration shall be a definition and shall be
701   // the only declaration of the function or function template in the
702   // translation unit.
703   if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
704       functionDeclHasDefaultArgument(Old)) {
705     Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
706     Diag(Old->getLocation(), diag::note_previous_declaration);
707     Invalid = true;
708   }
709 
710   // C++11 [temp.friend]p4 (DR329):
711   //   When a function is defined in a friend function declaration in a class
712   //   template, the function is instantiated when the function is odr-used.
713   //   The same restrictions on multiple declarations and definitions that
714   //   apply to non-template function declarations and definitions also apply
715   //   to these implicit definitions.
716   const FunctionDecl *OldDefinition = nullptr;
717   if (New->isThisDeclarationInstantiatedFromAFriendDefinition() &&
718       Old->isDefined(OldDefinition, true))
719     CheckForFunctionRedefinition(New, OldDefinition);
720 
721   return Invalid;
722 }
723 
724 NamedDecl *
725 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
726                                    MultiTemplateParamsArg TemplateParamLists) {
727   assert(D.isDecompositionDeclarator());
728   const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
729 
730   // The syntax only allows a decomposition declarator as a simple-declaration,
731   // a for-range-declaration, or a condition in Clang, but we parse it in more
732   // cases than that.
733   if (!D.mayHaveDecompositionDeclarator()) {
734     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
735       << Decomp.getSourceRange();
736     return nullptr;
737   }
738 
739   if (!TemplateParamLists.empty()) {
740     // FIXME: There's no rule against this, but there are also no rules that
741     // would actually make it usable, so we reject it for now.
742     Diag(TemplateParamLists.front()->getTemplateLoc(),
743          diag::err_decomp_decl_template);
744     return nullptr;
745   }
746 
747   Diag(Decomp.getLSquareLoc(),
748        !getLangOpts().CPlusPlus17
749            ? diag::ext_decomp_decl
750            : D.getContext() == DeclaratorContext::Condition
751                  ? diag::ext_decomp_decl_cond
752                  : diag::warn_cxx14_compat_decomp_decl)
753       << Decomp.getSourceRange();
754 
755   // The semantic context is always just the current context.
756   DeclContext *const DC = CurContext;
757 
758   // C++17 [dcl.dcl]/8:
759   //   The decl-specifier-seq shall contain only the type-specifier auto
760   //   and cv-qualifiers.
761   // C++20 [dcl.dcl]/8:
762   //   If decl-specifier-seq contains any decl-specifier other than static,
763   //   thread_local, auto, or cv-qualifiers, the program is ill-formed.
764   // C++2b [dcl.pre]/6:
765   //   Each decl-specifier in the decl-specifier-seq shall be static,
766   //   thread_local, auto (9.2.9.6 [dcl.spec.auto]), or a cv-qualifier.
767   auto &DS = D.getDeclSpec();
768   {
769     // Note: While constrained-auto needs to be checked, we do so separately so
770     // we can emit a better diagnostic.
771     SmallVector<StringRef, 8> BadSpecifiers;
772     SmallVector<SourceLocation, 8> BadSpecifierLocs;
773     SmallVector<StringRef, 8> CPlusPlus20Specifiers;
774     SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
775     if (auto SCS = DS.getStorageClassSpec()) {
776       if (SCS == DeclSpec::SCS_static) {
777         CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
778         CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
779       } else {
780         BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
781         BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
782       }
783     }
784     if (auto TSCS = DS.getThreadStorageClassSpec()) {
785       CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
786       CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
787     }
788     if (DS.hasConstexprSpecifier()) {
789       BadSpecifiers.push_back(
790           DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
791       BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
792     }
793     if (DS.isInlineSpecified()) {
794       BadSpecifiers.push_back("inline");
795       BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
796     }
797 
798     if (!BadSpecifiers.empty()) {
799       auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
800       Err << (int)BadSpecifiers.size()
801           << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
802       // Don't add FixItHints to remove the specifiers; we do still respect
803       // them when building the underlying variable.
804       for (auto Loc : BadSpecifierLocs)
805         Err << SourceRange(Loc, Loc);
806     } else if (!CPlusPlus20Specifiers.empty()) {
807       auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
808                          getLangOpts().CPlusPlus20
809                              ? diag::warn_cxx17_compat_decomp_decl_spec
810                              : diag::ext_decomp_decl_spec);
811       Warn << (int)CPlusPlus20Specifiers.size()
812            << llvm::join(CPlusPlus20Specifiers.begin(),
813                          CPlusPlus20Specifiers.end(), " ");
814       for (auto Loc : CPlusPlus20SpecifierLocs)
815         Warn << SourceRange(Loc, Loc);
816     }
817     // We can't recover from it being declared as a typedef.
818     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
819       return nullptr;
820   }
821 
822   // C++2a [dcl.struct.bind]p1:
823   //   A cv that includes volatile is deprecated
824   if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
825       getLangOpts().CPlusPlus20)
826     Diag(DS.getVolatileSpecLoc(),
827          diag::warn_deprecated_volatile_structured_binding);
828 
829   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
830   QualType R = TInfo->getType();
831 
832   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
833                                       UPPC_DeclarationType))
834     D.setInvalidType();
835 
836   // The syntax only allows a single ref-qualifier prior to the decomposition
837   // declarator. No other declarator chunks are permitted. Also check the type
838   // specifier here.
839   if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
840       D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
841       (D.getNumTypeObjects() == 1 &&
842        D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
843     Diag(Decomp.getLSquareLoc(),
844          (D.hasGroupingParens() ||
845           (D.getNumTypeObjects() &&
846            D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
847              ? diag::err_decomp_decl_parens
848              : diag::err_decomp_decl_type)
849         << R;
850 
851     // In most cases, there's no actual problem with an explicitly-specified
852     // type, but a function type won't work here, and ActOnVariableDeclarator
853     // shouldn't be called for such a type.
854     if (R->isFunctionType())
855       D.setInvalidType();
856   }
857 
858   // Constrained auto is prohibited by [decl.pre]p6, so check that here.
859   if (DS.isConstrainedAuto()) {
860     TemplateIdAnnotation *TemplRep = DS.getRepAsTemplateId();
861     assert(TemplRep->Kind == TNK_Concept_template &&
862            "No other template kind should be possible for a constrained auto");
863 
864     SourceRange TemplRange{TemplRep->TemplateNameLoc,
865                            TemplRep->RAngleLoc.isValid()
866                                ? TemplRep->RAngleLoc
867                                : TemplRep->TemplateNameLoc};
868     Diag(TemplRep->TemplateNameLoc, diag::err_decomp_decl_constraint)
869         << TemplRange << FixItHint::CreateRemoval(TemplRange);
870   }
871 
872   // Build the BindingDecls.
873   SmallVector<BindingDecl*, 8> Bindings;
874 
875   // Build the BindingDecls.
876   for (auto &B : D.getDecompositionDeclarator().bindings()) {
877     // Check for name conflicts.
878     DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
879     LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
880                           ForVisibleRedeclaration);
881     LookupName(Previous, S,
882                /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
883 
884     // It's not permitted to shadow a template parameter name.
885     if (Previous.isSingleResult() &&
886         Previous.getFoundDecl()->isTemplateParameter()) {
887       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
888                                       Previous.getFoundDecl());
889       Previous.clear();
890     }
891 
892     auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
893 
894     // Find the shadowed declaration before filtering for scope.
895     NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
896                                   ? getShadowedDeclaration(BD, Previous)
897                                   : nullptr;
898 
899     bool ConsiderLinkage = DC->isFunctionOrMethod() &&
900                            DS.getStorageClassSpec() == DeclSpec::SCS_extern;
901     FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
902                          /*AllowInlineNamespace*/false);
903 
904     if (!Previous.empty()) {
905       auto *Old = Previous.getRepresentativeDecl();
906       Diag(B.NameLoc, diag::err_redefinition) << B.Name;
907       Diag(Old->getLocation(), diag::note_previous_definition);
908     } else if (ShadowedDecl && !D.isRedeclaration()) {
909       CheckShadow(BD, ShadowedDecl, Previous);
910     }
911     PushOnScopeChains(BD, S, true);
912     Bindings.push_back(BD);
913     ParsingInitForAutoVars.insert(BD);
914   }
915 
916   // There are no prior lookup results for the variable itself, because it
917   // is unnamed.
918   DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
919                                Decomp.getLSquareLoc());
920   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
921                         ForVisibleRedeclaration);
922 
923   // Build the variable that holds the non-decomposed object.
924   bool AddToScope = true;
925   NamedDecl *New =
926       ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
927                               MultiTemplateParamsArg(), AddToScope, Bindings);
928   if (AddToScope) {
929     S->AddDecl(New);
930     CurContext->addHiddenDecl(New);
931   }
932 
933   if (isInOpenMPDeclareTargetContext())
934     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
935 
936   return New;
937 }
938 
939 static bool checkSimpleDecomposition(
940     Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
941     QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
942     llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
943   if ((int64_t)Bindings.size() != NumElems) {
944     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
945         << DecompType << (unsigned)Bindings.size()
946         << (unsigned)NumElems.getLimitedValue(UINT_MAX)
947         << toString(NumElems, 10) << (NumElems < Bindings.size());
948     return true;
949   }
950 
951   unsigned I = 0;
952   for (auto *B : Bindings) {
953     SourceLocation Loc = B->getLocation();
954     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
955     if (E.isInvalid())
956       return true;
957     E = GetInit(Loc, E.get(), I++);
958     if (E.isInvalid())
959       return true;
960     B->setBinding(ElemType, E.get());
961   }
962 
963   return false;
964 }
965 
966 static bool checkArrayLikeDecomposition(Sema &S,
967                                         ArrayRef<BindingDecl *> Bindings,
968                                         ValueDecl *Src, QualType DecompType,
969                                         const llvm::APSInt &NumElems,
970                                         QualType ElemType) {
971   return checkSimpleDecomposition(
972       S, Bindings, Src, DecompType, NumElems, ElemType,
973       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
974         ExprResult E = S.ActOnIntegerConstant(Loc, I);
975         if (E.isInvalid())
976           return ExprError();
977         return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
978       });
979 }
980 
981 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
982                                     ValueDecl *Src, QualType DecompType,
983                                     const ConstantArrayType *CAT) {
984   return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
985                                      llvm::APSInt(CAT->getSize()),
986                                      CAT->getElementType());
987 }
988 
989 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
990                                      ValueDecl *Src, QualType DecompType,
991                                      const VectorType *VT) {
992   return checkArrayLikeDecomposition(
993       S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
994       S.Context.getQualifiedType(VT->getElementType(),
995                                  DecompType.getQualifiers()));
996 }
997 
998 static bool checkComplexDecomposition(Sema &S,
999                                       ArrayRef<BindingDecl *> Bindings,
1000                                       ValueDecl *Src, QualType DecompType,
1001                                       const ComplexType *CT) {
1002   return checkSimpleDecomposition(
1003       S, Bindings, Src, DecompType, llvm::APSInt::get(2),
1004       S.Context.getQualifiedType(CT->getElementType(),
1005                                  DecompType.getQualifiers()),
1006       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1007         return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
1008       });
1009 }
1010 
1011 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
1012                                      TemplateArgumentListInfo &Args,
1013                                      const TemplateParameterList *Params) {
1014   SmallString<128> SS;
1015   llvm::raw_svector_ostream OS(SS);
1016   bool First = true;
1017   unsigned I = 0;
1018   for (auto &Arg : Args.arguments()) {
1019     if (!First)
1020       OS << ", ";
1021     Arg.getArgument().print(PrintingPolicy, OS,
1022                             TemplateParameterList::shouldIncludeTypeForArgument(
1023                                 PrintingPolicy, Params, I));
1024     First = false;
1025     I++;
1026   }
1027   return std::string(OS.str());
1028 }
1029 
1030 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
1031                                      SourceLocation Loc, StringRef Trait,
1032                                      TemplateArgumentListInfo &Args,
1033                                      unsigned DiagID) {
1034   auto DiagnoseMissing = [&] {
1035     if (DiagID)
1036       S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
1037                                                Args, /*Params*/ nullptr);
1038     return true;
1039   };
1040 
1041   // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1042   NamespaceDecl *Std = S.getStdNamespace();
1043   if (!Std)
1044     return DiagnoseMissing();
1045 
1046   // Look up the trait itself, within namespace std. We can diagnose various
1047   // problems with this lookup even if we've been asked to not diagnose a
1048   // missing specialization, because this can only fail if the user has been
1049   // declaring their own names in namespace std or we don't support the
1050   // standard library implementation in use.
1051   LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
1052                       Loc, Sema::LookupOrdinaryName);
1053   if (!S.LookupQualifiedName(Result, Std))
1054     return DiagnoseMissing();
1055   if (Result.isAmbiguous())
1056     return true;
1057 
1058   ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1059   if (!TraitTD) {
1060     Result.suppressDiagnostics();
1061     NamedDecl *Found = *Result.begin();
1062     S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1063     S.Diag(Found->getLocation(), diag::note_declared_at);
1064     return true;
1065   }
1066 
1067   // Build the template-id.
1068   QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
1069   if (TraitTy.isNull())
1070     return true;
1071   if (!S.isCompleteType(Loc, TraitTy)) {
1072     if (DiagID)
1073       S.RequireCompleteType(
1074           Loc, TraitTy, DiagID,
1075           printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1076                             TraitTD->getTemplateParameters()));
1077     return true;
1078   }
1079 
1080   CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1081   assert(RD && "specialization of class template is not a class?");
1082 
1083   // Look up the member of the trait type.
1084   S.LookupQualifiedName(TraitMemberLookup, RD);
1085   return TraitMemberLookup.isAmbiguous();
1086 }
1087 
1088 static TemplateArgumentLoc
1089 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
1090                                    uint64_t I) {
1091   TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
1092   return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1093 }
1094 
1095 static TemplateArgumentLoc
1096 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
1097   return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
1098 }
1099 
1100 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1101 
1102 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1103                                llvm::APSInt &Size) {
1104   EnterExpressionEvaluationContext ContextRAII(
1105       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1106 
1107   DeclarationName Value = S.PP.getIdentifierInfo("value");
1108   LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1109 
1110   // Form template argument list for tuple_size<T>.
1111   TemplateArgumentListInfo Args(Loc, Loc);
1112   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1113 
1114   // If there's no tuple_size specialization or the lookup of 'value' is empty,
1115   // it's not tuple-like.
1116   if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1117       R.empty())
1118     return IsTupleLike::NotTupleLike;
1119 
1120   // If we get this far, we've committed to the tuple interpretation, but
1121   // we can still fail if there actually isn't a usable ::value.
1122 
1123   struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1124     LookupResult &R;
1125     TemplateArgumentListInfo &Args;
1126     ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1127         : R(R), Args(Args) {}
1128     Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1129                                                SourceLocation Loc) override {
1130       return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1131              << printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1132                                   /*Params*/ nullptr);
1133     }
1134   } Diagnoser(R, Args);
1135 
1136   ExprResult E =
1137       S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1138   if (E.isInvalid())
1139     return IsTupleLike::Error;
1140 
1141   E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
1142   if (E.isInvalid())
1143     return IsTupleLike::Error;
1144 
1145   return IsTupleLike::TupleLike;
1146 }
1147 
1148 /// \return std::tuple_element<I, T>::type.
1149 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1150                                         unsigned I, QualType T) {
1151   // Form template argument list for tuple_element<I, T>.
1152   TemplateArgumentListInfo Args(Loc, Loc);
1153   Args.addArgument(
1154       getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1155   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1156 
1157   DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1158   LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1159   if (lookupStdTypeTraitMember(
1160           S, R, Loc, "tuple_element", Args,
1161           diag::err_decomp_decl_std_tuple_element_not_specialized))
1162     return QualType();
1163 
1164   auto *TD = R.getAsSingle<TypeDecl>();
1165   if (!TD) {
1166     R.suppressDiagnostics();
1167     S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1168         << printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1169                              /*Params*/ nullptr);
1170     if (!R.empty())
1171       S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1172     return QualType();
1173   }
1174 
1175   return S.Context.getTypeDeclType(TD);
1176 }
1177 
1178 namespace {
1179 struct InitializingBinding {
1180   Sema &S;
1181   InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1182     Sema::CodeSynthesisContext Ctx;
1183     Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding;
1184     Ctx.PointOfInstantiation = BD->getLocation();
1185     Ctx.Entity = BD;
1186     S.pushCodeSynthesisContext(Ctx);
1187   }
1188   ~InitializingBinding() {
1189     S.popCodeSynthesisContext();
1190   }
1191 };
1192 }
1193 
1194 static bool checkTupleLikeDecomposition(Sema &S,
1195                                         ArrayRef<BindingDecl *> Bindings,
1196                                         VarDecl *Src, QualType DecompType,
1197                                         const llvm::APSInt &TupleSize) {
1198   if ((int64_t)Bindings.size() != TupleSize) {
1199     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1200         << DecompType << (unsigned)Bindings.size()
1201         << (unsigned)TupleSize.getLimitedValue(UINT_MAX)
1202         << toString(TupleSize, 10) << (TupleSize < Bindings.size());
1203     return true;
1204   }
1205 
1206   if (Bindings.empty())
1207     return false;
1208 
1209   DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1210 
1211   // [dcl.decomp]p3:
1212   //   The unqualified-id get is looked up in the scope of E by class member
1213   //   access lookup ...
1214   LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1215   bool UseMemberGet = false;
1216   if (S.isCompleteType(Src->getLocation(), DecompType)) {
1217     if (auto *RD = DecompType->getAsCXXRecordDecl())
1218       S.LookupQualifiedName(MemberGet, RD);
1219     if (MemberGet.isAmbiguous())
1220       return true;
1221     //   ... and if that finds at least one declaration that is a function
1222     //   template whose first template parameter is a non-type parameter ...
1223     for (NamedDecl *D : MemberGet) {
1224       if (FunctionTemplateDecl *FTD =
1225               dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1226         TemplateParameterList *TPL = FTD->getTemplateParameters();
1227         if (TPL->size() != 0 &&
1228             isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1229           //   ... the initializer is e.get<i>().
1230           UseMemberGet = true;
1231           break;
1232         }
1233       }
1234     }
1235   }
1236 
1237   unsigned I = 0;
1238   for (auto *B : Bindings) {
1239     InitializingBinding InitContext(S, B);
1240     SourceLocation Loc = B->getLocation();
1241 
1242     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1243     if (E.isInvalid())
1244       return true;
1245 
1246     //   e is an lvalue if the type of the entity is an lvalue reference and
1247     //   an xvalue otherwise
1248     if (!Src->getType()->isLValueReferenceType())
1249       E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1250                                    E.get(), nullptr, VK_XValue,
1251                                    FPOptionsOverride());
1252 
1253     TemplateArgumentListInfo Args(Loc, Loc);
1254     Args.addArgument(
1255         getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1256 
1257     if (UseMemberGet) {
1258       //   if [lookup of member get] finds at least one declaration, the
1259       //   initializer is e.get<i-1>().
1260       E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1261                                      CXXScopeSpec(), SourceLocation(), nullptr,
1262                                      MemberGet, &Args, nullptr);
1263       if (E.isInvalid())
1264         return true;
1265 
1266       E = S.BuildCallExpr(nullptr, E.get(), Loc, std::nullopt, Loc);
1267     } else {
1268       //   Otherwise, the initializer is get<i-1>(e), where get is looked up
1269       //   in the associated namespaces.
1270       Expr *Get = UnresolvedLookupExpr::Create(
1271           S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1272           DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1273           UnresolvedSetIterator(), UnresolvedSetIterator());
1274 
1275       Expr *Arg = E.get();
1276       E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1277     }
1278     if (E.isInvalid())
1279       return true;
1280     Expr *Init = E.get();
1281 
1282     //   Given the type T designated by std::tuple_element<i - 1, E>::type,
1283     QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1284     if (T.isNull())
1285       return true;
1286 
1287     //   each vi is a variable of type "reference to T" initialized with the
1288     //   initializer, where the reference is an lvalue reference if the
1289     //   initializer is an lvalue and an rvalue reference otherwise
1290     QualType RefType =
1291         S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1292     if (RefType.isNull())
1293       return true;
1294     auto *RefVD = VarDecl::Create(
1295         S.Context, Src->getDeclContext(), Loc, Loc,
1296         B->getDeclName().getAsIdentifierInfo(), RefType,
1297         S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1298     RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1299     RefVD->setTSCSpec(Src->getTSCSpec());
1300     RefVD->setImplicit();
1301     if (Src->isInlineSpecified())
1302       RefVD->setInlineSpecified();
1303     RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1304 
1305     InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1306     InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1307     InitializationSequence Seq(S, Entity, Kind, Init);
1308     E = Seq.Perform(S, Entity, Kind, Init);
1309     if (E.isInvalid())
1310       return true;
1311     E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1312     if (E.isInvalid())
1313       return true;
1314     RefVD->setInit(E.get());
1315     S.CheckCompleteVariableDeclaration(RefVD);
1316 
1317     E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1318                                    DeclarationNameInfo(B->getDeclName(), Loc),
1319                                    RefVD);
1320     if (E.isInvalid())
1321       return true;
1322 
1323     B->setBinding(T, E.get());
1324     I++;
1325   }
1326 
1327   return false;
1328 }
1329 
1330 /// Find the base class to decompose in a built-in decomposition of a class type.
1331 /// This base class search is, unfortunately, not quite like any other that we
1332 /// perform anywhere else in C++.
1333 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1334                                                 const CXXRecordDecl *RD,
1335                                                 CXXCastPath &BasePath) {
1336   auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1337                           CXXBasePath &Path) {
1338     return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1339   };
1340 
1341   const CXXRecordDecl *ClassWithFields = nullptr;
1342   AccessSpecifier AS = AS_public;
1343   if (RD->hasDirectFields())
1344     // [dcl.decomp]p4:
1345     //   Otherwise, all of E's non-static data members shall be public direct
1346     //   members of E ...
1347     ClassWithFields = RD;
1348   else {
1349     //   ... or of ...
1350     CXXBasePaths Paths;
1351     Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1352     if (!RD->lookupInBases(BaseHasFields, Paths)) {
1353       // If no classes have fields, just decompose RD itself. (This will work
1354       // if and only if zero bindings were provided.)
1355       return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1356     }
1357 
1358     CXXBasePath *BestPath = nullptr;
1359     for (auto &P : Paths) {
1360       if (!BestPath)
1361         BestPath = &P;
1362       else if (!S.Context.hasSameType(P.back().Base->getType(),
1363                                       BestPath->back().Base->getType())) {
1364         //   ... the same ...
1365         S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1366           << false << RD << BestPath->back().Base->getType()
1367           << P.back().Base->getType();
1368         return DeclAccessPair();
1369       } else if (P.Access < BestPath->Access) {
1370         BestPath = &P;
1371       }
1372     }
1373 
1374     //   ... unambiguous ...
1375     QualType BaseType = BestPath->back().Base->getType();
1376     if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1377       S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1378         << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1379       return DeclAccessPair();
1380     }
1381 
1382     //   ... [accessible, implied by other rules] base class of E.
1383     S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1384                            *BestPath, diag::err_decomp_decl_inaccessible_base);
1385     AS = BestPath->Access;
1386 
1387     ClassWithFields = BaseType->getAsCXXRecordDecl();
1388     S.BuildBasePathArray(Paths, BasePath);
1389   }
1390 
1391   // The above search did not check whether the selected class itself has base
1392   // classes with fields, so check that now.
1393   CXXBasePaths Paths;
1394   if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1395     S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1396       << (ClassWithFields == RD) << RD << ClassWithFields
1397       << Paths.front().back().Base->getType();
1398     return DeclAccessPair();
1399   }
1400 
1401   return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1402 }
1403 
1404 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1405                                      ValueDecl *Src, QualType DecompType,
1406                                      const CXXRecordDecl *OrigRD) {
1407   if (S.RequireCompleteType(Src->getLocation(), DecompType,
1408                             diag::err_incomplete_type))
1409     return true;
1410 
1411   CXXCastPath BasePath;
1412   DeclAccessPair BasePair =
1413       findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1414   const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1415   if (!RD)
1416     return true;
1417   QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1418                                                  DecompType.getQualifiers());
1419 
1420   auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1421     unsigned NumFields = llvm::count_if(
1422         RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1423     assert(Bindings.size() != NumFields);
1424     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1425         << DecompType << (unsigned)Bindings.size() << NumFields << NumFields
1426         << (NumFields < Bindings.size());
1427     return true;
1428   };
1429 
1430   //   all of E's non-static data members shall be [...] well-formed
1431   //   when named as e.name in the context of the structured binding,
1432   //   E shall not have an anonymous union member, ...
1433   unsigned I = 0;
1434   for (auto *FD : RD->fields()) {
1435     if (FD->isUnnamedBitfield())
1436       continue;
1437 
1438     // All the non-static data members are required to be nameable, so they
1439     // must all have names.
1440     if (!FD->getDeclName()) {
1441       if (RD->isLambda()) {
1442         S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda);
1443         S.Diag(RD->getLocation(), diag::note_lambda_decl);
1444         return true;
1445       }
1446 
1447       if (FD->isAnonymousStructOrUnion()) {
1448         S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1449           << DecompType << FD->getType()->isUnionType();
1450         S.Diag(FD->getLocation(), diag::note_declared_at);
1451         return true;
1452       }
1453 
1454       // FIXME: Are there any other ways we could have an anonymous member?
1455     }
1456 
1457     // We have a real field to bind.
1458     if (I >= Bindings.size())
1459       return DiagnoseBadNumberOfBindings();
1460     auto *B = Bindings[I++];
1461     SourceLocation Loc = B->getLocation();
1462 
1463     // The field must be accessible in the context of the structured binding.
1464     // We already checked that the base class is accessible.
1465     // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1466     // const_cast here.
1467     S.CheckStructuredBindingMemberAccess(
1468         Loc, const_cast<CXXRecordDecl *>(OrigRD),
1469         DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1470                                      BasePair.getAccess(), FD->getAccess())));
1471 
1472     // Initialize the binding to Src.FD.
1473     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1474     if (E.isInvalid())
1475       return true;
1476     E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1477                             VK_LValue, &BasePath);
1478     if (E.isInvalid())
1479       return true;
1480     E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1481                                   CXXScopeSpec(), FD,
1482                                   DeclAccessPair::make(FD, FD->getAccess()),
1483                                   DeclarationNameInfo(FD->getDeclName(), Loc));
1484     if (E.isInvalid())
1485       return true;
1486 
1487     // If the type of the member is T, the referenced type is cv T, where cv is
1488     // the cv-qualification of the decomposition expression.
1489     //
1490     // FIXME: We resolve a defect here: if the field is mutable, we do not add
1491     // 'const' to the type of the field.
1492     Qualifiers Q = DecompType.getQualifiers();
1493     if (FD->isMutable())
1494       Q.removeConst();
1495     B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1496   }
1497 
1498   if (I != Bindings.size())
1499     return DiagnoseBadNumberOfBindings();
1500 
1501   return false;
1502 }
1503 
1504 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1505   QualType DecompType = DD->getType();
1506 
1507   // If the type of the decomposition is dependent, then so is the type of
1508   // each binding.
1509   if (DecompType->isDependentType()) {
1510     for (auto *B : DD->bindings())
1511       B->setType(Context.DependentTy);
1512     return;
1513   }
1514 
1515   DecompType = DecompType.getNonReferenceType();
1516   ArrayRef<BindingDecl*> Bindings = DD->bindings();
1517 
1518   // C++1z [dcl.decomp]/2:
1519   //   If E is an array type [...]
1520   // As an extension, we also support decomposition of built-in complex and
1521   // vector types.
1522   if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1523     if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1524       DD->setInvalidDecl();
1525     return;
1526   }
1527   if (auto *VT = DecompType->getAs<VectorType>()) {
1528     if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1529       DD->setInvalidDecl();
1530     return;
1531   }
1532   if (auto *CT = DecompType->getAs<ComplexType>()) {
1533     if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1534       DD->setInvalidDecl();
1535     return;
1536   }
1537 
1538   // C++1z [dcl.decomp]/3:
1539   //   if the expression std::tuple_size<E>::value is a well-formed integral
1540   //   constant expression, [...]
1541   llvm::APSInt TupleSize(32);
1542   switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1543   case IsTupleLike::Error:
1544     DD->setInvalidDecl();
1545     return;
1546 
1547   case IsTupleLike::TupleLike:
1548     if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1549       DD->setInvalidDecl();
1550     return;
1551 
1552   case IsTupleLike::NotTupleLike:
1553     break;
1554   }
1555 
1556   // C++1z [dcl.dcl]/8:
1557   //   [E shall be of array or non-union class type]
1558   CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1559   if (!RD || RD->isUnion()) {
1560     Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1561         << DD << !RD << DecompType;
1562     DD->setInvalidDecl();
1563     return;
1564   }
1565 
1566   // C++1z [dcl.decomp]/4:
1567   //   all of E's non-static data members shall be [...] direct members of
1568   //   E or of the same unambiguous public base class of E, ...
1569   if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1570     DD->setInvalidDecl();
1571 }
1572 
1573 /// Merge the exception specifications of two variable declarations.
1574 ///
1575 /// This is called when there's a redeclaration of a VarDecl. The function
1576 /// checks if the redeclaration might have an exception specification and
1577 /// validates compatibility and merges the specs if necessary.
1578 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1579   // Shortcut if exceptions are disabled.
1580   if (!getLangOpts().CXXExceptions)
1581     return;
1582 
1583   assert(Context.hasSameType(New->getType(), Old->getType()) &&
1584          "Should only be called if types are otherwise the same.");
1585 
1586   QualType NewType = New->getType();
1587   QualType OldType = Old->getType();
1588 
1589   // We're only interested in pointers and references to functions, as well
1590   // as pointers to member functions.
1591   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1592     NewType = R->getPointeeType();
1593     OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1594   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1595     NewType = P->getPointeeType();
1596     OldType = OldType->castAs<PointerType>()->getPointeeType();
1597   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1598     NewType = M->getPointeeType();
1599     OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1600   }
1601 
1602   if (!NewType->isFunctionProtoType())
1603     return;
1604 
1605   // There's lots of special cases for functions. For function pointers, system
1606   // libraries are hopefully not as broken so that we don't need these
1607   // workarounds.
1608   if (CheckEquivalentExceptionSpec(
1609         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1610         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1611     New->setInvalidDecl();
1612   }
1613 }
1614 
1615 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1616 /// function declaration are well-formed according to C++
1617 /// [dcl.fct.default].
1618 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1619   unsigned NumParams = FD->getNumParams();
1620   unsigned ParamIdx = 0;
1621 
1622   // This checking doesn't make sense for explicit specializations; their
1623   // default arguments are determined by the declaration we're specializing,
1624   // not by FD.
1625   if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1626     return;
1627   if (auto *FTD = FD->getDescribedFunctionTemplate())
1628     if (FTD->isMemberSpecialization())
1629       return;
1630 
1631   // Find first parameter with a default argument
1632   for (; ParamIdx < NumParams; ++ParamIdx) {
1633     ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1634     if (Param->hasDefaultArg())
1635       break;
1636   }
1637 
1638   // C++20 [dcl.fct.default]p4:
1639   //   In a given function declaration, each parameter subsequent to a parameter
1640   //   with a default argument shall have a default argument supplied in this or
1641   //   a previous declaration, unless the parameter was expanded from a
1642   //   parameter pack, or shall be a function parameter pack.
1643   for (; ParamIdx < NumParams; ++ParamIdx) {
1644     ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1645     if (!Param->hasDefaultArg() && !Param->isParameterPack() &&
1646         !(CurrentInstantiationScope &&
1647           CurrentInstantiationScope->isLocalPackExpansion(Param))) {
1648       if (Param->isInvalidDecl())
1649         /* We already complained about this parameter. */;
1650       else if (Param->getIdentifier())
1651         Diag(Param->getLocation(),
1652              diag::err_param_default_argument_missing_name)
1653           << Param->getIdentifier();
1654       else
1655         Diag(Param->getLocation(),
1656              diag::err_param_default_argument_missing);
1657     }
1658   }
1659 }
1660 
1661 /// Check that the given type is a literal type. Issue a diagnostic if not,
1662 /// if Kind is Diagnose.
1663 /// \return \c true if a problem has been found (and optionally diagnosed).
1664 template <typename... Ts>
1665 static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
1666                              SourceLocation Loc, QualType T, unsigned DiagID,
1667                              Ts &&...DiagArgs) {
1668   if (T->isDependentType())
1669     return false;
1670 
1671   switch (Kind) {
1672   case Sema::CheckConstexprKind::Diagnose:
1673     return SemaRef.RequireLiteralType(Loc, T, DiagID,
1674                                       std::forward<Ts>(DiagArgs)...);
1675 
1676   case Sema::CheckConstexprKind::CheckValid:
1677     return !T->isLiteralType(SemaRef.Context);
1678   }
1679 
1680   llvm_unreachable("unknown CheckConstexprKind");
1681 }
1682 
1683 /// Determine whether a destructor cannot be constexpr due to
1684 static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
1685                                                const CXXDestructorDecl *DD,
1686                                                Sema::CheckConstexprKind Kind) {
1687   auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1688     const CXXRecordDecl *RD =
1689         T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1690     if (!RD || RD->hasConstexprDestructor())
1691       return true;
1692 
1693     if (Kind == Sema::CheckConstexprKind::Diagnose) {
1694       SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1695           << static_cast<int>(DD->getConstexprKind()) << !FD
1696           << (FD ? FD->getDeclName() : DeclarationName()) << T;
1697       SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1698           << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1699     }
1700     return false;
1701   };
1702 
1703   const CXXRecordDecl *RD = DD->getParent();
1704   for (const CXXBaseSpecifier &B : RD->bases())
1705     if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1706       return false;
1707   for (const FieldDecl *FD : RD->fields())
1708     if (!Check(FD->getLocation(), FD->getType(), FD))
1709       return false;
1710   return true;
1711 }
1712 
1713 /// Check whether a function's parameter types are all literal types. If so,
1714 /// return true. If not, produce a suitable diagnostic and return false.
1715 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1716                                          const FunctionDecl *FD,
1717                                          Sema::CheckConstexprKind Kind) {
1718   unsigned ArgIndex = 0;
1719   const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1720   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1721                                               e = FT->param_type_end();
1722        i != e; ++i, ++ArgIndex) {
1723     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1724     SourceLocation ParamLoc = PD->getLocation();
1725     if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1726                          diag::err_constexpr_non_literal_param, ArgIndex + 1,
1727                          PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1728                          FD->isConsteval()))
1729       return false;
1730   }
1731   return true;
1732 }
1733 
1734 /// Check whether a function's return type is a literal type. If so, return
1735 /// true. If not, produce a suitable diagnostic and return false.
1736 static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1737                                      Sema::CheckConstexprKind Kind) {
1738   if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1739                        diag::err_constexpr_non_literal_return,
1740                        FD->isConsteval()))
1741     return false;
1742   return true;
1743 }
1744 
1745 /// Get diagnostic %select index for tag kind for
1746 /// record diagnostic message.
1747 /// WARNING: Indexes apply to particular diagnostics only!
1748 ///
1749 /// \returns diagnostic %select index.
1750 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1751   switch (Tag) {
1752   case TTK_Struct: return 0;
1753   case TTK_Interface: return 1;
1754   case TTK_Class:  return 2;
1755   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1756   }
1757 }
1758 
1759 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1760                                        Stmt *Body,
1761                                        Sema::CheckConstexprKind Kind);
1762 
1763 // Check whether a function declaration satisfies the requirements of a
1764 // constexpr function definition or a constexpr constructor definition. If so,
1765 // return true. If not, produce appropriate diagnostics (unless asked not to by
1766 // Kind) and return false.
1767 //
1768 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1769 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
1770                                             CheckConstexprKind Kind) {
1771   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1772   if (MD && MD->isInstance()) {
1773     // C++11 [dcl.constexpr]p4:
1774     //  The definition of a constexpr constructor shall satisfy the following
1775     //  constraints:
1776     //  - the class shall not have any virtual base classes;
1777     //
1778     // FIXME: This only applies to constructors and destructors, not arbitrary
1779     // member functions.
1780     const CXXRecordDecl *RD = MD->getParent();
1781     if (RD->getNumVBases()) {
1782       if (Kind == CheckConstexprKind::CheckValid)
1783         return false;
1784 
1785       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1786         << isa<CXXConstructorDecl>(NewFD)
1787         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1788       for (const auto &I : RD->vbases())
1789         Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1790             << I.getSourceRange();
1791       return false;
1792     }
1793   }
1794 
1795   if (!isa<CXXConstructorDecl>(NewFD)) {
1796     // C++11 [dcl.constexpr]p3:
1797     //  The definition of a constexpr function shall satisfy the following
1798     //  constraints:
1799     // - it shall not be virtual; (removed in C++20)
1800     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1801     if (Method && Method->isVirtual()) {
1802       if (getLangOpts().CPlusPlus20) {
1803         if (Kind == CheckConstexprKind::Diagnose)
1804           Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1805       } else {
1806         if (Kind == CheckConstexprKind::CheckValid)
1807           return false;
1808 
1809         Method = Method->getCanonicalDecl();
1810         Diag(Method->getLocation(), diag::err_constexpr_virtual);
1811 
1812         // If it's not obvious why this function is virtual, find an overridden
1813         // function which uses the 'virtual' keyword.
1814         const CXXMethodDecl *WrittenVirtual = Method;
1815         while (!WrittenVirtual->isVirtualAsWritten())
1816           WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1817         if (WrittenVirtual != Method)
1818           Diag(WrittenVirtual->getLocation(),
1819                diag::note_overridden_virtual_function);
1820         return false;
1821       }
1822     }
1823 
1824     // - its return type shall be a literal type;
1825     if (!CheckConstexprReturnType(*this, NewFD, Kind))
1826       return false;
1827   }
1828 
1829   if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1830     // A destructor can be constexpr only if the defaulted destructor could be;
1831     // we don't need to check the members and bases if we already know they all
1832     // have constexpr destructors.
1833     if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1834       if (Kind == CheckConstexprKind::CheckValid)
1835         return false;
1836       if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1837         return false;
1838     }
1839   }
1840 
1841   // - each of its parameter types shall be a literal type;
1842   if (!CheckConstexprParameterTypes(*this, NewFD, Kind))
1843     return false;
1844 
1845   Stmt *Body = NewFD->getBody();
1846   assert(Body &&
1847          "CheckConstexprFunctionDefinition called on function with no body");
1848   return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1849 }
1850 
1851 /// Check the given declaration statement is legal within a constexpr function
1852 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1853 ///
1854 /// \return true if the body is OK (maybe only as an extension), false if we
1855 ///         have diagnosed a problem.
1856 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1857                                    DeclStmt *DS, SourceLocation &Cxx1yLoc,
1858                                    Sema::CheckConstexprKind Kind) {
1859   // C++11 [dcl.constexpr]p3 and p4:
1860   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
1861   //  contain only
1862   for (const auto *DclIt : DS->decls()) {
1863     switch (DclIt->getKind()) {
1864     case Decl::StaticAssert:
1865     case Decl::Using:
1866     case Decl::UsingShadow:
1867     case Decl::UsingDirective:
1868     case Decl::UnresolvedUsingTypename:
1869     case Decl::UnresolvedUsingValue:
1870     case Decl::UsingEnum:
1871       //   - static_assert-declarations
1872       //   - using-declarations,
1873       //   - using-directives,
1874       //   - using-enum-declaration
1875       continue;
1876 
1877     case Decl::Typedef:
1878     case Decl::TypeAlias: {
1879       //   - typedef declarations and alias-declarations that do not define
1880       //     classes or enumerations,
1881       const auto *TN = cast<TypedefNameDecl>(DclIt);
1882       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1883         // Don't allow variably-modified types in constexpr functions.
1884         if (Kind == Sema::CheckConstexprKind::Diagnose) {
1885           TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1886           SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1887             << TL.getSourceRange() << TL.getType()
1888             << isa<CXXConstructorDecl>(Dcl);
1889         }
1890         return false;
1891       }
1892       continue;
1893     }
1894 
1895     case Decl::Enum:
1896     case Decl::CXXRecord:
1897       // C++1y allows types to be defined, not just declared.
1898       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1899         if (Kind == Sema::CheckConstexprKind::Diagnose) {
1900           SemaRef.Diag(DS->getBeginLoc(),
1901                        SemaRef.getLangOpts().CPlusPlus14
1902                            ? diag::warn_cxx11_compat_constexpr_type_definition
1903                            : diag::ext_constexpr_type_definition)
1904               << isa<CXXConstructorDecl>(Dcl);
1905         } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1906           return false;
1907         }
1908       }
1909       continue;
1910 
1911     case Decl::EnumConstant:
1912     case Decl::IndirectField:
1913     case Decl::ParmVar:
1914       // These can only appear with other declarations which are banned in
1915       // C++11 and permitted in C++1y, so ignore them.
1916       continue;
1917 
1918     case Decl::Var:
1919     case Decl::Decomposition: {
1920       // C++1y [dcl.constexpr]p3 allows anything except:
1921       //   a definition of a variable of non-literal type or of static or
1922       //   thread storage duration or [before C++2a] for which no
1923       //   initialization is performed.
1924       const auto *VD = cast<VarDecl>(DclIt);
1925       if (VD->isThisDeclarationADefinition()) {
1926         if (VD->isStaticLocal()) {
1927           if (Kind == Sema::CheckConstexprKind::Diagnose) {
1928             SemaRef.Diag(VD->getLocation(),
1929                          SemaRef.getLangOpts().CPlusPlus2b
1930                              ? diag::warn_cxx20_compat_constexpr_var
1931                              : diag::ext_constexpr_static_var)
1932                 << isa<CXXConstructorDecl>(Dcl)
1933                 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1934           } else if (!SemaRef.getLangOpts().CPlusPlus2b) {
1935             return false;
1936           }
1937         }
1938         if (SemaRef.LangOpts.CPlusPlus2b) {
1939           CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1940                            diag::warn_cxx20_compat_constexpr_var,
1941                            isa<CXXConstructorDecl>(Dcl),
1942                            /*variable of non-literal type*/ 2);
1943         } else if (CheckLiteralType(
1944                        SemaRef, Kind, VD->getLocation(), VD->getType(),
1945                        diag::err_constexpr_local_var_non_literal_type,
1946                        isa<CXXConstructorDecl>(Dcl))) {
1947           return false;
1948         }
1949         if (!VD->getType()->isDependentType() &&
1950             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1951           if (Kind == Sema::CheckConstexprKind::Diagnose) {
1952             SemaRef.Diag(
1953                 VD->getLocation(),
1954                 SemaRef.getLangOpts().CPlusPlus20
1955                     ? diag::warn_cxx17_compat_constexpr_local_var_no_init
1956                     : diag::ext_constexpr_local_var_no_init)
1957                 << isa<CXXConstructorDecl>(Dcl);
1958           } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1959             return false;
1960           }
1961           continue;
1962         }
1963       }
1964       if (Kind == Sema::CheckConstexprKind::Diagnose) {
1965         SemaRef.Diag(VD->getLocation(),
1966                      SemaRef.getLangOpts().CPlusPlus14
1967                       ? diag::warn_cxx11_compat_constexpr_local_var
1968                       : diag::ext_constexpr_local_var)
1969           << isa<CXXConstructorDecl>(Dcl);
1970       } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1971         return false;
1972       }
1973       continue;
1974     }
1975 
1976     case Decl::NamespaceAlias:
1977     case Decl::Function:
1978       // These are disallowed in C++11 and permitted in C++1y. Allow them
1979       // everywhere as an extension.
1980       if (!Cxx1yLoc.isValid())
1981         Cxx1yLoc = DS->getBeginLoc();
1982       continue;
1983 
1984     default:
1985       if (Kind == Sema::CheckConstexprKind::Diagnose) {
1986         SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1987             << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
1988       }
1989       return false;
1990     }
1991   }
1992 
1993   return true;
1994 }
1995 
1996 /// Check that the given field is initialized within a constexpr constructor.
1997 ///
1998 /// \param Dcl The constexpr constructor being checked.
1999 /// \param Field The field being checked. This may be a member of an anonymous
2000 ///        struct or union nested within the class being checked.
2001 /// \param Inits All declarations, including anonymous struct/union members and
2002 ///        indirect members, for which any initialization was provided.
2003 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach
2004 ///        multiple notes for different members to the same error.
2005 /// \param Kind Whether we're diagnosing a constructor as written or determining
2006 ///        whether the formal requirements are satisfied.
2007 /// \return \c false if we're checking for validity and the constructor does
2008 ///         not satisfy the requirements on a constexpr constructor.
2009 static bool CheckConstexprCtorInitializer(Sema &SemaRef,
2010                                           const FunctionDecl *Dcl,
2011                                           FieldDecl *Field,
2012                                           llvm::SmallSet<Decl*, 16> &Inits,
2013                                           bool &Diagnosed,
2014                                           Sema::CheckConstexprKind Kind) {
2015   // In C++20 onwards, there's nothing to check for validity.
2016   if (Kind == Sema::CheckConstexprKind::CheckValid &&
2017       SemaRef.getLangOpts().CPlusPlus20)
2018     return true;
2019 
2020   if (Field->isInvalidDecl())
2021     return true;
2022 
2023   if (Field->isUnnamedBitfield())
2024     return true;
2025 
2026   // Anonymous unions with no variant members and empty anonymous structs do not
2027   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
2028   // indirect fields don't need initializing.
2029   if (Field->isAnonymousStructOrUnion() &&
2030       (Field->getType()->isUnionType()
2031            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
2032            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
2033     return true;
2034 
2035   if (!Inits.count(Field)) {
2036     if (Kind == Sema::CheckConstexprKind::Diagnose) {
2037       if (!Diagnosed) {
2038         SemaRef.Diag(Dcl->getLocation(),
2039                      SemaRef.getLangOpts().CPlusPlus20
2040                          ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
2041                          : diag::ext_constexpr_ctor_missing_init);
2042         Diagnosed = true;
2043       }
2044       SemaRef.Diag(Field->getLocation(),
2045                    diag::note_constexpr_ctor_missing_init);
2046     } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2047       return false;
2048     }
2049   } else if (Field->isAnonymousStructOrUnion()) {
2050     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
2051     for (auto *I : RD->fields())
2052       // If an anonymous union contains an anonymous struct of which any member
2053       // is initialized, all members must be initialized.
2054       if (!RD->isUnion() || Inits.count(I))
2055         if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2056                                            Kind))
2057           return false;
2058   }
2059   return true;
2060 }
2061 
2062 /// Check the provided statement is allowed in a constexpr function
2063 /// definition.
2064 static bool
2065 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
2066                            SmallVectorImpl<SourceLocation> &ReturnStmts,
2067                            SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2068                            SourceLocation &Cxx2bLoc,
2069                            Sema::CheckConstexprKind Kind) {
2070   // - its function-body shall be [...] a compound-statement that contains only
2071   switch (S->getStmtClass()) {
2072   case Stmt::NullStmtClass:
2073     //   - null statements,
2074     return true;
2075 
2076   case Stmt::DeclStmtClass:
2077     //   - static_assert-declarations
2078     //   - using-declarations,
2079     //   - using-directives,
2080     //   - typedef declarations and alias-declarations that do not define
2081     //     classes or enumerations,
2082     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
2083       return false;
2084     return true;
2085 
2086   case Stmt::ReturnStmtClass:
2087     //   - and exactly one return statement;
2088     if (isa<CXXConstructorDecl>(Dcl)) {
2089       // C++1y allows return statements in constexpr constructors.
2090       if (!Cxx1yLoc.isValid())
2091         Cxx1yLoc = S->getBeginLoc();
2092       return true;
2093     }
2094 
2095     ReturnStmts.push_back(S->getBeginLoc());
2096     return true;
2097 
2098   case Stmt::AttributedStmtClass:
2099     // Attributes on a statement don't affect its formal kind and hence don't
2100     // affect its validity in a constexpr function.
2101     return CheckConstexprFunctionStmt(
2102         SemaRef, Dcl, cast<AttributedStmt>(S)->getSubStmt(), ReturnStmts,
2103         Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);
2104 
2105   case Stmt::CompoundStmtClass: {
2106     // C++1y allows compound-statements.
2107     if (!Cxx1yLoc.isValid())
2108       Cxx1yLoc = S->getBeginLoc();
2109 
2110     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2111     for (auto *BodyIt : CompStmt->body()) {
2112       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2113                                       Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2114         return false;
2115     }
2116     return true;
2117   }
2118 
2119   case Stmt::IfStmtClass: {
2120     // C++1y allows if-statements.
2121     if (!Cxx1yLoc.isValid())
2122       Cxx1yLoc = S->getBeginLoc();
2123 
2124     IfStmt *If = cast<IfStmt>(S);
2125     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2126                                     Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2127       return false;
2128     if (If->getElse() &&
2129         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2130                                     Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2131       return false;
2132     return true;
2133   }
2134 
2135   case Stmt::WhileStmtClass:
2136   case Stmt::DoStmtClass:
2137   case Stmt::ForStmtClass:
2138   case Stmt::CXXForRangeStmtClass:
2139   case Stmt::ContinueStmtClass:
2140     // C++1y allows all of these. We don't allow them as extensions in C++11,
2141     // because they don't make sense without variable mutation.
2142     if (!SemaRef.getLangOpts().CPlusPlus14)
2143       break;
2144     if (!Cxx1yLoc.isValid())
2145       Cxx1yLoc = S->getBeginLoc();
2146     for (Stmt *SubStmt : S->children()) {
2147       if (SubStmt &&
2148           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2149                                       Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2150         return false;
2151     }
2152     return true;
2153 
2154   case Stmt::SwitchStmtClass:
2155   case Stmt::CaseStmtClass:
2156   case Stmt::DefaultStmtClass:
2157   case Stmt::BreakStmtClass:
2158     // C++1y allows switch-statements, and since they don't need variable
2159     // mutation, we can reasonably allow them in C++11 as an extension.
2160     if (!Cxx1yLoc.isValid())
2161       Cxx1yLoc = S->getBeginLoc();
2162     for (Stmt *SubStmt : S->children()) {
2163       if (SubStmt &&
2164           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2165                                       Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2166         return false;
2167     }
2168     return true;
2169 
2170   case Stmt::LabelStmtClass:
2171   case Stmt::GotoStmtClass:
2172     if (Cxx2bLoc.isInvalid())
2173       Cxx2bLoc = S->getBeginLoc();
2174     for (Stmt *SubStmt : S->children()) {
2175       if (SubStmt &&
2176           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2177                                       Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2178         return false;
2179     }
2180     return true;
2181 
2182   case Stmt::GCCAsmStmtClass:
2183   case Stmt::MSAsmStmtClass:
2184     // C++2a allows inline assembly statements.
2185   case Stmt::CXXTryStmtClass:
2186     if (Cxx2aLoc.isInvalid())
2187       Cxx2aLoc = S->getBeginLoc();
2188     for (Stmt *SubStmt : S->children()) {
2189       if (SubStmt &&
2190           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2191                                       Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2192         return false;
2193     }
2194     return true;
2195 
2196   case Stmt::CXXCatchStmtClass:
2197     // Do not bother checking the language mode (already covered by the
2198     // try block check).
2199     if (!CheckConstexprFunctionStmt(
2200             SemaRef, Dcl, cast<CXXCatchStmt>(S)->getHandlerBlock(), ReturnStmts,
2201             Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2202       return false;
2203     return true;
2204 
2205   default:
2206     if (!isa<Expr>(S))
2207       break;
2208 
2209     // C++1y allows expression-statements.
2210     if (!Cxx1yLoc.isValid())
2211       Cxx1yLoc = S->getBeginLoc();
2212     return true;
2213   }
2214 
2215   if (Kind == Sema::CheckConstexprKind::Diagnose) {
2216     SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2217         << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2218   }
2219   return false;
2220 }
2221 
2222 /// Check the body for the given constexpr function declaration only contains
2223 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2224 ///
2225 /// \return true if the body is OK, false if we have found or diagnosed a
2226 /// problem.
2227 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2228                                        Stmt *Body,
2229                                        Sema::CheckConstexprKind Kind) {
2230   SmallVector<SourceLocation, 4> ReturnStmts;
2231 
2232   if (isa<CXXTryStmt>(Body)) {
2233     // C++11 [dcl.constexpr]p3:
2234     //  The definition of a constexpr function shall satisfy the following
2235     //  constraints: [...]
2236     // - its function-body shall be = delete, = default, or a
2237     //   compound-statement
2238     //
2239     // C++11 [dcl.constexpr]p4:
2240     //  In the definition of a constexpr constructor, [...]
2241     // - its function-body shall not be a function-try-block;
2242     //
2243     // This restriction is lifted in C++2a, as long as inner statements also
2244     // apply the general constexpr rules.
2245     switch (Kind) {
2246     case Sema::CheckConstexprKind::CheckValid:
2247       if (!SemaRef.getLangOpts().CPlusPlus20)
2248         return false;
2249       break;
2250 
2251     case Sema::CheckConstexprKind::Diagnose:
2252       SemaRef.Diag(Body->getBeginLoc(),
2253            !SemaRef.getLangOpts().CPlusPlus20
2254                ? diag::ext_constexpr_function_try_block_cxx20
2255                : diag::warn_cxx17_compat_constexpr_function_try_block)
2256           << isa<CXXConstructorDecl>(Dcl);
2257       break;
2258     }
2259   }
2260 
2261   // - its function-body shall be [...] a compound-statement that contains only
2262   //   [... list of cases ...]
2263   //
2264   // Note that walking the children here is enough to properly check for
2265   // CompoundStmt and CXXTryStmt body.
2266   SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc;
2267   for (Stmt *SubStmt : Body->children()) {
2268     if (SubStmt &&
2269         !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2270                                     Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2271       return false;
2272   }
2273 
2274   if (Kind == Sema::CheckConstexprKind::CheckValid) {
2275     // If this is only valid as an extension, report that we don't satisfy the
2276     // constraints of the current language.
2277     if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus2b) ||
2278         (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2279         (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2280       return false;
2281   } else if (Cxx2bLoc.isValid()) {
2282     SemaRef.Diag(Cxx2bLoc,
2283                  SemaRef.getLangOpts().CPlusPlus2b
2284                      ? diag::warn_cxx20_compat_constexpr_body_invalid_stmt
2285                      : diag::ext_constexpr_body_invalid_stmt_cxx2b)
2286         << isa<CXXConstructorDecl>(Dcl);
2287   } else if (Cxx2aLoc.isValid()) {
2288     SemaRef.Diag(Cxx2aLoc,
2289          SemaRef.getLangOpts().CPlusPlus20
2290            ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2291            : diag::ext_constexpr_body_invalid_stmt_cxx20)
2292       << isa<CXXConstructorDecl>(Dcl);
2293   } else if (Cxx1yLoc.isValid()) {
2294     SemaRef.Diag(Cxx1yLoc,
2295          SemaRef.getLangOpts().CPlusPlus14
2296            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2297            : diag::ext_constexpr_body_invalid_stmt)
2298       << isa<CXXConstructorDecl>(Dcl);
2299   }
2300 
2301   if (const CXXConstructorDecl *Constructor
2302         = dyn_cast<CXXConstructorDecl>(Dcl)) {
2303     const CXXRecordDecl *RD = Constructor->getParent();
2304     // DR1359:
2305     // - every non-variant non-static data member and base class sub-object
2306     //   shall be initialized;
2307     // DR1460:
2308     // - if the class is a union having variant members, exactly one of them
2309     //   shall be initialized;
2310     if (RD->isUnion()) {
2311       if (Constructor->getNumCtorInitializers() == 0 &&
2312           RD->hasVariantMembers()) {
2313         if (Kind == Sema::CheckConstexprKind::Diagnose) {
2314           SemaRef.Diag(
2315               Dcl->getLocation(),
2316               SemaRef.getLangOpts().CPlusPlus20
2317                   ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2318                   : diag::ext_constexpr_union_ctor_no_init);
2319         } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2320           return false;
2321         }
2322       }
2323     } else if (!Constructor->isDependentContext() &&
2324                !Constructor->isDelegatingConstructor()) {
2325       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2326 
2327       // Skip detailed checking if we have enough initializers, and we would
2328       // allow at most one initializer per member.
2329       bool AnyAnonStructUnionMembers = false;
2330       unsigned Fields = 0;
2331       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2332            E = RD->field_end(); I != E; ++I, ++Fields) {
2333         if (I->isAnonymousStructOrUnion()) {
2334           AnyAnonStructUnionMembers = true;
2335           break;
2336         }
2337       }
2338       // DR1460:
2339       // - if the class is a union-like class, but is not a union, for each of
2340       //   its anonymous union members having variant members, exactly one of
2341       //   them shall be initialized;
2342       if (AnyAnonStructUnionMembers ||
2343           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2344         // Check initialization of non-static data members. Base classes are
2345         // always initialized so do not need to be checked. Dependent bases
2346         // might not have initializers in the member initializer list.
2347         llvm::SmallSet<Decl*, 16> Inits;
2348         for (const auto *I: Constructor->inits()) {
2349           if (FieldDecl *FD = I->getMember())
2350             Inits.insert(FD);
2351           else if (IndirectFieldDecl *ID = I->getIndirectMember())
2352             Inits.insert(ID->chain_begin(), ID->chain_end());
2353         }
2354 
2355         bool Diagnosed = false;
2356         for (auto *I : RD->fields())
2357           if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2358                                              Kind))
2359             return false;
2360       }
2361     }
2362   } else {
2363     if (ReturnStmts.empty()) {
2364       // C++1y doesn't require constexpr functions to contain a 'return'
2365       // statement. We still do, unless the return type might be void, because
2366       // otherwise if there's no return statement, the function cannot
2367       // be used in a core constant expression.
2368       bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
2369                 (Dcl->getReturnType()->isVoidType() ||
2370                  Dcl->getReturnType()->isDependentType());
2371       switch (Kind) {
2372       case Sema::CheckConstexprKind::Diagnose:
2373         SemaRef.Diag(Dcl->getLocation(),
2374                      OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2375                         : diag::err_constexpr_body_no_return)
2376             << Dcl->isConsteval();
2377         if (!OK)
2378           return false;
2379         break;
2380 
2381       case Sema::CheckConstexprKind::CheckValid:
2382         // The formal requirements don't include this rule in C++14, even
2383         // though the "must be able to produce a constant expression" rules
2384         // still imply it in some cases.
2385         if (!SemaRef.getLangOpts().CPlusPlus14)
2386           return false;
2387         break;
2388       }
2389     } else if (ReturnStmts.size() > 1) {
2390       switch (Kind) {
2391       case Sema::CheckConstexprKind::Diagnose:
2392         SemaRef.Diag(
2393             ReturnStmts.back(),
2394             SemaRef.getLangOpts().CPlusPlus14
2395                 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2396                 : diag::ext_constexpr_body_multiple_return);
2397         for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2398           SemaRef.Diag(ReturnStmts[I],
2399                        diag::note_constexpr_body_previous_return);
2400         break;
2401 
2402       case Sema::CheckConstexprKind::CheckValid:
2403         if (!SemaRef.getLangOpts().CPlusPlus14)
2404           return false;
2405         break;
2406       }
2407     }
2408   }
2409 
2410   // C++11 [dcl.constexpr]p5:
2411   //   if no function argument values exist such that the function invocation
2412   //   substitution would produce a constant expression, the program is
2413   //   ill-formed; no diagnostic required.
2414   // C++11 [dcl.constexpr]p3:
2415   //   - every constructor call and implicit conversion used in initializing the
2416   //     return value shall be one of those allowed in a constant expression.
2417   // C++11 [dcl.constexpr]p4:
2418   //   - every constructor involved in initializing non-static data members and
2419   //     base class sub-objects shall be a constexpr constructor.
2420   //
2421   // Note that this rule is distinct from the "requirements for a constexpr
2422   // function", so is not checked in CheckValid mode.
2423   SmallVector<PartialDiagnosticAt, 8> Diags;
2424   if (Kind == Sema::CheckConstexprKind::Diagnose &&
2425       !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2426     SemaRef.Diag(Dcl->getLocation(),
2427                  diag::ext_constexpr_function_never_constant_expr)
2428         << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2429     for (size_t I = 0, N = Diags.size(); I != N; ++I)
2430       SemaRef.Diag(Diags[I].first, Diags[I].second);
2431     // Don't return false here: we allow this for compatibility in
2432     // system headers.
2433   }
2434 
2435   return true;
2436 }
2437 
2438 /// Get the class that is directly named by the current context. This is the
2439 /// class for which an unqualified-id in this scope could name a constructor
2440 /// or destructor.
2441 ///
2442 /// If the scope specifier denotes a class, this will be that class.
2443 /// If the scope specifier is empty, this will be the class whose
2444 /// member-specification we are currently within. Otherwise, there
2445 /// is no such class.
2446 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2447   assert(getLangOpts().CPlusPlus && "No class names in C!");
2448 
2449   if (SS && SS->isInvalid())
2450     return nullptr;
2451 
2452   if (SS && SS->isNotEmpty()) {
2453     DeclContext *DC = computeDeclContext(*SS, true);
2454     return dyn_cast_or_null<CXXRecordDecl>(DC);
2455   }
2456 
2457   return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2458 }
2459 
2460 /// isCurrentClassName - Determine whether the identifier II is the
2461 /// name of the class type currently being defined. In the case of
2462 /// nested classes, this will only return true if II is the name of
2463 /// the innermost class.
2464 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2465                               const CXXScopeSpec *SS) {
2466   CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2467   return CurDecl && &II == CurDecl->getIdentifier();
2468 }
2469 
2470 /// Determine whether the identifier II is a typo for the name of
2471 /// the class type currently being defined. If so, update it to the identifier
2472 /// that should have been used.
2473 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2474   assert(getLangOpts().CPlusPlus && "No class names in C!");
2475 
2476   if (!getLangOpts().SpellChecking)
2477     return false;
2478 
2479   CXXRecordDecl *CurDecl;
2480   if (SS && SS->isSet() && !SS->isInvalid()) {
2481     DeclContext *DC = computeDeclContext(*SS, true);
2482     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2483   } else
2484     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2485 
2486   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2487       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2488           < II->getLength()) {
2489     II = CurDecl->getIdentifier();
2490     return true;
2491   }
2492 
2493   return false;
2494 }
2495 
2496 /// Determine whether the given class is a base class of the given
2497 /// class, including looking at dependent bases.
2498 static bool findCircularInheritance(const CXXRecordDecl *Class,
2499                                     const CXXRecordDecl *Current) {
2500   SmallVector<const CXXRecordDecl*, 8> Queue;
2501 
2502   Class = Class->getCanonicalDecl();
2503   while (true) {
2504     for (const auto &I : Current->bases()) {
2505       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2506       if (!Base)
2507         continue;
2508 
2509       Base = Base->getDefinition();
2510       if (!Base)
2511         continue;
2512 
2513       if (Base->getCanonicalDecl() == Class)
2514         return true;
2515 
2516       Queue.push_back(Base);
2517     }
2518 
2519     if (Queue.empty())
2520       return false;
2521 
2522     Current = Queue.pop_back_val();
2523   }
2524 
2525   return false;
2526 }
2527 
2528 /// Check the validity of a C++ base class specifier.
2529 ///
2530 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2531 /// and returns NULL otherwise.
2532 CXXBaseSpecifier *
2533 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2534                          SourceRange SpecifierRange,
2535                          bool Virtual, AccessSpecifier Access,
2536                          TypeSourceInfo *TInfo,
2537                          SourceLocation EllipsisLoc) {
2538   // In HLSL, unspecified class access is public rather than private.
2539   if (getLangOpts().HLSL && Class->getTagKind() == TTK_Class &&
2540       Access == AS_none)
2541     Access = AS_public;
2542 
2543   QualType BaseType = TInfo->getType();
2544   if (BaseType->containsErrors()) {
2545     // Already emitted a diagnostic when parsing the error type.
2546     return nullptr;
2547   }
2548   // C++ [class.union]p1:
2549   //   A union shall not have base classes.
2550   if (Class->isUnion()) {
2551     Diag(Class->getLocation(), diag::err_base_clause_on_union)
2552       << SpecifierRange;
2553     return nullptr;
2554   }
2555 
2556   if (EllipsisLoc.isValid() &&
2557       !TInfo->getType()->containsUnexpandedParameterPack()) {
2558     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2559       << TInfo->getTypeLoc().getSourceRange();
2560     EllipsisLoc = SourceLocation();
2561   }
2562 
2563   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2564 
2565   if (BaseType->isDependentType()) {
2566     // Make sure that we don't have circular inheritance among our dependent
2567     // bases. For non-dependent bases, the check for completeness below handles
2568     // this.
2569     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2570       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2571           ((BaseDecl = BaseDecl->getDefinition()) &&
2572            findCircularInheritance(Class, BaseDecl))) {
2573         Diag(BaseLoc, diag::err_circular_inheritance)
2574           << BaseType << Context.getTypeDeclType(Class);
2575 
2576         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2577           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2578             << BaseType;
2579 
2580         return nullptr;
2581       }
2582     }
2583 
2584     // Make sure that we don't make an ill-formed AST where the type of the
2585     // Class is non-dependent and its attached base class specifier is an
2586     // dependent type, which violates invariants in many clang code paths (e.g.
2587     // constexpr evaluator). If this case happens (in errory-recovery mode), we
2588     // explicitly mark the Class decl invalid. The diagnostic was already
2589     // emitted.
2590     if (!Class->getTypeForDecl()->isDependentType())
2591       Class->setInvalidDecl();
2592     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2593                                           Class->getTagKind() == TTK_Class,
2594                                           Access, TInfo, EllipsisLoc);
2595   }
2596 
2597   // Base specifiers must be record types.
2598   if (!BaseType->isRecordType()) {
2599     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2600     return nullptr;
2601   }
2602 
2603   // C++ [class.union]p1:
2604   //   A union shall not be used as a base class.
2605   if (BaseType->isUnionType()) {
2606     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2607     return nullptr;
2608   }
2609 
2610   // For the MS ABI, propagate DLL attributes to base class templates.
2611   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2612     if (Attr *ClassAttr = getDLLAttr(Class)) {
2613       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2614               BaseType->getAsCXXRecordDecl())) {
2615         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2616                                             BaseLoc);
2617       }
2618     }
2619   }
2620 
2621   // C++ [class.derived]p2:
2622   //   The class-name in a base-specifier shall not be an incompletely
2623   //   defined class.
2624   if (RequireCompleteType(BaseLoc, BaseType,
2625                           diag::err_incomplete_base_class, SpecifierRange)) {
2626     Class->setInvalidDecl();
2627     return nullptr;
2628   }
2629 
2630   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2631   RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl();
2632   assert(BaseDecl && "Record type has no declaration");
2633   BaseDecl = BaseDecl->getDefinition();
2634   assert(BaseDecl && "Base type is not incomplete, but has no definition");
2635   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2636   assert(CXXBaseDecl && "Base type is not a C++ type");
2637 
2638   // Microsoft docs say:
2639   // "If a base-class has a code_seg attribute, derived classes must have the
2640   // same attribute."
2641   const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2642   const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2643   if ((DerivedCSA || BaseCSA) &&
2644       (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2645     Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2646     Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2647       << CXXBaseDecl;
2648     return nullptr;
2649   }
2650 
2651   // A class which contains a flexible array member is not suitable for use as a
2652   // base class:
2653   //   - If the layout determines that a base comes before another base,
2654   //     the flexible array member would index into the subsequent base.
2655   //   - If the layout determines that base comes before the derived class,
2656   //     the flexible array member would index into the derived class.
2657   if (CXXBaseDecl->hasFlexibleArrayMember()) {
2658     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2659       << CXXBaseDecl->getDeclName();
2660     return nullptr;
2661   }
2662 
2663   // C++ [class]p3:
2664   //   If a class is marked final and it appears as a base-type-specifier in
2665   //   base-clause, the program is ill-formed.
2666   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2667     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2668       << CXXBaseDecl->getDeclName()
2669       << FA->isSpelledAsSealed();
2670     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2671         << CXXBaseDecl->getDeclName() << FA->getRange();
2672     return nullptr;
2673   }
2674 
2675   if (BaseDecl->isInvalidDecl())
2676     Class->setInvalidDecl();
2677 
2678   // Create the base specifier.
2679   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2680                                         Class->getTagKind() == TTK_Class,
2681                                         Access, TInfo, EllipsisLoc);
2682 }
2683 
2684 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2685 /// one entry in the base class list of a class specifier, for
2686 /// example:
2687 ///    class foo : public bar, virtual private baz {
2688 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2689 BaseResult Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2690                                     const ParsedAttributesView &Attributes,
2691                                     bool Virtual, AccessSpecifier Access,
2692                                     ParsedType basetype, SourceLocation BaseLoc,
2693                                     SourceLocation EllipsisLoc) {
2694   if (!classdecl)
2695     return true;
2696 
2697   AdjustDeclIfTemplate(classdecl);
2698   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2699   if (!Class)
2700     return true;
2701 
2702   // We haven't yet attached the base specifiers.
2703   Class->setIsParsingBaseSpecifiers();
2704 
2705   // We do not support any C++11 attributes on base-specifiers yet.
2706   // Diagnose any attributes we see.
2707   for (const ParsedAttr &AL : Attributes) {
2708     if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2709       continue;
2710     Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2711                           ? (unsigned)diag::warn_unknown_attribute_ignored
2712                           : (unsigned)diag::err_base_specifier_attribute)
2713         << AL << AL.getRange();
2714   }
2715 
2716   TypeSourceInfo *TInfo = nullptr;
2717   GetTypeFromParser(basetype, &TInfo);
2718 
2719   if (EllipsisLoc.isInvalid() &&
2720       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2721                                       UPPC_BaseType))
2722     return true;
2723 
2724   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2725                                                       Virtual, Access, TInfo,
2726                                                       EllipsisLoc))
2727     return BaseSpec;
2728   else
2729     Class->setInvalidDecl();
2730 
2731   return true;
2732 }
2733 
2734 /// Use small set to collect indirect bases.  As this is only used
2735 /// locally, there's no need to abstract the small size parameter.
2736 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2737 
2738 /// Recursively add the bases of Type.  Don't add Type itself.
2739 static void
2740 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2741                   const QualType &Type)
2742 {
2743   // Even though the incoming type is a base, it might not be
2744   // a class -- it could be a template parm, for instance.
2745   if (auto Rec = Type->getAs<RecordType>()) {
2746     auto Decl = Rec->getAsCXXRecordDecl();
2747 
2748     // Iterate over its bases.
2749     for (const auto &BaseSpec : Decl->bases()) {
2750       QualType Base = Context.getCanonicalType(BaseSpec.getType())
2751         .getUnqualifiedType();
2752       if (Set.insert(Base).second)
2753         // If we've not already seen it, recurse.
2754         NoteIndirectBases(Context, Set, Base);
2755     }
2756   }
2757 }
2758 
2759 /// Performs the actual work of attaching the given base class
2760 /// specifiers to a C++ class.
2761 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2762                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2763  if (Bases.empty())
2764     return false;
2765 
2766   // Used to keep track of which base types we have already seen, so
2767   // that we can properly diagnose redundant direct base types. Note
2768   // that the key is always the unqualified canonical type of the base
2769   // class.
2770   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2771 
2772   // Used to track indirect bases so we can see if a direct base is
2773   // ambiguous.
2774   IndirectBaseSet IndirectBaseTypes;
2775 
2776   // Copy non-redundant base specifiers into permanent storage.
2777   unsigned NumGoodBases = 0;
2778   bool Invalid = false;
2779   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2780     QualType NewBaseType
2781       = Context.getCanonicalType(Bases[idx]->getType());
2782     NewBaseType = NewBaseType.getLocalUnqualifiedType();
2783 
2784     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2785     if (KnownBase) {
2786       // C++ [class.mi]p3:
2787       //   A class shall not be specified as a direct base class of a
2788       //   derived class more than once.
2789       Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2790           << KnownBase->getType() << Bases[idx]->getSourceRange();
2791 
2792       // Delete the duplicate base class specifier; we're going to
2793       // overwrite its pointer later.
2794       Context.Deallocate(Bases[idx]);
2795 
2796       Invalid = true;
2797     } else {
2798       // Okay, add this new base class.
2799       KnownBase = Bases[idx];
2800       Bases[NumGoodBases++] = Bases[idx];
2801 
2802       if (NewBaseType->isDependentType())
2803         continue;
2804       // Note this base's direct & indirect bases, if there could be ambiguity.
2805       if (Bases.size() > 1)
2806         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2807 
2808       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2809         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2810         if (Class->isInterface() &&
2811               (!RD->isInterfaceLike() ||
2812                KnownBase->getAccessSpecifier() != AS_public)) {
2813           // The Microsoft extension __interface does not permit bases that
2814           // are not themselves public interfaces.
2815           Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2816               << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2817               << RD->getSourceRange();
2818           Invalid = true;
2819         }
2820         if (RD->hasAttr<WeakAttr>())
2821           Class->addAttr(WeakAttr::CreateImplicit(Context));
2822       }
2823     }
2824   }
2825 
2826   // Attach the remaining base class specifiers to the derived class.
2827   Class->setBases(Bases.data(), NumGoodBases);
2828 
2829   // Check that the only base classes that are duplicate are virtual.
2830   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2831     // Check whether this direct base is inaccessible due to ambiguity.
2832     QualType BaseType = Bases[idx]->getType();
2833 
2834     // Skip all dependent types in templates being used as base specifiers.
2835     // Checks below assume that the base specifier is a CXXRecord.
2836     if (BaseType->isDependentType())
2837       continue;
2838 
2839     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2840       .getUnqualifiedType();
2841 
2842     if (IndirectBaseTypes.count(CanonicalBase)) {
2843       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2844                          /*DetectVirtual=*/true);
2845       bool found
2846         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2847       assert(found);
2848       (void)found;
2849 
2850       if (Paths.isAmbiguous(CanonicalBase))
2851         Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2852             << BaseType << getAmbiguousPathsDisplayString(Paths)
2853             << Bases[idx]->getSourceRange();
2854       else
2855         assert(Bases[idx]->isVirtual());
2856     }
2857 
2858     // Delete the base class specifier, since its data has been copied
2859     // into the CXXRecordDecl.
2860     Context.Deallocate(Bases[idx]);
2861   }
2862 
2863   return Invalid;
2864 }
2865 
2866 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2867 /// class, after checking whether there are any duplicate base
2868 /// classes.
2869 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2870                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2871   if (!ClassDecl || Bases.empty())
2872     return;
2873 
2874   AdjustDeclIfTemplate(ClassDecl);
2875   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2876 }
2877 
2878 /// Determine whether the type \p Derived is a C++ class that is
2879 /// derived from the type \p Base.
2880 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2881   if (!getLangOpts().CPlusPlus)
2882     return false;
2883 
2884   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2885   if (!DerivedRD)
2886     return false;
2887 
2888   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2889   if (!BaseRD)
2890     return false;
2891 
2892   // If either the base or the derived type is invalid, don't try to
2893   // check whether one is derived from the other.
2894   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2895     return false;
2896 
2897   // FIXME: In a modules build, do we need the entire path to be visible for us
2898   // to be able to use the inheritance relationship?
2899   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2900     return false;
2901 
2902   return DerivedRD->isDerivedFrom(BaseRD);
2903 }
2904 
2905 /// Determine whether the type \p Derived is a C++ class that is
2906 /// derived from the type \p Base.
2907 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2908                          CXXBasePaths &Paths) {
2909   if (!getLangOpts().CPlusPlus)
2910     return false;
2911 
2912   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2913   if (!DerivedRD)
2914     return false;
2915 
2916   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2917   if (!BaseRD)
2918     return false;
2919 
2920   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2921     return false;
2922 
2923   return DerivedRD->isDerivedFrom(BaseRD, Paths);
2924 }
2925 
2926 static void BuildBasePathArray(const CXXBasePath &Path,
2927                                CXXCastPath &BasePathArray) {
2928   // We first go backward and check if we have a virtual base.
2929   // FIXME: It would be better if CXXBasePath had the base specifier for
2930   // the nearest virtual base.
2931   unsigned Start = 0;
2932   for (unsigned I = Path.size(); I != 0; --I) {
2933     if (Path[I - 1].Base->isVirtual()) {
2934       Start = I - 1;
2935       break;
2936     }
2937   }
2938 
2939   // Now add all bases.
2940   for (unsigned I = Start, E = Path.size(); I != E; ++I)
2941     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2942 }
2943 
2944 
2945 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2946                               CXXCastPath &BasePathArray) {
2947   assert(BasePathArray.empty() && "Base path array must be empty!");
2948   assert(Paths.isRecordingPaths() && "Must record paths!");
2949   return ::BuildBasePathArray(Paths.front(), BasePathArray);
2950 }
2951 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2952 /// conversion (where Derived and Base are class types) is
2953 /// well-formed, meaning that the conversion is unambiguous (and
2954 /// that all of the base classes are accessible). Returns true
2955 /// and emits a diagnostic if the code is ill-formed, returns false
2956 /// otherwise. Loc is the location where this routine should point to
2957 /// if there is an error, and Range is the source range to highlight
2958 /// if there is an error.
2959 ///
2960 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
2961 /// diagnostic for the respective type of error will be suppressed, but the
2962 /// check for ill-formed code will still be performed.
2963 bool
2964 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2965                                    unsigned InaccessibleBaseID,
2966                                    unsigned AmbiguousBaseConvID,
2967                                    SourceLocation Loc, SourceRange Range,
2968                                    DeclarationName Name,
2969                                    CXXCastPath *BasePath,
2970                                    bool IgnoreAccess) {
2971   // First, determine whether the path from Derived to Base is
2972   // ambiguous. This is slightly more expensive than checking whether
2973   // the Derived to Base conversion exists, because here we need to
2974   // explore multiple paths to determine if there is an ambiguity.
2975   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2976                      /*DetectVirtual=*/false);
2977   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2978   if (!DerivationOkay)
2979     return true;
2980 
2981   const CXXBasePath *Path = nullptr;
2982   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2983     Path = &Paths.front();
2984 
2985   // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2986   // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2987   // user to access such bases.
2988   if (!Path && getLangOpts().MSVCCompat) {
2989     for (const CXXBasePath &PossiblePath : Paths) {
2990       if (PossiblePath.size() == 1) {
2991         Path = &PossiblePath;
2992         if (AmbiguousBaseConvID)
2993           Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2994               << Base << Derived << Range;
2995         break;
2996       }
2997     }
2998   }
2999 
3000   if (Path) {
3001     if (!IgnoreAccess) {
3002       // Check that the base class can be accessed.
3003       switch (
3004           CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
3005       case AR_inaccessible:
3006         return true;
3007       case AR_accessible:
3008       case AR_dependent:
3009       case AR_delayed:
3010         break;
3011       }
3012     }
3013 
3014     // Build a base path if necessary.
3015     if (BasePath)
3016       ::BuildBasePathArray(*Path, *BasePath);
3017     return false;
3018   }
3019 
3020   if (AmbiguousBaseConvID) {
3021     // We know that the derived-to-base conversion is ambiguous, and
3022     // we're going to produce a diagnostic. Perform the derived-to-base
3023     // search just one more time to compute all of the possible paths so
3024     // that we can print them out. This is more expensive than any of
3025     // the previous derived-to-base checks we've done, but at this point
3026     // performance isn't as much of an issue.
3027     Paths.clear();
3028     Paths.setRecordingPaths(true);
3029     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3030     assert(StillOkay && "Can only be used with a derived-to-base conversion");
3031     (void)StillOkay;
3032 
3033     // Build up a textual representation of the ambiguous paths, e.g.,
3034     // D -> B -> A, that will be used to illustrate the ambiguous
3035     // conversions in the diagnostic. We only print one of the paths
3036     // to each base class subobject.
3037     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3038 
3039     Diag(Loc, AmbiguousBaseConvID)
3040     << Derived << Base << PathDisplayStr << Range << Name;
3041   }
3042   return true;
3043 }
3044 
3045 bool
3046 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
3047                                    SourceLocation Loc, SourceRange Range,
3048                                    CXXCastPath *BasePath,
3049                                    bool IgnoreAccess) {
3050   return CheckDerivedToBaseConversion(
3051       Derived, Base, diag::err_upcast_to_inaccessible_base,
3052       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
3053       BasePath, IgnoreAccess);
3054 }
3055 
3056 
3057 /// Builds a string representing ambiguous paths from a
3058 /// specific derived class to different subobjects of the same base
3059 /// class.
3060 ///
3061 /// This function builds a string that can be used in error messages
3062 /// to show the different paths that one can take through the
3063 /// inheritance hierarchy to go from the derived class to different
3064 /// subobjects of a base class. The result looks something like this:
3065 /// @code
3066 /// struct D -> struct B -> struct A
3067 /// struct D -> struct C -> struct A
3068 /// @endcode
3069 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
3070   std::string PathDisplayStr;
3071   std::set<unsigned> DisplayedPaths;
3072   for (CXXBasePaths::paths_iterator Path = Paths.begin();
3073        Path != Paths.end(); ++Path) {
3074     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
3075       // We haven't displayed a path to this particular base
3076       // class subobject yet.
3077       PathDisplayStr += "\n    ";
3078       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
3079       for (CXXBasePath::const_iterator Element = Path->begin();
3080            Element != Path->end(); ++Element)
3081         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
3082     }
3083   }
3084 
3085   return PathDisplayStr;
3086 }
3087 
3088 //===----------------------------------------------------------------------===//
3089 // C++ class member Handling
3090 //===----------------------------------------------------------------------===//
3091 
3092 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
3093 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
3094                                 SourceLocation ColonLoc,
3095                                 const ParsedAttributesView &Attrs) {
3096   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
3097   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
3098                                                   ASLoc, ColonLoc);
3099   CurContext->addHiddenDecl(ASDecl);
3100   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
3101 }
3102 
3103 /// CheckOverrideControl - Check C++11 override control semantics.
3104 void Sema::CheckOverrideControl(NamedDecl *D) {
3105   if (D->isInvalidDecl())
3106     return;
3107 
3108   // We only care about "override" and "final" declarations.
3109   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3110     return;
3111 
3112   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3113 
3114   // We can't check dependent instance methods.
3115   if (MD && MD->isInstance() &&
3116       (MD->getParent()->hasAnyDependentBases() ||
3117        MD->getType()->isDependentType()))
3118     return;
3119 
3120   if (MD && !MD->isVirtual()) {
3121     // If we have a non-virtual method, check if it hides a virtual method.
3122     // (In that case, it's most likely the method has the wrong type.)
3123     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3124     FindHiddenVirtualMethods(MD, OverloadedMethods);
3125 
3126     if (!OverloadedMethods.empty()) {
3127       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3128         Diag(OA->getLocation(),
3129              diag::override_keyword_hides_virtual_member_function)
3130           << "override" << (OverloadedMethods.size() > 1);
3131       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3132         Diag(FA->getLocation(),
3133              diag::override_keyword_hides_virtual_member_function)
3134           << (FA->isSpelledAsSealed() ? "sealed" : "final")
3135           << (OverloadedMethods.size() > 1);
3136       }
3137       NoteHiddenVirtualMethods(MD, OverloadedMethods);
3138       MD->setInvalidDecl();
3139       return;
3140     }
3141     // Fall through into the general case diagnostic.
3142     // FIXME: We might want to attempt typo correction here.
3143   }
3144 
3145   if (!MD || !MD->isVirtual()) {
3146     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3147       Diag(OA->getLocation(),
3148            diag::override_keyword_only_allowed_on_virtual_member_functions)
3149         << "override" << FixItHint::CreateRemoval(OA->getLocation());
3150       D->dropAttr<OverrideAttr>();
3151     }
3152     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3153       Diag(FA->getLocation(),
3154            diag::override_keyword_only_allowed_on_virtual_member_functions)
3155         << (FA->isSpelledAsSealed() ? "sealed" : "final")
3156         << FixItHint::CreateRemoval(FA->getLocation());
3157       D->dropAttr<FinalAttr>();
3158     }
3159     return;
3160   }
3161 
3162   // C++11 [class.virtual]p5:
3163   //   If a function is marked with the virt-specifier override and
3164   //   does not override a member function of a base class, the program is
3165   //   ill-formed.
3166   bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3167   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3168     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3169       << MD->getDeclName();
3170 }
3171 
3172 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) {
3173   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3174     return;
3175   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3176   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3177     return;
3178 
3179   SourceLocation Loc = MD->getLocation();
3180   SourceLocation SpellingLoc = Loc;
3181   if (getSourceManager().isMacroArgExpansion(Loc))
3182     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3183   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3184   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3185       return;
3186 
3187   if (MD->size_overridden_methods() > 0) {
3188     auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3189       unsigned DiagID =
3190           Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3191               ? DiagInconsistent
3192               : DiagSuggest;
3193       Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3194       const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3195       Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3196     };
3197     if (isa<CXXDestructorDecl>(MD))
3198       EmitDiag(
3199           diag::warn_inconsistent_destructor_marked_not_override_overriding,
3200           diag::warn_suggest_destructor_marked_not_override_overriding);
3201     else
3202       EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3203                diag::warn_suggest_function_marked_not_override_overriding);
3204   }
3205 }
3206 
3207 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
3208 /// function overrides a virtual member function marked 'final', according to
3209 /// C++11 [class.virtual]p4.
3210 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3211                                                   const CXXMethodDecl *Old) {
3212   FinalAttr *FA = Old->getAttr<FinalAttr>();
3213   if (!FA)
3214     return false;
3215 
3216   Diag(New->getLocation(), diag::err_final_function_overridden)
3217     << New->getDeclName()
3218     << FA->isSpelledAsSealed();
3219   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3220   return true;
3221 }
3222 
3223 static bool InitializationHasSideEffects(const FieldDecl &FD) {
3224   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3225   // FIXME: Destruction of ObjC lifetime types has side-effects.
3226   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3227     return !RD->isCompleteDefinition() ||
3228            !RD->hasTrivialDefaultConstructor() ||
3229            !RD->hasTrivialDestructor();
3230   return false;
3231 }
3232 
3233 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
3234   ParsedAttributesView::const_iterator Itr =
3235       llvm::find_if(list, [](const ParsedAttr &AL) {
3236         return AL.isDeclspecPropertyAttribute();
3237       });
3238   if (Itr != list.end())
3239     return &*Itr;
3240   return nullptr;
3241 }
3242 
3243 // Check if there is a field shadowing.
3244 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3245                                       DeclarationName FieldName,
3246                                       const CXXRecordDecl *RD,
3247                                       bool DeclIsField) {
3248   if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3249     return;
3250 
3251   // To record a shadowed field in a base
3252   std::map<CXXRecordDecl*, NamedDecl*> Bases;
3253   auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3254                            CXXBasePath &Path) {
3255     const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3256     // Record an ambiguous path directly
3257     if (Bases.find(Base) != Bases.end())
3258       return true;
3259     for (const auto Field : Base->lookup(FieldName)) {
3260       if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3261           Field->getAccess() != AS_private) {
3262         assert(Field->getAccess() != AS_none);
3263         assert(Bases.find(Base) == Bases.end());
3264         Bases[Base] = Field;
3265         return true;
3266       }
3267     }
3268     return false;
3269   };
3270 
3271   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3272                      /*DetectVirtual=*/true);
3273   if (!RD->lookupInBases(FieldShadowed, Paths))
3274     return;
3275 
3276   for (const auto &P : Paths) {
3277     auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3278     auto It = Bases.find(Base);
3279     // Skip duplicated bases
3280     if (It == Bases.end())
3281       continue;
3282     auto BaseField = It->second;
3283     assert(BaseField->getAccess() != AS_private);
3284     if (AS_none !=
3285         CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3286       Diag(Loc, diag::warn_shadow_field)
3287         << FieldName << RD << Base << DeclIsField;
3288       Diag(BaseField->getLocation(), diag::note_shadow_field);
3289       Bases.erase(It);
3290     }
3291   }
3292 }
3293 
3294 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
3295 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
3296 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
3297 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
3298 /// present (but parsing it has been deferred).
3299 NamedDecl *
3300 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3301                                MultiTemplateParamsArg TemplateParameterLists,
3302                                Expr *BW, const VirtSpecifiers &VS,
3303                                InClassInitStyle InitStyle) {
3304   const DeclSpec &DS = D.getDeclSpec();
3305   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3306   DeclarationName Name = NameInfo.getName();
3307   SourceLocation Loc = NameInfo.getLoc();
3308 
3309   // For anonymous bitfields, the location should point to the type.
3310   if (Loc.isInvalid())
3311     Loc = D.getBeginLoc();
3312 
3313   Expr *BitWidth = static_cast<Expr*>(BW);
3314 
3315   assert(isa<CXXRecordDecl>(CurContext));
3316   assert(!DS.isFriendSpecified());
3317 
3318   bool isFunc = D.isDeclarationOfFunction();
3319   const ParsedAttr *MSPropertyAttr =
3320       getMSPropertyAttr(D.getDeclSpec().getAttributes());
3321 
3322   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3323     // The Microsoft extension __interface only permits public member functions
3324     // and prohibits constructors, destructors, operators, non-public member
3325     // functions, static methods and data members.
3326     unsigned InvalidDecl;
3327     bool ShowDeclName = true;
3328     if (!isFunc &&
3329         (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3330       InvalidDecl = 0;
3331     else if (!isFunc)
3332       InvalidDecl = 1;
3333     else if (AS != AS_public)
3334       InvalidDecl = 2;
3335     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3336       InvalidDecl = 3;
3337     else switch (Name.getNameKind()) {
3338       case DeclarationName::CXXConstructorName:
3339         InvalidDecl = 4;
3340         ShowDeclName = false;
3341         break;
3342 
3343       case DeclarationName::CXXDestructorName:
3344         InvalidDecl = 5;
3345         ShowDeclName = false;
3346         break;
3347 
3348       case DeclarationName::CXXOperatorName:
3349       case DeclarationName::CXXConversionFunctionName:
3350         InvalidDecl = 6;
3351         break;
3352 
3353       default:
3354         InvalidDecl = 0;
3355         break;
3356     }
3357 
3358     if (InvalidDecl) {
3359       if (ShowDeclName)
3360         Diag(Loc, diag::err_invalid_member_in_interface)
3361           << (InvalidDecl-1) << Name;
3362       else
3363         Diag(Loc, diag::err_invalid_member_in_interface)
3364           << (InvalidDecl-1) << "";
3365       return nullptr;
3366     }
3367   }
3368 
3369   // C++ 9.2p6: A member shall not be declared to have automatic storage
3370   // duration (auto, register) or with the extern storage-class-specifier.
3371   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3372   // data members and cannot be applied to names declared const or static,
3373   // and cannot be applied to reference members.
3374   switch (DS.getStorageClassSpec()) {
3375   case DeclSpec::SCS_unspecified:
3376   case DeclSpec::SCS_typedef:
3377   case DeclSpec::SCS_static:
3378     break;
3379   case DeclSpec::SCS_mutable:
3380     if (isFunc) {
3381       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3382 
3383       // FIXME: It would be nicer if the keyword was ignored only for this
3384       // declarator. Otherwise we could get follow-up errors.
3385       D.getMutableDeclSpec().ClearStorageClassSpecs();
3386     }
3387     break;
3388   default:
3389     Diag(DS.getStorageClassSpecLoc(),
3390          diag::err_storageclass_invalid_for_member);
3391     D.getMutableDeclSpec().ClearStorageClassSpecs();
3392     break;
3393   }
3394 
3395   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3396                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3397                       !isFunc);
3398 
3399   if (DS.hasConstexprSpecifier() && isInstField) {
3400     SemaDiagnosticBuilder B =
3401         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3402     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3403     if (InitStyle == ICIS_NoInit) {
3404       B << 0 << 0;
3405       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3406         B << FixItHint::CreateRemoval(ConstexprLoc);
3407       else {
3408         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3409         D.getMutableDeclSpec().ClearConstexprSpec();
3410         const char *PrevSpec;
3411         unsigned DiagID;
3412         bool Failed = D.getMutableDeclSpec().SetTypeQual(
3413             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3414         (void)Failed;
3415         assert(!Failed && "Making a constexpr member const shouldn't fail");
3416       }
3417     } else {
3418       B << 1;
3419       const char *PrevSpec;
3420       unsigned DiagID;
3421       if (D.getMutableDeclSpec().SetStorageClassSpec(
3422           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3423           Context.getPrintingPolicy())) {
3424         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3425                "This is the only DeclSpec that should fail to be applied");
3426         B << 1;
3427       } else {
3428         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3429         isInstField = false;
3430       }
3431     }
3432   }
3433 
3434   NamedDecl *Member;
3435   if (isInstField) {
3436     CXXScopeSpec &SS = D.getCXXScopeSpec();
3437 
3438     // Data members must have identifiers for names.
3439     if (!Name.isIdentifier()) {
3440       Diag(Loc, diag::err_bad_variable_name)
3441         << Name;
3442       return nullptr;
3443     }
3444 
3445     IdentifierInfo *II = Name.getAsIdentifierInfo();
3446 
3447     // Member field could not be with "template" keyword.
3448     // So TemplateParameterLists should be empty in this case.
3449     if (TemplateParameterLists.size()) {
3450       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3451       if (TemplateParams->size()) {
3452         // There is no such thing as a member field template.
3453         Diag(D.getIdentifierLoc(), diag::err_template_member)
3454             << II
3455             << SourceRange(TemplateParams->getTemplateLoc(),
3456                 TemplateParams->getRAngleLoc());
3457       } else {
3458         // There is an extraneous 'template<>' for this member.
3459         Diag(TemplateParams->getTemplateLoc(),
3460             diag::err_template_member_noparams)
3461             << II
3462             << SourceRange(TemplateParams->getTemplateLoc(),
3463                 TemplateParams->getRAngleLoc());
3464       }
3465       return nullptr;
3466     }
3467 
3468     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
3469       Diag(D.getIdentifierLoc(), diag::err_member_with_template_arguments)
3470           << II
3471           << SourceRange(D.getName().TemplateId->LAngleLoc,
3472                          D.getName().TemplateId->RAngleLoc)
3473           << D.getName().TemplateId->LAngleLoc;
3474       D.SetIdentifier(II, Loc);
3475     }
3476 
3477     if (SS.isSet() && !SS.isInvalid()) {
3478       // The user provided a superfluous scope specifier inside a class
3479       // definition:
3480       //
3481       // class X {
3482       //   int X::member;
3483       // };
3484       if (DeclContext *DC = computeDeclContext(SS, false))
3485         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3486                                      D.getName().getKind() ==
3487                                          UnqualifiedIdKind::IK_TemplateId);
3488       else
3489         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3490           << Name << SS.getRange();
3491 
3492       SS.clear();
3493     }
3494 
3495     if (MSPropertyAttr) {
3496       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3497                                 BitWidth, InitStyle, AS, *MSPropertyAttr);
3498       if (!Member)
3499         return nullptr;
3500       isInstField = false;
3501     } else {
3502       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3503                                 BitWidth, InitStyle, AS);
3504       if (!Member)
3505         return nullptr;
3506     }
3507 
3508     CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3509   } else {
3510     Member = HandleDeclarator(S, D, TemplateParameterLists);
3511     if (!Member)
3512       return nullptr;
3513 
3514     // Non-instance-fields can't have a bitfield.
3515     if (BitWidth) {
3516       if (Member->isInvalidDecl()) {
3517         // don't emit another diagnostic.
3518       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3519         // C++ 9.6p3: A bit-field shall not be a static member.
3520         // "static member 'A' cannot be a bit-field"
3521         Diag(Loc, diag::err_static_not_bitfield)
3522           << Name << BitWidth->getSourceRange();
3523       } else if (isa<TypedefDecl>(Member)) {
3524         // "typedef member 'x' cannot be a bit-field"
3525         Diag(Loc, diag::err_typedef_not_bitfield)
3526           << Name << BitWidth->getSourceRange();
3527       } else {
3528         // A function typedef ("typedef int f(); f a;").
3529         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3530         Diag(Loc, diag::err_not_integral_type_bitfield)
3531           << Name << cast<ValueDecl>(Member)->getType()
3532           << BitWidth->getSourceRange();
3533       }
3534 
3535       BitWidth = nullptr;
3536       Member->setInvalidDecl();
3537     }
3538 
3539     NamedDecl *NonTemplateMember = Member;
3540     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3541       NonTemplateMember = FunTmpl->getTemplatedDecl();
3542     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3543       NonTemplateMember = VarTmpl->getTemplatedDecl();
3544 
3545     Member->setAccess(AS);
3546 
3547     // If we have declared a member function template or static data member
3548     // template, set the access of the templated declaration as well.
3549     if (NonTemplateMember != Member)
3550       NonTemplateMember->setAccess(AS);
3551 
3552     // C++ [temp.deduct.guide]p3:
3553     //   A deduction guide [...] for a member class template [shall be
3554     //   declared] with the same access [as the template].
3555     if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3556       auto *TD = DG->getDeducedTemplate();
3557       // Access specifiers are only meaningful if both the template and the
3558       // deduction guide are from the same scope.
3559       if (AS != TD->getAccess() &&
3560           TD->getDeclContext()->getRedeclContext()->Equals(
3561               DG->getDeclContext()->getRedeclContext())) {
3562         Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3563         Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3564             << TD->getAccess();
3565         const AccessSpecDecl *LastAccessSpec = nullptr;
3566         for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3567           if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3568             LastAccessSpec = AccessSpec;
3569         }
3570         assert(LastAccessSpec && "differing access with no access specifier");
3571         Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3572             << AS;
3573       }
3574     }
3575   }
3576 
3577   if (VS.isOverrideSpecified())
3578     Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(),
3579                                          AttributeCommonInfo::AS_Keyword));
3580   if (VS.isFinalSpecified())
3581     Member->addAttr(FinalAttr::Create(
3582         Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword,
3583         static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed())));
3584 
3585   if (VS.getLastLocation().isValid()) {
3586     // Update the end location of a method that has a virt-specifiers.
3587     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3588       MD->setRangeEnd(VS.getLastLocation());
3589   }
3590 
3591   CheckOverrideControl(Member);
3592 
3593   assert((Name || isInstField) && "No identifier for non-field ?");
3594 
3595   if (isInstField) {
3596     FieldDecl *FD = cast<FieldDecl>(Member);
3597     FieldCollector->Add(FD);
3598 
3599     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3600       // Remember all explicit private FieldDecls that have a name, no side
3601       // effects and are not part of a dependent type declaration.
3602       if (!FD->isImplicit() && FD->getDeclName() &&
3603           FD->getAccess() == AS_private &&
3604           !FD->hasAttr<UnusedAttr>() &&
3605           !FD->getParent()->isDependentContext() &&
3606           !InitializationHasSideEffects(*FD))
3607         UnusedPrivateFields.insert(FD);
3608     }
3609   }
3610 
3611   return Member;
3612 }
3613 
3614 namespace {
3615   class UninitializedFieldVisitor
3616       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3617     Sema &S;
3618     // List of Decls to generate a warning on.  Also remove Decls that become
3619     // initialized.
3620     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3621     // List of base classes of the record.  Classes are removed after their
3622     // initializers.
3623     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3624     // Vector of decls to be removed from the Decl set prior to visiting the
3625     // nodes.  These Decls may have been initialized in the prior initializer.
3626     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3627     // If non-null, add a note to the warning pointing back to the constructor.
3628     const CXXConstructorDecl *Constructor;
3629     // Variables to hold state when processing an initializer list.  When
3630     // InitList is true, special case initialization of FieldDecls matching
3631     // InitListFieldDecl.
3632     bool InitList;
3633     FieldDecl *InitListFieldDecl;
3634     llvm::SmallVector<unsigned, 4> InitFieldIndex;
3635 
3636   public:
3637     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3638     UninitializedFieldVisitor(Sema &S,
3639                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3640                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3641       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3642         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3643 
3644     // Returns true if the use of ME is not an uninitialized use.
3645     bool IsInitListMemberExprInitialized(MemberExpr *ME,
3646                                          bool CheckReferenceOnly) {
3647       llvm::SmallVector<FieldDecl*, 4> Fields;
3648       bool ReferenceField = false;
3649       while (ME) {
3650         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3651         if (!FD)
3652           return false;
3653         Fields.push_back(FD);
3654         if (FD->getType()->isReferenceType())
3655           ReferenceField = true;
3656         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3657       }
3658 
3659       // Binding a reference to an uninitialized field is not an
3660       // uninitialized use.
3661       if (CheckReferenceOnly && !ReferenceField)
3662         return true;
3663 
3664       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3665       // Discard the first field since it is the field decl that is being
3666       // initialized.
3667       for (const FieldDecl *FD : llvm::drop_begin(llvm::reverse(Fields)))
3668         UsedFieldIndex.push_back(FD->getFieldIndex());
3669 
3670       for (auto UsedIter = UsedFieldIndex.begin(),
3671                 UsedEnd = UsedFieldIndex.end(),
3672                 OrigIter = InitFieldIndex.begin(),
3673                 OrigEnd = InitFieldIndex.end();
3674            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3675         if (*UsedIter < *OrigIter)
3676           return true;
3677         if (*UsedIter > *OrigIter)
3678           break;
3679       }
3680 
3681       return false;
3682     }
3683 
3684     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3685                           bool AddressOf) {
3686       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3687         return;
3688 
3689       // FieldME is the inner-most MemberExpr that is not an anonymous struct
3690       // or union.
3691       MemberExpr *FieldME = ME;
3692 
3693       bool AllPODFields = FieldME->getType().isPODType(S.Context);
3694 
3695       Expr *Base = ME;
3696       while (MemberExpr *SubME =
3697                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3698 
3699         if (isa<VarDecl>(SubME->getMemberDecl()))
3700           return;
3701 
3702         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3703           if (!FD->isAnonymousStructOrUnion())
3704             FieldME = SubME;
3705 
3706         if (!FieldME->getType().isPODType(S.Context))
3707           AllPODFields = false;
3708 
3709         Base = SubME->getBase();
3710       }
3711 
3712       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3713         Visit(Base);
3714         return;
3715       }
3716 
3717       if (AddressOf && AllPODFields)
3718         return;
3719 
3720       ValueDecl* FoundVD = FieldME->getMemberDecl();
3721 
3722       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3723         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3724           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3725         }
3726 
3727         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3728           QualType T = BaseCast->getType();
3729           if (T->isPointerType() &&
3730               BaseClasses.count(T->getPointeeType())) {
3731             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3732                 << T->getPointeeType() << FoundVD;
3733           }
3734         }
3735       }
3736 
3737       if (!Decls.count(FoundVD))
3738         return;
3739 
3740       const bool IsReference = FoundVD->getType()->isReferenceType();
3741 
3742       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3743         // Special checking for initializer lists.
3744         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3745           return;
3746         }
3747       } else {
3748         // Prevent double warnings on use of unbounded references.
3749         if (CheckReferenceOnly && !IsReference)
3750           return;
3751       }
3752 
3753       unsigned diag = IsReference
3754           ? diag::warn_reference_field_is_uninit
3755           : diag::warn_field_is_uninit;
3756       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3757       if (Constructor)
3758         S.Diag(Constructor->getLocation(),
3759                diag::note_uninit_in_this_constructor)
3760           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3761 
3762     }
3763 
3764     void HandleValue(Expr *E, bool AddressOf) {
3765       E = E->IgnoreParens();
3766 
3767       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3768         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3769                          AddressOf /*AddressOf*/);
3770         return;
3771       }
3772 
3773       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3774         Visit(CO->getCond());
3775         HandleValue(CO->getTrueExpr(), AddressOf);
3776         HandleValue(CO->getFalseExpr(), AddressOf);
3777         return;
3778       }
3779 
3780       if (BinaryConditionalOperator *BCO =
3781               dyn_cast<BinaryConditionalOperator>(E)) {
3782         Visit(BCO->getCond());
3783         HandleValue(BCO->getFalseExpr(), AddressOf);
3784         return;
3785       }
3786 
3787       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3788         HandleValue(OVE->getSourceExpr(), AddressOf);
3789         return;
3790       }
3791 
3792       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3793         switch (BO->getOpcode()) {
3794         default:
3795           break;
3796         case(BO_PtrMemD):
3797         case(BO_PtrMemI):
3798           HandleValue(BO->getLHS(), AddressOf);
3799           Visit(BO->getRHS());
3800           return;
3801         case(BO_Comma):
3802           Visit(BO->getLHS());
3803           HandleValue(BO->getRHS(), AddressOf);
3804           return;
3805         }
3806       }
3807 
3808       Visit(E);
3809     }
3810 
3811     void CheckInitListExpr(InitListExpr *ILE) {
3812       InitFieldIndex.push_back(0);
3813       for (auto *Child : ILE->children()) {
3814         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3815           CheckInitListExpr(SubList);
3816         } else {
3817           Visit(Child);
3818         }
3819         ++InitFieldIndex.back();
3820       }
3821       InitFieldIndex.pop_back();
3822     }
3823 
3824     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3825                           FieldDecl *Field, const Type *BaseClass) {
3826       // Remove Decls that may have been initialized in the previous
3827       // initializer.
3828       for (ValueDecl* VD : DeclsToRemove)
3829         Decls.erase(VD);
3830       DeclsToRemove.clear();
3831 
3832       Constructor = FieldConstructor;
3833       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3834 
3835       if (ILE && Field) {
3836         InitList = true;
3837         InitListFieldDecl = Field;
3838         InitFieldIndex.clear();
3839         CheckInitListExpr(ILE);
3840       } else {
3841         InitList = false;
3842         Visit(E);
3843       }
3844 
3845       if (Field)
3846         Decls.erase(Field);
3847       if (BaseClass)
3848         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3849     }
3850 
3851     void VisitMemberExpr(MemberExpr *ME) {
3852       // All uses of unbounded reference fields will warn.
3853       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3854     }
3855 
3856     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3857       if (E->getCastKind() == CK_LValueToRValue) {
3858         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3859         return;
3860       }
3861 
3862       Inherited::VisitImplicitCastExpr(E);
3863     }
3864 
3865     void VisitCXXConstructExpr(CXXConstructExpr *E) {
3866       if (E->getConstructor()->isCopyConstructor()) {
3867         Expr *ArgExpr = E->getArg(0);
3868         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3869           if (ILE->getNumInits() == 1)
3870             ArgExpr = ILE->getInit(0);
3871         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3872           if (ICE->getCastKind() == CK_NoOp)
3873             ArgExpr = ICE->getSubExpr();
3874         HandleValue(ArgExpr, false /*AddressOf*/);
3875         return;
3876       }
3877       Inherited::VisitCXXConstructExpr(E);
3878     }
3879 
3880     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3881       Expr *Callee = E->getCallee();
3882       if (isa<MemberExpr>(Callee)) {
3883         HandleValue(Callee, false /*AddressOf*/);
3884         for (auto *Arg : E->arguments())
3885           Visit(Arg);
3886         return;
3887       }
3888 
3889       Inherited::VisitCXXMemberCallExpr(E);
3890     }
3891 
3892     void VisitCallExpr(CallExpr *E) {
3893       // Treat std::move as a use.
3894       if (E->isCallToStdMove()) {
3895         HandleValue(E->getArg(0), /*AddressOf=*/false);
3896         return;
3897       }
3898 
3899       Inherited::VisitCallExpr(E);
3900     }
3901 
3902     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3903       Expr *Callee = E->getCallee();
3904 
3905       if (isa<UnresolvedLookupExpr>(Callee))
3906         return Inherited::VisitCXXOperatorCallExpr(E);
3907 
3908       Visit(Callee);
3909       for (auto *Arg : E->arguments())
3910         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3911     }
3912 
3913     void VisitBinaryOperator(BinaryOperator *E) {
3914       // If a field assignment is detected, remove the field from the
3915       // uninitiailized field set.
3916       if (E->getOpcode() == BO_Assign)
3917         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3918           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3919             if (!FD->getType()->isReferenceType())
3920               DeclsToRemove.push_back(FD);
3921 
3922       if (E->isCompoundAssignmentOp()) {
3923         HandleValue(E->getLHS(), false /*AddressOf*/);
3924         Visit(E->getRHS());
3925         return;
3926       }
3927 
3928       Inherited::VisitBinaryOperator(E);
3929     }
3930 
3931     void VisitUnaryOperator(UnaryOperator *E) {
3932       if (E->isIncrementDecrementOp()) {
3933         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3934         return;
3935       }
3936       if (E->getOpcode() == UO_AddrOf) {
3937         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3938           HandleValue(ME->getBase(), true /*AddressOf*/);
3939           return;
3940         }
3941       }
3942 
3943       Inherited::VisitUnaryOperator(E);
3944     }
3945   };
3946 
3947   // Diagnose value-uses of fields to initialize themselves, e.g.
3948   //   foo(foo)
3949   // where foo is not also a parameter to the constructor.
3950   // Also diagnose across field uninitialized use such as
3951   //   x(y), y(x)
3952   // TODO: implement -Wuninitialized and fold this into that framework.
3953   static void DiagnoseUninitializedFields(
3954       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3955 
3956     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3957                                            Constructor->getLocation())) {
3958       return;
3959     }
3960 
3961     if (Constructor->isInvalidDecl())
3962       return;
3963 
3964     const CXXRecordDecl *RD = Constructor->getParent();
3965 
3966     if (RD->isDependentContext())
3967       return;
3968 
3969     // Holds fields that are uninitialized.
3970     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3971 
3972     // At the beginning, all fields are uninitialized.
3973     for (auto *I : RD->decls()) {
3974       if (auto *FD = dyn_cast<FieldDecl>(I)) {
3975         UninitializedFields.insert(FD);
3976       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3977         UninitializedFields.insert(IFD->getAnonField());
3978       }
3979     }
3980 
3981     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3982     for (auto I : RD->bases())
3983       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3984 
3985     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3986       return;
3987 
3988     UninitializedFieldVisitor UninitializedChecker(SemaRef,
3989                                                    UninitializedFields,
3990                                                    UninitializedBaseClasses);
3991 
3992     for (const auto *FieldInit : Constructor->inits()) {
3993       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3994         break;
3995 
3996       Expr *InitExpr = FieldInit->getInit();
3997       if (!InitExpr)
3998         continue;
3999 
4000       if (CXXDefaultInitExpr *Default =
4001               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
4002         InitExpr = Default->getExpr();
4003         if (!InitExpr)
4004           continue;
4005         // In class initializers will point to the constructor.
4006         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
4007                                               FieldInit->getAnyMember(),
4008                                               FieldInit->getBaseClass());
4009       } else {
4010         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
4011                                               FieldInit->getAnyMember(),
4012                                               FieldInit->getBaseClass());
4013       }
4014     }
4015   }
4016 } // namespace
4017 
4018 /// Enter a new C++ default initializer scope. After calling this, the
4019 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
4020 /// parsing or instantiating the initializer failed.
4021 void Sema::ActOnStartCXXInClassMemberInitializer() {
4022   // Create a synthetic function scope to represent the call to the constructor
4023   // that notionally surrounds a use of this initializer.
4024   PushFunctionScope();
4025 }
4026 
4027 void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) {
4028   if (!D.isFunctionDeclarator())
4029     return;
4030   auto &FTI = D.getFunctionTypeInfo();
4031   if (!FTI.Params)
4032     return;
4033   for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
4034                                                           FTI.NumParams)) {
4035     auto *ParamDecl = cast<NamedDecl>(Param.Param);
4036     if (ParamDecl->getDeclName())
4037       PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
4038   }
4039 }
4040 
4041 ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {
4042   return ActOnRequiresClause(ConstraintExpr);
4043 }
4044 
4045 ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) {
4046   if (ConstraintExpr.isInvalid())
4047     return ExprError();
4048 
4049   ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr);
4050   if (ConstraintExpr.isInvalid())
4051     return ExprError();
4052 
4053   if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),
4054                                       UPPC_RequiresClause))
4055     return ExprError();
4056 
4057   return ConstraintExpr;
4058 }
4059 
4060 ExprResult Sema::ConvertMemberDefaultInitExpression(FieldDecl *FD,
4061                                                     Expr *InitExpr,
4062                                                     SourceLocation InitLoc) {
4063   InitializedEntity Entity =
4064       InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
4065   InitializationKind Kind =
4066       FD->getInClassInitStyle() == ICIS_ListInit
4067           ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
4068                                                  InitExpr->getBeginLoc(),
4069                                                  InitExpr->getEndLoc())
4070           : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
4071   InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4072   return Seq.Perform(*this, Entity, Kind, InitExpr);
4073 }
4074 
4075 /// This is invoked after parsing an in-class initializer for a
4076 /// non-static C++ class member, and after instantiating an in-class initializer
4077 /// in a class template. Such actions are deferred until the class is complete.
4078 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
4079                                                   SourceLocation InitLoc,
4080                                                   Expr *InitExpr) {
4081   // Pop the notional constructor scope we created earlier.
4082   PopFunctionScopeInfo(nullptr, D);
4083 
4084   FieldDecl *FD = dyn_cast<FieldDecl>(D);
4085   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
4086          "must set init style when field is created");
4087 
4088   if (!InitExpr) {
4089     D->setInvalidDecl();
4090     if (FD)
4091       FD->removeInClassInitializer();
4092     return;
4093   }
4094 
4095   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
4096     FD->setInvalidDecl();
4097     FD->removeInClassInitializer();
4098     return;
4099   }
4100 
4101   ExprResult Init = CorrectDelayedTyposInExpr(InitExpr, /*InitDecl=*/nullptr,
4102                                               /*RecoverUncorrectedTypos=*/true);
4103   assert(Init.isUsable() && "Init should at least have a RecoveryExpr");
4104   if (!FD->getType()->isDependentType() && !Init.get()->isTypeDependent()) {
4105     Init = ConvertMemberDefaultInitExpression(FD, Init.get(), InitLoc);
4106     // C++11 [class.base.init]p7:
4107     //   The initialization of each base and member constitutes a
4108     //   full-expression.
4109     if (!Init.isInvalid())
4110       Init = ActOnFinishFullExpr(Init.get(), /*DiscarededValue=*/false);
4111     if (Init.isInvalid()) {
4112       FD->setInvalidDecl();
4113       return;
4114     }
4115   }
4116 
4117   FD->setInClassInitializer(Init.get());
4118 }
4119 
4120 /// Find the direct and/or virtual base specifiers that
4121 /// correspond to the given base type, for use in base initialization
4122 /// within a constructor.
4123 static bool FindBaseInitializer(Sema &SemaRef,
4124                                 CXXRecordDecl *ClassDecl,
4125                                 QualType BaseType,
4126                                 const CXXBaseSpecifier *&DirectBaseSpec,
4127                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
4128   // First, check for a direct base class.
4129   DirectBaseSpec = nullptr;
4130   for (const auto &Base : ClassDecl->bases()) {
4131     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
4132       // We found a direct base of this type. That's what we're
4133       // initializing.
4134       DirectBaseSpec = &Base;
4135       break;
4136     }
4137   }
4138 
4139   // Check for a virtual base class.
4140   // FIXME: We might be able to short-circuit this if we know in advance that
4141   // there are no virtual bases.
4142   VirtualBaseSpec = nullptr;
4143   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4144     // We haven't found a base yet; search the class hierarchy for a
4145     // virtual base class.
4146     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4147                        /*DetectVirtual=*/false);
4148     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4149                               SemaRef.Context.getTypeDeclType(ClassDecl),
4150                               BaseType, Paths)) {
4151       for (CXXBasePaths::paths_iterator Path = Paths.begin();
4152            Path != Paths.end(); ++Path) {
4153         if (Path->back().Base->isVirtual()) {
4154           VirtualBaseSpec = Path->back().Base;
4155           break;
4156         }
4157       }
4158     }
4159   }
4160 
4161   return DirectBaseSpec || VirtualBaseSpec;
4162 }
4163 
4164 /// Handle a C++ member initializer using braced-init-list syntax.
4165 MemInitResult
4166 Sema::ActOnMemInitializer(Decl *ConstructorD,
4167                           Scope *S,
4168                           CXXScopeSpec &SS,
4169                           IdentifierInfo *MemberOrBase,
4170                           ParsedType TemplateTypeTy,
4171                           const DeclSpec &DS,
4172                           SourceLocation IdLoc,
4173                           Expr *InitList,
4174                           SourceLocation EllipsisLoc) {
4175   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4176                              DS, IdLoc, InitList,
4177                              EllipsisLoc);
4178 }
4179 
4180 /// Handle a C++ member initializer using parentheses syntax.
4181 MemInitResult
4182 Sema::ActOnMemInitializer(Decl *ConstructorD,
4183                           Scope *S,
4184                           CXXScopeSpec &SS,
4185                           IdentifierInfo *MemberOrBase,
4186                           ParsedType TemplateTypeTy,
4187                           const DeclSpec &DS,
4188                           SourceLocation IdLoc,
4189                           SourceLocation LParenLoc,
4190                           ArrayRef<Expr *> Args,
4191                           SourceLocation RParenLoc,
4192                           SourceLocation EllipsisLoc) {
4193   Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4194   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4195                              DS, IdLoc, List, EllipsisLoc);
4196 }
4197 
4198 namespace {
4199 
4200 // Callback to only accept typo corrections that can be a valid C++ member
4201 // initializer: either a non-static field member or a base class.
4202 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4203 public:
4204   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4205       : ClassDecl(ClassDecl) {}
4206 
4207   bool ValidateCandidate(const TypoCorrection &candidate) override {
4208     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4209       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4210         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4211       return isa<TypeDecl>(ND);
4212     }
4213     return false;
4214   }
4215 
4216   std::unique_ptr<CorrectionCandidateCallback> clone() override {
4217     return std::make_unique<MemInitializerValidatorCCC>(*this);
4218   }
4219 
4220 private:
4221   CXXRecordDecl *ClassDecl;
4222 };
4223 
4224 }
4225 
4226 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4227                                              CXXScopeSpec &SS,
4228                                              ParsedType TemplateTypeTy,
4229                                              IdentifierInfo *MemberOrBase) {
4230   if (SS.getScopeRep() || TemplateTypeTy)
4231     return nullptr;
4232   for (auto *D : ClassDecl->lookup(MemberOrBase))
4233     if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D))
4234       return cast<ValueDecl>(D);
4235   return nullptr;
4236 }
4237 
4238 /// Handle a C++ member initializer.
4239 MemInitResult
4240 Sema::BuildMemInitializer(Decl *ConstructorD,
4241                           Scope *S,
4242                           CXXScopeSpec &SS,
4243                           IdentifierInfo *MemberOrBase,
4244                           ParsedType TemplateTypeTy,
4245                           const DeclSpec &DS,
4246                           SourceLocation IdLoc,
4247                           Expr *Init,
4248                           SourceLocation EllipsisLoc) {
4249   ExprResult Res = CorrectDelayedTyposInExpr(Init, /*InitDecl=*/nullptr,
4250                                              /*RecoverUncorrectedTypos=*/true);
4251   if (!Res.isUsable())
4252     return true;
4253   Init = Res.get();
4254 
4255   if (!ConstructorD)
4256     return true;
4257 
4258   AdjustDeclIfTemplate(ConstructorD);
4259 
4260   CXXConstructorDecl *Constructor
4261     = dyn_cast<CXXConstructorDecl>(ConstructorD);
4262   if (!Constructor) {
4263     // The user wrote a constructor initializer on a function that is
4264     // not a C++ constructor. Ignore the error for now, because we may
4265     // have more member initializers coming; we'll diagnose it just
4266     // once in ActOnMemInitializers.
4267     return true;
4268   }
4269 
4270   CXXRecordDecl *ClassDecl = Constructor->getParent();
4271 
4272   // C++ [class.base.init]p2:
4273   //   Names in a mem-initializer-id are looked up in the scope of the
4274   //   constructor's class and, if not found in that scope, are looked
4275   //   up in the scope containing the constructor's definition.
4276   //   [Note: if the constructor's class contains a member with the
4277   //   same name as a direct or virtual base class of the class, a
4278   //   mem-initializer-id naming the member or base class and composed
4279   //   of a single identifier refers to the class member. A
4280   //   mem-initializer-id for the hidden base class may be specified
4281   //   using a qualified name. ]
4282 
4283   // Look for a member, first.
4284   if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4285           ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4286     if (EllipsisLoc.isValid())
4287       Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4288           << MemberOrBase
4289           << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4290 
4291     return BuildMemberInitializer(Member, Init, IdLoc);
4292   }
4293   // It didn't name a member, so see if it names a class.
4294   QualType BaseType;
4295   TypeSourceInfo *TInfo = nullptr;
4296 
4297   if (TemplateTypeTy) {
4298     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4299     if (BaseType.isNull())
4300       return true;
4301   } else if (DS.getTypeSpecType() == TST_decltype) {
4302     BaseType = BuildDecltypeType(DS.getRepAsExpr());
4303   } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4304     Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4305     return true;
4306   } else {
4307     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4308     LookupParsedName(R, S, &SS);
4309 
4310     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4311     if (!TyD) {
4312       if (R.isAmbiguous()) return true;
4313 
4314       // We don't want access-control diagnostics here.
4315       R.suppressDiagnostics();
4316 
4317       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4318         bool NotUnknownSpecialization = false;
4319         DeclContext *DC = computeDeclContext(SS, false);
4320         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4321           NotUnknownSpecialization = !Record->hasAnyDependentBases();
4322 
4323         if (!NotUnknownSpecialization) {
4324           // When the scope specifier can refer to a member of an unknown
4325           // specialization, we take it as a type name.
4326           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
4327                                        SS.getWithLocInContext(Context),
4328                                        *MemberOrBase, IdLoc);
4329           if (BaseType.isNull())
4330             return true;
4331 
4332           TInfo = Context.CreateTypeSourceInfo(BaseType);
4333           DependentNameTypeLoc TL =
4334               TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4335           if (!TL.isNull()) {
4336             TL.setNameLoc(IdLoc);
4337             TL.setElaboratedKeywordLoc(SourceLocation());
4338             TL.setQualifierLoc(SS.getWithLocInContext(Context));
4339           }
4340 
4341           R.clear();
4342           R.setLookupName(MemberOrBase);
4343         }
4344       }
4345 
4346       if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) {
4347         if (auto UnqualifiedBase = R.getAsSingle<ClassTemplateDecl>()) {
4348           auto *TempSpec = cast<TemplateSpecializationType>(
4349               UnqualifiedBase->getInjectedClassNameSpecialization());
4350           TemplateName TN = TempSpec->getTemplateName();
4351           for (auto const &Base : ClassDecl->bases()) {
4352             auto BaseTemplate =
4353                 Base.getType()->getAs<TemplateSpecializationType>();
4354             if (BaseTemplate && Context.hasSameTemplateName(
4355                                     BaseTemplate->getTemplateName(), TN)) {
4356               Diag(IdLoc, diag::ext_unqualified_base_class)
4357                   << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4358               BaseType = Base.getType();
4359               break;
4360             }
4361           }
4362         }
4363       }
4364 
4365       // If no results were found, try to correct typos.
4366       TypoCorrection Corr;
4367       MemInitializerValidatorCCC CCC(ClassDecl);
4368       if (R.empty() && BaseType.isNull() &&
4369           (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4370                               CCC, CTK_ErrorRecovery, ClassDecl))) {
4371         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4372           // We have found a non-static data member with a similar
4373           // name to what was typed; complain and initialize that
4374           // member.
4375           diagnoseTypo(Corr,
4376                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
4377                          << MemberOrBase << true);
4378           return BuildMemberInitializer(Member, Init, IdLoc);
4379         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4380           const CXXBaseSpecifier *DirectBaseSpec;
4381           const CXXBaseSpecifier *VirtualBaseSpec;
4382           if (FindBaseInitializer(*this, ClassDecl,
4383                                   Context.getTypeDeclType(Type),
4384                                   DirectBaseSpec, VirtualBaseSpec)) {
4385             // We have found a direct or virtual base class with a
4386             // similar name to what was typed; complain and initialize
4387             // that base class.
4388             diagnoseTypo(Corr,
4389                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
4390                            << MemberOrBase << false,
4391                          PDiag() /*Suppress note, we provide our own.*/);
4392 
4393             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4394                                                               : VirtualBaseSpec;
4395             Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4396                 << BaseSpec->getType() << BaseSpec->getSourceRange();
4397 
4398             TyD = Type;
4399           }
4400         }
4401       }
4402 
4403       if (!TyD && BaseType.isNull()) {
4404         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4405           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4406         return true;
4407       }
4408     }
4409 
4410     if (BaseType.isNull()) {
4411       BaseType = getElaboratedType(ETK_None, SS, Context.getTypeDeclType(TyD));
4412       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4413       TInfo = Context.CreateTypeSourceInfo(BaseType);
4414       ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
4415       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4416       TL.setElaboratedKeywordLoc(SourceLocation());
4417       TL.setQualifierLoc(SS.getWithLocInContext(Context));
4418     }
4419   }
4420 
4421   if (!TInfo)
4422     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4423 
4424   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4425 }
4426 
4427 MemInitResult
4428 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4429                              SourceLocation IdLoc) {
4430   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4431   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4432   assert((DirectMember || IndirectMember) &&
4433          "Member must be a FieldDecl or IndirectFieldDecl");
4434 
4435   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4436     return true;
4437 
4438   if (Member->isInvalidDecl())
4439     return true;
4440 
4441   MultiExprArg Args;
4442   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4443     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4444   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4445     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4446   } else {
4447     // Template instantiation doesn't reconstruct ParenListExprs for us.
4448     Args = Init;
4449   }
4450 
4451   SourceRange InitRange = Init->getSourceRange();
4452 
4453   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4454     // Can't check initialization for a member of dependent type or when
4455     // any of the arguments are type-dependent expressions.
4456     DiscardCleanupsInEvaluationContext();
4457   } else {
4458     bool InitList = false;
4459     if (isa<InitListExpr>(Init)) {
4460       InitList = true;
4461       Args = Init;
4462     }
4463 
4464     // Initialize the member.
4465     InitializedEntity MemberEntity =
4466       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4467                    : InitializedEntity::InitializeMember(IndirectMember,
4468                                                          nullptr);
4469     InitializationKind Kind =
4470         InitList ? InitializationKind::CreateDirectList(
4471                        IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4472                  : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4473                                                     InitRange.getEnd());
4474 
4475     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4476     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4477                                             nullptr);
4478     if (!MemberInit.isInvalid()) {
4479       // C++11 [class.base.init]p7:
4480       //   The initialization of each base and member constitutes a
4481       //   full-expression.
4482       MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4483                                        /*DiscardedValue*/ false);
4484     }
4485 
4486     if (MemberInit.isInvalid()) {
4487       // Args were sensible expressions but we couldn't initialize the member
4488       // from them. Preserve them in a RecoveryExpr instead.
4489       Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4490                                 Member->getType())
4491                  .get();
4492       if (!Init)
4493         return true;
4494     } else {
4495       Init = MemberInit.get();
4496     }
4497   }
4498 
4499   if (DirectMember) {
4500     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4501                                             InitRange.getBegin(), Init,
4502                                             InitRange.getEnd());
4503   } else {
4504     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4505                                             InitRange.getBegin(), Init,
4506                                             InitRange.getEnd());
4507   }
4508 }
4509 
4510 MemInitResult
4511 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4512                                  CXXRecordDecl *ClassDecl) {
4513   SourceLocation NameLoc = TInfo->getTypeLoc().getSourceRange().getBegin();
4514   if (!LangOpts.CPlusPlus11)
4515     return Diag(NameLoc, diag::err_delegating_ctor)
4516            << TInfo->getTypeLoc().getSourceRange();
4517   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4518 
4519   bool InitList = true;
4520   MultiExprArg Args = Init;
4521   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4522     InitList = false;
4523     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4524   }
4525 
4526   SourceRange InitRange = Init->getSourceRange();
4527   // Initialize the object.
4528   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4529                                      QualType(ClassDecl->getTypeForDecl(), 0));
4530   InitializationKind Kind =
4531       InitList ? InitializationKind::CreateDirectList(
4532                      NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4533                : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4534                                                   InitRange.getEnd());
4535   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4536   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4537                                               Args, nullptr);
4538   if (!DelegationInit.isInvalid()) {
4539     assert((DelegationInit.get()->containsErrors() ||
4540             cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&
4541            "Delegating constructor with no target?");
4542 
4543     // C++11 [class.base.init]p7:
4544     //   The initialization of each base and member constitutes a
4545     //   full-expression.
4546     DelegationInit = ActOnFinishFullExpr(
4547         DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4548   }
4549 
4550   if (DelegationInit.isInvalid()) {
4551     DelegationInit =
4552         CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4553                            QualType(ClassDecl->getTypeForDecl(), 0));
4554     if (DelegationInit.isInvalid())
4555       return true;
4556   } else {
4557     // If we are in a dependent context, template instantiation will
4558     // perform this type-checking again. Just save the arguments that we
4559     // received in a ParenListExpr.
4560     // FIXME: This isn't quite ideal, since our ASTs don't capture all
4561     // of the information that we have about the base
4562     // initializer. However, deconstructing the ASTs is a dicey process,
4563     // and this approach is far more likely to get the corner cases right.
4564     if (CurContext->isDependentContext())
4565       DelegationInit = Init;
4566   }
4567 
4568   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4569                                           DelegationInit.getAs<Expr>(),
4570                                           InitRange.getEnd());
4571 }
4572 
4573 MemInitResult
4574 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4575                            Expr *Init, CXXRecordDecl *ClassDecl,
4576                            SourceLocation EllipsisLoc) {
4577   SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getBeginLoc();
4578 
4579   if (!BaseType->isDependentType() && !BaseType->isRecordType())
4580     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4581            << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
4582 
4583   // C++ [class.base.init]p2:
4584   //   [...] Unless the mem-initializer-id names a nonstatic data
4585   //   member of the constructor's class or a direct or virtual base
4586   //   of that class, the mem-initializer is ill-formed. A
4587   //   mem-initializer-list can initialize a base class using any
4588   //   name that denotes that base class type.
4589 
4590   // We can store the initializers in "as-written" form and delay analysis until
4591   // instantiation if the constructor is dependent. But not for dependent
4592   // (broken) code in a non-template! SetCtorInitializers does not expect this.
4593   bool Dependent = CurContext->isDependentContext() &&
4594                    (BaseType->isDependentType() || Init->isTypeDependent());
4595 
4596   SourceRange InitRange = Init->getSourceRange();
4597   if (EllipsisLoc.isValid()) {
4598     // This is a pack expansion.
4599     if (!BaseType->containsUnexpandedParameterPack())  {
4600       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4601         << SourceRange(BaseLoc, InitRange.getEnd());
4602 
4603       EllipsisLoc = SourceLocation();
4604     }
4605   } else {
4606     // Check for any unexpanded parameter packs.
4607     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4608       return true;
4609 
4610     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4611       return true;
4612   }
4613 
4614   // Check for direct and virtual base classes.
4615   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4616   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4617   if (!Dependent) {
4618     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4619                                        BaseType))
4620       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4621 
4622     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4623                         VirtualBaseSpec);
4624 
4625     // C++ [base.class.init]p2:
4626     // Unless the mem-initializer-id names a nonstatic data member of the
4627     // constructor's class or a direct or virtual base of that class, the
4628     // mem-initializer is ill-formed.
4629     if (!DirectBaseSpec && !VirtualBaseSpec) {
4630       // If the class has any dependent bases, then it's possible that
4631       // one of those types will resolve to the same type as
4632       // BaseType. Therefore, just treat this as a dependent base
4633       // class initialization.  FIXME: Should we try to check the
4634       // initialization anyway? It seems odd.
4635       if (ClassDecl->hasAnyDependentBases())
4636         Dependent = true;
4637       else
4638         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4639                << BaseType << Context.getTypeDeclType(ClassDecl)
4640                << BaseTInfo->getTypeLoc().getSourceRange();
4641     }
4642   }
4643 
4644   if (Dependent) {
4645     DiscardCleanupsInEvaluationContext();
4646 
4647     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4648                                             /*IsVirtual=*/false,
4649                                             InitRange.getBegin(), Init,
4650                                             InitRange.getEnd(), EllipsisLoc);
4651   }
4652 
4653   // C++ [base.class.init]p2:
4654   //   If a mem-initializer-id is ambiguous because it designates both
4655   //   a direct non-virtual base class and an inherited virtual base
4656   //   class, the mem-initializer is ill-formed.
4657   if (DirectBaseSpec && VirtualBaseSpec)
4658     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4659       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4660 
4661   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4662   if (!BaseSpec)
4663     BaseSpec = VirtualBaseSpec;
4664 
4665   // Initialize the base.
4666   bool InitList = true;
4667   MultiExprArg Args = Init;
4668   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4669     InitList = false;
4670     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4671   }
4672 
4673   InitializedEntity BaseEntity =
4674     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4675   InitializationKind Kind =
4676       InitList ? InitializationKind::CreateDirectList(BaseLoc)
4677                : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4678                                                   InitRange.getEnd());
4679   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4680   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4681   if (!BaseInit.isInvalid()) {
4682     // C++11 [class.base.init]p7:
4683     //   The initialization of each base and member constitutes a
4684     //   full-expression.
4685     BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4686                                    /*DiscardedValue*/ false);
4687   }
4688 
4689   if (BaseInit.isInvalid()) {
4690     BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(),
4691                                   Args, BaseType);
4692     if (BaseInit.isInvalid())
4693       return true;
4694   } else {
4695     // If we are in a dependent context, template instantiation will
4696     // perform this type-checking again. Just save the arguments that we
4697     // received in a ParenListExpr.
4698     // FIXME: This isn't quite ideal, since our ASTs don't capture all
4699     // of the information that we have about the base
4700     // initializer. However, deconstructing the ASTs is a dicey process,
4701     // and this approach is far more likely to get the corner cases right.
4702     if (CurContext->isDependentContext())
4703       BaseInit = Init;
4704   }
4705 
4706   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4707                                           BaseSpec->isVirtual(),
4708                                           InitRange.getBegin(),
4709                                           BaseInit.getAs<Expr>(),
4710                                           InitRange.getEnd(), EllipsisLoc);
4711 }
4712 
4713 // Create a static_cast\<T&&>(expr).
4714 static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
4715   QualType TargetType =
4716       SemaRef.BuildReferenceType(E->getType(), /*SpelledAsLValue*/ false,
4717                                  SourceLocation(), DeclarationName());
4718   SourceLocation ExprLoc = E->getBeginLoc();
4719   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4720       TargetType, ExprLoc);
4721 
4722   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4723                                    SourceRange(ExprLoc, ExprLoc),
4724                                    E->getSourceRange()).get();
4725 }
4726 
4727 /// ImplicitInitializerKind - How an implicit base or member initializer should
4728 /// initialize its base or member.
4729 enum ImplicitInitializerKind {
4730   IIK_Default,
4731   IIK_Copy,
4732   IIK_Move,
4733   IIK_Inherit
4734 };
4735 
4736 static bool
4737 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4738                              ImplicitInitializerKind ImplicitInitKind,
4739                              CXXBaseSpecifier *BaseSpec,
4740                              bool IsInheritedVirtualBase,
4741                              CXXCtorInitializer *&CXXBaseInit) {
4742   InitializedEntity InitEntity
4743     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4744                                         IsInheritedVirtualBase);
4745 
4746   ExprResult BaseInit;
4747 
4748   switch (ImplicitInitKind) {
4749   case IIK_Inherit:
4750   case IIK_Default: {
4751     InitializationKind InitKind
4752       = InitializationKind::CreateDefault(Constructor->getLocation());
4753     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, std::nullopt);
4754     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, std::nullopt);
4755     break;
4756   }
4757 
4758   case IIK_Move:
4759   case IIK_Copy: {
4760     bool Moving = ImplicitInitKind == IIK_Move;
4761     ParmVarDecl *Param = Constructor->getParamDecl(0);
4762     QualType ParamType = Param->getType().getNonReferenceType();
4763 
4764     Expr *CopyCtorArg =
4765       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4766                           SourceLocation(), Param, false,
4767                           Constructor->getLocation(), ParamType,
4768                           VK_LValue, nullptr);
4769 
4770     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4771 
4772     // Cast to the base class to avoid ambiguities.
4773     QualType ArgTy =
4774       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4775                                        ParamType.getQualifiers());
4776 
4777     if (Moving) {
4778       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4779     }
4780 
4781     CXXCastPath BasePath;
4782     BasePath.push_back(BaseSpec);
4783     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4784                                             CK_UncheckedDerivedToBase,
4785                                             Moving ? VK_XValue : VK_LValue,
4786                                             &BasePath).get();
4787 
4788     InitializationKind InitKind
4789       = InitializationKind::CreateDirect(Constructor->getLocation(),
4790                                          SourceLocation(), SourceLocation());
4791     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4792     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4793     break;
4794   }
4795   }
4796 
4797   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4798   if (BaseInit.isInvalid())
4799     return true;
4800 
4801   CXXBaseInit =
4802     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4803                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4804                                                         SourceLocation()),
4805                                              BaseSpec->isVirtual(),
4806                                              SourceLocation(),
4807                                              BaseInit.getAs<Expr>(),
4808                                              SourceLocation(),
4809                                              SourceLocation());
4810 
4811   return false;
4812 }
4813 
4814 static bool RefersToRValueRef(Expr *MemRef) {
4815   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4816   return Referenced->getType()->isRValueReferenceType();
4817 }
4818 
4819 static bool
4820 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4821                                ImplicitInitializerKind ImplicitInitKind,
4822                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4823                                CXXCtorInitializer *&CXXMemberInit) {
4824   if (Field->isInvalidDecl())
4825     return true;
4826 
4827   SourceLocation Loc = Constructor->getLocation();
4828 
4829   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4830     bool Moving = ImplicitInitKind == IIK_Move;
4831     ParmVarDecl *Param = Constructor->getParamDecl(0);
4832     QualType ParamType = Param->getType().getNonReferenceType();
4833 
4834     // Suppress copying zero-width bitfields.
4835     if (Field->isZeroLengthBitField(SemaRef.Context))
4836       return false;
4837 
4838     Expr *MemberExprBase =
4839       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4840                           SourceLocation(), Param, false,
4841                           Loc, ParamType, VK_LValue, nullptr);
4842 
4843     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4844 
4845     if (Moving) {
4846       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4847     }
4848 
4849     // Build a reference to this field within the parameter.
4850     CXXScopeSpec SS;
4851     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4852                               Sema::LookupMemberName);
4853     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4854                                   : cast<ValueDecl>(Field), AS_public);
4855     MemberLookup.resolveKind();
4856     ExprResult CtorArg
4857       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4858                                          ParamType, Loc,
4859                                          /*IsArrow=*/false,
4860                                          SS,
4861                                          /*TemplateKWLoc=*/SourceLocation(),
4862                                          /*FirstQualifierInScope=*/nullptr,
4863                                          MemberLookup,
4864                                          /*TemplateArgs=*/nullptr,
4865                                          /*S*/nullptr);
4866     if (CtorArg.isInvalid())
4867       return true;
4868 
4869     // C++11 [class.copy]p15:
4870     //   - if a member m has rvalue reference type T&&, it is direct-initialized
4871     //     with static_cast<T&&>(x.m);
4872     if (RefersToRValueRef(CtorArg.get())) {
4873       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4874     }
4875 
4876     InitializedEntity Entity =
4877         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4878                                                        /*Implicit*/ true)
4879                  : InitializedEntity::InitializeMember(Field, nullptr,
4880                                                        /*Implicit*/ true);
4881 
4882     // Direct-initialize to use the copy constructor.
4883     InitializationKind InitKind =
4884       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4885 
4886     Expr *CtorArgE = CtorArg.getAs<Expr>();
4887     InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4888     ExprResult MemberInit =
4889         InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4890     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4891     if (MemberInit.isInvalid())
4892       return true;
4893 
4894     if (Indirect)
4895       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4896           SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4897     else
4898       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4899           SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4900     return false;
4901   }
4902 
4903   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4904          "Unhandled implicit init kind!");
4905 
4906   QualType FieldBaseElementType =
4907     SemaRef.Context.getBaseElementType(Field->getType());
4908 
4909   if (FieldBaseElementType->isRecordType()) {
4910     InitializedEntity InitEntity =
4911         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4912                                                        /*Implicit*/ true)
4913                  : InitializedEntity::InitializeMember(Field, nullptr,
4914                                                        /*Implicit*/ true);
4915     InitializationKind InitKind =
4916       InitializationKind::CreateDefault(Loc);
4917 
4918     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, std::nullopt);
4919     ExprResult MemberInit =
4920         InitSeq.Perform(SemaRef, InitEntity, InitKind, std::nullopt);
4921 
4922     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4923     if (MemberInit.isInvalid())
4924       return true;
4925 
4926     if (Indirect)
4927       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4928                                                                Indirect, Loc,
4929                                                                Loc,
4930                                                                MemberInit.get(),
4931                                                                Loc);
4932     else
4933       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4934                                                                Field, Loc, Loc,
4935                                                                MemberInit.get(),
4936                                                                Loc);
4937     return false;
4938   }
4939 
4940   if (!Field->getParent()->isUnion()) {
4941     if (FieldBaseElementType->isReferenceType()) {
4942       SemaRef.Diag(Constructor->getLocation(),
4943                    diag::err_uninitialized_member_in_ctor)
4944       << (int)Constructor->isImplicit()
4945       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4946       << 0 << Field->getDeclName();
4947       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4948       return true;
4949     }
4950 
4951     if (FieldBaseElementType.isConstQualified()) {
4952       SemaRef.Diag(Constructor->getLocation(),
4953                    diag::err_uninitialized_member_in_ctor)
4954       << (int)Constructor->isImplicit()
4955       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4956       << 1 << Field->getDeclName();
4957       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4958       return true;
4959     }
4960   }
4961 
4962   if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4963     // ARC and Weak:
4964     //   Default-initialize Objective-C pointers to NULL.
4965     CXXMemberInit
4966       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4967                                                  Loc, Loc,
4968                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4969                                                  Loc);
4970     return false;
4971   }
4972 
4973   // Nothing to initialize.
4974   CXXMemberInit = nullptr;
4975   return false;
4976 }
4977 
4978 namespace {
4979 struct BaseAndFieldInfo {
4980   Sema &S;
4981   CXXConstructorDecl *Ctor;
4982   bool AnyErrorsInInits;
4983   ImplicitInitializerKind IIK;
4984   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4985   SmallVector<CXXCtorInitializer*, 8> AllToInit;
4986   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4987 
4988   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4989     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4990     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4991     if (Ctor->getInheritedConstructor())
4992       IIK = IIK_Inherit;
4993     else if (Generated && Ctor->isCopyConstructor())
4994       IIK = IIK_Copy;
4995     else if (Generated && Ctor->isMoveConstructor())
4996       IIK = IIK_Move;
4997     else
4998       IIK = IIK_Default;
4999   }
5000 
5001   bool isImplicitCopyOrMove() const {
5002     switch (IIK) {
5003     case IIK_Copy:
5004     case IIK_Move:
5005       return true;
5006 
5007     case IIK_Default:
5008     case IIK_Inherit:
5009       return false;
5010     }
5011 
5012     llvm_unreachable("Invalid ImplicitInitializerKind!");
5013   }
5014 
5015   bool addFieldInitializer(CXXCtorInitializer *Init) {
5016     AllToInit.push_back(Init);
5017 
5018     // Check whether this initializer makes the field "used".
5019     if (Init->getInit()->HasSideEffects(S.Context))
5020       S.UnusedPrivateFields.remove(Init->getAnyMember());
5021 
5022     return false;
5023   }
5024 
5025   bool isInactiveUnionMember(FieldDecl *Field) {
5026     RecordDecl *Record = Field->getParent();
5027     if (!Record->isUnion())
5028       return false;
5029 
5030     if (FieldDecl *Active =
5031             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
5032       return Active != Field->getCanonicalDecl();
5033 
5034     // In an implicit copy or move constructor, ignore any in-class initializer.
5035     if (isImplicitCopyOrMove())
5036       return true;
5037 
5038     // If there's no explicit initialization, the field is active only if it
5039     // has an in-class initializer...
5040     if (Field->hasInClassInitializer())
5041       return false;
5042     // ... or it's an anonymous struct or union whose class has an in-class
5043     // initializer.
5044     if (!Field->isAnonymousStructOrUnion())
5045       return true;
5046     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
5047     return !FieldRD->hasInClassInitializer();
5048   }
5049 
5050   /// Determine whether the given field is, or is within, a union member
5051   /// that is inactive (because there was an initializer given for a different
5052   /// member of the union, or because the union was not initialized at all).
5053   bool isWithinInactiveUnionMember(FieldDecl *Field,
5054                                    IndirectFieldDecl *Indirect) {
5055     if (!Indirect)
5056       return isInactiveUnionMember(Field);
5057 
5058     for (auto *C : Indirect->chain()) {
5059       FieldDecl *Field = dyn_cast<FieldDecl>(C);
5060       if (Field && isInactiveUnionMember(Field))
5061         return true;
5062     }
5063     return false;
5064   }
5065 };
5066 }
5067 
5068 /// Determine whether the given type is an incomplete or zero-lenfgth
5069 /// array type.
5070 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
5071   if (T->isIncompleteArrayType())
5072     return true;
5073 
5074   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
5075     if (!ArrayT->getSize())
5076       return true;
5077 
5078     T = ArrayT->getElementType();
5079   }
5080 
5081   return false;
5082 }
5083 
5084 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
5085                                     FieldDecl *Field,
5086                                     IndirectFieldDecl *Indirect = nullptr) {
5087   if (Field->isInvalidDecl())
5088     return false;
5089 
5090   // Overwhelmingly common case: we have a direct initializer for this field.
5091   if (CXXCtorInitializer *Init =
5092           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
5093     return Info.addFieldInitializer(Init);
5094 
5095   // C++11 [class.base.init]p8:
5096   //   if the entity is a non-static data member that has a
5097   //   brace-or-equal-initializer and either
5098   //   -- the constructor's class is a union and no other variant member of that
5099   //      union is designated by a mem-initializer-id or
5100   //   -- the constructor's class is not a union, and, if the entity is a member
5101   //      of an anonymous union, no other member of that union is designated by
5102   //      a mem-initializer-id,
5103   //   the entity is initialized as specified in [dcl.init].
5104   //
5105   // We also apply the same rules to handle anonymous structs within anonymous
5106   // unions.
5107   if (Info.isWithinInactiveUnionMember(Field, Indirect))
5108     return false;
5109 
5110   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
5111     ExprResult DIE =
5112         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
5113     if (DIE.isInvalid())
5114       return true;
5115 
5116     auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
5117     SemaRef.checkInitializerLifetime(Entity, DIE.get());
5118 
5119     CXXCtorInitializer *Init;
5120     if (Indirect)
5121       Init = new (SemaRef.Context)
5122           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
5123                              SourceLocation(), DIE.get(), SourceLocation());
5124     else
5125       Init = new (SemaRef.Context)
5126           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
5127                              SourceLocation(), DIE.get(), SourceLocation());
5128     return Info.addFieldInitializer(Init);
5129   }
5130 
5131   // Don't initialize incomplete or zero-length arrays.
5132   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
5133     return false;
5134 
5135   // Don't try to build an implicit initializer if there were semantic
5136   // errors in any of the initializers (and therefore we might be
5137   // missing some that the user actually wrote).
5138   if (Info.AnyErrorsInInits)
5139     return false;
5140 
5141   CXXCtorInitializer *Init = nullptr;
5142   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
5143                                      Indirect, Init))
5144     return true;
5145 
5146   if (!Init)
5147     return false;
5148 
5149   return Info.addFieldInitializer(Init);
5150 }
5151 
5152 bool
5153 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5154                                CXXCtorInitializer *Initializer) {
5155   assert(Initializer->isDelegatingInitializer());
5156   Constructor->setNumCtorInitializers(1);
5157   CXXCtorInitializer **initializer =
5158     new (Context) CXXCtorInitializer*[1];
5159   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
5160   Constructor->setCtorInitializers(initializer);
5161 
5162   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
5163     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5164     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5165   }
5166 
5167   DelegatingCtorDecls.push_back(Constructor);
5168 
5169   DiagnoseUninitializedFields(*this, Constructor);
5170 
5171   return false;
5172 }
5173 
5174 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5175                                ArrayRef<CXXCtorInitializer *> Initializers) {
5176   if (Constructor->isDependentContext()) {
5177     // Just store the initializers as written, they will be checked during
5178     // instantiation.
5179     if (!Initializers.empty()) {
5180       Constructor->setNumCtorInitializers(Initializers.size());
5181       CXXCtorInitializer **baseOrMemberInitializers =
5182         new (Context) CXXCtorInitializer*[Initializers.size()];
5183       memcpy(baseOrMemberInitializers, Initializers.data(),
5184              Initializers.size() * sizeof(CXXCtorInitializer*));
5185       Constructor->setCtorInitializers(baseOrMemberInitializers);
5186     }
5187 
5188     // Let template instantiation know whether we had errors.
5189     if (AnyErrors)
5190       Constructor->setInvalidDecl();
5191 
5192     return false;
5193   }
5194 
5195   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5196 
5197   // We need to build the initializer AST according to order of construction
5198   // and not what user specified in the Initializers list.
5199   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5200   if (!ClassDecl)
5201     return true;
5202 
5203   bool HadError = false;
5204 
5205   for (unsigned i = 0; i < Initializers.size(); i++) {
5206     CXXCtorInitializer *Member = Initializers[i];
5207 
5208     if (Member->isBaseInitializer())
5209       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
5210     else {
5211       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5212 
5213       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5214         for (auto *C : F->chain()) {
5215           FieldDecl *FD = dyn_cast<FieldDecl>(C);
5216           if (FD && FD->getParent()->isUnion())
5217             Info.ActiveUnionMember.insert(std::make_pair(
5218                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5219         }
5220       } else if (FieldDecl *FD = Member->getMember()) {
5221         if (FD->getParent()->isUnion())
5222           Info.ActiveUnionMember.insert(std::make_pair(
5223               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5224       }
5225     }
5226   }
5227 
5228   // Keep track of the direct virtual bases.
5229   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
5230   for (auto &I : ClassDecl->bases()) {
5231     if (I.isVirtual())
5232       DirectVBases.insert(&I);
5233   }
5234 
5235   // Push virtual bases before others.
5236   for (auto &VBase : ClassDecl->vbases()) {
5237     if (CXXCtorInitializer *Value
5238         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
5239       // [class.base.init]p7, per DR257:
5240       //   A mem-initializer where the mem-initializer-id names a virtual base
5241       //   class is ignored during execution of a constructor of any class that
5242       //   is not the most derived class.
5243       if (ClassDecl->isAbstract()) {
5244         // FIXME: Provide a fixit to remove the base specifier. This requires
5245         // tracking the location of the associated comma for a base specifier.
5246         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5247           << VBase.getType() << ClassDecl;
5248         DiagnoseAbstractType(ClassDecl);
5249       }
5250 
5251       Info.AllToInit.push_back(Value);
5252     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5253       // [class.base.init]p8, per DR257:
5254       //   If a given [...] base class is not named by a mem-initializer-id
5255       //   [...] and the entity is not a virtual base class of an abstract
5256       //   class, then [...] the entity is default-initialized.
5257       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5258       CXXCtorInitializer *CXXBaseInit;
5259       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5260                                        &VBase, IsInheritedVirtualBase,
5261                                        CXXBaseInit)) {
5262         HadError = true;
5263         continue;
5264       }
5265 
5266       Info.AllToInit.push_back(CXXBaseInit);
5267     }
5268   }
5269 
5270   // Non-virtual bases.
5271   for (auto &Base : ClassDecl->bases()) {
5272     // Virtuals are in the virtual base list and already constructed.
5273     if (Base.isVirtual())
5274       continue;
5275 
5276     if (CXXCtorInitializer *Value
5277           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
5278       Info.AllToInit.push_back(Value);
5279     } else if (!AnyErrors) {
5280       CXXCtorInitializer *CXXBaseInit;
5281       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5282                                        &Base, /*IsInheritedVirtualBase=*/false,
5283                                        CXXBaseInit)) {
5284         HadError = true;
5285         continue;
5286       }
5287 
5288       Info.AllToInit.push_back(CXXBaseInit);
5289     }
5290   }
5291 
5292   // Fields.
5293   for (auto *Mem : ClassDecl->decls()) {
5294     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5295       // C++ [class.bit]p2:
5296       //   A declaration for a bit-field that omits the identifier declares an
5297       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
5298       //   initialized.
5299       if (F->isUnnamedBitfield())
5300         continue;
5301 
5302       // If we're not generating the implicit copy/move constructor, then we'll
5303       // handle anonymous struct/union fields based on their individual
5304       // indirect fields.
5305       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5306         continue;
5307 
5308       if (CollectFieldInitializer(*this, Info, F))
5309         HadError = true;
5310       continue;
5311     }
5312 
5313     // Beyond this point, we only consider default initialization.
5314     if (Info.isImplicitCopyOrMove())
5315       continue;
5316 
5317     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5318       if (F->getType()->isIncompleteArrayType()) {
5319         assert(ClassDecl->hasFlexibleArrayMember() &&
5320                "Incomplete array type is not valid");
5321         continue;
5322       }
5323 
5324       // Initialize each field of an anonymous struct individually.
5325       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5326         HadError = true;
5327 
5328       continue;
5329     }
5330   }
5331 
5332   unsigned NumInitializers = Info.AllToInit.size();
5333   if (NumInitializers > 0) {
5334     Constructor->setNumCtorInitializers(NumInitializers);
5335     CXXCtorInitializer **baseOrMemberInitializers =
5336       new (Context) CXXCtorInitializer*[NumInitializers];
5337     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5338            NumInitializers * sizeof(CXXCtorInitializer*));
5339     Constructor->setCtorInitializers(baseOrMemberInitializers);
5340 
5341     // Constructors implicitly reference the base and member
5342     // destructors.
5343     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
5344                                            Constructor->getParent());
5345   }
5346 
5347   return HadError;
5348 }
5349 
5350 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5351   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5352     const RecordDecl *RD = RT->getDecl();
5353     if (RD->isAnonymousStructOrUnion()) {
5354       for (auto *Field : RD->fields())
5355         PopulateKeysForFields(Field, IdealInits);
5356       return;
5357     }
5358   }
5359   IdealInits.push_back(Field->getCanonicalDecl());
5360 }
5361 
5362 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5363   return Context.getCanonicalType(BaseType).getTypePtr();
5364 }
5365 
5366 static const void *GetKeyForMember(ASTContext &Context,
5367                                    CXXCtorInitializer *Member) {
5368   if (!Member->isAnyMemberInitializer())
5369     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5370 
5371   return Member->getAnyMember()->getCanonicalDecl();
5372 }
5373 
5374 static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag,
5375                                  const CXXCtorInitializer *Previous,
5376                                  const CXXCtorInitializer *Current) {
5377   if (Previous->isAnyMemberInitializer())
5378     Diag << 0 << Previous->getAnyMember();
5379   else
5380     Diag << 1 << Previous->getTypeSourceInfo()->getType();
5381 
5382   if (Current->isAnyMemberInitializer())
5383     Diag << 0 << Current->getAnyMember();
5384   else
5385     Diag << 1 << Current->getTypeSourceInfo()->getType();
5386 }
5387 
5388 static void DiagnoseBaseOrMemInitializerOrder(
5389     Sema &SemaRef, const CXXConstructorDecl *Constructor,
5390     ArrayRef<CXXCtorInitializer *> Inits) {
5391   if (Constructor->getDeclContext()->isDependentContext())
5392     return;
5393 
5394   // Don't check initializers order unless the warning is enabled at the
5395   // location of at least one initializer.
5396   bool ShouldCheckOrder = false;
5397   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5398     CXXCtorInitializer *Init = Inits[InitIndex];
5399     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5400                                  Init->getSourceLocation())) {
5401       ShouldCheckOrder = true;
5402       break;
5403     }
5404   }
5405   if (!ShouldCheckOrder)
5406     return;
5407 
5408   // Build the list of bases and members in the order that they'll
5409   // actually be initialized.  The explicit initializers should be in
5410   // this same order but may be missing things.
5411   SmallVector<const void*, 32> IdealInitKeys;
5412 
5413   const CXXRecordDecl *ClassDecl = Constructor->getParent();
5414 
5415   // 1. Virtual bases.
5416   for (const auto &VBase : ClassDecl->vbases())
5417     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5418 
5419   // 2. Non-virtual bases.
5420   for (const auto &Base : ClassDecl->bases()) {
5421     if (Base.isVirtual())
5422       continue;
5423     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5424   }
5425 
5426   // 3. Direct fields.
5427   for (auto *Field : ClassDecl->fields()) {
5428     if (Field->isUnnamedBitfield())
5429       continue;
5430 
5431     PopulateKeysForFields(Field, IdealInitKeys);
5432   }
5433 
5434   unsigned NumIdealInits = IdealInitKeys.size();
5435   unsigned IdealIndex = 0;
5436 
5437   // Track initializers that are in an incorrect order for either a warning or
5438   // note if multiple ones occur.
5439   SmallVector<unsigned> WarnIndexes;
5440   // Correlates the index of an initializer in the init-list to the index of
5441   // the field/base in the class.
5442   SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5443 
5444   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5445     const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]);
5446 
5447     // Scan forward to try to find this initializer in the idealized
5448     // initializers list.
5449     for (; IdealIndex != NumIdealInits; ++IdealIndex)
5450       if (InitKey == IdealInitKeys[IdealIndex])
5451         break;
5452 
5453     // If we didn't find this initializer, it must be because we
5454     // scanned past it on a previous iteration.  That can only
5455     // happen if we're out of order;  emit a warning.
5456     if (IdealIndex == NumIdealInits && InitIndex) {
5457       WarnIndexes.push_back(InitIndex);
5458 
5459       // Move back to the initializer's location in the ideal list.
5460       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5461         if (InitKey == IdealInitKeys[IdealIndex])
5462           break;
5463 
5464       assert(IdealIndex < NumIdealInits &&
5465              "initializer not found in initializer list");
5466     }
5467     CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex);
5468   }
5469 
5470   if (WarnIndexes.empty())
5471     return;
5472 
5473   // Sort based on the ideal order, first in the pair.
5474   llvm::sort(CorrelatedInitOrder, llvm::less_first());
5475 
5476   // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5477   // emit the diagnostic before we can try adding notes.
5478   {
5479     Sema::SemaDiagnosticBuilder D = SemaRef.Diag(
5480         Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5481         WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5482                                 : diag::warn_some_initializers_out_of_order);
5483 
5484     for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5485       if (CorrelatedInitOrder[I].second == I)
5486         continue;
5487       // Ideally we would be using InsertFromRange here, but clang doesn't
5488       // appear to handle InsertFromRange correctly when the source range is
5489       // modified by another fix-it.
5490       D << FixItHint::CreateReplacement(
5491           Inits[I]->getSourceRange(),
5492           Lexer::getSourceText(
5493               CharSourceRange::getTokenRange(
5494                   Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5495               SemaRef.getSourceManager(), SemaRef.getLangOpts()));
5496     }
5497 
5498     // If there is only 1 item out of order, the warning expects the name and
5499     // type of each being added to it.
5500     if (WarnIndexes.size() == 1) {
5501       AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1],
5502                            Inits[WarnIndexes.front()]);
5503       return;
5504     }
5505   }
5506   // More than 1 item to warn, create notes letting the user know which ones
5507   // are bad.
5508   for (unsigned WarnIndex : WarnIndexes) {
5509     const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5510     auto D = SemaRef.Diag(PrevInit->getSourceLocation(),
5511                           diag::note_initializer_out_of_order);
5512     AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]);
5513     D << PrevInit->getSourceRange();
5514   }
5515 }
5516 
5517 namespace {
5518 bool CheckRedundantInit(Sema &S,
5519                         CXXCtorInitializer *Init,
5520                         CXXCtorInitializer *&PrevInit) {
5521   if (!PrevInit) {
5522     PrevInit = Init;
5523     return false;
5524   }
5525 
5526   if (FieldDecl *Field = Init->getAnyMember())
5527     S.Diag(Init->getSourceLocation(),
5528            diag::err_multiple_mem_initialization)
5529       << Field->getDeclName()
5530       << Init->getSourceRange();
5531   else {
5532     const Type *BaseClass = Init->getBaseClass();
5533     assert(BaseClass && "neither field nor base");
5534     S.Diag(Init->getSourceLocation(),
5535            diag::err_multiple_base_initialization)
5536       << QualType(BaseClass, 0)
5537       << Init->getSourceRange();
5538   }
5539   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5540     << 0 << PrevInit->getSourceRange();
5541 
5542   return true;
5543 }
5544 
5545 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5546 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5547 
5548 bool CheckRedundantUnionInit(Sema &S,
5549                              CXXCtorInitializer *Init,
5550                              RedundantUnionMap &Unions) {
5551   FieldDecl *Field = Init->getAnyMember();
5552   RecordDecl *Parent = Field->getParent();
5553   NamedDecl *Child = Field;
5554 
5555   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5556     if (Parent->isUnion()) {
5557       UnionEntry &En = Unions[Parent];
5558       if (En.first && En.first != Child) {
5559         S.Diag(Init->getSourceLocation(),
5560                diag::err_multiple_mem_union_initialization)
5561           << Field->getDeclName()
5562           << Init->getSourceRange();
5563         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5564           << 0 << En.second->getSourceRange();
5565         return true;
5566       }
5567       if (!En.first) {
5568         En.first = Child;
5569         En.second = Init;
5570       }
5571       if (!Parent->isAnonymousStructOrUnion())
5572         return false;
5573     }
5574 
5575     Child = Parent;
5576     Parent = cast<RecordDecl>(Parent->getDeclContext());
5577   }
5578 
5579   return false;
5580 }
5581 } // namespace
5582 
5583 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5584 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5585                                 SourceLocation ColonLoc,
5586                                 ArrayRef<CXXCtorInitializer*> MemInits,
5587                                 bool AnyErrors) {
5588   if (!ConstructorDecl)
5589     return;
5590 
5591   AdjustDeclIfTemplate(ConstructorDecl);
5592 
5593   CXXConstructorDecl *Constructor
5594     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5595 
5596   if (!Constructor) {
5597     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5598     return;
5599   }
5600 
5601   // Mapping for the duplicate initializers check.
5602   // For member initializers, this is keyed with a FieldDecl*.
5603   // For base initializers, this is keyed with a Type*.
5604   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5605 
5606   // Mapping for the inconsistent anonymous-union initializers check.
5607   RedundantUnionMap MemberUnions;
5608 
5609   bool HadError = false;
5610   for (unsigned i = 0; i < MemInits.size(); i++) {
5611     CXXCtorInitializer *Init = MemInits[i];
5612 
5613     // Set the source order index.
5614     Init->setSourceOrder(i);
5615 
5616     if (Init->isAnyMemberInitializer()) {
5617       const void *Key = GetKeyForMember(Context, Init);
5618       if (CheckRedundantInit(*this, Init, Members[Key]) ||
5619           CheckRedundantUnionInit(*this, Init, MemberUnions))
5620         HadError = true;
5621     } else if (Init->isBaseInitializer()) {
5622       const void *Key = GetKeyForMember(Context, Init);
5623       if (CheckRedundantInit(*this, Init, Members[Key]))
5624         HadError = true;
5625     } else {
5626       assert(Init->isDelegatingInitializer());
5627       // This must be the only initializer
5628       if (MemInits.size() != 1) {
5629         Diag(Init->getSourceLocation(),
5630              diag::err_delegating_initializer_alone)
5631           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5632         // We will treat this as being the only initializer.
5633       }
5634       SetDelegatingInitializer(Constructor, MemInits[i]);
5635       // Return immediately as the initializer is set.
5636       return;
5637     }
5638   }
5639 
5640   if (HadError)
5641     return;
5642 
5643   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5644 
5645   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5646 
5647   DiagnoseUninitializedFields(*this, Constructor);
5648 }
5649 
5650 void
5651 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5652                                              CXXRecordDecl *ClassDecl) {
5653   // Ignore dependent contexts. Also ignore unions, since their members never
5654   // have destructors implicitly called.
5655   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5656     return;
5657 
5658   // FIXME: all the access-control diagnostics are positioned on the
5659   // field/base declaration.  That's probably good; that said, the
5660   // user might reasonably want to know why the destructor is being
5661   // emitted, and we currently don't say.
5662 
5663   // Non-static data members.
5664   for (auto *Field : ClassDecl->fields()) {
5665     if (Field->isInvalidDecl())
5666       continue;
5667 
5668     // Don't destroy incomplete or zero-length arrays.
5669     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5670       continue;
5671 
5672     QualType FieldType = Context.getBaseElementType(Field->getType());
5673 
5674     const RecordType* RT = FieldType->getAs<RecordType>();
5675     if (!RT)
5676       continue;
5677 
5678     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5679     if (FieldClassDecl->isInvalidDecl())
5680       continue;
5681     if (FieldClassDecl->hasIrrelevantDestructor())
5682       continue;
5683     // The destructor for an implicit anonymous union member is never invoked.
5684     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5685       continue;
5686 
5687     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5688     // Dtor might still be missing, e.g because it's invalid.
5689     if (!Dtor)
5690       continue;
5691     CheckDestructorAccess(Field->getLocation(), Dtor,
5692                           PDiag(diag::err_access_dtor_field)
5693                             << Field->getDeclName()
5694                             << FieldType);
5695 
5696     MarkFunctionReferenced(Location, Dtor);
5697     DiagnoseUseOfDecl(Dtor, Location);
5698   }
5699 
5700   // We only potentially invoke the destructors of potentially constructed
5701   // subobjects.
5702   bool VisitVirtualBases = !ClassDecl->isAbstract();
5703 
5704   // If the destructor exists and has already been marked used in the MS ABI,
5705   // then virtual base destructors have already been checked and marked used.
5706   // Skip checking them again to avoid duplicate diagnostics.
5707   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5708     CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5709     if (Dtor && Dtor->isUsed())
5710       VisitVirtualBases = false;
5711   }
5712 
5713   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5714 
5715   // Bases.
5716   for (const auto &Base : ClassDecl->bases()) {
5717     const RecordType *RT = Base.getType()->getAs<RecordType>();
5718     if (!RT)
5719       continue;
5720 
5721     // Remember direct virtual bases.
5722     if (Base.isVirtual()) {
5723       if (!VisitVirtualBases)
5724         continue;
5725       DirectVirtualBases.insert(RT);
5726     }
5727 
5728     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5729     // If our base class is invalid, we probably can't get its dtor anyway.
5730     if (BaseClassDecl->isInvalidDecl())
5731       continue;
5732     if (BaseClassDecl->hasIrrelevantDestructor())
5733       continue;
5734 
5735     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5736     // Dtor might still be missing, e.g because it's invalid.
5737     if (!Dtor)
5738       continue;
5739 
5740     // FIXME: caret should be on the start of the class name
5741     CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5742                           PDiag(diag::err_access_dtor_base)
5743                               << Base.getType() << Base.getSourceRange(),
5744                           Context.getTypeDeclType(ClassDecl));
5745 
5746     MarkFunctionReferenced(Location, Dtor);
5747     DiagnoseUseOfDecl(Dtor, Location);
5748   }
5749 
5750   if (VisitVirtualBases)
5751     MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5752                                          &DirectVirtualBases);
5753 }
5754 
5755 void Sema::MarkVirtualBaseDestructorsReferenced(
5756     SourceLocation Location, CXXRecordDecl *ClassDecl,
5757     llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) {
5758   // Virtual bases.
5759   for (const auto &VBase : ClassDecl->vbases()) {
5760     // Bases are always records in a well-formed non-dependent class.
5761     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5762 
5763     // Ignore already visited direct virtual bases.
5764     if (DirectVirtualBases && DirectVirtualBases->count(RT))
5765       continue;
5766 
5767     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5768     // If our base class is invalid, we probably can't get its dtor anyway.
5769     if (BaseClassDecl->isInvalidDecl())
5770       continue;
5771     if (BaseClassDecl->hasIrrelevantDestructor())
5772       continue;
5773 
5774     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5775     // Dtor might still be missing, e.g because it's invalid.
5776     if (!Dtor)
5777       continue;
5778     if (CheckDestructorAccess(
5779             ClassDecl->getLocation(), Dtor,
5780             PDiag(diag::err_access_dtor_vbase)
5781                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5782             Context.getTypeDeclType(ClassDecl)) ==
5783         AR_accessible) {
5784       CheckDerivedToBaseConversion(
5785           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5786           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5787           SourceRange(), DeclarationName(), nullptr);
5788     }
5789 
5790     MarkFunctionReferenced(Location, Dtor);
5791     DiagnoseUseOfDecl(Dtor, Location);
5792   }
5793 }
5794 
5795 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5796   if (!CDtorDecl)
5797     return;
5798 
5799   if (CXXConstructorDecl *Constructor
5800       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5801     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5802     DiagnoseUninitializedFields(*this, Constructor);
5803   }
5804 }
5805 
5806 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5807   if (!getLangOpts().CPlusPlus)
5808     return false;
5809 
5810   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5811   if (!RD)
5812     return false;
5813 
5814   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5815   // class template specialization here, but doing so breaks a lot of code.
5816 
5817   // We can't answer whether something is abstract until it has a
5818   // definition. If it's currently being defined, we'll walk back
5819   // over all the declarations when we have a full definition.
5820   const CXXRecordDecl *Def = RD->getDefinition();
5821   if (!Def || Def->isBeingDefined())
5822     return false;
5823 
5824   return RD->isAbstract();
5825 }
5826 
5827 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5828                                   TypeDiagnoser &Diagnoser) {
5829   if (!isAbstractType(Loc, T))
5830     return false;
5831 
5832   T = Context.getBaseElementType(T);
5833   Diagnoser.diagnose(*this, Loc, T);
5834   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5835   return true;
5836 }
5837 
5838 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5839   // Check if we've already emitted the list of pure virtual functions
5840   // for this class.
5841   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5842     return;
5843 
5844   // If the diagnostic is suppressed, don't emit the notes. We're only
5845   // going to emit them once, so try to attach them to a diagnostic we're
5846   // actually going to show.
5847   if (Diags.isLastDiagnosticIgnored())
5848     return;
5849 
5850   CXXFinalOverriderMap FinalOverriders;
5851   RD->getFinalOverriders(FinalOverriders);
5852 
5853   // Keep a set of seen pure methods so we won't diagnose the same method
5854   // more than once.
5855   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5856 
5857   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5858                                    MEnd = FinalOverriders.end();
5859        M != MEnd;
5860        ++M) {
5861     for (OverridingMethods::iterator SO = M->second.begin(),
5862                                   SOEnd = M->second.end();
5863          SO != SOEnd; ++SO) {
5864       // C++ [class.abstract]p4:
5865       //   A class is abstract if it contains or inherits at least one
5866       //   pure virtual function for which the final overrider is pure
5867       //   virtual.
5868 
5869       //
5870       if (SO->second.size() != 1)
5871         continue;
5872 
5873       if (!SO->second.front().Method->isPure())
5874         continue;
5875 
5876       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5877         continue;
5878 
5879       Diag(SO->second.front().Method->getLocation(),
5880            diag::note_pure_virtual_function)
5881         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5882     }
5883   }
5884 
5885   if (!PureVirtualClassDiagSet)
5886     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5887   PureVirtualClassDiagSet->insert(RD);
5888 }
5889 
5890 namespace {
5891 struct AbstractUsageInfo {
5892   Sema &S;
5893   CXXRecordDecl *Record;
5894   CanQualType AbstractType;
5895   bool Invalid;
5896 
5897   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5898     : S(S), Record(Record),
5899       AbstractType(S.Context.getCanonicalType(
5900                    S.Context.getTypeDeclType(Record))),
5901       Invalid(false) {}
5902 
5903   void DiagnoseAbstractType() {
5904     if (Invalid) return;
5905     S.DiagnoseAbstractType(Record);
5906     Invalid = true;
5907   }
5908 
5909   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5910 };
5911 
5912 struct CheckAbstractUsage {
5913   AbstractUsageInfo &Info;
5914   const NamedDecl *Ctx;
5915 
5916   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5917     : Info(Info), Ctx(Ctx) {}
5918 
5919   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5920     switch (TL.getTypeLocClass()) {
5921 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5922 #define TYPELOC(CLASS, PARENT) \
5923     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5924 #include "clang/AST/TypeLocNodes.def"
5925     }
5926   }
5927 
5928   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5929     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5930     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5931       if (!TL.getParam(I))
5932         continue;
5933 
5934       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5935       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5936     }
5937   }
5938 
5939   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5940     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5941   }
5942 
5943   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5944     // Visit the type parameters from a permissive context.
5945     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5946       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5947       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5948         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5949           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5950       // TODO: other template argument types?
5951     }
5952   }
5953 
5954   // Visit pointee types from a permissive context.
5955 #define CheckPolymorphic(Type) \
5956   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5957     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5958   }
5959   CheckPolymorphic(PointerTypeLoc)
5960   CheckPolymorphic(ReferenceTypeLoc)
5961   CheckPolymorphic(MemberPointerTypeLoc)
5962   CheckPolymorphic(BlockPointerTypeLoc)
5963   CheckPolymorphic(AtomicTypeLoc)
5964 
5965   /// Handle all the types we haven't given a more specific
5966   /// implementation for above.
5967   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5968     // Every other kind of type that we haven't called out already
5969     // that has an inner type is either (1) sugar or (2) contains that
5970     // inner type in some way as a subobject.
5971     if (TypeLoc Next = TL.getNextTypeLoc())
5972       return Visit(Next, Sel);
5973 
5974     // If there's no inner type and we're in a permissive context,
5975     // don't diagnose.
5976     if (Sel == Sema::AbstractNone) return;
5977 
5978     // Check whether the type matches the abstract type.
5979     QualType T = TL.getType();
5980     if (T->isArrayType()) {
5981       Sel = Sema::AbstractArrayType;
5982       T = Info.S.Context.getBaseElementType(T);
5983     }
5984     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5985     if (CT != Info.AbstractType) return;
5986 
5987     // It matched; do some magic.
5988     // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
5989     if (Sel == Sema::AbstractArrayType) {
5990       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5991         << T << TL.getSourceRange();
5992     } else {
5993       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5994         << Sel << T << TL.getSourceRange();
5995     }
5996     Info.DiagnoseAbstractType();
5997   }
5998 };
5999 
6000 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
6001                                   Sema::AbstractDiagSelID Sel) {
6002   CheckAbstractUsage(*this, D).Visit(TL, Sel);
6003 }
6004 
6005 }
6006 
6007 /// Check for invalid uses of an abstract type in a function declaration.
6008 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6009                                     FunctionDecl *FD) {
6010   // No need to do the check on definitions, which require that
6011   // the return/param types be complete.
6012   if (FD->doesThisDeclarationHaveABody())
6013     return;
6014 
6015   // For safety's sake, just ignore it if we don't have type source
6016   // information.  This should never happen for non-implicit methods,
6017   // but...
6018   if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6019     Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone);
6020 }
6021 
6022 /// Check for invalid uses of an abstract type in a variable0 declaration.
6023 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6024                                     VarDecl *VD) {
6025   // No need to do the check on definitions, which require that
6026   // the type is complete.
6027   if (VD->isThisDeclarationADefinition())
6028     return;
6029 
6030   Info.CheckType(VD, VD->getTypeSourceInfo()->getTypeLoc(),
6031                  Sema::AbstractVariableType);
6032 }
6033 
6034 /// Check for invalid uses of an abstract type within a class definition.
6035 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6036                                     CXXRecordDecl *RD) {
6037   for (auto *D : RD->decls()) {
6038     if (D->isImplicit()) continue;
6039 
6040     // Step through friends to the befriended declaration.
6041     if (auto *FD = dyn_cast<FriendDecl>(D)) {
6042       D = FD->getFriendDecl();
6043       if (!D) continue;
6044     }
6045 
6046     // Functions and function templates.
6047     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6048       CheckAbstractClassUsage(Info, FD);
6049     } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {
6050       CheckAbstractClassUsage(Info, FTD->getTemplatedDecl());
6051 
6052     // Fields and static variables.
6053     } else if (auto *FD = dyn_cast<FieldDecl>(D)) {
6054       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6055         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
6056     } else if (auto *VD = dyn_cast<VarDecl>(D)) {
6057       CheckAbstractClassUsage(Info, VD);
6058     } else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) {
6059       CheckAbstractClassUsage(Info, VTD->getTemplatedDecl());
6060 
6061     // Nested classes and class templates.
6062     } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6063       CheckAbstractClassUsage(Info, RD);
6064     } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) {
6065       CheckAbstractClassUsage(Info, CTD->getTemplatedDecl());
6066     }
6067   }
6068 }
6069 
6070 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
6071   Attr *ClassAttr = getDLLAttr(Class);
6072   if (!ClassAttr)
6073     return;
6074 
6075   assert(ClassAttr->getKind() == attr::DLLExport);
6076 
6077   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6078 
6079   if (TSK == TSK_ExplicitInstantiationDeclaration)
6080     // Don't go any further if this is just an explicit instantiation
6081     // declaration.
6082     return;
6083 
6084   // Add a context note to explain how we got to any diagnostics produced below.
6085   struct MarkingClassDllexported {
6086     Sema &S;
6087     MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
6088                             SourceLocation AttrLoc)
6089         : S(S) {
6090       Sema::CodeSynthesisContext Ctx;
6091       Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;
6092       Ctx.PointOfInstantiation = AttrLoc;
6093       Ctx.Entity = Class;
6094       S.pushCodeSynthesisContext(Ctx);
6095     }
6096     ~MarkingClassDllexported() {
6097       S.popCodeSynthesisContext();
6098     }
6099   } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
6100 
6101   if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
6102     S.MarkVTableUsed(Class->getLocation(), Class, true);
6103 
6104   for (Decl *Member : Class->decls()) {
6105     // Skip members that were not marked exported.
6106     if (!Member->hasAttr<DLLExportAttr>())
6107       continue;
6108 
6109     // Defined static variables that are members of an exported base
6110     // class must be marked export too.
6111     auto *VD = dyn_cast<VarDecl>(Member);
6112     if (VD && VD->getStorageClass() == SC_Static &&
6113         TSK == TSK_ImplicitInstantiation)
6114       S.MarkVariableReferenced(VD->getLocation(), VD);
6115 
6116     auto *MD = dyn_cast<CXXMethodDecl>(Member);
6117     if (!MD)
6118       continue;
6119 
6120     if (MD->isUserProvided()) {
6121       // Instantiate non-default class member functions ...
6122 
6123       // .. except for certain kinds of template specializations.
6124       if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
6125         continue;
6126 
6127       // If this is an MS ABI dllexport default constructor, instantiate any
6128       // default arguments.
6129       if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6130         auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6131         if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
6132           S.InstantiateDefaultCtorDefaultArgs(CD);
6133         }
6134       }
6135 
6136       S.MarkFunctionReferenced(Class->getLocation(), MD);
6137 
6138       // The function will be passed to the consumer when its definition is
6139       // encountered.
6140     } else if (MD->isExplicitlyDefaulted()) {
6141       // Synthesize and instantiate explicitly defaulted methods.
6142       S.MarkFunctionReferenced(Class->getLocation(), MD);
6143 
6144       if (TSK != TSK_ExplicitInstantiationDefinition) {
6145         // Except for explicit instantiation defs, we will not see the
6146         // definition again later, so pass it to the consumer now.
6147         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
6148       }
6149     } else if (!MD->isTrivial() ||
6150                MD->isCopyAssignmentOperator() ||
6151                MD->isMoveAssignmentOperator()) {
6152       // Synthesize and instantiate non-trivial implicit methods, and the copy
6153       // and move assignment operators. The latter are exported even if they
6154       // are trivial, because the address of an operator can be taken and
6155       // should compare equal across libraries.
6156       S.MarkFunctionReferenced(Class->getLocation(), MD);
6157 
6158       // There is no later point when we will see the definition of this
6159       // function, so pass it to the consumer now.
6160       S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
6161     }
6162   }
6163 }
6164 
6165 static void checkForMultipleExportedDefaultConstructors(Sema &S,
6166                                                         CXXRecordDecl *Class) {
6167   // Only the MS ABI has default constructor closures, so we don't need to do
6168   // this semantic checking anywhere else.
6169   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
6170     return;
6171 
6172   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6173   for (Decl *Member : Class->decls()) {
6174     // Look for exported default constructors.
6175     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
6176     if (!CD || !CD->isDefaultConstructor())
6177       continue;
6178     auto *Attr = CD->getAttr<DLLExportAttr>();
6179     if (!Attr)
6180       continue;
6181 
6182     // If the class is non-dependent, mark the default arguments as ODR-used so
6183     // that we can properly codegen the constructor closure.
6184     if (!Class->isDependentContext()) {
6185       for (ParmVarDecl *PD : CD->parameters()) {
6186         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
6187         S.DiscardCleanupsInEvaluationContext();
6188       }
6189     }
6190 
6191     if (LastExportedDefaultCtor) {
6192       S.Diag(LastExportedDefaultCtor->getLocation(),
6193              diag::err_attribute_dll_ambiguous_default_ctor)
6194           << Class;
6195       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
6196           << CD->getDeclName();
6197       return;
6198     }
6199     LastExportedDefaultCtor = CD;
6200   }
6201 }
6202 
6203 static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
6204                                                        CXXRecordDecl *Class) {
6205   bool ErrorReported = false;
6206   auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6207                                                      ClassTemplateDecl *TD) {
6208     if (ErrorReported)
6209       return;
6210     S.Diag(TD->getLocation(),
6211            diag::err_cuda_device_builtin_surftex_cls_template)
6212         << /*surface*/ 0 << TD;
6213     ErrorReported = true;
6214   };
6215 
6216   ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6217   if (!TD) {
6218     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6219     if (!SD) {
6220       S.Diag(Class->getLocation(),
6221              diag::err_cuda_device_builtin_surftex_ref_decl)
6222           << /*surface*/ 0 << Class;
6223       S.Diag(Class->getLocation(),
6224              diag::note_cuda_device_builtin_surftex_should_be_template_class)
6225           << Class;
6226       return;
6227     }
6228     TD = SD->getSpecializedTemplate();
6229   }
6230 
6231   TemplateParameterList *Params = TD->getTemplateParameters();
6232   unsigned N = Params->size();
6233 
6234   if (N != 2) {
6235     reportIllegalClassTemplate(S, TD);
6236     S.Diag(TD->getLocation(),
6237            diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6238         << TD << 2;
6239   }
6240   if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6241     reportIllegalClassTemplate(S, TD);
6242     S.Diag(TD->getLocation(),
6243            diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6244         << TD << /*1st*/ 0 << /*type*/ 0;
6245   }
6246   if (N > 1) {
6247     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6248     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6249       reportIllegalClassTemplate(S, TD);
6250       S.Diag(TD->getLocation(),
6251              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6252           << TD << /*2nd*/ 1 << /*integer*/ 1;
6253     }
6254   }
6255 }
6256 
6257 static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
6258                                                        CXXRecordDecl *Class) {
6259   bool ErrorReported = false;
6260   auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6261                                                      ClassTemplateDecl *TD) {
6262     if (ErrorReported)
6263       return;
6264     S.Diag(TD->getLocation(),
6265            diag::err_cuda_device_builtin_surftex_cls_template)
6266         << /*texture*/ 1 << TD;
6267     ErrorReported = true;
6268   };
6269 
6270   ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6271   if (!TD) {
6272     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6273     if (!SD) {
6274       S.Diag(Class->getLocation(),
6275              diag::err_cuda_device_builtin_surftex_ref_decl)
6276           << /*texture*/ 1 << Class;
6277       S.Diag(Class->getLocation(),
6278              diag::note_cuda_device_builtin_surftex_should_be_template_class)
6279           << Class;
6280       return;
6281     }
6282     TD = SD->getSpecializedTemplate();
6283   }
6284 
6285   TemplateParameterList *Params = TD->getTemplateParameters();
6286   unsigned N = Params->size();
6287 
6288   if (N != 3) {
6289     reportIllegalClassTemplate(S, TD);
6290     S.Diag(TD->getLocation(),
6291            diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6292         << TD << 3;
6293   }
6294   if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6295     reportIllegalClassTemplate(S, TD);
6296     S.Diag(TD->getLocation(),
6297            diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6298         << TD << /*1st*/ 0 << /*type*/ 0;
6299   }
6300   if (N > 1) {
6301     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6302     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6303       reportIllegalClassTemplate(S, TD);
6304       S.Diag(TD->getLocation(),
6305              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6306           << TD << /*2nd*/ 1 << /*integer*/ 1;
6307     }
6308   }
6309   if (N > 2) {
6310     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6311     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6312       reportIllegalClassTemplate(S, TD);
6313       S.Diag(TD->getLocation(),
6314              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6315           << TD << /*3rd*/ 2 << /*integer*/ 1;
6316     }
6317   }
6318 }
6319 
6320 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
6321   // Mark any compiler-generated routines with the implicit code_seg attribute.
6322   for (auto *Method : Class->methods()) {
6323     if (Method->isUserProvided())
6324       continue;
6325     if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6326       Method->addAttr(A);
6327   }
6328 }
6329 
6330 /// Check class-level dllimport/dllexport attribute.
6331 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
6332   Attr *ClassAttr = getDLLAttr(Class);
6333 
6334   // MSVC inherits DLL attributes to partial class template specializations.
6335   if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6336     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6337       if (Attr *TemplateAttr =
6338               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6339         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6340         A->setInherited(true);
6341         ClassAttr = A;
6342       }
6343     }
6344   }
6345 
6346   if (!ClassAttr)
6347     return;
6348 
6349   if (!Class->isExternallyVisible()) {
6350     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6351         << Class << ClassAttr;
6352     return;
6353   }
6354 
6355   if (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6356       !ClassAttr->isInherited()) {
6357     // Diagnose dll attributes on members of class with dll attribute.
6358     for (Decl *Member : Class->decls()) {
6359       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
6360         continue;
6361       InheritableAttr *MemberAttr = getDLLAttr(Member);
6362       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6363         continue;
6364 
6365       Diag(MemberAttr->getLocation(),
6366              diag::err_attribute_dll_member_of_dll_class)
6367           << MemberAttr << ClassAttr;
6368       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6369       Member->setInvalidDecl();
6370     }
6371   }
6372 
6373   if (Class->getDescribedClassTemplate())
6374     // Don't inherit dll attribute until the template is instantiated.
6375     return;
6376 
6377   // The class is either imported or exported.
6378   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6379 
6380   // Check if this was a dllimport attribute propagated from a derived class to
6381   // a base class template specialization. We don't apply these attributes to
6382   // static data members.
6383   const bool PropagatedImport =
6384       !ClassExported &&
6385       cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6386 
6387   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6388 
6389   // Ignore explicit dllexport on explicit class template instantiation
6390   // declarations, except in MinGW mode.
6391   if (ClassExported && !ClassAttr->isInherited() &&
6392       TSK == TSK_ExplicitInstantiationDeclaration &&
6393       !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
6394     Class->dropAttr<DLLExportAttr>();
6395     return;
6396   }
6397 
6398   // Force declaration of implicit members so they can inherit the attribute.
6399   ForceDeclarationOfImplicitMembers(Class);
6400 
6401   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6402   // seem to be true in practice?
6403 
6404   for (Decl *Member : Class->decls()) {
6405     VarDecl *VD = dyn_cast<VarDecl>(Member);
6406     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6407 
6408     // Only methods and static fields inherit the attributes.
6409     if (!VD && !MD)
6410       continue;
6411 
6412     if (MD) {
6413       // Don't process deleted methods.
6414       if (MD->isDeleted())
6415         continue;
6416 
6417       if (MD->isInlined()) {
6418         // MinGW does not import or export inline methods. But do it for
6419         // template instantiations.
6420         if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6421             TSK != TSK_ExplicitInstantiationDeclaration &&
6422             TSK != TSK_ExplicitInstantiationDefinition)
6423           continue;
6424 
6425         // MSVC versions before 2015 don't export the move assignment operators
6426         // and move constructor, so don't attempt to import/export them if
6427         // we have a definition.
6428         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6429         if ((MD->isMoveAssignmentOperator() ||
6430              (Ctor && Ctor->isMoveConstructor())) &&
6431             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6432           continue;
6433 
6434         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6435         // operator is exported anyway.
6436         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6437             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6438           continue;
6439       }
6440     }
6441 
6442     // Don't apply dllimport attributes to static data members of class template
6443     // instantiations when the attribute is propagated from a derived class.
6444     if (VD && PropagatedImport)
6445       continue;
6446 
6447     if (!cast<NamedDecl>(Member)->isExternallyVisible())
6448       continue;
6449 
6450     if (!getDLLAttr(Member)) {
6451       InheritableAttr *NewAttr = nullptr;
6452 
6453       // Do not export/import inline function when -fno-dllexport-inlines is
6454       // passed. But add attribute for later local static var check.
6455       if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6456           TSK != TSK_ExplicitInstantiationDeclaration &&
6457           TSK != TSK_ExplicitInstantiationDefinition) {
6458         if (ClassExported) {
6459           NewAttr = ::new (getASTContext())
6460               DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6461         } else {
6462           NewAttr = ::new (getASTContext())
6463               DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6464         }
6465       } else {
6466         NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6467       }
6468 
6469       NewAttr->setInherited(true);
6470       Member->addAttr(NewAttr);
6471 
6472       if (MD) {
6473         // Propagate DLLAttr to friend re-declarations of MD that have already
6474         // been constructed.
6475         for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6476              FD = FD->getPreviousDecl()) {
6477           if (FD->getFriendObjectKind() == Decl::FOK_None)
6478             continue;
6479           assert(!getDLLAttr(FD) &&
6480                  "friend re-decl should not already have a DLLAttr");
6481           NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6482           NewAttr->setInherited(true);
6483           FD->addAttr(NewAttr);
6484         }
6485       }
6486     }
6487   }
6488 
6489   if (ClassExported)
6490     DelayedDllExportClasses.push_back(Class);
6491 }
6492 
6493 /// Perform propagation of DLL attributes from a derived class to a
6494 /// templated base class for MS compatibility.
6495 void Sema::propagateDLLAttrToBaseClassTemplate(
6496     CXXRecordDecl *Class, Attr *ClassAttr,
6497     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6498   if (getDLLAttr(
6499           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6500     // If the base class template has a DLL attribute, don't try to change it.
6501     return;
6502   }
6503 
6504   auto TSK = BaseTemplateSpec->getSpecializationKind();
6505   if (!getDLLAttr(BaseTemplateSpec) &&
6506       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
6507        TSK == TSK_ImplicitInstantiation)) {
6508     // The template hasn't been instantiated yet (or it has, but only as an
6509     // explicit instantiation declaration or implicit instantiation, which means
6510     // we haven't codegenned any members yet), so propagate the attribute.
6511     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6512     NewAttr->setInherited(true);
6513     BaseTemplateSpec->addAttr(NewAttr);
6514 
6515     // If this was an import, mark that we propagated it from a derived class to
6516     // a base class template specialization.
6517     if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6518       ImportAttr->setPropagatedToBaseTemplate();
6519 
6520     // If the template is already instantiated, checkDLLAttributeRedeclaration()
6521     // needs to be run again to work see the new attribute. Otherwise this will
6522     // get run whenever the template is instantiated.
6523     if (TSK != TSK_Undeclared)
6524       checkClassLevelDLLAttribute(BaseTemplateSpec);
6525 
6526     return;
6527   }
6528 
6529   if (getDLLAttr(BaseTemplateSpec)) {
6530     // The template has already been specialized or instantiated with an
6531     // attribute, explicitly or through propagation. We should not try to change
6532     // it.
6533     return;
6534   }
6535 
6536   // The template was previously instantiated or explicitly specialized without
6537   // a dll attribute, It's too late for us to add an attribute, so warn that
6538   // this is unsupported.
6539   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6540       << BaseTemplateSpec->isExplicitSpecialization();
6541   Diag(ClassAttr->getLocation(), diag::note_attribute);
6542   if (BaseTemplateSpec->isExplicitSpecialization()) {
6543     Diag(BaseTemplateSpec->getLocation(),
6544            diag::note_template_class_explicit_specialization_was_here)
6545         << BaseTemplateSpec;
6546   } else {
6547     Diag(BaseTemplateSpec->getPointOfInstantiation(),
6548            diag::note_template_class_instantiation_was_here)
6549         << BaseTemplateSpec;
6550   }
6551 }
6552 
6553 /// Determine the kind of defaulting that would be done for a given function.
6554 ///
6555 /// If the function is both a default constructor and a copy / move constructor
6556 /// (due to having a default argument for the first parameter), this picks
6557 /// CXXDefaultConstructor.
6558 ///
6559 /// FIXME: Check that case is properly handled by all callers.
6560 Sema::DefaultedFunctionKind
6561 Sema::getDefaultedFunctionKind(const FunctionDecl *FD) {
6562   if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6563     if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
6564       if (Ctor->isDefaultConstructor())
6565         return Sema::CXXDefaultConstructor;
6566 
6567       if (Ctor->isCopyConstructor())
6568         return Sema::CXXCopyConstructor;
6569 
6570       if (Ctor->isMoveConstructor())
6571         return Sema::CXXMoveConstructor;
6572     }
6573 
6574     if (MD->isCopyAssignmentOperator())
6575       return Sema::CXXCopyAssignment;
6576 
6577     if (MD->isMoveAssignmentOperator())
6578       return Sema::CXXMoveAssignment;
6579 
6580     if (isa<CXXDestructorDecl>(FD))
6581       return Sema::CXXDestructor;
6582   }
6583 
6584   switch (FD->getDeclName().getCXXOverloadedOperator()) {
6585   case OO_EqualEqual:
6586     return DefaultedComparisonKind::Equal;
6587 
6588   case OO_ExclaimEqual:
6589     return DefaultedComparisonKind::NotEqual;
6590 
6591   case OO_Spaceship:
6592     // No point allowing this if <=> doesn't exist in the current language mode.
6593     if (!getLangOpts().CPlusPlus20)
6594       break;
6595     return DefaultedComparisonKind::ThreeWay;
6596 
6597   case OO_Less:
6598   case OO_LessEqual:
6599   case OO_Greater:
6600   case OO_GreaterEqual:
6601     // No point allowing this if <=> doesn't exist in the current language mode.
6602     if (!getLangOpts().CPlusPlus20)
6603       break;
6604     return DefaultedComparisonKind::Relational;
6605 
6606   default:
6607     break;
6608   }
6609 
6610   // Not defaultable.
6611   return DefaultedFunctionKind();
6612 }
6613 
6614 static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,
6615                                     SourceLocation DefaultLoc) {
6616   Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD);
6617   if (DFK.isComparison())
6618     return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6619 
6620   switch (DFK.asSpecialMember()) {
6621   case Sema::CXXDefaultConstructor:
6622     S.DefineImplicitDefaultConstructor(DefaultLoc,
6623                                        cast<CXXConstructorDecl>(FD));
6624     break;
6625   case Sema::CXXCopyConstructor:
6626     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6627     break;
6628   case Sema::CXXCopyAssignment:
6629     S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6630     break;
6631   case Sema::CXXDestructor:
6632     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD));
6633     break;
6634   case Sema::CXXMoveConstructor:
6635     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6636     break;
6637   case Sema::CXXMoveAssignment:
6638     S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6639     break;
6640   case Sema::CXXInvalid:
6641     llvm_unreachable("Invalid special member.");
6642   }
6643 }
6644 
6645 /// Determine whether a type is permitted to be passed or returned in
6646 /// registers, per C++ [class.temporary]p3.
6647 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6648                                TargetInfo::CallingConvKind CCK) {
6649   if (D->isDependentType() || D->isInvalidDecl())
6650     return false;
6651 
6652   // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6653   // The PS4 platform ABI follows the behavior of Clang 3.2.
6654   if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6655     return !D->hasNonTrivialDestructorForCall() &&
6656            !D->hasNonTrivialCopyConstructorForCall();
6657 
6658   if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6659     bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6660     bool DtorIsTrivialForCall = false;
6661 
6662     // If a class has at least one eligible, trivial copy constructor, it
6663     // is passed according to the C ABI. Otherwise, it is passed indirectly.
6664     //
6665     // Note: This permits classes with non-trivial copy or move ctors to be
6666     // passed in registers, so long as they *also* have a trivial copy ctor,
6667     // which is non-conforming.
6668     if (D->needsImplicitCopyConstructor()) {
6669       if (!D->defaultedCopyConstructorIsDeleted()) {
6670         if (D->hasTrivialCopyConstructor())
6671           CopyCtorIsTrivial = true;
6672         if (D->hasTrivialCopyConstructorForCall())
6673           CopyCtorIsTrivialForCall = true;
6674       }
6675     } else {
6676       for (const CXXConstructorDecl *CD : D->ctors()) {
6677         if (CD->isCopyConstructor() && !CD->isDeleted() &&
6678             !CD->isIneligibleOrNotSelected()) {
6679           if (CD->isTrivial())
6680             CopyCtorIsTrivial = true;
6681           if (CD->isTrivialForCall())
6682             CopyCtorIsTrivialForCall = true;
6683         }
6684       }
6685     }
6686 
6687     if (D->needsImplicitDestructor()) {
6688       if (!D->defaultedDestructorIsDeleted() &&
6689           D->hasTrivialDestructorForCall())
6690         DtorIsTrivialForCall = true;
6691     } else if (const auto *DD = D->getDestructor()) {
6692       if (!DD->isDeleted() && DD->isTrivialForCall())
6693         DtorIsTrivialForCall = true;
6694     }
6695 
6696     // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6697     if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6698       return true;
6699 
6700     // If a class has a destructor, we'd really like to pass it indirectly
6701     // because it allows us to elide copies.  Unfortunately, MSVC makes that
6702     // impossible for small types, which it will pass in a single register or
6703     // stack slot. Most objects with dtors are large-ish, so handle that early.
6704     // We can't call out all large objects as being indirect because there are
6705     // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6706     // how we pass large POD types.
6707 
6708     // Note: This permits small classes with nontrivial destructors to be
6709     // passed in registers, which is non-conforming.
6710     bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6711     uint64_t TypeSize = isAArch64 ? 128 : 64;
6712 
6713     if (CopyCtorIsTrivial &&
6714         S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6715       return true;
6716     return false;
6717   }
6718 
6719   // Per C++ [class.temporary]p3, the relevant condition is:
6720   //   each copy constructor, move constructor, and destructor of X is
6721   //   either trivial or deleted, and X has at least one non-deleted copy
6722   //   or move constructor
6723   bool HasNonDeletedCopyOrMove = false;
6724 
6725   if (D->needsImplicitCopyConstructor() &&
6726       !D->defaultedCopyConstructorIsDeleted()) {
6727     if (!D->hasTrivialCopyConstructorForCall())
6728       return false;
6729     HasNonDeletedCopyOrMove = true;
6730   }
6731 
6732   if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6733       !D->defaultedMoveConstructorIsDeleted()) {
6734     if (!D->hasTrivialMoveConstructorForCall())
6735       return false;
6736     HasNonDeletedCopyOrMove = true;
6737   }
6738 
6739   if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6740       !D->hasTrivialDestructorForCall())
6741     return false;
6742 
6743   for (const CXXMethodDecl *MD : D->methods()) {
6744     if (MD->isDeleted() || MD->isIneligibleOrNotSelected())
6745       continue;
6746 
6747     auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6748     if (CD && CD->isCopyOrMoveConstructor())
6749       HasNonDeletedCopyOrMove = true;
6750     else if (!isa<CXXDestructorDecl>(MD))
6751       continue;
6752 
6753     if (!MD->isTrivialForCall())
6754       return false;
6755   }
6756 
6757   return HasNonDeletedCopyOrMove;
6758 }
6759 
6760 /// Report an error regarding overriding, along with any relevant
6761 /// overridden methods.
6762 ///
6763 /// \param DiagID the primary error to report.
6764 /// \param MD the overriding method.
6765 static bool
6766 ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
6767                 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
6768   bool IssuedDiagnostic = false;
6769   for (const CXXMethodDecl *O : MD->overridden_methods()) {
6770     if (Report(O)) {
6771       if (!IssuedDiagnostic) {
6772         S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6773         IssuedDiagnostic = true;
6774       }
6775       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
6776     }
6777   }
6778   return IssuedDiagnostic;
6779 }
6780 
6781 /// Perform semantic checks on a class definition that has been
6782 /// completing, introducing implicitly-declared members, checking for
6783 /// abstract types, etc.
6784 ///
6785 /// \param S The scope in which the class was parsed. Null if we didn't just
6786 ///        parse a class definition.
6787 /// \param Record The completed class.
6788 void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
6789   if (!Record)
6790     return;
6791 
6792   if (Record->isAbstract() && !Record->isInvalidDecl()) {
6793     AbstractUsageInfo Info(*this, Record);
6794     CheckAbstractClassUsage(Info, Record);
6795   }
6796 
6797   // If this is not an aggregate type and has no user-declared constructor,
6798   // complain about any non-static data members of reference or const scalar
6799   // type, since they will never get initializers.
6800   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6801       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6802       !Record->isLambda()) {
6803     bool Complained = false;
6804     for (const auto *F : Record->fields()) {
6805       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6806         continue;
6807 
6808       if (F->getType()->isReferenceType() ||
6809           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6810         if (!Complained) {
6811           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6812             << Record->getTagKind() << Record;
6813           Complained = true;
6814         }
6815 
6816         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6817           << F->getType()->isReferenceType()
6818           << F->getDeclName();
6819       }
6820     }
6821   }
6822 
6823   if (Record->getIdentifier()) {
6824     // C++ [class.mem]p13:
6825     //   If T is the name of a class, then each of the following shall have a
6826     //   name different from T:
6827     //     - every member of every anonymous union that is a member of class T.
6828     //
6829     // C++ [class.mem]p14:
6830     //   In addition, if class T has a user-declared constructor (12.1), every
6831     //   non-static data member of class T shall have a name different from T.
6832     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6833     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6834          ++I) {
6835       NamedDecl *D = (*I)->getUnderlyingDecl();
6836       if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6837            Record->hasUserDeclaredConstructor()) ||
6838           isa<IndirectFieldDecl>(D)) {
6839         Diag((*I)->getLocation(), diag::err_member_name_of_class)
6840           << D->getDeclName();
6841         break;
6842       }
6843     }
6844   }
6845 
6846   // Warn if the class has virtual methods but non-virtual public destructor.
6847   if (Record->isPolymorphic() && !Record->isDependentType()) {
6848     CXXDestructorDecl *dtor = Record->getDestructor();
6849     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6850         !Record->hasAttr<FinalAttr>())
6851       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6852            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6853   }
6854 
6855   if (Record->isAbstract()) {
6856     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6857       Diag(Record->getLocation(), diag::warn_abstract_final_class)
6858         << FA->isSpelledAsSealed();
6859       DiagnoseAbstractType(Record);
6860     }
6861   }
6862 
6863   // Warn if the class has a final destructor but is not itself marked final.
6864   if (!Record->hasAttr<FinalAttr>()) {
6865     if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
6866       if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
6867         Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
6868             << FA->isSpelledAsSealed()
6869             << FixItHint::CreateInsertion(
6870                    getLocForEndOfToken(Record->getLocation()),
6871                    (FA->isSpelledAsSealed() ? " sealed" : " final"));
6872         Diag(Record->getLocation(),
6873              diag::note_final_dtor_non_final_class_silence)
6874             << Context.getRecordType(Record) << FA->isSpelledAsSealed();
6875       }
6876     }
6877   }
6878 
6879   // See if trivial_abi has to be dropped.
6880   if (Record->hasAttr<TrivialABIAttr>())
6881     checkIllFormedTrivialABIStruct(*Record);
6882 
6883   // Set HasTrivialSpecialMemberForCall if the record has attribute
6884   // "trivial_abi".
6885   bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6886 
6887   if (HasTrivialABI)
6888     Record->setHasTrivialSpecialMemberForCall();
6889 
6890   // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
6891   // We check these last because they can depend on the properties of the
6892   // primary comparison functions (==, <=>).
6893   llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
6894 
6895   // Perform checks that can't be done until we know all the properties of a
6896   // member function (whether it's defaulted, deleted, virtual, overriding,
6897   // ...).
6898   auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
6899     // A static function cannot override anything.
6900     if (MD->getStorageClass() == SC_Static) {
6901       if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
6902                           [](const CXXMethodDecl *) { return true; }))
6903         return;
6904     }
6905 
6906     // A deleted function cannot override a non-deleted function and vice
6907     // versa.
6908     if (ReportOverrides(*this,
6909                         MD->isDeleted() ? diag::err_deleted_override
6910                                         : diag::err_non_deleted_override,
6911                         MD, [&](const CXXMethodDecl *V) {
6912                           return MD->isDeleted() != V->isDeleted();
6913                         })) {
6914       if (MD->isDefaulted() && MD->isDeleted())
6915         // Explain why this defaulted function was deleted.
6916         DiagnoseDeletedDefaultedFunction(MD);
6917       return;
6918     }
6919 
6920     // A consteval function cannot override a non-consteval function and vice
6921     // versa.
6922     if (ReportOverrides(*this,
6923                         MD->isConsteval() ? diag::err_consteval_override
6924                                           : diag::err_non_consteval_override,
6925                         MD, [&](const CXXMethodDecl *V) {
6926                           return MD->isConsteval() != V->isConsteval();
6927                         })) {
6928       if (MD->isDefaulted() && MD->isDeleted())
6929         // Explain why this defaulted function was deleted.
6930         DiagnoseDeletedDefaultedFunction(MD);
6931       return;
6932     }
6933   };
6934 
6935   auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
6936     if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
6937       return false;
6938 
6939     DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
6940     if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||
6941         DFK.asComparison() == DefaultedComparisonKind::Relational) {
6942       DefaultedSecondaryComparisons.push_back(FD);
6943       return true;
6944     }
6945 
6946     CheckExplicitlyDefaultedFunction(S, FD);
6947     return false;
6948   };
6949 
6950   auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
6951     // Check whether the explicitly-defaulted members are valid.
6952     bool Incomplete = CheckForDefaultedFunction(M);
6953 
6954     // Skip the rest of the checks for a member of a dependent class.
6955     if (Record->isDependentType())
6956       return;
6957 
6958     // For an explicitly defaulted or deleted special member, we defer
6959     // determining triviality until the class is complete. That time is now!
6960     CXXSpecialMember CSM = getSpecialMember(M);
6961     if (!M->isImplicit() && !M->isUserProvided()) {
6962       if (CSM != CXXInvalid) {
6963         M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6964         // Inform the class that we've finished declaring this member.
6965         Record->finishedDefaultedOrDeletedMember(M);
6966         M->setTrivialForCall(
6967             HasTrivialABI ||
6968             SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6969         Record->setTrivialForCallFlags(M);
6970       }
6971     }
6972 
6973     // Set triviality for the purpose of calls if this is a user-provided
6974     // copy/move constructor or destructor.
6975     if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6976          CSM == CXXDestructor) && M->isUserProvided()) {
6977       M->setTrivialForCall(HasTrivialABI);
6978       Record->setTrivialForCallFlags(M);
6979     }
6980 
6981     if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6982         M->hasAttr<DLLExportAttr>()) {
6983       if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6984           M->isTrivial() &&
6985           (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6986            CSM == CXXDestructor))
6987         M->dropAttr<DLLExportAttr>();
6988 
6989       if (M->hasAttr<DLLExportAttr>()) {
6990         // Define after any fields with in-class initializers have been parsed.
6991         DelayedDllExportMemberFunctions.push_back(M);
6992       }
6993     }
6994 
6995     // Define defaulted constexpr virtual functions that override a base class
6996     // function right away.
6997     // FIXME: We can defer doing this until the vtable is marked as used.
6998     if (CSM != CXXInvalid && !M->isDeleted() && M->isDefaulted() &&
6999         M->isConstexpr() && M->size_overridden_methods())
7000       DefineDefaultedFunction(*this, M, M->getLocation());
7001 
7002     if (!Incomplete)
7003       CheckCompletedMemberFunction(M);
7004   };
7005 
7006   // Check the destructor before any other member function. We need to
7007   // determine whether it's trivial in order to determine whether the claas
7008   // type is a literal type, which is a prerequisite for determining whether
7009   // other special member functions are valid and whether they're implicitly
7010   // 'constexpr'.
7011   if (CXXDestructorDecl *Dtor = Record->getDestructor())
7012     CompleteMemberFunction(Dtor);
7013 
7014   bool HasMethodWithOverrideControl = false,
7015        HasOverridingMethodWithoutOverrideControl = false;
7016   for (auto *D : Record->decls()) {
7017     if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
7018       // FIXME: We could do this check for dependent types with non-dependent
7019       // bases.
7020       if (!Record->isDependentType()) {
7021         // See if a method overloads virtual methods in a base
7022         // class without overriding any.
7023         if (!M->isStatic())
7024           DiagnoseHiddenVirtualMethods(M);
7025         if (M->hasAttr<OverrideAttr>())
7026           HasMethodWithOverrideControl = true;
7027         else if (M->size_overridden_methods() > 0)
7028           HasOverridingMethodWithoutOverrideControl = true;
7029       }
7030 
7031       if (!isa<CXXDestructorDecl>(M))
7032         CompleteMemberFunction(M);
7033     } else if (auto *F = dyn_cast<FriendDecl>(D)) {
7034       CheckForDefaultedFunction(
7035           dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
7036     }
7037   }
7038 
7039   if (HasOverridingMethodWithoutOverrideControl) {
7040     bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
7041     for (auto *M : Record->methods())
7042       DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
7043   }
7044 
7045   // Check the defaulted secondary comparisons after any other member functions.
7046   for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
7047     CheckExplicitlyDefaultedFunction(S, FD);
7048 
7049     // If this is a member function, we deferred checking it until now.
7050     if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
7051       CheckCompletedMemberFunction(MD);
7052   }
7053 
7054   // ms_struct is a request to use the same ABI rules as MSVC.  Check
7055   // whether this class uses any C++ features that are implemented
7056   // completely differently in MSVC, and if so, emit a diagnostic.
7057   // That diagnostic defaults to an error, but we allow projects to
7058   // map it down to a warning (or ignore it).  It's a fairly common
7059   // practice among users of the ms_struct pragma to mass-annotate
7060   // headers, sweeping up a bunch of types that the project doesn't
7061   // really rely on MSVC-compatible layout for.  We must therefore
7062   // support "ms_struct except for C++ stuff" as a secondary ABI.
7063   // Don't emit this diagnostic if the feature was enabled as a
7064   // language option (as opposed to via a pragma or attribute), as
7065   // the option -mms-bitfields otherwise essentially makes it impossible
7066   // to build C++ code, unless this diagnostic is turned off.
7067   if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields &&
7068       (Record->isPolymorphic() || Record->getNumBases())) {
7069     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
7070   }
7071 
7072   checkClassLevelDLLAttribute(Record);
7073   checkClassLevelCodeSegAttribute(Record);
7074 
7075   bool ClangABICompat4 =
7076       Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
7077   TargetInfo::CallingConvKind CCK =
7078       Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
7079   bool CanPass = canPassInRegisters(*this, Record, CCK);
7080 
7081   // Do not change ArgPassingRestrictions if it has already been set to
7082   // APK_CanNeverPassInRegs.
7083   if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
7084     Record->setArgPassingRestrictions(CanPass
7085                                           ? RecordDecl::APK_CanPassInRegs
7086                                           : RecordDecl::APK_CannotPassInRegs);
7087 
7088   // If canPassInRegisters returns true despite the record having a non-trivial
7089   // destructor, the record is destructed in the callee. This happens only when
7090   // the record or one of its subobjects has a field annotated with trivial_abi
7091   // or a field qualified with ObjC __strong/__weak.
7092   if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
7093     Record->setParamDestroyedInCallee(true);
7094   else if (Record->hasNonTrivialDestructor())
7095     Record->setParamDestroyedInCallee(CanPass);
7096 
7097   if (getLangOpts().ForceEmitVTables) {
7098     // If we want to emit all the vtables, we need to mark it as used.  This
7099     // is especially required for cases like vtable assumption loads.
7100     MarkVTableUsed(Record->getInnerLocStart(), Record);
7101   }
7102 
7103   if (getLangOpts().CUDA) {
7104     if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
7105       checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record);
7106     else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
7107       checkCUDADeviceBuiltinTextureClassTemplate(*this, Record);
7108   }
7109 }
7110 
7111 /// Look up the special member function that would be called by a special
7112 /// member function for a subobject of class type.
7113 ///
7114 /// \param Class The class type of the subobject.
7115 /// \param CSM The kind of special member function.
7116 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
7117 /// \param ConstRHS True if this is a copy operation with a const object
7118 ///        on its RHS, that is, if the argument to the outer special member
7119 ///        function is 'const' and this is not a field marked 'mutable'.
7120 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
7121     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
7122     unsigned FieldQuals, bool ConstRHS) {
7123   unsigned LHSQuals = 0;
7124   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
7125     LHSQuals = FieldQuals;
7126 
7127   unsigned RHSQuals = FieldQuals;
7128   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
7129     RHSQuals = 0;
7130   else if (ConstRHS)
7131     RHSQuals |= Qualifiers::Const;
7132 
7133   return S.LookupSpecialMember(Class, CSM,
7134                                RHSQuals & Qualifiers::Const,
7135                                RHSQuals & Qualifiers::Volatile,
7136                                false,
7137                                LHSQuals & Qualifiers::Const,
7138                                LHSQuals & Qualifiers::Volatile);
7139 }
7140 
7141 class Sema::InheritedConstructorInfo {
7142   Sema &S;
7143   SourceLocation UseLoc;
7144 
7145   /// A mapping from the base classes through which the constructor was
7146   /// inherited to the using shadow declaration in that base class (or a null
7147   /// pointer if the constructor was declared in that base class).
7148   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
7149       InheritedFromBases;
7150 
7151 public:
7152   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
7153                            ConstructorUsingShadowDecl *Shadow)
7154       : S(S), UseLoc(UseLoc) {
7155     bool DiagnosedMultipleConstructedBases = false;
7156     CXXRecordDecl *ConstructedBase = nullptr;
7157     BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
7158 
7159     // Find the set of such base class subobjects and check that there's a
7160     // unique constructed subobject.
7161     for (auto *D : Shadow->redecls()) {
7162       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
7163       auto *DNominatedBase = DShadow->getNominatedBaseClass();
7164       auto *DConstructedBase = DShadow->getConstructedBaseClass();
7165 
7166       InheritedFromBases.insert(
7167           std::make_pair(DNominatedBase->getCanonicalDecl(),
7168                          DShadow->getNominatedBaseClassShadowDecl()));
7169       if (DShadow->constructsVirtualBase())
7170         InheritedFromBases.insert(
7171             std::make_pair(DConstructedBase->getCanonicalDecl(),
7172                            DShadow->getConstructedBaseClassShadowDecl()));
7173       else
7174         assert(DNominatedBase == DConstructedBase);
7175 
7176       // [class.inhctor.init]p2:
7177       //   If the constructor was inherited from multiple base class subobjects
7178       //   of type B, the program is ill-formed.
7179       if (!ConstructedBase) {
7180         ConstructedBase = DConstructedBase;
7181         ConstructedBaseIntroducer = D->getIntroducer();
7182       } else if (ConstructedBase != DConstructedBase &&
7183                  !Shadow->isInvalidDecl()) {
7184         if (!DiagnosedMultipleConstructedBases) {
7185           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
7186               << Shadow->getTargetDecl();
7187           S.Diag(ConstructedBaseIntroducer->getLocation(),
7188                  diag::note_ambiguous_inherited_constructor_using)
7189               << ConstructedBase;
7190           DiagnosedMultipleConstructedBases = true;
7191         }
7192         S.Diag(D->getIntroducer()->getLocation(),
7193                diag::note_ambiguous_inherited_constructor_using)
7194             << DConstructedBase;
7195       }
7196     }
7197 
7198     if (DiagnosedMultipleConstructedBases)
7199       Shadow->setInvalidDecl();
7200   }
7201 
7202   /// Find the constructor to use for inherited construction of a base class,
7203   /// and whether that base class constructor inherits the constructor from a
7204   /// virtual base class (in which case it won't actually invoke it).
7205   std::pair<CXXConstructorDecl *, bool>
7206   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
7207     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
7208     if (It == InheritedFromBases.end())
7209       return std::make_pair(nullptr, false);
7210 
7211     // This is an intermediary class.
7212     if (It->second)
7213       return std::make_pair(
7214           S.findInheritingConstructor(UseLoc, Ctor, It->second),
7215           It->second->constructsVirtualBase());
7216 
7217     // This is the base class from which the constructor was inherited.
7218     return std::make_pair(Ctor, false);
7219   }
7220 };
7221 
7222 /// Is the special member function which would be selected to perform the
7223 /// specified operation on the specified class type a constexpr constructor?
7224 static bool
7225 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
7226                          Sema::CXXSpecialMember CSM, unsigned Quals,
7227                          bool ConstRHS,
7228                          CXXConstructorDecl *InheritedCtor = nullptr,
7229                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
7230   // Suppress duplicate constraint checking here, in case a constraint check
7231   // caused us to decide to do this.  Any truely recursive checks will get
7232   // caught during these checks anyway.
7233   Sema::SatisfactionStackResetRAII SSRAII{S};
7234 
7235   // If we're inheriting a constructor, see if we need to call it for this base
7236   // class.
7237   if (InheritedCtor) {
7238     assert(CSM == Sema::CXXDefaultConstructor);
7239     auto BaseCtor =
7240         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
7241     if (BaseCtor)
7242       return BaseCtor->isConstexpr();
7243   }
7244 
7245   if (CSM == Sema::CXXDefaultConstructor)
7246     return ClassDecl->hasConstexprDefaultConstructor();
7247   if (CSM == Sema::CXXDestructor)
7248     return ClassDecl->hasConstexprDestructor();
7249 
7250   Sema::SpecialMemberOverloadResult SMOR =
7251       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
7252   if (!SMOR.getMethod())
7253     // A constructor we wouldn't select can't be "involved in initializing"
7254     // anything.
7255     return true;
7256   return SMOR.getMethod()->isConstexpr();
7257 }
7258 
7259 /// Determine whether the specified special member function would be constexpr
7260 /// if it were implicitly defined.
7261 static bool defaultedSpecialMemberIsConstexpr(
7262     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
7263     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
7264     Sema::InheritedConstructorInfo *Inherited = nullptr) {
7265   if (!S.getLangOpts().CPlusPlus11)
7266     return false;
7267 
7268   // C++11 [dcl.constexpr]p4:
7269   // In the definition of a constexpr constructor [...]
7270   bool Ctor = true;
7271   switch (CSM) {
7272   case Sema::CXXDefaultConstructor:
7273     if (Inherited)
7274       break;
7275     // Since default constructor lookup is essentially trivial (and cannot
7276     // involve, for instance, template instantiation), we compute whether a
7277     // defaulted default constructor is constexpr directly within CXXRecordDecl.
7278     //
7279     // This is important for performance; we need to know whether the default
7280     // constructor is constexpr to determine whether the type is a literal type.
7281     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7282 
7283   case Sema::CXXCopyConstructor:
7284   case Sema::CXXMoveConstructor:
7285     // For copy or move constructors, we need to perform overload resolution.
7286     break;
7287 
7288   case Sema::CXXCopyAssignment:
7289   case Sema::CXXMoveAssignment:
7290     if (!S.getLangOpts().CPlusPlus14)
7291       return false;
7292     // In C++1y, we need to perform overload resolution.
7293     Ctor = false;
7294     break;
7295 
7296   case Sema::CXXDestructor:
7297     return ClassDecl->defaultedDestructorIsConstexpr();
7298 
7299   case Sema::CXXInvalid:
7300     return false;
7301   }
7302 
7303   //   -- if the class is a non-empty union, or for each non-empty anonymous
7304   //      union member of a non-union class, exactly one non-static data member
7305   //      shall be initialized; [DR1359]
7306   //
7307   // If we squint, this is guaranteed, since exactly one non-static data member
7308   // will be initialized (if the constructor isn't deleted), we just don't know
7309   // which one.
7310   if (Ctor && ClassDecl->isUnion())
7311     return CSM == Sema::CXXDefaultConstructor
7312                ? ClassDecl->hasInClassInitializer() ||
7313                      !ClassDecl->hasVariantMembers()
7314                : true;
7315 
7316   //   -- the class shall not have any virtual base classes;
7317   if (Ctor && ClassDecl->getNumVBases())
7318     return false;
7319 
7320   // C++1y [class.copy]p26:
7321   //   -- [the class] is a literal type, and
7322   if (!Ctor && !ClassDecl->isLiteral())
7323     return false;
7324 
7325   //   -- every constructor involved in initializing [...] base class
7326   //      sub-objects shall be a constexpr constructor;
7327   //   -- the assignment operator selected to copy/move each direct base
7328   //      class is a constexpr function, and
7329   for (const auto &B : ClassDecl->bases()) {
7330     const RecordType *BaseType = B.getType()->getAs<RecordType>();
7331     if (!BaseType)
7332       continue;
7333     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7334     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7335                                   InheritedCtor, Inherited))
7336       return false;
7337   }
7338 
7339   //   -- every constructor involved in initializing non-static data members
7340   //      [...] shall be a constexpr constructor;
7341   //   -- every non-static data member and base class sub-object shall be
7342   //      initialized
7343   //   -- for each non-static data member of X that is of class type (or array
7344   //      thereof), the assignment operator selected to copy/move that member is
7345   //      a constexpr function
7346   for (const auto *F : ClassDecl->fields()) {
7347     if (F->isInvalidDecl())
7348       continue;
7349     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
7350       continue;
7351     QualType BaseType = S.Context.getBaseElementType(F->getType());
7352     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
7353       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7354       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7355                                     BaseType.getCVRQualifiers(),
7356                                     ConstArg && !F->isMutable()))
7357         return false;
7358     } else if (CSM == Sema::CXXDefaultConstructor) {
7359       return false;
7360     }
7361   }
7362 
7363   // All OK, it's constexpr!
7364   return true;
7365 }
7366 
7367 namespace {
7368 /// RAII object to register a defaulted function as having its exception
7369 /// specification computed.
7370 struct ComputingExceptionSpec {
7371   Sema &S;
7372 
7373   ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7374       : S(S) {
7375     Sema::CodeSynthesisContext Ctx;
7376     Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
7377     Ctx.PointOfInstantiation = Loc;
7378     Ctx.Entity = FD;
7379     S.pushCodeSynthesisContext(Ctx);
7380   }
7381   ~ComputingExceptionSpec() {
7382     S.popCodeSynthesisContext();
7383   }
7384 };
7385 }
7386 
7387 static Sema::ImplicitExceptionSpecification
7388 ComputeDefaultedSpecialMemberExceptionSpec(
7389     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
7390     Sema::InheritedConstructorInfo *ICI);
7391 
7392 static Sema::ImplicitExceptionSpecification
7393 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7394                                         FunctionDecl *FD,
7395                                         Sema::DefaultedComparisonKind DCK);
7396 
7397 static Sema::ImplicitExceptionSpecification
7398 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {
7399   auto DFK = S.getDefaultedFunctionKind(FD);
7400   if (DFK.isSpecialMember())
7401     return ComputeDefaultedSpecialMemberExceptionSpec(
7402         S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7403   if (DFK.isComparison())
7404     return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
7405                                                    DFK.asComparison());
7406 
7407   auto *CD = cast<CXXConstructorDecl>(FD);
7408   assert(CD->getInheritedConstructor() &&
7409          "only defaulted functions and inherited constructors have implicit "
7410          "exception specs");
7411   Sema::InheritedConstructorInfo ICI(
7412       S, Loc, CD->getInheritedConstructor().getShadowDecl());
7413   return ComputeDefaultedSpecialMemberExceptionSpec(
7414       S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
7415 }
7416 
7417 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
7418                                                             CXXMethodDecl *MD) {
7419   FunctionProtoType::ExtProtoInfo EPI;
7420 
7421   // Build an exception specification pointing back at this member.
7422   EPI.ExceptionSpec.Type = EST_Unevaluated;
7423   EPI.ExceptionSpec.SourceDecl = MD;
7424 
7425   // Set the calling convention to the default for C++ instance methods.
7426   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
7427       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7428                                             /*IsCXXMethod=*/true));
7429   return EPI;
7430 }
7431 
7432 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {
7433   const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7434   if (FPT->getExceptionSpecType() != EST_Unevaluated)
7435     return;
7436 
7437   // Evaluate the exception specification.
7438   auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7439   auto ESI = IES.getExceptionSpec();
7440 
7441   // Update the type of the special member to use it.
7442   UpdateExceptionSpec(FD, ESI);
7443 }
7444 
7445 void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
7446   assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7447 
7448   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
7449   if (!DefKind) {
7450     assert(FD->getDeclContext()->isDependentContext());
7451     return;
7452   }
7453 
7454   if (DefKind.isComparison())
7455     UnusedPrivateFields.clear();
7456 
7457   if (DefKind.isSpecialMember()
7458           ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
7459                                                   DefKind.asSpecialMember(),
7460                                                   FD->getDefaultLoc())
7461           : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison()))
7462     FD->setInvalidDecl();
7463 }
7464 
7465 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7466                                                  CXXSpecialMember CSM,
7467                                                  SourceLocation DefaultLoc) {
7468   CXXRecordDecl *RD = MD->getParent();
7469 
7470   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
7471          "not an explicitly-defaulted special member");
7472 
7473   // Defer all checking for special members of a dependent type.
7474   if (RD->isDependentType())
7475     return false;
7476 
7477   // Whether this was the first-declared instance of the constructor.
7478   // This affects whether we implicitly add an exception spec and constexpr.
7479   bool First = MD == MD->getCanonicalDecl();
7480 
7481   bool HadError = false;
7482 
7483   // C++11 [dcl.fct.def.default]p1:
7484   //   A function that is explicitly defaulted shall
7485   //     -- be a special member function [...] (checked elsewhere),
7486   //     -- have the same type (except for ref-qualifiers, and except that a
7487   //        copy operation can take a non-const reference) as an implicit
7488   //        declaration, and
7489   //     -- not have default arguments.
7490   // C++2a changes the second bullet to instead delete the function if it's
7491   // defaulted on its first declaration, unless it's "an assignment operator,
7492   // and its return type differs or its parameter type is not a reference".
7493   bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7494   bool ShouldDeleteForTypeMismatch = false;
7495   unsigned ExpectedParams = 1;
7496   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
7497     ExpectedParams = 0;
7498   if (MD->getNumParams() != ExpectedParams) {
7499     // This checks for default arguments: a copy or move constructor with a
7500     // default argument is classified as a default constructor, and assignment
7501     // operations and destructors can't have default arguments.
7502     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7503       << CSM << MD->getSourceRange();
7504     HadError = true;
7505   } else if (MD->isVariadic()) {
7506     if (DeleteOnTypeMismatch)
7507       ShouldDeleteForTypeMismatch = true;
7508     else {
7509       Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7510         << CSM << MD->getSourceRange();
7511       HadError = true;
7512     }
7513   }
7514 
7515   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
7516 
7517   bool CanHaveConstParam = false;
7518   if (CSM == CXXCopyConstructor)
7519     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7520   else if (CSM == CXXCopyAssignment)
7521     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7522 
7523   QualType ReturnType = Context.VoidTy;
7524   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
7525     // Check for return type matching.
7526     ReturnType = Type->getReturnType();
7527 
7528     QualType DeclType = Context.getTypeDeclType(RD);
7529     DeclType = Context.getElaboratedType(ETK_None, nullptr, DeclType, nullptr);
7530     DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
7531     QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7532 
7533     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7534       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7535         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
7536       HadError = true;
7537     }
7538 
7539     // A defaulted special member cannot have cv-qualifiers.
7540     if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
7541       if (DeleteOnTypeMismatch)
7542         ShouldDeleteForTypeMismatch = true;
7543       else {
7544         Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7545           << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
7546         HadError = true;
7547       }
7548     }
7549   }
7550 
7551   // Check for parameter type matching.
7552   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
7553   bool HasConstParam = false;
7554   if (ExpectedParams && ArgType->isReferenceType()) {
7555     // Argument must be reference to possibly-const T.
7556     QualType ReferentType = ArgType->getPointeeType();
7557     HasConstParam = ReferentType.isConstQualified();
7558 
7559     if (ReferentType.isVolatileQualified()) {
7560       if (DeleteOnTypeMismatch)
7561         ShouldDeleteForTypeMismatch = true;
7562       else {
7563         Diag(MD->getLocation(),
7564              diag::err_defaulted_special_member_volatile_param) << CSM;
7565         HadError = true;
7566       }
7567     }
7568 
7569     if (HasConstParam && !CanHaveConstParam) {
7570       if (DeleteOnTypeMismatch)
7571         ShouldDeleteForTypeMismatch = true;
7572       else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
7573         Diag(MD->getLocation(),
7574              diag::err_defaulted_special_member_copy_const_param)
7575           << (CSM == CXXCopyAssignment);
7576         // FIXME: Explain why this special member can't be const.
7577         HadError = true;
7578       } else {
7579         Diag(MD->getLocation(),
7580              diag::err_defaulted_special_member_move_const_param)
7581           << (CSM == CXXMoveAssignment);
7582         HadError = true;
7583       }
7584     }
7585   } else if (ExpectedParams) {
7586     // A copy assignment operator can take its argument by value, but a
7587     // defaulted one cannot.
7588     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
7589     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
7590     HadError = true;
7591   }
7592 
7593   // C++11 [dcl.fct.def.default]p2:
7594   //   An explicitly-defaulted function may be declared constexpr only if it
7595   //   would have been implicitly declared as constexpr,
7596   // Do not apply this rule to members of class templates, since core issue 1358
7597   // makes such functions always instantiate to constexpr functions. For
7598   // functions which cannot be constexpr (for non-constructors in C++11 and for
7599   // destructors in C++14 and C++17), this is checked elsewhere.
7600   //
7601   // FIXME: This should not apply if the member is deleted.
7602   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
7603                                                      HasConstParam);
7604 
7605   // C++14 [dcl.constexpr]p6 (CWG DR647/CWG DR1358):
7606   //   If the instantiated template specialization of a constexpr function
7607   //   template or member function of a class template would fail to satisfy
7608   //   the requirements for a constexpr function or constexpr constructor, that
7609   //   specialization is still a constexpr function or constexpr constructor,
7610   //   even though a call to such a function cannot appear in a constant
7611   //   expression.
7612   if (MD->isTemplateInstantiation() && MD->isConstexpr())
7613     Constexpr = true;
7614 
7615   if ((getLangOpts().CPlusPlus20 ||
7616        (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
7617                                   : isa<CXXConstructorDecl>(MD))) &&
7618       MD->isConstexpr() && !Constexpr &&
7619       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
7620     Diag(MD->getBeginLoc(), MD->isConsteval()
7621                                 ? diag::err_incorrect_defaulted_consteval
7622                                 : diag::err_incorrect_defaulted_constexpr)
7623         << CSM;
7624     // FIXME: Explain why the special member can't be constexpr.
7625     HadError = true;
7626   }
7627 
7628   if (First) {
7629     // C++2a [dcl.fct.def.default]p3:
7630     //   If a function is explicitly defaulted on its first declaration, it is
7631     //   implicitly considered to be constexpr if the implicit declaration
7632     //   would be.
7633     MD->setConstexprKind(Constexpr ? (MD->isConsteval()
7634                                           ? ConstexprSpecKind::Consteval
7635                                           : ConstexprSpecKind::Constexpr)
7636                                    : ConstexprSpecKind::Unspecified);
7637 
7638     if (!Type->hasExceptionSpec()) {
7639       // C++2a [except.spec]p3:
7640       //   If a declaration of a function does not have a noexcept-specifier
7641       //   [and] is defaulted on its first declaration, [...] the exception
7642       //   specification is as specified below
7643       FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
7644       EPI.ExceptionSpec.Type = EST_Unevaluated;
7645       EPI.ExceptionSpec.SourceDecl = MD;
7646       MD->setType(Context.getFunctionType(
7647           ReturnType, llvm::ArrayRef(&ArgType, ExpectedParams), EPI));
7648     }
7649   }
7650 
7651   if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
7652     if (First) {
7653       SetDeclDeleted(MD, MD->getLocation());
7654       if (!inTemplateInstantiation() && !HadError) {
7655         Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
7656         if (ShouldDeleteForTypeMismatch) {
7657           Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
7658         } else if (ShouldDeleteSpecialMember(MD, CSM, nullptr,
7659                                              /*Diagnose*/ true) &&
7660                    DefaultLoc.isValid()) {
7661           Diag(DefaultLoc, diag::note_replace_equals_default_to_delete)
7662               << FixItHint::CreateReplacement(DefaultLoc, "delete");
7663         }
7664       }
7665       if (ShouldDeleteForTypeMismatch && !HadError) {
7666         Diag(MD->getLocation(),
7667              diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
7668       }
7669     } else {
7670       // C++11 [dcl.fct.def.default]p4:
7671       //   [For a] user-provided explicitly-defaulted function [...] if such a
7672       //   function is implicitly defined as deleted, the program is ill-formed.
7673       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
7674       assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
7675       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7676       HadError = true;
7677     }
7678   }
7679 
7680   return HadError;
7681 }
7682 
7683 namespace {
7684 /// Helper class for building and checking a defaulted comparison.
7685 ///
7686 /// Defaulted functions are built in two phases:
7687 ///
7688 ///  * First, the set of operations that the function will perform are
7689 ///    identified, and some of them are checked. If any of the checked
7690 ///    operations is invalid in certain ways, the comparison function is
7691 ///    defined as deleted and no body is built.
7692 ///  * Then, if the function is not defined as deleted, the body is built.
7693 ///
7694 /// This is accomplished by performing two visitation steps over the eventual
7695 /// body of the function.
7696 template<typename Derived, typename ResultList, typename Result,
7697          typename Subobject>
7698 class DefaultedComparisonVisitor {
7699 public:
7700   using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
7701 
7702   DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7703                              DefaultedComparisonKind DCK)
7704       : S(S), RD(RD), FD(FD), DCK(DCK) {
7705     if (auto *Info = FD->getDefaultedFunctionInfo()) {
7706       // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
7707       // UnresolvedSet to avoid this copy.
7708       Fns.assign(Info->getUnqualifiedLookups().begin(),
7709                  Info->getUnqualifiedLookups().end());
7710     }
7711   }
7712 
7713   ResultList visit() {
7714     // The type of an lvalue naming a parameter of this function.
7715     QualType ParamLvalType =
7716         FD->getParamDecl(0)->getType().getNonReferenceType();
7717 
7718     ResultList Results;
7719 
7720     switch (DCK) {
7721     case DefaultedComparisonKind::None:
7722       llvm_unreachable("not a defaulted comparison");
7723 
7724     case DefaultedComparisonKind::Equal:
7725     case DefaultedComparisonKind::ThreeWay:
7726       getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
7727       return Results;
7728 
7729     case DefaultedComparisonKind::NotEqual:
7730     case DefaultedComparisonKind::Relational:
7731       Results.add(getDerived().visitExpandedSubobject(
7732           ParamLvalType, getDerived().getCompleteObject()));
7733       return Results;
7734     }
7735     llvm_unreachable("");
7736   }
7737 
7738 protected:
7739   Derived &getDerived() { return static_cast<Derived&>(*this); }
7740 
7741   /// Visit the expanded list of subobjects of the given type, as specified in
7742   /// C++2a [class.compare.default].
7743   ///
7744   /// \return \c true if the ResultList object said we're done, \c false if not.
7745   bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
7746                        Qualifiers Quals) {
7747     // C++2a [class.compare.default]p4:
7748     //   The direct base class subobjects of C
7749     for (CXXBaseSpecifier &Base : Record->bases())
7750       if (Results.add(getDerived().visitSubobject(
7751               S.Context.getQualifiedType(Base.getType(), Quals),
7752               getDerived().getBase(&Base))))
7753         return true;
7754 
7755     //   followed by the non-static data members of C
7756     for (FieldDecl *Field : Record->fields()) {
7757       // Recursively expand anonymous structs.
7758       if (Field->isAnonymousStructOrUnion()) {
7759         if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
7760                             Quals))
7761           return true;
7762         continue;
7763       }
7764 
7765       // Figure out the type of an lvalue denoting this field.
7766       Qualifiers FieldQuals = Quals;
7767       if (Field->isMutable())
7768         FieldQuals.removeConst();
7769       QualType FieldType =
7770           S.Context.getQualifiedType(Field->getType(), FieldQuals);
7771 
7772       if (Results.add(getDerived().visitSubobject(
7773               FieldType, getDerived().getField(Field))))
7774         return true;
7775     }
7776 
7777     //   form a list of subobjects.
7778     return false;
7779   }
7780 
7781   Result visitSubobject(QualType Type, Subobject Subobj) {
7782     //   In that list, any subobject of array type is recursively expanded
7783     const ArrayType *AT = S.Context.getAsArrayType(Type);
7784     if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
7785       return getDerived().visitSubobjectArray(CAT->getElementType(),
7786                                               CAT->getSize(), Subobj);
7787     return getDerived().visitExpandedSubobject(Type, Subobj);
7788   }
7789 
7790   Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
7791                              Subobject Subobj) {
7792     return getDerived().visitSubobject(Type, Subobj);
7793   }
7794 
7795 protected:
7796   Sema &S;
7797   CXXRecordDecl *RD;
7798   FunctionDecl *FD;
7799   DefaultedComparisonKind DCK;
7800   UnresolvedSet<16> Fns;
7801 };
7802 
7803 /// Information about a defaulted comparison, as determined by
7804 /// DefaultedComparisonAnalyzer.
7805 struct DefaultedComparisonInfo {
7806   bool Deleted = false;
7807   bool Constexpr = true;
7808   ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
7809 
7810   static DefaultedComparisonInfo deleted() {
7811     DefaultedComparisonInfo Deleted;
7812     Deleted.Deleted = true;
7813     return Deleted;
7814   }
7815 
7816   bool add(const DefaultedComparisonInfo &R) {
7817     Deleted |= R.Deleted;
7818     Constexpr &= R.Constexpr;
7819     Category = commonComparisonType(Category, R.Category);
7820     return Deleted;
7821   }
7822 };
7823 
7824 /// An element in the expanded list of subobjects of a defaulted comparison, as
7825 /// specified in C++2a [class.compare.default]p4.
7826 struct DefaultedComparisonSubobject {
7827   enum { CompleteObject, Member, Base } Kind;
7828   NamedDecl *Decl;
7829   SourceLocation Loc;
7830 };
7831 
7832 /// A visitor over the notional body of a defaulted comparison that determines
7833 /// whether that body would be deleted or constexpr.
7834 class DefaultedComparisonAnalyzer
7835     : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
7836                                         DefaultedComparisonInfo,
7837                                         DefaultedComparisonInfo,
7838                                         DefaultedComparisonSubobject> {
7839 public:
7840   enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
7841 
7842 private:
7843   DiagnosticKind Diagnose;
7844 
7845 public:
7846   using Base = DefaultedComparisonVisitor;
7847   using Result = DefaultedComparisonInfo;
7848   using Subobject = DefaultedComparisonSubobject;
7849 
7850   friend Base;
7851 
7852   DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7853                               DefaultedComparisonKind DCK,
7854                               DiagnosticKind Diagnose = NoDiagnostics)
7855       : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
7856 
7857   Result visit() {
7858     if ((DCK == DefaultedComparisonKind::Equal ||
7859          DCK == DefaultedComparisonKind::ThreeWay) &&
7860         RD->hasVariantMembers()) {
7861       // C++2a [class.compare.default]p2 [P2002R0]:
7862       //   A defaulted comparison operator function for class C is defined as
7863       //   deleted if [...] C has variant members.
7864       if (Diagnose == ExplainDeleted) {
7865         S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
7866           << FD << RD->isUnion() << RD;
7867       }
7868       return Result::deleted();
7869     }
7870 
7871     return Base::visit();
7872   }
7873 
7874 private:
7875   Subobject getCompleteObject() {
7876     return Subobject{Subobject::CompleteObject, RD, FD->getLocation()};
7877   }
7878 
7879   Subobject getBase(CXXBaseSpecifier *Base) {
7880     return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
7881                      Base->getBaseTypeLoc()};
7882   }
7883 
7884   Subobject getField(FieldDecl *Field) {
7885     return Subobject{Subobject::Member, Field, Field->getLocation()};
7886   }
7887 
7888   Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
7889     // C++2a [class.compare.default]p2 [P2002R0]:
7890     //   A defaulted <=> or == operator function for class C is defined as
7891     //   deleted if any non-static data member of C is of reference type
7892     if (Type->isReferenceType()) {
7893       if (Diagnose == ExplainDeleted) {
7894         S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
7895             << FD << RD;
7896       }
7897       return Result::deleted();
7898     }
7899 
7900     // [...] Let xi be an lvalue denoting the ith element [...]
7901     OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
7902     Expr *Args[] = {&Xi, &Xi};
7903 
7904     // All operators start by trying to apply that same operator recursively.
7905     OverloadedOperatorKind OO = FD->getOverloadedOperator();
7906     assert(OO != OO_None && "not an overloaded operator!");
7907     return visitBinaryOperator(OO, Args, Subobj);
7908   }
7909 
7910   Result
7911   visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
7912                       Subobject Subobj,
7913                       OverloadCandidateSet *SpaceshipCandidates = nullptr) {
7914     // Note that there is no need to consider rewritten candidates here if
7915     // we've already found there is no viable 'operator<=>' candidate (and are
7916     // considering synthesizing a '<=>' from '==' and '<').
7917     OverloadCandidateSet CandidateSet(
7918         FD->getLocation(), OverloadCandidateSet::CSK_Operator,
7919         OverloadCandidateSet::OperatorRewriteInfo(
7920             OO, FD->getLocation(),
7921             /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
7922 
7923     /// C++2a [class.compare.default]p1 [P2002R0]:
7924     ///   [...] the defaulted function itself is never a candidate for overload
7925     ///   resolution [...]
7926     CandidateSet.exclude(FD);
7927 
7928     if (Args[0]->getType()->isOverloadableType())
7929       S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
7930     else
7931       // FIXME: We determine whether this is a valid expression by checking to
7932       // see if there's a viable builtin operator candidate for it. That isn't
7933       // really what the rules ask us to do, but should give the right results.
7934       S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
7935 
7936     Result R;
7937 
7938     OverloadCandidateSet::iterator Best;
7939     switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
7940     case OR_Success: {
7941       // C++2a [class.compare.secondary]p2 [P2002R0]:
7942       //   The operator function [...] is defined as deleted if [...] the
7943       //   candidate selected by overload resolution is not a rewritten
7944       //   candidate.
7945       if ((DCK == DefaultedComparisonKind::NotEqual ||
7946            DCK == DefaultedComparisonKind::Relational) &&
7947           !Best->RewriteKind) {
7948         if (Diagnose == ExplainDeleted) {
7949           if (Best->Function) {
7950             S.Diag(Best->Function->getLocation(),
7951                    diag::note_defaulted_comparison_not_rewritten_callee)
7952                 << FD;
7953           } else {
7954             assert(Best->Conversions.size() == 2 &&
7955                    Best->Conversions[0].isUserDefined() &&
7956                    "non-user-defined conversion from class to built-in "
7957                    "comparison");
7958             S.Diag(Best->Conversions[0]
7959                        .UserDefined.FoundConversionFunction.getDecl()
7960                        ->getLocation(),
7961                    diag::note_defaulted_comparison_not_rewritten_conversion)
7962                 << FD;
7963           }
7964         }
7965         return Result::deleted();
7966       }
7967 
7968       // Throughout C++2a [class.compare]: if overload resolution does not
7969       // result in a usable function, the candidate function is defined as
7970       // deleted. This requires that we selected an accessible function.
7971       //
7972       // Note that this only considers the access of the function when named
7973       // within the type of the subobject, and not the access path for any
7974       // derived-to-base conversion.
7975       CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
7976       if (ArgClass && Best->FoundDecl.getDecl() &&
7977           Best->FoundDecl.getDecl()->isCXXClassMember()) {
7978         QualType ObjectType = Subobj.Kind == Subobject::Member
7979                                   ? Args[0]->getType()
7980                                   : S.Context.getRecordType(RD);
7981         if (!S.isMemberAccessibleForDeletion(
7982                 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
7983                 Diagnose == ExplainDeleted
7984                     ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
7985                           << FD << Subobj.Kind << Subobj.Decl
7986                     : S.PDiag()))
7987           return Result::deleted();
7988       }
7989 
7990       bool NeedsDeducing =
7991           OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
7992 
7993       if (FunctionDecl *BestFD = Best->Function) {
7994         // C++2a [class.compare.default]p3 [P2002R0]:
7995         //   A defaulted comparison function is constexpr-compatible if
7996         //   [...] no overlod resolution performed [...] results in a
7997         //   non-constexpr function.
7998         assert(!BestFD->isDeleted() && "wrong overload resolution result");
7999         // If it's not constexpr, explain why not.
8000         if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
8001           if (Subobj.Kind != Subobject::CompleteObject)
8002             S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
8003               << Subobj.Kind << Subobj.Decl;
8004           S.Diag(BestFD->getLocation(),
8005                  diag::note_defaulted_comparison_not_constexpr_here);
8006           // Bail out after explaining; we don't want any more notes.
8007           return Result::deleted();
8008         }
8009         R.Constexpr &= BestFD->isConstexpr();
8010 
8011         if (NeedsDeducing) {
8012           // If any callee has an undeduced return type, deduce it now.
8013           // FIXME: It's not clear how a failure here should be handled. For
8014           // now, we produce an eager diagnostic, because that is forward
8015           // compatible with most (all?) other reasonable options.
8016           if (BestFD->getReturnType()->isUndeducedType() &&
8017               S.DeduceReturnType(BestFD, FD->getLocation(),
8018                                  /*Diagnose=*/false)) {
8019             // Don't produce a duplicate error when asked to explain why the
8020             // comparison is deleted: we diagnosed that when initially checking
8021             // the defaulted operator.
8022             if (Diagnose == NoDiagnostics) {
8023               S.Diag(
8024                   FD->getLocation(),
8025                   diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
8026                   << Subobj.Kind << Subobj.Decl;
8027               S.Diag(
8028                   Subobj.Loc,
8029                   diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
8030                   << Subobj.Kind << Subobj.Decl;
8031               S.Diag(BestFD->getLocation(),
8032                      diag::note_defaulted_comparison_cannot_deduce_callee)
8033                   << Subobj.Kind << Subobj.Decl;
8034             }
8035             return Result::deleted();
8036           }
8037           auto *Info = S.Context.CompCategories.lookupInfoForType(
8038               BestFD->getCallResultType());
8039           if (!Info) {
8040             if (Diagnose == ExplainDeleted) {
8041               S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
8042                   << Subobj.Kind << Subobj.Decl
8043                   << BestFD->getCallResultType().withoutLocalFastQualifiers();
8044               S.Diag(BestFD->getLocation(),
8045                      diag::note_defaulted_comparison_cannot_deduce_callee)
8046                   << Subobj.Kind << Subobj.Decl;
8047             }
8048             return Result::deleted();
8049           }
8050           R.Category = Info->Kind;
8051         }
8052       } else {
8053         QualType T = Best->BuiltinParamTypes[0];
8054         assert(T == Best->BuiltinParamTypes[1] &&
8055                "builtin comparison for different types?");
8056         assert(Best->BuiltinParamTypes[2].isNull() &&
8057                "invalid builtin comparison");
8058 
8059         if (NeedsDeducing) {
8060           std::optional<ComparisonCategoryType> Cat =
8061               getComparisonCategoryForBuiltinCmp(T);
8062           assert(Cat && "no category for builtin comparison?");
8063           R.Category = *Cat;
8064         }
8065       }
8066 
8067       // Note that we might be rewriting to a different operator. That call is
8068       // not considered until we come to actually build the comparison function.
8069       break;
8070     }
8071 
8072     case OR_Ambiguous:
8073       if (Diagnose == ExplainDeleted) {
8074         unsigned Kind = 0;
8075         if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
8076           Kind = OO == OO_EqualEqual ? 1 : 2;
8077         CandidateSet.NoteCandidates(
8078             PartialDiagnosticAt(
8079                 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
8080                                 << FD << Kind << Subobj.Kind << Subobj.Decl),
8081             S, OCD_AmbiguousCandidates, Args);
8082       }
8083       R = Result::deleted();
8084       break;
8085 
8086     case OR_Deleted:
8087       if (Diagnose == ExplainDeleted) {
8088         if ((DCK == DefaultedComparisonKind::NotEqual ||
8089              DCK == DefaultedComparisonKind::Relational) &&
8090             !Best->RewriteKind) {
8091           S.Diag(Best->Function->getLocation(),
8092                  diag::note_defaulted_comparison_not_rewritten_callee)
8093               << FD;
8094         } else {
8095           S.Diag(Subobj.Loc,
8096                  diag::note_defaulted_comparison_calls_deleted)
8097               << FD << Subobj.Kind << Subobj.Decl;
8098           S.NoteDeletedFunction(Best->Function);
8099         }
8100       }
8101       R = Result::deleted();
8102       break;
8103 
8104     case OR_No_Viable_Function:
8105       // If there's no usable candidate, we're done unless we can rewrite a
8106       // '<=>' in terms of '==' and '<'.
8107       if (OO == OO_Spaceship &&
8108           S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) {
8109         // For any kind of comparison category return type, we need a usable
8110         // '==' and a usable '<'.
8111         if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
8112                                        &CandidateSet)))
8113           R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
8114         break;
8115       }
8116 
8117       if (Diagnose == ExplainDeleted) {
8118         S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
8119             << FD << (OO == OO_ExclaimEqual) << Subobj.Kind << Subobj.Decl;
8120 
8121         // For a three-way comparison, list both the candidates for the
8122         // original operator and the candidates for the synthesized operator.
8123         if (SpaceshipCandidates) {
8124           SpaceshipCandidates->NoteCandidates(
8125               S, Args,
8126               SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
8127                                                       Args, FD->getLocation()));
8128           S.Diag(Subobj.Loc,
8129                  diag::note_defaulted_comparison_no_viable_function_synthesized)
8130               << (OO == OO_EqualEqual ? 0 : 1);
8131         }
8132 
8133         CandidateSet.NoteCandidates(
8134             S, Args,
8135             CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
8136                                             FD->getLocation()));
8137       }
8138       R = Result::deleted();
8139       break;
8140     }
8141 
8142     return R;
8143   }
8144 };
8145 
8146 /// A list of statements.
8147 struct StmtListResult {
8148   bool IsInvalid = false;
8149   llvm::SmallVector<Stmt*, 16> Stmts;
8150 
8151   bool add(const StmtResult &S) {
8152     IsInvalid |= S.isInvalid();
8153     if (IsInvalid)
8154       return true;
8155     Stmts.push_back(S.get());
8156     return false;
8157   }
8158 };
8159 
8160 /// A visitor over the notional body of a defaulted comparison that synthesizes
8161 /// the actual body.
8162 class DefaultedComparisonSynthesizer
8163     : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
8164                                         StmtListResult, StmtResult,
8165                                         std::pair<ExprResult, ExprResult>> {
8166   SourceLocation Loc;
8167   unsigned ArrayDepth = 0;
8168 
8169 public:
8170   using Base = DefaultedComparisonVisitor;
8171   using ExprPair = std::pair<ExprResult, ExprResult>;
8172 
8173   friend Base;
8174 
8175   DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8176                                  DefaultedComparisonKind DCK,
8177                                  SourceLocation BodyLoc)
8178       : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
8179 
8180   /// Build a suitable function body for this defaulted comparison operator.
8181   StmtResult build() {
8182     Sema::CompoundScopeRAII CompoundScope(S);
8183 
8184     StmtListResult Stmts = visit();
8185     if (Stmts.IsInvalid)
8186       return StmtError();
8187 
8188     ExprResult RetVal;
8189     switch (DCK) {
8190     case DefaultedComparisonKind::None:
8191       llvm_unreachable("not a defaulted comparison");
8192 
8193     case DefaultedComparisonKind::Equal: {
8194       // C++2a [class.eq]p3:
8195       //   [...] compar[e] the corresponding elements [...] until the first
8196       //   index i where xi == yi yields [...] false. If no such index exists,
8197       //   V is true. Otherwise, V is false.
8198       //
8199       // Join the comparisons with '&&'s and return the result. Use a right
8200       // fold (traversing the conditions right-to-left), because that
8201       // short-circuits more naturally.
8202       auto OldStmts = std::move(Stmts.Stmts);
8203       Stmts.Stmts.clear();
8204       ExprResult CmpSoFar;
8205       // Finish a particular comparison chain.
8206       auto FinishCmp = [&] {
8207         if (Expr *Prior = CmpSoFar.get()) {
8208           // Convert the last expression to 'return ...;'
8209           if (RetVal.isUnset() && Stmts.Stmts.empty())
8210             RetVal = CmpSoFar;
8211           // Convert any prior comparison to 'if (!(...)) return false;'
8212           else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
8213             return true;
8214           CmpSoFar = ExprResult();
8215         }
8216         return false;
8217       };
8218       for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
8219         Expr *E = dyn_cast<Expr>(EAsStmt);
8220         if (!E) {
8221           // Found an array comparison.
8222           if (FinishCmp() || Stmts.add(EAsStmt))
8223             return StmtError();
8224           continue;
8225         }
8226 
8227         if (CmpSoFar.isUnset()) {
8228           CmpSoFar = E;
8229           continue;
8230         }
8231         CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
8232         if (CmpSoFar.isInvalid())
8233           return StmtError();
8234       }
8235       if (FinishCmp())
8236         return StmtError();
8237       std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
8238       //   If no such index exists, V is true.
8239       if (RetVal.isUnset())
8240         RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
8241       break;
8242     }
8243 
8244     case DefaultedComparisonKind::ThreeWay: {
8245       // Per C++2a [class.spaceship]p3, as a fallback add:
8246       // return static_cast<R>(std::strong_ordering::equal);
8247       QualType StrongOrdering = S.CheckComparisonCategoryType(
8248           ComparisonCategoryType::StrongOrdering, Loc,
8249           Sema::ComparisonCategoryUsage::DefaultedOperator);
8250       if (StrongOrdering.isNull())
8251         return StmtError();
8252       VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)
8253                              .getValueInfo(ComparisonCategoryResult::Equal)
8254                              ->VD;
8255       RetVal = getDecl(EqualVD);
8256       if (RetVal.isInvalid())
8257         return StmtError();
8258       RetVal = buildStaticCastToR(RetVal.get());
8259       break;
8260     }
8261 
8262     case DefaultedComparisonKind::NotEqual:
8263     case DefaultedComparisonKind::Relational:
8264       RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
8265       break;
8266     }
8267 
8268     // Build the final return statement.
8269     if (RetVal.isInvalid())
8270       return StmtError();
8271     StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
8272     if (ReturnStmt.isInvalid())
8273       return StmtError();
8274     Stmts.Stmts.push_back(ReturnStmt.get());
8275 
8276     return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
8277   }
8278 
8279 private:
8280   ExprResult getDecl(ValueDecl *VD) {
8281     return S.BuildDeclarationNameExpr(
8282         CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8283   }
8284 
8285   ExprResult getParam(unsigned I) {
8286     ParmVarDecl *PD = FD->getParamDecl(I);
8287     return getDecl(PD);
8288   }
8289 
8290   ExprPair getCompleteObject() {
8291     unsigned Param = 0;
8292     ExprResult LHS;
8293     if (isa<CXXMethodDecl>(FD)) {
8294       // LHS is '*this'.
8295       LHS = S.ActOnCXXThis(Loc);
8296       if (!LHS.isInvalid())
8297         LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
8298     } else {
8299       LHS = getParam(Param++);
8300     }
8301     ExprResult RHS = getParam(Param++);
8302     assert(Param == FD->getNumParams());
8303     return {LHS, RHS};
8304   }
8305 
8306   ExprPair getBase(CXXBaseSpecifier *Base) {
8307     ExprPair Obj = getCompleteObject();
8308     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8309       return {ExprError(), ExprError()};
8310     CXXCastPath Path = {Base};
8311     return {S.ImpCastExprToType(Obj.first.get(), Base->getType(),
8312                                 CK_DerivedToBase, VK_LValue, &Path),
8313             S.ImpCastExprToType(Obj.second.get(), Base->getType(),
8314                                 CK_DerivedToBase, VK_LValue, &Path)};
8315   }
8316 
8317   ExprPair getField(FieldDecl *Field) {
8318     ExprPair Obj = getCompleteObject();
8319     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8320       return {ExprError(), ExprError()};
8321 
8322     DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8323     DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8324     return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8325                                       CXXScopeSpec(), Field, Found, NameInfo),
8326             S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8327                                       CXXScopeSpec(), Field, Found, NameInfo)};
8328   }
8329 
8330   // FIXME: When expanding a subobject, register a note in the code synthesis
8331   // stack to say which subobject we're comparing.
8332 
8333   StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8334     if (Cond.isInvalid())
8335       return StmtError();
8336 
8337     ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8338     if (NotCond.isInvalid())
8339       return StmtError();
8340 
8341     ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8342     assert(!False.isInvalid() && "should never fail");
8343     StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8344     if (ReturnFalse.isInvalid())
8345       return StmtError();
8346 
8347     return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, nullptr,
8348                          S.ActOnCondition(nullptr, Loc, NotCond.get(),
8349                                           Sema::ConditionKind::Boolean),
8350                          Loc, ReturnFalse.get(), SourceLocation(), nullptr);
8351   }
8352 
8353   StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8354                                  ExprPair Subobj) {
8355     QualType SizeType = S.Context.getSizeType();
8356     Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8357 
8358     // Build 'size_t i$n = 0'.
8359     IdentifierInfo *IterationVarName = nullptr;
8360     {
8361       SmallString<8> Str;
8362       llvm::raw_svector_ostream OS(Str);
8363       OS << "i" << ArrayDepth;
8364       IterationVarName = &S.Context.Idents.get(OS.str());
8365     }
8366     VarDecl *IterationVar = VarDecl::Create(
8367         S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8368         S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
8369     llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8370     IterationVar->setInit(
8371         IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8372     Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8373 
8374     auto IterRef = [&] {
8375       ExprResult Ref = S.BuildDeclarationNameExpr(
8376           CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8377           IterationVar);
8378       assert(!Ref.isInvalid() && "can't reference our own variable?");
8379       return Ref.get();
8380     };
8381 
8382     // Build 'i$n != Size'.
8383     ExprResult Cond = S.CreateBuiltinBinOp(
8384         Loc, BO_NE, IterRef(),
8385         IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8386     assert(!Cond.isInvalid() && "should never fail");
8387 
8388     // Build '++i$n'.
8389     ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8390     assert(!Inc.isInvalid() && "should never fail");
8391 
8392     // Build 'a[i$n]' and 'b[i$n]'.
8393     auto Index = [&](ExprResult E) {
8394       if (E.isInvalid())
8395         return ExprError();
8396       return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8397     };
8398     Subobj.first = Index(Subobj.first);
8399     Subobj.second = Index(Subobj.second);
8400 
8401     // Compare the array elements.
8402     ++ArrayDepth;
8403     StmtResult Substmt = visitSubobject(Type, Subobj);
8404     --ArrayDepth;
8405 
8406     if (Substmt.isInvalid())
8407       return StmtError();
8408 
8409     // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8410     // For outer levels or for an 'operator<=>' we already have a suitable
8411     // statement that returns as necessary.
8412     if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8413       assert(DCK == DefaultedComparisonKind::Equal &&
8414              "should have non-expression statement");
8415       Substmt = buildIfNotCondReturnFalse(ElemCmp);
8416       if (Substmt.isInvalid())
8417         return StmtError();
8418     }
8419 
8420     // Build 'for (...) ...'
8421     return S.ActOnForStmt(Loc, Loc, Init,
8422                           S.ActOnCondition(nullptr, Loc, Cond.get(),
8423                                            Sema::ConditionKind::Boolean),
8424                           S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
8425                           Substmt.get());
8426   }
8427 
8428   StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8429     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8430       return StmtError();
8431 
8432     OverloadedOperatorKind OO = FD->getOverloadedOperator();
8433     BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO);
8434     ExprResult Op;
8435     if (Type->isOverloadableType())
8436       Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8437                                    Obj.second.get(), /*PerformADL=*/true,
8438                                    /*AllowRewrittenCandidates=*/true, FD);
8439     else
8440       Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8441     if (Op.isInvalid())
8442       return StmtError();
8443 
8444     switch (DCK) {
8445     case DefaultedComparisonKind::None:
8446       llvm_unreachable("not a defaulted comparison");
8447 
8448     case DefaultedComparisonKind::Equal:
8449       // Per C++2a [class.eq]p2, each comparison is individually contextually
8450       // converted to bool.
8451       Op = S.PerformContextuallyConvertToBool(Op.get());
8452       if (Op.isInvalid())
8453         return StmtError();
8454       return Op.get();
8455 
8456     case DefaultedComparisonKind::ThreeWay: {
8457       // Per C++2a [class.spaceship]p3, form:
8458       //   if (R cmp = static_cast<R>(op); cmp != 0)
8459       //     return cmp;
8460       QualType R = FD->getReturnType();
8461       Op = buildStaticCastToR(Op.get());
8462       if (Op.isInvalid())
8463         return StmtError();
8464 
8465       // R cmp = ...;
8466       IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8467       VarDecl *VD =
8468           VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8469                           S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None);
8470       S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8471       Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8472 
8473       // cmp != 0
8474       ExprResult VDRef = getDecl(VD);
8475       if (VDRef.isInvalid())
8476         return StmtError();
8477       llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8478       Expr *Zero =
8479           IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8480       ExprResult Comp;
8481       if (VDRef.get()->getType()->isOverloadableType())
8482         Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8483                                        true, FD);
8484       else
8485         Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8486       if (Comp.isInvalid())
8487         return StmtError();
8488       Sema::ConditionResult Cond = S.ActOnCondition(
8489           nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8490       if (Cond.isInvalid())
8491         return StmtError();
8492 
8493       // return cmp;
8494       VDRef = getDecl(VD);
8495       if (VDRef.isInvalid())
8496         return StmtError();
8497       StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
8498       if (ReturnStmt.isInvalid())
8499         return StmtError();
8500 
8501       // if (...)
8502       return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, InitStmt, Cond,
8503                            Loc, ReturnStmt.get(),
8504                            /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
8505     }
8506 
8507     case DefaultedComparisonKind::NotEqual:
8508     case DefaultedComparisonKind::Relational:
8509       // C++2a [class.compare.secondary]p2:
8510       //   Otherwise, the operator function yields x @ y.
8511       return Op.get();
8512     }
8513     llvm_unreachable("");
8514   }
8515 
8516   /// Build "static_cast<R>(E)".
8517   ExprResult buildStaticCastToR(Expr *E) {
8518     QualType R = FD->getReturnType();
8519     assert(!R->isUndeducedType() && "type should have been deduced already");
8520 
8521     // Don't bother forming a no-op cast in the common case.
8522     if (E->isPRValue() && S.Context.hasSameType(E->getType(), R))
8523       return E;
8524     return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8525                                S.Context.getTrivialTypeSourceInfo(R, Loc), E,
8526                                SourceRange(Loc, Loc), SourceRange(Loc, Loc));
8527   }
8528 };
8529 }
8530 
8531 /// Perform the unqualified lookups that might be needed to form a defaulted
8532 /// comparison function for the given operator.
8533 static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S,
8534                                                   UnresolvedSetImpl &Operators,
8535                                                   OverloadedOperatorKind Op) {
8536   auto Lookup = [&](OverloadedOperatorKind OO) {
8537     Self.LookupOverloadedOperatorName(OO, S, Operators);
8538   };
8539 
8540   // Every defaulted operator looks up itself.
8541   Lookup(Op);
8542   // ... and the rewritten form of itself, if any.
8543   if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op))
8544     Lookup(ExtraOp);
8545 
8546   // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8547   // synthesize a three-way comparison from '<' and '=='. In a dependent
8548   // context, we also need to look up '==' in case we implicitly declare a
8549   // defaulted 'operator=='.
8550   if (Op == OO_Spaceship) {
8551     Lookup(OO_ExclaimEqual);
8552     Lookup(OO_Less);
8553     Lookup(OO_EqualEqual);
8554   }
8555 }
8556 
8557 bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD,
8558                                               DefaultedComparisonKind DCK) {
8559   assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
8560 
8561   // Perform any unqualified lookups we're going to need to default this
8562   // function.
8563   if (S) {
8564     UnresolvedSet<32> Operators;
8565     lookupOperatorsForDefaultedComparison(*this, S, Operators,
8566                                           FD->getOverloadedOperator());
8567     FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create(
8568         Context, Operators.pairs()));
8569   }
8570 
8571   // C++2a [class.compare.default]p1:
8572   //   A defaulted comparison operator function for some class C shall be a
8573   //   non-template function declared in the member-specification of C that is
8574   //    -- a non-static const member of C having one parameter of type
8575   //       const C&, or
8576   //    -- a friend of C having two parameters of type const C& or two
8577   //       parameters of type C.
8578 
8579   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
8580   bool IsMethod = isa<CXXMethodDecl>(FD);
8581   if (IsMethod) {
8582     auto *MD = cast<CXXMethodDecl>(FD);
8583     assert(!MD->isStatic() && "comparison function cannot be a static member");
8584 
8585     // If we're out-of-class, this is the class we're comparing.
8586     if (!RD)
8587       RD = MD->getParent();
8588 
8589     if (!MD->isConst()) {
8590       SourceLocation InsertLoc;
8591       if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
8592         InsertLoc = getLocForEndOfToken(Loc.getRParenLoc());
8593       // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8594       // corresponding defaulted 'operator<=>' already.
8595       if (!MD->isImplicit()) {
8596         Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const)
8597             << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
8598       }
8599 
8600       // Add the 'const' to the type to recover.
8601       const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8602       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8603       EPI.TypeQuals.addConst();
8604       MD->setType(Context.getFunctionType(FPT->getReturnType(),
8605                                           FPT->getParamTypes(), EPI));
8606     }
8607   }
8608 
8609   if (FD->getNumParams() != (IsMethod ? 1 : 2)) {
8610     // Let's not worry about using a variadic template pack here -- who would do
8611     // such a thing?
8612     Diag(FD->getLocation(), diag::err_defaulted_comparison_num_args)
8613         << int(IsMethod) << int(DCK);
8614     return true;
8615   }
8616 
8617   const ParmVarDecl *KnownParm = nullptr;
8618   for (const ParmVarDecl *Param : FD->parameters()) {
8619     QualType ParmTy = Param->getType();
8620     if (ParmTy->isDependentType())
8621       continue;
8622     if (!KnownParm) {
8623       auto CTy = ParmTy;
8624       // Is it `T const &`?
8625       bool Ok = !IsMethod;
8626       QualType ExpectedTy;
8627       if (RD)
8628         ExpectedTy = Context.getRecordType(RD);
8629       if (auto *Ref = CTy->getAs<ReferenceType>()) {
8630         CTy = Ref->getPointeeType();
8631         if (RD)
8632           ExpectedTy.addConst();
8633         Ok = true;
8634       }
8635 
8636       // Is T a class?
8637       if (!Ok) {
8638       } else if (RD) {
8639         if (!RD->isDependentType() && !Context.hasSameType(CTy, ExpectedTy))
8640           Ok = false;
8641       } else if (auto *CRD = CTy->getAsRecordDecl()) {
8642         RD = cast<CXXRecordDecl>(CRD);
8643       } else {
8644         Ok = false;
8645       }
8646 
8647       if (Ok) {
8648         KnownParm = Param;
8649       } else {
8650         // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8651         // corresponding defaulted 'operator<=>' already.
8652         if (!FD->isImplicit()) {
8653           if (RD) {
8654             QualType PlainTy = Context.getRecordType(RD);
8655             QualType RefTy =
8656                 Context.getLValueReferenceType(PlainTy.withConst());
8657             Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
8658                 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
8659                 << Param->getSourceRange();
8660           } else {
8661             assert(!IsMethod && "should know expected type for method");
8662             Diag(FD->getLocation(),
8663                  diag::err_defaulted_comparison_param_unknown)
8664                 << int(DCK) << ParmTy << Param->getSourceRange();
8665           }
8666         }
8667         return true;
8668       }
8669     } else if (!Context.hasSameType(KnownParm->getType(), ParmTy)) {
8670       Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
8671           << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
8672           << ParmTy << Param->getSourceRange();
8673       return true;
8674     }
8675   }
8676 
8677   assert(RD && "must have determined class");
8678   if (IsMethod) {
8679   } else if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
8680     // In-class, must be a friend decl.
8681     assert(FD->getFriendObjectKind() && "expected a friend declaration");
8682   } else {
8683     // Out of class, require the defaulted comparison to be a friend (of a
8684     // complete type).
8685     if (RequireCompleteType(FD->getLocation(), Context.getRecordType(RD),
8686                             diag::err_defaulted_comparison_not_friend, int(DCK),
8687                             int(1)))
8688       return true;
8689 
8690     if (llvm::none_of(RD->friends(), [&](const FriendDecl *F) {
8691           return FD->getCanonicalDecl() ==
8692                  F->getFriendDecl()->getCanonicalDecl();
8693         })) {
8694       Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend)
8695           << int(DCK) << int(0) << RD;
8696       Diag(RD->getCanonicalDecl()->getLocation(), diag::note_declared_at);
8697       return true;
8698     }
8699   }
8700 
8701   // C++2a [class.eq]p1, [class.rel]p1:
8702   //   A [defaulted comparison other than <=>] shall have a declared return
8703   //   type bool.
8704   if (DCK != DefaultedComparisonKind::ThreeWay &&
8705       !FD->getDeclaredReturnType()->isDependentType() &&
8706       !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
8707     Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
8708         << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
8709         << FD->getReturnTypeSourceRange();
8710     return true;
8711   }
8712   // C++2a [class.spaceship]p2 [P2002R0]:
8713   //   Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
8714   //   R shall not contain a placeholder type.
8715   if (QualType RT = FD->getDeclaredReturnType();
8716       DCK == DefaultedComparisonKind::ThreeWay &&
8717       RT->getContainedDeducedType() &&
8718       (!Context.hasSameType(RT, Context.getAutoDeductType()) ||
8719        RT->getContainedAutoType()->isConstrained())) {
8720     Diag(FD->getLocation(),
8721          diag::err_defaulted_comparison_deduced_return_type_not_auto)
8722         << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
8723         << FD->getReturnTypeSourceRange();
8724     return true;
8725   }
8726 
8727   // For a defaulted function in a dependent class, defer all remaining checks
8728   // until instantiation.
8729   if (RD->isDependentType())
8730     return false;
8731 
8732   // Determine whether the function should be defined as deleted.
8733   DefaultedComparisonInfo Info =
8734       DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
8735 
8736   bool First = FD == FD->getCanonicalDecl();
8737 
8738   if (!First) {
8739     if (Info.Deleted) {
8740       // C++11 [dcl.fct.def.default]p4:
8741       //   [For a] user-provided explicitly-defaulted function [...] if such a
8742       //   function is implicitly defined as deleted, the program is ill-formed.
8743       //
8744       // This is really just a consequence of the general rule that you can
8745       // only delete a function on its first declaration.
8746       Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
8747           << FD->isImplicit() << (int)DCK;
8748       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8749                                   DefaultedComparisonAnalyzer::ExplainDeleted)
8750           .visit();
8751       return true;
8752     }
8753     if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
8754       // C++20 [class.compare.default]p1:
8755       //   [...] A definition of a comparison operator as defaulted that appears
8756       //   in a class shall be the first declaration of that function.
8757       Diag(FD->getLocation(), diag::err_non_first_default_compare_in_class)
8758           << (int)DCK;
8759       Diag(FD->getCanonicalDecl()->getLocation(),
8760            diag::note_previous_declaration);
8761       return true;
8762     }
8763   }
8764 
8765   // If we want to delete the function, then do so; there's nothing else to
8766   // check in that case.
8767   if (Info.Deleted) {
8768     SetDeclDeleted(FD, FD->getLocation());
8769     if (!inTemplateInstantiation() && !FD->isImplicit()) {
8770       Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
8771           << (int)DCK;
8772       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8773                                   DefaultedComparisonAnalyzer::ExplainDeleted)
8774           .visit();
8775       if (FD->getDefaultLoc().isValid())
8776         Diag(FD->getDefaultLoc(), diag::note_replace_equals_default_to_delete)
8777             << FixItHint::CreateReplacement(FD->getDefaultLoc(), "delete");
8778     }
8779     return false;
8780   }
8781 
8782   // C++2a [class.spaceship]p2:
8783   //   The return type is deduced as the common comparison type of R0, R1, ...
8784   if (DCK == DefaultedComparisonKind::ThreeWay &&
8785       FD->getDeclaredReturnType()->isUndeducedAutoType()) {
8786     SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();
8787     if (RetLoc.isInvalid())
8788       RetLoc = FD->getBeginLoc();
8789     // FIXME: Should we really care whether we have the complete type and the
8790     // 'enumerator' constants here? A forward declaration seems sufficient.
8791     QualType Cat = CheckComparisonCategoryType(
8792         Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
8793     if (Cat.isNull())
8794       return true;
8795     Context.adjustDeducedFunctionResultType(
8796         FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
8797   }
8798 
8799   // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8800   //   An explicitly-defaulted function that is not defined as deleted may be
8801   //   declared constexpr or consteval only if it is constexpr-compatible.
8802   // C++2a [class.compare.default]p3 [P2002R0]:
8803   //   A defaulted comparison function is constexpr-compatible if it satisfies
8804   //   the requirements for a constexpr function [...]
8805   // The only relevant requirements are that the parameter and return types are
8806   // literal types. The remaining conditions are checked by the analyzer.
8807   if (FD->isConstexpr()) {
8808     if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) &&
8809         CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) &&
8810         !Info.Constexpr) {
8811       Diag(FD->getBeginLoc(),
8812            diag::err_incorrect_defaulted_comparison_constexpr)
8813           << FD->isImplicit() << (int)DCK << FD->isConsteval();
8814       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8815                                   DefaultedComparisonAnalyzer::ExplainConstexpr)
8816           .visit();
8817     }
8818   }
8819 
8820   // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8821   //   If a constexpr-compatible function is explicitly defaulted on its first
8822   //   declaration, it is implicitly considered to be constexpr.
8823   // FIXME: Only applying this to the first declaration seems problematic, as
8824   // simple reorderings can affect the meaning of the program.
8825   if (First && !FD->isConstexpr() && Info.Constexpr)
8826     FD->setConstexprKind(ConstexprSpecKind::Constexpr);
8827 
8828   // C++2a [except.spec]p3:
8829   //   If a declaration of a function does not have a noexcept-specifier
8830   //   [and] is defaulted on its first declaration, [...] the exception
8831   //   specification is as specified below
8832   if (FD->getExceptionSpecType() == EST_None) {
8833     auto *FPT = FD->getType()->castAs<FunctionProtoType>();
8834     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8835     EPI.ExceptionSpec.Type = EST_Unevaluated;
8836     EPI.ExceptionSpec.SourceDecl = FD;
8837     FD->setType(Context.getFunctionType(FPT->getReturnType(),
8838                                         FPT->getParamTypes(), EPI));
8839   }
8840 
8841   return false;
8842 }
8843 
8844 void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
8845                                              FunctionDecl *Spaceship) {
8846   Sema::CodeSynthesisContext Ctx;
8847   Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;
8848   Ctx.PointOfInstantiation = Spaceship->getEndLoc();
8849   Ctx.Entity = Spaceship;
8850   pushCodeSynthesisContext(Ctx);
8851 
8852   if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
8853     EqualEqual->setImplicit();
8854 
8855   popCodeSynthesisContext();
8856 }
8857 
8858 void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,
8859                                      DefaultedComparisonKind DCK) {
8860   assert(FD->isDefaulted() && !FD->isDeleted() &&
8861          !FD->doesThisDeclarationHaveABody());
8862   if (FD->willHaveBody() || FD->isInvalidDecl())
8863     return;
8864 
8865   SynthesizedFunctionScope Scope(*this, FD);
8866 
8867   // Add a context note for diagnostics produced after this point.
8868   Scope.addContextNote(UseLoc);
8869 
8870   {
8871     // Build and set up the function body.
8872     // The first parameter has type maybe-ref-to maybe-const T, use that to get
8873     // the type of the class being compared.
8874     auto PT = FD->getParamDecl(0)->getType();
8875     CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
8876     SourceLocation BodyLoc =
8877         FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8878     StmtResult Body =
8879         DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
8880     if (Body.isInvalid()) {
8881       FD->setInvalidDecl();
8882       return;
8883     }
8884     FD->setBody(Body.get());
8885     FD->markUsed(Context);
8886   }
8887 
8888   // The exception specification is needed because we are defining the
8889   // function. Note that this will reuse the body we just built.
8890   ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>());
8891 
8892   if (ASTMutationListener *L = getASTMutationListener())
8893     L->CompletedImplicitDefinition(FD);
8894 }
8895 
8896 static Sema::ImplicitExceptionSpecification
8897 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
8898                                         FunctionDecl *FD,
8899                                         Sema::DefaultedComparisonKind DCK) {
8900   ComputingExceptionSpec CES(S, FD, Loc);
8901   Sema::ImplicitExceptionSpecification ExceptSpec(S);
8902 
8903   if (FD->isInvalidDecl())
8904     return ExceptSpec;
8905 
8906   // The common case is that we just defined the comparison function. In that
8907   // case, just look at whether the body can throw.
8908   if (FD->hasBody()) {
8909     ExceptSpec.CalledStmt(FD->getBody());
8910   } else {
8911     // Otherwise, build a body so we can check it. This should ideally only
8912     // happen when we're not actually marking the function referenced. (This is
8913     // only really important for efficiency: we don't want to build and throw
8914     // away bodies for comparison functions more than we strictly need to.)
8915 
8916     // Pretend to synthesize the function body in an unevaluated context.
8917     // Note that we can't actually just go ahead and define the function here:
8918     // we are not permitted to mark its callees as referenced.
8919     Sema::SynthesizedFunctionScope Scope(S, FD);
8920     EnterExpressionEvaluationContext Context(
8921         S, Sema::ExpressionEvaluationContext::Unevaluated);
8922 
8923     CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
8924     SourceLocation BodyLoc =
8925         FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8926     StmtResult Body =
8927         DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
8928     if (!Body.isInvalid())
8929       ExceptSpec.CalledStmt(Body.get());
8930 
8931     // FIXME: Can we hold onto this body and just transform it to potentially
8932     // evaluated when we're asked to define the function rather than rebuilding
8933     // it? Either that, or we should only build the bits of the body that we
8934     // need (the expressions, not the statements).
8935   }
8936 
8937   return ExceptSpec;
8938 }
8939 
8940 void Sema::CheckDelayedMemberExceptionSpecs() {
8941   decltype(DelayedOverridingExceptionSpecChecks) Overriding;
8942   decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
8943 
8944   std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
8945   std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
8946 
8947   // Perform any deferred checking of exception specifications for virtual
8948   // destructors.
8949   for (auto &Check : Overriding)
8950     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
8951 
8952   // Perform any deferred checking of exception specifications for befriended
8953   // special members.
8954   for (auto &Check : Equivalent)
8955     CheckEquivalentExceptionSpec(Check.second, Check.first);
8956 }
8957 
8958 namespace {
8959 /// CRTP base class for visiting operations performed by a special member
8960 /// function (or inherited constructor).
8961 template<typename Derived>
8962 struct SpecialMemberVisitor {
8963   Sema &S;
8964   CXXMethodDecl *MD;
8965   Sema::CXXSpecialMember CSM;
8966   Sema::InheritedConstructorInfo *ICI;
8967 
8968   // Properties of the special member, computed for convenience.
8969   bool IsConstructor = false, IsAssignment = false, ConstArg = false;
8970 
8971   SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
8972                        Sema::InheritedConstructorInfo *ICI)
8973       : S(S), MD(MD), CSM(CSM), ICI(ICI) {
8974     switch (CSM) {
8975     case Sema::CXXDefaultConstructor:
8976     case Sema::CXXCopyConstructor:
8977     case Sema::CXXMoveConstructor:
8978       IsConstructor = true;
8979       break;
8980     case Sema::CXXCopyAssignment:
8981     case Sema::CXXMoveAssignment:
8982       IsAssignment = true;
8983       break;
8984     case Sema::CXXDestructor:
8985       break;
8986     case Sema::CXXInvalid:
8987       llvm_unreachable("invalid special member kind");
8988     }
8989 
8990     if (MD->getNumParams()) {
8991       if (const ReferenceType *RT =
8992               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
8993         ConstArg = RT->getPointeeType().isConstQualified();
8994     }
8995   }
8996 
8997   Derived &getDerived() { return static_cast<Derived&>(*this); }
8998 
8999   /// Is this a "move" special member?
9000   bool isMove() const {
9001     return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
9002   }
9003 
9004   /// Look up the corresponding special member in the given class.
9005   Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
9006                                              unsigned Quals, bool IsMutable) {
9007     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
9008                                        ConstArg && !IsMutable);
9009   }
9010 
9011   /// Look up the constructor for the specified base class to see if it's
9012   /// overridden due to this being an inherited constructor.
9013   Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
9014     if (!ICI)
9015       return {};
9016     assert(CSM == Sema::CXXDefaultConstructor);
9017     auto *BaseCtor =
9018       cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
9019     if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
9020       return MD;
9021     return {};
9022   }
9023 
9024   /// A base or member subobject.
9025   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
9026 
9027   /// Get the location to use for a subobject in diagnostics.
9028   static SourceLocation getSubobjectLoc(Subobject Subobj) {
9029     // FIXME: For an indirect virtual base, the direct base leading to
9030     // the indirect virtual base would be a more useful choice.
9031     if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
9032       return B->getBaseTypeLoc();
9033     else
9034       return Subobj.get<FieldDecl*>()->getLocation();
9035   }
9036 
9037   enum BasesToVisit {
9038     /// Visit all non-virtual (direct) bases.
9039     VisitNonVirtualBases,
9040     /// Visit all direct bases, virtual or not.
9041     VisitDirectBases,
9042     /// Visit all non-virtual bases, and all virtual bases if the class
9043     /// is not abstract.
9044     VisitPotentiallyConstructedBases,
9045     /// Visit all direct or virtual bases.
9046     VisitAllBases
9047   };
9048 
9049   // Visit the bases and members of the class.
9050   bool visit(BasesToVisit Bases) {
9051     CXXRecordDecl *RD = MD->getParent();
9052 
9053     if (Bases == VisitPotentiallyConstructedBases)
9054       Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
9055 
9056     for (auto &B : RD->bases())
9057       if ((Bases == VisitDirectBases || !B.isVirtual()) &&
9058           getDerived().visitBase(&B))
9059         return true;
9060 
9061     if (Bases == VisitAllBases)
9062       for (auto &B : RD->vbases())
9063         if (getDerived().visitBase(&B))
9064           return true;
9065 
9066     for (auto *F : RD->fields())
9067       if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
9068           getDerived().visitField(F))
9069         return true;
9070 
9071     return false;
9072   }
9073 };
9074 }
9075 
9076 namespace {
9077 struct SpecialMemberDeletionInfo
9078     : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
9079   bool Diagnose;
9080 
9081   SourceLocation Loc;
9082 
9083   bool AllFieldsAreConst;
9084 
9085   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
9086                             Sema::CXXSpecialMember CSM,
9087                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
9088       : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
9089         Loc(MD->getLocation()), AllFieldsAreConst(true) {}
9090 
9091   bool inUnion() const { return MD->getParent()->isUnion(); }
9092 
9093   Sema::CXXSpecialMember getEffectiveCSM() {
9094     return ICI ? Sema::CXXInvalid : CSM;
9095   }
9096 
9097   bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
9098 
9099   bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
9100   bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
9101 
9102   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
9103   bool shouldDeleteForField(FieldDecl *FD);
9104   bool shouldDeleteForAllConstMembers();
9105 
9106   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
9107                                      unsigned Quals);
9108   bool shouldDeleteForSubobjectCall(Subobject Subobj,
9109                                     Sema::SpecialMemberOverloadResult SMOR,
9110                                     bool IsDtorCallInCtor);
9111 
9112   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
9113 };
9114 }
9115 
9116 /// Is the given special member inaccessible when used on the given
9117 /// sub-object.
9118 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
9119                                              CXXMethodDecl *target) {
9120   /// If we're operating on a base class, the object type is the
9121   /// type of this special member.
9122   QualType objectTy;
9123   AccessSpecifier access = target->getAccess();
9124   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
9125     objectTy = S.Context.getTypeDeclType(MD->getParent());
9126     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
9127 
9128   // If we're operating on a field, the object type is the type of the field.
9129   } else {
9130     objectTy = S.Context.getTypeDeclType(target->getParent());
9131   }
9132 
9133   return S.isMemberAccessibleForDeletion(
9134       target->getParent(), DeclAccessPair::make(target, access), objectTy);
9135 }
9136 
9137 /// Check whether we should delete a special member due to the implicit
9138 /// definition containing a call to a special member of a subobject.
9139 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
9140     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
9141     bool IsDtorCallInCtor) {
9142   CXXMethodDecl *Decl = SMOR.getMethod();
9143   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9144 
9145   int DiagKind = -1;
9146 
9147   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
9148     DiagKind = !Decl ? 0 : 1;
9149   else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9150     DiagKind = 2;
9151   else if (!isAccessible(Subobj, Decl))
9152     DiagKind = 3;
9153   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
9154            !Decl->isTrivial()) {
9155     // A member of a union must have a trivial corresponding special member.
9156     // As a weird special case, a destructor call from a union's constructor
9157     // must be accessible and non-deleted, but need not be trivial. Such a
9158     // destructor is never actually called, but is semantically checked as
9159     // if it were.
9160     DiagKind = 4;
9161   }
9162 
9163   if (DiagKind == -1)
9164     return false;
9165 
9166   if (Diagnose) {
9167     if (Field) {
9168       S.Diag(Field->getLocation(),
9169              diag::note_deleted_special_member_class_subobject)
9170         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
9171         << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
9172     } else {
9173       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
9174       S.Diag(Base->getBeginLoc(),
9175              diag::note_deleted_special_member_class_subobject)
9176           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9177           << Base->getType() << DiagKind << IsDtorCallInCtor
9178           << /*IsObjCPtr*/false;
9179     }
9180 
9181     if (DiagKind == 1)
9182       S.NoteDeletedFunction(Decl);
9183     // FIXME: Explain inaccessibility if DiagKind == 3.
9184   }
9185 
9186   return true;
9187 }
9188 
9189 /// Check whether we should delete a special member function due to having a
9190 /// direct or virtual base class or non-static data member of class type M.
9191 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
9192     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
9193   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9194   bool IsMutable = Field && Field->isMutable();
9195 
9196   // C++11 [class.ctor]p5:
9197   // -- any direct or virtual base class, or non-static data member with no
9198   //    brace-or-equal-initializer, has class type M (or array thereof) and
9199   //    either M has no default constructor or overload resolution as applied
9200   //    to M's default constructor results in an ambiguity or in a function
9201   //    that is deleted or inaccessible
9202   // C++11 [class.copy]p11, C++11 [class.copy]p23:
9203   // -- a direct or virtual base class B that cannot be copied/moved because
9204   //    overload resolution, as applied to B's corresponding special member,
9205   //    results in an ambiguity or a function that is deleted or inaccessible
9206   //    from the defaulted special member
9207   // C++11 [class.dtor]p5:
9208   // -- any direct or virtual base class [...] has a type with a destructor
9209   //    that is deleted or inaccessible
9210   if (!(CSM == Sema::CXXDefaultConstructor &&
9211         Field && Field->hasInClassInitializer()) &&
9212       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
9213                                    false))
9214     return true;
9215 
9216   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
9217   // -- any direct or virtual base class or non-static data member has a
9218   //    type with a destructor that is deleted or inaccessible
9219   if (IsConstructor) {
9220     Sema::SpecialMemberOverloadResult SMOR =
9221         S.LookupSpecialMember(Class, Sema::CXXDestructor,
9222                               false, false, false, false, false);
9223     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
9224       return true;
9225   }
9226 
9227   return false;
9228 }
9229 
9230 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
9231     FieldDecl *FD, QualType FieldType) {
9232   // The defaulted special functions are defined as deleted if this is a variant
9233   // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
9234   // type under ARC.
9235   if (!FieldType.hasNonTrivialObjCLifetime())
9236     return false;
9237 
9238   // Don't make the defaulted default constructor defined as deleted if the
9239   // member has an in-class initializer.
9240   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
9241     return false;
9242 
9243   if (Diagnose) {
9244     auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
9245     S.Diag(FD->getLocation(),
9246            diag::note_deleted_special_member_class_subobject)
9247         << getEffectiveCSM() << ParentClass << /*IsField*/true
9248         << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
9249   }
9250 
9251   return true;
9252 }
9253 
9254 /// Check whether we should delete a special member function due to the class
9255 /// having a particular direct or virtual base class.
9256 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
9257   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
9258   // If program is correct, BaseClass cannot be null, but if it is, the error
9259   // must be reported elsewhere.
9260   if (!BaseClass)
9261     return false;
9262   // If we have an inheriting constructor, check whether we're calling an
9263   // inherited constructor instead of a default constructor.
9264   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
9265   if (auto *BaseCtor = SMOR.getMethod()) {
9266     // Note that we do not check access along this path; other than that,
9267     // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9268     // FIXME: Check that the base has a usable destructor! Sink this into
9269     // shouldDeleteForClassSubobject.
9270     if (BaseCtor->isDeleted() && Diagnose) {
9271       S.Diag(Base->getBeginLoc(),
9272              diag::note_deleted_special_member_class_subobject)
9273           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9274           << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
9275           << /*IsObjCPtr*/false;
9276       S.NoteDeletedFunction(BaseCtor);
9277     }
9278     return BaseCtor->isDeleted();
9279   }
9280   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
9281 }
9282 
9283 /// Check whether we should delete a special member function due to the class
9284 /// having a particular non-static data member.
9285 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
9286   QualType FieldType = S.Context.getBaseElementType(FD->getType());
9287   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
9288 
9289   if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9290     return true;
9291 
9292   if (CSM == Sema::CXXDefaultConstructor) {
9293     // For a default constructor, all references must be initialized in-class
9294     // and, if a union, it must have a non-const member.
9295     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9296       if (Diagnose)
9297         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9298           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9299       return true;
9300     }
9301     // C++11 [class.ctor]p5 (modified by DR2394): any non-variant non-static
9302     // data member of const-qualified type (or array thereof) with no
9303     // brace-or-equal-initializer is not const-default-constructible.
9304     if (!inUnion() && FieldType.isConstQualified() &&
9305         !FD->hasInClassInitializer() &&
9306         (!FieldRecord || !FieldRecord->allowConstDefaultInit())) {
9307       if (Diagnose)
9308         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9309           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9310       return true;
9311     }
9312 
9313     if (inUnion() && !FieldType.isConstQualified())
9314       AllFieldsAreConst = false;
9315   } else if (CSM == Sema::CXXCopyConstructor) {
9316     // For a copy constructor, data members must not be of rvalue reference
9317     // type.
9318     if (FieldType->isRValueReferenceType()) {
9319       if (Diagnose)
9320         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
9321           << MD->getParent() << FD << FieldType;
9322       return true;
9323     }
9324   } else if (IsAssignment) {
9325     // For an assignment operator, data members must not be of reference type.
9326     if (FieldType->isReferenceType()) {
9327       if (Diagnose)
9328         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9329           << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9330       return true;
9331     }
9332     if (!FieldRecord && FieldType.isConstQualified()) {
9333       // C++11 [class.copy]p23:
9334       // -- a non-static data member of const non-class type (or array thereof)
9335       if (Diagnose)
9336         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9337           << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9338       return true;
9339     }
9340   }
9341 
9342   if (FieldRecord) {
9343     // Some additional restrictions exist on the variant members.
9344     if (!inUnion() && FieldRecord->isUnion() &&
9345         FieldRecord->isAnonymousStructOrUnion()) {
9346       bool AllVariantFieldsAreConst = true;
9347 
9348       // FIXME: Handle anonymous unions declared within anonymous unions.
9349       for (auto *UI : FieldRecord->fields()) {
9350         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
9351 
9352         if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
9353           return true;
9354 
9355         if (!UnionFieldType.isConstQualified())
9356           AllVariantFieldsAreConst = false;
9357 
9358         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9359         if (UnionFieldRecord &&
9360             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
9361                                           UnionFieldType.getCVRQualifiers()))
9362           return true;
9363       }
9364 
9365       // At least one member in each anonymous union must be non-const
9366       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
9367           !FieldRecord->field_empty()) {
9368         if (Diagnose)
9369           S.Diag(FieldRecord->getLocation(),
9370                  diag::note_deleted_default_ctor_all_const)
9371             << !!ICI << MD->getParent() << /*anonymous union*/1;
9372         return true;
9373       }
9374 
9375       // Don't check the implicit member of the anonymous union type.
9376       // This is technically non-conformant but supported, and we have a
9377       // diagnostic for this elsewhere.
9378       return false;
9379     }
9380 
9381     if (shouldDeleteForClassSubobject(FieldRecord, FD,
9382                                       FieldType.getCVRQualifiers()))
9383       return true;
9384   }
9385 
9386   return false;
9387 }
9388 
9389 /// C++11 [class.ctor] p5:
9390 ///   A defaulted default constructor for a class X is defined as deleted if
9391 /// X is a union and all of its variant members are of const-qualified type.
9392 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9393   // This is a silly definition, because it gives an empty union a deleted
9394   // default constructor. Don't do that.
9395   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
9396     bool AnyFields = false;
9397     for (auto *F : MD->getParent()->fields())
9398       if ((AnyFields = !F->isUnnamedBitfield()))
9399         break;
9400     if (!AnyFields)
9401       return false;
9402     if (Diagnose)
9403       S.Diag(MD->getParent()->getLocation(),
9404              diag::note_deleted_default_ctor_all_const)
9405         << !!ICI << MD->getParent() << /*not anonymous union*/0;
9406     return true;
9407   }
9408   return false;
9409 }
9410 
9411 /// Determine whether a defaulted special member function should be defined as
9412 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9413 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9414 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
9415                                      InheritedConstructorInfo *ICI,
9416                                      bool Diagnose) {
9417   if (MD->isInvalidDecl())
9418     return false;
9419   CXXRecordDecl *RD = MD->getParent();
9420   assert(!RD->isDependentType() && "do deletion after instantiation");
9421   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
9422     return false;
9423 
9424   // C++11 [expr.lambda.prim]p19:
9425   //   The closure type associated with a lambda-expression has a
9426   //   deleted (8.4.3) default constructor and a deleted copy
9427   //   assignment operator.
9428   // C++2a adds back these operators if the lambda has no lambda-capture.
9429   if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
9430       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
9431     if (Diagnose)
9432       Diag(RD->getLocation(), diag::note_lambda_decl);
9433     return true;
9434   }
9435 
9436   // For an anonymous struct or union, the copy and assignment special members
9437   // will never be used, so skip the check. For an anonymous union declared at
9438   // namespace scope, the constructor and destructor are used.
9439   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
9440       RD->isAnonymousStructOrUnion())
9441     return false;
9442 
9443   // C++11 [class.copy]p7, p18:
9444   //   If the class definition declares a move constructor or move assignment
9445   //   operator, an implicitly declared copy constructor or copy assignment
9446   //   operator is defined as deleted.
9447   if (MD->isImplicit() &&
9448       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
9449     CXXMethodDecl *UserDeclaredMove = nullptr;
9450 
9451     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9452     // deletion of the corresponding copy operation, not both copy operations.
9453     // MSVC 2015 has adopted the standards conforming behavior.
9454     bool DeletesOnlyMatchingCopy =
9455         getLangOpts().MSVCCompat &&
9456         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
9457 
9458     if (RD->hasUserDeclaredMoveConstructor() &&
9459         (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
9460       if (!Diagnose) return true;
9461 
9462       // Find any user-declared move constructor.
9463       for (auto *I : RD->ctors()) {
9464         if (I->isMoveConstructor()) {
9465           UserDeclaredMove = I;
9466           break;
9467         }
9468       }
9469       assert(UserDeclaredMove);
9470     } else if (RD->hasUserDeclaredMoveAssignment() &&
9471                (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
9472       if (!Diagnose) return true;
9473 
9474       // Find any user-declared move assignment operator.
9475       for (auto *I : RD->methods()) {
9476         if (I->isMoveAssignmentOperator()) {
9477           UserDeclaredMove = I;
9478           break;
9479         }
9480       }
9481       assert(UserDeclaredMove);
9482     }
9483 
9484     if (UserDeclaredMove) {
9485       Diag(UserDeclaredMove->getLocation(),
9486            diag::note_deleted_copy_user_declared_move)
9487         << (CSM == CXXCopyAssignment) << RD
9488         << UserDeclaredMove->isMoveAssignmentOperator();
9489       return true;
9490     }
9491   }
9492 
9493   // Do access control from the special member function
9494   ContextRAII MethodContext(*this, MD);
9495 
9496   // C++11 [class.dtor]p5:
9497   // -- for a virtual destructor, lookup of the non-array deallocation function
9498   //    results in an ambiguity or in a function that is deleted or inaccessible
9499   if (CSM == CXXDestructor && MD->isVirtual()) {
9500     FunctionDecl *OperatorDelete = nullptr;
9501     DeclarationName Name =
9502       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
9503     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
9504                                  OperatorDelete, /*Diagnose*/false)) {
9505       if (Diagnose)
9506         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
9507       return true;
9508     }
9509   }
9510 
9511   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
9512 
9513   // Per DR1611, do not consider virtual bases of constructors of abstract
9514   // classes, since we are not going to construct them.
9515   // Per DR1658, do not consider virtual bases of destructors of abstract
9516   // classes either.
9517   // Per DR2180, for assignment operators we only assign (and thus only
9518   // consider) direct bases.
9519   if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
9520                                  : SMI.VisitPotentiallyConstructedBases))
9521     return true;
9522 
9523   if (SMI.shouldDeleteForAllConstMembers())
9524     return true;
9525 
9526   if (getLangOpts().CUDA) {
9527     // We should delete the special member in CUDA mode if target inference
9528     // failed.
9529     // For inherited constructors (non-null ICI), CSM may be passed so that MD
9530     // is treated as certain special member, which may not reflect what special
9531     // member MD really is. However inferCUDATargetForImplicitSpecialMember
9532     // expects CSM to match MD, therefore recalculate CSM.
9533     assert(ICI || CSM == getSpecialMember(MD));
9534     auto RealCSM = CSM;
9535     if (ICI)
9536       RealCSM = getSpecialMember(MD);
9537 
9538     return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
9539                                                    SMI.ConstArg, Diagnose);
9540   }
9541 
9542   return false;
9543 }
9544 
9545 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {
9546   DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
9547   assert(DFK && "not a defaultable function");
9548   assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
9549 
9550   if (DFK.isSpecialMember()) {
9551     ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),
9552                               nullptr, /*Diagnose=*/true);
9553   } else {
9554     DefaultedComparisonAnalyzer(
9555         *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
9556         DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
9557         .visit();
9558   }
9559 }
9560 
9561 /// Perform lookup for a special member of the specified kind, and determine
9562 /// whether it is trivial. If the triviality can be determined without the
9563 /// lookup, skip it. This is intended for use when determining whether a
9564 /// special member of a containing object is trivial, and thus does not ever
9565 /// perform overload resolution for default constructors.
9566 ///
9567 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
9568 /// member that was most likely to be intended to be trivial, if any.
9569 ///
9570 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
9571 /// determine whether the special member is trivial.
9572 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
9573                                      Sema::CXXSpecialMember CSM, unsigned Quals,
9574                                      bool ConstRHS,
9575                                      Sema::TrivialABIHandling TAH,
9576                                      CXXMethodDecl **Selected) {
9577   if (Selected)
9578     *Selected = nullptr;
9579 
9580   switch (CSM) {
9581   case Sema::CXXInvalid:
9582     llvm_unreachable("not a special member");
9583 
9584   case Sema::CXXDefaultConstructor:
9585     // C++11 [class.ctor]p5:
9586     //   A default constructor is trivial if:
9587     //    - all the [direct subobjects] have trivial default constructors
9588     //
9589     // Note, no overload resolution is performed in this case.
9590     if (RD->hasTrivialDefaultConstructor())
9591       return true;
9592 
9593     if (Selected) {
9594       // If there's a default constructor which could have been trivial, dig it
9595       // out. Otherwise, if there's any user-provided default constructor, point
9596       // to that as an example of why there's not a trivial one.
9597       CXXConstructorDecl *DefCtor = nullptr;
9598       if (RD->needsImplicitDefaultConstructor())
9599         S.DeclareImplicitDefaultConstructor(RD);
9600       for (auto *CI : RD->ctors()) {
9601         if (!CI->isDefaultConstructor())
9602           continue;
9603         DefCtor = CI;
9604         if (!DefCtor->isUserProvided())
9605           break;
9606       }
9607 
9608       *Selected = DefCtor;
9609     }
9610 
9611     return false;
9612 
9613   case Sema::CXXDestructor:
9614     // C++11 [class.dtor]p5:
9615     //   A destructor is trivial if:
9616     //    - all the direct [subobjects] have trivial destructors
9617     if (RD->hasTrivialDestructor() ||
9618         (TAH == Sema::TAH_ConsiderTrivialABI &&
9619          RD->hasTrivialDestructorForCall()))
9620       return true;
9621 
9622     if (Selected) {
9623       if (RD->needsImplicitDestructor())
9624         S.DeclareImplicitDestructor(RD);
9625       *Selected = RD->getDestructor();
9626     }
9627 
9628     return false;
9629 
9630   case Sema::CXXCopyConstructor:
9631     // C++11 [class.copy]p12:
9632     //   A copy constructor is trivial if:
9633     //    - the constructor selected to copy each direct [subobject] is trivial
9634     if (RD->hasTrivialCopyConstructor() ||
9635         (TAH == Sema::TAH_ConsiderTrivialABI &&
9636          RD->hasTrivialCopyConstructorForCall())) {
9637       if (Quals == Qualifiers::Const)
9638         // We must either select the trivial copy constructor or reach an
9639         // ambiguity; no need to actually perform overload resolution.
9640         return true;
9641     } else if (!Selected) {
9642       return false;
9643     }
9644     // In C++98, we are not supposed to perform overload resolution here, but we
9645     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
9646     // cases like B as having a non-trivial copy constructor:
9647     //   struct A { template<typename T> A(T&); };
9648     //   struct B { mutable A a; };
9649     goto NeedOverloadResolution;
9650 
9651   case Sema::CXXCopyAssignment:
9652     // C++11 [class.copy]p25:
9653     //   A copy assignment operator is trivial if:
9654     //    - the assignment operator selected to copy each direct [subobject] is
9655     //      trivial
9656     if (RD->hasTrivialCopyAssignment()) {
9657       if (Quals == Qualifiers::Const)
9658         return true;
9659     } else if (!Selected) {
9660       return false;
9661     }
9662     // In C++98, we are not supposed to perform overload resolution here, but we
9663     // treat that as a language defect.
9664     goto NeedOverloadResolution;
9665 
9666   case Sema::CXXMoveConstructor:
9667   case Sema::CXXMoveAssignment:
9668   NeedOverloadResolution:
9669     Sema::SpecialMemberOverloadResult SMOR =
9670         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
9671 
9672     // The standard doesn't describe how to behave if the lookup is ambiguous.
9673     // We treat it as not making the member non-trivial, just like the standard
9674     // mandates for the default constructor. This should rarely matter, because
9675     // the member will also be deleted.
9676     if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9677       return true;
9678 
9679     if (!SMOR.getMethod()) {
9680       assert(SMOR.getKind() ==
9681              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
9682       return false;
9683     }
9684 
9685     // We deliberately don't check if we found a deleted special member. We're
9686     // not supposed to!
9687     if (Selected)
9688       *Selected = SMOR.getMethod();
9689 
9690     if (TAH == Sema::TAH_ConsiderTrivialABI &&
9691         (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
9692       return SMOR.getMethod()->isTrivialForCall();
9693     return SMOR.getMethod()->isTrivial();
9694   }
9695 
9696   llvm_unreachable("unknown special method kind");
9697 }
9698 
9699 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
9700   for (auto *CI : RD->ctors())
9701     if (!CI->isImplicit())
9702       return CI;
9703 
9704   // Look for constructor templates.
9705   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
9706   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
9707     if (CXXConstructorDecl *CD =
9708           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
9709       return CD;
9710   }
9711 
9712   return nullptr;
9713 }
9714 
9715 /// The kind of subobject we are checking for triviality. The values of this
9716 /// enumeration are used in diagnostics.
9717 enum TrivialSubobjectKind {
9718   /// The subobject is a base class.
9719   TSK_BaseClass,
9720   /// The subobject is a non-static data member.
9721   TSK_Field,
9722   /// The object is actually the complete object.
9723   TSK_CompleteObject
9724 };
9725 
9726 /// Check whether the special member selected for a given type would be trivial.
9727 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
9728                                       QualType SubType, bool ConstRHS,
9729                                       Sema::CXXSpecialMember CSM,
9730                                       TrivialSubobjectKind Kind,
9731                                       Sema::TrivialABIHandling TAH, bool Diagnose) {
9732   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
9733   if (!SubRD)
9734     return true;
9735 
9736   CXXMethodDecl *Selected;
9737   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
9738                                ConstRHS, TAH, Diagnose ? &Selected : nullptr))
9739     return true;
9740 
9741   if (Diagnose) {
9742     if (ConstRHS)
9743       SubType.addConst();
9744 
9745     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
9746       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
9747         << Kind << SubType.getUnqualifiedType();
9748       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
9749         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
9750     } else if (!Selected)
9751       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
9752         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
9753     else if (Selected->isUserProvided()) {
9754       if (Kind == TSK_CompleteObject)
9755         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
9756           << Kind << SubType.getUnqualifiedType() << CSM;
9757       else {
9758         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
9759           << Kind << SubType.getUnqualifiedType() << CSM;
9760         S.Diag(Selected->getLocation(), diag::note_declared_at);
9761       }
9762     } else {
9763       if (Kind != TSK_CompleteObject)
9764         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
9765           << Kind << SubType.getUnqualifiedType() << CSM;
9766 
9767       // Explain why the defaulted or deleted special member isn't trivial.
9768       S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
9769                                Diagnose);
9770     }
9771   }
9772 
9773   return false;
9774 }
9775 
9776 /// Check whether the members of a class type allow a special member to be
9777 /// trivial.
9778 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
9779                                      Sema::CXXSpecialMember CSM,
9780                                      bool ConstArg,
9781                                      Sema::TrivialABIHandling TAH,
9782                                      bool Diagnose) {
9783   for (const auto *FI : RD->fields()) {
9784     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
9785       continue;
9786 
9787     QualType FieldType = S.Context.getBaseElementType(FI->getType());
9788 
9789     // Pretend anonymous struct or union members are members of this class.
9790     if (FI->isAnonymousStructOrUnion()) {
9791       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
9792                                     CSM, ConstArg, TAH, Diagnose))
9793         return false;
9794       continue;
9795     }
9796 
9797     // C++11 [class.ctor]p5:
9798     //   A default constructor is trivial if [...]
9799     //    -- no non-static data member of its class has a
9800     //       brace-or-equal-initializer
9801     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
9802       if (Diagnose)
9803         S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
9804             << FI;
9805       return false;
9806     }
9807 
9808     // Objective C ARC 4.3.5:
9809     //   [...] nontrivally ownership-qualified types are [...] not trivially
9810     //   default constructible, copy constructible, move constructible, copy
9811     //   assignable, move assignable, or destructible [...]
9812     if (FieldType.hasNonTrivialObjCLifetime()) {
9813       if (Diagnose)
9814         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
9815           << RD << FieldType.getObjCLifetime();
9816       return false;
9817     }
9818 
9819     bool ConstRHS = ConstArg && !FI->isMutable();
9820     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
9821                                    CSM, TSK_Field, TAH, Diagnose))
9822       return false;
9823   }
9824 
9825   return true;
9826 }
9827 
9828 /// Diagnose why the specified class does not have a trivial special member of
9829 /// the given kind.
9830 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
9831   QualType Ty = Context.getRecordType(RD);
9832 
9833   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
9834   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
9835                             TSK_CompleteObject, TAH_IgnoreTrivialABI,
9836                             /*Diagnose*/true);
9837 }
9838 
9839 /// Determine whether a defaulted or deleted special member function is trivial,
9840 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
9841 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
9842 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
9843                                   TrivialABIHandling TAH, bool Diagnose) {
9844   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
9845 
9846   CXXRecordDecl *RD = MD->getParent();
9847 
9848   bool ConstArg = false;
9849 
9850   // C++11 [class.copy]p12, p25: [DR1593]
9851   //   A [special member] is trivial if [...] its parameter-type-list is
9852   //   equivalent to the parameter-type-list of an implicit declaration [...]
9853   switch (CSM) {
9854   case CXXDefaultConstructor:
9855   case CXXDestructor:
9856     // Trivial default constructors and destructors cannot have parameters.
9857     break;
9858 
9859   case CXXCopyConstructor:
9860   case CXXCopyAssignment: {
9861     const ParmVarDecl *Param0 = MD->getParamDecl(0);
9862     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
9863 
9864     // When ClangABICompat14 is true, CXX copy constructors will only be trivial
9865     // if they are not user-provided and their parameter-type-list is equivalent
9866     // to the parameter-type-list of an implicit declaration. This maintains the
9867     // behavior before dr2171 was implemented.
9868     //
9869     // Otherwise, if ClangABICompat14 is false, All copy constructors can be
9870     // trivial, if they are not user-provided, regardless of the qualifiers on
9871     // the reference type.
9872     const bool ClangABICompat14 = Context.getLangOpts().getClangABICompat() <=
9873                                   LangOptions::ClangABI::Ver14;
9874     if (!RT ||
9875         ((RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) &&
9876          ClangABICompat14)) {
9877       if (Diagnose)
9878         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9879           << Param0->getSourceRange() << Param0->getType()
9880           << Context.getLValueReferenceType(
9881                Context.getRecordType(RD).withConst());
9882       return false;
9883     }
9884 
9885     ConstArg = RT->getPointeeType().isConstQualified();
9886     break;
9887   }
9888 
9889   case CXXMoveConstructor:
9890   case CXXMoveAssignment: {
9891     // Trivial move operations always have non-cv-qualified parameters.
9892     const ParmVarDecl *Param0 = MD->getParamDecl(0);
9893     const RValueReferenceType *RT =
9894       Param0->getType()->getAs<RValueReferenceType>();
9895     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
9896       if (Diagnose)
9897         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9898           << Param0->getSourceRange() << Param0->getType()
9899           << Context.getRValueReferenceType(Context.getRecordType(RD));
9900       return false;
9901     }
9902     break;
9903   }
9904 
9905   case CXXInvalid:
9906     llvm_unreachable("not a special member");
9907   }
9908 
9909   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
9910     if (Diagnose)
9911       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
9912            diag::note_nontrivial_default_arg)
9913         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
9914     return false;
9915   }
9916   if (MD->isVariadic()) {
9917     if (Diagnose)
9918       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
9919     return false;
9920   }
9921 
9922   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9923   //   A copy/move [constructor or assignment operator] is trivial if
9924   //    -- the [member] selected to copy/move each direct base class subobject
9925   //       is trivial
9926   //
9927   // C++11 [class.copy]p12, C++11 [class.copy]p25:
9928   //   A [default constructor or destructor] is trivial if
9929   //    -- all the direct base classes have trivial [default constructors or
9930   //       destructors]
9931   for (const auto &BI : RD->bases())
9932     if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
9933                                    ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
9934       return false;
9935 
9936   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9937   //   A copy/move [constructor or assignment operator] for a class X is
9938   //   trivial if
9939   //    -- for each non-static data member of X that is of class type (or array
9940   //       thereof), the constructor selected to copy/move that member is
9941   //       trivial
9942   //
9943   // C++11 [class.copy]p12, C++11 [class.copy]p25:
9944   //   A [default constructor or destructor] is trivial if
9945   //    -- for all of the non-static data members of its class that are of class
9946   //       type (or array thereof), each such class has a trivial [default
9947   //       constructor or destructor]
9948   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
9949     return false;
9950 
9951   // C++11 [class.dtor]p5:
9952   //   A destructor is trivial if [...]
9953   //    -- the destructor is not virtual
9954   if (CSM == CXXDestructor && MD->isVirtual()) {
9955     if (Diagnose)
9956       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
9957     return false;
9958   }
9959 
9960   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
9961   //   A [special member] for class X is trivial if [...]
9962   //    -- class X has no virtual functions and no virtual base classes
9963   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
9964     if (!Diagnose)
9965       return false;
9966 
9967     if (RD->getNumVBases()) {
9968       // Check for virtual bases. We already know that the corresponding
9969       // member in all bases is trivial, so vbases must all be direct.
9970       CXXBaseSpecifier &BS = *RD->vbases_begin();
9971       assert(BS.isVirtual());
9972       Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
9973       return false;
9974     }
9975 
9976     // Must have a virtual method.
9977     for (const auto *MI : RD->methods()) {
9978       if (MI->isVirtual()) {
9979         SourceLocation MLoc = MI->getBeginLoc();
9980         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
9981         return false;
9982       }
9983     }
9984 
9985     llvm_unreachable("dynamic class with no vbases and no virtual functions");
9986   }
9987 
9988   // Looks like it's trivial!
9989   return true;
9990 }
9991 
9992 namespace {
9993 struct FindHiddenVirtualMethod {
9994   Sema *S;
9995   CXXMethodDecl *Method;
9996   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
9997   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9998 
9999 private:
10000   /// Check whether any most overridden method from MD in Methods
10001   static bool CheckMostOverridenMethods(
10002       const CXXMethodDecl *MD,
10003       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
10004     if (MD->size_overridden_methods() == 0)
10005       return Methods.count(MD->getCanonicalDecl());
10006     for (const CXXMethodDecl *O : MD->overridden_methods())
10007       if (CheckMostOverridenMethods(O, Methods))
10008         return true;
10009     return false;
10010   }
10011 
10012 public:
10013   /// Member lookup function that determines whether a given C++
10014   /// method overloads virtual methods in a base class without overriding any,
10015   /// to be used with CXXRecordDecl::lookupInBases().
10016   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
10017     RecordDecl *BaseRecord =
10018         Specifier->getType()->castAs<RecordType>()->getDecl();
10019 
10020     DeclarationName Name = Method->getDeclName();
10021     assert(Name.getNameKind() == DeclarationName::Identifier);
10022 
10023     bool foundSameNameMethod = false;
10024     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
10025     for (Path.Decls = BaseRecord->lookup(Name).begin();
10026          Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
10027       NamedDecl *D = *Path.Decls;
10028       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
10029         MD = MD->getCanonicalDecl();
10030         foundSameNameMethod = true;
10031         // Interested only in hidden virtual methods.
10032         if (!MD->isVirtual())
10033           continue;
10034         // If the method we are checking overrides a method from its base
10035         // don't warn about the other overloaded methods. Clang deviates from
10036         // GCC by only diagnosing overloads of inherited virtual functions that
10037         // do not override any other virtual functions in the base. GCC's
10038         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
10039         // function from a base class. These cases may be better served by a
10040         // warning (not specific to virtual functions) on call sites when the
10041         // call would select a different function from the base class, were it
10042         // visible.
10043         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
10044         if (!S->IsOverload(Method, MD, false))
10045           return true;
10046         // Collect the overload only if its hidden.
10047         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
10048           overloadedMethods.push_back(MD);
10049       }
10050     }
10051 
10052     if (foundSameNameMethod)
10053       OverloadedMethods.append(overloadedMethods.begin(),
10054                                overloadedMethods.end());
10055     return foundSameNameMethod;
10056   }
10057 };
10058 } // end anonymous namespace
10059 
10060 /// Add the most overridden methods from MD to Methods
10061 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
10062                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
10063   if (MD->size_overridden_methods() == 0)
10064     Methods.insert(MD->getCanonicalDecl());
10065   else
10066     for (const CXXMethodDecl *O : MD->overridden_methods())
10067       AddMostOverridenMethods(O, Methods);
10068 }
10069 
10070 /// Check if a method overloads virtual methods in a base class without
10071 /// overriding any.
10072 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
10073                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10074   if (!MD->getDeclName().isIdentifier())
10075     return;
10076 
10077   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
10078                      /*bool RecordPaths=*/false,
10079                      /*bool DetectVirtual=*/false);
10080   FindHiddenVirtualMethod FHVM;
10081   FHVM.Method = MD;
10082   FHVM.S = this;
10083 
10084   // Keep the base methods that were overridden or introduced in the subclass
10085   // by 'using' in a set. A base method not in this set is hidden.
10086   CXXRecordDecl *DC = MD->getParent();
10087   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
10088   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
10089     NamedDecl *ND = *I;
10090     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
10091       ND = shad->getTargetDecl();
10092     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
10093       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
10094   }
10095 
10096   if (DC->lookupInBases(FHVM, Paths))
10097     OverloadedMethods = FHVM.OverloadedMethods;
10098 }
10099 
10100 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
10101                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10102   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
10103     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
10104     PartialDiagnostic PD = PDiag(
10105          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
10106     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
10107     Diag(overloadedMD->getLocation(), PD);
10108   }
10109 }
10110 
10111 /// Diagnose methods which overload virtual methods in a base class
10112 /// without overriding any.
10113 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
10114   if (MD->isInvalidDecl())
10115     return;
10116 
10117   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
10118     return;
10119 
10120   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10121   FindHiddenVirtualMethods(MD, OverloadedMethods);
10122   if (!OverloadedMethods.empty()) {
10123     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
10124       << MD << (OverloadedMethods.size() > 1);
10125 
10126     NoteHiddenVirtualMethods(MD, OverloadedMethods);
10127   }
10128 }
10129 
10130 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
10131   auto PrintDiagAndRemoveAttr = [&](unsigned N) {
10132     // No diagnostics if this is a template instantiation.
10133     if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) {
10134       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10135            diag::ext_cannot_use_trivial_abi) << &RD;
10136       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10137            diag::note_cannot_use_trivial_abi_reason) << &RD << N;
10138     }
10139     RD.dropAttr<TrivialABIAttr>();
10140   };
10141 
10142   // Ill-formed if the copy and move constructors are deleted.
10143   auto HasNonDeletedCopyOrMoveConstructor = [&]() {
10144     // If the type is dependent, then assume it might have
10145     // implicit copy or move ctor because we won't know yet at this point.
10146     if (RD.isDependentType())
10147       return true;
10148     if (RD.needsImplicitCopyConstructor() &&
10149         !RD.defaultedCopyConstructorIsDeleted())
10150       return true;
10151     if (RD.needsImplicitMoveConstructor() &&
10152         !RD.defaultedMoveConstructorIsDeleted())
10153       return true;
10154     for (const CXXConstructorDecl *CD : RD.ctors())
10155       if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
10156         return true;
10157     return false;
10158   };
10159 
10160   if (!HasNonDeletedCopyOrMoveConstructor()) {
10161     PrintDiagAndRemoveAttr(0);
10162     return;
10163   }
10164 
10165   // Ill-formed if the struct has virtual functions.
10166   if (RD.isPolymorphic()) {
10167     PrintDiagAndRemoveAttr(1);
10168     return;
10169   }
10170 
10171   for (const auto &B : RD.bases()) {
10172     // Ill-formed if the base class is non-trivial for the purpose of calls or a
10173     // virtual base.
10174     if (!B.getType()->isDependentType() &&
10175         !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
10176       PrintDiagAndRemoveAttr(2);
10177       return;
10178     }
10179 
10180     if (B.isVirtual()) {
10181       PrintDiagAndRemoveAttr(3);
10182       return;
10183     }
10184   }
10185 
10186   for (const auto *FD : RD.fields()) {
10187     // Ill-formed if the field is an ObjectiveC pointer or of a type that is
10188     // non-trivial for the purpose of calls.
10189     QualType FT = FD->getType();
10190     if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
10191       PrintDiagAndRemoveAttr(4);
10192       return;
10193     }
10194 
10195     if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
10196       if (!RT->isDependentType() &&
10197           !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
10198         PrintDiagAndRemoveAttr(5);
10199         return;
10200       }
10201   }
10202 }
10203 
10204 void Sema::ActOnFinishCXXMemberSpecification(
10205     Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
10206     SourceLocation RBrac, const ParsedAttributesView &AttrList) {
10207   if (!TagDecl)
10208     return;
10209 
10210   AdjustDeclIfTemplate(TagDecl);
10211 
10212   for (const ParsedAttr &AL : AttrList) {
10213     if (AL.getKind() != ParsedAttr::AT_Visibility)
10214       continue;
10215     AL.setInvalid();
10216     Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
10217   }
10218 
10219   ActOnFields(S, RLoc, TagDecl,
10220               llvm::ArrayRef(
10221                   // strict aliasing violation!
10222                   reinterpret_cast<Decl **>(FieldCollector->getCurFields()),
10223                   FieldCollector->getCurNumFields()),
10224               LBrac, RBrac, AttrList);
10225 
10226   CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));
10227 }
10228 
10229 /// Find the equality comparison functions that should be implicitly declared
10230 /// in a given class definition, per C++2a [class.compare.default]p3.
10231 static void findImplicitlyDeclaredEqualityComparisons(
10232     ASTContext &Ctx, CXXRecordDecl *RD,
10233     llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {
10234   DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
10235   if (!RD->lookup(EqEq).empty())
10236     // Member operator== explicitly declared: no implicit operator==s.
10237     return;
10238 
10239   // Traverse friends looking for an '==' or a '<=>'.
10240   for (FriendDecl *Friend : RD->friends()) {
10241     FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
10242     if (!FD) continue;
10243 
10244     if (FD->getOverloadedOperator() == OO_EqualEqual) {
10245       // Friend operator== explicitly declared: no implicit operator==s.
10246       Spaceships.clear();
10247       return;
10248     }
10249 
10250     if (FD->getOverloadedOperator() == OO_Spaceship &&
10251         FD->isExplicitlyDefaulted())
10252       Spaceships.push_back(FD);
10253   }
10254 
10255   // Look for members named 'operator<=>'.
10256   DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
10257   for (NamedDecl *ND : RD->lookup(Cmp)) {
10258     // Note that we could find a non-function here (either a function template
10259     // or a using-declaration). Neither case results in an implicit
10260     // 'operator=='.
10261     if (auto *FD = dyn_cast<FunctionDecl>(ND))
10262       if (FD->isExplicitlyDefaulted())
10263         Spaceships.push_back(FD);
10264   }
10265 }
10266 
10267 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
10268 /// special functions, such as the default constructor, copy
10269 /// constructor, or destructor, to the given C++ class (C++
10270 /// [special]p1).  This routine can only be executed just before the
10271 /// definition of the class is complete.
10272 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
10273   // Don't add implicit special members to templated classes.
10274   // FIXME: This means unqualified lookups for 'operator=' within a class
10275   // template don't work properly.
10276   if (!ClassDecl->isDependentType()) {
10277     if (ClassDecl->needsImplicitDefaultConstructor()) {
10278       ++getASTContext().NumImplicitDefaultConstructors;
10279 
10280       if (ClassDecl->hasInheritedConstructor())
10281         DeclareImplicitDefaultConstructor(ClassDecl);
10282     }
10283 
10284     if (ClassDecl->needsImplicitCopyConstructor()) {
10285       ++getASTContext().NumImplicitCopyConstructors;
10286 
10287       // If the properties or semantics of the copy constructor couldn't be
10288       // determined while the class was being declared, force a declaration
10289       // of it now.
10290       if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
10291           ClassDecl->hasInheritedConstructor())
10292         DeclareImplicitCopyConstructor(ClassDecl);
10293       // For the MS ABI we need to know whether the copy ctor is deleted. A
10294       // prerequisite for deleting the implicit copy ctor is that the class has
10295       // a move ctor or move assignment that is either user-declared or whose
10296       // semantics are inherited from a subobject. FIXME: We should provide a
10297       // more direct way for CodeGen to ask whether the constructor was deleted.
10298       else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10299                (ClassDecl->hasUserDeclaredMoveConstructor() ||
10300                 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10301                 ClassDecl->hasUserDeclaredMoveAssignment() ||
10302                 ClassDecl->needsOverloadResolutionForMoveAssignment()))
10303         DeclareImplicitCopyConstructor(ClassDecl);
10304     }
10305 
10306     if (getLangOpts().CPlusPlus11 &&
10307         ClassDecl->needsImplicitMoveConstructor()) {
10308       ++getASTContext().NumImplicitMoveConstructors;
10309 
10310       if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10311           ClassDecl->hasInheritedConstructor())
10312         DeclareImplicitMoveConstructor(ClassDecl);
10313     }
10314 
10315     if (ClassDecl->needsImplicitCopyAssignment()) {
10316       ++getASTContext().NumImplicitCopyAssignmentOperators;
10317 
10318       // If we have a dynamic class, then the copy assignment operator may be
10319       // virtual, so we have to declare it immediately. This ensures that, e.g.,
10320       // it shows up in the right place in the vtable and that we diagnose
10321       // problems with the implicit exception specification.
10322       if (ClassDecl->isDynamicClass() ||
10323           ClassDecl->needsOverloadResolutionForCopyAssignment() ||
10324           ClassDecl->hasInheritedAssignment())
10325         DeclareImplicitCopyAssignment(ClassDecl);
10326     }
10327 
10328     if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10329       ++getASTContext().NumImplicitMoveAssignmentOperators;
10330 
10331       // Likewise for the move assignment operator.
10332       if (ClassDecl->isDynamicClass() ||
10333           ClassDecl->needsOverloadResolutionForMoveAssignment() ||
10334           ClassDecl->hasInheritedAssignment())
10335         DeclareImplicitMoveAssignment(ClassDecl);
10336     }
10337 
10338     if (ClassDecl->needsImplicitDestructor()) {
10339       ++getASTContext().NumImplicitDestructors;
10340 
10341       // If we have a dynamic class, then the destructor may be virtual, so we
10342       // have to declare the destructor immediately. This ensures that, e.g., it
10343       // shows up in the right place in the vtable and that we diagnose problems
10344       // with the implicit exception specification.
10345       if (ClassDecl->isDynamicClass() ||
10346           ClassDecl->needsOverloadResolutionForDestructor())
10347         DeclareImplicitDestructor(ClassDecl);
10348     }
10349   }
10350 
10351   // C++2a [class.compare.default]p3:
10352   //   If the member-specification does not explicitly declare any member or
10353   //   friend named operator==, an == operator function is declared implicitly
10354   //   for each defaulted three-way comparison operator function defined in
10355   //   the member-specification
10356   // FIXME: Consider doing this lazily.
10357   // We do this during the initial parse for a class template, not during
10358   // instantiation, so that we can handle unqualified lookups for 'operator=='
10359   // when parsing the template.
10360   if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) {
10361     llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
10362     findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl,
10363                                               DefaultedSpaceships);
10364     for (auto *FD : DefaultedSpaceships)
10365       DeclareImplicitEqualityComparison(ClassDecl, FD);
10366   }
10367 }
10368 
10369 unsigned
10370 Sema::ActOnReenterTemplateScope(Decl *D,
10371                                 llvm::function_ref<Scope *()> EnterScope) {
10372   if (!D)
10373     return 0;
10374   AdjustDeclIfTemplate(D);
10375 
10376   // In order to get name lookup right, reenter template scopes in order from
10377   // outermost to innermost.
10378   SmallVector<TemplateParameterList *, 4> ParameterLists;
10379   DeclContext *LookupDC = dyn_cast<DeclContext>(D);
10380 
10381   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
10382     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
10383       ParameterLists.push_back(DD->getTemplateParameterList(i));
10384 
10385     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10386       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
10387         ParameterLists.push_back(FTD->getTemplateParameters());
10388     } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10389       LookupDC = VD->getDeclContext();
10390 
10391       if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())
10392         ParameterLists.push_back(VTD->getTemplateParameters());
10393       else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
10394         ParameterLists.push_back(PSD->getTemplateParameters());
10395     }
10396   } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
10397     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
10398       ParameterLists.push_back(TD->getTemplateParameterList(i));
10399 
10400     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
10401       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
10402         ParameterLists.push_back(CTD->getTemplateParameters());
10403       else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
10404         ParameterLists.push_back(PSD->getTemplateParameters());
10405     }
10406   }
10407   // FIXME: Alias declarations and concepts.
10408 
10409   unsigned Count = 0;
10410   Scope *InnermostTemplateScope = nullptr;
10411   for (TemplateParameterList *Params : ParameterLists) {
10412     // Ignore explicit specializations; they don't contribute to the template
10413     // depth.
10414     if (Params->size() == 0)
10415       continue;
10416 
10417     InnermostTemplateScope = EnterScope();
10418     for (NamedDecl *Param : *Params) {
10419       if (Param->getDeclName()) {
10420         InnermostTemplateScope->AddDecl(Param);
10421         IdResolver.AddDecl(Param);
10422       }
10423     }
10424     ++Count;
10425   }
10426 
10427   // Associate the new template scopes with the corresponding entities.
10428   if (InnermostTemplateScope) {
10429     assert(LookupDC && "no enclosing DeclContext for template lookup");
10430     EnterTemplatedContext(InnermostTemplateScope, LookupDC);
10431   }
10432 
10433   return Count;
10434 }
10435 
10436 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10437   if (!RecordD) return;
10438   AdjustDeclIfTemplate(RecordD);
10439   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
10440   PushDeclContext(S, Record);
10441 }
10442 
10443 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10444   if (!RecordD) return;
10445   PopDeclContext();
10446 }
10447 
10448 /// This is used to implement the constant expression evaluation part of the
10449 /// attribute enable_if extension. There is nothing in standard C++ which would
10450 /// require reentering parameters.
10451 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
10452   if (!Param)
10453     return;
10454 
10455   S->AddDecl(Param);
10456   if (Param->getDeclName())
10457     IdResolver.AddDecl(Param);
10458 }
10459 
10460 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
10461 /// parsing a top-level (non-nested) C++ class, and we are now
10462 /// parsing those parts of the given Method declaration that could
10463 /// not be parsed earlier (C++ [class.mem]p2), such as default
10464 /// arguments. This action should enter the scope of the given
10465 /// Method declaration as if we had just parsed the qualified method
10466 /// name. However, it should not bring the parameters into scope;
10467 /// that will be performed by ActOnDelayedCXXMethodParameter.
10468 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10469 }
10470 
10471 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
10472 /// C++ method declaration. We're (re-)introducing the given
10473 /// function parameter into scope for use in parsing later parts of
10474 /// the method declaration. For example, we could see an
10475 /// ActOnParamDefaultArgument event for this parameter.
10476 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
10477   if (!ParamD)
10478     return;
10479 
10480   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
10481 
10482   S->AddDecl(Param);
10483   if (Param->getDeclName())
10484     IdResolver.AddDecl(Param);
10485 }
10486 
10487 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
10488 /// processing the delayed method declaration for Method. The method
10489 /// declaration is now considered finished. There may be a separate
10490 /// ActOnStartOfFunctionDef action later (not necessarily
10491 /// immediately!) for this method, if it was also defined inside the
10492 /// class body.
10493 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10494   if (!MethodD)
10495     return;
10496 
10497   AdjustDeclIfTemplate(MethodD);
10498 
10499   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
10500 
10501   // Now that we have our default arguments, check the constructor
10502   // again. It could produce additional diagnostics or affect whether
10503   // the class has implicitly-declared destructors, among other
10504   // things.
10505   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
10506     CheckConstructor(Constructor);
10507 
10508   // Check the default arguments, which we may have added.
10509   if (!Method->isInvalidDecl())
10510     CheckCXXDefaultArguments(Method);
10511 }
10512 
10513 // Emit the given diagnostic for each non-address-space qualifier.
10514 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
10515 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10516   const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10517   if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10518     bool DiagOccured = false;
10519     FTI.MethodQualifiers->forEachQualifier(
10520         [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10521                                    SourceLocation SL) {
10522           // This diagnostic should be emitted on any qualifier except an addr
10523           // space qualifier. However, forEachQualifier currently doesn't visit
10524           // addr space qualifiers, so there's no way to write this condition
10525           // right now; we just diagnose on everything.
10526           S.Diag(SL, DiagID) << QualName << SourceRange(SL);
10527           DiagOccured = true;
10528         });
10529     if (DiagOccured)
10530       D.setInvalidType();
10531   }
10532 }
10533 
10534 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
10535 /// the well-formedness of the constructor declarator @p D with type @p
10536 /// R. If there are any errors in the declarator, this routine will
10537 /// emit diagnostics and set the invalid bit to true.  In any case, the type
10538 /// will be updated to reflect a well-formed type for the constructor and
10539 /// returned.
10540 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
10541                                           StorageClass &SC) {
10542   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10543 
10544   // C++ [class.ctor]p3:
10545   //   A constructor shall not be virtual (10.3) or static (9.4). A
10546   //   constructor can be invoked for a const, volatile or const
10547   //   volatile object. A constructor shall not be declared const,
10548   //   volatile, or const volatile (9.3.2).
10549   if (isVirtual) {
10550     if (!D.isInvalidType())
10551       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10552         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
10553         << SourceRange(D.getIdentifierLoc());
10554     D.setInvalidType();
10555   }
10556   if (SC == SC_Static) {
10557     if (!D.isInvalidType())
10558       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10559         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10560         << SourceRange(D.getIdentifierLoc());
10561     D.setInvalidType();
10562     SC = SC_None;
10563   }
10564 
10565   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10566     diagnoseIgnoredQualifiers(
10567         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
10568         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
10569         D.getDeclSpec().getRestrictSpecLoc(),
10570         D.getDeclSpec().getAtomicSpecLoc());
10571     D.setInvalidType();
10572   }
10573 
10574   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
10575 
10576   // C++0x [class.ctor]p4:
10577   //   A constructor shall not be declared with a ref-qualifier.
10578   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10579   if (FTI.hasRefQualifier()) {
10580     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
10581       << FTI.RefQualifierIsLValueRef
10582       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10583     D.setInvalidType();
10584   }
10585 
10586   // Rebuild the function type "R" without any type qualifiers (in
10587   // case any of the errors above fired) and with "void" as the
10588   // return type, since constructors don't have return types.
10589   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10590   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
10591     return R;
10592 
10593   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10594   EPI.TypeQuals = Qualifiers();
10595   EPI.RefQualifier = RQ_None;
10596 
10597   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
10598 }
10599 
10600 /// CheckConstructor - Checks a fully-formed constructor for
10601 /// well-formedness, issuing any diagnostics required. Returns true if
10602 /// the constructor declarator is invalid.
10603 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
10604   CXXRecordDecl *ClassDecl
10605     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
10606   if (!ClassDecl)
10607     return Constructor->setInvalidDecl();
10608 
10609   // C++ [class.copy]p3:
10610   //   A declaration of a constructor for a class X is ill-formed if
10611   //   its first parameter is of type (optionally cv-qualified) X and
10612   //   either there are no other parameters or else all other
10613   //   parameters have default arguments.
10614   if (!Constructor->isInvalidDecl() &&
10615       Constructor->hasOneParamOrDefaultArgs() &&
10616       Constructor->getTemplateSpecializationKind() !=
10617           TSK_ImplicitInstantiation) {
10618     QualType ParamType = Constructor->getParamDecl(0)->getType();
10619     QualType ClassTy = Context.getTagDeclType(ClassDecl);
10620     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
10621       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
10622       const char *ConstRef
10623         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
10624                                                         : " const &";
10625       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
10626         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
10627 
10628       // FIXME: Rather that making the constructor invalid, we should endeavor
10629       // to fix the type.
10630       Constructor->setInvalidDecl();
10631     }
10632   }
10633 }
10634 
10635 /// CheckDestructor - Checks a fully-formed destructor definition for
10636 /// well-formedness, issuing any diagnostics required.  Returns true
10637 /// on error.
10638 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
10639   CXXRecordDecl *RD = Destructor->getParent();
10640 
10641   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
10642     SourceLocation Loc;
10643 
10644     if (!Destructor->isImplicit())
10645       Loc = Destructor->getLocation();
10646     else
10647       Loc = RD->getLocation();
10648 
10649     // If we have a virtual destructor, look up the deallocation function
10650     if (FunctionDecl *OperatorDelete =
10651             FindDeallocationFunctionForDestructor(Loc, RD)) {
10652       Expr *ThisArg = nullptr;
10653 
10654       // If the notional 'delete this' expression requires a non-trivial
10655       // conversion from 'this' to the type of a destroying operator delete's
10656       // first parameter, perform that conversion now.
10657       if (OperatorDelete->isDestroyingOperatorDelete()) {
10658         QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
10659         if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
10660           // C++ [class.dtor]p13:
10661           //   ... as if for the expression 'delete this' appearing in a
10662           //   non-virtual destructor of the destructor's class.
10663           ContextRAII SwitchContext(*this, Destructor);
10664           ExprResult This =
10665               ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
10666           assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
10667           This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
10668           if (This.isInvalid()) {
10669             // FIXME: Register this as a context note so that it comes out
10670             // in the right order.
10671             Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
10672             return true;
10673           }
10674           ThisArg = This.get();
10675         }
10676       }
10677 
10678       DiagnoseUseOfDecl(OperatorDelete, Loc);
10679       MarkFunctionReferenced(Loc, OperatorDelete);
10680       Destructor->setOperatorDelete(OperatorDelete, ThisArg);
10681     }
10682   }
10683 
10684   return false;
10685 }
10686 
10687 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
10688 /// the well-formednes of the destructor declarator @p D with type @p
10689 /// R. If there are any errors in the declarator, this routine will
10690 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
10691 /// will be updated to reflect a well-formed type for the destructor and
10692 /// returned.
10693 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
10694                                          StorageClass& SC) {
10695   // C++ [class.dtor]p1:
10696   //   [...] A typedef-name that names a class is a class-name
10697   //   (7.1.3); however, a typedef-name that names a class shall not
10698   //   be used as the identifier in the declarator for a destructor
10699   //   declaration.
10700   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
10701   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
10702     Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10703       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
10704   else if (const TemplateSpecializationType *TST =
10705              DeclaratorType->getAs<TemplateSpecializationType>())
10706     if (TST->isTypeAlias())
10707       Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10708         << DeclaratorType << 1;
10709 
10710   // C++ [class.dtor]p2:
10711   //   A destructor is used to destroy objects of its class type. A
10712   //   destructor takes no parameters, and no return type can be
10713   //   specified for it (not even void). The address of a destructor
10714   //   shall not be taken. A destructor shall not be static. A
10715   //   destructor can be invoked for a const, volatile or const
10716   //   volatile object. A destructor shall not be declared const,
10717   //   volatile or const volatile (9.3.2).
10718   if (SC == SC_Static) {
10719     if (!D.isInvalidType())
10720       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
10721         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10722         << SourceRange(D.getIdentifierLoc())
10723         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10724 
10725     SC = SC_None;
10726   }
10727   if (!D.isInvalidType()) {
10728     // Destructors don't have return types, but the parser will
10729     // happily parse something like:
10730     //
10731     //   class X {
10732     //     float ~X();
10733     //   };
10734     //
10735     // The return type will be eliminated later.
10736     if (D.getDeclSpec().hasTypeSpecifier())
10737       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
10738         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
10739         << SourceRange(D.getIdentifierLoc());
10740     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10741       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
10742                                 SourceLocation(),
10743                                 D.getDeclSpec().getConstSpecLoc(),
10744                                 D.getDeclSpec().getVolatileSpecLoc(),
10745                                 D.getDeclSpec().getRestrictSpecLoc(),
10746                                 D.getDeclSpec().getAtomicSpecLoc());
10747       D.setInvalidType();
10748     }
10749   }
10750 
10751   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
10752 
10753   // C++0x [class.dtor]p2:
10754   //   A destructor shall not be declared with a ref-qualifier.
10755   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10756   if (FTI.hasRefQualifier()) {
10757     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
10758       << FTI.RefQualifierIsLValueRef
10759       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10760     D.setInvalidType();
10761   }
10762 
10763   // Make sure we don't have any parameters.
10764   if (FTIHasNonVoidParameters(FTI)) {
10765     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
10766 
10767     // Delete the parameters.
10768     FTI.freeParams();
10769     D.setInvalidType();
10770   }
10771 
10772   // Make sure the destructor isn't variadic.
10773   if (FTI.isVariadic) {
10774     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
10775     D.setInvalidType();
10776   }
10777 
10778   // Rebuild the function type "R" without any type qualifiers or
10779   // parameters (in case any of the errors above fired) and with
10780   // "void" as the return type, since destructors don't have return
10781   // types.
10782   if (!D.isInvalidType())
10783     return R;
10784 
10785   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10786   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10787   EPI.Variadic = false;
10788   EPI.TypeQuals = Qualifiers();
10789   EPI.RefQualifier = RQ_None;
10790   return Context.getFunctionType(Context.VoidTy, std::nullopt, EPI);
10791 }
10792 
10793 static void extendLeft(SourceRange &R, SourceRange Before) {
10794   if (Before.isInvalid())
10795     return;
10796   R.setBegin(Before.getBegin());
10797   if (R.getEnd().isInvalid())
10798     R.setEnd(Before.getEnd());
10799 }
10800 
10801 static void extendRight(SourceRange &R, SourceRange After) {
10802   if (After.isInvalid())
10803     return;
10804   if (R.getBegin().isInvalid())
10805     R.setBegin(After.getBegin());
10806   R.setEnd(After.getEnd());
10807 }
10808 
10809 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
10810 /// well-formednes of the conversion function declarator @p D with
10811 /// type @p R. If there are any errors in the declarator, this routine
10812 /// will emit diagnostics and return true. Otherwise, it will return
10813 /// false. Either way, the type @p R will be updated to reflect a
10814 /// well-formed type for the conversion operator.
10815 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
10816                                      StorageClass& SC) {
10817   // C++ [class.conv.fct]p1:
10818   //   Neither parameter types nor return type can be specified. The
10819   //   type of a conversion function (8.3.5) is "function taking no
10820   //   parameter returning conversion-type-id."
10821   if (SC == SC_Static) {
10822     if (!D.isInvalidType())
10823       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
10824         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10825         << D.getName().getSourceRange();
10826     D.setInvalidType();
10827     SC = SC_None;
10828   }
10829 
10830   TypeSourceInfo *ConvTSI = nullptr;
10831   QualType ConvType =
10832       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
10833 
10834   const DeclSpec &DS = D.getDeclSpec();
10835   if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
10836     // Conversion functions don't have return types, but the parser will
10837     // happily parse something like:
10838     //
10839     //   class X {
10840     //     float operator bool();
10841     //   };
10842     //
10843     // The return type will be changed later anyway.
10844     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
10845       << SourceRange(DS.getTypeSpecTypeLoc())
10846       << SourceRange(D.getIdentifierLoc());
10847     D.setInvalidType();
10848   } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
10849     // It's also plausible that the user writes type qualifiers in the wrong
10850     // place, such as:
10851     //   struct S { const operator int(); };
10852     // FIXME: we could provide a fixit to move the qualifiers onto the
10853     // conversion type.
10854     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
10855         << SourceRange(D.getIdentifierLoc()) << 0;
10856     D.setInvalidType();
10857   }
10858 
10859   const auto *Proto = R->castAs<FunctionProtoType>();
10860 
10861   // Make sure we don't have any parameters.
10862   if (Proto->getNumParams() > 0) {
10863     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
10864 
10865     // Delete the parameters.
10866     D.getFunctionTypeInfo().freeParams();
10867     D.setInvalidType();
10868   } else if (Proto->isVariadic()) {
10869     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
10870     D.setInvalidType();
10871   }
10872 
10873   // Diagnose "&operator bool()" and other such nonsense.  This
10874   // is actually a gcc extension which we don't support.
10875   if (Proto->getReturnType() != ConvType) {
10876     bool NeedsTypedef = false;
10877     SourceRange Before, After;
10878 
10879     // Walk the chunks and extract information on them for our diagnostic.
10880     bool PastFunctionChunk = false;
10881     for (auto &Chunk : D.type_objects()) {
10882       switch (Chunk.Kind) {
10883       case DeclaratorChunk::Function:
10884         if (!PastFunctionChunk) {
10885           if (Chunk.Fun.HasTrailingReturnType) {
10886             TypeSourceInfo *TRT = nullptr;
10887             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
10888             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
10889           }
10890           PastFunctionChunk = true;
10891           break;
10892         }
10893         [[fallthrough]];
10894       case DeclaratorChunk::Array:
10895         NeedsTypedef = true;
10896         extendRight(After, Chunk.getSourceRange());
10897         break;
10898 
10899       case DeclaratorChunk::Pointer:
10900       case DeclaratorChunk::BlockPointer:
10901       case DeclaratorChunk::Reference:
10902       case DeclaratorChunk::MemberPointer:
10903       case DeclaratorChunk::Pipe:
10904         extendLeft(Before, Chunk.getSourceRange());
10905         break;
10906 
10907       case DeclaratorChunk::Paren:
10908         extendLeft(Before, Chunk.Loc);
10909         extendRight(After, Chunk.EndLoc);
10910         break;
10911       }
10912     }
10913 
10914     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
10915                          After.isValid()  ? After.getBegin() :
10916                                             D.getIdentifierLoc();
10917     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
10918     DB << Before << After;
10919 
10920     if (!NeedsTypedef) {
10921       DB << /*don't need a typedef*/0;
10922 
10923       // If we can provide a correct fix-it hint, do so.
10924       if (After.isInvalid() && ConvTSI) {
10925         SourceLocation InsertLoc =
10926             getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
10927         DB << FixItHint::CreateInsertion(InsertLoc, " ")
10928            << FixItHint::CreateInsertionFromRange(
10929                   InsertLoc, CharSourceRange::getTokenRange(Before))
10930            << FixItHint::CreateRemoval(Before);
10931       }
10932     } else if (!Proto->getReturnType()->isDependentType()) {
10933       DB << /*typedef*/1 << Proto->getReturnType();
10934     } else if (getLangOpts().CPlusPlus11) {
10935       DB << /*alias template*/2 << Proto->getReturnType();
10936     } else {
10937       DB << /*might not be fixable*/3;
10938     }
10939 
10940     // Recover by incorporating the other type chunks into the result type.
10941     // Note, this does *not* change the name of the function. This is compatible
10942     // with the GCC extension:
10943     //   struct S { &operator int(); } s;
10944     //   int &r = s.operator int(); // ok in GCC
10945     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
10946     ConvType = Proto->getReturnType();
10947   }
10948 
10949   // C++ [class.conv.fct]p4:
10950   //   The conversion-type-id shall not represent a function type nor
10951   //   an array type.
10952   if (ConvType->isArrayType()) {
10953     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
10954     ConvType = Context.getPointerType(ConvType);
10955     D.setInvalidType();
10956   } else if (ConvType->isFunctionType()) {
10957     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
10958     ConvType = Context.getPointerType(ConvType);
10959     D.setInvalidType();
10960   }
10961 
10962   // Rebuild the function type "R" without any parameters (in case any
10963   // of the errors above fired) and with the conversion type as the
10964   // return type.
10965   if (D.isInvalidType())
10966     R = Context.getFunctionType(ConvType, std::nullopt,
10967                                 Proto->getExtProtoInfo());
10968 
10969   // C++0x explicit conversion operators.
10970   if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20)
10971     Diag(DS.getExplicitSpecLoc(),
10972          getLangOpts().CPlusPlus11
10973              ? diag::warn_cxx98_compat_explicit_conversion_functions
10974              : diag::ext_explicit_conversion_functions)
10975         << SourceRange(DS.getExplicitSpecRange());
10976 }
10977 
10978 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
10979 /// the declaration of the given C++ conversion function. This routine
10980 /// is responsible for recording the conversion function in the C++
10981 /// class, if possible.
10982 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
10983   assert(Conversion && "Expected to receive a conversion function declaration");
10984 
10985   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
10986 
10987   // Make sure we aren't redeclaring the conversion function.
10988   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
10989   // C++ [class.conv.fct]p1:
10990   //   [...] A conversion function is never used to convert a
10991   //   (possibly cv-qualified) object to the (possibly cv-qualified)
10992   //   same object type (or a reference to it), to a (possibly
10993   //   cv-qualified) base class of that type (or a reference to it),
10994   //   or to (possibly cv-qualified) void.
10995   QualType ClassType
10996     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10997   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
10998     ConvType = ConvTypeRef->getPointeeType();
10999   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
11000       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
11001     /* Suppress diagnostics for instantiations. */;
11002   else if (Conversion->size_overridden_methods() != 0)
11003     /* Suppress diagnostics for overriding virtual function in a base class. */;
11004   else if (ConvType->isRecordType()) {
11005     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
11006     if (ConvType == ClassType)
11007       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
11008         << ClassType;
11009     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
11010       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
11011         <<  ClassType << ConvType;
11012   } else if (ConvType->isVoidType()) {
11013     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
11014       << ClassType << ConvType;
11015   }
11016 
11017   if (FunctionTemplateDecl *ConversionTemplate
11018                                 = Conversion->getDescribedFunctionTemplate())
11019     return ConversionTemplate;
11020 
11021   return Conversion;
11022 }
11023 
11024 namespace {
11025 /// Utility class to accumulate and print a diagnostic listing the invalid
11026 /// specifier(s) on a declaration.
11027 struct BadSpecifierDiagnoser {
11028   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
11029       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
11030   ~BadSpecifierDiagnoser() {
11031     Diagnostic << Specifiers;
11032   }
11033 
11034   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
11035     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
11036   }
11037   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
11038     return check(SpecLoc,
11039                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
11040   }
11041   void check(SourceLocation SpecLoc, const char *Spec) {
11042     if (SpecLoc.isInvalid()) return;
11043     Diagnostic << SourceRange(SpecLoc, SpecLoc);
11044     if (!Specifiers.empty()) Specifiers += " ";
11045     Specifiers += Spec;
11046   }
11047 
11048   Sema &S;
11049   Sema::SemaDiagnosticBuilder Diagnostic;
11050   std::string Specifiers;
11051 };
11052 }
11053 
11054 /// Check the validity of a declarator that we parsed for a deduction-guide.
11055 /// These aren't actually declarators in the grammar, so we need to check that
11056 /// the user didn't specify any pieces that are not part of the deduction-guide
11057 /// grammar.
11058 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
11059                                          StorageClass &SC) {
11060   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
11061   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
11062   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
11063 
11064   // C++ [temp.deduct.guide]p3:
11065   //   A deduction-gide shall be declared in the same scope as the
11066   //   corresponding class template.
11067   if (!CurContext->getRedeclContext()->Equals(
11068           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
11069     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
11070       << GuidedTemplateDecl;
11071     Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
11072   }
11073 
11074   auto &DS = D.getMutableDeclSpec();
11075   // We leave 'friend' and 'virtual' to be rejected in the normal way.
11076   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
11077       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
11078       DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
11079     BadSpecifierDiagnoser Diagnoser(
11080         *this, D.getIdentifierLoc(),
11081         diag::err_deduction_guide_invalid_specifier);
11082 
11083     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
11084     DS.ClearStorageClassSpecs();
11085     SC = SC_None;
11086 
11087     // 'explicit' is permitted.
11088     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
11089     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
11090     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
11091     DS.ClearConstexprSpec();
11092 
11093     Diagnoser.check(DS.getConstSpecLoc(), "const");
11094     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
11095     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
11096     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
11097     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
11098     DS.ClearTypeQualifiers();
11099 
11100     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
11101     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
11102     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
11103     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
11104     DS.ClearTypeSpecType();
11105   }
11106 
11107   if (D.isInvalidType())
11108     return;
11109 
11110   // Check the declarator is simple enough.
11111   bool FoundFunction = false;
11112   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
11113     if (Chunk.Kind == DeclaratorChunk::Paren)
11114       continue;
11115     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
11116       Diag(D.getDeclSpec().getBeginLoc(),
11117            diag::err_deduction_guide_with_complex_decl)
11118           << D.getSourceRange();
11119       break;
11120     }
11121     if (!Chunk.Fun.hasTrailingReturnType()) {
11122       Diag(D.getName().getBeginLoc(),
11123            diag::err_deduction_guide_no_trailing_return_type);
11124       break;
11125     }
11126 
11127     // Check that the return type is written as a specialization of
11128     // the template specified as the deduction-guide's name.
11129     // The template name may not be qualified. [temp.deduct.guide]
11130     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
11131     TypeSourceInfo *TSI = nullptr;
11132     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
11133     assert(TSI && "deduction guide has valid type but invalid return type?");
11134     bool AcceptableReturnType = false;
11135     bool MightInstantiateToSpecialization = false;
11136     if (auto RetTST =
11137             TSI->getTypeLoc().getAsAdjusted<TemplateSpecializationTypeLoc>()) {
11138       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
11139       bool TemplateMatches =
11140           Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
11141       auto TKind = SpecifiedName.getKind();
11142       // A Using TemplateName can't actually be valid (either it's qualified, or
11143       // we're in the wrong scope). But we have diagnosed these problems
11144       // already.
11145       bool SimplyWritten = TKind == TemplateName::Template ||
11146                            TKind == TemplateName::UsingTemplate;
11147       if (SimplyWritten && TemplateMatches)
11148         AcceptableReturnType = true;
11149       else {
11150         // This could still instantiate to the right type, unless we know it
11151         // names the wrong class template.
11152         auto *TD = SpecifiedName.getAsTemplateDecl();
11153         MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
11154                                              !TemplateMatches);
11155       }
11156     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
11157       MightInstantiateToSpecialization = true;
11158     }
11159 
11160     if (!AcceptableReturnType) {
11161       Diag(TSI->getTypeLoc().getBeginLoc(),
11162            diag::err_deduction_guide_bad_trailing_return_type)
11163           << GuidedTemplate << TSI->getType()
11164           << MightInstantiateToSpecialization
11165           << TSI->getTypeLoc().getSourceRange();
11166     }
11167 
11168     // Keep going to check that we don't have any inner declarator pieces (we
11169     // could still have a function returning a pointer to a function).
11170     FoundFunction = true;
11171   }
11172 
11173   if (D.isFunctionDefinition())
11174     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
11175 }
11176 
11177 //===----------------------------------------------------------------------===//
11178 // Namespace Handling
11179 //===----------------------------------------------------------------------===//
11180 
11181 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
11182 /// reopened.
11183 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
11184                                             SourceLocation Loc,
11185                                             IdentifierInfo *II, bool *IsInline,
11186                                             NamespaceDecl *PrevNS) {
11187   assert(*IsInline != PrevNS->isInline());
11188 
11189   // 'inline' must appear on the original definition, but not necessarily
11190   // on all extension definitions, so the note should point to the first
11191   // definition to avoid confusion.
11192   PrevNS = PrevNS->getFirstDecl();
11193 
11194   if (PrevNS->isInline())
11195     // The user probably just forgot the 'inline', so suggest that it
11196     // be added back.
11197     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
11198       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
11199   else
11200     S.Diag(Loc, diag::err_inline_namespace_mismatch);
11201 
11202   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
11203   *IsInline = PrevNS->isInline();
11204 }
11205 
11206 /// ActOnStartNamespaceDef - This is called at the start of a namespace
11207 /// definition.
11208 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
11209                                    SourceLocation InlineLoc,
11210                                    SourceLocation NamespaceLoc,
11211                                    SourceLocation IdentLoc, IdentifierInfo *II,
11212                                    SourceLocation LBrace,
11213                                    const ParsedAttributesView &AttrList,
11214                                    UsingDirectiveDecl *&UD, bool IsNested) {
11215   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
11216   // For anonymous namespace, take the location of the left brace.
11217   SourceLocation Loc = II ? IdentLoc : LBrace;
11218   bool IsInline = InlineLoc.isValid();
11219   bool IsInvalid = false;
11220   bool IsStd = false;
11221   bool AddToKnown = false;
11222   Scope *DeclRegionScope = NamespcScope->getParent();
11223 
11224   NamespaceDecl *PrevNS = nullptr;
11225   if (II) {
11226     // C++ [namespace.def]p2:
11227     //   The identifier in an original-namespace-definition shall not
11228     //   have been previously defined in the declarative region in
11229     //   which the original-namespace-definition appears. The
11230     //   identifier in an original-namespace-definition is the name of
11231     //   the namespace. Subsequently in that declarative region, it is
11232     //   treated as an original-namespace-name.
11233     //
11234     // Since namespace names are unique in their scope, and we don't
11235     // look through using directives, just look for any ordinary names
11236     // as if by qualified name lookup.
11237     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
11238                    ForExternalRedeclaration);
11239     LookupQualifiedName(R, CurContext->getRedeclContext());
11240     NamedDecl *PrevDecl =
11241         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
11242     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
11243 
11244     if (PrevNS) {
11245       // This is an extended namespace definition.
11246       if (IsInline != PrevNS->isInline())
11247         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
11248                                         &IsInline, PrevNS);
11249     } else if (PrevDecl) {
11250       // This is an invalid name redefinition.
11251       Diag(Loc, diag::err_redefinition_different_kind)
11252         << II;
11253       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11254       IsInvalid = true;
11255       // Continue on to push Namespc as current DeclContext and return it.
11256     } else if (II->isStr("std") &&
11257                CurContext->getRedeclContext()->isTranslationUnit()) {
11258       // This is the first "real" definition of the namespace "std", so update
11259       // our cache of the "std" namespace to point at this definition.
11260       PrevNS = getStdNamespace();
11261       IsStd = true;
11262       AddToKnown = !IsInline;
11263     } else {
11264       // We've seen this namespace for the first time.
11265       AddToKnown = !IsInline;
11266     }
11267   } else {
11268     // Anonymous namespaces.
11269 
11270     // Determine whether the parent already has an anonymous namespace.
11271     DeclContext *Parent = CurContext->getRedeclContext();
11272     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11273       PrevNS = TU->getAnonymousNamespace();
11274     } else {
11275       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
11276       PrevNS = ND->getAnonymousNamespace();
11277     }
11278 
11279     if (PrevNS && IsInline != PrevNS->isInline())
11280       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
11281                                       &IsInline, PrevNS);
11282   }
11283 
11284   NamespaceDecl *Namespc = NamespaceDecl::Create(
11285       Context, CurContext, IsInline, StartLoc, Loc, II, PrevNS, IsNested);
11286   if (IsInvalid)
11287     Namespc->setInvalidDecl();
11288 
11289   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
11290   AddPragmaAttributes(DeclRegionScope, Namespc);
11291 
11292   // FIXME: Should we be merging attributes?
11293   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
11294     PushNamespaceVisibilityAttr(Attr, Loc);
11295 
11296   if (IsStd)
11297     StdNamespace = Namespc;
11298   if (AddToKnown)
11299     KnownNamespaces[Namespc] = false;
11300 
11301   if (II) {
11302     PushOnScopeChains(Namespc, DeclRegionScope);
11303   } else {
11304     // Link the anonymous namespace into its parent.
11305     DeclContext *Parent = CurContext->getRedeclContext();
11306     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11307       TU->setAnonymousNamespace(Namespc);
11308     } else {
11309       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
11310     }
11311 
11312     CurContext->addDecl(Namespc);
11313 
11314     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
11315     //   behaves as if it were replaced by
11316     //     namespace unique { /* empty body */ }
11317     //     using namespace unique;
11318     //     namespace unique { namespace-body }
11319     //   where all occurrences of 'unique' in a translation unit are
11320     //   replaced by the same identifier and this identifier differs
11321     //   from all other identifiers in the entire program.
11322 
11323     // We just create the namespace with an empty name and then add an
11324     // implicit using declaration, just like the standard suggests.
11325     //
11326     // CodeGen enforces the "universally unique" aspect by giving all
11327     // declarations semantically contained within an anonymous
11328     // namespace internal linkage.
11329 
11330     if (!PrevNS) {
11331       UD = UsingDirectiveDecl::Create(Context, Parent,
11332                                       /* 'using' */ LBrace,
11333                                       /* 'namespace' */ SourceLocation(),
11334                                       /* qualifier */ NestedNameSpecifierLoc(),
11335                                       /* identifier */ SourceLocation(),
11336                                       Namespc,
11337                                       /* Ancestor */ Parent);
11338       UD->setImplicit();
11339       Parent->addDecl(UD);
11340     }
11341   }
11342 
11343   ActOnDocumentableDecl(Namespc);
11344 
11345   // Although we could have an invalid decl (i.e. the namespace name is a
11346   // redefinition), push it as current DeclContext and try to continue parsing.
11347   // FIXME: We should be able to push Namespc here, so that the each DeclContext
11348   // for the namespace has the declarations that showed up in that particular
11349   // namespace definition.
11350   PushDeclContext(NamespcScope, Namespc);
11351   return Namespc;
11352 }
11353 
11354 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
11355 /// is a namespace alias, returns the namespace it points to.
11356 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
11357   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
11358     return AD->getNamespace();
11359   return dyn_cast_or_null<NamespaceDecl>(D);
11360 }
11361 
11362 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
11363 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
11364 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
11365   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
11366   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
11367   Namespc->setRBraceLoc(RBrace);
11368   PopDeclContext();
11369   if (Namespc->hasAttr<VisibilityAttr>())
11370     PopPragmaVisibility(true, RBrace);
11371   // If this namespace contains an export-declaration, export it now.
11372   if (DeferredExportedNamespaces.erase(Namespc))
11373     Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
11374 }
11375 
11376 CXXRecordDecl *Sema::getStdBadAlloc() const {
11377   return cast_or_null<CXXRecordDecl>(
11378                                   StdBadAlloc.get(Context.getExternalSource()));
11379 }
11380 
11381 EnumDecl *Sema::getStdAlignValT() const {
11382   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
11383 }
11384 
11385 NamespaceDecl *Sema::getStdNamespace() const {
11386   return cast_or_null<NamespaceDecl>(
11387                                  StdNamespace.get(Context.getExternalSource()));
11388 }
11389 
11390 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
11391   if (!StdExperimentalNamespaceCache) {
11392     if (auto Std = getStdNamespace()) {
11393       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
11394                           SourceLocation(), LookupNamespaceName);
11395       if (!LookupQualifiedName(Result, Std) ||
11396           !(StdExperimentalNamespaceCache =
11397                 Result.getAsSingle<NamespaceDecl>()))
11398         Result.suppressDiagnostics();
11399     }
11400   }
11401   return StdExperimentalNamespaceCache;
11402 }
11403 
11404 namespace {
11405 
11406 enum UnsupportedSTLSelect {
11407   USS_InvalidMember,
11408   USS_MissingMember,
11409   USS_NonTrivial,
11410   USS_Other
11411 };
11412 
11413 struct InvalidSTLDiagnoser {
11414   Sema &S;
11415   SourceLocation Loc;
11416   QualType TyForDiags;
11417 
11418   QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
11419                       const VarDecl *VD = nullptr) {
11420     {
11421       auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
11422                << TyForDiags << ((int)Sel);
11423       if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
11424         assert(!Name.empty());
11425         D << Name;
11426       }
11427     }
11428     if (Sel == USS_InvalidMember) {
11429       S.Diag(VD->getLocation(), diag::note_var_declared_here)
11430           << VD << VD->getSourceRange();
11431     }
11432     return QualType();
11433   }
11434 };
11435 } // namespace
11436 
11437 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
11438                                            SourceLocation Loc,
11439                                            ComparisonCategoryUsage Usage) {
11440   assert(getLangOpts().CPlusPlus &&
11441          "Looking for comparison category type outside of C++.");
11442 
11443   // Use an elaborated type for diagnostics which has a name containing the
11444   // prepended 'std' namespace but not any inline namespace names.
11445   auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
11446     auto *NNS =
11447         NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
11448     return Context.getElaboratedType(ETK_None, NNS, Info->getType());
11449   };
11450 
11451   // Check if we've already successfully checked the comparison category type
11452   // before. If so, skip checking it again.
11453   ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
11454   if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
11455     // The only thing we need to check is that the type has a reachable
11456     // definition in the current context.
11457     if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11458       return QualType();
11459 
11460     return Info->getType();
11461   }
11462 
11463   // If lookup failed
11464   if (!Info) {
11465     std::string NameForDiags = "std::";
11466     NameForDiags += ComparisonCategories::getCategoryString(Kind);
11467     Diag(Loc, diag::err_implied_comparison_category_type_not_found)
11468         << NameForDiags << (int)Usage;
11469     return QualType();
11470   }
11471 
11472   assert(Info->Kind == Kind);
11473   assert(Info->Record);
11474 
11475   // Update the Record decl in case we encountered a forward declaration on our
11476   // first pass. FIXME: This is a bit of a hack.
11477   if (Info->Record->hasDefinition())
11478     Info->Record = Info->Record->getDefinition();
11479 
11480   if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11481     return QualType();
11482 
11483   InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
11484 
11485   if (!Info->Record->isTriviallyCopyable())
11486     return UnsupportedSTLError(USS_NonTrivial);
11487 
11488   for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
11489     CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
11490     // Tolerate empty base classes.
11491     if (Base->isEmpty())
11492       continue;
11493     // Reject STL implementations which have at least one non-empty base.
11494     return UnsupportedSTLError();
11495   }
11496 
11497   // Check that the STL has implemented the types using a single integer field.
11498   // This expectation allows better codegen for builtin operators. We require:
11499   //   (1) The class has exactly one field.
11500   //   (2) The field is an integral or enumeration type.
11501   auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
11502   if (std::distance(FIt, FEnd) != 1 ||
11503       !FIt->getType()->isIntegralOrEnumerationType()) {
11504     return UnsupportedSTLError();
11505   }
11506 
11507   // Build each of the require values and store them in Info.
11508   for (ComparisonCategoryResult CCR :
11509        ComparisonCategories::getPossibleResultsForType(Kind)) {
11510     StringRef MemName = ComparisonCategories::getResultString(CCR);
11511     ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
11512 
11513     if (!ValInfo)
11514       return UnsupportedSTLError(USS_MissingMember, MemName);
11515 
11516     VarDecl *VD = ValInfo->VD;
11517     assert(VD && "should not be null!");
11518 
11519     // Attempt to diagnose reasons why the STL definition of this type
11520     // might be foobar, including it failing to be a constant expression.
11521     // TODO Handle more ways the lookup or result can be invalid.
11522     if (!VD->isStaticDataMember() ||
11523         !VD->isUsableInConstantExpressions(Context))
11524       return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
11525 
11526     // Attempt to evaluate the var decl as a constant expression and extract
11527     // the value of its first field as a ICE. If this fails, the STL
11528     // implementation is not supported.
11529     if (!ValInfo->hasValidIntValue())
11530       return UnsupportedSTLError();
11531 
11532     MarkVariableReferenced(Loc, VD);
11533   }
11534 
11535   // We've successfully built the required types and expressions. Update
11536   // the cache and return the newly cached value.
11537   FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
11538   return Info->getType();
11539 }
11540 
11541 /// Retrieve the special "std" namespace, which may require us to
11542 /// implicitly define the namespace.
11543 NamespaceDecl *Sema::getOrCreateStdNamespace() {
11544   if (!StdNamespace) {
11545     // The "std" namespace has not yet been defined, so build one implicitly.
11546     StdNamespace = NamespaceDecl::Create(
11547         Context, Context.getTranslationUnitDecl(),
11548         /*Inline=*/false, SourceLocation(), SourceLocation(),
11549         &PP.getIdentifierTable().get("std"),
11550         /*PrevDecl=*/nullptr, /*Nested=*/false);
11551     getStdNamespace()->setImplicit(true);
11552   }
11553 
11554   return getStdNamespace();
11555 }
11556 
11557 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
11558   assert(getLangOpts().CPlusPlus &&
11559          "Looking for std::initializer_list outside of C++.");
11560 
11561   // We're looking for implicit instantiations of
11562   // template <typename E> class std::initializer_list.
11563 
11564   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
11565     return false;
11566 
11567   ClassTemplateDecl *Template = nullptr;
11568   const TemplateArgument *Arguments = nullptr;
11569 
11570   if (const RecordType *RT = Ty->getAs<RecordType>()) {
11571 
11572     ClassTemplateSpecializationDecl *Specialization =
11573         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
11574     if (!Specialization)
11575       return false;
11576 
11577     Template = Specialization->getSpecializedTemplate();
11578     Arguments = Specialization->getTemplateArgs().data();
11579   } else if (const TemplateSpecializationType *TST =
11580                  Ty->getAs<TemplateSpecializationType>()) {
11581     Template = dyn_cast_or_null<ClassTemplateDecl>(
11582         TST->getTemplateName().getAsTemplateDecl());
11583     Arguments = TST->template_arguments().begin();
11584   }
11585   if (!Template)
11586     return false;
11587 
11588   if (!StdInitializerList) {
11589     // Haven't recognized std::initializer_list yet, maybe this is it.
11590     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
11591     if (TemplateClass->getIdentifier() !=
11592             &PP.getIdentifierTable().get("initializer_list") ||
11593         !getStdNamespace()->InEnclosingNamespaceSetOf(
11594             TemplateClass->getDeclContext()))
11595       return false;
11596     // This is a template called std::initializer_list, but is it the right
11597     // template?
11598     TemplateParameterList *Params = Template->getTemplateParameters();
11599     if (Params->getMinRequiredArguments() != 1)
11600       return false;
11601     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
11602       return false;
11603 
11604     // It's the right template.
11605     StdInitializerList = Template;
11606   }
11607 
11608   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
11609     return false;
11610 
11611   // This is an instance of std::initializer_list. Find the argument type.
11612   if (Element)
11613     *Element = Arguments[0].getAsType();
11614   return true;
11615 }
11616 
11617 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
11618   NamespaceDecl *Std = S.getStdNamespace();
11619   if (!Std) {
11620     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11621     return nullptr;
11622   }
11623 
11624   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
11625                       Loc, Sema::LookupOrdinaryName);
11626   if (!S.LookupQualifiedName(Result, Std)) {
11627     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11628     return nullptr;
11629   }
11630   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
11631   if (!Template) {
11632     Result.suppressDiagnostics();
11633     // We found something weird. Complain about the first thing we found.
11634     NamedDecl *Found = *Result.begin();
11635     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
11636     return nullptr;
11637   }
11638 
11639   // We found some template called std::initializer_list. Now verify that it's
11640   // correct.
11641   TemplateParameterList *Params = Template->getTemplateParameters();
11642   if (Params->getMinRequiredArguments() != 1 ||
11643       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
11644     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
11645     return nullptr;
11646   }
11647 
11648   return Template;
11649 }
11650 
11651 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
11652   if (!StdInitializerList) {
11653     StdInitializerList = LookupStdInitializerList(*this, Loc);
11654     if (!StdInitializerList)
11655       return QualType();
11656   }
11657 
11658   TemplateArgumentListInfo Args(Loc, Loc);
11659   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
11660                                        Context.getTrivialTypeSourceInfo(Element,
11661                                                                         Loc)));
11662   return Context.getElaboratedType(
11663       ElaboratedTypeKeyword::ETK_None,
11664       NestedNameSpecifier::Create(Context, nullptr, getStdNamespace()),
11665       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
11666 }
11667 
11668 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
11669   // C++ [dcl.init.list]p2:
11670   //   A constructor is an initializer-list constructor if its first parameter
11671   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
11672   //   std::initializer_list<E> for some type E, and either there are no other
11673   //   parameters or else all other parameters have default arguments.
11674   if (!Ctor->hasOneParamOrDefaultArgs())
11675     return false;
11676 
11677   QualType ArgType = Ctor->getParamDecl(0)->getType();
11678   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
11679     ArgType = RT->getPointeeType().getUnqualifiedType();
11680 
11681   return isStdInitializerList(ArgType, nullptr);
11682 }
11683 
11684 /// Determine whether a using statement is in a context where it will be
11685 /// apply in all contexts.
11686 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
11687   switch (CurContext->getDeclKind()) {
11688     case Decl::TranslationUnit:
11689       return true;
11690     case Decl::LinkageSpec:
11691       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
11692     default:
11693       return false;
11694   }
11695 }
11696 
11697 namespace {
11698 
11699 // Callback to only accept typo corrections that are namespaces.
11700 class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
11701 public:
11702   bool ValidateCandidate(const TypoCorrection &candidate) override {
11703     if (NamedDecl *ND = candidate.getCorrectionDecl())
11704       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
11705     return false;
11706   }
11707 
11708   std::unique_ptr<CorrectionCandidateCallback> clone() override {
11709     return std::make_unique<NamespaceValidatorCCC>(*this);
11710   }
11711 };
11712 
11713 }
11714 
11715 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
11716                                        CXXScopeSpec &SS,
11717                                        SourceLocation IdentLoc,
11718                                        IdentifierInfo *Ident) {
11719   R.clear();
11720   NamespaceValidatorCCC CCC{};
11721   if (TypoCorrection Corrected =
11722           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
11723                         Sema::CTK_ErrorRecovery)) {
11724     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
11725       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
11726       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
11727                               Ident->getName().equals(CorrectedStr);
11728       S.diagnoseTypo(Corrected,
11729                      S.PDiag(diag::err_using_directive_member_suggest)
11730                        << Ident << DC << DroppedSpecifier << SS.getRange(),
11731                      S.PDiag(diag::note_namespace_defined_here));
11732     } else {
11733       S.diagnoseTypo(Corrected,
11734                      S.PDiag(diag::err_using_directive_suggest) << Ident,
11735                      S.PDiag(diag::note_namespace_defined_here));
11736     }
11737     R.addDecl(Corrected.getFoundDecl());
11738     return true;
11739   }
11740   return false;
11741 }
11742 
11743 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
11744                                 SourceLocation NamespcLoc, CXXScopeSpec &SS,
11745                                 SourceLocation IdentLoc,
11746                                 IdentifierInfo *NamespcName,
11747                                 const ParsedAttributesView &AttrList) {
11748   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
11749   assert(NamespcName && "Invalid NamespcName.");
11750   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
11751 
11752   // This can only happen along a recovery path.
11753   while (S->isTemplateParamScope())
11754     S = S->getParent();
11755   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11756 
11757   UsingDirectiveDecl *UDir = nullptr;
11758   NestedNameSpecifier *Qualifier = nullptr;
11759   if (SS.isSet())
11760     Qualifier = SS.getScopeRep();
11761 
11762   // Lookup namespace name.
11763   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
11764   LookupParsedName(R, S, &SS);
11765   if (R.isAmbiguous())
11766     return nullptr;
11767 
11768   if (R.empty()) {
11769     R.clear();
11770     // Allow "using namespace std;" or "using namespace ::std;" even if
11771     // "std" hasn't been defined yet, for GCC compatibility.
11772     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
11773         NamespcName->isStr("std")) {
11774       Diag(IdentLoc, diag::ext_using_undefined_std);
11775       R.addDecl(getOrCreateStdNamespace());
11776       R.resolveKind();
11777     }
11778     // Otherwise, attempt typo correction.
11779     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
11780   }
11781 
11782   if (!R.empty()) {
11783     NamedDecl *Named = R.getRepresentativeDecl();
11784     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
11785     assert(NS && "expected namespace decl");
11786 
11787     // The use of a nested name specifier may trigger deprecation warnings.
11788     DiagnoseUseOfDecl(Named, IdentLoc);
11789 
11790     // C++ [namespace.udir]p1:
11791     //   A using-directive specifies that the names in the nominated
11792     //   namespace can be used in the scope in which the
11793     //   using-directive appears after the using-directive. During
11794     //   unqualified name lookup (3.4.1), the names appear as if they
11795     //   were declared in the nearest enclosing namespace which
11796     //   contains both the using-directive and the nominated
11797     //   namespace. [Note: in this context, "contains" means "contains
11798     //   directly or indirectly". ]
11799 
11800     // Find enclosing context containing both using-directive and
11801     // nominated namespace.
11802     DeclContext *CommonAncestor = NS;
11803     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
11804       CommonAncestor = CommonAncestor->getParent();
11805 
11806     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
11807                                       SS.getWithLocInContext(Context),
11808                                       IdentLoc, Named, CommonAncestor);
11809 
11810     if (IsUsingDirectiveInToplevelContext(CurContext) &&
11811         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
11812       Diag(IdentLoc, diag::warn_using_directive_in_header);
11813     }
11814 
11815     PushUsingDirective(S, UDir);
11816   } else {
11817     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
11818   }
11819 
11820   if (UDir)
11821     ProcessDeclAttributeList(S, UDir, AttrList);
11822 
11823   return UDir;
11824 }
11825 
11826 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
11827   // If the scope has an associated entity and the using directive is at
11828   // namespace or translation unit scope, add the UsingDirectiveDecl into
11829   // its lookup structure so qualified name lookup can find it.
11830   DeclContext *Ctx = S->getEntity();
11831   if (Ctx && !Ctx->isFunctionOrMethod())
11832     Ctx->addDecl(UDir);
11833   else
11834     // Otherwise, it is at block scope. The using-directives will affect lookup
11835     // only to the end of the scope.
11836     S->PushUsingDirective(UDir);
11837 }
11838 
11839 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
11840                                   SourceLocation UsingLoc,
11841                                   SourceLocation TypenameLoc, CXXScopeSpec &SS,
11842                                   UnqualifiedId &Name,
11843                                   SourceLocation EllipsisLoc,
11844                                   const ParsedAttributesView &AttrList) {
11845   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11846 
11847   if (SS.isEmpty()) {
11848     Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
11849     return nullptr;
11850   }
11851 
11852   switch (Name.getKind()) {
11853   case UnqualifiedIdKind::IK_ImplicitSelfParam:
11854   case UnqualifiedIdKind::IK_Identifier:
11855   case UnqualifiedIdKind::IK_OperatorFunctionId:
11856   case UnqualifiedIdKind::IK_LiteralOperatorId:
11857   case UnqualifiedIdKind::IK_ConversionFunctionId:
11858     break;
11859 
11860   case UnqualifiedIdKind::IK_ConstructorName:
11861   case UnqualifiedIdKind::IK_ConstructorTemplateId:
11862     // C++11 inheriting constructors.
11863     Diag(Name.getBeginLoc(),
11864          getLangOpts().CPlusPlus11
11865              ? diag::warn_cxx98_compat_using_decl_constructor
11866              : diag::err_using_decl_constructor)
11867         << SS.getRange();
11868 
11869     if (getLangOpts().CPlusPlus11) break;
11870 
11871     return nullptr;
11872 
11873   case UnqualifiedIdKind::IK_DestructorName:
11874     Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
11875     return nullptr;
11876 
11877   case UnqualifiedIdKind::IK_TemplateId:
11878     Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
11879         << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
11880     return nullptr;
11881 
11882   case UnqualifiedIdKind::IK_DeductionGuideName:
11883     llvm_unreachable("cannot parse qualified deduction guide name");
11884   }
11885 
11886   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
11887   DeclarationName TargetName = TargetNameInfo.getName();
11888   if (!TargetName)
11889     return nullptr;
11890 
11891   // Warn about access declarations.
11892   if (UsingLoc.isInvalid()) {
11893     Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
11894                                  ? diag::err_access_decl
11895                                  : diag::warn_access_decl_deprecated)
11896         << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
11897   }
11898 
11899   if (EllipsisLoc.isInvalid()) {
11900     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
11901         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
11902       return nullptr;
11903   } else {
11904     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
11905         !TargetNameInfo.containsUnexpandedParameterPack()) {
11906       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
11907         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
11908       EllipsisLoc = SourceLocation();
11909     }
11910   }
11911 
11912   NamedDecl *UD =
11913       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
11914                             SS, TargetNameInfo, EllipsisLoc, AttrList,
11915                             /*IsInstantiation*/ false,
11916                             AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists));
11917   if (UD)
11918     PushOnScopeChains(UD, S, /*AddToContext*/ false);
11919 
11920   return UD;
11921 }
11922 
11923 Decl *Sema::ActOnUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
11924                                       SourceLocation UsingLoc,
11925                                       SourceLocation EnumLoc,
11926                                       SourceLocation IdentLoc,
11927                                       IdentifierInfo &II, CXXScopeSpec *SS) {
11928   assert(!SS->isInvalid() && "ScopeSpec is invalid");
11929   TypeSourceInfo *TSI = nullptr;
11930   QualType EnumTy = GetTypeFromParser(
11931       getTypeName(II, IdentLoc, S, SS, /*isClassName=*/false,
11932                   /*HasTrailingDot=*/false,
11933                   /*ObjectType=*/nullptr, /*IsCtorOrDtorName=*/false,
11934                   /*WantNontrivialTypeSourceInfo=*/true),
11935       &TSI);
11936   if (EnumTy.isNull()) {
11937     Diag(IdentLoc, SS && isDependentScopeSpecifier(*SS)
11938                        ? diag::err_using_enum_is_dependent
11939                        : diag::err_unknown_typename)
11940         << II.getName()
11941         << SourceRange(SS ? SS->getBeginLoc() : IdentLoc, IdentLoc);
11942     return nullptr;
11943   }
11944 
11945   auto *Enum = dyn_cast_if_present<EnumDecl>(EnumTy->getAsTagDecl());
11946   if (!Enum) {
11947     Diag(IdentLoc, diag::err_using_enum_not_enum) << EnumTy;
11948     return nullptr;
11949   }
11950 
11951   if (auto *Def = Enum->getDefinition())
11952     Enum = Def;
11953 
11954   if (TSI == nullptr)
11955     TSI = Context.getTrivialTypeSourceInfo(EnumTy, IdentLoc);
11956 
11957   auto *UD =
11958       BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, IdentLoc, TSI, Enum);
11959 
11960   if (UD)
11961     PushOnScopeChains(UD, S, /*AddToContext*/ false);
11962 
11963   return UD;
11964 }
11965 
11966 /// Determine whether a using declaration considers the given
11967 /// declarations as "equivalent", e.g., if they are redeclarations of
11968 /// the same entity or are both typedefs of the same type.
11969 static bool
11970 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
11971   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
11972     return true;
11973 
11974   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
11975     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
11976       return Context.hasSameType(TD1->getUnderlyingType(),
11977                                  TD2->getUnderlyingType());
11978 
11979   // Two using_if_exists using-declarations are equivalent if both are
11980   // unresolved.
11981   if (isa<UnresolvedUsingIfExistsDecl>(D1) &&
11982       isa<UnresolvedUsingIfExistsDecl>(D2))
11983     return true;
11984 
11985   return false;
11986 }
11987 
11988 
11989 /// Determines whether to create a using shadow decl for a particular
11990 /// decl, given the set of decls existing prior to this using lookup.
11991 bool Sema::CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Orig,
11992                                 const LookupResult &Previous,
11993                                 UsingShadowDecl *&PrevShadow) {
11994   // Diagnose finding a decl which is not from a base class of the
11995   // current class.  We do this now because there are cases where this
11996   // function will silently decide not to build a shadow decl, which
11997   // will pre-empt further diagnostics.
11998   //
11999   // We don't need to do this in C++11 because we do the check once on
12000   // the qualifier.
12001   //
12002   // FIXME: diagnose the following if we care enough:
12003   //   struct A { int foo; };
12004   //   struct B : A { using A::foo; };
12005   //   template <class T> struct C : A {};
12006   //   template <class T> struct D : C<T> { using B::foo; } // <---
12007   // This is invalid (during instantiation) in C++03 because B::foo
12008   // resolves to the using decl in B, which is not a base class of D<T>.
12009   // We can't diagnose it immediately because C<T> is an unknown
12010   // specialization. The UsingShadowDecl in D<T> then points directly
12011   // to A::foo, which will look well-formed when we instantiate.
12012   // The right solution is to not collapse the shadow-decl chain.
12013   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord())
12014     if (auto *Using = dyn_cast<UsingDecl>(BUD)) {
12015       DeclContext *OrigDC = Orig->getDeclContext();
12016 
12017       // Handle enums and anonymous structs.
12018       if (isa<EnumDecl>(OrigDC))
12019         OrigDC = OrigDC->getParent();
12020       CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
12021       while (OrigRec->isAnonymousStructOrUnion())
12022         OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
12023 
12024       if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
12025         if (OrigDC == CurContext) {
12026           Diag(Using->getLocation(),
12027                diag::err_using_decl_nested_name_specifier_is_current_class)
12028               << Using->getQualifierLoc().getSourceRange();
12029           Diag(Orig->getLocation(), diag::note_using_decl_target);
12030           Using->setInvalidDecl();
12031           return true;
12032         }
12033 
12034         Diag(Using->getQualifierLoc().getBeginLoc(),
12035              diag::err_using_decl_nested_name_specifier_is_not_base_class)
12036             << Using->getQualifier() << cast<CXXRecordDecl>(CurContext)
12037             << Using->getQualifierLoc().getSourceRange();
12038         Diag(Orig->getLocation(), diag::note_using_decl_target);
12039         Using->setInvalidDecl();
12040         return true;
12041       }
12042     }
12043 
12044   if (Previous.empty()) return false;
12045 
12046   NamedDecl *Target = Orig;
12047   if (isa<UsingShadowDecl>(Target))
12048     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12049 
12050   // If the target happens to be one of the previous declarations, we
12051   // don't have a conflict.
12052   //
12053   // FIXME: but we might be increasing its access, in which case we
12054   // should redeclare it.
12055   NamedDecl *NonTag = nullptr, *Tag = nullptr;
12056   bool FoundEquivalentDecl = false;
12057   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
12058          I != E; ++I) {
12059     NamedDecl *D = (*I)->getUnderlyingDecl();
12060     // We can have UsingDecls in our Previous results because we use the same
12061     // LookupResult for checking whether the UsingDecl itself is a valid
12062     // redeclaration.
12063     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D) || isa<UsingEnumDecl>(D))
12064       continue;
12065 
12066     if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
12067       // C++ [class.mem]p19:
12068       //   If T is the name of a class, then [every named member other than
12069       //   a non-static data member] shall have a name different from T
12070       if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
12071           !isa<IndirectFieldDecl>(Target) &&
12072           !isa<UnresolvedUsingValueDecl>(Target) &&
12073           DiagnoseClassNameShadow(
12074               CurContext,
12075               DeclarationNameInfo(BUD->getDeclName(), BUD->getLocation())))
12076         return true;
12077     }
12078 
12079     if (IsEquivalentForUsingDecl(Context, D, Target)) {
12080       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
12081         PrevShadow = Shadow;
12082       FoundEquivalentDecl = true;
12083     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
12084       // We don't conflict with an existing using shadow decl of an equivalent
12085       // declaration, but we're not a redeclaration of it.
12086       FoundEquivalentDecl = true;
12087     }
12088 
12089     if (isVisible(D))
12090       (isa<TagDecl>(D) ? Tag : NonTag) = D;
12091   }
12092 
12093   if (FoundEquivalentDecl)
12094     return false;
12095 
12096   // Always emit a diagnostic for a mismatch between an unresolved
12097   // using_if_exists and a resolved using declaration in either direction.
12098   if (isa<UnresolvedUsingIfExistsDecl>(Target) !=
12099       (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) {
12100     if (!NonTag && !Tag)
12101       return false;
12102     Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12103     Diag(Target->getLocation(), diag::note_using_decl_target);
12104     Diag((NonTag ? NonTag : Tag)->getLocation(),
12105          diag::note_using_decl_conflict);
12106     BUD->setInvalidDecl();
12107     return true;
12108   }
12109 
12110   if (FunctionDecl *FD = Target->getAsFunction()) {
12111     NamedDecl *OldDecl = nullptr;
12112     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
12113                           /*IsForUsingDecl*/ true)) {
12114     case Ovl_Overload:
12115       return false;
12116 
12117     case Ovl_NonFunction:
12118       Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12119       break;
12120 
12121     // We found a decl with the exact signature.
12122     case Ovl_Match:
12123       // If we're in a record, we want to hide the target, so we
12124       // return true (without a diagnostic) to tell the caller not to
12125       // build a shadow decl.
12126       if (CurContext->isRecord())
12127         return true;
12128 
12129       // If we're not in a record, this is an error.
12130       Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12131       break;
12132     }
12133 
12134     Diag(Target->getLocation(), diag::note_using_decl_target);
12135     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
12136     BUD->setInvalidDecl();
12137     return true;
12138   }
12139 
12140   // Target is not a function.
12141 
12142   if (isa<TagDecl>(Target)) {
12143     // No conflict between a tag and a non-tag.
12144     if (!Tag) return false;
12145 
12146     Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12147     Diag(Target->getLocation(), diag::note_using_decl_target);
12148     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
12149     BUD->setInvalidDecl();
12150     return true;
12151   }
12152 
12153   // No conflict between a tag and a non-tag.
12154   if (!NonTag) return false;
12155 
12156   Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12157   Diag(Target->getLocation(), diag::note_using_decl_target);
12158   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
12159   BUD->setInvalidDecl();
12160   return true;
12161 }
12162 
12163 /// Determine whether a direct base class is a virtual base class.
12164 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
12165   if (!Derived->getNumVBases())
12166     return false;
12167   for (auto &B : Derived->bases())
12168     if (B.getType()->getAsCXXRecordDecl() == Base)
12169       return B.isVirtual();
12170   llvm_unreachable("not a direct base class");
12171 }
12172 
12173 /// Builds a shadow declaration corresponding to a 'using' declaration.
12174 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
12175                                             NamedDecl *Orig,
12176                                             UsingShadowDecl *PrevDecl) {
12177   // If we resolved to another shadow declaration, just coalesce them.
12178   NamedDecl *Target = Orig;
12179   if (isa<UsingShadowDecl>(Target)) {
12180     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12181     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
12182   }
12183 
12184   NamedDecl *NonTemplateTarget = Target;
12185   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
12186     NonTemplateTarget = TargetTD->getTemplatedDecl();
12187 
12188   UsingShadowDecl *Shadow;
12189   if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
12190     UsingDecl *Using = cast<UsingDecl>(BUD);
12191     bool IsVirtualBase =
12192         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
12193                             Using->getQualifier()->getAsRecordDecl());
12194     Shadow = ConstructorUsingShadowDecl::Create(
12195         Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase);
12196   } else {
12197     Shadow = UsingShadowDecl::Create(Context, CurContext, BUD->getLocation(),
12198                                      Target->getDeclName(), BUD, Target);
12199   }
12200   BUD->addShadowDecl(Shadow);
12201 
12202   Shadow->setAccess(BUD->getAccess());
12203   if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
12204     Shadow->setInvalidDecl();
12205 
12206   Shadow->setPreviousDecl(PrevDecl);
12207 
12208   if (S)
12209     PushOnScopeChains(Shadow, S);
12210   else
12211     CurContext->addDecl(Shadow);
12212 
12213 
12214   return Shadow;
12215 }
12216 
12217 /// Hides a using shadow declaration.  This is required by the current
12218 /// using-decl implementation when a resolvable using declaration in a
12219 /// class is followed by a declaration which would hide or override
12220 /// one or more of the using decl's targets; for example:
12221 ///
12222 ///   struct Base { void foo(int); };
12223 ///   struct Derived : Base {
12224 ///     using Base::foo;
12225 ///     void foo(int);
12226 ///   };
12227 ///
12228 /// The governing language is C++03 [namespace.udecl]p12:
12229 ///
12230 ///   When a using-declaration brings names from a base class into a
12231 ///   derived class scope, member functions in the derived class
12232 ///   override and/or hide member functions with the same name and
12233 ///   parameter types in a base class (rather than conflicting).
12234 ///
12235 /// There are two ways to implement this:
12236 ///   (1) optimistically create shadow decls when they're not hidden
12237 ///       by existing declarations, or
12238 ///   (2) don't create any shadow decls (or at least don't make them
12239 ///       visible) until we've fully parsed/instantiated the class.
12240 /// The problem with (1) is that we might have to retroactively remove
12241 /// a shadow decl, which requires several O(n) operations because the
12242 /// decl structures are (very reasonably) not designed for removal.
12243 /// (2) avoids this but is very fiddly and phase-dependent.
12244 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
12245   if (Shadow->getDeclName().getNameKind() ==
12246         DeclarationName::CXXConversionFunctionName)
12247     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
12248 
12249   // Remove it from the DeclContext...
12250   Shadow->getDeclContext()->removeDecl(Shadow);
12251 
12252   // ...and the scope, if applicable...
12253   if (S) {
12254     S->RemoveDecl(Shadow);
12255     IdResolver.RemoveDecl(Shadow);
12256   }
12257 
12258   // ...and the using decl.
12259   Shadow->getIntroducer()->removeShadowDecl(Shadow);
12260 
12261   // TODO: complain somehow if Shadow was used.  It shouldn't
12262   // be possible for this to happen, because...?
12263 }
12264 
12265 /// Find the base specifier for a base class with the given type.
12266 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
12267                                                 QualType DesiredBase,
12268                                                 bool &AnyDependentBases) {
12269   // Check whether the named type is a direct base class.
12270   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
12271     .getUnqualifiedType();
12272   for (auto &Base : Derived->bases()) {
12273     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
12274     if (CanonicalDesiredBase == BaseType)
12275       return &Base;
12276     if (BaseType->isDependentType())
12277       AnyDependentBases = true;
12278   }
12279   return nullptr;
12280 }
12281 
12282 namespace {
12283 class UsingValidatorCCC final : public CorrectionCandidateCallback {
12284 public:
12285   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
12286                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
12287       : HasTypenameKeyword(HasTypenameKeyword),
12288         IsInstantiation(IsInstantiation), OldNNS(NNS),
12289         RequireMemberOf(RequireMemberOf) {}
12290 
12291   bool ValidateCandidate(const TypoCorrection &Candidate) override {
12292     NamedDecl *ND = Candidate.getCorrectionDecl();
12293 
12294     // Keywords are not valid here.
12295     if (!ND || isa<NamespaceDecl>(ND))
12296       return false;
12297 
12298     // Completely unqualified names are invalid for a 'using' declaration.
12299     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
12300       return false;
12301 
12302     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
12303     // reject.
12304 
12305     if (RequireMemberOf) {
12306       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12307       if (FoundRecord && FoundRecord->isInjectedClassName()) {
12308         // No-one ever wants a using-declaration to name an injected-class-name
12309         // of a base class, unless they're declaring an inheriting constructor.
12310         ASTContext &Ctx = ND->getASTContext();
12311         if (!Ctx.getLangOpts().CPlusPlus11)
12312           return false;
12313         QualType FoundType = Ctx.getRecordType(FoundRecord);
12314 
12315         // Check that the injected-class-name is named as a member of its own
12316         // type; we don't want to suggest 'using Derived::Base;', since that
12317         // means something else.
12318         NestedNameSpecifier *Specifier =
12319             Candidate.WillReplaceSpecifier()
12320                 ? Candidate.getCorrectionSpecifier()
12321                 : OldNNS;
12322         if (!Specifier->getAsType() ||
12323             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
12324           return false;
12325 
12326         // Check that this inheriting constructor declaration actually names a
12327         // direct base class of the current class.
12328         bool AnyDependentBases = false;
12329         if (!findDirectBaseWithType(RequireMemberOf,
12330                                     Ctx.getRecordType(FoundRecord),
12331                                     AnyDependentBases) &&
12332             !AnyDependentBases)
12333           return false;
12334       } else {
12335         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
12336         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
12337           return false;
12338 
12339         // FIXME: Check that the base class member is accessible?
12340       }
12341     } else {
12342       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12343       if (FoundRecord && FoundRecord->isInjectedClassName())
12344         return false;
12345     }
12346 
12347     if (isa<TypeDecl>(ND))
12348       return HasTypenameKeyword || !IsInstantiation;
12349 
12350     return !HasTypenameKeyword;
12351   }
12352 
12353   std::unique_ptr<CorrectionCandidateCallback> clone() override {
12354     return std::make_unique<UsingValidatorCCC>(*this);
12355   }
12356 
12357 private:
12358   bool HasTypenameKeyword;
12359   bool IsInstantiation;
12360   NestedNameSpecifier *OldNNS;
12361   CXXRecordDecl *RequireMemberOf;
12362 };
12363 } // end anonymous namespace
12364 
12365 /// Remove decls we can't actually see from a lookup being used to declare
12366 /// shadow using decls.
12367 ///
12368 /// \param S - The scope of the potential shadow decl
12369 /// \param Previous - The lookup of a potential shadow decl's name.
12370 void Sema::FilterUsingLookup(Scope *S, LookupResult &Previous) {
12371   // It is really dumb that we have to do this.
12372   LookupResult::Filter F = Previous.makeFilter();
12373   while (F.hasNext()) {
12374     NamedDecl *D = F.next();
12375     if (!isDeclInScope(D, CurContext, S))
12376       F.erase();
12377     // If we found a local extern declaration that's not ordinarily visible,
12378     // and this declaration is being added to a non-block scope, ignore it.
12379     // We're only checking for scope conflicts here, not also for violations
12380     // of the linkage rules.
12381     else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
12382              !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
12383       F.erase();
12384   }
12385   F.done();
12386 }
12387 
12388 /// Builds a using declaration.
12389 ///
12390 /// \param IsInstantiation - Whether this call arises from an
12391 ///   instantiation of an unresolved using declaration.  We treat
12392 ///   the lookup differently for these declarations.
12393 NamedDecl *Sema::BuildUsingDeclaration(
12394     Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
12395     bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
12396     DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
12397     const ParsedAttributesView &AttrList, bool IsInstantiation,
12398     bool IsUsingIfExists) {
12399   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12400   SourceLocation IdentLoc = NameInfo.getLoc();
12401   assert(IdentLoc.isValid() && "Invalid TargetName location.");
12402 
12403   // FIXME: We ignore attributes for now.
12404 
12405   // For an inheriting constructor declaration, the name of the using
12406   // declaration is the name of a constructor in this class, not in the
12407   // base class.
12408   DeclarationNameInfo UsingName = NameInfo;
12409   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
12410     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
12411       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12412           Context.getCanonicalType(Context.getRecordType(RD))));
12413 
12414   // Do the redeclaration lookup in the current scope.
12415   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
12416                         ForVisibleRedeclaration);
12417   Previous.setHideTags(false);
12418   if (S) {
12419     LookupName(Previous, S);
12420 
12421     FilterUsingLookup(S, Previous);
12422   } else {
12423     assert(IsInstantiation && "no scope in non-instantiation");
12424     if (CurContext->isRecord())
12425       LookupQualifiedName(Previous, CurContext);
12426     else {
12427       // No redeclaration check is needed here; in non-member contexts we
12428       // diagnosed all possible conflicts with other using-declarations when
12429       // building the template:
12430       //
12431       // For a dependent non-type using declaration, the only valid case is
12432       // if we instantiate to a single enumerator. We check for conflicts
12433       // between shadow declarations we introduce, and we check in the template
12434       // definition for conflicts between a non-type using declaration and any
12435       // other declaration, which together covers all cases.
12436       //
12437       // A dependent typename using declaration will never successfully
12438       // instantiate, since it will always name a class member, so we reject
12439       // that in the template definition.
12440     }
12441   }
12442 
12443   // Check for invalid redeclarations.
12444   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
12445                                   SS, IdentLoc, Previous))
12446     return nullptr;
12447 
12448   // 'using_if_exists' doesn't make sense on an inherited constructor.
12449   if (IsUsingIfExists && UsingName.getName().getNameKind() ==
12450                              DeclarationName::CXXConstructorName) {
12451     Diag(UsingLoc, diag::err_using_if_exists_on_ctor);
12452     return nullptr;
12453   }
12454 
12455   DeclContext *LookupContext = computeDeclContext(SS);
12456   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
12457   if (!LookupContext || EllipsisLoc.isValid()) {
12458     NamedDecl *D;
12459     // Dependent scope, or an unexpanded pack
12460     if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword,
12461                                                   SS, NameInfo, IdentLoc))
12462       return nullptr;
12463 
12464     if (HasTypenameKeyword) {
12465       // FIXME: not all declaration name kinds are legal here
12466       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
12467                                               UsingLoc, TypenameLoc,
12468                                               QualifierLoc,
12469                                               IdentLoc, NameInfo.getName(),
12470                                               EllipsisLoc);
12471     } else {
12472       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
12473                                            QualifierLoc, NameInfo, EllipsisLoc);
12474     }
12475     D->setAccess(AS);
12476     CurContext->addDecl(D);
12477     ProcessDeclAttributeList(S, D, AttrList);
12478     return D;
12479   }
12480 
12481   auto Build = [&](bool Invalid) {
12482     UsingDecl *UD =
12483         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
12484                           UsingName, HasTypenameKeyword);
12485     UD->setAccess(AS);
12486     CurContext->addDecl(UD);
12487     ProcessDeclAttributeList(S, UD, AttrList);
12488     UD->setInvalidDecl(Invalid);
12489     return UD;
12490   };
12491   auto BuildInvalid = [&]{ return Build(true); };
12492   auto BuildValid = [&]{ return Build(false); };
12493 
12494   if (RequireCompleteDeclContext(SS, LookupContext))
12495     return BuildInvalid();
12496 
12497   // Look up the target name.
12498   LookupResult R(*this, NameInfo, LookupOrdinaryName);
12499 
12500   // Unlike most lookups, we don't always want to hide tag
12501   // declarations: tag names are visible through the using declaration
12502   // even if hidden by ordinary names, *except* in a dependent context
12503   // where they may be used by two-phase lookup.
12504   if (!IsInstantiation)
12505     R.setHideTags(false);
12506 
12507   // For the purposes of this lookup, we have a base object type
12508   // equal to that of the current context.
12509   if (CurContext->isRecord()) {
12510     R.setBaseObjectType(
12511                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
12512   }
12513 
12514   LookupQualifiedName(R, LookupContext);
12515 
12516   // Validate the context, now we have a lookup
12517   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
12518                               IdentLoc, &R))
12519     return nullptr;
12520 
12521   if (R.empty() && IsUsingIfExists)
12522     R.addDecl(UnresolvedUsingIfExistsDecl::Create(Context, CurContext, UsingLoc,
12523                                                   UsingName.getName()),
12524               AS_public);
12525 
12526   // Try to correct typos if possible. If constructor name lookup finds no
12527   // results, that means the named class has no explicit constructors, and we
12528   // suppressed declaring implicit ones (probably because it's dependent or
12529   // invalid).
12530   if (R.empty() &&
12531       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
12532     // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
12533     // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
12534     // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
12535     auto *II = NameInfo.getName().getAsIdentifierInfo();
12536     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
12537         CurContext->isStdNamespace() &&
12538         isa<TranslationUnitDecl>(LookupContext) &&
12539         getSourceManager().isInSystemHeader(UsingLoc))
12540       return nullptr;
12541     UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
12542                           dyn_cast<CXXRecordDecl>(CurContext));
12543     if (TypoCorrection Corrected =
12544             CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
12545                         CTK_ErrorRecovery)) {
12546       // We reject candidates where DroppedSpecifier == true, hence the
12547       // literal '0' below.
12548       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
12549                                 << NameInfo.getName() << LookupContext << 0
12550                                 << SS.getRange());
12551 
12552       // If we picked a correction with no attached Decl we can't do anything
12553       // useful with it, bail out.
12554       NamedDecl *ND = Corrected.getCorrectionDecl();
12555       if (!ND)
12556         return BuildInvalid();
12557 
12558       // If we corrected to an inheriting constructor, handle it as one.
12559       auto *RD = dyn_cast<CXXRecordDecl>(ND);
12560       if (RD && RD->isInjectedClassName()) {
12561         // The parent of the injected class name is the class itself.
12562         RD = cast<CXXRecordDecl>(RD->getParent());
12563 
12564         // Fix up the information we'll use to build the using declaration.
12565         if (Corrected.WillReplaceSpecifier()) {
12566           NestedNameSpecifierLocBuilder Builder;
12567           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
12568                               QualifierLoc.getSourceRange());
12569           QualifierLoc = Builder.getWithLocInContext(Context);
12570         }
12571 
12572         // In this case, the name we introduce is the name of a derived class
12573         // constructor.
12574         auto *CurClass = cast<CXXRecordDecl>(CurContext);
12575         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12576             Context.getCanonicalType(Context.getRecordType(CurClass))));
12577         UsingName.setNamedTypeInfo(nullptr);
12578         for (auto *Ctor : LookupConstructors(RD))
12579           R.addDecl(Ctor);
12580         R.resolveKind();
12581       } else {
12582         // FIXME: Pick up all the declarations if we found an overloaded
12583         // function.
12584         UsingName.setName(ND->getDeclName());
12585         R.addDecl(ND);
12586       }
12587     } else {
12588       Diag(IdentLoc, diag::err_no_member)
12589         << NameInfo.getName() << LookupContext << SS.getRange();
12590       return BuildInvalid();
12591     }
12592   }
12593 
12594   if (R.isAmbiguous())
12595     return BuildInvalid();
12596 
12597   if (HasTypenameKeyword) {
12598     // If we asked for a typename and got a non-type decl, error out.
12599     if (!R.getAsSingle<TypeDecl>() &&
12600         !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) {
12601       Diag(IdentLoc, diag::err_using_typename_non_type);
12602       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12603         Diag((*I)->getUnderlyingDecl()->getLocation(),
12604              diag::note_using_decl_target);
12605       return BuildInvalid();
12606     }
12607   } else {
12608     // If we asked for a non-typename and we got a type, error out,
12609     // but only if this is an instantiation of an unresolved using
12610     // decl.  Otherwise just silently find the type name.
12611     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
12612       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
12613       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
12614       return BuildInvalid();
12615     }
12616   }
12617 
12618   // C++14 [namespace.udecl]p6:
12619   // A using-declaration shall not name a namespace.
12620   if (R.getAsSingle<NamespaceDecl>()) {
12621     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
12622       << SS.getRange();
12623     return BuildInvalid();
12624   }
12625 
12626   UsingDecl *UD = BuildValid();
12627 
12628   // Some additional rules apply to inheriting constructors.
12629   if (UsingName.getName().getNameKind() ==
12630         DeclarationName::CXXConstructorName) {
12631     // Suppress access diagnostics; the access check is instead performed at the
12632     // point of use for an inheriting constructor.
12633     R.suppressDiagnostics();
12634     if (CheckInheritingConstructorUsingDecl(UD))
12635       return UD;
12636   }
12637 
12638   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
12639     UsingShadowDecl *PrevDecl = nullptr;
12640     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
12641       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
12642   }
12643 
12644   return UD;
12645 }
12646 
12647 NamedDecl *Sema::BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
12648                                            SourceLocation UsingLoc,
12649                                            SourceLocation EnumLoc,
12650                                            SourceLocation NameLoc,
12651                                            TypeSourceInfo *EnumType,
12652                                            EnumDecl *ED) {
12653   bool Invalid = false;
12654 
12655   if (CurContext->getRedeclContext()->isRecord()) {
12656     /// In class scope, check if this is a duplicate, for better a diagnostic.
12657     DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
12658     LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
12659                           ForVisibleRedeclaration);
12660 
12661     LookupName(Previous, S);
12662 
12663     for (NamedDecl *D : Previous)
12664       if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D))
12665         if (UED->getEnumDecl() == ED) {
12666           Diag(UsingLoc, diag::err_using_enum_decl_redeclaration)
12667               << SourceRange(EnumLoc, NameLoc);
12668           Diag(D->getLocation(), diag::note_using_enum_decl) << 1;
12669           Invalid = true;
12670           break;
12671         }
12672   }
12673 
12674   if (RequireCompleteEnumDecl(ED, NameLoc))
12675     Invalid = true;
12676 
12677   UsingEnumDecl *UD = UsingEnumDecl::Create(Context, CurContext, UsingLoc,
12678                                             EnumLoc, NameLoc, EnumType);
12679   UD->setAccess(AS);
12680   CurContext->addDecl(UD);
12681 
12682   if (Invalid) {
12683     UD->setInvalidDecl();
12684     return UD;
12685   }
12686 
12687   // Create the shadow decls for each enumerator
12688   for (EnumConstantDecl *EC : ED->enumerators()) {
12689     UsingShadowDecl *PrevDecl = nullptr;
12690     DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
12691     LookupResult Previous(*this, DNI, LookupOrdinaryName,
12692                           ForVisibleRedeclaration);
12693     LookupName(Previous, S);
12694     FilterUsingLookup(S, Previous);
12695 
12696     if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl))
12697       BuildUsingShadowDecl(S, UD, EC, PrevDecl);
12698   }
12699 
12700   return UD;
12701 }
12702 
12703 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
12704                                     ArrayRef<NamedDecl *> Expansions) {
12705   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
12706          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
12707          isa<UsingPackDecl>(InstantiatedFrom));
12708 
12709   auto *UPD =
12710       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
12711   UPD->setAccess(InstantiatedFrom->getAccess());
12712   CurContext->addDecl(UPD);
12713   return UPD;
12714 }
12715 
12716 /// Additional checks for a using declaration referring to a constructor name.
12717 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
12718   assert(!UD->hasTypename() && "expecting a constructor name");
12719 
12720   const Type *SourceType = UD->getQualifier()->getAsType();
12721   assert(SourceType &&
12722          "Using decl naming constructor doesn't have type in scope spec.");
12723   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
12724 
12725   // Check whether the named type is a direct base class.
12726   bool AnyDependentBases = false;
12727   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
12728                                       AnyDependentBases);
12729   if (!Base && !AnyDependentBases) {
12730     Diag(UD->getUsingLoc(),
12731          diag::err_using_decl_constructor_not_in_direct_base)
12732       << UD->getNameInfo().getSourceRange()
12733       << QualType(SourceType, 0) << TargetClass;
12734     UD->setInvalidDecl();
12735     return true;
12736   }
12737 
12738   if (Base)
12739     Base->setInheritConstructors();
12740 
12741   return false;
12742 }
12743 
12744 /// Checks that the given using declaration is not an invalid
12745 /// redeclaration.  Note that this is checking only for the using decl
12746 /// itself, not for any ill-formedness among the UsingShadowDecls.
12747 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
12748                                        bool HasTypenameKeyword,
12749                                        const CXXScopeSpec &SS,
12750                                        SourceLocation NameLoc,
12751                                        const LookupResult &Prev) {
12752   NestedNameSpecifier *Qual = SS.getScopeRep();
12753 
12754   // C++03 [namespace.udecl]p8:
12755   // C++0x [namespace.udecl]p10:
12756   //   A using-declaration is a declaration and can therefore be used
12757   //   repeatedly where (and only where) multiple declarations are
12758   //   allowed.
12759   //
12760   // That's in non-member contexts.
12761   if (!CurContext->getRedeclContext()->isRecord()) {
12762     // A dependent qualifier outside a class can only ever resolve to an
12763     // enumeration type. Therefore it conflicts with any other non-type
12764     // declaration in the same scope.
12765     // FIXME: How should we check for dependent type-type conflicts at block
12766     // scope?
12767     if (Qual->isDependent() && !HasTypenameKeyword) {
12768       for (auto *D : Prev) {
12769         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
12770           bool OldCouldBeEnumerator =
12771               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
12772           Diag(NameLoc,
12773                OldCouldBeEnumerator ? diag::err_redefinition
12774                                     : diag::err_redefinition_different_kind)
12775               << Prev.getLookupName();
12776           Diag(D->getLocation(), diag::note_previous_definition);
12777           return true;
12778         }
12779       }
12780     }
12781     return false;
12782   }
12783 
12784   const NestedNameSpecifier *CNNS =
12785       Context.getCanonicalNestedNameSpecifier(Qual);
12786   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
12787     NamedDecl *D = *I;
12788 
12789     bool DTypename;
12790     NestedNameSpecifier *DQual;
12791     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
12792       DTypename = UD->hasTypename();
12793       DQual = UD->getQualifier();
12794     } else if (UnresolvedUsingValueDecl *UD
12795                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
12796       DTypename = false;
12797       DQual = UD->getQualifier();
12798     } else if (UnresolvedUsingTypenameDecl *UD
12799                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
12800       DTypename = true;
12801       DQual = UD->getQualifier();
12802     } else continue;
12803 
12804     // using decls differ if one says 'typename' and the other doesn't.
12805     // FIXME: non-dependent using decls?
12806     if (HasTypenameKeyword != DTypename) continue;
12807 
12808     // using decls differ if they name different scopes (but note that
12809     // template instantiation can cause this check to trigger when it
12810     // didn't before instantiation).
12811     if (CNNS != Context.getCanonicalNestedNameSpecifier(DQual))
12812       continue;
12813 
12814     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
12815     Diag(D->getLocation(), diag::note_using_decl) << 1;
12816     return true;
12817   }
12818 
12819   return false;
12820 }
12821 
12822 /// Checks that the given nested-name qualifier used in a using decl
12823 /// in the current context is appropriately related to the current
12824 /// scope.  If an error is found, diagnoses it and returns true.
12825 /// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's the
12826 /// result of that lookup. UD is likewise nullptr, except when we have an
12827 /// already-populated UsingDecl whose shadow decls contain the same information
12828 /// (i.e. we're instantiating a UsingDecl with non-dependent scope).
12829 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
12830                                    const CXXScopeSpec &SS,
12831                                    const DeclarationNameInfo &NameInfo,
12832                                    SourceLocation NameLoc,
12833                                    const LookupResult *R, const UsingDecl *UD) {
12834   DeclContext *NamedContext = computeDeclContext(SS);
12835   assert(bool(NamedContext) == (R || UD) && !(R && UD) &&
12836          "resolvable context must have exactly one set of decls");
12837 
12838   // C++ 20 permits using an enumerator that does not have a class-hierarchy
12839   // relationship.
12840   bool Cxx20Enumerator = false;
12841   if (NamedContext) {
12842     EnumConstantDecl *EC = nullptr;
12843     if (R)
12844       EC = R->getAsSingle<EnumConstantDecl>();
12845     else if (UD && UD->shadow_size() == 1)
12846       EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl());
12847     if (EC)
12848       Cxx20Enumerator = getLangOpts().CPlusPlus20;
12849 
12850     if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) {
12851       // C++14 [namespace.udecl]p7:
12852       // A using-declaration shall not name a scoped enumerator.
12853       // C++20 p1099 permits enumerators.
12854       if (EC && R && ED->isScoped())
12855         Diag(SS.getBeginLoc(),
12856              getLangOpts().CPlusPlus20
12857                  ? diag::warn_cxx17_compat_using_decl_scoped_enumerator
12858                  : diag::ext_using_decl_scoped_enumerator)
12859             << SS.getRange();
12860 
12861       // We want to consider the scope of the enumerator
12862       NamedContext = ED->getDeclContext();
12863     }
12864   }
12865 
12866   if (!CurContext->isRecord()) {
12867     // C++03 [namespace.udecl]p3:
12868     // C++0x [namespace.udecl]p8:
12869     //   A using-declaration for a class member shall be a member-declaration.
12870     // C++20 [namespace.udecl]p7
12871     //   ... other than an enumerator ...
12872 
12873     // If we weren't able to compute a valid scope, it might validly be a
12874     // dependent class or enumeration scope. If we have a 'typename' keyword,
12875     // the scope must resolve to a class type.
12876     if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
12877                      : !HasTypename)
12878       return false; // OK
12879 
12880     Diag(NameLoc,
12881          Cxx20Enumerator
12882              ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
12883              : diag::err_using_decl_can_not_refer_to_class_member)
12884         << SS.getRange();
12885 
12886     if (Cxx20Enumerator)
12887       return false; // OK
12888 
12889     auto *RD = NamedContext
12890                    ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
12891                    : nullptr;
12892     if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) {
12893       // See if there's a helpful fixit
12894 
12895       if (!R) {
12896         // We will have already diagnosed the problem on the template
12897         // definition,  Maybe we should do so again?
12898       } else if (R->getAsSingle<TypeDecl>()) {
12899         if (getLangOpts().CPlusPlus11) {
12900           // Convert 'using X::Y;' to 'using Y = X::Y;'.
12901           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
12902             << 0 // alias declaration
12903             << FixItHint::CreateInsertion(SS.getBeginLoc(),
12904                                           NameInfo.getName().getAsString() +
12905                                               " = ");
12906         } else {
12907           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
12908           SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
12909           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
12910             << 1 // typedef declaration
12911             << FixItHint::CreateReplacement(UsingLoc, "typedef")
12912             << FixItHint::CreateInsertion(
12913                    InsertLoc, " " + NameInfo.getName().getAsString());
12914         }
12915       } else if (R->getAsSingle<VarDecl>()) {
12916         // Don't provide a fixit outside C++11 mode; we don't want to suggest
12917         // repeating the type of the static data member here.
12918         FixItHint FixIt;
12919         if (getLangOpts().CPlusPlus11) {
12920           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12921           FixIt = FixItHint::CreateReplacement(
12922               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
12923         }
12924 
12925         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12926           << 2 // reference declaration
12927           << FixIt;
12928       } else if (R->getAsSingle<EnumConstantDecl>()) {
12929         // Don't provide a fixit outside C++11 mode; we don't want to suggest
12930         // repeating the type of the enumeration here, and we can't do so if
12931         // the type is anonymous.
12932         FixItHint FixIt;
12933         if (getLangOpts().CPlusPlus11) {
12934           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12935           FixIt = FixItHint::CreateReplacement(
12936               UsingLoc,
12937               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
12938         }
12939 
12940         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12941           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
12942           << FixIt;
12943       }
12944     }
12945 
12946     return true; // Fail
12947   }
12948 
12949   // If the named context is dependent, we can't decide much.
12950   if (!NamedContext) {
12951     // FIXME: in C++0x, we can diagnose if we can prove that the
12952     // nested-name-specifier does not refer to a base class, which is
12953     // still possible in some cases.
12954 
12955     // Otherwise we have to conservatively report that things might be
12956     // okay.
12957     return false;
12958   }
12959 
12960   // The current scope is a record.
12961   if (!NamedContext->isRecord()) {
12962     // Ideally this would point at the last name in the specifier,
12963     // but we don't have that level of source info.
12964     Diag(SS.getBeginLoc(),
12965          Cxx20Enumerator
12966              ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
12967              : diag::err_using_decl_nested_name_specifier_is_not_class)
12968         << SS.getScopeRep() << SS.getRange();
12969 
12970     if (Cxx20Enumerator)
12971       return false; // OK
12972 
12973     return true;
12974   }
12975 
12976   if (!NamedContext->isDependentContext() &&
12977       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
12978     return true;
12979 
12980   if (getLangOpts().CPlusPlus11) {
12981     // C++11 [namespace.udecl]p3:
12982     //   In a using-declaration used as a member-declaration, the
12983     //   nested-name-specifier shall name a base class of the class
12984     //   being defined.
12985 
12986     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
12987                                  cast<CXXRecordDecl>(NamedContext))) {
12988 
12989       if (Cxx20Enumerator) {
12990         Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator)
12991             << SS.getRange();
12992         return false;
12993       }
12994 
12995       if (CurContext == NamedContext) {
12996         Diag(SS.getBeginLoc(),
12997              diag::err_using_decl_nested_name_specifier_is_current_class)
12998             << SS.getRange();
12999         return !getLangOpts().CPlusPlus20;
13000       }
13001 
13002       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
13003         Diag(SS.getBeginLoc(),
13004              diag::err_using_decl_nested_name_specifier_is_not_base_class)
13005             << SS.getScopeRep() << cast<CXXRecordDecl>(CurContext)
13006             << SS.getRange();
13007       }
13008       return true;
13009     }
13010 
13011     return false;
13012   }
13013 
13014   // C++03 [namespace.udecl]p4:
13015   //   A using-declaration used as a member-declaration shall refer
13016   //   to a member of a base class of the class being defined [etc.].
13017 
13018   // Salient point: SS doesn't have to name a base class as long as
13019   // lookup only finds members from base classes.  Therefore we can
13020   // diagnose here only if we can prove that can't happen,
13021   // i.e. if the class hierarchies provably don't intersect.
13022 
13023   // TODO: it would be nice if "definitely valid" results were cached
13024   // in the UsingDecl and UsingShadowDecl so that these checks didn't
13025   // need to be repeated.
13026 
13027   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
13028   auto Collect = [&Bases](const CXXRecordDecl *Base) {
13029     Bases.insert(Base);
13030     return true;
13031   };
13032 
13033   // Collect all bases. Return false if we find a dependent base.
13034   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
13035     return false;
13036 
13037   // Returns true if the base is dependent or is one of the accumulated base
13038   // classes.
13039   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
13040     return !Bases.count(Base);
13041   };
13042 
13043   // Return false if the class has a dependent base or if it or one
13044   // of its bases is present in the base set of the current context.
13045   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
13046       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
13047     return false;
13048 
13049   Diag(SS.getRange().getBegin(),
13050        diag::err_using_decl_nested_name_specifier_is_not_base_class)
13051     << SS.getScopeRep()
13052     << cast<CXXRecordDecl>(CurContext)
13053     << SS.getRange();
13054 
13055   return true;
13056 }
13057 
13058 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
13059                                   MultiTemplateParamsArg TemplateParamLists,
13060                                   SourceLocation UsingLoc, UnqualifiedId &Name,
13061                                   const ParsedAttributesView &AttrList,
13062                                   TypeResult Type, Decl *DeclFromDeclSpec) {
13063   // Skip up to the relevant declaration scope.
13064   while (S->isTemplateParamScope())
13065     S = S->getParent();
13066   assert((S->getFlags() & Scope::DeclScope) &&
13067          "got alias-declaration outside of declaration scope");
13068 
13069   if (Type.isInvalid())
13070     return nullptr;
13071 
13072   bool Invalid = false;
13073   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
13074   TypeSourceInfo *TInfo = nullptr;
13075   GetTypeFromParser(Type.get(), &TInfo);
13076 
13077   if (DiagnoseClassNameShadow(CurContext, NameInfo))
13078     return nullptr;
13079 
13080   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
13081                                       UPPC_DeclarationType)) {
13082     Invalid = true;
13083     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13084                                              TInfo->getTypeLoc().getBeginLoc());
13085   }
13086 
13087   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
13088                         TemplateParamLists.size()
13089                             ? forRedeclarationInCurContext()
13090                             : ForVisibleRedeclaration);
13091   LookupName(Previous, S);
13092 
13093   // Warn about shadowing the name of a template parameter.
13094   if (Previous.isSingleResult() &&
13095       Previous.getFoundDecl()->isTemplateParameter()) {
13096     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
13097     Previous.clear();
13098   }
13099 
13100   assert(Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
13101          "name in alias declaration must be an identifier");
13102   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
13103                                                Name.StartLocation,
13104                                                Name.Identifier, TInfo);
13105 
13106   NewTD->setAccess(AS);
13107 
13108   if (Invalid)
13109     NewTD->setInvalidDecl();
13110 
13111   ProcessDeclAttributeList(S, NewTD, AttrList);
13112   AddPragmaAttributes(S, NewTD);
13113 
13114   CheckTypedefForVariablyModifiedType(S, NewTD);
13115   Invalid |= NewTD->isInvalidDecl();
13116 
13117   bool Redeclaration = false;
13118 
13119   NamedDecl *NewND;
13120   if (TemplateParamLists.size()) {
13121     TypeAliasTemplateDecl *OldDecl = nullptr;
13122     TemplateParameterList *OldTemplateParams = nullptr;
13123 
13124     if (TemplateParamLists.size() != 1) {
13125       Diag(UsingLoc, diag::err_alias_template_extra_headers)
13126         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
13127          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
13128     }
13129     TemplateParameterList *TemplateParams = TemplateParamLists[0];
13130 
13131     // Check that we can declare a template here.
13132     if (CheckTemplateDeclScope(S, TemplateParams))
13133       return nullptr;
13134 
13135     // Only consider previous declarations in the same scope.
13136     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
13137                          /*ExplicitInstantiationOrSpecialization*/false);
13138     if (!Previous.empty()) {
13139       Redeclaration = true;
13140 
13141       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
13142       if (!OldDecl && !Invalid) {
13143         Diag(UsingLoc, diag::err_redefinition_different_kind)
13144           << Name.Identifier;
13145 
13146         NamedDecl *OldD = Previous.getRepresentativeDecl();
13147         if (OldD->getLocation().isValid())
13148           Diag(OldD->getLocation(), diag::note_previous_definition);
13149 
13150         Invalid = true;
13151       }
13152 
13153       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
13154         if (TemplateParameterListsAreEqual(TemplateParams,
13155                                            OldDecl->getTemplateParameters(),
13156                                            /*Complain=*/true,
13157                                            TPL_TemplateMatch))
13158           OldTemplateParams =
13159               OldDecl->getMostRecentDecl()->getTemplateParameters();
13160         else
13161           Invalid = true;
13162 
13163         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
13164         if (!Invalid &&
13165             !Context.hasSameType(OldTD->getUnderlyingType(),
13166                                  NewTD->getUnderlyingType())) {
13167           // FIXME: The C++0x standard does not clearly say this is ill-formed,
13168           // but we can't reasonably accept it.
13169           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
13170             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
13171           if (OldTD->getLocation().isValid())
13172             Diag(OldTD->getLocation(), diag::note_previous_definition);
13173           Invalid = true;
13174         }
13175       }
13176     }
13177 
13178     // Merge any previous default template arguments into our parameters,
13179     // and check the parameter list.
13180     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
13181                                    TPC_TypeAliasTemplate))
13182       return nullptr;
13183 
13184     TypeAliasTemplateDecl *NewDecl =
13185       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
13186                                     Name.Identifier, TemplateParams,
13187                                     NewTD);
13188     NewTD->setDescribedAliasTemplate(NewDecl);
13189 
13190     NewDecl->setAccess(AS);
13191 
13192     if (Invalid)
13193       NewDecl->setInvalidDecl();
13194     else if (OldDecl) {
13195       NewDecl->setPreviousDecl(OldDecl);
13196       CheckRedeclarationInModule(NewDecl, OldDecl);
13197     }
13198 
13199     NewND = NewDecl;
13200   } else {
13201     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
13202       setTagNameForLinkagePurposes(TD, NewTD);
13203       handleTagNumbering(TD, S);
13204     }
13205     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
13206     NewND = NewTD;
13207   }
13208 
13209   PushOnScopeChains(NewND, S);
13210   ActOnDocumentableDecl(NewND);
13211   return NewND;
13212 }
13213 
13214 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
13215                                    SourceLocation AliasLoc,
13216                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
13217                                    SourceLocation IdentLoc,
13218                                    IdentifierInfo *Ident) {
13219 
13220   // Lookup the namespace name.
13221   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
13222   LookupParsedName(R, S, &SS);
13223 
13224   if (R.isAmbiguous())
13225     return nullptr;
13226 
13227   if (R.empty()) {
13228     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
13229       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
13230       return nullptr;
13231     }
13232   }
13233   assert(!R.isAmbiguous() && !R.empty());
13234   NamedDecl *ND = R.getRepresentativeDecl();
13235 
13236   // Check if we have a previous declaration with the same name.
13237   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
13238                      ForVisibleRedeclaration);
13239   LookupName(PrevR, S);
13240 
13241   // Check we're not shadowing a template parameter.
13242   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
13243     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
13244     PrevR.clear();
13245   }
13246 
13247   // Filter out any other lookup result from an enclosing scope.
13248   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
13249                        /*AllowInlineNamespace*/false);
13250 
13251   // Find the previous declaration and check that we can redeclare it.
13252   NamespaceAliasDecl *Prev = nullptr;
13253   if (PrevR.isSingleResult()) {
13254     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
13255     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
13256       // We already have an alias with the same name that points to the same
13257       // namespace; check that it matches.
13258       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
13259         Prev = AD;
13260       } else if (isVisible(PrevDecl)) {
13261         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
13262           << Alias;
13263         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
13264           << AD->getNamespace();
13265         return nullptr;
13266       }
13267     } else if (isVisible(PrevDecl)) {
13268       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
13269                             ? diag::err_redefinition
13270                             : diag::err_redefinition_different_kind;
13271       Diag(AliasLoc, DiagID) << Alias;
13272       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13273       return nullptr;
13274     }
13275   }
13276 
13277   // The use of a nested name specifier may trigger deprecation warnings.
13278   DiagnoseUseOfDecl(ND, IdentLoc);
13279 
13280   NamespaceAliasDecl *AliasDecl =
13281     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
13282                                Alias, SS.getWithLocInContext(Context),
13283                                IdentLoc, ND);
13284   if (Prev)
13285     AliasDecl->setPreviousDecl(Prev);
13286 
13287   PushOnScopeChains(AliasDecl, S);
13288   return AliasDecl;
13289 }
13290 
13291 namespace {
13292 struct SpecialMemberExceptionSpecInfo
13293     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
13294   SourceLocation Loc;
13295   Sema::ImplicitExceptionSpecification ExceptSpec;
13296 
13297   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
13298                                  Sema::CXXSpecialMember CSM,
13299                                  Sema::InheritedConstructorInfo *ICI,
13300                                  SourceLocation Loc)
13301       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
13302 
13303   bool visitBase(CXXBaseSpecifier *Base);
13304   bool visitField(FieldDecl *FD);
13305 
13306   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
13307                            unsigned Quals);
13308 
13309   void visitSubobjectCall(Subobject Subobj,
13310                           Sema::SpecialMemberOverloadResult SMOR);
13311 };
13312 }
13313 
13314 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
13315   auto *RT = Base->getType()->getAs<RecordType>();
13316   if (!RT)
13317     return false;
13318 
13319   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
13320   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
13321   if (auto *BaseCtor = SMOR.getMethod()) {
13322     visitSubobjectCall(Base, BaseCtor);
13323     return false;
13324   }
13325 
13326   visitClassSubobject(BaseClass, Base, 0);
13327   return false;
13328 }
13329 
13330 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
13331   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
13332     Expr *E = FD->getInClassInitializer();
13333     if (!E)
13334       // FIXME: It's a little wasteful to build and throw away a
13335       // CXXDefaultInitExpr here.
13336       // FIXME: We should have a single context note pointing at Loc, and
13337       // this location should be MD->getLocation() instead, since that's
13338       // the location where we actually use the default init expression.
13339       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
13340     if (E)
13341       ExceptSpec.CalledExpr(E);
13342   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
13343                             ->getAs<RecordType>()) {
13344     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
13345                         FD->getType().getCVRQualifiers());
13346   }
13347   return false;
13348 }
13349 
13350 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
13351                                                          Subobject Subobj,
13352                                                          unsigned Quals) {
13353   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
13354   bool IsMutable = Field && Field->isMutable();
13355   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
13356 }
13357 
13358 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
13359     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
13360   // Note, if lookup fails, it doesn't matter what exception specification we
13361   // choose because the special member will be deleted.
13362   if (CXXMethodDecl *MD = SMOR.getMethod())
13363     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
13364 }
13365 
13366 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
13367   llvm::APSInt Result;
13368   ExprResult Converted = CheckConvertedConstantExpression(
13369       ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
13370   ExplicitSpec.setExpr(Converted.get());
13371   if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
13372     ExplicitSpec.setKind(Result.getBoolValue()
13373                              ? ExplicitSpecKind::ResolvedTrue
13374                              : ExplicitSpecKind::ResolvedFalse);
13375     return true;
13376   }
13377   ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
13378   return false;
13379 }
13380 
13381 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
13382   ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
13383   if (!ExplicitExpr->isTypeDependent())
13384     tryResolveExplicitSpecifier(ES);
13385   return ES;
13386 }
13387 
13388 static Sema::ImplicitExceptionSpecification
13389 ComputeDefaultedSpecialMemberExceptionSpec(
13390     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
13391     Sema::InheritedConstructorInfo *ICI) {
13392   ComputingExceptionSpec CES(S, MD, Loc);
13393 
13394   CXXRecordDecl *ClassDecl = MD->getParent();
13395 
13396   // C++ [except.spec]p14:
13397   //   An implicitly declared special member function (Clause 12) shall have an
13398   //   exception-specification. [...]
13399   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
13400   if (ClassDecl->isInvalidDecl())
13401     return Info.ExceptSpec;
13402 
13403   // FIXME: If this diagnostic fires, we're probably missing a check for
13404   // attempting to resolve an exception specification before it's known
13405   // at a higher level.
13406   if (S.RequireCompleteType(MD->getLocation(),
13407                             S.Context.getRecordType(ClassDecl),
13408                             diag::err_exception_spec_incomplete_type))
13409     return Info.ExceptSpec;
13410 
13411   // C++1z [except.spec]p7:
13412   //   [Look for exceptions thrown by] a constructor selected [...] to
13413   //   initialize a potentially constructed subobject,
13414   // C++1z [except.spec]p8:
13415   //   The exception specification for an implicitly-declared destructor, or a
13416   //   destructor without a noexcept-specifier, is potentially-throwing if and
13417   //   only if any of the destructors for any of its potentially constructed
13418   //   subojects is potentially throwing.
13419   // FIXME: We respect the first rule but ignore the "potentially constructed"
13420   // in the second rule to resolve a core issue (no number yet) that would have
13421   // us reject:
13422   //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
13423   //   struct B : A {};
13424   //   struct C : B { void f(); };
13425   // ... due to giving B::~B() a non-throwing exception specification.
13426   Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
13427                                 : Info.VisitAllBases);
13428 
13429   return Info.ExceptSpec;
13430 }
13431 
13432 namespace {
13433 /// RAII object to register a special member as being currently declared.
13434 struct DeclaringSpecialMember {
13435   Sema &S;
13436   Sema::SpecialMemberDecl D;
13437   Sema::ContextRAII SavedContext;
13438   bool WasAlreadyBeingDeclared;
13439 
13440   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
13441       : S(S), D(RD, CSM), SavedContext(S, RD) {
13442     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
13443     if (WasAlreadyBeingDeclared)
13444       // This almost never happens, but if it does, ensure that our cache
13445       // doesn't contain a stale result.
13446       S.SpecialMemberCache.clear();
13447     else {
13448       // Register a note to be produced if we encounter an error while
13449       // declaring the special member.
13450       Sema::CodeSynthesisContext Ctx;
13451       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
13452       // FIXME: We don't have a location to use here. Using the class's
13453       // location maintains the fiction that we declare all special members
13454       // with the class, but (1) it's not clear that lying about that helps our
13455       // users understand what's going on, and (2) there may be outer contexts
13456       // on the stack (some of which are relevant) and printing them exposes
13457       // our lies.
13458       Ctx.PointOfInstantiation = RD->getLocation();
13459       Ctx.Entity = RD;
13460       Ctx.SpecialMember = CSM;
13461       S.pushCodeSynthesisContext(Ctx);
13462     }
13463   }
13464   ~DeclaringSpecialMember() {
13465     if (!WasAlreadyBeingDeclared) {
13466       S.SpecialMembersBeingDeclared.erase(D);
13467       S.popCodeSynthesisContext();
13468     }
13469   }
13470 
13471   /// Are we already trying to declare this special member?
13472   bool isAlreadyBeingDeclared() const {
13473     return WasAlreadyBeingDeclared;
13474   }
13475 };
13476 }
13477 
13478 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
13479   // Look up any existing declarations, but don't trigger declaration of all
13480   // implicit special members with this name.
13481   DeclarationName Name = FD->getDeclName();
13482   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
13483                  ForExternalRedeclaration);
13484   for (auto *D : FD->getParent()->lookup(Name))
13485     if (auto *Acceptable = R.getAcceptableDecl(D))
13486       R.addDecl(Acceptable);
13487   R.resolveKind();
13488   R.suppressDiagnostics();
13489 
13490   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/ false,
13491                            FD->isThisDeclarationADefinition());
13492 }
13493 
13494 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
13495                                           QualType ResultTy,
13496                                           ArrayRef<QualType> Args) {
13497   // Build an exception specification pointing back at this constructor.
13498   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
13499 
13500   LangAS AS = getDefaultCXXMethodAddrSpace();
13501   if (AS != LangAS::Default) {
13502     EPI.TypeQuals.addAddressSpace(AS);
13503   }
13504 
13505   auto QT = Context.getFunctionType(ResultTy, Args, EPI);
13506   SpecialMem->setType(QT);
13507 
13508   // During template instantiation of implicit special member functions we need
13509   // a reliable TypeSourceInfo for the function prototype in order to allow
13510   // functions to be substituted.
13511   if (inTemplateInstantiation() &&
13512       cast<CXXRecordDecl>(SpecialMem->getParent())->isLambda()) {
13513     TypeSourceInfo *TSI =
13514         Context.getTrivialTypeSourceInfo(SpecialMem->getType());
13515     SpecialMem->setTypeSourceInfo(TSI);
13516   }
13517 }
13518 
13519 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
13520                                                      CXXRecordDecl *ClassDecl) {
13521   // C++ [class.ctor]p5:
13522   //   A default constructor for a class X is a constructor of class X
13523   //   that can be called without an argument. If there is no
13524   //   user-declared constructor for class X, a default constructor is
13525   //   implicitly declared. An implicitly-declared default constructor
13526   //   is an inline public member of its class.
13527   assert(ClassDecl->needsImplicitDefaultConstructor() &&
13528          "Should not build implicit default constructor!");
13529 
13530   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
13531   if (DSM.isAlreadyBeingDeclared())
13532     return nullptr;
13533 
13534   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13535                                                      CXXDefaultConstructor,
13536                                                      false);
13537 
13538   // Create the actual constructor declaration.
13539   CanQualType ClassType
13540     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13541   SourceLocation ClassLoc = ClassDecl->getLocation();
13542   DeclarationName Name
13543     = Context.DeclarationNames.getCXXConstructorName(ClassType);
13544   DeclarationNameInfo NameInfo(Name, ClassLoc);
13545   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
13546       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
13547       /*TInfo=*/nullptr, ExplicitSpecifier(),
13548       getCurFPFeatures().isFPConstrained(),
13549       /*isInline=*/true, /*isImplicitlyDeclared=*/true,
13550       Constexpr ? ConstexprSpecKind::Constexpr
13551                 : ConstexprSpecKind::Unspecified);
13552   DefaultCon->setAccess(AS_public);
13553   DefaultCon->setDefaulted();
13554 
13555   setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, std::nullopt);
13556 
13557   if (getLangOpts().CUDA)
13558     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
13559                                             DefaultCon,
13560                                             /* ConstRHS */ false,
13561                                             /* Diagnose */ false);
13562 
13563   // We don't need to use SpecialMemberIsTrivial here; triviality for default
13564   // constructors is easy to compute.
13565   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
13566 
13567   // Note that we have declared this constructor.
13568   ++getASTContext().NumImplicitDefaultConstructorsDeclared;
13569 
13570   Scope *S = getScopeForContext(ClassDecl);
13571   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
13572 
13573   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
13574     SetDeclDeleted(DefaultCon, ClassLoc);
13575 
13576   if (S)
13577     PushOnScopeChains(DefaultCon, S, false);
13578   ClassDecl->addDecl(DefaultCon);
13579 
13580   return DefaultCon;
13581 }
13582 
13583 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
13584                                             CXXConstructorDecl *Constructor) {
13585   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
13586           !Constructor->doesThisDeclarationHaveABody() &&
13587           !Constructor->isDeleted()) &&
13588     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
13589   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13590     return;
13591 
13592   CXXRecordDecl *ClassDecl = Constructor->getParent();
13593   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
13594 
13595   SynthesizedFunctionScope Scope(*this, Constructor);
13596 
13597   // The exception specification is needed because we are defining the
13598   // function.
13599   ResolveExceptionSpec(CurrentLocation,
13600                        Constructor->getType()->castAs<FunctionProtoType>());
13601   MarkVTableUsed(CurrentLocation, ClassDecl);
13602 
13603   // Add a context note for diagnostics produced after this point.
13604   Scope.addContextNote(CurrentLocation);
13605 
13606   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
13607     Constructor->setInvalidDecl();
13608     return;
13609   }
13610 
13611   SourceLocation Loc = Constructor->getEndLoc().isValid()
13612                            ? Constructor->getEndLoc()
13613                            : Constructor->getLocation();
13614   Constructor->setBody(new (Context) CompoundStmt(Loc));
13615   Constructor->markUsed(Context);
13616 
13617   if (ASTMutationListener *L = getASTMutationListener()) {
13618     L->CompletedImplicitDefinition(Constructor);
13619   }
13620 
13621   DiagnoseUninitializedFields(*this, Constructor);
13622 }
13623 
13624 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
13625   // Perform any delayed checks on exception specifications.
13626   CheckDelayedMemberExceptionSpecs();
13627 }
13628 
13629 /// Find or create the fake constructor we synthesize to model constructing an
13630 /// object of a derived class via a constructor of a base class.
13631 CXXConstructorDecl *
13632 Sema::findInheritingConstructor(SourceLocation Loc,
13633                                 CXXConstructorDecl *BaseCtor,
13634                                 ConstructorUsingShadowDecl *Shadow) {
13635   CXXRecordDecl *Derived = Shadow->getParent();
13636   SourceLocation UsingLoc = Shadow->getLocation();
13637 
13638   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
13639   // For now we use the name of the base class constructor as a member of the
13640   // derived class to indicate a (fake) inherited constructor name.
13641   DeclarationName Name = BaseCtor->getDeclName();
13642 
13643   // Check to see if we already have a fake constructor for this inherited
13644   // constructor call.
13645   for (NamedDecl *Ctor : Derived->lookup(Name))
13646     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
13647                                ->getInheritedConstructor()
13648                                .getConstructor(),
13649                            BaseCtor))
13650       return cast<CXXConstructorDecl>(Ctor);
13651 
13652   DeclarationNameInfo NameInfo(Name, UsingLoc);
13653   TypeSourceInfo *TInfo =
13654       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
13655   FunctionProtoTypeLoc ProtoLoc =
13656       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
13657 
13658   // Check the inherited constructor is valid and find the list of base classes
13659   // from which it was inherited.
13660   InheritedConstructorInfo ICI(*this, Loc, Shadow);
13661 
13662   bool Constexpr =
13663       BaseCtor->isConstexpr() &&
13664       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
13665                                         false, BaseCtor, &ICI);
13666 
13667   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
13668       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
13669       BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
13670       /*isInline=*/true,
13671       /*isImplicitlyDeclared=*/true,
13672       Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified,
13673       InheritedConstructor(Shadow, BaseCtor),
13674       BaseCtor->getTrailingRequiresClause());
13675   if (Shadow->isInvalidDecl())
13676     DerivedCtor->setInvalidDecl();
13677 
13678   // Build an unevaluated exception specification for this fake constructor.
13679   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
13680   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13681   EPI.ExceptionSpec.Type = EST_Unevaluated;
13682   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
13683   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
13684                                                FPT->getParamTypes(), EPI));
13685 
13686   // Build the parameter declarations.
13687   SmallVector<ParmVarDecl *, 16> ParamDecls;
13688   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
13689     TypeSourceInfo *TInfo =
13690         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
13691     ParmVarDecl *PD = ParmVarDecl::Create(
13692         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
13693         FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
13694     PD->setScopeInfo(0, I);
13695     PD->setImplicit();
13696     // Ensure attributes are propagated onto parameters (this matters for
13697     // format, pass_object_size, ...).
13698     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
13699     ParamDecls.push_back(PD);
13700     ProtoLoc.setParam(I, PD);
13701   }
13702 
13703   // Set up the new constructor.
13704   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
13705   DerivedCtor->setAccess(BaseCtor->getAccess());
13706   DerivedCtor->setParams(ParamDecls);
13707   Derived->addDecl(DerivedCtor);
13708 
13709   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
13710     SetDeclDeleted(DerivedCtor, UsingLoc);
13711 
13712   return DerivedCtor;
13713 }
13714 
13715 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
13716   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
13717                                Ctor->getInheritedConstructor().getShadowDecl());
13718   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
13719                             /*Diagnose*/true);
13720 }
13721 
13722 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
13723                                        CXXConstructorDecl *Constructor) {
13724   CXXRecordDecl *ClassDecl = Constructor->getParent();
13725   assert(Constructor->getInheritedConstructor() &&
13726          !Constructor->doesThisDeclarationHaveABody() &&
13727          !Constructor->isDeleted());
13728   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13729     return;
13730 
13731   // Initializations are performed "as if by a defaulted default constructor",
13732   // so enter the appropriate scope.
13733   SynthesizedFunctionScope Scope(*this, Constructor);
13734 
13735   // The exception specification is needed because we are defining the
13736   // function.
13737   ResolveExceptionSpec(CurrentLocation,
13738                        Constructor->getType()->castAs<FunctionProtoType>());
13739   MarkVTableUsed(CurrentLocation, ClassDecl);
13740 
13741   // Add a context note for diagnostics produced after this point.
13742   Scope.addContextNote(CurrentLocation);
13743 
13744   ConstructorUsingShadowDecl *Shadow =
13745       Constructor->getInheritedConstructor().getShadowDecl();
13746   CXXConstructorDecl *InheritedCtor =
13747       Constructor->getInheritedConstructor().getConstructor();
13748 
13749   // [class.inhctor.init]p1:
13750   //   initialization proceeds as if a defaulted default constructor is used to
13751   //   initialize the D object and each base class subobject from which the
13752   //   constructor was inherited
13753 
13754   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
13755   CXXRecordDecl *RD = Shadow->getParent();
13756   SourceLocation InitLoc = Shadow->getLocation();
13757 
13758   // Build explicit initializers for all base classes from which the
13759   // constructor was inherited.
13760   SmallVector<CXXCtorInitializer*, 8> Inits;
13761   for (bool VBase : {false, true}) {
13762     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
13763       if (B.isVirtual() != VBase)
13764         continue;
13765 
13766       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
13767       if (!BaseRD)
13768         continue;
13769 
13770       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
13771       if (!BaseCtor.first)
13772         continue;
13773 
13774       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
13775       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
13776           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
13777 
13778       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
13779       Inits.push_back(new (Context) CXXCtorInitializer(
13780           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
13781           SourceLocation()));
13782     }
13783   }
13784 
13785   // We now proceed as if for a defaulted default constructor, with the relevant
13786   // initializers replaced.
13787 
13788   if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
13789     Constructor->setInvalidDecl();
13790     return;
13791   }
13792 
13793   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
13794   Constructor->markUsed(Context);
13795 
13796   if (ASTMutationListener *L = getASTMutationListener()) {
13797     L->CompletedImplicitDefinition(Constructor);
13798   }
13799 
13800   DiagnoseUninitializedFields(*this, Constructor);
13801 }
13802 
13803 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
13804   // C++ [class.dtor]p2:
13805   //   If a class has no user-declared destructor, a destructor is
13806   //   declared implicitly. An implicitly-declared destructor is an
13807   //   inline public member of its class.
13808   assert(ClassDecl->needsImplicitDestructor());
13809 
13810   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
13811   if (DSM.isAlreadyBeingDeclared())
13812     return nullptr;
13813 
13814   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13815                                                      CXXDestructor,
13816                                                      false);
13817 
13818   // Create the actual destructor declaration.
13819   CanQualType ClassType
13820     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13821   SourceLocation ClassLoc = ClassDecl->getLocation();
13822   DeclarationName Name
13823     = Context.DeclarationNames.getCXXDestructorName(ClassType);
13824   DeclarationNameInfo NameInfo(Name, ClassLoc);
13825   CXXDestructorDecl *Destructor = CXXDestructorDecl::Create(
13826       Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr,
13827       getCurFPFeatures().isFPConstrained(),
13828       /*isInline=*/true,
13829       /*isImplicitlyDeclared=*/true,
13830       Constexpr ? ConstexprSpecKind::Constexpr
13831                 : ConstexprSpecKind::Unspecified);
13832   Destructor->setAccess(AS_public);
13833   Destructor->setDefaulted();
13834 
13835   setupImplicitSpecialMemberType(Destructor, Context.VoidTy, std::nullopt);
13836 
13837   if (getLangOpts().CUDA)
13838     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
13839                                             Destructor,
13840                                             /* ConstRHS */ false,
13841                                             /* Diagnose */ false);
13842 
13843   // We don't need to use SpecialMemberIsTrivial here; triviality for
13844   // destructors is easy to compute.
13845   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
13846   Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
13847                                 ClassDecl->hasTrivialDestructorForCall());
13848 
13849   // Note that we have declared this destructor.
13850   ++getASTContext().NumImplicitDestructorsDeclared;
13851 
13852   Scope *S = getScopeForContext(ClassDecl);
13853   CheckImplicitSpecialMemberDeclaration(S, Destructor);
13854 
13855   // We can't check whether an implicit destructor is deleted before we complete
13856   // the definition of the class, because its validity depends on the alignment
13857   // of the class. We'll check this from ActOnFields once the class is complete.
13858   if (ClassDecl->isCompleteDefinition() &&
13859       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
13860     SetDeclDeleted(Destructor, ClassLoc);
13861 
13862   // Introduce this destructor into its scope.
13863   if (S)
13864     PushOnScopeChains(Destructor, S, false);
13865   ClassDecl->addDecl(Destructor);
13866 
13867   return Destructor;
13868 }
13869 
13870 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
13871                                     CXXDestructorDecl *Destructor) {
13872   assert((Destructor->isDefaulted() &&
13873           !Destructor->doesThisDeclarationHaveABody() &&
13874           !Destructor->isDeleted()) &&
13875          "DefineImplicitDestructor - call it for implicit default dtor");
13876   if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
13877     return;
13878 
13879   CXXRecordDecl *ClassDecl = Destructor->getParent();
13880   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
13881 
13882   SynthesizedFunctionScope Scope(*this, Destructor);
13883 
13884   // The exception specification is needed because we are defining the
13885   // function.
13886   ResolveExceptionSpec(CurrentLocation,
13887                        Destructor->getType()->castAs<FunctionProtoType>());
13888   MarkVTableUsed(CurrentLocation, ClassDecl);
13889 
13890   // Add a context note for diagnostics produced after this point.
13891   Scope.addContextNote(CurrentLocation);
13892 
13893   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13894                                          Destructor->getParent());
13895 
13896   if (CheckDestructor(Destructor)) {
13897     Destructor->setInvalidDecl();
13898     return;
13899   }
13900 
13901   SourceLocation Loc = Destructor->getEndLoc().isValid()
13902                            ? Destructor->getEndLoc()
13903                            : Destructor->getLocation();
13904   Destructor->setBody(new (Context) CompoundStmt(Loc));
13905   Destructor->markUsed(Context);
13906 
13907   if (ASTMutationListener *L = getASTMutationListener()) {
13908     L->CompletedImplicitDefinition(Destructor);
13909   }
13910 }
13911 
13912 void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
13913                                           CXXDestructorDecl *Destructor) {
13914   if (Destructor->isInvalidDecl())
13915     return;
13916 
13917   CXXRecordDecl *ClassDecl = Destructor->getParent();
13918   assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13919          "implicit complete dtors unneeded outside MS ABI");
13920   assert(ClassDecl->getNumVBases() > 0 &&
13921          "complete dtor only exists for classes with vbases");
13922 
13923   SynthesizedFunctionScope Scope(*this, Destructor);
13924 
13925   // Add a context note for diagnostics produced after this point.
13926   Scope.addContextNote(CurrentLocation);
13927 
13928   MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
13929 }
13930 
13931 /// Perform any semantic analysis which needs to be delayed until all
13932 /// pending class member declarations have been parsed.
13933 void Sema::ActOnFinishCXXMemberDecls() {
13934   // If the context is an invalid C++ class, just suppress these checks.
13935   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
13936     if (Record->isInvalidDecl()) {
13937       DelayedOverridingExceptionSpecChecks.clear();
13938       DelayedEquivalentExceptionSpecChecks.clear();
13939       return;
13940     }
13941     checkForMultipleExportedDefaultConstructors(*this, Record);
13942   }
13943 }
13944 
13945 void Sema::ActOnFinishCXXNonNestedClass() {
13946   referenceDLLExportedClassMethods();
13947 
13948   if (!DelayedDllExportMemberFunctions.empty()) {
13949     SmallVector<CXXMethodDecl*, 4> WorkList;
13950     std::swap(DelayedDllExportMemberFunctions, WorkList);
13951     for (CXXMethodDecl *M : WorkList) {
13952       DefineDefaultedFunction(*this, M, M->getLocation());
13953 
13954       // Pass the method to the consumer to get emitted. This is not necessary
13955       // for explicit instantiation definitions, as they will get emitted
13956       // anyway.
13957       if (M->getParent()->getTemplateSpecializationKind() !=
13958           TSK_ExplicitInstantiationDefinition)
13959         ActOnFinishInlineFunctionDef(M);
13960     }
13961   }
13962 }
13963 
13964 void Sema::referenceDLLExportedClassMethods() {
13965   if (!DelayedDllExportClasses.empty()) {
13966     // Calling ReferenceDllExportedMembers might cause the current function to
13967     // be called again, so use a local copy of DelayedDllExportClasses.
13968     SmallVector<CXXRecordDecl *, 4> WorkList;
13969     std::swap(DelayedDllExportClasses, WorkList);
13970     for (CXXRecordDecl *Class : WorkList)
13971       ReferenceDllExportedMembers(*this, Class);
13972   }
13973 }
13974 
13975 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
13976   assert(getLangOpts().CPlusPlus11 &&
13977          "adjusting dtor exception specs was introduced in c++11");
13978 
13979   if (Destructor->isDependentContext())
13980     return;
13981 
13982   // C++11 [class.dtor]p3:
13983   //   A declaration of a destructor that does not have an exception-
13984   //   specification is implicitly considered to have the same exception-
13985   //   specification as an implicit declaration.
13986   const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
13987   if (DtorType->hasExceptionSpec())
13988     return;
13989 
13990   // Replace the destructor's type, building off the existing one. Fortunately,
13991   // the only thing of interest in the destructor type is its extended info.
13992   // The return and arguments are fixed.
13993   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
13994   EPI.ExceptionSpec.Type = EST_Unevaluated;
13995   EPI.ExceptionSpec.SourceDecl = Destructor;
13996   Destructor->setType(
13997       Context.getFunctionType(Context.VoidTy, std::nullopt, EPI));
13998 
13999   // FIXME: If the destructor has a body that could throw, and the newly created
14000   // spec doesn't allow exceptions, we should emit a warning, because this
14001   // change in behavior can break conforming C++03 programs at runtime.
14002   // However, we don't have a body or an exception specification yet, so it
14003   // needs to be done somewhere else.
14004 }
14005 
14006 namespace {
14007 /// An abstract base class for all helper classes used in building the
14008 //  copy/move operators. These classes serve as factory functions and help us
14009 //  avoid using the same Expr* in the AST twice.
14010 class ExprBuilder {
14011   ExprBuilder(const ExprBuilder&) = delete;
14012   ExprBuilder &operator=(const ExprBuilder&) = delete;
14013 
14014 protected:
14015   static Expr *assertNotNull(Expr *E) {
14016     assert(E && "Expression construction must not fail.");
14017     return E;
14018   }
14019 
14020 public:
14021   ExprBuilder() {}
14022   virtual ~ExprBuilder() {}
14023 
14024   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
14025 };
14026 
14027 class RefBuilder: public ExprBuilder {
14028   VarDecl *Var;
14029   QualType VarType;
14030 
14031 public:
14032   Expr *build(Sema &S, SourceLocation Loc) const override {
14033     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
14034   }
14035 
14036   RefBuilder(VarDecl *Var, QualType VarType)
14037       : Var(Var), VarType(VarType) {}
14038 };
14039 
14040 class ThisBuilder: public ExprBuilder {
14041 public:
14042   Expr *build(Sema &S, SourceLocation Loc) const override {
14043     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
14044   }
14045 };
14046 
14047 class CastBuilder: public ExprBuilder {
14048   const ExprBuilder &Builder;
14049   QualType Type;
14050   ExprValueKind Kind;
14051   const CXXCastPath &Path;
14052 
14053 public:
14054   Expr *build(Sema &S, SourceLocation Loc) const override {
14055     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
14056                                              CK_UncheckedDerivedToBase, Kind,
14057                                              &Path).get());
14058   }
14059 
14060   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
14061               const CXXCastPath &Path)
14062       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
14063 };
14064 
14065 class DerefBuilder: public ExprBuilder {
14066   const ExprBuilder &Builder;
14067 
14068 public:
14069   Expr *build(Sema &S, SourceLocation Loc) const override {
14070     return assertNotNull(
14071         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
14072   }
14073 
14074   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14075 };
14076 
14077 class MemberBuilder: public ExprBuilder {
14078   const ExprBuilder &Builder;
14079   QualType Type;
14080   CXXScopeSpec SS;
14081   bool IsArrow;
14082   LookupResult &MemberLookup;
14083 
14084 public:
14085   Expr *build(Sema &S, SourceLocation Loc) const override {
14086     return assertNotNull(S.BuildMemberReferenceExpr(
14087         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
14088         nullptr, MemberLookup, nullptr, nullptr).get());
14089   }
14090 
14091   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
14092                 LookupResult &MemberLookup)
14093       : Builder(Builder), Type(Type), IsArrow(IsArrow),
14094         MemberLookup(MemberLookup) {}
14095 };
14096 
14097 class MoveCastBuilder: public ExprBuilder {
14098   const ExprBuilder &Builder;
14099 
14100 public:
14101   Expr *build(Sema &S, SourceLocation Loc) const override {
14102     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
14103   }
14104 
14105   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14106 };
14107 
14108 class LvalueConvBuilder: public ExprBuilder {
14109   const ExprBuilder &Builder;
14110 
14111 public:
14112   Expr *build(Sema &S, SourceLocation Loc) const override {
14113     return assertNotNull(
14114         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
14115   }
14116 
14117   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14118 };
14119 
14120 class SubscriptBuilder: public ExprBuilder {
14121   const ExprBuilder &Base;
14122   const ExprBuilder &Index;
14123 
14124 public:
14125   Expr *build(Sema &S, SourceLocation Loc) const override {
14126     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
14127         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
14128   }
14129 
14130   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
14131       : Base(Base), Index(Index) {}
14132 };
14133 
14134 } // end anonymous namespace
14135 
14136 /// When generating a defaulted copy or move assignment operator, if a field
14137 /// should be copied with __builtin_memcpy rather than via explicit assignments,
14138 /// do so. This optimization only applies for arrays of scalars, and for arrays
14139 /// of class type where the selected copy/move-assignment operator is trivial.
14140 static StmtResult
14141 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
14142                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
14143   // Compute the size of the memory buffer to be copied.
14144   QualType SizeType = S.Context.getSizeType();
14145   llvm::APInt Size(S.Context.getTypeSize(SizeType),
14146                    S.Context.getTypeSizeInChars(T).getQuantity());
14147 
14148   // Take the address of the field references for "from" and "to". We
14149   // directly construct UnaryOperators here because semantic analysis
14150   // does not permit us to take the address of an xvalue.
14151   Expr *From = FromB.build(S, Loc);
14152   From = UnaryOperator::Create(
14153       S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
14154       VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14155   Expr *To = ToB.build(S, Loc);
14156   To = UnaryOperator::Create(
14157       S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
14158       VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14159 
14160   const Type *E = T->getBaseElementTypeUnsafe();
14161   bool NeedsCollectableMemCpy =
14162       E->isRecordType() &&
14163       E->castAs<RecordType>()->getDecl()->hasObjectMember();
14164 
14165   // Create a reference to the __builtin_objc_memmove_collectable function
14166   StringRef MemCpyName = NeedsCollectableMemCpy ?
14167     "__builtin_objc_memmove_collectable" :
14168     "__builtin_memcpy";
14169   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
14170                  Sema::LookupOrdinaryName);
14171   S.LookupName(R, S.TUScope, true);
14172 
14173   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
14174   if (!MemCpy)
14175     // Something went horribly wrong earlier, and we will have complained
14176     // about it.
14177     return StmtError();
14178 
14179   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
14180                                             VK_PRValue, Loc, nullptr);
14181   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
14182 
14183   Expr *CallArgs[] = {
14184     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
14185   };
14186   ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
14187                                     Loc, CallArgs, Loc);
14188 
14189   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
14190   return Call.getAs<Stmt>();
14191 }
14192 
14193 /// Builds a statement that copies/moves the given entity from \p From to
14194 /// \c To.
14195 ///
14196 /// This routine is used to copy/move the members of a class with an
14197 /// implicitly-declared copy/move assignment operator. When the entities being
14198 /// copied are arrays, this routine builds for loops to copy them.
14199 ///
14200 /// \param S The Sema object used for type-checking.
14201 ///
14202 /// \param Loc The location where the implicit copy/move is being generated.
14203 ///
14204 /// \param T The type of the expressions being copied/moved. Both expressions
14205 /// must have this type.
14206 ///
14207 /// \param To The expression we are copying/moving to.
14208 ///
14209 /// \param From The expression we are copying/moving from.
14210 ///
14211 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
14212 /// Otherwise, it's a non-static member subobject.
14213 ///
14214 /// \param Copying Whether we're copying or moving.
14215 ///
14216 /// \param Depth Internal parameter recording the depth of the recursion.
14217 ///
14218 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
14219 /// if a memcpy should be used instead.
14220 static StmtResult
14221 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
14222                                  const ExprBuilder &To, const ExprBuilder &From,
14223                                  bool CopyingBaseSubobject, bool Copying,
14224                                  unsigned Depth = 0) {
14225   // C++11 [class.copy]p28:
14226   //   Each subobject is assigned in the manner appropriate to its type:
14227   //
14228   //     - if the subobject is of class type, as if by a call to operator= with
14229   //       the subobject as the object expression and the corresponding
14230   //       subobject of x as a single function argument (as if by explicit
14231   //       qualification; that is, ignoring any possible virtual overriding
14232   //       functions in more derived classes);
14233   //
14234   // C++03 [class.copy]p13:
14235   //     - if the subobject is of class type, the copy assignment operator for
14236   //       the class is used (as if by explicit qualification; that is,
14237   //       ignoring any possible virtual overriding functions in more derived
14238   //       classes);
14239   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
14240     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
14241 
14242     // Look for operator=.
14243     DeclarationName Name
14244       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14245     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
14246     S.LookupQualifiedName(OpLookup, ClassDecl, false);
14247 
14248     // Prior to C++11, filter out any result that isn't a copy/move-assignment
14249     // operator.
14250     if (!S.getLangOpts().CPlusPlus11) {
14251       LookupResult::Filter F = OpLookup.makeFilter();
14252       while (F.hasNext()) {
14253         NamedDecl *D = F.next();
14254         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
14255           if (Method->isCopyAssignmentOperator() ||
14256               (!Copying && Method->isMoveAssignmentOperator()))
14257             continue;
14258 
14259         F.erase();
14260       }
14261       F.done();
14262     }
14263 
14264     // Suppress the protected check (C++ [class.protected]) for each of the
14265     // assignment operators we found. This strange dance is required when
14266     // we're assigning via a base classes's copy-assignment operator. To
14267     // ensure that we're getting the right base class subobject (without
14268     // ambiguities), we need to cast "this" to that subobject type; to
14269     // ensure that we don't go through the virtual call mechanism, we need
14270     // to qualify the operator= name with the base class (see below). However,
14271     // this means that if the base class has a protected copy assignment
14272     // operator, the protected member access check will fail. So, we
14273     // rewrite "protected" access to "public" access in this case, since we
14274     // know by construction that we're calling from a derived class.
14275     if (CopyingBaseSubobject) {
14276       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
14277            L != LEnd; ++L) {
14278         if (L.getAccess() == AS_protected)
14279           L.setAccess(AS_public);
14280       }
14281     }
14282 
14283     // Create the nested-name-specifier that will be used to qualify the
14284     // reference to operator=; this is required to suppress the virtual
14285     // call mechanism.
14286     CXXScopeSpec SS;
14287     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
14288     SS.MakeTrivial(S.Context,
14289                    NestedNameSpecifier::Create(S.Context, nullptr, false,
14290                                                CanonicalT),
14291                    Loc);
14292 
14293     // Create the reference to operator=.
14294     ExprResult OpEqualRef
14295       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
14296                                    SS, /*TemplateKWLoc=*/SourceLocation(),
14297                                    /*FirstQualifierInScope=*/nullptr,
14298                                    OpLookup,
14299                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
14300                                    /*SuppressQualifierCheck=*/true);
14301     if (OpEqualRef.isInvalid())
14302       return StmtError();
14303 
14304     // Build the call to the assignment operator.
14305 
14306     Expr *FromInst = From.build(S, Loc);
14307     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
14308                                                   OpEqualRef.getAs<Expr>(),
14309                                                   Loc, FromInst, Loc);
14310     if (Call.isInvalid())
14311       return StmtError();
14312 
14313     // If we built a call to a trivial 'operator=' while copying an array,
14314     // bail out. We'll replace the whole shebang with a memcpy.
14315     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
14316     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
14317       return StmtResult((Stmt*)nullptr);
14318 
14319     // Convert to an expression-statement, and clean up any produced
14320     // temporaries.
14321     return S.ActOnExprStmt(Call);
14322   }
14323 
14324   //     - if the subobject is of scalar type, the built-in assignment
14325   //       operator is used.
14326   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
14327   if (!ArrayTy) {
14328     ExprResult Assignment = S.CreateBuiltinBinOp(
14329         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
14330     if (Assignment.isInvalid())
14331       return StmtError();
14332     return S.ActOnExprStmt(Assignment);
14333   }
14334 
14335   //     - if the subobject is an array, each element is assigned, in the
14336   //       manner appropriate to the element type;
14337 
14338   // Construct a loop over the array bounds, e.g.,
14339   //
14340   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
14341   //
14342   // that will copy each of the array elements.
14343   QualType SizeType = S.Context.getSizeType();
14344 
14345   // Create the iteration variable.
14346   IdentifierInfo *IterationVarName = nullptr;
14347   {
14348     SmallString<8> Str;
14349     llvm::raw_svector_ostream OS(Str);
14350     OS << "__i" << Depth;
14351     IterationVarName = &S.Context.Idents.get(OS.str());
14352   }
14353   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
14354                                           IterationVarName, SizeType,
14355                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
14356                                           SC_None);
14357 
14358   // Initialize the iteration variable to zero.
14359   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
14360   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
14361 
14362   // Creates a reference to the iteration variable.
14363   RefBuilder IterationVarRef(IterationVar, SizeType);
14364   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
14365 
14366   // Create the DeclStmt that holds the iteration variable.
14367   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
14368 
14369   // Subscript the "from" and "to" expressions with the iteration variable.
14370   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
14371   MoveCastBuilder FromIndexMove(FromIndexCopy);
14372   const ExprBuilder *FromIndex;
14373   if (Copying)
14374     FromIndex = &FromIndexCopy;
14375   else
14376     FromIndex = &FromIndexMove;
14377 
14378   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
14379 
14380   // Build the copy/move for an individual element of the array.
14381   StmtResult Copy =
14382     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
14383                                      ToIndex, *FromIndex, CopyingBaseSubobject,
14384                                      Copying, Depth + 1);
14385   // Bail out if copying fails or if we determined that we should use memcpy.
14386   if (Copy.isInvalid() || !Copy.get())
14387     return Copy;
14388 
14389   // Create the comparison against the array bound.
14390   llvm::APInt Upper
14391     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
14392   Expr *Comparison = BinaryOperator::Create(
14393       S.Context, IterationVarRefRVal.build(S, Loc),
14394       IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
14395       S.Context.BoolTy, VK_PRValue, OK_Ordinary, Loc,
14396       S.CurFPFeatureOverrides());
14397 
14398   // Create the pre-increment of the iteration variable. We can determine
14399   // whether the increment will overflow based on the value of the array
14400   // bound.
14401   Expr *Increment = UnaryOperator::Create(
14402       S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
14403       OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
14404 
14405   // Construct the loop that copies all elements of this array.
14406   return S.ActOnForStmt(
14407       Loc, Loc, InitStmt,
14408       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
14409       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
14410 }
14411 
14412 static StmtResult
14413 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
14414                       const ExprBuilder &To, const ExprBuilder &From,
14415                       bool CopyingBaseSubobject, bool Copying) {
14416   // Maybe we should use a memcpy?
14417   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
14418       T.isTriviallyCopyableType(S.Context))
14419     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14420 
14421   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
14422                                                      CopyingBaseSubobject,
14423                                                      Copying, 0));
14424 
14425   // If we ended up picking a trivial assignment operator for an array of a
14426   // non-trivially-copyable class type, just emit a memcpy.
14427   if (!Result.isInvalid() && !Result.get())
14428     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14429 
14430   return Result;
14431 }
14432 
14433 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
14434   // Note: The following rules are largely analoguous to the copy
14435   // constructor rules. Note that virtual bases are not taken into account
14436   // for determining the argument type of the operator. Note also that
14437   // operators taking an object instead of a reference are allowed.
14438   assert(ClassDecl->needsImplicitCopyAssignment());
14439 
14440   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
14441   if (DSM.isAlreadyBeingDeclared())
14442     return nullptr;
14443 
14444   QualType ArgType = Context.getTypeDeclType(ClassDecl);
14445   ArgType = Context.getElaboratedType(ETK_None, nullptr, ArgType, nullptr);
14446   LangAS AS = getDefaultCXXMethodAddrSpace();
14447   if (AS != LangAS::Default)
14448     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14449   QualType RetType = Context.getLValueReferenceType(ArgType);
14450   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
14451   if (Const)
14452     ArgType = ArgType.withConst();
14453 
14454   ArgType = Context.getLValueReferenceType(ArgType);
14455 
14456   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14457                                                      CXXCopyAssignment,
14458                                                      Const);
14459 
14460   //   An implicitly-declared copy assignment operator is an inline public
14461   //   member of its class.
14462   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14463   SourceLocation ClassLoc = ClassDecl->getLocation();
14464   DeclarationNameInfo NameInfo(Name, ClassLoc);
14465   CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
14466       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14467       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14468       getCurFPFeatures().isFPConstrained(),
14469       /*isInline=*/true,
14470       Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
14471       SourceLocation());
14472   CopyAssignment->setAccess(AS_public);
14473   CopyAssignment->setDefaulted();
14474   CopyAssignment->setImplicit();
14475 
14476   setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
14477 
14478   if (getLangOpts().CUDA)
14479     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
14480                                             CopyAssignment,
14481                                             /* ConstRHS */ Const,
14482                                             /* Diagnose */ false);
14483 
14484   // Add the parameter to the operator.
14485   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
14486                                                ClassLoc, ClassLoc,
14487                                                /*Id=*/nullptr, ArgType,
14488                                                /*TInfo=*/nullptr, SC_None,
14489                                                nullptr);
14490   CopyAssignment->setParams(FromParam);
14491 
14492   CopyAssignment->setTrivial(
14493     ClassDecl->needsOverloadResolutionForCopyAssignment()
14494       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
14495       : ClassDecl->hasTrivialCopyAssignment());
14496 
14497   // Note that we have added this copy-assignment operator.
14498   ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
14499 
14500   Scope *S = getScopeForContext(ClassDecl);
14501   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
14502 
14503   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) {
14504     ClassDecl->setImplicitCopyAssignmentIsDeleted();
14505     SetDeclDeleted(CopyAssignment, ClassLoc);
14506   }
14507 
14508   if (S)
14509     PushOnScopeChains(CopyAssignment, S, false);
14510   ClassDecl->addDecl(CopyAssignment);
14511 
14512   return CopyAssignment;
14513 }
14514 
14515 /// Diagnose an implicit copy operation for a class which is odr-used, but
14516 /// which is deprecated because the class has a user-declared copy constructor,
14517 /// copy assignment operator, or destructor.
14518 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
14519   assert(CopyOp->isImplicit());
14520 
14521   CXXRecordDecl *RD = CopyOp->getParent();
14522   CXXMethodDecl *UserDeclaredOperation = nullptr;
14523 
14524   if (RD->hasUserDeclaredDestructor()) {
14525     UserDeclaredOperation = RD->getDestructor();
14526   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
14527              RD->hasUserDeclaredCopyConstructor()) {
14528     // Find any user-declared copy constructor.
14529     for (auto *I : RD->ctors()) {
14530       if (I->isCopyConstructor()) {
14531         UserDeclaredOperation = I;
14532         break;
14533       }
14534     }
14535     assert(UserDeclaredOperation);
14536   } else if (isa<CXXConstructorDecl>(CopyOp) &&
14537              RD->hasUserDeclaredCopyAssignment()) {
14538     // Find any user-declared move assignment operator.
14539     for (auto *I : RD->methods()) {
14540       if (I->isCopyAssignmentOperator()) {
14541         UserDeclaredOperation = I;
14542         break;
14543       }
14544     }
14545     assert(UserDeclaredOperation);
14546   }
14547 
14548   if (UserDeclaredOperation) {
14549     bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
14550     bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation);
14551     bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp);
14552     unsigned DiagID =
14553         (UDOIsUserProvided && UDOIsDestructor)
14554             ? diag::warn_deprecated_copy_with_user_provided_dtor
14555         : (UDOIsUserProvided && !UDOIsDestructor)
14556             ? diag::warn_deprecated_copy_with_user_provided_copy
14557         : (!UDOIsUserProvided && UDOIsDestructor)
14558             ? diag::warn_deprecated_copy_with_dtor
14559             : diag::warn_deprecated_copy;
14560     S.Diag(UserDeclaredOperation->getLocation(), DiagID)
14561         << RD << IsCopyAssignment;
14562   }
14563 }
14564 
14565 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
14566                                         CXXMethodDecl *CopyAssignOperator) {
14567   assert((CopyAssignOperator->isDefaulted() &&
14568           CopyAssignOperator->isOverloadedOperator() &&
14569           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
14570           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
14571           !CopyAssignOperator->isDeleted()) &&
14572          "DefineImplicitCopyAssignment called for wrong function");
14573   if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
14574     return;
14575 
14576   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
14577   if (ClassDecl->isInvalidDecl()) {
14578     CopyAssignOperator->setInvalidDecl();
14579     return;
14580   }
14581 
14582   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
14583 
14584   // The exception specification is needed because we are defining the
14585   // function.
14586   ResolveExceptionSpec(CurrentLocation,
14587                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
14588 
14589   // Add a context note for diagnostics produced after this point.
14590   Scope.addContextNote(CurrentLocation);
14591 
14592   // C++11 [class.copy]p18:
14593   //   The [definition of an implicitly declared copy assignment operator] is
14594   //   deprecated if the class has a user-declared copy constructor or a
14595   //   user-declared destructor.
14596   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
14597     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
14598 
14599   // C++0x [class.copy]p30:
14600   //   The implicitly-defined or explicitly-defaulted copy assignment operator
14601   //   for a non-union class X performs memberwise copy assignment of its
14602   //   subobjects. The direct base classes of X are assigned first, in the
14603   //   order of their declaration in the base-specifier-list, and then the
14604   //   immediate non-static data members of X are assigned, in the order in
14605   //   which they were declared in the class definition.
14606 
14607   // The statements that form the synthesized function body.
14608   SmallVector<Stmt*, 8> Statements;
14609 
14610   // The parameter for the "other" object, which we are copying from.
14611   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
14612   Qualifiers OtherQuals = Other->getType().getQualifiers();
14613   QualType OtherRefType = Other->getType();
14614   if (const LValueReferenceType *OtherRef
14615                                 = OtherRefType->getAs<LValueReferenceType>()) {
14616     OtherRefType = OtherRef->getPointeeType();
14617     OtherQuals = OtherRefType.getQualifiers();
14618   }
14619 
14620   // Our location for everything implicitly-generated.
14621   SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
14622                            ? CopyAssignOperator->getEndLoc()
14623                            : CopyAssignOperator->getLocation();
14624 
14625   // Builds a DeclRefExpr for the "other" object.
14626   RefBuilder OtherRef(Other, OtherRefType);
14627 
14628   // Builds the "this" pointer.
14629   ThisBuilder This;
14630 
14631   // Assign base classes.
14632   bool Invalid = false;
14633   for (auto &Base : ClassDecl->bases()) {
14634     // Form the assignment:
14635     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
14636     QualType BaseType = Base.getType().getUnqualifiedType();
14637     if (!BaseType->isRecordType()) {
14638       Invalid = true;
14639       continue;
14640     }
14641 
14642     CXXCastPath BasePath;
14643     BasePath.push_back(&Base);
14644 
14645     // Construct the "from" expression, which is an implicit cast to the
14646     // appropriately-qualified base type.
14647     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
14648                      VK_LValue, BasePath);
14649 
14650     // Dereference "this".
14651     DerefBuilder DerefThis(This);
14652     CastBuilder To(DerefThis,
14653                    Context.getQualifiedType(
14654                        BaseType, CopyAssignOperator->getMethodQualifiers()),
14655                    VK_LValue, BasePath);
14656 
14657     // Build the copy.
14658     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
14659                                             To, From,
14660                                             /*CopyingBaseSubobject=*/true,
14661                                             /*Copying=*/true);
14662     if (Copy.isInvalid()) {
14663       CopyAssignOperator->setInvalidDecl();
14664       return;
14665     }
14666 
14667     // Success! Record the copy.
14668     Statements.push_back(Copy.getAs<Expr>());
14669   }
14670 
14671   // Assign non-static members.
14672   for (auto *Field : ClassDecl->fields()) {
14673     // FIXME: We should form some kind of AST representation for the implied
14674     // memcpy in a union copy operation.
14675     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14676       continue;
14677 
14678     if (Field->isInvalidDecl()) {
14679       Invalid = true;
14680       continue;
14681     }
14682 
14683     // Check for members of reference type; we can't copy those.
14684     if (Field->getType()->isReferenceType()) {
14685       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14686         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14687       Diag(Field->getLocation(), diag::note_declared_at);
14688       Invalid = true;
14689       continue;
14690     }
14691 
14692     // Check for members of const-qualified, non-class type.
14693     QualType BaseType = Context.getBaseElementType(Field->getType());
14694     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14695       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14696         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14697       Diag(Field->getLocation(), diag::note_declared_at);
14698       Invalid = true;
14699       continue;
14700     }
14701 
14702     // Suppress assigning zero-width bitfields.
14703     if (Field->isZeroLengthBitField(Context))
14704       continue;
14705 
14706     QualType FieldType = Field->getType().getNonReferenceType();
14707     if (FieldType->isIncompleteArrayType()) {
14708       assert(ClassDecl->hasFlexibleArrayMember() &&
14709              "Incomplete array type is not valid");
14710       continue;
14711     }
14712 
14713     // Build references to the field in the object we're copying from and to.
14714     CXXScopeSpec SS; // Intentionally empty
14715     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14716                               LookupMemberName);
14717     MemberLookup.addDecl(Field);
14718     MemberLookup.resolveKind();
14719 
14720     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
14721 
14722     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/!LangOpts.HLSL,
14723                      MemberLookup);
14724 
14725     // Build the copy of this field.
14726     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
14727                                             To, From,
14728                                             /*CopyingBaseSubobject=*/false,
14729                                             /*Copying=*/true);
14730     if (Copy.isInvalid()) {
14731       CopyAssignOperator->setInvalidDecl();
14732       return;
14733     }
14734 
14735     // Success! Record the copy.
14736     Statements.push_back(Copy.getAs<Stmt>());
14737   }
14738 
14739   if (!Invalid) {
14740     // Add a "return *this;"
14741     Expr *ThisExpr = nullptr;
14742     if (!LangOpts.HLSL) {
14743       ExprResult ThisObj =
14744           CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14745       ThisExpr = ThisObj.get();
14746     } else {
14747       ThisExpr = This.build(*this, Loc);
14748     }
14749 
14750     StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
14751     if (Return.isInvalid())
14752       Invalid = true;
14753     else
14754       Statements.push_back(Return.getAs<Stmt>());
14755   }
14756 
14757   if (Invalid) {
14758     CopyAssignOperator->setInvalidDecl();
14759     return;
14760   }
14761 
14762   StmtResult Body;
14763   {
14764     CompoundScopeRAII CompoundScope(*this);
14765     Body = ActOnCompoundStmt(Loc, Loc, Statements,
14766                              /*isStmtExpr=*/false);
14767     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
14768   }
14769   CopyAssignOperator->setBody(Body.getAs<Stmt>());
14770   CopyAssignOperator->markUsed(Context);
14771 
14772   if (ASTMutationListener *L = getASTMutationListener()) {
14773     L->CompletedImplicitDefinition(CopyAssignOperator);
14774   }
14775 }
14776 
14777 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
14778   assert(ClassDecl->needsImplicitMoveAssignment());
14779 
14780   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
14781   if (DSM.isAlreadyBeingDeclared())
14782     return nullptr;
14783 
14784   // Note: The following rules are largely analoguous to the move
14785   // constructor rules.
14786 
14787   QualType ArgType = Context.getTypeDeclType(ClassDecl);
14788   ArgType = Context.getElaboratedType(ETK_None, nullptr, ArgType, nullptr);
14789   LangAS AS = getDefaultCXXMethodAddrSpace();
14790   if (AS != LangAS::Default)
14791     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14792   QualType RetType = Context.getLValueReferenceType(ArgType);
14793   ArgType = Context.getRValueReferenceType(ArgType);
14794 
14795   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14796                                                      CXXMoveAssignment,
14797                                                      false);
14798 
14799   //   An implicitly-declared move assignment operator is an inline public
14800   //   member of its class.
14801   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14802   SourceLocation ClassLoc = ClassDecl->getLocation();
14803   DeclarationNameInfo NameInfo(Name, ClassLoc);
14804   CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
14805       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14806       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14807       getCurFPFeatures().isFPConstrained(),
14808       /*isInline=*/true,
14809       Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
14810       SourceLocation());
14811   MoveAssignment->setAccess(AS_public);
14812   MoveAssignment->setDefaulted();
14813   MoveAssignment->setImplicit();
14814 
14815   setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType);
14816 
14817   if (getLangOpts().CUDA)
14818     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
14819                                             MoveAssignment,
14820                                             /* ConstRHS */ false,
14821                                             /* Diagnose */ false);
14822 
14823   // Add the parameter to the operator.
14824   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
14825                                                ClassLoc, ClassLoc,
14826                                                /*Id=*/nullptr, ArgType,
14827                                                /*TInfo=*/nullptr, SC_None,
14828                                                nullptr);
14829   MoveAssignment->setParams(FromParam);
14830 
14831   MoveAssignment->setTrivial(
14832     ClassDecl->needsOverloadResolutionForMoveAssignment()
14833       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
14834       : ClassDecl->hasTrivialMoveAssignment());
14835 
14836   // Note that we have added this copy-assignment operator.
14837   ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
14838 
14839   Scope *S = getScopeForContext(ClassDecl);
14840   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
14841 
14842   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
14843     ClassDecl->setImplicitMoveAssignmentIsDeleted();
14844     SetDeclDeleted(MoveAssignment, ClassLoc);
14845   }
14846 
14847   if (S)
14848     PushOnScopeChains(MoveAssignment, S, false);
14849   ClassDecl->addDecl(MoveAssignment);
14850 
14851   return MoveAssignment;
14852 }
14853 
14854 /// Check if we're implicitly defining a move assignment operator for a class
14855 /// with virtual bases. Such a move assignment might move-assign the virtual
14856 /// base multiple times.
14857 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
14858                                                SourceLocation CurrentLocation) {
14859   assert(!Class->isDependentContext() && "should not define dependent move");
14860 
14861   // Only a virtual base could get implicitly move-assigned multiple times.
14862   // Only a non-trivial move assignment can observe this. We only want to
14863   // diagnose if we implicitly define an assignment operator that assigns
14864   // two base classes, both of which move-assign the same virtual base.
14865   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
14866       Class->getNumBases() < 2)
14867     return;
14868 
14869   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
14870   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
14871   VBaseMap VBases;
14872 
14873   for (auto &BI : Class->bases()) {
14874     Worklist.push_back(&BI);
14875     while (!Worklist.empty()) {
14876       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
14877       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
14878 
14879       // If the base has no non-trivial move assignment operators,
14880       // we don't care about moves from it.
14881       if (!Base->hasNonTrivialMoveAssignment())
14882         continue;
14883 
14884       // If there's nothing virtual here, skip it.
14885       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
14886         continue;
14887 
14888       // If we're not actually going to call a move assignment for this base,
14889       // or the selected move assignment is trivial, skip it.
14890       Sema::SpecialMemberOverloadResult SMOR =
14891         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
14892                               /*ConstArg*/false, /*VolatileArg*/false,
14893                               /*RValueThis*/true, /*ConstThis*/false,
14894                               /*VolatileThis*/false);
14895       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
14896           !SMOR.getMethod()->isMoveAssignmentOperator())
14897         continue;
14898 
14899       if (BaseSpec->isVirtual()) {
14900         // We're going to move-assign this virtual base, and its move
14901         // assignment operator is not trivial. If this can happen for
14902         // multiple distinct direct bases of Class, diagnose it. (If it
14903         // only happens in one base, we'll diagnose it when synthesizing
14904         // that base class's move assignment operator.)
14905         CXXBaseSpecifier *&Existing =
14906             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
14907                 .first->second;
14908         if (Existing && Existing != &BI) {
14909           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
14910             << Class << Base;
14911           S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
14912               << (Base->getCanonicalDecl() ==
14913                   Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14914               << Base << Existing->getType() << Existing->getSourceRange();
14915           S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
14916               << (Base->getCanonicalDecl() ==
14917                   BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14918               << Base << BI.getType() << BaseSpec->getSourceRange();
14919 
14920           // Only diagnose each vbase once.
14921           Existing = nullptr;
14922         }
14923       } else {
14924         // Only walk over bases that have defaulted move assignment operators.
14925         // We assume that any user-provided move assignment operator handles
14926         // the multiple-moves-of-vbase case itself somehow.
14927         if (!SMOR.getMethod()->isDefaulted())
14928           continue;
14929 
14930         // We're going to move the base classes of Base. Add them to the list.
14931         llvm::append_range(Worklist, llvm::make_pointer_range(Base->bases()));
14932       }
14933     }
14934   }
14935 }
14936 
14937 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
14938                                         CXXMethodDecl *MoveAssignOperator) {
14939   assert((MoveAssignOperator->isDefaulted() &&
14940           MoveAssignOperator->isOverloadedOperator() &&
14941           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
14942           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
14943           !MoveAssignOperator->isDeleted()) &&
14944          "DefineImplicitMoveAssignment called for wrong function");
14945   if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
14946     return;
14947 
14948   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
14949   if (ClassDecl->isInvalidDecl()) {
14950     MoveAssignOperator->setInvalidDecl();
14951     return;
14952   }
14953 
14954   // C++0x [class.copy]p28:
14955   //   The implicitly-defined or move assignment operator for a non-union class
14956   //   X performs memberwise move assignment of its subobjects. The direct base
14957   //   classes of X are assigned first, in the order of their declaration in the
14958   //   base-specifier-list, and then the immediate non-static data members of X
14959   //   are assigned, in the order in which they were declared in the class
14960   //   definition.
14961 
14962   // Issue a warning if our implicit move assignment operator will move
14963   // from a virtual base more than once.
14964   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
14965 
14966   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
14967 
14968   // The exception specification is needed because we are defining the
14969   // function.
14970   ResolveExceptionSpec(CurrentLocation,
14971                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
14972 
14973   // Add a context note for diagnostics produced after this point.
14974   Scope.addContextNote(CurrentLocation);
14975 
14976   // The statements that form the synthesized function body.
14977   SmallVector<Stmt*, 8> Statements;
14978 
14979   // The parameter for the "other" object, which we are move from.
14980   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
14981   QualType OtherRefType =
14982       Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
14983 
14984   // Our location for everything implicitly-generated.
14985   SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
14986                            ? MoveAssignOperator->getEndLoc()
14987                            : MoveAssignOperator->getLocation();
14988 
14989   // Builds a reference to the "other" object.
14990   RefBuilder OtherRef(Other, OtherRefType);
14991   // Cast to rvalue.
14992   MoveCastBuilder MoveOther(OtherRef);
14993 
14994   // Builds the "this" pointer.
14995   ThisBuilder This;
14996 
14997   // Assign base classes.
14998   bool Invalid = false;
14999   for (auto &Base : ClassDecl->bases()) {
15000     // C++11 [class.copy]p28:
15001     //   It is unspecified whether subobjects representing virtual base classes
15002     //   are assigned more than once by the implicitly-defined copy assignment
15003     //   operator.
15004     // FIXME: Do not assign to a vbase that will be assigned by some other base
15005     // class. For a move-assignment, this can result in the vbase being moved
15006     // multiple times.
15007 
15008     // Form the assignment:
15009     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
15010     QualType BaseType = Base.getType().getUnqualifiedType();
15011     if (!BaseType->isRecordType()) {
15012       Invalid = true;
15013       continue;
15014     }
15015 
15016     CXXCastPath BasePath;
15017     BasePath.push_back(&Base);
15018 
15019     // Construct the "from" expression, which is an implicit cast to the
15020     // appropriately-qualified base type.
15021     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
15022 
15023     // Dereference "this".
15024     DerefBuilder DerefThis(This);
15025 
15026     // Implicitly cast "this" to the appropriately-qualified base type.
15027     CastBuilder To(DerefThis,
15028                    Context.getQualifiedType(
15029                        BaseType, MoveAssignOperator->getMethodQualifiers()),
15030                    VK_LValue, BasePath);
15031 
15032     // Build the move.
15033     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
15034                                             To, From,
15035                                             /*CopyingBaseSubobject=*/true,
15036                                             /*Copying=*/false);
15037     if (Move.isInvalid()) {
15038       MoveAssignOperator->setInvalidDecl();
15039       return;
15040     }
15041 
15042     // Success! Record the move.
15043     Statements.push_back(Move.getAs<Expr>());
15044   }
15045 
15046   // Assign non-static members.
15047   for (auto *Field : ClassDecl->fields()) {
15048     // FIXME: We should form some kind of AST representation for the implied
15049     // memcpy in a union copy operation.
15050     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
15051       continue;
15052 
15053     if (Field->isInvalidDecl()) {
15054       Invalid = true;
15055       continue;
15056     }
15057 
15058     // Check for members of reference type; we can't move those.
15059     if (Field->getType()->isReferenceType()) {
15060       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15061         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
15062       Diag(Field->getLocation(), diag::note_declared_at);
15063       Invalid = true;
15064       continue;
15065     }
15066 
15067     // Check for members of const-qualified, non-class type.
15068     QualType BaseType = Context.getBaseElementType(Field->getType());
15069     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
15070       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15071         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
15072       Diag(Field->getLocation(), diag::note_declared_at);
15073       Invalid = true;
15074       continue;
15075     }
15076 
15077     // Suppress assigning zero-width bitfields.
15078     if (Field->isZeroLengthBitField(Context))
15079       continue;
15080 
15081     QualType FieldType = Field->getType().getNonReferenceType();
15082     if (FieldType->isIncompleteArrayType()) {
15083       assert(ClassDecl->hasFlexibleArrayMember() &&
15084              "Incomplete array type is not valid");
15085       continue;
15086     }
15087 
15088     // Build references to the field in the object we're copying from and to.
15089     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15090                               LookupMemberName);
15091     MemberLookup.addDecl(Field);
15092     MemberLookup.resolveKind();
15093     MemberBuilder From(MoveOther, OtherRefType,
15094                        /*IsArrow=*/false, MemberLookup);
15095     MemberBuilder To(This, getCurrentThisType(),
15096                      /*IsArrow=*/true, MemberLookup);
15097 
15098     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
15099         "Member reference with rvalue base must be rvalue except for reference "
15100         "members, which aren't allowed for move assignment.");
15101 
15102     // Build the move of this field.
15103     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
15104                                             To, From,
15105                                             /*CopyingBaseSubobject=*/false,
15106                                             /*Copying=*/false);
15107     if (Move.isInvalid()) {
15108       MoveAssignOperator->setInvalidDecl();
15109       return;
15110     }
15111 
15112     // Success! Record the copy.
15113     Statements.push_back(Move.getAs<Stmt>());
15114   }
15115 
15116   if (!Invalid) {
15117     // Add a "return *this;"
15118     ExprResult ThisObj =
15119         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
15120 
15121     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
15122     if (Return.isInvalid())
15123       Invalid = true;
15124     else
15125       Statements.push_back(Return.getAs<Stmt>());
15126   }
15127 
15128   if (Invalid) {
15129     MoveAssignOperator->setInvalidDecl();
15130     return;
15131   }
15132 
15133   StmtResult Body;
15134   {
15135     CompoundScopeRAII CompoundScope(*this);
15136     Body = ActOnCompoundStmt(Loc, Loc, Statements,
15137                              /*isStmtExpr=*/false);
15138     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15139   }
15140   MoveAssignOperator->setBody(Body.getAs<Stmt>());
15141   MoveAssignOperator->markUsed(Context);
15142 
15143   if (ASTMutationListener *L = getASTMutationListener()) {
15144     L->CompletedImplicitDefinition(MoveAssignOperator);
15145   }
15146 }
15147 
15148 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
15149                                                     CXXRecordDecl *ClassDecl) {
15150   // C++ [class.copy]p4:
15151   //   If the class definition does not explicitly declare a copy
15152   //   constructor, one is declared implicitly.
15153   assert(ClassDecl->needsImplicitCopyConstructor());
15154 
15155   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
15156   if (DSM.isAlreadyBeingDeclared())
15157     return nullptr;
15158 
15159   QualType ClassType = Context.getTypeDeclType(ClassDecl);
15160   QualType ArgType = ClassType;
15161   ArgType = Context.getElaboratedType(ETK_None, nullptr, ArgType, nullptr);
15162   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
15163   if (Const)
15164     ArgType = ArgType.withConst();
15165 
15166   LangAS AS = getDefaultCXXMethodAddrSpace();
15167   if (AS != LangAS::Default)
15168     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15169 
15170   ArgType = Context.getLValueReferenceType(ArgType);
15171 
15172   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
15173                                                      CXXCopyConstructor,
15174                                                      Const);
15175 
15176   DeclarationName Name
15177     = Context.DeclarationNames.getCXXConstructorName(
15178                                            Context.getCanonicalType(ClassType));
15179   SourceLocation ClassLoc = ClassDecl->getLocation();
15180   DeclarationNameInfo NameInfo(Name, ClassLoc);
15181 
15182   //   An implicitly-declared copy constructor is an inline public
15183   //   member of its class.
15184   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
15185       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15186       ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15187       /*isInline=*/true,
15188       /*isImplicitlyDeclared=*/true,
15189       Constexpr ? ConstexprSpecKind::Constexpr
15190                 : ConstexprSpecKind::Unspecified);
15191   CopyConstructor->setAccess(AS_public);
15192   CopyConstructor->setDefaulted();
15193 
15194   setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
15195 
15196   if (getLangOpts().CUDA)
15197     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
15198                                             CopyConstructor,
15199                                             /* ConstRHS */ Const,
15200                                             /* Diagnose */ false);
15201 
15202   // During template instantiation of special member functions we need a
15203   // reliable TypeSourceInfo for the parameter types in order to allow functions
15204   // to be substituted.
15205   TypeSourceInfo *TSI = nullptr;
15206   if (inTemplateInstantiation() && ClassDecl->isLambda())
15207     TSI = Context.getTrivialTypeSourceInfo(ArgType);
15208 
15209   // Add the parameter to the constructor.
15210   ParmVarDecl *FromParam =
15211       ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc,
15212                           /*IdentifierInfo=*/nullptr, ArgType,
15213                           /*TInfo=*/TSI, SC_None, nullptr);
15214   CopyConstructor->setParams(FromParam);
15215 
15216   CopyConstructor->setTrivial(
15217       ClassDecl->needsOverloadResolutionForCopyConstructor()
15218           ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
15219           : ClassDecl->hasTrivialCopyConstructor());
15220 
15221   CopyConstructor->setTrivialForCall(
15222       ClassDecl->hasAttr<TrivialABIAttr>() ||
15223       (ClassDecl->needsOverloadResolutionForCopyConstructor()
15224            ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
15225              TAH_ConsiderTrivialABI)
15226            : ClassDecl->hasTrivialCopyConstructorForCall()));
15227 
15228   // Note that we have declared this constructor.
15229   ++getASTContext().NumImplicitCopyConstructorsDeclared;
15230 
15231   Scope *S = getScopeForContext(ClassDecl);
15232   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
15233 
15234   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
15235     ClassDecl->setImplicitCopyConstructorIsDeleted();
15236     SetDeclDeleted(CopyConstructor, ClassLoc);
15237   }
15238 
15239   if (S)
15240     PushOnScopeChains(CopyConstructor, S, false);
15241   ClassDecl->addDecl(CopyConstructor);
15242 
15243   return CopyConstructor;
15244 }
15245 
15246 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
15247                                          CXXConstructorDecl *CopyConstructor) {
15248   assert((CopyConstructor->isDefaulted() &&
15249           CopyConstructor->isCopyConstructor() &&
15250           !CopyConstructor->doesThisDeclarationHaveABody() &&
15251           !CopyConstructor->isDeleted()) &&
15252          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
15253   if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
15254     return;
15255 
15256   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
15257   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
15258 
15259   SynthesizedFunctionScope Scope(*this, CopyConstructor);
15260 
15261   // The exception specification is needed because we are defining the
15262   // function.
15263   ResolveExceptionSpec(CurrentLocation,
15264                        CopyConstructor->getType()->castAs<FunctionProtoType>());
15265   MarkVTableUsed(CurrentLocation, ClassDecl);
15266 
15267   // Add a context note for diagnostics produced after this point.
15268   Scope.addContextNote(CurrentLocation);
15269 
15270   // C++11 [class.copy]p7:
15271   //   The [definition of an implicitly declared copy constructor] is
15272   //   deprecated if the class has a user-declared copy assignment operator
15273   //   or a user-declared destructor.
15274   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
15275     diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
15276 
15277   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
15278     CopyConstructor->setInvalidDecl();
15279   }  else {
15280     SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
15281                              ? CopyConstructor->getEndLoc()
15282                              : CopyConstructor->getLocation();
15283     Sema::CompoundScopeRAII CompoundScope(*this);
15284     CopyConstructor->setBody(
15285         ActOnCompoundStmt(Loc, Loc, std::nullopt, /*isStmtExpr=*/false)
15286             .getAs<Stmt>());
15287     CopyConstructor->markUsed(Context);
15288   }
15289 
15290   if (ASTMutationListener *L = getASTMutationListener()) {
15291     L->CompletedImplicitDefinition(CopyConstructor);
15292   }
15293 }
15294 
15295 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
15296                                                     CXXRecordDecl *ClassDecl) {
15297   assert(ClassDecl->needsImplicitMoveConstructor());
15298 
15299   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
15300   if (DSM.isAlreadyBeingDeclared())
15301     return nullptr;
15302 
15303   QualType ClassType = Context.getTypeDeclType(ClassDecl);
15304 
15305   QualType ArgType = ClassType;
15306   ArgType = Context.getElaboratedType(ETK_None, nullptr, ArgType, nullptr);
15307   LangAS AS = getDefaultCXXMethodAddrSpace();
15308   if (AS != LangAS::Default)
15309     ArgType = Context.getAddrSpaceQualType(ClassType, AS);
15310   ArgType = Context.getRValueReferenceType(ArgType);
15311 
15312   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
15313                                                      CXXMoveConstructor,
15314                                                      false);
15315 
15316   DeclarationName Name
15317     = Context.DeclarationNames.getCXXConstructorName(
15318                                            Context.getCanonicalType(ClassType));
15319   SourceLocation ClassLoc = ClassDecl->getLocation();
15320   DeclarationNameInfo NameInfo(Name, ClassLoc);
15321 
15322   // C++11 [class.copy]p11:
15323   //   An implicitly-declared copy/move constructor is an inline public
15324   //   member of its class.
15325   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
15326       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15327       ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15328       /*isInline=*/true,
15329       /*isImplicitlyDeclared=*/true,
15330       Constexpr ? ConstexprSpecKind::Constexpr
15331                 : ConstexprSpecKind::Unspecified);
15332   MoveConstructor->setAccess(AS_public);
15333   MoveConstructor->setDefaulted();
15334 
15335   setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
15336 
15337   if (getLangOpts().CUDA)
15338     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
15339                                             MoveConstructor,
15340                                             /* ConstRHS */ false,
15341                                             /* Diagnose */ false);
15342 
15343   // Add the parameter to the constructor.
15344   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
15345                                                ClassLoc, ClassLoc,
15346                                                /*IdentifierInfo=*/nullptr,
15347                                                ArgType, /*TInfo=*/nullptr,
15348                                                SC_None, nullptr);
15349   MoveConstructor->setParams(FromParam);
15350 
15351   MoveConstructor->setTrivial(
15352       ClassDecl->needsOverloadResolutionForMoveConstructor()
15353           ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
15354           : ClassDecl->hasTrivialMoveConstructor());
15355 
15356   MoveConstructor->setTrivialForCall(
15357       ClassDecl->hasAttr<TrivialABIAttr>() ||
15358       (ClassDecl->needsOverloadResolutionForMoveConstructor()
15359            ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
15360                                     TAH_ConsiderTrivialABI)
15361            : ClassDecl->hasTrivialMoveConstructorForCall()));
15362 
15363   // Note that we have declared this constructor.
15364   ++getASTContext().NumImplicitMoveConstructorsDeclared;
15365 
15366   Scope *S = getScopeForContext(ClassDecl);
15367   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
15368 
15369   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
15370     ClassDecl->setImplicitMoveConstructorIsDeleted();
15371     SetDeclDeleted(MoveConstructor, ClassLoc);
15372   }
15373 
15374   if (S)
15375     PushOnScopeChains(MoveConstructor, S, false);
15376   ClassDecl->addDecl(MoveConstructor);
15377 
15378   return MoveConstructor;
15379 }
15380 
15381 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
15382                                          CXXConstructorDecl *MoveConstructor) {
15383   assert((MoveConstructor->isDefaulted() &&
15384           MoveConstructor->isMoveConstructor() &&
15385           !MoveConstructor->doesThisDeclarationHaveABody() &&
15386           !MoveConstructor->isDeleted()) &&
15387          "DefineImplicitMoveConstructor - call it for implicit move ctor");
15388   if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
15389     return;
15390 
15391   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
15392   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
15393 
15394   SynthesizedFunctionScope Scope(*this, MoveConstructor);
15395 
15396   // The exception specification is needed because we are defining the
15397   // function.
15398   ResolveExceptionSpec(CurrentLocation,
15399                        MoveConstructor->getType()->castAs<FunctionProtoType>());
15400   MarkVTableUsed(CurrentLocation, ClassDecl);
15401 
15402   // Add a context note for diagnostics produced after this point.
15403   Scope.addContextNote(CurrentLocation);
15404 
15405   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
15406     MoveConstructor->setInvalidDecl();
15407   } else {
15408     SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
15409                              ? MoveConstructor->getEndLoc()
15410                              : MoveConstructor->getLocation();
15411     Sema::CompoundScopeRAII CompoundScope(*this);
15412     MoveConstructor->setBody(
15413         ActOnCompoundStmt(Loc, Loc, std::nullopt, /*isStmtExpr=*/false)
15414             .getAs<Stmt>());
15415     MoveConstructor->markUsed(Context);
15416   }
15417 
15418   if (ASTMutationListener *L = getASTMutationListener()) {
15419     L->CompletedImplicitDefinition(MoveConstructor);
15420   }
15421 }
15422 
15423 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
15424   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
15425 }
15426 
15427 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
15428                             SourceLocation CurrentLocation,
15429                             CXXConversionDecl *Conv) {
15430   SynthesizedFunctionScope Scope(*this, Conv);
15431   assert(!Conv->getReturnType()->isUndeducedType());
15432 
15433   QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
15434   CallingConv CC =
15435       ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
15436 
15437   CXXRecordDecl *Lambda = Conv->getParent();
15438   FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
15439   FunctionDecl *Invoker =
15440       CallOp->isStatic() ? CallOp : Lambda->getLambdaStaticInvoker(CC);
15441 
15442   if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
15443     CallOp = InstantiateFunctionDeclaration(
15444         CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
15445     if (!CallOp)
15446       return;
15447 
15448     if (CallOp != Invoker) {
15449       Invoker = InstantiateFunctionDeclaration(
15450           Invoker->getDescribedFunctionTemplate(), TemplateArgs,
15451           CurrentLocation);
15452       if (!Invoker)
15453         return;
15454     }
15455   }
15456 
15457   if (CallOp->isInvalidDecl())
15458     return;
15459 
15460   // Mark the call operator referenced (and add to pending instantiations
15461   // if necessary).
15462   // For both the conversion and static-invoker template specializations
15463   // we construct their body's in this function, so no need to add them
15464   // to the PendingInstantiations.
15465   MarkFunctionReferenced(CurrentLocation, CallOp);
15466 
15467   if (Invoker != CallOp) {
15468     // Fill in the __invoke function with a dummy implementation. IR generation
15469     // will fill in the actual details. Update its type in case it contained
15470     // an 'auto'.
15471     Invoker->markUsed(Context);
15472     Invoker->setReferenced();
15473     Invoker->setType(Conv->getReturnType()->getPointeeType());
15474     Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
15475   }
15476 
15477   // Construct the body of the conversion function { return __invoke; }.
15478   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), VK_LValue,
15479                                        Conv->getLocation());
15480   assert(FunctionRef && "Can't refer to __invoke function?");
15481   Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
15482   Conv->setBody(CompoundStmt::Create(Context, Return, FPOptionsOverride(),
15483                                      Conv->getLocation(), Conv->getLocation()));
15484   Conv->markUsed(Context);
15485   Conv->setReferenced();
15486 
15487   if (ASTMutationListener *L = getASTMutationListener()) {
15488     L->CompletedImplicitDefinition(Conv);
15489     if (Invoker != CallOp)
15490       L->CompletedImplicitDefinition(Invoker);
15491   }
15492 }
15493 
15494 void Sema::DefineImplicitLambdaToBlockPointerConversion(
15495     SourceLocation CurrentLocation, CXXConversionDecl *Conv) {
15496   assert(!Conv->getParent()->isGenericLambda());
15497 
15498   SynthesizedFunctionScope Scope(*this, Conv);
15499 
15500   // Copy-initialize the lambda object as needed to capture it.
15501   Expr *This = ActOnCXXThis(CurrentLocation).get();
15502   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
15503 
15504   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
15505                                                         Conv->getLocation(),
15506                                                         Conv, DerefThis);
15507 
15508   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
15509   // behavior.  Note that only the general conversion function does this
15510   // (since it's unusable otherwise); in the case where we inline the
15511   // block literal, it has block literal lifetime semantics.
15512   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
15513     BuildBlock = ImplicitCastExpr::Create(
15514         Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
15515         BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride());
15516 
15517   if (BuildBlock.isInvalid()) {
15518     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15519     Conv->setInvalidDecl();
15520     return;
15521   }
15522 
15523   // Create the return statement that returns the block from the conversion
15524   // function.
15525   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
15526   if (Return.isInvalid()) {
15527     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15528     Conv->setInvalidDecl();
15529     return;
15530   }
15531 
15532   // Set the body of the conversion function.
15533   Stmt *ReturnS = Return.get();
15534   Conv->setBody(CompoundStmt::Create(Context, ReturnS, FPOptionsOverride(),
15535                                      Conv->getLocation(), Conv->getLocation()));
15536   Conv->markUsed(Context);
15537 
15538   // We're done; notify the mutation listener, if any.
15539   if (ASTMutationListener *L = getASTMutationListener()) {
15540     L->CompletedImplicitDefinition(Conv);
15541   }
15542 }
15543 
15544 /// Determine whether the given list arguments contains exactly one
15545 /// "real" (non-default) argument.
15546 static bool hasOneRealArgument(MultiExprArg Args) {
15547   switch (Args.size()) {
15548   case 0:
15549     return false;
15550 
15551   default:
15552     if (!Args[1]->isDefaultArgument())
15553       return false;
15554 
15555     [[fallthrough]];
15556   case 1:
15557     return !Args[0]->isDefaultArgument();
15558   }
15559 
15560   return false;
15561 }
15562 
15563 ExprResult
15564 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15565                             NamedDecl *FoundDecl,
15566                             CXXConstructorDecl *Constructor,
15567                             MultiExprArg ExprArgs,
15568                             bool HadMultipleCandidates,
15569                             bool IsListInitialization,
15570                             bool IsStdInitListInitialization,
15571                             bool RequiresZeroInit,
15572                             unsigned ConstructKind,
15573                             SourceRange ParenRange) {
15574   bool Elidable = false;
15575 
15576   // C++0x [class.copy]p34:
15577   //   When certain criteria are met, an implementation is allowed to
15578   //   omit the copy/move construction of a class object, even if the
15579   //   copy/move constructor and/or destructor for the object have
15580   //   side effects. [...]
15581   //     - when a temporary class object that has not been bound to a
15582   //       reference (12.2) would be copied/moved to a class object
15583   //       with the same cv-unqualified type, the copy/move operation
15584   //       can be omitted by constructing the temporary object
15585   //       directly into the target of the omitted copy/move
15586   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
15587       // FIXME: Converting constructors should also be accepted.
15588       // But to fix this, the logic that digs down into a CXXConstructExpr
15589       // to find the source object needs to handle it.
15590       // Right now it assumes the source object is passed directly as the
15591       // first argument.
15592       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
15593     Expr *SubExpr = ExprArgs[0];
15594     // FIXME: Per above, this is also incorrect if we want to accept
15595     //        converting constructors, as isTemporaryObject will
15596     //        reject temporaries with different type from the
15597     //        CXXRecord itself.
15598     Elidable = SubExpr->isTemporaryObject(
15599         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
15600   }
15601 
15602   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
15603                                FoundDecl, Constructor,
15604                                Elidable, ExprArgs, HadMultipleCandidates,
15605                                IsListInitialization,
15606                                IsStdInitListInitialization, RequiresZeroInit,
15607                                ConstructKind, ParenRange);
15608 }
15609 
15610 ExprResult
15611 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15612                             NamedDecl *FoundDecl,
15613                             CXXConstructorDecl *Constructor,
15614                             bool Elidable,
15615                             MultiExprArg ExprArgs,
15616                             bool HadMultipleCandidates,
15617                             bool IsListInitialization,
15618                             bool IsStdInitListInitialization,
15619                             bool RequiresZeroInit,
15620                             unsigned ConstructKind,
15621                             SourceRange ParenRange) {
15622   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
15623     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
15624     // The only way to get here is if we did overlaod resolution to find the
15625     // shadow decl, so we don't need to worry about re-checking the trailing
15626     // requires clause.
15627     if (DiagnoseUseOfOverloadedDecl(Constructor, ConstructLoc))
15628       return ExprError();
15629   }
15630 
15631   return BuildCXXConstructExpr(
15632       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
15633       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
15634       RequiresZeroInit, ConstructKind, ParenRange);
15635 }
15636 
15637 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
15638 /// including handling of its default argument expressions.
15639 ExprResult
15640 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15641                             CXXConstructorDecl *Constructor,
15642                             bool Elidable,
15643                             MultiExprArg ExprArgs,
15644                             bool HadMultipleCandidates,
15645                             bool IsListInitialization,
15646                             bool IsStdInitListInitialization,
15647                             bool RequiresZeroInit,
15648                             unsigned ConstructKind,
15649                             SourceRange ParenRange) {
15650   assert(declaresSameEntity(
15651              Constructor->getParent(),
15652              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
15653          "given constructor for wrong type");
15654   MarkFunctionReferenced(ConstructLoc, Constructor);
15655   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
15656     return ExprError();
15657   if (getLangOpts().SYCLIsDevice &&
15658       !checkSYCLDeviceFunction(ConstructLoc, Constructor))
15659     return ExprError();
15660 
15661   return CheckForImmediateInvocation(
15662       CXXConstructExpr::Create(
15663           Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
15664           HadMultipleCandidates, IsListInitialization,
15665           IsStdInitListInitialization, RequiresZeroInit,
15666           static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
15667           ParenRange),
15668       Constructor);
15669 }
15670 
15671 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
15672   if (VD->isInvalidDecl()) return;
15673   // If initializing the variable failed, don't also diagnose problems with
15674   // the destructor, they're likely related.
15675   if (VD->getInit() && VD->getInit()->containsErrors())
15676     return;
15677 
15678   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
15679   if (ClassDecl->isInvalidDecl()) return;
15680   if (ClassDecl->hasIrrelevantDestructor()) return;
15681   if (ClassDecl->isDependentContext()) return;
15682 
15683   if (VD->isNoDestroy(getASTContext()))
15684     return;
15685 
15686   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
15687 
15688   // If this is an array, we'll require the destructor during initialization, so
15689   // we can skip over this. We still want to emit exit-time destructor warnings
15690   // though.
15691   if (!VD->getType()->isArrayType()) {
15692     MarkFunctionReferenced(VD->getLocation(), Destructor);
15693     CheckDestructorAccess(VD->getLocation(), Destructor,
15694                           PDiag(diag::err_access_dtor_var)
15695                               << VD->getDeclName() << VD->getType());
15696     DiagnoseUseOfDecl(Destructor, VD->getLocation());
15697   }
15698 
15699   if (Destructor->isTrivial()) return;
15700 
15701   // If the destructor is constexpr, check whether the variable has constant
15702   // destruction now.
15703   if (Destructor->isConstexpr()) {
15704     bool HasConstantInit = false;
15705     if (VD->getInit() && !VD->getInit()->isValueDependent())
15706       HasConstantInit = VD->evaluateValue();
15707     SmallVector<PartialDiagnosticAt, 8> Notes;
15708     if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
15709         HasConstantInit) {
15710       Diag(VD->getLocation(),
15711            diag::err_constexpr_var_requires_const_destruction) << VD;
15712       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15713         Diag(Notes[I].first, Notes[I].second);
15714     }
15715   }
15716 
15717   if (!VD->hasGlobalStorage()) return;
15718 
15719   // Emit warning for non-trivial dtor in global scope (a real global,
15720   // class-static, function-static).
15721   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
15722 
15723   // TODO: this should be re-enabled for static locals by !CXAAtExit
15724   if (!VD->isStaticLocal())
15725     Diag(VD->getLocation(), diag::warn_global_destructor);
15726 }
15727 
15728 /// Given a constructor and the set of arguments provided for the
15729 /// constructor, convert the arguments and add any required default arguments
15730 /// to form a proper call to this constructor.
15731 ///
15732 /// \returns true if an error occurred, false otherwise.
15733 bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
15734                                    QualType DeclInitType, MultiExprArg ArgsPtr,
15735                                    SourceLocation Loc,
15736                                    SmallVectorImpl<Expr *> &ConvertedArgs,
15737                                    bool AllowExplicit,
15738                                    bool IsListInitialization) {
15739   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
15740   unsigned NumArgs = ArgsPtr.size();
15741   Expr **Args = ArgsPtr.data();
15742 
15743   const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
15744   unsigned NumParams = Proto->getNumParams();
15745 
15746   // If too few arguments are available, we'll fill in the rest with defaults.
15747   if (NumArgs < NumParams)
15748     ConvertedArgs.reserve(NumParams);
15749   else
15750     ConvertedArgs.reserve(NumArgs);
15751 
15752   VariadicCallType CallType =
15753     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
15754   SmallVector<Expr *, 8> AllArgs;
15755   bool Invalid = GatherArgumentsForCall(
15756       Loc, Constructor, Proto, 0, llvm::ArrayRef(Args, NumArgs), AllArgs,
15757       CallType, AllowExplicit, IsListInitialization);
15758   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
15759 
15760   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
15761 
15762   CheckConstructorCall(Constructor, DeclInitType,
15763                        llvm::ArrayRef(AllArgs.data(), AllArgs.size()), Proto,
15764                        Loc);
15765 
15766   return Invalid;
15767 }
15768 
15769 static inline bool
15770 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
15771                                        const FunctionDecl *FnDecl) {
15772   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
15773   if (isa<NamespaceDecl>(DC)) {
15774     return SemaRef.Diag(FnDecl->getLocation(),
15775                         diag::err_operator_new_delete_declared_in_namespace)
15776       << FnDecl->getDeclName();
15777   }
15778 
15779   if (isa<TranslationUnitDecl>(DC) &&
15780       FnDecl->getStorageClass() == SC_Static) {
15781     return SemaRef.Diag(FnDecl->getLocation(),
15782                         diag::err_operator_new_delete_declared_static)
15783       << FnDecl->getDeclName();
15784   }
15785 
15786   return false;
15787 }
15788 
15789 static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef,
15790                                              const PointerType *PtrTy) {
15791   auto &Ctx = SemaRef.Context;
15792   Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
15793   PtrQuals.removeAddressSpace();
15794   return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType(
15795       PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
15796 }
15797 
15798 static inline bool
15799 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
15800                             CanQualType ExpectedResultType,
15801                             CanQualType ExpectedFirstParamType,
15802                             unsigned DependentParamTypeDiag,
15803                             unsigned InvalidParamTypeDiag) {
15804   QualType ResultType =
15805       FnDecl->getType()->castAs<FunctionType>()->getReturnType();
15806 
15807   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15808     // The operator is valid on any address space for OpenCL.
15809     // Drop address space from actual and expected result types.
15810     if (const auto *PtrTy = ResultType->getAs<PointerType>())
15811       ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15812 
15813     if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>())
15814       ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
15815   }
15816 
15817   // Check that the result type is what we expect.
15818   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) {
15819     // Reject even if the type is dependent; an operator delete function is
15820     // required to have a non-dependent result type.
15821     return SemaRef.Diag(
15822                FnDecl->getLocation(),
15823                ResultType->isDependentType()
15824                    ? diag::err_operator_new_delete_dependent_result_type
15825                    : diag::err_operator_new_delete_invalid_result_type)
15826            << FnDecl->getDeclName() << ExpectedResultType;
15827   }
15828 
15829   // A function template must have at least 2 parameters.
15830   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
15831     return SemaRef.Diag(FnDecl->getLocation(),
15832                       diag::err_operator_new_delete_template_too_few_parameters)
15833         << FnDecl->getDeclName();
15834 
15835   // The function decl must have at least 1 parameter.
15836   if (FnDecl->getNumParams() == 0)
15837     return SemaRef.Diag(FnDecl->getLocation(),
15838                         diag::err_operator_new_delete_too_few_parameters)
15839       << FnDecl->getDeclName();
15840 
15841   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
15842   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15843     // The operator is valid on any address space for OpenCL.
15844     // Drop address space from actual and expected first parameter types.
15845     if (const auto *PtrTy =
15846             FnDecl->getParamDecl(0)->getType()->getAs<PointerType>())
15847       FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15848 
15849     if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>())
15850       ExpectedFirstParamType =
15851           RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
15852   }
15853 
15854   // Check that the first parameter type is what we expect.
15855   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
15856       ExpectedFirstParamType) {
15857     // The first parameter type is not allowed to be dependent. As a tentative
15858     // DR resolution, we allow a dependent parameter type if it is the right
15859     // type anyway, to allow destroying operator delete in class templates.
15860     return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType()
15861                                                    ? DependentParamTypeDiag
15862                                                    : InvalidParamTypeDiag)
15863            << FnDecl->getDeclName() << ExpectedFirstParamType;
15864   }
15865 
15866   return false;
15867 }
15868 
15869 static bool
15870 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
15871   // C++ [basic.stc.dynamic.allocation]p1:
15872   //   A program is ill-formed if an allocation function is declared in a
15873   //   namespace scope other than global scope or declared static in global
15874   //   scope.
15875   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15876     return true;
15877 
15878   CanQualType SizeTy =
15879     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
15880 
15881   // C++ [basic.stc.dynamic.allocation]p1:
15882   //  The return type shall be void*. The first parameter shall have type
15883   //  std::size_t.
15884   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
15885                                   SizeTy,
15886                                   diag::err_operator_new_dependent_param_type,
15887                                   diag::err_operator_new_param_type))
15888     return true;
15889 
15890   // C++ [basic.stc.dynamic.allocation]p1:
15891   //  The first parameter shall not have an associated default argument.
15892   if (FnDecl->getParamDecl(0)->hasDefaultArg())
15893     return SemaRef.Diag(FnDecl->getLocation(),
15894                         diag::err_operator_new_default_arg)
15895       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
15896 
15897   return false;
15898 }
15899 
15900 static bool
15901 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
15902   // C++ [basic.stc.dynamic.deallocation]p1:
15903   //   A program is ill-formed if deallocation functions are declared in a
15904   //   namespace scope other than global scope or declared static in global
15905   //   scope.
15906   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15907     return true;
15908 
15909   auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
15910 
15911   // C++ P0722:
15912   //   Within a class C, the first parameter of a destroying operator delete
15913   //   shall be of type C *. The first parameter of any other deallocation
15914   //   function shall be of type void *.
15915   CanQualType ExpectedFirstParamType =
15916       MD && MD->isDestroyingOperatorDelete()
15917           ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
15918                 SemaRef.Context.getRecordType(MD->getParent())))
15919           : SemaRef.Context.VoidPtrTy;
15920 
15921   // C++ [basic.stc.dynamic.deallocation]p2:
15922   //   Each deallocation function shall return void
15923   if (CheckOperatorNewDeleteTypes(
15924           SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
15925           diag::err_operator_delete_dependent_param_type,
15926           diag::err_operator_delete_param_type))
15927     return true;
15928 
15929   // C++ P0722:
15930   //   A destroying operator delete shall be a usual deallocation function.
15931   if (MD && !MD->getParent()->isDependentContext() &&
15932       MD->isDestroyingOperatorDelete() &&
15933       !SemaRef.isUsualDeallocationFunction(MD)) {
15934     SemaRef.Diag(MD->getLocation(),
15935                  diag::err_destroying_operator_delete_not_usual);
15936     return true;
15937   }
15938 
15939   return false;
15940 }
15941 
15942 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
15943 /// of this overloaded operator is well-formed. If so, returns false;
15944 /// otherwise, emits appropriate diagnostics and returns true.
15945 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
15946   assert(FnDecl && FnDecl->isOverloadedOperator() &&
15947          "Expected an overloaded operator declaration");
15948 
15949   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
15950 
15951   // C++ [over.oper]p5:
15952   //   The allocation and deallocation functions, operator new,
15953   //   operator new[], operator delete and operator delete[], are
15954   //   described completely in 3.7.3. The attributes and restrictions
15955   //   found in the rest of this subclause do not apply to them unless
15956   //   explicitly stated in 3.7.3.
15957   if (Op == OO_Delete || Op == OO_Array_Delete)
15958     return CheckOperatorDeleteDeclaration(*this, FnDecl);
15959 
15960   if (Op == OO_New || Op == OO_Array_New)
15961     return CheckOperatorNewDeclaration(*this, FnDecl);
15962 
15963   // C++ [over.oper]p7:
15964   //   An operator function shall either be a member function or
15965   //   be a non-member function and have at least one parameter
15966   //   whose type is a class, a reference to a class, an enumeration,
15967   //   or a reference to an enumeration.
15968   // Note: Before C++23, a member function could not be static. The only member
15969   //       function allowed to be static is the call operator function.
15970   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
15971     if (MethodDecl->isStatic()) {
15972       if (Op == OO_Call || Op == OO_Subscript)
15973         Diag(FnDecl->getLocation(),
15974              (LangOpts.CPlusPlus2b
15975                   ? diag::warn_cxx20_compat_operator_overload_static
15976                   : diag::ext_operator_overload_static))
15977             << FnDecl;
15978       else
15979         return Diag(FnDecl->getLocation(), diag::err_operator_overload_static)
15980                << FnDecl;
15981     }
15982   } else {
15983     bool ClassOrEnumParam = false;
15984     for (auto *Param : FnDecl->parameters()) {
15985       QualType ParamType = Param->getType().getNonReferenceType();
15986       if (ParamType->isDependentType() || ParamType->isRecordType() ||
15987           ParamType->isEnumeralType()) {
15988         ClassOrEnumParam = true;
15989         break;
15990       }
15991     }
15992 
15993     if (!ClassOrEnumParam)
15994       return Diag(FnDecl->getLocation(),
15995                   diag::err_operator_overload_needs_class_or_enum)
15996         << FnDecl->getDeclName();
15997   }
15998 
15999   // C++ [over.oper]p8:
16000   //   An operator function cannot have default arguments (8.3.6),
16001   //   except where explicitly stated below.
16002   //
16003   // Only the function-call operator (C++ [over.call]p1) and the subscript
16004   // operator (CWG2507) allow default arguments.
16005   if (Op != OO_Call) {
16006     ParmVarDecl *FirstDefaultedParam = nullptr;
16007     for (auto *Param : FnDecl->parameters()) {
16008       if (Param->hasDefaultArg()) {
16009         FirstDefaultedParam = Param;
16010         break;
16011       }
16012     }
16013     if (FirstDefaultedParam) {
16014       if (Op == OO_Subscript) {
16015         Diag(FnDecl->getLocation(), LangOpts.CPlusPlus2b
16016                                         ? diag::ext_subscript_overload
16017                                         : diag::error_subscript_overload)
16018             << FnDecl->getDeclName() << 1
16019             << FirstDefaultedParam->getDefaultArgRange();
16020       } else {
16021         return Diag(FirstDefaultedParam->getLocation(),
16022                     diag::err_operator_overload_default_arg)
16023                << FnDecl->getDeclName()
16024                << FirstDefaultedParam->getDefaultArgRange();
16025       }
16026     }
16027   }
16028 
16029   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
16030     { false, false, false }
16031 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
16032     , { Unary, Binary, MemberOnly }
16033 #include "clang/Basic/OperatorKinds.def"
16034   };
16035 
16036   bool CanBeUnaryOperator = OperatorUses[Op][0];
16037   bool CanBeBinaryOperator = OperatorUses[Op][1];
16038   bool MustBeMemberOperator = OperatorUses[Op][2];
16039 
16040   // C++ [over.oper]p8:
16041   //   [...] Operator functions cannot have more or fewer parameters
16042   //   than the number required for the corresponding operator, as
16043   //   described in the rest of this subclause.
16044   unsigned NumParams = FnDecl->getNumParams()
16045                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
16046   if (Op != OO_Call && Op != OO_Subscript &&
16047       ((NumParams == 1 && !CanBeUnaryOperator) ||
16048        (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||
16049        (NumParams > 2))) {
16050     // We have the wrong number of parameters.
16051     unsigned ErrorKind;
16052     if (CanBeUnaryOperator && CanBeBinaryOperator) {
16053       ErrorKind = 2;  // 2 -> unary or binary.
16054     } else if (CanBeUnaryOperator) {
16055       ErrorKind = 0;  // 0 -> unary
16056     } else {
16057       assert(CanBeBinaryOperator &&
16058              "All non-call overloaded operators are unary or binary!");
16059       ErrorKind = 1;  // 1 -> binary
16060     }
16061     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
16062       << FnDecl->getDeclName() << NumParams << ErrorKind;
16063   }
16064 
16065   if (Op == OO_Subscript && NumParams != 2) {
16066     Diag(FnDecl->getLocation(), LangOpts.CPlusPlus2b
16067                                     ? diag::ext_subscript_overload
16068                                     : diag::error_subscript_overload)
16069         << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);
16070   }
16071 
16072   // Overloaded operators other than operator() and operator[] cannot be
16073   // variadic.
16074   if (Op != OO_Call &&
16075       FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
16076     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
16077            << FnDecl->getDeclName();
16078   }
16079 
16080   // Some operators must be member functions.
16081   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
16082     return Diag(FnDecl->getLocation(),
16083                 diag::err_operator_overload_must_be_member)
16084       << FnDecl->getDeclName();
16085   }
16086 
16087   // C++ [over.inc]p1:
16088   //   The user-defined function called operator++ implements the
16089   //   prefix and postfix ++ operator. If this function is a member
16090   //   function with no parameters, or a non-member function with one
16091   //   parameter of class or enumeration type, it defines the prefix
16092   //   increment operator ++ for objects of that type. If the function
16093   //   is a member function with one parameter (which shall be of type
16094   //   int) or a non-member function with two parameters (the second
16095   //   of which shall be of type int), it defines the postfix
16096   //   increment operator ++ for objects of that type.
16097   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
16098     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
16099     QualType ParamType = LastParam->getType();
16100 
16101     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
16102         !ParamType->isDependentType())
16103       return Diag(LastParam->getLocation(),
16104                   diag::err_operator_overload_post_incdec_must_be_int)
16105         << LastParam->getType() << (Op == OO_MinusMinus);
16106   }
16107 
16108   return false;
16109 }
16110 
16111 static bool
16112 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
16113                                           FunctionTemplateDecl *TpDecl) {
16114   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
16115 
16116   // Must have one or two template parameters.
16117   if (TemplateParams->size() == 1) {
16118     NonTypeTemplateParmDecl *PmDecl =
16119         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
16120 
16121     // The template parameter must be a char parameter pack.
16122     if (PmDecl && PmDecl->isTemplateParameterPack() &&
16123         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
16124       return false;
16125 
16126     // C++20 [over.literal]p5:
16127     //   A string literal operator template is a literal operator template
16128     //   whose template-parameter-list comprises a single non-type
16129     //   template-parameter of class type.
16130     //
16131     // As a DR resolution, we also allow placeholders for deduced class
16132     // template specializations.
16133     if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
16134         !PmDecl->isTemplateParameterPack() &&
16135         (PmDecl->getType()->isRecordType() ||
16136          PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
16137       return false;
16138   } else if (TemplateParams->size() == 2) {
16139     TemplateTypeParmDecl *PmType =
16140         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
16141     NonTypeTemplateParmDecl *PmArgs =
16142         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
16143 
16144     // The second template parameter must be a parameter pack with the
16145     // first template parameter as its type.
16146     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
16147         PmArgs->isTemplateParameterPack()) {
16148       const TemplateTypeParmType *TArgs =
16149           PmArgs->getType()->getAs<TemplateTypeParmType>();
16150       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
16151           TArgs->getIndex() == PmType->getIndex()) {
16152         if (!SemaRef.inTemplateInstantiation())
16153           SemaRef.Diag(TpDecl->getLocation(),
16154                        diag::ext_string_literal_operator_template);
16155         return false;
16156       }
16157     }
16158   }
16159 
16160   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
16161                diag::err_literal_operator_template)
16162       << TpDecl->getTemplateParameters()->getSourceRange();
16163   return true;
16164 }
16165 
16166 /// CheckLiteralOperatorDeclaration - Check whether the declaration
16167 /// of this literal operator function is well-formed. If so, returns
16168 /// false; otherwise, emits appropriate diagnostics and returns true.
16169 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
16170   if (isa<CXXMethodDecl>(FnDecl)) {
16171     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
16172       << FnDecl->getDeclName();
16173     return true;
16174   }
16175 
16176   if (FnDecl->isExternC()) {
16177     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
16178     if (const LinkageSpecDecl *LSD =
16179             FnDecl->getDeclContext()->getExternCContext())
16180       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
16181     return true;
16182   }
16183 
16184   // This might be the definition of a literal operator template.
16185   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
16186 
16187   // This might be a specialization of a literal operator template.
16188   if (!TpDecl)
16189     TpDecl = FnDecl->getPrimaryTemplate();
16190 
16191   // template <char...> type operator "" name() and
16192   // template <class T, T...> type operator "" name() are the only valid
16193   // template signatures, and the only valid signatures with no parameters.
16194   //
16195   // C++20 also allows template <SomeClass T> type operator "" name().
16196   if (TpDecl) {
16197     if (FnDecl->param_size() != 0) {
16198       Diag(FnDecl->getLocation(),
16199            diag::err_literal_operator_template_with_params);
16200       return true;
16201     }
16202 
16203     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
16204       return true;
16205 
16206   } else if (FnDecl->param_size() == 1) {
16207     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
16208 
16209     QualType ParamType = Param->getType().getUnqualifiedType();
16210 
16211     // Only unsigned long long int, long double, any character type, and const
16212     // char * are allowed as the only parameters.
16213     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
16214         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
16215         Context.hasSameType(ParamType, Context.CharTy) ||
16216         Context.hasSameType(ParamType, Context.WideCharTy) ||
16217         Context.hasSameType(ParamType, Context.Char8Ty) ||
16218         Context.hasSameType(ParamType, Context.Char16Ty) ||
16219         Context.hasSameType(ParamType, Context.Char32Ty)) {
16220     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
16221       QualType InnerType = Ptr->getPointeeType();
16222 
16223       // Pointer parameter must be a const char *.
16224       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
16225                                 Context.CharTy) &&
16226             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
16227         Diag(Param->getSourceRange().getBegin(),
16228              diag::err_literal_operator_param)
16229             << ParamType << "'const char *'" << Param->getSourceRange();
16230         return true;
16231       }
16232 
16233     } else if (ParamType->isRealFloatingType()) {
16234       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16235           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
16236       return true;
16237 
16238     } else if (ParamType->isIntegerType()) {
16239       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16240           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
16241       return true;
16242 
16243     } else {
16244       Diag(Param->getSourceRange().getBegin(),
16245            diag::err_literal_operator_invalid_param)
16246           << ParamType << Param->getSourceRange();
16247       return true;
16248     }
16249 
16250   } else if (FnDecl->param_size() == 2) {
16251     FunctionDecl::param_iterator Param = FnDecl->param_begin();
16252 
16253     // First, verify that the first parameter is correct.
16254 
16255     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
16256 
16257     // Two parameter function must have a pointer to const as a
16258     // first parameter; let's strip those qualifiers.
16259     const PointerType *PT = FirstParamType->getAs<PointerType>();
16260 
16261     if (!PT) {
16262       Diag((*Param)->getSourceRange().getBegin(),
16263            diag::err_literal_operator_param)
16264           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16265       return true;
16266     }
16267 
16268     QualType PointeeType = PT->getPointeeType();
16269     // First parameter must be const
16270     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
16271       Diag((*Param)->getSourceRange().getBegin(),
16272            diag::err_literal_operator_param)
16273           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16274       return true;
16275     }
16276 
16277     QualType InnerType = PointeeType.getUnqualifiedType();
16278     // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
16279     // const char32_t* are allowed as the first parameter to a two-parameter
16280     // function
16281     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
16282           Context.hasSameType(InnerType, Context.WideCharTy) ||
16283           Context.hasSameType(InnerType, Context.Char8Ty) ||
16284           Context.hasSameType(InnerType, Context.Char16Ty) ||
16285           Context.hasSameType(InnerType, Context.Char32Ty))) {
16286       Diag((*Param)->getSourceRange().getBegin(),
16287            diag::err_literal_operator_param)
16288           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16289       return true;
16290     }
16291 
16292     // Move on to the second and final parameter.
16293     ++Param;
16294 
16295     // The second parameter must be a std::size_t.
16296     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
16297     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
16298       Diag((*Param)->getSourceRange().getBegin(),
16299            diag::err_literal_operator_param)
16300           << SecondParamType << Context.getSizeType()
16301           << (*Param)->getSourceRange();
16302       return true;
16303     }
16304   } else {
16305     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
16306     return true;
16307   }
16308 
16309   // Parameters are good.
16310 
16311   // A parameter-declaration-clause containing a default argument is not
16312   // equivalent to any of the permitted forms.
16313   for (auto *Param : FnDecl->parameters()) {
16314     if (Param->hasDefaultArg()) {
16315       Diag(Param->getDefaultArgRange().getBegin(),
16316            diag::err_literal_operator_default_argument)
16317         << Param->getDefaultArgRange();
16318       break;
16319     }
16320   }
16321 
16322   StringRef LiteralName
16323     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
16324   if (LiteralName[0] != '_' &&
16325       !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
16326     // C++11 [usrlit.suffix]p1:
16327     //   Literal suffix identifiers that do not start with an underscore
16328     //   are reserved for future standardization.
16329     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
16330       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
16331   }
16332 
16333   return false;
16334 }
16335 
16336 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
16337 /// linkage specification, including the language and (if present)
16338 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
16339 /// language string literal. LBraceLoc, if valid, provides the location of
16340 /// the '{' brace. Otherwise, this linkage specification does not
16341 /// have any braces.
16342 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
16343                                            Expr *LangStr,
16344                                            SourceLocation LBraceLoc) {
16345   StringLiteral *Lit = cast<StringLiteral>(LangStr);
16346   if (!Lit->isOrdinary()) {
16347     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
16348       << LangStr->getSourceRange();
16349     return nullptr;
16350   }
16351 
16352   StringRef Lang = Lit->getString();
16353   LinkageSpecDecl::LanguageIDs Language;
16354   if (Lang == "C")
16355     Language = LinkageSpecDecl::lang_c;
16356   else if (Lang == "C++")
16357     Language = LinkageSpecDecl::lang_cxx;
16358   else {
16359     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
16360       << LangStr->getSourceRange();
16361     return nullptr;
16362   }
16363 
16364   // FIXME: Add all the various semantics of linkage specifications
16365 
16366   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
16367                                                LangStr->getExprLoc(), Language,
16368                                                LBraceLoc.isValid());
16369 
16370   /// C++ [module.unit]p7.2.3
16371   /// - Otherwise, if the declaration
16372   ///   - ...
16373   ///   - ...
16374   ///   - appears within a linkage-specification,
16375   ///   it is attached to the global module.
16376   ///
16377   /// If the declaration is already in global module fragment, we don't
16378   /// need to attach it again.
16379   if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
16380     Module *GlobalModule =
16381         PushGlobalModuleFragment(ExternLoc, /*IsImplicit=*/true);
16382     /// According to [module.reach]p3.2,
16383     /// The declaration in global module fragment is reachable if it is not
16384     /// discarded. And the discarded declaration should be deleted. So it
16385     /// doesn't matter mark the declaration in global module fragment as
16386     /// reachable here.
16387     D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ReachableWhenImported);
16388     D->setLocalOwningModule(GlobalModule);
16389   }
16390 
16391   CurContext->addDecl(D);
16392   PushDeclContext(S, D);
16393   return D;
16394 }
16395 
16396 /// ActOnFinishLinkageSpecification - Complete the definition of
16397 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
16398 /// valid, it's the position of the closing '}' brace in a linkage
16399 /// specification that uses braces.
16400 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
16401                                             Decl *LinkageSpec,
16402                                             SourceLocation RBraceLoc) {
16403   if (RBraceLoc.isValid()) {
16404     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
16405     LSDecl->setRBraceLoc(RBraceLoc);
16406   }
16407 
16408   // If the current module doesn't has Parent, it implies that the
16409   // LinkageSpec isn't in the module created by itself. So we don't
16410   // need to pop it.
16411   if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
16412       getCurrentModule()->isGlobalModule() && getCurrentModule()->Parent)
16413     PopGlobalModuleFragment();
16414 
16415   PopDeclContext();
16416   return LinkageSpec;
16417 }
16418 
16419 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
16420                                   const ParsedAttributesView &AttrList,
16421                                   SourceLocation SemiLoc) {
16422   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
16423   // Attribute declarations appertain to empty declaration so we handle
16424   // them here.
16425   ProcessDeclAttributeList(S, ED, AttrList);
16426 
16427   CurContext->addDecl(ED);
16428   return ED;
16429 }
16430 
16431 /// Perform semantic analysis for the variable declaration that
16432 /// occurs within a C++ catch clause, returning the newly-created
16433 /// variable.
16434 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
16435                                          TypeSourceInfo *TInfo,
16436                                          SourceLocation StartLoc,
16437                                          SourceLocation Loc,
16438                                          IdentifierInfo *Name) {
16439   bool Invalid = false;
16440   QualType ExDeclType = TInfo->getType();
16441 
16442   // Arrays and functions decay.
16443   if (ExDeclType->isArrayType())
16444     ExDeclType = Context.getArrayDecayedType(ExDeclType);
16445   else if (ExDeclType->isFunctionType())
16446     ExDeclType = Context.getPointerType(ExDeclType);
16447 
16448   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
16449   // The exception-declaration shall not denote a pointer or reference to an
16450   // incomplete type, other than [cv] void*.
16451   // N2844 forbids rvalue references.
16452   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
16453     Diag(Loc, diag::err_catch_rvalue_ref);
16454     Invalid = true;
16455   }
16456 
16457   if (ExDeclType->isVariablyModifiedType()) {
16458     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
16459     Invalid = true;
16460   }
16461 
16462   QualType BaseType = ExDeclType;
16463   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
16464   unsigned DK = diag::err_catch_incomplete;
16465   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
16466     BaseType = Ptr->getPointeeType();
16467     Mode = 1;
16468     DK = diag::err_catch_incomplete_ptr;
16469   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
16470     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
16471     BaseType = Ref->getPointeeType();
16472     Mode = 2;
16473     DK = diag::err_catch_incomplete_ref;
16474   }
16475   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
16476       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
16477     Invalid = true;
16478 
16479   if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
16480     Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
16481     Invalid = true;
16482   }
16483 
16484   if (!Invalid && !ExDeclType->isDependentType() &&
16485       RequireNonAbstractType(Loc, ExDeclType,
16486                              diag::err_abstract_type_in_decl,
16487                              AbstractVariableType))
16488     Invalid = true;
16489 
16490   // Only the non-fragile NeXT runtime currently supports C++ catches
16491   // of ObjC types, and no runtime supports catching ObjC types by value.
16492   if (!Invalid && getLangOpts().ObjC) {
16493     QualType T = ExDeclType;
16494     if (const ReferenceType *RT = T->getAs<ReferenceType>())
16495       T = RT->getPointeeType();
16496 
16497     if (T->isObjCObjectType()) {
16498       Diag(Loc, diag::err_objc_object_catch);
16499       Invalid = true;
16500     } else if (T->isObjCObjectPointerType()) {
16501       // FIXME: should this be a test for macosx-fragile specifically?
16502       if (getLangOpts().ObjCRuntime.isFragile())
16503         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
16504     }
16505   }
16506 
16507   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
16508                                     ExDeclType, TInfo, SC_None);
16509   ExDecl->setExceptionVariable(true);
16510 
16511   // In ARC, infer 'retaining' for variables of retainable type.
16512   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
16513     Invalid = true;
16514 
16515   if (!Invalid && !ExDeclType->isDependentType()) {
16516     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
16517       // Insulate this from anything else we might currently be parsing.
16518       EnterExpressionEvaluationContext scope(
16519           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
16520 
16521       // C++ [except.handle]p16:
16522       //   The object declared in an exception-declaration or, if the
16523       //   exception-declaration does not specify a name, a temporary (12.2) is
16524       //   copy-initialized (8.5) from the exception object. [...]
16525       //   The object is destroyed when the handler exits, after the destruction
16526       //   of any automatic objects initialized within the handler.
16527       //
16528       // We just pretend to initialize the object with itself, then make sure
16529       // it can be destroyed later.
16530       QualType initType = Context.getExceptionObjectType(ExDeclType);
16531 
16532       InitializedEntity entity =
16533         InitializedEntity::InitializeVariable(ExDecl);
16534       InitializationKind initKind =
16535         InitializationKind::CreateCopy(Loc, SourceLocation());
16536 
16537       Expr *opaqueValue =
16538         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
16539       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
16540       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
16541       if (result.isInvalid())
16542         Invalid = true;
16543       else {
16544         // If the constructor used was non-trivial, set this as the
16545         // "initializer".
16546         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
16547         if (!construct->getConstructor()->isTrivial()) {
16548           Expr *init = MaybeCreateExprWithCleanups(construct);
16549           ExDecl->setInit(init);
16550         }
16551 
16552         // And make sure it's destructable.
16553         FinalizeVarWithDestructor(ExDecl, recordType);
16554       }
16555     }
16556   }
16557 
16558   if (Invalid)
16559     ExDecl->setInvalidDecl();
16560 
16561   return ExDecl;
16562 }
16563 
16564 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
16565 /// handler.
16566 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
16567   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16568   bool Invalid = D.isInvalidType();
16569 
16570   // Check for unexpanded parameter packs.
16571   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16572                                       UPPC_ExceptionType)) {
16573     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
16574                                              D.getIdentifierLoc());
16575     Invalid = true;
16576   }
16577 
16578   IdentifierInfo *II = D.getIdentifier();
16579   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
16580                                              LookupOrdinaryName,
16581                                              ForVisibleRedeclaration)) {
16582     // The scope should be freshly made just for us. There is just no way
16583     // it contains any previous declaration, except for function parameters in
16584     // a function-try-block's catch statement.
16585     assert(!S->isDeclScope(PrevDecl));
16586     if (isDeclInScope(PrevDecl, CurContext, S)) {
16587       Diag(D.getIdentifierLoc(), diag::err_redefinition)
16588         << D.getIdentifier();
16589       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
16590       Invalid = true;
16591     } else if (PrevDecl->isTemplateParameter())
16592       // Maybe we will complain about the shadowed template parameter.
16593       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16594   }
16595 
16596   if (D.getCXXScopeSpec().isSet() && !Invalid) {
16597     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
16598       << D.getCXXScopeSpec().getRange();
16599     Invalid = true;
16600   }
16601 
16602   VarDecl *ExDecl = BuildExceptionDeclaration(
16603       S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
16604   if (Invalid)
16605     ExDecl->setInvalidDecl();
16606 
16607   // Add the exception declaration into this scope.
16608   if (II)
16609     PushOnScopeChains(ExDecl, S);
16610   else
16611     CurContext->addDecl(ExDecl);
16612 
16613   ProcessDeclAttributes(S, ExDecl, D);
16614   return ExDecl;
16615 }
16616 
16617 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
16618                                          Expr *AssertExpr,
16619                                          Expr *AssertMessageExpr,
16620                                          SourceLocation RParenLoc) {
16621   StringLiteral *AssertMessage =
16622       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
16623 
16624   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
16625     return nullptr;
16626 
16627   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
16628                                       AssertMessage, RParenLoc, false);
16629 }
16630 
16631 /// Convert \V to a string we can present to the user in a diagnostic
16632 /// \T is the type of the expression that has been evaluated into \V
16633 static bool ConvertAPValueToString(const APValue &V, QualType T,
16634                                    SmallVectorImpl<char> &Str) {
16635   if (!V.hasValue())
16636     return false;
16637 
16638   switch (V.getKind()) {
16639   case APValue::ValueKind::Int:
16640     if (T->isBooleanType()) {
16641       // Bools are reduced to ints during evaluation, but for
16642       // diagnostic purposes we want to print them as
16643       // true or false.
16644       int64_t BoolValue = V.getInt().getExtValue();
16645       assert((BoolValue == 0 || BoolValue == 1) &&
16646              "Bool type, but value is not 0 or 1");
16647       llvm::raw_svector_ostream OS(Str);
16648       OS << (BoolValue ? "true" : "false");
16649     } else if (T->isCharType()) {
16650       // Same is true for chars.
16651       Str.push_back('\'');
16652       Str.push_back(V.getInt().getExtValue());
16653       Str.push_back('\'');
16654     } else
16655       V.getInt().toString(Str);
16656 
16657     break;
16658 
16659   case APValue::ValueKind::Float:
16660     V.getFloat().toString(Str);
16661     break;
16662 
16663   case APValue::ValueKind::LValue:
16664     if (V.isNullPointer()) {
16665       llvm::raw_svector_ostream OS(Str);
16666       OS << "nullptr";
16667     } else
16668       return false;
16669     break;
16670 
16671   case APValue::ValueKind::ComplexFloat: {
16672     llvm::raw_svector_ostream OS(Str);
16673     OS << '(';
16674     V.getComplexFloatReal().toString(Str);
16675     OS << " + ";
16676     V.getComplexFloatImag().toString(Str);
16677     OS << "i)";
16678   } break;
16679 
16680   case APValue::ValueKind::ComplexInt: {
16681     llvm::raw_svector_ostream OS(Str);
16682     OS << '(';
16683     V.getComplexIntReal().toString(Str);
16684     OS << " + ";
16685     V.getComplexIntImag().toString(Str);
16686     OS << "i)";
16687   } break;
16688 
16689   default:
16690     return false;
16691   }
16692 
16693   return true;
16694 }
16695 
16696 /// Some Expression types are not useful to print notes about,
16697 /// e.g. literals and values that have already been expanded
16698 /// before such as int-valued template parameters.
16699 static bool UsefulToPrintExpr(const Expr *E) {
16700   E = E->IgnoreParenImpCasts();
16701   // Literals are pretty easy for humans to understand.
16702   if (isa<IntegerLiteral, FloatingLiteral, CharacterLiteral, CXXBoolLiteralExpr,
16703           CXXNullPtrLiteralExpr, FixedPointLiteral, ImaginaryLiteral>(E))
16704     return false;
16705 
16706   // These have been substituted from template parameters
16707   // and appear as literals in the static assert error.
16708   if (isa<SubstNonTypeTemplateParmExpr>(E))
16709     return false;
16710 
16711   // -5 is also simple to understand.
16712   if (const auto *UnaryOp = dyn_cast<UnaryOperator>(E))
16713     return UsefulToPrintExpr(UnaryOp->getSubExpr());
16714 
16715   // Ignore nested binary operators. This could be a FIXME for improvements
16716   // to the diagnostics in the future.
16717   if (isa<BinaryOperator>(E))
16718     return false;
16719 
16720   return true;
16721 }
16722 
16723 /// Try to print more useful information about a failed static_assert
16724 /// with expression \E
16725 void Sema::DiagnoseStaticAssertDetails(const Expr *E) {
16726   if (const auto *Op = dyn_cast<BinaryOperator>(E)) {
16727     const Expr *LHS = Op->getLHS()->IgnoreParenImpCasts();
16728     const Expr *RHS = Op->getRHS()->IgnoreParenImpCasts();
16729 
16730     // Ignore comparisons of boolean expressions with a boolean literal.
16731     if ((isa<CXXBoolLiteralExpr>(LHS) && RHS->getType()->isBooleanType()) ||
16732         (isa<CXXBoolLiteralExpr>(RHS) && LHS->getType()->isBooleanType()))
16733       return;
16734 
16735     // Don't print obvious expressions.
16736     if (!UsefulToPrintExpr(LHS) && !UsefulToPrintExpr(RHS))
16737       return;
16738 
16739     struct {
16740       const clang::Expr *Cond;
16741       Expr::EvalResult Result;
16742       SmallString<12> ValueString;
16743       bool Print;
16744     } DiagSide[2] = {{LHS, Expr::EvalResult(), {}, false},
16745                      {RHS, Expr::EvalResult(), {}, false}};
16746     for (unsigned I = 0; I < 2; I++) {
16747       const Expr *Side = DiagSide[I].Cond;
16748 
16749       Side->EvaluateAsRValue(DiagSide[I].Result, Context, true);
16750 
16751       DiagSide[I].Print = ConvertAPValueToString(
16752           DiagSide[I].Result.Val, Side->getType(), DiagSide[I].ValueString);
16753     }
16754     if (DiagSide[0].Print && DiagSide[1].Print) {
16755       Diag(Op->getExprLoc(), diag::note_expr_evaluates_to)
16756           << DiagSide[0].ValueString << Op->getOpcodeStr()
16757           << DiagSide[1].ValueString << Op->getSourceRange();
16758     }
16759   }
16760 }
16761 
16762 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
16763                                          Expr *AssertExpr,
16764                                          StringLiteral *AssertMessage,
16765                                          SourceLocation RParenLoc,
16766                                          bool Failed) {
16767   assert(AssertExpr != nullptr && "Expected non-null condition");
16768   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
16769       !Failed) {
16770     // In a static_assert-declaration, the constant-expression shall be a
16771     // constant expression that can be contextually converted to bool.
16772     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
16773     if (Converted.isInvalid())
16774       Failed = true;
16775 
16776     ExprResult FullAssertExpr =
16777         ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
16778                             /*DiscardedValue*/ false,
16779                             /*IsConstexpr*/ true);
16780     if (FullAssertExpr.isInvalid())
16781       Failed = true;
16782     else
16783       AssertExpr = FullAssertExpr.get();
16784 
16785     llvm::APSInt Cond;
16786     Expr *BaseExpr = AssertExpr;
16787     AllowFoldKind FoldKind = NoFold;
16788 
16789     if (!getLangOpts().CPlusPlus) {
16790       // In C mode, allow folding as an extension for better compatibility with
16791       // C++ in terms of expressions like static_assert("test") or
16792       // static_assert(nullptr).
16793       FoldKind = AllowFold;
16794     }
16795 
16796     if (!Failed && VerifyIntegerConstantExpression(
16797                        BaseExpr, &Cond,
16798                        diag::err_static_assert_expression_is_not_constant,
16799                        FoldKind).isInvalid())
16800       Failed = true;
16801 
16802     if (!Failed && !Cond) {
16803       SmallString<256> MsgBuffer;
16804       llvm::raw_svector_ostream Msg(MsgBuffer);
16805       if (AssertMessage) {
16806         const auto *MsgStr = cast<StringLiteral>(AssertMessage);
16807         if (MsgStr->isOrdinary())
16808           Msg << MsgStr->getString();
16809         else
16810           MsgStr->printPretty(Msg, nullptr, getPrintingPolicy());
16811       }
16812 
16813       Expr *InnerCond = nullptr;
16814       std::string InnerCondDescription;
16815       std::tie(InnerCond, InnerCondDescription) =
16816         findFailedBooleanCondition(Converted.get());
16817       if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {
16818         // Drill down into concept specialization expressions to see why they
16819         // weren't satisfied.
16820         Diag(StaticAssertLoc, diag::err_static_assert_failed)
16821           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16822         ConstraintSatisfaction Satisfaction;
16823         if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
16824           DiagnoseUnsatisfiedConstraint(Satisfaction);
16825       } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
16826                            && !isa<IntegerLiteral>(InnerCond)) {
16827         Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
16828           << InnerCondDescription << !AssertMessage
16829           << Msg.str() << InnerCond->getSourceRange();
16830         DiagnoseStaticAssertDetails(InnerCond);
16831       } else {
16832         Diag(StaticAssertLoc, diag::err_static_assert_failed)
16833           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16834       }
16835       Failed = true;
16836     }
16837   } else {
16838     ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
16839                                                     /*DiscardedValue*/false,
16840                                                     /*IsConstexpr*/true);
16841     if (FullAssertExpr.isInvalid())
16842       Failed = true;
16843     else
16844       AssertExpr = FullAssertExpr.get();
16845   }
16846 
16847   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
16848                                         AssertExpr, AssertMessage, RParenLoc,
16849                                         Failed);
16850 
16851   CurContext->addDecl(Decl);
16852   return Decl;
16853 }
16854 
16855 /// Perform semantic analysis of the given friend type declaration.
16856 ///
16857 /// \returns A friend declaration that.
16858 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
16859                                       SourceLocation FriendLoc,
16860                                       TypeSourceInfo *TSInfo) {
16861   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
16862 
16863   QualType T = TSInfo->getType();
16864   SourceRange TypeRange = TSInfo->getTypeLoc().getSourceRange();
16865 
16866   // C++03 [class.friend]p2:
16867   //   An elaborated-type-specifier shall be used in a friend declaration
16868   //   for a class.*
16869   //
16870   //   * The class-key of the elaborated-type-specifier is required.
16871   if (!CodeSynthesisContexts.empty()) {
16872     // Do not complain about the form of friend template types during any kind
16873     // of code synthesis. For template instantiation, we will have complained
16874     // when the template was defined.
16875   } else {
16876     if (!T->isElaboratedTypeSpecifier()) {
16877       // If we evaluated the type to a record type, suggest putting
16878       // a tag in front.
16879       if (const RecordType *RT = T->getAs<RecordType>()) {
16880         RecordDecl *RD = RT->getDecl();
16881 
16882         SmallString<16> InsertionText(" ");
16883         InsertionText += RD->getKindName();
16884 
16885         Diag(TypeRange.getBegin(),
16886              getLangOpts().CPlusPlus11 ?
16887                diag::warn_cxx98_compat_unelaborated_friend_type :
16888                diag::ext_unelaborated_friend_type)
16889           << (unsigned) RD->getTagKind()
16890           << T
16891           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
16892                                         InsertionText);
16893       } else {
16894         Diag(FriendLoc,
16895              getLangOpts().CPlusPlus11 ?
16896                diag::warn_cxx98_compat_nonclass_type_friend :
16897                diag::ext_nonclass_type_friend)
16898           << T
16899           << TypeRange;
16900       }
16901     } else if (T->getAs<EnumType>()) {
16902       Diag(FriendLoc,
16903            getLangOpts().CPlusPlus11 ?
16904              diag::warn_cxx98_compat_enum_friend :
16905              diag::ext_enum_friend)
16906         << T
16907         << TypeRange;
16908     }
16909 
16910     // C++11 [class.friend]p3:
16911     //   A friend declaration that does not declare a function shall have one
16912     //   of the following forms:
16913     //     friend elaborated-type-specifier ;
16914     //     friend simple-type-specifier ;
16915     //     friend typename-specifier ;
16916     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
16917       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
16918   }
16919 
16920   //   If the type specifier in a friend declaration designates a (possibly
16921   //   cv-qualified) class type, that class is declared as a friend; otherwise,
16922   //   the friend declaration is ignored.
16923   return FriendDecl::Create(Context, CurContext,
16924                             TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
16925                             FriendLoc);
16926 }
16927 
16928 /// Handle a friend tag declaration where the scope specifier was
16929 /// templated.
16930 DeclResult Sema::ActOnTemplatedFriendTag(
16931     Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc,
16932     CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
16933     const ParsedAttributesView &Attr, MultiTemplateParamsArg TempParamLists) {
16934   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
16935 
16936   bool IsMemberSpecialization = false;
16937   bool Invalid = false;
16938 
16939   if (TemplateParameterList *TemplateParams =
16940           MatchTemplateParametersToScopeSpecifier(
16941               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
16942               IsMemberSpecialization, Invalid)) {
16943     if (TemplateParams->size() > 0) {
16944       // This is a declaration of a class template.
16945       if (Invalid)
16946         return true;
16947 
16948       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
16949                                 NameLoc, Attr, TemplateParams, AS_public,
16950                                 /*ModulePrivateLoc=*/SourceLocation(),
16951                                 FriendLoc, TempParamLists.size() - 1,
16952                                 TempParamLists.data()).get();
16953     } else {
16954       // The "template<>" header is extraneous.
16955       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16956         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
16957       IsMemberSpecialization = true;
16958     }
16959   }
16960 
16961   if (Invalid) return true;
16962 
16963   bool isAllExplicitSpecializations = true;
16964   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
16965     if (TempParamLists[I]->size()) {
16966       isAllExplicitSpecializations = false;
16967       break;
16968     }
16969   }
16970 
16971   // FIXME: don't ignore attributes.
16972 
16973   // If it's explicit specializations all the way down, just forget
16974   // about the template header and build an appropriate non-templated
16975   // friend.  TODO: for source fidelity, remember the headers.
16976   if (isAllExplicitSpecializations) {
16977     if (SS.isEmpty()) {
16978       bool Owned = false;
16979       bool IsDependent = false;
16980       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, Attr,
16981                       AS_public,
16982                       /*ModulePrivateLoc=*/SourceLocation(),
16983                       MultiTemplateParamsArg(), Owned, IsDependent,
16984                       /*ScopedEnumKWLoc=*/SourceLocation(),
16985                       /*ScopedEnumUsesClassTag=*/false,
16986                       /*UnderlyingType=*/TypeResult(),
16987                       /*IsTypeSpecifier=*/false,
16988                       /*IsTemplateParamOrArg=*/false, /*OOK=*/OOK_Outside);
16989     }
16990 
16991     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
16992     ElaboratedTypeKeyword Keyword
16993       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16994     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
16995                                    *Name, NameLoc);
16996     if (T.isNull())
16997       return true;
16998 
16999     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
17000     if (isa<DependentNameType>(T)) {
17001       DependentNameTypeLoc TL =
17002           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
17003       TL.setElaboratedKeywordLoc(TagLoc);
17004       TL.setQualifierLoc(QualifierLoc);
17005       TL.setNameLoc(NameLoc);
17006     } else {
17007       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
17008       TL.setElaboratedKeywordLoc(TagLoc);
17009       TL.setQualifierLoc(QualifierLoc);
17010       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
17011     }
17012 
17013     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
17014                                             TSI, FriendLoc, TempParamLists);
17015     Friend->setAccess(AS_public);
17016     CurContext->addDecl(Friend);
17017     return Friend;
17018   }
17019 
17020   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
17021 
17022 
17023 
17024   // Handle the case of a templated-scope friend class.  e.g.
17025   //   template <class T> class A<T>::B;
17026   // FIXME: we don't support these right now.
17027   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
17028     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
17029   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
17030   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
17031   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
17032   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
17033   TL.setElaboratedKeywordLoc(TagLoc);
17034   TL.setQualifierLoc(SS.getWithLocInContext(Context));
17035   TL.setNameLoc(NameLoc);
17036 
17037   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
17038                                           TSI, FriendLoc, TempParamLists);
17039   Friend->setAccess(AS_public);
17040   Friend->setUnsupportedFriend(true);
17041   CurContext->addDecl(Friend);
17042   return Friend;
17043 }
17044 
17045 /// Handle a friend type declaration.  This works in tandem with
17046 /// ActOnTag.
17047 ///
17048 /// Notes on friend class templates:
17049 ///
17050 /// We generally treat friend class declarations as if they were
17051 /// declaring a class.  So, for example, the elaborated type specifier
17052 /// in a friend declaration is required to obey the restrictions of a
17053 /// class-head (i.e. no typedefs in the scope chain), template
17054 /// parameters are required to match up with simple template-ids, &c.
17055 /// However, unlike when declaring a template specialization, it's
17056 /// okay to refer to a template specialization without an empty
17057 /// template parameter declaration, e.g.
17058 ///   friend class A<T>::B<unsigned>;
17059 /// We permit this as a special case; if there are any template
17060 /// parameters present at all, require proper matching, i.e.
17061 ///   template <> template \<class T> friend class A<int>::B;
17062 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
17063                                 MultiTemplateParamsArg TempParams) {
17064   SourceLocation Loc = DS.getBeginLoc();
17065 
17066   assert(DS.isFriendSpecified());
17067   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
17068 
17069   // C++ [class.friend]p3:
17070   // A friend declaration that does not declare a function shall have one of
17071   // the following forms:
17072   //     friend elaborated-type-specifier ;
17073   //     friend simple-type-specifier ;
17074   //     friend typename-specifier ;
17075   //
17076   // Any declaration with a type qualifier does not have that form. (It's
17077   // legal to specify a qualified type as a friend, you just can't write the
17078   // keywords.)
17079   if (DS.getTypeQualifiers()) {
17080     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
17081       Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
17082     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
17083       Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
17084     if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
17085       Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
17086     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
17087       Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
17088     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
17089       Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
17090   }
17091 
17092   // Try to convert the decl specifier to a type.  This works for
17093   // friend templates because ActOnTag never produces a ClassTemplateDecl
17094   // for a TUK_Friend.
17095   Declarator TheDeclarator(DS, ParsedAttributesView::none(),
17096                            DeclaratorContext::Member);
17097   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
17098   QualType T = TSI->getType();
17099   if (TheDeclarator.isInvalidType())
17100     return nullptr;
17101 
17102   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
17103     return nullptr;
17104 
17105   // This is definitely an error in C++98.  It's probably meant to
17106   // be forbidden in C++0x, too, but the specification is just
17107   // poorly written.
17108   //
17109   // The problem is with declarations like the following:
17110   //   template <T> friend A<T>::foo;
17111   // where deciding whether a class C is a friend or not now hinges
17112   // on whether there exists an instantiation of A that causes
17113   // 'foo' to equal C.  There are restrictions on class-heads
17114   // (which we declare (by fiat) elaborated friend declarations to
17115   // be) that makes this tractable.
17116   //
17117   // FIXME: handle "template <> friend class A<T>;", which
17118   // is possibly well-formed?  Who even knows?
17119   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
17120     Diag(Loc, diag::err_tagless_friend_type_template)
17121       << DS.getSourceRange();
17122     return nullptr;
17123   }
17124 
17125   // C++98 [class.friend]p1: A friend of a class is a function
17126   //   or class that is not a member of the class . . .
17127   // This is fixed in DR77, which just barely didn't make the C++03
17128   // deadline.  It's also a very silly restriction that seriously
17129   // affects inner classes and which nobody else seems to implement;
17130   // thus we never diagnose it, not even in -pedantic.
17131   //
17132   // But note that we could warn about it: it's always useless to
17133   // friend one of your own members (it's not, however, worthless to
17134   // friend a member of an arbitrary specialization of your template).
17135 
17136   Decl *D;
17137   if (!TempParams.empty())
17138     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
17139                                    TempParams,
17140                                    TSI,
17141                                    DS.getFriendSpecLoc());
17142   else
17143     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
17144 
17145   if (!D)
17146     return nullptr;
17147 
17148   D->setAccess(AS_public);
17149   CurContext->addDecl(D);
17150 
17151   return D;
17152 }
17153 
17154 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
17155                                         MultiTemplateParamsArg TemplateParams) {
17156   const DeclSpec &DS = D.getDeclSpec();
17157 
17158   assert(DS.isFriendSpecified());
17159   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
17160 
17161   SourceLocation Loc = D.getIdentifierLoc();
17162   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17163 
17164   // C++ [class.friend]p1
17165   //   A friend of a class is a function or class....
17166   // Note that this sees through typedefs, which is intended.
17167   // It *doesn't* see through dependent types, which is correct
17168   // according to [temp.arg.type]p3:
17169   //   If a declaration acquires a function type through a
17170   //   type dependent on a template-parameter and this causes
17171   //   a declaration that does not use the syntactic form of a
17172   //   function declarator to have a function type, the program
17173   //   is ill-formed.
17174   if (!TInfo->getType()->isFunctionType()) {
17175     Diag(Loc, diag::err_unexpected_friend);
17176 
17177     // It might be worthwhile to try to recover by creating an
17178     // appropriate declaration.
17179     return nullptr;
17180   }
17181 
17182   // C++ [namespace.memdef]p3
17183   //  - If a friend declaration in a non-local class first declares a
17184   //    class or function, the friend class or function is a member
17185   //    of the innermost enclosing namespace.
17186   //  - The name of the friend is not found by simple name lookup
17187   //    until a matching declaration is provided in that namespace
17188   //    scope (either before or after the class declaration granting
17189   //    friendship).
17190   //  - If a friend function is called, its name may be found by the
17191   //    name lookup that considers functions from namespaces and
17192   //    classes associated with the types of the function arguments.
17193   //  - When looking for a prior declaration of a class or a function
17194   //    declared as a friend, scopes outside the innermost enclosing
17195   //    namespace scope are not considered.
17196 
17197   CXXScopeSpec &SS = D.getCXXScopeSpec();
17198   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
17199   assert(NameInfo.getName());
17200 
17201   // Check for unexpanded parameter packs.
17202   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
17203       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
17204       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
17205     return nullptr;
17206 
17207   // The context we found the declaration in, or in which we should
17208   // create the declaration.
17209   DeclContext *DC;
17210   Scope *DCScope = S;
17211   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
17212                         ForExternalRedeclaration);
17213 
17214   // There are five cases here.
17215   //   - There's no scope specifier and we're in a local class. Only look
17216   //     for functions declared in the immediately-enclosing block scope.
17217   // We recover from invalid scope qualifiers as if they just weren't there.
17218   FunctionDecl *FunctionContainingLocalClass = nullptr;
17219   if ((SS.isInvalid() || !SS.isSet()) &&
17220       (FunctionContainingLocalClass =
17221            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
17222     // C++11 [class.friend]p11:
17223     //   If a friend declaration appears in a local class and the name
17224     //   specified is an unqualified name, a prior declaration is
17225     //   looked up without considering scopes that are outside the
17226     //   innermost enclosing non-class scope. For a friend function
17227     //   declaration, if there is no prior declaration, the program is
17228     //   ill-formed.
17229 
17230     // Find the innermost enclosing non-class scope. This is the block
17231     // scope containing the local class definition (or for a nested class,
17232     // the outer local class).
17233     DCScope = S->getFnParent();
17234 
17235     // Look up the function name in the scope.
17236     Previous.clear(LookupLocalFriendName);
17237     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
17238 
17239     if (!Previous.empty()) {
17240       // All possible previous declarations must have the same context:
17241       // either they were declared at block scope or they are members of
17242       // one of the enclosing local classes.
17243       DC = Previous.getRepresentativeDecl()->getDeclContext();
17244     } else {
17245       // This is ill-formed, but provide the context that we would have
17246       // declared the function in, if we were permitted to, for error recovery.
17247       DC = FunctionContainingLocalClass;
17248     }
17249     adjustContextForLocalExternDecl(DC);
17250 
17251     // C++ [class.friend]p6:
17252     //   A function can be defined in a friend declaration of a class if and
17253     //   only if the class is a non-local class (9.8), the function name is
17254     //   unqualified, and the function has namespace scope.
17255     if (D.isFunctionDefinition()) {
17256       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
17257     }
17258 
17259   //   - There's no scope specifier, in which case we just go to the
17260   //     appropriate scope and look for a function or function template
17261   //     there as appropriate.
17262   } else if (SS.isInvalid() || !SS.isSet()) {
17263     // C++11 [namespace.memdef]p3:
17264     //   If the name in a friend declaration is neither qualified nor
17265     //   a template-id and the declaration is a function or an
17266     //   elaborated-type-specifier, the lookup to determine whether
17267     //   the entity has been previously declared shall not consider
17268     //   any scopes outside the innermost enclosing namespace.
17269     bool isTemplateId =
17270         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
17271 
17272     // Find the appropriate context according to the above.
17273     DC = CurContext;
17274 
17275     // Skip class contexts.  If someone can cite chapter and verse
17276     // for this behavior, that would be nice --- it's what GCC and
17277     // EDG do, and it seems like a reasonable intent, but the spec
17278     // really only says that checks for unqualified existing
17279     // declarations should stop at the nearest enclosing namespace,
17280     // not that they should only consider the nearest enclosing
17281     // namespace.
17282     while (DC->isRecord())
17283       DC = DC->getParent();
17284 
17285     DeclContext *LookupDC = DC->getNonTransparentContext();
17286     while (true) {
17287       LookupQualifiedName(Previous, LookupDC);
17288 
17289       if (!Previous.empty()) {
17290         DC = LookupDC;
17291         break;
17292       }
17293 
17294       if (isTemplateId) {
17295         if (isa<TranslationUnitDecl>(LookupDC)) break;
17296       } else {
17297         if (LookupDC->isFileContext()) break;
17298       }
17299       LookupDC = LookupDC->getParent();
17300     }
17301 
17302     DCScope = getScopeForDeclContext(S, DC);
17303 
17304   //   - There's a non-dependent scope specifier, in which case we
17305   //     compute it and do a previous lookup there for a function
17306   //     or function template.
17307   } else if (!SS.getScopeRep()->isDependent()) {
17308     DC = computeDeclContext(SS);
17309     if (!DC) return nullptr;
17310 
17311     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
17312 
17313     LookupQualifiedName(Previous, DC);
17314 
17315     // C++ [class.friend]p1: A friend of a class is a function or
17316     //   class that is not a member of the class . . .
17317     if (DC->Equals(CurContext))
17318       Diag(DS.getFriendSpecLoc(),
17319            getLangOpts().CPlusPlus11 ?
17320              diag::warn_cxx98_compat_friend_is_member :
17321              diag::err_friend_is_member);
17322 
17323     if (D.isFunctionDefinition()) {
17324       // C++ [class.friend]p6:
17325       //   A function can be defined in a friend declaration of a class if and
17326       //   only if the class is a non-local class (9.8), the function name is
17327       //   unqualified, and the function has namespace scope.
17328       //
17329       // FIXME: We should only do this if the scope specifier names the
17330       // innermost enclosing namespace; otherwise the fixit changes the
17331       // meaning of the code.
17332       SemaDiagnosticBuilder DB
17333         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
17334 
17335       DB << SS.getScopeRep();
17336       if (DC->isFileContext())
17337         DB << FixItHint::CreateRemoval(SS.getRange());
17338       SS.clear();
17339     }
17340 
17341   //   - There's a scope specifier that does not match any template
17342   //     parameter lists, in which case we use some arbitrary context,
17343   //     create a method or method template, and wait for instantiation.
17344   //   - There's a scope specifier that does match some template
17345   //     parameter lists, which we don't handle right now.
17346   } else {
17347     if (D.isFunctionDefinition()) {
17348       // C++ [class.friend]p6:
17349       //   A function can be defined in a friend declaration of a class if and
17350       //   only if the class is a non-local class (9.8), the function name is
17351       //   unqualified, and the function has namespace scope.
17352       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
17353         << SS.getScopeRep();
17354     }
17355 
17356     DC = CurContext;
17357     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
17358   }
17359 
17360   if (!DC->isRecord()) {
17361     int DiagArg = -1;
17362     switch (D.getName().getKind()) {
17363     case UnqualifiedIdKind::IK_ConstructorTemplateId:
17364     case UnqualifiedIdKind::IK_ConstructorName:
17365       DiagArg = 0;
17366       break;
17367     case UnqualifiedIdKind::IK_DestructorName:
17368       DiagArg = 1;
17369       break;
17370     case UnqualifiedIdKind::IK_ConversionFunctionId:
17371       DiagArg = 2;
17372       break;
17373     case UnqualifiedIdKind::IK_DeductionGuideName:
17374       DiagArg = 3;
17375       break;
17376     case UnqualifiedIdKind::IK_Identifier:
17377     case UnqualifiedIdKind::IK_ImplicitSelfParam:
17378     case UnqualifiedIdKind::IK_LiteralOperatorId:
17379     case UnqualifiedIdKind::IK_OperatorFunctionId:
17380     case UnqualifiedIdKind::IK_TemplateId:
17381       break;
17382     }
17383     // This implies that it has to be an operator or function.
17384     if (DiagArg >= 0) {
17385       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
17386       return nullptr;
17387     }
17388   }
17389 
17390   // FIXME: This is an egregious hack to cope with cases where the scope stack
17391   // does not contain the declaration context, i.e., in an out-of-line
17392   // definition of a class.
17393   Scope FakeDCScope(S, Scope::DeclScope, Diags);
17394   if (!DCScope) {
17395     FakeDCScope.setEntity(DC);
17396     DCScope = &FakeDCScope;
17397   }
17398 
17399   bool AddToScope = true;
17400   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
17401                                           TemplateParams, AddToScope);
17402   if (!ND) return nullptr;
17403 
17404   assert(ND->getLexicalDeclContext() == CurContext);
17405 
17406   // If we performed typo correction, we might have added a scope specifier
17407   // and changed the decl context.
17408   DC = ND->getDeclContext();
17409 
17410   // Add the function declaration to the appropriate lookup tables,
17411   // adjusting the redeclarations list as necessary.  We don't
17412   // want to do this yet if the friending class is dependent.
17413   //
17414   // Also update the scope-based lookup if the target context's
17415   // lookup context is in lexical scope.
17416   if (!CurContext->isDependentContext()) {
17417     DC = DC->getRedeclContext();
17418     DC->makeDeclVisibleInContext(ND);
17419     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
17420       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
17421   }
17422 
17423   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
17424                                        D.getIdentifierLoc(), ND,
17425                                        DS.getFriendSpecLoc());
17426   FrD->setAccess(AS_public);
17427   CurContext->addDecl(FrD);
17428 
17429   if (ND->isInvalidDecl()) {
17430     FrD->setInvalidDecl();
17431   } else {
17432     if (DC->isRecord()) CheckFriendAccess(ND);
17433 
17434     FunctionDecl *FD;
17435     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
17436       FD = FTD->getTemplatedDecl();
17437     else
17438       FD = cast<FunctionDecl>(ND);
17439 
17440     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
17441     // default argument expression, that declaration shall be a definition
17442     // and shall be the only declaration of the function or function
17443     // template in the translation unit.
17444     if (functionDeclHasDefaultArgument(FD)) {
17445       // We can't look at FD->getPreviousDecl() because it may not have been set
17446       // if we're in a dependent context. If the function is known to be a
17447       // redeclaration, we will have narrowed Previous down to the right decl.
17448       if (D.isRedeclaration()) {
17449         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
17450         Diag(Previous.getRepresentativeDecl()->getLocation(),
17451              diag::note_previous_declaration);
17452       } else if (!D.isFunctionDefinition())
17453         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
17454     }
17455 
17456     // Mark templated-scope function declarations as unsupported.
17457     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
17458       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
17459         << SS.getScopeRep() << SS.getRange()
17460         << cast<CXXRecordDecl>(CurContext);
17461       FrD->setUnsupportedFriend(true);
17462     }
17463   }
17464 
17465   warnOnReservedIdentifier(ND);
17466 
17467   return ND;
17468 }
17469 
17470 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
17471   AdjustDeclIfTemplate(Dcl);
17472 
17473   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
17474   if (!Fn) {
17475     Diag(DelLoc, diag::err_deleted_non_function);
17476     return;
17477   }
17478 
17479   // Deleted function does not have a body.
17480   Fn->setWillHaveBody(false);
17481 
17482   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
17483     // Don't consider the implicit declaration we generate for explicit
17484     // specializations. FIXME: Do not generate these implicit declarations.
17485     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
17486          Prev->getPreviousDecl()) &&
17487         !Prev->isDefined()) {
17488       Diag(DelLoc, diag::err_deleted_decl_not_first);
17489       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
17490            Prev->isImplicit() ? diag::note_previous_implicit_declaration
17491                               : diag::note_previous_declaration);
17492       // We can't recover from this; the declaration might have already
17493       // been used.
17494       Fn->setInvalidDecl();
17495       return;
17496     }
17497 
17498     // To maintain the invariant that functions are only deleted on their first
17499     // declaration, mark the implicitly-instantiated declaration of the
17500     // explicitly-specialized function as deleted instead of marking the
17501     // instantiated redeclaration.
17502     Fn = Fn->getCanonicalDecl();
17503   }
17504 
17505   // dllimport/dllexport cannot be deleted.
17506   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
17507     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
17508     Fn->setInvalidDecl();
17509   }
17510 
17511   // C++11 [basic.start.main]p3:
17512   //   A program that defines main as deleted [...] is ill-formed.
17513   if (Fn->isMain())
17514     Diag(DelLoc, diag::err_deleted_main);
17515 
17516   // C++11 [dcl.fct.def.delete]p4:
17517   //  A deleted function is implicitly inline.
17518   Fn->setImplicitlyInline();
17519   Fn->setDeletedAsWritten();
17520 }
17521 
17522 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
17523   if (!Dcl || Dcl->isInvalidDecl())
17524     return;
17525 
17526   auto *FD = dyn_cast<FunctionDecl>(Dcl);
17527   if (!FD) {
17528     if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
17529       if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
17530         Diag(DefaultLoc, diag::err_defaulted_comparison_template);
17531         return;
17532       }
17533     }
17534 
17535     Diag(DefaultLoc, diag::err_default_special_members)
17536         << getLangOpts().CPlusPlus20;
17537     return;
17538   }
17539 
17540   // Reject if this can't possibly be a defaultable function.
17541   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
17542   if (!DefKind &&
17543       // A dependent function that doesn't locally look defaultable can
17544       // still instantiate to a defaultable function if it's a constructor
17545       // or assignment operator.
17546       (!FD->isDependentContext() ||
17547        (!isa<CXXConstructorDecl>(FD) &&
17548         FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
17549     Diag(DefaultLoc, diag::err_default_special_members)
17550         << getLangOpts().CPlusPlus20;
17551     return;
17552   }
17553 
17554   // Issue compatibility warning. We already warned if the operator is
17555   // 'operator<=>' when parsing the '<=>' token.
17556   if (DefKind.isComparison() &&
17557       DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
17558     Diag(DefaultLoc, getLangOpts().CPlusPlus20
17559                          ? diag::warn_cxx17_compat_defaulted_comparison
17560                          : diag::ext_defaulted_comparison);
17561   }
17562 
17563   FD->setDefaulted();
17564   FD->setExplicitlyDefaulted();
17565   FD->setDefaultLoc(DefaultLoc);
17566 
17567   // Defer checking functions that are defaulted in a dependent context.
17568   if (FD->isDependentContext())
17569     return;
17570 
17571   // Unset that we will have a body for this function. We might not,
17572   // if it turns out to be trivial, and we don't need this marking now
17573   // that we've marked it as defaulted.
17574   FD->setWillHaveBody(false);
17575 
17576   if (DefKind.isComparison()) {
17577     // If this comparison's defaulting occurs within the definition of its
17578     // lexical class context, we have to do the checking when complete.
17579     if (auto const *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()))
17580       if (!RD->isCompleteDefinition())
17581         return;
17582   }
17583 
17584   // If this member fn was defaulted on its first declaration, we will have
17585   // already performed the checking in CheckCompletedCXXClass. Such a
17586   // declaration doesn't trigger an implicit definition.
17587   if (isa<CXXMethodDecl>(FD)) {
17588     const FunctionDecl *Primary = FD;
17589     if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
17590       // Ask the template instantiation pattern that actually had the
17591       // '= default' on it.
17592       Primary = Pattern;
17593     if (Primary->getCanonicalDecl()->isDefaulted())
17594       return;
17595   }
17596 
17597   if (DefKind.isComparison()) {
17598     if (CheckExplicitlyDefaultedComparison(nullptr, FD, DefKind.asComparison()))
17599       FD->setInvalidDecl();
17600     else
17601       DefineDefaultedComparison(DefaultLoc, FD, DefKind.asComparison());
17602   } else {
17603     auto *MD = cast<CXXMethodDecl>(FD);
17604 
17605     if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember(),
17606                                               DefaultLoc))
17607       MD->setInvalidDecl();
17608     else
17609       DefineDefaultedFunction(*this, MD, DefaultLoc);
17610   }
17611 }
17612 
17613 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
17614   for (Stmt *SubStmt : S->children()) {
17615     if (!SubStmt)
17616       continue;
17617     if (isa<ReturnStmt>(SubStmt))
17618       Self.Diag(SubStmt->getBeginLoc(),
17619                 diag::err_return_in_constructor_handler);
17620     if (!isa<Expr>(SubStmt))
17621       SearchForReturnInStmt(Self, SubStmt);
17622   }
17623 }
17624 
17625 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
17626   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
17627     CXXCatchStmt *Handler = TryBlock->getHandler(I);
17628     SearchForReturnInStmt(*this, Handler);
17629   }
17630 }
17631 
17632 void Sema::SetFunctionBodyKind(Decl *D, SourceLocation Loc,
17633                                FnBodyKind BodyKind) {
17634   switch (BodyKind) {
17635   case FnBodyKind::Delete:
17636     SetDeclDeleted(D, Loc);
17637     break;
17638   case FnBodyKind::Default:
17639     SetDeclDefaulted(D, Loc);
17640     break;
17641   case FnBodyKind::Other:
17642     llvm_unreachable(
17643         "Parsed function body should be '= delete;' or '= default;'");
17644   }
17645 }
17646 
17647 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
17648                                              const CXXMethodDecl *Old) {
17649   const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
17650   const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
17651 
17652   if (OldFT->hasExtParameterInfos()) {
17653     for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
17654       // A parameter of the overriding method should be annotated with noescape
17655       // if the corresponding parameter of the overridden method is annotated.
17656       if (OldFT->getExtParameterInfo(I).isNoEscape() &&
17657           !NewFT->getExtParameterInfo(I).isNoEscape()) {
17658         Diag(New->getParamDecl(I)->getLocation(),
17659              diag::warn_overriding_method_missing_noescape);
17660         Diag(Old->getParamDecl(I)->getLocation(),
17661              diag::note_overridden_marked_noescape);
17662       }
17663   }
17664 
17665   // Virtual overrides must have the same code_seg.
17666   const auto *OldCSA = Old->getAttr<CodeSegAttr>();
17667   const auto *NewCSA = New->getAttr<CodeSegAttr>();
17668   if ((NewCSA || OldCSA) &&
17669       (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
17670     Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
17671     Diag(Old->getLocation(), diag::note_previous_declaration);
17672     return true;
17673   }
17674 
17675   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
17676 
17677   // If the calling conventions match, everything is fine
17678   if (NewCC == OldCC)
17679     return false;
17680 
17681   // If the calling conventions mismatch because the new function is static,
17682   // suppress the calling convention mismatch error; the error about static
17683   // function override (err_static_overrides_virtual from
17684   // Sema::CheckFunctionDeclaration) is more clear.
17685   if (New->getStorageClass() == SC_Static)
17686     return false;
17687 
17688   Diag(New->getLocation(),
17689        diag::err_conflicting_overriding_cc_attributes)
17690     << New->getDeclName() << New->getType() << Old->getType();
17691   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
17692   return true;
17693 }
17694 
17695 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
17696                                              const CXXMethodDecl *Old) {
17697   QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
17698   QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
17699 
17700   if (Context.hasSameType(NewTy, OldTy) ||
17701       NewTy->isDependentType() || OldTy->isDependentType())
17702     return false;
17703 
17704   // Check if the return types are covariant
17705   QualType NewClassTy, OldClassTy;
17706 
17707   /// Both types must be pointers or references to classes.
17708   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
17709     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
17710       NewClassTy = NewPT->getPointeeType();
17711       OldClassTy = OldPT->getPointeeType();
17712     }
17713   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
17714     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
17715       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
17716         NewClassTy = NewRT->getPointeeType();
17717         OldClassTy = OldRT->getPointeeType();
17718       }
17719     }
17720   }
17721 
17722   // The return types aren't either both pointers or references to a class type.
17723   if (NewClassTy.isNull()) {
17724     Diag(New->getLocation(),
17725          diag::err_different_return_type_for_overriding_virtual_function)
17726         << New->getDeclName() << NewTy << OldTy
17727         << New->getReturnTypeSourceRange();
17728     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17729         << Old->getReturnTypeSourceRange();
17730 
17731     return true;
17732   }
17733 
17734   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
17735     // C++14 [class.virtual]p8:
17736     //   If the class type in the covariant return type of D::f differs from
17737     //   that of B::f, the class type in the return type of D::f shall be
17738     //   complete at the point of declaration of D::f or shall be the class
17739     //   type D.
17740     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
17741       if (!RT->isBeingDefined() &&
17742           RequireCompleteType(New->getLocation(), NewClassTy,
17743                               diag::err_covariant_return_incomplete,
17744                               New->getDeclName()))
17745         return true;
17746     }
17747 
17748     // Check if the new class derives from the old class.
17749     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
17750       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
17751           << New->getDeclName() << NewTy << OldTy
17752           << New->getReturnTypeSourceRange();
17753       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17754           << Old->getReturnTypeSourceRange();
17755       return true;
17756     }
17757 
17758     // Check if we the conversion from derived to base is valid.
17759     if (CheckDerivedToBaseConversion(
17760             NewClassTy, OldClassTy,
17761             diag::err_covariant_return_inaccessible_base,
17762             diag::err_covariant_return_ambiguous_derived_to_base_conv,
17763             New->getLocation(), New->getReturnTypeSourceRange(),
17764             New->getDeclName(), nullptr)) {
17765       // FIXME: this note won't trigger for delayed access control
17766       // diagnostics, and it's impossible to get an undelayed error
17767       // here from access control during the original parse because
17768       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
17769       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17770           << Old->getReturnTypeSourceRange();
17771       return true;
17772     }
17773   }
17774 
17775   // The qualifiers of the return types must be the same.
17776   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
17777     Diag(New->getLocation(),
17778          diag::err_covariant_return_type_different_qualifications)
17779         << New->getDeclName() << NewTy << OldTy
17780         << New->getReturnTypeSourceRange();
17781     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17782         << Old->getReturnTypeSourceRange();
17783     return true;
17784   }
17785 
17786 
17787   // The new class type must have the same or less qualifiers as the old type.
17788   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
17789     Diag(New->getLocation(),
17790          diag::err_covariant_return_type_class_type_more_qualified)
17791         << New->getDeclName() << NewTy << OldTy
17792         << New->getReturnTypeSourceRange();
17793     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17794         << Old->getReturnTypeSourceRange();
17795     return true;
17796   }
17797 
17798   return false;
17799 }
17800 
17801 /// Mark the given method pure.
17802 ///
17803 /// \param Method the method to be marked pure.
17804 ///
17805 /// \param InitRange the source range that covers the "0" initializer.
17806 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
17807   SourceLocation EndLoc = InitRange.getEnd();
17808   if (EndLoc.isValid())
17809     Method->setRangeEnd(EndLoc);
17810 
17811   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
17812     Method->setPure();
17813     return false;
17814   }
17815 
17816   if (!Method->isInvalidDecl())
17817     Diag(Method->getLocation(), diag::err_non_virtual_pure)
17818       << Method->getDeclName() << InitRange;
17819   return true;
17820 }
17821 
17822 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
17823   if (D->getFriendObjectKind())
17824     Diag(D->getLocation(), diag::err_pure_friend);
17825   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
17826     CheckPureMethod(M, ZeroLoc);
17827   else
17828     Diag(D->getLocation(), diag::err_illegal_initializer);
17829 }
17830 
17831 /// Determine whether the given declaration is a global variable or
17832 /// static data member.
17833 static bool isNonlocalVariable(const Decl *D) {
17834   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
17835     return Var->hasGlobalStorage();
17836 
17837   return false;
17838 }
17839 
17840 /// Invoked when we are about to parse an initializer for the declaration
17841 /// 'Dcl'.
17842 ///
17843 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
17844 /// static data member of class X, names should be looked up in the scope of
17845 /// class X. If the declaration had a scope specifier, a scope will have
17846 /// been created and passed in for this purpose. Otherwise, S will be null.
17847 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
17848   // If there is no declaration, there was an error parsing it.
17849   if (!D || D->isInvalidDecl())
17850     return;
17851 
17852   // We will always have a nested name specifier here, but this declaration
17853   // might not be out of line if the specifier names the current namespace:
17854   //   extern int n;
17855   //   int ::n = 0;
17856   if (S && D->isOutOfLine())
17857     EnterDeclaratorContext(S, D->getDeclContext());
17858 
17859   // If we are parsing the initializer for a static data member, push a
17860   // new expression evaluation context that is associated with this static
17861   // data member.
17862   if (isNonlocalVariable(D))
17863     PushExpressionEvaluationContext(
17864         ExpressionEvaluationContext::PotentiallyEvaluated, D);
17865 }
17866 
17867 /// Invoked after we are finished parsing an initializer for the declaration D.
17868 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
17869   // If there is no declaration, there was an error parsing it.
17870   if (!D || D->isInvalidDecl())
17871     return;
17872 
17873   if (isNonlocalVariable(D))
17874     PopExpressionEvaluationContext();
17875 
17876   if (S && D->isOutOfLine())
17877     ExitDeclaratorContext(S);
17878 }
17879 
17880 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
17881 /// C++ if/switch/while/for statement.
17882 /// e.g: "if (int x = f()) {...}"
17883 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
17884   // C++ 6.4p2:
17885   // The declarator shall not specify a function or an array.
17886   // The type-specifier-seq shall not contain typedef and shall not declare a
17887   // new class or enumeration.
17888   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
17889          "Parser allowed 'typedef' as storage class of condition decl.");
17890 
17891   Decl *Dcl = ActOnDeclarator(S, D);
17892   if (!Dcl)
17893     return true;
17894 
17895   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
17896     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
17897       << D.getSourceRange();
17898     return true;
17899   }
17900 
17901   return Dcl;
17902 }
17903 
17904 void Sema::LoadExternalVTableUses() {
17905   if (!ExternalSource)
17906     return;
17907 
17908   SmallVector<ExternalVTableUse, 4> VTables;
17909   ExternalSource->ReadUsedVTables(VTables);
17910   SmallVector<VTableUse, 4> NewUses;
17911   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
17912     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
17913       = VTablesUsed.find(VTables[I].Record);
17914     // Even if a definition wasn't required before, it may be required now.
17915     if (Pos != VTablesUsed.end()) {
17916       if (!Pos->second && VTables[I].DefinitionRequired)
17917         Pos->second = true;
17918       continue;
17919     }
17920 
17921     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
17922     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
17923   }
17924 
17925   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
17926 }
17927 
17928 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
17929                           bool DefinitionRequired) {
17930   // Ignore any vtable uses in unevaluated operands or for classes that do
17931   // not have a vtable.
17932   if (!Class->isDynamicClass() || Class->isDependentContext() ||
17933       CurContext->isDependentContext() || isUnevaluatedContext())
17934     return;
17935   // Do not mark as used if compiling for the device outside of the target
17936   // region.
17937   if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
17938       !isInOpenMPDeclareTargetContext() &&
17939       !isInOpenMPTargetExecutionDirective()) {
17940     if (!DefinitionRequired)
17941       MarkVirtualMembersReferenced(Loc, Class);
17942     return;
17943   }
17944 
17945   // Try to insert this class into the map.
17946   LoadExternalVTableUses();
17947   Class = Class->getCanonicalDecl();
17948   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
17949     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
17950   if (!Pos.second) {
17951     // If we already had an entry, check to see if we are promoting this vtable
17952     // to require a definition. If so, we need to reappend to the VTableUses
17953     // list, since we may have already processed the first entry.
17954     if (DefinitionRequired && !Pos.first->second) {
17955       Pos.first->second = true;
17956     } else {
17957       // Otherwise, we can early exit.
17958       return;
17959     }
17960   } else {
17961     // The Microsoft ABI requires that we perform the destructor body
17962     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
17963     // the deleting destructor is emitted with the vtable, not with the
17964     // destructor definition as in the Itanium ABI.
17965     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
17966       CXXDestructorDecl *DD = Class->getDestructor();
17967       if (DD && DD->isVirtual() && !DD->isDeleted()) {
17968         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
17969           // If this is an out-of-line declaration, marking it referenced will
17970           // not do anything. Manually call CheckDestructor to look up operator
17971           // delete().
17972           ContextRAII SavedContext(*this, DD);
17973           CheckDestructor(DD);
17974         } else {
17975           MarkFunctionReferenced(Loc, Class->getDestructor());
17976         }
17977       }
17978     }
17979   }
17980 
17981   // Local classes need to have their virtual members marked
17982   // immediately. For all other classes, we mark their virtual members
17983   // at the end of the translation unit.
17984   if (Class->isLocalClass())
17985     MarkVirtualMembersReferenced(Loc, Class);
17986   else
17987     VTableUses.push_back(std::make_pair(Class, Loc));
17988 }
17989 
17990 bool Sema::DefineUsedVTables() {
17991   LoadExternalVTableUses();
17992   if (VTableUses.empty())
17993     return false;
17994 
17995   // Note: The VTableUses vector could grow as a result of marking
17996   // the members of a class as "used", so we check the size each
17997   // time through the loop and prefer indices (which are stable) to
17998   // iterators (which are not).
17999   bool DefinedAnything = false;
18000   for (unsigned I = 0; I != VTableUses.size(); ++I) {
18001     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
18002     if (!Class)
18003       continue;
18004     TemplateSpecializationKind ClassTSK =
18005         Class->getTemplateSpecializationKind();
18006 
18007     SourceLocation Loc = VTableUses[I].second;
18008 
18009     bool DefineVTable = true;
18010 
18011     // If this class has a key function, but that key function is
18012     // defined in another translation unit, we don't need to emit the
18013     // vtable even though we're using it.
18014     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
18015     if (KeyFunction && !KeyFunction->hasBody()) {
18016       // The key function is in another translation unit.
18017       DefineVTable = false;
18018       TemplateSpecializationKind TSK =
18019           KeyFunction->getTemplateSpecializationKind();
18020       assert(TSK != TSK_ExplicitInstantiationDefinition &&
18021              TSK != TSK_ImplicitInstantiation &&
18022              "Instantiations don't have key functions");
18023       (void)TSK;
18024     } else if (!KeyFunction) {
18025       // If we have a class with no key function that is the subject
18026       // of an explicit instantiation declaration, suppress the
18027       // vtable; it will live with the explicit instantiation
18028       // definition.
18029       bool IsExplicitInstantiationDeclaration =
18030           ClassTSK == TSK_ExplicitInstantiationDeclaration;
18031       for (auto *R : Class->redecls()) {
18032         TemplateSpecializationKind TSK
18033           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
18034         if (TSK == TSK_ExplicitInstantiationDeclaration)
18035           IsExplicitInstantiationDeclaration = true;
18036         else if (TSK == TSK_ExplicitInstantiationDefinition) {
18037           IsExplicitInstantiationDeclaration = false;
18038           break;
18039         }
18040       }
18041 
18042       if (IsExplicitInstantiationDeclaration)
18043         DefineVTable = false;
18044     }
18045 
18046     // The exception specifications for all virtual members may be needed even
18047     // if we are not providing an authoritative form of the vtable in this TU.
18048     // We may choose to emit it available_externally anyway.
18049     if (!DefineVTable) {
18050       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
18051       continue;
18052     }
18053 
18054     // Mark all of the virtual members of this class as referenced, so
18055     // that we can build a vtable. Then, tell the AST consumer that a
18056     // vtable for this class is required.
18057     DefinedAnything = true;
18058     MarkVirtualMembersReferenced(Loc, Class);
18059     CXXRecordDecl *Canonical = Class->getCanonicalDecl();
18060     if (VTablesUsed[Canonical])
18061       Consumer.HandleVTable(Class);
18062 
18063     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
18064     // no key function or the key function is inlined. Don't warn in C++ ABIs
18065     // that lack key functions, since the user won't be able to make one.
18066     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
18067         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation &&
18068         ClassTSK != TSK_ExplicitInstantiationDefinition) {
18069       const FunctionDecl *KeyFunctionDef = nullptr;
18070       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
18071                            KeyFunctionDef->isInlined()))
18072         Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
18073     }
18074   }
18075   VTableUses.clear();
18076 
18077   return DefinedAnything;
18078 }
18079 
18080 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
18081                                                  const CXXRecordDecl *RD) {
18082   for (const auto *I : RD->methods())
18083     if (I->isVirtual() && !I->isPure())
18084       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
18085 }
18086 
18087 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
18088                                         const CXXRecordDecl *RD,
18089                                         bool ConstexprOnly) {
18090   // Mark all functions which will appear in RD's vtable as used.
18091   CXXFinalOverriderMap FinalOverriders;
18092   RD->getFinalOverriders(FinalOverriders);
18093   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
18094                                             E = FinalOverriders.end();
18095        I != E; ++I) {
18096     for (OverridingMethods::const_iterator OI = I->second.begin(),
18097                                            OE = I->second.end();
18098          OI != OE; ++OI) {
18099       assert(OI->second.size() > 0 && "no final overrider");
18100       CXXMethodDecl *Overrider = OI->second.front().Method;
18101 
18102       // C++ [basic.def.odr]p2:
18103       //   [...] A virtual member function is used if it is not pure. [...]
18104       if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
18105         MarkFunctionReferenced(Loc, Overrider);
18106     }
18107   }
18108 
18109   // Only classes that have virtual bases need a VTT.
18110   if (RD->getNumVBases() == 0)
18111     return;
18112 
18113   for (const auto &I : RD->bases()) {
18114     const auto *Base =
18115         cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
18116     if (Base->getNumVBases() == 0)
18117       continue;
18118     MarkVirtualMembersReferenced(Loc, Base);
18119   }
18120 }
18121 
18122 /// SetIvarInitializers - This routine builds initialization ASTs for the
18123 /// Objective-C implementation whose ivars need be initialized.
18124 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
18125   if (!getLangOpts().CPlusPlus)
18126     return;
18127   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
18128     SmallVector<ObjCIvarDecl*, 8> ivars;
18129     CollectIvarsToConstructOrDestruct(OID, ivars);
18130     if (ivars.empty())
18131       return;
18132     SmallVector<CXXCtorInitializer*, 32> AllToInit;
18133     for (unsigned i = 0; i < ivars.size(); i++) {
18134       FieldDecl *Field = ivars[i];
18135       if (Field->isInvalidDecl())
18136         continue;
18137 
18138       CXXCtorInitializer *Member;
18139       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
18140       InitializationKind InitKind =
18141         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
18142 
18143       InitializationSequence InitSeq(*this, InitEntity, InitKind, std::nullopt);
18144       ExprResult MemberInit =
18145           InitSeq.Perform(*this, InitEntity, InitKind, std::nullopt);
18146       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
18147       // Note, MemberInit could actually come back empty if no initialization
18148       // is required (e.g., because it would call a trivial default constructor)
18149       if (!MemberInit.get() || MemberInit.isInvalid())
18150         continue;
18151 
18152       Member =
18153         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
18154                                          SourceLocation(),
18155                                          MemberInit.getAs<Expr>(),
18156                                          SourceLocation());
18157       AllToInit.push_back(Member);
18158 
18159       // Be sure that the destructor is accessible and is marked as referenced.
18160       if (const RecordType *RecordTy =
18161               Context.getBaseElementType(Field->getType())
18162                   ->getAs<RecordType>()) {
18163         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
18164         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
18165           MarkFunctionReferenced(Field->getLocation(), Destructor);
18166           CheckDestructorAccess(Field->getLocation(), Destructor,
18167                             PDiag(diag::err_access_dtor_ivar)
18168                               << Context.getBaseElementType(Field->getType()));
18169         }
18170       }
18171     }
18172     ObjCImplementation->setIvarInitializers(Context,
18173                                             AllToInit.data(), AllToInit.size());
18174   }
18175 }
18176 
18177 static
18178 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
18179                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
18180                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
18181                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
18182                            Sema &S) {
18183   if (Ctor->isInvalidDecl())
18184     return;
18185 
18186   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
18187 
18188   // Target may not be determinable yet, for instance if this is a dependent
18189   // call in an uninstantiated template.
18190   if (Target) {
18191     const FunctionDecl *FNTarget = nullptr;
18192     (void)Target->hasBody(FNTarget);
18193     Target = const_cast<CXXConstructorDecl*>(
18194       cast_or_null<CXXConstructorDecl>(FNTarget));
18195   }
18196 
18197   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
18198                      // Avoid dereferencing a null pointer here.
18199                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
18200 
18201   if (!Current.insert(Canonical).second)
18202     return;
18203 
18204   // We know that beyond here, we aren't chaining into a cycle.
18205   if (!Target || !Target->isDelegatingConstructor() ||
18206       Target->isInvalidDecl() || Valid.count(TCanonical)) {
18207     Valid.insert(Current.begin(), Current.end());
18208     Current.clear();
18209   // We've hit a cycle.
18210   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
18211              Current.count(TCanonical)) {
18212     // If we haven't diagnosed this cycle yet, do so now.
18213     if (!Invalid.count(TCanonical)) {
18214       S.Diag((*Ctor->init_begin())->getSourceLocation(),
18215              diag::warn_delegating_ctor_cycle)
18216         << Ctor;
18217 
18218       // Don't add a note for a function delegating directly to itself.
18219       if (TCanonical != Canonical)
18220         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
18221 
18222       CXXConstructorDecl *C = Target;
18223       while (C->getCanonicalDecl() != Canonical) {
18224         const FunctionDecl *FNTarget = nullptr;
18225         (void)C->getTargetConstructor()->hasBody(FNTarget);
18226         assert(FNTarget && "Ctor cycle through bodiless function");
18227 
18228         C = const_cast<CXXConstructorDecl*>(
18229           cast<CXXConstructorDecl>(FNTarget));
18230         S.Diag(C->getLocation(), diag::note_which_delegates_to);
18231       }
18232     }
18233 
18234     Invalid.insert(Current.begin(), Current.end());
18235     Current.clear();
18236   } else {
18237     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
18238   }
18239 }
18240 
18241 
18242 void Sema::CheckDelegatingCtorCycles() {
18243   llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
18244 
18245   for (DelegatingCtorDeclsType::iterator
18246            I = DelegatingCtorDecls.begin(ExternalSource.get()),
18247            E = DelegatingCtorDecls.end();
18248        I != E; ++I)
18249     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
18250 
18251   for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
18252     (*CI)->setInvalidDecl();
18253 }
18254 
18255 namespace {
18256   /// AST visitor that finds references to the 'this' expression.
18257   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
18258     Sema &S;
18259 
18260   public:
18261     explicit FindCXXThisExpr(Sema &S) : S(S) { }
18262 
18263     bool VisitCXXThisExpr(CXXThisExpr *E) {
18264       S.Diag(E->getLocation(), diag::err_this_static_member_func)
18265         << E->isImplicit();
18266       return false;
18267     }
18268   };
18269 }
18270 
18271 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
18272   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
18273   if (!TSInfo)
18274     return false;
18275 
18276   TypeLoc TL = TSInfo->getTypeLoc();
18277   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
18278   if (!ProtoTL)
18279     return false;
18280 
18281   // C++11 [expr.prim.general]p3:
18282   //   [The expression this] shall not appear before the optional
18283   //   cv-qualifier-seq and it shall not appear within the declaration of a
18284   //   static member function (although its type and value category are defined
18285   //   within a static member function as they are within a non-static member
18286   //   function). [ Note: this is because declaration matching does not occur
18287   //  until the complete declarator is known. - end note ]
18288   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
18289   FindCXXThisExpr Finder(*this);
18290 
18291   // If the return type came after the cv-qualifier-seq, check it now.
18292   if (Proto->hasTrailingReturn() &&
18293       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
18294     return true;
18295 
18296   // Check the exception specification.
18297   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
18298     return true;
18299 
18300   // Check the trailing requires clause
18301   if (Expr *E = Method->getTrailingRequiresClause())
18302     if (!Finder.TraverseStmt(E))
18303       return true;
18304 
18305   return checkThisInStaticMemberFunctionAttributes(Method);
18306 }
18307 
18308 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
18309   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
18310   if (!TSInfo)
18311     return false;
18312 
18313   TypeLoc TL = TSInfo->getTypeLoc();
18314   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
18315   if (!ProtoTL)
18316     return false;
18317 
18318   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
18319   FindCXXThisExpr Finder(*this);
18320 
18321   switch (Proto->getExceptionSpecType()) {
18322   case EST_Unparsed:
18323   case EST_Uninstantiated:
18324   case EST_Unevaluated:
18325   case EST_BasicNoexcept:
18326   case EST_NoThrow:
18327   case EST_DynamicNone:
18328   case EST_MSAny:
18329   case EST_None:
18330     break;
18331 
18332   case EST_DependentNoexcept:
18333   case EST_NoexceptFalse:
18334   case EST_NoexceptTrue:
18335     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
18336       return true;
18337     [[fallthrough]];
18338 
18339   case EST_Dynamic:
18340     for (const auto &E : Proto->exceptions()) {
18341       if (!Finder.TraverseType(E))
18342         return true;
18343     }
18344     break;
18345   }
18346 
18347   return false;
18348 }
18349 
18350 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
18351   FindCXXThisExpr Finder(*this);
18352 
18353   // Check attributes.
18354   for (const auto *A : Method->attrs()) {
18355     // FIXME: This should be emitted by tblgen.
18356     Expr *Arg = nullptr;
18357     ArrayRef<Expr *> Args;
18358     if (const auto *G = dyn_cast<GuardedByAttr>(A))
18359       Arg = G->getArg();
18360     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
18361       Arg = G->getArg();
18362     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
18363       Args = llvm::ArrayRef(AA->args_begin(), AA->args_size());
18364     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
18365       Args = llvm::ArrayRef(AB->args_begin(), AB->args_size());
18366     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
18367       Arg = ETLF->getSuccessValue();
18368       Args = llvm::ArrayRef(ETLF->args_begin(), ETLF->args_size());
18369     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
18370       Arg = STLF->getSuccessValue();
18371       Args = llvm::ArrayRef(STLF->args_begin(), STLF->args_size());
18372     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
18373       Arg = LR->getArg();
18374     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
18375       Args = llvm::ArrayRef(LE->args_begin(), LE->args_size());
18376     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
18377       Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
18378     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
18379       Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
18380     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
18381       Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
18382     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
18383       Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
18384 
18385     if (Arg && !Finder.TraverseStmt(Arg))
18386       return true;
18387 
18388     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
18389       if (!Finder.TraverseStmt(Args[I]))
18390         return true;
18391     }
18392   }
18393 
18394   return false;
18395 }
18396 
18397 void Sema::checkExceptionSpecification(
18398     bool IsTopLevel, ExceptionSpecificationType EST,
18399     ArrayRef<ParsedType> DynamicExceptions,
18400     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
18401     SmallVectorImpl<QualType> &Exceptions,
18402     FunctionProtoType::ExceptionSpecInfo &ESI) {
18403   Exceptions.clear();
18404   ESI.Type = EST;
18405   if (EST == EST_Dynamic) {
18406     Exceptions.reserve(DynamicExceptions.size());
18407     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
18408       // FIXME: Preserve type source info.
18409       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
18410 
18411       if (IsTopLevel) {
18412         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
18413         collectUnexpandedParameterPacks(ET, Unexpanded);
18414         if (!Unexpanded.empty()) {
18415           DiagnoseUnexpandedParameterPacks(
18416               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
18417               Unexpanded);
18418           continue;
18419         }
18420       }
18421 
18422       // Check that the type is valid for an exception spec, and
18423       // drop it if not.
18424       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
18425         Exceptions.push_back(ET);
18426     }
18427     ESI.Exceptions = Exceptions;
18428     return;
18429   }
18430 
18431   if (isComputedNoexcept(EST)) {
18432     assert((NoexceptExpr->isTypeDependent() ||
18433             NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
18434             Context.BoolTy) &&
18435            "Parser should have made sure that the expression is boolean");
18436     if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
18437       ESI.Type = EST_BasicNoexcept;
18438       return;
18439     }
18440 
18441     ESI.NoexceptExpr = NoexceptExpr;
18442     return;
18443   }
18444 }
18445 
18446 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
18447              ExceptionSpecificationType EST,
18448              SourceRange SpecificationRange,
18449              ArrayRef<ParsedType> DynamicExceptions,
18450              ArrayRef<SourceRange> DynamicExceptionRanges,
18451              Expr *NoexceptExpr) {
18452   if (!MethodD)
18453     return;
18454 
18455   // Dig out the method we're referring to.
18456   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
18457     MethodD = FunTmpl->getTemplatedDecl();
18458 
18459   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
18460   if (!Method)
18461     return;
18462 
18463   // Check the exception specification.
18464   llvm::SmallVector<QualType, 4> Exceptions;
18465   FunctionProtoType::ExceptionSpecInfo ESI;
18466   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
18467                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
18468                               ESI);
18469 
18470   // Update the exception specification on the function type.
18471   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
18472 
18473   if (Method->isStatic())
18474     checkThisInStaticMemberFunctionExceptionSpec(Method);
18475 
18476   if (Method->isVirtual()) {
18477     // Check overrides, which we previously had to delay.
18478     for (const CXXMethodDecl *O : Method->overridden_methods())
18479       CheckOverridingFunctionExceptionSpec(Method, O);
18480   }
18481 }
18482 
18483 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
18484 ///
18485 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
18486                                        SourceLocation DeclStart, Declarator &D,
18487                                        Expr *BitWidth,
18488                                        InClassInitStyle InitStyle,
18489                                        AccessSpecifier AS,
18490                                        const ParsedAttr &MSPropertyAttr) {
18491   IdentifierInfo *II = D.getIdentifier();
18492   if (!II) {
18493     Diag(DeclStart, diag::err_anonymous_property);
18494     return nullptr;
18495   }
18496   SourceLocation Loc = D.getIdentifierLoc();
18497 
18498   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
18499   QualType T = TInfo->getType();
18500   if (getLangOpts().CPlusPlus) {
18501     CheckExtraCXXDefaultArguments(D);
18502 
18503     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
18504                                         UPPC_DataMemberType)) {
18505       D.setInvalidType();
18506       T = Context.IntTy;
18507       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
18508     }
18509   }
18510 
18511   DiagnoseFunctionSpecifiers(D.getDeclSpec());
18512 
18513   if (D.getDeclSpec().isInlineSpecified())
18514     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
18515         << getLangOpts().CPlusPlus17;
18516   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
18517     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
18518          diag::err_invalid_thread)
18519       << DeclSpec::getSpecifierName(TSCS);
18520 
18521   // Check to see if this name was declared as a member previously
18522   NamedDecl *PrevDecl = nullptr;
18523   LookupResult Previous(*this, II, Loc, LookupMemberName,
18524                         ForVisibleRedeclaration);
18525   LookupName(Previous, S);
18526   switch (Previous.getResultKind()) {
18527   case LookupResult::Found:
18528   case LookupResult::FoundUnresolvedValue:
18529     PrevDecl = Previous.getAsSingle<NamedDecl>();
18530     break;
18531 
18532   case LookupResult::FoundOverloaded:
18533     PrevDecl = Previous.getRepresentativeDecl();
18534     break;
18535 
18536   case LookupResult::NotFound:
18537   case LookupResult::NotFoundInCurrentInstantiation:
18538   case LookupResult::Ambiguous:
18539     break;
18540   }
18541 
18542   if (PrevDecl && PrevDecl->isTemplateParameter()) {
18543     // Maybe we will complain about the shadowed template parameter.
18544     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
18545     // Just pretend that we didn't see the previous declaration.
18546     PrevDecl = nullptr;
18547   }
18548 
18549   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
18550     PrevDecl = nullptr;
18551 
18552   SourceLocation TSSL = D.getBeginLoc();
18553   MSPropertyDecl *NewPD =
18554       MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
18555                              MSPropertyAttr.getPropertyDataGetter(),
18556                              MSPropertyAttr.getPropertyDataSetter());
18557   ProcessDeclAttributes(TUScope, NewPD, D);
18558   NewPD->setAccess(AS);
18559 
18560   if (NewPD->isInvalidDecl())
18561     Record->setInvalidDecl();
18562 
18563   if (D.getDeclSpec().isModulePrivateSpecified())
18564     NewPD->setModulePrivate();
18565 
18566   if (NewPD->isInvalidDecl() && PrevDecl) {
18567     // Don't introduce NewFD into scope; there's already something
18568     // with the same name in the same scope.
18569   } else if (II) {
18570     PushOnScopeChains(NewPD, S);
18571   } else
18572     Record->addDecl(NewPD);
18573 
18574   return NewPD;
18575 }
18576 
18577 void Sema::ActOnStartFunctionDeclarationDeclarator(
18578     Declarator &Declarator, unsigned TemplateParameterDepth) {
18579   auto &Info = InventedParameterInfos.emplace_back();
18580   TemplateParameterList *ExplicitParams = nullptr;
18581   ArrayRef<TemplateParameterList *> ExplicitLists =
18582       Declarator.getTemplateParameterLists();
18583   if (!ExplicitLists.empty()) {
18584     bool IsMemberSpecialization, IsInvalid;
18585     ExplicitParams = MatchTemplateParametersToScopeSpecifier(
18586         Declarator.getBeginLoc(), Declarator.getIdentifierLoc(),
18587         Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
18588         ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
18589         /*SuppressDiagnostic=*/true);
18590   }
18591   if (ExplicitParams) {
18592     Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
18593     llvm::append_range(Info.TemplateParams, *ExplicitParams);
18594     Info.NumExplicitTemplateParams = ExplicitParams->size();
18595   } else {
18596     Info.AutoTemplateParameterDepth = TemplateParameterDepth;
18597     Info.NumExplicitTemplateParams = 0;
18598   }
18599 }
18600 
18601 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
18602   auto &FSI = InventedParameterInfos.back();
18603   if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
18604     if (FSI.NumExplicitTemplateParams != 0) {
18605       TemplateParameterList *ExplicitParams =
18606           Declarator.getTemplateParameterLists().back();
18607       Declarator.setInventedTemplateParameterList(
18608           TemplateParameterList::Create(
18609               Context, ExplicitParams->getTemplateLoc(),
18610               ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
18611               ExplicitParams->getRAngleLoc(),
18612               ExplicitParams->getRequiresClause()));
18613     } else {
18614       Declarator.setInventedTemplateParameterList(
18615           TemplateParameterList::Create(
18616               Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
18617               SourceLocation(), /*RequiresClause=*/nullptr));
18618     }
18619   }
18620   InventedParameterInfos.pop_back();
18621 }
18622