xref: /freebsd/contrib/llvm-project/clang/lib/Sema/SemaDeclCXX.cpp (revision 3750ccefb8629a08890bfbae894dd6bc6a7483b4)
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/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/RecordLayout.h"
26 #include "clang/AST/RecursiveASTVisitor.h"
27 #include "clang/AST/StmtVisitor.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/AST/TypeOrdering.h"
30 #include "clang/Basic/AttributeCommonInfo.h"
31 #include "clang/Basic/PartialDiagnostic.h"
32 #include "clang/Basic/Specifiers.h"
33 #include "clang/Basic/TargetInfo.h"
34 #include "clang/Lex/LiteralSupport.h"
35 #include "clang/Lex/Preprocessor.h"
36 #include "clang/Sema/CXXFieldCollector.h"
37 #include "clang/Sema/DeclSpec.h"
38 #include "clang/Sema/EnterExpressionEvaluationContext.h"
39 #include "clang/Sema/Initialization.h"
40 #include "clang/Sema/Lookup.h"
41 #include "clang/Sema/Ownership.h"
42 #include "clang/Sema/ParsedTemplate.h"
43 #include "clang/Sema/Scope.h"
44 #include "clang/Sema/ScopeInfo.h"
45 #include "clang/Sema/SemaCUDA.h"
46 #include "clang/Sema/SemaInternal.h"
47 #include "clang/Sema/SemaObjC.h"
48 #include "clang/Sema/SemaOpenMP.h"
49 #include "clang/Sema/Template.h"
50 #include "llvm/ADT/ArrayRef.h"
51 #include "llvm/ADT/STLExtras.h"
52 #include "llvm/ADT/STLForwardCompat.h"
53 #include "llvm/ADT/ScopeExit.h"
54 #include "llvm/ADT/SmallString.h"
55 #include "llvm/ADT/StringExtras.h"
56 #include "llvm/Support/ConvertUTF.h"
57 #include "llvm/Support/SaveAndRestore.h"
58 #include <map>
59 #include <optional>
60 #include <set>
61 
62 using namespace clang;
63 
64 //===----------------------------------------------------------------------===//
65 // CheckDefaultArgumentVisitor
66 //===----------------------------------------------------------------------===//
67 
68 namespace {
69 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
70 /// the default argument of a parameter to determine whether it
71 /// contains any ill-formed subexpressions. For example, this will
72 /// diagnose the use of local variables or parameters within the
73 /// default argument expression.
74 class CheckDefaultArgumentVisitor
75     : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
76   Sema &S;
77   const Expr *DefaultArg;
78 
79 public:
80   CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
81       : S(S), DefaultArg(DefaultArg) {}
82 
83   bool VisitExpr(const Expr *Node);
84   bool VisitDeclRefExpr(const DeclRefExpr *DRE);
85   bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
86   bool VisitLambdaExpr(const LambdaExpr *Lambda);
87   bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
88 };
89 
90 /// VisitExpr - Visit all of the children of this expression.
91 bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
92   bool IsInvalid = false;
93   for (const Stmt *SubStmt : Node->children())
94     if (SubStmt)
95       IsInvalid |= Visit(SubStmt);
96   return IsInvalid;
97 }
98 
99 /// VisitDeclRefExpr - Visit a reference to a declaration, to
100 /// determine whether this declaration can be used in the default
101 /// argument expression.
102 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
103   const ValueDecl *Decl = dyn_cast<ValueDecl>(DRE->getDecl());
104 
105   if (!isa<VarDecl, BindingDecl>(Decl))
106     return false;
107 
108   if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {
109     // C++ [dcl.fct.default]p9:
110     //   [...] parameters of a function shall not be used in default
111     //   argument expressions, even if they are not evaluated. [...]
112     //
113     // C++17 [dcl.fct.default]p9 (by CWG 2082):
114     //   [...] A parameter shall not appear as a potentially-evaluated
115     //   expression in a default argument. [...]
116     //
117     if (DRE->isNonOdrUse() != NOUR_Unevaluated)
118       return S.Diag(DRE->getBeginLoc(),
119                     diag::err_param_default_argument_references_param)
120              << Param->getDeclName() << DefaultArg->getSourceRange();
121   } else if (auto *VD = Decl->getPotentiallyDecomposedVarDecl()) {
122     // C++ [dcl.fct.default]p7:
123     //   Local variables shall not be used in default argument
124     //   expressions.
125     //
126     // C++17 [dcl.fct.default]p7 (by CWG 2082):
127     //   A local variable shall not appear as a potentially-evaluated
128     //   expression in a default argument.
129     //
130     // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
131     //   Note: A local variable cannot be odr-used (6.3) in a default
132     //   argument.
133     //
134     if (VD->isLocalVarDecl() && !DRE->isNonOdrUse())
135       return S.Diag(DRE->getBeginLoc(),
136                     diag::err_param_default_argument_references_local)
137              << Decl << DefaultArg->getSourceRange();
138   }
139   return false;
140 }
141 
142 /// VisitCXXThisExpr - Visit a C++ "this" expression.
143 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
144   // C++ [dcl.fct.default]p8:
145   //   The keyword this shall not be used in a default argument of a
146   //   member function.
147   return S.Diag(ThisE->getBeginLoc(),
148                 diag::err_param_default_argument_references_this)
149          << ThisE->getSourceRange();
150 }
151 
152 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
153     const PseudoObjectExpr *POE) {
154   bool Invalid = false;
155   for (const Expr *E : POE->semantics()) {
156     // Look through bindings.
157     if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
158       E = OVE->getSourceExpr();
159       assert(E && "pseudo-object binding without source expression?");
160     }
161 
162     Invalid |= Visit(E);
163   }
164   return Invalid;
165 }
166 
167 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
168   // [expr.prim.lambda.capture]p9
169   // a lambda-expression appearing in a default argument cannot implicitly or
170   // explicitly capture any local entity. Such a lambda-expression can still
171   // have an init-capture if any full-expression in its initializer satisfies
172   // the constraints of an expression appearing in a default argument.
173   bool Invalid = false;
174   for (const LambdaCapture &LC : Lambda->captures()) {
175     if (!Lambda->isInitCapture(&LC))
176       return S.Diag(LC.getLocation(), diag::err_lambda_capture_default_arg);
177     // Init captures are always VarDecl.
178     auto *D = cast<VarDecl>(LC.getCapturedVar());
179     Invalid |= Visit(D->getInit());
180   }
181   return Invalid;
182 }
183 } // namespace
184 
185 void
186 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
187                                                  const CXXMethodDecl *Method) {
188   // If we have an MSAny spec already, don't bother.
189   if (!Method || ComputedEST == EST_MSAny)
190     return;
191 
192   const FunctionProtoType *Proto
193     = Method->getType()->getAs<FunctionProtoType>();
194   Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
195   if (!Proto)
196     return;
197 
198   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
199 
200   // If we have a throw-all spec at this point, ignore the function.
201   if (ComputedEST == EST_None)
202     return;
203 
204   if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
205     EST = EST_BasicNoexcept;
206 
207   switch (EST) {
208   case EST_Unparsed:
209   case EST_Uninstantiated:
210   case EST_Unevaluated:
211     llvm_unreachable("should not see unresolved exception specs here");
212 
213   // If this function can throw any exceptions, make a note of that.
214   case EST_MSAny:
215   case EST_None:
216     // FIXME: Whichever we see last of MSAny and None determines our result.
217     // We should make a consistent, order-independent choice here.
218     ClearExceptions();
219     ComputedEST = EST;
220     return;
221   case EST_NoexceptFalse:
222     ClearExceptions();
223     ComputedEST = EST_None;
224     return;
225   // FIXME: If the call to this decl is using any of its default arguments, we
226   // need to search them for potentially-throwing calls.
227   // If this function has a basic noexcept, it doesn't affect the outcome.
228   case EST_BasicNoexcept:
229   case EST_NoexceptTrue:
230   case EST_NoThrow:
231     return;
232   // If we're still at noexcept(true) and there's a throw() callee,
233   // change to that specification.
234   case EST_DynamicNone:
235     if (ComputedEST == EST_BasicNoexcept)
236       ComputedEST = EST_DynamicNone;
237     return;
238   case EST_DependentNoexcept:
239     llvm_unreachable(
240         "should not generate implicit declarations for dependent cases");
241   case EST_Dynamic:
242     break;
243   }
244   assert(EST == EST_Dynamic && "EST case not considered earlier.");
245   assert(ComputedEST != EST_None &&
246          "Shouldn't collect exceptions when throw-all is guaranteed.");
247   ComputedEST = EST_Dynamic;
248   // Record the exceptions in this function's exception specification.
249   for (const auto &E : Proto->exceptions())
250     if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
251       Exceptions.push_back(E);
252 }
253 
254 void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) {
255   if (!S || ComputedEST == EST_MSAny)
256     return;
257 
258   // FIXME:
259   //
260   // C++0x [except.spec]p14:
261   //   [An] implicit exception-specification specifies the type-id T if and
262   // only if T is allowed by the exception-specification of a function directly
263   // invoked by f's implicit definition; f shall allow all exceptions if any
264   // function it directly invokes allows all exceptions, and f shall allow no
265   // exceptions if every function it directly invokes allows no exceptions.
266   //
267   // Note in particular that if an implicit exception-specification is generated
268   // for a function containing a throw-expression, that specification can still
269   // be noexcept(true).
270   //
271   // Note also that 'directly invoked' is not defined in the standard, and there
272   // is no indication that we should only consider potentially-evaluated calls.
273   //
274   // Ultimately we should implement the intent of the standard: the exception
275   // specification should be the set of exceptions which can be thrown by the
276   // implicit definition. For now, we assume that any non-nothrow expression can
277   // throw any exception.
278 
279   if (Self->canThrow(S))
280     ComputedEST = EST_None;
281 }
282 
283 ExprResult Sema::ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
284                                              SourceLocation EqualLoc) {
285   if (RequireCompleteType(Param->getLocation(), Param->getType(),
286                           diag::err_typecheck_decl_incomplete_type))
287     return true;
288 
289   // C++ [dcl.fct.default]p5
290   //   A default argument expression is implicitly converted (clause
291   //   4) to the parameter type. The default argument expression has
292   //   the same semantic constraints as the initializer expression in
293   //   a declaration of a variable of the parameter type, using the
294   //   copy-initialization semantics (8.5).
295   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
296                                                                     Param);
297   InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
298                                                            EqualLoc);
299   InitializationSequence InitSeq(*this, Entity, Kind, Arg);
300   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
301   if (Result.isInvalid())
302     return true;
303   Arg = Result.getAs<Expr>();
304 
305   CheckCompletedExpr(Arg, EqualLoc);
306   Arg = MaybeCreateExprWithCleanups(Arg);
307 
308   return Arg;
309 }
310 
311 void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
312                                    SourceLocation EqualLoc) {
313   // Add the default argument to the parameter
314   Param->setDefaultArg(Arg);
315 
316   // We have already instantiated this parameter; provide each of the
317   // instantiations with the uninstantiated default argument.
318   UnparsedDefaultArgInstantiationsMap::iterator InstPos
319     = UnparsedDefaultArgInstantiations.find(Param);
320   if (InstPos != UnparsedDefaultArgInstantiations.end()) {
321     for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
322       InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
323 
324     // We're done tracking this parameter's instantiations.
325     UnparsedDefaultArgInstantiations.erase(InstPos);
326   }
327 }
328 
329 void
330 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
331                                 Expr *DefaultArg) {
332   if (!param || !DefaultArg)
333     return;
334 
335   ParmVarDecl *Param = cast<ParmVarDecl>(param);
336   UnparsedDefaultArgLocs.erase(Param);
337 
338   // Default arguments are only permitted in C++
339   if (!getLangOpts().CPlusPlus) {
340     Diag(EqualLoc, diag::err_param_default_argument)
341       << DefaultArg->getSourceRange();
342     return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
343   }
344 
345   // Check for unexpanded parameter packs.
346   if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument))
347     return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
348 
349   // C++11 [dcl.fct.default]p3
350   //   A default argument expression [...] shall not be specified for a
351   //   parameter pack.
352   if (Param->isParameterPack()) {
353     Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
354         << DefaultArg->getSourceRange();
355     // Recover by discarding the default argument.
356     Param->setDefaultArg(nullptr);
357     return;
358   }
359 
360   ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);
361   if (Result.isInvalid())
362     return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
363 
364   DefaultArg = Result.getAs<Expr>();
365 
366   // Check that the default argument is well-formed
367   CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
368   if (DefaultArgChecker.Visit(DefaultArg))
369     return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
370 
371   SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
372 }
373 
374 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
375                                              SourceLocation EqualLoc,
376                                              SourceLocation ArgLoc) {
377   if (!param)
378     return;
379 
380   ParmVarDecl *Param = cast<ParmVarDecl>(param);
381   Param->setUnparsedDefaultArg();
382   UnparsedDefaultArgLocs[Param] = ArgLoc;
383 }
384 
385 void Sema::ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc,
386                                           Expr *DefaultArg) {
387   if (!param)
388     return;
389 
390   ParmVarDecl *Param = cast<ParmVarDecl>(param);
391   Param->setInvalidDecl();
392   UnparsedDefaultArgLocs.erase(Param);
393   ExprResult RE;
394   if (DefaultArg) {
395     RE = CreateRecoveryExpr(EqualLoc, DefaultArg->getEndLoc(), {DefaultArg},
396                             Param->getType().getNonReferenceType());
397   } else {
398     RE = CreateRecoveryExpr(EqualLoc, EqualLoc, {},
399                             Param->getType().getNonReferenceType());
400   }
401   Param->setDefaultArg(RE.get());
402 }
403 
404 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
405   // C++ [dcl.fct.default]p3
406   //   A default argument expression shall be specified only in the
407   //   parameter-declaration-clause of a function declaration or in a
408   //   template-parameter (14.1). It shall not be specified for a
409   //   parameter pack. If it is specified in a
410   //   parameter-declaration-clause, it shall not occur within a
411   //   declarator or abstract-declarator of a parameter-declaration.
412   bool MightBeFunction = D.isFunctionDeclarationContext();
413   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
414     DeclaratorChunk &chunk = D.getTypeObject(i);
415     if (chunk.Kind == DeclaratorChunk::Function) {
416       if (MightBeFunction) {
417         // This is a function declaration. It can have default arguments, but
418         // keep looking in case its return type is a function type with default
419         // arguments.
420         MightBeFunction = false;
421         continue;
422       }
423       for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
424            ++argIdx) {
425         ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
426         if (Param->hasUnparsedDefaultArg()) {
427           std::unique_ptr<CachedTokens> Toks =
428               std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
429           SourceRange SR;
430           if (Toks->size() > 1)
431             SR = SourceRange((*Toks)[1].getLocation(),
432                              Toks->back().getLocation());
433           else
434             SR = UnparsedDefaultArgLocs[Param];
435           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
436             << SR;
437         } else if (Param->getDefaultArg()) {
438           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
439             << Param->getDefaultArg()->getSourceRange();
440           Param->setDefaultArg(nullptr);
441         }
442       }
443     } else if (chunk.Kind != DeclaratorChunk::Paren) {
444       MightBeFunction = false;
445     }
446   }
447 }
448 
449 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
450   return llvm::any_of(FD->parameters(), [](ParmVarDecl *P) {
451     return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
452   });
453 }
454 
455 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
456                                 Scope *S) {
457   bool Invalid = false;
458 
459   // The declaration context corresponding to the scope is the semantic
460   // parent, unless this is a local function declaration, in which case
461   // it is that surrounding function.
462   DeclContext *ScopeDC = New->isLocalExternDecl()
463                              ? New->getLexicalDeclContext()
464                              : New->getDeclContext();
465 
466   // Find the previous declaration for the purpose of default arguments.
467   FunctionDecl *PrevForDefaultArgs = Old;
468   for (/**/; PrevForDefaultArgs;
469        // Don't bother looking back past the latest decl if this is a local
470        // extern declaration; nothing else could work.
471        PrevForDefaultArgs = New->isLocalExternDecl()
472                                 ? nullptr
473                                 : PrevForDefaultArgs->getPreviousDecl()) {
474     // Ignore hidden declarations.
475     if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
476       continue;
477 
478     if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
479         !New->isCXXClassMember()) {
480       // Ignore default arguments of old decl if they are not in
481       // the same scope and this is not an out-of-line definition of
482       // a member function.
483       continue;
484     }
485 
486     if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
487       // If only one of these is a local function declaration, then they are
488       // declared in different scopes, even though isDeclInScope may think
489       // they're in the same scope. (If both are local, the scope check is
490       // sufficient, and if neither is local, then they are in the same scope.)
491       continue;
492     }
493 
494     // We found the right previous declaration.
495     break;
496   }
497 
498   // C++ [dcl.fct.default]p4:
499   //   For non-template functions, default arguments can be added in
500   //   later declarations of a function in the same
501   //   scope. Declarations in different scopes have completely
502   //   distinct sets of default arguments. That is, declarations in
503   //   inner scopes do not acquire default arguments from
504   //   declarations in outer scopes, and vice versa. In a given
505   //   function declaration, all parameters subsequent to a
506   //   parameter with a default argument shall have default
507   //   arguments supplied in this or previous declarations. A
508   //   default argument shall not be redefined by a later
509   //   declaration (not even to the same value).
510   //
511   // C++ [dcl.fct.default]p6:
512   //   Except for member functions of class templates, the default arguments
513   //   in a member function definition that appears outside of the class
514   //   definition are added to the set of default arguments provided by the
515   //   member function declaration in the class definition.
516   for (unsigned p = 0, NumParams = PrevForDefaultArgs
517                                        ? PrevForDefaultArgs->getNumParams()
518                                        : 0;
519        p < NumParams; ++p) {
520     ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
521     ParmVarDecl *NewParam = New->getParamDecl(p);
522 
523     bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
524     bool NewParamHasDfl = NewParam->hasDefaultArg();
525 
526     if (OldParamHasDfl && NewParamHasDfl) {
527       unsigned DiagDefaultParamID =
528         diag::err_param_default_argument_redefinition;
529 
530       // MSVC accepts that default parameters be redefined for member functions
531       // of template class. The new default parameter's value is ignored.
532       Invalid = true;
533       if (getLangOpts().MicrosoftExt) {
534         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
535         if (MD && MD->getParent()->getDescribedClassTemplate()) {
536           // Merge the old default argument into the new parameter.
537           NewParam->setHasInheritedDefaultArg();
538           if (OldParam->hasUninstantiatedDefaultArg())
539             NewParam->setUninstantiatedDefaultArg(
540                                       OldParam->getUninstantiatedDefaultArg());
541           else
542             NewParam->setDefaultArg(OldParam->getInit());
543           DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
544           Invalid = false;
545         }
546       }
547 
548       // FIXME: If we knew where the '=' was, we could easily provide a fix-it
549       // hint here. Alternatively, we could walk the type-source information
550       // for NewParam to find the last source location in the type... but it
551       // isn't worth the effort right now. This is the kind of test case that
552       // is hard to get right:
553       //   int f(int);
554       //   void g(int (*fp)(int) = f);
555       //   void g(int (*fp)(int) = &f);
556       Diag(NewParam->getLocation(), DiagDefaultParamID)
557         << NewParam->getDefaultArgRange();
558 
559       // Look for the function declaration where the default argument was
560       // actually written, which may be a declaration prior to Old.
561       for (auto Older = PrevForDefaultArgs;
562            OldParam->hasInheritedDefaultArg(); /**/) {
563         Older = Older->getPreviousDecl();
564         OldParam = Older->getParamDecl(p);
565       }
566 
567       Diag(OldParam->getLocation(), diag::note_previous_definition)
568         << OldParam->getDefaultArgRange();
569     } else if (OldParamHasDfl) {
570       // Merge the old default argument into the new parameter unless the new
571       // function is a friend declaration in a template class. In the latter
572       // case the default arguments will be inherited when the friend
573       // declaration will be instantiated.
574       if (New->getFriendObjectKind() == Decl::FOK_None ||
575           !New->getLexicalDeclContext()->isDependentContext()) {
576         // It's important to use getInit() here;  getDefaultArg()
577         // strips off any top-level ExprWithCleanups.
578         NewParam->setHasInheritedDefaultArg();
579         if (OldParam->hasUnparsedDefaultArg())
580           NewParam->setUnparsedDefaultArg();
581         else if (OldParam->hasUninstantiatedDefaultArg())
582           NewParam->setUninstantiatedDefaultArg(
583                                        OldParam->getUninstantiatedDefaultArg());
584         else
585           NewParam->setDefaultArg(OldParam->getInit());
586       }
587     } else if (NewParamHasDfl) {
588       if (New->getDescribedFunctionTemplate()) {
589         // Paragraph 4, quoted above, only applies to non-template functions.
590         Diag(NewParam->getLocation(),
591              diag::err_param_default_argument_template_redecl)
592           << NewParam->getDefaultArgRange();
593         Diag(PrevForDefaultArgs->getLocation(),
594              diag::note_template_prev_declaration)
595             << false;
596       } else if (New->getTemplateSpecializationKind()
597                    != TSK_ImplicitInstantiation &&
598                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
599         // C++ [temp.expr.spec]p21:
600         //   Default function arguments shall not be specified in a declaration
601         //   or a definition for one of the following explicit specializations:
602         //     - the explicit specialization of a function template;
603         //     - the explicit specialization of a member function template;
604         //     - the explicit specialization of a member function of a class
605         //       template where the class template specialization to which the
606         //       member function specialization belongs is implicitly
607         //       instantiated.
608         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
609           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
610           << New->getDeclName()
611           << NewParam->getDefaultArgRange();
612       } else if (New->getDeclContext()->isDependentContext()) {
613         // C++ [dcl.fct.default]p6 (DR217):
614         //   Default arguments for a member function of a class template shall
615         //   be specified on the initial declaration of the member function
616         //   within the class template.
617         //
618         // Reading the tea leaves a bit in DR217 and its reference to DR205
619         // leads me to the conclusion that one cannot add default function
620         // arguments for an out-of-line definition of a member function of a
621         // dependent type.
622         int WhichKind = 2;
623         if (CXXRecordDecl *Record
624               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
625           if (Record->getDescribedClassTemplate())
626             WhichKind = 0;
627           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
628             WhichKind = 1;
629           else
630             WhichKind = 2;
631         }
632 
633         Diag(NewParam->getLocation(),
634              diag::err_param_default_argument_member_template_redecl)
635           << WhichKind
636           << NewParam->getDefaultArgRange();
637       }
638     }
639   }
640 
641   // DR1344: If a default argument is added outside a class definition and that
642   // default argument makes the function a special member function, the program
643   // is ill-formed. This can only happen for constructors.
644   if (isa<CXXConstructorDecl>(New) &&
645       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
646     CXXSpecialMemberKind NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
647                          OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
648     if (NewSM != OldSM) {
649       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
650       assert(NewParam->hasDefaultArg());
651       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
652           << NewParam->getDefaultArgRange() << llvm::to_underlying(NewSM);
653       Diag(Old->getLocation(), diag::note_previous_declaration);
654     }
655   }
656 
657   const FunctionDecl *Def;
658   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
659   // template has a constexpr specifier then all its declarations shall
660   // contain the constexpr specifier.
661   if (New->getConstexprKind() != Old->getConstexprKind()) {
662     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
663         << New << static_cast<int>(New->getConstexprKind())
664         << static_cast<int>(Old->getConstexprKind());
665     Diag(Old->getLocation(), diag::note_previous_declaration);
666     Invalid = true;
667   } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
668              Old->isDefined(Def) &&
669              // If a friend function is inlined but does not have 'inline'
670              // specifier, it is a definition. Do not report attribute conflict
671              // in this case, redefinition will be diagnosed later.
672              (New->isInlineSpecified() ||
673               New->getFriendObjectKind() == Decl::FOK_None)) {
674     // C++11 [dcl.fcn.spec]p4:
675     //   If the definition of a function appears in a translation unit before its
676     //   first declaration as inline, the program is ill-formed.
677     Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
678     Diag(Def->getLocation(), diag::note_previous_definition);
679     Invalid = true;
680   }
681 
682   // C++17 [temp.deduct.guide]p3:
683   //   Two deduction guide declarations in the same translation unit
684   //   for the same class template shall not have equivalent
685   //   parameter-declaration-clauses.
686   if (isa<CXXDeductionGuideDecl>(New) &&
687       !New->isFunctionTemplateSpecialization() && isVisible(Old)) {
688     Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
689     Diag(Old->getLocation(), diag::note_previous_declaration);
690   }
691 
692   // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
693   // argument expression, that declaration shall be a definition and shall be
694   // the only declaration of the function or function template in the
695   // translation unit.
696   if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
697       functionDeclHasDefaultArgument(Old)) {
698     Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
699     Diag(Old->getLocation(), diag::note_previous_declaration);
700     Invalid = true;
701   }
702 
703   // C++11 [temp.friend]p4 (DR329):
704   //   When a function is defined in a friend function declaration in a class
705   //   template, the function is instantiated when the function is odr-used.
706   //   The same restrictions on multiple declarations and definitions that
707   //   apply to non-template function declarations and definitions also apply
708   //   to these implicit definitions.
709   const FunctionDecl *OldDefinition = nullptr;
710   if (New->isThisDeclarationInstantiatedFromAFriendDefinition() &&
711       Old->isDefined(OldDefinition, true))
712     CheckForFunctionRedefinition(New, OldDefinition);
713 
714   return Invalid;
715 }
716 
717 void Sema::DiagPlaceholderVariableDefinition(SourceLocation Loc) {
718   Diag(Loc, getLangOpts().CPlusPlus26
719                 ? diag::warn_cxx23_placeholder_var_definition
720                 : diag::ext_placeholder_var_definition);
721 }
722 
723 NamedDecl *
724 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
725                                    MultiTemplateParamsArg TemplateParamLists) {
726   assert(D.isDecompositionDeclarator());
727   const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
728 
729   // The syntax only allows a decomposition declarator as a simple-declaration,
730   // a for-range-declaration, or a condition in Clang, but we parse it in more
731   // cases than that.
732   if (!D.mayHaveDecompositionDeclarator()) {
733     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
734       << Decomp.getSourceRange();
735     return nullptr;
736   }
737 
738   if (!TemplateParamLists.empty()) {
739     // FIXME: There's no rule against this, but there are also no rules that
740     // would actually make it usable, so we reject it for now.
741     Diag(TemplateParamLists.front()->getTemplateLoc(),
742          diag::err_decomp_decl_template);
743     return nullptr;
744   }
745 
746   Diag(Decomp.getLSquareLoc(),
747        !getLangOpts().CPlusPlus17
748            ? diag::ext_decomp_decl
749            : D.getContext() == DeclaratorContext::Condition
750                  ? diag::ext_decomp_decl_cond
751                  : diag::warn_cxx14_compat_decomp_decl)
752       << Decomp.getSourceRange();
753 
754   // The semantic context is always just the current context.
755   DeclContext *const DC = CurContext;
756 
757   // C++17 [dcl.dcl]/8:
758   //   The decl-specifier-seq shall contain only the type-specifier auto
759   //   and cv-qualifiers.
760   // C++20 [dcl.dcl]/8:
761   //   If decl-specifier-seq contains any decl-specifier other than static,
762   //   thread_local, auto, or cv-qualifiers, the program is ill-formed.
763   // C++23 [dcl.pre]/6:
764   //   Each decl-specifier in the decl-specifier-seq shall be static,
765   //   thread_local, auto (9.2.9.6 [dcl.spec.auto]), or a cv-qualifier.
766   auto &DS = D.getDeclSpec();
767   {
768     // Note: While constrained-auto needs to be checked, we do so separately so
769     // we can emit a better diagnostic.
770     SmallVector<StringRef, 8> BadSpecifiers;
771     SmallVector<SourceLocation, 8> BadSpecifierLocs;
772     SmallVector<StringRef, 8> CPlusPlus20Specifiers;
773     SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
774     if (auto SCS = DS.getStorageClassSpec()) {
775       if (SCS == DeclSpec::SCS_static) {
776         CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
777         CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
778       } else {
779         BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
780         BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
781       }
782     }
783     if (auto TSCS = DS.getThreadStorageClassSpec()) {
784       CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
785       CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
786     }
787     if (DS.hasConstexprSpecifier()) {
788       BadSpecifiers.push_back(
789           DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
790       BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
791     }
792     if (DS.isInlineSpecified()) {
793       BadSpecifiers.push_back("inline");
794       BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
795     }
796 
797     if (!BadSpecifiers.empty()) {
798       auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
799       Err << (int)BadSpecifiers.size()
800           << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
801       // Don't add FixItHints to remove the specifiers; we do still respect
802       // them when building the underlying variable.
803       for (auto Loc : BadSpecifierLocs)
804         Err << SourceRange(Loc, Loc);
805     } else if (!CPlusPlus20Specifiers.empty()) {
806       auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
807                          getLangOpts().CPlusPlus20
808                              ? diag::warn_cxx17_compat_decomp_decl_spec
809                              : diag::ext_decomp_decl_spec);
810       Warn << (int)CPlusPlus20Specifiers.size()
811            << llvm::join(CPlusPlus20Specifiers.begin(),
812                          CPlusPlus20Specifiers.end(), " ");
813       for (auto Loc : CPlusPlus20SpecifierLocs)
814         Warn << SourceRange(Loc, Loc);
815     }
816     // We can't recover from it being declared as a typedef.
817     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
818       return nullptr;
819   }
820 
821   // C++2a [dcl.struct.bind]p1:
822   //   A cv that includes volatile is deprecated
823   if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
824       getLangOpts().CPlusPlus20)
825     Diag(DS.getVolatileSpecLoc(),
826          diag::warn_deprecated_volatile_structured_binding);
827 
828   TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
829   QualType R = TInfo->getType();
830 
831   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
832                                       UPPC_DeclarationType))
833     D.setInvalidType();
834 
835   // The syntax only allows a single ref-qualifier prior to the decomposition
836   // declarator. No other declarator chunks are permitted. Also check the type
837   // specifier here.
838   if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
839       D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
840       (D.getNumTypeObjects() == 1 &&
841        D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
842     Diag(Decomp.getLSquareLoc(),
843          (D.hasGroupingParens() ||
844           (D.getNumTypeObjects() &&
845            D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
846              ? diag::err_decomp_decl_parens
847              : diag::err_decomp_decl_type)
848         << R;
849 
850     // In most cases, there's no actual problem with an explicitly-specified
851     // type, but a function type won't work here, and ActOnVariableDeclarator
852     // shouldn't be called for such a type.
853     if (R->isFunctionType())
854       D.setInvalidType();
855   }
856 
857   // Constrained auto is prohibited by [decl.pre]p6, so check that here.
858   if (DS.isConstrainedAuto()) {
859     TemplateIdAnnotation *TemplRep = DS.getRepAsTemplateId();
860     assert(TemplRep->Kind == TNK_Concept_template &&
861            "No other template kind should be possible for a constrained auto");
862 
863     SourceRange TemplRange{TemplRep->TemplateNameLoc,
864                            TemplRep->RAngleLoc.isValid()
865                                ? TemplRep->RAngleLoc
866                                : TemplRep->TemplateNameLoc};
867     Diag(TemplRep->TemplateNameLoc, diag::err_decomp_decl_constraint)
868         << TemplRange << FixItHint::CreateRemoval(TemplRange);
869   }
870 
871   // Build the BindingDecls.
872   SmallVector<BindingDecl*, 8> Bindings;
873 
874   // Build the BindingDecls.
875   for (auto &B : D.getDecompositionDeclarator().bindings()) {
876     // Check for name conflicts.
877     DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
878     IdentifierInfo *VarName = B.Name;
879     assert(VarName && "Cannot have an unnamed binding declaration");
880 
881     LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
882                           RedeclarationKind::ForVisibleRedeclaration);
883     LookupName(Previous, S,
884                /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
885 
886     // It's not permitted to shadow a template parameter name.
887     if (Previous.isSingleResult() &&
888         Previous.getFoundDecl()->isTemplateParameter()) {
889       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
890                                       Previous.getFoundDecl());
891       Previous.clear();
892     }
893 
894     auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, VarName);
895 
896     ProcessDeclAttributeList(S, BD, *B.Attrs);
897 
898     // Find the shadowed declaration before filtering for scope.
899     NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
900                                   ? getShadowedDeclaration(BD, Previous)
901                                   : nullptr;
902 
903     bool ConsiderLinkage = DC->isFunctionOrMethod() &&
904                            DS.getStorageClassSpec() == DeclSpec::SCS_extern;
905     FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
906                          /*AllowInlineNamespace*/false);
907 
908     bool IsPlaceholder = DS.getStorageClassSpec() != DeclSpec::SCS_static &&
909                          DC->isFunctionOrMethod() && VarName->isPlaceholder();
910     if (!Previous.empty()) {
911       if (IsPlaceholder) {
912         bool sameDC = (Previous.end() - 1)
913                           ->getDeclContext()
914                           ->getRedeclContext()
915                           ->Equals(DC->getRedeclContext());
916         if (sameDC &&
917             isDeclInScope(*(Previous.end() - 1), CurContext, S, false)) {
918           Previous.clear();
919           DiagPlaceholderVariableDefinition(B.NameLoc);
920         }
921       } else {
922         auto *Old = Previous.getRepresentativeDecl();
923         Diag(B.NameLoc, diag::err_redefinition) << B.Name;
924         Diag(Old->getLocation(), diag::note_previous_definition);
925       }
926     } else if (ShadowedDecl && !D.isRedeclaration()) {
927       CheckShadow(BD, ShadowedDecl, Previous);
928     }
929     PushOnScopeChains(BD, S, true);
930     Bindings.push_back(BD);
931     ParsingInitForAutoVars.insert(BD);
932   }
933 
934   // There are no prior lookup results for the variable itself, because it
935   // is unnamed.
936   DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
937                                Decomp.getLSquareLoc());
938   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
939                         RedeclarationKind::ForVisibleRedeclaration);
940 
941   // Build the variable that holds the non-decomposed object.
942   bool AddToScope = true;
943   NamedDecl *New =
944       ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
945                               MultiTemplateParamsArg(), AddToScope, Bindings);
946   if (AddToScope) {
947     S->AddDecl(New);
948     CurContext->addHiddenDecl(New);
949   }
950 
951   if (OpenMP().isInOpenMPDeclareTargetContext())
952     OpenMP().checkDeclIsAllowedInOpenMPTarget(nullptr, New);
953 
954   return New;
955 }
956 
957 static bool checkSimpleDecomposition(
958     Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
959     QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
960     llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
961   if ((int64_t)Bindings.size() != NumElems) {
962     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
963         << DecompType << (unsigned)Bindings.size()
964         << (unsigned)NumElems.getLimitedValue(UINT_MAX)
965         << toString(NumElems, 10) << (NumElems < Bindings.size());
966     return true;
967   }
968 
969   unsigned I = 0;
970   for (auto *B : Bindings) {
971     SourceLocation Loc = B->getLocation();
972     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
973     if (E.isInvalid())
974       return true;
975     E = GetInit(Loc, E.get(), I++);
976     if (E.isInvalid())
977       return true;
978     B->setBinding(ElemType, E.get());
979   }
980 
981   return false;
982 }
983 
984 static bool checkArrayLikeDecomposition(Sema &S,
985                                         ArrayRef<BindingDecl *> Bindings,
986                                         ValueDecl *Src, QualType DecompType,
987                                         const llvm::APSInt &NumElems,
988                                         QualType ElemType) {
989   return checkSimpleDecomposition(
990       S, Bindings, Src, DecompType, NumElems, ElemType,
991       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
992         ExprResult E = S.ActOnIntegerConstant(Loc, I);
993         if (E.isInvalid())
994           return ExprError();
995         return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
996       });
997 }
998 
999 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1000                                     ValueDecl *Src, QualType DecompType,
1001                                     const ConstantArrayType *CAT) {
1002   return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
1003                                      llvm::APSInt(CAT->getSize()),
1004                                      CAT->getElementType());
1005 }
1006 
1007 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1008                                      ValueDecl *Src, QualType DecompType,
1009                                      const VectorType *VT) {
1010   return checkArrayLikeDecomposition(
1011       S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
1012       S.Context.getQualifiedType(VT->getElementType(),
1013                                  DecompType.getQualifiers()));
1014 }
1015 
1016 static bool checkComplexDecomposition(Sema &S,
1017                                       ArrayRef<BindingDecl *> Bindings,
1018                                       ValueDecl *Src, QualType DecompType,
1019                                       const ComplexType *CT) {
1020   return checkSimpleDecomposition(
1021       S, Bindings, Src, DecompType, llvm::APSInt::get(2),
1022       S.Context.getQualifiedType(CT->getElementType(),
1023                                  DecompType.getQualifiers()),
1024       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1025         return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
1026       });
1027 }
1028 
1029 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
1030                                      TemplateArgumentListInfo &Args,
1031                                      const TemplateParameterList *Params) {
1032   SmallString<128> SS;
1033   llvm::raw_svector_ostream OS(SS);
1034   bool First = true;
1035   unsigned I = 0;
1036   for (auto &Arg : Args.arguments()) {
1037     if (!First)
1038       OS << ", ";
1039     Arg.getArgument().print(PrintingPolicy, OS,
1040                             TemplateParameterList::shouldIncludeTypeForArgument(
1041                                 PrintingPolicy, Params, I));
1042     First = false;
1043     I++;
1044   }
1045   return std::string(OS.str());
1046 }
1047 
1048 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
1049                                      SourceLocation Loc, StringRef Trait,
1050                                      TemplateArgumentListInfo &Args,
1051                                      unsigned DiagID) {
1052   auto DiagnoseMissing = [&] {
1053     if (DiagID)
1054       S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
1055                                                Args, /*Params*/ nullptr);
1056     return true;
1057   };
1058 
1059   // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1060   NamespaceDecl *Std = S.getStdNamespace();
1061   if (!Std)
1062     return DiagnoseMissing();
1063 
1064   // Look up the trait itself, within namespace std. We can diagnose various
1065   // problems with this lookup even if we've been asked to not diagnose a
1066   // missing specialization, because this can only fail if the user has been
1067   // declaring their own names in namespace std or we don't support the
1068   // standard library implementation in use.
1069   LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
1070                       Loc, Sema::LookupOrdinaryName);
1071   if (!S.LookupQualifiedName(Result, Std))
1072     return DiagnoseMissing();
1073   if (Result.isAmbiguous())
1074     return true;
1075 
1076   ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1077   if (!TraitTD) {
1078     Result.suppressDiagnostics();
1079     NamedDecl *Found = *Result.begin();
1080     S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1081     S.Diag(Found->getLocation(), diag::note_declared_at);
1082     return true;
1083   }
1084 
1085   // Build the template-id.
1086   QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
1087   if (TraitTy.isNull())
1088     return true;
1089   if (!S.isCompleteType(Loc, TraitTy)) {
1090     if (DiagID)
1091       S.RequireCompleteType(
1092           Loc, TraitTy, DiagID,
1093           printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1094                             TraitTD->getTemplateParameters()));
1095     return true;
1096   }
1097 
1098   CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1099   assert(RD && "specialization of class template is not a class?");
1100 
1101   // Look up the member of the trait type.
1102   S.LookupQualifiedName(TraitMemberLookup, RD);
1103   return TraitMemberLookup.isAmbiguous();
1104 }
1105 
1106 static TemplateArgumentLoc
1107 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
1108                                    uint64_t I) {
1109   TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
1110   return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1111 }
1112 
1113 static TemplateArgumentLoc
1114 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
1115   return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
1116 }
1117 
1118 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1119 
1120 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1121                                llvm::APSInt &Size) {
1122   EnterExpressionEvaluationContext ContextRAII(
1123       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1124 
1125   DeclarationName Value = S.PP.getIdentifierInfo("value");
1126   LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1127 
1128   // Form template argument list for tuple_size<T>.
1129   TemplateArgumentListInfo Args(Loc, Loc);
1130   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1131 
1132   // If there's no tuple_size specialization or the lookup of 'value' is empty,
1133   // it's not tuple-like.
1134   if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1135       R.empty())
1136     return IsTupleLike::NotTupleLike;
1137 
1138   // If we get this far, we've committed to the tuple interpretation, but
1139   // we can still fail if there actually isn't a usable ::value.
1140 
1141   struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1142     LookupResult &R;
1143     TemplateArgumentListInfo &Args;
1144     ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1145         : R(R), Args(Args) {}
1146     Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1147                                                SourceLocation Loc) override {
1148       return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1149              << printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1150                                   /*Params*/ nullptr);
1151     }
1152   } Diagnoser(R, Args);
1153 
1154   ExprResult E =
1155       S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1156   if (E.isInvalid())
1157     return IsTupleLike::Error;
1158 
1159   E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
1160   if (E.isInvalid())
1161     return IsTupleLike::Error;
1162 
1163   return IsTupleLike::TupleLike;
1164 }
1165 
1166 /// \return std::tuple_element<I, T>::type.
1167 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1168                                         unsigned I, QualType T) {
1169   // Form template argument list for tuple_element<I, T>.
1170   TemplateArgumentListInfo Args(Loc, Loc);
1171   Args.addArgument(
1172       getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1173   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1174 
1175   DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1176   LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1177   if (lookupStdTypeTraitMember(
1178           S, R, Loc, "tuple_element", Args,
1179           diag::err_decomp_decl_std_tuple_element_not_specialized))
1180     return QualType();
1181 
1182   auto *TD = R.getAsSingle<TypeDecl>();
1183   if (!TD) {
1184     R.suppressDiagnostics();
1185     S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1186         << printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1187                              /*Params*/ nullptr);
1188     if (!R.empty())
1189       S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1190     return QualType();
1191   }
1192 
1193   return S.Context.getTypeDeclType(TD);
1194 }
1195 
1196 namespace {
1197 struct InitializingBinding {
1198   Sema &S;
1199   InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1200     Sema::CodeSynthesisContext Ctx;
1201     Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding;
1202     Ctx.PointOfInstantiation = BD->getLocation();
1203     Ctx.Entity = BD;
1204     S.pushCodeSynthesisContext(Ctx);
1205   }
1206   ~InitializingBinding() {
1207     S.popCodeSynthesisContext();
1208   }
1209 };
1210 }
1211 
1212 static bool checkTupleLikeDecomposition(Sema &S,
1213                                         ArrayRef<BindingDecl *> Bindings,
1214                                         VarDecl *Src, QualType DecompType,
1215                                         const llvm::APSInt &TupleSize) {
1216   if ((int64_t)Bindings.size() != TupleSize) {
1217     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1218         << DecompType << (unsigned)Bindings.size()
1219         << (unsigned)TupleSize.getLimitedValue(UINT_MAX)
1220         << toString(TupleSize, 10) << (TupleSize < Bindings.size());
1221     return true;
1222   }
1223 
1224   if (Bindings.empty())
1225     return false;
1226 
1227   DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1228 
1229   // [dcl.decomp]p3:
1230   //   The unqualified-id get is looked up in the scope of E by class member
1231   //   access lookup ...
1232   LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1233   bool UseMemberGet = false;
1234   if (S.isCompleteType(Src->getLocation(), DecompType)) {
1235     if (auto *RD = DecompType->getAsCXXRecordDecl())
1236       S.LookupQualifiedName(MemberGet, RD);
1237     if (MemberGet.isAmbiguous())
1238       return true;
1239     //   ... and if that finds at least one declaration that is a function
1240     //   template whose first template parameter is a non-type parameter ...
1241     for (NamedDecl *D : MemberGet) {
1242       if (FunctionTemplateDecl *FTD =
1243               dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1244         TemplateParameterList *TPL = FTD->getTemplateParameters();
1245         if (TPL->size() != 0 &&
1246             isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1247           //   ... the initializer is e.get<i>().
1248           UseMemberGet = true;
1249           break;
1250         }
1251       }
1252     }
1253   }
1254 
1255   unsigned I = 0;
1256   for (auto *B : Bindings) {
1257     InitializingBinding InitContext(S, B);
1258     SourceLocation Loc = B->getLocation();
1259 
1260     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1261     if (E.isInvalid())
1262       return true;
1263 
1264     //   e is an lvalue if the type of the entity is an lvalue reference and
1265     //   an xvalue otherwise
1266     if (!Src->getType()->isLValueReferenceType())
1267       E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1268                                    E.get(), nullptr, VK_XValue,
1269                                    FPOptionsOverride());
1270 
1271     TemplateArgumentListInfo Args(Loc, Loc);
1272     Args.addArgument(
1273         getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1274 
1275     if (UseMemberGet) {
1276       //   if [lookup of member get] finds at least one declaration, the
1277       //   initializer is e.get<i-1>().
1278       E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1279                                      CXXScopeSpec(), SourceLocation(), nullptr,
1280                                      MemberGet, &Args, nullptr);
1281       if (E.isInvalid())
1282         return true;
1283 
1284       E = S.BuildCallExpr(nullptr, E.get(), Loc, std::nullopt, Loc);
1285     } else {
1286       //   Otherwise, the initializer is get<i-1>(e), where get is looked up
1287       //   in the associated namespaces.
1288       Expr *Get = UnresolvedLookupExpr::Create(
1289           S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1290           DeclarationNameInfo(GetDN, Loc), /*RequiresADL=*/true, &Args,
1291           UnresolvedSetIterator(), UnresolvedSetIterator(),
1292           /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
1293 
1294       Expr *Arg = E.get();
1295       E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1296     }
1297     if (E.isInvalid())
1298       return true;
1299     Expr *Init = E.get();
1300 
1301     //   Given the type T designated by std::tuple_element<i - 1, E>::type,
1302     QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1303     if (T.isNull())
1304       return true;
1305 
1306     //   each vi is a variable of type "reference to T" initialized with the
1307     //   initializer, where the reference is an lvalue reference if the
1308     //   initializer is an lvalue and an rvalue reference otherwise
1309     QualType RefType =
1310         S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1311     if (RefType.isNull())
1312       return true;
1313     auto *RefVD = VarDecl::Create(
1314         S.Context, Src->getDeclContext(), Loc, Loc,
1315         B->getDeclName().getAsIdentifierInfo(), RefType,
1316         S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1317     RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1318     RefVD->setTSCSpec(Src->getTSCSpec());
1319     RefVD->setImplicit();
1320     if (Src->isInlineSpecified())
1321       RefVD->setInlineSpecified();
1322     RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1323 
1324     InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1325     InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1326     InitializationSequence Seq(S, Entity, Kind, Init);
1327     E = Seq.Perform(S, Entity, Kind, Init);
1328     if (E.isInvalid())
1329       return true;
1330     E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1331     if (E.isInvalid())
1332       return true;
1333     RefVD->setInit(E.get());
1334     S.CheckCompleteVariableDeclaration(RefVD);
1335 
1336     E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1337                                    DeclarationNameInfo(B->getDeclName(), Loc),
1338                                    RefVD);
1339     if (E.isInvalid())
1340       return true;
1341 
1342     B->setBinding(T, E.get());
1343     I++;
1344   }
1345 
1346   return false;
1347 }
1348 
1349 /// Find the base class to decompose in a built-in decomposition of a class type.
1350 /// This base class search is, unfortunately, not quite like any other that we
1351 /// perform anywhere else in C++.
1352 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1353                                                 const CXXRecordDecl *RD,
1354                                                 CXXCastPath &BasePath) {
1355   auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1356                           CXXBasePath &Path) {
1357     return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1358   };
1359 
1360   const CXXRecordDecl *ClassWithFields = nullptr;
1361   AccessSpecifier AS = AS_public;
1362   if (RD->hasDirectFields())
1363     // [dcl.decomp]p4:
1364     //   Otherwise, all of E's non-static data members shall be public direct
1365     //   members of E ...
1366     ClassWithFields = RD;
1367   else {
1368     //   ... or of ...
1369     CXXBasePaths Paths;
1370     Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1371     if (!RD->lookupInBases(BaseHasFields, Paths)) {
1372       // If no classes have fields, just decompose RD itself. (This will work
1373       // if and only if zero bindings were provided.)
1374       return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1375     }
1376 
1377     CXXBasePath *BestPath = nullptr;
1378     for (auto &P : Paths) {
1379       if (!BestPath)
1380         BestPath = &P;
1381       else if (!S.Context.hasSameType(P.back().Base->getType(),
1382                                       BestPath->back().Base->getType())) {
1383         //   ... the same ...
1384         S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1385           << false << RD << BestPath->back().Base->getType()
1386           << P.back().Base->getType();
1387         return DeclAccessPair();
1388       } else if (P.Access < BestPath->Access) {
1389         BestPath = &P;
1390       }
1391     }
1392 
1393     //   ... unambiguous ...
1394     QualType BaseType = BestPath->back().Base->getType();
1395     if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1396       S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1397         << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1398       return DeclAccessPair();
1399     }
1400 
1401     //   ... [accessible, implied by other rules] base class of E.
1402     S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1403                            *BestPath, diag::err_decomp_decl_inaccessible_base);
1404     AS = BestPath->Access;
1405 
1406     ClassWithFields = BaseType->getAsCXXRecordDecl();
1407     S.BuildBasePathArray(Paths, BasePath);
1408   }
1409 
1410   // The above search did not check whether the selected class itself has base
1411   // classes with fields, so check that now.
1412   CXXBasePaths Paths;
1413   if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1414     S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1415       << (ClassWithFields == RD) << RD << ClassWithFields
1416       << Paths.front().back().Base->getType();
1417     return DeclAccessPair();
1418   }
1419 
1420   return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1421 }
1422 
1423 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1424                                      ValueDecl *Src, QualType DecompType,
1425                                      const CXXRecordDecl *OrigRD) {
1426   if (S.RequireCompleteType(Src->getLocation(), DecompType,
1427                             diag::err_incomplete_type))
1428     return true;
1429 
1430   CXXCastPath BasePath;
1431   DeclAccessPair BasePair =
1432       findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1433   const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1434   if (!RD)
1435     return true;
1436   QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1437                                                  DecompType.getQualifiers());
1438 
1439   auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1440     unsigned NumFields = llvm::count_if(
1441         RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitField(); });
1442     assert(Bindings.size() != NumFields);
1443     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1444         << DecompType << (unsigned)Bindings.size() << NumFields << NumFields
1445         << (NumFields < Bindings.size());
1446     return true;
1447   };
1448 
1449   //   all of E's non-static data members shall be [...] well-formed
1450   //   when named as e.name in the context of the structured binding,
1451   //   E shall not have an anonymous union member, ...
1452   unsigned I = 0;
1453   for (auto *FD : RD->fields()) {
1454     if (FD->isUnnamedBitField())
1455       continue;
1456 
1457     // All the non-static data members are required to be nameable, so they
1458     // must all have names.
1459     if (!FD->getDeclName()) {
1460       if (RD->isLambda()) {
1461         S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda);
1462         S.Diag(RD->getLocation(), diag::note_lambda_decl);
1463         return true;
1464       }
1465 
1466       if (FD->isAnonymousStructOrUnion()) {
1467         S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1468           << DecompType << FD->getType()->isUnionType();
1469         S.Diag(FD->getLocation(), diag::note_declared_at);
1470         return true;
1471       }
1472 
1473       // FIXME: Are there any other ways we could have an anonymous member?
1474     }
1475 
1476     // We have a real field to bind.
1477     if (I >= Bindings.size())
1478       return DiagnoseBadNumberOfBindings();
1479     auto *B = Bindings[I++];
1480     SourceLocation Loc = B->getLocation();
1481 
1482     // The field must be accessible in the context of the structured binding.
1483     // We already checked that the base class is accessible.
1484     // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1485     // const_cast here.
1486     S.CheckStructuredBindingMemberAccess(
1487         Loc, const_cast<CXXRecordDecl *>(OrigRD),
1488         DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1489                                      BasePair.getAccess(), FD->getAccess())));
1490 
1491     // Initialize the binding to Src.FD.
1492     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1493     if (E.isInvalid())
1494       return true;
1495     E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1496                             VK_LValue, &BasePath);
1497     if (E.isInvalid())
1498       return true;
1499     E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1500                                   CXXScopeSpec(), FD,
1501                                   DeclAccessPair::make(FD, FD->getAccess()),
1502                                   DeclarationNameInfo(FD->getDeclName(), Loc));
1503     if (E.isInvalid())
1504       return true;
1505 
1506     // If the type of the member is T, the referenced type is cv T, where cv is
1507     // the cv-qualification of the decomposition expression.
1508     //
1509     // FIXME: We resolve a defect here: if the field is mutable, we do not add
1510     // 'const' to the type of the field.
1511     Qualifiers Q = DecompType.getQualifiers();
1512     if (FD->isMutable())
1513       Q.removeConst();
1514     B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1515   }
1516 
1517   if (I != Bindings.size())
1518     return DiagnoseBadNumberOfBindings();
1519 
1520   return false;
1521 }
1522 
1523 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1524   QualType DecompType = DD->getType();
1525 
1526   // If the type of the decomposition is dependent, then so is the type of
1527   // each binding.
1528   if (DecompType->isDependentType()) {
1529     for (auto *B : DD->bindings())
1530       B->setType(Context.DependentTy);
1531     return;
1532   }
1533 
1534   DecompType = DecompType.getNonReferenceType();
1535   ArrayRef<BindingDecl*> Bindings = DD->bindings();
1536 
1537   // C++1z [dcl.decomp]/2:
1538   //   If E is an array type [...]
1539   // As an extension, we also support decomposition of built-in complex and
1540   // vector types.
1541   if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1542     if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1543       DD->setInvalidDecl();
1544     return;
1545   }
1546   if (auto *VT = DecompType->getAs<VectorType>()) {
1547     if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1548       DD->setInvalidDecl();
1549     return;
1550   }
1551   if (auto *CT = DecompType->getAs<ComplexType>()) {
1552     if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1553       DD->setInvalidDecl();
1554     return;
1555   }
1556 
1557   // C++1z [dcl.decomp]/3:
1558   //   if the expression std::tuple_size<E>::value is a well-formed integral
1559   //   constant expression, [...]
1560   llvm::APSInt TupleSize(32);
1561   switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1562   case IsTupleLike::Error:
1563     DD->setInvalidDecl();
1564     return;
1565 
1566   case IsTupleLike::TupleLike:
1567     if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1568       DD->setInvalidDecl();
1569     return;
1570 
1571   case IsTupleLike::NotTupleLike:
1572     break;
1573   }
1574 
1575   // C++1z [dcl.dcl]/8:
1576   //   [E shall be of array or non-union class type]
1577   CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1578   if (!RD || RD->isUnion()) {
1579     Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1580         << DD << !RD << DecompType;
1581     DD->setInvalidDecl();
1582     return;
1583   }
1584 
1585   // C++1z [dcl.decomp]/4:
1586   //   all of E's non-static data members shall be [...] direct members of
1587   //   E or of the same unambiguous public base class of E, ...
1588   if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1589     DD->setInvalidDecl();
1590 }
1591 
1592 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1593   // Shortcut if exceptions are disabled.
1594   if (!getLangOpts().CXXExceptions)
1595     return;
1596 
1597   assert(Context.hasSameType(New->getType(), Old->getType()) &&
1598          "Should only be called if types are otherwise the same.");
1599 
1600   QualType NewType = New->getType();
1601   QualType OldType = Old->getType();
1602 
1603   // We're only interested in pointers and references to functions, as well
1604   // as pointers to member functions.
1605   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1606     NewType = R->getPointeeType();
1607     OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1608   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1609     NewType = P->getPointeeType();
1610     OldType = OldType->castAs<PointerType>()->getPointeeType();
1611   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1612     NewType = M->getPointeeType();
1613     OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1614   }
1615 
1616   if (!NewType->isFunctionProtoType())
1617     return;
1618 
1619   // There's lots of special cases for functions. For function pointers, system
1620   // libraries are hopefully not as broken so that we don't need these
1621   // workarounds.
1622   if (CheckEquivalentExceptionSpec(
1623         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1624         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1625     New->setInvalidDecl();
1626   }
1627 }
1628 
1629 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1630 /// function declaration are well-formed according to C++
1631 /// [dcl.fct.default].
1632 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1633   // This checking doesn't make sense for explicit specializations; their
1634   // default arguments are determined by the declaration we're specializing,
1635   // not by FD.
1636   if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1637     return;
1638   if (auto *FTD = FD->getDescribedFunctionTemplate())
1639     if (FTD->isMemberSpecialization())
1640       return;
1641 
1642   unsigned NumParams = FD->getNumParams();
1643   unsigned ParamIdx = 0;
1644 
1645   // Find first parameter with a default argument
1646   for (; ParamIdx < NumParams; ++ParamIdx) {
1647     ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1648     if (Param->hasDefaultArg())
1649       break;
1650   }
1651 
1652   // C++20 [dcl.fct.default]p4:
1653   //   In a given function declaration, each parameter subsequent to a parameter
1654   //   with a default argument shall have a default argument supplied in this or
1655   //   a previous declaration, unless the parameter was expanded from a
1656   //   parameter pack, or shall be a function parameter pack.
1657   for (++ParamIdx; ParamIdx < NumParams; ++ParamIdx) {
1658     ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1659     if (Param->hasDefaultArg() || Param->isParameterPack() ||
1660         (CurrentInstantiationScope &&
1661          CurrentInstantiationScope->isLocalPackExpansion(Param)))
1662       continue;
1663     if (Param->isInvalidDecl())
1664       /* We already complained about this parameter. */;
1665     else if (Param->getIdentifier())
1666       Diag(Param->getLocation(), diag::err_param_default_argument_missing_name)
1667           << Param->getIdentifier();
1668     else
1669       Diag(Param->getLocation(), diag::err_param_default_argument_missing);
1670   }
1671 }
1672 
1673 /// Check that the given type is a literal type. Issue a diagnostic if not,
1674 /// if Kind is Diagnose.
1675 /// \return \c true if a problem has been found (and optionally diagnosed).
1676 template <typename... Ts>
1677 static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
1678                              SourceLocation Loc, QualType T, unsigned DiagID,
1679                              Ts &&...DiagArgs) {
1680   if (T->isDependentType())
1681     return false;
1682 
1683   switch (Kind) {
1684   case Sema::CheckConstexprKind::Diagnose:
1685     return SemaRef.RequireLiteralType(Loc, T, DiagID,
1686                                       std::forward<Ts>(DiagArgs)...);
1687 
1688   case Sema::CheckConstexprKind::CheckValid:
1689     return !T->isLiteralType(SemaRef.Context);
1690   }
1691 
1692   llvm_unreachable("unknown CheckConstexprKind");
1693 }
1694 
1695 /// Determine whether a destructor cannot be constexpr due to
1696 static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
1697                                                const CXXDestructorDecl *DD,
1698                                                Sema::CheckConstexprKind Kind) {
1699   assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1700          "this check is obsolete for C++23");
1701   auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1702     const CXXRecordDecl *RD =
1703         T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1704     if (!RD || RD->hasConstexprDestructor())
1705       return true;
1706 
1707     if (Kind == Sema::CheckConstexprKind::Diagnose) {
1708       SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1709           << static_cast<int>(DD->getConstexprKind()) << !FD
1710           << (FD ? FD->getDeclName() : DeclarationName()) << T;
1711       SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1712           << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1713     }
1714     return false;
1715   };
1716 
1717   const CXXRecordDecl *RD = DD->getParent();
1718   for (const CXXBaseSpecifier &B : RD->bases())
1719     if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1720       return false;
1721   for (const FieldDecl *FD : RD->fields())
1722     if (!Check(FD->getLocation(), FD->getType(), FD))
1723       return false;
1724   return true;
1725 }
1726 
1727 /// Check whether a function's parameter types are all literal types. If so,
1728 /// return true. If not, produce a suitable diagnostic and return false.
1729 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1730                                          const FunctionDecl *FD,
1731                                          Sema::CheckConstexprKind Kind) {
1732   assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1733          "this check is obsolete for C++23");
1734   unsigned ArgIndex = 0;
1735   const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1736   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1737                                               e = FT->param_type_end();
1738        i != e; ++i, ++ArgIndex) {
1739     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1740     assert(PD && "null in a parameter list");
1741     SourceLocation ParamLoc = PD->getLocation();
1742     if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1743                          diag::err_constexpr_non_literal_param, ArgIndex + 1,
1744                          PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1745                          FD->isConsteval()))
1746       return false;
1747   }
1748   return true;
1749 }
1750 
1751 /// Check whether a function's return type is a literal type. If so, return
1752 /// true. If not, produce a suitable diagnostic and return false.
1753 static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1754                                      Sema::CheckConstexprKind Kind) {
1755   assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1756          "this check is obsolete for C++23");
1757   if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1758                        diag::err_constexpr_non_literal_return,
1759                        FD->isConsteval()))
1760     return false;
1761   return true;
1762 }
1763 
1764 /// Get diagnostic %select index for tag kind for
1765 /// record diagnostic message.
1766 /// WARNING: Indexes apply to particular diagnostics only!
1767 ///
1768 /// \returns diagnostic %select index.
1769 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1770   switch (Tag) {
1771   case TagTypeKind::Struct:
1772     return 0;
1773   case TagTypeKind::Interface:
1774     return 1;
1775   case TagTypeKind::Class:
1776     return 2;
1777   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1778   }
1779 }
1780 
1781 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1782                                        Stmt *Body,
1783                                        Sema::CheckConstexprKind Kind);
1784 static bool CheckConstexprMissingReturn(Sema &SemaRef, const FunctionDecl *Dcl);
1785 
1786 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
1787                                             CheckConstexprKind Kind) {
1788   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1789   if (MD && MD->isInstance()) {
1790     // C++11 [dcl.constexpr]p4:
1791     //  The definition of a constexpr constructor shall satisfy the following
1792     //  constraints:
1793     //  - the class shall not have any virtual base classes;
1794     //
1795     // FIXME: This only applies to constructors and destructors, not arbitrary
1796     // member functions.
1797     const CXXRecordDecl *RD = MD->getParent();
1798     if (RD->getNumVBases()) {
1799       if (Kind == CheckConstexprKind::CheckValid)
1800         return false;
1801 
1802       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1803         << isa<CXXConstructorDecl>(NewFD)
1804         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1805       for (const auto &I : RD->vbases())
1806         Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1807             << I.getSourceRange();
1808       return false;
1809     }
1810   }
1811 
1812   if (!isa<CXXConstructorDecl>(NewFD)) {
1813     // C++11 [dcl.constexpr]p3:
1814     //  The definition of a constexpr function shall satisfy the following
1815     //  constraints:
1816     // - it shall not be virtual; (removed in C++20)
1817     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1818     if (Method && Method->isVirtual()) {
1819       if (getLangOpts().CPlusPlus20) {
1820         if (Kind == CheckConstexprKind::Diagnose)
1821           Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1822       } else {
1823         if (Kind == CheckConstexprKind::CheckValid)
1824           return false;
1825 
1826         Method = Method->getCanonicalDecl();
1827         Diag(Method->getLocation(), diag::err_constexpr_virtual);
1828 
1829         // If it's not obvious why this function is virtual, find an overridden
1830         // function which uses the 'virtual' keyword.
1831         const CXXMethodDecl *WrittenVirtual = Method;
1832         while (!WrittenVirtual->isVirtualAsWritten())
1833           WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1834         if (WrittenVirtual != Method)
1835           Diag(WrittenVirtual->getLocation(),
1836                diag::note_overridden_virtual_function);
1837         return false;
1838       }
1839     }
1840 
1841     // - its return type shall be a literal type; (removed in C++23)
1842     if (!getLangOpts().CPlusPlus23 &&
1843         !CheckConstexprReturnType(*this, NewFD, Kind))
1844       return false;
1845   }
1846 
1847   if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1848     // A destructor can be constexpr only if the defaulted destructor could be;
1849     // we don't need to check the members and bases if we already know they all
1850     // have constexpr destructors. (removed in C++23)
1851     if (!getLangOpts().CPlusPlus23 &&
1852         !Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1853       if (Kind == CheckConstexprKind::CheckValid)
1854         return false;
1855       if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1856         return false;
1857     }
1858   }
1859 
1860   // - each of its parameter types shall be a literal type; (removed in C++23)
1861   if (!getLangOpts().CPlusPlus23 &&
1862       !CheckConstexprParameterTypes(*this, NewFD, Kind))
1863     return false;
1864 
1865   Stmt *Body = NewFD->getBody();
1866   assert(Body &&
1867          "CheckConstexprFunctionDefinition called on function with no body");
1868   return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1869 }
1870 
1871 /// Check the given declaration statement is legal within a constexpr function
1872 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1873 ///
1874 /// \return true if the body is OK (maybe only as an extension), false if we
1875 ///         have diagnosed a problem.
1876 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1877                                    DeclStmt *DS, SourceLocation &Cxx1yLoc,
1878                                    Sema::CheckConstexprKind Kind) {
1879   // C++11 [dcl.constexpr]p3 and p4:
1880   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
1881   //  contain only
1882   for (const auto *DclIt : DS->decls()) {
1883     switch (DclIt->getKind()) {
1884     case Decl::StaticAssert:
1885     case Decl::Using:
1886     case Decl::UsingShadow:
1887     case Decl::UsingDirective:
1888     case Decl::UnresolvedUsingTypename:
1889     case Decl::UnresolvedUsingValue:
1890     case Decl::UsingEnum:
1891       //   - static_assert-declarations
1892       //   - using-declarations,
1893       //   - using-directives,
1894       //   - using-enum-declaration
1895       continue;
1896 
1897     case Decl::Typedef:
1898     case Decl::TypeAlias: {
1899       //   - typedef declarations and alias-declarations that do not define
1900       //     classes or enumerations,
1901       const auto *TN = cast<TypedefNameDecl>(DclIt);
1902       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1903         // Don't allow variably-modified types in constexpr functions.
1904         if (Kind == Sema::CheckConstexprKind::Diagnose) {
1905           TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1906           SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1907             << TL.getSourceRange() << TL.getType()
1908             << isa<CXXConstructorDecl>(Dcl);
1909         }
1910         return false;
1911       }
1912       continue;
1913     }
1914 
1915     case Decl::Enum:
1916     case Decl::CXXRecord:
1917       // C++1y allows types to be defined, not just declared.
1918       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1919         if (Kind == Sema::CheckConstexprKind::Diagnose) {
1920           SemaRef.Diag(DS->getBeginLoc(),
1921                        SemaRef.getLangOpts().CPlusPlus14
1922                            ? diag::warn_cxx11_compat_constexpr_type_definition
1923                            : diag::ext_constexpr_type_definition)
1924               << isa<CXXConstructorDecl>(Dcl);
1925         } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1926           return false;
1927         }
1928       }
1929       continue;
1930 
1931     case Decl::EnumConstant:
1932     case Decl::IndirectField:
1933     case Decl::ParmVar:
1934       // These can only appear with other declarations which are banned in
1935       // C++11 and permitted in C++1y, so ignore them.
1936       continue;
1937 
1938     case Decl::Var:
1939     case Decl::Decomposition: {
1940       // C++1y [dcl.constexpr]p3 allows anything except:
1941       //   a definition of a variable of non-literal type or of static or
1942       //   thread storage duration or [before C++2a] for which no
1943       //   initialization is performed.
1944       const auto *VD = cast<VarDecl>(DclIt);
1945       if (VD->isThisDeclarationADefinition()) {
1946         if (VD->isStaticLocal()) {
1947           if (Kind == Sema::CheckConstexprKind::Diagnose) {
1948             SemaRef.Diag(VD->getLocation(),
1949                          SemaRef.getLangOpts().CPlusPlus23
1950                              ? diag::warn_cxx20_compat_constexpr_var
1951                              : diag::ext_constexpr_static_var)
1952                 << isa<CXXConstructorDecl>(Dcl)
1953                 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1954           } else if (!SemaRef.getLangOpts().CPlusPlus23) {
1955             return false;
1956           }
1957         }
1958         if (SemaRef.LangOpts.CPlusPlus23) {
1959           CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1960                            diag::warn_cxx20_compat_constexpr_var,
1961                            isa<CXXConstructorDecl>(Dcl),
1962                            /*variable of non-literal type*/ 2);
1963         } else if (CheckLiteralType(
1964                        SemaRef, Kind, VD->getLocation(), VD->getType(),
1965                        diag::err_constexpr_local_var_non_literal_type,
1966                        isa<CXXConstructorDecl>(Dcl))) {
1967           return false;
1968         }
1969         if (!VD->getType()->isDependentType() &&
1970             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1971           if (Kind == Sema::CheckConstexprKind::Diagnose) {
1972             SemaRef.Diag(
1973                 VD->getLocation(),
1974                 SemaRef.getLangOpts().CPlusPlus20
1975                     ? diag::warn_cxx17_compat_constexpr_local_var_no_init
1976                     : diag::ext_constexpr_local_var_no_init)
1977                 << isa<CXXConstructorDecl>(Dcl);
1978           } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1979             return false;
1980           }
1981           continue;
1982         }
1983       }
1984       if (Kind == Sema::CheckConstexprKind::Diagnose) {
1985         SemaRef.Diag(VD->getLocation(),
1986                      SemaRef.getLangOpts().CPlusPlus14
1987                       ? diag::warn_cxx11_compat_constexpr_local_var
1988                       : diag::ext_constexpr_local_var)
1989           << isa<CXXConstructorDecl>(Dcl);
1990       } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1991         return false;
1992       }
1993       continue;
1994     }
1995 
1996     case Decl::NamespaceAlias:
1997     case Decl::Function:
1998       // These are disallowed in C++11 and permitted in C++1y. Allow them
1999       // everywhere as an extension.
2000       if (!Cxx1yLoc.isValid())
2001         Cxx1yLoc = DS->getBeginLoc();
2002       continue;
2003 
2004     default:
2005       if (Kind == Sema::CheckConstexprKind::Diagnose) {
2006         SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2007             << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2008       }
2009       return false;
2010     }
2011   }
2012 
2013   return true;
2014 }
2015 
2016 /// Check that the given field is initialized within a constexpr constructor.
2017 ///
2018 /// \param Dcl The constexpr constructor being checked.
2019 /// \param Field The field being checked. This may be a member of an anonymous
2020 ///        struct or union nested within the class being checked.
2021 /// \param Inits All declarations, including anonymous struct/union members and
2022 ///        indirect members, for which any initialization was provided.
2023 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach
2024 ///        multiple notes for different members to the same error.
2025 /// \param Kind Whether we're diagnosing a constructor as written or determining
2026 ///        whether the formal requirements are satisfied.
2027 /// \return \c false if we're checking for validity and the constructor does
2028 ///         not satisfy the requirements on a constexpr constructor.
2029 static bool CheckConstexprCtorInitializer(Sema &SemaRef,
2030                                           const FunctionDecl *Dcl,
2031                                           FieldDecl *Field,
2032                                           llvm::SmallSet<Decl*, 16> &Inits,
2033                                           bool &Diagnosed,
2034                                           Sema::CheckConstexprKind Kind) {
2035   // In C++20 onwards, there's nothing to check for validity.
2036   if (Kind == Sema::CheckConstexprKind::CheckValid &&
2037       SemaRef.getLangOpts().CPlusPlus20)
2038     return true;
2039 
2040   if (Field->isInvalidDecl())
2041     return true;
2042 
2043   if (Field->isUnnamedBitField())
2044     return true;
2045 
2046   // Anonymous unions with no variant members and empty anonymous structs do not
2047   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
2048   // indirect fields don't need initializing.
2049   if (Field->isAnonymousStructOrUnion() &&
2050       (Field->getType()->isUnionType()
2051            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
2052            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
2053     return true;
2054 
2055   if (!Inits.count(Field)) {
2056     if (Kind == Sema::CheckConstexprKind::Diagnose) {
2057       if (!Diagnosed) {
2058         SemaRef.Diag(Dcl->getLocation(),
2059                      SemaRef.getLangOpts().CPlusPlus20
2060                          ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
2061                          : diag::ext_constexpr_ctor_missing_init);
2062         Diagnosed = true;
2063       }
2064       SemaRef.Diag(Field->getLocation(),
2065                    diag::note_constexpr_ctor_missing_init);
2066     } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2067       return false;
2068     }
2069   } else if (Field->isAnonymousStructOrUnion()) {
2070     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
2071     for (auto *I : RD->fields())
2072       // If an anonymous union contains an anonymous struct of which any member
2073       // is initialized, all members must be initialized.
2074       if (!RD->isUnion() || Inits.count(I))
2075         if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2076                                            Kind))
2077           return false;
2078   }
2079   return true;
2080 }
2081 
2082 /// Check the provided statement is allowed in a constexpr function
2083 /// definition.
2084 static bool
2085 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
2086                            SmallVectorImpl<SourceLocation> &ReturnStmts,
2087                            SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2088                            SourceLocation &Cxx2bLoc,
2089                            Sema::CheckConstexprKind Kind) {
2090   // - its function-body shall be [...] a compound-statement that contains only
2091   switch (S->getStmtClass()) {
2092   case Stmt::NullStmtClass:
2093     //   - null statements,
2094     return true;
2095 
2096   case Stmt::DeclStmtClass:
2097     //   - static_assert-declarations
2098     //   - using-declarations,
2099     //   - using-directives,
2100     //   - typedef declarations and alias-declarations that do not define
2101     //     classes or enumerations,
2102     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
2103       return false;
2104     return true;
2105 
2106   case Stmt::ReturnStmtClass:
2107     //   - and exactly one return statement;
2108     if (isa<CXXConstructorDecl>(Dcl)) {
2109       // C++1y allows return statements in constexpr constructors.
2110       if (!Cxx1yLoc.isValid())
2111         Cxx1yLoc = S->getBeginLoc();
2112       return true;
2113     }
2114 
2115     ReturnStmts.push_back(S->getBeginLoc());
2116     return true;
2117 
2118   case Stmt::AttributedStmtClass:
2119     // Attributes on a statement don't affect its formal kind and hence don't
2120     // affect its validity in a constexpr function.
2121     return CheckConstexprFunctionStmt(
2122         SemaRef, Dcl, cast<AttributedStmt>(S)->getSubStmt(), ReturnStmts,
2123         Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);
2124 
2125   case Stmt::CompoundStmtClass: {
2126     // C++1y allows compound-statements.
2127     if (!Cxx1yLoc.isValid())
2128       Cxx1yLoc = S->getBeginLoc();
2129 
2130     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2131     for (auto *BodyIt : CompStmt->body()) {
2132       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2133                                       Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2134         return false;
2135     }
2136     return true;
2137   }
2138 
2139   case Stmt::IfStmtClass: {
2140     // C++1y allows if-statements.
2141     if (!Cxx1yLoc.isValid())
2142       Cxx1yLoc = S->getBeginLoc();
2143 
2144     IfStmt *If = cast<IfStmt>(S);
2145     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2146                                     Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2147       return false;
2148     if (If->getElse() &&
2149         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2150                                     Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2151       return false;
2152     return true;
2153   }
2154 
2155   case Stmt::WhileStmtClass:
2156   case Stmt::DoStmtClass:
2157   case Stmt::ForStmtClass:
2158   case Stmt::CXXForRangeStmtClass:
2159   case Stmt::ContinueStmtClass:
2160     // C++1y allows all of these. We don't allow them as extensions in C++11,
2161     // because they don't make sense without variable mutation.
2162     if (!SemaRef.getLangOpts().CPlusPlus14)
2163       break;
2164     if (!Cxx1yLoc.isValid())
2165       Cxx1yLoc = S->getBeginLoc();
2166     for (Stmt *SubStmt : S->children()) {
2167       if (SubStmt &&
2168           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2169                                       Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2170         return false;
2171     }
2172     return true;
2173 
2174   case Stmt::SwitchStmtClass:
2175   case Stmt::CaseStmtClass:
2176   case Stmt::DefaultStmtClass:
2177   case Stmt::BreakStmtClass:
2178     // C++1y allows switch-statements, and since they don't need variable
2179     // mutation, we can reasonably allow them in C++11 as an extension.
2180     if (!Cxx1yLoc.isValid())
2181       Cxx1yLoc = S->getBeginLoc();
2182     for (Stmt *SubStmt : S->children()) {
2183       if (SubStmt &&
2184           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2185                                       Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2186         return false;
2187     }
2188     return true;
2189 
2190   case Stmt::LabelStmtClass:
2191   case Stmt::GotoStmtClass:
2192     if (Cxx2bLoc.isInvalid())
2193       Cxx2bLoc = S->getBeginLoc();
2194     for (Stmt *SubStmt : S->children()) {
2195       if (SubStmt &&
2196           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2197                                       Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2198         return false;
2199     }
2200     return true;
2201 
2202   case Stmt::GCCAsmStmtClass:
2203   case Stmt::MSAsmStmtClass:
2204     // C++2a allows inline assembly statements.
2205   case Stmt::CXXTryStmtClass:
2206     if (Cxx2aLoc.isInvalid())
2207       Cxx2aLoc = S->getBeginLoc();
2208     for (Stmt *SubStmt : S->children()) {
2209       if (SubStmt &&
2210           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2211                                       Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2212         return false;
2213     }
2214     return true;
2215 
2216   case Stmt::CXXCatchStmtClass:
2217     // Do not bother checking the language mode (already covered by the
2218     // try block check).
2219     if (!CheckConstexprFunctionStmt(
2220             SemaRef, Dcl, cast<CXXCatchStmt>(S)->getHandlerBlock(), ReturnStmts,
2221             Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2222       return false;
2223     return true;
2224 
2225   default:
2226     if (!isa<Expr>(S))
2227       break;
2228 
2229     // C++1y allows expression-statements.
2230     if (!Cxx1yLoc.isValid())
2231       Cxx1yLoc = S->getBeginLoc();
2232     return true;
2233   }
2234 
2235   if (Kind == Sema::CheckConstexprKind::Diagnose) {
2236     SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2237         << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2238   }
2239   return false;
2240 }
2241 
2242 /// Check the body for the given constexpr function declaration only contains
2243 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2244 ///
2245 /// \return true if the body is OK, false if we have found or diagnosed a
2246 /// problem.
2247 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2248                                        Stmt *Body,
2249                                        Sema::CheckConstexprKind Kind) {
2250   SmallVector<SourceLocation, 4> ReturnStmts;
2251 
2252   if (isa<CXXTryStmt>(Body)) {
2253     // C++11 [dcl.constexpr]p3:
2254     //  The definition of a constexpr function shall satisfy the following
2255     //  constraints: [...]
2256     // - its function-body shall be = delete, = default, or a
2257     //   compound-statement
2258     //
2259     // C++11 [dcl.constexpr]p4:
2260     //  In the definition of a constexpr constructor, [...]
2261     // - its function-body shall not be a function-try-block;
2262     //
2263     // This restriction is lifted in C++2a, as long as inner statements also
2264     // apply the general constexpr rules.
2265     switch (Kind) {
2266     case Sema::CheckConstexprKind::CheckValid:
2267       if (!SemaRef.getLangOpts().CPlusPlus20)
2268         return false;
2269       break;
2270 
2271     case Sema::CheckConstexprKind::Diagnose:
2272       SemaRef.Diag(Body->getBeginLoc(),
2273            !SemaRef.getLangOpts().CPlusPlus20
2274                ? diag::ext_constexpr_function_try_block_cxx20
2275                : diag::warn_cxx17_compat_constexpr_function_try_block)
2276           << isa<CXXConstructorDecl>(Dcl);
2277       break;
2278     }
2279   }
2280 
2281   // - its function-body shall be [...] a compound-statement that contains only
2282   //   [... list of cases ...]
2283   //
2284   // Note that walking the children here is enough to properly check for
2285   // CompoundStmt and CXXTryStmt body.
2286   SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc;
2287   for (Stmt *SubStmt : Body->children()) {
2288     if (SubStmt &&
2289         !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2290                                     Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2291       return false;
2292   }
2293 
2294   if (Kind == Sema::CheckConstexprKind::CheckValid) {
2295     // If this is only valid as an extension, report that we don't satisfy the
2296     // constraints of the current language.
2297     if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus23) ||
2298         (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2299         (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2300       return false;
2301   } else if (Cxx2bLoc.isValid()) {
2302     SemaRef.Diag(Cxx2bLoc,
2303                  SemaRef.getLangOpts().CPlusPlus23
2304                      ? diag::warn_cxx20_compat_constexpr_body_invalid_stmt
2305                      : diag::ext_constexpr_body_invalid_stmt_cxx23)
2306         << isa<CXXConstructorDecl>(Dcl);
2307   } else if (Cxx2aLoc.isValid()) {
2308     SemaRef.Diag(Cxx2aLoc,
2309          SemaRef.getLangOpts().CPlusPlus20
2310            ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2311            : diag::ext_constexpr_body_invalid_stmt_cxx20)
2312       << isa<CXXConstructorDecl>(Dcl);
2313   } else if (Cxx1yLoc.isValid()) {
2314     SemaRef.Diag(Cxx1yLoc,
2315          SemaRef.getLangOpts().CPlusPlus14
2316            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2317            : diag::ext_constexpr_body_invalid_stmt)
2318       << isa<CXXConstructorDecl>(Dcl);
2319   }
2320 
2321   if (const CXXConstructorDecl *Constructor
2322         = dyn_cast<CXXConstructorDecl>(Dcl)) {
2323     const CXXRecordDecl *RD = Constructor->getParent();
2324     // DR1359:
2325     // - every non-variant non-static data member and base class sub-object
2326     //   shall be initialized;
2327     // DR1460:
2328     // - if the class is a union having variant members, exactly one of them
2329     //   shall be initialized;
2330     if (RD->isUnion()) {
2331       if (Constructor->getNumCtorInitializers() == 0 &&
2332           RD->hasVariantMembers()) {
2333         if (Kind == Sema::CheckConstexprKind::Diagnose) {
2334           SemaRef.Diag(
2335               Dcl->getLocation(),
2336               SemaRef.getLangOpts().CPlusPlus20
2337                   ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2338                   : diag::ext_constexpr_union_ctor_no_init);
2339         } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2340           return false;
2341         }
2342       }
2343     } else if (!Constructor->isDependentContext() &&
2344                !Constructor->isDelegatingConstructor()) {
2345       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2346 
2347       // Skip detailed checking if we have enough initializers, and we would
2348       // allow at most one initializer per member.
2349       bool AnyAnonStructUnionMembers = false;
2350       unsigned Fields = 0;
2351       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2352            E = RD->field_end(); I != E; ++I, ++Fields) {
2353         if (I->isAnonymousStructOrUnion()) {
2354           AnyAnonStructUnionMembers = true;
2355           break;
2356         }
2357       }
2358       // DR1460:
2359       // - if the class is a union-like class, but is not a union, for each of
2360       //   its anonymous union members having variant members, exactly one of
2361       //   them shall be initialized;
2362       if (AnyAnonStructUnionMembers ||
2363           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2364         // Check initialization of non-static data members. Base classes are
2365         // always initialized so do not need to be checked. Dependent bases
2366         // might not have initializers in the member initializer list.
2367         llvm::SmallSet<Decl*, 16> Inits;
2368         for (const auto *I: Constructor->inits()) {
2369           if (FieldDecl *FD = I->getMember())
2370             Inits.insert(FD);
2371           else if (IndirectFieldDecl *ID = I->getIndirectMember())
2372             Inits.insert(ID->chain_begin(), ID->chain_end());
2373         }
2374 
2375         bool Diagnosed = false;
2376         for (auto *I : RD->fields())
2377           if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2378                                              Kind))
2379             return false;
2380       }
2381     }
2382   } else {
2383     if (ReturnStmts.empty()) {
2384       switch (Kind) {
2385       case Sema::CheckConstexprKind::Diagnose:
2386         if (!CheckConstexprMissingReturn(SemaRef, Dcl))
2387           return false;
2388         break;
2389 
2390       case Sema::CheckConstexprKind::CheckValid:
2391         // The formal requirements don't include this rule in C++14, even
2392         // though the "must be able to produce a constant expression" rules
2393         // still imply it in some cases.
2394         if (!SemaRef.getLangOpts().CPlusPlus14)
2395           return false;
2396         break;
2397       }
2398     } else if (ReturnStmts.size() > 1) {
2399       switch (Kind) {
2400       case Sema::CheckConstexprKind::Diagnose:
2401         SemaRef.Diag(
2402             ReturnStmts.back(),
2403             SemaRef.getLangOpts().CPlusPlus14
2404                 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2405                 : diag::ext_constexpr_body_multiple_return);
2406         for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2407           SemaRef.Diag(ReturnStmts[I],
2408                        diag::note_constexpr_body_previous_return);
2409         break;
2410 
2411       case Sema::CheckConstexprKind::CheckValid:
2412         if (!SemaRef.getLangOpts().CPlusPlus14)
2413           return false;
2414         break;
2415       }
2416     }
2417   }
2418 
2419   // C++11 [dcl.constexpr]p5:
2420   //   if no function argument values exist such that the function invocation
2421   //   substitution would produce a constant expression, the program is
2422   //   ill-formed; no diagnostic required.
2423   // C++11 [dcl.constexpr]p3:
2424   //   - every constructor call and implicit conversion used in initializing the
2425   //     return value shall be one of those allowed in a constant expression.
2426   // C++11 [dcl.constexpr]p4:
2427   //   - every constructor involved in initializing non-static data members and
2428   //     base class sub-objects shall be a constexpr constructor.
2429   //
2430   // Note that this rule is distinct from the "requirements for a constexpr
2431   // function", so is not checked in CheckValid mode. Because the check for
2432   // constexpr potential is expensive, skip the check if the diagnostic is
2433   // disabled, the function is declared in a system header, or we're in C++23
2434   // or later mode (see https://wg21.link/P2448).
2435   bool SkipCheck =
2436       !SemaRef.getLangOpts().CheckConstexprFunctionBodies ||
2437       SemaRef.getSourceManager().isInSystemHeader(Dcl->getLocation()) ||
2438       SemaRef.getDiagnostics().isIgnored(
2439           diag::ext_constexpr_function_never_constant_expr, Dcl->getLocation());
2440   SmallVector<PartialDiagnosticAt, 8> Diags;
2441   if (Kind == Sema::CheckConstexprKind::Diagnose && !SkipCheck &&
2442       !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2443     SemaRef.Diag(Dcl->getLocation(),
2444                  diag::ext_constexpr_function_never_constant_expr)
2445         << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval()
2446         << Dcl->getNameInfo().getSourceRange();
2447     for (size_t I = 0, N = Diags.size(); I != N; ++I)
2448       SemaRef.Diag(Diags[I].first, Diags[I].second);
2449     // Don't return false here: we allow this for compatibility in
2450     // system headers.
2451   }
2452 
2453   return true;
2454 }
2455 
2456 static bool CheckConstexprMissingReturn(Sema &SemaRef,
2457                                         const FunctionDecl *Dcl) {
2458   bool IsVoidOrDependentType = Dcl->getReturnType()->isVoidType() ||
2459                                Dcl->getReturnType()->isDependentType();
2460   // Skip emitting a missing return error diagnostic for non-void functions
2461   // since C++23 no longer mandates constexpr functions to yield constant
2462   // expressions.
2463   if (SemaRef.getLangOpts().CPlusPlus23 && !IsVoidOrDependentType)
2464     return true;
2465 
2466   // C++14 doesn't require constexpr functions to contain a 'return'
2467   // statement. We still do, unless the return type might be void, because
2468   // otherwise if there's no return statement, the function cannot
2469   // be used in a core constant expression.
2470   bool OK = SemaRef.getLangOpts().CPlusPlus14 && IsVoidOrDependentType;
2471   SemaRef.Diag(Dcl->getLocation(),
2472                OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2473                   : diag::err_constexpr_body_no_return)
2474       << Dcl->isConsteval();
2475   return OK;
2476 }
2477 
2478 bool Sema::CheckImmediateEscalatingFunctionDefinition(
2479     FunctionDecl *FD, const sema::FunctionScopeInfo *FSI) {
2480   if (!getLangOpts().CPlusPlus20 || !FD->isImmediateEscalating())
2481     return true;
2482   FD->setBodyContainsImmediateEscalatingExpressions(
2483       FSI->FoundImmediateEscalatingExpression);
2484   if (FSI->FoundImmediateEscalatingExpression) {
2485     auto it = UndefinedButUsed.find(FD->getCanonicalDecl());
2486     if (it != UndefinedButUsed.end()) {
2487       Diag(it->second, diag::err_immediate_function_used_before_definition)
2488           << it->first;
2489       Diag(FD->getLocation(), diag::note_defined_here) << FD;
2490       if (FD->isImmediateFunction() && !FD->isConsteval())
2491         DiagnoseImmediateEscalatingReason(FD);
2492       return false;
2493     }
2494   }
2495   return true;
2496 }
2497 
2498 void Sema::DiagnoseImmediateEscalatingReason(FunctionDecl *FD) {
2499   assert(FD->isImmediateEscalating() && !FD->isConsteval() &&
2500          "expected an immediate function");
2501   assert(FD->hasBody() && "expected the function to have a body");
2502   struct ImmediateEscalatingExpressionsVisitor
2503       : public RecursiveASTVisitor<ImmediateEscalatingExpressionsVisitor> {
2504 
2505     using Base = RecursiveASTVisitor<ImmediateEscalatingExpressionsVisitor>;
2506     Sema &SemaRef;
2507 
2508     const FunctionDecl *ImmediateFn;
2509     bool ImmediateFnIsConstructor;
2510     CXXConstructorDecl *CurrentConstructor = nullptr;
2511     CXXCtorInitializer *CurrentInit = nullptr;
2512 
2513     ImmediateEscalatingExpressionsVisitor(Sema &SemaRef, FunctionDecl *FD)
2514         : SemaRef(SemaRef), ImmediateFn(FD),
2515           ImmediateFnIsConstructor(isa<CXXConstructorDecl>(FD)) {}
2516 
2517     bool shouldVisitImplicitCode() const { return true; }
2518     bool shouldVisitLambdaBody() const { return false; }
2519 
2520     void Diag(const Expr *E, const FunctionDecl *Fn, bool IsCall) {
2521       SourceLocation Loc = E->getBeginLoc();
2522       SourceRange Range = E->getSourceRange();
2523       if (CurrentConstructor && CurrentInit) {
2524         Loc = CurrentConstructor->getLocation();
2525         Range = CurrentInit->isWritten() ? CurrentInit->getSourceRange()
2526                                          : SourceRange();
2527       }
2528 
2529       FieldDecl* InitializedField = CurrentInit ? CurrentInit->getAnyMember() : nullptr;
2530 
2531       SemaRef.Diag(Loc, diag::note_immediate_function_reason)
2532           << ImmediateFn << Fn << Fn->isConsteval() << IsCall
2533           << isa<CXXConstructorDecl>(Fn) << ImmediateFnIsConstructor
2534           << (InitializedField != nullptr)
2535           << (CurrentInit && !CurrentInit->isWritten())
2536           << InitializedField << Range;
2537     }
2538     bool TraverseCallExpr(CallExpr *E) {
2539       if (const auto *DR =
2540               dyn_cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit());
2541           DR && DR->isImmediateEscalating()) {
2542         Diag(E, E->getDirectCallee(), /*IsCall=*/true);
2543         return false;
2544       }
2545 
2546       for (Expr *A : E->arguments())
2547         if (!getDerived().TraverseStmt(A))
2548           return false;
2549 
2550       return true;
2551     }
2552 
2553     bool VisitDeclRefExpr(DeclRefExpr *E) {
2554       if (const auto *ReferencedFn = dyn_cast<FunctionDecl>(E->getDecl());
2555           ReferencedFn && E->isImmediateEscalating()) {
2556         Diag(E, ReferencedFn, /*IsCall=*/false);
2557         return false;
2558       }
2559 
2560       return true;
2561     }
2562 
2563     bool VisitCXXConstructExpr(CXXConstructExpr *E) {
2564       CXXConstructorDecl *D = E->getConstructor();
2565       if (E->isImmediateEscalating()) {
2566         Diag(E, D, /*IsCall=*/true);
2567         return false;
2568       }
2569       return true;
2570     }
2571 
2572     bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
2573       llvm::SaveAndRestore RAII(CurrentInit, Init);
2574       return Base::TraverseConstructorInitializer(Init);
2575     }
2576 
2577     bool TraverseCXXConstructorDecl(CXXConstructorDecl *Ctr) {
2578       llvm::SaveAndRestore RAII(CurrentConstructor, Ctr);
2579       return Base::TraverseCXXConstructorDecl(Ctr);
2580     }
2581 
2582     bool TraverseType(QualType T) { return true; }
2583     bool VisitBlockExpr(BlockExpr *T) { return true; }
2584 
2585   } Visitor(*this, FD);
2586   Visitor.TraverseDecl(FD);
2587 }
2588 
2589 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2590   assert(getLangOpts().CPlusPlus && "No class names in C!");
2591 
2592   if (SS && SS->isInvalid())
2593     return nullptr;
2594 
2595   if (SS && SS->isNotEmpty()) {
2596     DeclContext *DC = computeDeclContext(*SS, true);
2597     return dyn_cast_or_null<CXXRecordDecl>(DC);
2598   }
2599 
2600   return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2601 }
2602 
2603 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2604                               const CXXScopeSpec *SS) {
2605   CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2606   return CurDecl && &II == CurDecl->getIdentifier();
2607 }
2608 
2609 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2610   assert(getLangOpts().CPlusPlus && "No class names in C!");
2611 
2612   if (!getLangOpts().SpellChecking)
2613     return false;
2614 
2615   CXXRecordDecl *CurDecl;
2616   if (SS && SS->isSet() && !SS->isInvalid()) {
2617     DeclContext *DC = computeDeclContext(*SS, true);
2618     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2619   } else
2620     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2621 
2622   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2623       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2624           < II->getLength()) {
2625     II = CurDecl->getIdentifier();
2626     return true;
2627   }
2628 
2629   return false;
2630 }
2631 
2632 CXXBaseSpecifier *Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2633                                            SourceRange SpecifierRange,
2634                                            bool Virtual, AccessSpecifier Access,
2635                                            TypeSourceInfo *TInfo,
2636                                            SourceLocation EllipsisLoc) {
2637   QualType BaseType = TInfo->getType();
2638   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2639   if (BaseType->containsErrors()) {
2640     // Already emitted a diagnostic when parsing the error type.
2641     return nullptr;
2642   }
2643 
2644   if (EllipsisLoc.isValid() && !BaseType->containsUnexpandedParameterPack()) {
2645     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2646       << TInfo->getTypeLoc().getSourceRange();
2647     EllipsisLoc = SourceLocation();
2648   }
2649 
2650   auto *BaseDecl =
2651       dyn_cast_if_present<CXXRecordDecl>(computeDeclContext(BaseType));
2652   // C++ [class.derived.general]p2:
2653   //   A class-or-decltype shall denote a (possibly cv-qualified) class type
2654   //   that is not an incompletely defined class; any cv-qualifiers are
2655   //   ignored.
2656   if (BaseDecl) {
2657     // C++ [class.union.general]p4:
2658     // [...]  A union shall not be used as a base class.
2659     if (BaseDecl->isUnion()) {
2660       Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2661       return nullptr;
2662     }
2663 
2664     // For the MS ABI, propagate DLL attributes to base class templates.
2665     if (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
2666         Context.getTargetInfo().getTriple().isPS()) {
2667       if (Attr *ClassAttr = getDLLAttr(Class)) {
2668         if (auto *BaseSpec =
2669                 dyn_cast<ClassTemplateSpecializationDecl>(BaseDecl)) {
2670           propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseSpec,
2671                                               BaseLoc);
2672         }
2673       }
2674     }
2675 
2676     if (RequireCompleteType(BaseLoc, BaseType, diag::err_incomplete_base_class,
2677                             SpecifierRange)) {
2678       Class->setInvalidDecl();
2679       return nullptr;
2680     }
2681 
2682     BaseDecl = BaseDecl->getDefinition();
2683     assert(BaseDecl && "Base type is not incomplete, but has no definition");
2684 
2685     // Microsoft docs say:
2686     // "If a base-class has a code_seg attribute, derived classes must have the
2687     // same attribute."
2688     const auto *BaseCSA = BaseDecl->getAttr<CodeSegAttr>();
2689     const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2690     if ((DerivedCSA || BaseCSA) &&
2691         (!BaseCSA || !DerivedCSA ||
2692          BaseCSA->getName() != DerivedCSA->getName())) {
2693       Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2694       Diag(BaseDecl->getLocation(), diag::note_base_class_specified_here)
2695           << BaseDecl;
2696       return nullptr;
2697     }
2698 
2699     // A class which contains a flexible array member is not suitable for use as
2700     // a base class:
2701     //   - If the layout determines that a base comes before another base,
2702     //     the flexible array member would index into the subsequent base.
2703     //   - If the layout determines that base comes before the derived class,
2704     //     the flexible array member would index into the derived class.
2705     if (BaseDecl->hasFlexibleArrayMember()) {
2706       Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2707           << BaseDecl->getDeclName();
2708       return nullptr;
2709     }
2710 
2711     // C++ [class]p3:
2712     //   If a class is marked final and it appears as a base-type-specifier in
2713     //   base-clause, the program is ill-formed.
2714     if (FinalAttr *FA = BaseDecl->getAttr<FinalAttr>()) {
2715       Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2716           << BaseDecl->getDeclName() << FA->isSpelledAsSealed();
2717       Diag(BaseDecl->getLocation(), diag::note_entity_declared_at)
2718           << BaseDecl->getDeclName() << FA->getRange();
2719       return nullptr;
2720     }
2721 
2722     // If the base class is invalid the derived class is as well.
2723     if (BaseDecl->isInvalidDecl())
2724       Class->setInvalidDecl();
2725   } else if (BaseType->isDependentType()) {
2726     // Make sure that we don't make an ill-formed AST where the type of the
2727     // Class is non-dependent and its attached base class specifier is an
2728     // dependent type, which violates invariants in many clang code paths (e.g.
2729     // constexpr evaluator). If this case happens (in errory-recovery mode), we
2730     // explicitly mark the Class decl invalid. The diagnostic was already
2731     // emitted.
2732     if (!Class->isDependentContext())
2733       Class->setInvalidDecl();
2734   } else {
2735     // The base class is some non-dependent non-class type.
2736     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2737     return nullptr;
2738   }
2739 
2740   // In HLSL, unspecified class access is public rather than private.
2741   if (getLangOpts().HLSL && Class->getTagKind() == TagTypeKind::Class &&
2742       Access == AS_none)
2743     Access = AS_public;
2744 
2745   // Create the base specifier.
2746   return new (Context) CXXBaseSpecifier(
2747       SpecifierRange, Virtual, Class->getTagKind() == TagTypeKind::Class,
2748       Access, TInfo, EllipsisLoc);
2749 }
2750 
2751 BaseResult Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2752                                     const ParsedAttributesView &Attributes,
2753                                     bool Virtual, AccessSpecifier Access,
2754                                     ParsedType basetype, SourceLocation BaseLoc,
2755                                     SourceLocation EllipsisLoc) {
2756   if (!classdecl)
2757     return true;
2758 
2759   AdjustDeclIfTemplate(classdecl);
2760   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2761   if (!Class)
2762     return true;
2763 
2764   // We haven't yet attached the base specifiers.
2765   Class->setIsParsingBaseSpecifiers();
2766 
2767   // We do not support any C++11 attributes on base-specifiers yet.
2768   // Diagnose any attributes we see.
2769   for (const ParsedAttr &AL : Attributes) {
2770     if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2771       continue;
2772     if (AL.getKind() == ParsedAttr::UnknownAttribute)
2773       Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
2774           << AL << AL.getRange();
2775     else
2776       Diag(AL.getLoc(), diag::err_base_specifier_attribute)
2777           << AL << AL.isRegularKeywordAttribute() << AL.getRange();
2778   }
2779 
2780   TypeSourceInfo *TInfo = nullptr;
2781   GetTypeFromParser(basetype, &TInfo);
2782 
2783   if (EllipsisLoc.isInvalid() &&
2784       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2785                                       UPPC_BaseType))
2786     return true;
2787 
2788   // C++ [class.union.general]p4:
2789   //   [...] A union shall not have base classes.
2790   if (Class->isUnion()) {
2791     Diag(Class->getLocation(), diag::err_base_clause_on_union)
2792         << SpecifierRange;
2793     return true;
2794   }
2795 
2796   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2797                                                       Virtual, Access, TInfo,
2798                                                       EllipsisLoc))
2799     return BaseSpec;
2800 
2801   Class->setInvalidDecl();
2802   return true;
2803 }
2804 
2805 /// Use small set to collect indirect bases.  As this is only used
2806 /// locally, there's no need to abstract the small size parameter.
2807 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2808 
2809 /// Recursively add the bases of Type.  Don't add Type itself.
2810 static void
2811 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2812                   const QualType &Type)
2813 {
2814   // Even though the incoming type is a base, it might not be
2815   // a class -- it could be a template parm, for instance.
2816   if (auto Rec = Type->getAs<RecordType>()) {
2817     auto Decl = Rec->getAsCXXRecordDecl();
2818 
2819     // Iterate over its bases.
2820     for (const auto &BaseSpec : Decl->bases()) {
2821       QualType Base = Context.getCanonicalType(BaseSpec.getType())
2822         .getUnqualifiedType();
2823       if (Set.insert(Base).second)
2824         // If we've not already seen it, recurse.
2825         NoteIndirectBases(Context, Set, Base);
2826     }
2827   }
2828 }
2829 
2830 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2831                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2832  if (Bases.empty())
2833     return false;
2834 
2835   // Used to keep track of which base types we have already seen, so
2836   // that we can properly diagnose redundant direct base types. Note
2837   // that the key is always the unqualified canonical type of the base
2838   // class.
2839   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2840 
2841   // Used to track indirect bases so we can see if a direct base is
2842   // ambiguous.
2843   IndirectBaseSet IndirectBaseTypes;
2844 
2845   // Copy non-redundant base specifiers into permanent storage.
2846   unsigned NumGoodBases = 0;
2847   bool Invalid = false;
2848   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2849     QualType NewBaseType
2850       = Context.getCanonicalType(Bases[idx]->getType());
2851     NewBaseType = NewBaseType.getLocalUnqualifiedType();
2852 
2853     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2854     if (KnownBase) {
2855       // C++ [class.mi]p3:
2856       //   A class shall not be specified as a direct base class of a
2857       //   derived class more than once.
2858       Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2859           << KnownBase->getType() << Bases[idx]->getSourceRange();
2860 
2861       // Delete the duplicate base class specifier; we're going to
2862       // overwrite its pointer later.
2863       Context.Deallocate(Bases[idx]);
2864 
2865       Invalid = true;
2866     } else {
2867       // Okay, add this new base class.
2868       KnownBase = Bases[idx];
2869       Bases[NumGoodBases++] = Bases[idx];
2870 
2871       if (NewBaseType->isDependentType())
2872         continue;
2873       // Note this base's direct & indirect bases, if there could be ambiguity.
2874       if (Bases.size() > 1)
2875         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2876 
2877       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2878         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2879         if (Class->isInterface() &&
2880               (!RD->isInterfaceLike() ||
2881                KnownBase->getAccessSpecifier() != AS_public)) {
2882           // The Microsoft extension __interface does not permit bases that
2883           // are not themselves public interfaces.
2884           Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2885               << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2886               << RD->getSourceRange();
2887           Invalid = true;
2888         }
2889         if (RD->hasAttr<WeakAttr>())
2890           Class->addAttr(WeakAttr::CreateImplicit(Context));
2891       }
2892     }
2893   }
2894 
2895   // Attach the remaining base class specifiers to the derived class.
2896   Class->setBases(Bases.data(), NumGoodBases);
2897 
2898   // Check that the only base classes that are duplicate are virtual.
2899   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2900     // Check whether this direct base is inaccessible due to ambiguity.
2901     QualType BaseType = Bases[idx]->getType();
2902 
2903     // Skip all dependent types in templates being used as base specifiers.
2904     // Checks below assume that the base specifier is a CXXRecord.
2905     if (BaseType->isDependentType())
2906       continue;
2907 
2908     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2909       .getUnqualifiedType();
2910 
2911     if (IndirectBaseTypes.count(CanonicalBase)) {
2912       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2913                          /*DetectVirtual=*/true);
2914       bool found
2915         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2916       assert(found);
2917       (void)found;
2918 
2919       if (Paths.isAmbiguous(CanonicalBase))
2920         Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2921             << BaseType << getAmbiguousPathsDisplayString(Paths)
2922             << Bases[idx]->getSourceRange();
2923       else
2924         assert(Bases[idx]->isVirtual());
2925     }
2926 
2927     // Delete the base class specifier, since its data has been copied
2928     // into the CXXRecordDecl.
2929     Context.Deallocate(Bases[idx]);
2930   }
2931 
2932   return Invalid;
2933 }
2934 
2935 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2936                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2937   if (!ClassDecl || Bases.empty())
2938     return;
2939 
2940   AdjustDeclIfTemplate(ClassDecl);
2941   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2942 }
2943 
2944 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2945   if (!getLangOpts().CPlusPlus)
2946     return false;
2947 
2948   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2949   if (!DerivedRD)
2950     return false;
2951 
2952   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2953   if (!BaseRD)
2954     return false;
2955 
2956   // If either the base or the derived type is invalid, don't try to
2957   // check whether one is derived from the other.
2958   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2959     return false;
2960 
2961   // FIXME: In a modules build, do we need the entire path to be visible for us
2962   // to be able to use the inheritance relationship?
2963   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2964     return false;
2965 
2966   return DerivedRD->isDerivedFrom(BaseRD);
2967 }
2968 
2969 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2970                          CXXBasePaths &Paths) {
2971   if (!getLangOpts().CPlusPlus)
2972     return false;
2973 
2974   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2975   if (!DerivedRD)
2976     return false;
2977 
2978   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2979   if (!BaseRD)
2980     return false;
2981 
2982   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2983     return false;
2984 
2985   return DerivedRD->isDerivedFrom(BaseRD, Paths);
2986 }
2987 
2988 static void BuildBasePathArray(const CXXBasePath &Path,
2989                                CXXCastPath &BasePathArray) {
2990   // We first go backward and check if we have a virtual base.
2991   // FIXME: It would be better if CXXBasePath had the base specifier for
2992   // the nearest virtual base.
2993   unsigned Start = 0;
2994   for (unsigned I = Path.size(); I != 0; --I) {
2995     if (Path[I - 1].Base->isVirtual()) {
2996       Start = I - 1;
2997       break;
2998     }
2999   }
3000 
3001   // Now add all bases.
3002   for (unsigned I = Start, E = Path.size(); I != E; ++I)
3003     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
3004 }
3005 
3006 
3007 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
3008                               CXXCastPath &BasePathArray) {
3009   assert(BasePathArray.empty() && "Base path array must be empty!");
3010   assert(Paths.isRecordingPaths() && "Must record paths!");
3011   return ::BuildBasePathArray(Paths.front(), BasePathArray);
3012 }
3013 
3014 bool
3015 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
3016                                    unsigned InaccessibleBaseID,
3017                                    unsigned AmbiguousBaseConvID,
3018                                    SourceLocation Loc, SourceRange Range,
3019                                    DeclarationName Name,
3020                                    CXXCastPath *BasePath,
3021                                    bool IgnoreAccess) {
3022   // First, determine whether the path from Derived to Base is
3023   // ambiguous. This is slightly more expensive than checking whether
3024   // the Derived to Base conversion exists, because here we need to
3025   // explore multiple paths to determine if there is an ambiguity.
3026   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3027                      /*DetectVirtual=*/false);
3028   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3029   if (!DerivationOkay)
3030     return true;
3031 
3032   const CXXBasePath *Path = nullptr;
3033   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
3034     Path = &Paths.front();
3035 
3036   // For MSVC compatibility, check if Derived directly inherits from Base. Clang
3037   // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
3038   // user to access such bases.
3039   if (!Path && getLangOpts().MSVCCompat) {
3040     for (const CXXBasePath &PossiblePath : Paths) {
3041       if (PossiblePath.size() == 1) {
3042         Path = &PossiblePath;
3043         if (AmbiguousBaseConvID)
3044           Diag(Loc, diag::ext_ms_ambiguous_direct_base)
3045               << Base << Derived << Range;
3046         break;
3047       }
3048     }
3049   }
3050 
3051   if (Path) {
3052     if (!IgnoreAccess) {
3053       // Check that the base class can be accessed.
3054       switch (
3055           CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
3056       case AR_inaccessible:
3057         return true;
3058       case AR_accessible:
3059       case AR_dependent:
3060       case AR_delayed:
3061         break;
3062       }
3063     }
3064 
3065     // Build a base path if necessary.
3066     if (BasePath)
3067       ::BuildBasePathArray(*Path, *BasePath);
3068     return false;
3069   }
3070 
3071   if (AmbiguousBaseConvID) {
3072     // We know that the derived-to-base conversion is ambiguous, and
3073     // we're going to produce a diagnostic. Perform the derived-to-base
3074     // search just one more time to compute all of the possible paths so
3075     // that we can print them out. This is more expensive than any of
3076     // the previous derived-to-base checks we've done, but at this point
3077     // performance isn't as much of an issue.
3078     Paths.clear();
3079     Paths.setRecordingPaths(true);
3080     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3081     assert(StillOkay && "Can only be used with a derived-to-base conversion");
3082     (void)StillOkay;
3083 
3084     // Build up a textual representation of the ambiguous paths, e.g.,
3085     // D -> B -> A, that will be used to illustrate the ambiguous
3086     // conversions in the diagnostic. We only print one of the paths
3087     // to each base class subobject.
3088     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3089 
3090     Diag(Loc, AmbiguousBaseConvID)
3091     << Derived << Base << PathDisplayStr << Range << Name;
3092   }
3093   return true;
3094 }
3095 
3096 bool
3097 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
3098                                    SourceLocation Loc, SourceRange Range,
3099                                    CXXCastPath *BasePath,
3100                                    bool IgnoreAccess) {
3101   return CheckDerivedToBaseConversion(
3102       Derived, Base, diag::err_upcast_to_inaccessible_base,
3103       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
3104       BasePath, IgnoreAccess);
3105 }
3106 
3107 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
3108   std::string PathDisplayStr;
3109   std::set<unsigned> DisplayedPaths;
3110   for (CXXBasePaths::paths_iterator Path = Paths.begin();
3111        Path != Paths.end(); ++Path) {
3112     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
3113       // We haven't displayed a path to this particular base
3114       // class subobject yet.
3115       PathDisplayStr += "\n    ";
3116       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
3117       for (CXXBasePath::const_iterator Element = Path->begin();
3118            Element != Path->end(); ++Element)
3119         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
3120     }
3121   }
3122 
3123   return PathDisplayStr;
3124 }
3125 
3126 //===----------------------------------------------------------------------===//
3127 // C++ class member Handling
3128 //===----------------------------------------------------------------------===//
3129 
3130 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
3131                                 SourceLocation ColonLoc,
3132                                 const ParsedAttributesView &Attrs) {
3133   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
3134   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
3135                                                   ASLoc, ColonLoc);
3136   CurContext->addHiddenDecl(ASDecl);
3137   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
3138 }
3139 
3140 void Sema::CheckOverrideControl(NamedDecl *D) {
3141   if (D->isInvalidDecl())
3142     return;
3143 
3144   // We only care about "override" and "final" declarations.
3145   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3146     return;
3147 
3148   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3149 
3150   // We can't check dependent instance methods.
3151   if (MD && MD->isInstance() &&
3152       (MD->getParent()->hasAnyDependentBases() ||
3153        MD->getType()->isDependentType()))
3154     return;
3155 
3156   if (MD && !MD->isVirtual()) {
3157     // If we have a non-virtual method, check if it hides a virtual method.
3158     // (In that case, it's most likely the method has the wrong type.)
3159     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3160     FindHiddenVirtualMethods(MD, OverloadedMethods);
3161 
3162     if (!OverloadedMethods.empty()) {
3163       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3164         Diag(OA->getLocation(),
3165              diag::override_keyword_hides_virtual_member_function)
3166           << "override" << (OverloadedMethods.size() > 1);
3167       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3168         Diag(FA->getLocation(),
3169              diag::override_keyword_hides_virtual_member_function)
3170           << (FA->isSpelledAsSealed() ? "sealed" : "final")
3171           << (OverloadedMethods.size() > 1);
3172       }
3173       NoteHiddenVirtualMethods(MD, OverloadedMethods);
3174       MD->setInvalidDecl();
3175       return;
3176     }
3177     // Fall through into the general case diagnostic.
3178     // FIXME: We might want to attempt typo correction here.
3179   }
3180 
3181   if (!MD || !MD->isVirtual()) {
3182     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3183       Diag(OA->getLocation(),
3184            diag::override_keyword_only_allowed_on_virtual_member_functions)
3185         << "override" << FixItHint::CreateRemoval(OA->getLocation());
3186       D->dropAttr<OverrideAttr>();
3187     }
3188     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3189       Diag(FA->getLocation(),
3190            diag::override_keyword_only_allowed_on_virtual_member_functions)
3191         << (FA->isSpelledAsSealed() ? "sealed" : "final")
3192         << FixItHint::CreateRemoval(FA->getLocation());
3193       D->dropAttr<FinalAttr>();
3194     }
3195     return;
3196   }
3197 
3198   // C++11 [class.virtual]p5:
3199   //   If a function is marked with the virt-specifier override and
3200   //   does not override a member function of a base class, the program is
3201   //   ill-formed.
3202   bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3203   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3204     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3205       << MD->getDeclName();
3206 }
3207 
3208 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) {
3209   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3210     return;
3211   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3212   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3213     return;
3214 
3215   SourceLocation Loc = MD->getLocation();
3216   SourceLocation SpellingLoc = Loc;
3217   if (getSourceManager().isMacroArgExpansion(Loc))
3218     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3219   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3220   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3221       return;
3222 
3223   if (MD->size_overridden_methods() > 0) {
3224     auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3225       unsigned DiagID =
3226           Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3227               ? DiagInconsistent
3228               : DiagSuggest;
3229       Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3230       const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3231       Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3232     };
3233     if (isa<CXXDestructorDecl>(MD))
3234       EmitDiag(
3235           diag::warn_inconsistent_destructor_marked_not_override_overriding,
3236           diag::warn_suggest_destructor_marked_not_override_overriding);
3237     else
3238       EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3239                diag::warn_suggest_function_marked_not_override_overriding);
3240   }
3241 }
3242 
3243 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3244                                                   const CXXMethodDecl *Old) {
3245   FinalAttr *FA = Old->getAttr<FinalAttr>();
3246   if (!FA)
3247     return false;
3248 
3249   Diag(New->getLocation(), diag::err_final_function_overridden)
3250     << New->getDeclName()
3251     << FA->isSpelledAsSealed();
3252   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3253   return true;
3254 }
3255 
3256 static bool InitializationHasSideEffects(const FieldDecl &FD) {
3257   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3258   // FIXME: Destruction of ObjC lifetime types has side-effects.
3259   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3260     return !RD->isCompleteDefinition() ||
3261            !RD->hasTrivialDefaultConstructor() ||
3262            !RD->hasTrivialDestructor();
3263   return false;
3264 }
3265 
3266 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3267                                       DeclarationName FieldName,
3268                                       const CXXRecordDecl *RD,
3269                                       bool DeclIsField) {
3270   if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3271     return;
3272 
3273   // To record a shadowed field in a base
3274   std::map<CXXRecordDecl*, NamedDecl*> Bases;
3275   auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3276                            CXXBasePath &Path) {
3277     const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3278     // Record an ambiguous path directly
3279     if (Bases.find(Base) != Bases.end())
3280       return true;
3281     for (const auto Field : Base->lookup(FieldName)) {
3282       if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3283           Field->getAccess() != AS_private) {
3284         assert(Field->getAccess() != AS_none);
3285         assert(Bases.find(Base) == Bases.end());
3286         Bases[Base] = Field;
3287         return true;
3288       }
3289     }
3290     return false;
3291   };
3292 
3293   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3294                      /*DetectVirtual=*/true);
3295   if (!RD->lookupInBases(FieldShadowed, Paths))
3296     return;
3297 
3298   for (const auto &P : Paths) {
3299     auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3300     auto It = Bases.find(Base);
3301     // Skip duplicated bases
3302     if (It == Bases.end())
3303       continue;
3304     auto BaseField = It->second;
3305     assert(BaseField->getAccess() != AS_private);
3306     if (AS_none !=
3307         CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3308       Diag(Loc, diag::warn_shadow_field)
3309         << FieldName << RD << Base << DeclIsField;
3310       Diag(BaseField->getLocation(), diag::note_shadow_field);
3311       Bases.erase(It);
3312     }
3313   }
3314 }
3315 
3316 NamedDecl *
3317 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3318                                MultiTemplateParamsArg TemplateParameterLists,
3319                                Expr *BW, const VirtSpecifiers &VS,
3320                                InClassInitStyle InitStyle) {
3321   const DeclSpec &DS = D.getDeclSpec();
3322   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3323   DeclarationName Name = NameInfo.getName();
3324   SourceLocation Loc = NameInfo.getLoc();
3325 
3326   // For anonymous bitfields, the location should point to the type.
3327   if (Loc.isInvalid())
3328     Loc = D.getBeginLoc();
3329 
3330   Expr *BitWidth = static_cast<Expr*>(BW);
3331 
3332   assert(isa<CXXRecordDecl>(CurContext));
3333   assert(!DS.isFriendSpecified());
3334 
3335   bool isFunc = D.isDeclarationOfFunction();
3336   const ParsedAttr *MSPropertyAttr =
3337       D.getDeclSpec().getAttributes().getMSPropertyAttr();
3338 
3339   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3340     // The Microsoft extension __interface only permits public member functions
3341     // and prohibits constructors, destructors, operators, non-public member
3342     // functions, static methods and data members.
3343     unsigned InvalidDecl;
3344     bool ShowDeclName = true;
3345     if (!isFunc &&
3346         (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3347       InvalidDecl = 0;
3348     else if (!isFunc)
3349       InvalidDecl = 1;
3350     else if (AS != AS_public)
3351       InvalidDecl = 2;
3352     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3353       InvalidDecl = 3;
3354     else switch (Name.getNameKind()) {
3355       case DeclarationName::CXXConstructorName:
3356         InvalidDecl = 4;
3357         ShowDeclName = false;
3358         break;
3359 
3360       case DeclarationName::CXXDestructorName:
3361         InvalidDecl = 5;
3362         ShowDeclName = false;
3363         break;
3364 
3365       case DeclarationName::CXXOperatorName:
3366       case DeclarationName::CXXConversionFunctionName:
3367         InvalidDecl = 6;
3368         break;
3369 
3370       default:
3371         InvalidDecl = 0;
3372         break;
3373     }
3374 
3375     if (InvalidDecl) {
3376       if (ShowDeclName)
3377         Diag(Loc, diag::err_invalid_member_in_interface)
3378           << (InvalidDecl-1) << Name;
3379       else
3380         Diag(Loc, diag::err_invalid_member_in_interface)
3381           << (InvalidDecl-1) << "";
3382       return nullptr;
3383     }
3384   }
3385 
3386   // C++ 9.2p6: A member shall not be declared to have automatic storage
3387   // duration (auto, register) or with the extern storage-class-specifier.
3388   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3389   // data members and cannot be applied to names declared const or static,
3390   // and cannot be applied to reference members.
3391   switch (DS.getStorageClassSpec()) {
3392   case DeclSpec::SCS_unspecified:
3393   case DeclSpec::SCS_typedef:
3394   case DeclSpec::SCS_static:
3395     break;
3396   case DeclSpec::SCS_mutable:
3397     if (isFunc) {
3398       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3399 
3400       // FIXME: It would be nicer if the keyword was ignored only for this
3401       // declarator. Otherwise we could get follow-up errors.
3402       D.getMutableDeclSpec().ClearStorageClassSpecs();
3403     }
3404     break;
3405   default:
3406     Diag(DS.getStorageClassSpecLoc(),
3407          diag::err_storageclass_invalid_for_member);
3408     D.getMutableDeclSpec().ClearStorageClassSpecs();
3409     break;
3410   }
3411 
3412   bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3413                       DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3414                      !isFunc && TemplateParameterLists.empty();
3415 
3416   if (DS.hasConstexprSpecifier() && isInstField) {
3417     SemaDiagnosticBuilder B =
3418         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3419     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3420     if (InitStyle == ICIS_NoInit) {
3421       B << 0 << 0;
3422       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3423         B << FixItHint::CreateRemoval(ConstexprLoc);
3424       else {
3425         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3426         D.getMutableDeclSpec().ClearConstexprSpec();
3427         const char *PrevSpec;
3428         unsigned DiagID;
3429         bool Failed = D.getMutableDeclSpec().SetTypeQual(
3430             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3431         (void)Failed;
3432         assert(!Failed && "Making a constexpr member const shouldn't fail");
3433       }
3434     } else {
3435       B << 1;
3436       const char *PrevSpec;
3437       unsigned DiagID;
3438       if (D.getMutableDeclSpec().SetStorageClassSpec(
3439           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3440           Context.getPrintingPolicy())) {
3441         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3442                "This is the only DeclSpec that should fail to be applied");
3443         B << 1;
3444       } else {
3445         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3446         isInstField = false;
3447       }
3448     }
3449   }
3450 
3451   NamedDecl *Member;
3452   if (isInstField) {
3453     CXXScopeSpec &SS = D.getCXXScopeSpec();
3454 
3455     // Data members must have identifiers for names.
3456     if (!Name.isIdentifier()) {
3457       Diag(Loc, diag::err_bad_variable_name)
3458         << Name;
3459       return nullptr;
3460     }
3461 
3462     IdentifierInfo *II = Name.getAsIdentifierInfo();
3463     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
3464       Diag(D.getIdentifierLoc(), diag::err_member_with_template_arguments)
3465           << II
3466           << SourceRange(D.getName().TemplateId->LAngleLoc,
3467                          D.getName().TemplateId->RAngleLoc)
3468           << D.getName().TemplateId->LAngleLoc;
3469       D.SetIdentifier(II, Loc);
3470     }
3471 
3472     if (SS.isSet() && !SS.isInvalid()) {
3473       // The user provided a superfluous scope specifier inside a class
3474       // definition:
3475       //
3476       // class X {
3477       //   int X::member;
3478       // };
3479       if (DeclContext *DC = computeDeclContext(SS, false)) {
3480         TemplateIdAnnotation *TemplateId =
3481             D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
3482                 ? D.getName().TemplateId
3483                 : nullptr;
3484         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3485                                      TemplateId,
3486                                      /*IsMemberSpecialization=*/false);
3487       } else {
3488         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3489           << Name << SS.getRange();
3490       }
3491       SS.clear();
3492     }
3493 
3494     if (MSPropertyAttr) {
3495       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3496                                 BitWidth, InitStyle, AS, *MSPropertyAttr);
3497       if (!Member)
3498         return nullptr;
3499       isInstField = false;
3500     } else {
3501       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3502                                 BitWidth, InitStyle, AS);
3503       if (!Member)
3504         return nullptr;
3505     }
3506 
3507     CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3508   } else {
3509     Member = HandleDeclarator(S, D, TemplateParameterLists);
3510     if (!Member)
3511       return nullptr;
3512 
3513     // Non-instance-fields can't have a bitfield.
3514     if (BitWidth) {
3515       if (Member->isInvalidDecl()) {
3516         // don't emit another diagnostic.
3517       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3518         // C++ 9.6p3: A bit-field shall not be a static member.
3519         // "static member 'A' cannot be a bit-field"
3520         Diag(Loc, diag::err_static_not_bitfield)
3521           << Name << BitWidth->getSourceRange();
3522       } else if (isa<TypedefDecl>(Member)) {
3523         // "typedef member 'x' cannot be a bit-field"
3524         Diag(Loc, diag::err_typedef_not_bitfield)
3525           << Name << BitWidth->getSourceRange();
3526       } else {
3527         // A function typedef ("typedef int f(); f a;").
3528         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3529         Diag(Loc, diag::err_not_integral_type_bitfield)
3530           << Name << cast<ValueDecl>(Member)->getType()
3531           << BitWidth->getSourceRange();
3532       }
3533 
3534       BitWidth = nullptr;
3535       Member->setInvalidDecl();
3536     }
3537 
3538     NamedDecl *NonTemplateMember = Member;
3539     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3540       NonTemplateMember = FunTmpl->getTemplatedDecl();
3541     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3542       NonTemplateMember = VarTmpl->getTemplatedDecl();
3543 
3544     Member->setAccess(AS);
3545 
3546     // If we have declared a member function template or static data member
3547     // template, set the access of the templated declaration as well.
3548     if (NonTemplateMember != Member)
3549       NonTemplateMember->setAccess(AS);
3550 
3551     // C++ [temp.deduct.guide]p3:
3552     //   A deduction guide [...] for a member class template [shall be
3553     //   declared] with the same access [as the template].
3554     if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3555       auto *TD = DG->getDeducedTemplate();
3556       // Access specifiers are only meaningful if both the template and the
3557       // deduction guide are from the same scope.
3558       if (AS != TD->getAccess() &&
3559           TD->getDeclContext()->getRedeclContext()->Equals(
3560               DG->getDeclContext()->getRedeclContext())) {
3561         Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3562         Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3563             << TD->getAccess();
3564         const AccessSpecDecl *LastAccessSpec = nullptr;
3565         for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3566           if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3567             LastAccessSpec = AccessSpec;
3568         }
3569         assert(LastAccessSpec && "differing access with no access specifier");
3570         Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3571             << AS;
3572       }
3573     }
3574   }
3575 
3576   if (VS.isOverrideSpecified())
3577     Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc()));
3578   if (VS.isFinalSpecified())
3579     Member->addAttr(FinalAttr::Create(Context, VS.getFinalLoc(),
3580                                       VS.isFinalSpelledSealed()
3581                                           ? FinalAttr::Keyword_sealed
3582                                           : FinalAttr::Keyword_final));
3583 
3584   if (VS.getLastLocation().isValid()) {
3585     // Update the end location of a method that has a virt-specifiers.
3586     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3587       MD->setRangeEnd(VS.getLastLocation());
3588   }
3589 
3590   CheckOverrideControl(Member);
3591 
3592   assert((Name || isInstField) && "No identifier for non-field ?");
3593 
3594   if (isInstField) {
3595     FieldDecl *FD = cast<FieldDecl>(Member);
3596     FieldCollector->Add(FD);
3597 
3598     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3599       // Remember all explicit private FieldDecls that have a name, no side
3600       // effects and are not part of a dependent type declaration.
3601 
3602       auto DeclHasUnusedAttr = [](const QualType &T) {
3603         if (const TagDecl *TD = T->getAsTagDecl())
3604           return TD->hasAttr<UnusedAttr>();
3605         if (const TypedefType *TDT = T->getAs<TypedefType>())
3606           return TDT->getDecl()->hasAttr<UnusedAttr>();
3607         return false;
3608       };
3609 
3610       if (!FD->isImplicit() && FD->getDeclName() &&
3611           FD->getAccess() == AS_private &&
3612           !FD->hasAttr<UnusedAttr>() &&
3613           !FD->getParent()->isDependentContext() &&
3614           !DeclHasUnusedAttr(FD->getType()) &&
3615           !InitializationHasSideEffects(*FD))
3616         UnusedPrivateFields.insert(FD);
3617     }
3618   }
3619 
3620   return Member;
3621 }
3622 
3623 namespace {
3624   class UninitializedFieldVisitor
3625       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3626     Sema &S;
3627     // List of Decls to generate a warning on.  Also remove Decls that become
3628     // initialized.
3629     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3630     // List of base classes of the record.  Classes are removed after their
3631     // initializers.
3632     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3633     // Vector of decls to be removed from the Decl set prior to visiting the
3634     // nodes.  These Decls may have been initialized in the prior initializer.
3635     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3636     // If non-null, add a note to the warning pointing back to the constructor.
3637     const CXXConstructorDecl *Constructor;
3638     // Variables to hold state when processing an initializer list.  When
3639     // InitList is true, special case initialization of FieldDecls matching
3640     // InitListFieldDecl.
3641     bool InitList;
3642     FieldDecl *InitListFieldDecl;
3643     llvm::SmallVector<unsigned, 4> InitFieldIndex;
3644 
3645   public:
3646     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3647     UninitializedFieldVisitor(Sema &S,
3648                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3649                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3650       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3651         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3652 
3653     // Returns true if the use of ME is not an uninitialized use.
3654     bool IsInitListMemberExprInitialized(MemberExpr *ME,
3655                                          bool CheckReferenceOnly) {
3656       llvm::SmallVector<FieldDecl*, 4> Fields;
3657       bool ReferenceField = false;
3658       while (ME) {
3659         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3660         if (!FD)
3661           return false;
3662         Fields.push_back(FD);
3663         if (FD->getType()->isReferenceType())
3664           ReferenceField = true;
3665         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3666       }
3667 
3668       // Binding a reference to an uninitialized field is not an
3669       // uninitialized use.
3670       if (CheckReferenceOnly && !ReferenceField)
3671         return true;
3672 
3673       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3674       // Discard the first field since it is the field decl that is being
3675       // initialized.
3676       for (const FieldDecl *FD : llvm::drop_begin(llvm::reverse(Fields)))
3677         UsedFieldIndex.push_back(FD->getFieldIndex());
3678 
3679       for (auto UsedIter = UsedFieldIndex.begin(),
3680                 UsedEnd = UsedFieldIndex.end(),
3681                 OrigIter = InitFieldIndex.begin(),
3682                 OrigEnd = InitFieldIndex.end();
3683            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3684         if (*UsedIter < *OrigIter)
3685           return true;
3686         if (*UsedIter > *OrigIter)
3687           break;
3688       }
3689 
3690       return false;
3691     }
3692 
3693     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3694                           bool AddressOf) {
3695       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3696         return;
3697 
3698       // FieldME is the inner-most MemberExpr that is not an anonymous struct
3699       // or union.
3700       MemberExpr *FieldME = ME;
3701 
3702       bool AllPODFields = FieldME->getType().isPODType(S.Context);
3703 
3704       Expr *Base = ME;
3705       while (MemberExpr *SubME =
3706                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3707 
3708         if (isa<VarDecl>(SubME->getMemberDecl()))
3709           return;
3710 
3711         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3712           if (!FD->isAnonymousStructOrUnion())
3713             FieldME = SubME;
3714 
3715         if (!FieldME->getType().isPODType(S.Context))
3716           AllPODFields = false;
3717 
3718         Base = SubME->getBase();
3719       }
3720 
3721       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3722         Visit(Base);
3723         return;
3724       }
3725 
3726       if (AddressOf && AllPODFields)
3727         return;
3728 
3729       ValueDecl* FoundVD = FieldME->getMemberDecl();
3730 
3731       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3732         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3733           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3734         }
3735 
3736         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3737           QualType T = BaseCast->getType();
3738           if (T->isPointerType() &&
3739               BaseClasses.count(T->getPointeeType())) {
3740             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3741                 << T->getPointeeType() << FoundVD;
3742           }
3743         }
3744       }
3745 
3746       if (!Decls.count(FoundVD))
3747         return;
3748 
3749       const bool IsReference = FoundVD->getType()->isReferenceType();
3750 
3751       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3752         // Special checking for initializer lists.
3753         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3754           return;
3755         }
3756       } else {
3757         // Prevent double warnings on use of unbounded references.
3758         if (CheckReferenceOnly && !IsReference)
3759           return;
3760       }
3761 
3762       unsigned diag = IsReference
3763           ? diag::warn_reference_field_is_uninit
3764           : diag::warn_field_is_uninit;
3765       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3766       if (Constructor)
3767         S.Diag(Constructor->getLocation(),
3768                diag::note_uninit_in_this_constructor)
3769           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3770 
3771     }
3772 
3773     void HandleValue(Expr *E, bool AddressOf) {
3774       E = E->IgnoreParens();
3775 
3776       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3777         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3778                          AddressOf /*AddressOf*/);
3779         return;
3780       }
3781 
3782       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3783         Visit(CO->getCond());
3784         HandleValue(CO->getTrueExpr(), AddressOf);
3785         HandleValue(CO->getFalseExpr(), AddressOf);
3786         return;
3787       }
3788 
3789       if (BinaryConditionalOperator *BCO =
3790               dyn_cast<BinaryConditionalOperator>(E)) {
3791         Visit(BCO->getCond());
3792         HandleValue(BCO->getFalseExpr(), AddressOf);
3793         return;
3794       }
3795 
3796       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3797         HandleValue(OVE->getSourceExpr(), AddressOf);
3798         return;
3799       }
3800 
3801       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3802         switch (BO->getOpcode()) {
3803         default:
3804           break;
3805         case(BO_PtrMemD):
3806         case(BO_PtrMemI):
3807           HandleValue(BO->getLHS(), AddressOf);
3808           Visit(BO->getRHS());
3809           return;
3810         case(BO_Comma):
3811           Visit(BO->getLHS());
3812           HandleValue(BO->getRHS(), AddressOf);
3813           return;
3814         }
3815       }
3816 
3817       Visit(E);
3818     }
3819 
3820     void CheckInitListExpr(InitListExpr *ILE) {
3821       InitFieldIndex.push_back(0);
3822       for (auto *Child : ILE->children()) {
3823         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3824           CheckInitListExpr(SubList);
3825         } else {
3826           Visit(Child);
3827         }
3828         ++InitFieldIndex.back();
3829       }
3830       InitFieldIndex.pop_back();
3831     }
3832 
3833     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3834                           FieldDecl *Field, const Type *BaseClass) {
3835       // Remove Decls that may have been initialized in the previous
3836       // initializer.
3837       for (ValueDecl* VD : DeclsToRemove)
3838         Decls.erase(VD);
3839       DeclsToRemove.clear();
3840 
3841       Constructor = FieldConstructor;
3842       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3843 
3844       if (ILE && Field) {
3845         InitList = true;
3846         InitListFieldDecl = Field;
3847         InitFieldIndex.clear();
3848         CheckInitListExpr(ILE);
3849       } else {
3850         InitList = false;
3851         Visit(E);
3852       }
3853 
3854       if (Field)
3855         Decls.erase(Field);
3856       if (BaseClass)
3857         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3858     }
3859 
3860     void VisitMemberExpr(MemberExpr *ME) {
3861       // All uses of unbounded reference fields will warn.
3862       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3863     }
3864 
3865     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3866       if (E->getCastKind() == CK_LValueToRValue) {
3867         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3868         return;
3869       }
3870 
3871       Inherited::VisitImplicitCastExpr(E);
3872     }
3873 
3874     void VisitCXXConstructExpr(CXXConstructExpr *E) {
3875       if (E->getConstructor()->isCopyConstructor()) {
3876         Expr *ArgExpr = E->getArg(0);
3877         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3878           if (ILE->getNumInits() == 1)
3879             ArgExpr = ILE->getInit(0);
3880         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3881           if (ICE->getCastKind() == CK_NoOp)
3882             ArgExpr = ICE->getSubExpr();
3883         HandleValue(ArgExpr, false /*AddressOf*/);
3884         return;
3885       }
3886       Inherited::VisitCXXConstructExpr(E);
3887     }
3888 
3889     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3890       Expr *Callee = E->getCallee();
3891       if (isa<MemberExpr>(Callee)) {
3892         HandleValue(Callee, false /*AddressOf*/);
3893         for (auto *Arg : E->arguments())
3894           Visit(Arg);
3895         return;
3896       }
3897 
3898       Inherited::VisitCXXMemberCallExpr(E);
3899     }
3900 
3901     void VisitCallExpr(CallExpr *E) {
3902       // Treat std::move as a use.
3903       if (E->isCallToStdMove()) {
3904         HandleValue(E->getArg(0), /*AddressOf=*/false);
3905         return;
3906       }
3907 
3908       Inherited::VisitCallExpr(E);
3909     }
3910 
3911     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3912       Expr *Callee = E->getCallee();
3913 
3914       if (isa<UnresolvedLookupExpr>(Callee))
3915         return Inherited::VisitCXXOperatorCallExpr(E);
3916 
3917       Visit(Callee);
3918       for (auto *Arg : E->arguments())
3919         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3920     }
3921 
3922     void VisitBinaryOperator(BinaryOperator *E) {
3923       // If a field assignment is detected, remove the field from the
3924       // uninitiailized field set.
3925       if (E->getOpcode() == BO_Assign)
3926         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3927           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3928             if (!FD->getType()->isReferenceType())
3929               DeclsToRemove.push_back(FD);
3930 
3931       if (E->isCompoundAssignmentOp()) {
3932         HandleValue(E->getLHS(), false /*AddressOf*/);
3933         Visit(E->getRHS());
3934         return;
3935       }
3936 
3937       Inherited::VisitBinaryOperator(E);
3938     }
3939 
3940     void VisitUnaryOperator(UnaryOperator *E) {
3941       if (E->isIncrementDecrementOp()) {
3942         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3943         return;
3944       }
3945       if (E->getOpcode() == UO_AddrOf) {
3946         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3947           HandleValue(ME->getBase(), true /*AddressOf*/);
3948           return;
3949         }
3950       }
3951 
3952       Inherited::VisitUnaryOperator(E);
3953     }
3954   };
3955 
3956   // Diagnose value-uses of fields to initialize themselves, e.g.
3957   //   foo(foo)
3958   // where foo is not also a parameter to the constructor.
3959   // Also diagnose across field uninitialized use such as
3960   //   x(y), y(x)
3961   // TODO: implement -Wuninitialized and fold this into that framework.
3962   static void DiagnoseUninitializedFields(
3963       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3964 
3965     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3966                                            Constructor->getLocation())) {
3967       return;
3968     }
3969 
3970     if (Constructor->isInvalidDecl())
3971       return;
3972 
3973     const CXXRecordDecl *RD = Constructor->getParent();
3974 
3975     if (RD->isDependentContext())
3976       return;
3977 
3978     // Holds fields that are uninitialized.
3979     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3980 
3981     // At the beginning, all fields are uninitialized.
3982     for (auto *I : RD->decls()) {
3983       if (auto *FD = dyn_cast<FieldDecl>(I)) {
3984         UninitializedFields.insert(FD);
3985       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3986         UninitializedFields.insert(IFD->getAnonField());
3987       }
3988     }
3989 
3990     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3991     for (const auto &I : RD->bases())
3992       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3993 
3994     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3995       return;
3996 
3997     UninitializedFieldVisitor UninitializedChecker(SemaRef,
3998                                                    UninitializedFields,
3999                                                    UninitializedBaseClasses);
4000 
4001     for (const auto *FieldInit : Constructor->inits()) {
4002       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4003         break;
4004 
4005       Expr *InitExpr = FieldInit->getInit();
4006       if (!InitExpr)
4007         continue;
4008 
4009       if (CXXDefaultInitExpr *Default =
4010               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
4011         InitExpr = Default->getExpr();
4012         if (!InitExpr)
4013           continue;
4014         // In class initializers will point to the constructor.
4015         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
4016                                               FieldInit->getAnyMember(),
4017                                               FieldInit->getBaseClass());
4018       } else {
4019         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
4020                                               FieldInit->getAnyMember(),
4021                                               FieldInit->getBaseClass());
4022       }
4023     }
4024   }
4025 } // namespace
4026 
4027 void Sema::ActOnStartCXXInClassMemberInitializer() {
4028   // Create a synthetic function scope to represent the call to the constructor
4029   // that notionally surrounds a use of this initializer.
4030   PushFunctionScope();
4031 }
4032 
4033 void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) {
4034   if (!D.isFunctionDeclarator())
4035     return;
4036   auto &FTI = D.getFunctionTypeInfo();
4037   if (!FTI.Params)
4038     return;
4039   for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
4040                                                           FTI.NumParams)) {
4041     auto *ParamDecl = cast<NamedDecl>(Param.Param);
4042     if (ParamDecl->getDeclName())
4043       PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
4044   }
4045 }
4046 
4047 ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {
4048   return ActOnRequiresClause(ConstraintExpr);
4049 }
4050 
4051 ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) {
4052   if (ConstraintExpr.isInvalid())
4053     return ExprError();
4054 
4055   ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr);
4056   if (ConstraintExpr.isInvalid())
4057     return ExprError();
4058 
4059   if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),
4060                                       UPPC_RequiresClause))
4061     return ExprError();
4062 
4063   return ConstraintExpr;
4064 }
4065 
4066 ExprResult Sema::ConvertMemberDefaultInitExpression(FieldDecl *FD,
4067                                                     Expr *InitExpr,
4068                                                     SourceLocation InitLoc) {
4069   InitializedEntity Entity =
4070       InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
4071   InitializationKind Kind =
4072       FD->getInClassInitStyle() == ICIS_ListInit
4073           ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
4074                                                  InitExpr->getBeginLoc(),
4075                                                  InitExpr->getEndLoc())
4076           : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
4077   InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4078   return Seq.Perform(*this, Entity, Kind, InitExpr);
4079 }
4080 
4081 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
4082                                                   SourceLocation InitLoc,
4083                                                   Expr *InitExpr) {
4084   // Pop the notional constructor scope we created earlier.
4085   PopFunctionScopeInfo(nullptr, D);
4086 
4087   FieldDecl *FD = dyn_cast<FieldDecl>(D);
4088   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
4089          "must set init style when field is created");
4090 
4091   if (!InitExpr) {
4092     D->setInvalidDecl();
4093     if (FD)
4094       FD->removeInClassInitializer();
4095     return;
4096   }
4097 
4098   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
4099     FD->setInvalidDecl();
4100     FD->removeInClassInitializer();
4101     return;
4102   }
4103 
4104   ExprResult Init = CorrectDelayedTyposInExpr(InitExpr, /*InitDecl=*/nullptr,
4105                                               /*RecoverUncorrectedTypos=*/true);
4106   assert(Init.isUsable() && "Init should at least have a RecoveryExpr");
4107   if (!FD->getType()->isDependentType() && !Init.get()->isTypeDependent()) {
4108     Init = ConvertMemberDefaultInitExpression(FD, Init.get(), InitLoc);
4109     // C++11 [class.base.init]p7:
4110     //   The initialization of each base and member constitutes a
4111     //   full-expression.
4112     if (!Init.isInvalid())
4113       Init = ActOnFinishFullExpr(Init.get(), /*DiscarededValue=*/false);
4114     if (Init.isInvalid()) {
4115       FD->setInvalidDecl();
4116       return;
4117     }
4118   }
4119 
4120   FD->setInClassInitializer(Init.get());
4121 }
4122 
4123 /// Find the direct and/or virtual base specifiers that
4124 /// correspond to the given base type, for use in base initialization
4125 /// within a constructor.
4126 static bool FindBaseInitializer(Sema &SemaRef,
4127                                 CXXRecordDecl *ClassDecl,
4128                                 QualType BaseType,
4129                                 const CXXBaseSpecifier *&DirectBaseSpec,
4130                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
4131   // First, check for a direct base class.
4132   DirectBaseSpec = nullptr;
4133   for (const auto &Base : ClassDecl->bases()) {
4134     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
4135       // We found a direct base of this type. That's what we're
4136       // initializing.
4137       DirectBaseSpec = &Base;
4138       break;
4139     }
4140   }
4141 
4142   // Check for a virtual base class.
4143   // FIXME: We might be able to short-circuit this if we know in advance that
4144   // there are no virtual bases.
4145   VirtualBaseSpec = nullptr;
4146   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4147     // We haven't found a base yet; search the class hierarchy for a
4148     // virtual base class.
4149     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4150                        /*DetectVirtual=*/false);
4151     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4152                               SemaRef.Context.getTypeDeclType(ClassDecl),
4153                               BaseType, Paths)) {
4154       for (CXXBasePaths::paths_iterator Path = Paths.begin();
4155            Path != Paths.end(); ++Path) {
4156         if (Path->back().Base->isVirtual()) {
4157           VirtualBaseSpec = Path->back().Base;
4158           break;
4159         }
4160       }
4161     }
4162   }
4163 
4164   return DirectBaseSpec || VirtualBaseSpec;
4165 }
4166 
4167 MemInitResult
4168 Sema::ActOnMemInitializer(Decl *ConstructorD,
4169                           Scope *S,
4170                           CXXScopeSpec &SS,
4171                           IdentifierInfo *MemberOrBase,
4172                           ParsedType TemplateTypeTy,
4173                           const DeclSpec &DS,
4174                           SourceLocation IdLoc,
4175                           Expr *InitList,
4176                           SourceLocation EllipsisLoc) {
4177   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4178                              DS, IdLoc, InitList,
4179                              EllipsisLoc);
4180 }
4181 
4182 MemInitResult
4183 Sema::ActOnMemInitializer(Decl *ConstructorD,
4184                           Scope *S,
4185                           CXXScopeSpec &SS,
4186                           IdentifierInfo *MemberOrBase,
4187                           ParsedType TemplateTypeTy,
4188                           const DeclSpec &DS,
4189                           SourceLocation IdLoc,
4190                           SourceLocation LParenLoc,
4191                           ArrayRef<Expr *> Args,
4192                           SourceLocation RParenLoc,
4193                           SourceLocation EllipsisLoc) {
4194   Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4195   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4196                              DS, IdLoc, List, EllipsisLoc);
4197 }
4198 
4199 namespace {
4200 
4201 // Callback to only accept typo corrections that can be a valid C++ member
4202 // initializer: either a non-static field member or a base class.
4203 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4204 public:
4205   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4206       : ClassDecl(ClassDecl) {}
4207 
4208   bool ValidateCandidate(const TypoCorrection &candidate) override {
4209     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4210       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4211         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4212       return isa<TypeDecl>(ND);
4213     }
4214     return false;
4215   }
4216 
4217   std::unique_ptr<CorrectionCandidateCallback> clone() override {
4218     return std::make_unique<MemInitializerValidatorCCC>(*this);
4219   }
4220 
4221 private:
4222   CXXRecordDecl *ClassDecl;
4223 };
4224 
4225 }
4226 
4227 bool Sema::DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc,
4228                                              RecordDecl *ClassDecl,
4229                                              const IdentifierInfo *Name) {
4230   DeclContextLookupResult Result = ClassDecl->lookup(Name);
4231   DeclContextLookupResult::iterator Found =
4232       llvm::find_if(Result, [this](const NamedDecl *Elem) {
4233         return isa<FieldDecl, IndirectFieldDecl>(Elem) &&
4234                Elem->isPlaceholderVar(getLangOpts());
4235       });
4236   // We did not find a placeholder variable
4237   if (Found == Result.end())
4238     return false;
4239   Diag(Loc, diag::err_using_placeholder_variable) << Name;
4240   for (DeclContextLookupResult::iterator It = Found; It != Result.end(); It++) {
4241     const NamedDecl *ND = *It;
4242     if (ND->getDeclContext() != ND->getDeclContext())
4243       break;
4244     if (isa<FieldDecl, IndirectFieldDecl>(ND) &&
4245         ND->isPlaceholderVar(getLangOpts()))
4246       Diag(ND->getLocation(), diag::note_reference_placeholder) << ND;
4247   }
4248   return true;
4249 }
4250 
4251 ValueDecl *
4252 Sema::tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl,
4253                                     const IdentifierInfo *MemberOrBase) {
4254   ValueDecl *ND = nullptr;
4255   for (auto *D : ClassDecl->lookup(MemberOrBase)) {
4256     if (isa<FieldDecl, IndirectFieldDecl>(D)) {
4257       bool IsPlaceholder = D->isPlaceholderVar(getLangOpts());
4258       if (ND) {
4259         if (IsPlaceholder && D->getDeclContext() == ND->getDeclContext())
4260           return nullptr;
4261         break;
4262       }
4263       if (!IsPlaceholder)
4264         return cast<ValueDecl>(D);
4265       ND = cast<ValueDecl>(D);
4266     }
4267   }
4268   return ND;
4269 }
4270 
4271 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4272                                              CXXScopeSpec &SS,
4273                                              ParsedType TemplateTypeTy,
4274                                              IdentifierInfo *MemberOrBase) {
4275   if (SS.getScopeRep() || TemplateTypeTy)
4276     return nullptr;
4277   return tryLookupUnambiguousFieldDecl(ClassDecl, MemberOrBase);
4278 }
4279 
4280 MemInitResult
4281 Sema::BuildMemInitializer(Decl *ConstructorD,
4282                           Scope *S,
4283                           CXXScopeSpec &SS,
4284                           IdentifierInfo *MemberOrBase,
4285                           ParsedType TemplateTypeTy,
4286                           const DeclSpec &DS,
4287                           SourceLocation IdLoc,
4288                           Expr *Init,
4289                           SourceLocation EllipsisLoc) {
4290   ExprResult Res = CorrectDelayedTyposInExpr(Init, /*InitDecl=*/nullptr,
4291                                              /*RecoverUncorrectedTypos=*/true);
4292   if (!Res.isUsable())
4293     return true;
4294   Init = Res.get();
4295 
4296   if (!ConstructorD)
4297     return true;
4298 
4299   AdjustDeclIfTemplate(ConstructorD);
4300 
4301   CXXConstructorDecl *Constructor
4302     = dyn_cast<CXXConstructorDecl>(ConstructorD);
4303   if (!Constructor) {
4304     // The user wrote a constructor initializer on a function that is
4305     // not a C++ constructor. Ignore the error for now, because we may
4306     // have more member initializers coming; we'll diagnose it just
4307     // once in ActOnMemInitializers.
4308     return true;
4309   }
4310 
4311   CXXRecordDecl *ClassDecl = Constructor->getParent();
4312 
4313   // C++ [class.base.init]p2:
4314   //   Names in a mem-initializer-id are looked up in the scope of the
4315   //   constructor's class and, if not found in that scope, are looked
4316   //   up in the scope containing the constructor's definition.
4317   //   [Note: if the constructor's class contains a member with the
4318   //   same name as a direct or virtual base class of the class, a
4319   //   mem-initializer-id naming the member or base class and composed
4320   //   of a single identifier refers to the class member. A
4321   //   mem-initializer-id for the hidden base class may be specified
4322   //   using a qualified name. ]
4323 
4324   // Look for a member, first.
4325   if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4326           ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4327     if (EllipsisLoc.isValid())
4328       Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4329           << MemberOrBase
4330           << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4331 
4332     return BuildMemberInitializer(Member, Init, IdLoc);
4333   }
4334   // It didn't name a member, so see if it names a class.
4335   QualType BaseType;
4336   TypeSourceInfo *TInfo = nullptr;
4337 
4338   if (TemplateTypeTy) {
4339     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4340     if (BaseType.isNull())
4341       return true;
4342   } else if (DS.getTypeSpecType() == TST_decltype) {
4343     BaseType = BuildDecltypeType(DS.getRepAsExpr());
4344   } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4345     Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4346     return true;
4347   } else if (DS.getTypeSpecType() == TST_typename_pack_indexing) {
4348     BaseType =
4349         BuildPackIndexingType(DS.getRepAsType().get(), DS.getPackIndexingExpr(),
4350                               DS.getBeginLoc(), DS.getEllipsisLoc());
4351   } else {
4352     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4353     LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
4354 
4355     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4356     if (!TyD) {
4357       if (R.isAmbiguous()) return true;
4358 
4359       // We don't want access-control diagnostics here.
4360       R.suppressDiagnostics();
4361 
4362       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4363         bool NotUnknownSpecialization = false;
4364         DeclContext *DC = computeDeclContext(SS, false);
4365         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4366           NotUnknownSpecialization = !Record->hasAnyDependentBases();
4367 
4368         if (!NotUnknownSpecialization) {
4369           // When the scope specifier can refer to a member of an unknown
4370           // specialization, we take it as a type name.
4371           BaseType = CheckTypenameType(
4372               ElaboratedTypeKeyword::None, SourceLocation(),
4373               SS.getWithLocInContext(Context), *MemberOrBase, IdLoc);
4374           if (BaseType.isNull())
4375             return true;
4376 
4377           TInfo = Context.CreateTypeSourceInfo(BaseType);
4378           DependentNameTypeLoc TL =
4379               TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4380           if (!TL.isNull()) {
4381             TL.setNameLoc(IdLoc);
4382             TL.setElaboratedKeywordLoc(SourceLocation());
4383             TL.setQualifierLoc(SS.getWithLocInContext(Context));
4384           }
4385 
4386           R.clear();
4387           R.setLookupName(MemberOrBase);
4388         }
4389       }
4390 
4391       if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) {
4392         if (auto UnqualifiedBase = R.getAsSingle<ClassTemplateDecl>()) {
4393           auto *TempSpec = cast<TemplateSpecializationType>(
4394               UnqualifiedBase->getInjectedClassNameSpecialization());
4395           TemplateName TN = TempSpec->getTemplateName();
4396           for (auto const &Base : ClassDecl->bases()) {
4397             auto BaseTemplate =
4398                 Base.getType()->getAs<TemplateSpecializationType>();
4399             if (BaseTemplate && Context.hasSameTemplateName(
4400                                     BaseTemplate->getTemplateName(), TN)) {
4401               Diag(IdLoc, diag::ext_unqualified_base_class)
4402                   << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4403               BaseType = Base.getType();
4404               break;
4405             }
4406           }
4407         }
4408       }
4409 
4410       // If no results were found, try to correct typos.
4411       TypoCorrection Corr;
4412       MemInitializerValidatorCCC CCC(ClassDecl);
4413       if (R.empty() && BaseType.isNull() &&
4414           (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4415                               CCC, CTK_ErrorRecovery, ClassDecl))) {
4416         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4417           // We have found a non-static data member with a similar
4418           // name to what was typed; complain and initialize that
4419           // member.
4420           diagnoseTypo(Corr,
4421                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
4422                          << MemberOrBase << true);
4423           return BuildMemberInitializer(Member, Init, IdLoc);
4424         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4425           const CXXBaseSpecifier *DirectBaseSpec;
4426           const CXXBaseSpecifier *VirtualBaseSpec;
4427           if (FindBaseInitializer(*this, ClassDecl,
4428                                   Context.getTypeDeclType(Type),
4429                                   DirectBaseSpec, VirtualBaseSpec)) {
4430             // We have found a direct or virtual base class with a
4431             // similar name to what was typed; complain and initialize
4432             // that base class.
4433             diagnoseTypo(Corr,
4434                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
4435                            << MemberOrBase << false,
4436                          PDiag() /*Suppress note, we provide our own.*/);
4437 
4438             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4439                                                               : VirtualBaseSpec;
4440             Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4441                 << BaseSpec->getType() << BaseSpec->getSourceRange();
4442 
4443             TyD = Type;
4444           }
4445         }
4446       }
4447 
4448       if (!TyD && BaseType.isNull()) {
4449         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4450           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4451         return true;
4452       }
4453     }
4454 
4455     if (BaseType.isNull()) {
4456       BaseType = getElaboratedType(ElaboratedTypeKeyword::None, SS,
4457                                    Context.getTypeDeclType(TyD));
4458       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4459       TInfo = Context.CreateTypeSourceInfo(BaseType);
4460       ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
4461       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4462       TL.setElaboratedKeywordLoc(SourceLocation());
4463       TL.setQualifierLoc(SS.getWithLocInContext(Context));
4464     }
4465   }
4466 
4467   if (!TInfo)
4468     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4469 
4470   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4471 }
4472 
4473 MemInitResult
4474 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4475                              SourceLocation IdLoc) {
4476   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4477   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4478   assert((DirectMember || IndirectMember) &&
4479          "Member must be a FieldDecl or IndirectFieldDecl");
4480 
4481   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4482     return true;
4483 
4484   if (Member->isInvalidDecl())
4485     return true;
4486 
4487   MultiExprArg Args;
4488   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4489     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4490   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4491     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4492   } else {
4493     // Template instantiation doesn't reconstruct ParenListExprs for us.
4494     Args = Init;
4495   }
4496 
4497   SourceRange InitRange = Init->getSourceRange();
4498 
4499   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4500     // Can't check initialization for a member of dependent type or when
4501     // any of the arguments are type-dependent expressions.
4502     DiscardCleanupsInEvaluationContext();
4503   } else {
4504     bool InitList = false;
4505     if (isa<InitListExpr>(Init)) {
4506       InitList = true;
4507       Args = Init;
4508     }
4509 
4510     // Initialize the member.
4511     InitializedEntity MemberEntity =
4512       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4513                    : InitializedEntity::InitializeMember(IndirectMember,
4514                                                          nullptr);
4515     InitializationKind Kind =
4516         InitList ? InitializationKind::CreateDirectList(
4517                        IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4518                  : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4519                                                     InitRange.getEnd());
4520 
4521     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4522     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4523                                             nullptr);
4524     if (!MemberInit.isInvalid()) {
4525       // C++11 [class.base.init]p7:
4526       //   The initialization of each base and member constitutes a
4527       //   full-expression.
4528       MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4529                                        /*DiscardedValue*/ false);
4530     }
4531 
4532     if (MemberInit.isInvalid()) {
4533       // Args were sensible expressions but we couldn't initialize the member
4534       // from them. Preserve them in a RecoveryExpr instead.
4535       Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4536                                 Member->getType())
4537                  .get();
4538       if (!Init)
4539         return true;
4540     } else {
4541       Init = MemberInit.get();
4542     }
4543   }
4544 
4545   if (DirectMember) {
4546     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4547                                             InitRange.getBegin(), Init,
4548                                             InitRange.getEnd());
4549   } else {
4550     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4551                                             InitRange.getBegin(), Init,
4552                                             InitRange.getEnd());
4553   }
4554 }
4555 
4556 MemInitResult
4557 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4558                                  CXXRecordDecl *ClassDecl) {
4559   SourceLocation NameLoc = TInfo->getTypeLoc().getSourceRange().getBegin();
4560   if (!LangOpts.CPlusPlus11)
4561     return Diag(NameLoc, diag::err_delegating_ctor)
4562            << TInfo->getTypeLoc().getSourceRange();
4563   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4564 
4565   bool InitList = true;
4566   MultiExprArg Args = Init;
4567   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4568     InitList = false;
4569     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4570   }
4571 
4572   SourceRange InitRange = Init->getSourceRange();
4573   // Initialize the object.
4574   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4575                                      QualType(ClassDecl->getTypeForDecl(), 0));
4576   InitializationKind Kind =
4577       InitList ? InitializationKind::CreateDirectList(
4578                      NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4579                : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4580                                                   InitRange.getEnd());
4581   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4582   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4583                                               Args, nullptr);
4584   if (!DelegationInit.isInvalid()) {
4585     assert((DelegationInit.get()->containsErrors() ||
4586             cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&
4587            "Delegating constructor with no target?");
4588 
4589     // C++11 [class.base.init]p7:
4590     //   The initialization of each base and member constitutes a
4591     //   full-expression.
4592     DelegationInit = ActOnFinishFullExpr(
4593         DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4594   }
4595 
4596   if (DelegationInit.isInvalid()) {
4597     DelegationInit =
4598         CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4599                            QualType(ClassDecl->getTypeForDecl(), 0));
4600     if (DelegationInit.isInvalid())
4601       return true;
4602   } else {
4603     // If we are in a dependent context, template instantiation will
4604     // perform this type-checking again. Just save the arguments that we
4605     // received in a ParenListExpr.
4606     // FIXME: This isn't quite ideal, since our ASTs don't capture all
4607     // of the information that we have about the base
4608     // initializer. However, deconstructing the ASTs is a dicey process,
4609     // and this approach is far more likely to get the corner cases right.
4610     if (CurContext->isDependentContext())
4611       DelegationInit = Init;
4612   }
4613 
4614   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4615                                           DelegationInit.getAs<Expr>(),
4616                                           InitRange.getEnd());
4617 }
4618 
4619 MemInitResult
4620 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4621                            Expr *Init, CXXRecordDecl *ClassDecl,
4622                            SourceLocation EllipsisLoc) {
4623   SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getBeginLoc();
4624 
4625   if (!BaseType->isDependentType() && !BaseType->isRecordType())
4626     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4627            << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
4628 
4629   // C++ [class.base.init]p2:
4630   //   [...] Unless the mem-initializer-id names a nonstatic data
4631   //   member of the constructor's class or a direct or virtual base
4632   //   of that class, the mem-initializer is ill-formed. A
4633   //   mem-initializer-list can initialize a base class using any
4634   //   name that denotes that base class type.
4635 
4636   // We can store the initializers in "as-written" form and delay analysis until
4637   // instantiation if the constructor is dependent. But not for dependent
4638   // (broken) code in a non-template! SetCtorInitializers does not expect this.
4639   bool Dependent = CurContext->isDependentContext() &&
4640                    (BaseType->isDependentType() || Init->isTypeDependent());
4641 
4642   SourceRange InitRange = Init->getSourceRange();
4643   if (EllipsisLoc.isValid()) {
4644     // This is a pack expansion.
4645     if (!BaseType->containsUnexpandedParameterPack())  {
4646       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4647         << SourceRange(BaseLoc, InitRange.getEnd());
4648 
4649       EllipsisLoc = SourceLocation();
4650     }
4651   } else {
4652     // Check for any unexpanded parameter packs.
4653     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4654       return true;
4655 
4656     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4657       return true;
4658   }
4659 
4660   // Check for direct and virtual base classes.
4661   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4662   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4663   if (!Dependent) {
4664     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4665                                        BaseType))
4666       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4667 
4668     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4669                         VirtualBaseSpec);
4670 
4671     // C++ [base.class.init]p2:
4672     // Unless the mem-initializer-id names a nonstatic data member of the
4673     // constructor's class or a direct or virtual base of that class, the
4674     // mem-initializer is ill-formed.
4675     if (!DirectBaseSpec && !VirtualBaseSpec) {
4676       // If the class has any dependent bases, then it's possible that
4677       // one of those types will resolve to the same type as
4678       // BaseType. Therefore, just treat this as a dependent base
4679       // class initialization.  FIXME: Should we try to check the
4680       // initialization anyway? It seems odd.
4681       if (ClassDecl->hasAnyDependentBases())
4682         Dependent = true;
4683       else
4684         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4685                << BaseType << Context.getTypeDeclType(ClassDecl)
4686                << BaseTInfo->getTypeLoc().getSourceRange();
4687     }
4688   }
4689 
4690   if (Dependent) {
4691     DiscardCleanupsInEvaluationContext();
4692 
4693     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4694                                             /*IsVirtual=*/false,
4695                                             InitRange.getBegin(), Init,
4696                                             InitRange.getEnd(), EllipsisLoc);
4697   }
4698 
4699   // C++ [base.class.init]p2:
4700   //   If a mem-initializer-id is ambiguous because it designates both
4701   //   a direct non-virtual base class and an inherited virtual base
4702   //   class, the mem-initializer is ill-formed.
4703   if (DirectBaseSpec && VirtualBaseSpec)
4704     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4705       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4706 
4707   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4708   if (!BaseSpec)
4709     BaseSpec = VirtualBaseSpec;
4710 
4711   // Initialize the base.
4712   bool InitList = true;
4713   MultiExprArg Args = Init;
4714   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4715     InitList = false;
4716     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4717   }
4718 
4719   InitializedEntity BaseEntity =
4720     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4721   InitializationKind Kind =
4722       InitList ? InitializationKind::CreateDirectList(BaseLoc)
4723                : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4724                                                   InitRange.getEnd());
4725   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4726   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4727   if (!BaseInit.isInvalid()) {
4728     // C++11 [class.base.init]p7:
4729     //   The initialization of each base and member constitutes a
4730     //   full-expression.
4731     BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4732                                    /*DiscardedValue*/ false);
4733   }
4734 
4735   if (BaseInit.isInvalid()) {
4736     BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(),
4737                                   Args, BaseType);
4738     if (BaseInit.isInvalid())
4739       return true;
4740   } else {
4741     // If we are in a dependent context, template instantiation will
4742     // perform this type-checking again. Just save the arguments that we
4743     // received in a ParenListExpr.
4744     // FIXME: This isn't quite ideal, since our ASTs don't capture all
4745     // of the information that we have about the base
4746     // initializer. However, deconstructing the ASTs is a dicey process,
4747     // and this approach is far more likely to get the corner cases right.
4748     if (CurContext->isDependentContext())
4749       BaseInit = Init;
4750   }
4751 
4752   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4753                                           BaseSpec->isVirtual(),
4754                                           InitRange.getBegin(),
4755                                           BaseInit.getAs<Expr>(),
4756                                           InitRange.getEnd(), EllipsisLoc);
4757 }
4758 
4759 // Create a static_cast\<T&&>(expr).
4760 static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
4761   QualType TargetType =
4762       SemaRef.BuildReferenceType(E->getType(), /*SpelledAsLValue*/ false,
4763                                  SourceLocation(), DeclarationName());
4764   SourceLocation ExprLoc = E->getBeginLoc();
4765   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4766       TargetType, ExprLoc);
4767 
4768   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4769                                    SourceRange(ExprLoc, ExprLoc),
4770                                    E->getSourceRange()).get();
4771 }
4772 
4773 /// ImplicitInitializerKind - How an implicit base or member initializer should
4774 /// initialize its base or member.
4775 enum ImplicitInitializerKind {
4776   IIK_Default,
4777   IIK_Copy,
4778   IIK_Move,
4779   IIK_Inherit
4780 };
4781 
4782 static bool
4783 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4784                              ImplicitInitializerKind ImplicitInitKind,
4785                              CXXBaseSpecifier *BaseSpec,
4786                              bool IsInheritedVirtualBase,
4787                              CXXCtorInitializer *&CXXBaseInit) {
4788   InitializedEntity InitEntity
4789     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4790                                         IsInheritedVirtualBase);
4791 
4792   ExprResult BaseInit;
4793 
4794   switch (ImplicitInitKind) {
4795   case IIK_Inherit:
4796   case IIK_Default: {
4797     InitializationKind InitKind
4798       = InitializationKind::CreateDefault(Constructor->getLocation());
4799     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, std::nullopt);
4800     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, std::nullopt);
4801     break;
4802   }
4803 
4804   case IIK_Move:
4805   case IIK_Copy: {
4806     bool Moving = ImplicitInitKind == IIK_Move;
4807     ParmVarDecl *Param = Constructor->getParamDecl(0);
4808     QualType ParamType = Param->getType().getNonReferenceType();
4809 
4810     Expr *CopyCtorArg =
4811       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4812                           SourceLocation(), Param, false,
4813                           Constructor->getLocation(), ParamType,
4814                           VK_LValue, nullptr);
4815 
4816     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4817 
4818     // Cast to the base class to avoid ambiguities.
4819     QualType ArgTy =
4820       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4821                                        ParamType.getQualifiers());
4822 
4823     if (Moving) {
4824       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4825     }
4826 
4827     CXXCastPath BasePath;
4828     BasePath.push_back(BaseSpec);
4829     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4830                                             CK_UncheckedDerivedToBase,
4831                                             Moving ? VK_XValue : VK_LValue,
4832                                             &BasePath).get();
4833 
4834     InitializationKind InitKind
4835       = InitializationKind::CreateDirect(Constructor->getLocation(),
4836                                          SourceLocation(), SourceLocation());
4837     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4838     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4839     break;
4840   }
4841   }
4842 
4843   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4844   if (BaseInit.isInvalid())
4845     return true;
4846 
4847   CXXBaseInit =
4848     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4849                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4850                                                         SourceLocation()),
4851                                              BaseSpec->isVirtual(),
4852                                              SourceLocation(),
4853                                              BaseInit.getAs<Expr>(),
4854                                              SourceLocation(),
4855                                              SourceLocation());
4856 
4857   return false;
4858 }
4859 
4860 static bool RefersToRValueRef(Expr *MemRef) {
4861   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4862   return Referenced->getType()->isRValueReferenceType();
4863 }
4864 
4865 static bool
4866 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4867                                ImplicitInitializerKind ImplicitInitKind,
4868                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4869                                CXXCtorInitializer *&CXXMemberInit) {
4870   if (Field->isInvalidDecl())
4871     return true;
4872 
4873   SourceLocation Loc = Constructor->getLocation();
4874 
4875   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4876     bool Moving = ImplicitInitKind == IIK_Move;
4877     ParmVarDecl *Param = Constructor->getParamDecl(0);
4878     QualType ParamType = Param->getType().getNonReferenceType();
4879 
4880     // Suppress copying zero-width bitfields.
4881     if (Field->isZeroLengthBitField(SemaRef.Context))
4882       return false;
4883 
4884     Expr *MemberExprBase =
4885       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4886                           SourceLocation(), Param, false,
4887                           Loc, ParamType, VK_LValue, nullptr);
4888 
4889     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4890 
4891     if (Moving) {
4892       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4893     }
4894 
4895     // Build a reference to this field within the parameter.
4896     CXXScopeSpec SS;
4897     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4898                               Sema::LookupMemberName);
4899     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4900                                   : cast<ValueDecl>(Field), AS_public);
4901     MemberLookup.resolveKind();
4902     ExprResult CtorArg
4903       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4904                                          ParamType, Loc,
4905                                          /*IsArrow=*/false,
4906                                          SS,
4907                                          /*TemplateKWLoc=*/SourceLocation(),
4908                                          /*FirstQualifierInScope=*/nullptr,
4909                                          MemberLookup,
4910                                          /*TemplateArgs=*/nullptr,
4911                                          /*S*/nullptr);
4912     if (CtorArg.isInvalid())
4913       return true;
4914 
4915     // C++11 [class.copy]p15:
4916     //   - if a member m has rvalue reference type T&&, it is direct-initialized
4917     //     with static_cast<T&&>(x.m);
4918     if (RefersToRValueRef(CtorArg.get())) {
4919       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4920     }
4921 
4922     InitializedEntity Entity =
4923         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4924                                                        /*Implicit*/ true)
4925                  : InitializedEntity::InitializeMember(Field, nullptr,
4926                                                        /*Implicit*/ true);
4927 
4928     // Direct-initialize to use the copy constructor.
4929     InitializationKind InitKind =
4930       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4931 
4932     Expr *CtorArgE = CtorArg.getAs<Expr>();
4933     InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4934     ExprResult MemberInit =
4935         InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4936     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4937     if (MemberInit.isInvalid())
4938       return true;
4939 
4940     if (Indirect)
4941       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4942           SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4943     else
4944       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4945           SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4946     return false;
4947   }
4948 
4949   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4950          "Unhandled implicit init kind!");
4951 
4952   QualType FieldBaseElementType =
4953     SemaRef.Context.getBaseElementType(Field->getType());
4954 
4955   if (FieldBaseElementType->isRecordType()) {
4956     InitializedEntity InitEntity =
4957         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4958                                                        /*Implicit*/ true)
4959                  : InitializedEntity::InitializeMember(Field, nullptr,
4960                                                        /*Implicit*/ true);
4961     InitializationKind InitKind =
4962       InitializationKind::CreateDefault(Loc);
4963 
4964     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, std::nullopt);
4965     ExprResult MemberInit =
4966         InitSeq.Perform(SemaRef, InitEntity, InitKind, std::nullopt);
4967 
4968     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4969     if (MemberInit.isInvalid())
4970       return true;
4971 
4972     if (Indirect)
4973       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4974                                                                Indirect, Loc,
4975                                                                Loc,
4976                                                                MemberInit.get(),
4977                                                                Loc);
4978     else
4979       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4980                                                                Field, Loc, Loc,
4981                                                                MemberInit.get(),
4982                                                                Loc);
4983     return false;
4984   }
4985 
4986   if (!Field->getParent()->isUnion()) {
4987     if (FieldBaseElementType->isReferenceType()) {
4988       SemaRef.Diag(Constructor->getLocation(),
4989                    diag::err_uninitialized_member_in_ctor)
4990       << (int)Constructor->isImplicit()
4991       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4992       << 0 << Field->getDeclName();
4993       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4994       return true;
4995     }
4996 
4997     if (FieldBaseElementType.isConstQualified()) {
4998       SemaRef.Diag(Constructor->getLocation(),
4999                    diag::err_uninitialized_member_in_ctor)
5000       << (int)Constructor->isImplicit()
5001       << SemaRef.Context.getTagDeclType(Constructor->getParent())
5002       << 1 << Field->getDeclName();
5003       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
5004       return true;
5005     }
5006   }
5007 
5008   if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
5009     // ARC and Weak:
5010     //   Default-initialize Objective-C pointers to NULL.
5011     CXXMemberInit
5012       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
5013                                                  Loc, Loc,
5014                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
5015                                                  Loc);
5016     return false;
5017   }
5018 
5019   // Nothing to initialize.
5020   CXXMemberInit = nullptr;
5021   return false;
5022 }
5023 
5024 namespace {
5025 struct BaseAndFieldInfo {
5026   Sema &S;
5027   CXXConstructorDecl *Ctor;
5028   bool AnyErrorsInInits;
5029   ImplicitInitializerKind IIK;
5030   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
5031   SmallVector<CXXCtorInitializer*, 8> AllToInit;
5032   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
5033 
5034   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
5035     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
5036     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
5037     if (Ctor->getInheritedConstructor())
5038       IIK = IIK_Inherit;
5039     else if (Generated && Ctor->isCopyConstructor())
5040       IIK = IIK_Copy;
5041     else if (Generated && Ctor->isMoveConstructor())
5042       IIK = IIK_Move;
5043     else
5044       IIK = IIK_Default;
5045   }
5046 
5047   bool isImplicitCopyOrMove() const {
5048     switch (IIK) {
5049     case IIK_Copy:
5050     case IIK_Move:
5051       return true;
5052 
5053     case IIK_Default:
5054     case IIK_Inherit:
5055       return false;
5056     }
5057 
5058     llvm_unreachable("Invalid ImplicitInitializerKind!");
5059   }
5060 
5061   bool addFieldInitializer(CXXCtorInitializer *Init) {
5062     AllToInit.push_back(Init);
5063 
5064     // Check whether this initializer makes the field "used".
5065     if (Init->getInit()->HasSideEffects(S.Context))
5066       S.UnusedPrivateFields.remove(Init->getAnyMember());
5067 
5068     return false;
5069   }
5070 
5071   bool isInactiveUnionMember(FieldDecl *Field) {
5072     RecordDecl *Record = Field->getParent();
5073     if (!Record->isUnion())
5074       return false;
5075 
5076     if (FieldDecl *Active =
5077             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
5078       return Active != Field->getCanonicalDecl();
5079 
5080     // In an implicit copy or move constructor, ignore any in-class initializer.
5081     if (isImplicitCopyOrMove())
5082       return true;
5083 
5084     // If there's no explicit initialization, the field is active only if it
5085     // has an in-class initializer...
5086     if (Field->hasInClassInitializer())
5087       return false;
5088     // ... or it's an anonymous struct or union whose class has an in-class
5089     // initializer.
5090     if (!Field->isAnonymousStructOrUnion())
5091       return true;
5092     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
5093     return !FieldRD->hasInClassInitializer();
5094   }
5095 
5096   /// Determine whether the given field is, or is within, a union member
5097   /// that is inactive (because there was an initializer given for a different
5098   /// member of the union, or because the union was not initialized at all).
5099   bool isWithinInactiveUnionMember(FieldDecl *Field,
5100                                    IndirectFieldDecl *Indirect) {
5101     if (!Indirect)
5102       return isInactiveUnionMember(Field);
5103 
5104     for (auto *C : Indirect->chain()) {
5105       FieldDecl *Field = dyn_cast<FieldDecl>(C);
5106       if (Field && isInactiveUnionMember(Field))
5107         return true;
5108     }
5109     return false;
5110   }
5111 };
5112 }
5113 
5114 /// Determine whether the given type is an incomplete or zero-lenfgth
5115 /// array type.
5116 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
5117   if (T->isIncompleteArrayType())
5118     return true;
5119 
5120   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
5121     if (ArrayT->isZeroSize())
5122       return true;
5123 
5124     T = ArrayT->getElementType();
5125   }
5126 
5127   return false;
5128 }
5129 
5130 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
5131                                     FieldDecl *Field,
5132                                     IndirectFieldDecl *Indirect = nullptr) {
5133   if (Field->isInvalidDecl())
5134     return false;
5135 
5136   // Overwhelmingly common case: we have a direct initializer for this field.
5137   if (CXXCtorInitializer *Init =
5138           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
5139     return Info.addFieldInitializer(Init);
5140 
5141   // C++11 [class.base.init]p8:
5142   //   if the entity is a non-static data member that has a
5143   //   brace-or-equal-initializer and either
5144   //   -- the constructor's class is a union and no other variant member of that
5145   //      union is designated by a mem-initializer-id or
5146   //   -- the constructor's class is not a union, and, if the entity is a member
5147   //      of an anonymous union, no other member of that union is designated by
5148   //      a mem-initializer-id,
5149   //   the entity is initialized as specified in [dcl.init].
5150   //
5151   // We also apply the same rules to handle anonymous structs within anonymous
5152   // unions.
5153   if (Info.isWithinInactiveUnionMember(Field, Indirect))
5154     return false;
5155 
5156   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
5157     ExprResult DIE =
5158         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
5159     if (DIE.isInvalid())
5160       return true;
5161 
5162     auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
5163     SemaRef.checkInitializerLifetime(Entity, DIE.get());
5164 
5165     CXXCtorInitializer *Init;
5166     if (Indirect)
5167       Init = new (SemaRef.Context)
5168           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
5169                              SourceLocation(), DIE.get(), SourceLocation());
5170     else
5171       Init = new (SemaRef.Context)
5172           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
5173                              SourceLocation(), DIE.get(), SourceLocation());
5174     return Info.addFieldInitializer(Init);
5175   }
5176 
5177   // Don't initialize incomplete or zero-length arrays.
5178   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
5179     return false;
5180 
5181   // Don't try to build an implicit initializer if there were semantic
5182   // errors in any of the initializers (and therefore we might be
5183   // missing some that the user actually wrote).
5184   if (Info.AnyErrorsInInits)
5185     return false;
5186 
5187   CXXCtorInitializer *Init = nullptr;
5188   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
5189                                      Indirect, Init))
5190     return true;
5191 
5192   if (!Init)
5193     return false;
5194 
5195   return Info.addFieldInitializer(Init);
5196 }
5197 
5198 bool
5199 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5200                                CXXCtorInitializer *Initializer) {
5201   assert(Initializer->isDelegatingInitializer());
5202   Constructor->setNumCtorInitializers(1);
5203   CXXCtorInitializer **initializer =
5204     new (Context) CXXCtorInitializer*[1];
5205   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
5206   Constructor->setCtorInitializers(initializer);
5207 
5208   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
5209     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5210     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5211   }
5212 
5213   DelegatingCtorDecls.push_back(Constructor);
5214 
5215   DiagnoseUninitializedFields(*this, Constructor);
5216 
5217   return false;
5218 }
5219 
5220 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5221                                ArrayRef<CXXCtorInitializer *> Initializers) {
5222   if (Constructor->isDependentContext()) {
5223     // Just store the initializers as written, they will be checked during
5224     // instantiation.
5225     if (!Initializers.empty()) {
5226       Constructor->setNumCtorInitializers(Initializers.size());
5227       CXXCtorInitializer **baseOrMemberInitializers =
5228         new (Context) CXXCtorInitializer*[Initializers.size()];
5229       memcpy(baseOrMemberInitializers, Initializers.data(),
5230              Initializers.size() * sizeof(CXXCtorInitializer*));
5231       Constructor->setCtorInitializers(baseOrMemberInitializers);
5232     }
5233 
5234     // Let template instantiation know whether we had errors.
5235     if (AnyErrors)
5236       Constructor->setInvalidDecl();
5237 
5238     return false;
5239   }
5240 
5241   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5242 
5243   // We need to build the initializer AST according to order of construction
5244   // and not what user specified in the Initializers list.
5245   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5246   if (!ClassDecl)
5247     return true;
5248 
5249   bool HadError = false;
5250 
5251   for (unsigned i = 0; i < Initializers.size(); i++) {
5252     CXXCtorInitializer *Member = Initializers[i];
5253 
5254     if (Member->isBaseInitializer())
5255       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
5256     else {
5257       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5258 
5259       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5260         for (auto *C : F->chain()) {
5261           FieldDecl *FD = dyn_cast<FieldDecl>(C);
5262           if (FD && FD->getParent()->isUnion())
5263             Info.ActiveUnionMember.insert(std::make_pair(
5264                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5265         }
5266       } else if (FieldDecl *FD = Member->getMember()) {
5267         if (FD->getParent()->isUnion())
5268           Info.ActiveUnionMember.insert(std::make_pair(
5269               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5270       }
5271     }
5272   }
5273 
5274   // Keep track of the direct virtual bases.
5275   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
5276   for (auto &I : ClassDecl->bases()) {
5277     if (I.isVirtual())
5278       DirectVBases.insert(&I);
5279   }
5280 
5281   // Push virtual bases before others.
5282   for (auto &VBase : ClassDecl->vbases()) {
5283     if (CXXCtorInitializer *Value
5284         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
5285       // [class.base.init]p7, per DR257:
5286       //   A mem-initializer where the mem-initializer-id names a virtual base
5287       //   class is ignored during execution of a constructor of any class that
5288       //   is not the most derived class.
5289       if (ClassDecl->isAbstract()) {
5290         // FIXME: Provide a fixit to remove the base specifier. This requires
5291         // tracking the location of the associated comma for a base specifier.
5292         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5293           << VBase.getType() << ClassDecl;
5294         DiagnoseAbstractType(ClassDecl);
5295       }
5296 
5297       Info.AllToInit.push_back(Value);
5298     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5299       // [class.base.init]p8, per DR257:
5300       //   If a given [...] base class is not named by a mem-initializer-id
5301       //   [...] and the entity is not a virtual base class of an abstract
5302       //   class, then [...] the entity is default-initialized.
5303       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5304       CXXCtorInitializer *CXXBaseInit;
5305       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5306                                        &VBase, IsInheritedVirtualBase,
5307                                        CXXBaseInit)) {
5308         HadError = true;
5309         continue;
5310       }
5311 
5312       Info.AllToInit.push_back(CXXBaseInit);
5313     }
5314   }
5315 
5316   // Non-virtual bases.
5317   for (auto &Base : ClassDecl->bases()) {
5318     // Virtuals are in the virtual base list and already constructed.
5319     if (Base.isVirtual())
5320       continue;
5321 
5322     if (CXXCtorInitializer *Value
5323           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
5324       Info.AllToInit.push_back(Value);
5325     } else if (!AnyErrors) {
5326       CXXCtorInitializer *CXXBaseInit;
5327       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5328                                        &Base, /*IsInheritedVirtualBase=*/false,
5329                                        CXXBaseInit)) {
5330         HadError = true;
5331         continue;
5332       }
5333 
5334       Info.AllToInit.push_back(CXXBaseInit);
5335     }
5336   }
5337 
5338   // Fields.
5339   for (auto *Mem : ClassDecl->decls()) {
5340     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5341       // C++ [class.bit]p2:
5342       //   A declaration for a bit-field that omits the identifier declares an
5343       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
5344       //   initialized.
5345       if (F->isUnnamedBitField())
5346         continue;
5347 
5348       // If we're not generating the implicit copy/move constructor, then we'll
5349       // handle anonymous struct/union fields based on their individual
5350       // indirect fields.
5351       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5352         continue;
5353 
5354       if (CollectFieldInitializer(*this, Info, F))
5355         HadError = true;
5356       continue;
5357     }
5358 
5359     // Beyond this point, we only consider default initialization.
5360     if (Info.isImplicitCopyOrMove())
5361       continue;
5362 
5363     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5364       if (F->getType()->isIncompleteArrayType()) {
5365         assert(ClassDecl->hasFlexibleArrayMember() &&
5366                "Incomplete array type is not valid");
5367         continue;
5368       }
5369 
5370       // Initialize each field of an anonymous struct individually.
5371       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5372         HadError = true;
5373 
5374       continue;
5375     }
5376   }
5377 
5378   unsigned NumInitializers = Info.AllToInit.size();
5379   if (NumInitializers > 0) {
5380     Constructor->setNumCtorInitializers(NumInitializers);
5381     CXXCtorInitializer **baseOrMemberInitializers =
5382       new (Context) CXXCtorInitializer*[NumInitializers];
5383     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5384            NumInitializers * sizeof(CXXCtorInitializer*));
5385     Constructor->setCtorInitializers(baseOrMemberInitializers);
5386 
5387     // Constructors implicitly reference the base and member
5388     // destructors.
5389     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
5390                                            Constructor->getParent());
5391   }
5392 
5393   return HadError;
5394 }
5395 
5396 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5397   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5398     const RecordDecl *RD = RT->getDecl();
5399     if (RD->isAnonymousStructOrUnion()) {
5400       for (auto *Field : RD->fields())
5401         PopulateKeysForFields(Field, IdealInits);
5402       return;
5403     }
5404   }
5405   IdealInits.push_back(Field->getCanonicalDecl());
5406 }
5407 
5408 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5409   return Context.getCanonicalType(BaseType).getTypePtr();
5410 }
5411 
5412 static const void *GetKeyForMember(ASTContext &Context,
5413                                    CXXCtorInitializer *Member) {
5414   if (!Member->isAnyMemberInitializer())
5415     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5416 
5417   return Member->getAnyMember()->getCanonicalDecl();
5418 }
5419 
5420 static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag,
5421                                  const CXXCtorInitializer *Previous,
5422                                  const CXXCtorInitializer *Current) {
5423   if (Previous->isAnyMemberInitializer())
5424     Diag << 0 << Previous->getAnyMember();
5425   else
5426     Diag << 1 << Previous->getTypeSourceInfo()->getType();
5427 
5428   if (Current->isAnyMemberInitializer())
5429     Diag << 0 << Current->getAnyMember();
5430   else
5431     Diag << 1 << Current->getTypeSourceInfo()->getType();
5432 }
5433 
5434 static void DiagnoseBaseOrMemInitializerOrder(
5435     Sema &SemaRef, const CXXConstructorDecl *Constructor,
5436     ArrayRef<CXXCtorInitializer *> Inits) {
5437   if (Constructor->getDeclContext()->isDependentContext())
5438     return;
5439 
5440   // Don't check initializers order unless the warning is enabled at the
5441   // location of at least one initializer.
5442   bool ShouldCheckOrder = false;
5443   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5444     CXXCtorInitializer *Init = Inits[InitIndex];
5445     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5446                                  Init->getSourceLocation())) {
5447       ShouldCheckOrder = true;
5448       break;
5449     }
5450   }
5451   if (!ShouldCheckOrder)
5452     return;
5453 
5454   // Build the list of bases and members in the order that they'll
5455   // actually be initialized.  The explicit initializers should be in
5456   // this same order but may be missing things.
5457   SmallVector<const void*, 32> IdealInitKeys;
5458 
5459   const CXXRecordDecl *ClassDecl = Constructor->getParent();
5460 
5461   // 1. Virtual bases.
5462   for (const auto &VBase : ClassDecl->vbases())
5463     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5464 
5465   // 2. Non-virtual bases.
5466   for (const auto &Base : ClassDecl->bases()) {
5467     if (Base.isVirtual())
5468       continue;
5469     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5470   }
5471 
5472   // 3. Direct fields.
5473   for (auto *Field : ClassDecl->fields()) {
5474     if (Field->isUnnamedBitField())
5475       continue;
5476 
5477     PopulateKeysForFields(Field, IdealInitKeys);
5478   }
5479 
5480   unsigned NumIdealInits = IdealInitKeys.size();
5481   unsigned IdealIndex = 0;
5482 
5483   // Track initializers that are in an incorrect order for either a warning or
5484   // note if multiple ones occur.
5485   SmallVector<unsigned> WarnIndexes;
5486   // Correlates the index of an initializer in the init-list to the index of
5487   // the field/base in the class.
5488   SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5489 
5490   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5491     const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]);
5492 
5493     // Scan forward to try to find this initializer in the idealized
5494     // initializers list.
5495     for (; IdealIndex != NumIdealInits; ++IdealIndex)
5496       if (InitKey == IdealInitKeys[IdealIndex])
5497         break;
5498 
5499     // If we didn't find this initializer, it must be because we
5500     // scanned past it on a previous iteration.  That can only
5501     // happen if we're out of order;  emit a warning.
5502     if (IdealIndex == NumIdealInits && InitIndex) {
5503       WarnIndexes.push_back(InitIndex);
5504 
5505       // Move back to the initializer's location in the ideal list.
5506       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5507         if (InitKey == IdealInitKeys[IdealIndex])
5508           break;
5509 
5510       assert(IdealIndex < NumIdealInits &&
5511              "initializer not found in initializer list");
5512     }
5513     CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex);
5514   }
5515 
5516   if (WarnIndexes.empty())
5517     return;
5518 
5519   // Sort based on the ideal order, first in the pair.
5520   llvm::sort(CorrelatedInitOrder, llvm::less_first());
5521 
5522   // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5523   // emit the diagnostic before we can try adding notes.
5524   {
5525     Sema::SemaDiagnosticBuilder D = SemaRef.Diag(
5526         Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5527         WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5528                                 : diag::warn_some_initializers_out_of_order);
5529 
5530     for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5531       if (CorrelatedInitOrder[I].second == I)
5532         continue;
5533       // Ideally we would be using InsertFromRange here, but clang doesn't
5534       // appear to handle InsertFromRange correctly when the source range is
5535       // modified by another fix-it.
5536       D << FixItHint::CreateReplacement(
5537           Inits[I]->getSourceRange(),
5538           Lexer::getSourceText(
5539               CharSourceRange::getTokenRange(
5540                   Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5541               SemaRef.getSourceManager(), SemaRef.getLangOpts()));
5542     }
5543 
5544     // If there is only 1 item out of order, the warning expects the name and
5545     // type of each being added to it.
5546     if (WarnIndexes.size() == 1) {
5547       AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1],
5548                            Inits[WarnIndexes.front()]);
5549       return;
5550     }
5551   }
5552   // More than 1 item to warn, create notes letting the user know which ones
5553   // are bad.
5554   for (unsigned WarnIndex : WarnIndexes) {
5555     const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5556     auto D = SemaRef.Diag(PrevInit->getSourceLocation(),
5557                           diag::note_initializer_out_of_order);
5558     AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]);
5559     D << PrevInit->getSourceRange();
5560   }
5561 }
5562 
5563 namespace {
5564 bool CheckRedundantInit(Sema &S,
5565                         CXXCtorInitializer *Init,
5566                         CXXCtorInitializer *&PrevInit) {
5567   if (!PrevInit) {
5568     PrevInit = Init;
5569     return false;
5570   }
5571 
5572   if (FieldDecl *Field = Init->getAnyMember())
5573     S.Diag(Init->getSourceLocation(),
5574            diag::err_multiple_mem_initialization)
5575       << Field->getDeclName()
5576       << Init->getSourceRange();
5577   else {
5578     const Type *BaseClass = Init->getBaseClass();
5579     assert(BaseClass && "neither field nor base");
5580     S.Diag(Init->getSourceLocation(),
5581            diag::err_multiple_base_initialization)
5582       << QualType(BaseClass, 0)
5583       << Init->getSourceRange();
5584   }
5585   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5586     << 0 << PrevInit->getSourceRange();
5587 
5588   return true;
5589 }
5590 
5591 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5592 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5593 
5594 bool CheckRedundantUnionInit(Sema &S,
5595                              CXXCtorInitializer *Init,
5596                              RedundantUnionMap &Unions) {
5597   FieldDecl *Field = Init->getAnyMember();
5598   RecordDecl *Parent = Field->getParent();
5599   NamedDecl *Child = Field;
5600 
5601   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5602     if (Parent->isUnion()) {
5603       UnionEntry &En = Unions[Parent];
5604       if (En.first && En.first != Child) {
5605         S.Diag(Init->getSourceLocation(),
5606                diag::err_multiple_mem_union_initialization)
5607           << Field->getDeclName()
5608           << Init->getSourceRange();
5609         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5610           << 0 << En.second->getSourceRange();
5611         return true;
5612       }
5613       if (!En.first) {
5614         En.first = Child;
5615         En.second = Init;
5616       }
5617       if (!Parent->isAnonymousStructOrUnion())
5618         return false;
5619     }
5620 
5621     Child = Parent;
5622     Parent = cast<RecordDecl>(Parent->getDeclContext());
5623   }
5624 
5625   return false;
5626 }
5627 } // namespace
5628 
5629 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5630                                 SourceLocation ColonLoc,
5631                                 ArrayRef<CXXCtorInitializer*> MemInits,
5632                                 bool AnyErrors) {
5633   if (!ConstructorDecl)
5634     return;
5635 
5636   AdjustDeclIfTemplate(ConstructorDecl);
5637 
5638   CXXConstructorDecl *Constructor
5639     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5640 
5641   if (!Constructor) {
5642     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5643     return;
5644   }
5645 
5646   // Mapping for the duplicate initializers check.
5647   // For member initializers, this is keyed with a FieldDecl*.
5648   // For base initializers, this is keyed with a Type*.
5649   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5650 
5651   // Mapping for the inconsistent anonymous-union initializers check.
5652   RedundantUnionMap MemberUnions;
5653 
5654   bool HadError = false;
5655   for (unsigned i = 0; i < MemInits.size(); i++) {
5656     CXXCtorInitializer *Init = MemInits[i];
5657 
5658     // Set the source order index.
5659     Init->setSourceOrder(i);
5660 
5661     if (Init->isAnyMemberInitializer()) {
5662       const void *Key = GetKeyForMember(Context, Init);
5663       if (CheckRedundantInit(*this, Init, Members[Key]) ||
5664           CheckRedundantUnionInit(*this, Init, MemberUnions))
5665         HadError = true;
5666     } else if (Init->isBaseInitializer()) {
5667       const void *Key = GetKeyForMember(Context, Init);
5668       if (CheckRedundantInit(*this, Init, Members[Key]))
5669         HadError = true;
5670     } else {
5671       assert(Init->isDelegatingInitializer());
5672       // This must be the only initializer
5673       if (MemInits.size() != 1) {
5674         Diag(Init->getSourceLocation(),
5675              diag::err_delegating_initializer_alone)
5676           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5677         // We will treat this as being the only initializer.
5678       }
5679       SetDelegatingInitializer(Constructor, MemInits[i]);
5680       // Return immediately as the initializer is set.
5681       return;
5682     }
5683   }
5684 
5685   if (HadError)
5686     return;
5687 
5688   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5689 
5690   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5691 
5692   DiagnoseUninitializedFields(*this, Constructor);
5693 }
5694 
5695 void
5696 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5697                                              CXXRecordDecl *ClassDecl) {
5698   // Ignore dependent contexts. Also ignore unions, since their members never
5699   // have destructors implicitly called.
5700   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5701     return;
5702 
5703   // FIXME: all the access-control diagnostics are positioned on the
5704   // field/base declaration.  That's probably good; that said, the
5705   // user might reasonably want to know why the destructor is being
5706   // emitted, and we currently don't say.
5707 
5708   // Non-static data members.
5709   for (auto *Field : ClassDecl->fields()) {
5710     if (Field->isInvalidDecl())
5711       continue;
5712 
5713     // Don't destroy incomplete or zero-length arrays.
5714     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5715       continue;
5716 
5717     QualType FieldType = Context.getBaseElementType(Field->getType());
5718 
5719     const RecordType* RT = FieldType->getAs<RecordType>();
5720     if (!RT)
5721       continue;
5722 
5723     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5724     if (FieldClassDecl->isInvalidDecl())
5725       continue;
5726     if (FieldClassDecl->hasIrrelevantDestructor())
5727       continue;
5728     // The destructor for an implicit anonymous union member is never invoked.
5729     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5730       continue;
5731 
5732     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5733     // Dtor might still be missing, e.g because it's invalid.
5734     if (!Dtor)
5735       continue;
5736     CheckDestructorAccess(Field->getLocation(), Dtor,
5737                           PDiag(diag::err_access_dtor_field)
5738                             << Field->getDeclName()
5739                             << FieldType);
5740 
5741     MarkFunctionReferenced(Location, Dtor);
5742     DiagnoseUseOfDecl(Dtor, Location);
5743   }
5744 
5745   // We only potentially invoke the destructors of potentially constructed
5746   // subobjects.
5747   bool VisitVirtualBases = !ClassDecl->isAbstract();
5748 
5749   // If the destructor exists and has already been marked used in the MS ABI,
5750   // then virtual base destructors have already been checked and marked used.
5751   // Skip checking them again to avoid duplicate diagnostics.
5752   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5753     CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5754     if (Dtor && Dtor->isUsed())
5755       VisitVirtualBases = false;
5756   }
5757 
5758   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5759 
5760   // Bases.
5761   for (const auto &Base : ClassDecl->bases()) {
5762     const RecordType *RT = Base.getType()->getAs<RecordType>();
5763     if (!RT)
5764       continue;
5765 
5766     // Remember direct virtual bases.
5767     if (Base.isVirtual()) {
5768       if (!VisitVirtualBases)
5769         continue;
5770       DirectVirtualBases.insert(RT);
5771     }
5772 
5773     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5774     // If our base class is invalid, we probably can't get its dtor anyway.
5775     if (BaseClassDecl->isInvalidDecl())
5776       continue;
5777     if (BaseClassDecl->hasIrrelevantDestructor())
5778       continue;
5779 
5780     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5781     // Dtor might still be missing, e.g because it's invalid.
5782     if (!Dtor)
5783       continue;
5784 
5785     // FIXME: caret should be on the start of the class name
5786     CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5787                           PDiag(diag::err_access_dtor_base)
5788                               << Base.getType() << Base.getSourceRange(),
5789                           Context.getTypeDeclType(ClassDecl));
5790 
5791     MarkFunctionReferenced(Location, Dtor);
5792     DiagnoseUseOfDecl(Dtor, Location);
5793   }
5794 
5795   if (VisitVirtualBases)
5796     MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5797                                          &DirectVirtualBases);
5798 }
5799 
5800 void Sema::MarkVirtualBaseDestructorsReferenced(
5801     SourceLocation Location, CXXRecordDecl *ClassDecl,
5802     llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) {
5803   // Virtual bases.
5804   for (const auto &VBase : ClassDecl->vbases()) {
5805     // Bases are always records in a well-formed non-dependent class.
5806     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5807 
5808     // Ignore already visited direct virtual bases.
5809     if (DirectVirtualBases && DirectVirtualBases->count(RT))
5810       continue;
5811 
5812     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5813     // If our base class is invalid, we probably can't get its dtor anyway.
5814     if (BaseClassDecl->isInvalidDecl())
5815       continue;
5816     if (BaseClassDecl->hasIrrelevantDestructor())
5817       continue;
5818 
5819     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5820     // Dtor might still be missing, e.g because it's invalid.
5821     if (!Dtor)
5822       continue;
5823     if (CheckDestructorAccess(
5824             ClassDecl->getLocation(), Dtor,
5825             PDiag(diag::err_access_dtor_vbase)
5826                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5827             Context.getTypeDeclType(ClassDecl)) ==
5828         AR_accessible) {
5829       CheckDerivedToBaseConversion(
5830           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5831           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5832           SourceRange(), DeclarationName(), nullptr);
5833     }
5834 
5835     MarkFunctionReferenced(Location, Dtor);
5836     DiagnoseUseOfDecl(Dtor, Location);
5837   }
5838 }
5839 
5840 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5841   if (!CDtorDecl)
5842     return;
5843 
5844   if (CXXConstructorDecl *Constructor
5845       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5846     if (CXXRecordDecl *ClassDecl = Constructor->getParent();
5847         !ClassDecl || ClassDecl->isInvalidDecl()) {
5848       return;
5849     }
5850     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5851     DiagnoseUninitializedFields(*this, Constructor);
5852   }
5853 }
5854 
5855 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5856   if (!getLangOpts().CPlusPlus)
5857     return false;
5858 
5859   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5860   if (!RD)
5861     return false;
5862 
5863   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5864   // class template specialization here, but doing so breaks a lot of code.
5865 
5866   // We can't answer whether something is abstract until it has a
5867   // definition. If it's currently being defined, we'll walk back
5868   // over all the declarations when we have a full definition.
5869   const CXXRecordDecl *Def = RD->getDefinition();
5870   if (!Def || Def->isBeingDefined())
5871     return false;
5872 
5873   return RD->isAbstract();
5874 }
5875 
5876 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5877                                   TypeDiagnoser &Diagnoser) {
5878   if (!isAbstractType(Loc, T))
5879     return false;
5880 
5881   T = Context.getBaseElementType(T);
5882   Diagnoser.diagnose(*this, Loc, T);
5883   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5884   return true;
5885 }
5886 
5887 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5888   // Check if we've already emitted the list of pure virtual functions
5889   // for this class.
5890   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5891     return;
5892 
5893   // If the diagnostic is suppressed, don't emit the notes. We're only
5894   // going to emit them once, so try to attach them to a diagnostic we're
5895   // actually going to show.
5896   if (Diags.isLastDiagnosticIgnored())
5897     return;
5898 
5899   CXXFinalOverriderMap FinalOverriders;
5900   RD->getFinalOverriders(FinalOverriders);
5901 
5902   // Keep a set of seen pure methods so we won't diagnose the same method
5903   // more than once.
5904   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5905 
5906   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5907                                    MEnd = FinalOverriders.end();
5908        M != MEnd;
5909        ++M) {
5910     for (OverridingMethods::iterator SO = M->second.begin(),
5911                                   SOEnd = M->second.end();
5912          SO != SOEnd; ++SO) {
5913       // C++ [class.abstract]p4:
5914       //   A class is abstract if it contains or inherits at least one
5915       //   pure virtual function for which the final overrider is pure
5916       //   virtual.
5917 
5918       //
5919       if (SO->second.size() != 1)
5920         continue;
5921 
5922       if (!SO->second.front().Method->isPureVirtual())
5923         continue;
5924 
5925       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5926         continue;
5927 
5928       Diag(SO->second.front().Method->getLocation(),
5929            diag::note_pure_virtual_function)
5930         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5931     }
5932   }
5933 
5934   if (!PureVirtualClassDiagSet)
5935     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5936   PureVirtualClassDiagSet->insert(RD);
5937 }
5938 
5939 namespace {
5940 struct AbstractUsageInfo {
5941   Sema &S;
5942   CXXRecordDecl *Record;
5943   CanQualType AbstractType;
5944   bool Invalid;
5945 
5946   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5947     : S(S), Record(Record),
5948       AbstractType(S.Context.getCanonicalType(
5949                    S.Context.getTypeDeclType(Record))),
5950       Invalid(false) {}
5951 
5952   void DiagnoseAbstractType() {
5953     if (Invalid) return;
5954     S.DiagnoseAbstractType(Record);
5955     Invalid = true;
5956   }
5957 
5958   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5959 };
5960 
5961 struct CheckAbstractUsage {
5962   AbstractUsageInfo &Info;
5963   const NamedDecl *Ctx;
5964 
5965   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5966     : Info(Info), Ctx(Ctx) {}
5967 
5968   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5969     switch (TL.getTypeLocClass()) {
5970 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5971 #define TYPELOC(CLASS, PARENT) \
5972     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5973 #include "clang/AST/TypeLocNodes.def"
5974     }
5975   }
5976 
5977   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5978     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5979     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5980       if (!TL.getParam(I))
5981         continue;
5982 
5983       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5984       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5985     }
5986   }
5987 
5988   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5989     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5990   }
5991 
5992   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5993     // Visit the type parameters from a permissive context.
5994     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5995       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5996       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5997         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5998           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5999       // TODO: other template argument types?
6000     }
6001   }
6002 
6003   // Visit pointee types from a permissive context.
6004 #define CheckPolymorphic(Type) \
6005   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
6006     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
6007   }
6008   CheckPolymorphic(PointerTypeLoc)
6009   CheckPolymorphic(ReferenceTypeLoc)
6010   CheckPolymorphic(MemberPointerTypeLoc)
6011   CheckPolymorphic(BlockPointerTypeLoc)
6012   CheckPolymorphic(AtomicTypeLoc)
6013 
6014   /// Handle all the types we haven't given a more specific
6015   /// implementation for above.
6016   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6017     // Every other kind of type that we haven't called out already
6018     // that has an inner type is either (1) sugar or (2) contains that
6019     // inner type in some way as a subobject.
6020     if (TypeLoc Next = TL.getNextTypeLoc())
6021       return Visit(Next, Sel);
6022 
6023     // If there's no inner type and we're in a permissive context,
6024     // don't diagnose.
6025     if (Sel == Sema::AbstractNone) return;
6026 
6027     // Check whether the type matches the abstract type.
6028     QualType T = TL.getType();
6029     if (T->isArrayType()) {
6030       Sel = Sema::AbstractArrayType;
6031       T = Info.S.Context.getBaseElementType(T);
6032     }
6033     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
6034     if (CT != Info.AbstractType) return;
6035 
6036     // It matched; do some magic.
6037     // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
6038     if (Sel == Sema::AbstractArrayType) {
6039       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
6040         << T << TL.getSourceRange();
6041     } else {
6042       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
6043         << Sel << T << TL.getSourceRange();
6044     }
6045     Info.DiagnoseAbstractType();
6046   }
6047 };
6048 
6049 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
6050                                   Sema::AbstractDiagSelID Sel) {
6051   CheckAbstractUsage(*this, D).Visit(TL, Sel);
6052 }
6053 
6054 }
6055 
6056 /// Check for invalid uses of an abstract type in a function declaration.
6057 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6058                                     FunctionDecl *FD) {
6059   // Only definitions are required to refer to complete and
6060   // non-abstract types.
6061   if (!FD->doesThisDeclarationHaveABody())
6062     return;
6063 
6064   // For safety's sake, just ignore it if we don't have type source
6065   // information.  This should never happen for non-implicit methods,
6066   // but...
6067   if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6068     Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone);
6069 }
6070 
6071 /// Check for invalid uses of an abstract type in a variable0 declaration.
6072 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6073                                     VarDecl *VD) {
6074   // No need to do the check on definitions, which require that
6075   // the type is complete.
6076   if (VD->isThisDeclarationADefinition())
6077     return;
6078 
6079   Info.CheckType(VD, VD->getTypeSourceInfo()->getTypeLoc(),
6080                  Sema::AbstractVariableType);
6081 }
6082 
6083 /// Check for invalid uses of an abstract type within a class definition.
6084 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6085                                     CXXRecordDecl *RD) {
6086   for (auto *D : RD->decls()) {
6087     if (D->isImplicit()) continue;
6088 
6089     // Step through friends to the befriended declaration.
6090     if (auto *FD = dyn_cast<FriendDecl>(D)) {
6091       D = FD->getFriendDecl();
6092       if (!D) continue;
6093     }
6094 
6095     // Functions and function templates.
6096     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6097       CheckAbstractClassUsage(Info, FD);
6098     } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {
6099       CheckAbstractClassUsage(Info, FTD->getTemplatedDecl());
6100 
6101     // Fields and static variables.
6102     } else if (auto *FD = dyn_cast<FieldDecl>(D)) {
6103       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6104         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
6105     } else if (auto *VD = dyn_cast<VarDecl>(D)) {
6106       CheckAbstractClassUsage(Info, VD);
6107     } else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) {
6108       CheckAbstractClassUsage(Info, VTD->getTemplatedDecl());
6109 
6110     // Nested classes and class templates.
6111     } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6112       CheckAbstractClassUsage(Info, RD);
6113     } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) {
6114       CheckAbstractClassUsage(Info, CTD->getTemplatedDecl());
6115     }
6116   }
6117 }
6118 
6119 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
6120   Attr *ClassAttr = getDLLAttr(Class);
6121   if (!ClassAttr)
6122     return;
6123 
6124   assert(ClassAttr->getKind() == attr::DLLExport);
6125 
6126   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6127 
6128   if (TSK == TSK_ExplicitInstantiationDeclaration)
6129     // Don't go any further if this is just an explicit instantiation
6130     // declaration.
6131     return;
6132 
6133   // Add a context note to explain how we got to any diagnostics produced below.
6134   struct MarkingClassDllexported {
6135     Sema &S;
6136     MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
6137                             SourceLocation AttrLoc)
6138         : S(S) {
6139       Sema::CodeSynthesisContext Ctx;
6140       Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;
6141       Ctx.PointOfInstantiation = AttrLoc;
6142       Ctx.Entity = Class;
6143       S.pushCodeSynthesisContext(Ctx);
6144     }
6145     ~MarkingClassDllexported() {
6146       S.popCodeSynthesisContext();
6147     }
6148   } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
6149 
6150   if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
6151     S.MarkVTableUsed(Class->getLocation(), Class, true);
6152 
6153   for (Decl *Member : Class->decls()) {
6154     // Skip members that were not marked exported.
6155     if (!Member->hasAttr<DLLExportAttr>())
6156       continue;
6157 
6158     // Defined static variables that are members of an exported base
6159     // class must be marked export too.
6160     auto *VD = dyn_cast<VarDecl>(Member);
6161     if (VD && VD->getStorageClass() == SC_Static &&
6162         TSK == TSK_ImplicitInstantiation)
6163       S.MarkVariableReferenced(VD->getLocation(), VD);
6164 
6165     auto *MD = dyn_cast<CXXMethodDecl>(Member);
6166     if (!MD)
6167       continue;
6168 
6169     if (MD->isUserProvided()) {
6170       // Instantiate non-default class member functions ...
6171 
6172       // .. except for certain kinds of template specializations.
6173       if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
6174         continue;
6175 
6176       // If this is an MS ABI dllexport default constructor, instantiate any
6177       // default arguments.
6178       if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6179         auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6180         if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
6181           S.InstantiateDefaultCtorDefaultArgs(CD);
6182         }
6183       }
6184 
6185       S.MarkFunctionReferenced(Class->getLocation(), MD);
6186 
6187       // The function will be passed to the consumer when its definition is
6188       // encountered.
6189     } else if (MD->isExplicitlyDefaulted()) {
6190       // Synthesize and instantiate explicitly defaulted methods.
6191       S.MarkFunctionReferenced(Class->getLocation(), MD);
6192 
6193       if (TSK != TSK_ExplicitInstantiationDefinition) {
6194         // Except for explicit instantiation defs, we will not see the
6195         // definition again later, so pass it to the consumer now.
6196         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
6197       }
6198     } else if (!MD->isTrivial() ||
6199                MD->isCopyAssignmentOperator() ||
6200                MD->isMoveAssignmentOperator()) {
6201       // Synthesize and instantiate non-trivial implicit methods, and the copy
6202       // and move assignment operators. The latter are exported even if they
6203       // are trivial, because the address of an operator can be taken and
6204       // should compare equal across libraries.
6205       S.MarkFunctionReferenced(Class->getLocation(), MD);
6206 
6207       // There is no later point when we will see the definition of this
6208       // function, so pass it to the consumer now.
6209       S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
6210     }
6211   }
6212 }
6213 
6214 static void checkForMultipleExportedDefaultConstructors(Sema &S,
6215                                                         CXXRecordDecl *Class) {
6216   // Only the MS ABI has default constructor closures, so we don't need to do
6217   // this semantic checking anywhere else.
6218   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
6219     return;
6220 
6221   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6222   for (Decl *Member : Class->decls()) {
6223     // Look for exported default constructors.
6224     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
6225     if (!CD || !CD->isDefaultConstructor())
6226       continue;
6227     auto *Attr = CD->getAttr<DLLExportAttr>();
6228     if (!Attr)
6229       continue;
6230 
6231     // If the class is non-dependent, mark the default arguments as ODR-used so
6232     // that we can properly codegen the constructor closure.
6233     if (!Class->isDependentContext()) {
6234       for (ParmVarDecl *PD : CD->parameters()) {
6235         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
6236         S.DiscardCleanupsInEvaluationContext();
6237       }
6238     }
6239 
6240     if (LastExportedDefaultCtor) {
6241       S.Diag(LastExportedDefaultCtor->getLocation(),
6242              diag::err_attribute_dll_ambiguous_default_ctor)
6243           << Class;
6244       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
6245           << CD->getDeclName();
6246       return;
6247     }
6248     LastExportedDefaultCtor = CD;
6249   }
6250 }
6251 
6252 static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
6253                                                        CXXRecordDecl *Class) {
6254   bool ErrorReported = false;
6255   auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6256                                                      ClassTemplateDecl *TD) {
6257     if (ErrorReported)
6258       return;
6259     S.Diag(TD->getLocation(),
6260            diag::err_cuda_device_builtin_surftex_cls_template)
6261         << /*surface*/ 0 << TD;
6262     ErrorReported = true;
6263   };
6264 
6265   ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6266   if (!TD) {
6267     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6268     if (!SD) {
6269       S.Diag(Class->getLocation(),
6270              diag::err_cuda_device_builtin_surftex_ref_decl)
6271           << /*surface*/ 0 << Class;
6272       S.Diag(Class->getLocation(),
6273              diag::note_cuda_device_builtin_surftex_should_be_template_class)
6274           << Class;
6275       return;
6276     }
6277     TD = SD->getSpecializedTemplate();
6278   }
6279 
6280   TemplateParameterList *Params = TD->getTemplateParameters();
6281   unsigned N = Params->size();
6282 
6283   if (N != 2) {
6284     reportIllegalClassTemplate(S, TD);
6285     S.Diag(TD->getLocation(),
6286            diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6287         << TD << 2;
6288   }
6289   if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6290     reportIllegalClassTemplate(S, TD);
6291     S.Diag(TD->getLocation(),
6292            diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6293         << TD << /*1st*/ 0 << /*type*/ 0;
6294   }
6295   if (N > 1) {
6296     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6297     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6298       reportIllegalClassTemplate(S, TD);
6299       S.Diag(TD->getLocation(),
6300              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6301           << TD << /*2nd*/ 1 << /*integer*/ 1;
6302     }
6303   }
6304 }
6305 
6306 static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
6307                                                        CXXRecordDecl *Class) {
6308   bool ErrorReported = false;
6309   auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6310                                                      ClassTemplateDecl *TD) {
6311     if (ErrorReported)
6312       return;
6313     S.Diag(TD->getLocation(),
6314            diag::err_cuda_device_builtin_surftex_cls_template)
6315         << /*texture*/ 1 << TD;
6316     ErrorReported = true;
6317   };
6318 
6319   ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6320   if (!TD) {
6321     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6322     if (!SD) {
6323       S.Diag(Class->getLocation(),
6324              diag::err_cuda_device_builtin_surftex_ref_decl)
6325           << /*texture*/ 1 << Class;
6326       S.Diag(Class->getLocation(),
6327              diag::note_cuda_device_builtin_surftex_should_be_template_class)
6328           << Class;
6329       return;
6330     }
6331     TD = SD->getSpecializedTemplate();
6332   }
6333 
6334   TemplateParameterList *Params = TD->getTemplateParameters();
6335   unsigned N = Params->size();
6336 
6337   if (N != 3) {
6338     reportIllegalClassTemplate(S, TD);
6339     S.Diag(TD->getLocation(),
6340            diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6341         << TD << 3;
6342   }
6343   if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6344     reportIllegalClassTemplate(S, TD);
6345     S.Diag(TD->getLocation(),
6346            diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6347         << TD << /*1st*/ 0 << /*type*/ 0;
6348   }
6349   if (N > 1) {
6350     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6351     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6352       reportIllegalClassTemplate(S, TD);
6353       S.Diag(TD->getLocation(),
6354              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6355           << TD << /*2nd*/ 1 << /*integer*/ 1;
6356     }
6357   }
6358   if (N > 2) {
6359     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6360     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6361       reportIllegalClassTemplate(S, TD);
6362       S.Diag(TD->getLocation(),
6363              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6364           << TD << /*3rd*/ 2 << /*integer*/ 1;
6365     }
6366   }
6367 }
6368 
6369 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
6370   // Mark any compiler-generated routines with the implicit code_seg attribute.
6371   for (auto *Method : Class->methods()) {
6372     if (Method->isUserProvided())
6373       continue;
6374     if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6375       Method->addAttr(A);
6376   }
6377 }
6378 
6379 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
6380   Attr *ClassAttr = getDLLAttr(Class);
6381 
6382   // MSVC inherits DLL attributes to partial class template specializations.
6383   if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6384     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6385       if (Attr *TemplateAttr =
6386               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6387         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6388         A->setInherited(true);
6389         ClassAttr = A;
6390       }
6391     }
6392   }
6393 
6394   if (!ClassAttr)
6395     return;
6396 
6397   // MSVC allows imported or exported template classes that have UniqueExternal
6398   // linkage. This occurs when the template class has been instantiated with
6399   // a template parameter which itself has internal linkage.
6400   // We drop the attribute to avoid exporting or importing any members.
6401   if ((Context.getTargetInfo().getCXXABI().isMicrosoft() ||
6402        Context.getTargetInfo().getTriple().isPS()) &&
6403       (!Class->isExternallyVisible() && Class->hasExternalFormalLinkage())) {
6404     Class->dropAttrs<DLLExportAttr, DLLImportAttr>();
6405     return;
6406   }
6407 
6408   if (!Class->isExternallyVisible()) {
6409     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6410         << Class << ClassAttr;
6411     return;
6412   }
6413 
6414   if (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6415       !ClassAttr->isInherited()) {
6416     // Diagnose dll attributes on members of class with dll attribute.
6417     for (Decl *Member : Class->decls()) {
6418       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
6419         continue;
6420       InheritableAttr *MemberAttr = getDLLAttr(Member);
6421       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6422         continue;
6423 
6424       Diag(MemberAttr->getLocation(),
6425              diag::err_attribute_dll_member_of_dll_class)
6426           << MemberAttr << ClassAttr;
6427       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6428       Member->setInvalidDecl();
6429     }
6430   }
6431 
6432   if (Class->getDescribedClassTemplate())
6433     // Don't inherit dll attribute until the template is instantiated.
6434     return;
6435 
6436   // The class is either imported or exported.
6437   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6438 
6439   // Check if this was a dllimport attribute propagated from a derived class to
6440   // a base class template specialization. We don't apply these attributes to
6441   // static data members.
6442   const bool PropagatedImport =
6443       !ClassExported &&
6444       cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6445 
6446   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6447 
6448   // Ignore explicit dllexport on explicit class template instantiation
6449   // declarations, except in MinGW mode.
6450   if (ClassExported && !ClassAttr->isInherited() &&
6451       TSK == TSK_ExplicitInstantiationDeclaration &&
6452       !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
6453     Class->dropAttr<DLLExportAttr>();
6454     return;
6455   }
6456 
6457   // Force declaration of implicit members so they can inherit the attribute.
6458   ForceDeclarationOfImplicitMembers(Class);
6459 
6460   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6461   // seem to be true in practice?
6462 
6463   for (Decl *Member : Class->decls()) {
6464     VarDecl *VD = dyn_cast<VarDecl>(Member);
6465     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6466 
6467     // Only methods and static fields inherit the attributes.
6468     if (!VD && !MD)
6469       continue;
6470 
6471     if (MD) {
6472       // Don't process deleted methods.
6473       if (MD->isDeleted())
6474         continue;
6475 
6476       if (MD->isInlined()) {
6477         // MinGW does not import or export inline methods. But do it for
6478         // template instantiations.
6479         if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6480             TSK != TSK_ExplicitInstantiationDeclaration &&
6481             TSK != TSK_ExplicitInstantiationDefinition)
6482           continue;
6483 
6484         // MSVC versions before 2015 don't export the move assignment operators
6485         // and move constructor, so don't attempt to import/export them if
6486         // we have a definition.
6487         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6488         if ((MD->isMoveAssignmentOperator() ||
6489              (Ctor && Ctor->isMoveConstructor())) &&
6490             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6491           continue;
6492 
6493         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6494         // operator is exported anyway.
6495         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6496             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6497           continue;
6498       }
6499     }
6500 
6501     // Don't apply dllimport attributes to static data members of class template
6502     // instantiations when the attribute is propagated from a derived class.
6503     if (VD && PropagatedImport)
6504       continue;
6505 
6506     if (!cast<NamedDecl>(Member)->isExternallyVisible())
6507       continue;
6508 
6509     if (!getDLLAttr(Member)) {
6510       InheritableAttr *NewAttr = nullptr;
6511 
6512       // Do not export/import inline function when -fno-dllexport-inlines is
6513       // passed. But add attribute for later local static var check.
6514       if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6515           TSK != TSK_ExplicitInstantiationDeclaration &&
6516           TSK != TSK_ExplicitInstantiationDefinition) {
6517         if (ClassExported) {
6518           NewAttr = ::new (getASTContext())
6519               DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6520         } else {
6521           NewAttr = ::new (getASTContext())
6522               DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6523         }
6524       } else {
6525         NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6526       }
6527 
6528       NewAttr->setInherited(true);
6529       Member->addAttr(NewAttr);
6530 
6531       if (MD) {
6532         // Propagate DLLAttr to friend re-declarations of MD that have already
6533         // been constructed.
6534         for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6535              FD = FD->getPreviousDecl()) {
6536           if (FD->getFriendObjectKind() == Decl::FOK_None)
6537             continue;
6538           assert(!getDLLAttr(FD) &&
6539                  "friend re-decl should not already have a DLLAttr");
6540           NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6541           NewAttr->setInherited(true);
6542           FD->addAttr(NewAttr);
6543         }
6544       }
6545     }
6546   }
6547 
6548   if (ClassExported)
6549     DelayedDllExportClasses.push_back(Class);
6550 }
6551 
6552 void Sema::propagateDLLAttrToBaseClassTemplate(
6553     CXXRecordDecl *Class, Attr *ClassAttr,
6554     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6555   if (getDLLAttr(
6556           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6557     // If the base class template has a DLL attribute, don't try to change it.
6558     return;
6559   }
6560 
6561   auto TSK = BaseTemplateSpec->getSpecializationKind();
6562   if (!getDLLAttr(BaseTemplateSpec) &&
6563       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
6564        TSK == TSK_ImplicitInstantiation)) {
6565     // The template hasn't been instantiated yet (or it has, but only as an
6566     // explicit instantiation declaration or implicit instantiation, which means
6567     // we haven't codegenned any members yet), so propagate the attribute.
6568     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6569     NewAttr->setInherited(true);
6570     BaseTemplateSpec->addAttr(NewAttr);
6571 
6572     // If this was an import, mark that we propagated it from a derived class to
6573     // a base class template specialization.
6574     if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6575       ImportAttr->setPropagatedToBaseTemplate();
6576 
6577     // If the template is already instantiated, checkDLLAttributeRedeclaration()
6578     // needs to be run again to work see the new attribute. Otherwise this will
6579     // get run whenever the template is instantiated.
6580     if (TSK != TSK_Undeclared)
6581       checkClassLevelDLLAttribute(BaseTemplateSpec);
6582 
6583     return;
6584   }
6585 
6586   if (getDLLAttr(BaseTemplateSpec)) {
6587     // The template has already been specialized or instantiated with an
6588     // attribute, explicitly or through propagation. We should not try to change
6589     // it.
6590     return;
6591   }
6592 
6593   // The template was previously instantiated or explicitly specialized without
6594   // a dll attribute, It's too late for us to add an attribute, so warn that
6595   // this is unsupported.
6596   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6597       << BaseTemplateSpec->isExplicitSpecialization();
6598   Diag(ClassAttr->getLocation(), diag::note_attribute);
6599   if (BaseTemplateSpec->isExplicitSpecialization()) {
6600     Diag(BaseTemplateSpec->getLocation(),
6601            diag::note_template_class_explicit_specialization_was_here)
6602         << BaseTemplateSpec;
6603   } else {
6604     Diag(BaseTemplateSpec->getPointOfInstantiation(),
6605            diag::note_template_class_instantiation_was_here)
6606         << BaseTemplateSpec;
6607   }
6608 }
6609 
6610 Sema::DefaultedFunctionKind
6611 Sema::getDefaultedFunctionKind(const FunctionDecl *FD) {
6612   if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6613     if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
6614       if (Ctor->isDefaultConstructor())
6615         return CXXSpecialMemberKind::DefaultConstructor;
6616 
6617       if (Ctor->isCopyConstructor())
6618         return CXXSpecialMemberKind::CopyConstructor;
6619 
6620       if (Ctor->isMoveConstructor())
6621         return CXXSpecialMemberKind::MoveConstructor;
6622     }
6623 
6624     if (MD->isCopyAssignmentOperator())
6625       return CXXSpecialMemberKind::CopyAssignment;
6626 
6627     if (MD->isMoveAssignmentOperator())
6628       return CXXSpecialMemberKind::MoveAssignment;
6629 
6630     if (isa<CXXDestructorDecl>(FD))
6631       return CXXSpecialMemberKind::Destructor;
6632   }
6633 
6634   switch (FD->getDeclName().getCXXOverloadedOperator()) {
6635   case OO_EqualEqual:
6636     return DefaultedComparisonKind::Equal;
6637 
6638   case OO_ExclaimEqual:
6639     return DefaultedComparisonKind::NotEqual;
6640 
6641   case OO_Spaceship:
6642     // No point allowing this if <=> doesn't exist in the current language mode.
6643     if (!getLangOpts().CPlusPlus20)
6644       break;
6645     return DefaultedComparisonKind::ThreeWay;
6646 
6647   case OO_Less:
6648   case OO_LessEqual:
6649   case OO_Greater:
6650   case OO_GreaterEqual:
6651     // No point allowing this if <=> doesn't exist in the current language mode.
6652     if (!getLangOpts().CPlusPlus20)
6653       break;
6654     return DefaultedComparisonKind::Relational;
6655 
6656   default:
6657     break;
6658   }
6659 
6660   // Not defaultable.
6661   return DefaultedFunctionKind();
6662 }
6663 
6664 static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,
6665                                     SourceLocation DefaultLoc) {
6666   Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD);
6667   if (DFK.isComparison())
6668     return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6669 
6670   switch (DFK.asSpecialMember()) {
6671   case CXXSpecialMemberKind::DefaultConstructor:
6672     S.DefineImplicitDefaultConstructor(DefaultLoc,
6673                                        cast<CXXConstructorDecl>(FD));
6674     break;
6675   case CXXSpecialMemberKind::CopyConstructor:
6676     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6677     break;
6678   case CXXSpecialMemberKind::CopyAssignment:
6679     S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6680     break;
6681   case CXXSpecialMemberKind::Destructor:
6682     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD));
6683     break;
6684   case CXXSpecialMemberKind::MoveConstructor:
6685     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6686     break;
6687   case CXXSpecialMemberKind::MoveAssignment:
6688     S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6689     break;
6690   case CXXSpecialMemberKind::Invalid:
6691     llvm_unreachable("Invalid special member.");
6692   }
6693 }
6694 
6695 /// Determine whether a type is permitted to be passed or returned in
6696 /// registers, per C++ [class.temporary]p3.
6697 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6698                                TargetInfo::CallingConvKind CCK) {
6699   if (D->isDependentType() || D->isInvalidDecl())
6700     return false;
6701 
6702   // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6703   // The PS4 platform ABI follows the behavior of Clang 3.2.
6704   if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6705     return !D->hasNonTrivialDestructorForCall() &&
6706            !D->hasNonTrivialCopyConstructorForCall();
6707 
6708   if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6709     bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6710     bool DtorIsTrivialForCall = false;
6711 
6712     // If a class has at least one eligible, trivial copy constructor, it
6713     // is passed according to the C ABI. Otherwise, it is passed indirectly.
6714     //
6715     // Note: This permits classes with non-trivial copy or move ctors to be
6716     // passed in registers, so long as they *also* have a trivial copy ctor,
6717     // which is non-conforming.
6718     if (D->needsImplicitCopyConstructor()) {
6719       if (!D->defaultedCopyConstructorIsDeleted()) {
6720         if (D->hasTrivialCopyConstructor())
6721           CopyCtorIsTrivial = true;
6722         if (D->hasTrivialCopyConstructorForCall())
6723           CopyCtorIsTrivialForCall = true;
6724       }
6725     } else {
6726       for (const CXXConstructorDecl *CD : D->ctors()) {
6727         if (CD->isCopyConstructor() && !CD->isDeleted() &&
6728             !CD->isIneligibleOrNotSelected()) {
6729           if (CD->isTrivial())
6730             CopyCtorIsTrivial = true;
6731           if (CD->isTrivialForCall())
6732             CopyCtorIsTrivialForCall = true;
6733         }
6734       }
6735     }
6736 
6737     if (D->needsImplicitDestructor()) {
6738       if (!D->defaultedDestructorIsDeleted() &&
6739           D->hasTrivialDestructorForCall())
6740         DtorIsTrivialForCall = true;
6741     } else if (const auto *DD = D->getDestructor()) {
6742       if (!DD->isDeleted() && DD->isTrivialForCall())
6743         DtorIsTrivialForCall = true;
6744     }
6745 
6746     // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6747     if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6748       return true;
6749 
6750     // If a class has a destructor, we'd really like to pass it indirectly
6751     // because it allows us to elide copies.  Unfortunately, MSVC makes that
6752     // impossible for small types, which it will pass in a single register or
6753     // stack slot. Most objects with dtors are large-ish, so handle that early.
6754     // We can't call out all large objects as being indirect because there are
6755     // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6756     // how we pass large POD types.
6757 
6758     // Note: This permits small classes with nontrivial destructors to be
6759     // passed in registers, which is non-conforming.
6760     bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6761     uint64_t TypeSize = isAArch64 ? 128 : 64;
6762 
6763     if (CopyCtorIsTrivial &&
6764         S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6765       return true;
6766     return false;
6767   }
6768 
6769   // Per C++ [class.temporary]p3, the relevant condition is:
6770   //   each copy constructor, move constructor, and destructor of X is
6771   //   either trivial or deleted, and X has at least one non-deleted copy
6772   //   or move constructor
6773   bool HasNonDeletedCopyOrMove = false;
6774 
6775   if (D->needsImplicitCopyConstructor() &&
6776       !D->defaultedCopyConstructorIsDeleted()) {
6777     if (!D->hasTrivialCopyConstructorForCall())
6778       return false;
6779     HasNonDeletedCopyOrMove = true;
6780   }
6781 
6782   if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6783       !D->defaultedMoveConstructorIsDeleted()) {
6784     if (!D->hasTrivialMoveConstructorForCall())
6785       return false;
6786     HasNonDeletedCopyOrMove = true;
6787   }
6788 
6789   if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6790       !D->hasTrivialDestructorForCall())
6791     return false;
6792 
6793   for (const CXXMethodDecl *MD : D->methods()) {
6794     if (MD->isDeleted() || MD->isIneligibleOrNotSelected())
6795       continue;
6796 
6797     auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6798     if (CD && CD->isCopyOrMoveConstructor())
6799       HasNonDeletedCopyOrMove = true;
6800     else if (!isa<CXXDestructorDecl>(MD))
6801       continue;
6802 
6803     if (!MD->isTrivialForCall())
6804       return false;
6805   }
6806 
6807   return HasNonDeletedCopyOrMove;
6808 }
6809 
6810 /// Report an error regarding overriding, along with any relevant
6811 /// overridden methods.
6812 ///
6813 /// \param DiagID the primary error to report.
6814 /// \param MD the overriding method.
6815 static bool
6816 ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
6817                 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
6818   bool IssuedDiagnostic = false;
6819   for (const CXXMethodDecl *O : MD->overridden_methods()) {
6820     if (Report(O)) {
6821       if (!IssuedDiagnostic) {
6822         S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6823         IssuedDiagnostic = true;
6824       }
6825       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
6826     }
6827   }
6828   return IssuedDiagnostic;
6829 }
6830 
6831 void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
6832   if (!Record)
6833     return;
6834 
6835   if (Record->isAbstract() && !Record->isInvalidDecl()) {
6836     AbstractUsageInfo Info(*this, Record);
6837     CheckAbstractClassUsage(Info, Record);
6838   }
6839 
6840   // If this is not an aggregate type and has no user-declared constructor,
6841   // complain about any non-static data members of reference or const scalar
6842   // type, since they will never get initializers.
6843   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6844       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6845       !Record->isLambda()) {
6846     bool Complained = false;
6847     for (const auto *F : Record->fields()) {
6848       if (F->hasInClassInitializer() || F->isUnnamedBitField())
6849         continue;
6850 
6851       if (F->getType()->isReferenceType() ||
6852           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6853         if (!Complained) {
6854           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6855               << llvm::to_underlying(Record->getTagKind()) << Record;
6856           Complained = true;
6857         }
6858 
6859         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6860           << F->getType()->isReferenceType()
6861           << F->getDeclName();
6862       }
6863     }
6864   }
6865 
6866   if (Record->getIdentifier()) {
6867     // C++ [class.mem]p13:
6868     //   If T is the name of a class, then each of the following shall have a
6869     //   name different from T:
6870     //     - every member of every anonymous union that is a member of class T.
6871     //
6872     // C++ [class.mem]p14:
6873     //   In addition, if class T has a user-declared constructor (12.1), every
6874     //   non-static data member of class T shall have a name different from T.
6875     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6876     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6877          ++I) {
6878       NamedDecl *D = (*I)->getUnderlyingDecl();
6879       if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6880            Record->hasUserDeclaredConstructor()) ||
6881           isa<IndirectFieldDecl>(D)) {
6882         Diag((*I)->getLocation(), diag::err_member_name_of_class)
6883           << D->getDeclName();
6884         break;
6885       }
6886     }
6887   }
6888 
6889   // Warn if the class has virtual methods but non-virtual public destructor.
6890   if (Record->isPolymorphic() && !Record->isDependentType()) {
6891     CXXDestructorDecl *dtor = Record->getDestructor();
6892     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6893         !Record->hasAttr<FinalAttr>())
6894       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6895            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6896   }
6897 
6898   if (Record->isAbstract()) {
6899     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6900       Diag(Record->getLocation(), diag::warn_abstract_final_class)
6901         << FA->isSpelledAsSealed();
6902       DiagnoseAbstractType(Record);
6903     }
6904   }
6905 
6906   // Warn if the class has a final destructor but is not itself marked final.
6907   if (!Record->hasAttr<FinalAttr>()) {
6908     if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
6909       if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
6910         Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
6911             << FA->isSpelledAsSealed()
6912             << FixItHint::CreateInsertion(
6913                    getLocForEndOfToken(Record->getLocation()),
6914                    (FA->isSpelledAsSealed() ? " sealed" : " final"));
6915         Diag(Record->getLocation(),
6916              diag::note_final_dtor_non_final_class_silence)
6917             << Context.getRecordType(Record) << FA->isSpelledAsSealed();
6918       }
6919     }
6920   }
6921 
6922   // See if trivial_abi has to be dropped.
6923   if (Record->hasAttr<TrivialABIAttr>())
6924     checkIllFormedTrivialABIStruct(*Record);
6925 
6926   // Set HasTrivialSpecialMemberForCall if the record has attribute
6927   // "trivial_abi".
6928   bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6929 
6930   if (HasTrivialABI)
6931     Record->setHasTrivialSpecialMemberForCall();
6932 
6933   // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
6934   // We check these last because they can depend on the properties of the
6935   // primary comparison functions (==, <=>).
6936   llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
6937 
6938   // Perform checks that can't be done until we know all the properties of a
6939   // member function (whether it's defaulted, deleted, virtual, overriding,
6940   // ...).
6941   auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
6942     // A static function cannot override anything.
6943     if (MD->getStorageClass() == SC_Static) {
6944       if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
6945                           [](const CXXMethodDecl *) { return true; }))
6946         return;
6947     }
6948 
6949     // A deleted function cannot override a non-deleted function and vice
6950     // versa.
6951     if (ReportOverrides(*this,
6952                         MD->isDeleted() ? diag::err_deleted_override
6953                                         : diag::err_non_deleted_override,
6954                         MD, [&](const CXXMethodDecl *V) {
6955                           return MD->isDeleted() != V->isDeleted();
6956                         })) {
6957       if (MD->isDefaulted() && MD->isDeleted())
6958         // Explain why this defaulted function was deleted.
6959         DiagnoseDeletedDefaultedFunction(MD);
6960       return;
6961     }
6962 
6963     // A consteval function cannot override a non-consteval function and vice
6964     // versa.
6965     if (ReportOverrides(*this,
6966                         MD->isConsteval() ? diag::err_consteval_override
6967                                           : diag::err_non_consteval_override,
6968                         MD, [&](const CXXMethodDecl *V) {
6969                           return MD->isConsteval() != V->isConsteval();
6970                         })) {
6971       if (MD->isDefaulted() && MD->isDeleted())
6972         // Explain why this defaulted function was deleted.
6973         DiagnoseDeletedDefaultedFunction(MD);
6974       return;
6975     }
6976   };
6977 
6978   auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
6979     if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
6980       return false;
6981 
6982     DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
6983     if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||
6984         DFK.asComparison() == DefaultedComparisonKind::Relational) {
6985       DefaultedSecondaryComparisons.push_back(FD);
6986       return true;
6987     }
6988 
6989     CheckExplicitlyDefaultedFunction(S, FD);
6990     return false;
6991   };
6992 
6993   if (!Record->isInvalidDecl() &&
6994       Record->hasAttr<VTablePointerAuthenticationAttr>())
6995     checkIncorrectVTablePointerAuthenticationAttribute(*Record);
6996 
6997   auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
6998     // Check whether the explicitly-defaulted members are valid.
6999     bool Incomplete = CheckForDefaultedFunction(M);
7000 
7001     // Skip the rest of the checks for a member of a dependent class.
7002     if (Record->isDependentType())
7003       return;
7004 
7005     // For an explicitly defaulted or deleted special member, we defer
7006     // determining triviality until the class is complete. That time is now!
7007     CXXSpecialMemberKind CSM = getSpecialMember(M);
7008     if (!M->isImplicit() && !M->isUserProvided()) {
7009       if (CSM != CXXSpecialMemberKind::Invalid) {
7010         M->setTrivial(SpecialMemberIsTrivial(M, CSM));
7011         // Inform the class that we've finished declaring this member.
7012         Record->finishedDefaultedOrDeletedMember(M);
7013         M->setTrivialForCall(
7014             HasTrivialABI ||
7015             SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
7016         Record->setTrivialForCallFlags(M);
7017       }
7018     }
7019 
7020     // Set triviality for the purpose of calls if this is a user-provided
7021     // copy/move constructor or destructor.
7022     if ((CSM == CXXSpecialMemberKind::CopyConstructor ||
7023          CSM == CXXSpecialMemberKind::MoveConstructor ||
7024          CSM == CXXSpecialMemberKind::Destructor) &&
7025         M->isUserProvided()) {
7026       M->setTrivialForCall(HasTrivialABI);
7027       Record->setTrivialForCallFlags(M);
7028     }
7029 
7030     if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
7031         M->hasAttr<DLLExportAttr>()) {
7032       if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
7033           M->isTrivial() &&
7034           (CSM == CXXSpecialMemberKind::DefaultConstructor ||
7035            CSM == CXXSpecialMemberKind::CopyConstructor ||
7036            CSM == CXXSpecialMemberKind::Destructor))
7037         M->dropAttr<DLLExportAttr>();
7038 
7039       if (M->hasAttr<DLLExportAttr>()) {
7040         // Define after any fields with in-class initializers have been parsed.
7041         DelayedDllExportMemberFunctions.push_back(M);
7042       }
7043     }
7044 
7045     bool EffectivelyConstexprDestructor = true;
7046     // Avoid triggering vtable instantiation due to a dtor that is not
7047     // "effectively constexpr" for better compatibility.
7048     // See https://github.com/llvm/llvm-project/issues/102293 for more info.
7049     if (isa<CXXDestructorDecl>(M)) {
7050       auto Check = [](QualType T, auto &&Check) -> bool {
7051         const CXXRecordDecl *RD =
7052             T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
7053         if (!RD || !RD->isCompleteDefinition())
7054           return true;
7055 
7056         if (!RD->hasConstexprDestructor())
7057           return false;
7058 
7059         QualType CanUnqualT = T.getCanonicalType().getUnqualifiedType();
7060         for (const CXXBaseSpecifier &B : RD->bases())
7061           if (B.getType().getCanonicalType().getUnqualifiedType() !=
7062                   CanUnqualT &&
7063               !Check(B.getType(), Check))
7064             return false;
7065         for (const FieldDecl *FD : RD->fields())
7066           if (FD->getType().getCanonicalType().getUnqualifiedType() !=
7067                   CanUnqualT &&
7068               !Check(FD->getType(), Check))
7069             return false;
7070         return true;
7071       };
7072       EffectivelyConstexprDestructor =
7073           Check(QualType(Record->getTypeForDecl(), 0), Check);
7074     }
7075 
7076     // Define defaulted constexpr virtual functions that override a base class
7077     // function right away.
7078     // FIXME: We can defer doing this until the vtable is marked as used.
7079     if (CSM != CXXSpecialMemberKind::Invalid && !M->isDeleted() &&
7080         M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods() &&
7081         EffectivelyConstexprDestructor)
7082       DefineDefaultedFunction(*this, M, M->getLocation());
7083 
7084     if (!Incomplete)
7085       CheckCompletedMemberFunction(M);
7086   };
7087 
7088   // Check the destructor before any other member function. We need to
7089   // determine whether it's trivial in order to determine whether the claas
7090   // type is a literal type, which is a prerequisite for determining whether
7091   // other special member functions are valid and whether they're implicitly
7092   // 'constexpr'.
7093   if (CXXDestructorDecl *Dtor = Record->getDestructor())
7094     CompleteMemberFunction(Dtor);
7095 
7096   bool HasMethodWithOverrideControl = false,
7097        HasOverridingMethodWithoutOverrideControl = false;
7098   for (auto *D : Record->decls()) {
7099     if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
7100       // FIXME: We could do this check for dependent types with non-dependent
7101       // bases.
7102       if (!Record->isDependentType()) {
7103         // See if a method overloads virtual methods in a base
7104         // class without overriding any.
7105         if (!M->isStatic())
7106           DiagnoseHiddenVirtualMethods(M);
7107         if (M->hasAttr<OverrideAttr>())
7108           HasMethodWithOverrideControl = true;
7109         else if (M->size_overridden_methods() > 0)
7110           HasOverridingMethodWithoutOverrideControl = true;
7111       }
7112 
7113       if (!isa<CXXDestructorDecl>(M))
7114         CompleteMemberFunction(M);
7115     } else if (auto *F = dyn_cast<FriendDecl>(D)) {
7116       CheckForDefaultedFunction(
7117           dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
7118     }
7119   }
7120 
7121   if (HasOverridingMethodWithoutOverrideControl) {
7122     bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
7123     for (auto *M : Record->methods())
7124       DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
7125   }
7126 
7127   // Check the defaulted secondary comparisons after any other member functions.
7128   for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
7129     CheckExplicitlyDefaultedFunction(S, FD);
7130 
7131     // If this is a member function, we deferred checking it until now.
7132     if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
7133       CheckCompletedMemberFunction(MD);
7134   }
7135 
7136   // ms_struct is a request to use the same ABI rules as MSVC.  Check
7137   // whether this class uses any C++ features that are implemented
7138   // completely differently in MSVC, and if so, emit a diagnostic.
7139   // That diagnostic defaults to an error, but we allow projects to
7140   // map it down to a warning (or ignore it).  It's a fairly common
7141   // practice among users of the ms_struct pragma to mass-annotate
7142   // headers, sweeping up a bunch of types that the project doesn't
7143   // really rely on MSVC-compatible layout for.  We must therefore
7144   // support "ms_struct except for C++ stuff" as a secondary ABI.
7145   // Don't emit this diagnostic if the feature was enabled as a
7146   // language option (as opposed to via a pragma or attribute), as
7147   // the option -mms-bitfields otherwise essentially makes it impossible
7148   // to build C++ code, unless this diagnostic is turned off.
7149   if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields &&
7150       (Record->isPolymorphic() || Record->getNumBases())) {
7151     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
7152   }
7153 
7154   checkClassLevelDLLAttribute(Record);
7155   checkClassLevelCodeSegAttribute(Record);
7156 
7157   bool ClangABICompat4 =
7158       Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
7159   TargetInfo::CallingConvKind CCK =
7160       Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
7161   bool CanPass = canPassInRegisters(*this, Record, CCK);
7162 
7163   // Do not change ArgPassingRestrictions if it has already been set to
7164   // RecordArgPassingKind::CanNeverPassInRegs.
7165   if (Record->getArgPassingRestrictions() !=
7166       RecordArgPassingKind::CanNeverPassInRegs)
7167     Record->setArgPassingRestrictions(
7168         CanPass ? RecordArgPassingKind::CanPassInRegs
7169                 : RecordArgPassingKind::CannotPassInRegs);
7170 
7171   // If canPassInRegisters returns true despite the record having a non-trivial
7172   // destructor, the record is destructed in the callee. This happens only when
7173   // the record or one of its subobjects has a field annotated with trivial_abi
7174   // or a field qualified with ObjC __strong/__weak.
7175   if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
7176     Record->setParamDestroyedInCallee(true);
7177   else if (Record->hasNonTrivialDestructor())
7178     Record->setParamDestroyedInCallee(CanPass);
7179 
7180   if (getLangOpts().ForceEmitVTables) {
7181     // If we want to emit all the vtables, we need to mark it as used.  This
7182     // is especially required for cases like vtable assumption loads.
7183     MarkVTableUsed(Record->getInnerLocStart(), Record);
7184   }
7185 
7186   if (getLangOpts().CUDA) {
7187     if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
7188       checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record);
7189     else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
7190       checkCUDADeviceBuiltinTextureClassTemplate(*this, Record);
7191   }
7192 }
7193 
7194 /// Look up the special member function that would be called by a special
7195 /// member function for a subobject of class type.
7196 ///
7197 /// \param Class The class type of the subobject.
7198 /// \param CSM The kind of special member function.
7199 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
7200 /// \param ConstRHS True if this is a copy operation with a const object
7201 ///        on its RHS, that is, if the argument to the outer special member
7202 ///        function is 'const' and this is not a field marked 'mutable'.
7203 static Sema::SpecialMemberOverloadResult
7204 lookupCallFromSpecialMember(Sema &S, CXXRecordDecl *Class,
7205                             CXXSpecialMemberKind CSM, unsigned FieldQuals,
7206                             bool ConstRHS) {
7207   unsigned LHSQuals = 0;
7208   if (CSM == CXXSpecialMemberKind::CopyAssignment ||
7209       CSM == CXXSpecialMemberKind::MoveAssignment)
7210     LHSQuals = FieldQuals;
7211 
7212   unsigned RHSQuals = FieldQuals;
7213   if (CSM == CXXSpecialMemberKind::DefaultConstructor ||
7214       CSM == CXXSpecialMemberKind::Destructor)
7215     RHSQuals = 0;
7216   else if (ConstRHS)
7217     RHSQuals |= Qualifiers::Const;
7218 
7219   return S.LookupSpecialMember(Class, CSM,
7220                                RHSQuals & Qualifiers::Const,
7221                                RHSQuals & Qualifiers::Volatile,
7222                                false,
7223                                LHSQuals & Qualifiers::Const,
7224                                LHSQuals & Qualifiers::Volatile);
7225 }
7226 
7227 class Sema::InheritedConstructorInfo {
7228   Sema &S;
7229   SourceLocation UseLoc;
7230 
7231   /// A mapping from the base classes through which the constructor was
7232   /// inherited to the using shadow declaration in that base class (or a null
7233   /// pointer if the constructor was declared in that base class).
7234   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
7235       InheritedFromBases;
7236 
7237 public:
7238   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
7239                            ConstructorUsingShadowDecl *Shadow)
7240       : S(S), UseLoc(UseLoc) {
7241     bool DiagnosedMultipleConstructedBases = false;
7242     CXXRecordDecl *ConstructedBase = nullptr;
7243     BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
7244 
7245     // Find the set of such base class subobjects and check that there's a
7246     // unique constructed subobject.
7247     for (auto *D : Shadow->redecls()) {
7248       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
7249       auto *DNominatedBase = DShadow->getNominatedBaseClass();
7250       auto *DConstructedBase = DShadow->getConstructedBaseClass();
7251 
7252       InheritedFromBases.insert(
7253           std::make_pair(DNominatedBase->getCanonicalDecl(),
7254                          DShadow->getNominatedBaseClassShadowDecl()));
7255       if (DShadow->constructsVirtualBase())
7256         InheritedFromBases.insert(
7257             std::make_pair(DConstructedBase->getCanonicalDecl(),
7258                            DShadow->getConstructedBaseClassShadowDecl()));
7259       else
7260         assert(DNominatedBase == DConstructedBase);
7261 
7262       // [class.inhctor.init]p2:
7263       //   If the constructor was inherited from multiple base class subobjects
7264       //   of type B, the program is ill-formed.
7265       if (!ConstructedBase) {
7266         ConstructedBase = DConstructedBase;
7267         ConstructedBaseIntroducer = D->getIntroducer();
7268       } else if (ConstructedBase != DConstructedBase &&
7269                  !Shadow->isInvalidDecl()) {
7270         if (!DiagnosedMultipleConstructedBases) {
7271           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
7272               << Shadow->getTargetDecl();
7273           S.Diag(ConstructedBaseIntroducer->getLocation(),
7274                  diag::note_ambiguous_inherited_constructor_using)
7275               << ConstructedBase;
7276           DiagnosedMultipleConstructedBases = true;
7277         }
7278         S.Diag(D->getIntroducer()->getLocation(),
7279                diag::note_ambiguous_inherited_constructor_using)
7280             << DConstructedBase;
7281       }
7282     }
7283 
7284     if (DiagnosedMultipleConstructedBases)
7285       Shadow->setInvalidDecl();
7286   }
7287 
7288   /// Find the constructor to use for inherited construction of a base class,
7289   /// and whether that base class constructor inherits the constructor from a
7290   /// virtual base class (in which case it won't actually invoke it).
7291   std::pair<CXXConstructorDecl *, bool>
7292   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
7293     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
7294     if (It == InheritedFromBases.end())
7295       return std::make_pair(nullptr, false);
7296 
7297     // This is an intermediary class.
7298     if (It->second)
7299       return std::make_pair(
7300           S.findInheritingConstructor(UseLoc, Ctor, It->second),
7301           It->second->constructsVirtualBase());
7302 
7303     // This is the base class from which the constructor was inherited.
7304     return std::make_pair(Ctor, false);
7305   }
7306 };
7307 
7308 /// Is the special member function which would be selected to perform the
7309 /// specified operation on the specified class type a constexpr constructor?
7310 static bool specialMemberIsConstexpr(
7311     Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, unsigned Quals,
7312     bool ConstRHS, CXXConstructorDecl *InheritedCtor = nullptr,
7313     Sema::InheritedConstructorInfo *Inherited = nullptr) {
7314   // Suppress duplicate constraint checking here, in case a constraint check
7315   // caused us to decide to do this.  Any truely recursive checks will get
7316   // caught during these checks anyway.
7317   Sema::SatisfactionStackResetRAII SSRAII{S};
7318 
7319   // If we're inheriting a constructor, see if we need to call it for this base
7320   // class.
7321   if (InheritedCtor) {
7322     assert(CSM == CXXSpecialMemberKind::DefaultConstructor);
7323     auto BaseCtor =
7324         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
7325     if (BaseCtor)
7326       return BaseCtor->isConstexpr();
7327   }
7328 
7329   if (CSM == CXXSpecialMemberKind::DefaultConstructor)
7330     return ClassDecl->hasConstexprDefaultConstructor();
7331   if (CSM == CXXSpecialMemberKind::Destructor)
7332     return ClassDecl->hasConstexprDestructor();
7333 
7334   Sema::SpecialMemberOverloadResult SMOR =
7335       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
7336   if (!SMOR.getMethod())
7337     // A constructor we wouldn't select can't be "involved in initializing"
7338     // anything.
7339     return true;
7340   return SMOR.getMethod()->isConstexpr();
7341 }
7342 
7343 /// Determine whether the specified special member function would be constexpr
7344 /// if it were implicitly defined.
7345 static bool defaultedSpecialMemberIsConstexpr(
7346     Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, bool ConstArg,
7347     CXXConstructorDecl *InheritedCtor = nullptr,
7348     Sema::InheritedConstructorInfo *Inherited = nullptr) {
7349   if (!S.getLangOpts().CPlusPlus11)
7350     return false;
7351 
7352   // C++11 [dcl.constexpr]p4:
7353   // In the definition of a constexpr constructor [...]
7354   bool Ctor = true;
7355   switch (CSM) {
7356   case CXXSpecialMemberKind::DefaultConstructor:
7357     if (Inherited)
7358       break;
7359     // Since default constructor lookup is essentially trivial (and cannot
7360     // involve, for instance, template instantiation), we compute whether a
7361     // defaulted default constructor is constexpr directly within CXXRecordDecl.
7362     //
7363     // This is important for performance; we need to know whether the default
7364     // constructor is constexpr to determine whether the type is a literal type.
7365     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7366 
7367   case CXXSpecialMemberKind::CopyConstructor:
7368   case CXXSpecialMemberKind::MoveConstructor:
7369     // For copy or move constructors, we need to perform overload resolution.
7370     break;
7371 
7372   case CXXSpecialMemberKind::CopyAssignment:
7373   case CXXSpecialMemberKind::MoveAssignment:
7374     if (!S.getLangOpts().CPlusPlus14)
7375       return false;
7376     // In C++1y, we need to perform overload resolution.
7377     Ctor = false;
7378     break;
7379 
7380   case CXXSpecialMemberKind::Destructor:
7381     return ClassDecl->defaultedDestructorIsConstexpr();
7382 
7383   case CXXSpecialMemberKind::Invalid:
7384     return false;
7385   }
7386 
7387   //   -- if the class is a non-empty union, or for each non-empty anonymous
7388   //      union member of a non-union class, exactly one non-static data member
7389   //      shall be initialized; [DR1359]
7390   //
7391   // If we squint, this is guaranteed, since exactly one non-static data member
7392   // will be initialized (if the constructor isn't deleted), we just don't know
7393   // which one.
7394   if (Ctor && ClassDecl->isUnion())
7395     return CSM == CXXSpecialMemberKind::DefaultConstructor
7396                ? ClassDecl->hasInClassInitializer() ||
7397                      !ClassDecl->hasVariantMembers()
7398                : true;
7399 
7400   //   -- the class shall not have any virtual base classes;
7401   if (Ctor && ClassDecl->getNumVBases())
7402     return false;
7403 
7404   // C++1y [class.copy]p26:
7405   //   -- [the class] is a literal type, and
7406   if (!Ctor && !ClassDecl->isLiteral() && !S.getLangOpts().CPlusPlus23)
7407     return false;
7408 
7409   //   -- every constructor involved in initializing [...] base class
7410   //      sub-objects shall be a constexpr constructor;
7411   //   -- the assignment operator selected to copy/move each direct base
7412   //      class is a constexpr function, and
7413   if (!S.getLangOpts().CPlusPlus23) {
7414     for (const auto &B : ClassDecl->bases()) {
7415       const RecordType *BaseType = B.getType()->getAs<RecordType>();
7416       if (!BaseType)
7417         continue;
7418       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7419       if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7420                                     InheritedCtor, Inherited))
7421         return false;
7422     }
7423   }
7424 
7425   //   -- every constructor involved in initializing non-static data members
7426   //      [...] shall be a constexpr constructor;
7427   //   -- every non-static data member and base class sub-object shall be
7428   //      initialized
7429   //   -- for each non-static data member of X that is of class type (or array
7430   //      thereof), the assignment operator selected to copy/move that member is
7431   //      a constexpr function
7432   if (!S.getLangOpts().CPlusPlus23) {
7433     for (const auto *F : ClassDecl->fields()) {
7434       if (F->isInvalidDecl())
7435         continue;
7436       if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
7437           F->hasInClassInitializer())
7438         continue;
7439       QualType BaseType = S.Context.getBaseElementType(F->getType());
7440       if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
7441         CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7442         if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7443                                       BaseType.getCVRQualifiers(),
7444                                       ConstArg && !F->isMutable()))
7445           return false;
7446       } else if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
7447         return false;
7448       }
7449     }
7450   }
7451 
7452   // All OK, it's constexpr!
7453   return true;
7454 }
7455 
7456 namespace {
7457 /// RAII object to register a defaulted function as having its exception
7458 /// specification computed.
7459 struct ComputingExceptionSpec {
7460   Sema &S;
7461 
7462   ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7463       : S(S) {
7464     Sema::CodeSynthesisContext Ctx;
7465     Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
7466     Ctx.PointOfInstantiation = Loc;
7467     Ctx.Entity = FD;
7468     S.pushCodeSynthesisContext(Ctx);
7469   }
7470   ~ComputingExceptionSpec() {
7471     S.popCodeSynthesisContext();
7472   }
7473 };
7474 }
7475 
7476 static Sema::ImplicitExceptionSpecification
7477 ComputeDefaultedSpecialMemberExceptionSpec(Sema &S, SourceLocation Loc,
7478                                            CXXMethodDecl *MD,
7479                                            CXXSpecialMemberKind CSM,
7480                                            Sema::InheritedConstructorInfo *ICI);
7481 
7482 static Sema::ImplicitExceptionSpecification
7483 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7484                                         FunctionDecl *FD,
7485                                         Sema::DefaultedComparisonKind DCK);
7486 
7487 static Sema::ImplicitExceptionSpecification
7488 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {
7489   auto DFK = S.getDefaultedFunctionKind(FD);
7490   if (DFK.isSpecialMember())
7491     return ComputeDefaultedSpecialMemberExceptionSpec(
7492         S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7493   if (DFK.isComparison())
7494     return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
7495                                                    DFK.asComparison());
7496 
7497   auto *CD = cast<CXXConstructorDecl>(FD);
7498   assert(CD->getInheritedConstructor() &&
7499          "only defaulted functions and inherited constructors have implicit "
7500          "exception specs");
7501   Sema::InheritedConstructorInfo ICI(
7502       S, Loc, CD->getInheritedConstructor().getShadowDecl());
7503   return ComputeDefaultedSpecialMemberExceptionSpec(
7504       S, Loc, CD, CXXSpecialMemberKind::DefaultConstructor, &ICI);
7505 }
7506 
7507 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
7508                                                             CXXMethodDecl *MD) {
7509   FunctionProtoType::ExtProtoInfo EPI;
7510 
7511   // Build an exception specification pointing back at this member.
7512   EPI.ExceptionSpec.Type = EST_Unevaluated;
7513   EPI.ExceptionSpec.SourceDecl = MD;
7514 
7515   // Set the calling convention to the default for C++ instance methods.
7516   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
7517       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7518                                             /*IsCXXMethod=*/true));
7519   return EPI;
7520 }
7521 
7522 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {
7523   const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7524   if (FPT->getExceptionSpecType() != EST_Unevaluated)
7525     return;
7526 
7527   // Evaluate the exception specification.
7528   auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7529   auto ESI = IES.getExceptionSpec();
7530 
7531   // Update the type of the special member to use it.
7532   UpdateExceptionSpec(FD, ESI);
7533 }
7534 
7535 void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
7536   assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7537 
7538   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
7539   if (!DefKind) {
7540     assert(FD->getDeclContext()->isDependentContext());
7541     return;
7542   }
7543 
7544   if (DefKind.isComparison())
7545     UnusedPrivateFields.clear();
7546 
7547   if (DefKind.isSpecialMember()
7548           ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
7549                                                   DefKind.asSpecialMember(),
7550                                                   FD->getDefaultLoc())
7551           : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison()))
7552     FD->setInvalidDecl();
7553 }
7554 
7555 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7556                                                  CXXSpecialMemberKind CSM,
7557                                                  SourceLocation DefaultLoc) {
7558   CXXRecordDecl *RD = MD->getParent();
7559 
7560   assert(MD->isExplicitlyDefaulted() && CSM != CXXSpecialMemberKind::Invalid &&
7561          "not an explicitly-defaulted special member");
7562 
7563   // Defer all checking for special members of a dependent type.
7564   if (RD->isDependentType())
7565     return false;
7566 
7567   // Whether this was the first-declared instance of the constructor.
7568   // This affects whether we implicitly add an exception spec and constexpr.
7569   bool First = MD == MD->getCanonicalDecl();
7570 
7571   bool HadError = false;
7572 
7573   // C++11 [dcl.fct.def.default]p1:
7574   //   A function that is explicitly defaulted shall
7575   //     -- be a special member function [...] (checked elsewhere),
7576   //     -- have the same type (except for ref-qualifiers, and except that a
7577   //        copy operation can take a non-const reference) as an implicit
7578   //        declaration, and
7579   //     -- not have default arguments.
7580   // C++2a changes the second bullet to instead delete the function if it's
7581   // defaulted on its first declaration, unless it's "an assignment operator,
7582   // and its return type differs or its parameter type is not a reference".
7583   bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7584   bool ShouldDeleteForTypeMismatch = false;
7585   unsigned ExpectedParams = 1;
7586   if (CSM == CXXSpecialMemberKind::DefaultConstructor ||
7587       CSM == CXXSpecialMemberKind::Destructor)
7588     ExpectedParams = 0;
7589   if (MD->getNumExplicitParams() != ExpectedParams) {
7590     // This checks for default arguments: a copy or move constructor with a
7591     // default argument is classified as a default constructor, and assignment
7592     // operations and destructors can't have default arguments.
7593     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7594         << llvm::to_underlying(CSM) << MD->getSourceRange();
7595     HadError = true;
7596   } else if (MD->isVariadic()) {
7597     if (DeleteOnTypeMismatch)
7598       ShouldDeleteForTypeMismatch = true;
7599     else {
7600       Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7601           << llvm::to_underlying(CSM) << MD->getSourceRange();
7602       HadError = true;
7603     }
7604   }
7605 
7606   const FunctionProtoType *Type = MD->getType()->castAs<FunctionProtoType>();
7607 
7608   bool CanHaveConstParam = false;
7609   if (CSM == CXXSpecialMemberKind::CopyConstructor)
7610     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7611   else if (CSM == CXXSpecialMemberKind::CopyAssignment)
7612     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7613 
7614   QualType ReturnType = Context.VoidTy;
7615   if (CSM == CXXSpecialMemberKind::CopyAssignment ||
7616       CSM == CXXSpecialMemberKind::MoveAssignment) {
7617     // Check for return type matching.
7618     ReturnType = Type->getReturnType();
7619     QualType ThisType = MD->getFunctionObjectParameterType();
7620 
7621     QualType DeclType = Context.getTypeDeclType(RD);
7622     DeclType = Context.getElaboratedType(ElaboratedTypeKeyword::None, nullptr,
7623                                          DeclType, nullptr);
7624     DeclType = Context.getAddrSpaceQualType(
7625         DeclType, ThisType.getQualifiers().getAddressSpace());
7626     QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7627 
7628     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7629       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7630           << (CSM == CXXSpecialMemberKind::MoveAssignment)
7631           << ExpectedReturnType;
7632       HadError = true;
7633     }
7634 
7635     // A defaulted special member cannot have cv-qualifiers.
7636     if (ThisType.isConstQualified() || ThisType.isVolatileQualified()) {
7637       if (DeleteOnTypeMismatch)
7638         ShouldDeleteForTypeMismatch = true;
7639       else {
7640         Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7641             << (CSM == CXXSpecialMemberKind::MoveAssignment)
7642             << getLangOpts().CPlusPlus14;
7643         HadError = true;
7644       }
7645     }
7646     // [C++23][dcl.fct.def.default]/p2.2
7647     // if F2 has an implicit object parameter of type “reference to C”,
7648     // F1 may be an explicit object member function whose explicit object
7649     // parameter is of (possibly different) type “reference to C”,
7650     // in which case the type of F1 would differ from the type of F2
7651     // in that the type of F1 has an additional parameter;
7652     if (!Context.hasSameType(
7653             ThisType.getNonReferenceType().getUnqualifiedType(),
7654             Context.getRecordType(RD))) {
7655       if (DeleteOnTypeMismatch)
7656         ShouldDeleteForTypeMismatch = true;
7657       else {
7658         Diag(MD->getLocation(),
7659              diag::err_defaulted_special_member_explicit_object_mismatch)
7660             << (CSM == CXXSpecialMemberKind::MoveAssignment) << RD
7661             << MD->getSourceRange();
7662         HadError = true;
7663       }
7664     }
7665   }
7666 
7667   // Check for parameter type matching.
7668   QualType ArgType =
7669       ExpectedParams
7670           ? Type->getParamType(MD->isExplicitObjectMemberFunction() ? 1 : 0)
7671           : QualType();
7672   bool HasConstParam = false;
7673   if (ExpectedParams && ArgType->isReferenceType()) {
7674     // Argument must be reference to possibly-const T.
7675     QualType ReferentType = ArgType->getPointeeType();
7676     HasConstParam = ReferentType.isConstQualified();
7677 
7678     if (ReferentType.isVolatileQualified()) {
7679       if (DeleteOnTypeMismatch)
7680         ShouldDeleteForTypeMismatch = true;
7681       else {
7682         Diag(MD->getLocation(),
7683              diag::err_defaulted_special_member_volatile_param)
7684             << llvm::to_underlying(CSM);
7685         HadError = true;
7686       }
7687     }
7688 
7689     if (HasConstParam && !CanHaveConstParam) {
7690       if (DeleteOnTypeMismatch)
7691         ShouldDeleteForTypeMismatch = true;
7692       else if (CSM == CXXSpecialMemberKind::CopyConstructor ||
7693                CSM == CXXSpecialMemberKind::CopyAssignment) {
7694         Diag(MD->getLocation(),
7695              diag::err_defaulted_special_member_copy_const_param)
7696             << (CSM == CXXSpecialMemberKind::CopyAssignment);
7697         // FIXME: Explain why this special member can't be const.
7698         HadError = true;
7699       } else {
7700         Diag(MD->getLocation(),
7701              diag::err_defaulted_special_member_move_const_param)
7702             << (CSM == CXXSpecialMemberKind::MoveAssignment);
7703         HadError = true;
7704       }
7705     }
7706   } else if (ExpectedParams) {
7707     // A copy assignment operator can take its argument by value, but a
7708     // defaulted one cannot.
7709     assert(CSM == CXXSpecialMemberKind::CopyAssignment &&
7710            "unexpected non-ref argument");
7711     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
7712     HadError = true;
7713   }
7714 
7715   // C++11 [dcl.fct.def.default]p2:
7716   //   An explicitly-defaulted function may be declared constexpr only if it
7717   //   would have been implicitly declared as constexpr,
7718   // Do not apply this rule to members of class templates, since core issue 1358
7719   // makes such functions always instantiate to constexpr functions. For
7720   // functions which cannot be constexpr (for non-constructors in C++11 and for
7721   // destructors in C++14 and C++17), this is checked elsewhere.
7722   //
7723   // FIXME: This should not apply if the member is deleted.
7724   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
7725                                                      HasConstParam);
7726 
7727   // C++14 [dcl.constexpr]p6 (CWG DR647/CWG DR1358):
7728   //   If the instantiated template specialization of a constexpr function
7729   //   template or member function of a class template would fail to satisfy
7730   //   the requirements for a constexpr function or constexpr constructor, that
7731   //   specialization is still a constexpr function or constexpr constructor,
7732   //   even though a call to such a function cannot appear in a constant
7733   //   expression.
7734   if (MD->isTemplateInstantiation() && MD->isConstexpr())
7735     Constexpr = true;
7736 
7737   if ((getLangOpts().CPlusPlus20 ||
7738        (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
7739                                   : isa<CXXConstructorDecl>(MD))) &&
7740       MD->isConstexpr() && !Constexpr &&
7741       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
7742         if (!MD->isConsteval() && RD->getNumVBases()) {
7743           Diag(MD->getBeginLoc(),
7744                diag::err_incorrect_defaulted_constexpr_with_vb)
7745               << llvm::to_underlying(CSM);
7746           for (const auto &I : RD->vbases())
7747             Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here);
7748         } else {
7749           Diag(MD->getBeginLoc(), diag::err_incorrect_defaulted_constexpr)
7750               << llvm::to_underlying(CSM) << MD->isConsteval();
7751         }
7752         HadError = true;
7753         // FIXME: Explain why the special member can't be constexpr.
7754   }
7755 
7756   if (First) {
7757     // C++2a [dcl.fct.def.default]p3:
7758     //   If a function is explicitly defaulted on its first declaration, it is
7759     //   implicitly considered to be constexpr if the implicit declaration
7760     //   would be.
7761     MD->setConstexprKind(Constexpr ? (MD->isConsteval()
7762                                           ? ConstexprSpecKind::Consteval
7763                                           : ConstexprSpecKind::Constexpr)
7764                                    : ConstexprSpecKind::Unspecified);
7765 
7766     if (!Type->hasExceptionSpec()) {
7767       // C++2a [except.spec]p3:
7768       //   If a declaration of a function does not have a noexcept-specifier
7769       //   [and] is defaulted on its first declaration, [...] the exception
7770       //   specification is as specified below
7771       FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
7772       EPI.ExceptionSpec.Type = EST_Unevaluated;
7773       EPI.ExceptionSpec.SourceDecl = MD;
7774       MD->setType(
7775           Context.getFunctionType(ReturnType, Type->getParamTypes(), EPI));
7776     }
7777   }
7778 
7779   if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
7780     if (First) {
7781       SetDeclDeleted(MD, MD->getLocation());
7782       if (!inTemplateInstantiation() && !HadError) {
7783         Diag(MD->getLocation(), diag::warn_defaulted_method_deleted)
7784             << llvm::to_underlying(CSM);
7785         if (ShouldDeleteForTypeMismatch) {
7786           Diag(MD->getLocation(), diag::note_deleted_type_mismatch)
7787               << llvm::to_underlying(CSM);
7788         } else if (ShouldDeleteSpecialMember(MD, CSM, nullptr,
7789                                              /*Diagnose*/ true) &&
7790                    DefaultLoc.isValid()) {
7791           Diag(DefaultLoc, diag::note_replace_equals_default_to_delete)
7792               << FixItHint::CreateReplacement(DefaultLoc, "delete");
7793         }
7794       }
7795       if (ShouldDeleteForTypeMismatch && !HadError) {
7796         Diag(MD->getLocation(),
7797              diag::warn_cxx17_compat_defaulted_method_type_mismatch)
7798             << llvm::to_underlying(CSM);
7799       }
7800     } else {
7801       // C++11 [dcl.fct.def.default]p4:
7802       //   [For a] user-provided explicitly-defaulted function [...] if such a
7803       //   function is implicitly defined as deleted, the program is ill-formed.
7804       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
7805           << llvm::to_underlying(CSM);
7806       assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
7807       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7808       HadError = true;
7809     }
7810   }
7811 
7812   return HadError;
7813 }
7814 
7815 namespace {
7816 /// Helper class for building and checking a defaulted comparison.
7817 ///
7818 /// Defaulted functions are built in two phases:
7819 ///
7820 ///  * First, the set of operations that the function will perform are
7821 ///    identified, and some of them are checked. If any of the checked
7822 ///    operations is invalid in certain ways, the comparison function is
7823 ///    defined as deleted and no body is built.
7824 ///  * Then, if the function is not defined as deleted, the body is built.
7825 ///
7826 /// This is accomplished by performing two visitation steps over the eventual
7827 /// body of the function.
7828 template<typename Derived, typename ResultList, typename Result,
7829          typename Subobject>
7830 class DefaultedComparisonVisitor {
7831 public:
7832   using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
7833 
7834   DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7835                              DefaultedComparisonKind DCK)
7836       : S(S), RD(RD), FD(FD), DCK(DCK) {
7837     if (auto *Info = FD->getDefalutedOrDeletedInfo()) {
7838       // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
7839       // UnresolvedSet to avoid this copy.
7840       Fns.assign(Info->getUnqualifiedLookups().begin(),
7841                  Info->getUnqualifiedLookups().end());
7842     }
7843   }
7844 
7845   ResultList visit() {
7846     // The type of an lvalue naming a parameter of this function.
7847     QualType ParamLvalType =
7848         FD->getParamDecl(0)->getType().getNonReferenceType();
7849 
7850     ResultList Results;
7851 
7852     switch (DCK) {
7853     case DefaultedComparisonKind::None:
7854       llvm_unreachable("not a defaulted comparison");
7855 
7856     case DefaultedComparisonKind::Equal:
7857     case DefaultedComparisonKind::ThreeWay:
7858       getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
7859       return Results;
7860 
7861     case DefaultedComparisonKind::NotEqual:
7862     case DefaultedComparisonKind::Relational:
7863       Results.add(getDerived().visitExpandedSubobject(
7864           ParamLvalType, getDerived().getCompleteObject()));
7865       return Results;
7866     }
7867     llvm_unreachable("");
7868   }
7869 
7870 protected:
7871   Derived &getDerived() { return static_cast<Derived&>(*this); }
7872 
7873   /// Visit the expanded list of subobjects of the given type, as specified in
7874   /// C++2a [class.compare.default].
7875   ///
7876   /// \return \c true if the ResultList object said we're done, \c false if not.
7877   bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
7878                        Qualifiers Quals) {
7879     // C++2a [class.compare.default]p4:
7880     //   The direct base class subobjects of C
7881     for (CXXBaseSpecifier &Base : Record->bases())
7882       if (Results.add(getDerived().visitSubobject(
7883               S.Context.getQualifiedType(Base.getType(), Quals),
7884               getDerived().getBase(&Base))))
7885         return true;
7886 
7887     //   followed by the non-static data members of C
7888     for (FieldDecl *Field : Record->fields()) {
7889       // C++23 [class.bit]p2:
7890       //   Unnamed bit-fields are not members ...
7891       if (Field->isUnnamedBitField())
7892         continue;
7893       // Recursively expand anonymous structs.
7894       if (Field->isAnonymousStructOrUnion()) {
7895         if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
7896                             Quals))
7897           return true;
7898         continue;
7899       }
7900 
7901       // Figure out the type of an lvalue denoting this field.
7902       Qualifiers FieldQuals = Quals;
7903       if (Field->isMutable())
7904         FieldQuals.removeConst();
7905       QualType FieldType =
7906           S.Context.getQualifiedType(Field->getType(), FieldQuals);
7907 
7908       if (Results.add(getDerived().visitSubobject(
7909               FieldType, getDerived().getField(Field))))
7910         return true;
7911     }
7912 
7913     //   form a list of subobjects.
7914     return false;
7915   }
7916 
7917   Result visitSubobject(QualType Type, Subobject Subobj) {
7918     //   In that list, any subobject of array type is recursively expanded
7919     const ArrayType *AT = S.Context.getAsArrayType(Type);
7920     if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
7921       return getDerived().visitSubobjectArray(CAT->getElementType(),
7922                                               CAT->getSize(), Subobj);
7923     return getDerived().visitExpandedSubobject(Type, Subobj);
7924   }
7925 
7926   Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
7927                              Subobject Subobj) {
7928     return getDerived().visitSubobject(Type, Subobj);
7929   }
7930 
7931 protected:
7932   Sema &S;
7933   CXXRecordDecl *RD;
7934   FunctionDecl *FD;
7935   DefaultedComparisonKind DCK;
7936   UnresolvedSet<16> Fns;
7937 };
7938 
7939 /// Information about a defaulted comparison, as determined by
7940 /// DefaultedComparisonAnalyzer.
7941 struct DefaultedComparisonInfo {
7942   bool Deleted = false;
7943   bool Constexpr = true;
7944   ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
7945 
7946   static DefaultedComparisonInfo deleted() {
7947     DefaultedComparisonInfo Deleted;
7948     Deleted.Deleted = true;
7949     return Deleted;
7950   }
7951 
7952   bool add(const DefaultedComparisonInfo &R) {
7953     Deleted |= R.Deleted;
7954     Constexpr &= R.Constexpr;
7955     Category = commonComparisonType(Category, R.Category);
7956     return Deleted;
7957   }
7958 };
7959 
7960 /// An element in the expanded list of subobjects of a defaulted comparison, as
7961 /// specified in C++2a [class.compare.default]p4.
7962 struct DefaultedComparisonSubobject {
7963   enum { CompleteObject, Member, Base } Kind;
7964   NamedDecl *Decl;
7965   SourceLocation Loc;
7966 };
7967 
7968 /// A visitor over the notional body of a defaulted comparison that determines
7969 /// whether that body would be deleted or constexpr.
7970 class DefaultedComparisonAnalyzer
7971     : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
7972                                         DefaultedComparisonInfo,
7973                                         DefaultedComparisonInfo,
7974                                         DefaultedComparisonSubobject> {
7975 public:
7976   enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
7977 
7978 private:
7979   DiagnosticKind Diagnose;
7980 
7981 public:
7982   using Base = DefaultedComparisonVisitor;
7983   using Result = DefaultedComparisonInfo;
7984   using Subobject = DefaultedComparisonSubobject;
7985 
7986   friend Base;
7987 
7988   DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7989                               DefaultedComparisonKind DCK,
7990                               DiagnosticKind Diagnose = NoDiagnostics)
7991       : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
7992 
7993   Result visit() {
7994     if ((DCK == DefaultedComparisonKind::Equal ||
7995          DCK == DefaultedComparisonKind::ThreeWay) &&
7996         RD->hasVariantMembers()) {
7997       // C++2a [class.compare.default]p2 [P2002R0]:
7998       //   A defaulted comparison operator function for class C is defined as
7999       //   deleted if [...] C has variant members.
8000       if (Diagnose == ExplainDeleted) {
8001         S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
8002           << FD << RD->isUnion() << RD;
8003       }
8004       return Result::deleted();
8005     }
8006 
8007     return Base::visit();
8008   }
8009 
8010 private:
8011   Subobject getCompleteObject() {
8012     return Subobject{Subobject::CompleteObject, RD, FD->getLocation()};
8013   }
8014 
8015   Subobject getBase(CXXBaseSpecifier *Base) {
8016     return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
8017                      Base->getBaseTypeLoc()};
8018   }
8019 
8020   Subobject getField(FieldDecl *Field) {
8021     return Subobject{Subobject::Member, Field, Field->getLocation()};
8022   }
8023 
8024   Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
8025     // C++2a [class.compare.default]p2 [P2002R0]:
8026     //   A defaulted <=> or == operator function for class C is defined as
8027     //   deleted if any non-static data member of C is of reference type
8028     if (Type->isReferenceType()) {
8029       if (Diagnose == ExplainDeleted) {
8030         S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
8031             << FD << RD;
8032       }
8033       return Result::deleted();
8034     }
8035 
8036     // [...] Let xi be an lvalue denoting the ith element [...]
8037     OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
8038     Expr *Args[] = {&Xi, &Xi};
8039 
8040     // All operators start by trying to apply that same operator recursively.
8041     OverloadedOperatorKind OO = FD->getOverloadedOperator();
8042     assert(OO != OO_None && "not an overloaded operator!");
8043     return visitBinaryOperator(OO, Args, Subobj);
8044   }
8045 
8046   Result
8047   visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
8048                       Subobject Subobj,
8049                       OverloadCandidateSet *SpaceshipCandidates = nullptr) {
8050     // Note that there is no need to consider rewritten candidates here if
8051     // we've already found there is no viable 'operator<=>' candidate (and are
8052     // considering synthesizing a '<=>' from '==' and '<').
8053     OverloadCandidateSet CandidateSet(
8054         FD->getLocation(), OverloadCandidateSet::CSK_Operator,
8055         OverloadCandidateSet::OperatorRewriteInfo(
8056             OO, FD->getLocation(),
8057             /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
8058 
8059     /// C++2a [class.compare.default]p1 [P2002R0]:
8060     ///   [...] the defaulted function itself is never a candidate for overload
8061     ///   resolution [...]
8062     CandidateSet.exclude(FD);
8063 
8064     if (Args[0]->getType()->isOverloadableType())
8065       S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
8066     else
8067       // FIXME: We determine whether this is a valid expression by checking to
8068       // see if there's a viable builtin operator candidate for it. That isn't
8069       // really what the rules ask us to do, but should give the right results.
8070       S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
8071 
8072     Result R;
8073 
8074     OverloadCandidateSet::iterator Best;
8075     switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
8076     case OR_Success: {
8077       // C++2a [class.compare.secondary]p2 [P2002R0]:
8078       //   The operator function [...] is defined as deleted if [...] the
8079       //   candidate selected by overload resolution is not a rewritten
8080       //   candidate.
8081       if ((DCK == DefaultedComparisonKind::NotEqual ||
8082            DCK == DefaultedComparisonKind::Relational) &&
8083           !Best->RewriteKind) {
8084         if (Diagnose == ExplainDeleted) {
8085           if (Best->Function) {
8086             S.Diag(Best->Function->getLocation(),
8087                    diag::note_defaulted_comparison_not_rewritten_callee)
8088                 << FD;
8089           } else {
8090             assert(Best->Conversions.size() == 2 &&
8091                    Best->Conversions[0].isUserDefined() &&
8092                    "non-user-defined conversion from class to built-in "
8093                    "comparison");
8094             S.Diag(Best->Conversions[0]
8095                        .UserDefined.FoundConversionFunction.getDecl()
8096                        ->getLocation(),
8097                    diag::note_defaulted_comparison_not_rewritten_conversion)
8098                 << FD;
8099           }
8100         }
8101         return Result::deleted();
8102       }
8103 
8104       // Throughout C++2a [class.compare]: if overload resolution does not
8105       // result in a usable function, the candidate function is defined as
8106       // deleted. This requires that we selected an accessible function.
8107       //
8108       // Note that this only considers the access of the function when named
8109       // within the type of the subobject, and not the access path for any
8110       // derived-to-base conversion.
8111       CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
8112       if (ArgClass && Best->FoundDecl.getDecl() &&
8113           Best->FoundDecl.getDecl()->isCXXClassMember()) {
8114         QualType ObjectType = Subobj.Kind == Subobject::Member
8115                                   ? Args[0]->getType()
8116                                   : S.Context.getRecordType(RD);
8117         if (!S.isMemberAccessibleForDeletion(
8118                 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
8119                 Diagnose == ExplainDeleted
8120                     ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
8121                           << FD << Subobj.Kind << Subobj.Decl
8122                     : S.PDiag()))
8123           return Result::deleted();
8124       }
8125 
8126       bool NeedsDeducing =
8127           OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
8128 
8129       if (FunctionDecl *BestFD = Best->Function) {
8130         // C++2a [class.compare.default]p3 [P2002R0]:
8131         //   A defaulted comparison function is constexpr-compatible if
8132         //   [...] no overlod resolution performed [...] results in a
8133         //   non-constexpr function.
8134         assert(!BestFD->isDeleted() && "wrong overload resolution result");
8135         // If it's not constexpr, explain why not.
8136         if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
8137           if (Subobj.Kind != Subobject::CompleteObject)
8138             S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
8139               << Subobj.Kind << Subobj.Decl;
8140           S.Diag(BestFD->getLocation(),
8141                  diag::note_defaulted_comparison_not_constexpr_here);
8142           // Bail out after explaining; we don't want any more notes.
8143           return Result::deleted();
8144         }
8145         R.Constexpr &= BestFD->isConstexpr();
8146 
8147         if (NeedsDeducing) {
8148           // If any callee has an undeduced return type, deduce it now.
8149           // FIXME: It's not clear how a failure here should be handled. For
8150           // now, we produce an eager diagnostic, because that is forward
8151           // compatible with most (all?) other reasonable options.
8152           if (BestFD->getReturnType()->isUndeducedType() &&
8153               S.DeduceReturnType(BestFD, FD->getLocation(),
8154                                  /*Diagnose=*/false)) {
8155             // Don't produce a duplicate error when asked to explain why the
8156             // comparison is deleted: we diagnosed that when initially checking
8157             // the defaulted operator.
8158             if (Diagnose == NoDiagnostics) {
8159               S.Diag(
8160                   FD->getLocation(),
8161                   diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
8162                   << Subobj.Kind << Subobj.Decl;
8163               S.Diag(
8164                   Subobj.Loc,
8165                   diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
8166                   << Subobj.Kind << Subobj.Decl;
8167               S.Diag(BestFD->getLocation(),
8168                      diag::note_defaulted_comparison_cannot_deduce_callee)
8169                   << Subobj.Kind << Subobj.Decl;
8170             }
8171             return Result::deleted();
8172           }
8173           auto *Info = S.Context.CompCategories.lookupInfoForType(
8174               BestFD->getCallResultType());
8175           if (!Info) {
8176             if (Diagnose == ExplainDeleted) {
8177               S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
8178                   << Subobj.Kind << Subobj.Decl
8179                   << BestFD->getCallResultType().withoutLocalFastQualifiers();
8180               S.Diag(BestFD->getLocation(),
8181                      diag::note_defaulted_comparison_cannot_deduce_callee)
8182                   << Subobj.Kind << Subobj.Decl;
8183             }
8184             return Result::deleted();
8185           }
8186           R.Category = Info->Kind;
8187         }
8188       } else {
8189         QualType T = Best->BuiltinParamTypes[0];
8190         assert(T == Best->BuiltinParamTypes[1] &&
8191                "builtin comparison for different types?");
8192         assert(Best->BuiltinParamTypes[2].isNull() &&
8193                "invalid builtin comparison");
8194 
8195         if (NeedsDeducing) {
8196           std::optional<ComparisonCategoryType> Cat =
8197               getComparisonCategoryForBuiltinCmp(T);
8198           assert(Cat && "no category for builtin comparison?");
8199           R.Category = *Cat;
8200         }
8201       }
8202 
8203       // Note that we might be rewriting to a different operator. That call is
8204       // not considered until we come to actually build the comparison function.
8205       break;
8206     }
8207 
8208     case OR_Ambiguous:
8209       if (Diagnose == ExplainDeleted) {
8210         unsigned Kind = 0;
8211         if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
8212           Kind = OO == OO_EqualEqual ? 1 : 2;
8213         CandidateSet.NoteCandidates(
8214             PartialDiagnosticAt(
8215                 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
8216                                 << FD << Kind << Subobj.Kind << Subobj.Decl),
8217             S, OCD_AmbiguousCandidates, Args);
8218       }
8219       R = Result::deleted();
8220       break;
8221 
8222     case OR_Deleted:
8223       if (Diagnose == ExplainDeleted) {
8224         if ((DCK == DefaultedComparisonKind::NotEqual ||
8225              DCK == DefaultedComparisonKind::Relational) &&
8226             !Best->RewriteKind) {
8227           S.Diag(Best->Function->getLocation(),
8228                  diag::note_defaulted_comparison_not_rewritten_callee)
8229               << FD;
8230         } else {
8231           S.Diag(Subobj.Loc,
8232                  diag::note_defaulted_comparison_calls_deleted)
8233               << FD << Subobj.Kind << Subobj.Decl;
8234           S.NoteDeletedFunction(Best->Function);
8235         }
8236       }
8237       R = Result::deleted();
8238       break;
8239 
8240     case OR_No_Viable_Function:
8241       // If there's no usable candidate, we're done unless we can rewrite a
8242       // '<=>' in terms of '==' and '<'.
8243       if (OO == OO_Spaceship &&
8244           S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) {
8245         // For any kind of comparison category return type, we need a usable
8246         // '==' and a usable '<'.
8247         if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
8248                                        &CandidateSet)))
8249           R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
8250         break;
8251       }
8252 
8253       if (Diagnose == ExplainDeleted) {
8254         S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
8255             << FD << (OO == OO_EqualEqual || OO == OO_ExclaimEqual)
8256             << Subobj.Kind << Subobj.Decl;
8257 
8258         // For a three-way comparison, list both the candidates for the
8259         // original operator and the candidates for the synthesized operator.
8260         if (SpaceshipCandidates) {
8261           SpaceshipCandidates->NoteCandidates(
8262               S, Args,
8263               SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
8264                                                       Args, FD->getLocation()));
8265           S.Diag(Subobj.Loc,
8266                  diag::note_defaulted_comparison_no_viable_function_synthesized)
8267               << (OO == OO_EqualEqual ? 0 : 1);
8268         }
8269 
8270         CandidateSet.NoteCandidates(
8271             S, Args,
8272             CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
8273                                             FD->getLocation()));
8274       }
8275       R = Result::deleted();
8276       break;
8277     }
8278 
8279     return R;
8280   }
8281 };
8282 
8283 /// A list of statements.
8284 struct StmtListResult {
8285   bool IsInvalid = false;
8286   llvm::SmallVector<Stmt*, 16> Stmts;
8287 
8288   bool add(const StmtResult &S) {
8289     IsInvalid |= S.isInvalid();
8290     if (IsInvalid)
8291       return true;
8292     Stmts.push_back(S.get());
8293     return false;
8294   }
8295 };
8296 
8297 /// A visitor over the notional body of a defaulted comparison that synthesizes
8298 /// the actual body.
8299 class DefaultedComparisonSynthesizer
8300     : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
8301                                         StmtListResult, StmtResult,
8302                                         std::pair<ExprResult, ExprResult>> {
8303   SourceLocation Loc;
8304   unsigned ArrayDepth = 0;
8305 
8306 public:
8307   using Base = DefaultedComparisonVisitor;
8308   using ExprPair = std::pair<ExprResult, ExprResult>;
8309 
8310   friend Base;
8311 
8312   DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8313                                  DefaultedComparisonKind DCK,
8314                                  SourceLocation BodyLoc)
8315       : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
8316 
8317   /// Build a suitable function body for this defaulted comparison operator.
8318   StmtResult build() {
8319     Sema::CompoundScopeRAII CompoundScope(S);
8320 
8321     StmtListResult Stmts = visit();
8322     if (Stmts.IsInvalid)
8323       return StmtError();
8324 
8325     ExprResult RetVal;
8326     switch (DCK) {
8327     case DefaultedComparisonKind::None:
8328       llvm_unreachable("not a defaulted comparison");
8329 
8330     case DefaultedComparisonKind::Equal: {
8331       // C++2a [class.eq]p3:
8332       //   [...] compar[e] the corresponding elements [...] until the first
8333       //   index i where xi == yi yields [...] false. If no such index exists,
8334       //   V is true. Otherwise, V is false.
8335       //
8336       // Join the comparisons with '&&'s and return the result. Use a right
8337       // fold (traversing the conditions right-to-left), because that
8338       // short-circuits more naturally.
8339       auto OldStmts = std::move(Stmts.Stmts);
8340       Stmts.Stmts.clear();
8341       ExprResult CmpSoFar;
8342       // Finish a particular comparison chain.
8343       auto FinishCmp = [&] {
8344         if (Expr *Prior = CmpSoFar.get()) {
8345           // Convert the last expression to 'return ...;'
8346           if (RetVal.isUnset() && Stmts.Stmts.empty())
8347             RetVal = CmpSoFar;
8348           // Convert any prior comparison to 'if (!(...)) return false;'
8349           else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
8350             return true;
8351           CmpSoFar = ExprResult();
8352         }
8353         return false;
8354       };
8355       for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
8356         Expr *E = dyn_cast<Expr>(EAsStmt);
8357         if (!E) {
8358           // Found an array comparison.
8359           if (FinishCmp() || Stmts.add(EAsStmt))
8360             return StmtError();
8361           continue;
8362         }
8363 
8364         if (CmpSoFar.isUnset()) {
8365           CmpSoFar = E;
8366           continue;
8367         }
8368         CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
8369         if (CmpSoFar.isInvalid())
8370           return StmtError();
8371       }
8372       if (FinishCmp())
8373         return StmtError();
8374       std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
8375       //   If no such index exists, V is true.
8376       if (RetVal.isUnset())
8377         RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
8378       break;
8379     }
8380 
8381     case DefaultedComparisonKind::ThreeWay: {
8382       // Per C++2a [class.spaceship]p3, as a fallback add:
8383       // return static_cast<R>(std::strong_ordering::equal);
8384       QualType StrongOrdering = S.CheckComparisonCategoryType(
8385           ComparisonCategoryType::StrongOrdering, Loc,
8386           Sema::ComparisonCategoryUsage::DefaultedOperator);
8387       if (StrongOrdering.isNull())
8388         return StmtError();
8389       VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)
8390                              .getValueInfo(ComparisonCategoryResult::Equal)
8391                              ->VD;
8392       RetVal = getDecl(EqualVD);
8393       if (RetVal.isInvalid())
8394         return StmtError();
8395       RetVal = buildStaticCastToR(RetVal.get());
8396       break;
8397     }
8398 
8399     case DefaultedComparisonKind::NotEqual:
8400     case DefaultedComparisonKind::Relational:
8401       RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
8402       break;
8403     }
8404 
8405     // Build the final return statement.
8406     if (RetVal.isInvalid())
8407       return StmtError();
8408     StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
8409     if (ReturnStmt.isInvalid())
8410       return StmtError();
8411     Stmts.Stmts.push_back(ReturnStmt.get());
8412 
8413     return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
8414   }
8415 
8416 private:
8417   ExprResult getDecl(ValueDecl *VD) {
8418     return S.BuildDeclarationNameExpr(
8419         CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8420   }
8421 
8422   ExprResult getParam(unsigned I) {
8423     ParmVarDecl *PD = FD->getParamDecl(I);
8424     return getDecl(PD);
8425   }
8426 
8427   ExprPair getCompleteObject() {
8428     unsigned Param = 0;
8429     ExprResult LHS;
8430     if (const auto *MD = dyn_cast<CXXMethodDecl>(FD);
8431         MD && MD->isImplicitObjectMemberFunction()) {
8432       // LHS is '*this'.
8433       LHS = S.ActOnCXXThis(Loc);
8434       if (!LHS.isInvalid())
8435         LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
8436     } else {
8437       LHS = getParam(Param++);
8438     }
8439     ExprResult RHS = getParam(Param++);
8440     assert(Param == FD->getNumParams());
8441     return {LHS, RHS};
8442   }
8443 
8444   ExprPair getBase(CXXBaseSpecifier *Base) {
8445     ExprPair Obj = getCompleteObject();
8446     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8447       return {ExprError(), ExprError()};
8448     CXXCastPath Path = {Base};
8449     return {S.ImpCastExprToType(Obj.first.get(), Base->getType(),
8450                                 CK_DerivedToBase, VK_LValue, &Path),
8451             S.ImpCastExprToType(Obj.second.get(), Base->getType(),
8452                                 CK_DerivedToBase, VK_LValue, &Path)};
8453   }
8454 
8455   ExprPair getField(FieldDecl *Field) {
8456     ExprPair Obj = getCompleteObject();
8457     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8458       return {ExprError(), ExprError()};
8459 
8460     DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8461     DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8462     return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8463                                       CXXScopeSpec(), Field, Found, NameInfo),
8464             S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8465                                       CXXScopeSpec(), Field, Found, NameInfo)};
8466   }
8467 
8468   // FIXME: When expanding a subobject, register a note in the code synthesis
8469   // stack to say which subobject we're comparing.
8470 
8471   StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8472     if (Cond.isInvalid())
8473       return StmtError();
8474 
8475     ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8476     if (NotCond.isInvalid())
8477       return StmtError();
8478 
8479     ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8480     assert(!False.isInvalid() && "should never fail");
8481     StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8482     if (ReturnFalse.isInvalid())
8483       return StmtError();
8484 
8485     return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, nullptr,
8486                          S.ActOnCondition(nullptr, Loc, NotCond.get(),
8487                                           Sema::ConditionKind::Boolean),
8488                          Loc, ReturnFalse.get(), SourceLocation(), nullptr);
8489   }
8490 
8491   StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8492                                  ExprPair Subobj) {
8493     QualType SizeType = S.Context.getSizeType();
8494     Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8495 
8496     // Build 'size_t i$n = 0'.
8497     IdentifierInfo *IterationVarName = nullptr;
8498     {
8499       SmallString<8> Str;
8500       llvm::raw_svector_ostream OS(Str);
8501       OS << "i" << ArrayDepth;
8502       IterationVarName = &S.Context.Idents.get(OS.str());
8503     }
8504     VarDecl *IterationVar = VarDecl::Create(
8505         S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8506         S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
8507     llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8508     IterationVar->setInit(
8509         IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8510     Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8511 
8512     auto IterRef = [&] {
8513       ExprResult Ref = S.BuildDeclarationNameExpr(
8514           CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8515           IterationVar);
8516       assert(!Ref.isInvalid() && "can't reference our own variable?");
8517       return Ref.get();
8518     };
8519 
8520     // Build 'i$n != Size'.
8521     ExprResult Cond = S.CreateBuiltinBinOp(
8522         Loc, BO_NE, IterRef(),
8523         IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8524     assert(!Cond.isInvalid() && "should never fail");
8525 
8526     // Build '++i$n'.
8527     ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8528     assert(!Inc.isInvalid() && "should never fail");
8529 
8530     // Build 'a[i$n]' and 'b[i$n]'.
8531     auto Index = [&](ExprResult E) {
8532       if (E.isInvalid())
8533         return ExprError();
8534       return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8535     };
8536     Subobj.first = Index(Subobj.first);
8537     Subobj.second = Index(Subobj.second);
8538 
8539     // Compare the array elements.
8540     ++ArrayDepth;
8541     StmtResult Substmt = visitSubobject(Type, Subobj);
8542     --ArrayDepth;
8543 
8544     if (Substmt.isInvalid())
8545       return StmtError();
8546 
8547     // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8548     // For outer levels or for an 'operator<=>' we already have a suitable
8549     // statement that returns as necessary.
8550     if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8551       assert(DCK == DefaultedComparisonKind::Equal &&
8552              "should have non-expression statement");
8553       Substmt = buildIfNotCondReturnFalse(ElemCmp);
8554       if (Substmt.isInvalid())
8555         return StmtError();
8556     }
8557 
8558     // Build 'for (...) ...'
8559     return S.ActOnForStmt(Loc, Loc, Init,
8560                           S.ActOnCondition(nullptr, Loc, Cond.get(),
8561                                            Sema::ConditionKind::Boolean),
8562                           S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
8563                           Substmt.get());
8564   }
8565 
8566   StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8567     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8568       return StmtError();
8569 
8570     OverloadedOperatorKind OO = FD->getOverloadedOperator();
8571     BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO);
8572     ExprResult Op;
8573     if (Type->isOverloadableType())
8574       Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8575                                    Obj.second.get(), /*PerformADL=*/true,
8576                                    /*AllowRewrittenCandidates=*/true, FD);
8577     else
8578       Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8579     if (Op.isInvalid())
8580       return StmtError();
8581 
8582     switch (DCK) {
8583     case DefaultedComparisonKind::None:
8584       llvm_unreachable("not a defaulted comparison");
8585 
8586     case DefaultedComparisonKind::Equal:
8587       // Per C++2a [class.eq]p2, each comparison is individually contextually
8588       // converted to bool.
8589       Op = S.PerformContextuallyConvertToBool(Op.get());
8590       if (Op.isInvalid())
8591         return StmtError();
8592       return Op.get();
8593 
8594     case DefaultedComparisonKind::ThreeWay: {
8595       // Per C++2a [class.spaceship]p3, form:
8596       //   if (R cmp = static_cast<R>(op); cmp != 0)
8597       //     return cmp;
8598       QualType R = FD->getReturnType();
8599       Op = buildStaticCastToR(Op.get());
8600       if (Op.isInvalid())
8601         return StmtError();
8602 
8603       // R cmp = ...;
8604       IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8605       VarDecl *VD =
8606           VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8607                           S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None);
8608       S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8609       Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8610 
8611       // cmp != 0
8612       ExprResult VDRef = getDecl(VD);
8613       if (VDRef.isInvalid())
8614         return StmtError();
8615       llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8616       Expr *Zero =
8617           IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8618       ExprResult Comp;
8619       if (VDRef.get()->getType()->isOverloadableType())
8620         Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8621                                        true, FD);
8622       else
8623         Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8624       if (Comp.isInvalid())
8625         return StmtError();
8626       Sema::ConditionResult Cond = S.ActOnCondition(
8627           nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8628       if (Cond.isInvalid())
8629         return StmtError();
8630 
8631       // return cmp;
8632       VDRef = getDecl(VD);
8633       if (VDRef.isInvalid())
8634         return StmtError();
8635       StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
8636       if (ReturnStmt.isInvalid())
8637         return StmtError();
8638 
8639       // if (...)
8640       return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, InitStmt, Cond,
8641                            Loc, ReturnStmt.get(),
8642                            /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
8643     }
8644 
8645     case DefaultedComparisonKind::NotEqual:
8646     case DefaultedComparisonKind::Relational:
8647       // C++2a [class.compare.secondary]p2:
8648       //   Otherwise, the operator function yields x @ y.
8649       return Op.get();
8650     }
8651     llvm_unreachable("");
8652   }
8653 
8654   /// Build "static_cast<R>(E)".
8655   ExprResult buildStaticCastToR(Expr *E) {
8656     QualType R = FD->getReturnType();
8657     assert(!R->isUndeducedType() && "type should have been deduced already");
8658 
8659     // Don't bother forming a no-op cast in the common case.
8660     if (E->isPRValue() && S.Context.hasSameType(E->getType(), R))
8661       return E;
8662     return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8663                                S.Context.getTrivialTypeSourceInfo(R, Loc), E,
8664                                SourceRange(Loc, Loc), SourceRange(Loc, Loc));
8665   }
8666 };
8667 }
8668 
8669 /// Perform the unqualified lookups that might be needed to form a defaulted
8670 /// comparison function for the given operator.
8671 static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S,
8672                                                   UnresolvedSetImpl &Operators,
8673                                                   OverloadedOperatorKind Op) {
8674   auto Lookup = [&](OverloadedOperatorKind OO) {
8675     Self.LookupOverloadedOperatorName(OO, S, Operators);
8676   };
8677 
8678   // Every defaulted operator looks up itself.
8679   Lookup(Op);
8680   // ... and the rewritten form of itself, if any.
8681   if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op))
8682     Lookup(ExtraOp);
8683 
8684   // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8685   // synthesize a three-way comparison from '<' and '=='. In a dependent
8686   // context, we also need to look up '==' in case we implicitly declare a
8687   // defaulted 'operator=='.
8688   if (Op == OO_Spaceship) {
8689     Lookup(OO_ExclaimEqual);
8690     Lookup(OO_Less);
8691     Lookup(OO_EqualEqual);
8692   }
8693 }
8694 
8695 bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD,
8696                                               DefaultedComparisonKind DCK) {
8697   assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
8698 
8699   // Perform any unqualified lookups we're going to need to default this
8700   // function.
8701   if (S) {
8702     UnresolvedSet<32> Operators;
8703     lookupOperatorsForDefaultedComparison(*this, S, Operators,
8704                                           FD->getOverloadedOperator());
8705     FD->setDefaultedOrDeletedInfo(
8706         FunctionDecl::DefaultedOrDeletedFunctionInfo::Create(
8707             Context, Operators.pairs()));
8708   }
8709 
8710   // C++2a [class.compare.default]p1:
8711   //   A defaulted comparison operator function for some class C shall be a
8712   //   non-template function declared in the member-specification of C that is
8713   //    -- a non-static const non-volatile member of C having one parameter of
8714   //       type const C& and either no ref-qualifier or the ref-qualifier &, or
8715   //    -- a friend of C having two parameters of type const C& or two
8716   //       parameters of type C.
8717 
8718   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
8719   bool IsMethod = isa<CXXMethodDecl>(FD);
8720   if (IsMethod) {
8721     auto *MD = cast<CXXMethodDecl>(FD);
8722     assert(!MD->isStatic() && "comparison function cannot be a static member");
8723 
8724     if (MD->getRefQualifier() == RQ_RValue) {
8725       Diag(MD->getLocation(), diag::err_ref_qualifier_comparison_operator);
8726 
8727       // Remove the ref qualifier to recover.
8728       const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8729       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8730       EPI.RefQualifier = RQ_None;
8731       MD->setType(Context.getFunctionType(FPT->getReturnType(),
8732                                           FPT->getParamTypes(), EPI));
8733     }
8734 
8735     // If we're out-of-class, this is the class we're comparing.
8736     if (!RD)
8737       RD = MD->getParent();
8738     QualType T = MD->getFunctionObjectParameterType();
8739     if (!T.isConstQualified()) {
8740       SourceLocation Loc, InsertLoc;
8741       if (MD->isExplicitObjectMemberFunction()) {
8742         Loc = MD->getParamDecl(0)->getBeginLoc();
8743         InsertLoc = getLocForEndOfToken(
8744             MD->getParamDecl(0)->getExplicitObjectParamThisLoc());
8745       } else {
8746         Loc = MD->getLocation();
8747         if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
8748           InsertLoc = Loc.getRParenLoc();
8749       }
8750       // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8751       // corresponding defaulted 'operator<=>' already.
8752       if (!MD->isImplicit()) {
8753         Diag(Loc, diag::err_defaulted_comparison_non_const)
8754             << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
8755       }
8756 
8757       // Add the 'const' to the type to recover.
8758       const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8759       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8760       EPI.TypeQuals.addConst();
8761       MD->setType(Context.getFunctionType(FPT->getReturnType(),
8762                                           FPT->getParamTypes(), EPI));
8763     }
8764 
8765     if (MD->isVolatile()) {
8766       Diag(MD->getLocation(), diag::err_volatile_comparison_operator);
8767 
8768       // Remove the 'volatile' from the type to recover.
8769       const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8770       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8771       EPI.TypeQuals.removeVolatile();
8772       MD->setType(Context.getFunctionType(FPT->getReturnType(),
8773                                           FPT->getParamTypes(), EPI));
8774     }
8775   }
8776 
8777   if ((FD->getNumParams() -
8778        (unsigned)FD->hasCXXExplicitFunctionObjectParameter()) !=
8779       (IsMethod ? 1 : 2)) {
8780     // Let's not worry about using a variadic template pack here -- who would do
8781     // such a thing?
8782     Diag(FD->getLocation(), diag::err_defaulted_comparison_num_args)
8783         << int(IsMethod) << int(DCK);
8784     return true;
8785   }
8786 
8787   const ParmVarDecl *KnownParm = nullptr;
8788   for (const ParmVarDecl *Param : FD->parameters()) {
8789     if (Param->isExplicitObjectParameter())
8790       continue;
8791     QualType ParmTy = Param->getType();
8792 
8793     if (!KnownParm) {
8794       auto CTy = ParmTy;
8795       // Is it `T const &`?
8796       bool Ok = !IsMethod;
8797       QualType ExpectedTy;
8798       if (RD)
8799         ExpectedTy = Context.getRecordType(RD);
8800       if (auto *Ref = CTy->getAs<ReferenceType>()) {
8801         CTy = Ref->getPointeeType();
8802         if (RD)
8803           ExpectedTy.addConst();
8804         Ok = true;
8805       }
8806 
8807       // Is T a class?
8808       if (!Ok) {
8809       } else if (RD) {
8810         if (!RD->isDependentType() && !Context.hasSameType(CTy, ExpectedTy))
8811           Ok = false;
8812       } else if (auto *CRD = CTy->getAsRecordDecl()) {
8813         RD = cast<CXXRecordDecl>(CRD);
8814       } else {
8815         Ok = false;
8816       }
8817 
8818       if (Ok) {
8819         KnownParm = Param;
8820       } else {
8821         // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8822         // corresponding defaulted 'operator<=>' already.
8823         if (!FD->isImplicit()) {
8824           if (RD) {
8825             QualType PlainTy = Context.getRecordType(RD);
8826             QualType RefTy =
8827                 Context.getLValueReferenceType(PlainTy.withConst());
8828             Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
8829                 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
8830                 << Param->getSourceRange();
8831           } else {
8832             assert(!IsMethod && "should know expected type for method");
8833             Diag(FD->getLocation(),
8834                  diag::err_defaulted_comparison_param_unknown)
8835                 << int(DCK) << ParmTy << Param->getSourceRange();
8836           }
8837         }
8838         return true;
8839       }
8840     } else if (!Context.hasSameType(KnownParm->getType(), ParmTy)) {
8841       Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
8842           << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
8843           << ParmTy << Param->getSourceRange();
8844       return true;
8845     }
8846   }
8847 
8848   assert(RD && "must have determined class");
8849   if (IsMethod) {
8850   } else if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
8851     // In-class, must be a friend decl.
8852     assert(FD->getFriendObjectKind() && "expected a friend declaration");
8853   } else {
8854     // Out of class, require the defaulted comparison to be a friend (of a
8855     // complete type).
8856     if (RequireCompleteType(FD->getLocation(), Context.getRecordType(RD),
8857                             diag::err_defaulted_comparison_not_friend, int(DCK),
8858                             int(1)))
8859       return true;
8860 
8861     if (llvm::none_of(RD->friends(), [&](const FriendDecl *F) {
8862           return FD->getCanonicalDecl() ==
8863                  F->getFriendDecl()->getCanonicalDecl();
8864         })) {
8865       Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend)
8866           << int(DCK) << int(0) << RD;
8867       Diag(RD->getCanonicalDecl()->getLocation(), diag::note_declared_at);
8868       return true;
8869     }
8870   }
8871 
8872   // C++2a [class.eq]p1, [class.rel]p1:
8873   //   A [defaulted comparison other than <=>] shall have a declared return
8874   //   type bool.
8875   if (DCK != DefaultedComparisonKind::ThreeWay &&
8876       !FD->getDeclaredReturnType()->isDependentType() &&
8877       !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
8878     Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
8879         << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
8880         << FD->getReturnTypeSourceRange();
8881     return true;
8882   }
8883   // C++2a [class.spaceship]p2 [P2002R0]:
8884   //   Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
8885   //   R shall not contain a placeholder type.
8886   if (QualType RT = FD->getDeclaredReturnType();
8887       DCK == DefaultedComparisonKind::ThreeWay &&
8888       RT->getContainedDeducedType() &&
8889       (!Context.hasSameType(RT, Context.getAutoDeductType()) ||
8890        RT->getContainedAutoType()->isConstrained())) {
8891     Diag(FD->getLocation(),
8892          diag::err_defaulted_comparison_deduced_return_type_not_auto)
8893         << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
8894         << FD->getReturnTypeSourceRange();
8895     return true;
8896   }
8897 
8898   // For a defaulted function in a dependent class, defer all remaining checks
8899   // until instantiation.
8900   if (RD->isDependentType())
8901     return false;
8902 
8903   // Determine whether the function should be defined as deleted.
8904   DefaultedComparisonInfo Info =
8905       DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
8906 
8907   bool First = FD == FD->getCanonicalDecl();
8908 
8909   if (!First) {
8910     if (Info.Deleted) {
8911       // C++11 [dcl.fct.def.default]p4:
8912       //   [For a] user-provided explicitly-defaulted function [...] if such a
8913       //   function is implicitly defined as deleted, the program is ill-formed.
8914       //
8915       // This is really just a consequence of the general rule that you can
8916       // only delete a function on its first declaration.
8917       Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
8918           << FD->isImplicit() << (int)DCK;
8919       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8920                                   DefaultedComparisonAnalyzer::ExplainDeleted)
8921           .visit();
8922       return true;
8923     }
8924     if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
8925       // C++20 [class.compare.default]p1:
8926       //   [...] A definition of a comparison operator as defaulted that appears
8927       //   in a class shall be the first declaration of that function.
8928       Diag(FD->getLocation(), diag::err_non_first_default_compare_in_class)
8929           << (int)DCK;
8930       Diag(FD->getCanonicalDecl()->getLocation(),
8931            diag::note_previous_declaration);
8932       return true;
8933     }
8934   }
8935 
8936   // If we want to delete the function, then do so; there's nothing else to
8937   // check in that case.
8938   if (Info.Deleted) {
8939     SetDeclDeleted(FD, FD->getLocation());
8940     if (!inTemplateInstantiation() && !FD->isImplicit()) {
8941       Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
8942           << (int)DCK;
8943       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8944                                   DefaultedComparisonAnalyzer::ExplainDeleted)
8945           .visit();
8946       if (FD->getDefaultLoc().isValid())
8947         Diag(FD->getDefaultLoc(), diag::note_replace_equals_default_to_delete)
8948             << FixItHint::CreateReplacement(FD->getDefaultLoc(), "delete");
8949     }
8950     return false;
8951   }
8952 
8953   // C++2a [class.spaceship]p2:
8954   //   The return type is deduced as the common comparison type of R0, R1, ...
8955   if (DCK == DefaultedComparisonKind::ThreeWay &&
8956       FD->getDeclaredReturnType()->isUndeducedAutoType()) {
8957     SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();
8958     if (RetLoc.isInvalid())
8959       RetLoc = FD->getBeginLoc();
8960     // FIXME: Should we really care whether we have the complete type and the
8961     // 'enumerator' constants here? A forward declaration seems sufficient.
8962     QualType Cat = CheckComparisonCategoryType(
8963         Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
8964     if (Cat.isNull())
8965       return true;
8966     Context.adjustDeducedFunctionResultType(
8967         FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
8968   }
8969 
8970   // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8971   //   An explicitly-defaulted function that is not defined as deleted may be
8972   //   declared constexpr or consteval only if it is constexpr-compatible.
8973   // C++2a [class.compare.default]p3 [P2002R0]:
8974   //   A defaulted comparison function is constexpr-compatible if it satisfies
8975   //   the requirements for a constexpr function [...]
8976   // The only relevant requirements are that the parameter and return types are
8977   // literal types. The remaining conditions are checked by the analyzer.
8978   //
8979   // We support P2448R2 in language modes earlier than C++23 as an extension.
8980   // The concept of constexpr-compatible was removed.
8981   // C++23 [dcl.fct.def.default]p3 [P2448R2]
8982   //  A function explicitly defaulted on its first declaration is implicitly
8983   //  inline, and is implicitly constexpr if it is constexpr-suitable.
8984   // C++23 [dcl.constexpr]p3
8985   //   A function is constexpr-suitable if
8986   //    - it is not a coroutine, and
8987   //    - if the function is a constructor or destructor, its class does not
8988   //      have any virtual base classes.
8989   if (FD->isConstexpr()) {
8990     if (!getLangOpts().CPlusPlus23 &&
8991         CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) &&
8992         CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) &&
8993         !Info.Constexpr) {
8994       Diag(FD->getBeginLoc(), diag::err_defaulted_comparison_constexpr_mismatch)
8995           << FD->isImplicit() << (int)DCK << FD->isConsteval();
8996       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8997                                   DefaultedComparisonAnalyzer::ExplainConstexpr)
8998           .visit();
8999     }
9000   }
9001 
9002   // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9003   //   If a constexpr-compatible function is explicitly defaulted on its first
9004   //   declaration, it is implicitly considered to be constexpr.
9005   // FIXME: Only applying this to the first declaration seems problematic, as
9006   // simple reorderings can affect the meaning of the program.
9007   if (First && !FD->isConstexpr() && Info.Constexpr)
9008     FD->setConstexprKind(ConstexprSpecKind::Constexpr);
9009 
9010   // C++2a [except.spec]p3:
9011   //   If a declaration of a function does not have a noexcept-specifier
9012   //   [and] is defaulted on its first declaration, [...] the exception
9013   //   specification is as specified below
9014   if (FD->getExceptionSpecType() == EST_None) {
9015     auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9016     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9017     EPI.ExceptionSpec.Type = EST_Unevaluated;
9018     EPI.ExceptionSpec.SourceDecl = FD;
9019     FD->setType(Context.getFunctionType(FPT->getReturnType(),
9020                                         FPT->getParamTypes(), EPI));
9021   }
9022 
9023   return false;
9024 }
9025 
9026 void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
9027                                              FunctionDecl *Spaceship) {
9028   Sema::CodeSynthesisContext Ctx;
9029   Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;
9030   Ctx.PointOfInstantiation = Spaceship->getEndLoc();
9031   Ctx.Entity = Spaceship;
9032   pushCodeSynthesisContext(Ctx);
9033 
9034   if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
9035     EqualEqual->setImplicit();
9036 
9037   popCodeSynthesisContext();
9038 }
9039 
9040 void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,
9041                                      DefaultedComparisonKind DCK) {
9042   assert(FD->isDefaulted() && !FD->isDeleted() &&
9043          !FD->doesThisDeclarationHaveABody());
9044   if (FD->willHaveBody() || FD->isInvalidDecl())
9045     return;
9046 
9047   SynthesizedFunctionScope Scope(*this, FD);
9048 
9049   // Add a context note for diagnostics produced after this point.
9050   Scope.addContextNote(UseLoc);
9051 
9052   {
9053     // Build and set up the function body.
9054     // The first parameter has type maybe-ref-to maybe-const T, use that to get
9055     // the type of the class being compared.
9056     auto PT = FD->getParamDecl(0)->getType();
9057     CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
9058     SourceLocation BodyLoc =
9059         FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9060     StmtResult Body =
9061         DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
9062     if (Body.isInvalid()) {
9063       FD->setInvalidDecl();
9064       return;
9065     }
9066     FD->setBody(Body.get());
9067     FD->markUsed(Context);
9068   }
9069 
9070   // The exception specification is needed because we are defining the
9071   // function. Note that this will reuse the body we just built.
9072   ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>());
9073 
9074   if (ASTMutationListener *L = getASTMutationListener())
9075     L->CompletedImplicitDefinition(FD);
9076 }
9077 
9078 static Sema::ImplicitExceptionSpecification
9079 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
9080                                         FunctionDecl *FD,
9081                                         Sema::DefaultedComparisonKind DCK) {
9082   ComputingExceptionSpec CES(S, FD, Loc);
9083   Sema::ImplicitExceptionSpecification ExceptSpec(S);
9084 
9085   if (FD->isInvalidDecl())
9086     return ExceptSpec;
9087 
9088   // The common case is that we just defined the comparison function. In that
9089   // case, just look at whether the body can throw.
9090   if (FD->hasBody()) {
9091     ExceptSpec.CalledStmt(FD->getBody());
9092   } else {
9093     // Otherwise, build a body so we can check it. This should ideally only
9094     // happen when we're not actually marking the function referenced. (This is
9095     // only really important for efficiency: we don't want to build and throw
9096     // away bodies for comparison functions more than we strictly need to.)
9097 
9098     // Pretend to synthesize the function body in an unevaluated context.
9099     // Note that we can't actually just go ahead and define the function here:
9100     // we are not permitted to mark its callees as referenced.
9101     Sema::SynthesizedFunctionScope Scope(S, FD);
9102     EnterExpressionEvaluationContext Context(
9103         S, Sema::ExpressionEvaluationContext::Unevaluated);
9104 
9105     CXXRecordDecl *RD =
9106         cast<CXXRecordDecl>(FD->getFriendObjectKind() == Decl::FOK_None
9107                                 ? FD->getDeclContext()
9108                                 : FD->getLexicalDeclContext());
9109     SourceLocation BodyLoc =
9110         FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9111     StmtResult Body =
9112         DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
9113     if (!Body.isInvalid())
9114       ExceptSpec.CalledStmt(Body.get());
9115 
9116     // FIXME: Can we hold onto this body and just transform it to potentially
9117     // evaluated when we're asked to define the function rather than rebuilding
9118     // it? Either that, or we should only build the bits of the body that we
9119     // need (the expressions, not the statements).
9120   }
9121 
9122   return ExceptSpec;
9123 }
9124 
9125 void Sema::CheckDelayedMemberExceptionSpecs() {
9126   decltype(DelayedOverridingExceptionSpecChecks) Overriding;
9127   decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
9128 
9129   std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
9130   std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
9131 
9132   // Perform any deferred checking of exception specifications for virtual
9133   // destructors.
9134   for (auto &Check : Overriding)
9135     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
9136 
9137   // Perform any deferred checking of exception specifications for befriended
9138   // special members.
9139   for (auto &Check : Equivalent)
9140     CheckEquivalentExceptionSpec(Check.second, Check.first);
9141 }
9142 
9143 namespace {
9144 /// CRTP base class for visiting operations performed by a special member
9145 /// function (or inherited constructor).
9146 template<typename Derived>
9147 struct SpecialMemberVisitor {
9148   Sema &S;
9149   CXXMethodDecl *MD;
9150   CXXSpecialMemberKind CSM;
9151   Sema::InheritedConstructorInfo *ICI;
9152 
9153   // Properties of the special member, computed for convenience.
9154   bool IsConstructor = false, IsAssignment = false, ConstArg = false;
9155 
9156   SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
9157                        Sema::InheritedConstructorInfo *ICI)
9158       : S(S), MD(MD), CSM(CSM), ICI(ICI) {
9159     switch (CSM) {
9160     case CXXSpecialMemberKind::DefaultConstructor:
9161     case CXXSpecialMemberKind::CopyConstructor:
9162     case CXXSpecialMemberKind::MoveConstructor:
9163       IsConstructor = true;
9164       break;
9165     case CXXSpecialMemberKind::CopyAssignment:
9166     case CXXSpecialMemberKind::MoveAssignment:
9167       IsAssignment = true;
9168       break;
9169     case CXXSpecialMemberKind::Destructor:
9170       break;
9171     case CXXSpecialMemberKind::Invalid:
9172       llvm_unreachable("invalid special member kind");
9173     }
9174 
9175     if (MD->getNumExplicitParams()) {
9176       if (const ReferenceType *RT =
9177               MD->getNonObjectParameter(0)->getType()->getAs<ReferenceType>())
9178         ConstArg = RT->getPointeeType().isConstQualified();
9179     }
9180   }
9181 
9182   Derived &getDerived() { return static_cast<Derived&>(*this); }
9183 
9184   /// Is this a "move" special member?
9185   bool isMove() const {
9186     return CSM == CXXSpecialMemberKind::MoveConstructor ||
9187            CSM == CXXSpecialMemberKind::MoveAssignment;
9188   }
9189 
9190   /// Look up the corresponding special member in the given class.
9191   Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
9192                                              unsigned Quals, bool IsMutable) {
9193     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
9194                                        ConstArg && !IsMutable);
9195   }
9196 
9197   /// Look up the constructor for the specified base class to see if it's
9198   /// overridden due to this being an inherited constructor.
9199   Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
9200     if (!ICI)
9201       return {};
9202     assert(CSM == CXXSpecialMemberKind::DefaultConstructor);
9203     auto *BaseCtor =
9204       cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
9205     if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
9206       return MD;
9207     return {};
9208   }
9209 
9210   /// A base or member subobject.
9211   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
9212 
9213   /// Get the location to use for a subobject in diagnostics.
9214   static SourceLocation getSubobjectLoc(Subobject Subobj) {
9215     // FIXME: For an indirect virtual base, the direct base leading to
9216     // the indirect virtual base would be a more useful choice.
9217     if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
9218       return B->getBaseTypeLoc();
9219     else
9220       return Subobj.get<FieldDecl*>()->getLocation();
9221   }
9222 
9223   enum BasesToVisit {
9224     /// Visit all non-virtual (direct) bases.
9225     VisitNonVirtualBases,
9226     /// Visit all direct bases, virtual or not.
9227     VisitDirectBases,
9228     /// Visit all non-virtual bases, and all virtual bases if the class
9229     /// is not abstract.
9230     VisitPotentiallyConstructedBases,
9231     /// Visit all direct or virtual bases.
9232     VisitAllBases
9233   };
9234 
9235   // Visit the bases and members of the class.
9236   bool visit(BasesToVisit Bases) {
9237     CXXRecordDecl *RD = MD->getParent();
9238 
9239     if (Bases == VisitPotentiallyConstructedBases)
9240       Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
9241 
9242     for (auto &B : RD->bases())
9243       if ((Bases == VisitDirectBases || !B.isVirtual()) &&
9244           getDerived().visitBase(&B))
9245         return true;
9246 
9247     if (Bases == VisitAllBases)
9248       for (auto &B : RD->vbases())
9249         if (getDerived().visitBase(&B))
9250           return true;
9251 
9252     for (auto *F : RD->fields())
9253       if (!F->isInvalidDecl() && !F->isUnnamedBitField() &&
9254           getDerived().visitField(F))
9255         return true;
9256 
9257     return false;
9258   }
9259 };
9260 }
9261 
9262 namespace {
9263 struct SpecialMemberDeletionInfo
9264     : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
9265   bool Diagnose;
9266 
9267   SourceLocation Loc;
9268 
9269   bool AllFieldsAreConst;
9270 
9271   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
9272                             CXXSpecialMemberKind CSM,
9273                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
9274       : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
9275         Loc(MD->getLocation()), AllFieldsAreConst(true) {}
9276 
9277   bool inUnion() const { return MD->getParent()->isUnion(); }
9278 
9279   CXXSpecialMemberKind getEffectiveCSM() {
9280     return ICI ? CXXSpecialMemberKind::Invalid : CSM;
9281   }
9282 
9283   bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
9284 
9285   bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
9286   bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
9287 
9288   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
9289   bool shouldDeleteForField(FieldDecl *FD);
9290   bool shouldDeleteForAllConstMembers();
9291 
9292   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
9293                                      unsigned Quals);
9294   bool shouldDeleteForSubobjectCall(Subobject Subobj,
9295                                     Sema::SpecialMemberOverloadResult SMOR,
9296                                     bool IsDtorCallInCtor);
9297 
9298   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
9299 };
9300 }
9301 
9302 /// Is the given special member inaccessible when used on the given
9303 /// sub-object.
9304 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
9305                                              CXXMethodDecl *target) {
9306   /// If we're operating on a base class, the object type is the
9307   /// type of this special member.
9308   QualType objectTy;
9309   AccessSpecifier access = target->getAccess();
9310   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
9311     objectTy = S.Context.getTypeDeclType(MD->getParent());
9312     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
9313 
9314   // If we're operating on a field, the object type is the type of the field.
9315   } else {
9316     objectTy = S.Context.getTypeDeclType(target->getParent());
9317   }
9318 
9319   return S.isMemberAccessibleForDeletion(
9320       target->getParent(), DeclAccessPair::make(target, access), objectTy);
9321 }
9322 
9323 /// Check whether we should delete a special member due to the implicit
9324 /// definition containing a call to a special member of a subobject.
9325 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
9326     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
9327     bool IsDtorCallInCtor) {
9328   CXXMethodDecl *Decl = SMOR.getMethod();
9329   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9330 
9331   int DiagKind = -1;
9332 
9333   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
9334     DiagKind = !Decl ? 0 : 1;
9335   else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9336     DiagKind = 2;
9337   else if (!isAccessible(Subobj, Decl))
9338     DiagKind = 3;
9339   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
9340            !Decl->isTrivial()) {
9341     // A member of a union must have a trivial corresponding special member.
9342     // As a weird special case, a destructor call from a union's constructor
9343     // must be accessible and non-deleted, but need not be trivial. Such a
9344     // destructor is never actually called, but is semantically checked as
9345     // if it were.
9346     if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
9347       // [class.default.ctor]p2:
9348       //   A defaulted default constructor for class X is defined as deleted if
9349       //   - X is a union that has a variant member with a non-trivial default
9350       //     constructor and no variant member of X has a default member
9351       //     initializer
9352       const auto *RD = cast<CXXRecordDecl>(Field->getParent());
9353       if (!RD->hasInClassInitializer())
9354         DiagKind = 4;
9355     } else {
9356       DiagKind = 4;
9357     }
9358   }
9359 
9360   if (DiagKind == -1)
9361     return false;
9362 
9363   if (Diagnose) {
9364     if (Field) {
9365       S.Diag(Field->getLocation(),
9366              diag::note_deleted_special_member_class_subobject)
9367           << llvm::to_underlying(getEffectiveCSM()) << MD->getParent()
9368           << /*IsField*/ true << Field << DiagKind << IsDtorCallInCtor
9369           << /*IsObjCPtr*/ false;
9370     } else {
9371       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
9372       S.Diag(Base->getBeginLoc(),
9373              diag::note_deleted_special_member_class_subobject)
9374           << llvm::to_underlying(getEffectiveCSM()) << MD->getParent()
9375           << /*IsField*/ false << Base->getType() << DiagKind
9376           << IsDtorCallInCtor << /*IsObjCPtr*/ false;
9377     }
9378 
9379     if (DiagKind == 1)
9380       S.NoteDeletedFunction(Decl);
9381     // FIXME: Explain inaccessibility if DiagKind == 3.
9382   }
9383 
9384   return true;
9385 }
9386 
9387 /// Check whether we should delete a special member function due to having a
9388 /// direct or virtual base class or non-static data member of class type M.
9389 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
9390     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
9391   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9392   bool IsMutable = Field && Field->isMutable();
9393 
9394   // C++11 [class.ctor]p5:
9395   // -- any direct or virtual base class, or non-static data member with no
9396   //    brace-or-equal-initializer, has class type M (or array thereof) and
9397   //    either M has no default constructor or overload resolution as applied
9398   //    to M's default constructor results in an ambiguity or in a function
9399   //    that is deleted or inaccessible
9400   // C++11 [class.copy]p11, C++11 [class.copy]p23:
9401   // -- a direct or virtual base class B that cannot be copied/moved because
9402   //    overload resolution, as applied to B's corresponding special member,
9403   //    results in an ambiguity or a function that is deleted or inaccessible
9404   //    from the defaulted special member
9405   // C++11 [class.dtor]p5:
9406   // -- any direct or virtual base class [...] has a type with a destructor
9407   //    that is deleted or inaccessible
9408   if (!(CSM == CXXSpecialMemberKind::DefaultConstructor && Field &&
9409         Field->hasInClassInitializer()) &&
9410       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
9411                                    false))
9412     return true;
9413 
9414   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
9415   // -- any direct or virtual base class or non-static data member has a
9416   //    type with a destructor that is deleted or inaccessible
9417   if (IsConstructor) {
9418     Sema::SpecialMemberOverloadResult SMOR =
9419         S.LookupSpecialMember(Class, CXXSpecialMemberKind::Destructor, false,
9420                               false, false, false, false);
9421     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
9422       return true;
9423   }
9424 
9425   return false;
9426 }
9427 
9428 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
9429     FieldDecl *FD, QualType FieldType) {
9430   // The defaulted special functions are defined as deleted if this is a variant
9431   // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
9432   // type under ARC.
9433   if (!FieldType.hasNonTrivialObjCLifetime())
9434     return false;
9435 
9436   // Don't make the defaulted default constructor defined as deleted if the
9437   // member has an in-class initializer.
9438   if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
9439       FD->hasInClassInitializer())
9440     return false;
9441 
9442   if (Diagnose) {
9443     auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
9444     S.Diag(FD->getLocation(), diag::note_deleted_special_member_class_subobject)
9445         << llvm::to_underlying(getEffectiveCSM()) << ParentClass
9446         << /*IsField*/ true << FD << 4 << /*IsDtorCallInCtor*/ false
9447         << /*IsObjCPtr*/ true;
9448   }
9449 
9450   return true;
9451 }
9452 
9453 /// Check whether we should delete a special member function due to the class
9454 /// having a particular direct or virtual base class.
9455 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
9456   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
9457   // If program is correct, BaseClass cannot be null, but if it is, the error
9458   // must be reported elsewhere.
9459   if (!BaseClass)
9460     return false;
9461   // If we have an inheriting constructor, check whether we're calling an
9462   // inherited constructor instead of a default constructor.
9463   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
9464   if (auto *BaseCtor = SMOR.getMethod()) {
9465     // Note that we do not check access along this path; other than that,
9466     // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9467     // FIXME: Check that the base has a usable destructor! Sink this into
9468     // shouldDeleteForClassSubobject.
9469     if (BaseCtor->isDeleted() && Diagnose) {
9470       S.Diag(Base->getBeginLoc(),
9471              diag::note_deleted_special_member_class_subobject)
9472           << llvm::to_underlying(getEffectiveCSM()) << MD->getParent()
9473           << /*IsField*/ false << Base->getType() << /*Deleted*/ 1
9474           << /*IsDtorCallInCtor*/ false << /*IsObjCPtr*/ false;
9475       S.NoteDeletedFunction(BaseCtor);
9476     }
9477     return BaseCtor->isDeleted();
9478   }
9479   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
9480 }
9481 
9482 /// Check whether we should delete a special member function due to the class
9483 /// having a particular non-static data member.
9484 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
9485   QualType FieldType = S.Context.getBaseElementType(FD->getType());
9486   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
9487 
9488   if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9489     return true;
9490 
9491   if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
9492     // For a default constructor, all references must be initialized in-class
9493     // and, if a union, it must have a non-const member.
9494     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9495       if (Diagnose)
9496         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9497           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9498       return true;
9499     }
9500     // C++11 [class.ctor]p5 (modified by DR2394): any non-variant non-static
9501     // data member of const-qualified type (or array thereof) with no
9502     // brace-or-equal-initializer is not const-default-constructible.
9503     if (!inUnion() && FieldType.isConstQualified() &&
9504         !FD->hasInClassInitializer() &&
9505         (!FieldRecord || !FieldRecord->allowConstDefaultInit())) {
9506       if (Diagnose)
9507         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9508           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9509       return true;
9510     }
9511 
9512     if (inUnion() && !FieldType.isConstQualified())
9513       AllFieldsAreConst = false;
9514   } else if (CSM == CXXSpecialMemberKind::CopyConstructor) {
9515     // For a copy constructor, data members must not be of rvalue reference
9516     // type.
9517     if (FieldType->isRValueReferenceType()) {
9518       if (Diagnose)
9519         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
9520           << MD->getParent() << FD << FieldType;
9521       return true;
9522     }
9523   } else if (IsAssignment) {
9524     // For an assignment operator, data members must not be of reference type.
9525     if (FieldType->isReferenceType()) {
9526       if (Diagnose)
9527         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9528           << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9529       return true;
9530     }
9531     if (!FieldRecord && FieldType.isConstQualified()) {
9532       // C++11 [class.copy]p23:
9533       // -- a non-static data member of const non-class type (or array thereof)
9534       if (Diagnose)
9535         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9536           << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9537       return true;
9538     }
9539   }
9540 
9541   if (FieldRecord) {
9542     // Some additional restrictions exist on the variant members.
9543     if (!inUnion() && FieldRecord->isUnion() &&
9544         FieldRecord->isAnonymousStructOrUnion()) {
9545       bool AllVariantFieldsAreConst = true;
9546 
9547       // FIXME: Handle anonymous unions declared within anonymous unions.
9548       for (auto *UI : FieldRecord->fields()) {
9549         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
9550 
9551         if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
9552           return true;
9553 
9554         if (!UnionFieldType.isConstQualified())
9555           AllVariantFieldsAreConst = false;
9556 
9557         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9558         if (UnionFieldRecord &&
9559             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
9560                                           UnionFieldType.getCVRQualifiers()))
9561           return true;
9562       }
9563 
9564       // At least one member in each anonymous union must be non-const
9565       if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
9566           AllVariantFieldsAreConst && !FieldRecord->field_empty()) {
9567         if (Diagnose)
9568           S.Diag(FieldRecord->getLocation(),
9569                  diag::note_deleted_default_ctor_all_const)
9570             << !!ICI << MD->getParent() << /*anonymous union*/1;
9571         return true;
9572       }
9573 
9574       // Don't check the implicit member of the anonymous union type.
9575       // This is technically non-conformant but supported, and we have a
9576       // diagnostic for this elsewhere.
9577       return false;
9578     }
9579 
9580     if (shouldDeleteForClassSubobject(FieldRecord, FD,
9581                                       FieldType.getCVRQualifiers()))
9582       return true;
9583   }
9584 
9585   return false;
9586 }
9587 
9588 /// C++11 [class.ctor] p5:
9589 ///   A defaulted default constructor for a class X is defined as deleted if
9590 /// X is a union and all of its variant members are of const-qualified type.
9591 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9592   // This is a silly definition, because it gives an empty union a deleted
9593   // default constructor. Don't do that.
9594   if (CSM == CXXSpecialMemberKind::DefaultConstructor && inUnion() &&
9595       AllFieldsAreConst) {
9596     bool AnyFields = false;
9597     for (auto *F : MD->getParent()->fields())
9598       if ((AnyFields = !F->isUnnamedBitField()))
9599         break;
9600     if (!AnyFields)
9601       return false;
9602     if (Diagnose)
9603       S.Diag(MD->getParent()->getLocation(),
9604              diag::note_deleted_default_ctor_all_const)
9605         << !!ICI << MD->getParent() << /*not anonymous union*/0;
9606     return true;
9607   }
9608   return false;
9609 }
9610 
9611 /// Determine whether a defaulted special member function should be defined as
9612 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9613 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9614 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD,
9615                                      CXXSpecialMemberKind CSM,
9616                                      InheritedConstructorInfo *ICI,
9617                                      bool Diagnose) {
9618   if (MD->isInvalidDecl())
9619     return false;
9620   CXXRecordDecl *RD = MD->getParent();
9621   assert(!RD->isDependentType() && "do deletion after instantiation");
9622   if (!LangOpts.CPlusPlus || (!LangOpts.CPlusPlus11 && !RD->isLambda()) ||
9623       RD->isInvalidDecl())
9624     return false;
9625 
9626   // C++11 [expr.lambda.prim]p19:
9627   //   The closure type associated with a lambda-expression has a
9628   //   deleted (8.4.3) default constructor and a deleted copy
9629   //   assignment operator.
9630   // C++2a adds back these operators if the lambda has no lambda-capture.
9631   if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
9632       (CSM == CXXSpecialMemberKind::DefaultConstructor ||
9633        CSM == CXXSpecialMemberKind::CopyAssignment)) {
9634     if (Diagnose)
9635       Diag(RD->getLocation(), diag::note_lambda_decl);
9636     return true;
9637   }
9638 
9639   // For an anonymous struct or union, the copy and assignment special members
9640   // will never be used, so skip the check. For an anonymous union declared at
9641   // namespace scope, the constructor and destructor are used.
9642   if (CSM != CXXSpecialMemberKind::DefaultConstructor &&
9643       CSM != CXXSpecialMemberKind::Destructor && RD->isAnonymousStructOrUnion())
9644     return false;
9645 
9646   // C++11 [class.copy]p7, p18:
9647   //   If the class definition declares a move constructor or move assignment
9648   //   operator, an implicitly declared copy constructor or copy assignment
9649   //   operator is defined as deleted.
9650   if (MD->isImplicit() && (CSM == CXXSpecialMemberKind::CopyConstructor ||
9651                            CSM == CXXSpecialMemberKind::CopyAssignment)) {
9652     CXXMethodDecl *UserDeclaredMove = nullptr;
9653 
9654     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9655     // deletion of the corresponding copy operation, not both copy operations.
9656     // MSVC 2015 has adopted the standards conforming behavior.
9657     bool DeletesOnlyMatchingCopy =
9658         getLangOpts().MSVCCompat &&
9659         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
9660 
9661     if (RD->hasUserDeclaredMoveConstructor() &&
9662         (!DeletesOnlyMatchingCopy ||
9663          CSM == CXXSpecialMemberKind::CopyConstructor)) {
9664       if (!Diagnose) return true;
9665 
9666       // Find any user-declared move constructor.
9667       for (auto *I : RD->ctors()) {
9668         if (I->isMoveConstructor()) {
9669           UserDeclaredMove = I;
9670           break;
9671         }
9672       }
9673       assert(UserDeclaredMove);
9674     } else if (RD->hasUserDeclaredMoveAssignment() &&
9675                (!DeletesOnlyMatchingCopy ||
9676                 CSM == CXXSpecialMemberKind::CopyAssignment)) {
9677       if (!Diagnose) return true;
9678 
9679       // Find any user-declared move assignment operator.
9680       for (auto *I : RD->methods()) {
9681         if (I->isMoveAssignmentOperator()) {
9682           UserDeclaredMove = I;
9683           break;
9684         }
9685       }
9686       assert(UserDeclaredMove);
9687     }
9688 
9689     if (UserDeclaredMove) {
9690       Diag(UserDeclaredMove->getLocation(),
9691            diag::note_deleted_copy_user_declared_move)
9692           << (CSM == CXXSpecialMemberKind::CopyAssignment) << RD
9693           << UserDeclaredMove->isMoveAssignmentOperator();
9694       return true;
9695     }
9696   }
9697 
9698   // Do access control from the special member function
9699   ContextRAII MethodContext(*this, MD);
9700 
9701   // C++11 [class.dtor]p5:
9702   // -- for a virtual destructor, lookup of the non-array deallocation function
9703   //    results in an ambiguity or in a function that is deleted or inaccessible
9704   if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
9705     FunctionDecl *OperatorDelete = nullptr;
9706     DeclarationName Name =
9707       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
9708     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
9709                                  OperatorDelete, /*Diagnose*/false)) {
9710       if (Diagnose)
9711         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
9712       return true;
9713     }
9714   }
9715 
9716   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
9717 
9718   // Per DR1611, do not consider virtual bases of constructors of abstract
9719   // classes, since we are not going to construct them.
9720   // Per DR1658, do not consider virtual bases of destructors of abstract
9721   // classes either.
9722   // Per DR2180, for assignment operators we only assign (and thus only
9723   // consider) direct bases.
9724   if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
9725                                  : SMI.VisitPotentiallyConstructedBases))
9726     return true;
9727 
9728   if (SMI.shouldDeleteForAllConstMembers())
9729     return true;
9730 
9731   if (getLangOpts().CUDA) {
9732     // We should delete the special member in CUDA mode if target inference
9733     // failed.
9734     // For inherited constructors (non-null ICI), CSM may be passed so that MD
9735     // is treated as certain special member, which may not reflect what special
9736     // member MD really is. However inferTargetForImplicitSpecialMember
9737     // expects CSM to match MD, therefore recalculate CSM.
9738     assert(ICI || CSM == getSpecialMember(MD));
9739     auto RealCSM = CSM;
9740     if (ICI)
9741       RealCSM = getSpecialMember(MD);
9742 
9743     return CUDA().inferTargetForImplicitSpecialMember(RD, RealCSM, MD,
9744                                                       SMI.ConstArg, Diagnose);
9745   }
9746 
9747   return false;
9748 }
9749 
9750 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {
9751   DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
9752   assert(DFK && "not a defaultable function");
9753   assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
9754 
9755   if (DFK.isSpecialMember()) {
9756     ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),
9757                               nullptr, /*Diagnose=*/true);
9758   } else {
9759     DefaultedComparisonAnalyzer(
9760         *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
9761         DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
9762         .visit();
9763   }
9764 }
9765 
9766 /// Perform lookup for a special member of the specified kind, and determine
9767 /// whether it is trivial. If the triviality can be determined without the
9768 /// lookup, skip it. This is intended for use when determining whether a
9769 /// special member of a containing object is trivial, and thus does not ever
9770 /// perform overload resolution for default constructors.
9771 ///
9772 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
9773 /// member that was most likely to be intended to be trivial, if any.
9774 ///
9775 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
9776 /// determine whether the special member is trivial.
9777 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
9778                                      CXXSpecialMemberKind CSM, unsigned Quals,
9779                                      bool ConstRHS,
9780                                      Sema::TrivialABIHandling TAH,
9781                                      CXXMethodDecl **Selected) {
9782   if (Selected)
9783     *Selected = nullptr;
9784 
9785   switch (CSM) {
9786   case CXXSpecialMemberKind::Invalid:
9787     llvm_unreachable("not a special member");
9788 
9789   case CXXSpecialMemberKind::DefaultConstructor:
9790     // C++11 [class.ctor]p5:
9791     //   A default constructor is trivial if:
9792     //    - all the [direct subobjects] have trivial default constructors
9793     //
9794     // Note, no overload resolution is performed in this case.
9795     if (RD->hasTrivialDefaultConstructor())
9796       return true;
9797 
9798     if (Selected) {
9799       // If there's a default constructor which could have been trivial, dig it
9800       // out. Otherwise, if there's any user-provided default constructor, point
9801       // to that as an example of why there's not a trivial one.
9802       CXXConstructorDecl *DefCtor = nullptr;
9803       if (RD->needsImplicitDefaultConstructor())
9804         S.DeclareImplicitDefaultConstructor(RD);
9805       for (auto *CI : RD->ctors()) {
9806         if (!CI->isDefaultConstructor())
9807           continue;
9808         DefCtor = CI;
9809         if (!DefCtor->isUserProvided())
9810           break;
9811       }
9812 
9813       *Selected = DefCtor;
9814     }
9815 
9816     return false;
9817 
9818   case CXXSpecialMemberKind::Destructor:
9819     // C++11 [class.dtor]p5:
9820     //   A destructor is trivial if:
9821     //    - all the direct [subobjects] have trivial destructors
9822     if (RD->hasTrivialDestructor() ||
9823         (TAH == Sema::TAH_ConsiderTrivialABI &&
9824          RD->hasTrivialDestructorForCall()))
9825       return true;
9826 
9827     if (Selected) {
9828       if (RD->needsImplicitDestructor())
9829         S.DeclareImplicitDestructor(RD);
9830       *Selected = RD->getDestructor();
9831     }
9832 
9833     return false;
9834 
9835   case CXXSpecialMemberKind::CopyConstructor:
9836     // C++11 [class.copy]p12:
9837     //   A copy constructor is trivial if:
9838     //    - the constructor selected to copy each direct [subobject] is trivial
9839     if (RD->hasTrivialCopyConstructor() ||
9840         (TAH == Sema::TAH_ConsiderTrivialABI &&
9841          RD->hasTrivialCopyConstructorForCall())) {
9842       if (Quals == Qualifiers::Const)
9843         // We must either select the trivial copy constructor or reach an
9844         // ambiguity; no need to actually perform overload resolution.
9845         return true;
9846     } else if (!Selected) {
9847       return false;
9848     }
9849     // In C++98, we are not supposed to perform overload resolution here, but we
9850     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
9851     // cases like B as having a non-trivial copy constructor:
9852     //   struct A { template<typename T> A(T&); };
9853     //   struct B { mutable A a; };
9854     goto NeedOverloadResolution;
9855 
9856   case CXXSpecialMemberKind::CopyAssignment:
9857     // C++11 [class.copy]p25:
9858     //   A copy assignment operator is trivial if:
9859     //    - the assignment operator selected to copy each direct [subobject] is
9860     //      trivial
9861     if (RD->hasTrivialCopyAssignment()) {
9862       if (Quals == Qualifiers::Const)
9863         return true;
9864     } else if (!Selected) {
9865       return false;
9866     }
9867     // In C++98, we are not supposed to perform overload resolution here, but we
9868     // treat that as a language defect.
9869     goto NeedOverloadResolution;
9870 
9871   case CXXSpecialMemberKind::MoveConstructor:
9872   case CXXSpecialMemberKind::MoveAssignment:
9873   NeedOverloadResolution:
9874     Sema::SpecialMemberOverloadResult SMOR =
9875         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
9876 
9877     // The standard doesn't describe how to behave if the lookup is ambiguous.
9878     // We treat it as not making the member non-trivial, just like the standard
9879     // mandates for the default constructor. This should rarely matter, because
9880     // the member will also be deleted.
9881     if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9882       return true;
9883 
9884     if (!SMOR.getMethod()) {
9885       assert(SMOR.getKind() ==
9886              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
9887       return false;
9888     }
9889 
9890     // We deliberately don't check if we found a deleted special member. We're
9891     // not supposed to!
9892     if (Selected)
9893       *Selected = SMOR.getMethod();
9894 
9895     if (TAH == Sema::TAH_ConsiderTrivialABI &&
9896         (CSM == CXXSpecialMemberKind::CopyConstructor ||
9897          CSM == CXXSpecialMemberKind::MoveConstructor))
9898       return SMOR.getMethod()->isTrivialForCall();
9899     return SMOR.getMethod()->isTrivial();
9900   }
9901 
9902   llvm_unreachable("unknown special method kind");
9903 }
9904 
9905 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
9906   for (auto *CI : RD->ctors())
9907     if (!CI->isImplicit())
9908       return CI;
9909 
9910   // Look for constructor templates.
9911   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
9912   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
9913     if (CXXConstructorDecl *CD =
9914           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
9915       return CD;
9916   }
9917 
9918   return nullptr;
9919 }
9920 
9921 /// The kind of subobject we are checking for triviality. The values of this
9922 /// enumeration are used in diagnostics.
9923 enum TrivialSubobjectKind {
9924   /// The subobject is a base class.
9925   TSK_BaseClass,
9926   /// The subobject is a non-static data member.
9927   TSK_Field,
9928   /// The object is actually the complete object.
9929   TSK_CompleteObject
9930 };
9931 
9932 /// Check whether the special member selected for a given type would be trivial.
9933 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
9934                                       QualType SubType, bool ConstRHS,
9935                                       CXXSpecialMemberKind CSM,
9936                                       TrivialSubobjectKind Kind,
9937                                       Sema::TrivialABIHandling TAH,
9938                                       bool Diagnose) {
9939   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
9940   if (!SubRD)
9941     return true;
9942 
9943   CXXMethodDecl *Selected;
9944   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
9945                                ConstRHS, TAH, Diagnose ? &Selected : nullptr))
9946     return true;
9947 
9948   if (Diagnose) {
9949     if (ConstRHS)
9950       SubType.addConst();
9951 
9952     if (!Selected && CSM == CXXSpecialMemberKind::DefaultConstructor) {
9953       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
9954         << Kind << SubType.getUnqualifiedType();
9955       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
9956         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
9957     } else if (!Selected)
9958       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
9959           << Kind << SubType.getUnqualifiedType() << llvm::to_underlying(CSM)
9960           << SubType;
9961     else if (Selected->isUserProvided()) {
9962       if (Kind == TSK_CompleteObject)
9963         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
9964             << Kind << SubType.getUnqualifiedType() << llvm::to_underlying(CSM);
9965       else {
9966         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
9967             << Kind << SubType.getUnqualifiedType() << llvm::to_underlying(CSM);
9968         S.Diag(Selected->getLocation(), diag::note_declared_at);
9969       }
9970     } else {
9971       if (Kind != TSK_CompleteObject)
9972         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
9973             << Kind << SubType.getUnqualifiedType() << llvm::to_underlying(CSM);
9974 
9975       // Explain why the defaulted or deleted special member isn't trivial.
9976       S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
9977                                Diagnose);
9978     }
9979   }
9980 
9981   return false;
9982 }
9983 
9984 /// Check whether the members of a class type allow a special member to be
9985 /// trivial.
9986 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
9987                                      CXXSpecialMemberKind CSM, bool ConstArg,
9988                                      Sema::TrivialABIHandling TAH,
9989                                      bool Diagnose) {
9990   for (const auto *FI : RD->fields()) {
9991     if (FI->isInvalidDecl() || FI->isUnnamedBitField())
9992       continue;
9993 
9994     QualType FieldType = S.Context.getBaseElementType(FI->getType());
9995 
9996     // Pretend anonymous struct or union members are members of this class.
9997     if (FI->isAnonymousStructOrUnion()) {
9998       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
9999                                     CSM, ConstArg, TAH, Diagnose))
10000         return false;
10001       continue;
10002     }
10003 
10004     // C++11 [class.ctor]p5:
10005     //   A default constructor is trivial if [...]
10006     //    -- no non-static data member of its class has a
10007     //       brace-or-equal-initializer
10008     if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
10009         FI->hasInClassInitializer()) {
10010       if (Diagnose)
10011         S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
10012             << FI;
10013       return false;
10014     }
10015 
10016     // Objective C ARC 4.3.5:
10017     //   [...] nontrivally ownership-qualified types are [...] not trivially
10018     //   default constructible, copy constructible, move constructible, copy
10019     //   assignable, move assignable, or destructible [...]
10020     if (FieldType.hasNonTrivialObjCLifetime()) {
10021       if (Diagnose)
10022         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
10023           << RD << FieldType.getObjCLifetime();
10024       return false;
10025     }
10026 
10027     bool ConstRHS = ConstArg && !FI->isMutable();
10028     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
10029                                    CSM, TSK_Field, TAH, Diagnose))
10030       return false;
10031   }
10032 
10033   return true;
10034 }
10035 
10036 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD,
10037                               CXXSpecialMemberKind CSM) {
10038   QualType Ty = Context.getRecordType(RD);
10039 
10040   bool ConstArg = (CSM == CXXSpecialMemberKind::CopyConstructor ||
10041                    CSM == CXXSpecialMemberKind::CopyAssignment);
10042   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
10043                             TSK_CompleteObject, TAH_IgnoreTrivialABI,
10044                             /*Diagnose*/true);
10045 }
10046 
10047 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
10048                                   TrivialABIHandling TAH, bool Diagnose) {
10049   assert(!MD->isUserProvided() && CSM != CXXSpecialMemberKind::Invalid &&
10050          "not special enough");
10051 
10052   CXXRecordDecl *RD = MD->getParent();
10053 
10054   bool ConstArg = false;
10055 
10056   // C++11 [class.copy]p12, p25: [DR1593]
10057   //   A [special member] is trivial if [...] its parameter-type-list is
10058   //   equivalent to the parameter-type-list of an implicit declaration [...]
10059   switch (CSM) {
10060   case CXXSpecialMemberKind::DefaultConstructor:
10061   case CXXSpecialMemberKind::Destructor:
10062     // Trivial default constructors and destructors cannot have parameters.
10063     break;
10064 
10065   case CXXSpecialMemberKind::CopyConstructor:
10066   case CXXSpecialMemberKind::CopyAssignment: {
10067     const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);
10068     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
10069 
10070     // When ClangABICompat14 is true, CXX copy constructors will only be trivial
10071     // if they are not user-provided and their parameter-type-list is equivalent
10072     // to the parameter-type-list of an implicit declaration. This maintains the
10073     // behavior before dr2171 was implemented.
10074     //
10075     // Otherwise, if ClangABICompat14 is false, All copy constructors can be
10076     // trivial, if they are not user-provided, regardless of the qualifiers on
10077     // the reference type.
10078     const bool ClangABICompat14 = Context.getLangOpts().getClangABICompat() <=
10079                                   LangOptions::ClangABI::Ver14;
10080     if (!RT ||
10081         ((RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) &&
10082          ClangABICompat14)) {
10083       if (Diagnose)
10084         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10085           << Param0->getSourceRange() << Param0->getType()
10086           << Context.getLValueReferenceType(
10087                Context.getRecordType(RD).withConst());
10088       return false;
10089     }
10090 
10091     ConstArg = RT->getPointeeType().isConstQualified();
10092     break;
10093   }
10094 
10095   case CXXSpecialMemberKind::MoveConstructor:
10096   case CXXSpecialMemberKind::MoveAssignment: {
10097     // Trivial move operations always have non-cv-qualified parameters.
10098     const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);
10099     const RValueReferenceType *RT =
10100       Param0->getType()->getAs<RValueReferenceType>();
10101     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
10102       if (Diagnose)
10103         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10104           << Param0->getSourceRange() << Param0->getType()
10105           << Context.getRValueReferenceType(Context.getRecordType(RD));
10106       return false;
10107     }
10108     break;
10109   }
10110 
10111   case CXXSpecialMemberKind::Invalid:
10112     llvm_unreachable("not a special member");
10113   }
10114 
10115   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
10116     if (Diagnose)
10117       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
10118            diag::note_nontrivial_default_arg)
10119         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
10120     return false;
10121   }
10122   if (MD->isVariadic()) {
10123     if (Diagnose)
10124       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
10125     return false;
10126   }
10127 
10128   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10129   //   A copy/move [constructor or assignment operator] is trivial if
10130   //    -- the [member] selected to copy/move each direct base class subobject
10131   //       is trivial
10132   //
10133   // C++11 [class.copy]p12, C++11 [class.copy]p25:
10134   //   A [default constructor or destructor] is trivial if
10135   //    -- all the direct base classes have trivial [default constructors or
10136   //       destructors]
10137   for (const auto &BI : RD->bases())
10138     if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
10139                                    ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
10140       return false;
10141 
10142   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10143   //   A copy/move [constructor or assignment operator] for a class X is
10144   //   trivial if
10145   //    -- for each non-static data member of X that is of class type (or array
10146   //       thereof), the constructor selected to copy/move that member is
10147   //       trivial
10148   //
10149   // C++11 [class.copy]p12, C++11 [class.copy]p25:
10150   //   A [default constructor or destructor] is trivial if
10151   //    -- for all of the non-static data members of its class that are of class
10152   //       type (or array thereof), each such class has a trivial [default
10153   //       constructor or destructor]
10154   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
10155     return false;
10156 
10157   // C++11 [class.dtor]p5:
10158   //   A destructor is trivial if [...]
10159   //    -- the destructor is not virtual
10160   if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
10161     if (Diagnose)
10162       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
10163     return false;
10164   }
10165 
10166   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
10167   //   A [special member] for class X is trivial if [...]
10168   //    -- class X has no virtual functions and no virtual base classes
10169   if (CSM != CXXSpecialMemberKind::Destructor &&
10170       MD->getParent()->isDynamicClass()) {
10171     if (!Diagnose)
10172       return false;
10173 
10174     if (RD->getNumVBases()) {
10175       // Check for virtual bases. We already know that the corresponding
10176       // member in all bases is trivial, so vbases must all be direct.
10177       CXXBaseSpecifier &BS = *RD->vbases_begin();
10178       assert(BS.isVirtual());
10179       Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
10180       return false;
10181     }
10182 
10183     // Must have a virtual method.
10184     for (const auto *MI : RD->methods()) {
10185       if (MI->isVirtual()) {
10186         SourceLocation MLoc = MI->getBeginLoc();
10187         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
10188         return false;
10189       }
10190     }
10191 
10192     llvm_unreachable("dynamic class with no vbases and no virtual functions");
10193   }
10194 
10195   // Looks like it's trivial!
10196   return true;
10197 }
10198 
10199 namespace {
10200 struct FindHiddenVirtualMethod {
10201   Sema *S;
10202   CXXMethodDecl *Method;
10203   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
10204   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10205 
10206 private:
10207   /// Check whether any most overridden method from MD in Methods
10208   static bool CheckMostOverridenMethods(
10209       const CXXMethodDecl *MD,
10210       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
10211     if (MD->size_overridden_methods() == 0)
10212       return Methods.count(MD->getCanonicalDecl());
10213     for (const CXXMethodDecl *O : MD->overridden_methods())
10214       if (CheckMostOverridenMethods(O, Methods))
10215         return true;
10216     return false;
10217   }
10218 
10219 public:
10220   /// Member lookup function that determines whether a given C++
10221   /// method overloads virtual methods in a base class without overriding any,
10222   /// to be used with CXXRecordDecl::lookupInBases().
10223   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
10224     RecordDecl *BaseRecord =
10225         Specifier->getType()->castAs<RecordType>()->getDecl();
10226 
10227     DeclarationName Name = Method->getDeclName();
10228     assert(Name.getNameKind() == DeclarationName::Identifier);
10229 
10230     bool foundSameNameMethod = false;
10231     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
10232     for (Path.Decls = BaseRecord->lookup(Name).begin();
10233          Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
10234       NamedDecl *D = *Path.Decls;
10235       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
10236         MD = MD->getCanonicalDecl();
10237         foundSameNameMethod = true;
10238         // Interested only in hidden virtual methods.
10239         if (!MD->isVirtual())
10240           continue;
10241         // If the method we are checking overrides a method from its base
10242         // don't warn about the other overloaded methods. Clang deviates from
10243         // GCC by only diagnosing overloads of inherited virtual functions that
10244         // do not override any other virtual functions in the base. GCC's
10245         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
10246         // function from a base class. These cases may be better served by a
10247         // warning (not specific to virtual functions) on call sites when the
10248         // call would select a different function from the base class, were it
10249         // visible.
10250         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
10251         if (!S->IsOverload(Method, MD, false))
10252           return true;
10253         // Collect the overload only if its hidden.
10254         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
10255           overloadedMethods.push_back(MD);
10256       }
10257     }
10258 
10259     if (foundSameNameMethod)
10260       OverloadedMethods.append(overloadedMethods.begin(),
10261                                overloadedMethods.end());
10262     return foundSameNameMethod;
10263   }
10264 };
10265 } // end anonymous namespace
10266 
10267 /// Add the most overridden methods from MD to Methods
10268 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
10269                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
10270   if (MD->size_overridden_methods() == 0)
10271     Methods.insert(MD->getCanonicalDecl());
10272   else
10273     for (const CXXMethodDecl *O : MD->overridden_methods())
10274       AddMostOverridenMethods(O, Methods);
10275 }
10276 
10277 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
10278                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10279   if (!MD->getDeclName().isIdentifier())
10280     return;
10281 
10282   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
10283                      /*bool RecordPaths=*/false,
10284                      /*bool DetectVirtual=*/false);
10285   FindHiddenVirtualMethod FHVM;
10286   FHVM.Method = MD;
10287   FHVM.S = this;
10288 
10289   // Keep the base methods that were overridden or introduced in the subclass
10290   // by 'using' in a set. A base method not in this set is hidden.
10291   CXXRecordDecl *DC = MD->getParent();
10292   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
10293   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
10294     NamedDecl *ND = *I;
10295     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
10296       ND = shad->getTargetDecl();
10297     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
10298       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
10299   }
10300 
10301   if (DC->lookupInBases(FHVM, Paths))
10302     OverloadedMethods = FHVM.OverloadedMethods;
10303 }
10304 
10305 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
10306                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10307   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
10308     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
10309     PartialDiagnostic PD = PDiag(
10310          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
10311     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
10312     Diag(overloadedMD->getLocation(), PD);
10313   }
10314 }
10315 
10316 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
10317   if (MD->isInvalidDecl())
10318     return;
10319 
10320   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
10321     return;
10322 
10323   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10324   FindHiddenVirtualMethods(MD, OverloadedMethods);
10325   if (!OverloadedMethods.empty()) {
10326     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
10327       << MD << (OverloadedMethods.size() > 1);
10328 
10329     NoteHiddenVirtualMethods(MD, OverloadedMethods);
10330   }
10331 }
10332 
10333 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
10334   auto PrintDiagAndRemoveAttr = [&](unsigned N) {
10335     // No diagnostics if this is a template instantiation.
10336     if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) {
10337       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10338            diag::ext_cannot_use_trivial_abi) << &RD;
10339       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10340            diag::note_cannot_use_trivial_abi_reason) << &RD << N;
10341     }
10342     RD.dropAttr<TrivialABIAttr>();
10343   };
10344 
10345   // Ill-formed if the copy and move constructors are deleted.
10346   auto HasNonDeletedCopyOrMoveConstructor = [&]() {
10347     // If the type is dependent, then assume it might have
10348     // implicit copy or move ctor because we won't know yet at this point.
10349     if (RD.isDependentType())
10350       return true;
10351     if (RD.needsImplicitCopyConstructor() &&
10352         !RD.defaultedCopyConstructorIsDeleted())
10353       return true;
10354     if (RD.needsImplicitMoveConstructor() &&
10355         !RD.defaultedMoveConstructorIsDeleted())
10356       return true;
10357     for (const CXXConstructorDecl *CD : RD.ctors())
10358       if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
10359         return true;
10360     return false;
10361   };
10362 
10363   if (!HasNonDeletedCopyOrMoveConstructor()) {
10364     PrintDiagAndRemoveAttr(0);
10365     return;
10366   }
10367 
10368   // Ill-formed if the struct has virtual functions.
10369   if (RD.isPolymorphic()) {
10370     PrintDiagAndRemoveAttr(1);
10371     return;
10372   }
10373 
10374   for (const auto &B : RD.bases()) {
10375     // Ill-formed if the base class is non-trivial for the purpose of calls or a
10376     // virtual base.
10377     if (!B.getType()->isDependentType() &&
10378         !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
10379       PrintDiagAndRemoveAttr(2);
10380       return;
10381     }
10382 
10383     if (B.isVirtual()) {
10384       PrintDiagAndRemoveAttr(3);
10385       return;
10386     }
10387   }
10388 
10389   for (const auto *FD : RD.fields()) {
10390     // Ill-formed if the field is an ObjectiveC pointer or of a type that is
10391     // non-trivial for the purpose of calls.
10392     QualType FT = FD->getType();
10393     if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
10394       PrintDiagAndRemoveAttr(4);
10395       return;
10396     }
10397 
10398     if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
10399       if (!RT->isDependentType() &&
10400           !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
10401         PrintDiagAndRemoveAttr(5);
10402         return;
10403       }
10404   }
10405 }
10406 
10407 void Sema::checkIncorrectVTablePointerAuthenticationAttribute(
10408     CXXRecordDecl &RD) {
10409   if (RequireCompleteType(RD.getLocation(), Context.getRecordType(&RD),
10410                           diag::err_incomplete_type_vtable_pointer_auth))
10411     return;
10412 
10413   const CXXRecordDecl *PrimaryBase = &RD;
10414   if (PrimaryBase->hasAnyDependentBases())
10415     return;
10416 
10417   while (1) {
10418     assert(PrimaryBase);
10419     const CXXRecordDecl *Base = nullptr;
10420     for (auto BasePtr : PrimaryBase->bases()) {
10421       if (!BasePtr.getType()->getAsCXXRecordDecl()->isDynamicClass())
10422         continue;
10423       Base = BasePtr.getType()->getAsCXXRecordDecl();
10424       break;
10425     }
10426     if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
10427       break;
10428     Diag(RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
10429          diag::err_non_top_level_vtable_pointer_auth)
10430         << &RD << Base;
10431     PrimaryBase = Base;
10432   }
10433 
10434   if (!RD.isPolymorphic())
10435     Diag(RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
10436          diag::err_non_polymorphic_vtable_pointer_auth)
10437         << &RD;
10438 }
10439 
10440 void Sema::ActOnFinishCXXMemberSpecification(
10441     Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
10442     SourceLocation RBrac, const ParsedAttributesView &AttrList) {
10443   if (!TagDecl)
10444     return;
10445 
10446   AdjustDeclIfTemplate(TagDecl);
10447 
10448   for (const ParsedAttr &AL : AttrList) {
10449     if (AL.getKind() != ParsedAttr::AT_Visibility)
10450       continue;
10451     AL.setInvalid();
10452     Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
10453   }
10454 
10455   ActOnFields(S, RLoc, TagDecl,
10456               llvm::ArrayRef(
10457                   // strict aliasing violation!
10458                   reinterpret_cast<Decl **>(FieldCollector->getCurFields()),
10459                   FieldCollector->getCurNumFields()),
10460               LBrac, RBrac, AttrList);
10461 
10462   CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));
10463 }
10464 
10465 /// Find the equality comparison functions that should be implicitly declared
10466 /// in a given class definition, per C++2a [class.compare.default]p3.
10467 static void findImplicitlyDeclaredEqualityComparisons(
10468     ASTContext &Ctx, CXXRecordDecl *RD,
10469     llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {
10470   DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
10471   if (!RD->lookup(EqEq).empty())
10472     // Member operator== explicitly declared: no implicit operator==s.
10473     return;
10474 
10475   // Traverse friends looking for an '==' or a '<=>'.
10476   for (FriendDecl *Friend : RD->friends()) {
10477     FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
10478     if (!FD) continue;
10479 
10480     if (FD->getOverloadedOperator() == OO_EqualEqual) {
10481       // Friend operator== explicitly declared: no implicit operator==s.
10482       Spaceships.clear();
10483       return;
10484     }
10485 
10486     if (FD->getOverloadedOperator() == OO_Spaceship &&
10487         FD->isExplicitlyDefaulted())
10488       Spaceships.push_back(FD);
10489   }
10490 
10491   // Look for members named 'operator<=>'.
10492   DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
10493   for (NamedDecl *ND : RD->lookup(Cmp)) {
10494     // Note that we could find a non-function here (either a function template
10495     // or a using-declaration). Neither case results in an implicit
10496     // 'operator=='.
10497     if (auto *FD = dyn_cast<FunctionDecl>(ND))
10498       if (FD->isExplicitlyDefaulted())
10499         Spaceships.push_back(FD);
10500   }
10501 }
10502 
10503 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
10504   // Don't add implicit special members to templated classes.
10505   // FIXME: This means unqualified lookups for 'operator=' within a class
10506   // template don't work properly.
10507   if (!ClassDecl->isDependentType()) {
10508     if (ClassDecl->needsImplicitDefaultConstructor()) {
10509       ++getASTContext().NumImplicitDefaultConstructors;
10510 
10511       if (ClassDecl->hasInheritedConstructor())
10512         DeclareImplicitDefaultConstructor(ClassDecl);
10513     }
10514 
10515     if (ClassDecl->needsImplicitCopyConstructor()) {
10516       ++getASTContext().NumImplicitCopyConstructors;
10517 
10518       // If the properties or semantics of the copy constructor couldn't be
10519       // determined while the class was being declared, force a declaration
10520       // of it now.
10521       if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
10522           ClassDecl->hasInheritedConstructor())
10523         DeclareImplicitCopyConstructor(ClassDecl);
10524       // For the MS ABI we need to know whether the copy ctor is deleted. A
10525       // prerequisite for deleting the implicit copy ctor is that the class has
10526       // a move ctor or move assignment that is either user-declared or whose
10527       // semantics are inherited from a subobject. FIXME: We should provide a
10528       // more direct way for CodeGen to ask whether the constructor was deleted.
10529       else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10530                (ClassDecl->hasUserDeclaredMoveConstructor() ||
10531                 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10532                 ClassDecl->hasUserDeclaredMoveAssignment() ||
10533                 ClassDecl->needsOverloadResolutionForMoveAssignment()))
10534         DeclareImplicitCopyConstructor(ClassDecl);
10535     }
10536 
10537     if (getLangOpts().CPlusPlus11 &&
10538         ClassDecl->needsImplicitMoveConstructor()) {
10539       ++getASTContext().NumImplicitMoveConstructors;
10540 
10541       if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10542           ClassDecl->hasInheritedConstructor())
10543         DeclareImplicitMoveConstructor(ClassDecl);
10544     }
10545 
10546     if (ClassDecl->needsImplicitCopyAssignment()) {
10547       ++getASTContext().NumImplicitCopyAssignmentOperators;
10548 
10549       // If we have a dynamic class, then the copy assignment operator may be
10550       // virtual, so we have to declare it immediately. This ensures that, e.g.,
10551       // it shows up in the right place in the vtable and that we diagnose
10552       // problems with the implicit exception specification.
10553       if (ClassDecl->isDynamicClass() ||
10554           ClassDecl->needsOverloadResolutionForCopyAssignment() ||
10555           ClassDecl->hasInheritedAssignment())
10556         DeclareImplicitCopyAssignment(ClassDecl);
10557     }
10558 
10559     if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10560       ++getASTContext().NumImplicitMoveAssignmentOperators;
10561 
10562       // Likewise for the move assignment operator.
10563       if (ClassDecl->isDynamicClass() ||
10564           ClassDecl->needsOverloadResolutionForMoveAssignment() ||
10565           ClassDecl->hasInheritedAssignment())
10566         DeclareImplicitMoveAssignment(ClassDecl);
10567     }
10568 
10569     if (ClassDecl->needsImplicitDestructor()) {
10570       ++getASTContext().NumImplicitDestructors;
10571 
10572       // If we have a dynamic class, then the destructor may be virtual, so we
10573       // have to declare the destructor immediately. This ensures that, e.g., it
10574       // shows up in the right place in the vtable and that we diagnose problems
10575       // with the implicit exception specification.
10576       if (ClassDecl->isDynamicClass() ||
10577           ClassDecl->needsOverloadResolutionForDestructor())
10578         DeclareImplicitDestructor(ClassDecl);
10579     }
10580   }
10581 
10582   // C++2a [class.compare.default]p3:
10583   //   If the member-specification does not explicitly declare any member or
10584   //   friend named operator==, an == operator function is declared implicitly
10585   //   for each defaulted three-way comparison operator function defined in
10586   //   the member-specification
10587   // FIXME: Consider doing this lazily.
10588   // We do this during the initial parse for a class template, not during
10589   // instantiation, so that we can handle unqualified lookups for 'operator=='
10590   // when parsing the template.
10591   if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) {
10592     llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
10593     findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl,
10594                                               DefaultedSpaceships);
10595     for (auto *FD : DefaultedSpaceships)
10596       DeclareImplicitEqualityComparison(ClassDecl, FD);
10597   }
10598 }
10599 
10600 unsigned
10601 Sema::ActOnReenterTemplateScope(Decl *D,
10602                                 llvm::function_ref<Scope *()> EnterScope) {
10603   if (!D)
10604     return 0;
10605   AdjustDeclIfTemplate(D);
10606 
10607   // In order to get name lookup right, reenter template scopes in order from
10608   // outermost to innermost.
10609   SmallVector<TemplateParameterList *, 4> ParameterLists;
10610   DeclContext *LookupDC = dyn_cast<DeclContext>(D);
10611 
10612   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
10613     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
10614       ParameterLists.push_back(DD->getTemplateParameterList(i));
10615 
10616     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10617       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
10618         ParameterLists.push_back(FTD->getTemplateParameters());
10619     } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10620       LookupDC = VD->getDeclContext();
10621 
10622       if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())
10623         ParameterLists.push_back(VTD->getTemplateParameters());
10624       else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
10625         ParameterLists.push_back(PSD->getTemplateParameters());
10626     }
10627   } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
10628     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
10629       ParameterLists.push_back(TD->getTemplateParameterList(i));
10630 
10631     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
10632       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
10633         ParameterLists.push_back(CTD->getTemplateParameters());
10634       else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
10635         ParameterLists.push_back(PSD->getTemplateParameters());
10636     }
10637   }
10638   // FIXME: Alias declarations and concepts.
10639 
10640   unsigned Count = 0;
10641   Scope *InnermostTemplateScope = nullptr;
10642   for (TemplateParameterList *Params : ParameterLists) {
10643     // Ignore explicit specializations; they don't contribute to the template
10644     // depth.
10645     if (Params->size() == 0)
10646       continue;
10647 
10648     InnermostTemplateScope = EnterScope();
10649     for (NamedDecl *Param : *Params) {
10650       if (Param->getDeclName()) {
10651         InnermostTemplateScope->AddDecl(Param);
10652         IdResolver.AddDecl(Param);
10653       }
10654     }
10655     ++Count;
10656   }
10657 
10658   // Associate the new template scopes with the corresponding entities.
10659   if (InnermostTemplateScope) {
10660     assert(LookupDC && "no enclosing DeclContext for template lookup");
10661     EnterTemplatedContext(InnermostTemplateScope, LookupDC);
10662   }
10663 
10664   return Count;
10665 }
10666 
10667 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10668   if (!RecordD) return;
10669   AdjustDeclIfTemplate(RecordD);
10670   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
10671   PushDeclContext(S, Record);
10672 }
10673 
10674 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10675   if (!RecordD) return;
10676   PopDeclContext();
10677 }
10678 
10679 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
10680   if (!Param)
10681     return;
10682 
10683   S->AddDecl(Param);
10684   if (Param->getDeclName())
10685     IdResolver.AddDecl(Param);
10686 }
10687 
10688 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10689 }
10690 
10691 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
10692 /// C++ method declaration. We're (re-)introducing the given
10693 /// function parameter into scope for use in parsing later parts of
10694 /// the method declaration. For example, we could see an
10695 /// ActOnParamDefaultArgument event for this parameter.
10696 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
10697   if (!ParamD)
10698     return;
10699 
10700   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
10701 
10702   S->AddDecl(Param);
10703   if (Param->getDeclName())
10704     IdResolver.AddDecl(Param);
10705 }
10706 
10707 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10708   if (!MethodD)
10709     return;
10710 
10711   AdjustDeclIfTemplate(MethodD);
10712 
10713   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
10714 
10715   // Now that we have our default arguments, check the constructor
10716   // again. It could produce additional diagnostics or affect whether
10717   // the class has implicitly-declared destructors, among other
10718   // things.
10719   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
10720     CheckConstructor(Constructor);
10721 
10722   // Check the default arguments, which we may have added.
10723   if (!Method->isInvalidDecl())
10724     CheckCXXDefaultArguments(Method);
10725 }
10726 
10727 // Emit the given diagnostic for each non-address-space qualifier.
10728 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
10729 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10730   const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10731   if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10732     bool DiagOccured = false;
10733     FTI.MethodQualifiers->forEachQualifier(
10734         [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10735                                    SourceLocation SL) {
10736           // This diagnostic should be emitted on any qualifier except an addr
10737           // space qualifier. However, forEachQualifier currently doesn't visit
10738           // addr space qualifiers, so there's no way to write this condition
10739           // right now; we just diagnose on everything.
10740           S.Diag(SL, DiagID) << QualName << SourceRange(SL);
10741           DiagOccured = true;
10742         });
10743     if (DiagOccured)
10744       D.setInvalidType();
10745   }
10746 }
10747 
10748 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
10749                                           StorageClass &SC) {
10750   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10751 
10752   // C++ [class.ctor]p3:
10753   //   A constructor shall not be virtual (10.3) or static (9.4). A
10754   //   constructor can be invoked for a const, volatile or const
10755   //   volatile object. A constructor shall not be declared const,
10756   //   volatile, or const volatile (9.3.2).
10757   if (isVirtual) {
10758     if (!D.isInvalidType())
10759       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10760         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
10761         << SourceRange(D.getIdentifierLoc());
10762     D.setInvalidType();
10763   }
10764   if (SC == SC_Static) {
10765     if (!D.isInvalidType())
10766       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10767         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10768         << SourceRange(D.getIdentifierLoc());
10769     D.setInvalidType();
10770     SC = SC_None;
10771   }
10772 
10773   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10774     diagnoseIgnoredQualifiers(
10775         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
10776         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
10777         D.getDeclSpec().getRestrictSpecLoc(),
10778         D.getDeclSpec().getAtomicSpecLoc());
10779     D.setInvalidType();
10780   }
10781 
10782   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
10783 
10784   // C++0x [class.ctor]p4:
10785   //   A constructor shall not be declared with a ref-qualifier.
10786   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10787   if (FTI.hasRefQualifier()) {
10788     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
10789       << FTI.RefQualifierIsLValueRef
10790       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10791     D.setInvalidType();
10792   }
10793 
10794   // Rebuild the function type "R" without any type qualifiers (in
10795   // case any of the errors above fired) and with "void" as the
10796   // return type, since constructors don't have return types.
10797   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10798   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
10799     return R;
10800 
10801   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10802   EPI.TypeQuals = Qualifiers();
10803   EPI.RefQualifier = RQ_None;
10804 
10805   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
10806 }
10807 
10808 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
10809   CXXRecordDecl *ClassDecl
10810     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
10811   if (!ClassDecl)
10812     return Constructor->setInvalidDecl();
10813 
10814   // C++ [class.copy]p3:
10815   //   A declaration of a constructor for a class X is ill-formed if
10816   //   its first parameter is of type (optionally cv-qualified) X and
10817   //   either there are no other parameters or else all other
10818   //   parameters have default arguments.
10819   if (!Constructor->isInvalidDecl() &&
10820       Constructor->hasOneParamOrDefaultArgs() &&
10821       Constructor->getTemplateSpecializationKind() !=
10822           TSK_ImplicitInstantiation) {
10823     QualType ParamType = Constructor->getParamDecl(0)->getType();
10824     QualType ClassTy = Context.getTagDeclType(ClassDecl);
10825     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
10826       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
10827       const char *ConstRef
10828         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
10829                                                         : " const &";
10830       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
10831         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
10832 
10833       // FIXME: Rather that making the constructor invalid, we should endeavor
10834       // to fix the type.
10835       Constructor->setInvalidDecl();
10836     }
10837   }
10838 }
10839 
10840 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
10841   CXXRecordDecl *RD = Destructor->getParent();
10842 
10843   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
10844     SourceLocation Loc;
10845 
10846     if (!Destructor->isImplicit())
10847       Loc = Destructor->getLocation();
10848     else
10849       Loc = RD->getLocation();
10850 
10851     // If we have a virtual destructor, look up the deallocation function
10852     if (FunctionDecl *OperatorDelete =
10853             FindDeallocationFunctionForDestructor(Loc, RD)) {
10854       Expr *ThisArg = nullptr;
10855 
10856       // If the notional 'delete this' expression requires a non-trivial
10857       // conversion from 'this' to the type of a destroying operator delete's
10858       // first parameter, perform that conversion now.
10859       if (OperatorDelete->isDestroyingOperatorDelete()) {
10860         QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
10861         if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
10862           // C++ [class.dtor]p13:
10863           //   ... as if for the expression 'delete this' appearing in a
10864           //   non-virtual destructor of the destructor's class.
10865           ContextRAII SwitchContext(*this, Destructor);
10866           ExprResult This =
10867               ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
10868           assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
10869           This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
10870           if (This.isInvalid()) {
10871             // FIXME: Register this as a context note so that it comes out
10872             // in the right order.
10873             Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
10874             return true;
10875           }
10876           ThisArg = This.get();
10877         }
10878       }
10879 
10880       DiagnoseUseOfDecl(OperatorDelete, Loc);
10881       MarkFunctionReferenced(Loc, OperatorDelete);
10882       Destructor->setOperatorDelete(OperatorDelete, ThisArg);
10883     }
10884   }
10885 
10886   return false;
10887 }
10888 
10889 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
10890                                          StorageClass& SC) {
10891   // C++ [class.dtor]p1:
10892   //   [...] A typedef-name that names a class is a class-name
10893   //   (7.1.3); however, a typedef-name that names a class shall not
10894   //   be used as the identifier in the declarator for a destructor
10895   //   declaration.
10896   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
10897   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
10898     Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10899       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
10900   else if (const TemplateSpecializationType *TST =
10901              DeclaratorType->getAs<TemplateSpecializationType>())
10902     if (TST->isTypeAlias())
10903       Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10904         << DeclaratorType << 1;
10905 
10906   // C++ [class.dtor]p2:
10907   //   A destructor is used to destroy objects of its class type. A
10908   //   destructor takes no parameters, and no return type can be
10909   //   specified for it (not even void). The address of a destructor
10910   //   shall not be taken. A destructor shall not be static. A
10911   //   destructor can be invoked for a const, volatile or const
10912   //   volatile object. A destructor shall not be declared const,
10913   //   volatile or const volatile (9.3.2).
10914   if (SC == SC_Static) {
10915     if (!D.isInvalidType())
10916       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
10917         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10918         << SourceRange(D.getIdentifierLoc())
10919         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10920 
10921     SC = SC_None;
10922   }
10923   if (!D.isInvalidType()) {
10924     // Destructors don't have return types, but the parser will
10925     // happily parse something like:
10926     //
10927     //   class X {
10928     //     float ~X();
10929     //   };
10930     //
10931     // The return type will be eliminated later.
10932     if (D.getDeclSpec().hasTypeSpecifier())
10933       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
10934         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
10935         << SourceRange(D.getIdentifierLoc());
10936     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10937       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
10938                                 SourceLocation(),
10939                                 D.getDeclSpec().getConstSpecLoc(),
10940                                 D.getDeclSpec().getVolatileSpecLoc(),
10941                                 D.getDeclSpec().getRestrictSpecLoc(),
10942                                 D.getDeclSpec().getAtomicSpecLoc());
10943       D.setInvalidType();
10944     }
10945   }
10946 
10947   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
10948 
10949   // C++0x [class.dtor]p2:
10950   //   A destructor shall not be declared with a ref-qualifier.
10951   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10952   if (FTI.hasRefQualifier()) {
10953     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
10954       << FTI.RefQualifierIsLValueRef
10955       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10956     D.setInvalidType();
10957   }
10958 
10959   // Make sure we don't have any parameters.
10960   if (FTIHasNonVoidParameters(FTI)) {
10961     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
10962 
10963     // Delete the parameters.
10964     FTI.freeParams();
10965     D.setInvalidType();
10966   }
10967 
10968   // Make sure the destructor isn't variadic.
10969   if (FTI.isVariadic) {
10970     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
10971     D.setInvalidType();
10972   }
10973 
10974   // Rebuild the function type "R" without any type qualifiers or
10975   // parameters (in case any of the errors above fired) and with
10976   // "void" as the return type, since destructors don't have return
10977   // types.
10978   if (!D.isInvalidType())
10979     return R;
10980 
10981   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10982   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10983   EPI.Variadic = false;
10984   EPI.TypeQuals = Qualifiers();
10985   EPI.RefQualifier = RQ_None;
10986   return Context.getFunctionType(Context.VoidTy, std::nullopt, EPI);
10987 }
10988 
10989 static void extendLeft(SourceRange &R, SourceRange Before) {
10990   if (Before.isInvalid())
10991     return;
10992   R.setBegin(Before.getBegin());
10993   if (R.getEnd().isInvalid())
10994     R.setEnd(Before.getEnd());
10995 }
10996 
10997 static void extendRight(SourceRange &R, SourceRange After) {
10998   if (After.isInvalid())
10999     return;
11000   if (R.getBegin().isInvalid())
11001     R.setBegin(After.getBegin());
11002   R.setEnd(After.getEnd());
11003 }
11004 
11005 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
11006                                      StorageClass& SC) {
11007   // C++ [class.conv.fct]p1:
11008   //   Neither parameter types nor return type can be specified. The
11009   //   type of a conversion function (8.3.5) is "function taking no
11010   //   parameter returning conversion-type-id."
11011   if (SC == SC_Static) {
11012     if (!D.isInvalidType())
11013       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
11014         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11015         << D.getName().getSourceRange();
11016     D.setInvalidType();
11017     SC = SC_None;
11018   }
11019 
11020   TypeSourceInfo *ConvTSI = nullptr;
11021   QualType ConvType =
11022       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
11023 
11024   const DeclSpec &DS = D.getDeclSpec();
11025   if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
11026     // Conversion functions don't have return types, but the parser will
11027     // happily parse something like:
11028     //
11029     //   class X {
11030     //     float operator bool();
11031     //   };
11032     //
11033     // The return type will be changed later anyway.
11034     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
11035       << SourceRange(DS.getTypeSpecTypeLoc())
11036       << SourceRange(D.getIdentifierLoc());
11037     D.setInvalidType();
11038   } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
11039     // It's also plausible that the user writes type qualifiers in the wrong
11040     // place, such as:
11041     //   struct S { const operator int(); };
11042     // FIXME: we could provide a fixit to move the qualifiers onto the
11043     // conversion type.
11044     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
11045         << SourceRange(D.getIdentifierLoc()) << 0;
11046     D.setInvalidType();
11047   }
11048   const auto *Proto = R->castAs<FunctionProtoType>();
11049   // Make sure we don't have any parameters.
11050   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11051   unsigned NumParam = Proto->getNumParams();
11052 
11053   // [C++2b]
11054   // A conversion function shall have no non-object parameters.
11055   if (NumParam == 1) {
11056     DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11057     if (const auto *First =
11058             dyn_cast_if_present<ParmVarDecl>(FTI.Params[0].Param);
11059         First && First->isExplicitObjectParameter())
11060       NumParam--;
11061   }
11062 
11063   if (NumParam != 0) {
11064     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
11065     // Delete the parameters.
11066     FTI.freeParams();
11067     D.setInvalidType();
11068   } else if (Proto->isVariadic()) {
11069     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
11070     D.setInvalidType();
11071   }
11072 
11073   // Diagnose "&operator bool()" and other such nonsense.  This
11074   // is actually a gcc extension which we don't support.
11075   if (Proto->getReturnType() != ConvType) {
11076     bool NeedsTypedef = false;
11077     SourceRange Before, After;
11078 
11079     // Walk the chunks and extract information on them for our diagnostic.
11080     bool PastFunctionChunk = false;
11081     for (auto &Chunk : D.type_objects()) {
11082       switch (Chunk.Kind) {
11083       case DeclaratorChunk::Function:
11084         if (!PastFunctionChunk) {
11085           if (Chunk.Fun.HasTrailingReturnType) {
11086             TypeSourceInfo *TRT = nullptr;
11087             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
11088             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
11089           }
11090           PastFunctionChunk = true;
11091           break;
11092         }
11093         [[fallthrough]];
11094       case DeclaratorChunk::Array:
11095         NeedsTypedef = true;
11096         extendRight(After, Chunk.getSourceRange());
11097         break;
11098 
11099       case DeclaratorChunk::Pointer:
11100       case DeclaratorChunk::BlockPointer:
11101       case DeclaratorChunk::Reference:
11102       case DeclaratorChunk::MemberPointer:
11103       case DeclaratorChunk::Pipe:
11104         extendLeft(Before, Chunk.getSourceRange());
11105         break;
11106 
11107       case DeclaratorChunk::Paren:
11108         extendLeft(Before, Chunk.Loc);
11109         extendRight(After, Chunk.EndLoc);
11110         break;
11111       }
11112     }
11113 
11114     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
11115                          After.isValid()  ? After.getBegin() :
11116                                             D.getIdentifierLoc();
11117     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
11118     DB << Before << After;
11119 
11120     if (!NeedsTypedef) {
11121       DB << /*don't need a typedef*/0;
11122 
11123       // If we can provide a correct fix-it hint, do so.
11124       if (After.isInvalid() && ConvTSI) {
11125         SourceLocation InsertLoc =
11126             getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
11127         DB << FixItHint::CreateInsertion(InsertLoc, " ")
11128            << FixItHint::CreateInsertionFromRange(
11129                   InsertLoc, CharSourceRange::getTokenRange(Before))
11130            << FixItHint::CreateRemoval(Before);
11131       }
11132     } else if (!Proto->getReturnType()->isDependentType()) {
11133       DB << /*typedef*/1 << Proto->getReturnType();
11134     } else if (getLangOpts().CPlusPlus11) {
11135       DB << /*alias template*/2 << Proto->getReturnType();
11136     } else {
11137       DB << /*might not be fixable*/3;
11138     }
11139 
11140     // Recover by incorporating the other type chunks into the result type.
11141     // Note, this does *not* change the name of the function. This is compatible
11142     // with the GCC extension:
11143     //   struct S { &operator int(); } s;
11144     //   int &r = s.operator int(); // ok in GCC
11145     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
11146     ConvType = Proto->getReturnType();
11147   }
11148 
11149   // C++ [class.conv.fct]p4:
11150   //   The conversion-type-id shall not represent a function type nor
11151   //   an array type.
11152   if (ConvType->isArrayType()) {
11153     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
11154     ConvType = Context.getPointerType(ConvType);
11155     D.setInvalidType();
11156   } else if (ConvType->isFunctionType()) {
11157     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
11158     ConvType = Context.getPointerType(ConvType);
11159     D.setInvalidType();
11160   }
11161 
11162   // Rebuild the function type "R" without any parameters (in case any
11163   // of the errors above fired) and with the conversion type as the
11164   // return type.
11165   if (D.isInvalidType())
11166     R = Context.getFunctionType(ConvType, std::nullopt,
11167                                 Proto->getExtProtoInfo());
11168 
11169   // C++0x explicit conversion operators.
11170   if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20)
11171     Diag(DS.getExplicitSpecLoc(),
11172          getLangOpts().CPlusPlus11
11173              ? diag::warn_cxx98_compat_explicit_conversion_functions
11174              : diag::ext_explicit_conversion_functions)
11175         << SourceRange(DS.getExplicitSpecRange());
11176 }
11177 
11178 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
11179   assert(Conversion && "Expected to receive a conversion function declaration");
11180 
11181   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
11182 
11183   // Make sure we aren't redeclaring the conversion function.
11184   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
11185   // C++ [class.conv.fct]p1:
11186   //   [...] A conversion function is never used to convert a
11187   //   (possibly cv-qualified) object to the (possibly cv-qualified)
11188   //   same object type (or a reference to it), to a (possibly
11189   //   cv-qualified) base class of that type (or a reference to it),
11190   //   or to (possibly cv-qualified) void.
11191   QualType ClassType
11192     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
11193   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
11194     ConvType = ConvTypeRef->getPointeeType();
11195   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
11196       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
11197     /* Suppress diagnostics for instantiations. */;
11198   else if (Conversion->size_overridden_methods() != 0)
11199     /* Suppress diagnostics for overriding virtual function in a base class. */;
11200   else if (ConvType->isRecordType()) {
11201     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
11202     if (ConvType == ClassType)
11203       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
11204         << ClassType;
11205     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
11206       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
11207         <<  ClassType << ConvType;
11208   } else if (ConvType->isVoidType()) {
11209     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
11210       << ClassType << ConvType;
11211   }
11212 
11213   if (FunctionTemplateDecl *ConversionTemplate =
11214           Conversion->getDescribedFunctionTemplate()) {
11215     if (const auto *ConvTypePtr = ConvType->getAs<PointerType>()) {
11216       ConvType = ConvTypePtr->getPointeeType();
11217     }
11218     if (ConvType->isUndeducedAutoType()) {
11219       Diag(Conversion->getTypeSpecStartLoc(), diag::err_auto_not_allowed)
11220           << getReturnTypeLoc(Conversion).getSourceRange()
11221           << llvm::to_underlying(ConvType->castAs<AutoType>()->getKeyword())
11222           << /* in declaration of conversion function template= */ 24;
11223     }
11224 
11225     return ConversionTemplate;
11226   }
11227 
11228   return Conversion;
11229 }
11230 
11231 void Sema::CheckExplicitObjectMemberFunction(DeclContext *DC, Declarator &D,
11232                                              DeclarationName Name, QualType R) {
11233   CheckExplicitObjectMemberFunction(D, Name, R, false, DC);
11234 }
11235 
11236 void Sema::CheckExplicitObjectLambda(Declarator &D) {
11237   CheckExplicitObjectMemberFunction(D, {}, {}, true);
11238 }
11239 
11240 void Sema::CheckExplicitObjectMemberFunction(Declarator &D,
11241                                              DeclarationName Name, QualType R,
11242                                              bool IsLambda, DeclContext *DC) {
11243   if (!D.isFunctionDeclarator())
11244     return;
11245 
11246   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11247   if (FTI.NumParams == 0)
11248     return;
11249   ParmVarDecl *ExplicitObjectParam = nullptr;
11250   for (unsigned Idx = 0; Idx < FTI.NumParams; Idx++) {
11251     const auto &ParamInfo = FTI.Params[Idx];
11252     if (!ParamInfo.Param)
11253       continue;
11254     ParmVarDecl *Param = cast<ParmVarDecl>(ParamInfo.Param);
11255     if (!Param->isExplicitObjectParameter())
11256       continue;
11257     if (Idx == 0) {
11258       ExplicitObjectParam = Param;
11259       continue;
11260     } else {
11261       Diag(Param->getLocation(),
11262            diag::err_explicit_object_parameter_must_be_first)
11263           << IsLambda << Param->getSourceRange();
11264     }
11265   }
11266   if (!ExplicitObjectParam)
11267     return;
11268 
11269   if (ExplicitObjectParam->hasDefaultArg()) {
11270     Diag(ExplicitObjectParam->getLocation(),
11271          diag::err_explicit_object_default_arg)
11272         << ExplicitObjectParam->getSourceRange();
11273   }
11274 
11275   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
11276       (D.getContext() == clang::DeclaratorContext::Member &&
11277        D.isStaticMember())) {
11278     Diag(ExplicitObjectParam->getBeginLoc(),
11279          diag::err_explicit_object_parameter_nonmember)
11280         << D.getSourceRange() << /*static=*/0 << IsLambda;
11281     D.setInvalidType();
11282   }
11283 
11284   if (D.getDeclSpec().isVirtualSpecified()) {
11285     Diag(ExplicitObjectParam->getBeginLoc(),
11286          diag::err_explicit_object_parameter_nonmember)
11287         << D.getSourceRange() << /*virtual=*/1 << IsLambda;
11288     D.setInvalidType();
11289   }
11290 
11291   // Friend declarations require some care. Consider:
11292   //
11293   // namespace N {
11294   // struct A{};
11295   // int f(A);
11296   // }
11297   //
11298   // struct S {
11299   //   struct T {
11300   //     int f(this T);
11301   //   };
11302   //
11303   //   friend int T::f(this T); // Allow this.
11304   //   friend int f(this S);    // But disallow this.
11305   //   friend int N::f(this A); // And disallow this.
11306   // };
11307   //
11308   // Here, it seems to suffice to check whether the scope
11309   // specifier designates a class type.
11310   if (D.getDeclSpec().isFriendSpecified() &&
11311       !isa_and_present<CXXRecordDecl>(
11312           computeDeclContext(D.getCXXScopeSpec()))) {
11313     Diag(ExplicitObjectParam->getBeginLoc(),
11314          diag::err_explicit_object_parameter_nonmember)
11315         << D.getSourceRange() << /*non-member=*/2 << IsLambda;
11316     D.setInvalidType();
11317   }
11318 
11319   if (IsLambda && FTI.hasMutableQualifier()) {
11320     Diag(ExplicitObjectParam->getBeginLoc(),
11321          diag::err_explicit_object_parameter_mutable)
11322         << D.getSourceRange();
11323   }
11324 
11325   if (IsLambda)
11326     return;
11327 
11328   if (!DC || !DC->isRecord()) {
11329     assert(D.isInvalidType() && "Explicit object parameter in non-member "
11330                                 "should have been diagnosed already");
11331     return;
11332   }
11333 
11334   // CWG2674: constructors and destructors cannot have explicit parameters.
11335   if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
11336       Name.getNameKind() == DeclarationName::CXXDestructorName) {
11337     Diag(ExplicitObjectParam->getBeginLoc(),
11338          diag::err_explicit_object_parameter_constructor)
11339         << (Name.getNameKind() == DeclarationName::CXXDestructorName)
11340         << D.getSourceRange();
11341     D.setInvalidType();
11342   }
11343 }
11344 
11345 namespace {
11346 /// Utility class to accumulate and print a diagnostic listing the invalid
11347 /// specifier(s) on a declaration.
11348 struct BadSpecifierDiagnoser {
11349   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
11350       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
11351   ~BadSpecifierDiagnoser() {
11352     Diagnostic << Specifiers;
11353   }
11354 
11355   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
11356     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
11357   }
11358   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
11359     return check(SpecLoc,
11360                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
11361   }
11362   void check(SourceLocation SpecLoc, const char *Spec) {
11363     if (SpecLoc.isInvalid()) return;
11364     Diagnostic << SourceRange(SpecLoc, SpecLoc);
11365     if (!Specifiers.empty()) Specifiers += " ";
11366     Specifiers += Spec;
11367   }
11368 
11369   Sema &S;
11370   Sema::SemaDiagnosticBuilder Diagnostic;
11371   std::string Specifiers;
11372 };
11373 }
11374 
11375 bool Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
11376                                          StorageClass &SC) {
11377   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
11378   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
11379   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
11380 
11381   // C++ [temp.deduct.guide]p3:
11382   //   A deduction-gide shall be declared in the same scope as the
11383   //   corresponding class template.
11384   if (!CurContext->getRedeclContext()->Equals(
11385           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
11386     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
11387       << GuidedTemplateDecl;
11388     NoteTemplateLocation(*GuidedTemplateDecl);
11389   }
11390 
11391   auto &DS = D.getMutableDeclSpec();
11392   // We leave 'friend' and 'virtual' to be rejected in the normal way.
11393   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
11394       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
11395       DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
11396     BadSpecifierDiagnoser Diagnoser(
11397         *this, D.getIdentifierLoc(),
11398         diag::err_deduction_guide_invalid_specifier);
11399 
11400     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
11401     DS.ClearStorageClassSpecs();
11402     SC = SC_None;
11403 
11404     // 'explicit' is permitted.
11405     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
11406     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
11407     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
11408     DS.ClearConstexprSpec();
11409 
11410     Diagnoser.check(DS.getConstSpecLoc(), "const");
11411     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
11412     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
11413     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
11414     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
11415     DS.ClearTypeQualifiers();
11416 
11417     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
11418     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
11419     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
11420     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
11421     DS.ClearTypeSpecType();
11422   }
11423 
11424   if (D.isInvalidType())
11425     return true;
11426 
11427   // Check the declarator is simple enough.
11428   bool FoundFunction = false;
11429   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
11430     if (Chunk.Kind == DeclaratorChunk::Paren)
11431       continue;
11432     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
11433       Diag(D.getDeclSpec().getBeginLoc(),
11434            diag::err_deduction_guide_with_complex_decl)
11435           << D.getSourceRange();
11436       break;
11437     }
11438     if (!Chunk.Fun.hasTrailingReturnType())
11439       return Diag(D.getName().getBeginLoc(),
11440                   diag::err_deduction_guide_no_trailing_return_type);
11441 
11442     // Check that the return type is written as a specialization of
11443     // the template specified as the deduction-guide's name.
11444     // The template name may not be qualified. [temp.deduct.guide]
11445     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
11446     TypeSourceInfo *TSI = nullptr;
11447     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
11448     assert(TSI && "deduction guide has valid type but invalid return type?");
11449     bool AcceptableReturnType = false;
11450     bool MightInstantiateToSpecialization = false;
11451     if (auto RetTST =
11452             TSI->getTypeLoc().getAsAdjusted<TemplateSpecializationTypeLoc>()) {
11453       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
11454       bool TemplateMatches =
11455           Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
11456 
11457       const QualifiedTemplateName *Qualifiers =
11458           SpecifiedName.getAsQualifiedTemplateName();
11459       assert(Qualifiers && "expected QualifiedTemplate");
11460       bool SimplyWritten = !Qualifiers->hasTemplateKeyword() &&
11461                            Qualifiers->getQualifier() == nullptr;
11462       if (SimplyWritten && TemplateMatches)
11463         AcceptableReturnType = true;
11464       else {
11465         // This could still instantiate to the right type, unless we know it
11466         // names the wrong class template.
11467         auto *TD = SpecifiedName.getAsTemplateDecl();
11468         MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
11469                                              !TemplateMatches);
11470       }
11471     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
11472       MightInstantiateToSpecialization = true;
11473     }
11474 
11475     if (!AcceptableReturnType)
11476       return Diag(TSI->getTypeLoc().getBeginLoc(),
11477                   diag::err_deduction_guide_bad_trailing_return_type)
11478              << GuidedTemplate << TSI->getType()
11479              << MightInstantiateToSpecialization
11480              << TSI->getTypeLoc().getSourceRange();
11481 
11482     // Keep going to check that we don't have any inner declarator pieces (we
11483     // could still have a function returning a pointer to a function).
11484     FoundFunction = true;
11485   }
11486 
11487   if (D.isFunctionDefinition())
11488     // we can still create a valid deduction guide here.
11489     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
11490   return false;
11491 }
11492 
11493 //===----------------------------------------------------------------------===//
11494 // Namespace Handling
11495 //===----------------------------------------------------------------------===//
11496 
11497 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
11498 /// reopened.
11499 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
11500                                             SourceLocation Loc,
11501                                             IdentifierInfo *II, bool *IsInline,
11502                                             NamespaceDecl *PrevNS) {
11503   assert(*IsInline != PrevNS->isInline());
11504 
11505   // 'inline' must appear on the original definition, but not necessarily
11506   // on all extension definitions, so the note should point to the first
11507   // definition to avoid confusion.
11508   PrevNS = PrevNS->getFirstDecl();
11509 
11510   if (PrevNS->isInline())
11511     // The user probably just forgot the 'inline', so suggest that it
11512     // be added back.
11513     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
11514       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
11515   else
11516     S.Diag(Loc, diag::err_inline_namespace_mismatch);
11517 
11518   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
11519   *IsInline = PrevNS->isInline();
11520 }
11521 
11522 /// ActOnStartNamespaceDef - This is called at the start of a namespace
11523 /// definition.
11524 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
11525                                    SourceLocation InlineLoc,
11526                                    SourceLocation NamespaceLoc,
11527                                    SourceLocation IdentLoc, IdentifierInfo *II,
11528                                    SourceLocation LBrace,
11529                                    const ParsedAttributesView &AttrList,
11530                                    UsingDirectiveDecl *&UD, bool IsNested) {
11531   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
11532   // For anonymous namespace, take the location of the left brace.
11533   SourceLocation Loc = II ? IdentLoc : LBrace;
11534   bool IsInline = InlineLoc.isValid();
11535   bool IsInvalid = false;
11536   bool IsStd = false;
11537   bool AddToKnown = false;
11538   Scope *DeclRegionScope = NamespcScope->getParent();
11539 
11540   NamespaceDecl *PrevNS = nullptr;
11541   if (II) {
11542     // C++ [namespace.std]p7:
11543     //   A translation unit shall not declare namespace std to be an inline
11544     //   namespace (9.8.2).
11545     //
11546     // Precondition: the std namespace is in the file scope and is declared to
11547     // be inline
11548     auto DiagnoseInlineStdNS = [&]() {
11549       assert(IsInline && II->isStr("std") &&
11550              CurContext->getRedeclContext()->isTranslationUnit() &&
11551              "Precondition of DiagnoseInlineStdNS not met");
11552       Diag(InlineLoc, diag::err_inline_namespace_std)
11553           << SourceRange(InlineLoc, InlineLoc.getLocWithOffset(6));
11554       IsInline = false;
11555     };
11556     // C++ [namespace.def]p2:
11557     //   The identifier in an original-namespace-definition shall not
11558     //   have been previously defined in the declarative region in
11559     //   which the original-namespace-definition appears. The
11560     //   identifier in an original-namespace-definition is the name of
11561     //   the namespace. Subsequently in that declarative region, it is
11562     //   treated as an original-namespace-name.
11563     //
11564     // Since namespace names are unique in their scope, and we don't
11565     // look through using directives, just look for any ordinary names
11566     // as if by qualified name lookup.
11567     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
11568                    RedeclarationKind::ForExternalRedeclaration);
11569     LookupQualifiedName(R, CurContext->getRedeclContext());
11570     NamedDecl *PrevDecl =
11571         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
11572     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
11573 
11574     if (PrevNS) {
11575       // This is an extended namespace definition.
11576       if (IsInline && II->isStr("std") &&
11577           CurContext->getRedeclContext()->isTranslationUnit())
11578         DiagnoseInlineStdNS();
11579       else if (IsInline != PrevNS->isInline())
11580         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
11581                                         &IsInline, PrevNS);
11582     } else if (PrevDecl) {
11583       // This is an invalid name redefinition.
11584       Diag(Loc, diag::err_redefinition_different_kind)
11585         << II;
11586       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11587       IsInvalid = true;
11588       // Continue on to push Namespc as current DeclContext and return it.
11589     } else if (II->isStr("std") &&
11590                CurContext->getRedeclContext()->isTranslationUnit()) {
11591       if (IsInline)
11592         DiagnoseInlineStdNS();
11593       // This is the first "real" definition of the namespace "std", so update
11594       // our cache of the "std" namespace to point at this definition.
11595       PrevNS = getStdNamespace();
11596       IsStd = true;
11597       AddToKnown = !IsInline;
11598     } else {
11599       // We've seen this namespace for the first time.
11600       AddToKnown = !IsInline;
11601     }
11602   } else {
11603     // Anonymous namespaces.
11604 
11605     // Determine whether the parent already has an anonymous namespace.
11606     DeclContext *Parent = CurContext->getRedeclContext();
11607     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11608       PrevNS = TU->getAnonymousNamespace();
11609     } else {
11610       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
11611       PrevNS = ND->getAnonymousNamespace();
11612     }
11613 
11614     if (PrevNS && IsInline != PrevNS->isInline())
11615       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
11616                                       &IsInline, PrevNS);
11617   }
11618 
11619   NamespaceDecl *Namespc = NamespaceDecl::Create(
11620       Context, CurContext, IsInline, StartLoc, Loc, II, PrevNS, IsNested);
11621   if (IsInvalid)
11622     Namespc->setInvalidDecl();
11623 
11624   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
11625   AddPragmaAttributes(DeclRegionScope, Namespc);
11626   ProcessAPINotes(Namespc);
11627 
11628   // FIXME: Should we be merging attributes?
11629   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
11630     PushNamespaceVisibilityAttr(Attr, Loc);
11631 
11632   if (IsStd)
11633     StdNamespace = Namespc;
11634   if (AddToKnown)
11635     KnownNamespaces[Namespc] = false;
11636 
11637   if (II) {
11638     PushOnScopeChains(Namespc, DeclRegionScope);
11639   } else {
11640     // Link the anonymous namespace into its parent.
11641     DeclContext *Parent = CurContext->getRedeclContext();
11642     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11643       TU->setAnonymousNamespace(Namespc);
11644     } else {
11645       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
11646     }
11647 
11648     CurContext->addDecl(Namespc);
11649 
11650     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
11651     //   behaves as if it were replaced by
11652     //     namespace unique { /* empty body */ }
11653     //     using namespace unique;
11654     //     namespace unique { namespace-body }
11655     //   where all occurrences of 'unique' in a translation unit are
11656     //   replaced by the same identifier and this identifier differs
11657     //   from all other identifiers in the entire program.
11658 
11659     // We just create the namespace with an empty name and then add an
11660     // implicit using declaration, just like the standard suggests.
11661     //
11662     // CodeGen enforces the "universally unique" aspect by giving all
11663     // declarations semantically contained within an anonymous
11664     // namespace internal linkage.
11665 
11666     if (!PrevNS) {
11667       UD = UsingDirectiveDecl::Create(Context, Parent,
11668                                       /* 'using' */ LBrace,
11669                                       /* 'namespace' */ SourceLocation(),
11670                                       /* qualifier */ NestedNameSpecifierLoc(),
11671                                       /* identifier */ SourceLocation(),
11672                                       Namespc,
11673                                       /* Ancestor */ Parent);
11674       UD->setImplicit();
11675       Parent->addDecl(UD);
11676     }
11677   }
11678 
11679   ActOnDocumentableDecl(Namespc);
11680 
11681   // Although we could have an invalid decl (i.e. the namespace name is a
11682   // redefinition), push it as current DeclContext and try to continue parsing.
11683   // FIXME: We should be able to push Namespc here, so that the each DeclContext
11684   // for the namespace has the declarations that showed up in that particular
11685   // namespace definition.
11686   PushDeclContext(NamespcScope, Namespc);
11687   return Namespc;
11688 }
11689 
11690 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
11691 /// is a namespace alias, returns the namespace it points to.
11692 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
11693   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
11694     return AD->getNamespace();
11695   return dyn_cast_or_null<NamespaceDecl>(D);
11696 }
11697 
11698 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
11699   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
11700   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
11701   Namespc->setRBraceLoc(RBrace);
11702   PopDeclContext();
11703   if (Namespc->hasAttr<VisibilityAttr>())
11704     PopPragmaVisibility(true, RBrace);
11705   // If this namespace contains an export-declaration, export it now.
11706   if (DeferredExportedNamespaces.erase(Namespc))
11707     Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
11708 }
11709 
11710 CXXRecordDecl *Sema::getStdBadAlloc() const {
11711   return cast_or_null<CXXRecordDecl>(
11712                                   StdBadAlloc.get(Context.getExternalSource()));
11713 }
11714 
11715 EnumDecl *Sema::getStdAlignValT() const {
11716   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
11717 }
11718 
11719 NamespaceDecl *Sema::getStdNamespace() const {
11720   return cast_or_null<NamespaceDecl>(
11721                                  StdNamespace.get(Context.getExternalSource()));
11722 }
11723 namespace {
11724 
11725 enum UnsupportedSTLSelect {
11726   USS_InvalidMember,
11727   USS_MissingMember,
11728   USS_NonTrivial,
11729   USS_Other
11730 };
11731 
11732 struct InvalidSTLDiagnoser {
11733   Sema &S;
11734   SourceLocation Loc;
11735   QualType TyForDiags;
11736 
11737   QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
11738                       const VarDecl *VD = nullptr) {
11739     {
11740       auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
11741                << TyForDiags << ((int)Sel);
11742       if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
11743         assert(!Name.empty());
11744         D << Name;
11745       }
11746     }
11747     if (Sel == USS_InvalidMember) {
11748       S.Diag(VD->getLocation(), diag::note_var_declared_here)
11749           << VD << VD->getSourceRange();
11750     }
11751     return QualType();
11752   }
11753 };
11754 } // namespace
11755 
11756 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
11757                                            SourceLocation Loc,
11758                                            ComparisonCategoryUsage Usage) {
11759   assert(getLangOpts().CPlusPlus &&
11760          "Looking for comparison category type outside of C++.");
11761 
11762   // Use an elaborated type for diagnostics which has a name containing the
11763   // prepended 'std' namespace but not any inline namespace names.
11764   auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
11765     auto *NNS =
11766         NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
11767     return Context.getElaboratedType(ElaboratedTypeKeyword::None, NNS,
11768                                      Info->getType());
11769   };
11770 
11771   // Check if we've already successfully checked the comparison category type
11772   // before. If so, skip checking it again.
11773   ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
11774   if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
11775     // The only thing we need to check is that the type has a reachable
11776     // definition in the current context.
11777     if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11778       return QualType();
11779 
11780     return Info->getType();
11781   }
11782 
11783   // If lookup failed
11784   if (!Info) {
11785     std::string NameForDiags = "std::";
11786     NameForDiags += ComparisonCategories::getCategoryString(Kind);
11787     Diag(Loc, diag::err_implied_comparison_category_type_not_found)
11788         << NameForDiags << (int)Usage;
11789     return QualType();
11790   }
11791 
11792   assert(Info->Kind == Kind);
11793   assert(Info->Record);
11794 
11795   // Update the Record decl in case we encountered a forward declaration on our
11796   // first pass. FIXME: This is a bit of a hack.
11797   if (Info->Record->hasDefinition())
11798     Info->Record = Info->Record->getDefinition();
11799 
11800   if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11801     return QualType();
11802 
11803   InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
11804 
11805   if (!Info->Record->isTriviallyCopyable())
11806     return UnsupportedSTLError(USS_NonTrivial);
11807 
11808   for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
11809     CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
11810     // Tolerate empty base classes.
11811     if (Base->isEmpty())
11812       continue;
11813     // Reject STL implementations which have at least one non-empty base.
11814     return UnsupportedSTLError();
11815   }
11816 
11817   // Check that the STL has implemented the types using a single integer field.
11818   // This expectation allows better codegen for builtin operators. We require:
11819   //   (1) The class has exactly one field.
11820   //   (2) The field is an integral or enumeration type.
11821   auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
11822   if (std::distance(FIt, FEnd) != 1 ||
11823       !FIt->getType()->isIntegralOrEnumerationType()) {
11824     return UnsupportedSTLError();
11825   }
11826 
11827   // Build each of the require values and store them in Info.
11828   for (ComparisonCategoryResult CCR :
11829        ComparisonCategories::getPossibleResultsForType(Kind)) {
11830     StringRef MemName = ComparisonCategories::getResultString(CCR);
11831     ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
11832 
11833     if (!ValInfo)
11834       return UnsupportedSTLError(USS_MissingMember, MemName);
11835 
11836     VarDecl *VD = ValInfo->VD;
11837     assert(VD && "should not be null!");
11838 
11839     // Attempt to diagnose reasons why the STL definition of this type
11840     // might be foobar, including it failing to be a constant expression.
11841     // TODO Handle more ways the lookup or result can be invalid.
11842     if (!VD->isStaticDataMember() ||
11843         !VD->isUsableInConstantExpressions(Context))
11844       return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
11845 
11846     // Attempt to evaluate the var decl as a constant expression and extract
11847     // the value of its first field as a ICE. If this fails, the STL
11848     // implementation is not supported.
11849     if (!ValInfo->hasValidIntValue())
11850       return UnsupportedSTLError();
11851 
11852     MarkVariableReferenced(Loc, VD);
11853   }
11854 
11855   // We've successfully built the required types and expressions. Update
11856   // the cache and return the newly cached value.
11857   FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
11858   return Info->getType();
11859 }
11860 
11861 NamespaceDecl *Sema::getOrCreateStdNamespace() {
11862   if (!StdNamespace) {
11863     // The "std" namespace has not yet been defined, so build one implicitly.
11864     StdNamespace = NamespaceDecl::Create(
11865         Context, Context.getTranslationUnitDecl(),
11866         /*Inline=*/false, SourceLocation(), SourceLocation(),
11867         &PP.getIdentifierTable().get("std"),
11868         /*PrevDecl=*/nullptr, /*Nested=*/false);
11869     getStdNamespace()->setImplicit(true);
11870     // We want the created NamespaceDecl to be available for redeclaration
11871     // lookups, but not for regular name lookups.
11872     Context.getTranslationUnitDecl()->addDecl(getStdNamespace());
11873     getStdNamespace()->clearIdentifierNamespace();
11874   }
11875 
11876   return getStdNamespace();
11877 }
11878 
11879 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
11880   assert(getLangOpts().CPlusPlus &&
11881          "Looking for std::initializer_list outside of C++.");
11882 
11883   // We're looking for implicit instantiations of
11884   // template <typename E> class std::initializer_list.
11885 
11886   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
11887     return false;
11888 
11889   ClassTemplateDecl *Template = nullptr;
11890   const TemplateArgument *Arguments = nullptr;
11891 
11892   if (const RecordType *RT = Ty->getAs<RecordType>()) {
11893 
11894     ClassTemplateSpecializationDecl *Specialization =
11895         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
11896     if (!Specialization)
11897       return false;
11898 
11899     Template = Specialization->getSpecializedTemplate();
11900     Arguments = Specialization->getTemplateArgs().data();
11901   } else {
11902     const TemplateSpecializationType *TST = nullptr;
11903     if (auto *ICN = Ty->getAs<InjectedClassNameType>())
11904       TST = ICN->getInjectedTST();
11905     else
11906       TST = Ty->getAs<TemplateSpecializationType>();
11907     if (TST) {
11908       Template = dyn_cast_or_null<ClassTemplateDecl>(
11909           TST->getTemplateName().getAsTemplateDecl());
11910       Arguments = TST->template_arguments().begin();
11911     }
11912   }
11913   if (!Template)
11914     return false;
11915 
11916   if (!StdInitializerList) {
11917     // Haven't recognized std::initializer_list yet, maybe this is it.
11918     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
11919     if (TemplateClass->getIdentifier() !=
11920             &PP.getIdentifierTable().get("initializer_list") ||
11921         !getStdNamespace()->InEnclosingNamespaceSetOf(
11922             TemplateClass->getDeclContext()))
11923       return false;
11924     // This is a template called std::initializer_list, but is it the right
11925     // template?
11926     TemplateParameterList *Params = Template->getTemplateParameters();
11927     if (Params->getMinRequiredArguments() != 1)
11928       return false;
11929     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
11930       return false;
11931 
11932     // It's the right template.
11933     StdInitializerList = Template;
11934   }
11935 
11936   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
11937     return false;
11938 
11939   // This is an instance of std::initializer_list. Find the argument type.
11940   if (Element)
11941     *Element = Arguments[0].getAsType();
11942   return true;
11943 }
11944 
11945 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
11946   NamespaceDecl *Std = S.getStdNamespace();
11947   if (!Std) {
11948     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11949     return nullptr;
11950   }
11951 
11952   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
11953                       Loc, Sema::LookupOrdinaryName);
11954   if (!S.LookupQualifiedName(Result, Std)) {
11955     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11956     return nullptr;
11957   }
11958   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
11959   if (!Template) {
11960     Result.suppressDiagnostics();
11961     // We found something weird. Complain about the first thing we found.
11962     NamedDecl *Found = *Result.begin();
11963     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
11964     return nullptr;
11965   }
11966 
11967   // We found some template called std::initializer_list. Now verify that it's
11968   // correct.
11969   TemplateParameterList *Params = Template->getTemplateParameters();
11970   if (Params->getMinRequiredArguments() != 1 ||
11971       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
11972     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
11973     return nullptr;
11974   }
11975 
11976   return Template;
11977 }
11978 
11979 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
11980   if (!StdInitializerList) {
11981     StdInitializerList = LookupStdInitializerList(*this, Loc);
11982     if (!StdInitializerList)
11983       return QualType();
11984   }
11985 
11986   TemplateArgumentListInfo Args(Loc, Loc);
11987   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
11988                                        Context.getTrivialTypeSourceInfo(Element,
11989                                                                         Loc)));
11990   return Context.getElaboratedType(
11991       ElaboratedTypeKeyword::None,
11992       NestedNameSpecifier::Create(Context, nullptr, getStdNamespace()),
11993       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
11994 }
11995 
11996 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
11997   // C++ [dcl.init.list]p2:
11998   //   A constructor is an initializer-list constructor if its first parameter
11999   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
12000   //   std::initializer_list<E> for some type E, and either there are no other
12001   //   parameters or else all other parameters have default arguments.
12002   if (!Ctor->hasOneParamOrDefaultArgs())
12003     return false;
12004 
12005   QualType ArgType = Ctor->getParamDecl(0)->getType();
12006   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
12007     ArgType = RT->getPointeeType().getUnqualifiedType();
12008 
12009   return isStdInitializerList(ArgType, nullptr);
12010 }
12011 
12012 /// Determine whether a using statement is in a context where it will be
12013 /// apply in all contexts.
12014 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
12015   switch (CurContext->getDeclKind()) {
12016     case Decl::TranslationUnit:
12017       return true;
12018     case Decl::LinkageSpec:
12019       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
12020     default:
12021       return false;
12022   }
12023 }
12024 
12025 namespace {
12026 
12027 // Callback to only accept typo corrections that are namespaces.
12028 class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
12029 public:
12030   bool ValidateCandidate(const TypoCorrection &candidate) override {
12031     if (NamedDecl *ND = candidate.getCorrectionDecl())
12032       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
12033     return false;
12034   }
12035 
12036   std::unique_ptr<CorrectionCandidateCallback> clone() override {
12037     return std::make_unique<NamespaceValidatorCCC>(*this);
12038   }
12039 };
12040 
12041 }
12042 
12043 static void DiagnoseInvisibleNamespace(const TypoCorrection &Corrected,
12044                                        Sema &S) {
12045   auto *ND = cast<NamespaceDecl>(Corrected.getFoundDecl());
12046   Module *M = ND->getOwningModule();
12047   assert(M && "hidden namespace definition not in a module?");
12048 
12049   if (M->isExplicitGlobalModule())
12050     S.Diag(Corrected.getCorrectionRange().getBegin(),
12051            diag::err_module_unimported_use_header)
12052         << (int)Sema::MissingImportKind::Declaration << Corrected.getFoundDecl()
12053         << /*Header Name*/ false;
12054   else
12055     S.Diag(Corrected.getCorrectionRange().getBegin(),
12056            diag::err_module_unimported_use)
12057         << (int)Sema::MissingImportKind::Declaration << Corrected.getFoundDecl()
12058         << M->getTopLevelModuleName();
12059 }
12060 
12061 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
12062                                        CXXScopeSpec &SS,
12063                                        SourceLocation IdentLoc,
12064                                        IdentifierInfo *Ident) {
12065   R.clear();
12066   NamespaceValidatorCCC CCC{};
12067   if (TypoCorrection Corrected =
12068           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
12069                         Sema::CTK_ErrorRecovery)) {
12070     // Generally we find it is confusing more than helpful to diagnose the
12071     // invisible namespace.
12072     // See https://github.com/llvm/llvm-project/issues/73893.
12073     //
12074     // However, we should diagnose when the users are trying to using an
12075     // invisible namespace. So we handle the case specially here.
12076     if (isa_and_nonnull<NamespaceDecl>(Corrected.getFoundDecl()) &&
12077         Corrected.requiresImport()) {
12078       DiagnoseInvisibleNamespace(Corrected, S);
12079     } else if (DeclContext *DC = S.computeDeclContext(SS, false)) {
12080       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
12081       bool DroppedSpecifier =
12082           Corrected.WillReplaceSpecifier() && Ident->getName() == CorrectedStr;
12083       S.diagnoseTypo(Corrected,
12084                      S.PDiag(diag::err_using_directive_member_suggest)
12085                        << Ident << DC << DroppedSpecifier << SS.getRange(),
12086                      S.PDiag(diag::note_namespace_defined_here));
12087     } else {
12088       S.diagnoseTypo(Corrected,
12089                      S.PDiag(diag::err_using_directive_suggest) << Ident,
12090                      S.PDiag(diag::note_namespace_defined_here));
12091     }
12092     R.addDecl(Corrected.getFoundDecl());
12093     return true;
12094   }
12095   return false;
12096 }
12097 
12098 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
12099                                 SourceLocation NamespcLoc, CXXScopeSpec &SS,
12100                                 SourceLocation IdentLoc,
12101                                 IdentifierInfo *NamespcName,
12102                                 const ParsedAttributesView &AttrList) {
12103   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12104   assert(NamespcName && "Invalid NamespcName.");
12105   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
12106 
12107   // Get the innermost enclosing declaration scope.
12108   S = S->getDeclParent();
12109 
12110   UsingDirectiveDecl *UDir = nullptr;
12111   NestedNameSpecifier *Qualifier = nullptr;
12112   if (SS.isSet())
12113     Qualifier = SS.getScopeRep();
12114 
12115   // Lookup namespace name.
12116   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
12117   LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
12118   if (R.isAmbiguous())
12119     return nullptr;
12120 
12121   if (R.empty()) {
12122     R.clear();
12123     // Allow "using namespace std;" or "using namespace ::std;" even if
12124     // "std" hasn't been defined yet, for GCC compatibility.
12125     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
12126         NamespcName->isStr("std")) {
12127       Diag(IdentLoc, diag::ext_using_undefined_std);
12128       R.addDecl(getOrCreateStdNamespace());
12129       R.resolveKind();
12130     }
12131     // Otherwise, attempt typo correction.
12132     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
12133   }
12134 
12135   if (!R.empty()) {
12136     NamedDecl *Named = R.getRepresentativeDecl();
12137     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
12138     assert(NS && "expected namespace decl");
12139 
12140     // The use of a nested name specifier may trigger deprecation warnings.
12141     DiagnoseUseOfDecl(Named, IdentLoc);
12142 
12143     // C++ [namespace.udir]p1:
12144     //   A using-directive specifies that the names in the nominated
12145     //   namespace can be used in the scope in which the
12146     //   using-directive appears after the using-directive. During
12147     //   unqualified name lookup (3.4.1), the names appear as if they
12148     //   were declared in the nearest enclosing namespace which
12149     //   contains both the using-directive and the nominated
12150     //   namespace. [Note: in this context, "contains" means "contains
12151     //   directly or indirectly". ]
12152 
12153     // Find enclosing context containing both using-directive and
12154     // nominated namespace.
12155     DeclContext *CommonAncestor = NS;
12156     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
12157       CommonAncestor = CommonAncestor->getParent();
12158 
12159     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
12160                                       SS.getWithLocInContext(Context),
12161                                       IdentLoc, Named, CommonAncestor);
12162 
12163     if (IsUsingDirectiveInToplevelContext(CurContext) &&
12164         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
12165       Diag(IdentLoc, diag::warn_using_directive_in_header);
12166     }
12167 
12168     PushUsingDirective(S, UDir);
12169   } else {
12170     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
12171   }
12172 
12173   if (UDir) {
12174     ProcessDeclAttributeList(S, UDir, AttrList);
12175     ProcessAPINotes(UDir);
12176   }
12177 
12178   return UDir;
12179 }
12180 
12181 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
12182   // If the scope has an associated entity and the using directive is at
12183   // namespace or translation unit scope, add the UsingDirectiveDecl into
12184   // its lookup structure so qualified name lookup can find it.
12185   DeclContext *Ctx = S->getEntity();
12186   if (Ctx && !Ctx->isFunctionOrMethod())
12187     Ctx->addDecl(UDir);
12188   else
12189     // Otherwise, it is at block scope. The using-directives will affect lookup
12190     // only to the end of the scope.
12191     S->PushUsingDirective(UDir);
12192 }
12193 
12194 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
12195                                   SourceLocation UsingLoc,
12196                                   SourceLocation TypenameLoc, CXXScopeSpec &SS,
12197                                   UnqualifiedId &Name,
12198                                   SourceLocation EllipsisLoc,
12199                                   const ParsedAttributesView &AttrList) {
12200   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
12201 
12202   if (SS.isEmpty()) {
12203     Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
12204     return nullptr;
12205   }
12206 
12207   switch (Name.getKind()) {
12208   case UnqualifiedIdKind::IK_ImplicitSelfParam:
12209   case UnqualifiedIdKind::IK_Identifier:
12210   case UnqualifiedIdKind::IK_OperatorFunctionId:
12211   case UnqualifiedIdKind::IK_LiteralOperatorId:
12212   case UnqualifiedIdKind::IK_ConversionFunctionId:
12213     break;
12214 
12215   case UnqualifiedIdKind::IK_ConstructorName:
12216   case UnqualifiedIdKind::IK_ConstructorTemplateId:
12217     // C++11 inheriting constructors.
12218     Diag(Name.getBeginLoc(),
12219          getLangOpts().CPlusPlus11
12220              ? diag::warn_cxx98_compat_using_decl_constructor
12221              : diag::err_using_decl_constructor)
12222         << SS.getRange();
12223 
12224     if (getLangOpts().CPlusPlus11) break;
12225 
12226     return nullptr;
12227 
12228   case UnqualifiedIdKind::IK_DestructorName:
12229     Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
12230     return nullptr;
12231 
12232   case UnqualifiedIdKind::IK_TemplateId:
12233     Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
12234         << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
12235     return nullptr;
12236 
12237   case UnqualifiedIdKind::IK_DeductionGuideName:
12238     llvm_unreachable("cannot parse qualified deduction guide name");
12239   }
12240 
12241   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
12242   DeclarationName TargetName = TargetNameInfo.getName();
12243   if (!TargetName)
12244     return nullptr;
12245 
12246   // Warn about access declarations.
12247   if (UsingLoc.isInvalid()) {
12248     Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
12249                                  ? diag::err_access_decl
12250                                  : diag::warn_access_decl_deprecated)
12251         << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
12252   }
12253 
12254   if (EllipsisLoc.isInvalid()) {
12255     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
12256         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
12257       return nullptr;
12258   } else {
12259     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
12260         !TargetNameInfo.containsUnexpandedParameterPack()) {
12261       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
12262         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
12263       EllipsisLoc = SourceLocation();
12264     }
12265   }
12266 
12267   NamedDecl *UD =
12268       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
12269                             SS, TargetNameInfo, EllipsisLoc, AttrList,
12270                             /*IsInstantiation*/ false,
12271                             AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists));
12272   if (UD)
12273     PushOnScopeChains(UD, S, /*AddToContext*/ false);
12274 
12275   return UD;
12276 }
12277 
12278 Decl *Sema::ActOnUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
12279                                       SourceLocation UsingLoc,
12280                                       SourceLocation EnumLoc, SourceRange TyLoc,
12281                                       const IdentifierInfo &II, ParsedType Ty,
12282                                       CXXScopeSpec *SS) {
12283   assert(!SS->isInvalid() && "ScopeSpec is invalid");
12284   TypeSourceInfo *TSI = nullptr;
12285   SourceLocation IdentLoc = TyLoc.getBegin();
12286   QualType EnumTy = GetTypeFromParser(Ty, &TSI);
12287   if (EnumTy.isNull()) {
12288     Diag(IdentLoc, SS && isDependentScopeSpecifier(*SS)
12289                        ? diag::err_using_enum_is_dependent
12290                        : diag::err_unknown_typename)
12291         << II.getName()
12292         << SourceRange(SS ? SS->getBeginLoc() : IdentLoc, TyLoc.getEnd());
12293     return nullptr;
12294   }
12295 
12296   if (EnumTy->isDependentType()) {
12297     Diag(IdentLoc, diag::err_using_enum_is_dependent);
12298     return nullptr;
12299   }
12300 
12301   auto *Enum = dyn_cast_if_present<EnumDecl>(EnumTy->getAsTagDecl());
12302   if (!Enum) {
12303     Diag(IdentLoc, diag::err_using_enum_not_enum) << EnumTy;
12304     return nullptr;
12305   }
12306 
12307   if (auto *Def = Enum->getDefinition())
12308     Enum = Def;
12309 
12310   if (TSI == nullptr)
12311     TSI = Context.getTrivialTypeSourceInfo(EnumTy, IdentLoc);
12312 
12313   auto *UD =
12314       BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, IdentLoc, TSI, Enum);
12315 
12316   if (UD)
12317     PushOnScopeChains(UD, S, /*AddToContext*/ false);
12318 
12319   return UD;
12320 }
12321 
12322 /// Determine whether a using declaration considers the given
12323 /// declarations as "equivalent", e.g., if they are redeclarations of
12324 /// the same entity or are both typedefs of the same type.
12325 static bool
12326 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
12327   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
12328     return true;
12329 
12330   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
12331     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
12332       return Context.hasSameType(TD1->getUnderlyingType(),
12333                                  TD2->getUnderlyingType());
12334 
12335   // Two using_if_exists using-declarations are equivalent if both are
12336   // unresolved.
12337   if (isa<UnresolvedUsingIfExistsDecl>(D1) &&
12338       isa<UnresolvedUsingIfExistsDecl>(D2))
12339     return true;
12340 
12341   return false;
12342 }
12343 
12344 bool Sema::CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Orig,
12345                                 const LookupResult &Previous,
12346                                 UsingShadowDecl *&PrevShadow) {
12347   // Diagnose finding a decl which is not from a base class of the
12348   // current class.  We do this now because there are cases where this
12349   // function will silently decide not to build a shadow decl, which
12350   // will pre-empt further diagnostics.
12351   //
12352   // We don't need to do this in C++11 because we do the check once on
12353   // the qualifier.
12354   //
12355   // FIXME: diagnose the following if we care enough:
12356   //   struct A { int foo; };
12357   //   struct B : A { using A::foo; };
12358   //   template <class T> struct C : A {};
12359   //   template <class T> struct D : C<T> { using B::foo; } // <---
12360   // This is invalid (during instantiation) in C++03 because B::foo
12361   // resolves to the using decl in B, which is not a base class of D<T>.
12362   // We can't diagnose it immediately because C<T> is an unknown
12363   // specialization. The UsingShadowDecl in D<T> then points directly
12364   // to A::foo, which will look well-formed when we instantiate.
12365   // The right solution is to not collapse the shadow-decl chain.
12366   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord())
12367     if (auto *Using = dyn_cast<UsingDecl>(BUD)) {
12368       DeclContext *OrigDC = Orig->getDeclContext();
12369 
12370       // Handle enums and anonymous structs.
12371       if (isa<EnumDecl>(OrigDC))
12372         OrigDC = OrigDC->getParent();
12373       CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
12374       while (OrigRec->isAnonymousStructOrUnion())
12375         OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
12376 
12377       if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
12378         if (OrigDC == CurContext) {
12379           Diag(Using->getLocation(),
12380                diag::err_using_decl_nested_name_specifier_is_current_class)
12381               << Using->getQualifierLoc().getSourceRange();
12382           Diag(Orig->getLocation(), diag::note_using_decl_target);
12383           Using->setInvalidDecl();
12384           return true;
12385         }
12386 
12387         Diag(Using->getQualifierLoc().getBeginLoc(),
12388              diag::err_using_decl_nested_name_specifier_is_not_base_class)
12389             << Using->getQualifier() << cast<CXXRecordDecl>(CurContext)
12390             << Using->getQualifierLoc().getSourceRange();
12391         Diag(Orig->getLocation(), diag::note_using_decl_target);
12392         Using->setInvalidDecl();
12393         return true;
12394       }
12395     }
12396 
12397   if (Previous.empty()) return false;
12398 
12399   NamedDecl *Target = Orig;
12400   if (isa<UsingShadowDecl>(Target))
12401     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12402 
12403   // If the target happens to be one of the previous declarations, we
12404   // don't have a conflict.
12405   //
12406   // FIXME: but we might be increasing its access, in which case we
12407   // should redeclare it.
12408   NamedDecl *NonTag = nullptr, *Tag = nullptr;
12409   bool FoundEquivalentDecl = false;
12410   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
12411          I != E; ++I) {
12412     NamedDecl *D = (*I)->getUnderlyingDecl();
12413     // We can have UsingDecls in our Previous results because we use the same
12414     // LookupResult for checking whether the UsingDecl itself is a valid
12415     // redeclaration.
12416     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D) || isa<UsingEnumDecl>(D))
12417       continue;
12418 
12419     if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
12420       // C++ [class.mem]p19:
12421       //   If T is the name of a class, then [every named member other than
12422       //   a non-static data member] shall have a name different from T
12423       if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
12424           !isa<IndirectFieldDecl>(Target) &&
12425           !isa<UnresolvedUsingValueDecl>(Target) &&
12426           DiagnoseClassNameShadow(
12427               CurContext,
12428               DeclarationNameInfo(BUD->getDeclName(), BUD->getLocation())))
12429         return true;
12430     }
12431 
12432     if (IsEquivalentForUsingDecl(Context, D, Target)) {
12433       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
12434         PrevShadow = Shadow;
12435       FoundEquivalentDecl = true;
12436     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
12437       // We don't conflict with an existing using shadow decl of an equivalent
12438       // declaration, but we're not a redeclaration of it.
12439       FoundEquivalentDecl = true;
12440     }
12441 
12442     if (isVisible(D))
12443       (isa<TagDecl>(D) ? Tag : NonTag) = D;
12444   }
12445 
12446   if (FoundEquivalentDecl)
12447     return false;
12448 
12449   // Always emit a diagnostic for a mismatch between an unresolved
12450   // using_if_exists and a resolved using declaration in either direction.
12451   if (isa<UnresolvedUsingIfExistsDecl>(Target) !=
12452       (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) {
12453     if (!NonTag && !Tag)
12454       return false;
12455     Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12456     Diag(Target->getLocation(), diag::note_using_decl_target);
12457     Diag((NonTag ? NonTag : Tag)->getLocation(),
12458          diag::note_using_decl_conflict);
12459     BUD->setInvalidDecl();
12460     return true;
12461   }
12462 
12463   if (FunctionDecl *FD = Target->getAsFunction()) {
12464     NamedDecl *OldDecl = nullptr;
12465     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
12466                           /*IsForUsingDecl*/ true)) {
12467     case Ovl_Overload:
12468       return false;
12469 
12470     case Ovl_NonFunction:
12471       Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12472       break;
12473 
12474     // We found a decl with the exact signature.
12475     case Ovl_Match:
12476       // If we're in a record, we want to hide the target, so we
12477       // return true (without a diagnostic) to tell the caller not to
12478       // build a shadow decl.
12479       if (CurContext->isRecord())
12480         return true;
12481 
12482       // If we're not in a record, this is an error.
12483       Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12484       break;
12485     }
12486 
12487     Diag(Target->getLocation(), diag::note_using_decl_target);
12488     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
12489     BUD->setInvalidDecl();
12490     return true;
12491   }
12492 
12493   // Target is not a function.
12494 
12495   if (isa<TagDecl>(Target)) {
12496     // No conflict between a tag and a non-tag.
12497     if (!Tag) return false;
12498 
12499     Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12500     Diag(Target->getLocation(), diag::note_using_decl_target);
12501     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
12502     BUD->setInvalidDecl();
12503     return true;
12504   }
12505 
12506   // No conflict between a tag and a non-tag.
12507   if (!NonTag) return false;
12508 
12509   Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12510   Diag(Target->getLocation(), diag::note_using_decl_target);
12511   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
12512   BUD->setInvalidDecl();
12513   return true;
12514 }
12515 
12516 /// Determine whether a direct base class is a virtual base class.
12517 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
12518   if (!Derived->getNumVBases())
12519     return false;
12520   for (auto &B : Derived->bases())
12521     if (B.getType()->getAsCXXRecordDecl() == Base)
12522       return B.isVirtual();
12523   llvm_unreachable("not a direct base class");
12524 }
12525 
12526 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
12527                                             NamedDecl *Orig,
12528                                             UsingShadowDecl *PrevDecl) {
12529   // If we resolved to another shadow declaration, just coalesce them.
12530   NamedDecl *Target = Orig;
12531   if (isa<UsingShadowDecl>(Target)) {
12532     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12533     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
12534   }
12535 
12536   NamedDecl *NonTemplateTarget = Target;
12537   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
12538     NonTemplateTarget = TargetTD->getTemplatedDecl();
12539 
12540   UsingShadowDecl *Shadow;
12541   if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
12542     UsingDecl *Using = cast<UsingDecl>(BUD);
12543     bool IsVirtualBase =
12544         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
12545                             Using->getQualifier()->getAsRecordDecl());
12546     Shadow = ConstructorUsingShadowDecl::Create(
12547         Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase);
12548   } else {
12549     Shadow = UsingShadowDecl::Create(Context, CurContext, BUD->getLocation(),
12550                                      Target->getDeclName(), BUD, Target);
12551   }
12552   BUD->addShadowDecl(Shadow);
12553 
12554   Shadow->setAccess(BUD->getAccess());
12555   if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
12556     Shadow->setInvalidDecl();
12557 
12558   Shadow->setPreviousDecl(PrevDecl);
12559 
12560   if (S)
12561     PushOnScopeChains(Shadow, S);
12562   else
12563     CurContext->addDecl(Shadow);
12564 
12565 
12566   return Shadow;
12567 }
12568 
12569 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
12570   if (Shadow->getDeclName().getNameKind() ==
12571         DeclarationName::CXXConversionFunctionName)
12572     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
12573 
12574   // Remove it from the DeclContext...
12575   Shadow->getDeclContext()->removeDecl(Shadow);
12576 
12577   // ...and the scope, if applicable...
12578   if (S) {
12579     S->RemoveDecl(Shadow);
12580     IdResolver.RemoveDecl(Shadow);
12581   }
12582 
12583   // ...and the using decl.
12584   Shadow->getIntroducer()->removeShadowDecl(Shadow);
12585 
12586   // TODO: complain somehow if Shadow was used.  It shouldn't
12587   // be possible for this to happen, because...?
12588 }
12589 
12590 /// Find the base specifier for a base class with the given type.
12591 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
12592                                                 QualType DesiredBase,
12593                                                 bool &AnyDependentBases) {
12594   // Check whether the named type is a direct base class.
12595   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
12596     .getUnqualifiedType();
12597   for (auto &Base : Derived->bases()) {
12598     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
12599     if (CanonicalDesiredBase == BaseType)
12600       return &Base;
12601     if (BaseType->isDependentType())
12602       AnyDependentBases = true;
12603   }
12604   return nullptr;
12605 }
12606 
12607 namespace {
12608 class UsingValidatorCCC final : public CorrectionCandidateCallback {
12609 public:
12610   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
12611                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
12612       : HasTypenameKeyword(HasTypenameKeyword),
12613         IsInstantiation(IsInstantiation), OldNNS(NNS),
12614         RequireMemberOf(RequireMemberOf) {}
12615 
12616   bool ValidateCandidate(const TypoCorrection &Candidate) override {
12617     NamedDecl *ND = Candidate.getCorrectionDecl();
12618 
12619     // Keywords are not valid here.
12620     if (!ND || isa<NamespaceDecl>(ND))
12621       return false;
12622 
12623     // Completely unqualified names are invalid for a 'using' declaration.
12624     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
12625       return false;
12626 
12627     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
12628     // reject.
12629 
12630     if (RequireMemberOf) {
12631       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12632       if (FoundRecord && FoundRecord->isInjectedClassName()) {
12633         // No-one ever wants a using-declaration to name an injected-class-name
12634         // of a base class, unless they're declaring an inheriting constructor.
12635         ASTContext &Ctx = ND->getASTContext();
12636         if (!Ctx.getLangOpts().CPlusPlus11)
12637           return false;
12638         QualType FoundType = Ctx.getRecordType(FoundRecord);
12639 
12640         // Check that the injected-class-name is named as a member of its own
12641         // type; we don't want to suggest 'using Derived::Base;', since that
12642         // means something else.
12643         NestedNameSpecifier *Specifier =
12644             Candidate.WillReplaceSpecifier()
12645                 ? Candidate.getCorrectionSpecifier()
12646                 : OldNNS;
12647         if (!Specifier->getAsType() ||
12648             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
12649           return false;
12650 
12651         // Check that this inheriting constructor declaration actually names a
12652         // direct base class of the current class.
12653         bool AnyDependentBases = false;
12654         if (!findDirectBaseWithType(RequireMemberOf,
12655                                     Ctx.getRecordType(FoundRecord),
12656                                     AnyDependentBases) &&
12657             !AnyDependentBases)
12658           return false;
12659       } else {
12660         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
12661         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
12662           return false;
12663 
12664         // FIXME: Check that the base class member is accessible?
12665       }
12666     } else {
12667       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12668       if (FoundRecord && FoundRecord->isInjectedClassName())
12669         return false;
12670     }
12671 
12672     if (isa<TypeDecl>(ND))
12673       return HasTypenameKeyword || !IsInstantiation;
12674 
12675     return !HasTypenameKeyword;
12676   }
12677 
12678   std::unique_ptr<CorrectionCandidateCallback> clone() override {
12679     return std::make_unique<UsingValidatorCCC>(*this);
12680   }
12681 
12682 private:
12683   bool HasTypenameKeyword;
12684   bool IsInstantiation;
12685   NestedNameSpecifier *OldNNS;
12686   CXXRecordDecl *RequireMemberOf;
12687 };
12688 } // end anonymous namespace
12689 
12690 void Sema::FilterUsingLookup(Scope *S, LookupResult &Previous) {
12691   // It is really dumb that we have to do this.
12692   LookupResult::Filter F = Previous.makeFilter();
12693   while (F.hasNext()) {
12694     NamedDecl *D = F.next();
12695     if (!isDeclInScope(D, CurContext, S))
12696       F.erase();
12697     // If we found a local extern declaration that's not ordinarily visible,
12698     // and this declaration is being added to a non-block scope, ignore it.
12699     // We're only checking for scope conflicts here, not also for violations
12700     // of the linkage rules.
12701     else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
12702              !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
12703       F.erase();
12704   }
12705   F.done();
12706 }
12707 
12708 NamedDecl *Sema::BuildUsingDeclaration(
12709     Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
12710     bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
12711     DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
12712     const ParsedAttributesView &AttrList, bool IsInstantiation,
12713     bool IsUsingIfExists) {
12714   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12715   SourceLocation IdentLoc = NameInfo.getLoc();
12716   assert(IdentLoc.isValid() && "Invalid TargetName location.");
12717 
12718   // FIXME: We ignore attributes for now.
12719 
12720   // For an inheriting constructor declaration, the name of the using
12721   // declaration is the name of a constructor in this class, not in the
12722   // base class.
12723   DeclarationNameInfo UsingName = NameInfo;
12724   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
12725     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
12726       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12727           Context.getCanonicalType(Context.getRecordType(RD))));
12728 
12729   // Do the redeclaration lookup in the current scope.
12730   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
12731                         RedeclarationKind::ForVisibleRedeclaration);
12732   Previous.setHideTags(false);
12733   if (S) {
12734     LookupName(Previous, S);
12735 
12736     FilterUsingLookup(S, Previous);
12737   } else {
12738     assert(IsInstantiation && "no scope in non-instantiation");
12739     if (CurContext->isRecord())
12740       LookupQualifiedName(Previous, CurContext);
12741     else {
12742       // No redeclaration check is needed here; in non-member contexts we
12743       // diagnosed all possible conflicts with other using-declarations when
12744       // building the template:
12745       //
12746       // For a dependent non-type using declaration, the only valid case is
12747       // if we instantiate to a single enumerator. We check for conflicts
12748       // between shadow declarations we introduce, and we check in the template
12749       // definition for conflicts between a non-type using declaration and any
12750       // other declaration, which together covers all cases.
12751       //
12752       // A dependent typename using declaration will never successfully
12753       // instantiate, since it will always name a class member, so we reject
12754       // that in the template definition.
12755     }
12756   }
12757 
12758   // Check for invalid redeclarations.
12759   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
12760                                   SS, IdentLoc, Previous))
12761     return nullptr;
12762 
12763   // 'using_if_exists' doesn't make sense on an inherited constructor.
12764   if (IsUsingIfExists && UsingName.getName().getNameKind() ==
12765                              DeclarationName::CXXConstructorName) {
12766     Diag(UsingLoc, diag::err_using_if_exists_on_ctor);
12767     return nullptr;
12768   }
12769 
12770   DeclContext *LookupContext = computeDeclContext(SS);
12771   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
12772   if (!LookupContext || EllipsisLoc.isValid()) {
12773     NamedDecl *D;
12774     // Dependent scope, or an unexpanded pack
12775     if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword,
12776                                                   SS, NameInfo, IdentLoc))
12777       return nullptr;
12778 
12779     if (HasTypenameKeyword) {
12780       // FIXME: not all declaration name kinds are legal here
12781       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
12782                                               UsingLoc, TypenameLoc,
12783                                               QualifierLoc,
12784                                               IdentLoc, NameInfo.getName(),
12785                                               EllipsisLoc);
12786     } else {
12787       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
12788                                            QualifierLoc, NameInfo, EllipsisLoc);
12789     }
12790     D->setAccess(AS);
12791     CurContext->addDecl(D);
12792     ProcessDeclAttributeList(S, D, AttrList);
12793     return D;
12794   }
12795 
12796   auto Build = [&](bool Invalid) {
12797     UsingDecl *UD =
12798         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
12799                           UsingName, HasTypenameKeyword);
12800     UD->setAccess(AS);
12801     CurContext->addDecl(UD);
12802     ProcessDeclAttributeList(S, UD, AttrList);
12803     UD->setInvalidDecl(Invalid);
12804     return UD;
12805   };
12806   auto BuildInvalid = [&]{ return Build(true); };
12807   auto BuildValid = [&]{ return Build(false); };
12808 
12809   if (RequireCompleteDeclContext(SS, LookupContext))
12810     return BuildInvalid();
12811 
12812   // Look up the target name.
12813   LookupResult R(*this, NameInfo, LookupOrdinaryName);
12814 
12815   // Unlike most lookups, we don't always want to hide tag
12816   // declarations: tag names are visible through the using declaration
12817   // even if hidden by ordinary names, *except* in a dependent context
12818   // where they may be used by two-phase lookup.
12819   if (!IsInstantiation)
12820     R.setHideTags(false);
12821 
12822   // For the purposes of this lookup, we have a base object type
12823   // equal to that of the current context.
12824   if (CurContext->isRecord()) {
12825     R.setBaseObjectType(
12826                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
12827   }
12828 
12829   LookupQualifiedName(R, LookupContext);
12830 
12831   // Validate the context, now we have a lookup
12832   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
12833                               IdentLoc, &R))
12834     return nullptr;
12835 
12836   if (R.empty() && IsUsingIfExists)
12837     R.addDecl(UnresolvedUsingIfExistsDecl::Create(Context, CurContext, UsingLoc,
12838                                                   UsingName.getName()),
12839               AS_public);
12840 
12841   // Try to correct typos if possible. If constructor name lookup finds no
12842   // results, that means the named class has no explicit constructors, and we
12843   // suppressed declaring implicit ones (probably because it's dependent or
12844   // invalid).
12845   if (R.empty() &&
12846       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
12847     // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
12848     // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
12849     // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
12850     auto *II = NameInfo.getName().getAsIdentifierInfo();
12851     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
12852         CurContext->isStdNamespace() &&
12853         isa<TranslationUnitDecl>(LookupContext) &&
12854         getSourceManager().isInSystemHeader(UsingLoc))
12855       return nullptr;
12856     UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
12857                           dyn_cast<CXXRecordDecl>(CurContext));
12858     if (TypoCorrection Corrected =
12859             CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
12860                         CTK_ErrorRecovery)) {
12861       // We reject candidates where DroppedSpecifier == true, hence the
12862       // literal '0' below.
12863       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
12864                                 << NameInfo.getName() << LookupContext << 0
12865                                 << SS.getRange());
12866 
12867       // If we picked a correction with no attached Decl we can't do anything
12868       // useful with it, bail out.
12869       NamedDecl *ND = Corrected.getCorrectionDecl();
12870       if (!ND)
12871         return BuildInvalid();
12872 
12873       // If we corrected to an inheriting constructor, handle it as one.
12874       auto *RD = dyn_cast<CXXRecordDecl>(ND);
12875       if (RD && RD->isInjectedClassName()) {
12876         // The parent of the injected class name is the class itself.
12877         RD = cast<CXXRecordDecl>(RD->getParent());
12878 
12879         // Fix up the information we'll use to build the using declaration.
12880         if (Corrected.WillReplaceSpecifier()) {
12881           NestedNameSpecifierLocBuilder Builder;
12882           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
12883                               QualifierLoc.getSourceRange());
12884           QualifierLoc = Builder.getWithLocInContext(Context);
12885         }
12886 
12887         // In this case, the name we introduce is the name of a derived class
12888         // constructor.
12889         auto *CurClass = cast<CXXRecordDecl>(CurContext);
12890         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12891             Context.getCanonicalType(Context.getRecordType(CurClass))));
12892         UsingName.setNamedTypeInfo(nullptr);
12893         for (auto *Ctor : LookupConstructors(RD))
12894           R.addDecl(Ctor);
12895         R.resolveKind();
12896       } else {
12897         // FIXME: Pick up all the declarations if we found an overloaded
12898         // function.
12899         UsingName.setName(ND->getDeclName());
12900         R.addDecl(ND);
12901       }
12902     } else {
12903       Diag(IdentLoc, diag::err_no_member)
12904         << NameInfo.getName() << LookupContext << SS.getRange();
12905       return BuildInvalid();
12906     }
12907   }
12908 
12909   if (R.isAmbiguous())
12910     return BuildInvalid();
12911 
12912   if (HasTypenameKeyword) {
12913     // If we asked for a typename and got a non-type decl, error out.
12914     if (!R.getAsSingle<TypeDecl>() &&
12915         !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) {
12916       Diag(IdentLoc, diag::err_using_typename_non_type);
12917       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12918         Diag((*I)->getUnderlyingDecl()->getLocation(),
12919              diag::note_using_decl_target);
12920       return BuildInvalid();
12921     }
12922   } else {
12923     // If we asked for a non-typename and we got a type, error out,
12924     // but only if this is an instantiation of an unresolved using
12925     // decl.  Otherwise just silently find the type name.
12926     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
12927       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
12928       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
12929       return BuildInvalid();
12930     }
12931   }
12932 
12933   // C++14 [namespace.udecl]p6:
12934   // A using-declaration shall not name a namespace.
12935   if (R.getAsSingle<NamespaceDecl>()) {
12936     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
12937         << SS.getRange();
12938     // Suggest using 'using namespace ...' instead.
12939     Diag(SS.getBeginLoc(), diag::note_namespace_using_decl)
12940         << FixItHint::CreateInsertion(SS.getBeginLoc(), "namespace ");
12941     return BuildInvalid();
12942   }
12943 
12944   UsingDecl *UD = BuildValid();
12945 
12946   // Some additional rules apply to inheriting constructors.
12947   if (UsingName.getName().getNameKind() ==
12948         DeclarationName::CXXConstructorName) {
12949     // Suppress access diagnostics; the access check is instead performed at the
12950     // point of use for an inheriting constructor.
12951     R.suppressDiagnostics();
12952     if (CheckInheritingConstructorUsingDecl(UD))
12953       return UD;
12954   }
12955 
12956   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
12957     UsingShadowDecl *PrevDecl = nullptr;
12958     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
12959       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
12960   }
12961 
12962   return UD;
12963 }
12964 
12965 NamedDecl *Sema::BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
12966                                            SourceLocation UsingLoc,
12967                                            SourceLocation EnumLoc,
12968                                            SourceLocation NameLoc,
12969                                            TypeSourceInfo *EnumType,
12970                                            EnumDecl *ED) {
12971   bool Invalid = false;
12972 
12973   if (CurContext->getRedeclContext()->isRecord()) {
12974     /// In class scope, check if this is a duplicate, for better a diagnostic.
12975     DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
12976     LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
12977                           RedeclarationKind::ForVisibleRedeclaration);
12978 
12979     LookupName(Previous, S);
12980 
12981     for (NamedDecl *D : Previous)
12982       if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D))
12983         if (UED->getEnumDecl() == ED) {
12984           Diag(UsingLoc, diag::err_using_enum_decl_redeclaration)
12985               << SourceRange(EnumLoc, NameLoc);
12986           Diag(D->getLocation(), diag::note_using_enum_decl) << 1;
12987           Invalid = true;
12988           break;
12989         }
12990   }
12991 
12992   if (RequireCompleteEnumDecl(ED, NameLoc))
12993     Invalid = true;
12994 
12995   UsingEnumDecl *UD = UsingEnumDecl::Create(Context, CurContext, UsingLoc,
12996                                             EnumLoc, NameLoc, EnumType);
12997   UD->setAccess(AS);
12998   CurContext->addDecl(UD);
12999 
13000   if (Invalid) {
13001     UD->setInvalidDecl();
13002     return UD;
13003   }
13004 
13005   // Create the shadow decls for each enumerator
13006   for (EnumConstantDecl *EC : ED->enumerators()) {
13007     UsingShadowDecl *PrevDecl = nullptr;
13008     DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
13009     LookupResult Previous(*this, DNI, LookupOrdinaryName,
13010                           RedeclarationKind::ForVisibleRedeclaration);
13011     LookupName(Previous, S);
13012     FilterUsingLookup(S, Previous);
13013 
13014     if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl))
13015       BuildUsingShadowDecl(S, UD, EC, PrevDecl);
13016   }
13017 
13018   return UD;
13019 }
13020 
13021 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
13022                                     ArrayRef<NamedDecl *> Expansions) {
13023   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
13024          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
13025          isa<UsingPackDecl>(InstantiatedFrom));
13026 
13027   auto *UPD =
13028       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
13029   UPD->setAccess(InstantiatedFrom->getAccess());
13030   CurContext->addDecl(UPD);
13031   return UPD;
13032 }
13033 
13034 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
13035   assert(!UD->hasTypename() && "expecting a constructor name");
13036 
13037   const Type *SourceType = UD->getQualifier()->getAsType();
13038   assert(SourceType &&
13039          "Using decl naming constructor doesn't have type in scope spec.");
13040   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
13041 
13042   // Check whether the named type is a direct base class.
13043   bool AnyDependentBases = false;
13044   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
13045                                       AnyDependentBases);
13046   if (!Base && !AnyDependentBases) {
13047     Diag(UD->getUsingLoc(),
13048          diag::err_using_decl_constructor_not_in_direct_base)
13049       << UD->getNameInfo().getSourceRange()
13050       << QualType(SourceType, 0) << TargetClass;
13051     UD->setInvalidDecl();
13052     return true;
13053   }
13054 
13055   if (Base)
13056     Base->setInheritConstructors();
13057 
13058   return false;
13059 }
13060 
13061 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
13062                                        bool HasTypenameKeyword,
13063                                        const CXXScopeSpec &SS,
13064                                        SourceLocation NameLoc,
13065                                        const LookupResult &Prev) {
13066   NestedNameSpecifier *Qual = SS.getScopeRep();
13067 
13068   // C++03 [namespace.udecl]p8:
13069   // C++0x [namespace.udecl]p10:
13070   //   A using-declaration is a declaration and can therefore be used
13071   //   repeatedly where (and only where) multiple declarations are
13072   //   allowed.
13073   //
13074   // That's in non-member contexts.
13075   if (!CurContext->getRedeclContext()->isRecord()) {
13076     // A dependent qualifier outside a class can only ever resolve to an
13077     // enumeration type. Therefore it conflicts with any other non-type
13078     // declaration in the same scope.
13079     // FIXME: How should we check for dependent type-type conflicts at block
13080     // scope?
13081     if (Qual->isDependent() && !HasTypenameKeyword) {
13082       for (auto *D : Prev) {
13083         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
13084           bool OldCouldBeEnumerator =
13085               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
13086           Diag(NameLoc,
13087                OldCouldBeEnumerator ? diag::err_redefinition
13088                                     : diag::err_redefinition_different_kind)
13089               << Prev.getLookupName();
13090           Diag(D->getLocation(), diag::note_previous_definition);
13091           return true;
13092         }
13093       }
13094     }
13095     return false;
13096   }
13097 
13098   const NestedNameSpecifier *CNNS =
13099       Context.getCanonicalNestedNameSpecifier(Qual);
13100   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
13101     NamedDecl *D = *I;
13102 
13103     bool DTypename;
13104     NestedNameSpecifier *DQual;
13105     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
13106       DTypename = UD->hasTypename();
13107       DQual = UD->getQualifier();
13108     } else if (UnresolvedUsingValueDecl *UD
13109                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
13110       DTypename = false;
13111       DQual = UD->getQualifier();
13112     } else if (UnresolvedUsingTypenameDecl *UD
13113                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
13114       DTypename = true;
13115       DQual = UD->getQualifier();
13116     } else continue;
13117 
13118     // using decls differ if one says 'typename' and the other doesn't.
13119     // FIXME: non-dependent using decls?
13120     if (HasTypenameKeyword != DTypename) continue;
13121 
13122     // using decls differ if they name different scopes (but note that
13123     // template instantiation can cause this check to trigger when it
13124     // didn't before instantiation).
13125     if (CNNS != Context.getCanonicalNestedNameSpecifier(DQual))
13126       continue;
13127 
13128     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
13129     Diag(D->getLocation(), diag::note_using_decl) << 1;
13130     return true;
13131   }
13132 
13133   return false;
13134 }
13135 
13136 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
13137                                    const CXXScopeSpec &SS,
13138                                    const DeclarationNameInfo &NameInfo,
13139                                    SourceLocation NameLoc,
13140                                    const LookupResult *R, const UsingDecl *UD) {
13141   DeclContext *NamedContext = computeDeclContext(SS);
13142   assert(bool(NamedContext) == (R || UD) && !(R && UD) &&
13143          "resolvable context must have exactly one set of decls");
13144 
13145   // C++ 20 permits using an enumerator that does not have a class-hierarchy
13146   // relationship.
13147   bool Cxx20Enumerator = false;
13148   if (NamedContext) {
13149     EnumConstantDecl *EC = nullptr;
13150     if (R)
13151       EC = R->getAsSingle<EnumConstantDecl>();
13152     else if (UD && UD->shadow_size() == 1)
13153       EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl());
13154     if (EC)
13155       Cxx20Enumerator = getLangOpts().CPlusPlus20;
13156 
13157     if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) {
13158       // C++14 [namespace.udecl]p7:
13159       // A using-declaration shall not name a scoped enumerator.
13160       // C++20 p1099 permits enumerators.
13161       if (EC && R && ED->isScoped())
13162         Diag(SS.getBeginLoc(),
13163              getLangOpts().CPlusPlus20
13164                  ? diag::warn_cxx17_compat_using_decl_scoped_enumerator
13165                  : diag::ext_using_decl_scoped_enumerator)
13166             << SS.getRange();
13167 
13168       // We want to consider the scope of the enumerator
13169       NamedContext = ED->getDeclContext();
13170     }
13171   }
13172 
13173   if (!CurContext->isRecord()) {
13174     // C++03 [namespace.udecl]p3:
13175     // C++0x [namespace.udecl]p8:
13176     //   A using-declaration for a class member shall be a member-declaration.
13177     // C++20 [namespace.udecl]p7
13178     //   ... other than an enumerator ...
13179 
13180     // If we weren't able to compute a valid scope, it might validly be a
13181     // dependent class or enumeration scope. If we have a 'typename' keyword,
13182     // the scope must resolve to a class type.
13183     if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
13184                      : !HasTypename)
13185       return false; // OK
13186 
13187     Diag(NameLoc,
13188          Cxx20Enumerator
13189              ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
13190              : diag::err_using_decl_can_not_refer_to_class_member)
13191         << SS.getRange();
13192 
13193     if (Cxx20Enumerator)
13194       return false; // OK
13195 
13196     auto *RD = NamedContext
13197                    ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
13198                    : nullptr;
13199     if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) {
13200       // See if there's a helpful fixit
13201 
13202       if (!R) {
13203         // We will have already diagnosed the problem on the template
13204         // definition,  Maybe we should do so again?
13205       } else if (R->getAsSingle<TypeDecl>()) {
13206         if (getLangOpts().CPlusPlus11) {
13207           // Convert 'using X::Y;' to 'using Y = X::Y;'.
13208           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
13209             << 0 // alias declaration
13210             << FixItHint::CreateInsertion(SS.getBeginLoc(),
13211                                           NameInfo.getName().getAsString() +
13212                                               " = ");
13213         } else {
13214           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
13215           SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
13216           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
13217             << 1 // typedef declaration
13218             << FixItHint::CreateReplacement(UsingLoc, "typedef")
13219             << FixItHint::CreateInsertion(
13220                    InsertLoc, " " + NameInfo.getName().getAsString());
13221         }
13222       } else if (R->getAsSingle<VarDecl>()) {
13223         // Don't provide a fixit outside C++11 mode; we don't want to suggest
13224         // repeating the type of the static data member here.
13225         FixItHint FixIt;
13226         if (getLangOpts().CPlusPlus11) {
13227           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13228           FixIt = FixItHint::CreateReplacement(
13229               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
13230         }
13231 
13232         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13233           << 2 // reference declaration
13234           << FixIt;
13235       } else if (R->getAsSingle<EnumConstantDecl>()) {
13236         // Don't provide a fixit outside C++11 mode; we don't want to suggest
13237         // repeating the type of the enumeration here, and we can't do so if
13238         // the type is anonymous.
13239         FixItHint FixIt;
13240         if (getLangOpts().CPlusPlus11) {
13241           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13242           FixIt = FixItHint::CreateReplacement(
13243               UsingLoc,
13244               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
13245         }
13246 
13247         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13248           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
13249           << FixIt;
13250       }
13251     }
13252 
13253     return true; // Fail
13254   }
13255 
13256   // If the named context is dependent, we can't decide much.
13257   if (!NamedContext) {
13258     // FIXME: in C++0x, we can diagnose if we can prove that the
13259     // nested-name-specifier does not refer to a base class, which is
13260     // still possible in some cases.
13261 
13262     // Otherwise we have to conservatively report that things might be
13263     // okay.
13264     return false;
13265   }
13266 
13267   // The current scope is a record.
13268   if (!NamedContext->isRecord()) {
13269     // Ideally this would point at the last name in the specifier,
13270     // but we don't have that level of source info.
13271     Diag(SS.getBeginLoc(),
13272          Cxx20Enumerator
13273              ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
13274              : diag::err_using_decl_nested_name_specifier_is_not_class)
13275         << SS.getScopeRep() << SS.getRange();
13276 
13277     if (Cxx20Enumerator)
13278       return false; // OK
13279 
13280     return true;
13281   }
13282 
13283   if (!NamedContext->isDependentContext() &&
13284       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
13285     return true;
13286 
13287   if (getLangOpts().CPlusPlus11) {
13288     // C++11 [namespace.udecl]p3:
13289     //   In a using-declaration used as a member-declaration, the
13290     //   nested-name-specifier shall name a base class of the class
13291     //   being defined.
13292 
13293     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
13294                                  cast<CXXRecordDecl>(NamedContext))) {
13295 
13296       if (Cxx20Enumerator) {
13297         Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator)
13298             << SS.getRange();
13299         return false;
13300       }
13301 
13302       if (CurContext == NamedContext) {
13303         Diag(SS.getBeginLoc(),
13304              diag::err_using_decl_nested_name_specifier_is_current_class)
13305             << SS.getRange();
13306         return !getLangOpts().CPlusPlus20;
13307       }
13308 
13309       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
13310         Diag(SS.getBeginLoc(),
13311              diag::err_using_decl_nested_name_specifier_is_not_base_class)
13312             << SS.getScopeRep() << cast<CXXRecordDecl>(CurContext)
13313             << SS.getRange();
13314       }
13315       return true;
13316     }
13317 
13318     return false;
13319   }
13320 
13321   // C++03 [namespace.udecl]p4:
13322   //   A using-declaration used as a member-declaration shall refer
13323   //   to a member of a base class of the class being defined [etc.].
13324 
13325   // Salient point: SS doesn't have to name a base class as long as
13326   // lookup only finds members from base classes.  Therefore we can
13327   // diagnose here only if we can prove that can't happen,
13328   // i.e. if the class hierarchies provably don't intersect.
13329 
13330   // TODO: it would be nice if "definitely valid" results were cached
13331   // in the UsingDecl and UsingShadowDecl so that these checks didn't
13332   // need to be repeated.
13333 
13334   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
13335   auto Collect = [&Bases](const CXXRecordDecl *Base) {
13336     Bases.insert(Base);
13337     return true;
13338   };
13339 
13340   // Collect all bases. Return false if we find a dependent base.
13341   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
13342     return false;
13343 
13344   // Returns true if the base is dependent or is one of the accumulated base
13345   // classes.
13346   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
13347     return !Bases.count(Base);
13348   };
13349 
13350   // Return false if the class has a dependent base or if it or one
13351   // of its bases is present in the base set of the current context.
13352   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
13353       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
13354     return false;
13355 
13356   Diag(SS.getRange().getBegin(),
13357        diag::err_using_decl_nested_name_specifier_is_not_base_class)
13358     << SS.getScopeRep()
13359     << cast<CXXRecordDecl>(CurContext)
13360     << SS.getRange();
13361 
13362   return true;
13363 }
13364 
13365 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
13366                                   MultiTemplateParamsArg TemplateParamLists,
13367                                   SourceLocation UsingLoc, UnqualifiedId &Name,
13368                                   const ParsedAttributesView &AttrList,
13369                                   TypeResult Type, Decl *DeclFromDeclSpec) {
13370   // Get the innermost enclosing declaration scope.
13371   S = S->getDeclParent();
13372 
13373   if (Type.isInvalid())
13374     return nullptr;
13375 
13376   bool Invalid = false;
13377   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
13378   TypeSourceInfo *TInfo = nullptr;
13379   GetTypeFromParser(Type.get(), &TInfo);
13380 
13381   if (DiagnoseClassNameShadow(CurContext, NameInfo))
13382     return nullptr;
13383 
13384   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
13385                                       UPPC_DeclarationType)) {
13386     Invalid = true;
13387     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13388                                              TInfo->getTypeLoc().getBeginLoc());
13389   }
13390 
13391   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
13392                         TemplateParamLists.size()
13393                             ? forRedeclarationInCurContext()
13394                             : RedeclarationKind::ForVisibleRedeclaration);
13395   LookupName(Previous, S);
13396 
13397   // Warn about shadowing the name of a template parameter.
13398   if (Previous.isSingleResult() &&
13399       Previous.getFoundDecl()->isTemplateParameter()) {
13400     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
13401     Previous.clear();
13402   }
13403 
13404   assert(Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
13405          "name in alias declaration must be an identifier");
13406   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
13407                                                Name.StartLocation,
13408                                                Name.Identifier, TInfo);
13409 
13410   NewTD->setAccess(AS);
13411 
13412   if (Invalid)
13413     NewTD->setInvalidDecl();
13414 
13415   ProcessDeclAttributeList(S, NewTD, AttrList);
13416   AddPragmaAttributes(S, NewTD);
13417   ProcessAPINotes(NewTD);
13418 
13419   CheckTypedefForVariablyModifiedType(S, NewTD);
13420   Invalid |= NewTD->isInvalidDecl();
13421 
13422   bool Redeclaration = false;
13423 
13424   NamedDecl *NewND;
13425   if (TemplateParamLists.size()) {
13426     TypeAliasTemplateDecl *OldDecl = nullptr;
13427     TemplateParameterList *OldTemplateParams = nullptr;
13428 
13429     if (TemplateParamLists.size() != 1) {
13430       Diag(UsingLoc, diag::err_alias_template_extra_headers)
13431         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
13432          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
13433       Invalid = true;
13434     }
13435     TemplateParameterList *TemplateParams = TemplateParamLists[0];
13436 
13437     // Check that we can declare a template here.
13438     if (CheckTemplateDeclScope(S, TemplateParams))
13439       return nullptr;
13440 
13441     // Only consider previous declarations in the same scope.
13442     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
13443                          /*ExplicitInstantiationOrSpecialization*/false);
13444     if (!Previous.empty()) {
13445       Redeclaration = true;
13446 
13447       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
13448       if (!OldDecl && !Invalid) {
13449         Diag(UsingLoc, diag::err_redefinition_different_kind)
13450           << Name.Identifier;
13451 
13452         NamedDecl *OldD = Previous.getRepresentativeDecl();
13453         if (OldD->getLocation().isValid())
13454           Diag(OldD->getLocation(), diag::note_previous_definition);
13455 
13456         Invalid = true;
13457       }
13458 
13459       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
13460         if (TemplateParameterListsAreEqual(TemplateParams,
13461                                            OldDecl->getTemplateParameters(),
13462                                            /*Complain=*/true,
13463                                            TPL_TemplateMatch))
13464           OldTemplateParams =
13465               OldDecl->getMostRecentDecl()->getTemplateParameters();
13466         else
13467           Invalid = true;
13468 
13469         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
13470         if (!Invalid &&
13471             !Context.hasSameType(OldTD->getUnderlyingType(),
13472                                  NewTD->getUnderlyingType())) {
13473           // FIXME: The C++0x standard does not clearly say this is ill-formed,
13474           // but we can't reasonably accept it.
13475           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
13476             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
13477           if (OldTD->getLocation().isValid())
13478             Diag(OldTD->getLocation(), diag::note_previous_definition);
13479           Invalid = true;
13480         }
13481       }
13482     }
13483 
13484     // Merge any previous default template arguments into our parameters,
13485     // and check the parameter list.
13486     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
13487                                    TPC_TypeAliasTemplate))
13488       return nullptr;
13489 
13490     TypeAliasTemplateDecl *NewDecl =
13491       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
13492                                     Name.Identifier, TemplateParams,
13493                                     NewTD);
13494     NewTD->setDescribedAliasTemplate(NewDecl);
13495 
13496     NewDecl->setAccess(AS);
13497 
13498     if (Invalid)
13499       NewDecl->setInvalidDecl();
13500     else if (OldDecl) {
13501       NewDecl->setPreviousDecl(OldDecl);
13502       CheckRedeclarationInModule(NewDecl, OldDecl);
13503     }
13504 
13505     NewND = NewDecl;
13506   } else {
13507     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
13508       setTagNameForLinkagePurposes(TD, NewTD);
13509       handleTagNumbering(TD, S);
13510     }
13511     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
13512     NewND = NewTD;
13513   }
13514 
13515   PushOnScopeChains(NewND, S);
13516   ActOnDocumentableDecl(NewND);
13517   return NewND;
13518 }
13519 
13520 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
13521                                    SourceLocation AliasLoc,
13522                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
13523                                    SourceLocation IdentLoc,
13524                                    IdentifierInfo *Ident) {
13525 
13526   // Lookup the namespace name.
13527   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
13528   LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
13529 
13530   if (R.isAmbiguous())
13531     return nullptr;
13532 
13533   if (R.empty()) {
13534     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
13535       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
13536       return nullptr;
13537     }
13538   }
13539   assert(!R.isAmbiguous() && !R.empty());
13540   NamedDecl *ND = R.getRepresentativeDecl();
13541 
13542   // Check if we have a previous declaration with the same name.
13543   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
13544                      RedeclarationKind::ForVisibleRedeclaration);
13545   LookupName(PrevR, S);
13546 
13547   // Check we're not shadowing a template parameter.
13548   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
13549     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
13550     PrevR.clear();
13551   }
13552 
13553   // Filter out any other lookup result from an enclosing scope.
13554   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
13555                        /*AllowInlineNamespace*/false);
13556 
13557   // Find the previous declaration and check that we can redeclare it.
13558   NamespaceAliasDecl *Prev = nullptr;
13559   if (PrevR.isSingleResult()) {
13560     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
13561     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
13562       // We already have an alias with the same name that points to the same
13563       // namespace; check that it matches.
13564       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
13565         Prev = AD;
13566       } else if (isVisible(PrevDecl)) {
13567         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
13568           << Alias;
13569         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
13570           << AD->getNamespace();
13571         return nullptr;
13572       }
13573     } else if (isVisible(PrevDecl)) {
13574       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
13575                             ? diag::err_redefinition
13576                             : diag::err_redefinition_different_kind;
13577       Diag(AliasLoc, DiagID) << Alias;
13578       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13579       return nullptr;
13580     }
13581   }
13582 
13583   // The use of a nested name specifier may trigger deprecation warnings.
13584   DiagnoseUseOfDecl(ND, IdentLoc);
13585 
13586   NamespaceAliasDecl *AliasDecl =
13587     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
13588                                Alias, SS.getWithLocInContext(Context),
13589                                IdentLoc, ND);
13590   if (Prev)
13591     AliasDecl->setPreviousDecl(Prev);
13592 
13593   PushOnScopeChains(AliasDecl, S);
13594   return AliasDecl;
13595 }
13596 
13597 namespace {
13598 struct SpecialMemberExceptionSpecInfo
13599     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
13600   SourceLocation Loc;
13601   Sema::ImplicitExceptionSpecification ExceptSpec;
13602 
13603   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
13604                                  CXXSpecialMemberKind CSM,
13605                                  Sema::InheritedConstructorInfo *ICI,
13606                                  SourceLocation Loc)
13607       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
13608 
13609   bool visitBase(CXXBaseSpecifier *Base);
13610   bool visitField(FieldDecl *FD);
13611 
13612   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
13613                            unsigned Quals);
13614 
13615   void visitSubobjectCall(Subobject Subobj,
13616                           Sema::SpecialMemberOverloadResult SMOR);
13617 };
13618 }
13619 
13620 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
13621   auto *RT = Base->getType()->getAs<RecordType>();
13622   if (!RT)
13623     return false;
13624 
13625   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
13626   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
13627   if (auto *BaseCtor = SMOR.getMethod()) {
13628     visitSubobjectCall(Base, BaseCtor);
13629     return false;
13630   }
13631 
13632   visitClassSubobject(BaseClass, Base, 0);
13633   return false;
13634 }
13635 
13636 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
13637   if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
13638       FD->hasInClassInitializer()) {
13639     Expr *E = FD->getInClassInitializer();
13640     if (!E)
13641       // FIXME: It's a little wasteful to build and throw away a
13642       // CXXDefaultInitExpr here.
13643       // FIXME: We should have a single context note pointing at Loc, and
13644       // this location should be MD->getLocation() instead, since that's
13645       // the location where we actually use the default init expression.
13646       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
13647     if (E)
13648       ExceptSpec.CalledExpr(E);
13649   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
13650                             ->getAs<RecordType>()) {
13651     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
13652                         FD->getType().getCVRQualifiers());
13653   }
13654   return false;
13655 }
13656 
13657 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
13658                                                          Subobject Subobj,
13659                                                          unsigned Quals) {
13660   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
13661   bool IsMutable = Field && Field->isMutable();
13662   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
13663 }
13664 
13665 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
13666     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
13667   // Note, if lookup fails, it doesn't matter what exception specification we
13668   // choose because the special member will be deleted.
13669   if (CXXMethodDecl *MD = SMOR.getMethod())
13670     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
13671 }
13672 
13673 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
13674   llvm::APSInt Result;
13675   ExprResult Converted = CheckConvertedConstantExpression(
13676       ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
13677   ExplicitSpec.setExpr(Converted.get());
13678   if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
13679     ExplicitSpec.setKind(Result.getBoolValue()
13680                              ? ExplicitSpecKind::ResolvedTrue
13681                              : ExplicitSpecKind::ResolvedFalse);
13682     return true;
13683   }
13684   ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
13685   return false;
13686 }
13687 
13688 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
13689   ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
13690   if (!ExplicitExpr->isTypeDependent())
13691     tryResolveExplicitSpecifier(ES);
13692   return ES;
13693 }
13694 
13695 static Sema::ImplicitExceptionSpecification
13696 ComputeDefaultedSpecialMemberExceptionSpec(
13697     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
13698     Sema::InheritedConstructorInfo *ICI) {
13699   ComputingExceptionSpec CES(S, MD, Loc);
13700 
13701   CXXRecordDecl *ClassDecl = MD->getParent();
13702 
13703   // C++ [except.spec]p14:
13704   //   An implicitly declared special member function (Clause 12) shall have an
13705   //   exception-specification. [...]
13706   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
13707   if (ClassDecl->isInvalidDecl())
13708     return Info.ExceptSpec;
13709 
13710   // FIXME: If this diagnostic fires, we're probably missing a check for
13711   // attempting to resolve an exception specification before it's known
13712   // at a higher level.
13713   if (S.RequireCompleteType(MD->getLocation(),
13714                             S.Context.getRecordType(ClassDecl),
13715                             diag::err_exception_spec_incomplete_type))
13716     return Info.ExceptSpec;
13717 
13718   // C++1z [except.spec]p7:
13719   //   [Look for exceptions thrown by] a constructor selected [...] to
13720   //   initialize a potentially constructed subobject,
13721   // C++1z [except.spec]p8:
13722   //   The exception specification for an implicitly-declared destructor, or a
13723   //   destructor without a noexcept-specifier, is potentially-throwing if and
13724   //   only if any of the destructors for any of its potentially constructed
13725   //   subojects is potentially throwing.
13726   // FIXME: We respect the first rule but ignore the "potentially constructed"
13727   // in the second rule to resolve a core issue (no number yet) that would have
13728   // us reject:
13729   //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
13730   //   struct B : A {};
13731   //   struct C : B { void f(); };
13732   // ... due to giving B::~B() a non-throwing exception specification.
13733   Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
13734                                 : Info.VisitAllBases);
13735 
13736   return Info.ExceptSpec;
13737 }
13738 
13739 namespace {
13740 /// RAII object to register a special member as being currently declared.
13741 struct DeclaringSpecialMember {
13742   Sema &S;
13743   Sema::SpecialMemberDecl D;
13744   Sema::ContextRAII SavedContext;
13745   bool WasAlreadyBeingDeclared;
13746 
13747   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM)
13748       : S(S), D(RD, CSM), SavedContext(S, RD) {
13749     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
13750     if (WasAlreadyBeingDeclared)
13751       // This almost never happens, but if it does, ensure that our cache
13752       // doesn't contain a stale result.
13753       S.SpecialMemberCache.clear();
13754     else {
13755       // Register a note to be produced if we encounter an error while
13756       // declaring the special member.
13757       Sema::CodeSynthesisContext Ctx;
13758       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
13759       // FIXME: We don't have a location to use here. Using the class's
13760       // location maintains the fiction that we declare all special members
13761       // with the class, but (1) it's not clear that lying about that helps our
13762       // users understand what's going on, and (2) there may be outer contexts
13763       // on the stack (some of which are relevant) and printing them exposes
13764       // our lies.
13765       Ctx.PointOfInstantiation = RD->getLocation();
13766       Ctx.Entity = RD;
13767       Ctx.SpecialMember = CSM;
13768       S.pushCodeSynthesisContext(Ctx);
13769     }
13770   }
13771   ~DeclaringSpecialMember() {
13772     if (!WasAlreadyBeingDeclared) {
13773       S.SpecialMembersBeingDeclared.erase(D);
13774       S.popCodeSynthesisContext();
13775     }
13776   }
13777 
13778   /// Are we already trying to declare this special member?
13779   bool isAlreadyBeingDeclared() const {
13780     return WasAlreadyBeingDeclared;
13781   }
13782 };
13783 }
13784 
13785 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
13786   // Look up any existing declarations, but don't trigger declaration of all
13787   // implicit special members with this name.
13788   DeclarationName Name = FD->getDeclName();
13789   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
13790                  RedeclarationKind::ForExternalRedeclaration);
13791   for (auto *D : FD->getParent()->lookup(Name))
13792     if (auto *Acceptable = R.getAcceptableDecl(D))
13793       R.addDecl(Acceptable);
13794   R.resolveKind();
13795   R.suppressDiagnostics();
13796 
13797   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/ false,
13798                            FD->isThisDeclarationADefinition());
13799 }
13800 
13801 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
13802                                           QualType ResultTy,
13803                                           ArrayRef<QualType> Args) {
13804   // Build an exception specification pointing back at this constructor.
13805   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
13806 
13807   LangAS AS = getDefaultCXXMethodAddrSpace();
13808   if (AS != LangAS::Default) {
13809     EPI.TypeQuals.addAddressSpace(AS);
13810   }
13811 
13812   auto QT = Context.getFunctionType(ResultTy, Args, EPI);
13813   SpecialMem->setType(QT);
13814 
13815   // During template instantiation of implicit special member functions we need
13816   // a reliable TypeSourceInfo for the function prototype in order to allow
13817   // functions to be substituted.
13818   if (inTemplateInstantiation() &&
13819       cast<CXXRecordDecl>(SpecialMem->getParent())->isLambda()) {
13820     TypeSourceInfo *TSI =
13821         Context.getTrivialTypeSourceInfo(SpecialMem->getType());
13822     SpecialMem->setTypeSourceInfo(TSI);
13823   }
13824 }
13825 
13826 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
13827                                                      CXXRecordDecl *ClassDecl) {
13828   // C++ [class.ctor]p5:
13829   //   A default constructor for a class X is a constructor of class X
13830   //   that can be called without an argument. If there is no
13831   //   user-declared constructor for class X, a default constructor is
13832   //   implicitly declared. An implicitly-declared default constructor
13833   //   is an inline public member of its class.
13834   assert(ClassDecl->needsImplicitDefaultConstructor() &&
13835          "Should not build implicit default constructor!");
13836 
13837   DeclaringSpecialMember DSM(*this, ClassDecl,
13838                              CXXSpecialMemberKind::DefaultConstructor);
13839   if (DSM.isAlreadyBeingDeclared())
13840     return nullptr;
13841 
13842   bool Constexpr = defaultedSpecialMemberIsConstexpr(
13843       *this, ClassDecl, CXXSpecialMemberKind::DefaultConstructor, false);
13844 
13845   // Create the actual constructor declaration.
13846   CanQualType ClassType
13847     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13848   SourceLocation ClassLoc = ClassDecl->getLocation();
13849   DeclarationName Name
13850     = Context.DeclarationNames.getCXXConstructorName(ClassType);
13851   DeclarationNameInfo NameInfo(Name, ClassLoc);
13852   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
13853       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
13854       /*TInfo=*/nullptr, ExplicitSpecifier(),
13855       getCurFPFeatures().isFPConstrained(),
13856       /*isInline=*/true, /*isImplicitlyDeclared=*/true,
13857       Constexpr ? ConstexprSpecKind::Constexpr
13858                 : ConstexprSpecKind::Unspecified);
13859   DefaultCon->setAccess(AS_public);
13860   DefaultCon->setDefaulted();
13861 
13862   setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, std::nullopt);
13863 
13864   if (getLangOpts().CUDA)
13865     CUDA().inferTargetForImplicitSpecialMember(
13866         ClassDecl, CXXSpecialMemberKind::DefaultConstructor, DefaultCon,
13867         /* ConstRHS */ false,
13868         /* Diagnose */ false);
13869 
13870   // We don't need to use SpecialMemberIsTrivial here; triviality for default
13871   // constructors is easy to compute.
13872   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
13873 
13874   // Note that we have declared this constructor.
13875   ++getASTContext().NumImplicitDefaultConstructorsDeclared;
13876 
13877   Scope *S = getScopeForContext(ClassDecl);
13878   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
13879 
13880   if (ShouldDeleteSpecialMember(DefaultCon,
13881                                 CXXSpecialMemberKind::DefaultConstructor))
13882     SetDeclDeleted(DefaultCon, ClassLoc);
13883 
13884   if (S)
13885     PushOnScopeChains(DefaultCon, S, false);
13886   ClassDecl->addDecl(DefaultCon);
13887 
13888   return DefaultCon;
13889 }
13890 
13891 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
13892                                             CXXConstructorDecl *Constructor) {
13893   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
13894           !Constructor->doesThisDeclarationHaveABody() &&
13895           !Constructor->isDeleted()) &&
13896     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
13897   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13898     return;
13899 
13900   CXXRecordDecl *ClassDecl = Constructor->getParent();
13901   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
13902   if (ClassDecl->isInvalidDecl()) {
13903     return;
13904   }
13905 
13906   SynthesizedFunctionScope Scope(*this, Constructor);
13907 
13908   // The exception specification is needed because we are defining the
13909   // function.
13910   ResolveExceptionSpec(CurrentLocation,
13911                        Constructor->getType()->castAs<FunctionProtoType>());
13912   MarkVTableUsed(CurrentLocation, ClassDecl);
13913 
13914   // Add a context note for diagnostics produced after this point.
13915   Scope.addContextNote(CurrentLocation);
13916 
13917   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
13918     Constructor->setInvalidDecl();
13919     return;
13920   }
13921 
13922   SourceLocation Loc = Constructor->getEndLoc().isValid()
13923                            ? Constructor->getEndLoc()
13924                            : Constructor->getLocation();
13925   Constructor->setBody(new (Context) CompoundStmt(Loc));
13926   Constructor->markUsed(Context);
13927 
13928   if (ASTMutationListener *L = getASTMutationListener()) {
13929     L->CompletedImplicitDefinition(Constructor);
13930   }
13931 
13932   DiagnoseUninitializedFields(*this, Constructor);
13933 }
13934 
13935 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
13936   // Perform any delayed checks on exception specifications.
13937   CheckDelayedMemberExceptionSpecs();
13938 }
13939 
13940 /// Find or create the fake constructor we synthesize to model constructing an
13941 /// object of a derived class via a constructor of a base class.
13942 CXXConstructorDecl *
13943 Sema::findInheritingConstructor(SourceLocation Loc,
13944                                 CXXConstructorDecl *BaseCtor,
13945                                 ConstructorUsingShadowDecl *Shadow) {
13946   CXXRecordDecl *Derived = Shadow->getParent();
13947   SourceLocation UsingLoc = Shadow->getLocation();
13948 
13949   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
13950   // For now we use the name of the base class constructor as a member of the
13951   // derived class to indicate a (fake) inherited constructor name.
13952   DeclarationName Name = BaseCtor->getDeclName();
13953 
13954   // Check to see if we already have a fake constructor for this inherited
13955   // constructor call.
13956   for (NamedDecl *Ctor : Derived->lookup(Name))
13957     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
13958                                ->getInheritedConstructor()
13959                                .getConstructor(),
13960                            BaseCtor))
13961       return cast<CXXConstructorDecl>(Ctor);
13962 
13963   DeclarationNameInfo NameInfo(Name, UsingLoc);
13964   TypeSourceInfo *TInfo =
13965       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
13966   FunctionProtoTypeLoc ProtoLoc =
13967       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
13968 
13969   // Check the inherited constructor is valid and find the list of base classes
13970   // from which it was inherited.
13971   InheritedConstructorInfo ICI(*this, Loc, Shadow);
13972 
13973   bool Constexpr = BaseCtor->isConstexpr() &&
13974                    defaultedSpecialMemberIsConstexpr(
13975                        *this, Derived, CXXSpecialMemberKind::DefaultConstructor,
13976                        false, BaseCtor, &ICI);
13977 
13978   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
13979       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
13980       BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
13981       /*isInline=*/true,
13982       /*isImplicitlyDeclared=*/true,
13983       Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified,
13984       InheritedConstructor(Shadow, BaseCtor),
13985       BaseCtor->getTrailingRequiresClause());
13986   if (Shadow->isInvalidDecl())
13987     DerivedCtor->setInvalidDecl();
13988 
13989   // Build an unevaluated exception specification for this fake constructor.
13990   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
13991   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13992   EPI.ExceptionSpec.Type = EST_Unevaluated;
13993   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
13994   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
13995                                                FPT->getParamTypes(), EPI));
13996 
13997   // Build the parameter declarations.
13998   SmallVector<ParmVarDecl *, 16> ParamDecls;
13999   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
14000     TypeSourceInfo *TInfo =
14001         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
14002     ParmVarDecl *PD = ParmVarDecl::Create(
14003         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
14004         FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
14005     PD->setScopeInfo(0, I);
14006     PD->setImplicit();
14007     // Ensure attributes are propagated onto parameters (this matters for
14008     // format, pass_object_size, ...).
14009     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
14010     ParamDecls.push_back(PD);
14011     ProtoLoc.setParam(I, PD);
14012   }
14013 
14014   // Set up the new constructor.
14015   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
14016   DerivedCtor->setAccess(BaseCtor->getAccess());
14017   DerivedCtor->setParams(ParamDecls);
14018   Derived->addDecl(DerivedCtor);
14019 
14020   if (ShouldDeleteSpecialMember(DerivedCtor,
14021                                 CXXSpecialMemberKind::DefaultConstructor, &ICI))
14022     SetDeclDeleted(DerivedCtor, UsingLoc);
14023 
14024   return DerivedCtor;
14025 }
14026 
14027 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
14028   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
14029                                Ctor->getInheritedConstructor().getShadowDecl());
14030   ShouldDeleteSpecialMember(Ctor, CXXSpecialMemberKind::DefaultConstructor,
14031                             &ICI,
14032                             /*Diagnose*/ true);
14033 }
14034 
14035 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
14036                                        CXXConstructorDecl *Constructor) {
14037   CXXRecordDecl *ClassDecl = Constructor->getParent();
14038   assert(Constructor->getInheritedConstructor() &&
14039          !Constructor->doesThisDeclarationHaveABody() &&
14040          !Constructor->isDeleted());
14041   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14042     return;
14043 
14044   // Initializations are performed "as if by a defaulted default constructor",
14045   // so enter the appropriate scope.
14046   SynthesizedFunctionScope Scope(*this, Constructor);
14047 
14048   // The exception specification is needed because we are defining the
14049   // function.
14050   ResolveExceptionSpec(CurrentLocation,
14051                        Constructor->getType()->castAs<FunctionProtoType>());
14052   MarkVTableUsed(CurrentLocation, ClassDecl);
14053 
14054   // Add a context note for diagnostics produced after this point.
14055   Scope.addContextNote(CurrentLocation);
14056 
14057   ConstructorUsingShadowDecl *Shadow =
14058       Constructor->getInheritedConstructor().getShadowDecl();
14059   CXXConstructorDecl *InheritedCtor =
14060       Constructor->getInheritedConstructor().getConstructor();
14061 
14062   // [class.inhctor.init]p1:
14063   //   initialization proceeds as if a defaulted default constructor is used to
14064   //   initialize the D object and each base class subobject from which the
14065   //   constructor was inherited
14066 
14067   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
14068   CXXRecordDecl *RD = Shadow->getParent();
14069   SourceLocation InitLoc = Shadow->getLocation();
14070 
14071   // Build explicit initializers for all base classes from which the
14072   // constructor was inherited.
14073   SmallVector<CXXCtorInitializer*, 8> Inits;
14074   for (bool VBase : {false, true}) {
14075     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
14076       if (B.isVirtual() != VBase)
14077         continue;
14078 
14079       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
14080       if (!BaseRD)
14081         continue;
14082 
14083       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
14084       if (!BaseCtor.first)
14085         continue;
14086 
14087       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
14088       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
14089           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
14090 
14091       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
14092       Inits.push_back(new (Context) CXXCtorInitializer(
14093           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
14094           SourceLocation()));
14095     }
14096   }
14097 
14098   // We now proceed as if for a defaulted default constructor, with the relevant
14099   // initializers replaced.
14100 
14101   if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
14102     Constructor->setInvalidDecl();
14103     return;
14104   }
14105 
14106   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
14107   Constructor->markUsed(Context);
14108 
14109   if (ASTMutationListener *L = getASTMutationListener()) {
14110     L->CompletedImplicitDefinition(Constructor);
14111   }
14112 
14113   DiagnoseUninitializedFields(*this, Constructor);
14114 }
14115 
14116 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
14117   // C++ [class.dtor]p2:
14118   //   If a class has no user-declared destructor, a destructor is
14119   //   declared implicitly. An implicitly-declared destructor is an
14120   //   inline public member of its class.
14121   assert(ClassDecl->needsImplicitDestructor());
14122 
14123   DeclaringSpecialMember DSM(*this, ClassDecl,
14124                              CXXSpecialMemberKind::Destructor);
14125   if (DSM.isAlreadyBeingDeclared())
14126     return nullptr;
14127 
14128   bool Constexpr = defaultedSpecialMemberIsConstexpr(
14129       *this, ClassDecl, CXXSpecialMemberKind::Destructor, false);
14130 
14131   // Create the actual destructor declaration.
14132   CanQualType ClassType
14133     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
14134   SourceLocation ClassLoc = ClassDecl->getLocation();
14135   DeclarationName Name
14136     = Context.DeclarationNames.getCXXDestructorName(ClassType);
14137   DeclarationNameInfo NameInfo(Name, ClassLoc);
14138   CXXDestructorDecl *Destructor = CXXDestructorDecl::Create(
14139       Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr,
14140       getCurFPFeatures().isFPConstrained(),
14141       /*isInline=*/true,
14142       /*isImplicitlyDeclared=*/true,
14143       Constexpr ? ConstexprSpecKind::Constexpr
14144                 : ConstexprSpecKind::Unspecified);
14145   Destructor->setAccess(AS_public);
14146   Destructor->setDefaulted();
14147 
14148   setupImplicitSpecialMemberType(Destructor, Context.VoidTy, std::nullopt);
14149 
14150   if (getLangOpts().CUDA)
14151     CUDA().inferTargetForImplicitSpecialMember(
14152         ClassDecl, CXXSpecialMemberKind::Destructor, Destructor,
14153         /* ConstRHS */ false,
14154         /* Diagnose */ false);
14155 
14156   // We don't need to use SpecialMemberIsTrivial here; triviality for
14157   // destructors is easy to compute.
14158   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
14159   Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
14160                                 ClassDecl->hasTrivialDestructorForCall());
14161 
14162   // Note that we have declared this destructor.
14163   ++getASTContext().NumImplicitDestructorsDeclared;
14164 
14165   Scope *S = getScopeForContext(ClassDecl);
14166   CheckImplicitSpecialMemberDeclaration(S, Destructor);
14167 
14168   // We can't check whether an implicit destructor is deleted before we complete
14169   // the definition of the class, because its validity depends on the alignment
14170   // of the class. We'll check this from ActOnFields once the class is complete.
14171   if (ClassDecl->isCompleteDefinition() &&
14172       ShouldDeleteSpecialMember(Destructor, CXXSpecialMemberKind::Destructor))
14173     SetDeclDeleted(Destructor, ClassLoc);
14174 
14175   // Introduce this destructor into its scope.
14176   if (S)
14177     PushOnScopeChains(Destructor, S, false);
14178   ClassDecl->addDecl(Destructor);
14179 
14180   return Destructor;
14181 }
14182 
14183 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
14184                                     CXXDestructorDecl *Destructor) {
14185   assert((Destructor->isDefaulted() &&
14186           !Destructor->doesThisDeclarationHaveABody() &&
14187           !Destructor->isDeleted()) &&
14188          "DefineImplicitDestructor - call it for implicit default dtor");
14189   if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
14190     return;
14191 
14192   CXXRecordDecl *ClassDecl = Destructor->getParent();
14193   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
14194 
14195   SynthesizedFunctionScope Scope(*this, Destructor);
14196 
14197   // The exception specification is needed because we are defining the
14198   // function.
14199   ResolveExceptionSpec(CurrentLocation,
14200                        Destructor->getType()->castAs<FunctionProtoType>());
14201   MarkVTableUsed(CurrentLocation, ClassDecl);
14202 
14203   // Add a context note for diagnostics produced after this point.
14204   Scope.addContextNote(CurrentLocation);
14205 
14206   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14207                                          Destructor->getParent());
14208 
14209   if (CheckDestructor(Destructor)) {
14210     Destructor->setInvalidDecl();
14211     return;
14212   }
14213 
14214   SourceLocation Loc = Destructor->getEndLoc().isValid()
14215                            ? Destructor->getEndLoc()
14216                            : Destructor->getLocation();
14217   Destructor->setBody(new (Context) CompoundStmt(Loc));
14218   Destructor->markUsed(Context);
14219 
14220   if (ASTMutationListener *L = getASTMutationListener()) {
14221     L->CompletedImplicitDefinition(Destructor);
14222   }
14223 }
14224 
14225 void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
14226                                           CXXDestructorDecl *Destructor) {
14227   if (Destructor->isInvalidDecl())
14228     return;
14229 
14230   CXXRecordDecl *ClassDecl = Destructor->getParent();
14231   assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14232          "implicit complete dtors unneeded outside MS ABI");
14233   assert(ClassDecl->getNumVBases() > 0 &&
14234          "complete dtor only exists for classes with vbases");
14235 
14236   SynthesizedFunctionScope Scope(*this, Destructor);
14237 
14238   // Add a context note for diagnostics produced after this point.
14239   Scope.addContextNote(CurrentLocation);
14240 
14241   MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
14242 }
14243 
14244 void Sema::ActOnFinishCXXMemberDecls() {
14245   // If the context is an invalid C++ class, just suppress these checks.
14246   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
14247     if (Record->isInvalidDecl()) {
14248       DelayedOverridingExceptionSpecChecks.clear();
14249       DelayedEquivalentExceptionSpecChecks.clear();
14250       return;
14251     }
14252     checkForMultipleExportedDefaultConstructors(*this, Record);
14253   }
14254 }
14255 
14256 void Sema::ActOnFinishCXXNonNestedClass() {
14257   referenceDLLExportedClassMethods();
14258 
14259   if (!DelayedDllExportMemberFunctions.empty()) {
14260     SmallVector<CXXMethodDecl*, 4> WorkList;
14261     std::swap(DelayedDllExportMemberFunctions, WorkList);
14262     for (CXXMethodDecl *M : WorkList) {
14263       DefineDefaultedFunction(*this, M, M->getLocation());
14264 
14265       // Pass the method to the consumer to get emitted. This is not necessary
14266       // for explicit instantiation definitions, as they will get emitted
14267       // anyway.
14268       if (M->getParent()->getTemplateSpecializationKind() !=
14269           TSK_ExplicitInstantiationDefinition)
14270         ActOnFinishInlineFunctionDef(M);
14271     }
14272   }
14273 }
14274 
14275 void Sema::referenceDLLExportedClassMethods() {
14276   if (!DelayedDllExportClasses.empty()) {
14277     // Calling ReferenceDllExportedMembers might cause the current function to
14278     // be called again, so use a local copy of DelayedDllExportClasses.
14279     SmallVector<CXXRecordDecl *, 4> WorkList;
14280     std::swap(DelayedDllExportClasses, WorkList);
14281     for (CXXRecordDecl *Class : WorkList)
14282       ReferenceDllExportedMembers(*this, Class);
14283   }
14284 }
14285 
14286 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
14287   assert(getLangOpts().CPlusPlus11 &&
14288          "adjusting dtor exception specs was introduced in c++11");
14289 
14290   if (Destructor->isDependentContext())
14291     return;
14292 
14293   // C++11 [class.dtor]p3:
14294   //   A declaration of a destructor that does not have an exception-
14295   //   specification is implicitly considered to have the same exception-
14296   //   specification as an implicit declaration.
14297   const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
14298   if (DtorType->hasExceptionSpec())
14299     return;
14300 
14301   // Replace the destructor's type, building off the existing one. Fortunately,
14302   // the only thing of interest in the destructor type is its extended info.
14303   // The return and arguments are fixed.
14304   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
14305   EPI.ExceptionSpec.Type = EST_Unevaluated;
14306   EPI.ExceptionSpec.SourceDecl = Destructor;
14307   Destructor->setType(
14308       Context.getFunctionType(Context.VoidTy, std::nullopt, EPI));
14309 
14310   // FIXME: If the destructor has a body that could throw, and the newly created
14311   // spec doesn't allow exceptions, we should emit a warning, because this
14312   // change in behavior can break conforming C++03 programs at runtime.
14313   // However, we don't have a body or an exception specification yet, so it
14314   // needs to be done somewhere else.
14315 }
14316 
14317 namespace {
14318 /// An abstract base class for all helper classes used in building the
14319 //  copy/move operators. These classes serve as factory functions and help us
14320 //  avoid using the same Expr* in the AST twice.
14321 class ExprBuilder {
14322   ExprBuilder(const ExprBuilder&) = delete;
14323   ExprBuilder &operator=(const ExprBuilder&) = delete;
14324 
14325 protected:
14326   static Expr *assertNotNull(Expr *E) {
14327     assert(E && "Expression construction must not fail.");
14328     return E;
14329   }
14330 
14331 public:
14332   ExprBuilder() {}
14333   virtual ~ExprBuilder() {}
14334 
14335   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
14336 };
14337 
14338 class RefBuilder: public ExprBuilder {
14339   VarDecl *Var;
14340   QualType VarType;
14341 
14342 public:
14343   Expr *build(Sema &S, SourceLocation Loc) const override {
14344     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
14345   }
14346 
14347   RefBuilder(VarDecl *Var, QualType VarType)
14348       : Var(Var), VarType(VarType) {}
14349 };
14350 
14351 class ThisBuilder: public ExprBuilder {
14352 public:
14353   Expr *build(Sema &S, SourceLocation Loc) const override {
14354     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
14355   }
14356 };
14357 
14358 class CastBuilder: public ExprBuilder {
14359   const ExprBuilder &Builder;
14360   QualType Type;
14361   ExprValueKind Kind;
14362   const CXXCastPath &Path;
14363 
14364 public:
14365   Expr *build(Sema &S, SourceLocation Loc) const override {
14366     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
14367                                              CK_UncheckedDerivedToBase, Kind,
14368                                              &Path).get());
14369   }
14370 
14371   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
14372               const CXXCastPath &Path)
14373       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
14374 };
14375 
14376 class DerefBuilder: public ExprBuilder {
14377   const ExprBuilder &Builder;
14378 
14379 public:
14380   Expr *build(Sema &S, SourceLocation Loc) const override {
14381     return assertNotNull(
14382         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
14383   }
14384 
14385   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14386 };
14387 
14388 class MemberBuilder: public ExprBuilder {
14389   const ExprBuilder &Builder;
14390   QualType Type;
14391   CXXScopeSpec SS;
14392   bool IsArrow;
14393   LookupResult &MemberLookup;
14394 
14395 public:
14396   Expr *build(Sema &S, SourceLocation Loc) const override {
14397     return assertNotNull(S.BuildMemberReferenceExpr(
14398         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
14399         nullptr, MemberLookup, nullptr, nullptr).get());
14400   }
14401 
14402   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
14403                 LookupResult &MemberLookup)
14404       : Builder(Builder), Type(Type), IsArrow(IsArrow),
14405         MemberLookup(MemberLookup) {}
14406 };
14407 
14408 class MoveCastBuilder: public ExprBuilder {
14409   const ExprBuilder &Builder;
14410 
14411 public:
14412   Expr *build(Sema &S, SourceLocation Loc) const override {
14413     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
14414   }
14415 
14416   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14417 };
14418 
14419 class LvalueConvBuilder: public ExprBuilder {
14420   const ExprBuilder &Builder;
14421 
14422 public:
14423   Expr *build(Sema &S, SourceLocation Loc) const override {
14424     return assertNotNull(
14425         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
14426   }
14427 
14428   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14429 };
14430 
14431 class SubscriptBuilder: public ExprBuilder {
14432   const ExprBuilder &Base;
14433   const ExprBuilder &Index;
14434 
14435 public:
14436   Expr *build(Sema &S, SourceLocation Loc) const override {
14437     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
14438         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
14439   }
14440 
14441   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
14442       : Base(Base), Index(Index) {}
14443 };
14444 
14445 } // end anonymous namespace
14446 
14447 /// When generating a defaulted copy or move assignment operator, if a field
14448 /// should be copied with __builtin_memcpy rather than via explicit assignments,
14449 /// do so. This optimization only applies for arrays of scalars, and for arrays
14450 /// of class type where the selected copy/move-assignment operator is trivial.
14451 static StmtResult
14452 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
14453                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
14454   // Compute the size of the memory buffer to be copied.
14455   QualType SizeType = S.Context.getSizeType();
14456   llvm::APInt Size(S.Context.getTypeSize(SizeType),
14457                    S.Context.getTypeSizeInChars(T).getQuantity());
14458 
14459   // Take the address of the field references for "from" and "to". We
14460   // directly construct UnaryOperators here because semantic analysis
14461   // does not permit us to take the address of an xvalue.
14462   Expr *From = FromB.build(S, Loc);
14463   From = UnaryOperator::Create(
14464       S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
14465       VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14466   Expr *To = ToB.build(S, Loc);
14467   To = UnaryOperator::Create(
14468       S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
14469       VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14470 
14471   const Type *E = T->getBaseElementTypeUnsafe();
14472   bool NeedsCollectableMemCpy =
14473       E->isRecordType() &&
14474       E->castAs<RecordType>()->getDecl()->hasObjectMember();
14475 
14476   // Create a reference to the __builtin_objc_memmove_collectable function
14477   StringRef MemCpyName = NeedsCollectableMemCpy ?
14478     "__builtin_objc_memmove_collectable" :
14479     "__builtin_memcpy";
14480   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
14481                  Sema::LookupOrdinaryName);
14482   S.LookupName(R, S.TUScope, true);
14483 
14484   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
14485   if (!MemCpy)
14486     // Something went horribly wrong earlier, and we will have complained
14487     // about it.
14488     return StmtError();
14489 
14490   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
14491                                             VK_PRValue, Loc, nullptr);
14492   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
14493 
14494   Expr *CallArgs[] = {
14495     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
14496   };
14497   ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
14498                                     Loc, CallArgs, Loc);
14499 
14500   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
14501   return Call.getAs<Stmt>();
14502 }
14503 
14504 /// Builds a statement that copies/moves the given entity from \p From to
14505 /// \c To.
14506 ///
14507 /// This routine is used to copy/move the members of a class with an
14508 /// implicitly-declared copy/move assignment operator. When the entities being
14509 /// copied are arrays, this routine builds for loops to copy them.
14510 ///
14511 /// \param S The Sema object used for type-checking.
14512 ///
14513 /// \param Loc The location where the implicit copy/move is being generated.
14514 ///
14515 /// \param T The type of the expressions being copied/moved. Both expressions
14516 /// must have this type.
14517 ///
14518 /// \param To The expression we are copying/moving to.
14519 ///
14520 /// \param From The expression we are copying/moving from.
14521 ///
14522 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
14523 /// Otherwise, it's a non-static member subobject.
14524 ///
14525 /// \param Copying Whether we're copying or moving.
14526 ///
14527 /// \param Depth Internal parameter recording the depth of the recursion.
14528 ///
14529 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
14530 /// if a memcpy should be used instead.
14531 static StmtResult
14532 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
14533                                  const ExprBuilder &To, const ExprBuilder &From,
14534                                  bool CopyingBaseSubobject, bool Copying,
14535                                  unsigned Depth = 0) {
14536   // C++11 [class.copy]p28:
14537   //   Each subobject is assigned in the manner appropriate to its type:
14538   //
14539   //     - if the subobject is of class type, as if by a call to operator= with
14540   //       the subobject as the object expression and the corresponding
14541   //       subobject of x as a single function argument (as if by explicit
14542   //       qualification; that is, ignoring any possible virtual overriding
14543   //       functions in more derived classes);
14544   //
14545   // C++03 [class.copy]p13:
14546   //     - if the subobject is of class type, the copy assignment operator for
14547   //       the class is used (as if by explicit qualification; that is,
14548   //       ignoring any possible virtual overriding functions in more derived
14549   //       classes);
14550   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
14551     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
14552 
14553     // Look for operator=.
14554     DeclarationName Name
14555       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14556     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
14557     S.LookupQualifiedName(OpLookup, ClassDecl, false);
14558 
14559     // Prior to C++11, filter out any result that isn't a copy/move-assignment
14560     // operator.
14561     if (!S.getLangOpts().CPlusPlus11) {
14562       LookupResult::Filter F = OpLookup.makeFilter();
14563       while (F.hasNext()) {
14564         NamedDecl *D = F.next();
14565         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
14566           if (Method->isCopyAssignmentOperator() ||
14567               (!Copying && Method->isMoveAssignmentOperator()))
14568             continue;
14569 
14570         F.erase();
14571       }
14572       F.done();
14573     }
14574 
14575     // Suppress the protected check (C++ [class.protected]) for each of the
14576     // assignment operators we found. This strange dance is required when
14577     // we're assigning via a base classes's copy-assignment operator. To
14578     // ensure that we're getting the right base class subobject (without
14579     // ambiguities), we need to cast "this" to that subobject type; to
14580     // ensure that we don't go through the virtual call mechanism, we need
14581     // to qualify the operator= name with the base class (see below). However,
14582     // this means that if the base class has a protected copy assignment
14583     // operator, the protected member access check will fail. So, we
14584     // rewrite "protected" access to "public" access in this case, since we
14585     // know by construction that we're calling from a derived class.
14586     if (CopyingBaseSubobject) {
14587       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
14588            L != LEnd; ++L) {
14589         if (L.getAccess() == AS_protected)
14590           L.setAccess(AS_public);
14591       }
14592     }
14593 
14594     // Create the nested-name-specifier that will be used to qualify the
14595     // reference to operator=; this is required to suppress the virtual
14596     // call mechanism.
14597     CXXScopeSpec SS;
14598     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
14599     SS.MakeTrivial(S.Context,
14600                    NestedNameSpecifier::Create(S.Context, nullptr, false,
14601                                                CanonicalT),
14602                    Loc);
14603 
14604     // Create the reference to operator=.
14605     ExprResult OpEqualRef
14606       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
14607                                    SS, /*TemplateKWLoc=*/SourceLocation(),
14608                                    /*FirstQualifierInScope=*/nullptr,
14609                                    OpLookup,
14610                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
14611                                    /*SuppressQualifierCheck=*/true);
14612     if (OpEqualRef.isInvalid())
14613       return StmtError();
14614 
14615     // Build the call to the assignment operator.
14616 
14617     Expr *FromInst = From.build(S, Loc);
14618     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
14619                                                   OpEqualRef.getAs<Expr>(),
14620                                                   Loc, FromInst, Loc);
14621     if (Call.isInvalid())
14622       return StmtError();
14623 
14624     // If we built a call to a trivial 'operator=' while copying an array,
14625     // bail out. We'll replace the whole shebang with a memcpy.
14626     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
14627     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
14628       return StmtResult((Stmt*)nullptr);
14629 
14630     // Convert to an expression-statement, and clean up any produced
14631     // temporaries.
14632     return S.ActOnExprStmt(Call);
14633   }
14634 
14635   //     - if the subobject is of scalar type, the built-in assignment
14636   //       operator is used.
14637   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
14638   if (!ArrayTy) {
14639     ExprResult Assignment = S.CreateBuiltinBinOp(
14640         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
14641     if (Assignment.isInvalid())
14642       return StmtError();
14643     return S.ActOnExprStmt(Assignment);
14644   }
14645 
14646   //     - if the subobject is an array, each element is assigned, in the
14647   //       manner appropriate to the element type;
14648 
14649   // Construct a loop over the array bounds, e.g.,
14650   //
14651   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
14652   //
14653   // that will copy each of the array elements.
14654   QualType SizeType = S.Context.getSizeType();
14655 
14656   // Create the iteration variable.
14657   IdentifierInfo *IterationVarName = nullptr;
14658   {
14659     SmallString<8> Str;
14660     llvm::raw_svector_ostream OS(Str);
14661     OS << "__i" << Depth;
14662     IterationVarName = &S.Context.Idents.get(OS.str());
14663   }
14664   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
14665                                           IterationVarName, SizeType,
14666                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
14667                                           SC_None);
14668 
14669   // Initialize the iteration variable to zero.
14670   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
14671   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
14672 
14673   // Creates a reference to the iteration variable.
14674   RefBuilder IterationVarRef(IterationVar, SizeType);
14675   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
14676 
14677   // Create the DeclStmt that holds the iteration variable.
14678   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
14679 
14680   // Subscript the "from" and "to" expressions with the iteration variable.
14681   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
14682   MoveCastBuilder FromIndexMove(FromIndexCopy);
14683   const ExprBuilder *FromIndex;
14684   if (Copying)
14685     FromIndex = &FromIndexCopy;
14686   else
14687     FromIndex = &FromIndexMove;
14688 
14689   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
14690 
14691   // Build the copy/move for an individual element of the array.
14692   StmtResult Copy =
14693     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
14694                                      ToIndex, *FromIndex, CopyingBaseSubobject,
14695                                      Copying, Depth + 1);
14696   // Bail out if copying fails or if we determined that we should use memcpy.
14697   if (Copy.isInvalid() || !Copy.get())
14698     return Copy;
14699 
14700   // Create the comparison against the array bound.
14701   llvm::APInt Upper
14702     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
14703   Expr *Comparison = BinaryOperator::Create(
14704       S.Context, IterationVarRefRVal.build(S, Loc),
14705       IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
14706       S.Context.BoolTy, VK_PRValue, OK_Ordinary, Loc,
14707       S.CurFPFeatureOverrides());
14708 
14709   // Create the pre-increment of the iteration variable. We can determine
14710   // whether the increment will overflow based on the value of the array
14711   // bound.
14712   Expr *Increment = UnaryOperator::Create(
14713       S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
14714       OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
14715 
14716   // Construct the loop that copies all elements of this array.
14717   return S.ActOnForStmt(
14718       Loc, Loc, InitStmt,
14719       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
14720       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
14721 }
14722 
14723 static StmtResult
14724 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
14725                       const ExprBuilder &To, const ExprBuilder &From,
14726                       bool CopyingBaseSubobject, bool Copying) {
14727   // Maybe we should use a memcpy?
14728   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
14729       T.isTriviallyCopyableType(S.Context))
14730     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14731 
14732   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
14733                                                      CopyingBaseSubobject,
14734                                                      Copying, 0));
14735 
14736   // If we ended up picking a trivial assignment operator for an array of a
14737   // non-trivially-copyable class type, just emit a memcpy.
14738   if (!Result.isInvalid() && !Result.get())
14739     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14740 
14741   return Result;
14742 }
14743 
14744 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
14745   // Note: The following rules are largely analoguous to the copy
14746   // constructor rules. Note that virtual bases are not taken into account
14747   // for determining the argument type of the operator. Note also that
14748   // operators taking an object instead of a reference are allowed.
14749   assert(ClassDecl->needsImplicitCopyAssignment());
14750 
14751   DeclaringSpecialMember DSM(*this, ClassDecl,
14752                              CXXSpecialMemberKind::CopyAssignment);
14753   if (DSM.isAlreadyBeingDeclared())
14754     return nullptr;
14755 
14756   QualType ArgType = Context.getTypeDeclType(ClassDecl);
14757   ArgType = Context.getElaboratedType(ElaboratedTypeKeyword::None, nullptr,
14758                                       ArgType, nullptr);
14759   LangAS AS = getDefaultCXXMethodAddrSpace();
14760   if (AS != LangAS::Default)
14761     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14762   QualType RetType = Context.getLValueReferenceType(ArgType);
14763   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
14764   if (Const)
14765     ArgType = ArgType.withConst();
14766 
14767   ArgType = Context.getLValueReferenceType(ArgType);
14768 
14769   bool Constexpr = defaultedSpecialMemberIsConstexpr(
14770       *this, ClassDecl, CXXSpecialMemberKind::CopyAssignment, Const);
14771 
14772   //   An implicitly-declared copy assignment operator is an inline public
14773   //   member of its class.
14774   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14775   SourceLocation ClassLoc = ClassDecl->getLocation();
14776   DeclarationNameInfo NameInfo(Name, ClassLoc);
14777   CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
14778       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14779       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14780       getCurFPFeatures().isFPConstrained(),
14781       /*isInline=*/true,
14782       Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
14783       SourceLocation());
14784   CopyAssignment->setAccess(AS_public);
14785   CopyAssignment->setDefaulted();
14786   CopyAssignment->setImplicit();
14787 
14788   setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
14789 
14790   if (getLangOpts().CUDA)
14791     CUDA().inferTargetForImplicitSpecialMember(
14792         ClassDecl, CXXSpecialMemberKind::CopyAssignment, CopyAssignment,
14793         /* ConstRHS */ Const,
14794         /* Diagnose */ false);
14795 
14796   // Add the parameter to the operator.
14797   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
14798                                                ClassLoc, ClassLoc,
14799                                                /*Id=*/nullptr, ArgType,
14800                                                /*TInfo=*/nullptr, SC_None,
14801                                                nullptr);
14802   CopyAssignment->setParams(FromParam);
14803 
14804   CopyAssignment->setTrivial(
14805       ClassDecl->needsOverloadResolutionForCopyAssignment()
14806           ? SpecialMemberIsTrivial(CopyAssignment,
14807                                    CXXSpecialMemberKind::CopyAssignment)
14808           : ClassDecl->hasTrivialCopyAssignment());
14809 
14810   // Note that we have added this copy-assignment operator.
14811   ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
14812 
14813   Scope *S = getScopeForContext(ClassDecl);
14814   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
14815 
14816   if (ShouldDeleteSpecialMember(CopyAssignment,
14817                                 CXXSpecialMemberKind::CopyAssignment)) {
14818     ClassDecl->setImplicitCopyAssignmentIsDeleted();
14819     SetDeclDeleted(CopyAssignment, ClassLoc);
14820   }
14821 
14822   if (S)
14823     PushOnScopeChains(CopyAssignment, S, false);
14824   ClassDecl->addDecl(CopyAssignment);
14825 
14826   return CopyAssignment;
14827 }
14828 
14829 /// Diagnose an implicit copy operation for a class which is odr-used, but
14830 /// which is deprecated because the class has a user-declared copy constructor,
14831 /// copy assignment operator, or destructor.
14832 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
14833   assert(CopyOp->isImplicit());
14834 
14835   CXXRecordDecl *RD = CopyOp->getParent();
14836   CXXMethodDecl *UserDeclaredOperation = nullptr;
14837 
14838   if (RD->hasUserDeclaredDestructor()) {
14839     UserDeclaredOperation = RD->getDestructor();
14840   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
14841              RD->hasUserDeclaredCopyConstructor()) {
14842     // Find any user-declared copy constructor.
14843     for (auto *I : RD->ctors()) {
14844       if (I->isCopyConstructor()) {
14845         UserDeclaredOperation = I;
14846         break;
14847       }
14848     }
14849     assert(UserDeclaredOperation);
14850   } else if (isa<CXXConstructorDecl>(CopyOp) &&
14851              RD->hasUserDeclaredCopyAssignment()) {
14852     // Find any user-declared move assignment operator.
14853     for (auto *I : RD->methods()) {
14854       if (I->isCopyAssignmentOperator()) {
14855         UserDeclaredOperation = I;
14856         break;
14857       }
14858     }
14859     assert(UserDeclaredOperation);
14860   }
14861 
14862   if (UserDeclaredOperation) {
14863     bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
14864     bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation);
14865     bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp);
14866     unsigned DiagID =
14867         (UDOIsUserProvided && UDOIsDestructor)
14868             ? diag::warn_deprecated_copy_with_user_provided_dtor
14869         : (UDOIsUserProvided && !UDOIsDestructor)
14870             ? diag::warn_deprecated_copy_with_user_provided_copy
14871         : (!UDOIsUserProvided && UDOIsDestructor)
14872             ? diag::warn_deprecated_copy_with_dtor
14873             : diag::warn_deprecated_copy;
14874     S.Diag(UserDeclaredOperation->getLocation(), DiagID)
14875         << RD << IsCopyAssignment;
14876   }
14877 }
14878 
14879 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
14880                                         CXXMethodDecl *CopyAssignOperator) {
14881   assert((CopyAssignOperator->isDefaulted() &&
14882           CopyAssignOperator->isOverloadedOperator() &&
14883           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
14884           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
14885           !CopyAssignOperator->isDeleted()) &&
14886          "DefineImplicitCopyAssignment called for wrong function");
14887   if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
14888     return;
14889 
14890   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
14891   if (ClassDecl->isInvalidDecl()) {
14892     CopyAssignOperator->setInvalidDecl();
14893     return;
14894   }
14895 
14896   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
14897 
14898   // The exception specification is needed because we are defining the
14899   // function.
14900   ResolveExceptionSpec(CurrentLocation,
14901                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
14902 
14903   // Add a context note for diagnostics produced after this point.
14904   Scope.addContextNote(CurrentLocation);
14905 
14906   // C++11 [class.copy]p18:
14907   //   The [definition of an implicitly declared copy assignment operator] is
14908   //   deprecated if the class has a user-declared copy constructor or a
14909   //   user-declared destructor.
14910   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
14911     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
14912 
14913   // C++0x [class.copy]p30:
14914   //   The implicitly-defined or explicitly-defaulted copy assignment operator
14915   //   for a non-union class X performs memberwise copy assignment of its
14916   //   subobjects. The direct base classes of X are assigned first, in the
14917   //   order of their declaration in the base-specifier-list, and then the
14918   //   immediate non-static data members of X are assigned, in the order in
14919   //   which they were declared in the class definition.
14920 
14921   // The statements that form the synthesized function body.
14922   SmallVector<Stmt*, 8> Statements;
14923 
14924   // The parameter for the "other" object, which we are copying from.
14925   ParmVarDecl *Other = CopyAssignOperator->getNonObjectParameter(0);
14926   Qualifiers OtherQuals = Other->getType().getQualifiers();
14927   QualType OtherRefType = Other->getType();
14928   if (OtherRefType->isLValueReferenceType()) {
14929     OtherRefType = OtherRefType->getPointeeType();
14930     OtherQuals = OtherRefType.getQualifiers();
14931   }
14932 
14933   // Our location for everything implicitly-generated.
14934   SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
14935                            ? CopyAssignOperator->getEndLoc()
14936                            : CopyAssignOperator->getLocation();
14937 
14938   // Builds a DeclRefExpr for the "other" object.
14939   RefBuilder OtherRef(Other, OtherRefType);
14940 
14941   // Builds the function object parameter.
14942   std::optional<ThisBuilder> This;
14943   std::optional<DerefBuilder> DerefThis;
14944   std::optional<RefBuilder> ExplicitObject;
14945   bool IsArrow = false;
14946   QualType ObjectType;
14947   if (CopyAssignOperator->isExplicitObjectMemberFunction()) {
14948     ObjectType = CopyAssignOperator->getParamDecl(0)->getType();
14949     if (ObjectType->isReferenceType())
14950       ObjectType = ObjectType->getPointeeType();
14951     ExplicitObject.emplace(CopyAssignOperator->getParamDecl(0), ObjectType);
14952   } else {
14953     ObjectType = getCurrentThisType();
14954     This.emplace();
14955     DerefThis.emplace(*This);
14956     IsArrow = !LangOpts.HLSL;
14957   }
14958   ExprBuilder &ObjectParameter =
14959       ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
14960                      : static_cast<ExprBuilder &>(*This);
14961 
14962   // Assign base classes.
14963   bool Invalid = false;
14964   for (auto &Base : ClassDecl->bases()) {
14965     // Form the assignment:
14966     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
14967     QualType BaseType = Base.getType().getUnqualifiedType();
14968     if (!BaseType->isRecordType()) {
14969       Invalid = true;
14970       continue;
14971     }
14972 
14973     CXXCastPath BasePath;
14974     BasePath.push_back(&Base);
14975 
14976     // Construct the "from" expression, which is an implicit cast to the
14977     // appropriately-qualified base type.
14978     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
14979                      VK_LValue, BasePath);
14980 
14981     // Dereference "this".
14982     CastBuilder To(
14983         ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
14984                        : static_cast<ExprBuilder &>(*DerefThis),
14985         Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),
14986         VK_LValue, BasePath);
14987 
14988     // Build the copy.
14989     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
14990                                             To, From,
14991                                             /*CopyingBaseSubobject=*/true,
14992                                             /*Copying=*/true);
14993     if (Copy.isInvalid()) {
14994       CopyAssignOperator->setInvalidDecl();
14995       return;
14996     }
14997 
14998     // Success! Record the copy.
14999     Statements.push_back(Copy.getAs<Expr>());
15000   }
15001 
15002   // Assign non-static members.
15003   for (auto *Field : ClassDecl->fields()) {
15004     // FIXME: We should form some kind of AST representation for the implied
15005     // memcpy in a union copy operation.
15006     if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15007       continue;
15008 
15009     if (Field->isInvalidDecl()) {
15010       Invalid = true;
15011       continue;
15012     }
15013 
15014     // Check for members of reference type; we can't copy those.
15015     if (Field->getType()->isReferenceType()) {
15016       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15017         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
15018       Diag(Field->getLocation(), diag::note_declared_at);
15019       Invalid = true;
15020       continue;
15021     }
15022 
15023     // Check for members of const-qualified, non-class type.
15024     QualType BaseType = Context.getBaseElementType(Field->getType());
15025     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
15026       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15027         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
15028       Diag(Field->getLocation(), diag::note_declared_at);
15029       Invalid = true;
15030       continue;
15031     }
15032 
15033     // Suppress assigning zero-width bitfields.
15034     if (Field->isZeroLengthBitField(Context))
15035       continue;
15036 
15037     QualType FieldType = Field->getType().getNonReferenceType();
15038     if (FieldType->isIncompleteArrayType()) {
15039       assert(ClassDecl->hasFlexibleArrayMember() &&
15040              "Incomplete array type is not valid");
15041       continue;
15042     }
15043 
15044     // Build references to the field in the object we're copying from and to.
15045     CXXScopeSpec SS; // Intentionally empty
15046     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15047                               LookupMemberName);
15048     MemberLookup.addDecl(Field);
15049     MemberLookup.resolveKind();
15050 
15051     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
15052     MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15053     // Build the copy of this field.
15054     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
15055                                             To, From,
15056                                             /*CopyingBaseSubobject=*/false,
15057                                             /*Copying=*/true);
15058     if (Copy.isInvalid()) {
15059       CopyAssignOperator->setInvalidDecl();
15060       return;
15061     }
15062 
15063     // Success! Record the copy.
15064     Statements.push_back(Copy.getAs<Stmt>());
15065   }
15066 
15067   if (!Invalid) {
15068     // Add a "return *this;"
15069     Expr *ThisExpr =
15070         (ExplicitObject  ? static_cast<ExprBuilder &>(*ExplicitObject)
15071          : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
15072                          : static_cast<ExprBuilder &>(*DerefThis))
15073             .build(*this, Loc);
15074     StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
15075     if (Return.isInvalid())
15076       Invalid = true;
15077     else
15078       Statements.push_back(Return.getAs<Stmt>());
15079   }
15080 
15081   if (Invalid) {
15082     CopyAssignOperator->setInvalidDecl();
15083     return;
15084   }
15085 
15086   StmtResult Body;
15087   {
15088     CompoundScopeRAII CompoundScope(*this);
15089     Body = ActOnCompoundStmt(Loc, Loc, Statements,
15090                              /*isStmtExpr=*/false);
15091     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15092   }
15093   CopyAssignOperator->setBody(Body.getAs<Stmt>());
15094   CopyAssignOperator->markUsed(Context);
15095 
15096   if (ASTMutationListener *L = getASTMutationListener()) {
15097     L->CompletedImplicitDefinition(CopyAssignOperator);
15098   }
15099 }
15100 
15101 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
15102   assert(ClassDecl->needsImplicitMoveAssignment());
15103 
15104   DeclaringSpecialMember DSM(*this, ClassDecl,
15105                              CXXSpecialMemberKind::MoveAssignment);
15106   if (DSM.isAlreadyBeingDeclared())
15107     return nullptr;
15108 
15109   // Note: The following rules are largely analoguous to the move
15110   // constructor rules.
15111 
15112   QualType ArgType = Context.getTypeDeclType(ClassDecl);
15113   ArgType = Context.getElaboratedType(ElaboratedTypeKeyword::None, nullptr,
15114                                       ArgType, nullptr);
15115   LangAS AS = getDefaultCXXMethodAddrSpace();
15116   if (AS != LangAS::Default)
15117     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15118   QualType RetType = Context.getLValueReferenceType(ArgType);
15119   ArgType = Context.getRValueReferenceType(ArgType);
15120 
15121   bool Constexpr = defaultedSpecialMemberIsConstexpr(
15122       *this, ClassDecl, CXXSpecialMemberKind::MoveAssignment, false);
15123 
15124   //   An implicitly-declared move assignment operator is an inline public
15125   //   member of its class.
15126   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
15127   SourceLocation ClassLoc = ClassDecl->getLocation();
15128   DeclarationNameInfo NameInfo(Name, ClassLoc);
15129   CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
15130       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
15131       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
15132       getCurFPFeatures().isFPConstrained(),
15133       /*isInline=*/true,
15134       Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
15135       SourceLocation());
15136   MoveAssignment->setAccess(AS_public);
15137   MoveAssignment->setDefaulted();
15138   MoveAssignment->setImplicit();
15139 
15140   setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType);
15141 
15142   if (getLangOpts().CUDA)
15143     CUDA().inferTargetForImplicitSpecialMember(
15144         ClassDecl, CXXSpecialMemberKind::MoveAssignment, MoveAssignment,
15145         /* ConstRHS */ false,
15146         /* Diagnose */ false);
15147 
15148   // Add the parameter to the operator.
15149   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
15150                                                ClassLoc, ClassLoc,
15151                                                /*Id=*/nullptr, ArgType,
15152                                                /*TInfo=*/nullptr, SC_None,
15153                                                nullptr);
15154   MoveAssignment->setParams(FromParam);
15155 
15156   MoveAssignment->setTrivial(
15157       ClassDecl->needsOverloadResolutionForMoveAssignment()
15158           ? SpecialMemberIsTrivial(MoveAssignment,
15159                                    CXXSpecialMemberKind::MoveAssignment)
15160           : ClassDecl->hasTrivialMoveAssignment());
15161 
15162   // Note that we have added this copy-assignment operator.
15163   ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
15164 
15165   Scope *S = getScopeForContext(ClassDecl);
15166   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
15167 
15168   if (ShouldDeleteSpecialMember(MoveAssignment,
15169                                 CXXSpecialMemberKind::MoveAssignment)) {
15170     ClassDecl->setImplicitMoveAssignmentIsDeleted();
15171     SetDeclDeleted(MoveAssignment, ClassLoc);
15172   }
15173 
15174   if (S)
15175     PushOnScopeChains(MoveAssignment, S, false);
15176   ClassDecl->addDecl(MoveAssignment);
15177 
15178   return MoveAssignment;
15179 }
15180 
15181 /// Check if we're implicitly defining a move assignment operator for a class
15182 /// with virtual bases. Such a move assignment might move-assign the virtual
15183 /// base multiple times.
15184 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
15185                                                SourceLocation CurrentLocation) {
15186   assert(!Class->isDependentContext() && "should not define dependent move");
15187 
15188   // Only a virtual base could get implicitly move-assigned multiple times.
15189   // Only a non-trivial move assignment can observe this. We only want to
15190   // diagnose if we implicitly define an assignment operator that assigns
15191   // two base classes, both of which move-assign the same virtual base.
15192   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
15193       Class->getNumBases() < 2)
15194     return;
15195 
15196   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
15197   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
15198   VBaseMap VBases;
15199 
15200   for (auto &BI : Class->bases()) {
15201     Worklist.push_back(&BI);
15202     while (!Worklist.empty()) {
15203       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
15204       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
15205 
15206       // If the base has no non-trivial move assignment operators,
15207       // we don't care about moves from it.
15208       if (!Base->hasNonTrivialMoveAssignment())
15209         continue;
15210 
15211       // If there's nothing virtual here, skip it.
15212       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
15213         continue;
15214 
15215       // If we're not actually going to call a move assignment for this base,
15216       // or the selected move assignment is trivial, skip it.
15217       Sema::SpecialMemberOverloadResult SMOR =
15218           S.LookupSpecialMember(Base, CXXSpecialMemberKind::MoveAssignment,
15219                                 /*ConstArg*/ false, /*VolatileArg*/ false,
15220                                 /*RValueThis*/ true, /*ConstThis*/ false,
15221                                 /*VolatileThis*/ false);
15222       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
15223           !SMOR.getMethod()->isMoveAssignmentOperator())
15224         continue;
15225 
15226       if (BaseSpec->isVirtual()) {
15227         // We're going to move-assign this virtual base, and its move
15228         // assignment operator is not trivial. If this can happen for
15229         // multiple distinct direct bases of Class, diagnose it. (If it
15230         // only happens in one base, we'll diagnose it when synthesizing
15231         // that base class's move assignment operator.)
15232         CXXBaseSpecifier *&Existing =
15233             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
15234                 .first->second;
15235         if (Existing && Existing != &BI) {
15236           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
15237             << Class << Base;
15238           S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
15239               << (Base->getCanonicalDecl() ==
15240                   Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15241               << Base << Existing->getType() << Existing->getSourceRange();
15242           S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
15243               << (Base->getCanonicalDecl() ==
15244                   BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15245               << Base << BI.getType() << BaseSpec->getSourceRange();
15246 
15247           // Only diagnose each vbase once.
15248           Existing = nullptr;
15249         }
15250       } else {
15251         // Only walk over bases that have defaulted move assignment operators.
15252         // We assume that any user-provided move assignment operator handles
15253         // the multiple-moves-of-vbase case itself somehow.
15254         if (!SMOR.getMethod()->isDefaulted())
15255           continue;
15256 
15257         // We're going to move the base classes of Base. Add them to the list.
15258         llvm::append_range(Worklist, llvm::make_pointer_range(Base->bases()));
15259       }
15260     }
15261   }
15262 }
15263 
15264 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
15265                                         CXXMethodDecl *MoveAssignOperator) {
15266   assert((MoveAssignOperator->isDefaulted() &&
15267           MoveAssignOperator->isOverloadedOperator() &&
15268           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
15269           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
15270           !MoveAssignOperator->isDeleted()) &&
15271          "DefineImplicitMoveAssignment called for wrong function");
15272   if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
15273     return;
15274 
15275   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
15276   if (ClassDecl->isInvalidDecl()) {
15277     MoveAssignOperator->setInvalidDecl();
15278     return;
15279   }
15280 
15281   // C++0x [class.copy]p28:
15282   //   The implicitly-defined or move assignment operator for a non-union class
15283   //   X performs memberwise move assignment of its subobjects. The direct base
15284   //   classes of X are assigned first, in the order of their declaration in the
15285   //   base-specifier-list, and then the immediate non-static data members of X
15286   //   are assigned, in the order in which they were declared in the class
15287   //   definition.
15288 
15289   // Issue a warning if our implicit move assignment operator will move
15290   // from a virtual base more than once.
15291   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
15292 
15293   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
15294 
15295   // The exception specification is needed because we are defining the
15296   // function.
15297   ResolveExceptionSpec(CurrentLocation,
15298                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
15299 
15300   // Add a context note for diagnostics produced after this point.
15301   Scope.addContextNote(CurrentLocation);
15302 
15303   // The statements that form the synthesized function body.
15304   SmallVector<Stmt*, 8> Statements;
15305 
15306   // The parameter for the "other" object, which we are move from.
15307   ParmVarDecl *Other = MoveAssignOperator->getNonObjectParameter(0);
15308   QualType OtherRefType =
15309       Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
15310 
15311   // Our location for everything implicitly-generated.
15312   SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
15313                            ? MoveAssignOperator->getEndLoc()
15314                            : MoveAssignOperator->getLocation();
15315 
15316   // Builds a reference to the "other" object.
15317   RefBuilder OtherRef(Other, OtherRefType);
15318   // Cast to rvalue.
15319   MoveCastBuilder MoveOther(OtherRef);
15320 
15321   // Builds the function object parameter.
15322   std::optional<ThisBuilder> This;
15323   std::optional<DerefBuilder> DerefThis;
15324   std::optional<RefBuilder> ExplicitObject;
15325   QualType ObjectType;
15326   if (MoveAssignOperator->isExplicitObjectMemberFunction()) {
15327     ObjectType = MoveAssignOperator->getParamDecl(0)->getType();
15328     if (ObjectType->isReferenceType())
15329       ObjectType = ObjectType->getPointeeType();
15330     ExplicitObject.emplace(MoveAssignOperator->getParamDecl(0), ObjectType);
15331   } else {
15332     ObjectType = getCurrentThisType();
15333     This.emplace();
15334     DerefThis.emplace(*This);
15335   }
15336   ExprBuilder &ObjectParameter =
15337       ExplicitObject ? *ExplicitObject : static_cast<ExprBuilder &>(*This);
15338 
15339   // Assign base classes.
15340   bool Invalid = false;
15341   for (auto &Base : ClassDecl->bases()) {
15342     // C++11 [class.copy]p28:
15343     //   It is unspecified whether subobjects representing virtual base classes
15344     //   are assigned more than once by the implicitly-defined copy assignment
15345     //   operator.
15346     // FIXME: Do not assign to a vbase that will be assigned by some other base
15347     // class. For a move-assignment, this can result in the vbase being moved
15348     // multiple times.
15349 
15350     // Form the assignment:
15351     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
15352     QualType BaseType = Base.getType().getUnqualifiedType();
15353     if (!BaseType->isRecordType()) {
15354       Invalid = true;
15355       continue;
15356     }
15357 
15358     CXXCastPath BasePath;
15359     BasePath.push_back(&Base);
15360 
15361     // Construct the "from" expression, which is an implicit cast to the
15362     // appropriately-qualified base type.
15363     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
15364 
15365     // Implicitly cast "this" to the appropriately-qualified base type.
15366     // Dereference "this".
15367     CastBuilder To(
15368         ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15369                        : static_cast<ExprBuilder &>(*DerefThis),
15370         Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),
15371         VK_LValue, BasePath);
15372 
15373     // Build the move.
15374     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
15375                                             To, From,
15376                                             /*CopyingBaseSubobject=*/true,
15377                                             /*Copying=*/false);
15378     if (Move.isInvalid()) {
15379       MoveAssignOperator->setInvalidDecl();
15380       return;
15381     }
15382 
15383     // Success! Record the move.
15384     Statements.push_back(Move.getAs<Expr>());
15385   }
15386 
15387   // Assign non-static members.
15388   for (auto *Field : ClassDecl->fields()) {
15389     // FIXME: We should form some kind of AST representation for the implied
15390     // memcpy in a union copy operation.
15391     if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15392       continue;
15393 
15394     if (Field->isInvalidDecl()) {
15395       Invalid = true;
15396       continue;
15397     }
15398 
15399     // Check for members of reference type; we can't move those.
15400     if (Field->getType()->isReferenceType()) {
15401       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15402         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
15403       Diag(Field->getLocation(), diag::note_declared_at);
15404       Invalid = true;
15405       continue;
15406     }
15407 
15408     // Check for members of const-qualified, non-class type.
15409     QualType BaseType = Context.getBaseElementType(Field->getType());
15410     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
15411       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15412         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
15413       Diag(Field->getLocation(), diag::note_declared_at);
15414       Invalid = true;
15415       continue;
15416     }
15417 
15418     // Suppress assigning zero-width bitfields.
15419     if (Field->isZeroLengthBitField(Context))
15420       continue;
15421 
15422     QualType FieldType = Field->getType().getNonReferenceType();
15423     if (FieldType->isIncompleteArrayType()) {
15424       assert(ClassDecl->hasFlexibleArrayMember() &&
15425              "Incomplete array type is not valid");
15426       continue;
15427     }
15428 
15429     // Build references to the field in the object we're copying from and to.
15430     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15431                               LookupMemberName);
15432     MemberLookup.addDecl(Field);
15433     MemberLookup.resolveKind();
15434     MemberBuilder From(MoveOther, OtherRefType,
15435                        /*IsArrow=*/false, MemberLookup);
15436     MemberBuilder To(ObjectParameter, ObjectType, /*IsArrow=*/!ExplicitObject,
15437                      MemberLookup);
15438 
15439     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
15440         "Member reference with rvalue base must be rvalue except for reference "
15441         "members, which aren't allowed for move assignment.");
15442 
15443     // Build the move of this field.
15444     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
15445                                             To, From,
15446                                             /*CopyingBaseSubobject=*/false,
15447                                             /*Copying=*/false);
15448     if (Move.isInvalid()) {
15449       MoveAssignOperator->setInvalidDecl();
15450       return;
15451     }
15452 
15453     // Success! Record the copy.
15454     Statements.push_back(Move.getAs<Stmt>());
15455   }
15456 
15457   if (!Invalid) {
15458     // Add a "return *this;"
15459     Expr *ThisExpr =
15460         (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15461                         : static_cast<ExprBuilder &>(*DerefThis))
15462             .build(*this, Loc);
15463 
15464     StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
15465     if (Return.isInvalid())
15466       Invalid = true;
15467     else
15468       Statements.push_back(Return.getAs<Stmt>());
15469   }
15470 
15471   if (Invalid) {
15472     MoveAssignOperator->setInvalidDecl();
15473     return;
15474   }
15475 
15476   StmtResult Body;
15477   {
15478     CompoundScopeRAII CompoundScope(*this);
15479     Body = ActOnCompoundStmt(Loc, Loc, Statements,
15480                              /*isStmtExpr=*/false);
15481     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15482   }
15483   MoveAssignOperator->setBody(Body.getAs<Stmt>());
15484   MoveAssignOperator->markUsed(Context);
15485 
15486   if (ASTMutationListener *L = getASTMutationListener()) {
15487     L->CompletedImplicitDefinition(MoveAssignOperator);
15488   }
15489 }
15490 
15491 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
15492                                                     CXXRecordDecl *ClassDecl) {
15493   // C++ [class.copy]p4:
15494   //   If the class definition does not explicitly declare a copy
15495   //   constructor, one is declared implicitly.
15496   assert(ClassDecl->needsImplicitCopyConstructor());
15497 
15498   DeclaringSpecialMember DSM(*this, ClassDecl,
15499                              CXXSpecialMemberKind::CopyConstructor);
15500   if (DSM.isAlreadyBeingDeclared())
15501     return nullptr;
15502 
15503   QualType ClassType = Context.getTypeDeclType(ClassDecl);
15504   QualType ArgType = ClassType;
15505   ArgType = Context.getElaboratedType(ElaboratedTypeKeyword::None, nullptr,
15506                                       ArgType, nullptr);
15507   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
15508   if (Const)
15509     ArgType = ArgType.withConst();
15510 
15511   LangAS AS = getDefaultCXXMethodAddrSpace();
15512   if (AS != LangAS::Default)
15513     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15514 
15515   ArgType = Context.getLValueReferenceType(ArgType);
15516 
15517   bool Constexpr = defaultedSpecialMemberIsConstexpr(
15518       *this, ClassDecl, CXXSpecialMemberKind::CopyConstructor, Const);
15519 
15520   DeclarationName Name
15521     = Context.DeclarationNames.getCXXConstructorName(
15522                                            Context.getCanonicalType(ClassType));
15523   SourceLocation ClassLoc = ClassDecl->getLocation();
15524   DeclarationNameInfo NameInfo(Name, ClassLoc);
15525 
15526   //   An implicitly-declared copy constructor is an inline public
15527   //   member of its class.
15528   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
15529       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15530       ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15531       /*isInline=*/true,
15532       /*isImplicitlyDeclared=*/true,
15533       Constexpr ? ConstexprSpecKind::Constexpr
15534                 : ConstexprSpecKind::Unspecified);
15535   CopyConstructor->setAccess(AS_public);
15536   CopyConstructor->setDefaulted();
15537 
15538   setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
15539 
15540   if (getLangOpts().CUDA)
15541     CUDA().inferTargetForImplicitSpecialMember(
15542         ClassDecl, CXXSpecialMemberKind::CopyConstructor, CopyConstructor,
15543         /* ConstRHS */ Const,
15544         /* Diagnose */ false);
15545 
15546   // During template instantiation of special member functions we need a
15547   // reliable TypeSourceInfo for the parameter types in order to allow functions
15548   // to be substituted.
15549   TypeSourceInfo *TSI = nullptr;
15550   if (inTemplateInstantiation() && ClassDecl->isLambda())
15551     TSI = Context.getTrivialTypeSourceInfo(ArgType);
15552 
15553   // Add the parameter to the constructor.
15554   ParmVarDecl *FromParam =
15555       ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc,
15556                           /*IdentifierInfo=*/nullptr, ArgType,
15557                           /*TInfo=*/TSI, SC_None, nullptr);
15558   CopyConstructor->setParams(FromParam);
15559 
15560   CopyConstructor->setTrivial(
15561       ClassDecl->needsOverloadResolutionForCopyConstructor()
15562           ? SpecialMemberIsTrivial(CopyConstructor,
15563                                    CXXSpecialMemberKind::CopyConstructor)
15564           : ClassDecl->hasTrivialCopyConstructor());
15565 
15566   CopyConstructor->setTrivialForCall(
15567       ClassDecl->hasAttr<TrivialABIAttr>() ||
15568       (ClassDecl->needsOverloadResolutionForCopyConstructor()
15569            ? SpecialMemberIsTrivial(CopyConstructor,
15570                                     CXXSpecialMemberKind::CopyConstructor,
15571                                     TAH_ConsiderTrivialABI)
15572            : ClassDecl->hasTrivialCopyConstructorForCall()));
15573 
15574   // Note that we have declared this constructor.
15575   ++getASTContext().NumImplicitCopyConstructorsDeclared;
15576 
15577   Scope *S = getScopeForContext(ClassDecl);
15578   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
15579 
15580   if (ShouldDeleteSpecialMember(CopyConstructor,
15581                                 CXXSpecialMemberKind::CopyConstructor)) {
15582     ClassDecl->setImplicitCopyConstructorIsDeleted();
15583     SetDeclDeleted(CopyConstructor, ClassLoc);
15584   }
15585 
15586   if (S)
15587     PushOnScopeChains(CopyConstructor, S, false);
15588   ClassDecl->addDecl(CopyConstructor);
15589 
15590   return CopyConstructor;
15591 }
15592 
15593 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
15594                                          CXXConstructorDecl *CopyConstructor) {
15595   assert((CopyConstructor->isDefaulted() &&
15596           CopyConstructor->isCopyConstructor() &&
15597           !CopyConstructor->doesThisDeclarationHaveABody() &&
15598           !CopyConstructor->isDeleted()) &&
15599          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
15600   if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
15601     return;
15602 
15603   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
15604   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
15605 
15606   SynthesizedFunctionScope Scope(*this, CopyConstructor);
15607 
15608   // The exception specification is needed because we are defining the
15609   // function.
15610   ResolveExceptionSpec(CurrentLocation,
15611                        CopyConstructor->getType()->castAs<FunctionProtoType>());
15612   MarkVTableUsed(CurrentLocation, ClassDecl);
15613 
15614   // Add a context note for diagnostics produced after this point.
15615   Scope.addContextNote(CurrentLocation);
15616 
15617   // C++11 [class.copy]p7:
15618   //   The [definition of an implicitly declared copy constructor] is
15619   //   deprecated if the class has a user-declared copy assignment operator
15620   //   or a user-declared destructor.
15621   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
15622     diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
15623 
15624   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
15625     CopyConstructor->setInvalidDecl();
15626   }  else {
15627     SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
15628                              ? CopyConstructor->getEndLoc()
15629                              : CopyConstructor->getLocation();
15630     Sema::CompoundScopeRAII CompoundScope(*this);
15631     CopyConstructor->setBody(
15632         ActOnCompoundStmt(Loc, Loc, std::nullopt, /*isStmtExpr=*/false)
15633             .getAs<Stmt>());
15634     CopyConstructor->markUsed(Context);
15635   }
15636 
15637   if (ASTMutationListener *L = getASTMutationListener()) {
15638     L->CompletedImplicitDefinition(CopyConstructor);
15639   }
15640 }
15641 
15642 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
15643                                                     CXXRecordDecl *ClassDecl) {
15644   assert(ClassDecl->needsImplicitMoveConstructor());
15645 
15646   DeclaringSpecialMember DSM(*this, ClassDecl,
15647                              CXXSpecialMemberKind::MoveConstructor);
15648   if (DSM.isAlreadyBeingDeclared())
15649     return nullptr;
15650 
15651   QualType ClassType = Context.getTypeDeclType(ClassDecl);
15652 
15653   QualType ArgType = ClassType;
15654   ArgType = Context.getElaboratedType(ElaboratedTypeKeyword::None, nullptr,
15655                                       ArgType, nullptr);
15656   LangAS AS = getDefaultCXXMethodAddrSpace();
15657   if (AS != LangAS::Default)
15658     ArgType = Context.getAddrSpaceQualType(ClassType, AS);
15659   ArgType = Context.getRValueReferenceType(ArgType);
15660 
15661   bool Constexpr = defaultedSpecialMemberIsConstexpr(
15662       *this, ClassDecl, CXXSpecialMemberKind::MoveConstructor, false);
15663 
15664   DeclarationName Name
15665     = Context.DeclarationNames.getCXXConstructorName(
15666                                            Context.getCanonicalType(ClassType));
15667   SourceLocation ClassLoc = ClassDecl->getLocation();
15668   DeclarationNameInfo NameInfo(Name, ClassLoc);
15669 
15670   // C++11 [class.copy]p11:
15671   //   An implicitly-declared copy/move constructor is an inline public
15672   //   member of its class.
15673   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
15674       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15675       ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15676       /*isInline=*/true,
15677       /*isImplicitlyDeclared=*/true,
15678       Constexpr ? ConstexprSpecKind::Constexpr
15679                 : ConstexprSpecKind::Unspecified);
15680   MoveConstructor->setAccess(AS_public);
15681   MoveConstructor->setDefaulted();
15682 
15683   setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
15684 
15685   if (getLangOpts().CUDA)
15686     CUDA().inferTargetForImplicitSpecialMember(
15687         ClassDecl, CXXSpecialMemberKind::MoveConstructor, MoveConstructor,
15688         /* ConstRHS */ false,
15689         /* Diagnose */ false);
15690 
15691   // Add the parameter to the constructor.
15692   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
15693                                                ClassLoc, ClassLoc,
15694                                                /*IdentifierInfo=*/nullptr,
15695                                                ArgType, /*TInfo=*/nullptr,
15696                                                SC_None, nullptr);
15697   MoveConstructor->setParams(FromParam);
15698 
15699   MoveConstructor->setTrivial(
15700       ClassDecl->needsOverloadResolutionForMoveConstructor()
15701           ? SpecialMemberIsTrivial(MoveConstructor,
15702                                    CXXSpecialMemberKind::MoveConstructor)
15703           : ClassDecl->hasTrivialMoveConstructor());
15704 
15705   MoveConstructor->setTrivialForCall(
15706       ClassDecl->hasAttr<TrivialABIAttr>() ||
15707       (ClassDecl->needsOverloadResolutionForMoveConstructor()
15708            ? SpecialMemberIsTrivial(MoveConstructor,
15709                                     CXXSpecialMemberKind::MoveConstructor,
15710                                     TAH_ConsiderTrivialABI)
15711            : ClassDecl->hasTrivialMoveConstructorForCall()));
15712 
15713   // Note that we have declared this constructor.
15714   ++getASTContext().NumImplicitMoveConstructorsDeclared;
15715 
15716   Scope *S = getScopeForContext(ClassDecl);
15717   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
15718 
15719   if (ShouldDeleteSpecialMember(MoveConstructor,
15720                                 CXXSpecialMemberKind::MoveConstructor)) {
15721     ClassDecl->setImplicitMoveConstructorIsDeleted();
15722     SetDeclDeleted(MoveConstructor, ClassLoc);
15723   }
15724 
15725   if (S)
15726     PushOnScopeChains(MoveConstructor, S, false);
15727   ClassDecl->addDecl(MoveConstructor);
15728 
15729   return MoveConstructor;
15730 }
15731 
15732 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
15733                                          CXXConstructorDecl *MoveConstructor) {
15734   assert((MoveConstructor->isDefaulted() &&
15735           MoveConstructor->isMoveConstructor() &&
15736           !MoveConstructor->doesThisDeclarationHaveABody() &&
15737           !MoveConstructor->isDeleted()) &&
15738          "DefineImplicitMoveConstructor - call it for implicit move ctor");
15739   if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
15740     return;
15741 
15742   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
15743   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
15744 
15745   SynthesizedFunctionScope Scope(*this, MoveConstructor);
15746 
15747   // The exception specification is needed because we are defining the
15748   // function.
15749   ResolveExceptionSpec(CurrentLocation,
15750                        MoveConstructor->getType()->castAs<FunctionProtoType>());
15751   MarkVTableUsed(CurrentLocation, ClassDecl);
15752 
15753   // Add a context note for diagnostics produced after this point.
15754   Scope.addContextNote(CurrentLocation);
15755 
15756   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
15757     MoveConstructor->setInvalidDecl();
15758   } else {
15759     SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
15760                              ? MoveConstructor->getEndLoc()
15761                              : MoveConstructor->getLocation();
15762     Sema::CompoundScopeRAII CompoundScope(*this);
15763     MoveConstructor->setBody(
15764         ActOnCompoundStmt(Loc, Loc, std::nullopt, /*isStmtExpr=*/false)
15765             .getAs<Stmt>());
15766     MoveConstructor->markUsed(Context);
15767   }
15768 
15769   if (ASTMutationListener *L = getASTMutationListener()) {
15770     L->CompletedImplicitDefinition(MoveConstructor);
15771   }
15772 }
15773 
15774 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
15775   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
15776 }
15777 
15778 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
15779                             SourceLocation CurrentLocation,
15780                             CXXConversionDecl *Conv) {
15781   SynthesizedFunctionScope Scope(*this, Conv);
15782   assert(!Conv->getReturnType()->isUndeducedType());
15783 
15784   QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
15785   CallingConv CC =
15786       ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
15787 
15788   CXXRecordDecl *Lambda = Conv->getParent();
15789   FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
15790   FunctionDecl *Invoker =
15791       CallOp->hasCXXExplicitFunctionObjectParameter() || CallOp->isStatic()
15792           ? CallOp
15793           : Lambda->getLambdaStaticInvoker(CC);
15794 
15795   if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
15796     CallOp = InstantiateFunctionDeclaration(
15797         CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
15798     if (!CallOp)
15799       return;
15800 
15801     if (CallOp != Invoker) {
15802       Invoker = InstantiateFunctionDeclaration(
15803           Invoker->getDescribedFunctionTemplate(), TemplateArgs,
15804           CurrentLocation);
15805       if (!Invoker)
15806         return;
15807     }
15808   }
15809 
15810   if (CallOp->isInvalidDecl())
15811     return;
15812 
15813   // Mark the call operator referenced (and add to pending instantiations
15814   // if necessary).
15815   // For both the conversion and static-invoker template specializations
15816   // we construct their body's in this function, so no need to add them
15817   // to the PendingInstantiations.
15818   MarkFunctionReferenced(CurrentLocation, CallOp);
15819 
15820   if (Invoker != CallOp) {
15821     // Fill in the __invoke function with a dummy implementation. IR generation
15822     // will fill in the actual details. Update its type in case it contained
15823     // an 'auto'.
15824     Invoker->markUsed(Context);
15825     Invoker->setReferenced();
15826     Invoker->setType(Conv->getReturnType()->getPointeeType());
15827     Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
15828   }
15829 
15830   // Construct the body of the conversion function { return __invoke; }.
15831   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), VK_LValue,
15832                                        Conv->getLocation());
15833   assert(FunctionRef && "Can't refer to __invoke function?");
15834   Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
15835   Conv->setBody(CompoundStmt::Create(Context, Return, FPOptionsOverride(),
15836                                      Conv->getLocation(), Conv->getLocation()));
15837   Conv->markUsed(Context);
15838   Conv->setReferenced();
15839 
15840   if (ASTMutationListener *L = getASTMutationListener()) {
15841     L->CompletedImplicitDefinition(Conv);
15842     if (Invoker != CallOp)
15843       L->CompletedImplicitDefinition(Invoker);
15844   }
15845 }
15846 
15847 void Sema::DefineImplicitLambdaToBlockPointerConversion(
15848     SourceLocation CurrentLocation, CXXConversionDecl *Conv) {
15849   assert(!Conv->getParent()->isGenericLambda());
15850 
15851   SynthesizedFunctionScope Scope(*this, Conv);
15852 
15853   // Copy-initialize the lambda object as needed to capture it.
15854   Expr *This = ActOnCXXThis(CurrentLocation).get();
15855   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
15856 
15857   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
15858                                                         Conv->getLocation(),
15859                                                         Conv, DerefThis);
15860 
15861   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
15862   // behavior.  Note that only the general conversion function does this
15863   // (since it's unusable otherwise); in the case where we inline the
15864   // block literal, it has block literal lifetime semantics.
15865   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
15866     BuildBlock = ImplicitCastExpr::Create(
15867         Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
15868         BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride());
15869 
15870   if (BuildBlock.isInvalid()) {
15871     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15872     Conv->setInvalidDecl();
15873     return;
15874   }
15875 
15876   // Create the return statement that returns the block from the conversion
15877   // function.
15878   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
15879   if (Return.isInvalid()) {
15880     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15881     Conv->setInvalidDecl();
15882     return;
15883   }
15884 
15885   // Set the body of the conversion function.
15886   Stmt *ReturnS = Return.get();
15887   Conv->setBody(CompoundStmt::Create(Context, ReturnS, FPOptionsOverride(),
15888                                      Conv->getLocation(), Conv->getLocation()));
15889   Conv->markUsed(Context);
15890 
15891   // We're done; notify the mutation listener, if any.
15892   if (ASTMutationListener *L = getASTMutationListener()) {
15893     L->CompletedImplicitDefinition(Conv);
15894   }
15895 }
15896 
15897 /// Determine whether the given list arguments contains exactly one
15898 /// "real" (non-default) argument.
15899 static bool hasOneRealArgument(MultiExprArg Args) {
15900   switch (Args.size()) {
15901   case 0:
15902     return false;
15903 
15904   default:
15905     if (!Args[1]->isDefaultArgument())
15906       return false;
15907 
15908     [[fallthrough]];
15909   case 1:
15910     return !Args[0]->isDefaultArgument();
15911   }
15912 
15913   return false;
15914 }
15915 
15916 ExprResult Sema::BuildCXXConstructExpr(
15917     SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
15918     CXXConstructorDecl *Constructor, MultiExprArg ExprArgs,
15919     bool HadMultipleCandidates, bool IsListInitialization,
15920     bool IsStdInitListInitialization, bool RequiresZeroInit,
15921     CXXConstructionKind ConstructKind, SourceRange ParenRange) {
15922   bool Elidable = false;
15923 
15924   // C++0x [class.copy]p34:
15925   //   When certain criteria are met, an implementation is allowed to
15926   //   omit the copy/move construction of a class object, even if the
15927   //   copy/move constructor and/or destructor for the object have
15928   //   side effects. [...]
15929   //     - when a temporary class object that has not been bound to a
15930   //       reference (12.2) would be copied/moved to a class object
15931   //       with the same cv-unqualified type, the copy/move operation
15932   //       can be omitted by constructing the temporary object
15933   //       directly into the target of the omitted copy/move
15934   if (ConstructKind == CXXConstructionKind::Complete && Constructor &&
15935       // FIXME: Converting constructors should also be accepted.
15936       // But to fix this, the logic that digs down into a CXXConstructExpr
15937       // to find the source object needs to handle it.
15938       // Right now it assumes the source object is passed directly as the
15939       // first argument.
15940       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
15941     Expr *SubExpr = ExprArgs[0];
15942     // FIXME: Per above, this is also incorrect if we want to accept
15943     //        converting constructors, as isTemporaryObject will
15944     //        reject temporaries with different type from the
15945     //        CXXRecord itself.
15946     Elidable = SubExpr->isTemporaryObject(
15947         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
15948   }
15949 
15950   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
15951                                FoundDecl, Constructor,
15952                                Elidable, ExprArgs, HadMultipleCandidates,
15953                                IsListInitialization,
15954                                IsStdInitListInitialization, RequiresZeroInit,
15955                                ConstructKind, ParenRange);
15956 }
15957 
15958 ExprResult Sema::BuildCXXConstructExpr(
15959     SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
15960     CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
15961     bool HadMultipleCandidates, bool IsListInitialization,
15962     bool IsStdInitListInitialization, bool RequiresZeroInit,
15963     CXXConstructionKind ConstructKind, SourceRange ParenRange) {
15964   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
15965     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
15966     // The only way to get here is if we did overload resolution to find the
15967     // shadow decl, so we don't need to worry about re-checking the trailing
15968     // requires clause.
15969     if (DiagnoseUseOfOverloadedDecl(Constructor, ConstructLoc))
15970       return ExprError();
15971   }
15972 
15973   return BuildCXXConstructExpr(
15974       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
15975       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
15976       RequiresZeroInit, ConstructKind, ParenRange);
15977 }
15978 
15979 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
15980 /// including handling of its default argument expressions.
15981 ExprResult Sema::BuildCXXConstructExpr(
15982     SourceLocation ConstructLoc, QualType DeclInitType,
15983     CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
15984     bool HadMultipleCandidates, bool IsListInitialization,
15985     bool IsStdInitListInitialization, bool RequiresZeroInit,
15986     CXXConstructionKind ConstructKind, SourceRange ParenRange) {
15987   assert(declaresSameEntity(
15988              Constructor->getParent(),
15989              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
15990          "given constructor for wrong type");
15991   MarkFunctionReferenced(ConstructLoc, Constructor);
15992   if (getLangOpts().CUDA && !CUDA().CheckCall(ConstructLoc, Constructor))
15993     return ExprError();
15994 
15995   return CheckForImmediateInvocation(
15996       CXXConstructExpr::Create(
15997           Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
15998           HadMultipleCandidates, IsListInitialization,
15999           IsStdInitListInitialization, RequiresZeroInit,
16000           static_cast<CXXConstructionKind>(ConstructKind), ParenRange),
16001       Constructor);
16002 }
16003 
16004 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
16005   if (VD->isInvalidDecl()) return;
16006   // If initializing the variable failed, don't also diagnose problems with
16007   // the destructor, they're likely related.
16008   if (VD->getInit() && VD->getInit()->containsErrors())
16009     return;
16010 
16011   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
16012   if (ClassDecl->isInvalidDecl()) return;
16013   if (ClassDecl->hasIrrelevantDestructor()) return;
16014   if (ClassDecl->isDependentContext()) return;
16015 
16016   if (VD->isNoDestroy(getASTContext()))
16017     return;
16018 
16019   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
16020   // The result of `LookupDestructor` might be nullptr if the destructor is
16021   // invalid, in which case it is marked as `IneligibleOrNotSelected` and
16022   // will not be selected by `CXXRecordDecl::getDestructor()`.
16023   if (!Destructor)
16024     return;
16025   // If this is an array, we'll require the destructor during initialization, so
16026   // we can skip over this. We still want to emit exit-time destructor warnings
16027   // though.
16028   if (!VD->getType()->isArrayType()) {
16029     MarkFunctionReferenced(VD->getLocation(), Destructor);
16030     CheckDestructorAccess(VD->getLocation(), Destructor,
16031                           PDiag(diag::err_access_dtor_var)
16032                               << VD->getDeclName() << VD->getType());
16033     DiagnoseUseOfDecl(Destructor, VD->getLocation());
16034   }
16035 
16036   if (Destructor->isTrivial()) return;
16037 
16038   // If the destructor is constexpr, check whether the variable has constant
16039   // destruction now.
16040   if (Destructor->isConstexpr()) {
16041     bool HasConstantInit = false;
16042     if (VD->getInit() && !VD->getInit()->isValueDependent())
16043       HasConstantInit = VD->evaluateValue();
16044     SmallVector<PartialDiagnosticAt, 8> Notes;
16045     if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
16046         HasConstantInit) {
16047       Diag(VD->getLocation(),
16048            diag::err_constexpr_var_requires_const_destruction) << VD;
16049       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
16050         Diag(Notes[I].first, Notes[I].second);
16051     }
16052   }
16053 
16054   if (!VD->hasGlobalStorage() || !VD->needsDestruction(Context))
16055     return;
16056 
16057   // Emit warning for non-trivial dtor in global scope (a real global,
16058   // class-static, function-static).
16059   if (!VD->hasAttr<AlwaysDestroyAttr>())
16060     Diag(VD->getLocation(), diag::warn_exit_time_destructor);
16061 
16062   // TODO: this should be re-enabled for static locals by !CXAAtExit
16063   if (!VD->isStaticLocal())
16064     Diag(VD->getLocation(), diag::warn_global_destructor);
16065 }
16066 
16067 bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
16068                                    QualType DeclInitType, MultiExprArg ArgsPtr,
16069                                    SourceLocation Loc,
16070                                    SmallVectorImpl<Expr *> &ConvertedArgs,
16071                                    bool AllowExplicit,
16072                                    bool IsListInitialization) {
16073   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
16074   unsigned NumArgs = ArgsPtr.size();
16075   Expr **Args = ArgsPtr.data();
16076 
16077   const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
16078   unsigned NumParams = Proto->getNumParams();
16079 
16080   // If too few arguments are available, we'll fill in the rest with defaults.
16081   if (NumArgs < NumParams)
16082     ConvertedArgs.reserve(NumParams);
16083   else
16084     ConvertedArgs.reserve(NumArgs);
16085 
16086   VariadicCallType CallType =
16087     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
16088   SmallVector<Expr *, 8> AllArgs;
16089   bool Invalid = GatherArgumentsForCall(
16090       Loc, Constructor, Proto, 0, llvm::ArrayRef(Args, NumArgs), AllArgs,
16091       CallType, AllowExplicit, IsListInitialization);
16092   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
16093 
16094   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
16095 
16096   CheckConstructorCall(Constructor, DeclInitType,
16097                        llvm::ArrayRef(AllArgs.data(), AllArgs.size()), Proto,
16098                        Loc);
16099 
16100   return Invalid;
16101 }
16102 
16103 static inline bool
16104 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
16105                                        const FunctionDecl *FnDecl) {
16106   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
16107   if (isa<NamespaceDecl>(DC)) {
16108     return SemaRef.Diag(FnDecl->getLocation(),
16109                         diag::err_operator_new_delete_declared_in_namespace)
16110       << FnDecl->getDeclName();
16111   }
16112 
16113   if (isa<TranslationUnitDecl>(DC) &&
16114       FnDecl->getStorageClass() == SC_Static) {
16115     return SemaRef.Diag(FnDecl->getLocation(),
16116                         diag::err_operator_new_delete_declared_static)
16117       << FnDecl->getDeclName();
16118   }
16119 
16120   return false;
16121 }
16122 
16123 static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef,
16124                                              const PointerType *PtrTy) {
16125   auto &Ctx = SemaRef.Context;
16126   Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
16127   PtrQuals.removeAddressSpace();
16128   return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType(
16129       PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
16130 }
16131 
16132 static inline bool
16133 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
16134                             CanQualType ExpectedResultType,
16135                             CanQualType ExpectedFirstParamType,
16136                             unsigned DependentParamTypeDiag,
16137                             unsigned InvalidParamTypeDiag) {
16138   QualType ResultType =
16139       FnDecl->getType()->castAs<FunctionType>()->getReturnType();
16140 
16141   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
16142     // The operator is valid on any address space for OpenCL.
16143     // Drop address space from actual and expected result types.
16144     if (const auto *PtrTy = ResultType->getAs<PointerType>())
16145       ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
16146 
16147     if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>())
16148       ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
16149   }
16150 
16151   // Check that the result type is what we expect.
16152   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) {
16153     // Reject even if the type is dependent; an operator delete function is
16154     // required to have a non-dependent result type.
16155     return SemaRef.Diag(
16156                FnDecl->getLocation(),
16157                ResultType->isDependentType()
16158                    ? diag::err_operator_new_delete_dependent_result_type
16159                    : diag::err_operator_new_delete_invalid_result_type)
16160            << FnDecl->getDeclName() << ExpectedResultType;
16161   }
16162 
16163   // A function template must have at least 2 parameters.
16164   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
16165     return SemaRef.Diag(FnDecl->getLocation(),
16166                       diag::err_operator_new_delete_template_too_few_parameters)
16167         << FnDecl->getDeclName();
16168 
16169   // The function decl must have at least 1 parameter.
16170   if (FnDecl->getNumParams() == 0)
16171     return SemaRef.Diag(FnDecl->getLocation(),
16172                         diag::err_operator_new_delete_too_few_parameters)
16173       << FnDecl->getDeclName();
16174 
16175   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
16176   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
16177     // The operator is valid on any address space for OpenCL.
16178     // Drop address space from actual and expected first parameter types.
16179     if (const auto *PtrTy =
16180             FnDecl->getParamDecl(0)->getType()->getAs<PointerType>())
16181       FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
16182 
16183     if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>())
16184       ExpectedFirstParamType =
16185           RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
16186   }
16187 
16188   // Check that the first parameter type is what we expect.
16189   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
16190       ExpectedFirstParamType) {
16191     // The first parameter type is not allowed to be dependent. As a tentative
16192     // DR resolution, we allow a dependent parameter type if it is the right
16193     // type anyway, to allow destroying operator delete in class templates.
16194     return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType()
16195                                                    ? DependentParamTypeDiag
16196                                                    : InvalidParamTypeDiag)
16197            << FnDecl->getDeclName() << ExpectedFirstParamType;
16198   }
16199 
16200   return false;
16201 }
16202 
16203 static bool
16204 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
16205   // C++ [basic.stc.dynamic.allocation]p1:
16206   //   A program is ill-formed if an allocation function is declared in a
16207   //   namespace scope other than global scope or declared static in global
16208   //   scope.
16209   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16210     return true;
16211 
16212   CanQualType SizeTy =
16213     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
16214 
16215   // C++ [basic.stc.dynamic.allocation]p1:
16216   //  The return type shall be void*. The first parameter shall have type
16217   //  std::size_t.
16218   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
16219                                   SizeTy,
16220                                   diag::err_operator_new_dependent_param_type,
16221                                   diag::err_operator_new_param_type))
16222     return true;
16223 
16224   // C++ [basic.stc.dynamic.allocation]p1:
16225   //  The first parameter shall not have an associated default argument.
16226   if (FnDecl->getParamDecl(0)->hasDefaultArg())
16227     return SemaRef.Diag(FnDecl->getLocation(),
16228                         diag::err_operator_new_default_arg)
16229       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
16230 
16231   return false;
16232 }
16233 
16234 static bool
16235 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
16236   // C++ [basic.stc.dynamic.deallocation]p1:
16237   //   A program is ill-formed if deallocation functions are declared in a
16238   //   namespace scope other than global scope or declared static in global
16239   //   scope.
16240   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16241     return true;
16242 
16243   auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
16244 
16245   // C++ P0722:
16246   //   Within a class C, the first parameter of a destroying operator delete
16247   //   shall be of type C *. The first parameter of any other deallocation
16248   //   function shall be of type void *.
16249   CanQualType ExpectedFirstParamType =
16250       MD && MD->isDestroyingOperatorDelete()
16251           ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
16252                 SemaRef.Context.getRecordType(MD->getParent())))
16253           : SemaRef.Context.VoidPtrTy;
16254 
16255   // C++ [basic.stc.dynamic.deallocation]p2:
16256   //   Each deallocation function shall return void
16257   if (CheckOperatorNewDeleteTypes(
16258           SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
16259           diag::err_operator_delete_dependent_param_type,
16260           diag::err_operator_delete_param_type))
16261     return true;
16262 
16263   // C++ P0722:
16264   //   A destroying operator delete shall be a usual deallocation function.
16265   if (MD && !MD->getParent()->isDependentContext() &&
16266       MD->isDestroyingOperatorDelete() &&
16267       !SemaRef.isUsualDeallocationFunction(MD)) {
16268     SemaRef.Diag(MD->getLocation(),
16269                  diag::err_destroying_operator_delete_not_usual);
16270     return true;
16271   }
16272 
16273   return false;
16274 }
16275 
16276 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
16277   assert(FnDecl && FnDecl->isOverloadedOperator() &&
16278          "Expected an overloaded operator declaration");
16279 
16280   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
16281 
16282   // C++ [over.oper]p5:
16283   //   The allocation and deallocation functions, operator new,
16284   //   operator new[], operator delete and operator delete[], are
16285   //   described completely in 3.7.3. The attributes and restrictions
16286   //   found in the rest of this subclause do not apply to them unless
16287   //   explicitly stated in 3.7.3.
16288   if (Op == OO_Delete || Op == OO_Array_Delete)
16289     return CheckOperatorDeleteDeclaration(*this, FnDecl);
16290 
16291   if (Op == OO_New || Op == OO_Array_New)
16292     return CheckOperatorNewDeclaration(*this, FnDecl);
16293 
16294   // C++ [over.oper]p7:
16295   //   An operator function shall either be a member function or
16296   //   be a non-member function and have at least one parameter
16297   //   whose type is a class, a reference to a class, an enumeration,
16298   //   or a reference to an enumeration.
16299   // Note: Before C++23, a member function could not be static. The only member
16300   //       function allowed to be static is the call operator function.
16301   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
16302     if (MethodDecl->isStatic()) {
16303       if (Op == OO_Call || Op == OO_Subscript)
16304         Diag(FnDecl->getLocation(),
16305              (LangOpts.CPlusPlus23
16306                   ? diag::warn_cxx20_compat_operator_overload_static
16307                   : diag::ext_operator_overload_static))
16308             << FnDecl;
16309       else
16310         return Diag(FnDecl->getLocation(), diag::err_operator_overload_static)
16311                << FnDecl;
16312     }
16313   } else {
16314     bool ClassOrEnumParam = false;
16315     for (auto *Param : FnDecl->parameters()) {
16316       QualType ParamType = Param->getType().getNonReferenceType();
16317       if (ParamType->isDependentType() || ParamType->isRecordType() ||
16318           ParamType->isEnumeralType()) {
16319         ClassOrEnumParam = true;
16320         break;
16321       }
16322     }
16323 
16324     if (!ClassOrEnumParam)
16325       return Diag(FnDecl->getLocation(),
16326                   diag::err_operator_overload_needs_class_or_enum)
16327         << FnDecl->getDeclName();
16328   }
16329 
16330   // C++ [over.oper]p8:
16331   //   An operator function cannot have default arguments (8.3.6),
16332   //   except where explicitly stated below.
16333   //
16334   // Only the function-call operator (C++ [over.call]p1) and the subscript
16335   // operator (CWG2507) allow default arguments.
16336   if (Op != OO_Call) {
16337     ParmVarDecl *FirstDefaultedParam = nullptr;
16338     for (auto *Param : FnDecl->parameters()) {
16339       if (Param->hasDefaultArg()) {
16340         FirstDefaultedParam = Param;
16341         break;
16342       }
16343     }
16344     if (FirstDefaultedParam) {
16345       if (Op == OO_Subscript) {
16346         Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
16347                                         ? diag::ext_subscript_overload
16348                                         : diag::error_subscript_overload)
16349             << FnDecl->getDeclName() << 1
16350             << FirstDefaultedParam->getDefaultArgRange();
16351       } else {
16352         return Diag(FirstDefaultedParam->getLocation(),
16353                     diag::err_operator_overload_default_arg)
16354                << FnDecl->getDeclName()
16355                << FirstDefaultedParam->getDefaultArgRange();
16356       }
16357     }
16358   }
16359 
16360   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
16361     { false, false, false }
16362 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
16363     , { Unary, Binary, MemberOnly }
16364 #include "clang/Basic/OperatorKinds.def"
16365   };
16366 
16367   bool CanBeUnaryOperator = OperatorUses[Op][0];
16368   bool CanBeBinaryOperator = OperatorUses[Op][1];
16369   bool MustBeMemberOperator = OperatorUses[Op][2];
16370 
16371   // C++ [over.oper]p8:
16372   //   [...] Operator functions cannot have more or fewer parameters
16373   //   than the number required for the corresponding operator, as
16374   //   described in the rest of this subclause.
16375   unsigned NumParams = FnDecl->getNumParams() +
16376                        (isa<CXXMethodDecl>(FnDecl) &&
16377                                 !FnDecl->hasCXXExplicitFunctionObjectParameter()
16378                             ? 1
16379                             : 0);
16380   if (Op != OO_Call && Op != OO_Subscript &&
16381       ((NumParams == 1 && !CanBeUnaryOperator) ||
16382        (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||
16383        (NumParams > 2))) {
16384     // We have the wrong number of parameters.
16385     unsigned ErrorKind;
16386     if (CanBeUnaryOperator && CanBeBinaryOperator) {
16387       ErrorKind = 2;  // 2 -> unary or binary.
16388     } else if (CanBeUnaryOperator) {
16389       ErrorKind = 0;  // 0 -> unary
16390     } else {
16391       assert(CanBeBinaryOperator &&
16392              "All non-call overloaded operators are unary or binary!");
16393       ErrorKind = 1;  // 1 -> binary
16394     }
16395     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
16396       << FnDecl->getDeclName() << NumParams << ErrorKind;
16397   }
16398 
16399   if (Op == OO_Subscript && NumParams != 2) {
16400     Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
16401                                     ? diag::ext_subscript_overload
16402                                     : diag::error_subscript_overload)
16403         << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);
16404   }
16405 
16406   // Overloaded operators other than operator() and operator[] cannot be
16407   // variadic.
16408   if (Op != OO_Call &&
16409       FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
16410     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
16411            << FnDecl->getDeclName();
16412   }
16413 
16414   // Some operators must be member functions.
16415   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
16416     return Diag(FnDecl->getLocation(),
16417                 diag::err_operator_overload_must_be_member)
16418       << FnDecl->getDeclName();
16419   }
16420 
16421   // C++ [over.inc]p1:
16422   //   The user-defined function called operator++ implements the
16423   //   prefix and postfix ++ operator. If this function is a member
16424   //   function with no parameters, or a non-member function with one
16425   //   parameter of class or enumeration type, it defines the prefix
16426   //   increment operator ++ for objects of that type. If the function
16427   //   is a member function with one parameter (which shall be of type
16428   //   int) or a non-member function with two parameters (the second
16429   //   of which shall be of type int), it defines the postfix
16430   //   increment operator ++ for objects of that type.
16431   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
16432     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
16433     QualType ParamType = LastParam->getType();
16434 
16435     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
16436         !ParamType->isDependentType())
16437       return Diag(LastParam->getLocation(),
16438                   diag::err_operator_overload_post_incdec_must_be_int)
16439         << LastParam->getType() << (Op == OO_MinusMinus);
16440   }
16441 
16442   return false;
16443 }
16444 
16445 static bool
16446 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
16447                                           FunctionTemplateDecl *TpDecl) {
16448   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
16449 
16450   // Must have one or two template parameters.
16451   if (TemplateParams->size() == 1) {
16452     NonTypeTemplateParmDecl *PmDecl =
16453         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
16454 
16455     // The template parameter must be a char parameter pack.
16456     if (PmDecl && PmDecl->isTemplateParameterPack() &&
16457         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
16458       return false;
16459 
16460     // C++20 [over.literal]p5:
16461     //   A string literal operator template is a literal operator template
16462     //   whose template-parameter-list comprises a single non-type
16463     //   template-parameter of class type.
16464     //
16465     // As a DR resolution, we also allow placeholders for deduced class
16466     // template specializations.
16467     if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
16468         !PmDecl->isTemplateParameterPack() &&
16469         (PmDecl->getType()->isRecordType() ||
16470          PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
16471       return false;
16472   } else if (TemplateParams->size() == 2) {
16473     TemplateTypeParmDecl *PmType =
16474         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
16475     NonTypeTemplateParmDecl *PmArgs =
16476         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
16477 
16478     // The second template parameter must be a parameter pack with the
16479     // first template parameter as its type.
16480     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
16481         PmArgs->isTemplateParameterPack()) {
16482       const TemplateTypeParmType *TArgs =
16483           PmArgs->getType()->getAs<TemplateTypeParmType>();
16484       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
16485           TArgs->getIndex() == PmType->getIndex()) {
16486         if (!SemaRef.inTemplateInstantiation())
16487           SemaRef.Diag(TpDecl->getLocation(),
16488                        diag::ext_string_literal_operator_template);
16489         return false;
16490       }
16491     }
16492   }
16493 
16494   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
16495                diag::err_literal_operator_template)
16496       << TpDecl->getTemplateParameters()->getSourceRange();
16497   return true;
16498 }
16499 
16500 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
16501   if (isa<CXXMethodDecl>(FnDecl)) {
16502     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
16503       << FnDecl->getDeclName();
16504     return true;
16505   }
16506 
16507   if (FnDecl->isExternC()) {
16508     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
16509     if (const LinkageSpecDecl *LSD =
16510             FnDecl->getDeclContext()->getExternCContext())
16511       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
16512     return true;
16513   }
16514 
16515   // This might be the definition of a literal operator template.
16516   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
16517 
16518   // This might be a specialization of a literal operator template.
16519   if (!TpDecl)
16520     TpDecl = FnDecl->getPrimaryTemplate();
16521 
16522   // template <char...> type operator "" name() and
16523   // template <class T, T...> type operator "" name() are the only valid
16524   // template signatures, and the only valid signatures with no parameters.
16525   //
16526   // C++20 also allows template <SomeClass T> type operator "" name().
16527   if (TpDecl) {
16528     if (FnDecl->param_size() != 0) {
16529       Diag(FnDecl->getLocation(),
16530            diag::err_literal_operator_template_with_params);
16531       return true;
16532     }
16533 
16534     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
16535       return true;
16536 
16537   } else if (FnDecl->param_size() == 1) {
16538     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
16539 
16540     QualType ParamType = Param->getType().getUnqualifiedType();
16541 
16542     // Only unsigned long long int, long double, any character type, and const
16543     // char * are allowed as the only parameters.
16544     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
16545         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
16546         Context.hasSameType(ParamType, Context.CharTy) ||
16547         Context.hasSameType(ParamType, Context.WideCharTy) ||
16548         Context.hasSameType(ParamType, Context.Char8Ty) ||
16549         Context.hasSameType(ParamType, Context.Char16Ty) ||
16550         Context.hasSameType(ParamType, Context.Char32Ty)) {
16551     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
16552       QualType InnerType = Ptr->getPointeeType();
16553 
16554       // Pointer parameter must be a const char *.
16555       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
16556                                 Context.CharTy) &&
16557             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
16558         Diag(Param->getSourceRange().getBegin(),
16559              diag::err_literal_operator_param)
16560             << ParamType << "'const char *'" << Param->getSourceRange();
16561         return true;
16562       }
16563 
16564     } else if (ParamType->isRealFloatingType()) {
16565       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16566           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
16567       return true;
16568 
16569     } else if (ParamType->isIntegerType()) {
16570       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16571           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
16572       return true;
16573 
16574     } else {
16575       Diag(Param->getSourceRange().getBegin(),
16576            diag::err_literal_operator_invalid_param)
16577           << ParamType << Param->getSourceRange();
16578       return true;
16579     }
16580 
16581   } else if (FnDecl->param_size() == 2) {
16582     FunctionDecl::param_iterator Param = FnDecl->param_begin();
16583 
16584     // First, verify that the first parameter is correct.
16585 
16586     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
16587 
16588     // Two parameter function must have a pointer to const as a
16589     // first parameter; let's strip those qualifiers.
16590     const PointerType *PT = FirstParamType->getAs<PointerType>();
16591 
16592     if (!PT) {
16593       Diag((*Param)->getSourceRange().getBegin(),
16594            diag::err_literal_operator_param)
16595           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16596       return true;
16597     }
16598 
16599     QualType PointeeType = PT->getPointeeType();
16600     // First parameter must be const
16601     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
16602       Diag((*Param)->getSourceRange().getBegin(),
16603            diag::err_literal_operator_param)
16604           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16605       return true;
16606     }
16607 
16608     QualType InnerType = PointeeType.getUnqualifiedType();
16609     // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
16610     // const char32_t* are allowed as the first parameter to a two-parameter
16611     // function
16612     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
16613           Context.hasSameType(InnerType, Context.WideCharTy) ||
16614           Context.hasSameType(InnerType, Context.Char8Ty) ||
16615           Context.hasSameType(InnerType, Context.Char16Ty) ||
16616           Context.hasSameType(InnerType, Context.Char32Ty))) {
16617       Diag((*Param)->getSourceRange().getBegin(),
16618            diag::err_literal_operator_param)
16619           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16620       return true;
16621     }
16622 
16623     // Move on to the second and final parameter.
16624     ++Param;
16625 
16626     // The second parameter must be a std::size_t.
16627     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
16628     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
16629       Diag((*Param)->getSourceRange().getBegin(),
16630            diag::err_literal_operator_param)
16631           << SecondParamType << Context.getSizeType()
16632           << (*Param)->getSourceRange();
16633       return true;
16634     }
16635   } else {
16636     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
16637     return true;
16638   }
16639 
16640   // Parameters are good.
16641 
16642   // A parameter-declaration-clause containing a default argument is not
16643   // equivalent to any of the permitted forms.
16644   for (auto *Param : FnDecl->parameters()) {
16645     if (Param->hasDefaultArg()) {
16646       Diag(Param->getDefaultArgRange().getBegin(),
16647            diag::err_literal_operator_default_argument)
16648         << Param->getDefaultArgRange();
16649       break;
16650     }
16651   }
16652 
16653   const IdentifierInfo *II = FnDecl->getDeclName().getCXXLiteralIdentifier();
16654   ReservedLiteralSuffixIdStatus Status = II->isReservedLiteralSuffixId();
16655   if (Status != ReservedLiteralSuffixIdStatus::NotReserved &&
16656       !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
16657     // C++23 [usrlit.suffix]p1:
16658     //   Literal suffix identifiers that do not start with an underscore are
16659     //   reserved for future standardization. Literal suffix identifiers that
16660     //   contain a double underscore __ are reserved for use by C++
16661     //   implementations.
16662     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
16663         << static_cast<int>(Status)
16664         << StringLiteralParser::isValidUDSuffix(getLangOpts(), II->getName());
16665   }
16666 
16667   return false;
16668 }
16669 
16670 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
16671                                            Expr *LangStr,
16672                                            SourceLocation LBraceLoc) {
16673   StringLiteral *Lit = cast<StringLiteral>(LangStr);
16674   assert(Lit->isUnevaluated() && "Unexpected string literal kind");
16675 
16676   StringRef Lang = Lit->getString();
16677   LinkageSpecLanguageIDs Language;
16678   if (Lang == "C")
16679     Language = LinkageSpecLanguageIDs::C;
16680   else if (Lang == "C++")
16681     Language = LinkageSpecLanguageIDs::CXX;
16682   else {
16683     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
16684       << LangStr->getSourceRange();
16685     return nullptr;
16686   }
16687 
16688   // FIXME: Add all the various semantics of linkage specifications
16689 
16690   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
16691                                                LangStr->getExprLoc(), Language,
16692                                                LBraceLoc.isValid());
16693 
16694   /// C++ [module.unit]p7.2.3
16695   /// - Otherwise, if the declaration
16696   ///   - ...
16697   ///   - ...
16698   ///   - appears within a linkage-specification,
16699   ///   it is attached to the global module.
16700   ///
16701   /// If the declaration is already in global module fragment, we don't
16702   /// need to attach it again.
16703   if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
16704     Module *GlobalModule = PushImplicitGlobalModuleFragment(ExternLoc);
16705     D->setLocalOwningModule(GlobalModule);
16706   }
16707 
16708   CurContext->addDecl(D);
16709   PushDeclContext(S, D);
16710   return D;
16711 }
16712 
16713 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
16714                                             Decl *LinkageSpec,
16715                                             SourceLocation RBraceLoc) {
16716   if (RBraceLoc.isValid()) {
16717     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
16718     LSDecl->setRBraceLoc(RBraceLoc);
16719   }
16720 
16721   // If the current module doesn't has Parent, it implies that the
16722   // LinkageSpec isn't in the module created by itself. So we don't
16723   // need to pop it.
16724   if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
16725       getCurrentModule()->isImplicitGlobalModule() &&
16726       getCurrentModule()->Parent)
16727     PopImplicitGlobalModuleFragment();
16728 
16729   PopDeclContext();
16730   return LinkageSpec;
16731 }
16732 
16733 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
16734                                   const ParsedAttributesView &AttrList,
16735                                   SourceLocation SemiLoc) {
16736   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
16737   // Attribute declarations appertain to empty declaration so we handle
16738   // them here.
16739   ProcessDeclAttributeList(S, ED, AttrList);
16740 
16741   CurContext->addDecl(ED);
16742   return ED;
16743 }
16744 
16745 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
16746                                          SourceLocation StartLoc,
16747                                          SourceLocation Loc,
16748                                          const IdentifierInfo *Name) {
16749   bool Invalid = false;
16750   QualType ExDeclType = TInfo->getType();
16751 
16752   // Arrays and functions decay.
16753   if (ExDeclType->isArrayType())
16754     ExDeclType = Context.getArrayDecayedType(ExDeclType);
16755   else if (ExDeclType->isFunctionType())
16756     ExDeclType = Context.getPointerType(ExDeclType);
16757 
16758   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
16759   // The exception-declaration shall not denote a pointer or reference to an
16760   // incomplete type, other than [cv] void*.
16761   // N2844 forbids rvalue references.
16762   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
16763     Diag(Loc, diag::err_catch_rvalue_ref);
16764     Invalid = true;
16765   }
16766 
16767   if (ExDeclType->isVariablyModifiedType()) {
16768     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
16769     Invalid = true;
16770   }
16771 
16772   QualType BaseType = ExDeclType;
16773   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
16774   unsigned DK = diag::err_catch_incomplete;
16775   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
16776     BaseType = Ptr->getPointeeType();
16777     Mode = 1;
16778     DK = diag::err_catch_incomplete_ptr;
16779   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
16780     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
16781     BaseType = Ref->getPointeeType();
16782     Mode = 2;
16783     DK = diag::err_catch_incomplete_ref;
16784   }
16785   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
16786       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
16787     Invalid = true;
16788 
16789   if (!Invalid && BaseType.isWebAssemblyReferenceType()) {
16790     Diag(Loc, diag::err_wasm_reftype_tc) << 1;
16791     Invalid = true;
16792   }
16793 
16794   if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
16795     Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
16796     Invalid = true;
16797   }
16798 
16799   if (!Invalid && !ExDeclType->isDependentType() &&
16800       RequireNonAbstractType(Loc, ExDeclType,
16801                              diag::err_abstract_type_in_decl,
16802                              AbstractVariableType))
16803     Invalid = true;
16804 
16805   // Only the non-fragile NeXT runtime currently supports C++ catches
16806   // of ObjC types, and no runtime supports catching ObjC types by value.
16807   if (!Invalid && getLangOpts().ObjC) {
16808     QualType T = ExDeclType;
16809     if (const ReferenceType *RT = T->getAs<ReferenceType>())
16810       T = RT->getPointeeType();
16811 
16812     if (T->isObjCObjectType()) {
16813       Diag(Loc, diag::err_objc_object_catch);
16814       Invalid = true;
16815     } else if (T->isObjCObjectPointerType()) {
16816       // FIXME: should this be a test for macosx-fragile specifically?
16817       if (getLangOpts().ObjCRuntime.isFragile())
16818         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
16819     }
16820   }
16821 
16822   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
16823                                     ExDeclType, TInfo, SC_None);
16824   ExDecl->setExceptionVariable(true);
16825 
16826   // In ARC, infer 'retaining' for variables of retainable type.
16827   if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(ExDecl))
16828     Invalid = true;
16829 
16830   if (!Invalid && !ExDeclType->isDependentType()) {
16831     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
16832       // Insulate this from anything else we might currently be parsing.
16833       EnterExpressionEvaluationContext scope(
16834           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
16835 
16836       // C++ [except.handle]p16:
16837       //   The object declared in an exception-declaration or, if the
16838       //   exception-declaration does not specify a name, a temporary (12.2) is
16839       //   copy-initialized (8.5) from the exception object. [...]
16840       //   The object is destroyed when the handler exits, after the destruction
16841       //   of any automatic objects initialized within the handler.
16842       //
16843       // We just pretend to initialize the object with itself, then make sure
16844       // it can be destroyed later.
16845       QualType initType = Context.getExceptionObjectType(ExDeclType);
16846 
16847       InitializedEntity entity =
16848         InitializedEntity::InitializeVariable(ExDecl);
16849       InitializationKind initKind =
16850         InitializationKind::CreateCopy(Loc, SourceLocation());
16851 
16852       Expr *opaqueValue =
16853         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
16854       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
16855       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
16856       if (result.isInvalid())
16857         Invalid = true;
16858       else {
16859         // If the constructor used was non-trivial, set this as the
16860         // "initializer".
16861         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
16862         if (!construct->getConstructor()->isTrivial()) {
16863           Expr *init = MaybeCreateExprWithCleanups(construct);
16864           ExDecl->setInit(init);
16865         }
16866 
16867         // And make sure it's destructable.
16868         FinalizeVarWithDestructor(ExDecl, recordType);
16869       }
16870     }
16871   }
16872 
16873   if (Invalid)
16874     ExDecl->setInvalidDecl();
16875 
16876   return ExDecl;
16877 }
16878 
16879 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
16880   TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
16881   bool Invalid = D.isInvalidType();
16882 
16883   // Check for unexpanded parameter packs.
16884   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16885                                       UPPC_ExceptionType)) {
16886     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
16887                                              D.getIdentifierLoc());
16888     Invalid = true;
16889   }
16890 
16891   const IdentifierInfo *II = D.getIdentifier();
16892   if (NamedDecl *PrevDecl =
16893           LookupSingleName(S, II, D.getIdentifierLoc(), LookupOrdinaryName,
16894                            RedeclarationKind::ForVisibleRedeclaration)) {
16895     // The scope should be freshly made just for us. There is just no way
16896     // it contains any previous declaration, except for function parameters in
16897     // a function-try-block's catch statement.
16898     assert(!S->isDeclScope(PrevDecl));
16899     if (isDeclInScope(PrevDecl, CurContext, S)) {
16900       Diag(D.getIdentifierLoc(), diag::err_redefinition)
16901         << D.getIdentifier();
16902       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
16903       Invalid = true;
16904     } else if (PrevDecl->isTemplateParameter())
16905       // Maybe we will complain about the shadowed template parameter.
16906       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16907   }
16908 
16909   if (D.getCXXScopeSpec().isSet() && !Invalid) {
16910     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
16911       << D.getCXXScopeSpec().getRange();
16912     Invalid = true;
16913   }
16914 
16915   VarDecl *ExDecl = BuildExceptionDeclaration(
16916       S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
16917   if (Invalid)
16918     ExDecl->setInvalidDecl();
16919 
16920   // Add the exception declaration into this scope.
16921   if (II)
16922     PushOnScopeChains(ExDecl, S);
16923   else
16924     CurContext->addDecl(ExDecl);
16925 
16926   ProcessDeclAttributes(S, ExDecl, D);
16927   return ExDecl;
16928 }
16929 
16930 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
16931                                          Expr *AssertExpr,
16932                                          Expr *AssertMessageExpr,
16933                                          SourceLocation RParenLoc) {
16934   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
16935     return nullptr;
16936 
16937   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
16938                                       AssertMessageExpr, RParenLoc, false);
16939 }
16940 
16941 static void WriteCharTypePrefix(BuiltinType::Kind BTK, llvm::raw_ostream &OS) {
16942   switch (BTK) {
16943   case BuiltinType::Char_S:
16944   case BuiltinType::Char_U:
16945     break;
16946   case BuiltinType::Char8:
16947     OS << "u8";
16948     break;
16949   case BuiltinType::Char16:
16950     OS << 'u';
16951     break;
16952   case BuiltinType::Char32:
16953     OS << 'U';
16954     break;
16955   case BuiltinType::WChar_S:
16956   case BuiltinType::WChar_U:
16957     OS << 'L';
16958     break;
16959   default:
16960     llvm_unreachable("Non-character type");
16961   }
16962 }
16963 
16964 /// Convert character's value, interpreted as a code unit, to a string.
16965 /// The value needs to be zero-extended to 32-bits.
16966 /// FIXME: This assumes Unicode literal encodings
16967 static void WriteCharValueForDiagnostic(uint32_t Value, const BuiltinType *BTy,
16968                                         unsigned TyWidth,
16969                                         SmallVectorImpl<char> &Str) {
16970   char Arr[UNI_MAX_UTF8_BYTES_PER_CODE_POINT];
16971   char *Ptr = Arr;
16972   BuiltinType::Kind K = BTy->getKind();
16973   llvm::raw_svector_ostream OS(Str);
16974 
16975   // This should catch Char_S, Char_U, Char8, and use of escaped characters in
16976   // other types.
16977   if (K == BuiltinType::Char_S || K == BuiltinType::Char_U ||
16978       K == BuiltinType::Char8 || Value <= 0x7F) {
16979     StringRef Escaped = escapeCStyle<EscapeChar::Single>(Value);
16980     if (!Escaped.empty())
16981       EscapeStringForDiagnostic(Escaped, Str);
16982     else
16983       OS << static_cast<char>(Value);
16984     return;
16985   }
16986 
16987   switch (K) {
16988   case BuiltinType::Char16:
16989   case BuiltinType::Char32:
16990   case BuiltinType::WChar_S:
16991   case BuiltinType::WChar_U: {
16992     if (llvm::ConvertCodePointToUTF8(Value, Ptr))
16993       EscapeStringForDiagnostic(StringRef(Arr, Ptr - Arr), Str);
16994     else
16995       OS << "\\x"
16996          << llvm::format_hex_no_prefix(Value, TyWidth / 4, /*Upper=*/true);
16997     break;
16998   }
16999   default:
17000     llvm_unreachable("Non-character type is passed");
17001   }
17002 }
17003 
17004 /// Convert \V to a string we can present to the user in a diagnostic
17005 /// \T is the type of the expression that has been evaluated into \V
17006 static bool ConvertAPValueToString(const APValue &V, QualType T,
17007                                    SmallVectorImpl<char> &Str,
17008                                    ASTContext &Context) {
17009   if (!V.hasValue())
17010     return false;
17011 
17012   switch (V.getKind()) {
17013   case APValue::ValueKind::Int:
17014     if (T->isBooleanType()) {
17015       // Bools are reduced to ints during evaluation, but for
17016       // diagnostic purposes we want to print them as
17017       // true or false.
17018       int64_t BoolValue = V.getInt().getExtValue();
17019       assert((BoolValue == 0 || BoolValue == 1) &&
17020              "Bool type, but value is not 0 or 1");
17021       llvm::raw_svector_ostream OS(Str);
17022       OS << (BoolValue ? "true" : "false");
17023     } else {
17024       llvm::raw_svector_ostream OS(Str);
17025       // Same is true for chars.
17026       // We want to print the character representation for textual types
17027       const auto *BTy = T->getAs<BuiltinType>();
17028       if (BTy) {
17029         switch (BTy->getKind()) {
17030         case BuiltinType::Char_S:
17031         case BuiltinType::Char_U:
17032         case BuiltinType::Char8:
17033         case BuiltinType::Char16:
17034         case BuiltinType::Char32:
17035         case BuiltinType::WChar_S:
17036         case BuiltinType::WChar_U: {
17037           unsigned TyWidth = Context.getIntWidth(T);
17038           assert(8 <= TyWidth && TyWidth <= 32 && "Unexpected integer width");
17039           uint32_t CodeUnit = static_cast<uint32_t>(V.getInt().getZExtValue());
17040           WriteCharTypePrefix(BTy->getKind(), OS);
17041           OS << '\'';
17042           WriteCharValueForDiagnostic(CodeUnit, BTy, TyWidth, Str);
17043           OS << "' (0x"
17044              << llvm::format_hex_no_prefix(CodeUnit, /*Width=*/2,
17045                                            /*Upper=*/true)
17046              << ", " << V.getInt() << ')';
17047           return true;
17048         }
17049         default:
17050           break;
17051         }
17052       }
17053       V.getInt().toString(Str);
17054     }
17055 
17056     break;
17057 
17058   case APValue::ValueKind::Float:
17059     V.getFloat().toString(Str);
17060     break;
17061 
17062   case APValue::ValueKind::LValue:
17063     if (V.isNullPointer()) {
17064       llvm::raw_svector_ostream OS(Str);
17065       OS << "nullptr";
17066     } else
17067       return false;
17068     break;
17069 
17070   case APValue::ValueKind::ComplexFloat: {
17071     llvm::raw_svector_ostream OS(Str);
17072     OS << '(';
17073     V.getComplexFloatReal().toString(Str);
17074     OS << " + ";
17075     V.getComplexFloatImag().toString(Str);
17076     OS << "i)";
17077   } break;
17078 
17079   case APValue::ValueKind::ComplexInt: {
17080     llvm::raw_svector_ostream OS(Str);
17081     OS << '(';
17082     V.getComplexIntReal().toString(Str);
17083     OS << " + ";
17084     V.getComplexIntImag().toString(Str);
17085     OS << "i)";
17086   } break;
17087 
17088   default:
17089     return false;
17090   }
17091 
17092   return true;
17093 }
17094 
17095 /// Some Expression types are not useful to print notes about,
17096 /// e.g. literals and values that have already been expanded
17097 /// before such as int-valued template parameters.
17098 static bool UsefulToPrintExpr(const Expr *E) {
17099   E = E->IgnoreParenImpCasts();
17100   // Literals are pretty easy for humans to understand.
17101   if (isa<IntegerLiteral, FloatingLiteral, CharacterLiteral, CXXBoolLiteralExpr,
17102           CXXNullPtrLiteralExpr, FixedPointLiteral, ImaginaryLiteral>(E))
17103     return false;
17104 
17105   // These have been substituted from template parameters
17106   // and appear as literals in the static assert error.
17107   if (isa<SubstNonTypeTemplateParmExpr>(E))
17108     return false;
17109 
17110   // -5 is also simple to understand.
17111   if (const auto *UnaryOp = dyn_cast<UnaryOperator>(E))
17112     return UsefulToPrintExpr(UnaryOp->getSubExpr());
17113 
17114   // Only print nested arithmetic operators.
17115   if (const auto *BO = dyn_cast<BinaryOperator>(E))
17116     return (BO->isShiftOp() || BO->isAdditiveOp() || BO->isMultiplicativeOp() ||
17117             BO->isBitwiseOp());
17118 
17119   return true;
17120 }
17121 
17122 void Sema::DiagnoseStaticAssertDetails(const Expr *E) {
17123   if (const auto *Op = dyn_cast<BinaryOperator>(E);
17124       Op && Op->getOpcode() != BO_LOr) {
17125     const Expr *LHS = Op->getLHS()->IgnoreParenImpCasts();
17126     const Expr *RHS = Op->getRHS()->IgnoreParenImpCasts();
17127 
17128     // Ignore comparisons of boolean expressions with a boolean literal.
17129     if ((isa<CXXBoolLiteralExpr>(LHS) && RHS->getType()->isBooleanType()) ||
17130         (isa<CXXBoolLiteralExpr>(RHS) && LHS->getType()->isBooleanType()))
17131       return;
17132 
17133     // Don't print obvious expressions.
17134     if (!UsefulToPrintExpr(LHS) && !UsefulToPrintExpr(RHS))
17135       return;
17136 
17137     struct {
17138       const clang::Expr *Cond;
17139       Expr::EvalResult Result;
17140       SmallString<12> ValueString;
17141       bool Print;
17142     } DiagSide[2] = {{LHS, Expr::EvalResult(), {}, false},
17143                      {RHS, Expr::EvalResult(), {}, false}};
17144     for (unsigned I = 0; I < 2; I++) {
17145       const Expr *Side = DiagSide[I].Cond;
17146 
17147       Side->EvaluateAsRValue(DiagSide[I].Result, Context, true);
17148 
17149       DiagSide[I].Print =
17150           ConvertAPValueToString(DiagSide[I].Result.Val, Side->getType(),
17151                                  DiagSide[I].ValueString, Context);
17152     }
17153     if (DiagSide[0].Print && DiagSide[1].Print) {
17154       Diag(Op->getExprLoc(), diag::note_expr_evaluates_to)
17155           << DiagSide[0].ValueString << Op->getOpcodeStr()
17156           << DiagSide[1].ValueString << Op->getSourceRange();
17157     }
17158   }
17159 }
17160 
17161 bool Sema::EvaluateStaticAssertMessageAsString(Expr *Message,
17162                                                std::string &Result,
17163                                                ASTContext &Ctx,
17164                                                bool ErrorOnInvalidMessage) {
17165   assert(Message);
17166   assert(!Message->isTypeDependent() && !Message->isValueDependent() &&
17167          "can't evaluate a dependant static assert message");
17168 
17169   if (const auto *SL = dyn_cast<StringLiteral>(Message)) {
17170     assert(SL->isUnevaluated() && "expected an unevaluated string");
17171     Result.assign(SL->getString().begin(), SL->getString().end());
17172     return true;
17173   }
17174 
17175   SourceLocation Loc = Message->getBeginLoc();
17176   QualType T = Message->getType().getNonReferenceType();
17177   auto *RD = T->getAsCXXRecordDecl();
17178   if (!RD) {
17179     Diag(Loc, diag::err_static_assert_invalid_message);
17180     return false;
17181   }
17182 
17183   auto FindMember = [&](StringRef Member, bool &Empty,
17184                         bool Diag = false) -> std::optional<LookupResult> {
17185     DeclarationName DN = PP.getIdentifierInfo(Member);
17186     LookupResult MemberLookup(*this, DN, Loc, Sema::LookupMemberName);
17187     LookupQualifiedName(MemberLookup, RD);
17188     Empty = MemberLookup.empty();
17189     OverloadCandidateSet Candidates(MemberLookup.getNameLoc(),
17190                                     OverloadCandidateSet::CSK_Normal);
17191     if (MemberLookup.empty())
17192       return std::nullopt;
17193     return std::move(MemberLookup);
17194   };
17195 
17196   bool SizeNotFound, DataNotFound;
17197   std::optional<LookupResult> SizeMember = FindMember("size", SizeNotFound);
17198   std::optional<LookupResult> DataMember = FindMember("data", DataNotFound);
17199   if (SizeNotFound || DataNotFound) {
17200     Diag(Loc, diag::err_static_assert_missing_member_function)
17201         << ((SizeNotFound && DataNotFound) ? 2
17202             : SizeNotFound                 ? 0
17203                                            : 1);
17204     return false;
17205   }
17206 
17207   if (!SizeMember || !DataMember) {
17208     if (!SizeMember)
17209       FindMember("size", SizeNotFound, /*Diag=*/true);
17210     if (!DataMember)
17211       FindMember("data", DataNotFound, /*Diag=*/true);
17212     return false;
17213   }
17214 
17215   auto BuildExpr = [&](LookupResult &LR) {
17216     ExprResult Res = BuildMemberReferenceExpr(
17217         Message, Message->getType(), Message->getBeginLoc(), false,
17218         CXXScopeSpec(), SourceLocation(), nullptr, LR, nullptr, nullptr);
17219     if (Res.isInvalid())
17220       return ExprError();
17221     Res = BuildCallExpr(nullptr, Res.get(), Loc, std::nullopt, Loc, nullptr,
17222                         false, true);
17223     if (Res.isInvalid())
17224       return ExprError();
17225     if (Res.get()->isTypeDependent() || Res.get()->isValueDependent())
17226       return ExprError();
17227     return TemporaryMaterializationConversion(Res.get());
17228   };
17229 
17230   ExprResult SizeE = BuildExpr(*SizeMember);
17231   ExprResult DataE = BuildExpr(*DataMember);
17232 
17233   QualType SizeT = Context.getSizeType();
17234   QualType ConstCharPtr =
17235       Context.getPointerType(Context.getConstType(Context.CharTy));
17236 
17237   ExprResult EvaluatedSize =
17238       SizeE.isInvalid() ? ExprError()
17239                         : BuildConvertedConstantExpression(
17240                               SizeE.get(), SizeT, CCEK_StaticAssertMessageSize);
17241   if (EvaluatedSize.isInvalid()) {
17242     Diag(Loc, diag::err_static_assert_invalid_mem_fn_ret_ty) << /*size*/ 0;
17243     return false;
17244   }
17245 
17246   ExprResult EvaluatedData =
17247       DataE.isInvalid()
17248           ? ExprError()
17249           : BuildConvertedConstantExpression(DataE.get(), ConstCharPtr,
17250                                              CCEK_StaticAssertMessageData);
17251   if (EvaluatedData.isInvalid()) {
17252     Diag(Loc, diag::err_static_assert_invalid_mem_fn_ret_ty) << /*data*/ 1;
17253     return false;
17254   }
17255 
17256   if (!ErrorOnInvalidMessage &&
17257       Diags.isIgnored(diag::warn_static_assert_message_constexpr, Loc))
17258     return true;
17259 
17260   Expr::EvalResult Status;
17261   SmallVector<PartialDiagnosticAt, 8> Notes;
17262   Status.Diag = &Notes;
17263   if (!Message->EvaluateCharRangeAsString(Result, EvaluatedSize.get(),
17264                                           EvaluatedData.get(), Ctx, Status) ||
17265       !Notes.empty()) {
17266     Diag(Message->getBeginLoc(),
17267          ErrorOnInvalidMessage ? diag::err_static_assert_message_constexpr
17268                                : diag::warn_static_assert_message_constexpr);
17269     for (const auto &Note : Notes)
17270       Diag(Note.first, Note.second);
17271     return !ErrorOnInvalidMessage;
17272   }
17273   return true;
17274 }
17275 
17276 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
17277                                          Expr *AssertExpr, Expr *AssertMessage,
17278                                          SourceLocation RParenLoc,
17279                                          bool Failed) {
17280   assert(AssertExpr != nullptr && "Expected non-null condition");
17281   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
17282       (!AssertMessage || (!AssertMessage->isTypeDependent() &&
17283                           !AssertMessage->isValueDependent())) &&
17284       !Failed) {
17285     // In a static_assert-declaration, the constant-expression shall be a
17286     // constant expression that can be contextually converted to bool.
17287     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
17288     if (Converted.isInvalid())
17289       Failed = true;
17290 
17291     ExprResult FullAssertExpr =
17292         ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
17293                             /*DiscardedValue*/ false,
17294                             /*IsConstexpr*/ true);
17295     if (FullAssertExpr.isInvalid())
17296       Failed = true;
17297     else
17298       AssertExpr = FullAssertExpr.get();
17299 
17300     llvm::APSInt Cond;
17301     Expr *BaseExpr = AssertExpr;
17302     AllowFoldKind FoldKind = NoFold;
17303 
17304     if (!getLangOpts().CPlusPlus) {
17305       // In C mode, allow folding as an extension for better compatibility with
17306       // C++ in terms of expressions like static_assert("test") or
17307       // static_assert(nullptr).
17308       FoldKind = AllowFold;
17309     }
17310 
17311     if (!Failed && VerifyIntegerConstantExpression(
17312                        BaseExpr, &Cond,
17313                        diag::err_static_assert_expression_is_not_constant,
17314                        FoldKind).isInvalid())
17315       Failed = true;
17316 
17317     // If the static_assert passes, only verify that
17318     // the message is grammatically valid without evaluating it.
17319     if (!Failed && AssertMessage && Cond.getBoolValue()) {
17320       std::string Str;
17321       EvaluateStaticAssertMessageAsString(AssertMessage, Str, Context,
17322                                           /*ErrorOnInvalidMessage=*/false);
17323     }
17324 
17325     // CWG2518
17326     // [dcl.pre]/p10  If [...] the expression is evaluated in the context of a
17327     // template definition, the declaration has no effect.
17328     bool InTemplateDefinition =
17329         getLangOpts().CPlusPlus && CurContext->isDependentContext();
17330 
17331     if (!Failed && !Cond && !InTemplateDefinition) {
17332       SmallString<256> MsgBuffer;
17333       llvm::raw_svector_ostream Msg(MsgBuffer);
17334       bool HasMessage = AssertMessage;
17335       if (AssertMessage) {
17336         std::string Str;
17337         HasMessage =
17338             EvaluateStaticAssertMessageAsString(
17339                 AssertMessage, Str, Context, /*ErrorOnInvalidMessage=*/true) ||
17340             !Str.empty();
17341         Msg << Str;
17342       }
17343       Expr *InnerCond = nullptr;
17344       std::string InnerCondDescription;
17345       std::tie(InnerCond, InnerCondDescription) =
17346         findFailedBooleanCondition(Converted.get());
17347       if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {
17348         // Drill down into concept specialization expressions to see why they
17349         // weren't satisfied.
17350         Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
17351             << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
17352         ConstraintSatisfaction Satisfaction;
17353         if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
17354           DiagnoseUnsatisfiedConstraint(Satisfaction);
17355       } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
17356                            && !isa<IntegerLiteral>(InnerCond)) {
17357         Diag(InnerCond->getBeginLoc(),
17358              diag::err_static_assert_requirement_failed)
17359             << InnerCondDescription << !HasMessage << Msg.str()
17360             << InnerCond->getSourceRange();
17361         DiagnoseStaticAssertDetails(InnerCond);
17362       } else {
17363         Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
17364             << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
17365         PrintContextStack();
17366       }
17367       Failed = true;
17368     }
17369   } else {
17370     ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
17371                                                     /*DiscardedValue*/false,
17372                                                     /*IsConstexpr*/true);
17373     if (FullAssertExpr.isInvalid())
17374       Failed = true;
17375     else
17376       AssertExpr = FullAssertExpr.get();
17377   }
17378 
17379   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
17380                                         AssertExpr, AssertMessage, RParenLoc,
17381                                         Failed);
17382 
17383   CurContext->addDecl(Decl);
17384   return Decl;
17385 }
17386 
17387 DeclResult Sema::ActOnTemplatedFriendTag(
17388     Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc,
17389     CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17390     const ParsedAttributesView &Attr, MultiTemplateParamsArg TempParamLists) {
17391   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
17392 
17393   bool IsMemberSpecialization = false;
17394   bool Invalid = false;
17395 
17396   if (TemplateParameterList *TemplateParams =
17397           MatchTemplateParametersToScopeSpecifier(
17398               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
17399               IsMemberSpecialization, Invalid)) {
17400     if (TemplateParams->size() > 0) {
17401       // This is a declaration of a class template.
17402       if (Invalid)
17403         return true;
17404 
17405       return CheckClassTemplate(S, TagSpec, TagUseKind::Friend, TagLoc, SS,
17406                                 Name, NameLoc, Attr, TemplateParams, AS_public,
17407                                 /*ModulePrivateLoc=*/SourceLocation(),
17408                                 FriendLoc, TempParamLists.size() - 1,
17409                                 TempParamLists.data())
17410           .get();
17411     } else {
17412       // The "template<>" header is extraneous.
17413       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
17414         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
17415       IsMemberSpecialization = true;
17416     }
17417   }
17418 
17419   if (Invalid) return true;
17420 
17421   bool isAllExplicitSpecializations = true;
17422   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
17423     if (TempParamLists[I]->size()) {
17424       isAllExplicitSpecializations = false;
17425       break;
17426     }
17427   }
17428 
17429   // FIXME: don't ignore attributes.
17430 
17431   // If it's explicit specializations all the way down, just forget
17432   // about the template header and build an appropriate non-templated
17433   // friend.  TODO: for source fidelity, remember the headers.
17434   if (isAllExplicitSpecializations) {
17435     if (SS.isEmpty()) {
17436       bool Owned = false;
17437       bool IsDependent = false;
17438       return ActOnTag(S, TagSpec, TagUseKind::Friend, TagLoc, SS, Name, NameLoc,
17439                       Attr, AS_public,
17440                       /*ModulePrivateLoc=*/SourceLocation(),
17441                       MultiTemplateParamsArg(), Owned, IsDependent,
17442                       /*ScopedEnumKWLoc=*/SourceLocation(),
17443                       /*ScopedEnumUsesClassTag=*/false,
17444                       /*UnderlyingType=*/TypeResult(),
17445                       /*IsTypeSpecifier=*/false,
17446                       /*IsTemplateParamOrArg=*/false, /*OOK=*/OOK_Outside);
17447     }
17448 
17449     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
17450     ElaboratedTypeKeyword Keyword
17451       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
17452     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
17453                                    *Name, NameLoc);
17454     if (T.isNull())
17455       return true;
17456 
17457     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
17458     if (isa<DependentNameType>(T)) {
17459       DependentNameTypeLoc TL =
17460           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
17461       TL.setElaboratedKeywordLoc(TagLoc);
17462       TL.setQualifierLoc(QualifierLoc);
17463       TL.setNameLoc(NameLoc);
17464     } else {
17465       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
17466       TL.setElaboratedKeywordLoc(TagLoc);
17467       TL.setQualifierLoc(QualifierLoc);
17468       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
17469     }
17470 
17471     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
17472                                             TSI, FriendLoc, TempParamLists);
17473     Friend->setAccess(AS_public);
17474     CurContext->addDecl(Friend);
17475     return Friend;
17476   }
17477 
17478   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
17479 
17480 
17481 
17482   // Handle the case of a templated-scope friend class.  e.g.
17483   //   template <class T> class A<T>::B;
17484   // FIXME: we don't support these right now.
17485   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
17486     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
17487   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
17488   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
17489   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
17490   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
17491   TL.setElaboratedKeywordLoc(TagLoc);
17492   TL.setQualifierLoc(SS.getWithLocInContext(Context));
17493   TL.setNameLoc(NameLoc);
17494 
17495   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
17496                                           TSI, FriendLoc, TempParamLists);
17497   Friend->setAccess(AS_public);
17498   Friend->setUnsupportedFriend(true);
17499   CurContext->addDecl(Friend);
17500   return Friend;
17501 }
17502 
17503 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
17504                                 MultiTemplateParamsArg TempParams) {
17505   SourceLocation Loc = DS.getBeginLoc();
17506   SourceLocation FriendLoc = DS.getFriendSpecLoc();
17507 
17508   assert(DS.isFriendSpecified());
17509   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
17510 
17511   // C++ [class.friend]p3:
17512   // A friend declaration that does not declare a function shall have one of
17513   // the following forms:
17514   //     friend elaborated-type-specifier ;
17515   //     friend simple-type-specifier ;
17516   //     friend typename-specifier ;
17517   //
17518   // If the friend keyword isn't first, or if the declarations has any type
17519   // qualifiers, then the declaration doesn't have that form.
17520   if (getLangOpts().CPlusPlus11 && !DS.isFriendSpecifiedFirst())
17521     Diag(FriendLoc, diag::err_friend_not_first_in_declaration);
17522   if (DS.getTypeQualifiers()) {
17523     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
17524       Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
17525     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
17526       Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
17527     if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
17528       Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
17529     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
17530       Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
17531     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
17532       Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
17533   }
17534 
17535   // Try to convert the decl specifier to a type.  This works for
17536   // friend templates because ActOnTag never produces a ClassTemplateDecl
17537   // for a TagUseKind::Friend.
17538   Declarator TheDeclarator(DS, ParsedAttributesView::none(),
17539                            DeclaratorContext::Member);
17540   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator);
17541   QualType T = TSI->getType();
17542   if (TheDeclarator.isInvalidType())
17543     return nullptr;
17544 
17545   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
17546     return nullptr;
17547 
17548   if (!T->isElaboratedTypeSpecifier()) {
17549     if (TempParams.size()) {
17550       // C++23 [dcl.pre]p5:
17551       //   In a simple-declaration, the optional init-declarator-list can be
17552       //   omitted only when declaring a class or enumeration, that is, when
17553       //   the decl-specifier-seq contains either a class-specifier, an
17554       //   elaborated-type-specifier with a class-key, or an enum-specifier.
17555       //
17556       // The declaration of a template-declaration or explicit-specialization
17557       // is never a member-declaration, so this must be a simple-declaration
17558       // with no init-declarator-list. Therefore, this is ill-formed.
17559       Diag(Loc, diag::err_tagless_friend_type_template) << DS.getSourceRange();
17560       return nullptr;
17561     } else if (const RecordDecl *RD = T->getAsRecordDecl()) {
17562       SmallString<16> InsertionText(" ");
17563       InsertionText += RD->getKindName();
17564 
17565       Diag(Loc, getLangOpts().CPlusPlus11
17566                     ? diag::warn_cxx98_compat_unelaborated_friend_type
17567                     : diag::ext_unelaborated_friend_type)
17568           << (unsigned)RD->getTagKind() << T
17569           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
17570                                         InsertionText);
17571     } else {
17572       Diag(FriendLoc, getLangOpts().CPlusPlus11
17573                           ? diag::warn_cxx98_compat_nonclass_type_friend
17574                           : diag::ext_nonclass_type_friend)
17575           << T << DS.getSourceRange();
17576     }
17577   }
17578 
17579   // C++98 [class.friend]p1: A friend of a class is a function
17580   //   or class that is not a member of the class . . .
17581   // This is fixed in DR77, which just barely didn't make the C++03
17582   // deadline.  It's also a very silly restriction that seriously
17583   // affects inner classes and which nobody else seems to implement;
17584   // thus we never diagnose it, not even in -pedantic.
17585   //
17586   // But note that we could warn about it: it's always useless to
17587   // friend one of your own members (it's not, however, worthless to
17588   // friend a member of an arbitrary specialization of your template).
17589 
17590   Decl *D;
17591   if (!TempParams.empty())
17592     D = FriendTemplateDecl::Create(Context, CurContext, Loc, TempParams, TSI,
17593                                    FriendLoc);
17594   else
17595     D = FriendDecl::Create(Context, CurContext, TSI->getTypeLoc().getBeginLoc(),
17596                            TSI, FriendLoc);
17597 
17598   if (!D)
17599     return nullptr;
17600 
17601   D->setAccess(AS_public);
17602   CurContext->addDecl(D);
17603 
17604   return D;
17605 }
17606 
17607 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
17608                                         MultiTemplateParamsArg TemplateParams) {
17609   const DeclSpec &DS = D.getDeclSpec();
17610 
17611   assert(DS.isFriendSpecified());
17612   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
17613 
17614   SourceLocation Loc = D.getIdentifierLoc();
17615   TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
17616 
17617   // C++ [class.friend]p1
17618   //   A friend of a class is a function or class....
17619   // Note that this sees through typedefs, which is intended.
17620   // It *doesn't* see through dependent types, which is correct
17621   // according to [temp.arg.type]p3:
17622   //   If a declaration acquires a function type through a
17623   //   type dependent on a template-parameter and this causes
17624   //   a declaration that does not use the syntactic form of a
17625   //   function declarator to have a function type, the program
17626   //   is ill-formed.
17627   if (!TInfo->getType()->isFunctionType()) {
17628     Diag(Loc, diag::err_unexpected_friend);
17629 
17630     // It might be worthwhile to try to recover by creating an
17631     // appropriate declaration.
17632     return nullptr;
17633   }
17634 
17635   // C++ [namespace.memdef]p3
17636   //  - If a friend declaration in a non-local class first declares a
17637   //    class or function, the friend class or function is a member
17638   //    of the innermost enclosing namespace.
17639   //  - The name of the friend is not found by simple name lookup
17640   //    until a matching declaration is provided in that namespace
17641   //    scope (either before or after the class declaration granting
17642   //    friendship).
17643   //  - If a friend function is called, its name may be found by the
17644   //    name lookup that considers functions from namespaces and
17645   //    classes associated with the types of the function arguments.
17646   //  - When looking for a prior declaration of a class or a function
17647   //    declared as a friend, scopes outside the innermost enclosing
17648   //    namespace scope are not considered.
17649 
17650   CXXScopeSpec &SS = D.getCXXScopeSpec();
17651   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
17652   assert(NameInfo.getName());
17653 
17654   // Check for unexpanded parameter packs.
17655   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
17656       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
17657       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
17658     return nullptr;
17659 
17660   // The context we found the declaration in, or in which we should
17661   // create the declaration.
17662   DeclContext *DC;
17663   Scope *DCScope = S;
17664   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
17665                         RedeclarationKind::ForExternalRedeclaration);
17666 
17667   bool isTemplateId = D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
17668 
17669   // There are five cases here.
17670   //   - There's no scope specifier and we're in a local class. Only look
17671   //     for functions declared in the immediately-enclosing block scope.
17672   // We recover from invalid scope qualifiers as if they just weren't there.
17673   FunctionDecl *FunctionContainingLocalClass = nullptr;
17674   if ((SS.isInvalid() || !SS.isSet()) &&
17675       (FunctionContainingLocalClass =
17676            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
17677     // C++11 [class.friend]p11:
17678     //   If a friend declaration appears in a local class and the name
17679     //   specified is an unqualified name, a prior declaration is
17680     //   looked up without considering scopes that are outside the
17681     //   innermost enclosing non-class scope. For a friend function
17682     //   declaration, if there is no prior declaration, the program is
17683     //   ill-formed.
17684 
17685     // Find the innermost enclosing non-class scope. This is the block
17686     // scope containing the local class definition (or for a nested class,
17687     // the outer local class).
17688     DCScope = S->getFnParent();
17689 
17690     // Look up the function name in the scope.
17691     Previous.clear(LookupLocalFriendName);
17692     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
17693 
17694     if (!Previous.empty()) {
17695       // All possible previous declarations must have the same context:
17696       // either they were declared at block scope or they are members of
17697       // one of the enclosing local classes.
17698       DC = Previous.getRepresentativeDecl()->getDeclContext();
17699     } else {
17700       // This is ill-formed, but provide the context that we would have
17701       // declared the function in, if we were permitted to, for error recovery.
17702       DC = FunctionContainingLocalClass;
17703     }
17704     adjustContextForLocalExternDecl(DC);
17705 
17706   //   - There's no scope specifier, in which case we just go to the
17707   //     appropriate scope and look for a function or function template
17708   //     there as appropriate.
17709   } else if (SS.isInvalid() || !SS.isSet()) {
17710     // C++11 [namespace.memdef]p3:
17711     //   If the name in a friend declaration is neither qualified nor
17712     //   a template-id and the declaration is a function or an
17713     //   elaborated-type-specifier, the lookup to determine whether
17714     //   the entity has been previously declared shall not consider
17715     //   any scopes outside the innermost enclosing namespace.
17716 
17717     // Find the appropriate context according to the above.
17718     DC = CurContext;
17719 
17720     // Skip class contexts.  If someone can cite chapter and verse
17721     // for this behavior, that would be nice --- it's what GCC and
17722     // EDG do, and it seems like a reasonable intent, but the spec
17723     // really only says that checks for unqualified existing
17724     // declarations should stop at the nearest enclosing namespace,
17725     // not that they should only consider the nearest enclosing
17726     // namespace.
17727     while (DC->isRecord())
17728       DC = DC->getParent();
17729 
17730     DeclContext *LookupDC = DC->getNonTransparentContext();
17731     while (true) {
17732       LookupQualifiedName(Previous, LookupDC);
17733 
17734       if (!Previous.empty()) {
17735         DC = LookupDC;
17736         break;
17737       }
17738 
17739       if (isTemplateId) {
17740         if (isa<TranslationUnitDecl>(LookupDC)) break;
17741       } else {
17742         if (LookupDC->isFileContext()) break;
17743       }
17744       LookupDC = LookupDC->getParent();
17745     }
17746 
17747     DCScope = getScopeForDeclContext(S, DC);
17748 
17749   //   - There's a non-dependent scope specifier, in which case we
17750   //     compute it and do a previous lookup there for a function
17751   //     or function template.
17752   } else if (!SS.getScopeRep()->isDependent()) {
17753     DC = computeDeclContext(SS);
17754     if (!DC) return nullptr;
17755 
17756     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
17757 
17758     LookupQualifiedName(Previous, DC);
17759 
17760     // C++ [class.friend]p1: A friend of a class is a function or
17761     //   class that is not a member of the class . . .
17762     if (DC->Equals(CurContext))
17763       Diag(DS.getFriendSpecLoc(),
17764            getLangOpts().CPlusPlus11 ?
17765              diag::warn_cxx98_compat_friend_is_member :
17766              diag::err_friend_is_member);
17767 
17768   //   - There's a scope specifier that does not match any template
17769   //     parameter lists, in which case we use some arbitrary context,
17770   //     create a method or method template, and wait for instantiation.
17771   //   - There's a scope specifier that does match some template
17772   //     parameter lists, which we don't handle right now.
17773   } else {
17774     DC = CurContext;
17775     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
17776   }
17777 
17778   if (!DC->isRecord()) {
17779     int DiagArg = -1;
17780     switch (D.getName().getKind()) {
17781     case UnqualifiedIdKind::IK_ConstructorTemplateId:
17782     case UnqualifiedIdKind::IK_ConstructorName:
17783       DiagArg = 0;
17784       break;
17785     case UnqualifiedIdKind::IK_DestructorName:
17786       DiagArg = 1;
17787       break;
17788     case UnqualifiedIdKind::IK_ConversionFunctionId:
17789       DiagArg = 2;
17790       break;
17791     case UnqualifiedIdKind::IK_DeductionGuideName:
17792       DiagArg = 3;
17793       break;
17794     case UnqualifiedIdKind::IK_Identifier:
17795     case UnqualifiedIdKind::IK_ImplicitSelfParam:
17796     case UnqualifiedIdKind::IK_LiteralOperatorId:
17797     case UnqualifiedIdKind::IK_OperatorFunctionId:
17798     case UnqualifiedIdKind::IK_TemplateId:
17799       break;
17800     }
17801     // This implies that it has to be an operator or function.
17802     if (DiagArg >= 0) {
17803       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
17804       return nullptr;
17805     }
17806   }
17807 
17808   // FIXME: This is an egregious hack to cope with cases where the scope stack
17809   // does not contain the declaration context, i.e., in an out-of-line
17810   // definition of a class.
17811   Scope FakeDCScope(S, Scope::DeclScope, Diags);
17812   if (!DCScope) {
17813     FakeDCScope.setEntity(DC);
17814     DCScope = &FakeDCScope;
17815   }
17816 
17817   bool AddToScope = true;
17818   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
17819                                           TemplateParams, AddToScope);
17820   if (!ND) return nullptr;
17821 
17822   assert(ND->getLexicalDeclContext() == CurContext);
17823 
17824   // If we performed typo correction, we might have added a scope specifier
17825   // and changed the decl context.
17826   DC = ND->getDeclContext();
17827 
17828   // Add the function declaration to the appropriate lookup tables,
17829   // adjusting the redeclarations list as necessary.  We don't
17830   // want to do this yet if the friending class is dependent.
17831   //
17832   // Also update the scope-based lookup if the target context's
17833   // lookup context is in lexical scope.
17834   if (!CurContext->isDependentContext()) {
17835     DC = DC->getRedeclContext();
17836     DC->makeDeclVisibleInContext(ND);
17837     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
17838       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
17839   }
17840 
17841   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
17842                                        D.getIdentifierLoc(), ND,
17843                                        DS.getFriendSpecLoc());
17844   FrD->setAccess(AS_public);
17845   CurContext->addDecl(FrD);
17846 
17847   if (ND->isInvalidDecl()) {
17848     FrD->setInvalidDecl();
17849   } else {
17850     if (DC->isRecord()) CheckFriendAccess(ND);
17851 
17852     FunctionDecl *FD;
17853     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
17854       FD = FTD->getTemplatedDecl();
17855     else
17856       FD = cast<FunctionDecl>(ND);
17857 
17858     // C++ [class.friend]p6:
17859     //   A function may be defined in a friend declaration of a class if and
17860     //   only if the class is a non-local class, and the function name is
17861     //   unqualified.
17862     if (D.isFunctionDefinition()) {
17863       // Qualified friend function definition.
17864       if (SS.isNotEmpty()) {
17865         // FIXME: We should only do this if the scope specifier names the
17866         // innermost enclosing namespace; otherwise the fixit changes the
17867         // meaning of the code.
17868         SemaDiagnosticBuilder DB =
17869             Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
17870 
17871         DB << SS.getScopeRep();
17872         if (DC->isFileContext())
17873           DB << FixItHint::CreateRemoval(SS.getRange());
17874 
17875         // Friend function defined in a local class.
17876       } else if (FunctionContainingLocalClass) {
17877         Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
17878 
17879         // Per [basic.pre]p4, a template-id is not a name. Therefore, if we have
17880         // a template-id, the function name is not unqualified because these is
17881         // no name. While the wording requires some reading in-between the
17882         // lines, GCC, MSVC, and EDG all consider a friend function
17883         // specialization definitions // to be de facto explicit specialization
17884         // and diagnose them as such.
17885       } else if (isTemplateId) {
17886         Diag(NameInfo.getBeginLoc(), diag::err_friend_specialization_def);
17887       }
17888     }
17889 
17890     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
17891     // default argument expression, that declaration shall be a definition
17892     // and shall be the only declaration of the function or function
17893     // template in the translation unit.
17894     if (functionDeclHasDefaultArgument(FD)) {
17895       // We can't look at FD->getPreviousDecl() because it may not have been set
17896       // if we're in a dependent context. If the function is known to be a
17897       // redeclaration, we will have narrowed Previous down to the right decl.
17898       if (D.isRedeclaration()) {
17899         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
17900         Diag(Previous.getRepresentativeDecl()->getLocation(),
17901              diag::note_previous_declaration);
17902       } else if (!D.isFunctionDefinition())
17903         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
17904     }
17905 
17906     // Mark templated-scope function declarations as unsupported.
17907     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
17908       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
17909         << SS.getScopeRep() << SS.getRange()
17910         << cast<CXXRecordDecl>(CurContext);
17911       FrD->setUnsupportedFriend(true);
17912     }
17913   }
17914 
17915   warnOnReservedIdentifier(ND);
17916 
17917   return ND;
17918 }
17919 
17920 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc,
17921                           StringLiteral *Message) {
17922   AdjustDeclIfTemplate(Dcl);
17923 
17924   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
17925   if (!Fn) {
17926     Diag(DelLoc, diag::err_deleted_non_function);
17927     return;
17928   }
17929 
17930   // Deleted function does not have a body.
17931   Fn->setWillHaveBody(false);
17932 
17933   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
17934     // Don't consider the implicit declaration we generate for explicit
17935     // specializations. FIXME: Do not generate these implicit declarations.
17936     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
17937          Prev->getPreviousDecl()) &&
17938         !Prev->isDefined()) {
17939       Diag(DelLoc, diag::err_deleted_decl_not_first);
17940       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
17941            Prev->isImplicit() ? diag::note_previous_implicit_declaration
17942                               : diag::note_previous_declaration);
17943       // We can't recover from this; the declaration might have already
17944       // been used.
17945       Fn->setInvalidDecl();
17946       return;
17947     }
17948 
17949     // To maintain the invariant that functions are only deleted on their first
17950     // declaration, mark the implicitly-instantiated declaration of the
17951     // explicitly-specialized function as deleted instead of marking the
17952     // instantiated redeclaration.
17953     Fn = Fn->getCanonicalDecl();
17954   }
17955 
17956   // dllimport/dllexport cannot be deleted.
17957   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
17958     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
17959     Fn->setInvalidDecl();
17960   }
17961 
17962   // C++11 [basic.start.main]p3:
17963   //   A program that defines main as deleted [...] is ill-formed.
17964   if (Fn->isMain())
17965     Diag(DelLoc, diag::err_deleted_main);
17966 
17967   // C++11 [dcl.fct.def.delete]p4:
17968   //  A deleted function is implicitly inline.
17969   Fn->setImplicitlyInline();
17970   Fn->setDeletedAsWritten(true, Message);
17971 }
17972 
17973 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
17974   if (!Dcl || Dcl->isInvalidDecl())
17975     return;
17976 
17977   auto *FD = dyn_cast<FunctionDecl>(Dcl);
17978   if (!FD) {
17979     if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
17980       if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
17981         Diag(DefaultLoc, diag::err_defaulted_comparison_template);
17982         return;
17983       }
17984     }
17985 
17986     Diag(DefaultLoc, diag::err_default_special_members)
17987         << getLangOpts().CPlusPlus20;
17988     return;
17989   }
17990 
17991   // Reject if this can't possibly be a defaultable function.
17992   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
17993   if (!DefKind &&
17994       // A dependent function that doesn't locally look defaultable can
17995       // still instantiate to a defaultable function if it's a constructor
17996       // or assignment operator.
17997       (!FD->isDependentContext() ||
17998        (!isa<CXXConstructorDecl>(FD) &&
17999         FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
18000     Diag(DefaultLoc, diag::err_default_special_members)
18001         << getLangOpts().CPlusPlus20;
18002     return;
18003   }
18004 
18005   // Issue compatibility warning. We already warned if the operator is
18006   // 'operator<=>' when parsing the '<=>' token.
18007   if (DefKind.isComparison() &&
18008       DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
18009     Diag(DefaultLoc, getLangOpts().CPlusPlus20
18010                          ? diag::warn_cxx17_compat_defaulted_comparison
18011                          : diag::ext_defaulted_comparison);
18012   }
18013 
18014   FD->setDefaulted();
18015   FD->setExplicitlyDefaulted();
18016   FD->setDefaultLoc(DefaultLoc);
18017 
18018   // Defer checking functions that are defaulted in a dependent context.
18019   if (FD->isDependentContext())
18020     return;
18021 
18022   // Unset that we will have a body for this function. We might not,
18023   // if it turns out to be trivial, and we don't need this marking now
18024   // that we've marked it as defaulted.
18025   FD->setWillHaveBody(false);
18026 
18027   if (DefKind.isComparison()) {
18028     // If this comparison's defaulting occurs within the definition of its
18029     // lexical class context, we have to do the checking when complete.
18030     if (auto const *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()))
18031       if (!RD->isCompleteDefinition())
18032         return;
18033   }
18034 
18035   // If this member fn was defaulted on its first declaration, we will have
18036   // already performed the checking in CheckCompletedCXXClass. Such a
18037   // declaration doesn't trigger an implicit definition.
18038   if (isa<CXXMethodDecl>(FD)) {
18039     const FunctionDecl *Primary = FD;
18040     if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
18041       // Ask the template instantiation pattern that actually had the
18042       // '= default' on it.
18043       Primary = Pattern;
18044     if (Primary->getCanonicalDecl()->isDefaulted())
18045       return;
18046   }
18047 
18048   if (DefKind.isComparison()) {
18049     if (CheckExplicitlyDefaultedComparison(nullptr, FD, DefKind.asComparison()))
18050       FD->setInvalidDecl();
18051     else
18052       DefineDefaultedComparison(DefaultLoc, FD, DefKind.asComparison());
18053   } else {
18054     auto *MD = cast<CXXMethodDecl>(FD);
18055 
18056     if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember(),
18057                                               DefaultLoc))
18058       MD->setInvalidDecl();
18059     else
18060       DefineDefaultedFunction(*this, MD, DefaultLoc);
18061   }
18062 }
18063 
18064 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
18065   for (Stmt *SubStmt : S->children()) {
18066     if (!SubStmt)
18067       continue;
18068     if (isa<ReturnStmt>(SubStmt))
18069       Self.Diag(SubStmt->getBeginLoc(),
18070                 diag::err_return_in_constructor_handler);
18071     if (!isa<Expr>(SubStmt))
18072       SearchForReturnInStmt(Self, SubStmt);
18073   }
18074 }
18075 
18076 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
18077   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
18078     CXXCatchStmt *Handler = TryBlock->getHandler(I);
18079     SearchForReturnInStmt(*this, Handler);
18080   }
18081 }
18082 
18083 void Sema::SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind,
18084                                StringLiteral *DeletedMessage) {
18085   switch (BodyKind) {
18086   case FnBodyKind::Delete:
18087     SetDeclDeleted(D, Loc, DeletedMessage);
18088     break;
18089   case FnBodyKind::Default:
18090     SetDeclDefaulted(D, Loc);
18091     break;
18092   case FnBodyKind::Other:
18093     llvm_unreachable(
18094         "Parsed function body should be '= delete;' or '= default;'");
18095   }
18096 }
18097 
18098 bool Sema::CheckOverridingFunctionAttributes(CXXMethodDecl *New,
18099                                              const CXXMethodDecl *Old) {
18100   const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
18101   const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
18102 
18103   if (OldFT->hasExtParameterInfos()) {
18104     for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
18105       // A parameter of the overriding method should be annotated with noescape
18106       // if the corresponding parameter of the overridden method is annotated.
18107       if (OldFT->getExtParameterInfo(I).isNoEscape() &&
18108           !NewFT->getExtParameterInfo(I).isNoEscape()) {
18109         Diag(New->getParamDecl(I)->getLocation(),
18110              diag::warn_overriding_method_missing_noescape);
18111         Diag(Old->getParamDecl(I)->getLocation(),
18112              diag::note_overridden_marked_noescape);
18113       }
18114   }
18115 
18116   // SME attributes must match when overriding a function declaration.
18117   if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
18118     Diag(New->getLocation(), diag::err_conflicting_overriding_attributes)
18119         << New << New->getType() << Old->getType();
18120     Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18121     return true;
18122   }
18123 
18124   // Virtual overrides must have the same code_seg.
18125   const auto *OldCSA = Old->getAttr<CodeSegAttr>();
18126   const auto *NewCSA = New->getAttr<CodeSegAttr>();
18127   if ((NewCSA || OldCSA) &&
18128       (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
18129     Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
18130     Diag(Old->getLocation(), diag::note_previous_declaration);
18131     return true;
18132   }
18133 
18134   // Virtual overrides: check for matching effects.
18135   if (Context.hasAnyFunctionEffects()) {
18136     const auto OldFX = Old->getFunctionEffects();
18137     const auto NewFXOrig = New->getFunctionEffects();
18138 
18139     if (OldFX != NewFXOrig) {
18140       FunctionEffectSet NewFX(NewFXOrig);
18141       const auto Diffs = FunctionEffectDifferences(OldFX, NewFX);
18142       FunctionEffectSet::Conflicts Errs;
18143       for (const auto &Diff : Diffs) {
18144         switch (Diff.shouldDiagnoseMethodOverride(*Old, OldFX, *New, NewFX)) {
18145         case FunctionEffectDiff::OverrideResult::NoAction:
18146           break;
18147         case FunctionEffectDiff::OverrideResult::Warn:
18148           Diag(New->getLocation(), diag::warn_mismatched_func_effect_override)
18149               << Diff.effectName();
18150           Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18151               << Old->getReturnTypeSourceRange();
18152           break;
18153         case FunctionEffectDiff::OverrideResult::Merge: {
18154           NewFX.insert(Diff.Old, Errs);
18155           const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
18156           FunctionProtoType::ExtProtoInfo EPI = NewFT->getExtProtoInfo();
18157           EPI.FunctionEffects = FunctionEffectsRef(NewFX);
18158           QualType ModQT = Context.getFunctionType(NewFT->getReturnType(),
18159                                                    NewFT->getParamTypes(), EPI);
18160           New->setType(ModQT);
18161           break;
18162         }
18163         }
18164       }
18165       if (!Errs.empty())
18166         diagnoseFunctionEffectMergeConflicts(Errs, New->getLocation(),
18167                                              Old->getLocation());
18168     }
18169   }
18170 
18171   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
18172 
18173   // If the calling conventions match, everything is fine
18174   if (NewCC == OldCC)
18175     return false;
18176 
18177   // If the calling conventions mismatch because the new function is static,
18178   // suppress the calling convention mismatch error; the error about static
18179   // function override (err_static_overrides_virtual from
18180   // Sema::CheckFunctionDeclaration) is more clear.
18181   if (New->getStorageClass() == SC_Static)
18182     return false;
18183 
18184   Diag(New->getLocation(),
18185        diag::err_conflicting_overriding_cc_attributes)
18186     << New->getDeclName() << New->getType() << Old->getType();
18187   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18188   return true;
18189 }
18190 
18191 bool Sema::CheckExplicitObjectOverride(CXXMethodDecl *New,
18192                                        const CXXMethodDecl *Old) {
18193   // CWG2553
18194   // A virtual function shall not be an explicit object member function.
18195   if (!New->isExplicitObjectMemberFunction())
18196     return true;
18197   Diag(New->getParamDecl(0)->getBeginLoc(),
18198        diag::err_explicit_object_parameter_nonmember)
18199       << New->getSourceRange() << /*virtual*/ 1 << /*IsLambda*/ false;
18200   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18201   New->setInvalidDecl();
18202   return false;
18203 }
18204 
18205 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
18206                                              const CXXMethodDecl *Old) {
18207   QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
18208   QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
18209 
18210   if (Context.hasSameType(NewTy, OldTy) ||
18211       NewTy->isDependentType() || OldTy->isDependentType())
18212     return false;
18213 
18214   // Check if the return types are covariant
18215   QualType NewClassTy, OldClassTy;
18216 
18217   /// Both types must be pointers or references to classes.
18218   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
18219     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
18220       NewClassTy = NewPT->getPointeeType();
18221       OldClassTy = OldPT->getPointeeType();
18222     }
18223   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
18224     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
18225       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
18226         NewClassTy = NewRT->getPointeeType();
18227         OldClassTy = OldRT->getPointeeType();
18228       }
18229     }
18230   }
18231 
18232   // The return types aren't either both pointers or references to a class type.
18233   if (NewClassTy.isNull()) {
18234     Diag(New->getLocation(),
18235          diag::err_different_return_type_for_overriding_virtual_function)
18236         << New->getDeclName() << NewTy << OldTy
18237         << New->getReturnTypeSourceRange();
18238     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18239         << Old->getReturnTypeSourceRange();
18240 
18241     return true;
18242   }
18243 
18244   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
18245     // C++14 [class.virtual]p8:
18246     //   If the class type in the covariant return type of D::f differs from
18247     //   that of B::f, the class type in the return type of D::f shall be
18248     //   complete at the point of declaration of D::f or shall be the class
18249     //   type D.
18250     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
18251       if (!RT->isBeingDefined() &&
18252           RequireCompleteType(New->getLocation(), NewClassTy,
18253                               diag::err_covariant_return_incomplete,
18254                               New->getDeclName()))
18255         return true;
18256     }
18257 
18258     // Check if the new class derives from the old class.
18259     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
18260       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
18261           << New->getDeclName() << NewTy << OldTy
18262           << New->getReturnTypeSourceRange();
18263       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18264           << Old->getReturnTypeSourceRange();
18265       return true;
18266     }
18267 
18268     // Check if we the conversion from derived to base is valid.
18269     if (CheckDerivedToBaseConversion(
18270             NewClassTy, OldClassTy,
18271             diag::err_covariant_return_inaccessible_base,
18272             diag::err_covariant_return_ambiguous_derived_to_base_conv,
18273             New->getLocation(), New->getReturnTypeSourceRange(),
18274             New->getDeclName(), nullptr)) {
18275       // FIXME: this note won't trigger for delayed access control
18276       // diagnostics, and it's impossible to get an undelayed error
18277       // here from access control during the original parse because
18278       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
18279       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18280           << Old->getReturnTypeSourceRange();
18281       return true;
18282     }
18283   }
18284 
18285   // The qualifiers of the return types must be the same.
18286   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
18287     Diag(New->getLocation(),
18288          diag::err_covariant_return_type_different_qualifications)
18289         << New->getDeclName() << NewTy << OldTy
18290         << New->getReturnTypeSourceRange();
18291     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18292         << Old->getReturnTypeSourceRange();
18293     return true;
18294   }
18295 
18296 
18297   // The new class type must have the same or less qualifiers as the old type.
18298   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
18299     Diag(New->getLocation(),
18300          diag::err_covariant_return_type_class_type_more_qualified)
18301         << New->getDeclName() << NewTy << OldTy
18302         << New->getReturnTypeSourceRange();
18303     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18304         << Old->getReturnTypeSourceRange();
18305     return true;
18306   }
18307 
18308   return false;
18309 }
18310 
18311 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
18312   SourceLocation EndLoc = InitRange.getEnd();
18313   if (EndLoc.isValid())
18314     Method->setRangeEnd(EndLoc);
18315 
18316   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
18317     Method->setIsPureVirtual();
18318     return false;
18319   }
18320 
18321   if (!Method->isInvalidDecl())
18322     Diag(Method->getLocation(), diag::err_non_virtual_pure)
18323       << Method->getDeclName() << InitRange;
18324   return true;
18325 }
18326 
18327 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
18328   if (D->getFriendObjectKind())
18329     Diag(D->getLocation(), diag::err_pure_friend);
18330   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
18331     CheckPureMethod(M, ZeroLoc);
18332   else
18333     Diag(D->getLocation(), diag::err_illegal_initializer);
18334 }
18335 
18336 /// Invoked when we are about to parse an initializer for the declaration
18337 /// 'Dcl'.
18338 ///
18339 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
18340 /// static data member of class X, names should be looked up in the scope of
18341 /// class X. If the declaration had a scope specifier, a scope will have
18342 /// been created and passed in for this purpose. Otherwise, S will be null.
18343 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
18344   assert(D && !D->isInvalidDecl());
18345 
18346   // We will always have a nested name specifier here, but this declaration
18347   // might not be out of line if the specifier names the current namespace:
18348   //   extern int n;
18349   //   int ::n = 0;
18350   if (S && D->isOutOfLine())
18351     EnterDeclaratorContext(S, D->getDeclContext());
18352 
18353   PushExpressionEvaluationContext(
18354       ExpressionEvaluationContext::PotentiallyEvaluated, D);
18355 }
18356 
18357 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
18358   assert(D);
18359 
18360   if (S && D->isOutOfLine())
18361     ExitDeclaratorContext(S);
18362 
18363   if (getLangOpts().CPlusPlus23) {
18364     // An expression or conversion is 'manifestly constant-evaluated' if it is:
18365     // [...]
18366     // - the initializer of a variable that is usable in constant expressions or
18367     //   has constant initialization.
18368     if (auto *VD = dyn_cast<VarDecl>(D);
18369         VD && (VD->isUsableInConstantExpressions(Context) ||
18370                VD->hasConstantInitialization())) {
18371       // An expression or conversion is in an 'immediate function context' if it
18372       // is potentially evaluated and either:
18373       // [...]
18374       // - it is a subexpression of a manifestly constant-evaluated expression
18375       //   or conversion.
18376       ExprEvalContexts.back().InImmediateFunctionContext = true;
18377     }
18378   }
18379 
18380   // Unless the initializer is in an immediate function context (as determined
18381   // above), this will evaluate all contained immediate function calls as
18382   // constant expressions. If the initializer IS an immediate function context,
18383   // the initializer has been determined to be a constant expression, and all
18384   // such evaluations will be elided (i.e., as if we "knew the whole time" that
18385   // it was a constant expression).
18386   PopExpressionEvaluationContext();
18387 }
18388 
18389 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
18390   // C++ 6.4p2:
18391   // The declarator shall not specify a function or an array.
18392   // The type-specifier-seq shall not contain typedef and shall not declare a
18393   // new class or enumeration.
18394   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
18395          "Parser allowed 'typedef' as storage class of condition decl.");
18396 
18397   Decl *Dcl = ActOnDeclarator(S, D);
18398   if (!Dcl)
18399     return true;
18400 
18401   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
18402     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
18403       << D.getSourceRange();
18404     return true;
18405   }
18406 
18407   if (auto *VD = dyn_cast<VarDecl>(Dcl))
18408     VD->setCXXCondDecl();
18409 
18410   return Dcl;
18411 }
18412 
18413 void Sema::LoadExternalVTableUses() {
18414   if (!ExternalSource)
18415     return;
18416 
18417   SmallVector<ExternalVTableUse, 4> VTables;
18418   ExternalSource->ReadUsedVTables(VTables);
18419   SmallVector<VTableUse, 4> NewUses;
18420   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
18421     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
18422       = VTablesUsed.find(VTables[I].Record);
18423     // Even if a definition wasn't required before, it may be required now.
18424     if (Pos != VTablesUsed.end()) {
18425       if (!Pos->second && VTables[I].DefinitionRequired)
18426         Pos->second = true;
18427       continue;
18428     }
18429 
18430     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
18431     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
18432   }
18433 
18434   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
18435 }
18436 
18437 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
18438                           bool DefinitionRequired) {
18439   // Ignore any vtable uses in unevaluated operands or for classes that do
18440   // not have a vtable.
18441   if (!Class->isDynamicClass() || Class->isDependentContext() ||
18442       CurContext->isDependentContext() || isUnevaluatedContext())
18443     return;
18444   // Do not mark as used if compiling for the device outside of the target
18445   // region.
18446   if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice &&
18447       !OpenMP().isInOpenMPDeclareTargetContext() &&
18448       !OpenMP().isInOpenMPTargetExecutionDirective()) {
18449     if (!DefinitionRequired)
18450       MarkVirtualMembersReferenced(Loc, Class);
18451     return;
18452   }
18453 
18454   // Try to insert this class into the map.
18455   LoadExternalVTableUses();
18456   Class = Class->getCanonicalDecl();
18457   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
18458     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
18459   if (!Pos.second) {
18460     // If we already had an entry, check to see if we are promoting this vtable
18461     // to require a definition. If so, we need to reappend to the VTableUses
18462     // list, since we may have already processed the first entry.
18463     if (DefinitionRequired && !Pos.first->second) {
18464       Pos.first->second = true;
18465     } else {
18466       // Otherwise, we can early exit.
18467       return;
18468     }
18469   } else {
18470     // The Microsoft ABI requires that we perform the destructor body
18471     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
18472     // the deleting destructor is emitted with the vtable, not with the
18473     // destructor definition as in the Itanium ABI.
18474     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
18475       CXXDestructorDecl *DD = Class->getDestructor();
18476       if (DD && DD->isVirtual() && !DD->isDeleted()) {
18477         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
18478           // If this is an out-of-line declaration, marking it referenced will
18479           // not do anything. Manually call CheckDestructor to look up operator
18480           // delete().
18481           ContextRAII SavedContext(*this, DD);
18482           CheckDestructor(DD);
18483         } else {
18484           MarkFunctionReferenced(Loc, Class->getDestructor());
18485         }
18486       }
18487     }
18488   }
18489 
18490   // Local classes need to have their virtual members marked
18491   // immediately. For all other classes, we mark their virtual members
18492   // at the end of the translation unit.
18493   if (Class->isLocalClass())
18494     MarkVirtualMembersReferenced(Loc, Class->getDefinition());
18495   else
18496     VTableUses.push_back(std::make_pair(Class, Loc));
18497 }
18498 
18499 bool Sema::DefineUsedVTables() {
18500   LoadExternalVTableUses();
18501   if (VTableUses.empty())
18502     return false;
18503 
18504   // Note: The VTableUses vector could grow as a result of marking
18505   // the members of a class as "used", so we check the size each
18506   // time through the loop and prefer indices (which are stable) to
18507   // iterators (which are not).
18508   bool DefinedAnything = false;
18509   for (unsigned I = 0; I != VTableUses.size(); ++I) {
18510     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
18511     if (!Class)
18512       continue;
18513     TemplateSpecializationKind ClassTSK =
18514         Class->getTemplateSpecializationKind();
18515 
18516     SourceLocation Loc = VTableUses[I].second;
18517 
18518     bool DefineVTable = true;
18519 
18520     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
18521     // V-tables for non-template classes with an owning module are always
18522     // uniquely emitted in that module.
18523     if (Class->isInCurrentModuleUnit()) {
18524       DefineVTable = true;
18525     } else if (KeyFunction && !KeyFunction->hasBody()) {
18526       // If this class has a key function, but that key function is
18527       // defined in another translation unit, we don't need to emit the
18528       // vtable even though we're using it.
18529       // The key function is in another translation unit.
18530       DefineVTable = false;
18531       TemplateSpecializationKind TSK =
18532           KeyFunction->getTemplateSpecializationKind();
18533       assert(TSK != TSK_ExplicitInstantiationDefinition &&
18534              TSK != TSK_ImplicitInstantiation &&
18535              "Instantiations don't have key functions");
18536       (void)TSK;
18537     } else if (!KeyFunction) {
18538       // If we have a class with no key function that is the subject
18539       // of an explicit instantiation declaration, suppress the
18540       // vtable; it will live with the explicit instantiation
18541       // definition.
18542       bool IsExplicitInstantiationDeclaration =
18543           ClassTSK == TSK_ExplicitInstantiationDeclaration;
18544       for (auto *R : Class->redecls()) {
18545         TemplateSpecializationKind TSK
18546           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
18547         if (TSK == TSK_ExplicitInstantiationDeclaration)
18548           IsExplicitInstantiationDeclaration = true;
18549         else if (TSK == TSK_ExplicitInstantiationDefinition) {
18550           IsExplicitInstantiationDeclaration = false;
18551           break;
18552         }
18553       }
18554 
18555       if (IsExplicitInstantiationDeclaration)
18556         DefineVTable = false;
18557     }
18558 
18559     // The exception specifications for all virtual members may be needed even
18560     // if we are not providing an authoritative form of the vtable in this TU.
18561     // We may choose to emit it available_externally anyway.
18562     if (!DefineVTable) {
18563       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
18564       continue;
18565     }
18566 
18567     // Mark all of the virtual members of this class as referenced, so
18568     // that we can build a vtable. Then, tell the AST consumer that a
18569     // vtable for this class is required.
18570     DefinedAnything = true;
18571     MarkVirtualMembersReferenced(Loc, Class);
18572     CXXRecordDecl *Canonical = Class->getCanonicalDecl();
18573     if (VTablesUsed[Canonical] && !Class->shouldEmitInExternalSource())
18574       Consumer.HandleVTable(Class);
18575 
18576     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
18577     // no key function or the key function is inlined. Don't warn in C++ ABIs
18578     // that lack key functions, since the user won't be able to make one.
18579     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
18580         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation &&
18581         ClassTSK != TSK_ExplicitInstantiationDefinition) {
18582       const FunctionDecl *KeyFunctionDef = nullptr;
18583       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
18584                            KeyFunctionDef->isInlined()))
18585         Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
18586     }
18587   }
18588   VTableUses.clear();
18589 
18590   return DefinedAnything;
18591 }
18592 
18593 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
18594                                                  const CXXRecordDecl *RD) {
18595   for (const auto *I : RD->methods())
18596     if (I->isVirtual() && !I->isPureVirtual())
18597       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
18598 }
18599 
18600 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
18601                                         const CXXRecordDecl *RD,
18602                                         bool ConstexprOnly) {
18603   // Mark all functions which will appear in RD's vtable as used.
18604   CXXFinalOverriderMap FinalOverriders;
18605   RD->getFinalOverriders(FinalOverriders);
18606   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
18607                                             E = FinalOverriders.end();
18608        I != E; ++I) {
18609     for (OverridingMethods::const_iterator OI = I->second.begin(),
18610                                            OE = I->second.end();
18611          OI != OE; ++OI) {
18612       assert(OI->second.size() > 0 && "no final overrider");
18613       CXXMethodDecl *Overrider = OI->second.front().Method;
18614 
18615       // C++ [basic.def.odr]p2:
18616       //   [...] A virtual member function is used if it is not pure. [...]
18617       if (!Overrider->isPureVirtual() &&
18618           (!ConstexprOnly || Overrider->isConstexpr()))
18619         MarkFunctionReferenced(Loc, Overrider);
18620     }
18621   }
18622 
18623   // Only classes that have virtual bases need a VTT.
18624   if (RD->getNumVBases() == 0)
18625     return;
18626 
18627   for (const auto &I : RD->bases()) {
18628     const auto *Base =
18629         cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
18630     if (Base->getNumVBases() == 0)
18631       continue;
18632     MarkVirtualMembersReferenced(Loc, Base);
18633   }
18634 }
18635 
18636 static
18637 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
18638                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
18639                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
18640                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
18641                            Sema &S) {
18642   if (Ctor->isInvalidDecl())
18643     return;
18644 
18645   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
18646 
18647   // Target may not be determinable yet, for instance if this is a dependent
18648   // call in an uninstantiated template.
18649   if (Target) {
18650     const FunctionDecl *FNTarget = nullptr;
18651     (void)Target->hasBody(FNTarget);
18652     Target = const_cast<CXXConstructorDecl*>(
18653       cast_or_null<CXXConstructorDecl>(FNTarget));
18654   }
18655 
18656   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
18657                      // Avoid dereferencing a null pointer here.
18658                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
18659 
18660   if (!Current.insert(Canonical).second)
18661     return;
18662 
18663   // We know that beyond here, we aren't chaining into a cycle.
18664   if (!Target || !Target->isDelegatingConstructor() ||
18665       Target->isInvalidDecl() || Valid.count(TCanonical)) {
18666     Valid.insert(Current.begin(), Current.end());
18667     Current.clear();
18668   // We've hit a cycle.
18669   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
18670              Current.count(TCanonical)) {
18671     // If we haven't diagnosed this cycle yet, do so now.
18672     if (!Invalid.count(TCanonical)) {
18673       S.Diag((*Ctor->init_begin())->getSourceLocation(),
18674              diag::warn_delegating_ctor_cycle)
18675         << Ctor;
18676 
18677       // Don't add a note for a function delegating directly to itself.
18678       if (TCanonical != Canonical)
18679         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
18680 
18681       CXXConstructorDecl *C = Target;
18682       while (C->getCanonicalDecl() != Canonical) {
18683         const FunctionDecl *FNTarget = nullptr;
18684         (void)C->getTargetConstructor()->hasBody(FNTarget);
18685         assert(FNTarget && "Ctor cycle through bodiless function");
18686 
18687         C = const_cast<CXXConstructorDecl*>(
18688           cast<CXXConstructorDecl>(FNTarget));
18689         S.Diag(C->getLocation(), diag::note_which_delegates_to);
18690       }
18691     }
18692 
18693     Invalid.insert(Current.begin(), Current.end());
18694     Current.clear();
18695   } else {
18696     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
18697   }
18698 }
18699 
18700 
18701 void Sema::CheckDelegatingCtorCycles() {
18702   llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
18703 
18704   for (DelegatingCtorDeclsType::iterator
18705            I = DelegatingCtorDecls.begin(ExternalSource.get()),
18706            E = DelegatingCtorDecls.end();
18707        I != E; ++I)
18708     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
18709 
18710   for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
18711     (*CI)->setInvalidDecl();
18712 }
18713 
18714 namespace {
18715   /// AST visitor that finds references to the 'this' expression.
18716   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
18717     Sema &S;
18718 
18719   public:
18720     explicit FindCXXThisExpr(Sema &S) : S(S) { }
18721 
18722     bool VisitCXXThisExpr(CXXThisExpr *E) {
18723       S.Diag(E->getLocation(), diag::err_this_static_member_func)
18724         << E->isImplicit();
18725       return false;
18726     }
18727   };
18728 }
18729 
18730 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
18731   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
18732   if (!TSInfo)
18733     return false;
18734 
18735   TypeLoc TL = TSInfo->getTypeLoc();
18736   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
18737   if (!ProtoTL)
18738     return false;
18739 
18740   // C++11 [expr.prim.general]p3:
18741   //   [The expression this] shall not appear before the optional
18742   //   cv-qualifier-seq and it shall not appear within the declaration of a
18743   //   static member function (although its type and value category are defined
18744   //   within a static member function as they are within a non-static member
18745   //   function). [ Note: this is because declaration matching does not occur
18746   //  until the complete declarator is known. - end note ]
18747   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
18748   FindCXXThisExpr Finder(*this);
18749 
18750   // If the return type came after the cv-qualifier-seq, check it now.
18751   if (Proto->hasTrailingReturn() &&
18752       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
18753     return true;
18754 
18755   // Check the exception specification.
18756   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
18757     return true;
18758 
18759   // Check the trailing requires clause
18760   if (Expr *E = Method->getTrailingRequiresClause())
18761     if (!Finder.TraverseStmt(E))
18762       return true;
18763 
18764   return checkThisInStaticMemberFunctionAttributes(Method);
18765 }
18766 
18767 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
18768   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
18769   if (!TSInfo)
18770     return false;
18771 
18772   TypeLoc TL = TSInfo->getTypeLoc();
18773   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
18774   if (!ProtoTL)
18775     return false;
18776 
18777   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
18778   FindCXXThisExpr Finder(*this);
18779 
18780   switch (Proto->getExceptionSpecType()) {
18781   case EST_Unparsed:
18782   case EST_Uninstantiated:
18783   case EST_Unevaluated:
18784   case EST_BasicNoexcept:
18785   case EST_NoThrow:
18786   case EST_DynamicNone:
18787   case EST_MSAny:
18788   case EST_None:
18789     break;
18790 
18791   case EST_DependentNoexcept:
18792   case EST_NoexceptFalse:
18793   case EST_NoexceptTrue:
18794     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
18795       return true;
18796     [[fallthrough]];
18797 
18798   case EST_Dynamic:
18799     for (const auto &E : Proto->exceptions()) {
18800       if (!Finder.TraverseType(E))
18801         return true;
18802     }
18803     break;
18804   }
18805 
18806   return false;
18807 }
18808 
18809 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
18810   FindCXXThisExpr Finder(*this);
18811 
18812   // Check attributes.
18813   for (const auto *A : Method->attrs()) {
18814     // FIXME: This should be emitted by tblgen.
18815     Expr *Arg = nullptr;
18816     ArrayRef<Expr *> Args;
18817     if (const auto *G = dyn_cast<GuardedByAttr>(A))
18818       Arg = G->getArg();
18819     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
18820       Arg = G->getArg();
18821     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
18822       Args = llvm::ArrayRef(AA->args_begin(), AA->args_size());
18823     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
18824       Args = llvm::ArrayRef(AB->args_begin(), AB->args_size());
18825     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
18826       Arg = ETLF->getSuccessValue();
18827       Args = llvm::ArrayRef(ETLF->args_begin(), ETLF->args_size());
18828     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
18829       Arg = STLF->getSuccessValue();
18830       Args = llvm::ArrayRef(STLF->args_begin(), STLF->args_size());
18831     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
18832       Arg = LR->getArg();
18833     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
18834       Args = llvm::ArrayRef(LE->args_begin(), LE->args_size());
18835     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
18836       Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
18837     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
18838       Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
18839     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
18840       Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
18841     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
18842       Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
18843 
18844     if (Arg && !Finder.TraverseStmt(Arg))
18845       return true;
18846 
18847     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
18848       if (!Finder.TraverseStmt(Args[I]))
18849         return true;
18850     }
18851   }
18852 
18853   return false;
18854 }
18855 
18856 void Sema::checkExceptionSpecification(
18857     bool IsTopLevel, ExceptionSpecificationType EST,
18858     ArrayRef<ParsedType> DynamicExceptions,
18859     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
18860     SmallVectorImpl<QualType> &Exceptions,
18861     FunctionProtoType::ExceptionSpecInfo &ESI) {
18862   Exceptions.clear();
18863   ESI.Type = EST;
18864   if (EST == EST_Dynamic) {
18865     Exceptions.reserve(DynamicExceptions.size());
18866     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
18867       // FIXME: Preserve type source info.
18868       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
18869 
18870       if (IsTopLevel) {
18871         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
18872         collectUnexpandedParameterPacks(ET, Unexpanded);
18873         if (!Unexpanded.empty()) {
18874           DiagnoseUnexpandedParameterPacks(
18875               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
18876               Unexpanded);
18877           continue;
18878         }
18879       }
18880 
18881       // Check that the type is valid for an exception spec, and
18882       // drop it if not.
18883       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
18884         Exceptions.push_back(ET);
18885     }
18886     ESI.Exceptions = Exceptions;
18887     return;
18888   }
18889 
18890   if (isComputedNoexcept(EST)) {
18891     assert((NoexceptExpr->isTypeDependent() ||
18892             NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
18893             Context.BoolTy) &&
18894            "Parser should have made sure that the expression is boolean");
18895     if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
18896       ESI.Type = EST_BasicNoexcept;
18897       return;
18898     }
18899 
18900     ESI.NoexceptExpr = NoexceptExpr;
18901     return;
18902   }
18903 }
18904 
18905 void Sema::actOnDelayedExceptionSpecification(
18906     Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange,
18907     ArrayRef<ParsedType> DynamicExceptions,
18908     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr) {
18909   if (!D)
18910     return;
18911 
18912   // Dig out the function we're referring to.
18913   if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
18914     D = FTD->getTemplatedDecl();
18915 
18916   FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
18917   if (!FD)
18918     return;
18919 
18920   // Check the exception specification.
18921   llvm::SmallVector<QualType, 4> Exceptions;
18922   FunctionProtoType::ExceptionSpecInfo ESI;
18923   checkExceptionSpecification(/*IsTopLevel=*/true, EST, DynamicExceptions,
18924                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
18925                               ESI);
18926 
18927   // Update the exception specification on the function type.
18928   Context.adjustExceptionSpec(FD, ESI, /*AsWritten=*/true);
18929 
18930   if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
18931     if (MD->isStatic())
18932       checkThisInStaticMemberFunctionExceptionSpec(MD);
18933 
18934     if (MD->isVirtual()) {
18935       // Check overrides, which we previously had to delay.
18936       for (const CXXMethodDecl *O : MD->overridden_methods())
18937         CheckOverridingFunctionExceptionSpec(MD, O);
18938     }
18939   }
18940 }
18941 
18942 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
18943 ///
18944 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
18945                                        SourceLocation DeclStart, Declarator &D,
18946                                        Expr *BitWidth,
18947                                        InClassInitStyle InitStyle,
18948                                        AccessSpecifier AS,
18949                                        const ParsedAttr &MSPropertyAttr) {
18950   const IdentifierInfo *II = D.getIdentifier();
18951   if (!II) {
18952     Diag(DeclStart, diag::err_anonymous_property);
18953     return nullptr;
18954   }
18955   SourceLocation Loc = D.getIdentifierLoc();
18956 
18957   TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
18958   QualType T = TInfo->getType();
18959   if (getLangOpts().CPlusPlus) {
18960     CheckExtraCXXDefaultArguments(D);
18961 
18962     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
18963                                         UPPC_DataMemberType)) {
18964       D.setInvalidType();
18965       T = Context.IntTy;
18966       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
18967     }
18968   }
18969 
18970   DiagnoseFunctionSpecifiers(D.getDeclSpec());
18971 
18972   if (D.getDeclSpec().isInlineSpecified())
18973     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
18974         << getLangOpts().CPlusPlus17;
18975   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
18976     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
18977          diag::err_invalid_thread)
18978       << DeclSpec::getSpecifierName(TSCS);
18979 
18980   // Check to see if this name was declared as a member previously
18981   NamedDecl *PrevDecl = nullptr;
18982   LookupResult Previous(*this, II, Loc, LookupMemberName,
18983                         RedeclarationKind::ForVisibleRedeclaration);
18984   LookupName(Previous, S);
18985   switch (Previous.getResultKind()) {
18986   case LookupResult::Found:
18987   case LookupResult::FoundUnresolvedValue:
18988     PrevDecl = Previous.getAsSingle<NamedDecl>();
18989     break;
18990 
18991   case LookupResult::FoundOverloaded:
18992     PrevDecl = Previous.getRepresentativeDecl();
18993     break;
18994 
18995   case LookupResult::NotFound:
18996   case LookupResult::NotFoundInCurrentInstantiation:
18997   case LookupResult::Ambiguous:
18998     break;
18999   }
19000 
19001   if (PrevDecl && PrevDecl->isTemplateParameter()) {
19002     // Maybe we will complain about the shadowed template parameter.
19003     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
19004     // Just pretend that we didn't see the previous declaration.
19005     PrevDecl = nullptr;
19006   }
19007 
19008   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
19009     PrevDecl = nullptr;
19010 
19011   SourceLocation TSSL = D.getBeginLoc();
19012   MSPropertyDecl *NewPD =
19013       MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
19014                              MSPropertyAttr.getPropertyDataGetter(),
19015                              MSPropertyAttr.getPropertyDataSetter());
19016   ProcessDeclAttributes(TUScope, NewPD, D);
19017   NewPD->setAccess(AS);
19018 
19019   if (NewPD->isInvalidDecl())
19020     Record->setInvalidDecl();
19021 
19022   if (D.getDeclSpec().isModulePrivateSpecified())
19023     NewPD->setModulePrivate();
19024 
19025   if (NewPD->isInvalidDecl() && PrevDecl) {
19026     // Don't introduce NewFD into scope; there's already something
19027     // with the same name in the same scope.
19028   } else if (II) {
19029     PushOnScopeChains(NewPD, S);
19030   } else
19031     Record->addDecl(NewPD);
19032 
19033   return NewPD;
19034 }
19035 
19036 void Sema::ActOnStartFunctionDeclarationDeclarator(
19037     Declarator &Declarator, unsigned TemplateParameterDepth) {
19038   auto &Info = InventedParameterInfos.emplace_back();
19039   TemplateParameterList *ExplicitParams = nullptr;
19040   ArrayRef<TemplateParameterList *> ExplicitLists =
19041       Declarator.getTemplateParameterLists();
19042   if (!ExplicitLists.empty()) {
19043     bool IsMemberSpecialization, IsInvalid;
19044     ExplicitParams = MatchTemplateParametersToScopeSpecifier(
19045         Declarator.getBeginLoc(), Declarator.getIdentifierLoc(),
19046         Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
19047         ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
19048         /*SuppressDiagnostic=*/true);
19049   }
19050   // C++23 [dcl.fct]p23:
19051   //   An abbreviated function template can have a template-head. The invented
19052   //   template-parameters are appended to the template-parameter-list after
19053   //   the explicitly declared template-parameters.
19054   //
19055   // A template-head must have one or more template-parameters (read:
19056   // 'template<>' is *not* a template-head). Only append the invented
19057   // template parameters if we matched the nested-name-specifier to a non-empty
19058   // TemplateParameterList.
19059   if (ExplicitParams && !ExplicitParams->empty()) {
19060     Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
19061     llvm::append_range(Info.TemplateParams, *ExplicitParams);
19062     Info.NumExplicitTemplateParams = ExplicitParams->size();
19063   } else {
19064     Info.AutoTemplateParameterDepth = TemplateParameterDepth;
19065     Info.NumExplicitTemplateParams = 0;
19066   }
19067 }
19068 
19069 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
19070   auto &FSI = InventedParameterInfos.back();
19071   if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
19072     if (FSI.NumExplicitTemplateParams != 0) {
19073       TemplateParameterList *ExplicitParams =
19074           Declarator.getTemplateParameterLists().back();
19075       Declarator.setInventedTemplateParameterList(
19076           TemplateParameterList::Create(
19077               Context, ExplicitParams->getTemplateLoc(),
19078               ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
19079               ExplicitParams->getRAngleLoc(),
19080               ExplicitParams->getRequiresClause()));
19081     } else {
19082       Declarator.setInventedTemplateParameterList(
19083           TemplateParameterList::Create(
19084               Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
19085               SourceLocation(), /*RequiresClause=*/nullptr));
19086     }
19087   }
19088   InventedParameterInfos.pop_back();
19089 }
19090