xref: /freebsd/contrib/llvm-project/clang/lib/Sema/SemaDeclCXX.cpp (revision f126890ac5386406dadf7c4cfa9566cbb56537c5)
1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for C++ declarations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/AST/ASTConsumer.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/ASTLambda.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/ComparisonCategories.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/RecordLayout.h"
25 #include "clang/AST/RecursiveASTVisitor.h"
26 #include "clang/AST/StmtVisitor.h"
27 #include "clang/AST/TypeLoc.h"
28 #include "clang/AST/TypeOrdering.h"
29 #include "clang/Basic/AttributeCommonInfo.h"
30 #include "clang/Basic/PartialDiagnostic.h"
31 #include "clang/Basic/Specifiers.h"
32 #include "clang/Basic/TargetInfo.h"
33 #include "clang/Lex/LiteralSupport.h"
34 #include "clang/Lex/Preprocessor.h"
35 #include "clang/Sema/CXXFieldCollector.h"
36 #include "clang/Sema/DeclSpec.h"
37 #include "clang/Sema/EnterExpressionEvaluationContext.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaInternal.h"
44 #include "clang/Sema/Template.h"
45 #include "llvm/ADT/STLExtras.h"
46 #include "llvm/ADT/ScopeExit.h"
47 #include "llvm/ADT/SmallString.h"
48 #include "llvm/ADT/StringExtras.h"
49 #include "llvm/Support/SaveAndRestore.h"
50 #include <map>
51 #include <optional>
52 #include <set>
53 
54 using namespace clang;
55 
56 //===----------------------------------------------------------------------===//
57 // CheckDefaultArgumentVisitor
58 //===----------------------------------------------------------------------===//
59 
60 namespace {
61 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
62 /// the default argument of a parameter to determine whether it
63 /// contains any ill-formed subexpressions. For example, this will
64 /// diagnose the use of local variables or parameters within the
65 /// default argument expression.
66 class CheckDefaultArgumentVisitor
67     : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
68   Sema &S;
69   const Expr *DefaultArg;
70 
71 public:
72   CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
73       : S(S), DefaultArg(DefaultArg) {}
74 
75   bool VisitExpr(const Expr *Node);
76   bool VisitDeclRefExpr(const DeclRefExpr *DRE);
77   bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
78   bool VisitLambdaExpr(const LambdaExpr *Lambda);
79   bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
80 };
81 
82 /// VisitExpr - Visit all of the children of this expression.
83 bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
84   bool IsInvalid = false;
85   for (const Stmt *SubStmt : Node->children())
86     IsInvalid |= Visit(SubStmt);
87   return IsInvalid;
88 }
89 
90 /// VisitDeclRefExpr - Visit a reference to a declaration, to
91 /// determine whether this declaration can be used in the default
92 /// argument expression.
93 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
94   const ValueDecl *Decl = dyn_cast<ValueDecl>(DRE->getDecl());
95 
96   if (!isa<VarDecl, BindingDecl>(Decl))
97     return false;
98 
99   if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {
100     // C++ [dcl.fct.default]p9:
101     //   [...] parameters of a function shall not be used in default
102     //   argument expressions, even if they are not evaluated. [...]
103     //
104     // C++17 [dcl.fct.default]p9 (by CWG 2082):
105     //   [...] A parameter shall not appear as a potentially-evaluated
106     //   expression in a default argument. [...]
107     //
108     if (DRE->isNonOdrUse() != NOUR_Unevaluated)
109       return S.Diag(DRE->getBeginLoc(),
110                     diag::err_param_default_argument_references_param)
111              << Param->getDeclName() << DefaultArg->getSourceRange();
112   } else if (auto *VD = Decl->getPotentiallyDecomposedVarDecl()) {
113     // C++ [dcl.fct.default]p7:
114     //   Local variables shall not be used in default argument
115     //   expressions.
116     //
117     // C++17 [dcl.fct.default]p7 (by CWG 2082):
118     //   A local variable shall not appear as a potentially-evaluated
119     //   expression in a default argument.
120     //
121     // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
122     //   Note: A local variable cannot be odr-used (6.3) in a default
123     //   argument.
124     //
125     if (VD->isLocalVarDecl() && !DRE->isNonOdrUse())
126       return S.Diag(DRE->getBeginLoc(),
127                     diag::err_param_default_argument_references_local)
128              << Decl << DefaultArg->getSourceRange();
129   }
130   return false;
131 }
132 
133 /// VisitCXXThisExpr - Visit a C++ "this" expression.
134 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
135   // C++ [dcl.fct.default]p8:
136   //   The keyword this shall not be used in a default argument of a
137   //   member function.
138   return S.Diag(ThisE->getBeginLoc(),
139                 diag::err_param_default_argument_references_this)
140          << ThisE->getSourceRange();
141 }
142 
143 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
144     const PseudoObjectExpr *POE) {
145   bool Invalid = false;
146   for (const Expr *E : POE->semantics()) {
147     // Look through bindings.
148     if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
149       E = OVE->getSourceExpr();
150       assert(E && "pseudo-object binding without source expression?");
151     }
152 
153     Invalid |= Visit(E);
154   }
155   return Invalid;
156 }
157 
158 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
159   // [expr.prim.lambda.capture]p9
160   // a lambda-expression appearing in a default argument cannot implicitly or
161   // explicitly capture any local entity. Such a lambda-expression can still
162   // have an init-capture if any full-expression in its initializer satisfies
163   // the constraints of an expression appearing in a default argument.
164   bool Invalid = false;
165   for (const LambdaCapture &LC : Lambda->captures()) {
166     if (!Lambda->isInitCapture(&LC))
167       return S.Diag(LC.getLocation(), diag::err_lambda_capture_default_arg);
168     // Init captures are always VarDecl.
169     auto *D = cast<VarDecl>(LC.getCapturedVar());
170     Invalid |= Visit(D->getInit());
171   }
172   return Invalid;
173 }
174 } // namespace
175 
176 void
177 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
178                                                  const CXXMethodDecl *Method) {
179   // If we have an MSAny spec already, don't bother.
180   if (!Method || ComputedEST == EST_MSAny)
181     return;
182 
183   const FunctionProtoType *Proto
184     = Method->getType()->getAs<FunctionProtoType>();
185   Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
186   if (!Proto)
187     return;
188 
189   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
190 
191   // If we have a throw-all spec at this point, ignore the function.
192   if (ComputedEST == EST_None)
193     return;
194 
195   if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
196     EST = EST_BasicNoexcept;
197 
198   switch (EST) {
199   case EST_Unparsed:
200   case EST_Uninstantiated:
201   case EST_Unevaluated:
202     llvm_unreachable("should not see unresolved exception specs here");
203 
204   // If this function can throw any exceptions, make a note of that.
205   case EST_MSAny:
206   case EST_None:
207     // FIXME: Whichever we see last of MSAny and None determines our result.
208     // We should make a consistent, order-independent choice here.
209     ClearExceptions();
210     ComputedEST = EST;
211     return;
212   case EST_NoexceptFalse:
213     ClearExceptions();
214     ComputedEST = EST_None;
215     return;
216   // FIXME: If the call to this decl is using any of its default arguments, we
217   // need to search them for potentially-throwing calls.
218   // If this function has a basic noexcept, it doesn't affect the outcome.
219   case EST_BasicNoexcept:
220   case EST_NoexceptTrue:
221   case EST_NoThrow:
222     return;
223   // If we're still at noexcept(true) and there's a throw() callee,
224   // change to that specification.
225   case EST_DynamicNone:
226     if (ComputedEST == EST_BasicNoexcept)
227       ComputedEST = EST_DynamicNone;
228     return;
229   case EST_DependentNoexcept:
230     llvm_unreachable(
231         "should not generate implicit declarations for dependent cases");
232   case EST_Dynamic:
233     break;
234   }
235   assert(EST == EST_Dynamic && "EST case not considered earlier.");
236   assert(ComputedEST != EST_None &&
237          "Shouldn't collect exceptions when throw-all is guaranteed.");
238   ComputedEST = EST_Dynamic;
239   // Record the exceptions in this function's exception specification.
240   for (const auto &E : Proto->exceptions())
241     if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
242       Exceptions.push_back(E);
243 }
244 
245 void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) {
246   if (!S || ComputedEST == EST_MSAny)
247     return;
248 
249   // FIXME:
250   //
251   // C++0x [except.spec]p14:
252   //   [An] implicit exception-specification specifies the type-id T if and
253   // only if T is allowed by the exception-specification of a function directly
254   // invoked by f's implicit definition; f shall allow all exceptions if any
255   // function it directly invokes allows all exceptions, and f shall allow no
256   // exceptions if every function it directly invokes allows no exceptions.
257   //
258   // Note in particular that if an implicit exception-specification is generated
259   // for a function containing a throw-expression, that specification can still
260   // be noexcept(true).
261   //
262   // Note also that 'directly invoked' is not defined in the standard, and there
263   // is no indication that we should only consider potentially-evaluated calls.
264   //
265   // Ultimately we should implement the intent of the standard: the exception
266   // specification should be the set of exceptions which can be thrown by the
267   // implicit definition. For now, we assume that any non-nothrow expression can
268   // throw any exception.
269 
270   if (Self->canThrow(S))
271     ComputedEST = EST_None;
272 }
273 
274 ExprResult Sema::ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
275                                              SourceLocation EqualLoc) {
276   if (RequireCompleteType(Param->getLocation(), Param->getType(),
277                           diag::err_typecheck_decl_incomplete_type))
278     return true;
279 
280   // C++ [dcl.fct.default]p5
281   //   A default argument expression is implicitly converted (clause
282   //   4) to the parameter type. The default argument expression has
283   //   the same semantic constraints as the initializer expression in
284   //   a declaration of a variable of the parameter type, using the
285   //   copy-initialization semantics (8.5).
286   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
287                                                                     Param);
288   InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
289                                                            EqualLoc);
290   InitializationSequence InitSeq(*this, Entity, Kind, Arg);
291   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
292   if (Result.isInvalid())
293     return true;
294   Arg = Result.getAs<Expr>();
295 
296   CheckCompletedExpr(Arg, EqualLoc);
297   Arg = MaybeCreateExprWithCleanups(Arg);
298 
299   return Arg;
300 }
301 
302 void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
303                                    SourceLocation EqualLoc) {
304   // Add the default argument to the parameter
305   Param->setDefaultArg(Arg);
306 
307   // We have already instantiated this parameter; provide each of the
308   // instantiations with the uninstantiated default argument.
309   UnparsedDefaultArgInstantiationsMap::iterator InstPos
310     = UnparsedDefaultArgInstantiations.find(Param);
311   if (InstPos != UnparsedDefaultArgInstantiations.end()) {
312     for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
313       InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
314 
315     // We're done tracking this parameter's instantiations.
316     UnparsedDefaultArgInstantiations.erase(InstPos);
317   }
318 }
319 
320 /// ActOnParamDefaultArgument - Check whether the default argument
321 /// provided for a function parameter is well-formed. If so, attach it
322 /// to the parameter declaration.
323 void
324 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
325                                 Expr *DefaultArg) {
326   if (!param || !DefaultArg)
327     return;
328 
329   ParmVarDecl *Param = cast<ParmVarDecl>(param);
330   UnparsedDefaultArgLocs.erase(Param);
331 
332   auto Fail = [&] {
333     Param->setInvalidDecl();
334     Param->setDefaultArg(new (Context) OpaqueValueExpr(
335         EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue));
336   };
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 Fail();
343   }
344 
345   // Check for unexpanded parameter packs.
346   if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
347     return Fail();
348   }
349 
350   // C++11 [dcl.fct.default]p3
351   //   A default argument expression [...] shall not be specified for a
352   //   parameter pack.
353   if (Param->isParameterPack()) {
354     Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
355         << DefaultArg->getSourceRange();
356     // Recover by discarding the default argument.
357     Param->setDefaultArg(nullptr);
358     return;
359   }
360 
361   ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);
362   if (Result.isInvalid())
363     return Fail();
364 
365   DefaultArg = Result.getAs<Expr>();
366 
367   // Check that the default argument is well-formed
368   CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
369   if (DefaultArgChecker.Visit(DefaultArg))
370     return Fail();
371 
372   SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
373 }
374 
375 /// ActOnParamUnparsedDefaultArgument - We've seen a default
376 /// argument for a function parameter, but we can't parse it yet
377 /// because we're inside a class definition. Note that this default
378 /// argument will be parsed later.
379 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
380                                              SourceLocation EqualLoc,
381                                              SourceLocation ArgLoc) {
382   if (!param)
383     return;
384 
385   ParmVarDecl *Param = cast<ParmVarDecl>(param);
386   Param->setUnparsedDefaultArg();
387   UnparsedDefaultArgLocs[Param] = ArgLoc;
388 }
389 
390 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
391 /// the default argument for the parameter param failed.
392 void Sema::ActOnParamDefaultArgumentError(Decl *param,
393                                           SourceLocation EqualLoc) {
394   if (!param)
395     return;
396 
397   ParmVarDecl *Param = cast<ParmVarDecl>(param);
398   Param->setInvalidDecl();
399   UnparsedDefaultArgLocs.erase(Param);
400   Param->setDefaultArg(new (Context) OpaqueValueExpr(
401       EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue));
402 }
403 
404 /// CheckExtraCXXDefaultArguments - Check for any extra default
405 /// arguments in the declarator, which is not a function declaration
406 /// or definition and therefore is not permitted to have default
407 /// arguments. This routine should be invoked for every declarator
408 /// that is not a function declaration or definition.
409 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
410   // C++ [dcl.fct.default]p3
411   //   A default argument expression shall be specified only in the
412   //   parameter-declaration-clause of a function declaration or in a
413   //   template-parameter (14.1). It shall not be specified for a
414   //   parameter pack. If it is specified in a
415   //   parameter-declaration-clause, it shall not occur within a
416   //   declarator or abstract-declarator of a parameter-declaration.
417   bool MightBeFunction = D.isFunctionDeclarationContext();
418   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
419     DeclaratorChunk &chunk = D.getTypeObject(i);
420     if (chunk.Kind == DeclaratorChunk::Function) {
421       if (MightBeFunction) {
422         // This is a function declaration. It can have default arguments, but
423         // keep looking in case its return type is a function type with default
424         // arguments.
425         MightBeFunction = false;
426         continue;
427       }
428       for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
429            ++argIdx) {
430         ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
431         if (Param->hasUnparsedDefaultArg()) {
432           std::unique_ptr<CachedTokens> Toks =
433               std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
434           SourceRange SR;
435           if (Toks->size() > 1)
436             SR = SourceRange((*Toks)[1].getLocation(),
437                              Toks->back().getLocation());
438           else
439             SR = UnparsedDefaultArgLocs[Param];
440           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
441             << SR;
442         } else if (Param->getDefaultArg()) {
443           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
444             << Param->getDefaultArg()->getSourceRange();
445           Param->setDefaultArg(nullptr);
446         }
447       }
448     } else if (chunk.Kind != DeclaratorChunk::Paren) {
449       MightBeFunction = false;
450     }
451   }
452 }
453 
454 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
455   return llvm::any_of(FD->parameters(), [](ParmVarDecl *P) {
456     return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
457   });
458 }
459 
460 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
461 /// function, once we already know that they have the same
462 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
463 /// error, false otherwise.
464 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
465                                 Scope *S) {
466   bool Invalid = false;
467 
468   // The declaration context corresponding to the scope is the semantic
469   // parent, unless this is a local function declaration, in which case
470   // it is that surrounding function.
471   DeclContext *ScopeDC = New->isLocalExternDecl()
472                              ? New->getLexicalDeclContext()
473                              : New->getDeclContext();
474 
475   // Find the previous declaration for the purpose of default arguments.
476   FunctionDecl *PrevForDefaultArgs = Old;
477   for (/**/; PrevForDefaultArgs;
478        // Don't bother looking back past the latest decl if this is a local
479        // extern declaration; nothing else could work.
480        PrevForDefaultArgs = New->isLocalExternDecl()
481                                 ? nullptr
482                                 : PrevForDefaultArgs->getPreviousDecl()) {
483     // Ignore hidden declarations.
484     if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
485       continue;
486 
487     if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
488         !New->isCXXClassMember()) {
489       // Ignore default arguments of old decl if they are not in
490       // the same scope and this is not an out-of-line definition of
491       // a member function.
492       continue;
493     }
494 
495     if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
496       // If only one of these is a local function declaration, then they are
497       // declared in different scopes, even though isDeclInScope may think
498       // they're in the same scope. (If both are local, the scope check is
499       // sufficient, and if neither is local, then they are in the same scope.)
500       continue;
501     }
502 
503     // We found the right previous declaration.
504     break;
505   }
506 
507   // C++ [dcl.fct.default]p4:
508   //   For non-template functions, default arguments can be added in
509   //   later declarations of a function in the same
510   //   scope. Declarations in different scopes have completely
511   //   distinct sets of default arguments. That is, declarations in
512   //   inner scopes do not acquire default arguments from
513   //   declarations in outer scopes, and vice versa. In a given
514   //   function declaration, all parameters subsequent to a
515   //   parameter with a default argument shall have default
516   //   arguments supplied in this or previous declarations. A
517   //   default argument shall not be redefined by a later
518   //   declaration (not even to the same value).
519   //
520   // C++ [dcl.fct.default]p6:
521   //   Except for member functions of class templates, the default arguments
522   //   in a member function definition that appears outside of the class
523   //   definition are added to the set of default arguments provided by the
524   //   member function declaration in the class definition.
525   for (unsigned p = 0, NumParams = PrevForDefaultArgs
526                                        ? PrevForDefaultArgs->getNumParams()
527                                        : 0;
528        p < NumParams; ++p) {
529     ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
530     ParmVarDecl *NewParam = New->getParamDecl(p);
531 
532     bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
533     bool NewParamHasDfl = NewParam->hasDefaultArg();
534 
535     if (OldParamHasDfl && NewParamHasDfl) {
536       unsigned DiagDefaultParamID =
537         diag::err_param_default_argument_redefinition;
538 
539       // MSVC accepts that default parameters be redefined for member functions
540       // of template class. The new default parameter's value is ignored.
541       Invalid = true;
542       if (getLangOpts().MicrosoftExt) {
543         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
544         if (MD && MD->getParent()->getDescribedClassTemplate()) {
545           // Merge the old default argument into the new parameter.
546           NewParam->setHasInheritedDefaultArg();
547           if (OldParam->hasUninstantiatedDefaultArg())
548             NewParam->setUninstantiatedDefaultArg(
549                                       OldParam->getUninstantiatedDefaultArg());
550           else
551             NewParam->setDefaultArg(OldParam->getInit());
552           DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
553           Invalid = false;
554         }
555       }
556 
557       // FIXME: If we knew where the '=' was, we could easily provide a fix-it
558       // hint here. Alternatively, we could walk the type-source information
559       // for NewParam to find the last source location in the type... but it
560       // isn't worth the effort right now. This is the kind of test case that
561       // is hard to get right:
562       //   int f(int);
563       //   void g(int (*fp)(int) = f);
564       //   void g(int (*fp)(int) = &f);
565       Diag(NewParam->getLocation(), DiagDefaultParamID)
566         << NewParam->getDefaultArgRange();
567 
568       // Look for the function declaration where the default argument was
569       // actually written, which may be a declaration prior to Old.
570       for (auto Older = PrevForDefaultArgs;
571            OldParam->hasInheritedDefaultArg(); /**/) {
572         Older = Older->getPreviousDecl();
573         OldParam = Older->getParamDecl(p);
574       }
575 
576       Diag(OldParam->getLocation(), diag::note_previous_definition)
577         << OldParam->getDefaultArgRange();
578     } else if (OldParamHasDfl) {
579       // Merge the old default argument into the new parameter unless the new
580       // function is a friend declaration in a template class. In the latter
581       // case the default arguments will be inherited when the friend
582       // declaration will be instantiated.
583       if (New->getFriendObjectKind() == Decl::FOK_None ||
584           !New->getLexicalDeclContext()->isDependentContext()) {
585         // It's important to use getInit() here;  getDefaultArg()
586         // strips off any top-level ExprWithCleanups.
587         NewParam->setHasInheritedDefaultArg();
588         if (OldParam->hasUnparsedDefaultArg())
589           NewParam->setUnparsedDefaultArg();
590         else if (OldParam->hasUninstantiatedDefaultArg())
591           NewParam->setUninstantiatedDefaultArg(
592                                        OldParam->getUninstantiatedDefaultArg());
593         else
594           NewParam->setDefaultArg(OldParam->getInit());
595       }
596     } else if (NewParamHasDfl) {
597       if (New->getDescribedFunctionTemplate()) {
598         // Paragraph 4, quoted above, only applies to non-template functions.
599         Diag(NewParam->getLocation(),
600              diag::err_param_default_argument_template_redecl)
601           << NewParam->getDefaultArgRange();
602         Diag(PrevForDefaultArgs->getLocation(),
603              diag::note_template_prev_declaration)
604             << false;
605       } else if (New->getTemplateSpecializationKind()
606                    != TSK_ImplicitInstantiation &&
607                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
608         // C++ [temp.expr.spec]p21:
609         //   Default function arguments shall not be specified in a declaration
610         //   or a definition for one of the following explicit specializations:
611         //     - the explicit specialization of a function template;
612         //     - the explicit specialization of a member function template;
613         //     - the explicit specialization of a member function of a class
614         //       template where the class template specialization to which the
615         //       member function specialization belongs is implicitly
616         //       instantiated.
617         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
618           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
619           << New->getDeclName()
620           << NewParam->getDefaultArgRange();
621       } else if (New->getDeclContext()->isDependentContext()) {
622         // C++ [dcl.fct.default]p6 (DR217):
623         //   Default arguments for a member function of a class template shall
624         //   be specified on the initial declaration of the member function
625         //   within the class template.
626         //
627         // Reading the tea leaves a bit in DR217 and its reference to DR205
628         // leads me to the conclusion that one cannot add default function
629         // arguments for an out-of-line definition of a member function of a
630         // dependent type.
631         int WhichKind = 2;
632         if (CXXRecordDecl *Record
633               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
634           if (Record->getDescribedClassTemplate())
635             WhichKind = 0;
636           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
637             WhichKind = 1;
638           else
639             WhichKind = 2;
640         }
641 
642         Diag(NewParam->getLocation(),
643              diag::err_param_default_argument_member_template_redecl)
644           << WhichKind
645           << NewParam->getDefaultArgRange();
646       }
647     }
648   }
649 
650   // DR1344: If a default argument is added outside a class definition and that
651   // default argument makes the function a special member function, the program
652   // is ill-formed. This can only happen for constructors.
653   if (isa<CXXConstructorDecl>(New) &&
654       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
655     CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
656                      OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
657     if (NewSM != OldSM) {
658       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
659       assert(NewParam->hasDefaultArg());
660       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
661         << NewParam->getDefaultArgRange() << NewSM;
662       Diag(Old->getLocation(), diag::note_previous_declaration);
663     }
664   }
665 
666   const FunctionDecl *Def;
667   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
668   // template has a constexpr specifier then all its declarations shall
669   // contain the constexpr specifier.
670   if (New->getConstexprKind() != Old->getConstexprKind()) {
671     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
672         << New << static_cast<int>(New->getConstexprKind())
673         << static_cast<int>(Old->getConstexprKind());
674     Diag(Old->getLocation(), diag::note_previous_declaration);
675     Invalid = true;
676   } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
677              Old->isDefined(Def) &&
678              // If a friend function is inlined but does not have 'inline'
679              // specifier, it is a definition. Do not report attribute conflict
680              // in this case, redefinition will be diagnosed later.
681              (New->isInlineSpecified() ||
682               New->getFriendObjectKind() == Decl::FOK_None)) {
683     // C++11 [dcl.fcn.spec]p4:
684     //   If the definition of a function appears in a translation unit before its
685     //   first declaration as inline, the program is ill-formed.
686     Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
687     Diag(Def->getLocation(), diag::note_previous_definition);
688     Invalid = true;
689   }
690 
691   // C++17 [temp.deduct.guide]p3:
692   //   Two deduction guide declarations in the same translation unit
693   //   for the same class template shall not have equivalent
694   //   parameter-declaration-clauses.
695   if (isa<CXXDeductionGuideDecl>(New) &&
696       !New->isFunctionTemplateSpecialization() && isVisible(Old)) {
697     Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
698     Diag(Old->getLocation(), diag::note_previous_declaration);
699   }
700 
701   // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
702   // argument expression, that declaration shall be a definition and shall be
703   // the only declaration of the function or function template in the
704   // translation unit.
705   if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
706       functionDeclHasDefaultArgument(Old)) {
707     Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
708     Diag(Old->getLocation(), diag::note_previous_declaration);
709     Invalid = true;
710   }
711 
712   // C++11 [temp.friend]p4 (DR329):
713   //   When a function is defined in a friend function declaration in a class
714   //   template, the function is instantiated when the function is odr-used.
715   //   The same restrictions on multiple declarations and definitions that
716   //   apply to non-template function declarations and definitions also apply
717   //   to these implicit definitions.
718   const FunctionDecl *OldDefinition = nullptr;
719   if (New->isThisDeclarationInstantiatedFromAFriendDefinition() &&
720       Old->isDefined(OldDefinition, true))
721     CheckForFunctionRedefinition(New, OldDefinition);
722 
723   return Invalid;
724 }
725 
726 NamedDecl *
727 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
728                                    MultiTemplateParamsArg TemplateParamLists) {
729   assert(D.isDecompositionDeclarator());
730   const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
731 
732   // The syntax only allows a decomposition declarator as a simple-declaration,
733   // a for-range-declaration, or a condition in Clang, but we parse it in more
734   // cases than that.
735   if (!D.mayHaveDecompositionDeclarator()) {
736     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
737       << Decomp.getSourceRange();
738     return nullptr;
739   }
740 
741   if (!TemplateParamLists.empty()) {
742     // FIXME: There's no rule against this, but there are also no rules that
743     // would actually make it usable, so we reject it for now.
744     Diag(TemplateParamLists.front()->getTemplateLoc(),
745          diag::err_decomp_decl_template);
746     return nullptr;
747   }
748 
749   Diag(Decomp.getLSquareLoc(),
750        !getLangOpts().CPlusPlus17
751            ? diag::ext_decomp_decl
752            : D.getContext() == DeclaratorContext::Condition
753                  ? diag::ext_decomp_decl_cond
754                  : diag::warn_cxx14_compat_decomp_decl)
755       << Decomp.getSourceRange();
756 
757   // The semantic context is always just the current context.
758   DeclContext *const DC = CurContext;
759 
760   // C++17 [dcl.dcl]/8:
761   //   The decl-specifier-seq shall contain only the type-specifier auto
762   //   and cv-qualifiers.
763   // C++20 [dcl.dcl]/8:
764   //   If decl-specifier-seq contains any decl-specifier other than static,
765   //   thread_local, auto, or cv-qualifiers, the program is ill-formed.
766   // C++23 [dcl.pre]/6:
767   //   Each decl-specifier in the decl-specifier-seq shall be static,
768   //   thread_local, auto (9.2.9.6 [dcl.spec.auto]), or a cv-qualifier.
769   auto &DS = D.getDeclSpec();
770   {
771     // Note: While constrained-auto needs to be checked, we do so separately so
772     // we can emit a better diagnostic.
773     SmallVector<StringRef, 8> BadSpecifiers;
774     SmallVector<SourceLocation, 8> BadSpecifierLocs;
775     SmallVector<StringRef, 8> CPlusPlus20Specifiers;
776     SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
777     if (auto SCS = DS.getStorageClassSpec()) {
778       if (SCS == DeclSpec::SCS_static) {
779         CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
780         CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
781       } else {
782         BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
783         BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
784       }
785     }
786     if (auto TSCS = DS.getThreadStorageClassSpec()) {
787       CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
788       CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
789     }
790     if (DS.hasConstexprSpecifier()) {
791       BadSpecifiers.push_back(
792           DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
793       BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
794     }
795     if (DS.isInlineSpecified()) {
796       BadSpecifiers.push_back("inline");
797       BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
798     }
799 
800     if (!BadSpecifiers.empty()) {
801       auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
802       Err << (int)BadSpecifiers.size()
803           << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
804       // Don't add FixItHints to remove the specifiers; we do still respect
805       // them when building the underlying variable.
806       for (auto Loc : BadSpecifierLocs)
807         Err << SourceRange(Loc, Loc);
808     } else if (!CPlusPlus20Specifiers.empty()) {
809       auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
810                          getLangOpts().CPlusPlus20
811                              ? diag::warn_cxx17_compat_decomp_decl_spec
812                              : diag::ext_decomp_decl_spec);
813       Warn << (int)CPlusPlus20Specifiers.size()
814            << llvm::join(CPlusPlus20Specifiers.begin(),
815                          CPlusPlus20Specifiers.end(), " ");
816       for (auto Loc : CPlusPlus20SpecifierLocs)
817         Warn << SourceRange(Loc, Loc);
818     }
819     // We can't recover from it being declared as a typedef.
820     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
821       return nullptr;
822   }
823 
824   // C++2a [dcl.struct.bind]p1:
825   //   A cv that includes volatile is deprecated
826   if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
827       getLangOpts().CPlusPlus20)
828     Diag(DS.getVolatileSpecLoc(),
829          diag::warn_deprecated_volatile_structured_binding);
830 
831   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
832   QualType R = TInfo->getType();
833 
834   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
835                                       UPPC_DeclarationType))
836     D.setInvalidType();
837 
838   // The syntax only allows a single ref-qualifier prior to the decomposition
839   // declarator. No other declarator chunks are permitted. Also check the type
840   // specifier here.
841   if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
842       D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
843       (D.getNumTypeObjects() == 1 &&
844        D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
845     Diag(Decomp.getLSquareLoc(),
846          (D.hasGroupingParens() ||
847           (D.getNumTypeObjects() &&
848            D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
849              ? diag::err_decomp_decl_parens
850              : diag::err_decomp_decl_type)
851         << R;
852 
853     // In most cases, there's no actual problem with an explicitly-specified
854     // type, but a function type won't work here, and ActOnVariableDeclarator
855     // shouldn't be called for such a type.
856     if (R->isFunctionType())
857       D.setInvalidType();
858   }
859 
860   // Constrained auto is prohibited by [decl.pre]p6, so check that here.
861   if (DS.isConstrainedAuto()) {
862     TemplateIdAnnotation *TemplRep = DS.getRepAsTemplateId();
863     assert(TemplRep->Kind == TNK_Concept_template &&
864            "No other template kind should be possible for a constrained auto");
865 
866     SourceRange TemplRange{TemplRep->TemplateNameLoc,
867                            TemplRep->RAngleLoc.isValid()
868                                ? TemplRep->RAngleLoc
869                                : TemplRep->TemplateNameLoc};
870     Diag(TemplRep->TemplateNameLoc, diag::err_decomp_decl_constraint)
871         << TemplRange << FixItHint::CreateRemoval(TemplRange);
872   }
873 
874   // Build the BindingDecls.
875   SmallVector<BindingDecl*, 8> Bindings;
876 
877   // Build the BindingDecls.
878   for (auto &B : D.getDecompositionDeclarator().bindings()) {
879     // Check for name conflicts.
880     DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
881     LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
882                           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, B.Name);
895 
896     // Find the shadowed declaration before filtering for scope.
897     NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
898                                   ? getShadowedDeclaration(BD, Previous)
899                                   : nullptr;
900 
901     bool ConsiderLinkage = DC->isFunctionOrMethod() &&
902                            DS.getStorageClassSpec() == DeclSpec::SCS_extern;
903     FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
904                          /*AllowInlineNamespace*/false);
905 
906     if (!Previous.empty()) {
907       auto *Old = Previous.getRepresentativeDecl();
908       Diag(B.NameLoc, diag::err_redefinition) << B.Name;
909       Diag(Old->getLocation(), diag::note_previous_definition);
910     } else if (ShadowedDecl && !D.isRedeclaration()) {
911       CheckShadow(BD, ShadowedDecl, Previous);
912     }
913     PushOnScopeChains(BD, S, true);
914     Bindings.push_back(BD);
915     ParsingInitForAutoVars.insert(BD);
916   }
917 
918   // There are no prior lookup results for the variable itself, because it
919   // is unnamed.
920   DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
921                                Decomp.getLSquareLoc());
922   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
923                         ForVisibleRedeclaration);
924 
925   // Build the variable that holds the non-decomposed object.
926   bool AddToScope = true;
927   NamedDecl *New =
928       ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
929                               MultiTemplateParamsArg(), AddToScope, Bindings);
930   if (AddToScope) {
931     S->AddDecl(New);
932     CurContext->addHiddenDecl(New);
933   }
934 
935   if (isInOpenMPDeclareTargetContext())
936     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
937 
938   return New;
939 }
940 
941 static bool checkSimpleDecomposition(
942     Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
943     QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
944     llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
945   if ((int64_t)Bindings.size() != NumElems) {
946     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
947         << DecompType << (unsigned)Bindings.size()
948         << (unsigned)NumElems.getLimitedValue(UINT_MAX)
949         << toString(NumElems, 10) << (NumElems < Bindings.size());
950     return true;
951   }
952 
953   unsigned I = 0;
954   for (auto *B : Bindings) {
955     SourceLocation Loc = B->getLocation();
956     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
957     if (E.isInvalid())
958       return true;
959     E = GetInit(Loc, E.get(), I++);
960     if (E.isInvalid())
961       return true;
962     B->setBinding(ElemType, E.get());
963   }
964 
965   return false;
966 }
967 
968 static bool checkArrayLikeDecomposition(Sema &S,
969                                         ArrayRef<BindingDecl *> Bindings,
970                                         ValueDecl *Src, QualType DecompType,
971                                         const llvm::APSInt &NumElems,
972                                         QualType ElemType) {
973   return checkSimpleDecomposition(
974       S, Bindings, Src, DecompType, NumElems, ElemType,
975       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
976         ExprResult E = S.ActOnIntegerConstant(Loc, I);
977         if (E.isInvalid())
978           return ExprError();
979         return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
980       });
981 }
982 
983 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
984                                     ValueDecl *Src, QualType DecompType,
985                                     const ConstantArrayType *CAT) {
986   return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
987                                      llvm::APSInt(CAT->getSize()),
988                                      CAT->getElementType());
989 }
990 
991 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
992                                      ValueDecl *Src, QualType DecompType,
993                                      const VectorType *VT) {
994   return checkArrayLikeDecomposition(
995       S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
996       S.Context.getQualifiedType(VT->getElementType(),
997                                  DecompType.getQualifiers()));
998 }
999 
1000 static bool checkComplexDecomposition(Sema &S,
1001                                       ArrayRef<BindingDecl *> Bindings,
1002                                       ValueDecl *Src, QualType DecompType,
1003                                       const ComplexType *CT) {
1004   return checkSimpleDecomposition(
1005       S, Bindings, Src, DecompType, llvm::APSInt::get(2),
1006       S.Context.getQualifiedType(CT->getElementType(),
1007                                  DecompType.getQualifiers()),
1008       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1009         return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
1010       });
1011 }
1012 
1013 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
1014                                      TemplateArgumentListInfo &Args,
1015                                      const TemplateParameterList *Params) {
1016   SmallString<128> SS;
1017   llvm::raw_svector_ostream OS(SS);
1018   bool First = true;
1019   unsigned I = 0;
1020   for (auto &Arg : Args.arguments()) {
1021     if (!First)
1022       OS << ", ";
1023     Arg.getArgument().print(PrintingPolicy, OS,
1024                             TemplateParameterList::shouldIncludeTypeForArgument(
1025                                 PrintingPolicy, Params, I));
1026     First = false;
1027     I++;
1028   }
1029   return std::string(OS.str());
1030 }
1031 
1032 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
1033                                      SourceLocation Loc, StringRef Trait,
1034                                      TemplateArgumentListInfo &Args,
1035                                      unsigned DiagID) {
1036   auto DiagnoseMissing = [&] {
1037     if (DiagID)
1038       S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
1039                                                Args, /*Params*/ nullptr);
1040     return true;
1041   };
1042 
1043   // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1044   NamespaceDecl *Std = S.getStdNamespace();
1045   if (!Std)
1046     return DiagnoseMissing();
1047 
1048   // Look up the trait itself, within namespace std. We can diagnose various
1049   // problems with this lookup even if we've been asked to not diagnose a
1050   // missing specialization, because this can only fail if the user has been
1051   // declaring their own names in namespace std or we don't support the
1052   // standard library implementation in use.
1053   LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
1054                       Loc, Sema::LookupOrdinaryName);
1055   if (!S.LookupQualifiedName(Result, Std))
1056     return DiagnoseMissing();
1057   if (Result.isAmbiguous())
1058     return true;
1059 
1060   ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1061   if (!TraitTD) {
1062     Result.suppressDiagnostics();
1063     NamedDecl *Found = *Result.begin();
1064     S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1065     S.Diag(Found->getLocation(), diag::note_declared_at);
1066     return true;
1067   }
1068 
1069   // Build the template-id.
1070   QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
1071   if (TraitTy.isNull())
1072     return true;
1073   if (!S.isCompleteType(Loc, TraitTy)) {
1074     if (DiagID)
1075       S.RequireCompleteType(
1076           Loc, TraitTy, DiagID,
1077           printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1078                             TraitTD->getTemplateParameters()));
1079     return true;
1080   }
1081 
1082   CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1083   assert(RD && "specialization of class template is not a class?");
1084 
1085   // Look up the member of the trait type.
1086   S.LookupQualifiedName(TraitMemberLookup, RD);
1087   return TraitMemberLookup.isAmbiguous();
1088 }
1089 
1090 static TemplateArgumentLoc
1091 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
1092                                    uint64_t I) {
1093   TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
1094   return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1095 }
1096 
1097 static TemplateArgumentLoc
1098 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
1099   return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
1100 }
1101 
1102 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1103 
1104 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1105                                llvm::APSInt &Size) {
1106   EnterExpressionEvaluationContext ContextRAII(
1107       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1108 
1109   DeclarationName Value = S.PP.getIdentifierInfo("value");
1110   LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1111 
1112   // Form template argument list for tuple_size<T>.
1113   TemplateArgumentListInfo Args(Loc, Loc);
1114   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1115 
1116   // If there's no tuple_size specialization or the lookup of 'value' is empty,
1117   // it's not tuple-like.
1118   if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1119       R.empty())
1120     return IsTupleLike::NotTupleLike;
1121 
1122   // If we get this far, we've committed to the tuple interpretation, but
1123   // we can still fail if there actually isn't a usable ::value.
1124 
1125   struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1126     LookupResult &R;
1127     TemplateArgumentListInfo &Args;
1128     ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1129         : R(R), Args(Args) {}
1130     Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1131                                                SourceLocation Loc) override {
1132       return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1133              << printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1134                                   /*Params*/ nullptr);
1135     }
1136   } Diagnoser(R, Args);
1137 
1138   ExprResult E =
1139       S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1140   if (E.isInvalid())
1141     return IsTupleLike::Error;
1142 
1143   E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
1144   if (E.isInvalid())
1145     return IsTupleLike::Error;
1146 
1147   return IsTupleLike::TupleLike;
1148 }
1149 
1150 /// \return std::tuple_element<I, T>::type.
1151 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1152                                         unsigned I, QualType T) {
1153   // Form template argument list for tuple_element<I, T>.
1154   TemplateArgumentListInfo Args(Loc, Loc);
1155   Args.addArgument(
1156       getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1157   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1158 
1159   DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1160   LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1161   if (lookupStdTypeTraitMember(
1162           S, R, Loc, "tuple_element", Args,
1163           diag::err_decomp_decl_std_tuple_element_not_specialized))
1164     return QualType();
1165 
1166   auto *TD = R.getAsSingle<TypeDecl>();
1167   if (!TD) {
1168     R.suppressDiagnostics();
1169     S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1170         << printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1171                              /*Params*/ nullptr);
1172     if (!R.empty())
1173       S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1174     return QualType();
1175   }
1176 
1177   return S.Context.getTypeDeclType(TD);
1178 }
1179 
1180 namespace {
1181 struct InitializingBinding {
1182   Sema &S;
1183   InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1184     Sema::CodeSynthesisContext Ctx;
1185     Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding;
1186     Ctx.PointOfInstantiation = BD->getLocation();
1187     Ctx.Entity = BD;
1188     S.pushCodeSynthesisContext(Ctx);
1189   }
1190   ~InitializingBinding() {
1191     S.popCodeSynthesisContext();
1192   }
1193 };
1194 }
1195 
1196 static bool checkTupleLikeDecomposition(Sema &S,
1197                                         ArrayRef<BindingDecl *> Bindings,
1198                                         VarDecl *Src, QualType DecompType,
1199                                         const llvm::APSInt &TupleSize) {
1200   if ((int64_t)Bindings.size() != TupleSize) {
1201     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1202         << DecompType << (unsigned)Bindings.size()
1203         << (unsigned)TupleSize.getLimitedValue(UINT_MAX)
1204         << toString(TupleSize, 10) << (TupleSize < Bindings.size());
1205     return true;
1206   }
1207 
1208   if (Bindings.empty())
1209     return false;
1210 
1211   DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1212 
1213   // [dcl.decomp]p3:
1214   //   The unqualified-id get is looked up in the scope of E by class member
1215   //   access lookup ...
1216   LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1217   bool UseMemberGet = false;
1218   if (S.isCompleteType(Src->getLocation(), DecompType)) {
1219     if (auto *RD = DecompType->getAsCXXRecordDecl())
1220       S.LookupQualifiedName(MemberGet, RD);
1221     if (MemberGet.isAmbiguous())
1222       return true;
1223     //   ... and if that finds at least one declaration that is a function
1224     //   template whose first template parameter is a non-type parameter ...
1225     for (NamedDecl *D : MemberGet) {
1226       if (FunctionTemplateDecl *FTD =
1227               dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1228         TemplateParameterList *TPL = FTD->getTemplateParameters();
1229         if (TPL->size() != 0 &&
1230             isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1231           //   ... the initializer is e.get<i>().
1232           UseMemberGet = true;
1233           break;
1234         }
1235       }
1236     }
1237   }
1238 
1239   unsigned I = 0;
1240   for (auto *B : Bindings) {
1241     InitializingBinding InitContext(S, B);
1242     SourceLocation Loc = B->getLocation();
1243 
1244     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1245     if (E.isInvalid())
1246       return true;
1247 
1248     //   e is an lvalue if the type of the entity is an lvalue reference and
1249     //   an xvalue otherwise
1250     if (!Src->getType()->isLValueReferenceType())
1251       E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1252                                    E.get(), nullptr, VK_XValue,
1253                                    FPOptionsOverride());
1254 
1255     TemplateArgumentListInfo Args(Loc, Loc);
1256     Args.addArgument(
1257         getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1258 
1259     if (UseMemberGet) {
1260       //   if [lookup of member get] finds at least one declaration, the
1261       //   initializer is e.get<i-1>().
1262       E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1263                                      CXXScopeSpec(), SourceLocation(), nullptr,
1264                                      MemberGet, &Args, nullptr);
1265       if (E.isInvalid())
1266         return true;
1267 
1268       E = S.BuildCallExpr(nullptr, E.get(), Loc, std::nullopt, Loc);
1269     } else {
1270       //   Otherwise, the initializer is get<i-1>(e), where get is looked up
1271       //   in the associated namespaces.
1272       Expr *Get = UnresolvedLookupExpr::Create(
1273           S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1274           DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1275           UnresolvedSetIterator(), UnresolvedSetIterator());
1276 
1277       Expr *Arg = E.get();
1278       E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1279     }
1280     if (E.isInvalid())
1281       return true;
1282     Expr *Init = E.get();
1283 
1284     //   Given the type T designated by std::tuple_element<i - 1, E>::type,
1285     QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1286     if (T.isNull())
1287       return true;
1288 
1289     //   each vi is a variable of type "reference to T" initialized with the
1290     //   initializer, where the reference is an lvalue reference if the
1291     //   initializer is an lvalue and an rvalue reference otherwise
1292     QualType RefType =
1293         S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1294     if (RefType.isNull())
1295       return true;
1296     auto *RefVD = VarDecl::Create(
1297         S.Context, Src->getDeclContext(), Loc, Loc,
1298         B->getDeclName().getAsIdentifierInfo(), RefType,
1299         S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1300     RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1301     RefVD->setTSCSpec(Src->getTSCSpec());
1302     RefVD->setImplicit();
1303     if (Src->isInlineSpecified())
1304       RefVD->setInlineSpecified();
1305     RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1306 
1307     InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1308     InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1309     InitializationSequence Seq(S, Entity, Kind, Init);
1310     E = Seq.Perform(S, Entity, Kind, Init);
1311     if (E.isInvalid())
1312       return true;
1313     E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1314     if (E.isInvalid())
1315       return true;
1316     RefVD->setInit(E.get());
1317     S.CheckCompleteVariableDeclaration(RefVD);
1318 
1319     E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1320                                    DeclarationNameInfo(B->getDeclName(), Loc),
1321                                    RefVD);
1322     if (E.isInvalid())
1323       return true;
1324 
1325     B->setBinding(T, E.get());
1326     I++;
1327   }
1328 
1329   return false;
1330 }
1331 
1332 /// Find the base class to decompose in a built-in decomposition of a class type.
1333 /// This base class search is, unfortunately, not quite like any other that we
1334 /// perform anywhere else in C++.
1335 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1336                                                 const CXXRecordDecl *RD,
1337                                                 CXXCastPath &BasePath) {
1338   auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1339                           CXXBasePath &Path) {
1340     return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1341   };
1342 
1343   const CXXRecordDecl *ClassWithFields = nullptr;
1344   AccessSpecifier AS = AS_public;
1345   if (RD->hasDirectFields())
1346     // [dcl.decomp]p4:
1347     //   Otherwise, all of E's non-static data members shall be public direct
1348     //   members of E ...
1349     ClassWithFields = RD;
1350   else {
1351     //   ... or of ...
1352     CXXBasePaths Paths;
1353     Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1354     if (!RD->lookupInBases(BaseHasFields, Paths)) {
1355       // If no classes have fields, just decompose RD itself. (This will work
1356       // if and only if zero bindings were provided.)
1357       return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1358     }
1359 
1360     CXXBasePath *BestPath = nullptr;
1361     for (auto &P : Paths) {
1362       if (!BestPath)
1363         BestPath = &P;
1364       else if (!S.Context.hasSameType(P.back().Base->getType(),
1365                                       BestPath->back().Base->getType())) {
1366         //   ... the same ...
1367         S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1368           << false << RD << BestPath->back().Base->getType()
1369           << P.back().Base->getType();
1370         return DeclAccessPair();
1371       } else if (P.Access < BestPath->Access) {
1372         BestPath = &P;
1373       }
1374     }
1375 
1376     //   ... unambiguous ...
1377     QualType BaseType = BestPath->back().Base->getType();
1378     if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1379       S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1380         << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1381       return DeclAccessPair();
1382     }
1383 
1384     //   ... [accessible, implied by other rules] base class of E.
1385     S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1386                            *BestPath, diag::err_decomp_decl_inaccessible_base);
1387     AS = BestPath->Access;
1388 
1389     ClassWithFields = BaseType->getAsCXXRecordDecl();
1390     S.BuildBasePathArray(Paths, BasePath);
1391   }
1392 
1393   // The above search did not check whether the selected class itself has base
1394   // classes with fields, so check that now.
1395   CXXBasePaths Paths;
1396   if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1397     S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1398       << (ClassWithFields == RD) << RD << ClassWithFields
1399       << Paths.front().back().Base->getType();
1400     return DeclAccessPair();
1401   }
1402 
1403   return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1404 }
1405 
1406 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1407                                      ValueDecl *Src, QualType DecompType,
1408                                      const CXXRecordDecl *OrigRD) {
1409   if (S.RequireCompleteType(Src->getLocation(), DecompType,
1410                             diag::err_incomplete_type))
1411     return true;
1412 
1413   CXXCastPath BasePath;
1414   DeclAccessPair BasePair =
1415       findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1416   const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1417   if (!RD)
1418     return true;
1419   QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1420                                                  DecompType.getQualifiers());
1421 
1422   auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1423     unsigned NumFields = llvm::count_if(
1424         RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1425     assert(Bindings.size() != NumFields);
1426     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1427         << DecompType << (unsigned)Bindings.size() << NumFields << NumFields
1428         << (NumFields < Bindings.size());
1429     return true;
1430   };
1431 
1432   //   all of E's non-static data members shall be [...] well-formed
1433   //   when named as e.name in the context of the structured binding,
1434   //   E shall not have an anonymous union member, ...
1435   unsigned I = 0;
1436   for (auto *FD : RD->fields()) {
1437     if (FD->isUnnamedBitfield())
1438       continue;
1439 
1440     // All the non-static data members are required to be nameable, so they
1441     // must all have names.
1442     if (!FD->getDeclName()) {
1443       if (RD->isLambda()) {
1444         S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda);
1445         S.Diag(RD->getLocation(), diag::note_lambda_decl);
1446         return true;
1447       }
1448 
1449       if (FD->isAnonymousStructOrUnion()) {
1450         S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1451           << DecompType << FD->getType()->isUnionType();
1452         S.Diag(FD->getLocation(), diag::note_declared_at);
1453         return true;
1454       }
1455 
1456       // FIXME: Are there any other ways we could have an anonymous member?
1457     }
1458 
1459     // We have a real field to bind.
1460     if (I >= Bindings.size())
1461       return DiagnoseBadNumberOfBindings();
1462     auto *B = Bindings[I++];
1463     SourceLocation Loc = B->getLocation();
1464 
1465     // The field must be accessible in the context of the structured binding.
1466     // We already checked that the base class is accessible.
1467     // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1468     // const_cast here.
1469     S.CheckStructuredBindingMemberAccess(
1470         Loc, const_cast<CXXRecordDecl *>(OrigRD),
1471         DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1472                                      BasePair.getAccess(), FD->getAccess())));
1473 
1474     // Initialize the binding to Src.FD.
1475     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1476     if (E.isInvalid())
1477       return true;
1478     E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1479                             VK_LValue, &BasePath);
1480     if (E.isInvalid())
1481       return true;
1482     E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1483                                   CXXScopeSpec(), FD,
1484                                   DeclAccessPair::make(FD, FD->getAccess()),
1485                                   DeclarationNameInfo(FD->getDeclName(), Loc));
1486     if (E.isInvalid())
1487       return true;
1488 
1489     // If the type of the member is T, the referenced type is cv T, where cv is
1490     // the cv-qualification of the decomposition expression.
1491     //
1492     // FIXME: We resolve a defect here: if the field is mutable, we do not add
1493     // 'const' to the type of the field.
1494     Qualifiers Q = DecompType.getQualifiers();
1495     if (FD->isMutable())
1496       Q.removeConst();
1497     B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1498   }
1499 
1500   if (I != Bindings.size())
1501     return DiagnoseBadNumberOfBindings();
1502 
1503   return false;
1504 }
1505 
1506 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1507   QualType DecompType = DD->getType();
1508 
1509   // If the type of the decomposition is dependent, then so is the type of
1510   // each binding.
1511   if (DecompType->isDependentType()) {
1512     for (auto *B : DD->bindings())
1513       B->setType(Context.DependentTy);
1514     return;
1515   }
1516 
1517   DecompType = DecompType.getNonReferenceType();
1518   ArrayRef<BindingDecl*> Bindings = DD->bindings();
1519 
1520   // C++1z [dcl.decomp]/2:
1521   //   If E is an array type [...]
1522   // As an extension, we also support decomposition of built-in complex and
1523   // vector types.
1524   if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1525     if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1526       DD->setInvalidDecl();
1527     return;
1528   }
1529   if (auto *VT = DecompType->getAs<VectorType>()) {
1530     if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1531       DD->setInvalidDecl();
1532     return;
1533   }
1534   if (auto *CT = DecompType->getAs<ComplexType>()) {
1535     if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1536       DD->setInvalidDecl();
1537     return;
1538   }
1539 
1540   // C++1z [dcl.decomp]/3:
1541   //   if the expression std::tuple_size<E>::value is a well-formed integral
1542   //   constant expression, [...]
1543   llvm::APSInt TupleSize(32);
1544   switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1545   case IsTupleLike::Error:
1546     DD->setInvalidDecl();
1547     return;
1548 
1549   case IsTupleLike::TupleLike:
1550     if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1551       DD->setInvalidDecl();
1552     return;
1553 
1554   case IsTupleLike::NotTupleLike:
1555     break;
1556   }
1557 
1558   // C++1z [dcl.dcl]/8:
1559   //   [E shall be of array or non-union class type]
1560   CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1561   if (!RD || RD->isUnion()) {
1562     Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1563         << DD << !RD << DecompType;
1564     DD->setInvalidDecl();
1565     return;
1566   }
1567 
1568   // C++1z [dcl.decomp]/4:
1569   //   all of E's non-static data members shall be [...] direct members of
1570   //   E or of the same unambiguous public base class of E, ...
1571   if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1572     DD->setInvalidDecl();
1573 }
1574 
1575 /// Merge the exception specifications of two variable declarations.
1576 ///
1577 /// This is called when there's a redeclaration of a VarDecl. The function
1578 /// checks if the redeclaration might have an exception specification and
1579 /// validates compatibility and merges the specs if necessary.
1580 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1581   // Shortcut if exceptions are disabled.
1582   if (!getLangOpts().CXXExceptions)
1583     return;
1584 
1585   assert(Context.hasSameType(New->getType(), Old->getType()) &&
1586          "Should only be called if types are otherwise the same.");
1587 
1588   QualType NewType = New->getType();
1589   QualType OldType = Old->getType();
1590 
1591   // We're only interested in pointers and references to functions, as well
1592   // as pointers to member functions.
1593   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1594     NewType = R->getPointeeType();
1595     OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1596   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1597     NewType = P->getPointeeType();
1598     OldType = OldType->castAs<PointerType>()->getPointeeType();
1599   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1600     NewType = M->getPointeeType();
1601     OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1602   }
1603 
1604   if (!NewType->isFunctionProtoType())
1605     return;
1606 
1607   // There's lots of special cases for functions. For function pointers, system
1608   // libraries are hopefully not as broken so that we don't need these
1609   // workarounds.
1610   if (CheckEquivalentExceptionSpec(
1611         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1612         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1613     New->setInvalidDecl();
1614   }
1615 }
1616 
1617 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1618 /// function declaration are well-formed according to C++
1619 /// [dcl.fct.default].
1620 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1621   unsigned NumParams = FD->getNumParams();
1622   unsigned ParamIdx = 0;
1623 
1624   // This checking doesn't make sense for explicit specializations; their
1625   // default arguments are determined by the declaration we're specializing,
1626   // not by FD.
1627   if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1628     return;
1629   if (auto *FTD = FD->getDescribedFunctionTemplate())
1630     if (FTD->isMemberSpecialization())
1631       return;
1632 
1633   // Find first parameter with a default argument
1634   for (; ParamIdx < NumParams; ++ParamIdx) {
1635     ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1636     if (Param->hasDefaultArg())
1637       break;
1638   }
1639 
1640   // C++20 [dcl.fct.default]p4:
1641   //   In a given function declaration, each parameter subsequent to a parameter
1642   //   with a default argument shall have a default argument supplied in this or
1643   //   a previous declaration, unless the parameter was expanded from a
1644   //   parameter pack, or shall be a function parameter pack.
1645   for (; ParamIdx < NumParams; ++ParamIdx) {
1646     ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1647     if (!Param->hasDefaultArg() && !Param->isParameterPack() &&
1648         !(CurrentInstantiationScope &&
1649           CurrentInstantiationScope->isLocalPackExpansion(Param))) {
1650       if (Param->isInvalidDecl())
1651         /* We already complained about this parameter. */;
1652       else if (Param->getIdentifier())
1653         Diag(Param->getLocation(),
1654              diag::err_param_default_argument_missing_name)
1655           << Param->getIdentifier();
1656       else
1657         Diag(Param->getLocation(),
1658              diag::err_param_default_argument_missing);
1659     }
1660   }
1661 }
1662 
1663 /// Check that the given type is a literal type. Issue a diagnostic if not,
1664 /// if Kind is Diagnose.
1665 /// \return \c true if a problem has been found (and optionally diagnosed).
1666 template <typename... Ts>
1667 static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
1668                              SourceLocation Loc, QualType T, unsigned DiagID,
1669                              Ts &&...DiagArgs) {
1670   if (T->isDependentType())
1671     return false;
1672 
1673   switch (Kind) {
1674   case Sema::CheckConstexprKind::Diagnose:
1675     return SemaRef.RequireLiteralType(Loc, T, DiagID,
1676                                       std::forward<Ts>(DiagArgs)...);
1677 
1678   case Sema::CheckConstexprKind::CheckValid:
1679     return !T->isLiteralType(SemaRef.Context);
1680   }
1681 
1682   llvm_unreachable("unknown CheckConstexprKind");
1683 }
1684 
1685 /// Determine whether a destructor cannot be constexpr due to
1686 static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
1687                                                const CXXDestructorDecl *DD,
1688                                                Sema::CheckConstexprKind Kind) {
1689   auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1690     const CXXRecordDecl *RD =
1691         T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1692     if (!RD || RD->hasConstexprDestructor())
1693       return true;
1694 
1695     if (Kind == Sema::CheckConstexprKind::Diagnose) {
1696       SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1697           << static_cast<int>(DD->getConstexprKind()) << !FD
1698           << (FD ? FD->getDeclName() : DeclarationName()) << T;
1699       SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1700           << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1701     }
1702     return false;
1703   };
1704 
1705   const CXXRecordDecl *RD = DD->getParent();
1706   for (const CXXBaseSpecifier &B : RD->bases())
1707     if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1708       return false;
1709   for (const FieldDecl *FD : RD->fields())
1710     if (!Check(FD->getLocation(), FD->getType(), FD))
1711       return false;
1712   return true;
1713 }
1714 
1715 /// Check whether a function's parameter types are all literal types. If so,
1716 /// return true. If not, produce a suitable diagnostic and return false.
1717 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1718                                          const FunctionDecl *FD,
1719                                          Sema::CheckConstexprKind Kind) {
1720   unsigned ArgIndex = 0;
1721   const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1722   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1723                                               e = FT->param_type_end();
1724        i != e; ++i, ++ArgIndex) {
1725     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1726     assert(PD && "null in a parameter list");
1727     SourceLocation ParamLoc = PD->getLocation();
1728     if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1729                          diag::err_constexpr_non_literal_param, ArgIndex + 1,
1730                          PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1731                          FD->isConsteval()))
1732       return false;
1733   }
1734   return true;
1735 }
1736 
1737 /// Check whether a function's return type is a literal type. If so, return
1738 /// true. If not, produce a suitable diagnostic and return false.
1739 static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1740                                      Sema::CheckConstexprKind Kind) {
1741   if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1742                        diag::err_constexpr_non_literal_return,
1743                        FD->isConsteval()))
1744     return false;
1745   return true;
1746 }
1747 
1748 /// Get diagnostic %select index for tag kind for
1749 /// record diagnostic message.
1750 /// WARNING: Indexes apply to particular diagnostics only!
1751 ///
1752 /// \returns diagnostic %select index.
1753 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1754   switch (Tag) {
1755   case TTK_Struct: return 0;
1756   case TTK_Interface: return 1;
1757   case TTK_Class:  return 2;
1758   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1759   }
1760 }
1761 
1762 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1763                                        Stmt *Body,
1764                                        Sema::CheckConstexprKind Kind);
1765 
1766 // Check whether a function declaration satisfies the requirements of a
1767 // constexpr function definition or a constexpr constructor definition. If so,
1768 // return true. If not, produce appropriate diagnostics (unless asked not to by
1769 // Kind) and return false.
1770 //
1771 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1772 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
1773                                             CheckConstexprKind Kind) {
1774   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1775   if (MD && MD->isInstance()) {
1776     // C++11 [dcl.constexpr]p4:
1777     //  The definition of a constexpr constructor shall satisfy the following
1778     //  constraints:
1779     //  - the class shall not have any virtual base classes;
1780     //
1781     // FIXME: This only applies to constructors and destructors, not arbitrary
1782     // member functions.
1783     const CXXRecordDecl *RD = MD->getParent();
1784     if (RD->getNumVBases()) {
1785       if (Kind == CheckConstexprKind::CheckValid)
1786         return false;
1787 
1788       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1789         << isa<CXXConstructorDecl>(NewFD)
1790         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1791       for (const auto &I : RD->vbases())
1792         Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1793             << I.getSourceRange();
1794       return false;
1795     }
1796   }
1797 
1798   if (!isa<CXXConstructorDecl>(NewFD)) {
1799     // C++11 [dcl.constexpr]p3:
1800     //  The definition of a constexpr function shall satisfy the following
1801     //  constraints:
1802     // - it shall not be virtual; (removed in C++20)
1803     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1804     if (Method && Method->isVirtual()) {
1805       if (getLangOpts().CPlusPlus20) {
1806         if (Kind == CheckConstexprKind::Diagnose)
1807           Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1808       } else {
1809         if (Kind == CheckConstexprKind::CheckValid)
1810           return false;
1811 
1812         Method = Method->getCanonicalDecl();
1813         Diag(Method->getLocation(), diag::err_constexpr_virtual);
1814 
1815         // If it's not obvious why this function is virtual, find an overridden
1816         // function which uses the 'virtual' keyword.
1817         const CXXMethodDecl *WrittenVirtual = Method;
1818         while (!WrittenVirtual->isVirtualAsWritten())
1819           WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1820         if (WrittenVirtual != Method)
1821           Diag(WrittenVirtual->getLocation(),
1822                diag::note_overridden_virtual_function);
1823         return false;
1824       }
1825     }
1826 
1827     // - its return type shall be a literal type;
1828     if (!CheckConstexprReturnType(*this, NewFD, Kind))
1829       return false;
1830   }
1831 
1832   if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1833     // A destructor can be constexpr only if the defaulted destructor could be;
1834     // we don't need to check the members and bases if we already know they all
1835     // have constexpr destructors.
1836     if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1837       if (Kind == CheckConstexprKind::CheckValid)
1838         return false;
1839       if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1840         return false;
1841     }
1842   }
1843 
1844   // - each of its parameter types shall be a literal type;
1845   if (!CheckConstexprParameterTypes(*this, NewFD, Kind))
1846     return false;
1847 
1848   Stmt *Body = NewFD->getBody();
1849   assert(Body &&
1850          "CheckConstexprFunctionDefinition called on function with no body");
1851   return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1852 }
1853 
1854 /// Check the given declaration statement is legal within a constexpr function
1855 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1856 ///
1857 /// \return true if the body is OK (maybe only as an extension), false if we
1858 ///         have diagnosed a problem.
1859 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1860                                    DeclStmt *DS, SourceLocation &Cxx1yLoc,
1861                                    Sema::CheckConstexprKind Kind) {
1862   // C++11 [dcl.constexpr]p3 and p4:
1863   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
1864   //  contain only
1865   for (const auto *DclIt : DS->decls()) {
1866     switch (DclIt->getKind()) {
1867     case Decl::StaticAssert:
1868     case Decl::Using:
1869     case Decl::UsingShadow:
1870     case Decl::UsingDirective:
1871     case Decl::UnresolvedUsingTypename:
1872     case Decl::UnresolvedUsingValue:
1873     case Decl::UsingEnum:
1874       //   - static_assert-declarations
1875       //   - using-declarations,
1876       //   - using-directives,
1877       //   - using-enum-declaration
1878       continue;
1879 
1880     case Decl::Typedef:
1881     case Decl::TypeAlias: {
1882       //   - typedef declarations and alias-declarations that do not define
1883       //     classes or enumerations,
1884       const auto *TN = cast<TypedefNameDecl>(DclIt);
1885       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1886         // Don't allow variably-modified types in constexpr functions.
1887         if (Kind == Sema::CheckConstexprKind::Diagnose) {
1888           TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1889           SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1890             << TL.getSourceRange() << TL.getType()
1891             << isa<CXXConstructorDecl>(Dcl);
1892         }
1893         return false;
1894       }
1895       continue;
1896     }
1897 
1898     case Decl::Enum:
1899     case Decl::CXXRecord:
1900       // C++1y allows types to be defined, not just declared.
1901       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1902         if (Kind == Sema::CheckConstexprKind::Diagnose) {
1903           SemaRef.Diag(DS->getBeginLoc(),
1904                        SemaRef.getLangOpts().CPlusPlus14
1905                            ? diag::warn_cxx11_compat_constexpr_type_definition
1906                            : diag::ext_constexpr_type_definition)
1907               << isa<CXXConstructorDecl>(Dcl);
1908         } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1909           return false;
1910         }
1911       }
1912       continue;
1913 
1914     case Decl::EnumConstant:
1915     case Decl::IndirectField:
1916     case Decl::ParmVar:
1917       // These can only appear with other declarations which are banned in
1918       // C++11 and permitted in C++1y, so ignore them.
1919       continue;
1920 
1921     case Decl::Var:
1922     case Decl::Decomposition: {
1923       // C++1y [dcl.constexpr]p3 allows anything except:
1924       //   a definition of a variable of non-literal type or of static or
1925       //   thread storage duration or [before C++2a] for which no
1926       //   initialization is performed.
1927       const auto *VD = cast<VarDecl>(DclIt);
1928       if (VD->isThisDeclarationADefinition()) {
1929         if (VD->isStaticLocal()) {
1930           if (Kind == Sema::CheckConstexprKind::Diagnose) {
1931             SemaRef.Diag(VD->getLocation(),
1932                          SemaRef.getLangOpts().CPlusPlus23
1933                              ? diag::warn_cxx20_compat_constexpr_var
1934                              : diag::ext_constexpr_static_var)
1935                 << isa<CXXConstructorDecl>(Dcl)
1936                 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1937           } else if (!SemaRef.getLangOpts().CPlusPlus23) {
1938             return false;
1939           }
1940         }
1941         if (SemaRef.LangOpts.CPlusPlus23) {
1942           CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1943                            diag::warn_cxx20_compat_constexpr_var,
1944                            isa<CXXConstructorDecl>(Dcl),
1945                            /*variable of non-literal type*/ 2);
1946         } else if (CheckLiteralType(
1947                        SemaRef, Kind, VD->getLocation(), VD->getType(),
1948                        diag::err_constexpr_local_var_non_literal_type,
1949                        isa<CXXConstructorDecl>(Dcl))) {
1950           return false;
1951         }
1952         if (!VD->getType()->isDependentType() &&
1953             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1954           if (Kind == Sema::CheckConstexprKind::Diagnose) {
1955             SemaRef.Diag(
1956                 VD->getLocation(),
1957                 SemaRef.getLangOpts().CPlusPlus20
1958                     ? diag::warn_cxx17_compat_constexpr_local_var_no_init
1959                     : diag::ext_constexpr_local_var_no_init)
1960                 << isa<CXXConstructorDecl>(Dcl);
1961           } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1962             return false;
1963           }
1964           continue;
1965         }
1966       }
1967       if (Kind == Sema::CheckConstexprKind::Diagnose) {
1968         SemaRef.Diag(VD->getLocation(),
1969                      SemaRef.getLangOpts().CPlusPlus14
1970                       ? diag::warn_cxx11_compat_constexpr_local_var
1971                       : diag::ext_constexpr_local_var)
1972           << isa<CXXConstructorDecl>(Dcl);
1973       } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1974         return false;
1975       }
1976       continue;
1977     }
1978 
1979     case Decl::NamespaceAlias:
1980     case Decl::Function:
1981       // These are disallowed in C++11 and permitted in C++1y. Allow them
1982       // everywhere as an extension.
1983       if (!Cxx1yLoc.isValid())
1984         Cxx1yLoc = DS->getBeginLoc();
1985       continue;
1986 
1987     default:
1988       if (Kind == Sema::CheckConstexprKind::Diagnose) {
1989         SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1990             << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
1991       }
1992       return false;
1993     }
1994   }
1995 
1996   return true;
1997 }
1998 
1999 /// Check that the given field is initialized within a constexpr constructor.
2000 ///
2001 /// \param Dcl The constexpr constructor being checked.
2002 /// \param Field The field being checked. This may be a member of an anonymous
2003 ///        struct or union nested within the class being checked.
2004 /// \param Inits All declarations, including anonymous struct/union members and
2005 ///        indirect members, for which any initialization was provided.
2006 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach
2007 ///        multiple notes for different members to the same error.
2008 /// \param Kind Whether we're diagnosing a constructor as written or determining
2009 ///        whether the formal requirements are satisfied.
2010 /// \return \c false if we're checking for validity and the constructor does
2011 ///         not satisfy the requirements on a constexpr constructor.
2012 static bool CheckConstexprCtorInitializer(Sema &SemaRef,
2013                                           const FunctionDecl *Dcl,
2014                                           FieldDecl *Field,
2015                                           llvm::SmallSet<Decl*, 16> &Inits,
2016                                           bool &Diagnosed,
2017                                           Sema::CheckConstexprKind Kind) {
2018   // In C++20 onwards, there's nothing to check for validity.
2019   if (Kind == Sema::CheckConstexprKind::CheckValid &&
2020       SemaRef.getLangOpts().CPlusPlus20)
2021     return true;
2022 
2023   if (Field->isInvalidDecl())
2024     return true;
2025 
2026   if (Field->isUnnamedBitfield())
2027     return true;
2028 
2029   // Anonymous unions with no variant members and empty anonymous structs do not
2030   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
2031   // indirect fields don't need initializing.
2032   if (Field->isAnonymousStructOrUnion() &&
2033       (Field->getType()->isUnionType()
2034            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
2035            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
2036     return true;
2037 
2038   if (!Inits.count(Field)) {
2039     if (Kind == Sema::CheckConstexprKind::Diagnose) {
2040       if (!Diagnosed) {
2041         SemaRef.Diag(Dcl->getLocation(),
2042                      SemaRef.getLangOpts().CPlusPlus20
2043                          ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
2044                          : diag::ext_constexpr_ctor_missing_init);
2045         Diagnosed = true;
2046       }
2047       SemaRef.Diag(Field->getLocation(),
2048                    diag::note_constexpr_ctor_missing_init);
2049     } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2050       return false;
2051     }
2052   } else if (Field->isAnonymousStructOrUnion()) {
2053     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
2054     for (auto *I : RD->fields())
2055       // If an anonymous union contains an anonymous struct of which any member
2056       // is initialized, all members must be initialized.
2057       if (!RD->isUnion() || Inits.count(I))
2058         if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2059                                            Kind))
2060           return false;
2061   }
2062   return true;
2063 }
2064 
2065 /// Check the provided statement is allowed in a constexpr function
2066 /// definition.
2067 static bool
2068 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
2069                            SmallVectorImpl<SourceLocation> &ReturnStmts,
2070                            SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2071                            SourceLocation &Cxx2bLoc,
2072                            Sema::CheckConstexprKind Kind) {
2073   // - its function-body shall be [...] a compound-statement that contains only
2074   switch (S->getStmtClass()) {
2075   case Stmt::NullStmtClass:
2076     //   - null statements,
2077     return true;
2078 
2079   case Stmt::DeclStmtClass:
2080     //   - static_assert-declarations
2081     //   - using-declarations,
2082     //   - using-directives,
2083     //   - typedef declarations and alias-declarations that do not define
2084     //     classes or enumerations,
2085     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
2086       return false;
2087     return true;
2088 
2089   case Stmt::ReturnStmtClass:
2090     //   - and exactly one return statement;
2091     if (isa<CXXConstructorDecl>(Dcl)) {
2092       // C++1y allows return statements in constexpr constructors.
2093       if (!Cxx1yLoc.isValid())
2094         Cxx1yLoc = S->getBeginLoc();
2095       return true;
2096     }
2097 
2098     ReturnStmts.push_back(S->getBeginLoc());
2099     return true;
2100 
2101   case Stmt::AttributedStmtClass:
2102     // Attributes on a statement don't affect its formal kind and hence don't
2103     // affect its validity in a constexpr function.
2104     return CheckConstexprFunctionStmt(
2105         SemaRef, Dcl, cast<AttributedStmt>(S)->getSubStmt(), ReturnStmts,
2106         Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);
2107 
2108   case Stmt::CompoundStmtClass: {
2109     // C++1y allows compound-statements.
2110     if (!Cxx1yLoc.isValid())
2111       Cxx1yLoc = S->getBeginLoc();
2112 
2113     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2114     for (auto *BodyIt : CompStmt->body()) {
2115       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2116                                       Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2117         return false;
2118     }
2119     return true;
2120   }
2121 
2122   case Stmt::IfStmtClass: {
2123     // C++1y allows if-statements.
2124     if (!Cxx1yLoc.isValid())
2125       Cxx1yLoc = S->getBeginLoc();
2126 
2127     IfStmt *If = cast<IfStmt>(S);
2128     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2129                                     Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2130       return false;
2131     if (If->getElse() &&
2132         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2133                                     Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2134       return false;
2135     return true;
2136   }
2137 
2138   case Stmt::WhileStmtClass:
2139   case Stmt::DoStmtClass:
2140   case Stmt::ForStmtClass:
2141   case Stmt::CXXForRangeStmtClass:
2142   case Stmt::ContinueStmtClass:
2143     // C++1y allows all of these. We don't allow them as extensions in C++11,
2144     // because they don't make sense without variable mutation.
2145     if (!SemaRef.getLangOpts().CPlusPlus14)
2146       break;
2147     if (!Cxx1yLoc.isValid())
2148       Cxx1yLoc = S->getBeginLoc();
2149     for (Stmt *SubStmt : S->children()) {
2150       if (SubStmt &&
2151           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2152                                       Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2153         return false;
2154     }
2155     return true;
2156 
2157   case Stmt::SwitchStmtClass:
2158   case Stmt::CaseStmtClass:
2159   case Stmt::DefaultStmtClass:
2160   case Stmt::BreakStmtClass:
2161     // C++1y allows switch-statements, and since they don't need variable
2162     // mutation, we can reasonably allow them in C++11 as an extension.
2163     if (!Cxx1yLoc.isValid())
2164       Cxx1yLoc = S->getBeginLoc();
2165     for (Stmt *SubStmt : S->children()) {
2166       if (SubStmt &&
2167           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2168                                       Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2169         return false;
2170     }
2171     return true;
2172 
2173   case Stmt::LabelStmtClass:
2174   case Stmt::GotoStmtClass:
2175     if (Cxx2bLoc.isInvalid())
2176       Cxx2bLoc = S->getBeginLoc();
2177     for (Stmt *SubStmt : S->children()) {
2178       if (SubStmt &&
2179           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2180                                       Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2181         return false;
2182     }
2183     return true;
2184 
2185   case Stmt::GCCAsmStmtClass:
2186   case Stmt::MSAsmStmtClass:
2187     // C++2a allows inline assembly statements.
2188   case Stmt::CXXTryStmtClass:
2189     if (Cxx2aLoc.isInvalid())
2190       Cxx2aLoc = S->getBeginLoc();
2191     for (Stmt *SubStmt : S->children()) {
2192       if (SubStmt &&
2193           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2194                                       Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2195         return false;
2196     }
2197     return true;
2198 
2199   case Stmt::CXXCatchStmtClass:
2200     // Do not bother checking the language mode (already covered by the
2201     // try block check).
2202     if (!CheckConstexprFunctionStmt(
2203             SemaRef, Dcl, cast<CXXCatchStmt>(S)->getHandlerBlock(), ReturnStmts,
2204             Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2205       return false;
2206     return true;
2207 
2208   default:
2209     if (!isa<Expr>(S))
2210       break;
2211 
2212     // C++1y allows expression-statements.
2213     if (!Cxx1yLoc.isValid())
2214       Cxx1yLoc = S->getBeginLoc();
2215     return true;
2216   }
2217 
2218   if (Kind == Sema::CheckConstexprKind::Diagnose) {
2219     SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2220         << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2221   }
2222   return false;
2223 }
2224 
2225 /// Check the body for the given constexpr function declaration only contains
2226 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2227 ///
2228 /// \return true if the body is OK, false if we have found or diagnosed a
2229 /// problem.
2230 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2231                                        Stmt *Body,
2232                                        Sema::CheckConstexprKind Kind) {
2233   SmallVector<SourceLocation, 4> ReturnStmts;
2234 
2235   if (isa<CXXTryStmt>(Body)) {
2236     // C++11 [dcl.constexpr]p3:
2237     //  The definition of a constexpr function shall satisfy the following
2238     //  constraints: [...]
2239     // - its function-body shall be = delete, = default, or a
2240     //   compound-statement
2241     //
2242     // C++11 [dcl.constexpr]p4:
2243     //  In the definition of a constexpr constructor, [...]
2244     // - its function-body shall not be a function-try-block;
2245     //
2246     // This restriction is lifted in C++2a, as long as inner statements also
2247     // apply the general constexpr rules.
2248     switch (Kind) {
2249     case Sema::CheckConstexprKind::CheckValid:
2250       if (!SemaRef.getLangOpts().CPlusPlus20)
2251         return false;
2252       break;
2253 
2254     case Sema::CheckConstexprKind::Diagnose:
2255       SemaRef.Diag(Body->getBeginLoc(),
2256            !SemaRef.getLangOpts().CPlusPlus20
2257                ? diag::ext_constexpr_function_try_block_cxx20
2258                : diag::warn_cxx17_compat_constexpr_function_try_block)
2259           << isa<CXXConstructorDecl>(Dcl);
2260       break;
2261     }
2262   }
2263 
2264   // - its function-body shall be [...] a compound-statement that contains only
2265   //   [... list of cases ...]
2266   //
2267   // Note that walking the children here is enough to properly check for
2268   // CompoundStmt and CXXTryStmt body.
2269   SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc;
2270   for (Stmt *SubStmt : Body->children()) {
2271     if (SubStmt &&
2272         !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2273                                     Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2274       return false;
2275   }
2276 
2277   if (Kind == Sema::CheckConstexprKind::CheckValid) {
2278     // If this is only valid as an extension, report that we don't satisfy the
2279     // constraints of the current language.
2280     if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus23) ||
2281         (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2282         (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2283       return false;
2284   } else if (Cxx2bLoc.isValid()) {
2285     SemaRef.Diag(Cxx2bLoc,
2286                  SemaRef.getLangOpts().CPlusPlus23
2287                      ? diag::warn_cxx20_compat_constexpr_body_invalid_stmt
2288                      : diag::ext_constexpr_body_invalid_stmt_cxx23)
2289         << isa<CXXConstructorDecl>(Dcl);
2290   } else if (Cxx2aLoc.isValid()) {
2291     SemaRef.Diag(Cxx2aLoc,
2292          SemaRef.getLangOpts().CPlusPlus20
2293            ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2294            : diag::ext_constexpr_body_invalid_stmt_cxx20)
2295       << isa<CXXConstructorDecl>(Dcl);
2296   } else if (Cxx1yLoc.isValid()) {
2297     SemaRef.Diag(Cxx1yLoc,
2298          SemaRef.getLangOpts().CPlusPlus14
2299            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2300            : diag::ext_constexpr_body_invalid_stmt)
2301       << isa<CXXConstructorDecl>(Dcl);
2302   }
2303 
2304   if (const CXXConstructorDecl *Constructor
2305         = dyn_cast<CXXConstructorDecl>(Dcl)) {
2306     const CXXRecordDecl *RD = Constructor->getParent();
2307     // DR1359:
2308     // - every non-variant non-static data member and base class sub-object
2309     //   shall be initialized;
2310     // DR1460:
2311     // - if the class is a union having variant members, exactly one of them
2312     //   shall be initialized;
2313     if (RD->isUnion()) {
2314       if (Constructor->getNumCtorInitializers() == 0 &&
2315           RD->hasVariantMembers()) {
2316         if (Kind == Sema::CheckConstexprKind::Diagnose) {
2317           SemaRef.Diag(
2318               Dcl->getLocation(),
2319               SemaRef.getLangOpts().CPlusPlus20
2320                   ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2321                   : diag::ext_constexpr_union_ctor_no_init);
2322         } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2323           return false;
2324         }
2325       }
2326     } else if (!Constructor->isDependentContext() &&
2327                !Constructor->isDelegatingConstructor()) {
2328       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2329 
2330       // Skip detailed checking if we have enough initializers, and we would
2331       // allow at most one initializer per member.
2332       bool AnyAnonStructUnionMembers = false;
2333       unsigned Fields = 0;
2334       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2335            E = RD->field_end(); I != E; ++I, ++Fields) {
2336         if (I->isAnonymousStructOrUnion()) {
2337           AnyAnonStructUnionMembers = true;
2338           break;
2339         }
2340       }
2341       // DR1460:
2342       // - if the class is a union-like class, but is not a union, for each of
2343       //   its anonymous union members having variant members, exactly one of
2344       //   them shall be initialized;
2345       if (AnyAnonStructUnionMembers ||
2346           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2347         // Check initialization of non-static data members. Base classes are
2348         // always initialized so do not need to be checked. Dependent bases
2349         // might not have initializers in the member initializer list.
2350         llvm::SmallSet<Decl*, 16> Inits;
2351         for (const auto *I: Constructor->inits()) {
2352           if (FieldDecl *FD = I->getMember())
2353             Inits.insert(FD);
2354           else if (IndirectFieldDecl *ID = I->getIndirectMember())
2355             Inits.insert(ID->chain_begin(), ID->chain_end());
2356         }
2357 
2358         bool Diagnosed = false;
2359         for (auto *I : RD->fields())
2360           if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2361                                              Kind))
2362             return false;
2363       }
2364     }
2365   } else {
2366     if (ReturnStmts.empty()) {
2367       // C++1y doesn't require constexpr functions to contain a 'return'
2368       // statement. We still do, unless the return type might be void, because
2369       // otherwise if there's no return statement, the function cannot
2370       // be used in a core constant expression.
2371       bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
2372                 (Dcl->getReturnType()->isVoidType() ||
2373                  Dcl->getReturnType()->isDependentType());
2374       switch (Kind) {
2375       case Sema::CheckConstexprKind::Diagnose:
2376         SemaRef.Diag(Dcl->getLocation(),
2377                      OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2378                         : diag::err_constexpr_body_no_return)
2379             << Dcl->isConsteval();
2380         if (!OK)
2381           return false;
2382         break;
2383 
2384       case Sema::CheckConstexprKind::CheckValid:
2385         // The formal requirements don't include this rule in C++14, even
2386         // though the "must be able to produce a constant expression" rules
2387         // still imply it in some cases.
2388         if (!SemaRef.getLangOpts().CPlusPlus14)
2389           return false;
2390         break;
2391       }
2392     } else if (ReturnStmts.size() > 1) {
2393       switch (Kind) {
2394       case Sema::CheckConstexprKind::Diagnose:
2395         SemaRef.Diag(
2396             ReturnStmts.back(),
2397             SemaRef.getLangOpts().CPlusPlus14
2398                 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2399                 : diag::ext_constexpr_body_multiple_return);
2400         for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2401           SemaRef.Diag(ReturnStmts[I],
2402                        diag::note_constexpr_body_previous_return);
2403         break;
2404 
2405       case Sema::CheckConstexprKind::CheckValid:
2406         if (!SemaRef.getLangOpts().CPlusPlus14)
2407           return false;
2408         break;
2409       }
2410     }
2411   }
2412 
2413   // C++11 [dcl.constexpr]p5:
2414   //   if no function argument values exist such that the function invocation
2415   //   substitution would produce a constant expression, the program is
2416   //   ill-formed; no diagnostic required.
2417   // C++11 [dcl.constexpr]p3:
2418   //   - every constructor call and implicit conversion used in initializing the
2419   //     return value shall be one of those allowed in a constant expression.
2420   // C++11 [dcl.constexpr]p4:
2421   //   - every constructor involved in initializing non-static data members and
2422   //     base class sub-objects shall be a constexpr constructor.
2423   //
2424   // Note that this rule is distinct from the "requirements for a constexpr
2425   // function", so is not checked in CheckValid mode.
2426   SmallVector<PartialDiagnosticAt, 8> Diags;
2427   if (Kind == Sema::CheckConstexprKind::Diagnose &&
2428       !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2429     SemaRef.Diag(Dcl->getLocation(),
2430                  diag::ext_constexpr_function_never_constant_expr)
2431         << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2432     for (size_t I = 0, N = Diags.size(); I != N; ++I)
2433       SemaRef.Diag(Diags[I].first, Diags[I].second);
2434     // Don't return false here: we allow this for compatibility in
2435     // system headers.
2436   }
2437 
2438   return true;
2439 }
2440 
2441 bool Sema::CheckImmediateEscalatingFunctionDefinition(
2442     FunctionDecl *FD, const sema::FunctionScopeInfo *FSI) {
2443   if (!getLangOpts().CPlusPlus20 || !FD->isImmediateEscalating())
2444     return true;
2445   FD->setBodyContainsImmediateEscalatingExpressions(
2446       FSI->FoundImmediateEscalatingExpression);
2447   if (FSI->FoundImmediateEscalatingExpression) {
2448     auto it = UndefinedButUsed.find(FD->getCanonicalDecl());
2449     if (it != UndefinedButUsed.end()) {
2450       Diag(it->second, diag::err_immediate_function_used_before_definition)
2451           << it->first;
2452       Diag(FD->getLocation(), diag::note_defined_here) << FD;
2453       if (FD->isImmediateFunction() && !FD->isConsteval())
2454         DiagnoseImmediateEscalatingReason(FD);
2455       return false;
2456     }
2457   }
2458   return true;
2459 }
2460 
2461 void Sema::DiagnoseImmediateEscalatingReason(FunctionDecl *FD) {
2462   assert(FD->isImmediateEscalating() && !FD->isConsteval() &&
2463          "expected an immediate function");
2464   assert(FD->hasBody() && "expected the function to have a body");
2465   struct ImmediateEscalatingExpressionsVisitor
2466       : public RecursiveASTVisitor<ImmediateEscalatingExpressionsVisitor> {
2467 
2468     using Base = RecursiveASTVisitor<ImmediateEscalatingExpressionsVisitor>;
2469     Sema &SemaRef;
2470 
2471     const FunctionDecl *ImmediateFn;
2472     bool ImmediateFnIsConstructor;
2473     CXXConstructorDecl *CurrentConstructor = nullptr;
2474     CXXCtorInitializer *CurrentInit = nullptr;
2475 
2476     ImmediateEscalatingExpressionsVisitor(Sema &SemaRef, FunctionDecl *FD)
2477         : SemaRef(SemaRef), ImmediateFn(FD),
2478           ImmediateFnIsConstructor(isa<CXXConstructorDecl>(FD)) {}
2479 
2480     bool shouldVisitImplicitCode() const { return true; }
2481     bool shouldVisitLambdaBody() const { return false; }
2482 
2483     void Diag(const Expr *E, const FunctionDecl *Fn, bool IsCall) {
2484       SourceLocation Loc = E->getBeginLoc();
2485       SourceRange Range = E->getSourceRange();
2486       if (CurrentConstructor && CurrentInit) {
2487         Loc = CurrentConstructor->getLocation();
2488         Range = CurrentInit->isWritten() ? CurrentInit->getSourceRange()
2489                                          : SourceRange();
2490       }
2491       SemaRef.Diag(Loc, diag::note_immediate_function_reason)
2492           << ImmediateFn << Fn << Fn->isConsteval() << IsCall
2493           << isa<CXXConstructorDecl>(Fn) << ImmediateFnIsConstructor
2494           << (CurrentInit != nullptr)
2495           << (CurrentInit && !CurrentInit->isWritten())
2496           << (CurrentInit ? CurrentInit->getAnyMember() : nullptr) << Range;
2497     }
2498     bool TraverseCallExpr(CallExpr *E) {
2499       if (const auto *DR =
2500               dyn_cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit());
2501           DR && DR->isImmediateEscalating()) {
2502         Diag(E, E->getDirectCallee(), /*IsCall=*/true);
2503         return false;
2504       }
2505 
2506       for (Expr *A : E->arguments())
2507         if (!getDerived().TraverseStmt(A))
2508           return false;
2509 
2510       return true;
2511     }
2512 
2513     bool VisitDeclRefExpr(DeclRefExpr *E) {
2514       if (const auto *ReferencedFn = dyn_cast<FunctionDecl>(E->getDecl());
2515           ReferencedFn && E->isImmediateEscalating()) {
2516         Diag(E, ReferencedFn, /*IsCall=*/false);
2517         return false;
2518       }
2519 
2520       return true;
2521     }
2522 
2523     bool VisitCXXConstructExpr(CXXConstructExpr *E) {
2524       CXXConstructorDecl *D = E->getConstructor();
2525       if (E->isImmediateEscalating()) {
2526         Diag(E, D, /*IsCall=*/true);
2527         return false;
2528       }
2529       return true;
2530     }
2531 
2532     bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
2533       llvm::SaveAndRestore RAII(CurrentInit, Init);
2534       return Base::TraverseConstructorInitializer(Init);
2535     }
2536 
2537     bool TraverseCXXConstructorDecl(CXXConstructorDecl *Ctr) {
2538       llvm::SaveAndRestore RAII(CurrentConstructor, Ctr);
2539       return Base::TraverseCXXConstructorDecl(Ctr);
2540     }
2541 
2542     bool TraverseType(QualType T) { return true; }
2543     bool VisitBlockExpr(BlockExpr *T) { return true; }
2544 
2545   } Visitor(*this, FD);
2546   Visitor.TraverseDecl(FD);
2547 }
2548 
2549 /// Get the class that is directly named by the current context. This is the
2550 /// class for which an unqualified-id in this scope could name a constructor
2551 /// or destructor.
2552 ///
2553 /// If the scope specifier denotes a class, this will be that class.
2554 /// If the scope specifier is empty, this will be the class whose
2555 /// member-specification we are currently within. Otherwise, there
2556 /// is no such class.
2557 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2558   assert(getLangOpts().CPlusPlus && "No class names in C!");
2559 
2560   if (SS && SS->isInvalid())
2561     return nullptr;
2562 
2563   if (SS && SS->isNotEmpty()) {
2564     DeclContext *DC = computeDeclContext(*SS, true);
2565     return dyn_cast_or_null<CXXRecordDecl>(DC);
2566   }
2567 
2568   return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2569 }
2570 
2571 /// isCurrentClassName - Determine whether the identifier II is the
2572 /// name of the class type currently being defined. In the case of
2573 /// nested classes, this will only return true if II is the name of
2574 /// the innermost class.
2575 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2576                               const CXXScopeSpec *SS) {
2577   CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2578   return CurDecl && &II == CurDecl->getIdentifier();
2579 }
2580 
2581 /// Determine whether the identifier II is a typo for the name of
2582 /// the class type currently being defined. If so, update it to the identifier
2583 /// that should have been used.
2584 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2585   assert(getLangOpts().CPlusPlus && "No class names in C!");
2586 
2587   if (!getLangOpts().SpellChecking)
2588     return false;
2589 
2590   CXXRecordDecl *CurDecl;
2591   if (SS && SS->isSet() && !SS->isInvalid()) {
2592     DeclContext *DC = computeDeclContext(*SS, true);
2593     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2594   } else
2595     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2596 
2597   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2598       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2599           < II->getLength()) {
2600     II = CurDecl->getIdentifier();
2601     return true;
2602   }
2603 
2604   return false;
2605 }
2606 
2607 /// Determine whether the given class is a base class of the given
2608 /// class, including looking at dependent bases.
2609 static bool findCircularInheritance(const CXXRecordDecl *Class,
2610                                     const CXXRecordDecl *Current) {
2611   SmallVector<const CXXRecordDecl*, 8> Queue;
2612 
2613   Class = Class->getCanonicalDecl();
2614   while (true) {
2615     for (const auto &I : Current->bases()) {
2616       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2617       if (!Base)
2618         continue;
2619 
2620       Base = Base->getDefinition();
2621       if (!Base)
2622         continue;
2623 
2624       if (Base->getCanonicalDecl() == Class)
2625         return true;
2626 
2627       Queue.push_back(Base);
2628     }
2629 
2630     if (Queue.empty())
2631       return false;
2632 
2633     Current = Queue.pop_back_val();
2634   }
2635 
2636   return false;
2637 }
2638 
2639 /// Check the validity of a C++ base class specifier.
2640 ///
2641 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2642 /// and returns NULL otherwise.
2643 CXXBaseSpecifier *
2644 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2645                          SourceRange SpecifierRange,
2646                          bool Virtual, AccessSpecifier Access,
2647                          TypeSourceInfo *TInfo,
2648                          SourceLocation EllipsisLoc) {
2649   // In HLSL, unspecified class access is public rather than private.
2650   if (getLangOpts().HLSL && Class->getTagKind() == TTK_Class &&
2651       Access == AS_none)
2652     Access = AS_public;
2653 
2654   QualType BaseType = TInfo->getType();
2655   if (BaseType->containsErrors()) {
2656     // Already emitted a diagnostic when parsing the error type.
2657     return nullptr;
2658   }
2659   // C++ [class.union]p1:
2660   //   A union shall not have base classes.
2661   if (Class->isUnion()) {
2662     Diag(Class->getLocation(), diag::err_base_clause_on_union)
2663       << SpecifierRange;
2664     return nullptr;
2665   }
2666 
2667   if (EllipsisLoc.isValid() &&
2668       !TInfo->getType()->containsUnexpandedParameterPack()) {
2669     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2670       << TInfo->getTypeLoc().getSourceRange();
2671     EllipsisLoc = SourceLocation();
2672   }
2673 
2674   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2675 
2676   if (BaseType->isDependentType()) {
2677     // Make sure that we don't have circular inheritance among our dependent
2678     // bases. For non-dependent bases, the check for completeness below handles
2679     // this.
2680     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2681       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2682           ((BaseDecl = BaseDecl->getDefinition()) &&
2683            findCircularInheritance(Class, BaseDecl))) {
2684         Diag(BaseLoc, diag::err_circular_inheritance)
2685           << BaseType << Context.getTypeDeclType(Class);
2686 
2687         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2688           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2689             << BaseType;
2690 
2691         return nullptr;
2692       }
2693     }
2694 
2695     // Make sure that we don't make an ill-formed AST where the type of the
2696     // Class is non-dependent and its attached base class specifier is an
2697     // dependent type, which violates invariants in many clang code paths (e.g.
2698     // constexpr evaluator). If this case happens (in errory-recovery mode), we
2699     // explicitly mark the Class decl invalid. The diagnostic was already
2700     // emitted.
2701     if (!Class->getTypeForDecl()->isDependentType())
2702       Class->setInvalidDecl();
2703     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2704                                           Class->getTagKind() == TTK_Class,
2705                                           Access, TInfo, EllipsisLoc);
2706   }
2707 
2708   // Base specifiers must be record types.
2709   if (!BaseType->isRecordType()) {
2710     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2711     return nullptr;
2712   }
2713 
2714   // C++ [class.union]p1:
2715   //   A union shall not be used as a base class.
2716   if (BaseType->isUnionType()) {
2717     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2718     return nullptr;
2719   }
2720 
2721   // For the MS ABI, propagate DLL attributes to base class templates.
2722   if (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
2723       Context.getTargetInfo().getTriple().isPS()) {
2724     if (Attr *ClassAttr = getDLLAttr(Class)) {
2725       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2726               BaseType->getAsCXXRecordDecl())) {
2727         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2728                                             BaseLoc);
2729       }
2730     }
2731   }
2732 
2733   // C++ [class.derived]p2:
2734   //   The class-name in a base-specifier shall not be an incompletely
2735   //   defined class.
2736   if (RequireCompleteType(BaseLoc, BaseType,
2737                           diag::err_incomplete_base_class, SpecifierRange)) {
2738     Class->setInvalidDecl();
2739     return nullptr;
2740   }
2741 
2742   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2743   RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl();
2744   assert(BaseDecl && "Record type has no declaration");
2745   BaseDecl = BaseDecl->getDefinition();
2746   assert(BaseDecl && "Base type is not incomplete, but has no definition");
2747   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2748   assert(CXXBaseDecl && "Base type is not a C++ type");
2749 
2750   // Microsoft docs say:
2751   // "If a base-class has a code_seg attribute, derived classes must have the
2752   // same attribute."
2753   const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2754   const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2755   if ((DerivedCSA || BaseCSA) &&
2756       (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2757     Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2758     Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2759       << CXXBaseDecl;
2760     return nullptr;
2761   }
2762 
2763   // A class which contains a flexible array member is not suitable for use as a
2764   // base class:
2765   //   - If the layout determines that a base comes before another base,
2766   //     the flexible array member would index into the subsequent base.
2767   //   - If the layout determines that base comes before the derived class,
2768   //     the flexible array member would index into the derived class.
2769   if (CXXBaseDecl->hasFlexibleArrayMember()) {
2770     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2771       << CXXBaseDecl->getDeclName();
2772     return nullptr;
2773   }
2774 
2775   // C++ [class]p3:
2776   //   If a class is marked final and it appears as a base-type-specifier in
2777   //   base-clause, the program is ill-formed.
2778   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2779     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2780       << CXXBaseDecl->getDeclName()
2781       << FA->isSpelledAsSealed();
2782     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2783         << CXXBaseDecl->getDeclName() << FA->getRange();
2784     return nullptr;
2785   }
2786 
2787   if (BaseDecl->isInvalidDecl())
2788     Class->setInvalidDecl();
2789 
2790   // Create the base specifier.
2791   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2792                                         Class->getTagKind() == TTK_Class,
2793                                         Access, TInfo, EllipsisLoc);
2794 }
2795 
2796 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2797 /// one entry in the base class list of a class specifier, for
2798 /// example:
2799 ///    class foo : public bar, virtual private baz {
2800 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2801 BaseResult Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2802                                     const ParsedAttributesView &Attributes,
2803                                     bool Virtual, AccessSpecifier Access,
2804                                     ParsedType basetype, SourceLocation BaseLoc,
2805                                     SourceLocation EllipsisLoc) {
2806   if (!classdecl)
2807     return true;
2808 
2809   AdjustDeclIfTemplate(classdecl);
2810   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2811   if (!Class)
2812     return true;
2813 
2814   // We haven't yet attached the base specifiers.
2815   Class->setIsParsingBaseSpecifiers();
2816 
2817   // We do not support any C++11 attributes on base-specifiers yet.
2818   // Diagnose any attributes we see.
2819   for (const ParsedAttr &AL : Attributes) {
2820     if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2821       continue;
2822     if (AL.getKind() == ParsedAttr::UnknownAttribute)
2823       Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
2824           << AL << AL.getRange();
2825     else
2826       Diag(AL.getLoc(), diag::err_base_specifier_attribute)
2827           << AL << AL.isRegularKeywordAttribute() << AL.getRange();
2828   }
2829 
2830   TypeSourceInfo *TInfo = nullptr;
2831   GetTypeFromParser(basetype, &TInfo);
2832 
2833   if (EllipsisLoc.isInvalid() &&
2834       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2835                                       UPPC_BaseType))
2836     return true;
2837 
2838   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2839                                                       Virtual, Access, TInfo,
2840                                                       EllipsisLoc))
2841     return BaseSpec;
2842   else
2843     Class->setInvalidDecl();
2844 
2845   return true;
2846 }
2847 
2848 /// Use small set to collect indirect bases.  As this is only used
2849 /// locally, there's no need to abstract the small size parameter.
2850 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2851 
2852 /// Recursively add the bases of Type.  Don't add Type itself.
2853 static void
2854 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2855                   const QualType &Type)
2856 {
2857   // Even though the incoming type is a base, it might not be
2858   // a class -- it could be a template parm, for instance.
2859   if (auto Rec = Type->getAs<RecordType>()) {
2860     auto Decl = Rec->getAsCXXRecordDecl();
2861 
2862     // Iterate over its bases.
2863     for (const auto &BaseSpec : Decl->bases()) {
2864       QualType Base = Context.getCanonicalType(BaseSpec.getType())
2865         .getUnqualifiedType();
2866       if (Set.insert(Base).second)
2867         // If we've not already seen it, recurse.
2868         NoteIndirectBases(Context, Set, Base);
2869     }
2870   }
2871 }
2872 
2873 /// Performs the actual work of attaching the given base class
2874 /// specifiers to a C++ class.
2875 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2876                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2877  if (Bases.empty())
2878     return false;
2879 
2880   // Used to keep track of which base types we have already seen, so
2881   // that we can properly diagnose redundant direct base types. Note
2882   // that the key is always the unqualified canonical type of the base
2883   // class.
2884   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2885 
2886   // Used to track indirect bases so we can see if a direct base is
2887   // ambiguous.
2888   IndirectBaseSet IndirectBaseTypes;
2889 
2890   // Copy non-redundant base specifiers into permanent storage.
2891   unsigned NumGoodBases = 0;
2892   bool Invalid = false;
2893   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2894     QualType NewBaseType
2895       = Context.getCanonicalType(Bases[idx]->getType());
2896     NewBaseType = NewBaseType.getLocalUnqualifiedType();
2897 
2898     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2899     if (KnownBase) {
2900       // C++ [class.mi]p3:
2901       //   A class shall not be specified as a direct base class of a
2902       //   derived class more than once.
2903       Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2904           << KnownBase->getType() << Bases[idx]->getSourceRange();
2905 
2906       // Delete the duplicate base class specifier; we're going to
2907       // overwrite its pointer later.
2908       Context.Deallocate(Bases[idx]);
2909 
2910       Invalid = true;
2911     } else {
2912       // Okay, add this new base class.
2913       KnownBase = Bases[idx];
2914       Bases[NumGoodBases++] = Bases[idx];
2915 
2916       if (NewBaseType->isDependentType())
2917         continue;
2918       // Note this base's direct & indirect bases, if there could be ambiguity.
2919       if (Bases.size() > 1)
2920         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2921 
2922       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2923         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2924         if (Class->isInterface() &&
2925               (!RD->isInterfaceLike() ||
2926                KnownBase->getAccessSpecifier() != AS_public)) {
2927           // The Microsoft extension __interface does not permit bases that
2928           // are not themselves public interfaces.
2929           Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2930               << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2931               << RD->getSourceRange();
2932           Invalid = true;
2933         }
2934         if (RD->hasAttr<WeakAttr>())
2935           Class->addAttr(WeakAttr::CreateImplicit(Context));
2936       }
2937     }
2938   }
2939 
2940   // Attach the remaining base class specifiers to the derived class.
2941   Class->setBases(Bases.data(), NumGoodBases);
2942 
2943   // Check that the only base classes that are duplicate are virtual.
2944   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2945     // Check whether this direct base is inaccessible due to ambiguity.
2946     QualType BaseType = Bases[idx]->getType();
2947 
2948     // Skip all dependent types in templates being used as base specifiers.
2949     // Checks below assume that the base specifier is a CXXRecord.
2950     if (BaseType->isDependentType())
2951       continue;
2952 
2953     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2954       .getUnqualifiedType();
2955 
2956     if (IndirectBaseTypes.count(CanonicalBase)) {
2957       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2958                          /*DetectVirtual=*/true);
2959       bool found
2960         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2961       assert(found);
2962       (void)found;
2963 
2964       if (Paths.isAmbiguous(CanonicalBase))
2965         Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2966             << BaseType << getAmbiguousPathsDisplayString(Paths)
2967             << Bases[idx]->getSourceRange();
2968       else
2969         assert(Bases[idx]->isVirtual());
2970     }
2971 
2972     // Delete the base class specifier, since its data has been copied
2973     // into the CXXRecordDecl.
2974     Context.Deallocate(Bases[idx]);
2975   }
2976 
2977   return Invalid;
2978 }
2979 
2980 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2981 /// class, after checking whether there are any duplicate base
2982 /// classes.
2983 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2984                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2985   if (!ClassDecl || Bases.empty())
2986     return;
2987 
2988   AdjustDeclIfTemplate(ClassDecl);
2989   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2990 }
2991 
2992 /// Determine whether the type \p Derived is a C++ class that is
2993 /// derived from the type \p Base.
2994 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2995   if (!getLangOpts().CPlusPlus)
2996     return false;
2997 
2998   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2999   if (!DerivedRD)
3000     return false;
3001 
3002   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
3003   if (!BaseRD)
3004     return false;
3005 
3006   // If either the base or the derived type is invalid, don't try to
3007   // check whether one is derived from the other.
3008   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
3009     return false;
3010 
3011   // FIXME: In a modules build, do we need the entire path to be visible for us
3012   // to be able to use the inheritance relationship?
3013   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
3014     return false;
3015 
3016   return DerivedRD->isDerivedFrom(BaseRD);
3017 }
3018 
3019 /// Determine whether the type \p Derived is a C++ class that is
3020 /// derived from the type \p Base.
3021 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
3022                          CXXBasePaths &Paths) {
3023   if (!getLangOpts().CPlusPlus)
3024     return false;
3025 
3026   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
3027   if (!DerivedRD)
3028     return false;
3029 
3030   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
3031   if (!BaseRD)
3032     return false;
3033 
3034   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
3035     return false;
3036 
3037   return DerivedRD->isDerivedFrom(BaseRD, Paths);
3038 }
3039 
3040 static void BuildBasePathArray(const CXXBasePath &Path,
3041                                CXXCastPath &BasePathArray) {
3042   // We first go backward and check if we have a virtual base.
3043   // FIXME: It would be better if CXXBasePath had the base specifier for
3044   // the nearest virtual base.
3045   unsigned Start = 0;
3046   for (unsigned I = Path.size(); I != 0; --I) {
3047     if (Path[I - 1].Base->isVirtual()) {
3048       Start = I - 1;
3049       break;
3050     }
3051   }
3052 
3053   // Now add all bases.
3054   for (unsigned I = Start, E = Path.size(); I != E; ++I)
3055     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
3056 }
3057 
3058 
3059 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
3060                               CXXCastPath &BasePathArray) {
3061   assert(BasePathArray.empty() && "Base path array must be empty!");
3062   assert(Paths.isRecordingPaths() && "Must record paths!");
3063   return ::BuildBasePathArray(Paths.front(), BasePathArray);
3064 }
3065 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
3066 /// conversion (where Derived and Base are class types) is
3067 /// well-formed, meaning that the conversion is unambiguous (and
3068 /// that all of the base classes are accessible). Returns true
3069 /// and emits a diagnostic if the code is ill-formed, returns false
3070 /// otherwise. Loc is the location where this routine should point to
3071 /// if there is an error, and Range is the source range to highlight
3072 /// if there is an error.
3073 ///
3074 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
3075 /// diagnostic for the respective type of error will be suppressed, but the
3076 /// check for ill-formed code will still be performed.
3077 bool
3078 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
3079                                    unsigned InaccessibleBaseID,
3080                                    unsigned AmbiguousBaseConvID,
3081                                    SourceLocation Loc, SourceRange Range,
3082                                    DeclarationName Name,
3083                                    CXXCastPath *BasePath,
3084                                    bool IgnoreAccess) {
3085   // First, determine whether the path from Derived to Base is
3086   // ambiguous. This is slightly more expensive than checking whether
3087   // the Derived to Base conversion exists, because here we need to
3088   // explore multiple paths to determine if there is an ambiguity.
3089   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3090                      /*DetectVirtual=*/false);
3091   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3092   if (!DerivationOkay)
3093     return true;
3094 
3095   const CXXBasePath *Path = nullptr;
3096   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
3097     Path = &Paths.front();
3098 
3099   // For MSVC compatibility, check if Derived directly inherits from Base. Clang
3100   // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
3101   // user to access such bases.
3102   if (!Path && getLangOpts().MSVCCompat) {
3103     for (const CXXBasePath &PossiblePath : Paths) {
3104       if (PossiblePath.size() == 1) {
3105         Path = &PossiblePath;
3106         if (AmbiguousBaseConvID)
3107           Diag(Loc, diag::ext_ms_ambiguous_direct_base)
3108               << Base << Derived << Range;
3109         break;
3110       }
3111     }
3112   }
3113 
3114   if (Path) {
3115     if (!IgnoreAccess) {
3116       // Check that the base class can be accessed.
3117       switch (
3118           CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
3119       case AR_inaccessible:
3120         return true;
3121       case AR_accessible:
3122       case AR_dependent:
3123       case AR_delayed:
3124         break;
3125       }
3126     }
3127 
3128     // Build a base path if necessary.
3129     if (BasePath)
3130       ::BuildBasePathArray(*Path, *BasePath);
3131     return false;
3132   }
3133 
3134   if (AmbiguousBaseConvID) {
3135     // We know that the derived-to-base conversion is ambiguous, and
3136     // we're going to produce a diagnostic. Perform the derived-to-base
3137     // search just one more time to compute all of the possible paths so
3138     // that we can print them out. This is more expensive than any of
3139     // the previous derived-to-base checks we've done, but at this point
3140     // performance isn't as much of an issue.
3141     Paths.clear();
3142     Paths.setRecordingPaths(true);
3143     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3144     assert(StillOkay && "Can only be used with a derived-to-base conversion");
3145     (void)StillOkay;
3146 
3147     // Build up a textual representation of the ambiguous paths, e.g.,
3148     // D -> B -> A, that will be used to illustrate the ambiguous
3149     // conversions in the diagnostic. We only print one of the paths
3150     // to each base class subobject.
3151     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3152 
3153     Diag(Loc, AmbiguousBaseConvID)
3154     << Derived << Base << PathDisplayStr << Range << Name;
3155   }
3156   return true;
3157 }
3158 
3159 bool
3160 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
3161                                    SourceLocation Loc, SourceRange Range,
3162                                    CXXCastPath *BasePath,
3163                                    bool IgnoreAccess) {
3164   return CheckDerivedToBaseConversion(
3165       Derived, Base, diag::err_upcast_to_inaccessible_base,
3166       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
3167       BasePath, IgnoreAccess);
3168 }
3169 
3170 
3171 /// Builds a string representing ambiguous paths from a
3172 /// specific derived class to different subobjects of the same base
3173 /// class.
3174 ///
3175 /// This function builds a string that can be used in error messages
3176 /// to show the different paths that one can take through the
3177 /// inheritance hierarchy to go from the derived class to different
3178 /// subobjects of a base class. The result looks something like this:
3179 /// @code
3180 /// struct D -> struct B -> struct A
3181 /// struct D -> struct C -> struct A
3182 /// @endcode
3183 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
3184   std::string PathDisplayStr;
3185   std::set<unsigned> DisplayedPaths;
3186   for (CXXBasePaths::paths_iterator Path = Paths.begin();
3187        Path != Paths.end(); ++Path) {
3188     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
3189       // We haven't displayed a path to this particular base
3190       // class subobject yet.
3191       PathDisplayStr += "\n    ";
3192       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
3193       for (CXXBasePath::const_iterator Element = Path->begin();
3194            Element != Path->end(); ++Element)
3195         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
3196     }
3197   }
3198 
3199   return PathDisplayStr;
3200 }
3201 
3202 //===----------------------------------------------------------------------===//
3203 // C++ class member Handling
3204 //===----------------------------------------------------------------------===//
3205 
3206 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
3207 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
3208                                 SourceLocation ColonLoc,
3209                                 const ParsedAttributesView &Attrs) {
3210   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
3211   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
3212                                                   ASLoc, ColonLoc);
3213   CurContext->addHiddenDecl(ASDecl);
3214   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
3215 }
3216 
3217 /// CheckOverrideControl - Check C++11 override control semantics.
3218 void Sema::CheckOverrideControl(NamedDecl *D) {
3219   if (D->isInvalidDecl())
3220     return;
3221 
3222   // We only care about "override" and "final" declarations.
3223   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3224     return;
3225 
3226   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3227 
3228   // We can't check dependent instance methods.
3229   if (MD && MD->isInstance() &&
3230       (MD->getParent()->hasAnyDependentBases() ||
3231        MD->getType()->isDependentType()))
3232     return;
3233 
3234   if (MD && !MD->isVirtual()) {
3235     // If we have a non-virtual method, check if it hides a virtual method.
3236     // (In that case, it's most likely the method has the wrong type.)
3237     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3238     FindHiddenVirtualMethods(MD, OverloadedMethods);
3239 
3240     if (!OverloadedMethods.empty()) {
3241       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3242         Diag(OA->getLocation(),
3243              diag::override_keyword_hides_virtual_member_function)
3244           << "override" << (OverloadedMethods.size() > 1);
3245       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3246         Diag(FA->getLocation(),
3247              diag::override_keyword_hides_virtual_member_function)
3248           << (FA->isSpelledAsSealed() ? "sealed" : "final")
3249           << (OverloadedMethods.size() > 1);
3250       }
3251       NoteHiddenVirtualMethods(MD, OverloadedMethods);
3252       MD->setInvalidDecl();
3253       return;
3254     }
3255     // Fall through into the general case diagnostic.
3256     // FIXME: We might want to attempt typo correction here.
3257   }
3258 
3259   if (!MD || !MD->isVirtual()) {
3260     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3261       Diag(OA->getLocation(),
3262            diag::override_keyword_only_allowed_on_virtual_member_functions)
3263         << "override" << FixItHint::CreateRemoval(OA->getLocation());
3264       D->dropAttr<OverrideAttr>();
3265     }
3266     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3267       Diag(FA->getLocation(),
3268            diag::override_keyword_only_allowed_on_virtual_member_functions)
3269         << (FA->isSpelledAsSealed() ? "sealed" : "final")
3270         << FixItHint::CreateRemoval(FA->getLocation());
3271       D->dropAttr<FinalAttr>();
3272     }
3273     return;
3274   }
3275 
3276   // C++11 [class.virtual]p5:
3277   //   If a function is marked with the virt-specifier override and
3278   //   does not override a member function of a base class, the program is
3279   //   ill-formed.
3280   bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3281   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3282     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3283       << MD->getDeclName();
3284 }
3285 
3286 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) {
3287   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3288     return;
3289   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3290   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3291     return;
3292 
3293   SourceLocation Loc = MD->getLocation();
3294   SourceLocation SpellingLoc = Loc;
3295   if (getSourceManager().isMacroArgExpansion(Loc))
3296     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3297   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3298   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3299       return;
3300 
3301   if (MD->size_overridden_methods() > 0) {
3302     auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3303       unsigned DiagID =
3304           Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3305               ? DiagInconsistent
3306               : DiagSuggest;
3307       Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3308       const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3309       Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3310     };
3311     if (isa<CXXDestructorDecl>(MD))
3312       EmitDiag(
3313           diag::warn_inconsistent_destructor_marked_not_override_overriding,
3314           diag::warn_suggest_destructor_marked_not_override_overriding);
3315     else
3316       EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3317                diag::warn_suggest_function_marked_not_override_overriding);
3318   }
3319 }
3320 
3321 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
3322 /// function overrides a virtual member function marked 'final', according to
3323 /// C++11 [class.virtual]p4.
3324 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3325                                                   const CXXMethodDecl *Old) {
3326   FinalAttr *FA = Old->getAttr<FinalAttr>();
3327   if (!FA)
3328     return false;
3329 
3330   Diag(New->getLocation(), diag::err_final_function_overridden)
3331     << New->getDeclName()
3332     << FA->isSpelledAsSealed();
3333   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3334   return true;
3335 }
3336 
3337 static bool InitializationHasSideEffects(const FieldDecl &FD) {
3338   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3339   // FIXME: Destruction of ObjC lifetime types has side-effects.
3340   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3341     return !RD->isCompleteDefinition() ||
3342            !RD->hasTrivialDefaultConstructor() ||
3343            !RD->hasTrivialDestructor();
3344   return false;
3345 }
3346 
3347 // Check if there is a field shadowing.
3348 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3349                                       DeclarationName FieldName,
3350                                       const CXXRecordDecl *RD,
3351                                       bool DeclIsField) {
3352   if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3353     return;
3354 
3355   // To record a shadowed field in a base
3356   std::map<CXXRecordDecl*, NamedDecl*> Bases;
3357   auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3358                            CXXBasePath &Path) {
3359     const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3360     // Record an ambiguous path directly
3361     if (Bases.find(Base) != Bases.end())
3362       return true;
3363     for (const auto Field : Base->lookup(FieldName)) {
3364       if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3365           Field->getAccess() != AS_private) {
3366         assert(Field->getAccess() != AS_none);
3367         assert(Bases.find(Base) == Bases.end());
3368         Bases[Base] = Field;
3369         return true;
3370       }
3371     }
3372     return false;
3373   };
3374 
3375   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3376                      /*DetectVirtual=*/true);
3377   if (!RD->lookupInBases(FieldShadowed, Paths))
3378     return;
3379 
3380   for (const auto &P : Paths) {
3381     auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3382     auto It = Bases.find(Base);
3383     // Skip duplicated bases
3384     if (It == Bases.end())
3385       continue;
3386     auto BaseField = It->second;
3387     assert(BaseField->getAccess() != AS_private);
3388     if (AS_none !=
3389         CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3390       Diag(Loc, diag::warn_shadow_field)
3391         << FieldName << RD << Base << DeclIsField;
3392       Diag(BaseField->getLocation(), diag::note_shadow_field);
3393       Bases.erase(It);
3394     }
3395   }
3396 }
3397 
3398 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
3399 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
3400 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
3401 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
3402 /// present (but parsing it has been deferred).
3403 NamedDecl *
3404 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3405                                MultiTemplateParamsArg TemplateParameterLists,
3406                                Expr *BW, const VirtSpecifiers &VS,
3407                                InClassInitStyle InitStyle) {
3408   const DeclSpec &DS = D.getDeclSpec();
3409   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3410   DeclarationName Name = NameInfo.getName();
3411   SourceLocation Loc = NameInfo.getLoc();
3412 
3413   // For anonymous bitfields, the location should point to the type.
3414   if (Loc.isInvalid())
3415     Loc = D.getBeginLoc();
3416 
3417   Expr *BitWidth = static_cast<Expr*>(BW);
3418 
3419   assert(isa<CXXRecordDecl>(CurContext));
3420   assert(!DS.isFriendSpecified());
3421 
3422   bool isFunc = D.isDeclarationOfFunction();
3423   const ParsedAttr *MSPropertyAttr =
3424       D.getDeclSpec().getAttributes().getMSPropertyAttr();
3425 
3426   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3427     // The Microsoft extension __interface only permits public member functions
3428     // and prohibits constructors, destructors, operators, non-public member
3429     // functions, static methods and data members.
3430     unsigned InvalidDecl;
3431     bool ShowDeclName = true;
3432     if (!isFunc &&
3433         (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3434       InvalidDecl = 0;
3435     else if (!isFunc)
3436       InvalidDecl = 1;
3437     else if (AS != AS_public)
3438       InvalidDecl = 2;
3439     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3440       InvalidDecl = 3;
3441     else switch (Name.getNameKind()) {
3442       case DeclarationName::CXXConstructorName:
3443         InvalidDecl = 4;
3444         ShowDeclName = false;
3445         break;
3446 
3447       case DeclarationName::CXXDestructorName:
3448         InvalidDecl = 5;
3449         ShowDeclName = false;
3450         break;
3451 
3452       case DeclarationName::CXXOperatorName:
3453       case DeclarationName::CXXConversionFunctionName:
3454         InvalidDecl = 6;
3455         break;
3456 
3457       default:
3458         InvalidDecl = 0;
3459         break;
3460     }
3461 
3462     if (InvalidDecl) {
3463       if (ShowDeclName)
3464         Diag(Loc, diag::err_invalid_member_in_interface)
3465           << (InvalidDecl-1) << Name;
3466       else
3467         Diag(Loc, diag::err_invalid_member_in_interface)
3468           << (InvalidDecl-1) << "";
3469       return nullptr;
3470     }
3471   }
3472 
3473   // C++ 9.2p6: A member shall not be declared to have automatic storage
3474   // duration (auto, register) or with the extern storage-class-specifier.
3475   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3476   // data members and cannot be applied to names declared const or static,
3477   // and cannot be applied to reference members.
3478   switch (DS.getStorageClassSpec()) {
3479   case DeclSpec::SCS_unspecified:
3480   case DeclSpec::SCS_typedef:
3481   case DeclSpec::SCS_static:
3482     break;
3483   case DeclSpec::SCS_mutable:
3484     if (isFunc) {
3485       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3486 
3487       // FIXME: It would be nicer if the keyword was ignored only for this
3488       // declarator. Otherwise we could get follow-up errors.
3489       D.getMutableDeclSpec().ClearStorageClassSpecs();
3490     }
3491     break;
3492   default:
3493     Diag(DS.getStorageClassSpecLoc(),
3494          diag::err_storageclass_invalid_for_member);
3495     D.getMutableDeclSpec().ClearStorageClassSpecs();
3496     break;
3497   }
3498 
3499   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3500                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3501                       !isFunc);
3502 
3503   if (DS.hasConstexprSpecifier() && isInstField) {
3504     SemaDiagnosticBuilder B =
3505         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3506     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3507     if (InitStyle == ICIS_NoInit) {
3508       B << 0 << 0;
3509       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3510         B << FixItHint::CreateRemoval(ConstexprLoc);
3511       else {
3512         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3513         D.getMutableDeclSpec().ClearConstexprSpec();
3514         const char *PrevSpec;
3515         unsigned DiagID;
3516         bool Failed = D.getMutableDeclSpec().SetTypeQual(
3517             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3518         (void)Failed;
3519         assert(!Failed && "Making a constexpr member const shouldn't fail");
3520       }
3521     } else {
3522       B << 1;
3523       const char *PrevSpec;
3524       unsigned DiagID;
3525       if (D.getMutableDeclSpec().SetStorageClassSpec(
3526           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3527           Context.getPrintingPolicy())) {
3528         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3529                "This is the only DeclSpec that should fail to be applied");
3530         B << 1;
3531       } else {
3532         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3533         isInstField = false;
3534       }
3535     }
3536   }
3537 
3538   NamedDecl *Member;
3539   if (isInstField) {
3540     CXXScopeSpec &SS = D.getCXXScopeSpec();
3541 
3542     // Data members must have identifiers for names.
3543     if (!Name.isIdentifier()) {
3544       Diag(Loc, diag::err_bad_variable_name)
3545         << Name;
3546       return nullptr;
3547     }
3548 
3549     IdentifierInfo *II = Name.getAsIdentifierInfo();
3550 
3551     // Member field could not be with "template" keyword.
3552     // So TemplateParameterLists should be empty in this case.
3553     if (TemplateParameterLists.size()) {
3554       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3555       if (TemplateParams->size()) {
3556         // There is no such thing as a member field template.
3557         Diag(D.getIdentifierLoc(), diag::err_template_member)
3558             << II
3559             << SourceRange(TemplateParams->getTemplateLoc(),
3560                 TemplateParams->getRAngleLoc());
3561       } else {
3562         // There is an extraneous 'template<>' for this member.
3563         Diag(TemplateParams->getTemplateLoc(),
3564             diag::err_template_member_noparams)
3565             << II
3566             << SourceRange(TemplateParams->getTemplateLoc(),
3567                 TemplateParams->getRAngleLoc());
3568       }
3569       return nullptr;
3570     }
3571 
3572     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
3573       Diag(D.getIdentifierLoc(), diag::err_member_with_template_arguments)
3574           << II
3575           << SourceRange(D.getName().TemplateId->LAngleLoc,
3576                          D.getName().TemplateId->RAngleLoc)
3577           << D.getName().TemplateId->LAngleLoc;
3578       D.SetIdentifier(II, Loc);
3579     }
3580 
3581     if (SS.isSet() && !SS.isInvalid()) {
3582       // The user provided a superfluous scope specifier inside a class
3583       // definition:
3584       //
3585       // class X {
3586       //   int X::member;
3587       // };
3588       if (DeclContext *DC = computeDeclContext(SS, false))
3589         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3590                                      D.getName().getKind() ==
3591                                          UnqualifiedIdKind::IK_TemplateId);
3592       else
3593         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3594           << Name << SS.getRange();
3595 
3596       SS.clear();
3597     }
3598 
3599     if (MSPropertyAttr) {
3600       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3601                                 BitWidth, InitStyle, AS, *MSPropertyAttr);
3602       if (!Member)
3603         return nullptr;
3604       isInstField = false;
3605     } else {
3606       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3607                                 BitWidth, InitStyle, AS);
3608       if (!Member)
3609         return nullptr;
3610     }
3611 
3612     CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3613   } else {
3614     Member = HandleDeclarator(S, D, TemplateParameterLists);
3615     if (!Member)
3616       return nullptr;
3617 
3618     // Non-instance-fields can't have a bitfield.
3619     if (BitWidth) {
3620       if (Member->isInvalidDecl()) {
3621         // don't emit another diagnostic.
3622       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3623         // C++ 9.6p3: A bit-field shall not be a static member.
3624         // "static member 'A' cannot be a bit-field"
3625         Diag(Loc, diag::err_static_not_bitfield)
3626           << Name << BitWidth->getSourceRange();
3627       } else if (isa<TypedefDecl>(Member)) {
3628         // "typedef member 'x' cannot be a bit-field"
3629         Diag(Loc, diag::err_typedef_not_bitfield)
3630           << Name << BitWidth->getSourceRange();
3631       } else {
3632         // A function typedef ("typedef int f(); f a;").
3633         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3634         Diag(Loc, diag::err_not_integral_type_bitfield)
3635           << Name << cast<ValueDecl>(Member)->getType()
3636           << BitWidth->getSourceRange();
3637       }
3638 
3639       BitWidth = nullptr;
3640       Member->setInvalidDecl();
3641     }
3642 
3643     NamedDecl *NonTemplateMember = Member;
3644     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3645       NonTemplateMember = FunTmpl->getTemplatedDecl();
3646     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3647       NonTemplateMember = VarTmpl->getTemplatedDecl();
3648 
3649     Member->setAccess(AS);
3650 
3651     // If we have declared a member function template or static data member
3652     // template, set the access of the templated declaration as well.
3653     if (NonTemplateMember != Member)
3654       NonTemplateMember->setAccess(AS);
3655 
3656     // C++ [temp.deduct.guide]p3:
3657     //   A deduction guide [...] for a member class template [shall be
3658     //   declared] with the same access [as the template].
3659     if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3660       auto *TD = DG->getDeducedTemplate();
3661       // Access specifiers are only meaningful if both the template and the
3662       // deduction guide are from the same scope.
3663       if (AS != TD->getAccess() &&
3664           TD->getDeclContext()->getRedeclContext()->Equals(
3665               DG->getDeclContext()->getRedeclContext())) {
3666         Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3667         Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3668             << TD->getAccess();
3669         const AccessSpecDecl *LastAccessSpec = nullptr;
3670         for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3671           if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3672             LastAccessSpec = AccessSpec;
3673         }
3674         assert(LastAccessSpec && "differing access with no access specifier");
3675         Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3676             << AS;
3677       }
3678     }
3679   }
3680 
3681   if (VS.isOverrideSpecified())
3682     Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc()));
3683   if (VS.isFinalSpecified())
3684     Member->addAttr(FinalAttr::Create(Context, VS.getFinalLoc(),
3685                                       VS.isFinalSpelledSealed()
3686                                           ? FinalAttr::Keyword_sealed
3687                                           : FinalAttr::Keyword_final));
3688 
3689   if (VS.getLastLocation().isValid()) {
3690     // Update the end location of a method that has a virt-specifiers.
3691     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3692       MD->setRangeEnd(VS.getLastLocation());
3693   }
3694 
3695   CheckOverrideControl(Member);
3696 
3697   assert((Name || isInstField) && "No identifier for non-field ?");
3698 
3699   if (isInstField) {
3700     FieldDecl *FD = cast<FieldDecl>(Member);
3701     FieldCollector->Add(FD);
3702 
3703     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3704       // Remember all explicit private FieldDecls that have a name, no side
3705       // effects and are not part of a dependent type declaration.
3706       if (!FD->isImplicit() && FD->getDeclName() &&
3707           FD->getAccess() == AS_private &&
3708           !FD->hasAttr<UnusedAttr>() &&
3709           !FD->getParent()->isDependentContext() &&
3710           !InitializationHasSideEffects(*FD))
3711         UnusedPrivateFields.insert(FD);
3712     }
3713   }
3714 
3715   return Member;
3716 }
3717 
3718 namespace {
3719   class UninitializedFieldVisitor
3720       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3721     Sema &S;
3722     // List of Decls to generate a warning on.  Also remove Decls that become
3723     // initialized.
3724     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3725     // List of base classes of the record.  Classes are removed after their
3726     // initializers.
3727     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3728     // Vector of decls to be removed from the Decl set prior to visiting the
3729     // nodes.  These Decls may have been initialized in the prior initializer.
3730     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3731     // If non-null, add a note to the warning pointing back to the constructor.
3732     const CXXConstructorDecl *Constructor;
3733     // Variables to hold state when processing an initializer list.  When
3734     // InitList is true, special case initialization of FieldDecls matching
3735     // InitListFieldDecl.
3736     bool InitList;
3737     FieldDecl *InitListFieldDecl;
3738     llvm::SmallVector<unsigned, 4> InitFieldIndex;
3739 
3740   public:
3741     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3742     UninitializedFieldVisitor(Sema &S,
3743                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3744                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3745       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3746         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3747 
3748     // Returns true if the use of ME is not an uninitialized use.
3749     bool IsInitListMemberExprInitialized(MemberExpr *ME,
3750                                          bool CheckReferenceOnly) {
3751       llvm::SmallVector<FieldDecl*, 4> Fields;
3752       bool ReferenceField = false;
3753       while (ME) {
3754         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3755         if (!FD)
3756           return false;
3757         Fields.push_back(FD);
3758         if (FD->getType()->isReferenceType())
3759           ReferenceField = true;
3760         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3761       }
3762 
3763       // Binding a reference to an uninitialized field is not an
3764       // uninitialized use.
3765       if (CheckReferenceOnly && !ReferenceField)
3766         return true;
3767 
3768       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3769       // Discard the first field since it is the field decl that is being
3770       // initialized.
3771       for (const FieldDecl *FD : llvm::drop_begin(llvm::reverse(Fields)))
3772         UsedFieldIndex.push_back(FD->getFieldIndex());
3773 
3774       for (auto UsedIter = UsedFieldIndex.begin(),
3775                 UsedEnd = UsedFieldIndex.end(),
3776                 OrigIter = InitFieldIndex.begin(),
3777                 OrigEnd = InitFieldIndex.end();
3778            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3779         if (*UsedIter < *OrigIter)
3780           return true;
3781         if (*UsedIter > *OrigIter)
3782           break;
3783       }
3784 
3785       return false;
3786     }
3787 
3788     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3789                           bool AddressOf) {
3790       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3791         return;
3792 
3793       // FieldME is the inner-most MemberExpr that is not an anonymous struct
3794       // or union.
3795       MemberExpr *FieldME = ME;
3796 
3797       bool AllPODFields = FieldME->getType().isPODType(S.Context);
3798 
3799       Expr *Base = ME;
3800       while (MemberExpr *SubME =
3801                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3802 
3803         if (isa<VarDecl>(SubME->getMemberDecl()))
3804           return;
3805 
3806         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3807           if (!FD->isAnonymousStructOrUnion())
3808             FieldME = SubME;
3809 
3810         if (!FieldME->getType().isPODType(S.Context))
3811           AllPODFields = false;
3812 
3813         Base = SubME->getBase();
3814       }
3815 
3816       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3817         Visit(Base);
3818         return;
3819       }
3820 
3821       if (AddressOf && AllPODFields)
3822         return;
3823 
3824       ValueDecl* FoundVD = FieldME->getMemberDecl();
3825 
3826       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3827         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3828           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3829         }
3830 
3831         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3832           QualType T = BaseCast->getType();
3833           if (T->isPointerType() &&
3834               BaseClasses.count(T->getPointeeType())) {
3835             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3836                 << T->getPointeeType() << FoundVD;
3837           }
3838         }
3839       }
3840 
3841       if (!Decls.count(FoundVD))
3842         return;
3843 
3844       const bool IsReference = FoundVD->getType()->isReferenceType();
3845 
3846       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3847         // Special checking for initializer lists.
3848         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3849           return;
3850         }
3851       } else {
3852         // Prevent double warnings on use of unbounded references.
3853         if (CheckReferenceOnly && !IsReference)
3854           return;
3855       }
3856 
3857       unsigned diag = IsReference
3858           ? diag::warn_reference_field_is_uninit
3859           : diag::warn_field_is_uninit;
3860       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3861       if (Constructor)
3862         S.Diag(Constructor->getLocation(),
3863                diag::note_uninit_in_this_constructor)
3864           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3865 
3866     }
3867 
3868     void HandleValue(Expr *E, bool AddressOf) {
3869       E = E->IgnoreParens();
3870 
3871       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3872         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3873                          AddressOf /*AddressOf*/);
3874         return;
3875       }
3876 
3877       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3878         Visit(CO->getCond());
3879         HandleValue(CO->getTrueExpr(), AddressOf);
3880         HandleValue(CO->getFalseExpr(), AddressOf);
3881         return;
3882       }
3883 
3884       if (BinaryConditionalOperator *BCO =
3885               dyn_cast<BinaryConditionalOperator>(E)) {
3886         Visit(BCO->getCond());
3887         HandleValue(BCO->getFalseExpr(), AddressOf);
3888         return;
3889       }
3890 
3891       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3892         HandleValue(OVE->getSourceExpr(), AddressOf);
3893         return;
3894       }
3895 
3896       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3897         switch (BO->getOpcode()) {
3898         default:
3899           break;
3900         case(BO_PtrMemD):
3901         case(BO_PtrMemI):
3902           HandleValue(BO->getLHS(), AddressOf);
3903           Visit(BO->getRHS());
3904           return;
3905         case(BO_Comma):
3906           Visit(BO->getLHS());
3907           HandleValue(BO->getRHS(), AddressOf);
3908           return;
3909         }
3910       }
3911 
3912       Visit(E);
3913     }
3914 
3915     void CheckInitListExpr(InitListExpr *ILE) {
3916       InitFieldIndex.push_back(0);
3917       for (auto *Child : ILE->children()) {
3918         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3919           CheckInitListExpr(SubList);
3920         } else {
3921           Visit(Child);
3922         }
3923         ++InitFieldIndex.back();
3924       }
3925       InitFieldIndex.pop_back();
3926     }
3927 
3928     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3929                           FieldDecl *Field, const Type *BaseClass) {
3930       // Remove Decls that may have been initialized in the previous
3931       // initializer.
3932       for (ValueDecl* VD : DeclsToRemove)
3933         Decls.erase(VD);
3934       DeclsToRemove.clear();
3935 
3936       Constructor = FieldConstructor;
3937       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3938 
3939       if (ILE && Field) {
3940         InitList = true;
3941         InitListFieldDecl = Field;
3942         InitFieldIndex.clear();
3943         CheckInitListExpr(ILE);
3944       } else {
3945         InitList = false;
3946         Visit(E);
3947       }
3948 
3949       if (Field)
3950         Decls.erase(Field);
3951       if (BaseClass)
3952         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3953     }
3954 
3955     void VisitMemberExpr(MemberExpr *ME) {
3956       // All uses of unbounded reference fields will warn.
3957       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3958     }
3959 
3960     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3961       if (E->getCastKind() == CK_LValueToRValue) {
3962         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3963         return;
3964       }
3965 
3966       Inherited::VisitImplicitCastExpr(E);
3967     }
3968 
3969     void VisitCXXConstructExpr(CXXConstructExpr *E) {
3970       if (E->getConstructor()->isCopyConstructor()) {
3971         Expr *ArgExpr = E->getArg(0);
3972         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3973           if (ILE->getNumInits() == 1)
3974             ArgExpr = ILE->getInit(0);
3975         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3976           if (ICE->getCastKind() == CK_NoOp)
3977             ArgExpr = ICE->getSubExpr();
3978         HandleValue(ArgExpr, false /*AddressOf*/);
3979         return;
3980       }
3981       Inherited::VisitCXXConstructExpr(E);
3982     }
3983 
3984     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3985       Expr *Callee = E->getCallee();
3986       if (isa<MemberExpr>(Callee)) {
3987         HandleValue(Callee, false /*AddressOf*/);
3988         for (auto *Arg : E->arguments())
3989           Visit(Arg);
3990         return;
3991       }
3992 
3993       Inherited::VisitCXXMemberCallExpr(E);
3994     }
3995 
3996     void VisitCallExpr(CallExpr *E) {
3997       // Treat std::move as a use.
3998       if (E->isCallToStdMove()) {
3999         HandleValue(E->getArg(0), /*AddressOf=*/false);
4000         return;
4001       }
4002 
4003       Inherited::VisitCallExpr(E);
4004     }
4005 
4006     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
4007       Expr *Callee = E->getCallee();
4008 
4009       if (isa<UnresolvedLookupExpr>(Callee))
4010         return Inherited::VisitCXXOperatorCallExpr(E);
4011 
4012       Visit(Callee);
4013       for (auto *Arg : E->arguments())
4014         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
4015     }
4016 
4017     void VisitBinaryOperator(BinaryOperator *E) {
4018       // If a field assignment is detected, remove the field from the
4019       // uninitiailized field set.
4020       if (E->getOpcode() == BO_Assign)
4021         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
4022           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
4023             if (!FD->getType()->isReferenceType())
4024               DeclsToRemove.push_back(FD);
4025 
4026       if (E->isCompoundAssignmentOp()) {
4027         HandleValue(E->getLHS(), false /*AddressOf*/);
4028         Visit(E->getRHS());
4029         return;
4030       }
4031 
4032       Inherited::VisitBinaryOperator(E);
4033     }
4034 
4035     void VisitUnaryOperator(UnaryOperator *E) {
4036       if (E->isIncrementDecrementOp()) {
4037         HandleValue(E->getSubExpr(), false /*AddressOf*/);
4038         return;
4039       }
4040       if (E->getOpcode() == UO_AddrOf) {
4041         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
4042           HandleValue(ME->getBase(), true /*AddressOf*/);
4043           return;
4044         }
4045       }
4046 
4047       Inherited::VisitUnaryOperator(E);
4048     }
4049   };
4050 
4051   // Diagnose value-uses of fields to initialize themselves, e.g.
4052   //   foo(foo)
4053   // where foo is not also a parameter to the constructor.
4054   // Also diagnose across field uninitialized use such as
4055   //   x(y), y(x)
4056   // TODO: implement -Wuninitialized and fold this into that framework.
4057   static void DiagnoseUninitializedFields(
4058       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
4059 
4060     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
4061                                            Constructor->getLocation())) {
4062       return;
4063     }
4064 
4065     if (Constructor->isInvalidDecl())
4066       return;
4067 
4068     const CXXRecordDecl *RD = Constructor->getParent();
4069 
4070     if (RD->isDependentContext())
4071       return;
4072 
4073     // Holds fields that are uninitialized.
4074     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
4075 
4076     // At the beginning, all fields are uninitialized.
4077     for (auto *I : RD->decls()) {
4078       if (auto *FD = dyn_cast<FieldDecl>(I)) {
4079         UninitializedFields.insert(FD);
4080       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
4081         UninitializedFields.insert(IFD->getAnonField());
4082       }
4083     }
4084 
4085     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
4086     for (const auto &I : RD->bases())
4087       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
4088 
4089     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4090       return;
4091 
4092     UninitializedFieldVisitor UninitializedChecker(SemaRef,
4093                                                    UninitializedFields,
4094                                                    UninitializedBaseClasses);
4095 
4096     for (const auto *FieldInit : Constructor->inits()) {
4097       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4098         break;
4099 
4100       Expr *InitExpr = FieldInit->getInit();
4101       if (!InitExpr)
4102         continue;
4103 
4104       if (CXXDefaultInitExpr *Default =
4105               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
4106         InitExpr = Default->getExpr();
4107         if (!InitExpr)
4108           continue;
4109         // In class initializers will point to the constructor.
4110         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
4111                                               FieldInit->getAnyMember(),
4112                                               FieldInit->getBaseClass());
4113       } else {
4114         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
4115                                               FieldInit->getAnyMember(),
4116                                               FieldInit->getBaseClass());
4117       }
4118     }
4119   }
4120 } // namespace
4121 
4122 /// Enter a new C++ default initializer scope. After calling this, the
4123 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
4124 /// parsing or instantiating the initializer failed.
4125 void Sema::ActOnStartCXXInClassMemberInitializer() {
4126   // Create a synthetic function scope to represent the call to the constructor
4127   // that notionally surrounds a use of this initializer.
4128   PushFunctionScope();
4129 }
4130 
4131 void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) {
4132   if (!D.isFunctionDeclarator())
4133     return;
4134   auto &FTI = D.getFunctionTypeInfo();
4135   if (!FTI.Params)
4136     return;
4137   for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
4138                                                           FTI.NumParams)) {
4139     auto *ParamDecl = cast<NamedDecl>(Param.Param);
4140     if (ParamDecl->getDeclName())
4141       PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
4142   }
4143 }
4144 
4145 ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {
4146   return ActOnRequiresClause(ConstraintExpr);
4147 }
4148 
4149 ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) {
4150   if (ConstraintExpr.isInvalid())
4151     return ExprError();
4152 
4153   ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr);
4154   if (ConstraintExpr.isInvalid())
4155     return ExprError();
4156 
4157   if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),
4158                                       UPPC_RequiresClause))
4159     return ExprError();
4160 
4161   return ConstraintExpr;
4162 }
4163 
4164 ExprResult Sema::ConvertMemberDefaultInitExpression(FieldDecl *FD,
4165                                                     Expr *InitExpr,
4166                                                     SourceLocation InitLoc) {
4167   InitializedEntity Entity =
4168       InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
4169   InitializationKind Kind =
4170       FD->getInClassInitStyle() == ICIS_ListInit
4171           ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
4172                                                  InitExpr->getBeginLoc(),
4173                                                  InitExpr->getEndLoc())
4174           : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
4175   InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4176   return Seq.Perform(*this, Entity, Kind, InitExpr);
4177 }
4178 
4179 /// This is invoked after parsing an in-class initializer for a
4180 /// non-static C++ class member, and after instantiating an in-class initializer
4181 /// in a class template. Such actions are deferred until the class is complete.
4182 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
4183                                                   SourceLocation InitLoc,
4184                                                   Expr *InitExpr) {
4185   // Pop the notional constructor scope we created earlier.
4186   PopFunctionScopeInfo(nullptr, D);
4187 
4188   FieldDecl *FD = dyn_cast<FieldDecl>(D);
4189   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
4190          "must set init style when field is created");
4191 
4192   if (!InitExpr) {
4193     D->setInvalidDecl();
4194     if (FD)
4195       FD->removeInClassInitializer();
4196     return;
4197   }
4198 
4199   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
4200     FD->setInvalidDecl();
4201     FD->removeInClassInitializer();
4202     return;
4203   }
4204 
4205   ExprResult Init = CorrectDelayedTyposInExpr(InitExpr, /*InitDecl=*/nullptr,
4206                                               /*RecoverUncorrectedTypos=*/true);
4207   assert(Init.isUsable() && "Init should at least have a RecoveryExpr");
4208   if (!FD->getType()->isDependentType() && !Init.get()->isTypeDependent()) {
4209     Init = ConvertMemberDefaultInitExpression(FD, Init.get(), InitLoc);
4210     // C++11 [class.base.init]p7:
4211     //   The initialization of each base and member constitutes a
4212     //   full-expression.
4213     if (!Init.isInvalid())
4214       Init = ActOnFinishFullExpr(Init.get(), /*DiscarededValue=*/false);
4215     if (Init.isInvalid()) {
4216       FD->setInvalidDecl();
4217       return;
4218     }
4219   }
4220 
4221   FD->setInClassInitializer(Init.get());
4222 }
4223 
4224 /// Find the direct and/or virtual base specifiers that
4225 /// correspond to the given base type, for use in base initialization
4226 /// within a constructor.
4227 static bool FindBaseInitializer(Sema &SemaRef,
4228                                 CXXRecordDecl *ClassDecl,
4229                                 QualType BaseType,
4230                                 const CXXBaseSpecifier *&DirectBaseSpec,
4231                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
4232   // First, check for a direct base class.
4233   DirectBaseSpec = nullptr;
4234   for (const auto &Base : ClassDecl->bases()) {
4235     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
4236       // We found a direct base of this type. That's what we're
4237       // initializing.
4238       DirectBaseSpec = &Base;
4239       break;
4240     }
4241   }
4242 
4243   // Check for a virtual base class.
4244   // FIXME: We might be able to short-circuit this if we know in advance that
4245   // there are no virtual bases.
4246   VirtualBaseSpec = nullptr;
4247   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4248     // We haven't found a base yet; search the class hierarchy for a
4249     // virtual base class.
4250     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4251                        /*DetectVirtual=*/false);
4252     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4253                               SemaRef.Context.getTypeDeclType(ClassDecl),
4254                               BaseType, Paths)) {
4255       for (CXXBasePaths::paths_iterator Path = Paths.begin();
4256            Path != Paths.end(); ++Path) {
4257         if (Path->back().Base->isVirtual()) {
4258           VirtualBaseSpec = Path->back().Base;
4259           break;
4260         }
4261       }
4262     }
4263   }
4264 
4265   return DirectBaseSpec || VirtualBaseSpec;
4266 }
4267 
4268 /// Handle a C++ member initializer using braced-init-list syntax.
4269 MemInitResult
4270 Sema::ActOnMemInitializer(Decl *ConstructorD,
4271                           Scope *S,
4272                           CXXScopeSpec &SS,
4273                           IdentifierInfo *MemberOrBase,
4274                           ParsedType TemplateTypeTy,
4275                           const DeclSpec &DS,
4276                           SourceLocation IdLoc,
4277                           Expr *InitList,
4278                           SourceLocation EllipsisLoc) {
4279   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4280                              DS, IdLoc, InitList,
4281                              EllipsisLoc);
4282 }
4283 
4284 /// Handle a C++ member initializer using parentheses syntax.
4285 MemInitResult
4286 Sema::ActOnMemInitializer(Decl *ConstructorD,
4287                           Scope *S,
4288                           CXXScopeSpec &SS,
4289                           IdentifierInfo *MemberOrBase,
4290                           ParsedType TemplateTypeTy,
4291                           const DeclSpec &DS,
4292                           SourceLocation IdLoc,
4293                           SourceLocation LParenLoc,
4294                           ArrayRef<Expr *> Args,
4295                           SourceLocation RParenLoc,
4296                           SourceLocation EllipsisLoc) {
4297   Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4298   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4299                              DS, IdLoc, List, EllipsisLoc);
4300 }
4301 
4302 namespace {
4303 
4304 // Callback to only accept typo corrections that can be a valid C++ member
4305 // initializer: either a non-static field member or a base class.
4306 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4307 public:
4308   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4309       : ClassDecl(ClassDecl) {}
4310 
4311   bool ValidateCandidate(const TypoCorrection &candidate) override {
4312     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4313       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4314         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4315       return isa<TypeDecl>(ND);
4316     }
4317     return false;
4318   }
4319 
4320   std::unique_ptr<CorrectionCandidateCallback> clone() override {
4321     return std::make_unique<MemInitializerValidatorCCC>(*this);
4322   }
4323 
4324 private:
4325   CXXRecordDecl *ClassDecl;
4326 };
4327 
4328 }
4329 
4330 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4331                                              CXXScopeSpec &SS,
4332                                              ParsedType TemplateTypeTy,
4333                                              IdentifierInfo *MemberOrBase) {
4334   if (SS.getScopeRep() || TemplateTypeTy)
4335     return nullptr;
4336   for (auto *D : ClassDecl->lookup(MemberOrBase))
4337     if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D))
4338       return cast<ValueDecl>(D);
4339   return nullptr;
4340 }
4341 
4342 /// Handle a C++ member initializer.
4343 MemInitResult
4344 Sema::BuildMemInitializer(Decl *ConstructorD,
4345                           Scope *S,
4346                           CXXScopeSpec &SS,
4347                           IdentifierInfo *MemberOrBase,
4348                           ParsedType TemplateTypeTy,
4349                           const DeclSpec &DS,
4350                           SourceLocation IdLoc,
4351                           Expr *Init,
4352                           SourceLocation EllipsisLoc) {
4353   ExprResult Res = CorrectDelayedTyposInExpr(Init, /*InitDecl=*/nullptr,
4354                                              /*RecoverUncorrectedTypos=*/true);
4355   if (!Res.isUsable())
4356     return true;
4357   Init = Res.get();
4358 
4359   if (!ConstructorD)
4360     return true;
4361 
4362   AdjustDeclIfTemplate(ConstructorD);
4363 
4364   CXXConstructorDecl *Constructor
4365     = dyn_cast<CXXConstructorDecl>(ConstructorD);
4366   if (!Constructor) {
4367     // The user wrote a constructor initializer on a function that is
4368     // not a C++ constructor. Ignore the error for now, because we may
4369     // have more member initializers coming; we'll diagnose it just
4370     // once in ActOnMemInitializers.
4371     return true;
4372   }
4373 
4374   CXXRecordDecl *ClassDecl = Constructor->getParent();
4375 
4376   // C++ [class.base.init]p2:
4377   //   Names in a mem-initializer-id are looked up in the scope of the
4378   //   constructor's class and, if not found in that scope, are looked
4379   //   up in the scope containing the constructor's definition.
4380   //   [Note: if the constructor's class contains a member with the
4381   //   same name as a direct or virtual base class of the class, a
4382   //   mem-initializer-id naming the member or base class and composed
4383   //   of a single identifier refers to the class member. A
4384   //   mem-initializer-id for the hidden base class may be specified
4385   //   using a qualified name. ]
4386 
4387   // Look for a member, first.
4388   if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4389           ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4390     if (EllipsisLoc.isValid())
4391       Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4392           << MemberOrBase
4393           << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4394 
4395     return BuildMemberInitializer(Member, Init, IdLoc);
4396   }
4397   // It didn't name a member, so see if it names a class.
4398   QualType BaseType;
4399   TypeSourceInfo *TInfo = nullptr;
4400 
4401   if (TemplateTypeTy) {
4402     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4403     if (BaseType.isNull())
4404       return true;
4405   } else if (DS.getTypeSpecType() == TST_decltype) {
4406     BaseType = BuildDecltypeType(DS.getRepAsExpr());
4407   } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4408     Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4409     return true;
4410   } else {
4411     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4412     LookupParsedName(R, S, &SS);
4413 
4414     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4415     if (!TyD) {
4416       if (R.isAmbiguous()) return true;
4417 
4418       // We don't want access-control diagnostics here.
4419       R.suppressDiagnostics();
4420 
4421       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4422         bool NotUnknownSpecialization = false;
4423         DeclContext *DC = computeDeclContext(SS, false);
4424         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4425           NotUnknownSpecialization = !Record->hasAnyDependentBases();
4426 
4427         if (!NotUnknownSpecialization) {
4428           // When the scope specifier can refer to a member of an unknown
4429           // specialization, we take it as a type name.
4430           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
4431                                        SS.getWithLocInContext(Context),
4432                                        *MemberOrBase, IdLoc);
4433           if (BaseType.isNull())
4434             return true;
4435 
4436           TInfo = Context.CreateTypeSourceInfo(BaseType);
4437           DependentNameTypeLoc TL =
4438               TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4439           if (!TL.isNull()) {
4440             TL.setNameLoc(IdLoc);
4441             TL.setElaboratedKeywordLoc(SourceLocation());
4442             TL.setQualifierLoc(SS.getWithLocInContext(Context));
4443           }
4444 
4445           R.clear();
4446           R.setLookupName(MemberOrBase);
4447         }
4448       }
4449 
4450       if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) {
4451         if (auto UnqualifiedBase = R.getAsSingle<ClassTemplateDecl>()) {
4452           auto *TempSpec = cast<TemplateSpecializationType>(
4453               UnqualifiedBase->getInjectedClassNameSpecialization());
4454           TemplateName TN = TempSpec->getTemplateName();
4455           for (auto const &Base : ClassDecl->bases()) {
4456             auto BaseTemplate =
4457                 Base.getType()->getAs<TemplateSpecializationType>();
4458             if (BaseTemplate && Context.hasSameTemplateName(
4459                                     BaseTemplate->getTemplateName(), TN)) {
4460               Diag(IdLoc, diag::ext_unqualified_base_class)
4461                   << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4462               BaseType = Base.getType();
4463               break;
4464             }
4465           }
4466         }
4467       }
4468 
4469       // If no results were found, try to correct typos.
4470       TypoCorrection Corr;
4471       MemInitializerValidatorCCC CCC(ClassDecl);
4472       if (R.empty() && BaseType.isNull() &&
4473           (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4474                               CCC, CTK_ErrorRecovery, ClassDecl))) {
4475         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4476           // We have found a non-static data member with a similar
4477           // name to what was typed; complain and initialize that
4478           // member.
4479           diagnoseTypo(Corr,
4480                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
4481                          << MemberOrBase << true);
4482           return BuildMemberInitializer(Member, Init, IdLoc);
4483         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4484           const CXXBaseSpecifier *DirectBaseSpec;
4485           const CXXBaseSpecifier *VirtualBaseSpec;
4486           if (FindBaseInitializer(*this, ClassDecl,
4487                                   Context.getTypeDeclType(Type),
4488                                   DirectBaseSpec, VirtualBaseSpec)) {
4489             // We have found a direct or virtual base class with a
4490             // similar name to what was typed; complain and initialize
4491             // that base class.
4492             diagnoseTypo(Corr,
4493                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
4494                            << MemberOrBase << false,
4495                          PDiag() /*Suppress note, we provide our own.*/);
4496 
4497             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4498                                                               : VirtualBaseSpec;
4499             Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4500                 << BaseSpec->getType() << BaseSpec->getSourceRange();
4501 
4502             TyD = Type;
4503           }
4504         }
4505       }
4506 
4507       if (!TyD && BaseType.isNull()) {
4508         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4509           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4510         return true;
4511       }
4512     }
4513 
4514     if (BaseType.isNull()) {
4515       BaseType = getElaboratedType(ETK_None, SS, Context.getTypeDeclType(TyD));
4516       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4517       TInfo = Context.CreateTypeSourceInfo(BaseType);
4518       ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
4519       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4520       TL.setElaboratedKeywordLoc(SourceLocation());
4521       TL.setQualifierLoc(SS.getWithLocInContext(Context));
4522     }
4523   }
4524 
4525   if (!TInfo)
4526     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4527 
4528   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4529 }
4530 
4531 MemInitResult
4532 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4533                              SourceLocation IdLoc) {
4534   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4535   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4536   assert((DirectMember || IndirectMember) &&
4537          "Member must be a FieldDecl or IndirectFieldDecl");
4538 
4539   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4540     return true;
4541 
4542   if (Member->isInvalidDecl())
4543     return true;
4544 
4545   MultiExprArg Args;
4546   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4547     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4548   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4549     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4550   } else {
4551     // Template instantiation doesn't reconstruct ParenListExprs for us.
4552     Args = Init;
4553   }
4554 
4555   SourceRange InitRange = Init->getSourceRange();
4556 
4557   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4558     // Can't check initialization for a member of dependent type or when
4559     // any of the arguments are type-dependent expressions.
4560     DiscardCleanupsInEvaluationContext();
4561   } else {
4562     bool InitList = false;
4563     if (isa<InitListExpr>(Init)) {
4564       InitList = true;
4565       Args = Init;
4566     }
4567 
4568     // Initialize the member.
4569     InitializedEntity MemberEntity =
4570       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4571                    : InitializedEntity::InitializeMember(IndirectMember,
4572                                                          nullptr);
4573     InitializationKind Kind =
4574         InitList ? InitializationKind::CreateDirectList(
4575                        IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4576                  : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4577                                                     InitRange.getEnd());
4578 
4579     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4580     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4581                                             nullptr);
4582     if (!MemberInit.isInvalid()) {
4583       // C++11 [class.base.init]p7:
4584       //   The initialization of each base and member constitutes a
4585       //   full-expression.
4586       MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4587                                        /*DiscardedValue*/ false);
4588     }
4589 
4590     if (MemberInit.isInvalid()) {
4591       // Args were sensible expressions but we couldn't initialize the member
4592       // from them. Preserve them in a RecoveryExpr instead.
4593       Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4594                                 Member->getType())
4595                  .get();
4596       if (!Init)
4597         return true;
4598     } else {
4599       Init = MemberInit.get();
4600     }
4601   }
4602 
4603   if (DirectMember) {
4604     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4605                                             InitRange.getBegin(), Init,
4606                                             InitRange.getEnd());
4607   } else {
4608     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4609                                             InitRange.getBegin(), Init,
4610                                             InitRange.getEnd());
4611   }
4612 }
4613 
4614 MemInitResult
4615 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4616                                  CXXRecordDecl *ClassDecl) {
4617   SourceLocation NameLoc = TInfo->getTypeLoc().getSourceRange().getBegin();
4618   if (!LangOpts.CPlusPlus11)
4619     return Diag(NameLoc, diag::err_delegating_ctor)
4620            << TInfo->getTypeLoc().getSourceRange();
4621   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4622 
4623   bool InitList = true;
4624   MultiExprArg Args = Init;
4625   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4626     InitList = false;
4627     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4628   }
4629 
4630   SourceRange InitRange = Init->getSourceRange();
4631   // Initialize the object.
4632   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4633                                      QualType(ClassDecl->getTypeForDecl(), 0));
4634   InitializationKind Kind =
4635       InitList ? InitializationKind::CreateDirectList(
4636                      NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4637                : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4638                                                   InitRange.getEnd());
4639   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4640   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4641                                               Args, nullptr);
4642   if (!DelegationInit.isInvalid()) {
4643     assert((DelegationInit.get()->containsErrors() ||
4644             cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&
4645            "Delegating constructor with no target?");
4646 
4647     // C++11 [class.base.init]p7:
4648     //   The initialization of each base and member constitutes a
4649     //   full-expression.
4650     DelegationInit = ActOnFinishFullExpr(
4651         DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4652   }
4653 
4654   if (DelegationInit.isInvalid()) {
4655     DelegationInit =
4656         CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4657                            QualType(ClassDecl->getTypeForDecl(), 0));
4658     if (DelegationInit.isInvalid())
4659       return true;
4660   } else {
4661     // If we are in a dependent context, template instantiation will
4662     // perform this type-checking again. Just save the arguments that we
4663     // received in a ParenListExpr.
4664     // FIXME: This isn't quite ideal, since our ASTs don't capture all
4665     // of the information that we have about the base
4666     // initializer. However, deconstructing the ASTs is a dicey process,
4667     // and this approach is far more likely to get the corner cases right.
4668     if (CurContext->isDependentContext())
4669       DelegationInit = Init;
4670   }
4671 
4672   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4673                                           DelegationInit.getAs<Expr>(),
4674                                           InitRange.getEnd());
4675 }
4676 
4677 MemInitResult
4678 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4679                            Expr *Init, CXXRecordDecl *ClassDecl,
4680                            SourceLocation EllipsisLoc) {
4681   SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getBeginLoc();
4682 
4683   if (!BaseType->isDependentType() && !BaseType->isRecordType())
4684     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4685            << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
4686 
4687   // C++ [class.base.init]p2:
4688   //   [...] Unless the mem-initializer-id names a nonstatic data
4689   //   member of the constructor's class or a direct or virtual base
4690   //   of that class, the mem-initializer is ill-formed. A
4691   //   mem-initializer-list can initialize a base class using any
4692   //   name that denotes that base class type.
4693 
4694   // We can store the initializers in "as-written" form and delay analysis until
4695   // instantiation if the constructor is dependent. But not for dependent
4696   // (broken) code in a non-template! SetCtorInitializers does not expect this.
4697   bool Dependent = CurContext->isDependentContext() &&
4698                    (BaseType->isDependentType() || Init->isTypeDependent());
4699 
4700   SourceRange InitRange = Init->getSourceRange();
4701   if (EllipsisLoc.isValid()) {
4702     // This is a pack expansion.
4703     if (!BaseType->containsUnexpandedParameterPack())  {
4704       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4705         << SourceRange(BaseLoc, InitRange.getEnd());
4706 
4707       EllipsisLoc = SourceLocation();
4708     }
4709   } else {
4710     // Check for any unexpanded parameter packs.
4711     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4712       return true;
4713 
4714     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4715       return true;
4716   }
4717 
4718   // Check for direct and virtual base classes.
4719   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4720   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4721   if (!Dependent) {
4722     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4723                                        BaseType))
4724       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4725 
4726     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4727                         VirtualBaseSpec);
4728 
4729     // C++ [base.class.init]p2:
4730     // Unless the mem-initializer-id names a nonstatic data member of the
4731     // constructor's class or a direct or virtual base of that class, the
4732     // mem-initializer is ill-formed.
4733     if (!DirectBaseSpec && !VirtualBaseSpec) {
4734       // If the class has any dependent bases, then it's possible that
4735       // one of those types will resolve to the same type as
4736       // BaseType. Therefore, just treat this as a dependent base
4737       // class initialization.  FIXME: Should we try to check the
4738       // initialization anyway? It seems odd.
4739       if (ClassDecl->hasAnyDependentBases())
4740         Dependent = true;
4741       else
4742         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4743                << BaseType << Context.getTypeDeclType(ClassDecl)
4744                << BaseTInfo->getTypeLoc().getSourceRange();
4745     }
4746   }
4747 
4748   if (Dependent) {
4749     DiscardCleanupsInEvaluationContext();
4750 
4751     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4752                                             /*IsVirtual=*/false,
4753                                             InitRange.getBegin(), Init,
4754                                             InitRange.getEnd(), EllipsisLoc);
4755   }
4756 
4757   // C++ [base.class.init]p2:
4758   //   If a mem-initializer-id is ambiguous because it designates both
4759   //   a direct non-virtual base class and an inherited virtual base
4760   //   class, the mem-initializer is ill-formed.
4761   if (DirectBaseSpec && VirtualBaseSpec)
4762     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4763       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4764 
4765   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4766   if (!BaseSpec)
4767     BaseSpec = VirtualBaseSpec;
4768 
4769   // Initialize the base.
4770   bool InitList = true;
4771   MultiExprArg Args = Init;
4772   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4773     InitList = false;
4774     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4775   }
4776 
4777   InitializedEntity BaseEntity =
4778     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4779   InitializationKind Kind =
4780       InitList ? InitializationKind::CreateDirectList(BaseLoc)
4781                : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4782                                                   InitRange.getEnd());
4783   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4784   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4785   if (!BaseInit.isInvalid()) {
4786     // C++11 [class.base.init]p7:
4787     //   The initialization of each base and member constitutes a
4788     //   full-expression.
4789     BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4790                                    /*DiscardedValue*/ false);
4791   }
4792 
4793   if (BaseInit.isInvalid()) {
4794     BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(),
4795                                   Args, BaseType);
4796     if (BaseInit.isInvalid())
4797       return true;
4798   } else {
4799     // If we are in a dependent context, template instantiation will
4800     // perform this type-checking again. Just save the arguments that we
4801     // received in a ParenListExpr.
4802     // FIXME: This isn't quite ideal, since our ASTs don't capture all
4803     // of the information that we have about the base
4804     // initializer. However, deconstructing the ASTs is a dicey process,
4805     // and this approach is far more likely to get the corner cases right.
4806     if (CurContext->isDependentContext())
4807       BaseInit = Init;
4808   }
4809 
4810   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4811                                           BaseSpec->isVirtual(),
4812                                           InitRange.getBegin(),
4813                                           BaseInit.getAs<Expr>(),
4814                                           InitRange.getEnd(), EllipsisLoc);
4815 }
4816 
4817 // Create a static_cast\<T&&>(expr).
4818 static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
4819   QualType TargetType =
4820       SemaRef.BuildReferenceType(E->getType(), /*SpelledAsLValue*/ false,
4821                                  SourceLocation(), DeclarationName());
4822   SourceLocation ExprLoc = E->getBeginLoc();
4823   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4824       TargetType, ExprLoc);
4825 
4826   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4827                                    SourceRange(ExprLoc, ExprLoc),
4828                                    E->getSourceRange()).get();
4829 }
4830 
4831 /// ImplicitInitializerKind - How an implicit base or member initializer should
4832 /// initialize its base or member.
4833 enum ImplicitInitializerKind {
4834   IIK_Default,
4835   IIK_Copy,
4836   IIK_Move,
4837   IIK_Inherit
4838 };
4839 
4840 static bool
4841 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4842                              ImplicitInitializerKind ImplicitInitKind,
4843                              CXXBaseSpecifier *BaseSpec,
4844                              bool IsInheritedVirtualBase,
4845                              CXXCtorInitializer *&CXXBaseInit) {
4846   InitializedEntity InitEntity
4847     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4848                                         IsInheritedVirtualBase);
4849 
4850   ExprResult BaseInit;
4851 
4852   switch (ImplicitInitKind) {
4853   case IIK_Inherit:
4854   case IIK_Default: {
4855     InitializationKind InitKind
4856       = InitializationKind::CreateDefault(Constructor->getLocation());
4857     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, std::nullopt);
4858     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, std::nullopt);
4859     break;
4860   }
4861 
4862   case IIK_Move:
4863   case IIK_Copy: {
4864     bool Moving = ImplicitInitKind == IIK_Move;
4865     ParmVarDecl *Param = Constructor->getParamDecl(0);
4866     QualType ParamType = Param->getType().getNonReferenceType();
4867 
4868     Expr *CopyCtorArg =
4869       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4870                           SourceLocation(), Param, false,
4871                           Constructor->getLocation(), ParamType,
4872                           VK_LValue, nullptr);
4873 
4874     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4875 
4876     // Cast to the base class to avoid ambiguities.
4877     QualType ArgTy =
4878       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4879                                        ParamType.getQualifiers());
4880 
4881     if (Moving) {
4882       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4883     }
4884 
4885     CXXCastPath BasePath;
4886     BasePath.push_back(BaseSpec);
4887     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4888                                             CK_UncheckedDerivedToBase,
4889                                             Moving ? VK_XValue : VK_LValue,
4890                                             &BasePath).get();
4891 
4892     InitializationKind InitKind
4893       = InitializationKind::CreateDirect(Constructor->getLocation(),
4894                                          SourceLocation(), SourceLocation());
4895     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4896     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4897     break;
4898   }
4899   }
4900 
4901   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4902   if (BaseInit.isInvalid())
4903     return true;
4904 
4905   CXXBaseInit =
4906     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4907                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4908                                                         SourceLocation()),
4909                                              BaseSpec->isVirtual(),
4910                                              SourceLocation(),
4911                                              BaseInit.getAs<Expr>(),
4912                                              SourceLocation(),
4913                                              SourceLocation());
4914 
4915   return false;
4916 }
4917 
4918 static bool RefersToRValueRef(Expr *MemRef) {
4919   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4920   return Referenced->getType()->isRValueReferenceType();
4921 }
4922 
4923 static bool
4924 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4925                                ImplicitInitializerKind ImplicitInitKind,
4926                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4927                                CXXCtorInitializer *&CXXMemberInit) {
4928   if (Field->isInvalidDecl())
4929     return true;
4930 
4931   SourceLocation Loc = Constructor->getLocation();
4932 
4933   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4934     bool Moving = ImplicitInitKind == IIK_Move;
4935     ParmVarDecl *Param = Constructor->getParamDecl(0);
4936     QualType ParamType = Param->getType().getNonReferenceType();
4937 
4938     // Suppress copying zero-width bitfields.
4939     if (Field->isZeroLengthBitField(SemaRef.Context))
4940       return false;
4941 
4942     Expr *MemberExprBase =
4943       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4944                           SourceLocation(), Param, false,
4945                           Loc, ParamType, VK_LValue, nullptr);
4946 
4947     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4948 
4949     if (Moving) {
4950       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4951     }
4952 
4953     // Build a reference to this field within the parameter.
4954     CXXScopeSpec SS;
4955     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4956                               Sema::LookupMemberName);
4957     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4958                                   : cast<ValueDecl>(Field), AS_public);
4959     MemberLookup.resolveKind();
4960     ExprResult CtorArg
4961       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4962                                          ParamType, Loc,
4963                                          /*IsArrow=*/false,
4964                                          SS,
4965                                          /*TemplateKWLoc=*/SourceLocation(),
4966                                          /*FirstQualifierInScope=*/nullptr,
4967                                          MemberLookup,
4968                                          /*TemplateArgs=*/nullptr,
4969                                          /*S*/nullptr);
4970     if (CtorArg.isInvalid())
4971       return true;
4972 
4973     // C++11 [class.copy]p15:
4974     //   - if a member m has rvalue reference type T&&, it is direct-initialized
4975     //     with static_cast<T&&>(x.m);
4976     if (RefersToRValueRef(CtorArg.get())) {
4977       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4978     }
4979 
4980     InitializedEntity Entity =
4981         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4982                                                        /*Implicit*/ true)
4983                  : InitializedEntity::InitializeMember(Field, nullptr,
4984                                                        /*Implicit*/ true);
4985 
4986     // Direct-initialize to use the copy constructor.
4987     InitializationKind InitKind =
4988       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4989 
4990     Expr *CtorArgE = CtorArg.getAs<Expr>();
4991     InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4992     ExprResult MemberInit =
4993         InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4994     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4995     if (MemberInit.isInvalid())
4996       return true;
4997 
4998     if (Indirect)
4999       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5000           SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5001     else
5002       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5003           SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5004     return false;
5005   }
5006 
5007   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
5008          "Unhandled implicit init kind!");
5009 
5010   QualType FieldBaseElementType =
5011     SemaRef.Context.getBaseElementType(Field->getType());
5012 
5013   if (FieldBaseElementType->isRecordType()) {
5014     InitializedEntity InitEntity =
5015         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
5016                                                        /*Implicit*/ true)
5017                  : InitializedEntity::InitializeMember(Field, nullptr,
5018                                                        /*Implicit*/ true);
5019     InitializationKind InitKind =
5020       InitializationKind::CreateDefault(Loc);
5021 
5022     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, std::nullopt);
5023     ExprResult MemberInit =
5024         InitSeq.Perform(SemaRef, InitEntity, InitKind, std::nullopt);
5025 
5026     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
5027     if (MemberInit.isInvalid())
5028       return true;
5029 
5030     if (Indirect)
5031       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5032                                                                Indirect, Loc,
5033                                                                Loc,
5034                                                                MemberInit.get(),
5035                                                                Loc);
5036     else
5037       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5038                                                                Field, Loc, Loc,
5039                                                                MemberInit.get(),
5040                                                                Loc);
5041     return false;
5042   }
5043 
5044   if (!Field->getParent()->isUnion()) {
5045     if (FieldBaseElementType->isReferenceType()) {
5046       SemaRef.Diag(Constructor->getLocation(),
5047                    diag::err_uninitialized_member_in_ctor)
5048       << (int)Constructor->isImplicit()
5049       << SemaRef.Context.getTagDeclType(Constructor->getParent())
5050       << 0 << Field->getDeclName();
5051       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
5052       return true;
5053     }
5054 
5055     if (FieldBaseElementType.isConstQualified()) {
5056       SemaRef.Diag(Constructor->getLocation(),
5057                    diag::err_uninitialized_member_in_ctor)
5058       << (int)Constructor->isImplicit()
5059       << SemaRef.Context.getTagDeclType(Constructor->getParent())
5060       << 1 << Field->getDeclName();
5061       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
5062       return true;
5063     }
5064   }
5065 
5066   if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
5067     // ARC and Weak:
5068     //   Default-initialize Objective-C pointers to NULL.
5069     CXXMemberInit
5070       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
5071                                                  Loc, Loc,
5072                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
5073                                                  Loc);
5074     return false;
5075   }
5076 
5077   // Nothing to initialize.
5078   CXXMemberInit = nullptr;
5079   return false;
5080 }
5081 
5082 namespace {
5083 struct BaseAndFieldInfo {
5084   Sema &S;
5085   CXXConstructorDecl *Ctor;
5086   bool AnyErrorsInInits;
5087   ImplicitInitializerKind IIK;
5088   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
5089   SmallVector<CXXCtorInitializer*, 8> AllToInit;
5090   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
5091 
5092   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
5093     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
5094     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
5095     if (Ctor->getInheritedConstructor())
5096       IIK = IIK_Inherit;
5097     else if (Generated && Ctor->isCopyConstructor())
5098       IIK = IIK_Copy;
5099     else if (Generated && Ctor->isMoveConstructor())
5100       IIK = IIK_Move;
5101     else
5102       IIK = IIK_Default;
5103   }
5104 
5105   bool isImplicitCopyOrMove() const {
5106     switch (IIK) {
5107     case IIK_Copy:
5108     case IIK_Move:
5109       return true;
5110 
5111     case IIK_Default:
5112     case IIK_Inherit:
5113       return false;
5114     }
5115 
5116     llvm_unreachable("Invalid ImplicitInitializerKind!");
5117   }
5118 
5119   bool addFieldInitializer(CXXCtorInitializer *Init) {
5120     AllToInit.push_back(Init);
5121 
5122     // Check whether this initializer makes the field "used".
5123     if (Init->getInit()->HasSideEffects(S.Context))
5124       S.UnusedPrivateFields.remove(Init->getAnyMember());
5125 
5126     return false;
5127   }
5128 
5129   bool isInactiveUnionMember(FieldDecl *Field) {
5130     RecordDecl *Record = Field->getParent();
5131     if (!Record->isUnion())
5132       return false;
5133 
5134     if (FieldDecl *Active =
5135             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
5136       return Active != Field->getCanonicalDecl();
5137 
5138     // In an implicit copy or move constructor, ignore any in-class initializer.
5139     if (isImplicitCopyOrMove())
5140       return true;
5141 
5142     // If there's no explicit initialization, the field is active only if it
5143     // has an in-class initializer...
5144     if (Field->hasInClassInitializer())
5145       return false;
5146     // ... or it's an anonymous struct or union whose class has an in-class
5147     // initializer.
5148     if (!Field->isAnonymousStructOrUnion())
5149       return true;
5150     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
5151     return !FieldRD->hasInClassInitializer();
5152   }
5153 
5154   /// Determine whether the given field is, or is within, a union member
5155   /// that is inactive (because there was an initializer given for a different
5156   /// member of the union, or because the union was not initialized at all).
5157   bool isWithinInactiveUnionMember(FieldDecl *Field,
5158                                    IndirectFieldDecl *Indirect) {
5159     if (!Indirect)
5160       return isInactiveUnionMember(Field);
5161 
5162     for (auto *C : Indirect->chain()) {
5163       FieldDecl *Field = dyn_cast<FieldDecl>(C);
5164       if (Field && isInactiveUnionMember(Field))
5165         return true;
5166     }
5167     return false;
5168   }
5169 };
5170 }
5171 
5172 /// Determine whether the given type is an incomplete or zero-lenfgth
5173 /// array type.
5174 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
5175   if (T->isIncompleteArrayType())
5176     return true;
5177 
5178   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
5179     if (!ArrayT->getSize())
5180       return true;
5181 
5182     T = ArrayT->getElementType();
5183   }
5184 
5185   return false;
5186 }
5187 
5188 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
5189                                     FieldDecl *Field,
5190                                     IndirectFieldDecl *Indirect = nullptr) {
5191   if (Field->isInvalidDecl())
5192     return false;
5193 
5194   // Overwhelmingly common case: we have a direct initializer for this field.
5195   if (CXXCtorInitializer *Init =
5196           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
5197     return Info.addFieldInitializer(Init);
5198 
5199   // C++11 [class.base.init]p8:
5200   //   if the entity is a non-static data member that has a
5201   //   brace-or-equal-initializer and either
5202   //   -- the constructor's class is a union and no other variant member of that
5203   //      union is designated by a mem-initializer-id or
5204   //   -- the constructor's class is not a union, and, if the entity is a member
5205   //      of an anonymous union, no other member of that union is designated by
5206   //      a mem-initializer-id,
5207   //   the entity is initialized as specified in [dcl.init].
5208   //
5209   // We also apply the same rules to handle anonymous structs within anonymous
5210   // unions.
5211   if (Info.isWithinInactiveUnionMember(Field, Indirect))
5212     return false;
5213 
5214   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
5215     ExprResult DIE =
5216         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
5217     if (DIE.isInvalid())
5218       return true;
5219 
5220     auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
5221     SemaRef.checkInitializerLifetime(Entity, DIE.get());
5222 
5223     CXXCtorInitializer *Init;
5224     if (Indirect)
5225       Init = new (SemaRef.Context)
5226           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
5227                              SourceLocation(), DIE.get(), SourceLocation());
5228     else
5229       Init = new (SemaRef.Context)
5230           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
5231                              SourceLocation(), DIE.get(), SourceLocation());
5232     return Info.addFieldInitializer(Init);
5233   }
5234 
5235   // Don't initialize incomplete or zero-length arrays.
5236   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
5237     return false;
5238 
5239   // Don't try to build an implicit initializer if there were semantic
5240   // errors in any of the initializers (and therefore we might be
5241   // missing some that the user actually wrote).
5242   if (Info.AnyErrorsInInits)
5243     return false;
5244 
5245   CXXCtorInitializer *Init = nullptr;
5246   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
5247                                      Indirect, Init))
5248     return true;
5249 
5250   if (!Init)
5251     return false;
5252 
5253   return Info.addFieldInitializer(Init);
5254 }
5255 
5256 bool
5257 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5258                                CXXCtorInitializer *Initializer) {
5259   assert(Initializer->isDelegatingInitializer());
5260   Constructor->setNumCtorInitializers(1);
5261   CXXCtorInitializer **initializer =
5262     new (Context) CXXCtorInitializer*[1];
5263   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
5264   Constructor->setCtorInitializers(initializer);
5265 
5266   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
5267     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5268     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5269   }
5270 
5271   DelegatingCtorDecls.push_back(Constructor);
5272 
5273   DiagnoseUninitializedFields(*this, Constructor);
5274 
5275   return false;
5276 }
5277 
5278 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5279                                ArrayRef<CXXCtorInitializer *> Initializers) {
5280   if (Constructor->isDependentContext()) {
5281     // Just store the initializers as written, they will be checked during
5282     // instantiation.
5283     if (!Initializers.empty()) {
5284       Constructor->setNumCtorInitializers(Initializers.size());
5285       CXXCtorInitializer **baseOrMemberInitializers =
5286         new (Context) CXXCtorInitializer*[Initializers.size()];
5287       memcpy(baseOrMemberInitializers, Initializers.data(),
5288              Initializers.size() * sizeof(CXXCtorInitializer*));
5289       Constructor->setCtorInitializers(baseOrMemberInitializers);
5290     }
5291 
5292     // Let template instantiation know whether we had errors.
5293     if (AnyErrors)
5294       Constructor->setInvalidDecl();
5295 
5296     return false;
5297   }
5298 
5299   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5300 
5301   // We need to build the initializer AST according to order of construction
5302   // and not what user specified in the Initializers list.
5303   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5304   if (!ClassDecl)
5305     return true;
5306 
5307   bool HadError = false;
5308 
5309   for (unsigned i = 0; i < Initializers.size(); i++) {
5310     CXXCtorInitializer *Member = Initializers[i];
5311 
5312     if (Member->isBaseInitializer())
5313       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
5314     else {
5315       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5316 
5317       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5318         for (auto *C : F->chain()) {
5319           FieldDecl *FD = dyn_cast<FieldDecl>(C);
5320           if (FD && FD->getParent()->isUnion())
5321             Info.ActiveUnionMember.insert(std::make_pair(
5322                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5323         }
5324       } else if (FieldDecl *FD = Member->getMember()) {
5325         if (FD->getParent()->isUnion())
5326           Info.ActiveUnionMember.insert(std::make_pair(
5327               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5328       }
5329     }
5330   }
5331 
5332   // Keep track of the direct virtual bases.
5333   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
5334   for (auto &I : ClassDecl->bases()) {
5335     if (I.isVirtual())
5336       DirectVBases.insert(&I);
5337   }
5338 
5339   // Push virtual bases before others.
5340   for (auto &VBase : ClassDecl->vbases()) {
5341     if (CXXCtorInitializer *Value
5342         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
5343       // [class.base.init]p7, per DR257:
5344       //   A mem-initializer where the mem-initializer-id names a virtual base
5345       //   class is ignored during execution of a constructor of any class that
5346       //   is not the most derived class.
5347       if (ClassDecl->isAbstract()) {
5348         // FIXME: Provide a fixit to remove the base specifier. This requires
5349         // tracking the location of the associated comma for a base specifier.
5350         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5351           << VBase.getType() << ClassDecl;
5352         DiagnoseAbstractType(ClassDecl);
5353       }
5354 
5355       Info.AllToInit.push_back(Value);
5356     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5357       // [class.base.init]p8, per DR257:
5358       //   If a given [...] base class is not named by a mem-initializer-id
5359       //   [...] and the entity is not a virtual base class of an abstract
5360       //   class, then [...] the entity is default-initialized.
5361       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5362       CXXCtorInitializer *CXXBaseInit;
5363       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5364                                        &VBase, IsInheritedVirtualBase,
5365                                        CXXBaseInit)) {
5366         HadError = true;
5367         continue;
5368       }
5369 
5370       Info.AllToInit.push_back(CXXBaseInit);
5371     }
5372   }
5373 
5374   // Non-virtual bases.
5375   for (auto &Base : ClassDecl->bases()) {
5376     // Virtuals are in the virtual base list and already constructed.
5377     if (Base.isVirtual())
5378       continue;
5379 
5380     if (CXXCtorInitializer *Value
5381           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
5382       Info.AllToInit.push_back(Value);
5383     } else if (!AnyErrors) {
5384       CXXCtorInitializer *CXXBaseInit;
5385       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5386                                        &Base, /*IsInheritedVirtualBase=*/false,
5387                                        CXXBaseInit)) {
5388         HadError = true;
5389         continue;
5390       }
5391 
5392       Info.AllToInit.push_back(CXXBaseInit);
5393     }
5394   }
5395 
5396   // Fields.
5397   for (auto *Mem : ClassDecl->decls()) {
5398     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5399       // C++ [class.bit]p2:
5400       //   A declaration for a bit-field that omits the identifier declares an
5401       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
5402       //   initialized.
5403       if (F->isUnnamedBitfield())
5404         continue;
5405 
5406       // If we're not generating the implicit copy/move constructor, then we'll
5407       // handle anonymous struct/union fields based on their individual
5408       // indirect fields.
5409       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5410         continue;
5411 
5412       if (CollectFieldInitializer(*this, Info, F))
5413         HadError = true;
5414       continue;
5415     }
5416 
5417     // Beyond this point, we only consider default initialization.
5418     if (Info.isImplicitCopyOrMove())
5419       continue;
5420 
5421     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5422       if (F->getType()->isIncompleteArrayType()) {
5423         assert(ClassDecl->hasFlexibleArrayMember() &&
5424                "Incomplete array type is not valid");
5425         continue;
5426       }
5427 
5428       // Initialize each field of an anonymous struct individually.
5429       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5430         HadError = true;
5431 
5432       continue;
5433     }
5434   }
5435 
5436   unsigned NumInitializers = Info.AllToInit.size();
5437   if (NumInitializers > 0) {
5438     Constructor->setNumCtorInitializers(NumInitializers);
5439     CXXCtorInitializer **baseOrMemberInitializers =
5440       new (Context) CXXCtorInitializer*[NumInitializers];
5441     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5442            NumInitializers * sizeof(CXXCtorInitializer*));
5443     Constructor->setCtorInitializers(baseOrMemberInitializers);
5444 
5445     // Constructors implicitly reference the base and member
5446     // destructors.
5447     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
5448                                            Constructor->getParent());
5449   }
5450 
5451   return HadError;
5452 }
5453 
5454 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5455   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5456     const RecordDecl *RD = RT->getDecl();
5457     if (RD->isAnonymousStructOrUnion()) {
5458       for (auto *Field : RD->fields())
5459         PopulateKeysForFields(Field, IdealInits);
5460       return;
5461     }
5462   }
5463   IdealInits.push_back(Field->getCanonicalDecl());
5464 }
5465 
5466 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5467   return Context.getCanonicalType(BaseType).getTypePtr();
5468 }
5469 
5470 static const void *GetKeyForMember(ASTContext &Context,
5471                                    CXXCtorInitializer *Member) {
5472   if (!Member->isAnyMemberInitializer())
5473     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5474 
5475   return Member->getAnyMember()->getCanonicalDecl();
5476 }
5477 
5478 static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag,
5479                                  const CXXCtorInitializer *Previous,
5480                                  const CXXCtorInitializer *Current) {
5481   if (Previous->isAnyMemberInitializer())
5482     Diag << 0 << Previous->getAnyMember();
5483   else
5484     Diag << 1 << Previous->getTypeSourceInfo()->getType();
5485 
5486   if (Current->isAnyMemberInitializer())
5487     Diag << 0 << Current->getAnyMember();
5488   else
5489     Diag << 1 << Current->getTypeSourceInfo()->getType();
5490 }
5491 
5492 static void DiagnoseBaseOrMemInitializerOrder(
5493     Sema &SemaRef, const CXXConstructorDecl *Constructor,
5494     ArrayRef<CXXCtorInitializer *> Inits) {
5495   if (Constructor->getDeclContext()->isDependentContext())
5496     return;
5497 
5498   // Don't check initializers order unless the warning is enabled at the
5499   // location of at least one initializer.
5500   bool ShouldCheckOrder = false;
5501   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5502     CXXCtorInitializer *Init = Inits[InitIndex];
5503     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5504                                  Init->getSourceLocation())) {
5505       ShouldCheckOrder = true;
5506       break;
5507     }
5508   }
5509   if (!ShouldCheckOrder)
5510     return;
5511 
5512   // Build the list of bases and members in the order that they'll
5513   // actually be initialized.  The explicit initializers should be in
5514   // this same order but may be missing things.
5515   SmallVector<const void*, 32> IdealInitKeys;
5516 
5517   const CXXRecordDecl *ClassDecl = Constructor->getParent();
5518 
5519   // 1. Virtual bases.
5520   for (const auto &VBase : ClassDecl->vbases())
5521     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5522 
5523   // 2. Non-virtual bases.
5524   for (const auto &Base : ClassDecl->bases()) {
5525     if (Base.isVirtual())
5526       continue;
5527     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5528   }
5529 
5530   // 3. Direct fields.
5531   for (auto *Field : ClassDecl->fields()) {
5532     if (Field->isUnnamedBitfield())
5533       continue;
5534 
5535     PopulateKeysForFields(Field, IdealInitKeys);
5536   }
5537 
5538   unsigned NumIdealInits = IdealInitKeys.size();
5539   unsigned IdealIndex = 0;
5540 
5541   // Track initializers that are in an incorrect order for either a warning or
5542   // note if multiple ones occur.
5543   SmallVector<unsigned> WarnIndexes;
5544   // Correlates the index of an initializer in the init-list to the index of
5545   // the field/base in the class.
5546   SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5547 
5548   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5549     const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]);
5550 
5551     // Scan forward to try to find this initializer in the idealized
5552     // initializers list.
5553     for (; IdealIndex != NumIdealInits; ++IdealIndex)
5554       if (InitKey == IdealInitKeys[IdealIndex])
5555         break;
5556 
5557     // If we didn't find this initializer, it must be because we
5558     // scanned past it on a previous iteration.  That can only
5559     // happen if we're out of order;  emit a warning.
5560     if (IdealIndex == NumIdealInits && InitIndex) {
5561       WarnIndexes.push_back(InitIndex);
5562 
5563       // Move back to the initializer's location in the ideal list.
5564       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5565         if (InitKey == IdealInitKeys[IdealIndex])
5566           break;
5567 
5568       assert(IdealIndex < NumIdealInits &&
5569              "initializer not found in initializer list");
5570     }
5571     CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex);
5572   }
5573 
5574   if (WarnIndexes.empty())
5575     return;
5576 
5577   // Sort based on the ideal order, first in the pair.
5578   llvm::sort(CorrelatedInitOrder, llvm::less_first());
5579 
5580   // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5581   // emit the diagnostic before we can try adding notes.
5582   {
5583     Sema::SemaDiagnosticBuilder D = SemaRef.Diag(
5584         Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5585         WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5586                                 : diag::warn_some_initializers_out_of_order);
5587 
5588     for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5589       if (CorrelatedInitOrder[I].second == I)
5590         continue;
5591       // Ideally we would be using InsertFromRange here, but clang doesn't
5592       // appear to handle InsertFromRange correctly when the source range is
5593       // modified by another fix-it.
5594       D << FixItHint::CreateReplacement(
5595           Inits[I]->getSourceRange(),
5596           Lexer::getSourceText(
5597               CharSourceRange::getTokenRange(
5598                   Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5599               SemaRef.getSourceManager(), SemaRef.getLangOpts()));
5600     }
5601 
5602     // If there is only 1 item out of order, the warning expects the name and
5603     // type of each being added to it.
5604     if (WarnIndexes.size() == 1) {
5605       AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1],
5606                            Inits[WarnIndexes.front()]);
5607       return;
5608     }
5609   }
5610   // More than 1 item to warn, create notes letting the user know which ones
5611   // are bad.
5612   for (unsigned WarnIndex : WarnIndexes) {
5613     const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5614     auto D = SemaRef.Diag(PrevInit->getSourceLocation(),
5615                           diag::note_initializer_out_of_order);
5616     AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]);
5617     D << PrevInit->getSourceRange();
5618   }
5619 }
5620 
5621 namespace {
5622 bool CheckRedundantInit(Sema &S,
5623                         CXXCtorInitializer *Init,
5624                         CXXCtorInitializer *&PrevInit) {
5625   if (!PrevInit) {
5626     PrevInit = Init;
5627     return false;
5628   }
5629 
5630   if (FieldDecl *Field = Init->getAnyMember())
5631     S.Diag(Init->getSourceLocation(),
5632            diag::err_multiple_mem_initialization)
5633       << Field->getDeclName()
5634       << Init->getSourceRange();
5635   else {
5636     const Type *BaseClass = Init->getBaseClass();
5637     assert(BaseClass && "neither field nor base");
5638     S.Diag(Init->getSourceLocation(),
5639            diag::err_multiple_base_initialization)
5640       << QualType(BaseClass, 0)
5641       << Init->getSourceRange();
5642   }
5643   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5644     << 0 << PrevInit->getSourceRange();
5645 
5646   return true;
5647 }
5648 
5649 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5650 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5651 
5652 bool CheckRedundantUnionInit(Sema &S,
5653                              CXXCtorInitializer *Init,
5654                              RedundantUnionMap &Unions) {
5655   FieldDecl *Field = Init->getAnyMember();
5656   RecordDecl *Parent = Field->getParent();
5657   NamedDecl *Child = Field;
5658 
5659   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5660     if (Parent->isUnion()) {
5661       UnionEntry &En = Unions[Parent];
5662       if (En.first && En.first != Child) {
5663         S.Diag(Init->getSourceLocation(),
5664                diag::err_multiple_mem_union_initialization)
5665           << Field->getDeclName()
5666           << Init->getSourceRange();
5667         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5668           << 0 << En.second->getSourceRange();
5669         return true;
5670       }
5671       if (!En.first) {
5672         En.first = Child;
5673         En.second = Init;
5674       }
5675       if (!Parent->isAnonymousStructOrUnion())
5676         return false;
5677     }
5678 
5679     Child = Parent;
5680     Parent = cast<RecordDecl>(Parent->getDeclContext());
5681   }
5682 
5683   return false;
5684 }
5685 } // namespace
5686 
5687 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5688 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5689                                 SourceLocation ColonLoc,
5690                                 ArrayRef<CXXCtorInitializer*> MemInits,
5691                                 bool AnyErrors) {
5692   if (!ConstructorDecl)
5693     return;
5694 
5695   AdjustDeclIfTemplate(ConstructorDecl);
5696 
5697   CXXConstructorDecl *Constructor
5698     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5699 
5700   if (!Constructor) {
5701     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5702     return;
5703   }
5704 
5705   // Mapping for the duplicate initializers check.
5706   // For member initializers, this is keyed with a FieldDecl*.
5707   // For base initializers, this is keyed with a Type*.
5708   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5709 
5710   // Mapping for the inconsistent anonymous-union initializers check.
5711   RedundantUnionMap MemberUnions;
5712 
5713   bool HadError = false;
5714   for (unsigned i = 0; i < MemInits.size(); i++) {
5715     CXXCtorInitializer *Init = MemInits[i];
5716 
5717     // Set the source order index.
5718     Init->setSourceOrder(i);
5719 
5720     if (Init->isAnyMemberInitializer()) {
5721       const void *Key = GetKeyForMember(Context, Init);
5722       if (CheckRedundantInit(*this, Init, Members[Key]) ||
5723           CheckRedundantUnionInit(*this, Init, MemberUnions))
5724         HadError = true;
5725     } else if (Init->isBaseInitializer()) {
5726       const void *Key = GetKeyForMember(Context, Init);
5727       if (CheckRedundantInit(*this, Init, Members[Key]))
5728         HadError = true;
5729     } else {
5730       assert(Init->isDelegatingInitializer());
5731       // This must be the only initializer
5732       if (MemInits.size() != 1) {
5733         Diag(Init->getSourceLocation(),
5734              diag::err_delegating_initializer_alone)
5735           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5736         // We will treat this as being the only initializer.
5737       }
5738       SetDelegatingInitializer(Constructor, MemInits[i]);
5739       // Return immediately as the initializer is set.
5740       return;
5741     }
5742   }
5743 
5744   if (HadError)
5745     return;
5746 
5747   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5748 
5749   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5750 
5751   DiagnoseUninitializedFields(*this, Constructor);
5752 }
5753 
5754 void
5755 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5756                                              CXXRecordDecl *ClassDecl) {
5757   // Ignore dependent contexts. Also ignore unions, since their members never
5758   // have destructors implicitly called.
5759   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5760     return;
5761 
5762   // FIXME: all the access-control diagnostics are positioned on the
5763   // field/base declaration.  That's probably good; that said, the
5764   // user might reasonably want to know why the destructor is being
5765   // emitted, and we currently don't say.
5766 
5767   // Non-static data members.
5768   for (auto *Field : ClassDecl->fields()) {
5769     if (Field->isInvalidDecl())
5770       continue;
5771 
5772     // Don't destroy incomplete or zero-length arrays.
5773     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5774       continue;
5775 
5776     QualType FieldType = Context.getBaseElementType(Field->getType());
5777 
5778     const RecordType* RT = FieldType->getAs<RecordType>();
5779     if (!RT)
5780       continue;
5781 
5782     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5783     if (FieldClassDecl->isInvalidDecl())
5784       continue;
5785     if (FieldClassDecl->hasIrrelevantDestructor())
5786       continue;
5787     // The destructor for an implicit anonymous union member is never invoked.
5788     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5789       continue;
5790 
5791     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5792     // Dtor might still be missing, e.g because it's invalid.
5793     if (!Dtor)
5794       continue;
5795     CheckDestructorAccess(Field->getLocation(), Dtor,
5796                           PDiag(diag::err_access_dtor_field)
5797                             << Field->getDeclName()
5798                             << FieldType);
5799 
5800     MarkFunctionReferenced(Location, Dtor);
5801     DiagnoseUseOfDecl(Dtor, Location);
5802   }
5803 
5804   // We only potentially invoke the destructors of potentially constructed
5805   // subobjects.
5806   bool VisitVirtualBases = !ClassDecl->isAbstract();
5807 
5808   // If the destructor exists and has already been marked used in the MS ABI,
5809   // then virtual base destructors have already been checked and marked used.
5810   // Skip checking them again to avoid duplicate diagnostics.
5811   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5812     CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5813     if (Dtor && Dtor->isUsed())
5814       VisitVirtualBases = false;
5815   }
5816 
5817   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5818 
5819   // Bases.
5820   for (const auto &Base : ClassDecl->bases()) {
5821     const RecordType *RT = Base.getType()->getAs<RecordType>();
5822     if (!RT)
5823       continue;
5824 
5825     // Remember direct virtual bases.
5826     if (Base.isVirtual()) {
5827       if (!VisitVirtualBases)
5828         continue;
5829       DirectVirtualBases.insert(RT);
5830     }
5831 
5832     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5833     // If our base class is invalid, we probably can't get its dtor anyway.
5834     if (BaseClassDecl->isInvalidDecl())
5835       continue;
5836     if (BaseClassDecl->hasIrrelevantDestructor())
5837       continue;
5838 
5839     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5840     // Dtor might still be missing, e.g because it's invalid.
5841     if (!Dtor)
5842       continue;
5843 
5844     // FIXME: caret should be on the start of the class name
5845     CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5846                           PDiag(diag::err_access_dtor_base)
5847                               << Base.getType() << Base.getSourceRange(),
5848                           Context.getTypeDeclType(ClassDecl));
5849 
5850     MarkFunctionReferenced(Location, Dtor);
5851     DiagnoseUseOfDecl(Dtor, Location);
5852   }
5853 
5854   if (VisitVirtualBases)
5855     MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5856                                          &DirectVirtualBases);
5857 }
5858 
5859 void Sema::MarkVirtualBaseDestructorsReferenced(
5860     SourceLocation Location, CXXRecordDecl *ClassDecl,
5861     llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) {
5862   // Virtual bases.
5863   for (const auto &VBase : ClassDecl->vbases()) {
5864     // Bases are always records in a well-formed non-dependent class.
5865     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5866 
5867     // Ignore already visited direct virtual bases.
5868     if (DirectVirtualBases && DirectVirtualBases->count(RT))
5869       continue;
5870 
5871     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5872     // If our base class is invalid, we probably can't get its dtor anyway.
5873     if (BaseClassDecl->isInvalidDecl())
5874       continue;
5875     if (BaseClassDecl->hasIrrelevantDestructor())
5876       continue;
5877 
5878     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5879     // Dtor might still be missing, e.g because it's invalid.
5880     if (!Dtor)
5881       continue;
5882     if (CheckDestructorAccess(
5883             ClassDecl->getLocation(), Dtor,
5884             PDiag(diag::err_access_dtor_vbase)
5885                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5886             Context.getTypeDeclType(ClassDecl)) ==
5887         AR_accessible) {
5888       CheckDerivedToBaseConversion(
5889           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5890           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5891           SourceRange(), DeclarationName(), nullptr);
5892     }
5893 
5894     MarkFunctionReferenced(Location, Dtor);
5895     DiagnoseUseOfDecl(Dtor, Location);
5896   }
5897 }
5898 
5899 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5900   if (!CDtorDecl)
5901     return;
5902 
5903   if (CXXConstructorDecl *Constructor
5904       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5905     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5906     DiagnoseUninitializedFields(*this, Constructor);
5907   }
5908 }
5909 
5910 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5911   if (!getLangOpts().CPlusPlus)
5912     return false;
5913 
5914   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5915   if (!RD)
5916     return false;
5917 
5918   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5919   // class template specialization here, but doing so breaks a lot of code.
5920 
5921   // We can't answer whether something is abstract until it has a
5922   // definition. If it's currently being defined, we'll walk back
5923   // over all the declarations when we have a full definition.
5924   const CXXRecordDecl *Def = RD->getDefinition();
5925   if (!Def || Def->isBeingDefined())
5926     return false;
5927 
5928   return RD->isAbstract();
5929 }
5930 
5931 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5932                                   TypeDiagnoser &Diagnoser) {
5933   if (!isAbstractType(Loc, T))
5934     return false;
5935 
5936   T = Context.getBaseElementType(T);
5937   Diagnoser.diagnose(*this, Loc, T);
5938   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5939   return true;
5940 }
5941 
5942 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5943   // Check if we've already emitted the list of pure virtual functions
5944   // for this class.
5945   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5946     return;
5947 
5948   // If the diagnostic is suppressed, don't emit the notes. We're only
5949   // going to emit them once, so try to attach them to a diagnostic we're
5950   // actually going to show.
5951   if (Diags.isLastDiagnosticIgnored())
5952     return;
5953 
5954   CXXFinalOverriderMap FinalOverriders;
5955   RD->getFinalOverriders(FinalOverriders);
5956 
5957   // Keep a set of seen pure methods so we won't diagnose the same method
5958   // more than once.
5959   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5960 
5961   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5962                                    MEnd = FinalOverriders.end();
5963        M != MEnd;
5964        ++M) {
5965     for (OverridingMethods::iterator SO = M->second.begin(),
5966                                   SOEnd = M->second.end();
5967          SO != SOEnd; ++SO) {
5968       // C++ [class.abstract]p4:
5969       //   A class is abstract if it contains or inherits at least one
5970       //   pure virtual function for which the final overrider is pure
5971       //   virtual.
5972 
5973       //
5974       if (SO->second.size() != 1)
5975         continue;
5976 
5977       if (!SO->second.front().Method->isPure())
5978         continue;
5979 
5980       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5981         continue;
5982 
5983       Diag(SO->second.front().Method->getLocation(),
5984            diag::note_pure_virtual_function)
5985         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5986     }
5987   }
5988 
5989   if (!PureVirtualClassDiagSet)
5990     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5991   PureVirtualClassDiagSet->insert(RD);
5992 }
5993 
5994 namespace {
5995 struct AbstractUsageInfo {
5996   Sema &S;
5997   CXXRecordDecl *Record;
5998   CanQualType AbstractType;
5999   bool Invalid;
6000 
6001   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
6002     : S(S), Record(Record),
6003       AbstractType(S.Context.getCanonicalType(
6004                    S.Context.getTypeDeclType(Record))),
6005       Invalid(false) {}
6006 
6007   void DiagnoseAbstractType() {
6008     if (Invalid) return;
6009     S.DiagnoseAbstractType(Record);
6010     Invalid = true;
6011   }
6012 
6013   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
6014 };
6015 
6016 struct CheckAbstractUsage {
6017   AbstractUsageInfo &Info;
6018   const NamedDecl *Ctx;
6019 
6020   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
6021     : Info(Info), Ctx(Ctx) {}
6022 
6023   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6024     switch (TL.getTypeLocClass()) {
6025 #define ABSTRACT_TYPELOC(CLASS, PARENT)
6026 #define TYPELOC(CLASS, PARENT) \
6027     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
6028 #include "clang/AST/TypeLocNodes.def"
6029     }
6030   }
6031 
6032   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6033     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
6034     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
6035       if (!TL.getParam(I))
6036         continue;
6037 
6038       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
6039       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
6040     }
6041   }
6042 
6043   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6044     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
6045   }
6046 
6047   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6048     // Visit the type parameters from a permissive context.
6049     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
6050       TemplateArgumentLoc TAL = TL.getArgLoc(I);
6051       if (TAL.getArgument().getKind() == TemplateArgument::Type)
6052         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
6053           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
6054       // TODO: other template argument types?
6055     }
6056   }
6057 
6058   // Visit pointee types from a permissive context.
6059 #define CheckPolymorphic(Type) \
6060   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
6061     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
6062   }
6063   CheckPolymorphic(PointerTypeLoc)
6064   CheckPolymorphic(ReferenceTypeLoc)
6065   CheckPolymorphic(MemberPointerTypeLoc)
6066   CheckPolymorphic(BlockPointerTypeLoc)
6067   CheckPolymorphic(AtomicTypeLoc)
6068 
6069   /// Handle all the types we haven't given a more specific
6070   /// implementation for above.
6071   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6072     // Every other kind of type that we haven't called out already
6073     // that has an inner type is either (1) sugar or (2) contains that
6074     // inner type in some way as a subobject.
6075     if (TypeLoc Next = TL.getNextTypeLoc())
6076       return Visit(Next, Sel);
6077 
6078     // If there's no inner type and we're in a permissive context,
6079     // don't diagnose.
6080     if (Sel == Sema::AbstractNone) return;
6081 
6082     // Check whether the type matches the abstract type.
6083     QualType T = TL.getType();
6084     if (T->isArrayType()) {
6085       Sel = Sema::AbstractArrayType;
6086       T = Info.S.Context.getBaseElementType(T);
6087     }
6088     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
6089     if (CT != Info.AbstractType) return;
6090 
6091     // It matched; do some magic.
6092     // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
6093     if (Sel == Sema::AbstractArrayType) {
6094       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
6095         << T << TL.getSourceRange();
6096     } else {
6097       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
6098         << Sel << T << TL.getSourceRange();
6099     }
6100     Info.DiagnoseAbstractType();
6101   }
6102 };
6103 
6104 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
6105                                   Sema::AbstractDiagSelID Sel) {
6106   CheckAbstractUsage(*this, D).Visit(TL, Sel);
6107 }
6108 
6109 }
6110 
6111 /// Check for invalid uses of an abstract type in a function declaration.
6112 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6113                                     FunctionDecl *FD) {
6114   // Only definitions are required to refer to complete and
6115   // non-abstract types.
6116   if (!FD->doesThisDeclarationHaveABody())
6117     return;
6118 
6119   // For safety's sake, just ignore it if we don't have type source
6120   // information.  This should never happen for non-implicit methods,
6121   // but...
6122   if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6123     Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone);
6124 }
6125 
6126 /// Check for invalid uses of an abstract type in a variable0 declaration.
6127 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6128                                     VarDecl *VD) {
6129   // No need to do the check on definitions, which require that
6130   // the type is complete.
6131   if (VD->isThisDeclarationADefinition())
6132     return;
6133 
6134   Info.CheckType(VD, VD->getTypeSourceInfo()->getTypeLoc(),
6135                  Sema::AbstractVariableType);
6136 }
6137 
6138 /// Check for invalid uses of an abstract type within a class definition.
6139 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6140                                     CXXRecordDecl *RD) {
6141   for (auto *D : RD->decls()) {
6142     if (D->isImplicit()) continue;
6143 
6144     // Step through friends to the befriended declaration.
6145     if (auto *FD = dyn_cast<FriendDecl>(D)) {
6146       D = FD->getFriendDecl();
6147       if (!D) continue;
6148     }
6149 
6150     // Functions and function templates.
6151     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6152       CheckAbstractClassUsage(Info, FD);
6153     } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {
6154       CheckAbstractClassUsage(Info, FTD->getTemplatedDecl());
6155 
6156     // Fields and static variables.
6157     } else if (auto *FD = dyn_cast<FieldDecl>(D)) {
6158       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6159         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
6160     } else if (auto *VD = dyn_cast<VarDecl>(D)) {
6161       CheckAbstractClassUsage(Info, VD);
6162     } else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) {
6163       CheckAbstractClassUsage(Info, VTD->getTemplatedDecl());
6164 
6165     // Nested classes and class templates.
6166     } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6167       CheckAbstractClassUsage(Info, RD);
6168     } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) {
6169       CheckAbstractClassUsage(Info, CTD->getTemplatedDecl());
6170     }
6171   }
6172 }
6173 
6174 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
6175   Attr *ClassAttr = getDLLAttr(Class);
6176   if (!ClassAttr)
6177     return;
6178 
6179   assert(ClassAttr->getKind() == attr::DLLExport);
6180 
6181   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6182 
6183   if (TSK == TSK_ExplicitInstantiationDeclaration)
6184     // Don't go any further if this is just an explicit instantiation
6185     // declaration.
6186     return;
6187 
6188   // Add a context note to explain how we got to any diagnostics produced below.
6189   struct MarkingClassDllexported {
6190     Sema &S;
6191     MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
6192                             SourceLocation AttrLoc)
6193         : S(S) {
6194       Sema::CodeSynthesisContext Ctx;
6195       Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;
6196       Ctx.PointOfInstantiation = AttrLoc;
6197       Ctx.Entity = Class;
6198       S.pushCodeSynthesisContext(Ctx);
6199     }
6200     ~MarkingClassDllexported() {
6201       S.popCodeSynthesisContext();
6202     }
6203   } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
6204 
6205   if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
6206     S.MarkVTableUsed(Class->getLocation(), Class, true);
6207 
6208   for (Decl *Member : Class->decls()) {
6209     // Skip members that were not marked exported.
6210     if (!Member->hasAttr<DLLExportAttr>())
6211       continue;
6212 
6213     // Defined static variables that are members of an exported base
6214     // class must be marked export too.
6215     auto *VD = dyn_cast<VarDecl>(Member);
6216     if (VD && VD->getStorageClass() == SC_Static &&
6217         TSK == TSK_ImplicitInstantiation)
6218       S.MarkVariableReferenced(VD->getLocation(), VD);
6219 
6220     auto *MD = dyn_cast<CXXMethodDecl>(Member);
6221     if (!MD)
6222       continue;
6223 
6224     if (MD->isUserProvided()) {
6225       // Instantiate non-default class member functions ...
6226 
6227       // .. except for certain kinds of template specializations.
6228       if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
6229         continue;
6230 
6231       // If this is an MS ABI dllexport default constructor, instantiate any
6232       // default arguments.
6233       if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6234         auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6235         if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
6236           S.InstantiateDefaultCtorDefaultArgs(CD);
6237         }
6238       }
6239 
6240       S.MarkFunctionReferenced(Class->getLocation(), MD);
6241 
6242       // The function will be passed to the consumer when its definition is
6243       // encountered.
6244     } else if (MD->isExplicitlyDefaulted()) {
6245       // Synthesize and instantiate explicitly defaulted methods.
6246       S.MarkFunctionReferenced(Class->getLocation(), MD);
6247 
6248       if (TSK != TSK_ExplicitInstantiationDefinition) {
6249         // Except for explicit instantiation defs, we will not see the
6250         // definition again later, so pass it to the consumer now.
6251         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
6252       }
6253     } else if (!MD->isTrivial() ||
6254                MD->isCopyAssignmentOperator() ||
6255                MD->isMoveAssignmentOperator()) {
6256       // Synthesize and instantiate non-trivial implicit methods, and the copy
6257       // and move assignment operators. The latter are exported even if they
6258       // are trivial, because the address of an operator can be taken and
6259       // should compare equal across libraries.
6260       S.MarkFunctionReferenced(Class->getLocation(), MD);
6261 
6262       // There is no later point when we will see the definition of this
6263       // function, so pass it to the consumer now.
6264       S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
6265     }
6266   }
6267 }
6268 
6269 static void checkForMultipleExportedDefaultConstructors(Sema &S,
6270                                                         CXXRecordDecl *Class) {
6271   // Only the MS ABI has default constructor closures, so we don't need to do
6272   // this semantic checking anywhere else.
6273   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
6274     return;
6275 
6276   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6277   for (Decl *Member : Class->decls()) {
6278     // Look for exported default constructors.
6279     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
6280     if (!CD || !CD->isDefaultConstructor())
6281       continue;
6282     auto *Attr = CD->getAttr<DLLExportAttr>();
6283     if (!Attr)
6284       continue;
6285 
6286     // If the class is non-dependent, mark the default arguments as ODR-used so
6287     // that we can properly codegen the constructor closure.
6288     if (!Class->isDependentContext()) {
6289       for (ParmVarDecl *PD : CD->parameters()) {
6290         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
6291         S.DiscardCleanupsInEvaluationContext();
6292       }
6293     }
6294 
6295     if (LastExportedDefaultCtor) {
6296       S.Diag(LastExportedDefaultCtor->getLocation(),
6297              diag::err_attribute_dll_ambiguous_default_ctor)
6298           << Class;
6299       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
6300           << CD->getDeclName();
6301       return;
6302     }
6303     LastExportedDefaultCtor = CD;
6304   }
6305 }
6306 
6307 static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
6308                                                        CXXRecordDecl *Class) {
6309   bool ErrorReported = false;
6310   auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6311                                                      ClassTemplateDecl *TD) {
6312     if (ErrorReported)
6313       return;
6314     S.Diag(TD->getLocation(),
6315            diag::err_cuda_device_builtin_surftex_cls_template)
6316         << /*surface*/ 0 << TD;
6317     ErrorReported = true;
6318   };
6319 
6320   ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6321   if (!TD) {
6322     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6323     if (!SD) {
6324       S.Diag(Class->getLocation(),
6325              diag::err_cuda_device_builtin_surftex_ref_decl)
6326           << /*surface*/ 0 << Class;
6327       S.Diag(Class->getLocation(),
6328              diag::note_cuda_device_builtin_surftex_should_be_template_class)
6329           << Class;
6330       return;
6331     }
6332     TD = SD->getSpecializedTemplate();
6333   }
6334 
6335   TemplateParameterList *Params = TD->getTemplateParameters();
6336   unsigned N = Params->size();
6337 
6338   if (N != 2) {
6339     reportIllegalClassTemplate(S, TD);
6340     S.Diag(TD->getLocation(),
6341            diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6342         << TD << 2;
6343   }
6344   if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6345     reportIllegalClassTemplate(S, TD);
6346     S.Diag(TD->getLocation(),
6347            diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6348         << TD << /*1st*/ 0 << /*type*/ 0;
6349   }
6350   if (N > 1) {
6351     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6352     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6353       reportIllegalClassTemplate(S, TD);
6354       S.Diag(TD->getLocation(),
6355              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6356           << TD << /*2nd*/ 1 << /*integer*/ 1;
6357     }
6358   }
6359 }
6360 
6361 static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
6362                                                        CXXRecordDecl *Class) {
6363   bool ErrorReported = false;
6364   auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6365                                                      ClassTemplateDecl *TD) {
6366     if (ErrorReported)
6367       return;
6368     S.Diag(TD->getLocation(),
6369            diag::err_cuda_device_builtin_surftex_cls_template)
6370         << /*texture*/ 1 << TD;
6371     ErrorReported = true;
6372   };
6373 
6374   ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6375   if (!TD) {
6376     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6377     if (!SD) {
6378       S.Diag(Class->getLocation(),
6379              diag::err_cuda_device_builtin_surftex_ref_decl)
6380           << /*texture*/ 1 << Class;
6381       S.Diag(Class->getLocation(),
6382              diag::note_cuda_device_builtin_surftex_should_be_template_class)
6383           << Class;
6384       return;
6385     }
6386     TD = SD->getSpecializedTemplate();
6387   }
6388 
6389   TemplateParameterList *Params = TD->getTemplateParameters();
6390   unsigned N = Params->size();
6391 
6392   if (N != 3) {
6393     reportIllegalClassTemplate(S, TD);
6394     S.Diag(TD->getLocation(),
6395            diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6396         << TD << 3;
6397   }
6398   if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6399     reportIllegalClassTemplate(S, TD);
6400     S.Diag(TD->getLocation(),
6401            diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6402         << TD << /*1st*/ 0 << /*type*/ 0;
6403   }
6404   if (N > 1) {
6405     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6406     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6407       reportIllegalClassTemplate(S, TD);
6408       S.Diag(TD->getLocation(),
6409              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6410           << TD << /*2nd*/ 1 << /*integer*/ 1;
6411     }
6412   }
6413   if (N > 2) {
6414     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6415     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6416       reportIllegalClassTemplate(S, TD);
6417       S.Diag(TD->getLocation(),
6418              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6419           << TD << /*3rd*/ 2 << /*integer*/ 1;
6420     }
6421   }
6422 }
6423 
6424 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
6425   // Mark any compiler-generated routines with the implicit code_seg attribute.
6426   for (auto *Method : Class->methods()) {
6427     if (Method->isUserProvided())
6428       continue;
6429     if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6430       Method->addAttr(A);
6431   }
6432 }
6433 
6434 /// Check class-level dllimport/dllexport attribute.
6435 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
6436   Attr *ClassAttr = getDLLAttr(Class);
6437 
6438   // MSVC inherits DLL attributes to partial class template specializations.
6439   if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6440     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6441       if (Attr *TemplateAttr =
6442               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6443         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6444         A->setInherited(true);
6445         ClassAttr = A;
6446       }
6447     }
6448   }
6449 
6450   if (!ClassAttr)
6451     return;
6452 
6453   // MSVC allows imported or exported template classes that have UniqueExternal
6454   // linkage. This occurs when the template class has been instantiated with
6455   // a template parameter which itself has internal linkage.
6456   // We drop the attribute to avoid exporting or importing any members.
6457   if ((Context.getTargetInfo().getCXXABI().isMicrosoft() ||
6458        Context.getTargetInfo().getTriple().isPS()) &&
6459       (!Class->isExternallyVisible() && Class->hasExternalFormalLinkage())) {
6460     Class->dropAttr<DLLExportAttr>();
6461     Class->dropAttr<DLLImportAttr>();
6462     return;
6463   }
6464 
6465   if (!Class->isExternallyVisible()) {
6466     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6467         << Class << ClassAttr;
6468     return;
6469   }
6470 
6471   if (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6472       !ClassAttr->isInherited()) {
6473     // Diagnose dll attributes on members of class with dll attribute.
6474     for (Decl *Member : Class->decls()) {
6475       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
6476         continue;
6477       InheritableAttr *MemberAttr = getDLLAttr(Member);
6478       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6479         continue;
6480 
6481       Diag(MemberAttr->getLocation(),
6482              diag::err_attribute_dll_member_of_dll_class)
6483           << MemberAttr << ClassAttr;
6484       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6485       Member->setInvalidDecl();
6486     }
6487   }
6488 
6489   if (Class->getDescribedClassTemplate())
6490     // Don't inherit dll attribute until the template is instantiated.
6491     return;
6492 
6493   // The class is either imported or exported.
6494   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6495 
6496   // Check if this was a dllimport attribute propagated from a derived class to
6497   // a base class template specialization. We don't apply these attributes to
6498   // static data members.
6499   const bool PropagatedImport =
6500       !ClassExported &&
6501       cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6502 
6503   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6504 
6505   // Ignore explicit dllexport on explicit class template instantiation
6506   // declarations, except in MinGW mode.
6507   if (ClassExported && !ClassAttr->isInherited() &&
6508       TSK == TSK_ExplicitInstantiationDeclaration &&
6509       !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
6510     Class->dropAttr<DLLExportAttr>();
6511     return;
6512   }
6513 
6514   // Force declaration of implicit members so they can inherit the attribute.
6515   ForceDeclarationOfImplicitMembers(Class);
6516 
6517   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6518   // seem to be true in practice?
6519 
6520   for (Decl *Member : Class->decls()) {
6521     VarDecl *VD = dyn_cast<VarDecl>(Member);
6522     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6523 
6524     // Only methods and static fields inherit the attributes.
6525     if (!VD && !MD)
6526       continue;
6527 
6528     if (MD) {
6529       // Don't process deleted methods.
6530       if (MD->isDeleted())
6531         continue;
6532 
6533       if (MD->isInlined()) {
6534         // MinGW does not import or export inline methods. But do it for
6535         // template instantiations.
6536         if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6537             TSK != TSK_ExplicitInstantiationDeclaration &&
6538             TSK != TSK_ExplicitInstantiationDefinition)
6539           continue;
6540 
6541         // MSVC versions before 2015 don't export the move assignment operators
6542         // and move constructor, so don't attempt to import/export them if
6543         // we have a definition.
6544         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6545         if ((MD->isMoveAssignmentOperator() ||
6546              (Ctor && Ctor->isMoveConstructor())) &&
6547             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6548           continue;
6549 
6550         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6551         // operator is exported anyway.
6552         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6553             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6554           continue;
6555       }
6556     }
6557 
6558     // Don't apply dllimport attributes to static data members of class template
6559     // instantiations when the attribute is propagated from a derived class.
6560     if (VD && PropagatedImport)
6561       continue;
6562 
6563     if (!cast<NamedDecl>(Member)->isExternallyVisible())
6564       continue;
6565 
6566     if (!getDLLAttr(Member)) {
6567       InheritableAttr *NewAttr = nullptr;
6568 
6569       // Do not export/import inline function when -fno-dllexport-inlines is
6570       // passed. But add attribute for later local static var check.
6571       if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6572           TSK != TSK_ExplicitInstantiationDeclaration &&
6573           TSK != TSK_ExplicitInstantiationDefinition) {
6574         if (ClassExported) {
6575           NewAttr = ::new (getASTContext())
6576               DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6577         } else {
6578           NewAttr = ::new (getASTContext())
6579               DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6580         }
6581       } else {
6582         NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6583       }
6584 
6585       NewAttr->setInherited(true);
6586       Member->addAttr(NewAttr);
6587 
6588       if (MD) {
6589         // Propagate DLLAttr to friend re-declarations of MD that have already
6590         // been constructed.
6591         for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6592              FD = FD->getPreviousDecl()) {
6593           if (FD->getFriendObjectKind() == Decl::FOK_None)
6594             continue;
6595           assert(!getDLLAttr(FD) &&
6596                  "friend re-decl should not already have a DLLAttr");
6597           NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6598           NewAttr->setInherited(true);
6599           FD->addAttr(NewAttr);
6600         }
6601       }
6602     }
6603   }
6604 
6605   if (ClassExported)
6606     DelayedDllExportClasses.push_back(Class);
6607 }
6608 
6609 /// Perform propagation of DLL attributes from a derived class to a
6610 /// templated base class for MS compatibility.
6611 void Sema::propagateDLLAttrToBaseClassTemplate(
6612     CXXRecordDecl *Class, Attr *ClassAttr,
6613     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6614   if (getDLLAttr(
6615           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6616     // If the base class template has a DLL attribute, don't try to change it.
6617     return;
6618   }
6619 
6620   auto TSK = BaseTemplateSpec->getSpecializationKind();
6621   if (!getDLLAttr(BaseTemplateSpec) &&
6622       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
6623        TSK == TSK_ImplicitInstantiation)) {
6624     // The template hasn't been instantiated yet (or it has, but only as an
6625     // explicit instantiation declaration or implicit instantiation, which means
6626     // we haven't codegenned any members yet), so propagate the attribute.
6627     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6628     NewAttr->setInherited(true);
6629     BaseTemplateSpec->addAttr(NewAttr);
6630 
6631     // If this was an import, mark that we propagated it from a derived class to
6632     // a base class template specialization.
6633     if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6634       ImportAttr->setPropagatedToBaseTemplate();
6635 
6636     // If the template is already instantiated, checkDLLAttributeRedeclaration()
6637     // needs to be run again to work see the new attribute. Otherwise this will
6638     // get run whenever the template is instantiated.
6639     if (TSK != TSK_Undeclared)
6640       checkClassLevelDLLAttribute(BaseTemplateSpec);
6641 
6642     return;
6643   }
6644 
6645   if (getDLLAttr(BaseTemplateSpec)) {
6646     // The template has already been specialized or instantiated with an
6647     // attribute, explicitly or through propagation. We should not try to change
6648     // it.
6649     return;
6650   }
6651 
6652   // The template was previously instantiated or explicitly specialized without
6653   // a dll attribute, It's too late for us to add an attribute, so warn that
6654   // this is unsupported.
6655   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6656       << BaseTemplateSpec->isExplicitSpecialization();
6657   Diag(ClassAttr->getLocation(), diag::note_attribute);
6658   if (BaseTemplateSpec->isExplicitSpecialization()) {
6659     Diag(BaseTemplateSpec->getLocation(),
6660            diag::note_template_class_explicit_specialization_was_here)
6661         << BaseTemplateSpec;
6662   } else {
6663     Diag(BaseTemplateSpec->getPointOfInstantiation(),
6664            diag::note_template_class_instantiation_was_here)
6665         << BaseTemplateSpec;
6666   }
6667 }
6668 
6669 /// Determine the kind of defaulting that would be done for a given function.
6670 ///
6671 /// If the function is both a default constructor and a copy / move constructor
6672 /// (due to having a default argument for the first parameter), this picks
6673 /// CXXDefaultConstructor.
6674 ///
6675 /// FIXME: Check that case is properly handled by all callers.
6676 Sema::DefaultedFunctionKind
6677 Sema::getDefaultedFunctionKind(const FunctionDecl *FD) {
6678   if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6679     if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
6680       if (Ctor->isDefaultConstructor())
6681         return Sema::CXXDefaultConstructor;
6682 
6683       if (Ctor->isCopyConstructor())
6684         return Sema::CXXCopyConstructor;
6685 
6686       if (Ctor->isMoveConstructor())
6687         return Sema::CXXMoveConstructor;
6688     }
6689 
6690     if (MD->isCopyAssignmentOperator())
6691       return Sema::CXXCopyAssignment;
6692 
6693     if (MD->isMoveAssignmentOperator())
6694       return Sema::CXXMoveAssignment;
6695 
6696     if (isa<CXXDestructorDecl>(FD))
6697       return Sema::CXXDestructor;
6698   }
6699 
6700   switch (FD->getDeclName().getCXXOverloadedOperator()) {
6701   case OO_EqualEqual:
6702     return DefaultedComparisonKind::Equal;
6703 
6704   case OO_ExclaimEqual:
6705     return DefaultedComparisonKind::NotEqual;
6706 
6707   case OO_Spaceship:
6708     // No point allowing this if <=> doesn't exist in the current language mode.
6709     if (!getLangOpts().CPlusPlus20)
6710       break;
6711     return DefaultedComparisonKind::ThreeWay;
6712 
6713   case OO_Less:
6714   case OO_LessEqual:
6715   case OO_Greater:
6716   case OO_GreaterEqual:
6717     // No point allowing this if <=> doesn't exist in the current language mode.
6718     if (!getLangOpts().CPlusPlus20)
6719       break;
6720     return DefaultedComparisonKind::Relational;
6721 
6722   default:
6723     break;
6724   }
6725 
6726   // Not defaultable.
6727   return DefaultedFunctionKind();
6728 }
6729 
6730 static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,
6731                                     SourceLocation DefaultLoc) {
6732   Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD);
6733   if (DFK.isComparison())
6734     return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6735 
6736   switch (DFK.asSpecialMember()) {
6737   case Sema::CXXDefaultConstructor:
6738     S.DefineImplicitDefaultConstructor(DefaultLoc,
6739                                        cast<CXXConstructorDecl>(FD));
6740     break;
6741   case Sema::CXXCopyConstructor:
6742     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6743     break;
6744   case Sema::CXXCopyAssignment:
6745     S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6746     break;
6747   case Sema::CXXDestructor:
6748     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD));
6749     break;
6750   case Sema::CXXMoveConstructor:
6751     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6752     break;
6753   case Sema::CXXMoveAssignment:
6754     S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6755     break;
6756   case Sema::CXXInvalid:
6757     llvm_unreachable("Invalid special member.");
6758   }
6759 }
6760 
6761 /// Determine whether a type is permitted to be passed or returned in
6762 /// registers, per C++ [class.temporary]p3.
6763 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6764                                TargetInfo::CallingConvKind CCK) {
6765   if (D->isDependentType() || D->isInvalidDecl())
6766     return false;
6767 
6768   // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6769   // The PS4 platform ABI follows the behavior of Clang 3.2.
6770   if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6771     return !D->hasNonTrivialDestructorForCall() &&
6772            !D->hasNonTrivialCopyConstructorForCall();
6773 
6774   if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6775     bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6776     bool DtorIsTrivialForCall = false;
6777 
6778     // If a class has at least one eligible, trivial copy constructor, it
6779     // is passed according to the C ABI. Otherwise, it is passed indirectly.
6780     //
6781     // Note: This permits classes with non-trivial copy or move ctors to be
6782     // passed in registers, so long as they *also* have a trivial copy ctor,
6783     // which is non-conforming.
6784     if (D->needsImplicitCopyConstructor()) {
6785       if (!D->defaultedCopyConstructorIsDeleted()) {
6786         if (D->hasTrivialCopyConstructor())
6787           CopyCtorIsTrivial = true;
6788         if (D->hasTrivialCopyConstructorForCall())
6789           CopyCtorIsTrivialForCall = true;
6790       }
6791     } else {
6792       for (const CXXConstructorDecl *CD : D->ctors()) {
6793         if (CD->isCopyConstructor() && !CD->isDeleted() &&
6794             !CD->isIneligibleOrNotSelected()) {
6795           if (CD->isTrivial())
6796             CopyCtorIsTrivial = true;
6797           if (CD->isTrivialForCall())
6798             CopyCtorIsTrivialForCall = true;
6799         }
6800       }
6801     }
6802 
6803     if (D->needsImplicitDestructor()) {
6804       if (!D->defaultedDestructorIsDeleted() &&
6805           D->hasTrivialDestructorForCall())
6806         DtorIsTrivialForCall = true;
6807     } else if (const auto *DD = D->getDestructor()) {
6808       if (!DD->isDeleted() && DD->isTrivialForCall())
6809         DtorIsTrivialForCall = true;
6810     }
6811 
6812     // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6813     if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6814       return true;
6815 
6816     // If a class has a destructor, we'd really like to pass it indirectly
6817     // because it allows us to elide copies.  Unfortunately, MSVC makes that
6818     // impossible for small types, which it will pass in a single register or
6819     // stack slot. Most objects with dtors are large-ish, so handle that early.
6820     // We can't call out all large objects as being indirect because there are
6821     // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6822     // how we pass large POD types.
6823 
6824     // Note: This permits small classes with nontrivial destructors to be
6825     // passed in registers, which is non-conforming.
6826     bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6827     uint64_t TypeSize = isAArch64 ? 128 : 64;
6828 
6829     if (CopyCtorIsTrivial &&
6830         S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6831       return true;
6832     return false;
6833   }
6834 
6835   // Per C++ [class.temporary]p3, the relevant condition is:
6836   //   each copy constructor, move constructor, and destructor of X is
6837   //   either trivial or deleted, and X has at least one non-deleted copy
6838   //   or move constructor
6839   bool HasNonDeletedCopyOrMove = false;
6840 
6841   if (D->needsImplicitCopyConstructor() &&
6842       !D->defaultedCopyConstructorIsDeleted()) {
6843     if (!D->hasTrivialCopyConstructorForCall())
6844       return false;
6845     HasNonDeletedCopyOrMove = true;
6846   }
6847 
6848   if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6849       !D->defaultedMoveConstructorIsDeleted()) {
6850     if (!D->hasTrivialMoveConstructorForCall())
6851       return false;
6852     HasNonDeletedCopyOrMove = true;
6853   }
6854 
6855   if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6856       !D->hasTrivialDestructorForCall())
6857     return false;
6858 
6859   for (const CXXMethodDecl *MD : D->methods()) {
6860     if (MD->isDeleted() || MD->isIneligibleOrNotSelected())
6861       continue;
6862 
6863     auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6864     if (CD && CD->isCopyOrMoveConstructor())
6865       HasNonDeletedCopyOrMove = true;
6866     else if (!isa<CXXDestructorDecl>(MD))
6867       continue;
6868 
6869     if (!MD->isTrivialForCall())
6870       return false;
6871   }
6872 
6873   return HasNonDeletedCopyOrMove;
6874 }
6875 
6876 /// Report an error regarding overriding, along with any relevant
6877 /// overridden methods.
6878 ///
6879 /// \param DiagID the primary error to report.
6880 /// \param MD the overriding method.
6881 static bool
6882 ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
6883                 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
6884   bool IssuedDiagnostic = false;
6885   for (const CXXMethodDecl *O : MD->overridden_methods()) {
6886     if (Report(O)) {
6887       if (!IssuedDiagnostic) {
6888         S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6889         IssuedDiagnostic = true;
6890       }
6891       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
6892     }
6893   }
6894   return IssuedDiagnostic;
6895 }
6896 
6897 /// Perform semantic checks on a class definition that has been
6898 /// completing, introducing implicitly-declared members, checking for
6899 /// abstract types, etc.
6900 ///
6901 /// \param S The scope in which the class was parsed. Null if we didn't just
6902 ///        parse a class definition.
6903 /// \param Record The completed class.
6904 void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
6905   if (!Record)
6906     return;
6907 
6908   if (Record->isAbstract() && !Record->isInvalidDecl()) {
6909     AbstractUsageInfo Info(*this, Record);
6910     CheckAbstractClassUsage(Info, Record);
6911   }
6912 
6913   // If this is not an aggregate type and has no user-declared constructor,
6914   // complain about any non-static data members of reference or const scalar
6915   // type, since they will never get initializers.
6916   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6917       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6918       !Record->isLambda()) {
6919     bool Complained = false;
6920     for (const auto *F : Record->fields()) {
6921       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6922         continue;
6923 
6924       if (F->getType()->isReferenceType() ||
6925           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6926         if (!Complained) {
6927           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6928             << Record->getTagKind() << Record;
6929           Complained = true;
6930         }
6931 
6932         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6933           << F->getType()->isReferenceType()
6934           << F->getDeclName();
6935       }
6936     }
6937   }
6938 
6939   if (Record->getIdentifier()) {
6940     // C++ [class.mem]p13:
6941     //   If T is the name of a class, then each of the following shall have a
6942     //   name different from T:
6943     //     - every member of every anonymous union that is a member of class T.
6944     //
6945     // C++ [class.mem]p14:
6946     //   In addition, if class T has a user-declared constructor (12.1), every
6947     //   non-static data member of class T shall have a name different from T.
6948     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6949     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6950          ++I) {
6951       NamedDecl *D = (*I)->getUnderlyingDecl();
6952       if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6953            Record->hasUserDeclaredConstructor()) ||
6954           isa<IndirectFieldDecl>(D)) {
6955         Diag((*I)->getLocation(), diag::err_member_name_of_class)
6956           << D->getDeclName();
6957         break;
6958       }
6959     }
6960   }
6961 
6962   // Warn if the class has virtual methods but non-virtual public destructor.
6963   if (Record->isPolymorphic() && !Record->isDependentType()) {
6964     CXXDestructorDecl *dtor = Record->getDestructor();
6965     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6966         !Record->hasAttr<FinalAttr>())
6967       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6968            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6969   }
6970 
6971   if (Record->isAbstract()) {
6972     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6973       Diag(Record->getLocation(), diag::warn_abstract_final_class)
6974         << FA->isSpelledAsSealed();
6975       DiagnoseAbstractType(Record);
6976     }
6977   }
6978 
6979   // Warn if the class has a final destructor but is not itself marked final.
6980   if (!Record->hasAttr<FinalAttr>()) {
6981     if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
6982       if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
6983         Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
6984             << FA->isSpelledAsSealed()
6985             << FixItHint::CreateInsertion(
6986                    getLocForEndOfToken(Record->getLocation()),
6987                    (FA->isSpelledAsSealed() ? " sealed" : " final"));
6988         Diag(Record->getLocation(),
6989              diag::note_final_dtor_non_final_class_silence)
6990             << Context.getRecordType(Record) << FA->isSpelledAsSealed();
6991       }
6992     }
6993   }
6994 
6995   // See if trivial_abi has to be dropped.
6996   if (Record->hasAttr<TrivialABIAttr>())
6997     checkIllFormedTrivialABIStruct(*Record);
6998 
6999   // Set HasTrivialSpecialMemberForCall if the record has attribute
7000   // "trivial_abi".
7001   bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
7002 
7003   if (HasTrivialABI)
7004     Record->setHasTrivialSpecialMemberForCall();
7005 
7006   // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
7007   // We check these last because they can depend on the properties of the
7008   // primary comparison functions (==, <=>).
7009   llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
7010 
7011   // Perform checks that can't be done until we know all the properties of a
7012   // member function (whether it's defaulted, deleted, virtual, overriding,
7013   // ...).
7014   auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
7015     // A static function cannot override anything.
7016     if (MD->getStorageClass() == SC_Static) {
7017       if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
7018                           [](const CXXMethodDecl *) { return true; }))
7019         return;
7020     }
7021 
7022     // A deleted function cannot override a non-deleted function and vice
7023     // versa.
7024     if (ReportOverrides(*this,
7025                         MD->isDeleted() ? diag::err_deleted_override
7026                                         : diag::err_non_deleted_override,
7027                         MD, [&](const CXXMethodDecl *V) {
7028                           return MD->isDeleted() != V->isDeleted();
7029                         })) {
7030       if (MD->isDefaulted() && MD->isDeleted())
7031         // Explain why this defaulted function was deleted.
7032         DiagnoseDeletedDefaultedFunction(MD);
7033       return;
7034     }
7035 
7036     // A consteval function cannot override a non-consteval function and vice
7037     // versa.
7038     if (ReportOverrides(*this,
7039                         MD->isConsteval() ? diag::err_consteval_override
7040                                           : diag::err_non_consteval_override,
7041                         MD, [&](const CXXMethodDecl *V) {
7042                           return MD->isConsteval() != V->isConsteval();
7043                         })) {
7044       if (MD->isDefaulted() && MD->isDeleted())
7045         // Explain why this defaulted function was deleted.
7046         DiagnoseDeletedDefaultedFunction(MD);
7047       return;
7048     }
7049   };
7050 
7051   auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
7052     if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
7053       return false;
7054 
7055     DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
7056     if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||
7057         DFK.asComparison() == DefaultedComparisonKind::Relational) {
7058       DefaultedSecondaryComparisons.push_back(FD);
7059       return true;
7060     }
7061 
7062     CheckExplicitlyDefaultedFunction(S, FD);
7063     return false;
7064   };
7065 
7066   auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
7067     // Check whether the explicitly-defaulted members are valid.
7068     bool Incomplete = CheckForDefaultedFunction(M);
7069 
7070     // Skip the rest of the checks for a member of a dependent class.
7071     if (Record->isDependentType())
7072       return;
7073 
7074     // For an explicitly defaulted or deleted special member, we defer
7075     // determining triviality until the class is complete. That time is now!
7076     CXXSpecialMember CSM = getSpecialMember(M);
7077     if (!M->isImplicit() && !M->isUserProvided()) {
7078       if (CSM != CXXInvalid) {
7079         M->setTrivial(SpecialMemberIsTrivial(M, CSM));
7080         // Inform the class that we've finished declaring this member.
7081         Record->finishedDefaultedOrDeletedMember(M);
7082         M->setTrivialForCall(
7083             HasTrivialABI ||
7084             SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
7085         Record->setTrivialForCallFlags(M);
7086       }
7087     }
7088 
7089     // Set triviality for the purpose of calls if this is a user-provided
7090     // copy/move constructor or destructor.
7091     if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
7092          CSM == CXXDestructor) && M->isUserProvided()) {
7093       M->setTrivialForCall(HasTrivialABI);
7094       Record->setTrivialForCallFlags(M);
7095     }
7096 
7097     if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
7098         M->hasAttr<DLLExportAttr>()) {
7099       if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
7100           M->isTrivial() &&
7101           (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
7102            CSM == CXXDestructor))
7103         M->dropAttr<DLLExportAttr>();
7104 
7105       if (M->hasAttr<DLLExportAttr>()) {
7106         // Define after any fields with in-class initializers have been parsed.
7107         DelayedDllExportMemberFunctions.push_back(M);
7108       }
7109     }
7110 
7111     // Define defaulted constexpr virtual functions that override a base class
7112     // function right away.
7113     // FIXME: We can defer doing this until the vtable is marked as used.
7114     if (CSM != CXXInvalid && !M->isDeleted() && M->isDefaulted() &&
7115         M->isConstexpr() && M->size_overridden_methods())
7116       DefineDefaultedFunction(*this, M, M->getLocation());
7117 
7118     if (!Incomplete)
7119       CheckCompletedMemberFunction(M);
7120   };
7121 
7122   // Check the destructor before any other member function. We need to
7123   // determine whether it's trivial in order to determine whether the claas
7124   // type is a literal type, which is a prerequisite for determining whether
7125   // other special member functions are valid and whether they're implicitly
7126   // 'constexpr'.
7127   if (CXXDestructorDecl *Dtor = Record->getDestructor())
7128     CompleteMemberFunction(Dtor);
7129 
7130   bool HasMethodWithOverrideControl = false,
7131        HasOverridingMethodWithoutOverrideControl = false;
7132   for (auto *D : Record->decls()) {
7133     if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
7134       // FIXME: We could do this check for dependent types with non-dependent
7135       // bases.
7136       if (!Record->isDependentType()) {
7137         // See if a method overloads virtual methods in a base
7138         // class without overriding any.
7139         if (!M->isStatic())
7140           DiagnoseHiddenVirtualMethods(M);
7141         if (M->hasAttr<OverrideAttr>())
7142           HasMethodWithOverrideControl = true;
7143         else if (M->size_overridden_methods() > 0)
7144           HasOverridingMethodWithoutOverrideControl = true;
7145       }
7146 
7147       if (!isa<CXXDestructorDecl>(M))
7148         CompleteMemberFunction(M);
7149     } else if (auto *F = dyn_cast<FriendDecl>(D)) {
7150       CheckForDefaultedFunction(
7151           dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
7152     }
7153   }
7154 
7155   if (HasOverridingMethodWithoutOverrideControl) {
7156     bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
7157     for (auto *M : Record->methods())
7158       DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
7159   }
7160 
7161   // Check the defaulted secondary comparisons after any other member functions.
7162   for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
7163     CheckExplicitlyDefaultedFunction(S, FD);
7164 
7165     // If this is a member function, we deferred checking it until now.
7166     if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
7167       CheckCompletedMemberFunction(MD);
7168   }
7169 
7170   // ms_struct is a request to use the same ABI rules as MSVC.  Check
7171   // whether this class uses any C++ features that are implemented
7172   // completely differently in MSVC, and if so, emit a diagnostic.
7173   // That diagnostic defaults to an error, but we allow projects to
7174   // map it down to a warning (or ignore it).  It's a fairly common
7175   // practice among users of the ms_struct pragma to mass-annotate
7176   // headers, sweeping up a bunch of types that the project doesn't
7177   // really rely on MSVC-compatible layout for.  We must therefore
7178   // support "ms_struct except for C++ stuff" as a secondary ABI.
7179   // Don't emit this diagnostic if the feature was enabled as a
7180   // language option (as opposed to via a pragma or attribute), as
7181   // the option -mms-bitfields otherwise essentially makes it impossible
7182   // to build C++ code, unless this diagnostic is turned off.
7183   if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields &&
7184       (Record->isPolymorphic() || Record->getNumBases())) {
7185     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
7186   }
7187 
7188   checkClassLevelDLLAttribute(Record);
7189   checkClassLevelCodeSegAttribute(Record);
7190 
7191   bool ClangABICompat4 =
7192       Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
7193   TargetInfo::CallingConvKind CCK =
7194       Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
7195   bool CanPass = canPassInRegisters(*this, Record, CCK);
7196 
7197   // Do not change ArgPassingRestrictions if it has already been set to
7198   // APK_CanNeverPassInRegs.
7199   if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
7200     Record->setArgPassingRestrictions(CanPass
7201                                           ? RecordDecl::APK_CanPassInRegs
7202                                           : RecordDecl::APK_CannotPassInRegs);
7203 
7204   // If canPassInRegisters returns true despite the record having a non-trivial
7205   // destructor, the record is destructed in the callee. This happens only when
7206   // the record or one of its subobjects has a field annotated with trivial_abi
7207   // or a field qualified with ObjC __strong/__weak.
7208   if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
7209     Record->setParamDestroyedInCallee(true);
7210   else if (Record->hasNonTrivialDestructor())
7211     Record->setParamDestroyedInCallee(CanPass);
7212 
7213   if (getLangOpts().ForceEmitVTables) {
7214     // If we want to emit all the vtables, we need to mark it as used.  This
7215     // is especially required for cases like vtable assumption loads.
7216     MarkVTableUsed(Record->getInnerLocStart(), Record);
7217   }
7218 
7219   if (getLangOpts().CUDA) {
7220     if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
7221       checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record);
7222     else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
7223       checkCUDADeviceBuiltinTextureClassTemplate(*this, Record);
7224   }
7225 }
7226 
7227 /// Look up the special member function that would be called by a special
7228 /// member function for a subobject of class type.
7229 ///
7230 /// \param Class The class type of the subobject.
7231 /// \param CSM The kind of special member function.
7232 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
7233 /// \param ConstRHS True if this is a copy operation with a const object
7234 ///        on its RHS, that is, if the argument to the outer special member
7235 ///        function is 'const' and this is not a field marked 'mutable'.
7236 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
7237     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
7238     unsigned FieldQuals, bool ConstRHS) {
7239   unsigned LHSQuals = 0;
7240   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
7241     LHSQuals = FieldQuals;
7242 
7243   unsigned RHSQuals = FieldQuals;
7244   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
7245     RHSQuals = 0;
7246   else if (ConstRHS)
7247     RHSQuals |= Qualifiers::Const;
7248 
7249   return S.LookupSpecialMember(Class, CSM,
7250                                RHSQuals & Qualifiers::Const,
7251                                RHSQuals & Qualifiers::Volatile,
7252                                false,
7253                                LHSQuals & Qualifiers::Const,
7254                                LHSQuals & Qualifiers::Volatile);
7255 }
7256 
7257 class Sema::InheritedConstructorInfo {
7258   Sema &S;
7259   SourceLocation UseLoc;
7260 
7261   /// A mapping from the base classes through which the constructor was
7262   /// inherited to the using shadow declaration in that base class (or a null
7263   /// pointer if the constructor was declared in that base class).
7264   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
7265       InheritedFromBases;
7266 
7267 public:
7268   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
7269                            ConstructorUsingShadowDecl *Shadow)
7270       : S(S), UseLoc(UseLoc) {
7271     bool DiagnosedMultipleConstructedBases = false;
7272     CXXRecordDecl *ConstructedBase = nullptr;
7273     BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
7274 
7275     // Find the set of such base class subobjects and check that there's a
7276     // unique constructed subobject.
7277     for (auto *D : Shadow->redecls()) {
7278       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
7279       auto *DNominatedBase = DShadow->getNominatedBaseClass();
7280       auto *DConstructedBase = DShadow->getConstructedBaseClass();
7281 
7282       InheritedFromBases.insert(
7283           std::make_pair(DNominatedBase->getCanonicalDecl(),
7284                          DShadow->getNominatedBaseClassShadowDecl()));
7285       if (DShadow->constructsVirtualBase())
7286         InheritedFromBases.insert(
7287             std::make_pair(DConstructedBase->getCanonicalDecl(),
7288                            DShadow->getConstructedBaseClassShadowDecl()));
7289       else
7290         assert(DNominatedBase == DConstructedBase);
7291 
7292       // [class.inhctor.init]p2:
7293       //   If the constructor was inherited from multiple base class subobjects
7294       //   of type B, the program is ill-formed.
7295       if (!ConstructedBase) {
7296         ConstructedBase = DConstructedBase;
7297         ConstructedBaseIntroducer = D->getIntroducer();
7298       } else if (ConstructedBase != DConstructedBase &&
7299                  !Shadow->isInvalidDecl()) {
7300         if (!DiagnosedMultipleConstructedBases) {
7301           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
7302               << Shadow->getTargetDecl();
7303           S.Diag(ConstructedBaseIntroducer->getLocation(),
7304                  diag::note_ambiguous_inherited_constructor_using)
7305               << ConstructedBase;
7306           DiagnosedMultipleConstructedBases = true;
7307         }
7308         S.Diag(D->getIntroducer()->getLocation(),
7309                diag::note_ambiguous_inherited_constructor_using)
7310             << DConstructedBase;
7311       }
7312     }
7313 
7314     if (DiagnosedMultipleConstructedBases)
7315       Shadow->setInvalidDecl();
7316   }
7317 
7318   /// Find the constructor to use for inherited construction of a base class,
7319   /// and whether that base class constructor inherits the constructor from a
7320   /// virtual base class (in which case it won't actually invoke it).
7321   std::pair<CXXConstructorDecl *, bool>
7322   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
7323     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
7324     if (It == InheritedFromBases.end())
7325       return std::make_pair(nullptr, false);
7326 
7327     // This is an intermediary class.
7328     if (It->second)
7329       return std::make_pair(
7330           S.findInheritingConstructor(UseLoc, Ctor, It->second),
7331           It->second->constructsVirtualBase());
7332 
7333     // This is the base class from which the constructor was inherited.
7334     return std::make_pair(Ctor, false);
7335   }
7336 };
7337 
7338 /// Is the special member function which would be selected to perform the
7339 /// specified operation on the specified class type a constexpr constructor?
7340 static bool
7341 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
7342                          Sema::CXXSpecialMember CSM, unsigned Quals,
7343                          bool ConstRHS,
7344                          CXXConstructorDecl *InheritedCtor = nullptr,
7345                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
7346   // Suppress duplicate constraint checking here, in case a constraint check
7347   // caused us to decide to do this.  Any truely recursive checks will get
7348   // caught during these checks anyway.
7349   Sema::SatisfactionStackResetRAII SSRAII{S};
7350 
7351   // If we're inheriting a constructor, see if we need to call it for this base
7352   // class.
7353   if (InheritedCtor) {
7354     assert(CSM == Sema::CXXDefaultConstructor);
7355     auto BaseCtor =
7356         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
7357     if (BaseCtor)
7358       return BaseCtor->isConstexpr();
7359   }
7360 
7361   if (CSM == Sema::CXXDefaultConstructor)
7362     return ClassDecl->hasConstexprDefaultConstructor();
7363   if (CSM == Sema::CXXDestructor)
7364     return ClassDecl->hasConstexprDestructor();
7365 
7366   Sema::SpecialMemberOverloadResult SMOR =
7367       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
7368   if (!SMOR.getMethod())
7369     // A constructor we wouldn't select can't be "involved in initializing"
7370     // anything.
7371     return true;
7372   return SMOR.getMethod()->isConstexpr();
7373 }
7374 
7375 /// Determine whether the specified special member function would be constexpr
7376 /// if it were implicitly defined.
7377 static bool defaultedSpecialMemberIsConstexpr(
7378     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
7379     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
7380     Sema::InheritedConstructorInfo *Inherited = nullptr) {
7381   if (!S.getLangOpts().CPlusPlus11)
7382     return false;
7383 
7384   // C++11 [dcl.constexpr]p4:
7385   // In the definition of a constexpr constructor [...]
7386   bool Ctor = true;
7387   switch (CSM) {
7388   case Sema::CXXDefaultConstructor:
7389     if (Inherited)
7390       break;
7391     // Since default constructor lookup is essentially trivial (and cannot
7392     // involve, for instance, template instantiation), we compute whether a
7393     // defaulted default constructor is constexpr directly within CXXRecordDecl.
7394     //
7395     // This is important for performance; we need to know whether the default
7396     // constructor is constexpr to determine whether the type is a literal type.
7397     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7398 
7399   case Sema::CXXCopyConstructor:
7400   case Sema::CXXMoveConstructor:
7401     // For copy or move constructors, we need to perform overload resolution.
7402     break;
7403 
7404   case Sema::CXXCopyAssignment:
7405   case Sema::CXXMoveAssignment:
7406     if (!S.getLangOpts().CPlusPlus14)
7407       return false;
7408     // In C++1y, we need to perform overload resolution.
7409     Ctor = false;
7410     break;
7411 
7412   case Sema::CXXDestructor:
7413     return ClassDecl->defaultedDestructorIsConstexpr();
7414 
7415   case Sema::CXXInvalid:
7416     return false;
7417   }
7418 
7419   //   -- if the class is a non-empty union, or for each non-empty anonymous
7420   //      union member of a non-union class, exactly one non-static data member
7421   //      shall be initialized; [DR1359]
7422   //
7423   // If we squint, this is guaranteed, since exactly one non-static data member
7424   // will be initialized (if the constructor isn't deleted), we just don't know
7425   // which one.
7426   if (Ctor && ClassDecl->isUnion())
7427     return CSM == Sema::CXXDefaultConstructor
7428                ? ClassDecl->hasInClassInitializer() ||
7429                      !ClassDecl->hasVariantMembers()
7430                : true;
7431 
7432   //   -- the class shall not have any virtual base classes;
7433   if (Ctor && ClassDecl->getNumVBases())
7434     return false;
7435 
7436   // C++1y [class.copy]p26:
7437   //   -- [the class] is a literal type, and
7438   if (!Ctor && !ClassDecl->isLiteral())
7439     return false;
7440 
7441   //   -- every constructor involved in initializing [...] base class
7442   //      sub-objects shall be a constexpr constructor;
7443   //   -- the assignment operator selected to copy/move each direct base
7444   //      class is a constexpr function, and
7445   for (const auto &B : ClassDecl->bases()) {
7446     const RecordType *BaseType = B.getType()->getAs<RecordType>();
7447     if (!BaseType)
7448       continue;
7449     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7450     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7451                                   InheritedCtor, Inherited))
7452       return false;
7453   }
7454 
7455   //   -- every constructor involved in initializing non-static data members
7456   //      [...] shall be a constexpr constructor;
7457   //   -- every non-static data member and base class sub-object shall be
7458   //      initialized
7459   //   -- for each non-static data member of X that is of class type (or array
7460   //      thereof), the assignment operator selected to copy/move that member is
7461   //      a constexpr function
7462   for (const auto *F : ClassDecl->fields()) {
7463     if (F->isInvalidDecl())
7464       continue;
7465     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
7466       continue;
7467     QualType BaseType = S.Context.getBaseElementType(F->getType());
7468     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
7469       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7470       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7471                                     BaseType.getCVRQualifiers(),
7472                                     ConstArg && !F->isMutable()))
7473         return false;
7474     } else if (CSM == Sema::CXXDefaultConstructor) {
7475       return false;
7476     }
7477   }
7478 
7479   // All OK, it's constexpr!
7480   return true;
7481 }
7482 
7483 namespace {
7484 /// RAII object to register a defaulted function as having its exception
7485 /// specification computed.
7486 struct ComputingExceptionSpec {
7487   Sema &S;
7488 
7489   ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7490       : S(S) {
7491     Sema::CodeSynthesisContext Ctx;
7492     Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
7493     Ctx.PointOfInstantiation = Loc;
7494     Ctx.Entity = FD;
7495     S.pushCodeSynthesisContext(Ctx);
7496   }
7497   ~ComputingExceptionSpec() {
7498     S.popCodeSynthesisContext();
7499   }
7500 };
7501 }
7502 
7503 static Sema::ImplicitExceptionSpecification
7504 ComputeDefaultedSpecialMemberExceptionSpec(
7505     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
7506     Sema::InheritedConstructorInfo *ICI);
7507 
7508 static Sema::ImplicitExceptionSpecification
7509 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7510                                         FunctionDecl *FD,
7511                                         Sema::DefaultedComparisonKind DCK);
7512 
7513 static Sema::ImplicitExceptionSpecification
7514 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {
7515   auto DFK = S.getDefaultedFunctionKind(FD);
7516   if (DFK.isSpecialMember())
7517     return ComputeDefaultedSpecialMemberExceptionSpec(
7518         S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7519   if (DFK.isComparison())
7520     return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
7521                                                    DFK.asComparison());
7522 
7523   auto *CD = cast<CXXConstructorDecl>(FD);
7524   assert(CD->getInheritedConstructor() &&
7525          "only defaulted functions and inherited constructors have implicit "
7526          "exception specs");
7527   Sema::InheritedConstructorInfo ICI(
7528       S, Loc, CD->getInheritedConstructor().getShadowDecl());
7529   return ComputeDefaultedSpecialMemberExceptionSpec(
7530       S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
7531 }
7532 
7533 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
7534                                                             CXXMethodDecl *MD) {
7535   FunctionProtoType::ExtProtoInfo EPI;
7536 
7537   // Build an exception specification pointing back at this member.
7538   EPI.ExceptionSpec.Type = EST_Unevaluated;
7539   EPI.ExceptionSpec.SourceDecl = MD;
7540 
7541   // Set the calling convention to the default for C++ instance methods.
7542   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
7543       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7544                                             /*IsCXXMethod=*/true));
7545   return EPI;
7546 }
7547 
7548 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {
7549   const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7550   if (FPT->getExceptionSpecType() != EST_Unevaluated)
7551     return;
7552 
7553   // Evaluate the exception specification.
7554   auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7555   auto ESI = IES.getExceptionSpec();
7556 
7557   // Update the type of the special member to use it.
7558   UpdateExceptionSpec(FD, ESI);
7559 }
7560 
7561 void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
7562   assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7563 
7564   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
7565   if (!DefKind) {
7566     assert(FD->getDeclContext()->isDependentContext());
7567     return;
7568   }
7569 
7570   if (DefKind.isComparison())
7571     UnusedPrivateFields.clear();
7572 
7573   if (DefKind.isSpecialMember()
7574           ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
7575                                                   DefKind.asSpecialMember(),
7576                                                   FD->getDefaultLoc())
7577           : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison()))
7578     FD->setInvalidDecl();
7579 }
7580 
7581 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7582                                                  CXXSpecialMember CSM,
7583                                                  SourceLocation DefaultLoc) {
7584   CXXRecordDecl *RD = MD->getParent();
7585 
7586   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
7587          "not an explicitly-defaulted special member");
7588 
7589   // Defer all checking for special members of a dependent type.
7590   if (RD->isDependentType())
7591     return false;
7592 
7593   // Whether this was the first-declared instance of the constructor.
7594   // This affects whether we implicitly add an exception spec and constexpr.
7595   bool First = MD == MD->getCanonicalDecl();
7596 
7597   bool HadError = false;
7598 
7599   // C++11 [dcl.fct.def.default]p1:
7600   //   A function that is explicitly defaulted shall
7601   //     -- be a special member function [...] (checked elsewhere),
7602   //     -- have the same type (except for ref-qualifiers, and except that a
7603   //        copy operation can take a non-const reference) as an implicit
7604   //        declaration, and
7605   //     -- not have default arguments.
7606   // C++2a changes the second bullet to instead delete the function if it's
7607   // defaulted on its first declaration, unless it's "an assignment operator,
7608   // and its return type differs or its parameter type is not a reference".
7609   bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7610   bool ShouldDeleteForTypeMismatch = false;
7611   unsigned ExpectedParams = 1;
7612   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
7613     ExpectedParams = 0;
7614   if (MD->getNumParams() != ExpectedParams) {
7615     // This checks for default arguments: a copy or move constructor with a
7616     // default argument is classified as a default constructor, and assignment
7617     // operations and destructors can't have default arguments.
7618     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7619       << CSM << MD->getSourceRange();
7620     HadError = true;
7621   } else if (MD->isVariadic()) {
7622     if (DeleteOnTypeMismatch)
7623       ShouldDeleteForTypeMismatch = true;
7624     else {
7625       Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7626         << CSM << MD->getSourceRange();
7627       HadError = true;
7628     }
7629   }
7630 
7631   const FunctionProtoType *Type = MD->getType()->castAs<FunctionProtoType>();
7632 
7633   bool CanHaveConstParam = false;
7634   if (CSM == CXXCopyConstructor)
7635     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7636   else if (CSM == CXXCopyAssignment)
7637     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7638 
7639   QualType ReturnType = Context.VoidTy;
7640   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
7641     // Check for return type matching.
7642     ReturnType = Type->getReturnType();
7643 
7644     QualType DeclType = Context.getTypeDeclType(RD);
7645     DeclType = Context.getElaboratedType(ETK_None, nullptr, DeclType, nullptr);
7646     DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
7647     QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7648 
7649     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7650       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7651         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
7652       HadError = true;
7653     }
7654 
7655     // A defaulted special member cannot have cv-qualifiers.
7656     if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
7657       if (DeleteOnTypeMismatch)
7658         ShouldDeleteForTypeMismatch = true;
7659       else {
7660         Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7661           << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
7662         HadError = true;
7663       }
7664     }
7665   }
7666 
7667   // Check for parameter type matching.
7668   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
7669   bool HasConstParam = false;
7670   if (ExpectedParams && ArgType->isReferenceType()) {
7671     // Argument must be reference to possibly-const T.
7672     QualType ReferentType = ArgType->getPointeeType();
7673     HasConstParam = ReferentType.isConstQualified();
7674 
7675     if (ReferentType.isVolatileQualified()) {
7676       if (DeleteOnTypeMismatch)
7677         ShouldDeleteForTypeMismatch = true;
7678       else {
7679         Diag(MD->getLocation(),
7680              diag::err_defaulted_special_member_volatile_param) << CSM;
7681         HadError = true;
7682       }
7683     }
7684 
7685     if (HasConstParam && !CanHaveConstParam) {
7686       if (DeleteOnTypeMismatch)
7687         ShouldDeleteForTypeMismatch = true;
7688       else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
7689         Diag(MD->getLocation(),
7690              diag::err_defaulted_special_member_copy_const_param)
7691           << (CSM == CXXCopyAssignment);
7692         // FIXME: Explain why this special member can't be const.
7693         HadError = true;
7694       } else {
7695         Diag(MD->getLocation(),
7696              diag::err_defaulted_special_member_move_const_param)
7697           << (CSM == CXXMoveAssignment);
7698         HadError = true;
7699       }
7700     }
7701   } else if (ExpectedParams) {
7702     // A copy assignment operator can take its argument by value, but a
7703     // defaulted one cannot.
7704     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
7705     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
7706     HadError = true;
7707   }
7708 
7709   // C++11 [dcl.fct.def.default]p2:
7710   //   An explicitly-defaulted function may be declared constexpr only if it
7711   //   would have been implicitly declared as constexpr,
7712   // Do not apply this rule to members of class templates, since core issue 1358
7713   // makes such functions always instantiate to constexpr functions. For
7714   // functions which cannot be constexpr (for non-constructors in C++11 and for
7715   // destructors in C++14 and C++17), this is checked elsewhere.
7716   //
7717   // FIXME: This should not apply if the member is deleted.
7718   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
7719                                                      HasConstParam);
7720 
7721   // C++14 [dcl.constexpr]p6 (CWG DR647/CWG DR1358):
7722   //   If the instantiated template specialization of a constexpr function
7723   //   template or member function of a class template would fail to satisfy
7724   //   the requirements for a constexpr function or constexpr constructor, that
7725   //   specialization is still a constexpr function or constexpr constructor,
7726   //   even though a call to such a function cannot appear in a constant
7727   //   expression.
7728   if (MD->isTemplateInstantiation() && MD->isConstexpr())
7729     Constexpr = true;
7730 
7731   if ((getLangOpts().CPlusPlus20 ||
7732        (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
7733                                   : isa<CXXConstructorDecl>(MD))) &&
7734       MD->isConstexpr() && !Constexpr &&
7735       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
7736     Diag(MD->getBeginLoc(), MD->isConsteval()
7737                                 ? diag::err_incorrect_defaulted_consteval
7738                                 : diag::err_incorrect_defaulted_constexpr)
7739         << CSM;
7740     // FIXME: Explain why the special member can't be constexpr.
7741     HadError = true;
7742   }
7743 
7744   if (First) {
7745     // C++2a [dcl.fct.def.default]p3:
7746     //   If a function is explicitly defaulted on its first declaration, it is
7747     //   implicitly considered to be constexpr if the implicit declaration
7748     //   would be.
7749     MD->setConstexprKind(Constexpr ? (MD->isConsteval()
7750                                           ? ConstexprSpecKind::Consteval
7751                                           : ConstexprSpecKind::Constexpr)
7752                                    : ConstexprSpecKind::Unspecified);
7753 
7754     if (!Type->hasExceptionSpec()) {
7755       // C++2a [except.spec]p3:
7756       //   If a declaration of a function does not have a noexcept-specifier
7757       //   [and] is defaulted on its first declaration, [...] the exception
7758       //   specification is as specified below
7759       FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
7760       EPI.ExceptionSpec.Type = EST_Unevaluated;
7761       EPI.ExceptionSpec.SourceDecl = MD;
7762       MD->setType(Context.getFunctionType(
7763           ReturnType, llvm::ArrayRef(&ArgType, ExpectedParams), EPI));
7764     }
7765   }
7766 
7767   if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
7768     if (First) {
7769       SetDeclDeleted(MD, MD->getLocation());
7770       if (!inTemplateInstantiation() && !HadError) {
7771         Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
7772         if (ShouldDeleteForTypeMismatch) {
7773           Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
7774         } else if (ShouldDeleteSpecialMember(MD, CSM, nullptr,
7775                                              /*Diagnose*/ true) &&
7776                    DefaultLoc.isValid()) {
7777           Diag(DefaultLoc, diag::note_replace_equals_default_to_delete)
7778               << FixItHint::CreateReplacement(DefaultLoc, "delete");
7779         }
7780       }
7781       if (ShouldDeleteForTypeMismatch && !HadError) {
7782         Diag(MD->getLocation(),
7783              diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
7784       }
7785     } else {
7786       // C++11 [dcl.fct.def.default]p4:
7787       //   [For a] user-provided explicitly-defaulted function [...] if such a
7788       //   function is implicitly defined as deleted, the program is ill-formed.
7789       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
7790       assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
7791       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7792       HadError = true;
7793     }
7794   }
7795 
7796   return HadError;
7797 }
7798 
7799 namespace {
7800 /// Helper class for building and checking a defaulted comparison.
7801 ///
7802 /// Defaulted functions are built in two phases:
7803 ///
7804 ///  * First, the set of operations that the function will perform are
7805 ///    identified, and some of them are checked. If any of the checked
7806 ///    operations is invalid in certain ways, the comparison function is
7807 ///    defined as deleted and no body is built.
7808 ///  * Then, if the function is not defined as deleted, the body is built.
7809 ///
7810 /// This is accomplished by performing two visitation steps over the eventual
7811 /// body of the function.
7812 template<typename Derived, typename ResultList, typename Result,
7813          typename Subobject>
7814 class DefaultedComparisonVisitor {
7815 public:
7816   using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
7817 
7818   DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7819                              DefaultedComparisonKind DCK)
7820       : S(S), RD(RD), FD(FD), DCK(DCK) {
7821     if (auto *Info = FD->getDefaultedFunctionInfo()) {
7822       // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
7823       // UnresolvedSet to avoid this copy.
7824       Fns.assign(Info->getUnqualifiedLookups().begin(),
7825                  Info->getUnqualifiedLookups().end());
7826     }
7827   }
7828 
7829   ResultList visit() {
7830     // The type of an lvalue naming a parameter of this function.
7831     QualType ParamLvalType =
7832         FD->getParamDecl(0)->getType().getNonReferenceType();
7833 
7834     ResultList Results;
7835 
7836     switch (DCK) {
7837     case DefaultedComparisonKind::None:
7838       llvm_unreachable("not a defaulted comparison");
7839 
7840     case DefaultedComparisonKind::Equal:
7841     case DefaultedComparisonKind::ThreeWay:
7842       getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
7843       return Results;
7844 
7845     case DefaultedComparisonKind::NotEqual:
7846     case DefaultedComparisonKind::Relational:
7847       Results.add(getDerived().visitExpandedSubobject(
7848           ParamLvalType, getDerived().getCompleteObject()));
7849       return Results;
7850     }
7851     llvm_unreachable("");
7852   }
7853 
7854 protected:
7855   Derived &getDerived() { return static_cast<Derived&>(*this); }
7856 
7857   /// Visit the expanded list of subobjects of the given type, as specified in
7858   /// C++2a [class.compare.default].
7859   ///
7860   /// \return \c true if the ResultList object said we're done, \c false if not.
7861   bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
7862                        Qualifiers Quals) {
7863     // C++2a [class.compare.default]p4:
7864     //   The direct base class subobjects of C
7865     for (CXXBaseSpecifier &Base : Record->bases())
7866       if (Results.add(getDerived().visitSubobject(
7867               S.Context.getQualifiedType(Base.getType(), Quals),
7868               getDerived().getBase(&Base))))
7869         return true;
7870 
7871     //   followed by the non-static data members of C
7872     for (FieldDecl *Field : Record->fields()) {
7873       // C++23 [class.bit]p2:
7874       //   Unnamed bit-fields are not members ...
7875       if (Field->isUnnamedBitfield())
7876         continue;
7877       // Recursively expand anonymous structs.
7878       if (Field->isAnonymousStructOrUnion()) {
7879         if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
7880                             Quals))
7881           return true;
7882         continue;
7883       }
7884 
7885       // Figure out the type of an lvalue denoting this field.
7886       Qualifiers FieldQuals = Quals;
7887       if (Field->isMutable())
7888         FieldQuals.removeConst();
7889       QualType FieldType =
7890           S.Context.getQualifiedType(Field->getType(), FieldQuals);
7891 
7892       if (Results.add(getDerived().visitSubobject(
7893               FieldType, getDerived().getField(Field))))
7894         return true;
7895     }
7896 
7897     //   form a list of subobjects.
7898     return false;
7899   }
7900 
7901   Result visitSubobject(QualType Type, Subobject Subobj) {
7902     //   In that list, any subobject of array type is recursively expanded
7903     const ArrayType *AT = S.Context.getAsArrayType(Type);
7904     if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
7905       return getDerived().visitSubobjectArray(CAT->getElementType(),
7906                                               CAT->getSize(), Subobj);
7907     return getDerived().visitExpandedSubobject(Type, Subobj);
7908   }
7909 
7910   Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
7911                              Subobject Subobj) {
7912     return getDerived().visitSubobject(Type, Subobj);
7913   }
7914 
7915 protected:
7916   Sema &S;
7917   CXXRecordDecl *RD;
7918   FunctionDecl *FD;
7919   DefaultedComparisonKind DCK;
7920   UnresolvedSet<16> Fns;
7921 };
7922 
7923 /// Information about a defaulted comparison, as determined by
7924 /// DefaultedComparisonAnalyzer.
7925 struct DefaultedComparisonInfo {
7926   bool Deleted = false;
7927   bool Constexpr = true;
7928   ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
7929 
7930   static DefaultedComparisonInfo deleted() {
7931     DefaultedComparisonInfo Deleted;
7932     Deleted.Deleted = true;
7933     return Deleted;
7934   }
7935 
7936   bool add(const DefaultedComparisonInfo &R) {
7937     Deleted |= R.Deleted;
7938     Constexpr &= R.Constexpr;
7939     Category = commonComparisonType(Category, R.Category);
7940     return Deleted;
7941   }
7942 };
7943 
7944 /// An element in the expanded list of subobjects of a defaulted comparison, as
7945 /// specified in C++2a [class.compare.default]p4.
7946 struct DefaultedComparisonSubobject {
7947   enum { CompleteObject, Member, Base } Kind;
7948   NamedDecl *Decl;
7949   SourceLocation Loc;
7950 };
7951 
7952 /// A visitor over the notional body of a defaulted comparison that determines
7953 /// whether that body would be deleted or constexpr.
7954 class DefaultedComparisonAnalyzer
7955     : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
7956                                         DefaultedComparisonInfo,
7957                                         DefaultedComparisonInfo,
7958                                         DefaultedComparisonSubobject> {
7959 public:
7960   enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
7961 
7962 private:
7963   DiagnosticKind Diagnose;
7964 
7965 public:
7966   using Base = DefaultedComparisonVisitor;
7967   using Result = DefaultedComparisonInfo;
7968   using Subobject = DefaultedComparisonSubobject;
7969 
7970   friend Base;
7971 
7972   DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7973                               DefaultedComparisonKind DCK,
7974                               DiagnosticKind Diagnose = NoDiagnostics)
7975       : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
7976 
7977   Result visit() {
7978     if ((DCK == DefaultedComparisonKind::Equal ||
7979          DCK == DefaultedComparisonKind::ThreeWay) &&
7980         RD->hasVariantMembers()) {
7981       // C++2a [class.compare.default]p2 [P2002R0]:
7982       //   A defaulted comparison operator function for class C is defined as
7983       //   deleted if [...] C has variant members.
7984       if (Diagnose == ExplainDeleted) {
7985         S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
7986           << FD << RD->isUnion() << RD;
7987       }
7988       return Result::deleted();
7989     }
7990 
7991     return Base::visit();
7992   }
7993 
7994 private:
7995   Subobject getCompleteObject() {
7996     return Subobject{Subobject::CompleteObject, RD, FD->getLocation()};
7997   }
7998 
7999   Subobject getBase(CXXBaseSpecifier *Base) {
8000     return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
8001                      Base->getBaseTypeLoc()};
8002   }
8003 
8004   Subobject getField(FieldDecl *Field) {
8005     return Subobject{Subobject::Member, Field, Field->getLocation()};
8006   }
8007 
8008   Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
8009     // C++2a [class.compare.default]p2 [P2002R0]:
8010     //   A defaulted <=> or == operator function for class C is defined as
8011     //   deleted if any non-static data member of C is of reference type
8012     if (Type->isReferenceType()) {
8013       if (Diagnose == ExplainDeleted) {
8014         S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
8015             << FD << RD;
8016       }
8017       return Result::deleted();
8018     }
8019 
8020     // [...] Let xi be an lvalue denoting the ith element [...]
8021     OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
8022     Expr *Args[] = {&Xi, &Xi};
8023 
8024     // All operators start by trying to apply that same operator recursively.
8025     OverloadedOperatorKind OO = FD->getOverloadedOperator();
8026     assert(OO != OO_None && "not an overloaded operator!");
8027     return visitBinaryOperator(OO, Args, Subobj);
8028   }
8029 
8030   Result
8031   visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
8032                       Subobject Subobj,
8033                       OverloadCandidateSet *SpaceshipCandidates = nullptr) {
8034     // Note that there is no need to consider rewritten candidates here if
8035     // we've already found there is no viable 'operator<=>' candidate (and are
8036     // considering synthesizing a '<=>' from '==' and '<').
8037     OverloadCandidateSet CandidateSet(
8038         FD->getLocation(), OverloadCandidateSet::CSK_Operator,
8039         OverloadCandidateSet::OperatorRewriteInfo(
8040             OO, FD->getLocation(),
8041             /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
8042 
8043     /// C++2a [class.compare.default]p1 [P2002R0]:
8044     ///   [...] the defaulted function itself is never a candidate for overload
8045     ///   resolution [...]
8046     CandidateSet.exclude(FD);
8047 
8048     if (Args[0]->getType()->isOverloadableType())
8049       S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
8050     else
8051       // FIXME: We determine whether this is a valid expression by checking to
8052       // see if there's a viable builtin operator candidate for it. That isn't
8053       // really what the rules ask us to do, but should give the right results.
8054       S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
8055 
8056     Result R;
8057 
8058     OverloadCandidateSet::iterator Best;
8059     switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
8060     case OR_Success: {
8061       // C++2a [class.compare.secondary]p2 [P2002R0]:
8062       //   The operator function [...] is defined as deleted if [...] the
8063       //   candidate selected by overload resolution is not a rewritten
8064       //   candidate.
8065       if ((DCK == DefaultedComparisonKind::NotEqual ||
8066            DCK == DefaultedComparisonKind::Relational) &&
8067           !Best->RewriteKind) {
8068         if (Diagnose == ExplainDeleted) {
8069           if (Best->Function) {
8070             S.Diag(Best->Function->getLocation(),
8071                    diag::note_defaulted_comparison_not_rewritten_callee)
8072                 << FD;
8073           } else {
8074             assert(Best->Conversions.size() == 2 &&
8075                    Best->Conversions[0].isUserDefined() &&
8076                    "non-user-defined conversion from class to built-in "
8077                    "comparison");
8078             S.Diag(Best->Conversions[0]
8079                        .UserDefined.FoundConversionFunction.getDecl()
8080                        ->getLocation(),
8081                    diag::note_defaulted_comparison_not_rewritten_conversion)
8082                 << FD;
8083           }
8084         }
8085         return Result::deleted();
8086       }
8087 
8088       // Throughout C++2a [class.compare]: if overload resolution does not
8089       // result in a usable function, the candidate function is defined as
8090       // deleted. This requires that we selected an accessible function.
8091       //
8092       // Note that this only considers the access of the function when named
8093       // within the type of the subobject, and not the access path for any
8094       // derived-to-base conversion.
8095       CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
8096       if (ArgClass && Best->FoundDecl.getDecl() &&
8097           Best->FoundDecl.getDecl()->isCXXClassMember()) {
8098         QualType ObjectType = Subobj.Kind == Subobject::Member
8099                                   ? Args[0]->getType()
8100                                   : S.Context.getRecordType(RD);
8101         if (!S.isMemberAccessibleForDeletion(
8102                 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
8103                 Diagnose == ExplainDeleted
8104                     ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
8105                           << FD << Subobj.Kind << Subobj.Decl
8106                     : S.PDiag()))
8107           return Result::deleted();
8108       }
8109 
8110       bool NeedsDeducing =
8111           OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
8112 
8113       if (FunctionDecl *BestFD = Best->Function) {
8114         // C++2a [class.compare.default]p3 [P2002R0]:
8115         //   A defaulted comparison function is constexpr-compatible if
8116         //   [...] no overlod resolution performed [...] results in a
8117         //   non-constexpr function.
8118         assert(!BestFD->isDeleted() && "wrong overload resolution result");
8119         // If it's not constexpr, explain why not.
8120         if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
8121           if (Subobj.Kind != Subobject::CompleteObject)
8122             S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
8123               << Subobj.Kind << Subobj.Decl;
8124           S.Diag(BestFD->getLocation(),
8125                  diag::note_defaulted_comparison_not_constexpr_here);
8126           // Bail out after explaining; we don't want any more notes.
8127           return Result::deleted();
8128         }
8129         R.Constexpr &= BestFD->isConstexpr();
8130 
8131         if (NeedsDeducing) {
8132           // If any callee has an undeduced return type, deduce it now.
8133           // FIXME: It's not clear how a failure here should be handled. For
8134           // now, we produce an eager diagnostic, because that is forward
8135           // compatible with most (all?) other reasonable options.
8136           if (BestFD->getReturnType()->isUndeducedType() &&
8137               S.DeduceReturnType(BestFD, FD->getLocation(),
8138                                  /*Diagnose=*/false)) {
8139             // Don't produce a duplicate error when asked to explain why the
8140             // comparison is deleted: we diagnosed that when initially checking
8141             // the defaulted operator.
8142             if (Diagnose == NoDiagnostics) {
8143               S.Diag(
8144                   FD->getLocation(),
8145                   diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
8146                   << Subobj.Kind << Subobj.Decl;
8147               S.Diag(
8148                   Subobj.Loc,
8149                   diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
8150                   << Subobj.Kind << Subobj.Decl;
8151               S.Diag(BestFD->getLocation(),
8152                      diag::note_defaulted_comparison_cannot_deduce_callee)
8153                   << Subobj.Kind << Subobj.Decl;
8154             }
8155             return Result::deleted();
8156           }
8157           auto *Info = S.Context.CompCategories.lookupInfoForType(
8158               BestFD->getCallResultType());
8159           if (!Info) {
8160             if (Diagnose == ExplainDeleted) {
8161               S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
8162                   << Subobj.Kind << Subobj.Decl
8163                   << BestFD->getCallResultType().withoutLocalFastQualifiers();
8164               S.Diag(BestFD->getLocation(),
8165                      diag::note_defaulted_comparison_cannot_deduce_callee)
8166                   << Subobj.Kind << Subobj.Decl;
8167             }
8168             return Result::deleted();
8169           }
8170           R.Category = Info->Kind;
8171         }
8172       } else {
8173         QualType T = Best->BuiltinParamTypes[0];
8174         assert(T == Best->BuiltinParamTypes[1] &&
8175                "builtin comparison for different types?");
8176         assert(Best->BuiltinParamTypes[2].isNull() &&
8177                "invalid builtin comparison");
8178 
8179         if (NeedsDeducing) {
8180           std::optional<ComparisonCategoryType> Cat =
8181               getComparisonCategoryForBuiltinCmp(T);
8182           assert(Cat && "no category for builtin comparison?");
8183           R.Category = *Cat;
8184         }
8185       }
8186 
8187       // Note that we might be rewriting to a different operator. That call is
8188       // not considered until we come to actually build the comparison function.
8189       break;
8190     }
8191 
8192     case OR_Ambiguous:
8193       if (Diagnose == ExplainDeleted) {
8194         unsigned Kind = 0;
8195         if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
8196           Kind = OO == OO_EqualEqual ? 1 : 2;
8197         CandidateSet.NoteCandidates(
8198             PartialDiagnosticAt(
8199                 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
8200                                 << FD << Kind << Subobj.Kind << Subobj.Decl),
8201             S, OCD_AmbiguousCandidates, Args);
8202       }
8203       R = Result::deleted();
8204       break;
8205 
8206     case OR_Deleted:
8207       if (Diagnose == ExplainDeleted) {
8208         if ((DCK == DefaultedComparisonKind::NotEqual ||
8209              DCK == DefaultedComparisonKind::Relational) &&
8210             !Best->RewriteKind) {
8211           S.Diag(Best->Function->getLocation(),
8212                  diag::note_defaulted_comparison_not_rewritten_callee)
8213               << FD;
8214         } else {
8215           S.Diag(Subobj.Loc,
8216                  diag::note_defaulted_comparison_calls_deleted)
8217               << FD << Subobj.Kind << Subobj.Decl;
8218           S.NoteDeletedFunction(Best->Function);
8219         }
8220       }
8221       R = Result::deleted();
8222       break;
8223 
8224     case OR_No_Viable_Function:
8225       // If there's no usable candidate, we're done unless we can rewrite a
8226       // '<=>' in terms of '==' and '<'.
8227       if (OO == OO_Spaceship &&
8228           S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) {
8229         // For any kind of comparison category return type, we need a usable
8230         // '==' and a usable '<'.
8231         if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
8232                                        &CandidateSet)))
8233           R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
8234         break;
8235       }
8236 
8237       if (Diagnose == ExplainDeleted) {
8238         S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
8239             << FD << (OO == OO_EqualEqual || OO == OO_ExclaimEqual)
8240             << Subobj.Kind << Subobj.Decl;
8241 
8242         // For a three-way comparison, list both the candidates for the
8243         // original operator and the candidates for the synthesized operator.
8244         if (SpaceshipCandidates) {
8245           SpaceshipCandidates->NoteCandidates(
8246               S, Args,
8247               SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
8248                                                       Args, FD->getLocation()));
8249           S.Diag(Subobj.Loc,
8250                  diag::note_defaulted_comparison_no_viable_function_synthesized)
8251               << (OO == OO_EqualEqual ? 0 : 1);
8252         }
8253 
8254         CandidateSet.NoteCandidates(
8255             S, Args,
8256             CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
8257                                             FD->getLocation()));
8258       }
8259       R = Result::deleted();
8260       break;
8261     }
8262 
8263     return R;
8264   }
8265 };
8266 
8267 /// A list of statements.
8268 struct StmtListResult {
8269   bool IsInvalid = false;
8270   llvm::SmallVector<Stmt*, 16> Stmts;
8271 
8272   bool add(const StmtResult &S) {
8273     IsInvalid |= S.isInvalid();
8274     if (IsInvalid)
8275       return true;
8276     Stmts.push_back(S.get());
8277     return false;
8278   }
8279 };
8280 
8281 /// A visitor over the notional body of a defaulted comparison that synthesizes
8282 /// the actual body.
8283 class DefaultedComparisonSynthesizer
8284     : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
8285                                         StmtListResult, StmtResult,
8286                                         std::pair<ExprResult, ExprResult>> {
8287   SourceLocation Loc;
8288   unsigned ArrayDepth = 0;
8289 
8290 public:
8291   using Base = DefaultedComparisonVisitor;
8292   using ExprPair = std::pair<ExprResult, ExprResult>;
8293 
8294   friend Base;
8295 
8296   DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8297                                  DefaultedComparisonKind DCK,
8298                                  SourceLocation BodyLoc)
8299       : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
8300 
8301   /// Build a suitable function body for this defaulted comparison operator.
8302   StmtResult build() {
8303     Sema::CompoundScopeRAII CompoundScope(S);
8304 
8305     StmtListResult Stmts = visit();
8306     if (Stmts.IsInvalid)
8307       return StmtError();
8308 
8309     ExprResult RetVal;
8310     switch (DCK) {
8311     case DefaultedComparisonKind::None:
8312       llvm_unreachable("not a defaulted comparison");
8313 
8314     case DefaultedComparisonKind::Equal: {
8315       // C++2a [class.eq]p3:
8316       //   [...] compar[e] the corresponding elements [...] until the first
8317       //   index i where xi == yi yields [...] false. If no such index exists,
8318       //   V is true. Otherwise, V is false.
8319       //
8320       // Join the comparisons with '&&'s and return the result. Use a right
8321       // fold (traversing the conditions right-to-left), because that
8322       // short-circuits more naturally.
8323       auto OldStmts = std::move(Stmts.Stmts);
8324       Stmts.Stmts.clear();
8325       ExprResult CmpSoFar;
8326       // Finish a particular comparison chain.
8327       auto FinishCmp = [&] {
8328         if (Expr *Prior = CmpSoFar.get()) {
8329           // Convert the last expression to 'return ...;'
8330           if (RetVal.isUnset() && Stmts.Stmts.empty())
8331             RetVal = CmpSoFar;
8332           // Convert any prior comparison to 'if (!(...)) return false;'
8333           else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
8334             return true;
8335           CmpSoFar = ExprResult();
8336         }
8337         return false;
8338       };
8339       for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
8340         Expr *E = dyn_cast<Expr>(EAsStmt);
8341         if (!E) {
8342           // Found an array comparison.
8343           if (FinishCmp() || Stmts.add(EAsStmt))
8344             return StmtError();
8345           continue;
8346         }
8347 
8348         if (CmpSoFar.isUnset()) {
8349           CmpSoFar = E;
8350           continue;
8351         }
8352         CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
8353         if (CmpSoFar.isInvalid())
8354           return StmtError();
8355       }
8356       if (FinishCmp())
8357         return StmtError();
8358       std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
8359       //   If no such index exists, V is true.
8360       if (RetVal.isUnset())
8361         RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
8362       break;
8363     }
8364 
8365     case DefaultedComparisonKind::ThreeWay: {
8366       // Per C++2a [class.spaceship]p3, as a fallback add:
8367       // return static_cast<R>(std::strong_ordering::equal);
8368       QualType StrongOrdering = S.CheckComparisonCategoryType(
8369           ComparisonCategoryType::StrongOrdering, Loc,
8370           Sema::ComparisonCategoryUsage::DefaultedOperator);
8371       if (StrongOrdering.isNull())
8372         return StmtError();
8373       VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)
8374                              .getValueInfo(ComparisonCategoryResult::Equal)
8375                              ->VD;
8376       RetVal = getDecl(EqualVD);
8377       if (RetVal.isInvalid())
8378         return StmtError();
8379       RetVal = buildStaticCastToR(RetVal.get());
8380       break;
8381     }
8382 
8383     case DefaultedComparisonKind::NotEqual:
8384     case DefaultedComparisonKind::Relational:
8385       RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
8386       break;
8387     }
8388 
8389     // Build the final return statement.
8390     if (RetVal.isInvalid())
8391       return StmtError();
8392     StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
8393     if (ReturnStmt.isInvalid())
8394       return StmtError();
8395     Stmts.Stmts.push_back(ReturnStmt.get());
8396 
8397     return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
8398   }
8399 
8400 private:
8401   ExprResult getDecl(ValueDecl *VD) {
8402     return S.BuildDeclarationNameExpr(
8403         CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8404   }
8405 
8406   ExprResult getParam(unsigned I) {
8407     ParmVarDecl *PD = FD->getParamDecl(I);
8408     return getDecl(PD);
8409   }
8410 
8411   ExprPair getCompleteObject() {
8412     unsigned Param = 0;
8413     ExprResult LHS;
8414     if (isa<CXXMethodDecl>(FD)) {
8415       // LHS is '*this'.
8416       LHS = S.ActOnCXXThis(Loc);
8417       if (!LHS.isInvalid())
8418         LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
8419     } else {
8420       LHS = getParam(Param++);
8421     }
8422     ExprResult RHS = getParam(Param++);
8423     assert(Param == FD->getNumParams());
8424     return {LHS, RHS};
8425   }
8426 
8427   ExprPair getBase(CXXBaseSpecifier *Base) {
8428     ExprPair Obj = getCompleteObject();
8429     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8430       return {ExprError(), ExprError()};
8431     CXXCastPath Path = {Base};
8432     return {S.ImpCastExprToType(Obj.first.get(), Base->getType(),
8433                                 CK_DerivedToBase, VK_LValue, &Path),
8434             S.ImpCastExprToType(Obj.second.get(), Base->getType(),
8435                                 CK_DerivedToBase, VK_LValue, &Path)};
8436   }
8437 
8438   ExprPair getField(FieldDecl *Field) {
8439     ExprPair Obj = getCompleteObject();
8440     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8441       return {ExprError(), ExprError()};
8442 
8443     DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8444     DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8445     return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8446                                       CXXScopeSpec(), Field, Found, NameInfo),
8447             S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8448                                       CXXScopeSpec(), Field, Found, NameInfo)};
8449   }
8450 
8451   // FIXME: When expanding a subobject, register a note in the code synthesis
8452   // stack to say which subobject we're comparing.
8453 
8454   StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8455     if (Cond.isInvalid())
8456       return StmtError();
8457 
8458     ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8459     if (NotCond.isInvalid())
8460       return StmtError();
8461 
8462     ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8463     assert(!False.isInvalid() && "should never fail");
8464     StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8465     if (ReturnFalse.isInvalid())
8466       return StmtError();
8467 
8468     return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, nullptr,
8469                          S.ActOnCondition(nullptr, Loc, NotCond.get(),
8470                                           Sema::ConditionKind::Boolean),
8471                          Loc, ReturnFalse.get(), SourceLocation(), nullptr);
8472   }
8473 
8474   StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8475                                  ExprPair Subobj) {
8476     QualType SizeType = S.Context.getSizeType();
8477     Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8478 
8479     // Build 'size_t i$n = 0'.
8480     IdentifierInfo *IterationVarName = nullptr;
8481     {
8482       SmallString<8> Str;
8483       llvm::raw_svector_ostream OS(Str);
8484       OS << "i" << ArrayDepth;
8485       IterationVarName = &S.Context.Idents.get(OS.str());
8486     }
8487     VarDecl *IterationVar = VarDecl::Create(
8488         S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8489         S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
8490     llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8491     IterationVar->setInit(
8492         IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8493     Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8494 
8495     auto IterRef = [&] {
8496       ExprResult Ref = S.BuildDeclarationNameExpr(
8497           CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8498           IterationVar);
8499       assert(!Ref.isInvalid() && "can't reference our own variable?");
8500       return Ref.get();
8501     };
8502 
8503     // Build 'i$n != Size'.
8504     ExprResult Cond = S.CreateBuiltinBinOp(
8505         Loc, BO_NE, IterRef(),
8506         IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8507     assert(!Cond.isInvalid() && "should never fail");
8508 
8509     // Build '++i$n'.
8510     ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8511     assert(!Inc.isInvalid() && "should never fail");
8512 
8513     // Build 'a[i$n]' and 'b[i$n]'.
8514     auto Index = [&](ExprResult E) {
8515       if (E.isInvalid())
8516         return ExprError();
8517       return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8518     };
8519     Subobj.first = Index(Subobj.first);
8520     Subobj.second = Index(Subobj.second);
8521 
8522     // Compare the array elements.
8523     ++ArrayDepth;
8524     StmtResult Substmt = visitSubobject(Type, Subobj);
8525     --ArrayDepth;
8526 
8527     if (Substmt.isInvalid())
8528       return StmtError();
8529 
8530     // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8531     // For outer levels or for an 'operator<=>' we already have a suitable
8532     // statement that returns as necessary.
8533     if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8534       assert(DCK == DefaultedComparisonKind::Equal &&
8535              "should have non-expression statement");
8536       Substmt = buildIfNotCondReturnFalse(ElemCmp);
8537       if (Substmt.isInvalid())
8538         return StmtError();
8539     }
8540 
8541     // Build 'for (...) ...'
8542     return S.ActOnForStmt(Loc, Loc, Init,
8543                           S.ActOnCondition(nullptr, Loc, Cond.get(),
8544                                            Sema::ConditionKind::Boolean),
8545                           S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
8546                           Substmt.get());
8547   }
8548 
8549   StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8550     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8551       return StmtError();
8552 
8553     OverloadedOperatorKind OO = FD->getOverloadedOperator();
8554     BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO);
8555     ExprResult Op;
8556     if (Type->isOverloadableType())
8557       Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8558                                    Obj.second.get(), /*PerformADL=*/true,
8559                                    /*AllowRewrittenCandidates=*/true, FD);
8560     else
8561       Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8562     if (Op.isInvalid())
8563       return StmtError();
8564 
8565     switch (DCK) {
8566     case DefaultedComparisonKind::None:
8567       llvm_unreachable("not a defaulted comparison");
8568 
8569     case DefaultedComparisonKind::Equal:
8570       // Per C++2a [class.eq]p2, each comparison is individually contextually
8571       // converted to bool.
8572       Op = S.PerformContextuallyConvertToBool(Op.get());
8573       if (Op.isInvalid())
8574         return StmtError();
8575       return Op.get();
8576 
8577     case DefaultedComparisonKind::ThreeWay: {
8578       // Per C++2a [class.spaceship]p3, form:
8579       //   if (R cmp = static_cast<R>(op); cmp != 0)
8580       //     return cmp;
8581       QualType R = FD->getReturnType();
8582       Op = buildStaticCastToR(Op.get());
8583       if (Op.isInvalid())
8584         return StmtError();
8585 
8586       // R cmp = ...;
8587       IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8588       VarDecl *VD =
8589           VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8590                           S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None);
8591       S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8592       Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8593 
8594       // cmp != 0
8595       ExprResult VDRef = getDecl(VD);
8596       if (VDRef.isInvalid())
8597         return StmtError();
8598       llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8599       Expr *Zero =
8600           IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8601       ExprResult Comp;
8602       if (VDRef.get()->getType()->isOverloadableType())
8603         Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8604                                        true, FD);
8605       else
8606         Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8607       if (Comp.isInvalid())
8608         return StmtError();
8609       Sema::ConditionResult Cond = S.ActOnCondition(
8610           nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8611       if (Cond.isInvalid())
8612         return StmtError();
8613 
8614       // return cmp;
8615       VDRef = getDecl(VD);
8616       if (VDRef.isInvalid())
8617         return StmtError();
8618       StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
8619       if (ReturnStmt.isInvalid())
8620         return StmtError();
8621 
8622       // if (...)
8623       return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, InitStmt, Cond,
8624                            Loc, ReturnStmt.get(),
8625                            /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
8626     }
8627 
8628     case DefaultedComparisonKind::NotEqual:
8629     case DefaultedComparisonKind::Relational:
8630       // C++2a [class.compare.secondary]p2:
8631       //   Otherwise, the operator function yields x @ y.
8632       return Op.get();
8633     }
8634     llvm_unreachable("");
8635   }
8636 
8637   /// Build "static_cast<R>(E)".
8638   ExprResult buildStaticCastToR(Expr *E) {
8639     QualType R = FD->getReturnType();
8640     assert(!R->isUndeducedType() && "type should have been deduced already");
8641 
8642     // Don't bother forming a no-op cast in the common case.
8643     if (E->isPRValue() && S.Context.hasSameType(E->getType(), R))
8644       return E;
8645     return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8646                                S.Context.getTrivialTypeSourceInfo(R, Loc), E,
8647                                SourceRange(Loc, Loc), SourceRange(Loc, Loc));
8648   }
8649 };
8650 }
8651 
8652 /// Perform the unqualified lookups that might be needed to form a defaulted
8653 /// comparison function for the given operator.
8654 static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S,
8655                                                   UnresolvedSetImpl &Operators,
8656                                                   OverloadedOperatorKind Op) {
8657   auto Lookup = [&](OverloadedOperatorKind OO) {
8658     Self.LookupOverloadedOperatorName(OO, S, Operators);
8659   };
8660 
8661   // Every defaulted operator looks up itself.
8662   Lookup(Op);
8663   // ... and the rewritten form of itself, if any.
8664   if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op))
8665     Lookup(ExtraOp);
8666 
8667   // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8668   // synthesize a three-way comparison from '<' and '=='. In a dependent
8669   // context, we also need to look up '==' in case we implicitly declare a
8670   // defaulted 'operator=='.
8671   if (Op == OO_Spaceship) {
8672     Lookup(OO_ExclaimEqual);
8673     Lookup(OO_Less);
8674     Lookup(OO_EqualEqual);
8675   }
8676 }
8677 
8678 bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD,
8679                                               DefaultedComparisonKind DCK) {
8680   assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
8681 
8682   // Perform any unqualified lookups we're going to need to default this
8683   // function.
8684   if (S) {
8685     UnresolvedSet<32> Operators;
8686     lookupOperatorsForDefaultedComparison(*this, S, Operators,
8687                                           FD->getOverloadedOperator());
8688     FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create(
8689         Context, Operators.pairs()));
8690   }
8691 
8692   // C++2a [class.compare.default]p1:
8693   //   A defaulted comparison operator function for some class C shall be a
8694   //   non-template function declared in the member-specification of C that is
8695   //    -- a non-static const non-volatile member of C having one parameter of
8696   //       type const C& and either no ref-qualifier or the ref-qualifier &, or
8697   //    -- a friend of C having two parameters of type const C& or two
8698   //       parameters of type C.
8699 
8700   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
8701   bool IsMethod = isa<CXXMethodDecl>(FD);
8702   if (IsMethod) {
8703     auto *MD = cast<CXXMethodDecl>(FD);
8704     assert(!MD->isStatic() && "comparison function cannot be a static member");
8705 
8706     if (MD->getRefQualifier() == RQ_RValue) {
8707       Diag(MD->getLocation(), diag::err_ref_qualifier_comparison_operator);
8708 
8709       // Remove the ref qualifier to recover.
8710       const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8711       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8712       EPI.RefQualifier = RQ_None;
8713       MD->setType(Context.getFunctionType(FPT->getReturnType(),
8714                                           FPT->getParamTypes(), EPI));
8715     }
8716 
8717     // If we're out-of-class, this is the class we're comparing.
8718     if (!RD)
8719       RD = MD->getParent();
8720 
8721     if (!MD->isConst()) {
8722       SourceLocation InsertLoc;
8723       if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
8724         InsertLoc = getLocForEndOfToken(Loc.getRParenLoc());
8725       // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8726       // corresponding defaulted 'operator<=>' already.
8727       if (!MD->isImplicit()) {
8728         Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const)
8729             << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
8730       }
8731 
8732       // Add the 'const' to the type to recover.
8733       const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8734       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8735       EPI.TypeQuals.addConst();
8736       MD->setType(Context.getFunctionType(FPT->getReturnType(),
8737                                           FPT->getParamTypes(), EPI));
8738     }
8739 
8740     if (MD->isVolatile()) {
8741       Diag(MD->getLocation(), diag::err_volatile_comparison_operator);
8742 
8743       // Remove the 'volatile' from the type to recover.
8744       const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8745       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8746       EPI.TypeQuals.removeVolatile();
8747       MD->setType(Context.getFunctionType(FPT->getReturnType(),
8748                                           FPT->getParamTypes(), EPI));
8749     }
8750   }
8751 
8752   if (FD->getNumParams() != (IsMethod ? 1 : 2)) {
8753     // Let's not worry about using a variadic template pack here -- who would do
8754     // such a thing?
8755     Diag(FD->getLocation(), diag::err_defaulted_comparison_num_args)
8756         << int(IsMethod) << int(DCK);
8757     return true;
8758   }
8759 
8760   const ParmVarDecl *KnownParm = nullptr;
8761   for (const ParmVarDecl *Param : FD->parameters()) {
8762     QualType ParmTy = Param->getType();
8763 
8764     if (!KnownParm) {
8765       auto CTy = ParmTy;
8766       // Is it `T const &`?
8767       bool Ok = !IsMethod;
8768       QualType ExpectedTy;
8769       if (RD)
8770         ExpectedTy = Context.getRecordType(RD);
8771       if (auto *Ref = CTy->getAs<ReferenceType>()) {
8772         CTy = Ref->getPointeeType();
8773         if (RD)
8774           ExpectedTy.addConst();
8775         Ok = true;
8776       }
8777 
8778       // Is T a class?
8779       if (!Ok) {
8780       } else if (RD) {
8781         if (!RD->isDependentType() && !Context.hasSameType(CTy, ExpectedTy))
8782           Ok = false;
8783       } else if (auto *CRD = CTy->getAsRecordDecl()) {
8784         RD = cast<CXXRecordDecl>(CRD);
8785       } else {
8786         Ok = false;
8787       }
8788 
8789       if (Ok) {
8790         KnownParm = Param;
8791       } else {
8792         // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8793         // corresponding defaulted 'operator<=>' already.
8794         if (!FD->isImplicit()) {
8795           if (RD) {
8796             QualType PlainTy = Context.getRecordType(RD);
8797             QualType RefTy =
8798                 Context.getLValueReferenceType(PlainTy.withConst());
8799             Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
8800                 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
8801                 << Param->getSourceRange();
8802           } else {
8803             assert(!IsMethod && "should know expected type for method");
8804             Diag(FD->getLocation(),
8805                  diag::err_defaulted_comparison_param_unknown)
8806                 << int(DCK) << ParmTy << Param->getSourceRange();
8807           }
8808         }
8809         return true;
8810       }
8811     } else if (!Context.hasSameType(KnownParm->getType(), ParmTy)) {
8812       Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
8813           << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
8814           << ParmTy << Param->getSourceRange();
8815       return true;
8816     }
8817   }
8818 
8819   assert(RD && "must have determined class");
8820   if (IsMethod) {
8821   } else if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
8822     // In-class, must be a friend decl.
8823     assert(FD->getFriendObjectKind() && "expected a friend declaration");
8824   } else {
8825     // Out of class, require the defaulted comparison to be a friend (of a
8826     // complete type).
8827     if (RequireCompleteType(FD->getLocation(), Context.getRecordType(RD),
8828                             diag::err_defaulted_comparison_not_friend, int(DCK),
8829                             int(1)))
8830       return true;
8831 
8832     if (llvm::none_of(RD->friends(), [&](const FriendDecl *F) {
8833           return FD->getCanonicalDecl() ==
8834                  F->getFriendDecl()->getCanonicalDecl();
8835         })) {
8836       Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend)
8837           << int(DCK) << int(0) << RD;
8838       Diag(RD->getCanonicalDecl()->getLocation(), diag::note_declared_at);
8839       return true;
8840     }
8841   }
8842 
8843   // C++2a [class.eq]p1, [class.rel]p1:
8844   //   A [defaulted comparison other than <=>] shall have a declared return
8845   //   type bool.
8846   if (DCK != DefaultedComparisonKind::ThreeWay &&
8847       !FD->getDeclaredReturnType()->isDependentType() &&
8848       !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
8849     Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
8850         << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
8851         << FD->getReturnTypeSourceRange();
8852     return true;
8853   }
8854   // C++2a [class.spaceship]p2 [P2002R0]:
8855   //   Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
8856   //   R shall not contain a placeholder type.
8857   if (QualType RT = FD->getDeclaredReturnType();
8858       DCK == DefaultedComparisonKind::ThreeWay &&
8859       RT->getContainedDeducedType() &&
8860       (!Context.hasSameType(RT, Context.getAutoDeductType()) ||
8861        RT->getContainedAutoType()->isConstrained())) {
8862     Diag(FD->getLocation(),
8863          diag::err_defaulted_comparison_deduced_return_type_not_auto)
8864         << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
8865         << FD->getReturnTypeSourceRange();
8866     return true;
8867   }
8868 
8869   // For a defaulted function in a dependent class, defer all remaining checks
8870   // until instantiation.
8871   if (RD->isDependentType())
8872     return false;
8873 
8874   // Determine whether the function should be defined as deleted.
8875   DefaultedComparisonInfo Info =
8876       DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
8877 
8878   bool First = FD == FD->getCanonicalDecl();
8879 
8880   if (!First) {
8881     if (Info.Deleted) {
8882       // C++11 [dcl.fct.def.default]p4:
8883       //   [For a] user-provided explicitly-defaulted function [...] if such a
8884       //   function is implicitly defined as deleted, the program is ill-formed.
8885       //
8886       // This is really just a consequence of the general rule that you can
8887       // only delete a function on its first declaration.
8888       Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
8889           << FD->isImplicit() << (int)DCK;
8890       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8891                                   DefaultedComparisonAnalyzer::ExplainDeleted)
8892           .visit();
8893       return true;
8894     }
8895     if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
8896       // C++20 [class.compare.default]p1:
8897       //   [...] A definition of a comparison operator as defaulted that appears
8898       //   in a class shall be the first declaration of that function.
8899       Diag(FD->getLocation(), diag::err_non_first_default_compare_in_class)
8900           << (int)DCK;
8901       Diag(FD->getCanonicalDecl()->getLocation(),
8902            diag::note_previous_declaration);
8903       return true;
8904     }
8905   }
8906 
8907   // If we want to delete the function, then do so; there's nothing else to
8908   // check in that case.
8909   if (Info.Deleted) {
8910     SetDeclDeleted(FD, FD->getLocation());
8911     if (!inTemplateInstantiation() && !FD->isImplicit()) {
8912       Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
8913           << (int)DCK;
8914       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8915                                   DefaultedComparisonAnalyzer::ExplainDeleted)
8916           .visit();
8917       if (FD->getDefaultLoc().isValid())
8918         Diag(FD->getDefaultLoc(), diag::note_replace_equals_default_to_delete)
8919             << FixItHint::CreateReplacement(FD->getDefaultLoc(), "delete");
8920     }
8921     return false;
8922   }
8923 
8924   // C++2a [class.spaceship]p2:
8925   //   The return type is deduced as the common comparison type of R0, R1, ...
8926   if (DCK == DefaultedComparisonKind::ThreeWay &&
8927       FD->getDeclaredReturnType()->isUndeducedAutoType()) {
8928     SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();
8929     if (RetLoc.isInvalid())
8930       RetLoc = FD->getBeginLoc();
8931     // FIXME: Should we really care whether we have the complete type and the
8932     // 'enumerator' constants here? A forward declaration seems sufficient.
8933     QualType Cat = CheckComparisonCategoryType(
8934         Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
8935     if (Cat.isNull())
8936       return true;
8937     Context.adjustDeducedFunctionResultType(
8938         FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
8939   }
8940 
8941   // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8942   //   An explicitly-defaulted function that is not defined as deleted may be
8943   //   declared constexpr or consteval only if it is constexpr-compatible.
8944   // C++2a [class.compare.default]p3 [P2002R0]:
8945   //   A defaulted comparison function is constexpr-compatible if it satisfies
8946   //   the requirements for a constexpr function [...]
8947   // The only relevant requirements are that the parameter and return types are
8948   // literal types. The remaining conditions are checked by the analyzer.
8949   //
8950   // We support P2448R2 in language modes earlier than C++23 as an extension.
8951   // The concept of constexpr-compatible was removed.
8952   // C++23 [dcl.fct.def.default]p3 [P2448R2]
8953   //  A function explicitly defaulted on its first declaration is implicitly
8954   //  inline, and is implicitly constexpr if it is constexpr-suitable.
8955   // C++23 [dcl.constexpr]p3
8956   //   A function is constexpr-suitable if
8957   //    - it is not a coroutine, and
8958   //    - if the function is a constructor or destructor, its class does not
8959   //      have any virtual base classes.
8960   if (FD->isConstexpr()) {
8961     if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) &&
8962         CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) &&
8963         !Info.Constexpr) {
8964       Diag(FD->getBeginLoc(),
8965            getLangOpts().CPlusPlus23
8966                ? diag::warn_cxx23_compat_defaulted_comparison_constexpr_mismatch
8967                : diag::ext_defaulted_comparison_constexpr_mismatch)
8968           << FD->isImplicit() << (int)DCK << FD->isConsteval();
8969       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8970                                   DefaultedComparisonAnalyzer::ExplainConstexpr)
8971           .visit();
8972     }
8973   }
8974 
8975   // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8976   //   If a constexpr-compatible function is explicitly defaulted on its first
8977   //   declaration, it is implicitly considered to be constexpr.
8978   // FIXME: Only applying this to the first declaration seems problematic, as
8979   // simple reorderings can affect the meaning of the program.
8980   if (First && !FD->isConstexpr() && Info.Constexpr)
8981     FD->setConstexprKind(ConstexprSpecKind::Constexpr);
8982 
8983   // C++2a [except.spec]p3:
8984   //   If a declaration of a function does not have a noexcept-specifier
8985   //   [and] is defaulted on its first declaration, [...] the exception
8986   //   specification is as specified below
8987   if (FD->getExceptionSpecType() == EST_None) {
8988     auto *FPT = FD->getType()->castAs<FunctionProtoType>();
8989     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8990     EPI.ExceptionSpec.Type = EST_Unevaluated;
8991     EPI.ExceptionSpec.SourceDecl = FD;
8992     FD->setType(Context.getFunctionType(FPT->getReturnType(),
8993                                         FPT->getParamTypes(), EPI));
8994   }
8995 
8996   return false;
8997 }
8998 
8999 void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
9000                                              FunctionDecl *Spaceship) {
9001   Sema::CodeSynthesisContext Ctx;
9002   Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;
9003   Ctx.PointOfInstantiation = Spaceship->getEndLoc();
9004   Ctx.Entity = Spaceship;
9005   pushCodeSynthesisContext(Ctx);
9006 
9007   if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
9008     EqualEqual->setImplicit();
9009 
9010   popCodeSynthesisContext();
9011 }
9012 
9013 void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,
9014                                      DefaultedComparisonKind DCK) {
9015   assert(FD->isDefaulted() && !FD->isDeleted() &&
9016          !FD->doesThisDeclarationHaveABody());
9017   if (FD->willHaveBody() || FD->isInvalidDecl())
9018     return;
9019 
9020   SynthesizedFunctionScope Scope(*this, FD);
9021 
9022   // Add a context note for diagnostics produced after this point.
9023   Scope.addContextNote(UseLoc);
9024 
9025   {
9026     // Build and set up the function body.
9027     // The first parameter has type maybe-ref-to maybe-const T, use that to get
9028     // the type of the class being compared.
9029     auto PT = FD->getParamDecl(0)->getType();
9030     CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
9031     SourceLocation BodyLoc =
9032         FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9033     StmtResult Body =
9034         DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
9035     if (Body.isInvalid()) {
9036       FD->setInvalidDecl();
9037       return;
9038     }
9039     FD->setBody(Body.get());
9040     FD->markUsed(Context);
9041   }
9042 
9043   // The exception specification is needed because we are defining the
9044   // function. Note that this will reuse the body we just built.
9045   ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>());
9046 
9047   if (ASTMutationListener *L = getASTMutationListener())
9048     L->CompletedImplicitDefinition(FD);
9049 }
9050 
9051 static Sema::ImplicitExceptionSpecification
9052 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
9053                                         FunctionDecl *FD,
9054                                         Sema::DefaultedComparisonKind DCK) {
9055   ComputingExceptionSpec CES(S, FD, Loc);
9056   Sema::ImplicitExceptionSpecification ExceptSpec(S);
9057 
9058   if (FD->isInvalidDecl())
9059     return ExceptSpec;
9060 
9061   // The common case is that we just defined the comparison function. In that
9062   // case, just look at whether the body can throw.
9063   if (FD->hasBody()) {
9064     ExceptSpec.CalledStmt(FD->getBody());
9065   } else {
9066     // Otherwise, build a body so we can check it. This should ideally only
9067     // happen when we're not actually marking the function referenced. (This is
9068     // only really important for efficiency: we don't want to build and throw
9069     // away bodies for comparison functions more than we strictly need to.)
9070 
9071     // Pretend to synthesize the function body in an unevaluated context.
9072     // Note that we can't actually just go ahead and define the function here:
9073     // we are not permitted to mark its callees as referenced.
9074     Sema::SynthesizedFunctionScope Scope(S, FD);
9075     EnterExpressionEvaluationContext Context(
9076         S, Sema::ExpressionEvaluationContext::Unevaluated);
9077 
9078     CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
9079     SourceLocation BodyLoc =
9080         FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9081     StmtResult Body =
9082         DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
9083     if (!Body.isInvalid())
9084       ExceptSpec.CalledStmt(Body.get());
9085 
9086     // FIXME: Can we hold onto this body and just transform it to potentially
9087     // evaluated when we're asked to define the function rather than rebuilding
9088     // it? Either that, or we should only build the bits of the body that we
9089     // need (the expressions, not the statements).
9090   }
9091 
9092   return ExceptSpec;
9093 }
9094 
9095 void Sema::CheckDelayedMemberExceptionSpecs() {
9096   decltype(DelayedOverridingExceptionSpecChecks) Overriding;
9097   decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
9098 
9099   std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
9100   std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
9101 
9102   // Perform any deferred checking of exception specifications for virtual
9103   // destructors.
9104   for (auto &Check : Overriding)
9105     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
9106 
9107   // Perform any deferred checking of exception specifications for befriended
9108   // special members.
9109   for (auto &Check : Equivalent)
9110     CheckEquivalentExceptionSpec(Check.second, Check.first);
9111 }
9112 
9113 namespace {
9114 /// CRTP base class for visiting operations performed by a special member
9115 /// function (or inherited constructor).
9116 template<typename Derived>
9117 struct SpecialMemberVisitor {
9118   Sema &S;
9119   CXXMethodDecl *MD;
9120   Sema::CXXSpecialMember CSM;
9121   Sema::InheritedConstructorInfo *ICI;
9122 
9123   // Properties of the special member, computed for convenience.
9124   bool IsConstructor = false, IsAssignment = false, ConstArg = false;
9125 
9126   SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
9127                        Sema::InheritedConstructorInfo *ICI)
9128       : S(S), MD(MD), CSM(CSM), ICI(ICI) {
9129     switch (CSM) {
9130     case Sema::CXXDefaultConstructor:
9131     case Sema::CXXCopyConstructor:
9132     case Sema::CXXMoveConstructor:
9133       IsConstructor = true;
9134       break;
9135     case Sema::CXXCopyAssignment:
9136     case Sema::CXXMoveAssignment:
9137       IsAssignment = true;
9138       break;
9139     case Sema::CXXDestructor:
9140       break;
9141     case Sema::CXXInvalid:
9142       llvm_unreachable("invalid special member kind");
9143     }
9144 
9145     if (MD->getNumParams()) {
9146       if (const ReferenceType *RT =
9147               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
9148         ConstArg = RT->getPointeeType().isConstQualified();
9149     }
9150   }
9151 
9152   Derived &getDerived() { return static_cast<Derived&>(*this); }
9153 
9154   /// Is this a "move" special member?
9155   bool isMove() const {
9156     return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
9157   }
9158 
9159   /// Look up the corresponding special member in the given class.
9160   Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
9161                                              unsigned Quals, bool IsMutable) {
9162     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
9163                                        ConstArg && !IsMutable);
9164   }
9165 
9166   /// Look up the constructor for the specified base class to see if it's
9167   /// overridden due to this being an inherited constructor.
9168   Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
9169     if (!ICI)
9170       return {};
9171     assert(CSM == Sema::CXXDefaultConstructor);
9172     auto *BaseCtor =
9173       cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
9174     if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
9175       return MD;
9176     return {};
9177   }
9178 
9179   /// A base or member subobject.
9180   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
9181 
9182   /// Get the location to use for a subobject in diagnostics.
9183   static SourceLocation getSubobjectLoc(Subobject Subobj) {
9184     // FIXME: For an indirect virtual base, the direct base leading to
9185     // the indirect virtual base would be a more useful choice.
9186     if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
9187       return B->getBaseTypeLoc();
9188     else
9189       return Subobj.get<FieldDecl*>()->getLocation();
9190   }
9191 
9192   enum BasesToVisit {
9193     /// Visit all non-virtual (direct) bases.
9194     VisitNonVirtualBases,
9195     /// Visit all direct bases, virtual or not.
9196     VisitDirectBases,
9197     /// Visit all non-virtual bases, and all virtual bases if the class
9198     /// is not abstract.
9199     VisitPotentiallyConstructedBases,
9200     /// Visit all direct or virtual bases.
9201     VisitAllBases
9202   };
9203 
9204   // Visit the bases and members of the class.
9205   bool visit(BasesToVisit Bases) {
9206     CXXRecordDecl *RD = MD->getParent();
9207 
9208     if (Bases == VisitPotentiallyConstructedBases)
9209       Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
9210 
9211     for (auto &B : RD->bases())
9212       if ((Bases == VisitDirectBases || !B.isVirtual()) &&
9213           getDerived().visitBase(&B))
9214         return true;
9215 
9216     if (Bases == VisitAllBases)
9217       for (auto &B : RD->vbases())
9218         if (getDerived().visitBase(&B))
9219           return true;
9220 
9221     for (auto *F : RD->fields())
9222       if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
9223           getDerived().visitField(F))
9224         return true;
9225 
9226     return false;
9227   }
9228 };
9229 }
9230 
9231 namespace {
9232 struct SpecialMemberDeletionInfo
9233     : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
9234   bool Diagnose;
9235 
9236   SourceLocation Loc;
9237 
9238   bool AllFieldsAreConst;
9239 
9240   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
9241                             Sema::CXXSpecialMember CSM,
9242                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
9243       : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
9244         Loc(MD->getLocation()), AllFieldsAreConst(true) {}
9245 
9246   bool inUnion() const { return MD->getParent()->isUnion(); }
9247 
9248   Sema::CXXSpecialMember getEffectiveCSM() {
9249     return ICI ? Sema::CXXInvalid : CSM;
9250   }
9251 
9252   bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
9253 
9254   bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
9255   bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
9256 
9257   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
9258   bool shouldDeleteForField(FieldDecl *FD);
9259   bool shouldDeleteForAllConstMembers();
9260 
9261   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
9262                                      unsigned Quals);
9263   bool shouldDeleteForSubobjectCall(Subobject Subobj,
9264                                     Sema::SpecialMemberOverloadResult SMOR,
9265                                     bool IsDtorCallInCtor);
9266 
9267   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
9268 };
9269 }
9270 
9271 /// Is the given special member inaccessible when used on the given
9272 /// sub-object.
9273 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
9274                                              CXXMethodDecl *target) {
9275   /// If we're operating on a base class, the object type is the
9276   /// type of this special member.
9277   QualType objectTy;
9278   AccessSpecifier access = target->getAccess();
9279   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
9280     objectTy = S.Context.getTypeDeclType(MD->getParent());
9281     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
9282 
9283   // If we're operating on a field, the object type is the type of the field.
9284   } else {
9285     objectTy = S.Context.getTypeDeclType(target->getParent());
9286   }
9287 
9288   return S.isMemberAccessibleForDeletion(
9289       target->getParent(), DeclAccessPair::make(target, access), objectTy);
9290 }
9291 
9292 /// Check whether we should delete a special member due to the implicit
9293 /// definition containing a call to a special member of a subobject.
9294 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
9295     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
9296     bool IsDtorCallInCtor) {
9297   CXXMethodDecl *Decl = SMOR.getMethod();
9298   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9299 
9300   int DiagKind = -1;
9301 
9302   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
9303     DiagKind = !Decl ? 0 : 1;
9304   else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9305     DiagKind = 2;
9306   else if (!isAccessible(Subobj, Decl))
9307     DiagKind = 3;
9308   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
9309            !Decl->isTrivial()) {
9310     // A member of a union must have a trivial corresponding special member.
9311     // As a weird special case, a destructor call from a union's constructor
9312     // must be accessible and non-deleted, but need not be trivial. Such a
9313     // destructor is never actually called, but is semantically checked as
9314     // if it were.
9315     if (CSM == Sema::CXXDefaultConstructor) {
9316       // [class.default.ctor]p2:
9317       //   A defaulted default constructor for class X is defined as deleted if
9318       //   - X is a union that has a variant member with a non-trivial default
9319       //     constructor and no variant member of X has a default member
9320       //     initializer
9321       const auto *RD = cast<CXXRecordDecl>(Field->getParent());
9322       if (!RD->hasInClassInitializer())
9323         DiagKind = 4;
9324     } else {
9325       DiagKind = 4;
9326     }
9327   }
9328 
9329   if (DiagKind == -1)
9330     return false;
9331 
9332   if (Diagnose) {
9333     if (Field) {
9334       S.Diag(Field->getLocation(),
9335              diag::note_deleted_special_member_class_subobject)
9336         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
9337         << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
9338     } else {
9339       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
9340       S.Diag(Base->getBeginLoc(),
9341              diag::note_deleted_special_member_class_subobject)
9342           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9343           << Base->getType() << DiagKind << IsDtorCallInCtor
9344           << /*IsObjCPtr*/false;
9345     }
9346 
9347     if (DiagKind == 1)
9348       S.NoteDeletedFunction(Decl);
9349     // FIXME: Explain inaccessibility if DiagKind == 3.
9350   }
9351 
9352   return true;
9353 }
9354 
9355 /// Check whether we should delete a special member function due to having a
9356 /// direct or virtual base class or non-static data member of class type M.
9357 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
9358     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
9359   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9360   bool IsMutable = Field && Field->isMutable();
9361 
9362   // C++11 [class.ctor]p5:
9363   // -- any direct or virtual base class, or non-static data member with no
9364   //    brace-or-equal-initializer, has class type M (or array thereof) and
9365   //    either M has no default constructor or overload resolution as applied
9366   //    to M's default constructor results in an ambiguity or in a function
9367   //    that is deleted or inaccessible
9368   // C++11 [class.copy]p11, C++11 [class.copy]p23:
9369   // -- a direct or virtual base class B that cannot be copied/moved because
9370   //    overload resolution, as applied to B's corresponding special member,
9371   //    results in an ambiguity or a function that is deleted or inaccessible
9372   //    from the defaulted special member
9373   // C++11 [class.dtor]p5:
9374   // -- any direct or virtual base class [...] has a type with a destructor
9375   //    that is deleted or inaccessible
9376   if (!(CSM == Sema::CXXDefaultConstructor &&
9377         Field && Field->hasInClassInitializer()) &&
9378       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
9379                                    false))
9380     return true;
9381 
9382   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
9383   // -- any direct or virtual base class or non-static data member has a
9384   //    type with a destructor that is deleted or inaccessible
9385   if (IsConstructor) {
9386     Sema::SpecialMemberOverloadResult SMOR =
9387         S.LookupSpecialMember(Class, Sema::CXXDestructor,
9388                               false, false, false, false, false);
9389     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
9390       return true;
9391   }
9392 
9393   return false;
9394 }
9395 
9396 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
9397     FieldDecl *FD, QualType FieldType) {
9398   // The defaulted special functions are defined as deleted if this is a variant
9399   // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
9400   // type under ARC.
9401   if (!FieldType.hasNonTrivialObjCLifetime())
9402     return false;
9403 
9404   // Don't make the defaulted default constructor defined as deleted if the
9405   // member has an in-class initializer.
9406   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
9407     return false;
9408 
9409   if (Diagnose) {
9410     auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
9411     S.Diag(FD->getLocation(),
9412            diag::note_deleted_special_member_class_subobject)
9413         << getEffectiveCSM() << ParentClass << /*IsField*/true
9414         << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
9415   }
9416 
9417   return true;
9418 }
9419 
9420 /// Check whether we should delete a special member function due to the class
9421 /// having a particular direct or virtual base class.
9422 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
9423   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
9424   // If program is correct, BaseClass cannot be null, but if it is, the error
9425   // must be reported elsewhere.
9426   if (!BaseClass)
9427     return false;
9428   // If we have an inheriting constructor, check whether we're calling an
9429   // inherited constructor instead of a default constructor.
9430   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
9431   if (auto *BaseCtor = SMOR.getMethod()) {
9432     // Note that we do not check access along this path; other than that,
9433     // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9434     // FIXME: Check that the base has a usable destructor! Sink this into
9435     // shouldDeleteForClassSubobject.
9436     if (BaseCtor->isDeleted() && Diagnose) {
9437       S.Diag(Base->getBeginLoc(),
9438              diag::note_deleted_special_member_class_subobject)
9439           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9440           << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
9441           << /*IsObjCPtr*/false;
9442       S.NoteDeletedFunction(BaseCtor);
9443     }
9444     return BaseCtor->isDeleted();
9445   }
9446   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
9447 }
9448 
9449 /// Check whether we should delete a special member function due to the class
9450 /// having a particular non-static data member.
9451 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
9452   QualType FieldType = S.Context.getBaseElementType(FD->getType());
9453   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
9454 
9455   if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9456     return true;
9457 
9458   if (CSM == Sema::CXXDefaultConstructor) {
9459     // For a default constructor, all references must be initialized in-class
9460     // and, if a union, it must have a non-const member.
9461     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9462       if (Diagnose)
9463         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9464           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9465       return true;
9466     }
9467     // C++11 [class.ctor]p5 (modified by DR2394): any non-variant non-static
9468     // data member of const-qualified type (or array thereof) with no
9469     // brace-or-equal-initializer is not const-default-constructible.
9470     if (!inUnion() && FieldType.isConstQualified() &&
9471         !FD->hasInClassInitializer() &&
9472         (!FieldRecord || !FieldRecord->allowConstDefaultInit())) {
9473       if (Diagnose)
9474         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9475           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9476       return true;
9477     }
9478 
9479     if (inUnion() && !FieldType.isConstQualified())
9480       AllFieldsAreConst = false;
9481   } else if (CSM == Sema::CXXCopyConstructor) {
9482     // For a copy constructor, data members must not be of rvalue reference
9483     // type.
9484     if (FieldType->isRValueReferenceType()) {
9485       if (Diagnose)
9486         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
9487           << MD->getParent() << FD << FieldType;
9488       return true;
9489     }
9490   } else if (IsAssignment) {
9491     // For an assignment operator, data members must not be of reference type.
9492     if (FieldType->isReferenceType()) {
9493       if (Diagnose)
9494         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9495           << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9496       return true;
9497     }
9498     if (!FieldRecord && FieldType.isConstQualified()) {
9499       // C++11 [class.copy]p23:
9500       // -- a non-static data member of const non-class type (or array thereof)
9501       if (Diagnose)
9502         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9503           << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9504       return true;
9505     }
9506   }
9507 
9508   if (FieldRecord) {
9509     // Some additional restrictions exist on the variant members.
9510     if (!inUnion() && FieldRecord->isUnion() &&
9511         FieldRecord->isAnonymousStructOrUnion()) {
9512       bool AllVariantFieldsAreConst = true;
9513 
9514       // FIXME: Handle anonymous unions declared within anonymous unions.
9515       for (auto *UI : FieldRecord->fields()) {
9516         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
9517 
9518         if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
9519           return true;
9520 
9521         if (!UnionFieldType.isConstQualified())
9522           AllVariantFieldsAreConst = false;
9523 
9524         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9525         if (UnionFieldRecord &&
9526             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
9527                                           UnionFieldType.getCVRQualifiers()))
9528           return true;
9529       }
9530 
9531       // At least one member in each anonymous union must be non-const
9532       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
9533           !FieldRecord->field_empty()) {
9534         if (Diagnose)
9535           S.Diag(FieldRecord->getLocation(),
9536                  diag::note_deleted_default_ctor_all_const)
9537             << !!ICI << MD->getParent() << /*anonymous union*/1;
9538         return true;
9539       }
9540 
9541       // Don't check the implicit member of the anonymous union type.
9542       // This is technically non-conformant but supported, and we have a
9543       // diagnostic for this elsewhere.
9544       return false;
9545     }
9546 
9547     if (shouldDeleteForClassSubobject(FieldRecord, FD,
9548                                       FieldType.getCVRQualifiers()))
9549       return true;
9550   }
9551 
9552   return false;
9553 }
9554 
9555 /// C++11 [class.ctor] p5:
9556 ///   A defaulted default constructor for a class X is defined as deleted if
9557 /// X is a union and all of its variant members are of const-qualified type.
9558 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9559   // This is a silly definition, because it gives an empty union a deleted
9560   // default constructor. Don't do that.
9561   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
9562     bool AnyFields = false;
9563     for (auto *F : MD->getParent()->fields())
9564       if ((AnyFields = !F->isUnnamedBitfield()))
9565         break;
9566     if (!AnyFields)
9567       return false;
9568     if (Diagnose)
9569       S.Diag(MD->getParent()->getLocation(),
9570              diag::note_deleted_default_ctor_all_const)
9571         << !!ICI << MD->getParent() << /*not anonymous union*/0;
9572     return true;
9573   }
9574   return false;
9575 }
9576 
9577 /// Determine whether a defaulted special member function should be defined as
9578 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9579 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9580 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
9581                                      InheritedConstructorInfo *ICI,
9582                                      bool Diagnose) {
9583   if (MD->isInvalidDecl())
9584     return false;
9585   CXXRecordDecl *RD = MD->getParent();
9586   assert(!RD->isDependentType() && "do deletion after instantiation");
9587   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
9588     return false;
9589 
9590   // C++11 [expr.lambda.prim]p19:
9591   //   The closure type associated with a lambda-expression has a
9592   //   deleted (8.4.3) default constructor and a deleted copy
9593   //   assignment operator.
9594   // C++2a adds back these operators if the lambda has no lambda-capture.
9595   if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
9596       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
9597     if (Diagnose)
9598       Diag(RD->getLocation(), diag::note_lambda_decl);
9599     return true;
9600   }
9601 
9602   // For an anonymous struct or union, the copy and assignment special members
9603   // will never be used, so skip the check. For an anonymous union declared at
9604   // namespace scope, the constructor and destructor are used.
9605   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
9606       RD->isAnonymousStructOrUnion())
9607     return false;
9608 
9609   // C++11 [class.copy]p7, p18:
9610   //   If the class definition declares a move constructor or move assignment
9611   //   operator, an implicitly declared copy constructor or copy assignment
9612   //   operator is defined as deleted.
9613   if (MD->isImplicit() &&
9614       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
9615     CXXMethodDecl *UserDeclaredMove = nullptr;
9616 
9617     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9618     // deletion of the corresponding copy operation, not both copy operations.
9619     // MSVC 2015 has adopted the standards conforming behavior.
9620     bool DeletesOnlyMatchingCopy =
9621         getLangOpts().MSVCCompat &&
9622         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
9623 
9624     if (RD->hasUserDeclaredMoveConstructor() &&
9625         (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
9626       if (!Diagnose) return true;
9627 
9628       // Find any user-declared move constructor.
9629       for (auto *I : RD->ctors()) {
9630         if (I->isMoveConstructor()) {
9631           UserDeclaredMove = I;
9632           break;
9633         }
9634       }
9635       assert(UserDeclaredMove);
9636     } else if (RD->hasUserDeclaredMoveAssignment() &&
9637                (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
9638       if (!Diagnose) return true;
9639 
9640       // Find any user-declared move assignment operator.
9641       for (auto *I : RD->methods()) {
9642         if (I->isMoveAssignmentOperator()) {
9643           UserDeclaredMove = I;
9644           break;
9645         }
9646       }
9647       assert(UserDeclaredMove);
9648     }
9649 
9650     if (UserDeclaredMove) {
9651       Diag(UserDeclaredMove->getLocation(),
9652            diag::note_deleted_copy_user_declared_move)
9653         << (CSM == CXXCopyAssignment) << RD
9654         << UserDeclaredMove->isMoveAssignmentOperator();
9655       return true;
9656     }
9657   }
9658 
9659   // Do access control from the special member function
9660   ContextRAII MethodContext(*this, MD);
9661 
9662   // C++11 [class.dtor]p5:
9663   // -- for a virtual destructor, lookup of the non-array deallocation function
9664   //    results in an ambiguity or in a function that is deleted or inaccessible
9665   if (CSM == CXXDestructor && MD->isVirtual()) {
9666     FunctionDecl *OperatorDelete = nullptr;
9667     DeclarationName Name =
9668       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
9669     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
9670                                  OperatorDelete, /*Diagnose*/false)) {
9671       if (Diagnose)
9672         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
9673       return true;
9674     }
9675   }
9676 
9677   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
9678 
9679   // Per DR1611, do not consider virtual bases of constructors of abstract
9680   // classes, since we are not going to construct them.
9681   // Per DR1658, do not consider virtual bases of destructors of abstract
9682   // classes either.
9683   // Per DR2180, for assignment operators we only assign (and thus only
9684   // consider) direct bases.
9685   if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
9686                                  : SMI.VisitPotentiallyConstructedBases))
9687     return true;
9688 
9689   if (SMI.shouldDeleteForAllConstMembers())
9690     return true;
9691 
9692   if (getLangOpts().CUDA) {
9693     // We should delete the special member in CUDA mode if target inference
9694     // failed.
9695     // For inherited constructors (non-null ICI), CSM may be passed so that MD
9696     // is treated as certain special member, which may not reflect what special
9697     // member MD really is. However inferCUDATargetForImplicitSpecialMember
9698     // expects CSM to match MD, therefore recalculate CSM.
9699     assert(ICI || CSM == getSpecialMember(MD));
9700     auto RealCSM = CSM;
9701     if (ICI)
9702       RealCSM = getSpecialMember(MD);
9703 
9704     return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
9705                                                    SMI.ConstArg, Diagnose);
9706   }
9707 
9708   return false;
9709 }
9710 
9711 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {
9712   DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
9713   assert(DFK && "not a defaultable function");
9714   assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
9715 
9716   if (DFK.isSpecialMember()) {
9717     ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),
9718                               nullptr, /*Diagnose=*/true);
9719   } else {
9720     DefaultedComparisonAnalyzer(
9721         *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
9722         DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
9723         .visit();
9724   }
9725 }
9726 
9727 /// Perform lookup for a special member of the specified kind, and determine
9728 /// whether it is trivial. If the triviality can be determined without the
9729 /// lookup, skip it. This is intended for use when determining whether a
9730 /// special member of a containing object is trivial, and thus does not ever
9731 /// perform overload resolution for default constructors.
9732 ///
9733 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
9734 /// member that was most likely to be intended to be trivial, if any.
9735 ///
9736 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
9737 /// determine whether the special member is trivial.
9738 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
9739                                      Sema::CXXSpecialMember CSM, unsigned Quals,
9740                                      bool ConstRHS,
9741                                      Sema::TrivialABIHandling TAH,
9742                                      CXXMethodDecl **Selected) {
9743   if (Selected)
9744     *Selected = nullptr;
9745 
9746   switch (CSM) {
9747   case Sema::CXXInvalid:
9748     llvm_unreachable("not a special member");
9749 
9750   case Sema::CXXDefaultConstructor:
9751     // C++11 [class.ctor]p5:
9752     //   A default constructor is trivial if:
9753     //    - all the [direct subobjects] have trivial default constructors
9754     //
9755     // Note, no overload resolution is performed in this case.
9756     if (RD->hasTrivialDefaultConstructor())
9757       return true;
9758 
9759     if (Selected) {
9760       // If there's a default constructor which could have been trivial, dig it
9761       // out. Otherwise, if there's any user-provided default constructor, point
9762       // to that as an example of why there's not a trivial one.
9763       CXXConstructorDecl *DefCtor = nullptr;
9764       if (RD->needsImplicitDefaultConstructor())
9765         S.DeclareImplicitDefaultConstructor(RD);
9766       for (auto *CI : RD->ctors()) {
9767         if (!CI->isDefaultConstructor())
9768           continue;
9769         DefCtor = CI;
9770         if (!DefCtor->isUserProvided())
9771           break;
9772       }
9773 
9774       *Selected = DefCtor;
9775     }
9776 
9777     return false;
9778 
9779   case Sema::CXXDestructor:
9780     // C++11 [class.dtor]p5:
9781     //   A destructor is trivial if:
9782     //    - all the direct [subobjects] have trivial destructors
9783     if (RD->hasTrivialDestructor() ||
9784         (TAH == Sema::TAH_ConsiderTrivialABI &&
9785          RD->hasTrivialDestructorForCall()))
9786       return true;
9787 
9788     if (Selected) {
9789       if (RD->needsImplicitDestructor())
9790         S.DeclareImplicitDestructor(RD);
9791       *Selected = RD->getDestructor();
9792     }
9793 
9794     return false;
9795 
9796   case Sema::CXXCopyConstructor:
9797     // C++11 [class.copy]p12:
9798     //   A copy constructor is trivial if:
9799     //    - the constructor selected to copy each direct [subobject] is trivial
9800     if (RD->hasTrivialCopyConstructor() ||
9801         (TAH == Sema::TAH_ConsiderTrivialABI &&
9802          RD->hasTrivialCopyConstructorForCall())) {
9803       if (Quals == Qualifiers::Const)
9804         // We must either select the trivial copy constructor or reach an
9805         // ambiguity; no need to actually perform overload resolution.
9806         return true;
9807     } else if (!Selected) {
9808       return false;
9809     }
9810     // In C++98, we are not supposed to perform overload resolution here, but we
9811     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
9812     // cases like B as having a non-trivial copy constructor:
9813     //   struct A { template<typename T> A(T&); };
9814     //   struct B { mutable A a; };
9815     goto NeedOverloadResolution;
9816 
9817   case Sema::CXXCopyAssignment:
9818     // C++11 [class.copy]p25:
9819     //   A copy assignment operator is trivial if:
9820     //    - the assignment operator selected to copy each direct [subobject] is
9821     //      trivial
9822     if (RD->hasTrivialCopyAssignment()) {
9823       if (Quals == Qualifiers::Const)
9824         return true;
9825     } else if (!Selected) {
9826       return false;
9827     }
9828     // In C++98, we are not supposed to perform overload resolution here, but we
9829     // treat that as a language defect.
9830     goto NeedOverloadResolution;
9831 
9832   case Sema::CXXMoveConstructor:
9833   case Sema::CXXMoveAssignment:
9834   NeedOverloadResolution:
9835     Sema::SpecialMemberOverloadResult SMOR =
9836         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
9837 
9838     // The standard doesn't describe how to behave if the lookup is ambiguous.
9839     // We treat it as not making the member non-trivial, just like the standard
9840     // mandates for the default constructor. This should rarely matter, because
9841     // the member will also be deleted.
9842     if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9843       return true;
9844 
9845     if (!SMOR.getMethod()) {
9846       assert(SMOR.getKind() ==
9847              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
9848       return false;
9849     }
9850 
9851     // We deliberately don't check if we found a deleted special member. We're
9852     // not supposed to!
9853     if (Selected)
9854       *Selected = SMOR.getMethod();
9855 
9856     if (TAH == Sema::TAH_ConsiderTrivialABI &&
9857         (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
9858       return SMOR.getMethod()->isTrivialForCall();
9859     return SMOR.getMethod()->isTrivial();
9860   }
9861 
9862   llvm_unreachable("unknown special method kind");
9863 }
9864 
9865 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
9866   for (auto *CI : RD->ctors())
9867     if (!CI->isImplicit())
9868       return CI;
9869 
9870   // Look for constructor templates.
9871   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
9872   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
9873     if (CXXConstructorDecl *CD =
9874           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
9875       return CD;
9876   }
9877 
9878   return nullptr;
9879 }
9880 
9881 /// The kind of subobject we are checking for triviality. The values of this
9882 /// enumeration are used in diagnostics.
9883 enum TrivialSubobjectKind {
9884   /// The subobject is a base class.
9885   TSK_BaseClass,
9886   /// The subobject is a non-static data member.
9887   TSK_Field,
9888   /// The object is actually the complete object.
9889   TSK_CompleteObject
9890 };
9891 
9892 /// Check whether the special member selected for a given type would be trivial.
9893 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
9894                                       QualType SubType, bool ConstRHS,
9895                                       Sema::CXXSpecialMember CSM,
9896                                       TrivialSubobjectKind Kind,
9897                                       Sema::TrivialABIHandling TAH, bool Diagnose) {
9898   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
9899   if (!SubRD)
9900     return true;
9901 
9902   CXXMethodDecl *Selected;
9903   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
9904                                ConstRHS, TAH, Diagnose ? &Selected : nullptr))
9905     return true;
9906 
9907   if (Diagnose) {
9908     if (ConstRHS)
9909       SubType.addConst();
9910 
9911     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
9912       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
9913         << Kind << SubType.getUnqualifiedType();
9914       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
9915         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
9916     } else if (!Selected)
9917       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
9918         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
9919     else if (Selected->isUserProvided()) {
9920       if (Kind == TSK_CompleteObject)
9921         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
9922           << Kind << SubType.getUnqualifiedType() << CSM;
9923       else {
9924         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
9925           << Kind << SubType.getUnqualifiedType() << CSM;
9926         S.Diag(Selected->getLocation(), diag::note_declared_at);
9927       }
9928     } else {
9929       if (Kind != TSK_CompleteObject)
9930         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
9931           << Kind << SubType.getUnqualifiedType() << CSM;
9932 
9933       // Explain why the defaulted or deleted special member isn't trivial.
9934       S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
9935                                Diagnose);
9936     }
9937   }
9938 
9939   return false;
9940 }
9941 
9942 /// Check whether the members of a class type allow a special member to be
9943 /// trivial.
9944 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
9945                                      Sema::CXXSpecialMember CSM,
9946                                      bool ConstArg,
9947                                      Sema::TrivialABIHandling TAH,
9948                                      bool Diagnose) {
9949   for (const auto *FI : RD->fields()) {
9950     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
9951       continue;
9952 
9953     QualType FieldType = S.Context.getBaseElementType(FI->getType());
9954 
9955     // Pretend anonymous struct or union members are members of this class.
9956     if (FI->isAnonymousStructOrUnion()) {
9957       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
9958                                     CSM, ConstArg, TAH, Diagnose))
9959         return false;
9960       continue;
9961     }
9962 
9963     // C++11 [class.ctor]p5:
9964     //   A default constructor is trivial if [...]
9965     //    -- no non-static data member of its class has a
9966     //       brace-or-equal-initializer
9967     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
9968       if (Diagnose)
9969         S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
9970             << FI;
9971       return false;
9972     }
9973 
9974     // Objective C ARC 4.3.5:
9975     //   [...] nontrivally ownership-qualified types are [...] not trivially
9976     //   default constructible, copy constructible, move constructible, copy
9977     //   assignable, move assignable, or destructible [...]
9978     if (FieldType.hasNonTrivialObjCLifetime()) {
9979       if (Diagnose)
9980         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
9981           << RD << FieldType.getObjCLifetime();
9982       return false;
9983     }
9984 
9985     bool ConstRHS = ConstArg && !FI->isMutable();
9986     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
9987                                    CSM, TSK_Field, TAH, Diagnose))
9988       return false;
9989   }
9990 
9991   return true;
9992 }
9993 
9994 /// Diagnose why the specified class does not have a trivial special member of
9995 /// the given kind.
9996 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
9997   QualType Ty = Context.getRecordType(RD);
9998 
9999   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
10000   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
10001                             TSK_CompleteObject, TAH_IgnoreTrivialABI,
10002                             /*Diagnose*/true);
10003 }
10004 
10005 /// Determine whether a defaulted or deleted special member function is trivial,
10006 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
10007 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
10008 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
10009                                   TrivialABIHandling TAH, bool Diagnose) {
10010   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
10011 
10012   CXXRecordDecl *RD = MD->getParent();
10013 
10014   bool ConstArg = false;
10015 
10016   // C++11 [class.copy]p12, p25: [DR1593]
10017   //   A [special member] is trivial if [...] its parameter-type-list is
10018   //   equivalent to the parameter-type-list of an implicit declaration [...]
10019   switch (CSM) {
10020   case CXXDefaultConstructor:
10021   case CXXDestructor:
10022     // Trivial default constructors and destructors cannot have parameters.
10023     break;
10024 
10025   case CXXCopyConstructor:
10026   case CXXCopyAssignment: {
10027     const ParmVarDecl *Param0 = MD->getParamDecl(0);
10028     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
10029 
10030     // When ClangABICompat14 is true, CXX copy constructors will only be trivial
10031     // if they are not user-provided and their parameter-type-list is equivalent
10032     // to the parameter-type-list of an implicit declaration. This maintains the
10033     // behavior before dr2171 was implemented.
10034     //
10035     // Otherwise, if ClangABICompat14 is false, All copy constructors can be
10036     // trivial, if they are not user-provided, regardless of the qualifiers on
10037     // the reference type.
10038     const bool ClangABICompat14 = Context.getLangOpts().getClangABICompat() <=
10039                                   LangOptions::ClangABI::Ver14;
10040     if (!RT ||
10041         ((RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) &&
10042          ClangABICompat14)) {
10043       if (Diagnose)
10044         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10045           << Param0->getSourceRange() << Param0->getType()
10046           << Context.getLValueReferenceType(
10047                Context.getRecordType(RD).withConst());
10048       return false;
10049     }
10050 
10051     ConstArg = RT->getPointeeType().isConstQualified();
10052     break;
10053   }
10054 
10055   case CXXMoveConstructor:
10056   case CXXMoveAssignment: {
10057     // Trivial move operations always have non-cv-qualified parameters.
10058     const ParmVarDecl *Param0 = MD->getParamDecl(0);
10059     const RValueReferenceType *RT =
10060       Param0->getType()->getAs<RValueReferenceType>();
10061     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
10062       if (Diagnose)
10063         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10064           << Param0->getSourceRange() << Param0->getType()
10065           << Context.getRValueReferenceType(Context.getRecordType(RD));
10066       return false;
10067     }
10068     break;
10069   }
10070 
10071   case CXXInvalid:
10072     llvm_unreachable("not a special member");
10073   }
10074 
10075   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
10076     if (Diagnose)
10077       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
10078            diag::note_nontrivial_default_arg)
10079         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
10080     return false;
10081   }
10082   if (MD->isVariadic()) {
10083     if (Diagnose)
10084       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
10085     return false;
10086   }
10087 
10088   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10089   //   A copy/move [constructor or assignment operator] is trivial if
10090   //    -- the [member] selected to copy/move each direct base class subobject
10091   //       is trivial
10092   //
10093   // C++11 [class.copy]p12, C++11 [class.copy]p25:
10094   //   A [default constructor or destructor] is trivial if
10095   //    -- all the direct base classes have trivial [default constructors or
10096   //       destructors]
10097   for (const auto &BI : RD->bases())
10098     if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
10099                                    ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
10100       return false;
10101 
10102   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10103   //   A copy/move [constructor or assignment operator] for a class X is
10104   //   trivial if
10105   //    -- for each non-static data member of X that is of class type (or array
10106   //       thereof), the constructor selected to copy/move that member is
10107   //       trivial
10108   //
10109   // C++11 [class.copy]p12, C++11 [class.copy]p25:
10110   //   A [default constructor or destructor] is trivial if
10111   //    -- for all of the non-static data members of its class that are of class
10112   //       type (or array thereof), each such class has a trivial [default
10113   //       constructor or destructor]
10114   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
10115     return false;
10116 
10117   // C++11 [class.dtor]p5:
10118   //   A destructor is trivial if [...]
10119   //    -- the destructor is not virtual
10120   if (CSM == CXXDestructor && MD->isVirtual()) {
10121     if (Diagnose)
10122       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
10123     return false;
10124   }
10125 
10126   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
10127   //   A [special member] for class X is trivial if [...]
10128   //    -- class X has no virtual functions and no virtual base classes
10129   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
10130     if (!Diagnose)
10131       return false;
10132 
10133     if (RD->getNumVBases()) {
10134       // Check for virtual bases. We already know that the corresponding
10135       // member in all bases is trivial, so vbases must all be direct.
10136       CXXBaseSpecifier &BS = *RD->vbases_begin();
10137       assert(BS.isVirtual());
10138       Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
10139       return false;
10140     }
10141 
10142     // Must have a virtual method.
10143     for (const auto *MI : RD->methods()) {
10144       if (MI->isVirtual()) {
10145         SourceLocation MLoc = MI->getBeginLoc();
10146         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
10147         return false;
10148       }
10149     }
10150 
10151     llvm_unreachable("dynamic class with no vbases and no virtual functions");
10152   }
10153 
10154   // Looks like it's trivial!
10155   return true;
10156 }
10157 
10158 namespace {
10159 struct FindHiddenVirtualMethod {
10160   Sema *S;
10161   CXXMethodDecl *Method;
10162   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
10163   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10164 
10165 private:
10166   /// Check whether any most overridden method from MD in Methods
10167   static bool CheckMostOverridenMethods(
10168       const CXXMethodDecl *MD,
10169       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
10170     if (MD->size_overridden_methods() == 0)
10171       return Methods.count(MD->getCanonicalDecl());
10172     for (const CXXMethodDecl *O : MD->overridden_methods())
10173       if (CheckMostOverridenMethods(O, Methods))
10174         return true;
10175     return false;
10176   }
10177 
10178 public:
10179   /// Member lookup function that determines whether a given C++
10180   /// method overloads virtual methods in a base class without overriding any,
10181   /// to be used with CXXRecordDecl::lookupInBases().
10182   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
10183     RecordDecl *BaseRecord =
10184         Specifier->getType()->castAs<RecordType>()->getDecl();
10185 
10186     DeclarationName Name = Method->getDeclName();
10187     assert(Name.getNameKind() == DeclarationName::Identifier);
10188 
10189     bool foundSameNameMethod = false;
10190     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
10191     for (Path.Decls = BaseRecord->lookup(Name).begin();
10192          Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
10193       NamedDecl *D = *Path.Decls;
10194       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
10195         MD = MD->getCanonicalDecl();
10196         foundSameNameMethod = true;
10197         // Interested only in hidden virtual methods.
10198         if (!MD->isVirtual())
10199           continue;
10200         // If the method we are checking overrides a method from its base
10201         // don't warn about the other overloaded methods. Clang deviates from
10202         // GCC by only diagnosing overloads of inherited virtual functions that
10203         // do not override any other virtual functions in the base. GCC's
10204         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
10205         // function from a base class. These cases may be better served by a
10206         // warning (not specific to virtual functions) on call sites when the
10207         // call would select a different function from the base class, were it
10208         // visible.
10209         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
10210         if (!S->IsOverload(Method, MD, false))
10211           return true;
10212         // Collect the overload only if its hidden.
10213         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
10214           overloadedMethods.push_back(MD);
10215       }
10216     }
10217 
10218     if (foundSameNameMethod)
10219       OverloadedMethods.append(overloadedMethods.begin(),
10220                                overloadedMethods.end());
10221     return foundSameNameMethod;
10222   }
10223 };
10224 } // end anonymous namespace
10225 
10226 /// Add the most overridden methods from MD to Methods
10227 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
10228                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
10229   if (MD->size_overridden_methods() == 0)
10230     Methods.insert(MD->getCanonicalDecl());
10231   else
10232     for (const CXXMethodDecl *O : MD->overridden_methods())
10233       AddMostOverridenMethods(O, Methods);
10234 }
10235 
10236 /// Check if a method overloads virtual methods in a base class without
10237 /// overriding any.
10238 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
10239                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10240   if (!MD->getDeclName().isIdentifier())
10241     return;
10242 
10243   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
10244                      /*bool RecordPaths=*/false,
10245                      /*bool DetectVirtual=*/false);
10246   FindHiddenVirtualMethod FHVM;
10247   FHVM.Method = MD;
10248   FHVM.S = this;
10249 
10250   // Keep the base methods that were overridden or introduced in the subclass
10251   // by 'using' in a set. A base method not in this set is hidden.
10252   CXXRecordDecl *DC = MD->getParent();
10253   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
10254   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
10255     NamedDecl *ND = *I;
10256     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
10257       ND = shad->getTargetDecl();
10258     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
10259       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
10260   }
10261 
10262   if (DC->lookupInBases(FHVM, Paths))
10263     OverloadedMethods = FHVM.OverloadedMethods;
10264 }
10265 
10266 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
10267                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10268   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
10269     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
10270     PartialDiagnostic PD = PDiag(
10271          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
10272     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
10273     Diag(overloadedMD->getLocation(), PD);
10274   }
10275 }
10276 
10277 /// Diagnose methods which overload virtual methods in a base class
10278 /// without overriding any.
10279 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
10280   if (MD->isInvalidDecl())
10281     return;
10282 
10283   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
10284     return;
10285 
10286   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10287   FindHiddenVirtualMethods(MD, OverloadedMethods);
10288   if (!OverloadedMethods.empty()) {
10289     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
10290       << MD << (OverloadedMethods.size() > 1);
10291 
10292     NoteHiddenVirtualMethods(MD, OverloadedMethods);
10293   }
10294 }
10295 
10296 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
10297   auto PrintDiagAndRemoveAttr = [&](unsigned N) {
10298     // No diagnostics if this is a template instantiation.
10299     if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) {
10300       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10301            diag::ext_cannot_use_trivial_abi) << &RD;
10302       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10303            diag::note_cannot_use_trivial_abi_reason) << &RD << N;
10304     }
10305     RD.dropAttr<TrivialABIAttr>();
10306   };
10307 
10308   // Ill-formed if the copy and move constructors are deleted.
10309   auto HasNonDeletedCopyOrMoveConstructor = [&]() {
10310     // If the type is dependent, then assume it might have
10311     // implicit copy or move ctor because we won't know yet at this point.
10312     if (RD.isDependentType())
10313       return true;
10314     if (RD.needsImplicitCopyConstructor() &&
10315         !RD.defaultedCopyConstructorIsDeleted())
10316       return true;
10317     if (RD.needsImplicitMoveConstructor() &&
10318         !RD.defaultedMoveConstructorIsDeleted())
10319       return true;
10320     for (const CXXConstructorDecl *CD : RD.ctors())
10321       if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
10322         return true;
10323     return false;
10324   };
10325 
10326   if (!HasNonDeletedCopyOrMoveConstructor()) {
10327     PrintDiagAndRemoveAttr(0);
10328     return;
10329   }
10330 
10331   // Ill-formed if the struct has virtual functions.
10332   if (RD.isPolymorphic()) {
10333     PrintDiagAndRemoveAttr(1);
10334     return;
10335   }
10336 
10337   for (const auto &B : RD.bases()) {
10338     // Ill-formed if the base class is non-trivial for the purpose of calls or a
10339     // virtual base.
10340     if (!B.getType()->isDependentType() &&
10341         !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
10342       PrintDiagAndRemoveAttr(2);
10343       return;
10344     }
10345 
10346     if (B.isVirtual()) {
10347       PrintDiagAndRemoveAttr(3);
10348       return;
10349     }
10350   }
10351 
10352   for (const auto *FD : RD.fields()) {
10353     // Ill-formed if the field is an ObjectiveC pointer or of a type that is
10354     // non-trivial for the purpose of calls.
10355     QualType FT = FD->getType();
10356     if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
10357       PrintDiagAndRemoveAttr(4);
10358       return;
10359     }
10360 
10361     if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
10362       if (!RT->isDependentType() &&
10363           !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
10364         PrintDiagAndRemoveAttr(5);
10365         return;
10366       }
10367   }
10368 }
10369 
10370 void Sema::ActOnFinishCXXMemberSpecification(
10371     Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
10372     SourceLocation RBrac, const ParsedAttributesView &AttrList) {
10373   if (!TagDecl)
10374     return;
10375 
10376   AdjustDeclIfTemplate(TagDecl);
10377 
10378   for (const ParsedAttr &AL : AttrList) {
10379     if (AL.getKind() != ParsedAttr::AT_Visibility)
10380       continue;
10381     AL.setInvalid();
10382     Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
10383   }
10384 
10385   ActOnFields(S, RLoc, TagDecl,
10386               llvm::ArrayRef(
10387                   // strict aliasing violation!
10388                   reinterpret_cast<Decl **>(FieldCollector->getCurFields()),
10389                   FieldCollector->getCurNumFields()),
10390               LBrac, RBrac, AttrList);
10391 
10392   CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));
10393 }
10394 
10395 /// Find the equality comparison functions that should be implicitly declared
10396 /// in a given class definition, per C++2a [class.compare.default]p3.
10397 static void findImplicitlyDeclaredEqualityComparisons(
10398     ASTContext &Ctx, CXXRecordDecl *RD,
10399     llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {
10400   DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
10401   if (!RD->lookup(EqEq).empty())
10402     // Member operator== explicitly declared: no implicit operator==s.
10403     return;
10404 
10405   // Traverse friends looking for an '==' or a '<=>'.
10406   for (FriendDecl *Friend : RD->friends()) {
10407     FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
10408     if (!FD) continue;
10409 
10410     if (FD->getOverloadedOperator() == OO_EqualEqual) {
10411       // Friend operator== explicitly declared: no implicit operator==s.
10412       Spaceships.clear();
10413       return;
10414     }
10415 
10416     if (FD->getOverloadedOperator() == OO_Spaceship &&
10417         FD->isExplicitlyDefaulted())
10418       Spaceships.push_back(FD);
10419   }
10420 
10421   // Look for members named 'operator<=>'.
10422   DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
10423   for (NamedDecl *ND : RD->lookup(Cmp)) {
10424     // Note that we could find a non-function here (either a function template
10425     // or a using-declaration). Neither case results in an implicit
10426     // 'operator=='.
10427     if (auto *FD = dyn_cast<FunctionDecl>(ND))
10428       if (FD->isExplicitlyDefaulted())
10429         Spaceships.push_back(FD);
10430   }
10431 }
10432 
10433 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
10434 /// special functions, such as the default constructor, copy
10435 /// constructor, or destructor, to the given C++ class (C++
10436 /// [special]p1).  This routine can only be executed just before the
10437 /// definition of the class is complete.
10438 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
10439   // Don't add implicit special members to templated classes.
10440   // FIXME: This means unqualified lookups for 'operator=' within a class
10441   // template don't work properly.
10442   if (!ClassDecl->isDependentType()) {
10443     if (ClassDecl->needsImplicitDefaultConstructor()) {
10444       ++getASTContext().NumImplicitDefaultConstructors;
10445 
10446       if (ClassDecl->hasInheritedConstructor())
10447         DeclareImplicitDefaultConstructor(ClassDecl);
10448     }
10449 
10450     if (ClassDecl->needsImplicitCopyConstructor()) {
10451       ++getASTContext().NumImplicitCopyConstructors;
10452 
10453       // If the properties or semantics of the copy constructor couldn't be
10454       // determined while the class was being declared, force a declaration
10455       // of it now.
10456       if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
10457           ClassDecl->hasInheritedConstructor())
10458         DeclareImplicitCopyConstructor(ClassDecl);
10459       // For the MS ABI we need to know whether the copy ctor is deleted. A
10460       // prerequisite for deleting the implicit copy ctor is that the class has
10461       // a move ctor or move assignment that is either user-declared or whose
10462       // semantics are inherited from a subobject. FIXME: We should provide a
10463       // more direct way for CodeGen to ask whether the constructor was deleted.
10464       else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10465                (ClassDecl->hasUserDeclaredMoveConstructor() ||
10466                 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10467                 ClassDecl->hasUserDeclaredMoveAssignment() ||
10468                 ClassDecl->needsOverloadResolutionForMoveAssignment()))
10469         DeclareImplicitCopyConstructor(ClassDecl);
10470     }
10471 
10472     if (getLangOpts().CPlusPlus11 &&
10473         ClassDecl->needsImplicitMoveConstructor()) {
10474       ++getASTContext().NumImplicitMoveConstructors;
10475 
10476       if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10477           ClassDecl->hasInheritedConstructor())
10478         DeclareImplicitMoveConstructor(ClassDecl);
10479     }
10480 
10481     if (ClassDecl->needsImplicitCopyAssignment()) {
10482       ++getASTContext().NumImplicitCopyAssignmentOperators;
10483 
10484       // If we have a dynamic class, then the copy assignment operator may be
10485       // virtual, so we have to declare it immediately. This ensures that, e.g.,
10486       // it shows up in the right place in the vtable and that we diagnose
10487       // problems with the implicit exception specification.
10488       if (ClassDecl->isDynamicClass() ||
10489           ClassDecl->needsOverloadResolutionForCopyAssignment() ||
10490           ClassDecl->hasInheritedAssignment())
10491         DeclareImplicitCopyAssignment(ClassDecl);
10492     }
10493 
10494     if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10495       ++getASTContext().NumImplicitMoveAssignmentOperators;
10496 
10497       // Likewise for the move assignment operator.
10498       if (ClassDecl->isDynamicClass() ||
10499           ClassDecl->needsOverloadResolutionForMoveAssignment() ||
10500           ClassDecl->hasInheritedAssignment())
10501         DeclareImplicitMoveAssignment(ClassDecl);
10502     }
10503 
10504     if (ClassDecl->needsImplicitDestructor()) {
10505       ++getASTContext().NumImplicitDestructors;
10506 
10507       // If we have a dynamic class, then the destructor may be virtual, so we
10508       // have to declare the destructor immediately. This ensures that, e.g., it
10509       // shows up in the right place in the vtable and that we diagnose problems
10510       // with the implicit exception specification.
10511       if (ClassDecl->isDynamicClass() ||
10512           ClassDecl->needsOverloadResolutionForDestructor())
10513         DeclareImplicitDestructor(ClassDecl);
10514     }
10515   }
10516 
10517   // C++2a [class.compare.default]p3:
10518   //   If the member-specification does not explicitly declare any member or
10519   //   friend named operator==, an == operator function is declared implicitly
10520   //   for each defaulted three-way comparison operator function defined in
10521   //   the member-specification
10522   // FIXME: Consider doing this lazily.
10523   // We do this during the initial parse for a class template, not during
10524   // instantiation, so that we can handle unqualified lookups for 'operator=='
10525   // when parsing the template.
10526   if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) {
10527     llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
10528     findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl,
10529                                               DefaultedSpaceships);
10530     for (auto *FD : DefaultedSpaceships)
10531       DeclareImplicitEqualityComparison(ClassDecl, FD);
10532   }
10533 }
10534 
10535 unsigned
10536 Sema::ActOnReenterTemplateScope(Decl *D,
10537                                 llvm::function_ref<Scope *()> EnterScope) {
10538   if (!D)
10539     return 0;
10540   AdjustDeclIfTemplate(D);
10541 
10542   // In order to get name lookup right, reenter template scopes in order from
10543   // outermost to innermost.
10544   SmallVector<TemplateParameterList *, 4> ParameterLists;
10545   DeclContext *LookupDC = dyn_cast<DeclContext>(D);
10546 
10547   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
10548     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
10549       ParameterLists.push_back(DD->getTemplateParameterList(i));
10550 
10551     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10552       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
10553         ParameterLists.push_back(FTD->getTemplateParameters());
10554     } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10555       LookupDC = VD->getDeclContext();
10556 
10557       if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())
10558         ParameterLists.push_back(VTD->getTemplateParameters());
10559       else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
10560         ParameterLists.push_back(PSD->getTemplateParameters());
10561     }
10562   } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
10563     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
10564       ParameterLists.push_back(TD->getTemplateParameterList(i));
10565 
10566     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
10567       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
10568         ParameterLists.push_back(CTD->getTemplateParameters());
10569       else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
10570         ParameterLists.push_back(PSD->getTemplateParameters());
10571     }
10572   }
10573   // FIXME: Alias declarations and concepts.
10574 
10575   unsigned Count = 0;
10576   Scope *InnermostTemplateScope = nullptr;
10577   for (TemplateParameterList *Params : ParameterLists) {
10578     // Ignore explicit specializations; they don't contribute to the template
10579     // depth.
10580     if (Params->size() == 0)
10581       continue;
10582 
10583     InnermostTemplateScope = EnterScope();
10584     for (NamedDecl *Param : *Params) {
10585       if (Param->getDeclName()) {
10586         InnermostTemplateScope->AddDecl(Param);
10587         IdResolver.AddDecl(Param);
10588       }
10589     }
10590     ++Count;
10591   }
10592 
10593   // Associate the new template scopes with the corresponding entities.
10594   if (InnermostTemplateScope) {
10595     assert(LookupDC && "no enclosing DeclContext for template lookup");
10596     EnterTemplatedContext(InnermostTemplateScope, LookupDC);
10597   }
10598 
10599   return Count;
10600 }
10601 
10602 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10603   if (!RecordD) return;
10604   AdjustDeclIfTemplate(RecordD);
10605   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
10606   PushDeclContext(S, Record);
10607 }
10608 
10609 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10610   if (!RecordD) return;
10611   PopDeclContext();
10612 }
10613 
10614 /// This is used to implement the constant expression evaluation part of the
10615 /// attribute enable_if extension. There is nothing in standard C++ which would
10616 /// require reentering parameters.
10617 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
10618   if (!Param)
10619     return;
10620 
10621   S->AddDecl(Param);
10622   if (Param->getDeclName())
10623     IdResolver.AddDecl(Param);
10624 }
10625 
10626 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
10627 /// parsing a top-level (non-nested) C++ class, and we are now
10628 /// parsing those parts of the given Method declaration that could
10629 /// not be parsed earlier (C++ [class.mem]p2), such as default
10630 /// arguments. This action should enter the scope of the given
10631 /// Method declaration as if we had just parsed the qualified method
10632 /// name. However, it should not bring the parameters into scope;
10633 /// that will be performed by ActOnDelayedCXXMethodParameter.
10634 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10635 }
10636 
10637 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
10638 /// C++ method declaration. We're (re-)introducing the given
10639 /// function parameter into scope for use in parsing later parts of
10640 /// the method declaration. For example, we could see an
10641 /// ActOnParamDefaultArgument event for this parameter.
10642 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
10643   if (!ParamD)
10644     return;
10645 
10646   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
10647 
10648   S->AddDecl(Param);
10649   if (Param->getDeclName())
10650     IdResolver.AddDecl(Param);
10651 }
10652 
10653 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
10654 /// processing the delayed method declaration for Method. The method
10655 /// declaration is now considered finished. There may be a separate
10656 /// ActOnStartOfFunctionDef action later (not necessarily
10657 /// immediately!) for this method, if it was also defined inside the
10658 /// class body.
10659 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10660   if (!MethodD)
10661     return;
10662 
10663   AdjustDeclIfTemplate(MethodD);
10664 
10665   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
10666 
10667   // Now that we have our default arguments, check the constructor
10668   // again. It could produce additional diagnostics or affect whether
10669   // the class has implicitly-declared destructors, among other
10670   // things.
10671   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
10672     CheckConstructor(Constructor);
10673 
10674   // Check the default arguments, which we may have added.
10675   if (!Method->isInvalidDecl())
10676     CheckCXXDefaultArguments(Method);
10677 }
10678 
10679 // Emit the given diagnostic for each non-address-space qualifier.
10680 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
10681 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10682   const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10683   if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10684     bool DiagOccured = false;
10685     FTI.MethodQualifiers->forEachQualifier(
10686         [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10687                                    SourceLocation SL) {
10688           // This diagnostic should be emitted on any qualifier except an addr
10689           // space qualifier. However, forEachQualifier currently doesn't visit
10690           // addr space qualifiers, so there's no way to write this condition
10691           // right now; we just diagnose on everything.
10692           S.Diag(SL, DiagID) << QualName << SourceRange(SL);
10693           DiagOccured = true;
10694         });
10695     if (DiagOccured)
10696       D.setInvalidType();
10697   }
10698 }
10699 
10700 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
10701 /// the well-formedness of the constructor declarator @p D with type @p
10702 /// R. If there are any errors in the declarator, this routine will
10703 /// emit diagnostics and set the invalid bit to true.  In any case, the type
10704 /// will be updated to reflect a well-formed type for the constructor and
10705 /// returned.
10706 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
10707                                           StorageClass &SC) {
10708   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10709 
10710   // C++ [class.ctor]p3:
10711   //   A constructor shall not be virtual (10.3) or static (9.4). A
10712   //   constructor can be invoked for a const, volatile or const
10713   //   volatile object. A constructor shall not be declared const,
10714   //   volatile, or const volatile (9.3.2).
10715   if (isVirtual) {
10716     if (!D.isInvalidType())
10717       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10718         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
10719         << SourceRange(D.getIdentifierLoc());
10720     D.setInvalidType();
10721   }
10722   if (SC == SC_Static) {
10723     if (!D.isInvalidType())
10724       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10725         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10726         << SourceRange(D.getIdentifierLoc());
10727     D.setInvalidType();
10728     SC = SC_None;
10729   }
10730 
10731   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10732     diagnoseIgnoredQualifiers(
10733         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
10734         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
10735         D.getDeclSpec().getRestrictSpecLoc(),
10736         D.getDeclSpec().getAtomicSpecLoc());
10737     D.setInvalidType();
10738   }
10739 
10740   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
10741 
10742   // C++0x [class.ctor]p4:
10743   //   A constructor shall not be declared with a ref-qualifier.
10744   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10745   if (FTI.hasRefQualifier()) {
10746     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
10747       << FTI.RefQualifierIsLValueRef
10748       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10749     D.setInvalidType();
10750   }
10751 
10752   // Rebuild the function type "R" without any type qualifiers (in
10753   // case any of the errors above fired) and with "void" as the
10754   // return type, since constructors don't have return types.
10755   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10756   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
10757     return R;
10758 
10759   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10760   EPI.TypeQuals = Qualifiers();
10761   EPI.RefQualifier = RQ_None;
10762 
10763   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
10764 }
10765 
10766 /// CheckConstructor - Checks a fully-formed constructor for
10767 /// well-formedness, issuing any diagnostics required. Returns true if
10768 /// the constructor declarator is invalid.
10769 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
10770   CXXRecordDecl *ClassDecl
10771     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
10772   if (!ClassDecl)
10773     return Constructor->setInvalidDecl();
10774 
10775   // C++ [class.copy]p3:
10776   //   A declaration of a constructor for a class X is ill-formed if
10777   //   its first parameter is of type (optionally cv-qualified) X and
10778   //   either there are no other parameters or else all other
10779   //   parameters have default arguments.
10780   if (!Constructor->isInvalidDecl() &&
10781       Constructor->hasOneParamOrDefaultArgs() &&
10782       Constructor->getTemplateSpecializationKind() !=
10783           TSK_ImplicitInstantiation) {
10784     QualType ParamType = Constructor->getParamDecl(0)->getType();
10785     QualType ClassTy = Context.getTagDeclType(ClassDecl);
10786     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
10787       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
10788       const char *ConstRef
10789         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
10790                                                         : " const &";
10791       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
10792         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
10793 
10794       // FIXME: Rather that making the constructor invalid, we should endeavor
10795       // to fix the type.
10796       Constructor->setInvalidDecl();
10797     }
10798   }
10799 }
10800 
10801 /// CheckDestructor - Checks a fully-formed destructor definition for
10802 /// well-formedness, issuing any diagnostics required.  Returns true
10803 /// on error.
10804 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
10805   CXXRecordDecl *RD = Destructor->getParent();
10806 
10807   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
10808     SourceLocation Loc;
10809 
10810     if (!Destructor->isImplicit())
10811       Loc = Destructor->getLocation();
10812     else
10813       Loc = RD->getLocation();
10814 
10815     // If we have a virtual destructor, look up the deallocation function
10816     if (FunctionDecl *OperatorDelete =
10817             FindDeallocationFunctionForDestructor(Loc, RD)) {
10818       Expr *ThisArg = nullptr;
10819 
10820       // If the notional 'delete this' expression requires a non-trivial
10821       // conversion from 'this' to the type of a destroying operator delete's
10822       // first parameter, perform that conversion now.
10823       if (OperatorDelete->isDestroyingOperatorDelete()) {
10824         QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
10825         if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
10826           // C++ [class.dtor]p13:
10827           //   ... as if for the expression 'delete this' appearing in a
10828           //   non-virtual destructor of the destructor's class.
10829           ContextRAII SwitchContext(*this, Destructor);
10830           ExprResult This =
10831               ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
10832           assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
10833           This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
10834           if (This.isInvalid()) {
10835             // FIXME: Register this as a context note so that it comes out
10836             // in the right order.
10837             Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
10838             return true;
10839           }
10840           ThisArg = This.get();
10841         }
10842       }
10843 
10844       DiagnoseUseOfDecl(OperatorDelete, Loc);
10845       MarkFunctionReferenced(Loc, OperatorDelete);
10846       Destructor->setOperatorDelete(OperatorDelete, ThisArg);
10847     }
10848   }
10849 
10850   return false;
10851 }
10852 
10853 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
10854 /// the well-formednes of the destructor declarator @p D with type @p
10855 /// R. If there are any errors in the declarator, this routine will
10856 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
10857 /// will be updated to reflect a well-formed type for the destructor and
10858 /// returned.
10859 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
10860                                          StorageClass& SC) {
10861   // C++ [class.dtor]p1:
10862   //   [...] A typedef-name that names a class is a class-name
10863   //   (7.1.3); however, a typedef-name that names a class shall not
10864   //   be used as the identifier in the declarator for a destructor
10865   //   declaration.
10866   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
10867   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
10868     Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10869       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
10870   else if (const TemplateSpecializationType *TST =
10871              DeclaratorType->getAs<TemplateSpecializationType>())
10872     if (TST->isTypeAlias())
10873       Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10874         << DeclaratorType << 1;
10875 
10876   // C++ [class.dtor]p2:
10877   //   A destructor is used to destroy objects of its class type. A
10878   //   destructor takes no parameters, and no return type can be
10879   //   specified for it (not even void). The address of a destructor
10880   //   shall not be taken. A destructor shall not be static. A
10881   //   destructor can be invoked for a const, volatile or const
10882   //   volatile object. A destructor shall not be declared const,
10883   //   volatile or const volatile (9.3.2).
10884   if (SC == SC_Static) {
10885     if (!D.isInvalidType())
10886       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
10887         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10888         << SourceRange(D.getIdentifierLoc())
10889         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10890 
10891     SC = SC_None;
10892   }
10893   if (!D.isInvalidType()) {
10894     // Destructors don't have return types, but the parser will
10895     // happily parse something like:
10896     //
10897     //   class X {
10898     //     float ~X();
10899     //   };
10900     //
10901     // The return type will be eliminated later.
10902     if (D.getDeclSpec().hasTypeSpecifier())
10903       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
10904         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
10905         << SourceRange(D.getIdentifierLoc());
10906     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10907       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
10908                                 SourceLocation(),
10909                                 D.getDeclSpec().getConstSpecLoc(),
10910                                 D.getDeclSpec().getVolatileSpecLoc(),
10911                                 D.getDeclSpec().getRestrictSpecLoc(),
10912                                 D.getDeclSpec().getAtomicSpecLoc());
10913       D.setInvalidType();
10914     }
10915   }
10916 
10917   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
10918 
10919   // C++0x [class.dtor]p2:
10920   //   A destructor shall not be declared with a ref-qualifier.
10921   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10922   if (FTI.hasRefQualifier()) {
10923     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
10924       << FTI.RefQualifierIsLValueRef
10925       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10926     D.setInvalidType();
10927   }
10928 
10929   // Make sure we don't have any parameters.
10930   if (FTIHasNonVoidParameters(FTI)) {
10931     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
10932 
10933     // Delete the parameters.
10934     FTI.freeParams();
10935     D.setInvalidType();
10936   }
10937 
10938   // Make sure the destructor isn't variadic.
10939   if (FTI.isVariadic) {
10940     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
10941     D.setInvalidType();
10942   }
10943 
10944   // Rebuild the function type "R" without any type qualifiers or
10945   // parameters (in case any of the errors above fired) and with
10946   // "void" as the return type, since destructors don't have return
10947   // types.
10948   if (!D.isInvalidType())
10949     return R;
10950 
10951   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10952   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10953   EPI.Variadic = false;
10954   EPI.TypeQuals = Qualifiers();
10955   EPI.RefQualifier = RQ_None;
10956   return Context.getFunctionType(Context.VoidTy, std::nullopt, EPI);
10957 }
10958 
10959 static void extendLeft(SourceRange &R, SourceRange Before) {
10960   if (Before.isInvalid())
10961     return;
10962   R.setBegin(Before.getBegin());
10963   if (R.getEnd().isInvalid())
10964     R.setEnd(Before.getEnd());
10965 }
10966 
10967 static void extendRight(SourceRange &R, SourceRange After) {
10968   if (After.isInvalid())
10969     return;
10970   if (R.getBegin().isInvalid())
10971     R.setBegin(After.getBegin());
10972   R.setEnd(After.getEnd());
10973 }
10974 
10975 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
10976 /// well-formednes of the conversion function declarator @p D with
10977 /// type @p R. If there are any errors in the declarator, this routine
10978 /// will emit diagnostics and return true. Otherwise, it will return
10979 /// false. Either way, the type @p R will be updated to reflect a
10980 /// well-formed type for the conversion operator.
10981 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
10982                                      StorageClass& SC) {
10983   // C++ [class.conv.fct]p1:
10984   //   Neither parameter types nor return type can be specified. The
10985   //   type of a conversion function (8.3.5) is "function taking no
10986   //   parameter returning conversion-type-id."
10987   if (SC == SC_Static) {
10988     if (!D.isInvalidType())
10989       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
10990         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10991         << D.getName().getSourceRange();
10992     D.setInvalidType();
10993     SC = SC_None;
10994   }
10995 
10996   TypeSourceInfo *ConvTSI = nullptr;
10997   QualType ConvType =
10998       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
10999 
11000   const DeclSpec &DS = D.getDeclSpec();
11001   if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
11002     // Conversion functions don't have return types, but the parser will
11003     // happily parse something like:
11004     //
11005     //   class X {
11006     //     float operator bool();
11007     //   };
11008     //
11009     // The return type will be changed later anyway.
11010     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
11011       << SourceRange(DS.getTypeSpecTypeLoc())
11012       << SourceRange(D.getIdentifierLoc());
11013     D.setInvalidType();
11014   } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
11015     // It's also plausible that the user writes type qualifiers in the wrong
11016     // place, such as:
11017     //   struct S { const operator int(); };
11018     // FIXME: we could provide a fixit to move the qualifiers onto the
11019     // conversion type.
11020     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
11021         << SourceRange(D.getIdentifierLoc()) << 0;
11022     D.setInvalidType();
11023   }
11024 
11025   const auto *Proto = R->castAs<FunctionProtoType>();
11026 
11027   // Make sure we don't have any parameters.
11028   if (Proto->getNumParams() > 0) {
11029     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
11030 
11031     // Delete the parameters.
11032     D.getFunctionTypeInfo().freeParams();
11033     D.setInvalidType();
11034   } else if (Proto->isVariadic()) {
11035     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
11036     D.setInvalidType();
11037   }
11038 
11039   // Diagnose "&operator bool()" and other such nonsense.  This
11040   // is actually a gcc extension which we don't support.
11041   if (Proto->getReturnType() != ConvType) {
11042     bool NeedsTypedef = false;
11043     SourceRange Before, After;
11044 
11045     // Walk the chunks and extract information on them for our diagnostic.
11046     bool PastFunctionChunk = false;
11047     for (auto &Chunk : D.type_objects()) {
11048       switch (Chunk.Kind) {
11049       case DeclaratorChunk::Function:
11050         if (!PastFunctionChunk) {
11051           if (Chunk.Fun.HasTrailingReturnType) {
11052             TypeSourceInfo *TRT = nullptr;
11053             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
11054             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
11055           }
11056           PastFunctionChunk = true;
11057           break;
11058         }
11059         [[fallthrough]];
11060       case DeclaratorChunk::Array:
11061         NeedsTypedef = true;
11062         extendRight(After, Chunk.getSourceRange());
11063         break;
11064 
11065       case DeclaratorChunk::Pointer:
11066       case DeclaratorChunk::BlockPointer:
11067       case DeclaratorChunk::Reference:
11068       case DeclaratorChunk::MemberPointer:
11069       case DeclaratorChunk::Pipe:
11070         extendLeft(Before, Chunk.getSourceRange());
11071         break;
11072 
11073       case DeclaratorChunk::Paren:
11074         extendLeft(Before, Chunk.Loc);
11075         extendRight(After, Chunk.EndLoc);
11076         break;
11077       }
11078     }
11079 
11080     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
11081                          After.isValid()  ? After.getBegin() :
11082                                             D.getIdentifierLoc();
11083     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
11084     DB << Before << After;
11085 
11086     if (!NeedsTypedef) {
11087       DB << /*don't need a typedef*/0;
11088 
11089       // If we can provide a correct fix-it hint, do so.
11090       if (After.isInvalid() && ConvTSI) {
11091         SourceLocation InsertLoc =
11092             getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
11093         DB << FixItHint::CreateInsertion(InsertLoc, " ")
11094            << FixItHint::CreateInsertionFromRange(
11095                   InsertLoc, CharSourceRange::getTokenRange(Before))
11096            << FixItHint::CreateRemoval(Before);
11097       }
11098     } else if (!Proto->getReturnType()->isDependentType()) {
11099       DB << /*typedef*/1 << Proto->getReturnType();
11100     } else if (getLangOpts().CPlusPlus11) {
11101       DB << /*alias template*/2 << Proto->getReturnType();
11102     } else {
11103       DB << /*might not be fixable*/3;
11104     }
11105 
11106     // Recover by incorporating the other type chunks into the result type.
11107     // Note, this does *not* change the name of the function. This is compatible
11108     // with the GCC extension:
11109     //   struct S { &operator int(); } s;
11110     //   int &r = s.operator int(); // ok in GCC
11111     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
11112     ConvType = Proto->getReturnType();
11113   }
11114 
11115   // C++ [class.conv.fct]p4:
11116   //   The conversion-type-id shall not represent a function type nor
11117   //   an array type.
11118   if (ConvType->isArrayType()) {
11119     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
11120     ConvType = Context.getPointerType(ConvType);
11121     D.setInvalidType();
11122   } else if (ConvType->isFunctionType()) {
11123     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
11124     ConvType = Context.getPointerType(ConvType);
11125     D.setInvalidType();
11126   }
11127 
11128   // Rebuild the function type "R" without any parameters (in case any
11129   // of the errors above fired) and with the conversion type as the
11130   // return type.
11131   if (D.isInvalidType())
11132     R = Context.getFunctionType(ConvType, std::nullopt,
11133                                 Proto->getExtProtoInfo());
11134 
11135   // C++0x explicit conversion operators.
11136   if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20)
11137     Diag(DS.getExplicitSpecLoc(),
11138          getLangOpts().CPlusPlus11
11139              ? diag::warn_cxx98_compat_explicit_conversion_functions
11140              : diag::ext_explicit_conversion_functions)
11141         << SourceRange(DS.getExplicitSpecRange());
11142 }
11143 
11144 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
11145 /// the declaration of the given C++ conversion function. This routine
11146 /// is responsible for recording the conversion function in the C++
11147 /// class, if possible.
11148 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
11149   assert(Conversion && "Expected to receive a conversion function declaration");
11150 
11151   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
11152 
11153   // Make sure we aren't redeclaring the conversion function.
11154   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
11155   // C++ [class.conv.fct]p1:
11156   //   [...] A conversion function is never used to convert a
11157   //   (possibly cv-qualified) object to the (possibly cv-qualified)
11158   //   same object type (or a reference to it), to a (possibly
11159   //   cv-qualified) base class of that type (or a reference to it),
11160   //   or to (possibly cv-qualified) void.
11161   QualType ClassType
11162     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
11163   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
11164     ConvType = ConvTypeRef->getPointeeType();
11165   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
11166       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
11167     /* Suppress diagnostics for instantiations. */;
11168   else if (Conversion->size_overridden_methods() != 0)
11169     /* Suppress diagnostics for overriding virtual function in a base class. */;
11170   else if (ConvType->isRecordType()) {
11171     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
11172     if (ConvType == ClassType)
11173       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
11174         << ClassType;
11175     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
11176       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
11177         <<  ClassType << ConvType;
11178   } else if (ConvType->isVoidType()) {
11179     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
11180       << ClassType << ConvType;
11181   }
11182 
11183   if (FunctionTemplateDecl *ConversionTemplate
11184                                 = Conversion->getDescribedFunctionTemplate())
11185     return ConversionTemplate;
11186 
11187   return Conversion;
11188 }
11189 
11190 namespace {
11191 /// Utility class to accumulate and print a diagnostic listing the invalid
11192 /// specifier(s) on a declaration.
11193 struct BadSpecifierDiagnoser {
11194   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
11195       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
11196   ~BadSpecifierDiagnoser() {
11197     Diagnostic << Specifiers;
11198   }
11199 
11200   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
11201     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
11202   }
11203   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
11204     return check(SpecLoc,
11205                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
11206   }
11207   void check(SourceLocation SpecLoc, const char *Spec) {
11208     if (SpecLoc.isInvalid()) return;
11209     Diagnostic << SourceRange(SpecLoc, SpecLoc);
11210     if (!Specifiers.empty()) Specifiers += " ";
11211     Specifiers += Spec;
11212   }
11213 
11214   Sema &S;
11215   Sema::SemaDiagnosticBuilder Diagnostic;
11216   std::string Specifiers;
11217 };
11218 }
11219 
11220 /// Check the validity of a declarator that we parsed for a deduction-guide.
11221 /// These aren't actually declarators in the grammar, so we need to check that
11222 /// the user didn't specify any pieces that are not part of the deduction-guide
11223 /// grammar. Return true on invalid deduction-guide.
11224 bool Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
11225                                          StorageClass &SC) {
11226   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
11227   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
11228   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
11229 
11230   // C++ [temp.deduct.guide]p3:
11231   //   A deduction-gide shall be declared in the same scope as the
11232   //   corresponding class template.
11233   if (!CurContext->getRedeclContext()->Equals(
11234           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
11235     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
11236       << GuidedTemplateDecl;
11237     Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
11238   }
11239 
11240   auto &DS = D.getMutableDeclSpec();
11241   // We leave 'friend' and 'virtual' to be rejected in the normal way.
11242   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
11243       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
11244       DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
11245     BadSpecifierDiagnoser Diagnoser(
11246         *this, D.getIdentifierLoc(),
11247         diag::err_deduction_guide_invalid_specifier);
11248 
11249     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
11250     DS.ClearStorageClassSpecs();
11251     SC = SC_None;
11252 
11253     // 'explicit' is permitted.
11254     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
11255     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
11256     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
11257     DS.ClearConstexprSpec();
11258 
11259     Diagnoser.check(DS.getConstSpecLoc(), "const");
11260     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
11261     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
11262     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
11263     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
11264     DS.ClearTypeQualifiers();
11265 
11266     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
11267     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
11268     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
11269     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
11270     DS.ClearTypeSpecType();
11271   }
11272 
11273   if (D.isInvalidType())
11274     return true;
11275 
11276   // Check the declarator is simple enough.
11277   bool FoundFunction = false;
11278   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
11279     if (Chunk.Kind == DeclaratorChunk::Paren)
11280       continue;
11281     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
11282       Diag(D.getDeclSpec().getBeginLoc(),
11283            diag::err_deduction_guide_with_complex_decl)
11284           << D.getSourceRange();
11285       break;
11286     }
11287     if (!Chunk.Fun.hasTrailingReturnType())
11288       return Diag(D.getName().getBeginLoc(),
11289                   diag::err_deduction_guide_no_trailing_return_type);
11290 
11291     // Check that the return type is written as a specialization of
11292     // the template specified as the deduction-guide's name.
11293     // The template name may not be qualified. [temp.deduct.guide]
11294     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
11295     TypeSourceInfo *TSI = nullptr;
11296     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
11297     assert(TSI && "deduction guide has valid type but invalid return type?");
11298     bool AcceptableReturnType = false;
11299     bool MightInstantiateToSpecialization = false;
11300     if (auto RetTST =
11301             TSI->getTypeLoc().getAsAdjusted<TemplateSpecializationTypeLoc>()) {
11302       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
11303       bool TemplateMatches =
11304           Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
11305       auto TKind = SpecifiedName.getKind();
11306       // A Using TemplateName can't actually be valid (either it's qualified, or
11307       // we're in the wrong scope). But we have diagnosed these problems
11308       // already.
11309       bool SimplyWritten = TKind == TemplateName::Template ||
11310                            TKind == TemplateName::UsingTemplate;
11311       if (SimplyWritten && TemplateMatches)
11312         AcceptableReturnType = true;
11313       else {
11314         // This could still instantiate to the right type, unless we know it
11315         // names the wrong class template.
11316         auto *TD = SpecifiedName.getAsTemplateDecl();
11317         MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
11318                                              !TemplateMatches);
11319       }
11320     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
11321       MightInstantiateToSpecialization = true;
11322     }
11323 
11324     if (!AcceptableReturnType)
11325       return Diag(TSI->getTypeLoc().getBeginLoc(),
11326                   diag::err_deduction_guide_bad_trailing_return_type)
11327              << GuidedTemplate << TSI->getType()
11328              << MightInstantiateToSpecialization
11329              << TSI->getTypeLoc().getSourceRange();
11330 
11331     // Keep going to check that we don't have any inner declarator pieces (we
11332     // could still have a function returning a pointer to a function).
11333     FoundFunction = true;
11334   }
11335 
11336   if (D.isFunctionDefinition())
11337     // we can still create a valid deduction guide here.
11338     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
11339   return false;
11340 }
11341 
11342 //===----------------------------------------------------------------------===//
11343 // Namespace Handling
11344 //===----------------------------------------------------------------------===//
11345 
11346 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
11347 /// reopened.
11348 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
11349                                             SourceLocation Loc,
11350                                             IdentifierInfo *II, bool *IsInline,
11351                                             NamespaceDecl *PrevNS) {
11352   assert(*IsInline != PrevNS->isInline());
11353 
11354   // 'inline' must appear on the original definition, but not necessarily
11355   // on all extension definitions, so the note should point to the first
11356   // definition to avoid confusion.
11357   PrevNS = PrevNS->getFirstDecl();
11358 
11359   if (PrevNS->isInline())
11360     // The user probably just forgot the 'inline', so suggest that it
11361     // be added back.
11362     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
11363       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
11364   else
11365     S.Diag(Loc, diag::err_inline_namespace_mismatch);
11366 
11367   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
11368   *IsInline = PrevNS->isInline();
11369 }
11370 
11371 /// ActOnStartNamespaceDef - This is called at the start of a namespace
11372 /// definition.
11373 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
11374                                    SourceLocation InlineLoc,
11375                                    SourceLocation NamespaceLoc,
11376                                    SourceLocation IdentLoc, IdentifierInfo *II,
11377                                    SourceLocation LBrace,
11378                                    const ParsedAttributesView &AttrList,
11379                                    UsingDirectiveDecl *&UD, bool IsNested) {
11380   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
11381   // For anonymous namespace, take the location of the left brace.
11382   SourceLocation Loc = II ? IdentLoc : LBrace;
11383   bool IsInline = InlineLoc.isValid();
11384   bool IsInvalid = false;
11385   bool IsStd = false;
11386   bool AddToKnown = false;
11387   Scope *DeclRegionScope = NamespcScope->getParent();
11388 
11389   NamespaceDecl *PrevNS = nullptr;
11390   if (II) {
11391     // C++ [namespace.std]p7:
11392     //   A translation unit shall not declare namespace std to be an inline
11393     //   namespace (9.8.2).
11394     //
11395     // Precondition: the std namespace is in the file scope and is declared to
11396     // be inline
11397     auto DiagnoseInlineStdNS = [&]() {
11398       assert(IsInline && II->isStr("std") &&
11399              CurContext->getRedeclContext()->isTranslationUnit() &&
11400              "Precondition of DiagnoseInlineStdNS not met");
11401       Diag(InlineLoc, diag::err_inline_namespace_std)
11402           << SourceRange(InlineLoc, InlineLoc.getLocWithOffset(6));
11403       IsInline = false;
11404     };
11405     // C++ [namespace.def]p2:
11406     //   The identifier in an original-namespace-definition shall not
11407     //   have been previously defined in the declarative region in
11408     //   which the original-namespace-definition appears. The
11409     //   identifier in an original-namespace-definition is the name of
11410     //   the namespace. Subsequently in that declarative region, it is
11411     //   treated as an original-namespace-name.
11412     //
11413     // Since namespace names are unique in their scope, and we don't
11414     // look through using directives, just look for any ordinary names
11415     // as if by qualified name lookup.
11416     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
11417                    ForExternalRedeclaration);
11418     LookupQualifiedName(R, CurContext->getRedeclContext());
11419     NamedDecl *PrevDecl =
11420         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
11421     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
11422 
11423     if (PrevNS) {
11424       // This is an extended namespace definition.
11425       if (IsInline && II->isStr("std") &&
11426           CurContext->getRedeclContext()->isTranslationUnit())
11427         DiagnoseInlineStdNS();
11428       else if (IsInline != PrevNS->isInline())
11429         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
11430                                         &IsInline, PrevNS);
11431     } else if (PrevDecl) {
11432       // This is an invalid name redefinition.
11433       Diag(Loc, diag::err_redefinition_different_kind)
11434         << II;
11435       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11436       IsInvalid = true;
11437       // Continue on to push Namespc as current DeclContext and return it.
11438     } else if (II->isStr("std") &&
11439                CurContext->getRedeclContext()->isTranslationUnit()) {
11440       if (IsInline)
11441         DiagnoseInlineStdNS();
11442       // This is the first "real" definition of the namespace "std", so update
11443       // our cache of the "std" namespace to point at this definition.
11444       PrevNS = getStdNamespace();
11445       IsStd = true;
11446       AddToKnown = !IsInline;
11447     } else {
11448       // We've seen this namespace for the first time.
11449       AddToKnown = !IsInline;
11450     }
11451   } else {
11452     // Anonymous namespaces.
11453 
11454     // Determine whether the parent already has an anonymous namespace.
11455     DeclContext *Parent = CurContext->getRedeclContext();
11456     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11457       PrevNS = TU->getAnonymousNamespace();
11458     } else {
11459       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
11460       PrevNS = ND->getAnonymousNamespace();
11461     }
11462 
11463     if (PrevNS && IsInline != PrevNS->isInline())
11464       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
11465                                       &IsInline, PrevNS);
11466   }
11467 
11468   NamespaceDecl *Namespc = NamespaceDecl::Create(
11469       Context, CurContext, IsInline, StartLoc, Loc, II, PrevNS, IsNested);
11470   if (IsInvalid)
11471     Namespc->setInvalidDecl();
11472 
11473   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
11474   AddPragmaAttributes(DeclRegionScope, Namespc);
11475 
11476   // FIXME: Should we be merging attributes?
11477   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
11478     PushNamespaceVisibilityAttr(Attr, Loc);
11479 
11480   if (IsStd)
11481     StdNamespace = Namespc;
11482   if (AddToKnown)
11483     KnownNamespaces[Namespc] = false;
11484 
11485   if (II) {
11486     PushOnScopeChains(Namespc, DeclRegionScope);
11487   } else {
11488     // Link the anonymous namespace into its parent.
11489     DeclContext *Parent = CurContext->getRedeclContext();
11490     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11491       TU->setAnonymousNamespace(Namespc);
11492     } else {
11493       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
11494     }
11495 
11496     CurContext->addDecl(Namespc);
11497 
11498     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
11499     //   behaves as if it were replaced by
11500     //     namespace unique { /* empty body */ }
11501     //     using namespace unique;
11502     //     namespace unique { namespace-body }
11503     //   where all occurrences of 'unique' in a translation unit are
11504     //   replaced by the same identifier and this identifier differs
11505     //   from all other identifiers in the entire program.
11506 
11507     // We just create the namespace with an empty name and then add an
11508     // implicit using declaration, just like the standard suggests.
11509     //
11510     // CodeGen enforces the "universally unique" aspect by giving all
11511     // declarations semantically contained within an anonymous
11512     // namespace internal linkage.
11513 
11514     if (!PrevNS) {
11515       UD = UsingDirectiveDecl::Create(Context, Parent,
11516                                       /* 'using' */ LBrace,
11517                                       /* 'namespace' */ SourceLocation(),
11518                                       /* qualifier */ NestedNameSpecifierLoc(),
11519                                       /* identifier */ SourceLocation(),
11520                                       Namespc,
11521                                       /* Ancestor */ Parent);
11522       UD->setImplicit();
11523       Parent->addDecl(UD);
11524     }
11525   }
11526 
11527   ActOnDocumentableDecl(Namespc);
11528 
11529   // Although we could have an invalid decl (i.e. the namespace name is a
11530   // redefinition), push it as current DeclContext and try to continue parsing.
11531   // FIXME: We should be able to push Namespc here, so that the each DeclContext
11532   // for the namespace has the declarations that showed up in that particular
11533   // namespace definition.
11534   PushDeclContext(NamespcScope, Namespc);
11535   return Namespc;
11536 }
11537 
11538 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
11539 /// is a namespace alias, returns the namespace it points to.
11540 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
11541   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
11542     return AD->getNamespace();
11543   return dyn_cast_or_null<NamespaceDecl>(D);
11544 }
11545 
11546 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
11547 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
11548 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
11549   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
11550   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
11551   Namespc->setRBraceLoc(RBrace);
11552   PopDeclContext();
11553   if (Namespc->hasAttr<VisibilityAttr>())
11554     PopPragmaVisibility(true, RBrace);
11555   // If this namespace contains an export-declaration, export it now.
11556   if (DeferredExportedNamespaces.erase(Namespc))
11557     Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
11558 }
11559 
11560 CXXRecordDecl *Sema::getStdBadAlloc() const {
11561   return cast_or_null<CXXRecordDecl>(
11562                                   StdBadAlloc.get(Context.getExternalSource()));
11563 }
11564 
11565 EnumDecl *Sema::getStdAlignValT() const {
11566   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
11567 }
11568 
11569 NamespaceDecl *Sema::getStdNamespace() const {
11570   return cast_or_null<NamespaceDecl>(
11571                                  StdNamespace.get(Context.getExternalSource()));
11572 }
11573 namespace {
11574 
11575 enum UnsupportedSTLSelect {
11576   USS_InvalidMember,
11577   USS_MissingMember,
11578   USS_NonTrivial,
11579   USS_Other
11580 };
11581 
11582 struct InvalidSTLDiagnoser {
11583   Sema &S;
11584   SourceLocation Loc;
11585   QualType TyForDiags;
11586 
11587   QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
11588                       const VarDecl *VD = nullptr) {
11589     {
11590       auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
11591                << TyForDiags << ((int)Sel);
11592       if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
11593         assert(!Name.empty());
11594         D << Name;
11595       }
11596     }
11597     if (Sel == USS_InvalidMember) {
11598       S.Diag(VD->getLocation(), diag::note_var_declared_here)
11599           << VD << VD->getSourceRange();
11600     }
11601     return QualType();
11602   }
11603 };
11604 } // namespace
11605 
11606 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
11607                                            SourceLocation Loc,
11608                                            ComparisonCategoryUsage Usage) {
11609   assert(getLangOpts().CPlusPlus &&
11610          "Looking for comparison category type outside of C++.");
11611 
11612   // Use an elaborated type for diagnostics which has a name containing the
11613   // prepended 'std' namespace but not any inline namespace names.
11614   auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
11615     auto *NNS =
11616         NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
11617     return Context.getElaboratedType(ETK_None, NNS, Info->getType());
11618   };
11619 
11620   // Check if we've already successfully checked the comparison category type
11621   // before. If so, skip checking it again.
11622   ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
11623   if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
11624     // The only thing we need to check is that the type has a reachable
11625     // definition in the current context.
11626     if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11627       return QualType();
11628 
11629     return Info->getType();
11630   }
11631 
11632   // If lookup failed
11633   if (!Info) {
11634     std::string NameForDiags = "std::";
11635     NameForDiags += ComparisonCategories::getCategoryString(Kind);
11636     Diag(Loc, diag::err_implied_comparison_category_type_not_found)
11637         << NameForDiags << (int)Usage;
11638     return QualType();
11639   }
11640 
11641   assert(Info->Kind == Kind);
11642   assert(Info->Record);
11643 
11644   // Update the Record decl in case we encountered a forward declaration on our
11645   // first pass. FIXME: This is a bit of a hack.
11646   if (Info->Record->hasDefinition())
11647     Info->Record = Info->Record->getDefinition();
11648 
11649   if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11650     return QualType();
11651 
11652   InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
11653 
11654   if (!Info->Record->isTriviallyCopyable())
11655     return UnsupportedSTLError(USS_NonTrivial);
11656 
11657   for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
11658     CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
11659     // Tolerate empty base classes.
11660     if (Base->isEmpty())
11661       continue;
11662     // Reject STL implementations which have at least one non-empty base.
11663     return UnsupportedSTLError();
11664   }
11665 
11666   // Check that the STL has implemented the types using a single integer field.
11667   // This expectation allows better codegen for builtin operators. We require:
11668   //   (1) The class has exactly one field.
11669   //   (2) The field is an integral or enumeration type.
11670   auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
11671   if (std::distance(FIt, FEnd) != 1 ||
11672       !FIt->getType()->isIntegralOrEnumerationType()) {
11673     return UnsupportedSTLError();
11674   }
11675 
11676   // Build each of the require values and store them in Info.
11677   for (ComparisonCategoryResult CCR :
11678        ComparisonCategories::getPossibleResultsForType(Kind)) {
11679     StringRef MemName = ComparisonCategories::getResultString(CCR);
11680     ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
11681 
11682     if (!ValInfo)
11683       return UnsupportedSTLError(USS_MissingMember, MemName);
11684 
11685     VarDecl *VD = ValInfo->VD;
11686     assert(VD && "should not be null!");
11687 
11688     // Attempt to diagnose reasons why the STL definition of this type
11689     // might be foobar, including it failing to be a constant expression.
11690     // TODO Handle more ways the lookup or result can be invalid.
11691     if (!VD->isStaticDataMember() ||
11692         !VD->isUsableInConstantExpressions(Context))
11693       return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
11694 
11695     // Attempt to evaluate the var decl as a constant expression and extract
11696     // the value of its first field as a ICE. If this fails, the STL
11697     // implementation is not supported.
11698     if (!ValInfo->hasValidIntValue())
11699       return UnsupportedSTLError();
11700 
11701     MarkVariableReferenced(Loc, VD);
11702   }
11703 
11704   // We've successfully built the required types and expressions. Update
11705   // the cache and return the newly cached value.
11706   FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
11707   return Info->getType();
11708 }
11709 
11710 /// Retrieve the special "std" namespace, which may require us to
11711 /// implicitly define the namespace.
11712 NamespaceDecl *Sema::getOrCreateStdNamespace() {
11713   if (!StdNamespace) {
11714     // The "std" namespace has not yet been defined, so build one implicitly.
11715     StdNamespace = NamespaceDecl::Create(
11716         Context, Context.getTranslationUnitDecl(),
11717         /*Inline=*/false, SourceLocation(), SourceLocation(),
11718         &PP.getIdentifierTable().get("std"),
11719         /*PrevDecl=*/nullptr, /*Nested=*/false);
11720     getStdNamespace()->setImplicit(true);
11721     // We want the created NamespaceDecl to be available for redeclaration
11722     // lookups, but not for regular name lookups.
11723     Context.getTranslationUnitDecl()->addDecl(getStdNamespace());
11724     getStdNamespace()->clearIdentifierNamespace();
11725   }
11726 
11727   return getStdNamespace();
11728 }
11729 
11730 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
11731   assert(getLangOpts().CPlusPlus &&
11732          "Looking for std::initializer_list outside of C++.");
11733 
11734   // We're looking for implicit instantiations of
11735   // template <typename E> class std::initializer_list.
11736 
11737   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
11738     return false;
11739 
11740   ClassTemplateDecl *Template = nullptr;
11741   const TemplateArgument *Arguments = nullptr;
11742 
11743   if (const RecordType *RT = Ty->getAs<RecordType>()) {
11744 
11745     ClassTemplateSpecializationDecl *Specialization =
11746         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
11747     if (!Specialization)
11748       return false;
11749 
11750     Template = Specialization->getSpecializedTemplate();
11751     Arguments = Specialization->getTemplateArgs().data();
11752   } else if (const TemplateSpecializationType *TST =
11753                  Ty->getAs<TemplateSpecializationType>()) {
11754     Template = dyn_cast_or_null<ClassTemplateDecl>(
11755         TST->getTemplateName().getAsTemplateDecl());
11756     Arguments = TST->template_arguments().begin();
11757   }
11758   if (!Template)
11759     return false;
11760 
11761   if (!StdInitializerList) {
11762     // Haven't recognized std::initializer_list yet, maybe this is it.
11763     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
11764     if (TemplateClass->getIdentifier() !=
11765             &PP.getIdentifierTable().get("initializer_list") ||
11766         !getStdNamespace()->InEnclosingNamespaceSetOf(
11767             TemplateClass->getDeclContext()))
11768       return false;
11769     // This is a template called std::initializer_list, but is it the right
11770     // template?
11771     TemplateParameterList *Params = Template->getTemplateParameters();
11772     if (Params->getMinRequiredArguments() != 1)
11773       return false;
11774     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
11775       return false;
11776 
11777     // It's the right template.
11778     StdInitializerList = Template;
11779   }
11780 
11781   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
11782     return false;
11783 
11784   // This is an instance of std::initializer_list. Find the argument type.
11785   if (Element)
11786     *Element = Arguments[0].getAsType();
11787   return true;
11788 }
11789 
11790 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
11791   NamespaceDecl *Std = S.getStdNamespace();
11792   if (!Std) {
11793     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11794     return nullptr;
11795   }
11796 
11797   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
11798                       Loc, Sema::LookupOrdinaryName);
11799   if (!S.LookupQualifiedName(Result, Std)) {
11800     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11801     return nullptr;
11802   }
11803   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
11804   if (!Template) {
11805     Result.suppressDiagnostics();
11806     // We found something weird. Complain about the first thing we found.
11807     NamedDecl *Found = *Result.begin();
11808     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
11809     return nullptr;
11810   }
11811 
11812   // We found some template called std::initializer_list. Now verify that it's
11813   // correct.
11814   TemplateParameterList *Params = Template->getTemplateParameters();
11815   if (Params->getMinRequiredArguments() != 1 ||
11816       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
11817     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
11818     return nullptr;
11819   }
11820 
11821   return Template;
11822 }
11823 
11824 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
11825   if (!StdInitializerList) {
11826     StdInitializerList = LookupStdInitializerList(*this, Loc);
11827     if (!StdInitializerList)
11828       return QualType();
11829   }
11830 
11831   TemplateArgumentListInfo Args(Loc, Loc);
11832   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
11833                                        Context.getTrivialTypeSourceInfo(Element,
11834                                                                         Loc)));
11835   return Context.getElaboratedType(
11836       ElaboratedTypeKeyword::ETK_None,
11837       NestedNameSpecifier::Create(Context, nullptr, getStdNamespace()),
11838       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
11839 }
11840 
11841 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
11842   // C++ [dcl.init.list]p2:
11843   //   A constructor is an initializer-list constructor if its first parameter
11844   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
11845   //   std::initializer_list<E> for some type E, and either there are no other
11846   //   parameters or else all other parameters have default arguments.
11847   if (!Ctor->hasOneParamOrDefaultArgs())
11848     return false;
11849 
11850   QualType ArgType = Ctor->getParamDecl(0)->getType();
11851   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
11852     ArgType = RT->getPointeeType().getUnqualifiedType();
11853 
11854   return isStdInitializerList(ArgType, nullptr);
11855 }
11856 
11857 /// Determine whether a using statement is in a context where it will be
11858 /// apply in all contexts.
11859 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
11860   switch (CurContext->getDeclKind()) {
11861     case Decl::TranslationUnit:
11862       return true;
11863     case Decl::LinkageSpec:
11864       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
11865     default:
11866       return false;
11867   }
11868 }
11869 
11870 namespace {
11871 
11872 // Callback to only accept typo corrections that are namespaces.
11873 class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
11874 public:
11875   bool ValidateCandidate(const TypoCorrection &candidate) override {
11876     if (NamedDecl *ND = candidate.getCorrectionDecl())
11877       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
11878     return false;
11879   }
11880 
11881   std::unique_ptr<CorrectionCandidateCallback> clone() override {
11882     return std::make_unique<NamespaceValidatorCCC>(*this);
11883   }
11884 };
11885 
11886 }
11887 
11888 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
11889                                        CXXScopeSpec &SS,
11890                                        SourceLocation IdentLoc,
11891                                        IdentifierInfo *Ident) {
11892   R.clear();
11893   NamespaceValidatorCCC CCC{};
11894   if (TypoCorrection Corrected =
11895           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
11896                         Sema::CTK_ErrorRecovery)) {
11897     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
11898       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
11899       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
11900                               Ident->getName().equals(CorrectedStr);
11901       S.diagnoseTypo(Corrected,
11902                      S.PDiag(diag::err_using_directive_member_suggest)
11903                        << Ident << DC << DroppedSpecifier << SS.getRange(),
11904                      S.PDiag(diag::note_namespace_defined_here));
11905     } else {
11906       S.diagnoseTypo(Corrected,
11907                      S.PDiag(diag::err_using_directive_suggest) << Ident,
11908                      S.PDiag(diag::note_namespace_defined_here));
11909     }
11910     R.addDecl(Corrected.getFoundDecl());
11911     return true;
11912   }
11913   return false;
11914 }
11915 
11916 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
11917                                 SourceLocation NamespcLoc, CXXScopeSpec &SS,
11918                                 SourceLocation IdentLoc,
11919                                 IdentifierInfo *NamespcName,
11920                                 const ParsedAttributesView &AttrList) {
11921   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
11922   assert(NamespcName && "Invalid NamespcName.");
11923   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
11924 
11925   // This can only happen along a recovery path.
11926   while (S->isTemplateParamScope())
11927     S = S->getParent();
11928   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11929 
11930   UsingDirectiveDecl *UDir = nullptr;
11931   NestedNameSpecifier *Qualifier = nullptr;
11932   if (SS.isSet())
11933     Qualifier = SS.getScopeRep();
11934 
11935   // Lookup namespace name.
11936   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
11937   LookupParsedName(R, S, &SS);
11938   if (R.isAmbiguous())
11939     return nullptr;
11940 
11941   if (R.empty()) {
11942     R.clear();
11943     // Allow "using namespace std;" or "using namespace ::std;" even if
11944     // "std" hasn't been defined yet, for GCC compatibility.
11945     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
11946         NamespcName->isStr("std")) {
11947       Diag(IdentLoc, diag::ext_using_undefined_std);
11948       R.addDecl(getOrCreateStdNamespace());
11949       R.resolveKind();
11950     }
11951     // Otherwise, attempt typo correction.
11952     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
11953   }
11954 
11955   if (!R.empty()) {
11956     NamedDecl *Named = R.getRepresentativeDecl();
11957     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
11958     assert(NS && "expected namespace decl");
11959 
11960     // The use of a nested name specifier may trigger deprecation warnings.
11961     DiagnoseUseOfDecl(Named, IdentLoc);
11962 
11963     // C++ [namespace.udir]p1:
11964     //   A using-directive specifies that the names in the nominated
11965     //   namespace can be used in the scope in which the
11966     //   using-directive appears after the using-directive. During
11967     //   unqualified name lookup (3.4.1), the names appear as if they
11968     //   were declared in the nearest enclosing namespace which
11969     //   contains both the using-directive and the nominated
11970     //   namespace. [Note: in this context, "contains" means "contains
11971     //   directly or indirectly". ]
11972 
11973     // Find enclosing context containing both using-directive and
11974     // nominated namespace.
11975     DeclContext *CommonAncestor = NS;
11976     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
11977       CommonAncestor = CommonAncestor->getParent();
11978 
11979     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
11980                                       SS.getWithLocInContext(Context),
11981                                       IdentLoc, Named, CommonAncestor);
11982 
11983     if (IsUsingDirectiveInToplevelContext(CurContext) &&
11984         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
11985       Diag(IdentLoc, diag::warn_using_directive_in_header);
11986     }
11987 
11988     PushUsingDirective(S, UDir);
11989   } else {
11990     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
11991   }
11992 
11993   if (UDir)
11994     ProcessDeclAttributeList(S, UDir, AttrList);
11995 
11996   return UDir;
11997 }
11998 
11999 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
12000   // If the scope has an associated entity and the using directive is at
12001   // namespace or translation unit scope, add the UsingDirectiveDecl into
12002   // its lookup structure so qualified name lookup can find it.
12003   DeclContext *Ctx = S->getEntity();
12004   if (Ctx && !Ctx->isFunctionOrMethod())
12005     Ctx->addDecl(UDir);
12006   else
12007     // Otherwise, it is at block scope. The using-directives will affect lookup
12008     // only to the end of the scope.
12009     S->PushUsingDirective(UDir);
12010 }
12011 
12012 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
12013                                   SourceLocation UsingLoc,
12014                                   SourceLocation TypenameLoc, CXXScopeSpec &SS,
12015                                   UnqualifiedId &Name,
12016                                   SourceLocation EllipsisLoc,
12017                                   const ParsedAttributesView &AttrList) {
12018   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
12019 
12020   if (SS.isEmpty()) {
12021     Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
12022     return nullptr;
12023   }
12024 
12025   switch (Name.getKind()) {
12026   case UnqualifiedIdKind::IK_ImplicitSelfParam:
12027   case UnqualifiedIdKind::IK_Identifier:
12028   case UnqualifiedIdKind::IK_OperatorFunctionId:
12029   case UnqualifiedIdKind::IK_LiteralOperatorId:
12030   case UnqualifiedIdKind::IK_ConversionFunctionId:
12031     break;
12032 
12033   case UnqualifiedIdKind::IK_ConstructorName:
12034   case UnqualifiedIdKind::IK_ConstructorTemplateId:
12035     // C++11 inheriting constructors.
12036     Diag(Name.getBeginLoc(),
12037          getLangOpts().CPlusPlus11
12038              ? diag::warn_cxx98_compat_using_decl_constructor
12039              : diag::err_using_decl_constructor)
12040         << SS.getRange();
12041 
12042     if (getLangOpts().CPlusPlus11) break;
12043 
12044     return nullptr;
12045 
12046   case UnqualifiedIdKind::IK_DestructorName:
12047     Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
12048     return nullptr;
12049 
12050   case UnqualifiedIdKind::IK_TemplateId:
12051     Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
12052         << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
12053     return nullptr;
12054 
12055   case UnqualifiedIdKind::IK_DeductionGuideName:
12056     llvm_unreachable("cannot parse qualified deduction guide name");
12057   }
12058 
12059   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
12060   DeclarationName TargetName = TargetNameInfo.getName();
12061   if (!TargetName)
12062     return nullptr;
12063 
12064   // Warn about access declarations.
12065   if (UsingLoc.isInvalid()) {
12066     Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
12067                                  ? diag::err_access_decl
12068                                  : diag::warn_access_decl_deprecated)
12069         << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
12070   }
12071 
12072   if (EllipsisLoc.isInvalid()) {
12073     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
12074         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
12075       return nullptr;
12076   } else {
12077     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
12078         !TargetNameInfo.containsUnexpandedParameterPack()) {
12079       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
12080         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
12081       EllipsisLoc = SourceLocation();
12082     }
12083   }
12084 
12085   NamedDecl *UD =
12086       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
12087                             SS, TargetNameInfo, EllipsisLoc, AttrList,
12088                             /*IsInstantiation*/ false,
12089                             AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists));
12090   if (UD)
12091     PushOnScopeChains(UD, S, /*AddToContext*/ false);
12092 
12093   return UD;
12094 }
12095 
12096 Decl *Sema::ActOnUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
12097                                       SourceLocation UsingLoc,
12098                                       SourceLocation EnumLoc,
12099                                       SourceLocation IdentLoc,
12100                                       IdentifierInfo &II, CXXScopeSpec *SS) {
12101   assert(!SS->isInvalid() && "ScopeSpec is invalid");
12102   TypeSourceInfo *TSI = nullptr;
12103   QualType EnumTy = GetTypeFromParser(
12104       getTypeName(II, IdentLoc, S, SS, /*isClassName=*/false,
12105                   /*HasTrailingDot=*/false,
12106                   /*ObjectType=*/nullptr, /*IsCtorOrDtorName=*/false,
12107                   /*WantNontrivialTypeSourceInfo=*/true),
12108       &TSI);
12109   if (EnumTy.isNull()) {
12110     Diag(IdentLoc, SS && isDependentScopeSpecifier(*SS)
12111                        ? diag::err_using_enum_is_dependent
12112                        : diag::err_unknown_typename)
12113         << II.getName()
12114         << SourceRange(SS ? SS->getBeginLoc() : IdentLoc, IdentLoc);
12115     return nullptr;
12116   }
12117 
12118   auto *Enum = dyn_cast_if_present<EnumDecl>(EnumTy->getAsTagDecl());
12119   if (!Enum) {
12120     Diag(IdentLoc, diag::err_using_enum_not_enum) << EnumTy;
12121     return nullptr;
12122   }
12123 
12124   if (auto *Def = Enum->getDefinition())
12125     Enum = Def;
12126 
12127   if (TSI == nullptr)
12128     TSI = Context.getTrivialTypeSourceInfo(EnumTy, IdentLoc);
12129 
12130   auto *UD =
12131       BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, IdentLoc, TSI, Enum);
12132 
12133   if (UD)
12134     PushOnScopeChains(UD, S, /*AddToContext*/ false);
12135 
12136   return UD;
12137 }
12138 
12139 /// Determine whether a using declaration considers the given
12140 /// declarations as "equivalent", e.g., if they are redeclarations of
12141 /// the same entity or are both typedefs of the same type.
12142 static bool
12143 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
12144   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
12145     return true;
12146 
12147   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
12148     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
12149       return Context.hasSameType(TD1->getUnderlyingType(),
12150                                  TD2->getUnderlyingType());
12151 
12152   // Two using_if_exists using-declarations are equivalent if both are
12153   // unresolved.
12154   if (isa<UnresolvedUsingIfExistsDecl>(D1) &&
12155       isa<UnresolvedUsingIfExistsDecl>(D2))
12156     return true;
12157 
12158   return false;
12159 }
12160 
12161 
12162 /// Determines whether to create a using shadow decl for a particular
12163 /// decl, given the set of decls existing prior to this using lookup.
12164 bool Sema::CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Orig,
12165                                 const LookupResult &Previous,
12166                                 UsingShadowDecl *&PrevShadow) {
12167   // Diagnose finding a decl which is not from a base class of the
12168   // current class.  We do this now because there are cases where this
12169   // function will silently decide not to build a shadow decl, which
12170   // will pre-empt further diagnostics.
12171   //
12172   // We don't need to do this in C++11 because we do the check once on
12173   // the qualifier.
12174   //
12175   // FIXME: diagnose the following if we care enough:
12176   //   struct A { int foo; };
12177   //   struct B : A { using A::foo; };
12178   //   template <class T> struct C : A {};
12179   //   template <class T> struct D : C<T> { using B::foo; } // <---
12180   // This is invalid (during instantiation) in C++03 because B::foo
12181   // resolves to the using decl in B, which is not a base class of D<T>.
12182   // We can't diagnose it immediately because C<T> is an unknown
12183   // specialization. The UsingShadowDecl in D<T> then points directly
12184   // to A::foo, which will look well-formed when we instantiate.
12185   // The right solution is to not collapse the shadow-decl chain.
12186   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord())
12187     if (auto *Using = dyn_cast<UsingDecl>(BUD)) {
12188       DeclContext *OrigDC = Orig->getDeclContext();
12189 
12190       // Handle enums and anonymous structs.
12191       if (isa<EnumDecl>(OrigDC))
12192         OrigDC = OrigDC->getParent();
12193       CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
12194       while (OrigRec->isAnonymousStructOrUnion())
12195         OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
12196 
12197       if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
12198         if (OrigDC == CurContext) {
12199           Diag(Using->getLocation(),
12200                diag::err_using_decl_nested_name_specifier_is_current_class)
12201               << Using->getQualifierLoc().getSourceRange();
12202           Diag(Orig->getLocation(), diag::note_using_decl_target);
12203           Using->setInvalidDecl();
12204           return true;
12205         }
12206 
12207         Diag(Using->getQualifierLoc().getBeginLoc(),
12208              diag::err_using_decl_nested_name_specifier_is_not_base_class)
12209             << Using->getQualifier() << cast<CXXRecordDecl>(CurContext)
12210             << Using->getQualifierLoc().getSourceRange();
12211         Diag(Orig->getLocation(), diag::note_using_decl_target);
12212         Using->setInvalidDecl();
12213         return true;
12214       }
12215     }
12216 
12217   if (Previous.empty()) return false;
12218 
12219   NamedDecl *Target = Orig;
12220   if (isa<UsingShadowDecl>(Target))
12221     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12222 
12223   // If the target happens to be one of the previous declarations, we
12224   // don't have a conflict.
12225   //
12226   // FIXME: but we might be increasing its access, in which case we
12227   // should redeclare it.
12228   NamedDecl *NonTag = nullptr, *Tag = nullptr;
12229   bool FoundEquivalentDecl = false;
12230   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
12231          I != E; ++I) {
12232     NamedDecl *D = (*I)->getUnderlyingDecl();
12233     // We can have UsingDecls in our Previous results because we use the same
12234     // LookupResult for checking whether the UsingDecl itself is a valid
12235     // redeclaration.
12236     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D) || isa<UsingEnumDecl>(D))
12237       continue;
12238 
12239     if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
12240       // C++ [class.mem]p19:
12241       //   If T is the name of a class, then [every named member other than
12242       //   a non-static data member] shall have a name different from T
12243       if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
12244           !isa<IndirectFieldDecl>(Target) &&
12245           !isa<UnresolvedUsingValueDecl>(Target) &&
12246           DiagnoseClassNameShadow(
12247               CurContext,
12248               DeclarationNameInfo(BUD->getDeclName(), BUD->getLocation())))
12249         return true;
12250     }
12251 
12252     if (IsEquivalentForUsingDecl(Context, D, Target)) {
12253       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
12254         PrevShadow = Shadow;
12255       FoundEquivalentDecl = true;
12256     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
12257       // We don't conflict with an existing using shadow decl of an equivalent
12258       // declaration, but we're not a redeclaration of it.
12259       FoundEquivalentDecl = true;
12260     }
12261 
12262     if (isVisible(D))
12263       (isa<TagDecl>(D) ? Tag : NonTag) = D;
12264   }
12265 
12266   if (FoundEquivalentDecl)
12267     return false;
12268 
12269   // Always emit a diagnostic for a mismatch between an unresolved
12270   // using_if_exists and a resolved using declaration in either direction.
12271   if (isa<UnresolvedUsingIfExistsDecl>(Target) !=
12272       (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) {
12273     if (!NonTag && !Tag)
12274       return false;
12275     Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12276     Diag(Target->getLocation(), diag::note_using_decl_target);
12277     Diag((NonTag ? NonTag : Tag)->getLocation(),
12278          diag::note_using_decl_conflict);
12279     BUD->setInvalidDecl();
12280     return true;
12281   }
12282 
12283   if (FunctionDecl *FD = Target->getAsFunction()) {
12284     NamedDecl *OldDecl = nullptr;
12285     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
12286                           /*IsForUsingDecl*/ true)) {
12287     case Ovl_Overload:
12288       return false;
12289 
12290     case Ovl_NonFunction:
12291       Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12292       break;
12293 
12294     // We found a decl with the exact signature.
12295     case Ovl_Match:
12296       // If we're in a record, we want to hide the target, so we
12297       // return true (without a diagnostic) to tell the caller not to
12298       // build a shadow decl.
12299       if (CurContext->isRecord())
12300         return true;
12301 
12302       // If we're not in a record, this is an error.
12303       Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12304       break;
12305     }
12306 
12307     Diag(Target->getLocation(), diag::note_using_decl_target);
12308     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
12309     BUD->setInvalidDecl();
12310     return true;
12311   }
12312 
12313   // Target is not a function.
12314 
12315   if (isa<TagDecl>(Target)) {
12316     // No conflict between a tag and a non-tag.
12317     if (!Tag) return false;
12318 
12319     Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12320     Diag(Target->getLocation(), diag::note_using_decl_target);
12321     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
12322     BUD->setInvalidDecl();
12323     return true;
12324   }
12325 
12326   // No conflict between a tag and a non-tag.
12327   if (!NonTag) return false;
12328 
12329   Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12330   Diag(Target->getLocation(), diag::note_using_decl_target);
12331   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
12332   BUD->setInvalidDecl();
12333   return true;
12334 }
12335 
12336 /// Determine whether a direct base class is a virtual base class.
12337 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
12338   if (!Derived->getNumVBases())
12339     return false;
12340   for (auto &B : Derived->bases())
12341     if (B.getType()->getAsCXXRecordDecl() == Base)
12342       return B.isVirtual();
12343   llvm_unreachable("not a direct base class");
12344 }
12345 
12346 /// Builds a shadow declaration corresponding to a 'using' declaration.
12347 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
12348                                             NamedDecl *Orig,
12349                                             UsingShadowDecl *PrevDecl) {
12350   // If we resolved to another shadow declaration, just coalesce them.
12351   NamedDecl *Target = Orig;
12352   if (isa<UsingShadowDecl>(Target)) {
12353     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12354     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
12355   }
12356 
12357   NamedDecl *NonTemplateTarget = Target;
12358   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
12359     NonTemplateTarget = TargetTD->getTemplatedDecl();
12360 
12361   UsingShadowDecl *Shadow;
12362   if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
12363     UsingDecl *Using = cast<UsingDecl>(BUD);
12364     bool IsVirtualBase =
12365         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
12366                             Using->getQualifier()->getAsRecordDecl());
12367     Shadow = ConstructorUsingShadowDecl::Create(
12368         Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase);
12369   } else {
12370     Shadow = UsingShadowDecl::Create(Context, CurContext, BUD->getLocation(),
12371                                      Target->getDeclName(), BUD, Target);
12372   }
12373   BUD->addShadowDecl(Shadow);
12374 
12375   Shadow->setAccess(BUD->getAccess());
12376   if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
12377     Shadow->setInvalidDecl();
12378 
12379   Shadow->setPreviousDecl(PrevDecl);
12380 
12381   if (S)
12382     PushOnScopeChains(Shadow, S);
12383   else
12384     CurContext->addDecl(Shadow);
12385 
12386 
12387   return Shadow;
12388 }
12389 
12390 /// Hides a using shadow declaration.  This is required by the current
12391 /// using-decl implementation when a resolvable using declaration in a
12392 /// class is followed by a declaration which would hide or override
12393 /// one or more of the using decl's targets; for example:
12394 ///
12395 ///   struct Base { void foo(int); };
12396 ///   struct Derived : Base {
12397 ///     using Base::foo;
12398 ///     void foo(int);
12399 ///   };
12400 ///
12401 /// The governing language is C++03 [namespace.udecl]p12:
12402 ///
12403 ///   When a using-declaration brings names from a base class into a
12404 ///   derived class scope, member functions in the derived class
12405 ///   override and/or hide member functions with the same name and
12406 ///   parameter types in a base class (rather than conflicting).
12407 ///
12408 /// There are two ways to implement this:
12409 ///   (1) optimistically create shadow decls when they're not hidden
12410 ///       by existing declarations, or
12411 ///   (2) don't create any shadow decls (or at least don't make them
12412 ///       visible) until we've fully parsed/instantiated the class.
12413 /// The problem with (1) is that we might have to retroactively remove
12414 /// a shadow decl, which requires several O(n) operations because the
12415 /// decl structures are (very reasonably) not designed for removal.
12416 /// (2) avoids this but is very fiddly and phase-dependent.
12417 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
12418   if (Shadow->getDeclName().getNameKind() ==
12419         DeclarationName::CXXConversionFunctionName)
12420     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
12421 
12422   // Remove it from the DeclContext...
12423   Shadow->getDeclContext()->removeDecl(Shadow);
12424 
12425   // ...and the scope, if applicable...
12426   if (S) {
12427     S->RemoveDecl(Shadow);
12428     IdResolver.RemoveDecl(Shadow);
12429   }
12430 
12431   // ...and the using decl.
12432   Shadow->getIntroducer()->removeShadowDecl(Shadow);
12433 
12434   // TODO: complain somehow if Shadow was used.  It shouldn't
12435   // be possible for this to happen, because...?
12436 }
12437 
12438 /// Find the base specifier for a base class with the given type.
12439 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
12440                                                 QualType DesiredBase,
12441                                                 bool &AnyDependentBases) {
12442   // Check whether the named type is a direct base class.
12443   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
12444     .getUnqualifiedType();
12445   for (auto &Base : Derived->bases()) {
12446     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
12447     if (CanonicalDesiredBase == BaseType)
12448       return &Base;
12449     if (BaseType->isDependentType())
12450       AnyDependentBases = true;
12451   }
12452   return nullptr;
12453 }
12454 
12455 namespace {
12456 class UsingValidatorCCC final : public CorrectionCandidateCallback {
12457 public:
12458   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
12459                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
12460       : HasTypenameKeyword(HasTypenameKeyword),
12461         IsInstantiation(IsInstantiation), OldNNS(NNS),
12462         RequireMemberOf(RequireMemberOf) {}
12463 
12464   bool ValidateCandidate(const TypoCorrection &Candidate) override {
12465     NamedDecl *ND = Candidate.getCorrectionDecl();
12466 
12467     // Keywords are not valid here.
12468     if (!ND || isa<NamespaceDecl>(ND))
12469       return false;
12470 
12471     // Completely unqualified names are invalid for a 'using' declaration.
12472     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
12473       return false;
12474 
12475     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
12476     // reject.
12477 
12478     if (RequireMemberOf) {
12479       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12480       if (FoundRecord && FoundRecord->isInjectedClassName()) {
12481         // No-one ever wants a using-declaration to name an injected-class-name
12482         // of a base class, unless they're declaring an inheriting constructor.
12483         ASTContext &Ctx = ND->getASTContext();
12484         if (!Ctx.getLangOpts().CPlusPlus11)
12485           return false;
12486         QualType FoundType = Ctx.getRecordType(FoundRecord);
12487 
12488         // Check that the injected-class-name is named as a member of its own
12489         // type; we don't want to suggest 'using Derived::Base;', since that
12490         // means something else.
12491         NestedNameSpecifier *Specifier =
12492             Candidate.WillReplaceSpecifier()
12493                 ? Candidate.getCorrectionSpecifier()
12494                 : OldNNS;
12495         if (!Specifier->getAsType() ||
12496             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
12497           return false;
12498 
12499         // Check that this inheriting constructor declaration actually names a
12500         // direct base class of the current class.
12501         bool AnyDependentBases = false;
12502         if (!findDirectBaseWithType(RequireMemberOf,
12503                                     Ctx.getRecordType(FoundRecord),
12504                                     AnyDependentBases) &&
12505             !AnyDependentBases)
12506           return false;
12507       } else {
12508         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
12509         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
12510           return false;
12511 
12512         // FIXME: Check that the base class member is accessible?
12513       }
12514     } else {
12515       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12516       if (FoundRecord && FoundRecord->isInjectedClassName())
12517         return false;
12518     }
12519 
12520     if (isa<TypeDecl>(ND))
12521       return HasTypenameKeyword || !IsInstantiation;
12522 
12523     return !HasTypenameKeyword;
12524   }
12525 
12526   std::unique_ptr<CorrectionCandidateCallback> clone() override {
12527     return std::make_unique<UsingValidatorCCC>(*this);
12528   }
12529 
12530 private:
12531   bool HasTypenameKeyword;
12532   bool IsInstantiation;
12533   NestedNameSpecifier *OldNNS;
12534   CXXRecordDecl *RequireMemberOf;
12535 };
12536 } // end anonymous namespace
12537 
12538 /// Remove decls we can't actually see from a lookup being used to declare
12539 /// shadow using decls.
12540 ///
12541 /// \param S - The scope of the potential shadow decl
12542 /// \param Previous - The lookup of a potential shadow decl's name.
12543 void Sema::FilterUsingLookup(Scope *S, LookupResult &Previous) {
12544   // It is really dumb that we have to do this.
12545   LookupResult::Filter F = Previous.makeFilter();
12546   while (F.hasNext()) {
12547     NamedDecl *D = F.next();
12548     if (!isDeclInScope(D, CurContext, S))
12549       F.erase();
12550     // If we found a local extern declaration that's not ordinarily visible,
12551     // and this declaration is being added to a non-block scope, ignore it.
12552     // We're only checking for scope conflicts here, not also for violations
12553     // of the linkage rules.
12554     else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
12555              !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
12556       F.erase();
12557   }
12558   F.done();
12559 }
12560 
12561 /// Builds a using declaration.
12562 ///
12563 /// \param IsInstantiation - Whether this call arises from an
12564 ///   instantiation of an unresolved using declaration.  We treat
12565 ///   the lookup differently for these declarations.
12566 NamedDecl *Sema::BuildUsingDeclaration(
12567     Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
12568     bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
12569     DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
12570     const ParsedAttributesView &AttrList, bool IsInstantiation,
12571     bool IsUsingIfExists) {
12572   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12573   SourceLocation IdentLoc = NameInfo.getLoc();
12574   assert(IdentLoc.isValid() && "Invalid TargetName location.");
12575 
12576   // FIXME: We ignore attributes for now.
12577 
12578   // For an inheriting constructor declaration, the name of the using
12579   // declaration is the name of a constructor in this class, not in the
12580   // base class.
12581   DeclarationNameInfo UsingName = NameInfo;
12582   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
12583     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
12584       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12585           Context.getCanonicalType(Context.getRecordType(RD))));
12586 
12587   // Do the redeclaration lookup in the current scope.
12588   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
12589                         ForVisibleRedeclaration);
12590   Previous.setHideTags(false);
12591   if (S) {
12592     LookupName(Previous, S);
12593 
12594     FilterUsingLookup(S, Previous);
12595   } else {
12596     assert(IsInstantiation && "no scope in non-instantiation");
12597     if (CurContext->isRecord())
12598       LookupQualifiedName(Previous, CurContext);
12599     else {
12600       // No redeclaration check is needed here; in non-member contexts we
12601       // diagnosed all possible conflicts with other using-declarations when
12602       // building the template:
12603       //
12604       // For a dependent non-type using declaration, the only valid case is
12605       // if we instantiate to a single enumerator. We check for conflicts
12606       // between shadow declarations we introduce, and we check in the template
12607       // definition for conflicts between a non-type using declaration and any
12608       // other declaration, which together covers all cases.
12609       //
12610       // A dependent typename using declaration will never successfully
12611       // instantiate, since it will always name a class member, so we reject
12612       // that in the template definition.
12613     }
12614   }
12615 
12616   // Check for invalid redeclarations.
12617   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
12618                                   SS, IdentLoc, Previous))
12619     return nullptr;
12620 
12621   // 'using_if_exists' doesn't make sense on an inherited constructor.
12622   if (IsUsingIfExists && UsingName.getName().getNameKind() ==
12623                              DeclarationName::CXXConstructorName) {
12624     Diag(UsingLoc, diag::err_using_if_exists_on_ctor);
12625     return nullptr;
12626   }
12627 
12628   DeclContext *LookupContext = computeDeclContext(SS);
12629   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
12630   if (!LookupContext || EllipsisLoc.isValid()) {
12631     NamedDecl *D;
12632     // Dependent scope, or an unexpanded pack
12633     if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword,
12634                                                   SS, NameInfo, IdentLoc))
12635       return nullptr;
12636 
12637     if (HasTypenameKeyword) {
12638       // FIXME: not all declaration name kinds are legal here
12639       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
12640                                               UsingLoc, TypenameLoc,
12641                                               QualifierLoc,
12642                                               IdentLoc, NameInfo.getName(),
12643                                               EllipsisLoc);
12644     } else {
12645       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
12646                                            QualifierLoc, NameInfo, EllipsisLoc);
12647     }
12648     D->setAccess(AS);
12649     CurContext->addDecl(D);
12650     ProcessDeclAttributeList(S, D, AttrList);
12651     return D;
12652   }
12653 
12654   auto Build = [&](bool Invalid) {
12655     UsingDecl *UD =
12656         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
12657                           UsingName, HasTypenameKeyword);
12658     UD->setAccess(AS);
12659     CurContext->addDecl(UD);
12660     ProcessDeclAttributeList(S, UD, AttrList);
12661     UD->setInvalidDecl(Invalid);
12662     return UD;
12663   };
12664   auto BuildInvalid = [&]{ return Build(true); };
12665   auto BuildValid = [&]{ return Build(false); };
12666 
12667   if (RequireCompleteDeclContext(SS, LookupContext))
12668     return BuildInvalid();
12669 
12670   // Look up the target name.
12671   LookupResult R(*this, NameInfo, LookupOrdinaryName);
12672 
12673   // Unlike most lookups, we don't always want to hide tag
12674   // declarations: tag names are visible through the using declaration
12675   // even if hidden by ordinary names, *except* in a dependent context
12676   // where they may be used by two-phase lookup.
12677   if (!IsInstantiation)
12678     R.setHideTags(false);
12679 
12680   // For the purposes of this lookup, we have a base object type
12681   // equal to that of the current context.
12682   if (CurContext->isRecord()) {
12683     R.setBaseObjectType(
12684                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
12685   }
12686 
12687   LookupQualifiedName(R, LookupContext);
12688 
12689   // Validate the context, now we have a lookup
12690   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
12691                               IdentLoc, &R))
12692     return nullptr;
12693 
12694   if (R.empty() && IsUsingIfExists)
12695     R.addDecl(UnresolvedUsingIfExistsDecl::Create(Context, CurContext, UsingLoc,
12696                                                   UsingName.getName()),
12697               AS_public);
12698 
12699   // Try to correct typos if possible. If constructor name lookup finds no
12700   // results, that means the named class has no explicit constructors, and we
12701   // suppressed declaring implicit ones (probably because it's dependent or
12702   // invalid).
12703   if (R.empty() &&
12704       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
12705     // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
12706     // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
12707     // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
12708     auto *II = NameInfo.getName().getAsIdentifierInfo();
12709     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
12710         CurContext->isStdNamespace() &&
12711         isa<TranslationUnitDecl>(LookupContext) &&
12712         getSourceManager().isInSystemHeader(UsingLoc))
12713       return nullptr;
12714     UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
12715                           dyn_cast<CXXRecordDecl>(CurContext));
12716     if (TypoCorrection Corrected =
12717             CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
12718                         CTK_ErrorRecovery)) {
12719       // We reject candidates where DroppedSpecifier == true, hence the
12720       // literal '0' below.
12721       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
12722                                 << NameInfo.getName() << LookupContext << 0
12723                                 << SS.getRange());
12724 
12725       // If we picked a correction with no attached Decl we can't do anything
12726       // useful with it, bail out.
12727       NamedDecl *ND = Corrected.getCorrectionDecl();
12728       if (!ND)
12729         return BuildInvalid();
12730 
12731       // If we corrected to an inheriting constructor, handle it as one.
12732       auto *RD = dyn_cast<CXXRecordDecl>(ND);
12733       if (RD && RD->isInjectedClassName()) {
12734         // The parent of the injected class name is the class itself.
12735         RD = cast<CXXRecordDecl>(RD->getParent());
12736 
12737         // Fix up the information we'll use to build the using declaration.
12738         if (Corrected.WillReplaceSpecifier()) {
12739           NestedNameSpecifierLocBuilder Builder;
12740           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
12741                               QualifierLoc.getSourceRange());
12742           QualifierLoc = Builder.getWithLocInContext(Context);
12743         }
12744 
12745         // In this case, the name we introduce is the name of a derived class
12746         // constructor.
12747         auto *CurClass = cast<CXXRecordDecl>(CurContext);
12748         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12749             Context.getCanonicalType(Context.getRecordType(CurClass))));
12750         UsingName.setNamedTypeInfo(nullptr);
12751         for (auto *Ctor : LookupConstructors(RD))
12752           R.addDecl(Ctor);
12753         R.resolveKind();
12754       } else {
12755         // FIXME: Pick up all the declarations if we found an overloaded
12756         // function.
12757         UsingName.setName(ND->getDeclName());
12758         R.addDecl(ND);
12759       }
12760     } else {
12761       Diag(IdentLoc, diag::err_no_member)
12762         << NameInfo.getName() << LookupContext << SS.getRange();
12763       return BuildInvalid();
12764     }
12765   }
12766 
12767   if (R.isAmbiguous())
12768     return BuildInvalid();
12769 
12770   if (HasTypenameKeyword) {
12771     // If we asked for a typename and got a non-type decl, error out.
12772     if (!R.getAsSingle<TypeDecl>() &&
12773         !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) {
12774       Diag(IdentLoc, diag::err_using_typename_non_type);
12775       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12776         Diag((*I)->getUnderlyingDecl()->getLocation(),
12777              diag::note_using_decl_target);
12778       return BuildInvalid();
12779     }
12780   } else {
12781     // If we asked for a non-typename and we got a type, error out,
12782     // but only if this is an instantiation of an unresolved using
12783     // decl.  Otherwise just silently find the type name.
12784     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
12785       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
12786       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
12787       return BuildInvalid();
12788     }
12789   }
12790 
12791   // C++14 [namespace.udecl]p6:
12792   // A using-declaration shall not name a namespace.
12793   if (R.getAsSingle<NamespaceDecl>()) {
12794     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
12795       << SS.getRange();
12796     return BuildInvalid();
12797   }
12798 
12799   UsingDecl *UD = BuildValid();
12800 
12801   // Some additional rules apply to inheriting constructors.
12802   if (UsingName.getName().getNameKind() ==
12803         DeclarationName::CXXConstructorName) {
12804     // Suppress access diagnostics; the access check is instead performed at the
12805     // point of use for an inheriting constructor.
12806     R.suppressDiagnostics();
12807     if (CheckInheritingConstructorUsingDecl(UD))
12808       return UD;
12809   }
12810 
12811   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
12812     UsingShadowDecl *PrevDecl = nullptr;
12813     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
12814       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
12815   }
12816 
12817   return UD;
12818 }
12819 
12820 NamedDecl *Sema::BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
12821                                            SourceLocation UsingLoc,
12822                                            SourceLocation EnumLoc,
12823                                            SourceLocation NameLoc,
12824                                            TypeSourceInfo *EnumType,
12825                                            EnumDecl *ED) {
12826   bool Invalid = false;
12827 
12828   if (CurContext->getRedeclContext()->isRecord()) {
12829     /// In class scope, check if this is a duplicate, for better a diagnostic.
12830     DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
12831     LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
12832                           ForVisibleRedeclaration);
12833 
12834     LookupName(Previous, S);
12835 
12836     for (NamedDecl *D : Previous)
12837       if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D))
12838         if (UED->getEnumDecl() == ED) {
12839           Diag(UsingLoc, diag::err_using_enum_decl_redeclaration)
12840               << SourceRange(EnumLoc, NameLoc);
12841           Diag(D->getLocation(), diag::note_using_enum_decl) << 1;
12842           Invalid = true;
12843           break;
12844         }
12845   }
12846 
12847   if (RequireCompleteEnumDecl(ED, NameLoc))
12848     Invalid = true;
12849 
12850   UsingEnumDecl *UD = UsingEnumDecl::Create(Context, CurContext, UsingLoc,
12851                                             EnumLoc, NameLoc, EnumType);
12852   UD->setAccess(AS);
12853   CurContext->addDecl(UD);
12854 
12855   if (Invalid) {
12856     UD->setInvalidDecl();
12857     return UD;
12858   }
12859 
12860   // Create the shadow decls for each enumerator
12861   for (EnumConstantDecl *EC : ED->enumerators()) {
12862     UsingShadowDecl *PrevDecl = nullptr;
12863     DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
12864     LookupResult Previous(*this, DNI, LookupOrdinaryName,
12865                           ForVisibleRedeclaration);
12866     LookupName(Previous, S);
12867     FilterUsingLookup(S, Previous);
12868 
12869     if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl))
12870       BuildUsingShadowDecl(S, UD, EC, PrevDecl);
12871   }
12872 
12873   return UD;
12874 }
12875 
12876 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
12877                                     ArrayRef<NamedDecl *> Expansions) {
12878   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
12879          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
12880          isa<UsingPackDecl>(InstantiatedFrom));
12881 
12882   auto *UPD =
12883       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
12884   UPD->setAccess(InstantiatedFrom->getAccess());
12885   CurContext->addDecl(UPD);
12886   return UPD;
12887 }
12888 
12889 /// Additional checks for a using declaration referring to a constructor name.
12890 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
12891   assert(!UD->hasTypename() && "expecting a constructor name");
12892 
12893   const Type *SourceType = UD->getQualifier()->getAsType();
12894   assert(SourceType &&
12895          "Using decl naming constructor doesn't have type in scope spec.");
12896   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
12897 
12898   // Check whether the named type is a direct base class.
12899   bool AnyDependentBases = false;
12900   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
12901                                       AnyDependentBases);
12902   if (!Base && !AnyDependentBases) {
12903     Diag(UD->getUsingLoc(),
12904          diag::err_using_decl_constructor_not_in_direct_base)
12905       << UD->getNameInfo().getSourceRange()
12906       << QualType(SourceType, 0) << TargetClass;
12907     UD->setInvalidDecl();
12908     return true;
12909   }
12910 
12911   if (Base)
12912     Base->setInheritConstructors();
12913 
12914   return false;
12915 }
12916 
12917 /// Checks that the given using declaration is not an invalid
12918 /// redeclaration.  Note that this is checking only for the using decl
12919 /// itself, not for any ill-formedness among the UsingShadowDecls.
12920 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
12921                                        bool HasTypenameKeyword,
12922                                        const CXXScopeSpec &SS,
12923                                        SourceLocation NameLoc,
12924                                        const LookupResult &Prev) {
12925   NestedNameSpecifier *Qual = SS.getScopeRep();
12926 
12927   // C++03 [namespace.udecl]p8:
12928   // C++0x [namespace.udecl]p10:
12929   //   A using-declaration is a declaration and can therefore be used
12930   //   repeatedly where (and only where) multiple declarations are
12931   //   allowed.
12932   //
12933   // That's in non-member contexts.
12934   if (!CurContext->getRedeclContext()->isRecord()) {
12935     // A dependent qualifier outside a class can only ever resolve to an
12936     // enumeration type. Therefore it conflicts with any other non-type
12937     // declaration in the same scope.
12938     // FIXME: How should we check for dependent type-type conflicts at block
12939     // scope?
12940     if (Qual->isDependent() && !HasTypenameKeyword) {
12941       for (auto *D : Prev) {
12942         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
12943           bool OldCouldBeEnumerator =
12944               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
12945           Diag(NameLoc,
12946                OldCouldBeEnumerator ? diag::err_redefinition
12947                                     : diag::err_redefinition_different_kind)
12948               << Prev.getLookupName();
12949           Diag(D->getLocation(), diag::note_previous_definition);
12950           return true;
12951         }
12952       }
12953     }
12954     return false;
12955   }
12956 
12957   const NestedNameSpecifier *CNNS =
12958       Context.getCanonicalNestedNameSpecifier(Qual);
12959   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
12960     NamedDecl *D = *I;
12961 
12962     bool DTypename;
12963     NestedNameSpecifier *DQual;
12964     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
12965       DTypename = UD->hasTypename();
12966       DQual = UD->getQualifier();
12967     } else if (UnresolvedUsingValueDecl *UD
12968                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
12969       DTypename = false;
12970       DQual = UD->getQualifier();
12971     } else if (UnresolvedUsingTypenameDecl *UD
12972                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
12973       DTypename = true;
12974       DQual = UD->getQualifier();
12975     } else continue;
12976 
12977     // using decls differ if one says 'typename' and the other doesn't.
12978     // FIXME: non-dependent using decls?
12979     if (HasTypenameKeyword != DTypename) continue;
12980 
12981     // using decls differ if they name different scopes (but note that
12982     // template instantiation can cause this check to trigger when it
12983     // didn't before instantiation).
12984     if (CNNS != Context.getCanonicalNestedNameSpecifier(DQual))
12985       continue;
12986 
12987     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
12988     Diag(D->getLocation(), diag::note_using_decl) << 1;
12989     return true;
12990   }
12991 
12992   return false;
12993 }
12994 
12995 /// Checks that the given nested-name qualifier used in a using decl
12996 /// in the current context is appropriately related to the current
12997 /// scope.  If an error is found, diagnoses it and returns true.
12998 /// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's the
12999 /// result of that lookup. UD is likewise nullptr, except when we have an
13000 /// already-populated UsingDecl whose shadow decls contain the same information
13001 /// (i.e. we're instantiating a UsingDecl with non-dependent scope).
13002 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
13003                                    const CXXScopeSpec &SS,
13004                                    const DeclarationNameInfo &NameInfo,
13005                                    SourceLocation NameLoc,
13006                                    const LookupResult *R, const UsingDecl *UD) {
13007   DeclContext *NamedContext = computeDeclContext(SS);
13008   assert(bool(NamedContext) == (R || UD) && !(R && UD) &&
13009          "resolvable context must have exactly one set of decls");
13010 
13011   // C++ 20 permits using an enumerator that does not have a class-hierarchy
13012   // relationship.
13013   bool Cxx20Enumerator = false;
13014   if (NamedContext) {
13015     EnumConstantDecl *EC = nullptr;
13016     if (R)
13017       EC = R->getAsSingle<EnumConstantDecl>();
13018     else if (UD && UD->shadow_size() == 1)
13019       EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl());
13020     if (EC)
13021       Cxx20Enumerator = getLangOpts().CPlusPlus20;
13022 
13023     if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) {
13024       // C++14 [namespace.udecl]p7:
13025       // A using-declaration shall not name a scoped enumerator.
13026       // C++20 p1099 permits enumerators.
13027       if (EC && R && ED->isScoped())
13028         Diag(SS.getBeginLoc(),
13029              getLangOpts().CPlusPlus20
13030                  ? diag::warn_cxx17_compat_using_decl_scoped_enumerator
13031                  : diag::ext_using_decl_scoped_enumerator)
13032             << SS.getRange();
13033 
13034       // We want to consider the scope of the enumerator
13035       NamedContext = ED->getDeclContext();
13036     }
13037   }
13038 
13039   if (!CurContext->isRecord()) {
13040     // C++03 [namespace.udecl]p3:
13041     // C++0x [namespace.udecl]p8:
13042     //   A using-declaration for a class member shall be a member-declaration.
13043     // C++20 [namespace.udecl]p7
13044     //   ... other than an enumerator ...
13045 
13046     // If we weren't able to compute a valid scope, it might validly be a
13047     // dependent class or enumeration scope. If we have a 'typename' keyword,
13048     // the scope must resolve to a class type.
13049     if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
13050                      : !HasTypename)
13051       return false; // OK
13052 
13053     Diag(NameLoc,
13054          Cxx20Enumerator
13055              ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
13056              : diag::err_using_decl_can_not_refer_to_class_member)
13057         << SS.getRange();
13058 
13059     if (Cxx20Enumerator)
13060       return false; // OK
13061 
13062     auto *RD = NamedContext
13063                    ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
13064                    : nullptr;
13065     if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) {
13066       // See if there's a helpful fixit
13067 
13068       if (!R) {
13069         // We will have already diagnosed the problem on the template
13070         // definition,  Maybe we should do so again?
13071       } else if (R->getAsSingle<TypeDecl>()) {
13072         if (getLangOpts().CPlusPlus11) {
13073           // Convert 'using X::Y;' to 'using Y = X::Y;'.
13074           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
13075             << 0 // alias declaration
13076             << FixItHint::CreateInsertion(SS.getBeginLoc(),
13077                                           NameInfo.getName().getAsString() +
13078                                               " = ");
13079         } else {
13080           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
13081           SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
13082           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
13083             << 1 // typedef declaration
13084             << FixItHint::CreateReplacement(UsingLoc, "typedef")
13085             << FixItHint::CreateInsertion(
13086                    InsertLoc, " " + NameInfo.getName().getAsString());
13087         }
13088       } else if (R->getAsSingle<VarDecl>()) {
13089         // Don't provide a fixit outside C++11 mode; we don't want to suggest
13090         // repeating the type of the static data member here.
13091         FixItHint FixIt;
13092         if (getLangOpts().CPlusPlus11) {
13093           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13094           FixIt = FixItHint::CreateReplacement(
13095               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
13096         }
13097 
13098         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13099           << 2 // reference declaration
13100           << FixIt;
13101       } else if (R->getAsSingle<EnumConstantDecl>()) {
13102         // Don't provide a fixit outside C++11 mode; we don't want to suggest
13103         // repeating the type of the enumeration here, and we can't do so if
13104         // the type is anonymous.
13105         FixItHint FixIt;
13106         if (getLangOpts().CPlusPlus11) {
13107           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13108           FixIt = FixItHint::CreateReplacement(
13109               UsingLoc,
13110               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
13111         }
13112 
13113         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13114           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
13115           << FixIt;
13116       }
13117     }
13118 
13119     return true; // Fail
13120   }
13121 
13122   // If the named context is dependent, we can't decide much.
13123   if (!NamedContext) {
13124     // FIXME: in C++0x, we can diagnose if we can prove that the
13125     // nested-name-specifier does not refer to a base class, which is
13126     // still possible in some cases.
13127 
13128     // Otherwise we have to conservatively report that things might be
13129     // okay.
13130     return false;
13131   }
13132 
13133   // The current scope is a record.
13134   if (!NamedContext->isRecord()) {
13135     // Ideally this would point at the last name in the specifier,
13136     // but we don't have that level of source info.
13137     Diag(SS.getBeginLoc(),
13138          Cxx20Enumerator
13139              ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
13140              : diag::err_using_decl_nested_name_specifier_is_not_class)
13141         << SS.getScopeRep() << SS.getRange();
13142 
13143     if (Cxx20Enumerator)
13144       return false; // OK
13145 
13146     return true;
13147   }
13148 
13149   if (!NamedContext->isDependentContext() &&
13150       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
13151     return true;
13152 
13153   if (getLangOpts().CPlusPlus11) {
13154     // C++11 [namespace.udecl]p3:
13155     //   In a using-declaration used as a member-declaration, the
13156     //   nested-name-specifier shall name a base class of the class
13157     //   being defined.
13158 
13159     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
13160                                  cast<CXXRecordDecl>(NamedContext))) {
13161 
13162       if (Cxx20Enumerator) {
13163         Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator)
13164             << SS.getRange();
13165         return false;
13166       }
13167 
13168       if (CurContext == NamedContext) {
13169         Diag(SS.getBeginLoc(),
13170              diag::err_using_decl_nested_name_specifier_is_current_class)
13171             << SS.getRange();
13172         return !getLangOpts().CPlusPlus20;
13173       }
13174 
13175       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
13176         Diag(SS.getBeginLoc(),
13177              diag::err_using_decl_nested_name_specifier_is_not_base_class)
13178             << SS.getScopeRep() << cast<CXXRecordDecl>(CurContext)
13179             << SS.getRange();
13180       }
13181       return true;
13182     }
13183 
13184     return false;
13185   }
13186 
13187   // C++03 [namespace.udecl]p4:
13188   //   A using-declaration used as a member-declaration shall refer
13189   //   to a member of a base class of the class being defined [etc.].
13190 
13191   // Salient point: SS doesn't have to name a base class as long as
13192   // lookup only finds members from base classes.  Therefore we can
13193   // diagnose here only if we can prove that can't happen,
13194   // i.e. if the class hierarchies provably don't intersect.
13195 
13196   // TODO: it would be nice if "definitely valid" results were cached
13197   // in the UsingDecl and UsingShadowDecl so that these checks didn't
13198   // need to be repeated.
13199 
13200   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
13201   auto Collect = [&Bases](const CXXRecordDecl *Base) {
13202     Bases.insert(Base);
13203     return true;
13204   };
13205 
13206   // Collect all bases. Return false if we find a dependent base.
13207   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
13208     return false;
13209 
13210   // Returns true if the base is dependent or is one of the accumulated base
13211   // classes.
13212   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
13213     return !Bases.count(Base);
13214   };
13215 
13216   // Return false if the class has a dependent base or if it or one
13217   // of its bases is present in the base set of the current context.
13218   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
13219       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
13220     return false;
13221 
13222   Diag(SS.getRange().getBegin(),
13223        diag::err_using_decl_nested_name_specifier_is_not_base_class)
13224     << SS.getScopeRep()
13225     << cast<CXXRecordDecl>(CurContext)
13226     << SS.getRange();
13227 
13228   return true;
13229 }
13230 
13231 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
13232                                   MultiTemplateParamsArg TemplateParamLists,
13233                                   SourceLocation UsingLoc, UnqualifiedId &Name,
13234                                   const ParsedAttributesView &AttrList,
13235                                   TypeResult Type, Decl *DeclFromDeclSpec) {
13236   // Skip up to the relevant declaration scope.
13237   while (S->isTemplateParamScope())
13238     S = S->getParent();
13239   assert((S->getFlags() & Scope::DeclScope) &&
13240          "got alias-declaration outside of declaration scope");
13241 
13242   if (Type.isInvalid())
13243     return nullptr;
13244 
13245   bool Invalid = false;
13246   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
13247   TypeSourceInfo *TInfo = nullptr;
13248   GetTypeFromParser(Type.get(), &TInfo);
13249 
13250   if (DiagnoseClassNameShadow(CurContext, NameInfo))
13251     return nullptr;
13252 
13253   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
13254                                       UPPC_DeclarationType)) {
13255     Invalid = true;
13256     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13257                                              TInfo->getTypeLoc().getBeginLoc());
13258   }
13259 
13260   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
13261                         TemplateParamLists.size()
13262                             ? forRedeclarationInCurContext()
13263                             : ForVisibleRedeclaration);
13264   LookupName(Previous, S);
13265 
13266   // Warn about shadowing the name of a template parameter.
13267   if (Previous.isSingleResult() &&
13268       Previous.getFoundDecl()->isTemplateParameter()) {
13269     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
13270     Previous.clear();
13271   }
13272 
13273   assert(Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
13274          "name in alias declaration must be an identifier");
13275   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
13276                                                Name.StartLocation,
13277                                                Name.Identifier, TInfo);
13278 
13279   NewTD->setAccess(AS);
13280 
13281   if (Invalid)
13282     NewTD->setInvalidDecl();
13283 
13284   ProcessDeclAttributeList(S, NewTD, AttrList);
13285   AddPragmaAttributes(S, NewTD);
13286 
13287   CheckTypedefForVariablyModifiedType(S, NewTD);
13288   Invalid |= NewTD->isInvalidDecl();
13289 
13290   bool Redeclaration = false;
13291 
13292   NamedDecl *NewND;
13293   if (TemplateParamLists.size()) {
13294     TypeAliasTemplateDecl *OldDecl = nullptr;
13295     TemplateParameterList *OldTemplateParams = nullptr;
13296 
13297     if (TemplateParamLists.size() != 1) {
13298       Diag(UsingLoc, diag::err_alias_template_extra_headers)
13299         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
13300          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
13301     }
13302     TemplateParameterList *TemplateParams = TemplateParamLists[0];
13303 
13304     // Check that we can declare a template here.
13305     if (CheckTemplateDeclScope(S, TemplateParams))
13306       return nullptr;
13307 
13308     // Only consider previous declarations in the same scope.
13309     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
13310                          /*ExplicitInstantiationOrSpecialization*/false);
13311     if (!Previous.empty()) {
13312       Redeclaration = true;
13313 
13314       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
13315       if (!OldDecl && !Invalid) {
13316         Diag(UsingLoc, diag::err_redefinition_different_kind)
13317           << Name.Identifier;
13318 
13319         NamedDecl *OldD = Previous.getRepresentativeDecl();
13320         if (OldD->getLocation().isValid())
13321           Diag(OldD->getLocation(), diag::note_previous_definition);
13322 
13323         Invalid = true;
13324       }
13325 
13326       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
13327         if (TemplateParameterListsAreEqual(TemplateParams,
13328                                            OldDecl->getTemplateParameters(),
13329                                            /*Complain=*/true,
13330                                            TPL_TemplateMatch))
13331           OldTemplateParams =
13332               OldDecl->getMostRecentDecl()->getTemplateParameters();
13333         else
13334           Invalid = true;
13335 
13336         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
13337         if (!Invalid &&
13338             !Context.hasSameType(OldTD->getUnderlyingType(),
13339                                  NewTD->getUnderlyingType())) {
13340           // FIXME: The C++0x standard does not clearly say this is ill-formed,
13341           // but we can't reasonably accept it.
13342           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
13343             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
13344           if (OldTD->getLocation().isValid())
13345             Diag(OldTD->getLocation(), diag::note_previous_definition);
13346           Invalid = true;
13347         }
13348       }
13349     }
13350 
13351     // Merge any previous default template arguments into our parameters,
13352     // and check the parameter list.
13353     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
13354                                    TPC_TypeAliasTemplate))
13355       return nullptr;
13356 
13357     TypeAliasTemplateDecl *NewDecl =
13358       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
13359                                     Name.Identifier, TemplateParams,
13360                                     NewTD);
13361     NewTD->setDescribedAliasTemplate(NewDecl);
13362 
13363     NewDecl->setAccess(AS);
13364 
13365     if (Invalid)
13366       NewDecl->setInvalidDecl();
13367     else if (OldDecl) {
13368       NewDecl->setPreviousDecl(OldDecl);
13369       CheckRedeclarationInModule(NewDecl, OldDecl);
13370     }
13371 
13372     NewND = NewDecl;
13373   } else {
13374     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
13375       setTagNameForLinkagePurposes(TD, NewTD);
13376       handleTagNumbering(TD, S);
13377     }
13378     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
13379     NewND = NewTD;
13380   }
13381 
13382   PushOnScopeChains(NewND, S);
13383   ActOnDocumentableDecl(NewND);
13384   return NewND;
13385 }
13386 
13387 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
13388                                    SourceLocation AliasLoc,
13389                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
13390                                    SourceLocation IdentLoc,
13391                                    IdentifierInfo *Ident) {
13392 
13393   // Lookup the namespace name.
13394   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
13395   LookupParsedName(R, S, &SS);
13396 
13397   if (R.isAmbiguous())
13398     return nullptr;
13399 
13400   if (R.empty()) {
13401     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
13402       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
13403       return nullptr;
13404     }
13405   }
13406   assert(!R.isAmbiguous() && !R.empty());
13407   NamedDecl *ND = R.getRepresentativeDecl();
13408 
13409   // Check if we have a previous declaration with the same name.
13410   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
13411                      ForVisibleRedeclaration);
13412   LookupName(PrevR, S);
13413 
13414   // Check we're not shadowing a template parameter.
13415   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
13416     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
13417     PrevR.clear();
13418   }
13419 
13420   // Filter out any other lookup result from an enclosing scope.
13421   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
13422                        /*AllowInlineNamespace*/false);
13423 
13424   // Find the previous declaration and check that we can redeclare it.
13425   NamespaceAliasDecl *Prev = nullptr;
13426   if (PrevR.isSingleResult()) {
13427     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
13428     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
13429       // We already have an alias with the same name that points to the same
13430       // namespace; check that it matches.
13431       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
13432         Prev = AD;
13433       } else if (isVisible(PrevDecl)) {
13434         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
13435           << Alias;
13436         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
13437           << AD->getNamespace();
13438         return nullptr;
13439       }
13440     } else if (isVisible(PrevDecl)) {
13441       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
13442                             ? diag::err_redefinition
13443                             : diag::err_redefinition_different_kind;
13444       Diag(AliasLoc, DiagID) << Alias;
13445       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13446       return nullptr;
13447     }
13448   }
13449 
13450   // The use of a nested name specifier may trigger deprecation warnings.
13451   DiagnoseUseOfDecl(ND, IdentLoc);
13452 
13453   NamespaceAliasDecl *AliasDecl =
13454     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
13455                                Alias, SS.getWithLocInContext(Context),
13456                                IdentLoc, ND);
13457   if (Prev)
13458     AliasDecl->setPreviousDecl(Prev);
13459 
13460   PushOnScopeChains(AliasDecl, S);
13461   return AliasDecl;
13462 }
13463 
13464 namespace {
13465 struct SpecialMemberExceptionSpecInfo
13466     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
13467   SourceLocation Loc;
13468   Sema::ImplicitExceptionSpecification ExceptSpec;
13469 
13470   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
13471                                  Sema::CXXSpecialMember CSM,
13472                                  Sema::InheritedConstructorInfo *ICI,
13473                                  SourceLocation Loc)
13474       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
13475 
13476   bool visitBase(CXXBaseSpecifier *Base);
13477   bool visitField(FieldDecl *FD);
13478 
13479   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
13480                            unsigned Quals);
13481 
13482   void visitSubobjectCall(Subobject Subobj,
13483                           Sema::SpecialMemberOverloadResult SMOR);
13484 };
13485 }
13486 
13487 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
13488   auto *RT = Base->getType()->getAs<RecordType>();
13489   if (!RT)
13490     return false;
13491 
13492   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
13493   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
13494   if (auto *BaseCtor = SMOR.getMethod()) {
13495     visitSubobjectCall(Base, BaseCtor);
13496     return false;
13497   }
13498 
13499   visitClassSubobject(BaseClass, Base, 0);
13500   return false;
13501 }
13502 
13503 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
13504   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
13505     Expr *E = FD->getInClassInitializer();
13506     if (!E)
13507       // FIXME: It's a little wasteful to build and throw away a
13508       // CXXDefaultInitExpr here.
13509       // FIXME: We should have a single context note pointing at Loc, and
13510       // this location should be MD->getLocation() instead, since that's
13511       // the location where we actually use the default init expression.
13512       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
13513     if (E)
13514       ExceptSpec.CalledExpr(E);
13515   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
13516                             ->getAs<RecordType>()) {
13517     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
13518                         FD->getType().getCVRQualifiers());
13519   }
13520   return false;
13521 }
13522 
13523 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
13524                                                          Subobject Subobj,
13525                                                          unsigned Quals) {
13526   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
13527   bool IsMutable = Field && Field->isMutable();
13528   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
13529 }
13530 
13531 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
13532     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
13533   // Note, if lookup fails, it doesn't matter what exception specification we
13534   // choose because the special member will be deleted.
13535   if (CXXMethodDecl *MD = SMOR.getMethod())
13536     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
13537 }
13538 
13539 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
13540   llvm::APSInt Result;
13541   ExprResult Converted = CheckConvertedConstantExpression(
13542       ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
13543   ExplicitSpec.setExpr(Converted.get());
13544   if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
13545     ExplicitSpec.setKind(Result.getBoolValue()
13546                              ? ExplicitSpecKind::ResolvedTrue
13547                              : ExplicitSpecKind::ResolvedFalse);
13548     return true;
13549   }
13550   ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
13551   return false;
13552 }
13553 
13554 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
13555   ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
13556   if (!ExplicitExpr->isTypeDependent())
13557     tryResolveExplicitSpecifier(ES);
13558   return ES;
13559 }
13560 
13561 static Sema::ImplicitExceptionSpecification
13562 ComputeDefaultedSpecialMemberExceptionSpec(
13563     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
13564     Sema::InheritedConstructorInfo *ICI) {
13565   ComputingExceptionSpec CES(S, MD, Loc);
13566 
13567   CXXRecordDecl *ClassDecl = MD->getParent();
13568 
13569   // C++ [except.spec]p14:
13570   //   An implicitly declared special member function (Clause 12) shall have an
13571   //   exception-specification. [...]
13572   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
13573   if (ClassDecl->isInvalidDecl())
13574     return Info.ExceptSpec;
13575 
13576   // FIXME: If this diagnostic fires, we're probably missing a check for
13577   // attempting to resolve an exception specification before it's known
13578   // at a higher level.
13579   if (S.RequireCompleteType(MD->getLocation(),
13580                             S.Context.getRecordType(ClassDecl),
13581                             diag::err_exception_spec_incomplete_type))
13582     return Info.ExceptSpec;
13583 
13584   // C++1z [except.spec]p7:
13585   //   [Look for exceptions thrown by] a constructor selected [...] to
13586   //   initialize a potentially constructed subobject,
13587   // C++1z [except.spec]p8:
13588   //   The exception specification for an implicitly-declared destructor, or a
13589   //   destructor without a noexcept-specifier, is potentially-throwing if and
13590   //   only if any of the destructors for any of its potentially constructed
13591   //   subojects is potentially throwing.
13592   // FIXME: We respect the first rule but ignore the "potentially constructed"
13593   // in the second rule to resolve a core issue (no number yet) that would have
13594   // us reject:
13595   //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
13596   //   struct B : A {};
13597   //   struct C : B { void f(); };
13598   // ... due to giving B::~B() a non-throwing exception specification.
13599   Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
13600                                 : Info.VisitAllBases);
13601 
13602   return Info.ExceptSpec;
13603 }
13604 
13605 namespace {
13606 /// RAII object to register a special member as being currently declared.
13607 struct DeclaringSpecialMember {
13608   Sema &S;
13609   Sema::SpecialMemberDecl D;
13610   Sema::ContextRAII SavedContext;
13611   bool WasAlreadyBeingDeclared;
13612 
13613   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
13614       : S(S), D(RD, CSM), SavedContext(S, RD) {
13615     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
13616     if (WasAlreadyBeingDeclared)
13617       // This almost never happens, but if it does, ensure that our cache
13618       // doesn't contain a stale result.
13619       S.SpecialMemberCache.clear();
13620     else {
13621       // Register a note to be produced if we encounter an error while
13622       // declaring the special member.
13623       Sema::CodeSynthesisContext Ctx;
13624       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
13625       // FIXME: We don't have a location to use here. Using the class's
13626       // location maintains the fiction that we declare all special members
13627       // with the class, but (1) it's not clear that lying about that helps our
13628       // users understand what's going on, and (2) there may be outer contexts
13629       // on the stack (some of which are relevant) and printing them exposes
13630       // our lies.
13631       Ctx.PointOfInstantiation = RD->getLocation();
13632       Ctx.Entity = RD;
13633       Ctx.SpecialMember = CSM;
13634       S.pushCodeSynthesisContext(Ctx);
13635     }
13636   }
13637   ~DeclaringSpecialMember() {
13638     if (!WasAlreadyBeingDeclared) {
13639       S.SpecialMembersBeingDeclared.erase(D);
13640       S.popCodeSynthesisContext();
13641     }
13642   }
13643 
13644   /// Are we already trying to declare this special member?
13645   bool isAlreadyBeingDeclared() const {
13646     return WasAlreadyBeingDeclared;
13647   }
13648 };
13649 }
13650 
13651 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
13652   // Look up any existing declarations, but don't trigger declaration of all
13653   // implicit special members with this name.
13654   DeclarationName Name = FD->getDeclName();
13655   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
13656                  ForExternalRedeclaration);
13657   for (auto *D : FD->getParent()->lookup(Name))
13658     if (auto *Acceptable = R.getAcceptableDecl(D))
13659       R.addDecl(Acceptable);
13660   R.resolveKind();
13661   R.suppressDiagnostics();
13662 
13663   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/ false,
13664                            FD->isThisDeclarationADefinition());
13665 }
13666 
13667 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
13668                                           QualType ResultTy,
13669                                           ArrayRef<QualType> Args) {
13670   // Build an exception specification pointing back at this constructor.
13671   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
13672 
13673   LangAS AS = getDefaultCXXMethodAddrSpace();
13674   if (AS != LangAS::Default) {
13675     EPI.TypeQuals.addAddressSpace(AS);
13676   }
13677 
13678   auto QT = Context.getFunctionType(ResultTy, Args, EPI);
13679   SpecialMem->setType(QT);
13680 
13681   // During template instantiation of implicit special member functions we need
13682   // a reliable TypeSourceInfo for the function prototype in order to allow
13683   // functions to be substituted.
13684   if (inTemplateInstantiation() &&
13685       cast<CXXRecordDecl>(SpecialMem->getParent())->isLambda()) {
13686     TypeSourceInfo *TSI =
13687         Context.getTrivialTypeSourceInfo(SpecialMem->getType());
13688     SpecialMem->setTypeSourceInfo(TSI);
13689   }
13690 }
13691 
13692 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
13693                                                      CXXRecordDecl *ClassDecl) {
13694   // C++ [class.ctor]p5:
13695   //   A default constructor for a class X is a constructor of class X
13696   //   that can be called without an argument. If there is no
13697   //   user-declared constructor for class X, a default constructor is
13698   //   implicitly declared. An implicitly-declared default constructor
13699   //   is an inline public member of its class.
13700   assert(ClassDecl->needsImplicitDefaultConstructor() &&
13701          "Should not build implicit default constructor!");
13702 
13703   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
13704   if (DSM.isAlreadyBeingDeclared())
13705     return nullptr;
13706 
13707   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13708                                                      CXXDefaultConstructor,
13709                                                      false);
13710 
13711   // Create the actual constructor declaration.
13712   CanQualType ClassType
13713     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13714   SourceLocation ClassLoc = ClassDecl->getLocation();
13715   DeclarationName Name
13716     = Context.DeclarationNames.getCXXConstructorName(ClassType);
13717   DeclarationNameInfo NameInfo(Name, ClassLoc);
13718   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
13719       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
13720       /*TInfo=*/nullptr, ExplicitSpecifier(),
13721       getCurFPFeatures().isFPConstrained(),
13722       /*isInline=*/true, /*isImplicitlyDeclared=*/true,
13723       Constexpr ? ConstexprSpecKind::Constexpr
13724                 : ConstexprSpecKind::Unspecified);
13725   DefaultCon->setAccess(AS_public);
13726   DefaultCon->setDefaulted();
13727 
13728   setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, std::nullopt);
13729 
13730   if (getLangOpts().CUDA)
13731     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
13732                                             DefaultCon,
13733                                             /* ConstRHS */ false,
13734                                             /* Diagnose */ false);
13735 
13736   // We don't need to use SpecialMemberIsTrivial here; triviality for default
13737   // constructors is easy to compute.
13738   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
13739 
13740   // Note that we have declared this constructor.
13741   ++getASTContext().NumImplicitDefaultConstructorsDeclared;
13742 
13743   Scope *S = getScopeForContext(ClassDecl);
13744   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
13745 
13746   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
13747     SetDeclDeleted(DefaultCon, ClassLoc);
13748 
13749   if (S)
13750     PushOnScopeChains(DefaultCon, S, false);
13751   ClassDecl->addDecl(DefaultCon);
13752 
13753   return DefaultCon;
13754 }
13755 
13756 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
13757                                             CXXConstructorDecl *Constructor) {
13758   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
13759           !Constructor->doesThisDeclarationHaveABody() &&
13760           !Constructor->isDeleted()) &&
13761     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
13762   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13763     return;
13764 
13765   CXXRecordDecl *ClassDecl = Constructor->getParent();
13766   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
13767 
13768   SynthesizedFunctionScope Scope(*this, Constructor);
13769 
13770   // The exception specification is needed because we are defining the
13771   // function.
13772   ResolveExceptionSpec(CurrentLocation,
13773                        Constructor->getType()->castAs<FunctionProtoType>());
13774   MarkVTableUsed(CurrentLocation, ClassDecl);
13775 
13776   // Add a context note for diagnostics produced after this point.
13777   Scope.addContextNote(CurrentLocation);
13778 
13779   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
13780     Constructor->setInvalidDecl();
13781     return;
13782   }
13783 
13784   SourceLocation Loc = Constructor->getEndLoc().isValid()
13785                            ? Constructor->getEndLoc()
13786                            : Constructor->getLocation();
13787   Constructor->setBody(new (Context) CompoundStmt(Loc));
13788   Constructor->markUsed(Context);
13789 
13790   if (ASTMutationListener *L = getASTMutationListener()) {
13791     L->CompletedImplicitDefinition(Constructor);
13792   }
13793 
13794   DiagnoseUninitializedFields(*this, Constructor);
13795 }
13796 
13797 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
13798   // Perform any delayed checks on exception specifications.
13799   CheckDelayedMemberExceptionSpecs();
13800 }
13801 
13802 /// Find or create the fake constructor we synthesize to model constructing an
13803 /// object of a derived class via a constructor of a base class.
13804 CXXConstructorDecl *
13805 Sema::findInheritingConstructor(SourceLocation Loc,
13806                                 CXXConstructorDecl *BaseCtor,
13807                                 ConstructorUsingShadowDecl *Shadow) {
13808   CXXRecordDecl *Derived = Shadow->getParent();
13809   SourceLocation UsingLoc = Shadow->getLocation();
13810 
13811   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
13812   // For now we use the name of the base class constructor as a member of the
13813   // derived class to indicate a (fake) inherited constructor name.
13814   DeclarationName Name = BaseCtor->getDeclName();
13815 
13816   // Check to see if we already have a fake constructor for this inherited
13817   // constructor call.
13818   for (NamedDecl *Ctor : Derived->lookup(Name))
13819     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
13820                                ->getInheritedConstructor()
13821                                .getConstructor(),
13822                            BaseCtor))
13823       return cast<CXXConstructorDecl>(Ctor);
13824 
13825   DeclarationNameInfo NameInfo(Name, UsingLoc);
13826   TypeSourceInfo *TInfo =
13827       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
13828   FunctionProtoTypeLoc ProtoLoc =
13829       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
13830 
13831   // Check the inherited constructor is valid and find the list of base classes
13832   // from which it was inherited.
13833   InheritedConstructorInfo ICI(*this, Loc, Shadow);
13834 
13835   bool Constexpr =
13836       BaseCtor->isConstexpr() &&
13837       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
13838                                         false, BaseCtor, &ICI);
13839 
13840   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
13841       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
13842       BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
13843       /*isInline=*/true,
13844       /*isImplicitlyDeclared=*/true,
13845       Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified,
13846       InheritedConstructor(Shadow, BaseCtor),
13847       BaseCtor->getTrailingRequiresClause());
13848   if (Shadow->isInvalidDecl())
13849     DerivedCtor->setInvalidDecl();
13850 
13851   // Build an unevaluated exception specification for this fake constructor.
13852   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
13853   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13854   EPI.ExceptionSpec.Type = EST_Unevaluated;
13855   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
13856   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
13857                                                FPT->getParamTypes(), EPI));
13858 
13859   // Build the parameter declarations.
13860   SmallVector<ParmVarDecl *, 16> ParamDecls;
13861   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
13862     TypeSourceInfo *TInfo =
13863         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
13864     ParmVarDecl *PD = ParmVarDecl::Create(
13865         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
13866         FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
13867     PD->setScopeInfo(0, I);
13868     PD->setImplicit();
13869     // Ensure attributes are propagated onto parameters (this matters for
13870     // format, pass_object_size, ...).
13871     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
13872     ParamDecls.push_back(PD);
13873     ProtoLoc.setParam(I, PD);
13874   }
13875 
13876   // Set up the new constructor.
13877   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
13878   DerivedCtor->setAccess(BaseCtor->getAccess());
13879   DerivedCtor->setParams(ParamDecls);
13880   Derived->addDecl(DerivedCtor);
13881 
13882   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
13883     SetDeclDeleted(DerivedCtor, UsingLoc);
13884 
13885   return DerivedCtor;
13886 }
13887 
13888 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
13889   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
13890                                Ctor->getInheritedConstructor().getShadowDecl());
13891   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
13892                             /*Diagnose*/true);
13893 }
13894 
13895 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
13896                                        CXXConstructorDecl *Constructor) {
13897   CXXRecordDecl *ClassDecl = Constructor->getParent();
13898   assert(Constructor->getInheritedConstructor() &&
13899          !Constructor->doesThisDeclarationHaveABody() &&
13900          !Constructor->isDeleted());
13901   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13902     return;
13903 
13904   // Initializations are performed "as if by a defaulted default constructor",
13905   // so enter the appropriate scope.
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   ConstructorUsingShadowDecl *Shadow =
13918       Constructor->getInheritedConstructor().getShadowDecl();
13919   CXXConstructorDecl *InheritedCtor =
13920       Constructor->getInheritedConstructor().getConstructor();
13921 
13922   // [class.inhctor.init]p1:
13923   //   initialization proceeds as if a defaulted default constructor is used to
13924   //   initialize the D object and each base class subobject from which the
13925   //   constructor was inherited
13926 
13927   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
13928   CXXRecordDecl *RD = Shadow->getParent();
13929   SourceLocation InitLoc = Shadow->getLocation();
13930 
13931   // Build explicit initializers for all base classes from which the
13932   // constructor was inherited.
13933   SmallVector<CXXCtorInitializer*, 8> Inits;
13934   for (bool VBase : {false, true}) {
13935     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
13936       if (B.isVirtual() != VBase)
13937         continue;
13938 
13939       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
13940       if (!BaseRD)
13941         continue;
13942 
13943       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
13944       if (!BaseCtor.first)
13945         continue;
13946 
13947       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
13948       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
13949           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
13950 
13951       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
13952       Inits.push_back(new (Context) CXXCtorInitializer(
13953           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
13954           SourceLocation()));
13955     }
13956   }
13957 
13958   // We now proceed as if for a defaulted default constructor, with the relevant
13959   // initializers replaced.
13960 
13961   if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
13962     Constructor->setInvalidDecl();
13963     return;
13964   }
13965 
13966   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
13967   Constructor->markUsed(Context);
13968 
13969   if (ASTMutationListener *L = getASTMutationListener()) {
13970     L->CompletedImplicitDefinition(Constructor);
13971   }
13972 
13973   DiagnoseUninitializedFields(*this, Constructor);
13974 }
13975 
13976 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
13977   // C++ [class.dtor]p2:
13978   //   If a class has no user-declared destructor, a destructor is
13979   //   declared implicitly. An implicitly-declared destructor is an
13980   //   inline public member of its class.
13981   assert(ClassDecl->needsImplicitDestructor());
13982 
13983   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
13984   if (DSM.isAlreadyBeingDeclared())
13985     return nullptr;
13986 
13987   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13988                                                      CXXDestructor,
13989                                                      false);
13990 
13991   // Create the actual destructor declaration.
13992   CanQualType ClassType
13993     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13994   SourceLocation ClassLoc = ClassDecl->getLocation();
13995   DeclarationName Name
13996     = Context.DeclarationNames.getCXXDestructorName(ClassType);
13997   DeclarationNameInfo NameInfo(Name, ClassLoc);
13998   CXXDestructorDecl *Destructor = CXXDestructorDecl::Create(
13999       Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr,
14000       getCurFPFeatures().isFPConstrained(),
14001       /*isInline=*/true,
14002       /*isImplicitlyDeclared=*/true,
14003       Constexpr ? ConstexprSpecKind::Constexpr
14004                 : ConstexprSpecKind::Unspecified);
14005   Destructor->setAccess(AS_public);
14006   Destructor->setDefaulted();
14007 
14008   setupImplicitSpecialMemberType(Destructor, Context.VoidTy, std::nullopt);
14009 
14010   if (getLangOpts().CUDA)
14011     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
14012                                             Destructor,
14013                                             /* ConstRHS */ false,
14014                                             /* Diagnose */ false);
14015 
14016   // We don't need to use SpecialMemberIsTrivial here; triviality for
14017   // destructors is easy to compute.
14018   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
14019   Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
14020                                 ClassDecl->hasTrivialDestructorForCall());
14021 
14022   // Note that we have declared this destructor.
14023   ++getASTContext().NumImplicitDestructorsDeclared;
14024 
14025   Scope *S = getScopeForContext(ClassDecl);
14026   CheckImplicitSpecialMemberDeclaration(S, Destructor);
14027 
14028   // We can't check whether an implicit destructor is deleted before we complete
14029   // the definition of the class, because its validity depends on the alignment
14030   // of the class. We'll check this from ActOnFields once the class is complete.
14031   if (ClassDecl->isCompleteDefinition() &&
14032       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
14033     SetDeclDeleted(Destructor, ClassLoc);
14034 
14035   // Introduce this destructor into its scope.
14036   if (S)
14037     PushOnScopeChains(Destructor, S, false);
14038   ClassDecl->addDecl(Destructor);
14039 
14040   return Destructor;
14041 }
14042 
14043 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
14044                                     CXXDestructorDecl *Destructor) {
14045   assert((Destructor->isDefaulted() &&
14046           !Destructor->doesThisDeclarationHaveABody() &&
14047           !Destructor->isDeleted()) &&
14048          "DefineImplicitDestructor - call it for implicit default dtor");
14049   if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
14050     return;
14051 
14052   CXXRecordDecl *ClassDecl = Destructor->getParent();
14053   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
14054 
14055   SynthesizedFunctionScope Scope(*this, Destructor);
14056 
14057   // The exception specification is needed because we are defining the
14058   // function.
14059   ResolveExceptionSpec(CurrentLocation,
14060                        Destructor->getType()->castAs<FunctionProtoType>());
14061   MarkVTableUsed(CurrentLocation, ClassDecl);
14062 
14063   // Add a context note for diagnostics produced after this point.
14064   Scope.addContextNote(CurrentLocation);
14065 
14066   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14067                                          Destructor->getParent());
14068 
14069   if (CheckDestructor(Destructor)) {
14070     Destructor->setInvalidDecl();
14071     return;
14072   }
14073 
14074   SourceLocation Loc = Destructor->getEndLoc().isValid()
14075                            ? Destructor->getEndLoc()
14076                            : Destructor->getLocation();
14077   Destructor->setBody(new (Context) CompoundStmt(Loc));
14078   Destructor->markUsed(Context);
14079 
14080   if (ASTMutationListener *L = getASTMutationListener()) {
14081     L->CompletedImplicitDefinition(Destructor);
14082   }
14083 }
14084 
14085 void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
14086                                           CXXDestructorDecl *Destructor) {
14087   if (Destructor->isInvalidDecl())
14088     return;
14089 
14090   CXXRecordDecl *ClassDecl = Destructor->getParent();
14091   assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14092          "implicit complete dtors unneeded outside MS ABI");
14093   assert(ClassDecl->getNumVBases() > 0 &&
14094          "complete dtor only exists for classes with vbases");
14095 
14096   SynthesizedFunctionScope Scope(*this, Destructor);
14097 
14098   // Add a context note for diagnostics produced after this point.
14099   Scope.addContextNote(CurrentLocation);
14100 
14101   MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
14102 }
14103 
14104 /// Perform any semantic analysis which needs to be delayed until all
14105 /// pending class member declarations have been parsed.
14106 void Sema::ActOnFinishCXXMemberDecls() {
14107   // If the context is an invalid C++ class, just suppress these checks.
14108   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
14109     if (Record->isInvalidDecl()) {
14110       DelayedOverridingExceptionSpecChecks.clear();
14111       DelayedEquivalentExceptionSpecChecks.clear();
14112       return;
14113     }
14114     checkForMultipleExportedDefaultConstructors(*this, Record);
14115   }
14116 }
14117 
14118 void Sema::ActOnFinishCXXNonNestedClass() {
14119   referenceDLLExportedClassMethods();
14120 
14121   if (!DelayedDllExportMemberFunctions.empty()) {
14122     SmallVector<CXXMethodDecl*, 4> WorkList;
14123     std::swap(DelayedDllExportMemberFunctions, WorkList);
14124     for (CXXMethodDecl *M : WorkList) {
14125       DefineDefaultedFunction(*this, M, M->getLocation());
14126 
14127       // Pass the method to the consumer to get emitted. This is not necessary
14128       // for explicit instantiation definitions, as they will get emitted
14129       // anyway.
14130       if (M->getParent()->getTemplateSpecializationKind() !=
14131           TSK_ExplicitInstantiationDefinition)
14132         ActOnFinishInlineFunctionDef(M);
14133     }
14134   }
14135 }
14136 
14137 void Sema::referenceDLLExportedClassMethods() {
14138   if (!DelayedDllExportClasses.empty()) {
14139     // Calling ReferenceDllExportedMembers might cause the current function to
14140     // be called again, so use a local copy of DelayedDllExportClasses.
14141     SmallVector<CXXRecordDecl *, 4> WorkList;
14142     std::swap(DelayedDllExportClasses, WorkList);
14143     for (CXXRecordDecl *Class : WorkList)
14144       ReferenceDllExportedMembers(*this, Class);
14145   }
14146 }
14147 
14148 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
14149   assert(getLangOpts().CPlusPlus11 &&
14150          "adjusting dtor exception specs was introduced in c++11");
14151 
14152   if (Destructor->isDependentContext())
14153     return;
14154 
14155   // C++11 [class.dtor]p3:
14156   //   A declaration of a destructor that does not have an exception-
14157   //   specification is implicitly considered to have the same exception-
14158   //   specification as an implicit declaration.
14159   const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
14160   if (DtorType->hasExceptionSpec())
14161     return;
14162 
14163   // Replace the destructor's type, building off the existing one. Fortunately,
14164   // the only thing of interest in the destructor type is its extended info.
14165   // The return and arguments are fixed.
14166   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
14167   EPI.ExceptionSpec.Type = EST_Unevaluated;
14168   EPI.ExceptionSpec.SourceDecl = Destructor;
14169   Destructor->setType(
14170       Context.getFunctionType(Context.VoidTy, std::nullopt, EPI));
14171 
14172   // FIXME: If the destructor has a body that could throw, and the newly created
14173   // spec doesn't allow exceptions, we should emit a warning, because this
14174   // change in behavior can break conforming C++03 programs at runtime.
14175   // However, we don't have a body or an exception specification yet, so it
14176   // needs to be done somewhere else.
14177 }
14178 
14179 namespace {
14180 /// An abstract base class for all helper classes used in building the
14181 //  copy/move operators. These classes serve as factory functions and help us
14182 //  avoid using the same Expr* in the AST twice.
14183 class ExprBuilder {
14184   ExprBuilder(const ExprBuilder&) = delete;
14185   ExprBuilder &operator=(const ExprBuilder&) = delete;
14186 
14187 protected:
14188   static Expr *assertNotNull(Expr *E) {
14189     assert(E && "Expression construction must not fail.");
14190     return E;
14191   }
14192 
14193 public:
14194   ExprBuilder() {}
14195   virtual ~ExprBuilder() {}
14196 
14197   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
14198 };
14199 
14200 class RefBuilder: public ExprBuilder {
14201   VarDecl *Var;
14202   QualType VarType;
14203 
14204 public:
14205   Expr *build(Sema &S, SourceLocation Loc) const override {
14206     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
14207   }
14208 
14209   RefBuilder(VarDecl *Var, QualType VarType)
14210       : Var(Var), VarType(VarType) {}
14211 };
14212 
14213 class ThisBuilder: public ExprBuilder {
14214 public:
14215   Expr *build(Sema &S, SourceLocation Loc) const override {
14216     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
14217   }
14218 };
14219 
14220 class CastBuilder: public ExprBuilder {
14221   const ExprBuilder &Builder;
14222   QualType Type;
14223   ExprValueKind Kind;
14224   const CXXCastPath &Path;
14225 
14226 public:
14227   Expr *build(Sema &S, SourceLocation Loc) const override {
14228     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
14229                                              CK_UncheckedDerivedToBase, Kind,
14230                                              &Path).get());
14231   }
14232 
14233   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
14234               const CXXCastPath &Path)
14235       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
14236 };
14237 
14238 class DerefBuilder: public ExprBuilder {
14239   const ExprBuilder &Builder;
14240 
14241 public:
14242   Expr *build(Sema &S, SourceLocation Loc) const override {
14243     return assertNotNull(
14244         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
14245   }
14246 
14247   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14248 };
14249 
14250 class MemberBuilder: public ExprBuilder {
14251   const ExprBuilder &Builder;
14252   QualType Type;
14253   CXXScopeSpec SS;
14254   bool IsArrow;
14255   LookupResult &MemberLookup;
14256 
14257 public:
14258   Expr *build(Sema &S, SourceLocation Loc) const override {
14259     return assertNotNull(S.BuildMemberReferenceExpr(
14260         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
14261         nullptr, MemberLookup, nullptr, nullptr).get());
14262   }
14263 
14264   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
14265                 LookupResult &MemberLookup)
14266       : Builder(Builder), Type(Type), IsArrow(IsArrow),
14267         MemberLookup(MemberLookup) {}
14268 };
14269 
14270 class MoveCastBuilder: public ExprBuilder {
14271   const ExprBuilder &Builder;
14272 
14273 public:
14274   Expr *build(Sema &S, SourceLocation Loc) const override {
14275     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
14276   }
14277 
14278   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14279 };
14280 
14281 class LvalueConvBuilder: public ExprBuilder {
14282   const ExprBuilder &Builder;
14283 
14284 public:
14285   Expr *build(Sema &S, SourceLocation Loc) const override {
14286     return assertNotNull(
14287         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
14288   }
14289 
14290   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14291 };
14292 
14293 class SubscriptBuilder: public ExprBuilder {
14294   const ExprBuilder &Base;
14295   const ExprBuilder &Index;
14296 
14297 public:
14298   Expr *build(Sema &S, SourceLocation Loc) const override {
14299     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
14300         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
14301   }
14302 
14303   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
14304       : Base(Base), Index(Index) {}
14305 };
14306 
14307 } // end anonymous namespace
14308 
14309 /// When generating a defaulted copy or move assignment operator, if a field
14310 /// should be copied with __builtin_memcpy rather than via explicit assignments,
14311 /// do so. This optimization only applies for arrays of scalars, and for arrays
14312 /// of class type where the selected copy/move-assignment operator is trivial.
14313 static StmtResult
14314 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
14315                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
14316   // Compute the size of the memory buffer to be copied.
14317   QualType SizeType = S.Context.getSizeType();
14318   llvm::APInt Size(S.Context.getTypeSize(SizeType),
14319                    S.Context.getTypeSizeInChars(T).getQuantity());
14320 
14321   // Take the address of the field references for "from" and "to". We
14322   // directly construct UnaryOperators here because semantic analysis
14323   // does not permit us to take the address of an xvalue.
14324   Expr *From = FromB.build(S, Loc);
14325   From = UnaryOperator::Create(
14326       S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
14327       VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14328   Expr *To = ToB.build(S, Loc);
14329   To = UnaryOperator::Create(
14330       S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
14331       VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14332 
14333   const Type *E = T->getBaseElementTypeUnsafe();
14334   bool NeedsCollectableMemCpy =
14335       E->isRecordType() &&
14336       E->castAs<RecordType>()->getDecl()->hasObjectMember();
14337 
14338   // Create a reference to the __builtin_objc_memmove_collectable function
14339   StringRef MemCpyName = NeedsCollectableMemCpy ?
14340     "__builtin_objc_memmove_collectable" :
14341     "__builtin_memcpy";
14342   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
14343                  Sema::LookupOrdinaryName);
14344   S.LookupName(R, S.TUScope, true);
14345 
14346   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
14347   if (!MemCpy)
14348     // Something went horribly wrong earlier, and we will have complained
14349     // about it.
14350     return StmtError();
14351 
14352   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
14353                                             VK_PRValue, Loc, nullptr);
14354   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
14355 
14356   Expr *CallArgs[] = {
14357     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
14358   };
14359   ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
14360                                     Loc, CallArgs, Loc);
14361 
14362   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
14363   return Call.getAs<Stmt>();
14364 }
14365 
14366 /// Builds a statement that copies/moves the given entity from \p From to
14367 /// \c To.
14368 ///
14369 /// This routine is used to copy/move the members of a class with an
14370 /// implicitly-declared copy/move assignment operator. When the entities being
14371 /// copied are arrays, this routine builds for loops to copy them.
14372 ///
14373 /// \param S The Sema object used for type-checking.
14374 ///
14375 /// \param Loc The location where the implicit copy/move is being generated.
14376 ///
14377 /// \param T The type of the expressions being copied/moved. Both expressions
14378 /// must have this type.
14379 ///
14380 /// \param To The expression we are copying/moving to.
14381 ///
14382 /// \param From The expression we are copying/moving from.
14383 ///
14384 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
14385 /// Otherwise, it's a non-static member subobject.
14386 ///
14387 /// \param Copying Whether we're copying or moving.
14388 ///
14389 /// \param Depth Internal parameter recording the depth of the recursion.
14390 ///
14391 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
14392 /// if a memcpy should be used instead.
14393 static StmtResult
14394 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
14395                                  const ExprBuilder &To, const ExprBuilder &From,
14396                                  bool CopyingBaseSubobject, bool Copying,
14397                                  unsigned Depth = 0) {
14398   // C++11 [class.copy]p28:
14399   //   Each subobject is assigned in the manner appropriate to its type:
14400   //
14401   //     - if the subobject is of class type, as if by a call to operator= with
14402   //       the subobject as the object expression and the corresponding
14403   //       subobject of x as a single function argument (as if by explicit
14404   //       qualification; that is, ignoring any possible virtual overriding
14405   //       functions in more derived classes);
14406   //
14407   // C++03 [class.copy]p13:
14408   //     - if the subobject is of class type, the copy assignment operator for
14409   //       the class is used (as if by explicit qualification; that is,
14410   //       ignoring any possible virtual overriding functions in more derived
14411   //       classes);
14412   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
14413     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
14414 
14415     // Look for operator=.
14416     DeclarationName Name
14417       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14418     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
14419     S.LookupQualifiedName(OpLookup, ClassDecl, false);
14420 
14421     // Prior to C++11, filter out any result that isn't a copy/move-assignment
14422     // operator.
14423     if (!S.getLangOpts().CPlusPlus11) {
14424       LookupResult::Filter F = OpLookup.makeFilter();
14425       while (F.hasNext()) {
14426         NamedDecl *D = F.next();
14427         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
14428           if (Method->isCopyAssignmentOperator() ||
14429               (!Copying && Method->isMoveAssignmentOperator()))
14430             continue;
14431 
14432         F.erase();
14433       }
14434       F.done();
14435     }
14436 
14437     // Suppress the protected check (C++ [class.protected]) for each of the
14438     // assignment operators we found. This strange dance is required when
14439     // we're assigning via a base classes's copy-assignment operator. To
14440     // ensure that we're getting the right base class subobject (without
14441     // ambiguities), we need to cast "this" to that subobject type; to
14442     // ensure that we don't go through the virtual call mechanism, we need
14443     // to qualify the operator= name with the base class (see below). However,
14444     // this means that if the base class has a protected copy assignment
14445     // operator, the protected member access check will fail. So, we
14446     // rewrite "protected" access to "public" access in this case, since we
14447     // know by construction that we're calling from a derived class.
14448     if (CopyingBaseSubobject) {
14449       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
14450            L != LEnd; ++L) {
14451         if (L.getAccess() == AS_protected)
14452           L.setAccess(AS_public);
14453       }
14454     }
14455 
14456     // Create the nested-name-specifier that will be used to qualify the
14457     // reference to operator=; this is required to suppress the virtual
14458     // call mechanism.
14459     CXXScopeSpec SS;
14460     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
14461     SS.MakeTrivial(S.Context,
14462                    NestedNameSpecifier::Create(S.Context, nullptr, false,
14463                                                CanonicalT),
14464                    Loc);
14465 
14466     // Create the reference to operator=.
14467     ExprResult OpEqualRef
14468       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
14469                                    SS, /*TemplateKWLoc=*/SourceLocation(),
14470                                    /*FirstQualifierInScope=*/nullptr,
14471                                    OpLookup,
14472                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
14473                                    /*SuppressQualifierCheck=*/true);
14474     if (OpEqualRef.isInvalid())
14475       return StmtError();
14476 
14477     // Build the call to the assignment operator.
14478 
14479     Expr *FromInst = From.build(S, Loc);
14480     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
14481                                                   OpEqualRef.getAs<Expr>(),
14482                                                   Loc, FromInst, Loc);
14483     if (Call.isInvalid())
14484       return StmtError();
14485 
14486     // If we built a call to a trivial 'operator=' while copying an array,
14487     // bail out. We'll replace the whole shebang with a memcpy.
14488     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
14489     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
14490       return StmtResult((Stmt*)nullptr);
14491 
14492     // Convert to an expression-statement, and clean up any produced
14493     // temporaries.
14494     return S.ActOnExprStmt(Call);
14495   }
14496 
14497   //     - if the subobject is of scalar type, the built-in assignment
14498   //       operator is used.
14499   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
14500   if (!ArrayTy) {
14501     ExprResult Assignment = S.CreateBuiltinBinOp(
14502         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
14503     if (Assignment.isInvalid())
14504       return StmtError();
14505     return S.ActOnExprStmt(Assignment);
14506   }
14507 
14508   //     - if the subobject is an array, each element is assigned, in the
14509   //       manner appropriate to the element type;
14510 
14511   // Construct a loop over the array bounds, e.g.,
14512   //
14513   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
14514   //
14515   // that will copy each of the array elements.
14516   QualType SizeType = S.Context.getSizeType();
14517 
14518   // Create the iteration variable.
14519   IdentifierInfo *IterationVarName = nullptr;
14520   {
14521     SmallString<8> Str;
14522     llvm::raw_svector_ostream OS(Str);
14523     OS << "__i" << Depth;
14524     IterationVarName = &S.Context.Idents.get(OS.str());
14525   }
14526   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
14527                                           IterationVarName, SizeType,
14528                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
14529                                           SC_None);
14530 
14531   // Initialize the iteration variable to zero.
14532   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
14533   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
14534 
14535   // Creates a reference to the iteration variable.
14536   RefBuilder IterationVarRef(IterationVar, SizeType);
14537   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
14538 
14539   // Create the DeclStmt that holds the iteration variable.
14540   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
14541 
14542   // Subscript the "from" and "to" expressions with the iteration variable.
14543   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
14544   MoveCastBuilder FromIndexMove(FromIndexCopy);
14545   const ExprBuilder *FromIndex;
14546   if (Copying)
14547     FromIndex = &FromIndexCopy;
14548   else
14549     FromIndex = &FromIndexMove;
14550 
14551   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
14552 
14553   // Build the copy/move for an individual element of the array.
14554   StmtResult Copy =
14555     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
14556                                      ToIndex, *FromIndex, CopyingBaseSubobject,
14557                                      Copying, Depth + 1);
14558   // Bail out if copying fails or if we determined that we should use memcpy.
14559   if (Copy.isInvalid() || !Copy.get())
14560     return Copy;
14561 
14562   // Create the comparison against the array bound.
14563   llvm::APInt Upper
14564     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
14565   Expr *Comparison = BinaryOperator::Create(
14566       S.Context, IterationVarRefRVal.build(S, Loc),
14567       IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
14568       S.Context.BoolTy, VK_PRValue, OK_Ordinary, Loc,
14569       S.CurFPFeatureOverrides());
14570 
14571   // Create the pre-increment of the iteration variable. We can determine
14572   // whether the increment will overflow based on the value of the array
14573   // bound.
14574   Expr *Increment = UnaryOperator::Create(
14575       S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
14576       OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
14577 
14578   // Construct the loop that copies all elements of this array.
14579   return S.ActOnForStmt(
14580       Loc, Loc, InitStmt,
14581       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
14582       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
14583 }
14584 
14585 static StmtResult
14586 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
14587                       const ExprBuilder &To, const ExprBuilder &From,
14588                       bool CopyingBaseSubobject, bool Copying) {
14589   // Maybe we should use a memcpy?
14590   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
14591       T.isTriviallyCopyableType(S.Context))
14592     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14593 
14594   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
14595                                                      CopyingBaseSubobject,
14596                                                      Copying, 0));
14597 
14598   // If we ended up picking a trivial assignment operator for an array of a
14599   // non-trivially-copyable class type, just emit a memcpy.
14600   if (!Result.isInvalid() && !Result.get())
14601     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14602 
14603   return Result;
14604 }
14605 
14606 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
14607   // Note: The following rules are largely analoguous to the copy
14608   // constructor rules. Note that virtual bases are not taken into account
14609   // for determining the argument type of the operator. Note also that
14610   // operators taking an object instead of a reference are allowed.
14611   assert(ClassDecl->needsImplicitCopyAssignment());
14612 
14613   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
14614   if (DSM.isAlreadyBeingDeclared())
14615     return nullptr;
14616 
14617   QualType ArgType = Context.getTypeDeclType(ClassDecl);
14618   ArgType = Context.getElaboratedType(ETK_None, nullptr, ArgType, nullptr);
14619   LangAS AS = getDefaultCXXMethodAddrSpace();
14620   if (AS != LangAS::Default)
14621     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14622   QualType RetType = Context.getLValueReferenceType(ArgType);
14623   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
14624   if (Const)
14625     ArgType = ArgType.withConst();
14626 
14627   ArgType = Context.getLValueReferenceType(ArgType);
14628 
14629   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14630                                                      CXXCopyAssignment,
14631                                                      Const);
14632 
14633   //   An implicitly-declared copy assignment operator is an inline public
14634   //   member of its class.
14635   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14636   SourceLocation ClassLoc = ClassDecl->getLocation();
14637   DeclarationNameInfo NameInfo(Name, ClassLoc);
14638   CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
14639       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14640       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14641       getCurFPFeatures().isFPConstrained(),
14642       /*isInline=*/true,
14643       Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
14644       SourceLocation());
14645   CopyAssignment->setAccess(AS_public);
14646   CopyAssignment->setDefaulted();
14647   CopyAssignment->setImplicit();
14648 
14649   setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
14650 
14651   if (getLangOpts().CUDA)
14652     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
14653                                             CopyAssignment,
14654                                             /* ConstRHS */ Const,
14655                                             /* Diagnose */ false);
14656 
14657   // Add the parameter to the operator.
14658   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
14659                                                ClassLoc, ClassLoc,
14660                                                /*Id=*/nullptr, ArgType,
14661                                                /*TInfo=*/nullptr, SC_None,
14662                                                nullptr);
14663   CopyAssignment->setParams(FromParam);
14664 
14665   CopyAssignment->setTrivial(
14666     ClassDecl->needsOverloadResolutionForCopyAssignment()
14667       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
14668       : ClassDecl->hasTrivialCopyAssignment());
14669 
14670   // Note that we have added this copy-assignment operator.
14671   ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
14672 
14673   Scope *S = getScopeForContext(ClassDecl);
14674   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
14675 
14676   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) {
14677     ClassDecl->setImplicitCopyAssignmentIsDeleted();
14678     SetDeclDeleted(CopyAssignment, ClassLoc);
14679   }
14680 
14681   if (S)
14682     PushOnScopeChains(CopyAssignment, S, false);
14683   ClassDecl->addDecl(CopyAssignment);
14684 
14685   return CopyAssignment;
14686 }
14687 
14688 /// Diagnose an implicit copy operation for a class which is odr-used, but
14689 /// which is deprecated because the class has a user-declared copy constructor,
14690 /// copy assignment operator, or destructor.
14691 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
14692   assert(CopyOp->isImplicit());
14693 
14694   CXXRecordDecl *RD = CopyOp->getParent();
14695   CXXMethodDecl *UserDeclaredOperation = nullptr;
14696 
14697   if (RD->hasUserDeclaredDestructor()) {
14698     UserDeclaredOperation = RD->getDestructor();
14699   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
14700              RD->hasUserDeclaredCopyConstructor()) {
14701     // Find any user-declared copy constructor.
14702     for (auto *I : RD->ctors()) {
14703       if (I->isCopyConstructor()) {
14704         UserDeclaredOperation = I;
14705         break;
14706       }
14707     }
14708     assert(UserDeclaredOperation);
14709   } else if (isa<CXXConstructorDecl>(CopyOp) &&
14710              RD->hasUserDeclaredCopyAssignment()) {
14711     // Find any user-declared move assignment operator.
14712     for (auto *I : RD->methods()) {
14713       if (I->isCopyAssignmentOperator()) {
14714         UserDeclaredOperation = I;
14715         break;
14716       }
14717     }
14718     assert(UserDeclaredOperation);
14719   }
14720 
14721   if (UserDeclaredOperation) {
14722     bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
14723     bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation);
14724     bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp);
14725     unsigned DiagID =
14726         (UDOIsUserProvided && UDOIsDestructor)
14727             ? diag::warn_deprecated_copy_with_user_provided_dtor
14728         : (UDOIsUserProvided && !UDOIsDestructor)
14729             ? diag::warn_deprecated_copy_with_user_provided_copy
14730         : (!UDOIsUserProvided && UDOIsDestructor)
14731             ? diag::warn_deprecated_copy_with_dtor
14732             : diag::warn_deprecated_copy;
14733     S.Diag(UserDeclaredOperation->getLocation(), DiagID)
14734         << RD << IsCopyAssignment;
14735   }
14736 }
14737 
14738 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
14739                                         CXXMethodDecl *CopyAssignOperator) {
14740   assert((CopyAssignOperator->isDefaulted() &&
14741           CopyAssignOperator->isOverloadedOperator() &&
14742           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
14743           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
14744           !CopyAssignOperator->isDeleted()) &&
14745          "DefineImplicitCopyAssignment called for wrong function");
14746   if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
14747     return;
14748 
14749   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
14750   if (ClassDecl->isInvalidDecl()) {
14751     CopyAssignOperator->setInvalidDecl();
14752     return;
14753   }
14754 
14755   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
14756 
14757   // The exception specification is needed because we are defining the
14758   // function.
14759   ResolveExceptionSpec(CurrentLocation,
14760                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
14761 
14762   // Add a context note for diagnostics produced after this point.
14763   Scope.addContextNote(CurrentLocation);
14764 
14765   // C++11 [class.copy]p18:
14766   //   The [definition of an implicitly declared copy assignment operator] is
14767   //   deprecated if the class has a user-declared copy constructor or a
14768   //   user-declared destructor.
14769   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
14770     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
14771 
14772   // C++0x [class.copy]p30:
14773   //   The implicitly-defined or explicitly-defaulted copy assignment operator
14774   //   for a non-union class X performs memberwise copy assignment of its
14775   //   subobjects. The direct base classes of X are assigned first, in the
14776   //   order of their declaration in the base-specifier-list, and then the
14777   //   immediate non-static data members of X are assigned, in the order in
14778   //   which they were declared in the class definition.
14779 
14780   // The statements that form the synthesized function body.
14781   SmallVector<Stmt*, 8> Statements;
14782 
14783   // The parameter for the "other" object, which we are copying from.
14784   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
14785   Qualifiers OtherQuals = Other->getType().getQualifiers();
14786   QualType OtherRefType = Other->getType();
14787   if (const LValueReferenceType *OtherRef
14788                                 = OtherRefType->getAs<LValueReferenceType>()) {
14789     OtherRefType = OtherRef->getPointeeType();
14790     OtherQuals = OtherRefType.getQualifiers();
14791   }
14792 
14793   // Our location for everything implicitly-generated.
14794   SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
14795                            ? CopyAssignOperator->getEndLoc()
14796                            : CopyAssignOperator->getLocation();
14797 
14798   // Builds a DeclRefExpr for the "other" object.
14799   RefBuilder OtherRef(Other, OtherRefType);
14800 
14801   // Builds the "this" pointer.
14802   ThisBuilder This;
14803 
14804   // Assign base classes.
14805   bool Invalid = false;
14806   for (auto &Base : ClassDecl->bases()) {
14807     // Form the assignment:
14808     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
14809     QualType BaseType = Base.getType().getUnqualifiedType();
14810     if (!BaseType->isRecordType()) {
14811       Invalid = true;
14812       continue;
14813     }
14814 
14815     CXXCastPath BasePath;
14816     BasePath.push_back(&Base);
14817 
14818     // Construct the "from" expression, which is an implicit cast to the
14819     // appropriately-qualified base type.
14820     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
14821                      VK_LValue, BasePath);
14822 
14823     // Dereference "this".
14824     DerefBuilder DerefThis(This);
14825     CastBuilder To(DerefThis,
14826                    Context.getQualifiedType(
14827                        BaseType, CopyAssignOperator->getMethodQualifiers()),
14828                    VK_LValue, BasePath);
14829 
14830     // Build the copy.
14831     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
14832                                             To, From,
14833                                             /*CopyingBaseSubobject=*/true,
14834                                             /*Copying=*/true);
14835     if (Copy.isInvalid()) {
14836       CopyAssignOperator->setInvalidDecl();
14837       return;
14838     }
14839 
14840     // Success! Record the copy.
14841     Statements.push_back(Copy.getAs<Expr>());
14842   }
14843 
14844   // Assign non-static members.
14845   for (auto *Field : ClassDecl->fields()) {
14846     // FIXME: We should form some kind of AST representation for the implied
14847     // memcpy in a union copy operation.
14848     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14849       continue;
14850 
14851     if (Field->isInvalidDecl()) {
14852       Invalid = true;
14853       continue;
14854     }
14855 
14856     // Check for members of reference type; we can't copy those.
14857     if (Field->getType()->isReferenceType()) {
14858       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14859         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14860       Diag(Field->getLocation(), diag::note_declared_at);
14861       Invalid = true;
14862       continue;
14863     }
14864 
14865     // Check for members of const-qualified, non-class type.
14866     QualType BaseType = Context.getBaseElementType(Field->getType());
14867     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14868       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14869         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14870       Diag(Field->getLocation(), diag::note_declared_at);
14871       Invalid = true;
14872       continue;
14873     }
14874 
14875     // Suppress assigning zero-width bitfields.
14876     if (Field->isZeroLengthBitField(Context))
14877       continue;
14878 
14879     QualType FieldType = Field->getType().getNonReferenceType();
14880     if (FieldType->isIncompleteArrayType()) {
14881       assert(ClassDecl->hasFlexibleArrayMember() &&
14882              "Incomplete array type is not valid");
14883       continue;
14884     }
14885 
14886     // Build references to the field in the object we're copying from and to.
14887     CXXScopeSpec SS; // Intentionally empty
14888     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14889                               LookupMemberName);
14890     MemberLookup.addDecl(Field);
14891     MemberLookup.resolveKind();
14892 
14893     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
14894 
14895     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/!LangOpts.HLSL,
14896                      MemberLookup);
14897 
14898     // Build the copy of this field.
14899     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
14900                                             To, From,
14901                                             /*CopyingBaseSubobject=*/false,
14902                                             /*Copying=*/true);
14903     if (Copy.isInvalid()) {
14904       CopyAssignOperator->setInvalidDecl();
14905       return;
14906     }
14907 
14908     // Success! Record the copy.
14909     Statements.push_back(Copy.getAs<Stmt>());
14910   }
14911 
14912   if (!Invalid) {
14913     // Add a "return *this;"
14914     Expr *ThisExpr = nullptr;
14915     if (!LangOpts.HLSL) {
14916       ExprResult ThisObj =
14917           CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14918       ThisExpr = ThisObj.get();
14919     } else {
14920       ThisExpr = This.build(*this, Loc);
14921     }
14922 
14923     StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
14924     if (Return.isInvalid())
14925       Invalid = true;
14926     else
14927       Statements.push_back(Return.getAs<Stmt>());
14928   }
14929 
14930   if (Invalid) {
14931     CopyAssignOperator->setInvalidDecl();
14932     return;
14933   }
14934 
14935   StmtResult Body;
14936   {
14937     CompoundScopeRAII CompoundScope(*this);
14938     Body = ActOnCompoundStmt(Loc, Loc, Statements,
14939                              /*isStmtExpr=*/false);
14940     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
14941   }
14942   CopyAssignOperator->setBody(Body.getAs<Stmt>());
14943   CopyAssignOperator->markUsed(Context);
14944 
14945   if (ASTMutationListener *L = getASTMutationListener()) {
14946     L->CompletedImplicitDefinition(CopyAssignOperator);
14947   }
14948 }
14949 
14950 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
14951   assert(ClassDecl->needsImplicitMoveAssignment());
14952 
14953   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
14954   if (DSM.isAlreadyBeingDeclared())
14955     return nullptr;
14956 
14957   // Note: The following rules are largely analoguous to the move
14958   // constructor rules.
14959 
14960   QualType ArgType = Context.getTypeDeclType(ClassDecl);
14961   ArgType = Context.getElaboratedType(ETK_None, nullptr, ArgType, nullptr);
14962   LangAS AS = getDefaultCXXMethodAddrSpace();
14963   if (AS != LangAS::Default)
14964     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14965   QualType RetType = Context.getLValueReferenceType(ArgType);
14966   ArgType = Context.getRValueReferenceType(ArgType);
14967 
14968   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14969                                                      CXXMoveAssignment,
14970                                                      false);
14971 
14972   //   An implicitly-declared move assignment operator is an inline public
14973   //   member of its class.
14974   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14975   SourceLocation ClassLoc = ClassDecl->getLocation();
14976   DeclarationNameInfo NameInfo(Name, ClassLoc);
14977   CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
14978       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14979       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14980       getCurFPFeatures().isFPConstrained(),
14981       /*isInline=*/true,
14982       Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
14983       SourceLocation());
14984   MoveAssignment->setAccess(AS_public);
14985   MoveAssignment->setDefaulted();
14986   MoveAssignment->setImplicit();
14987 
14988   setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType);
14989 
14990   if (getLangOpts().CUDA)
14991     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
14992                                             MoveAssignment,
14993                                             /* ConstRHS */ false,
14994                                             /* Diagnose */ false);
14995 
14996   // Add the parameter to the operator.
14997   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
14998                                                ClassLoc, ClassLoc,
14999                                                /*Id=*/nullptr, ArgType,
15000                                                /*TInfo=*/nullptr, SC_None,
15001                                                nullptr);
15002   MoveAssignment->setParams(FromParam);
15003 
15004   MoveAssignment->setTrivial(
15005     ClassDecl->needsOverloadResolutionForMoveAssignment()
15006       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
15007       : ClassDecl->hasTrivialMoveAssignment());
15008 
15009   // Note that we have added this copy-assignment operator.
15010   ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
15011 
15012   Scope *S = getScopeForContext(ClassDecl);
15013   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
15014 
15015   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
15016     ClassDecl->setImplicitMoveAssignmentIsDeleted();
15017     SetDeclDeleted(MoveAssignment, ClassLoc);
15018   }
15019 
15020   if (S)
15021     PushOnScopeChains(MoveAssignment, S, false);
15022   ClassDecl->addDecl(MoveAssignment);
15023 
15024   return MoveAssignment;
15025 }
15026 
15027 /// Check if we're implicitly defining a move assignment operator for a class
15028 /// with virtual bases. Such a move assignment might move-assign the virtual
15029 /// base multiple times.
15030 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
15031                                                SourceLocation CurrentLocation) {
15032   assert(!Class->isDependentContext() && "should not define dependent move");
15033 
15034   // Only a virtual base could get implicitly move-assigned multiple times.
15035   // Only a non-trivial move assignment can observe this. We only want to
15036   // diagnose if we implicitly define an assignment operator that assigns
15037   // two base classes, both of which move-assign the same virtual base.
15038   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
15039       Class->getNumBases() < 2)
15040     return;
15041 
15042   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
15043   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
15044   VBaseMap VBases;
15045 
15046   for (auto &BI : Class->bases()) {
15047     Worklist.push_back(&BI);
15048     while (!Worklist.empty()) {
15049       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
15050       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
15051 
15052       // If the base has no non-trivial move assignment operators,
15053       // we don't care about moves from it.
15054       if (!Base->hasNonTrivialMoveAssignment())
15055         continue;
15056 
15057       // If there's nothing virtual here, skip it.
15058       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
15059         continue;
15060 
15061       // If we're not actually going to call a move assignment for this base,
15062       // or the selected move assignment is trivial, skip it.
15063       Sema::SpecialMemberOverloadResult SMOR =
15064         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
15065                               /*ConstArg*/false, /*VolatileArg*/false,
15066                               /*RValueThis*/true, /*ConstThis*/false,
15067                               /*VolatileThis*/false);
15068       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
15069           !SMOR.getMethod()->isMoveAssignmentOperator())
15070         continue;
15071 
15072       if (BaseSpec->isVirtual()) {
15073         // We're going to move-assign this virtual base, and its move
15074         // assignment operator is not trivial. If this can happen for
15075         // multiple distinct direct bases of Class, diagnose it. (If it
15076         // only happens in one base, we'll diagnose it when synthesizing
15077         // that base class's move assignment operator.)
15078         CXXBaseSpecifier *&Existing =
15079             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
15080                 .first->second;
15081         if (Existing && Existing != &BI) {
15082           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
15083             << Class << Base;
15084           S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
15085               << (Base->getCanonicalDecl() ==
15086                   Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15087               << Base << Existing->getType() << Existing->getSourceRange();
15088           S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
15089               << (Base->getCanonicalDecl() ==
15090                   BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15091               << Base << BI.getType() << BaseSpec->getSourceRange();
15092 
15093           // Only diagnose each vbase once.
15094           Existing = nullptr;
15095         }
15096       } else {
15097         // Only walk over bases that have defaulted move assignment operators.
15098         // We assume that any user-provided move assignment operator handles
15099         // the multiple-moves-of-vbase case itself somehow.
15100         if (!SMOR.getMethod()->isDefaulted())
15101           continue;
15102 
15103         // We're going to move the base classes of Base. Add them to the list.
15104         llvm::append_range(Worklist, llvm::make_pointer_range(Base->bases()));
15105       }
15106     }
15107   }
15108 }
15109 
15110 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
15111                                         CXXMethodDecl *MoveAssignOperator) {
15112   assert((MoveAssignOperator->isDefaulted() &&
15113           MoveAssignOperator->isOverloadedOperator() &&
15114           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
15115           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
15116           !MoveAssignOperator->isDeleted()) &&
15117          "DefineImplicitMoveAssignment called for wrong function");
15118   if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
15119     return;
15120 
15121   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
15122   if (ClassDecl->isInvalidDecl()) {
15123     MoveAssignOperator->setInvalidDecl();
15124     return;
15125   }
15126 
15127   // C++0x [class.copy]p28:
15128   //   The implicitly-defined or move assignment operator for a non-union class
15129   //   X performs memberwise move assignment of its subobjects. The direct base
15130   //   classes of X are assigned first, in the order of their declaration in the
15131   //   base-specifier-list, and then the immediate non-static data members of X
15132   //   are assigned, in the order in which they were declared in the class
15133   //   definition.
15134 
15135   // Issue a warning if our implicit move assignment operator will move
15136   // from a virtual base more than once.
15137   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
15138 
15139   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
15140 
15141   // The exception specification is needed because we are defining the
15142   // function.
15143   ResolveExceptionSpec(CurrentLocation,
15144                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
15145 
15146   // Add a context note for diagnostics produced after this point.
15147   Scope.addContextNote(CurrentLocation);
15148 
15149   // The statements that form the synthesized function body.
15150   SmallVector<Stmt*, 8> Statements;
15151 
15152   // The parameter for the "other" object, which we are move from.
15153   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
15154   QualType OtherRefType =
15155       Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
15156 
15157   // Our location for everything implicitly-generated.
15158   SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
15159                            ? MoveAssignOperator->getEndLoc()
15160                            : MoveAssignOperator->getLocation();
15161 
15162   // Builds a reference to the "other" object.
15163   RefBuilder OtherRef(Other, OtherRefType);
15164   // Cast to rvalue.
15165   MoveCastBuilder MoveOther(OtherRef);
15166 
15167   // Builds the "this" pointer.
15168   ThisBuilder This;
15169 
15170   // Assign base classes.
15171   bool Invalid = false;
15172   for (auto &Base : ClassDecl->bases()) {
15173     // C++11 [class.copy]p28:
15174     //   It is unspecified whether subobjects representing virtual base classes
15175     //   are assigned more than once by the implicitly-defined copy assignment
15176     //   operator.
15177     // FIXME: Do not assign to a vbase that will be assigned by some other base
15178     // class. For a move-assignment, this can result in the vbase being moved
15179     // multiple times.
15180 
15181     // Form the assignment:
15182     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
15183     QualType BaseType = Base.getType().getUnqualifiedType();
15184     if (!BaseType->isRecordType()) {
15185       Invalid = true;
15186       continue;
15187     }
15188 
15189     CXXCastPath BasePath;
15190     BasePath.push_back(&Base);
15191 
15192     // Construct the "from" expression, which is an implicit cast to the
15193     // appropriately-qualified base type.
15194     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
15195 
15196     // Dereference "this".
15197     DerefBuilder DerefThis(This);
15198 
15199     // Implicitly cast "this" to the appropriately-qualified base type.
15200     CastBuilder To(DerefThis,
15201                    Context.getQualifiedType(
15202                        BaseType, MoveAssignOperator->getMethodQualifiers()),
15203                    VK_LValue, BasePath);
15204 
15205     // Build the move.
15206     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
15207                                             To, From,
15208                                             /*CopyingBaseSubobject=*/true,
15209                                             /*Copying=*/false);
15210     if (Move.isInvalid()) {
15211       MoveAssignOperator->setInvalidDecl();
15212       return;
15213     }
15214 
15215     // Success! Record the move.
15216     Statements.push_back(Move.getAs<Expr>());
15217   }
15218 
15219   // Assign non-static members.
15220   for (auto *Field : ClassDecl->fields()) {
15221     // FIXME: We should form some kind of AST representation for the implied
15222     // memcpy in a union copy operation.
15223     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
15224       continue;
15225 
15226     if (Field->isInvalidDecl()) {
15227       Invalid = true;
15228       continue;
15229     }
15230 
15231     // Check for members of reference type; we can't move those.
15232     if (Field->getType()->isReferenceType()) {
15233       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15234         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
15235       Diag(Field->getLocation(), diag::note_declared_at);
15236       Invalid = true;
15237       continue;
15238     }
15239 
15240     // Check for members of const-qualified, non-class type.
15241     QualType BaseType = Context.getBaseElementType(Field->getType());
15242     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
15243       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15244         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
15245       Diag(Field->getLocation(), diag::note_declared_at);
15246       Invalid = true;
15247       continue;
15248     }
15249 
15250     // Suppress assigning zero-width bitfields.
15251     if (Field->isZeroLengthBitField(Context))
15252       continue;
15253 
15254     QualType FieldType = Field->getType().getNonReferenceType();
15255     if (FieldType->isIncompleteArrayType()) {
15256       assert(ClassDecl->hasFlexibleArrayMember() &&
15257              "Incomplete array type is not valid");
15258       continue;
15259     }
15260 
15261     // Build references to the field in the object we're copying from and to.
15262     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15263                               LookupMemberName);
15264     MemberLookup.addDecl(Field);
15265     MemberLookup.resolveKind();
15266     MemberBuilder From(MoveOther, OtherRefType,
15267                        /*IsArrow=*/false, MemberLookup);
15268     MemberBuilder To(This, getCurrentThisType(),
15269                      /*IsArrow=*/true, MemberLookup);
15270 
15271     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
15272         "Member reference with rvalue base must be rvalue except for reference "
15273         "members, which aren't allowed for move assignment.");
15274 
15275     // Build the move of this field.
15276     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
15277                                             To, From,
15278                                             /*CopyingBaseSubobject=*/false,
15279                                             /*Copying=*/false);
15280     if (Move.isInvalid()) {
15281       MoveAssignOperator->setInvalidDecl();
15282       return;
15283     }
15284 
15285     // Success! Record the copy.
15286     Statements.push_back(Move.getAs<Stmt>());
15287   }
15288 
15289   if (!Invalid) {
15290     // Add a "return *this;"
15291     ExprResult ThisObj =
15292         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
15293 
15294     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
15295     if (Return.isInvalid())
15296       Invalid = true;
15297     else
15298       Statements.push_back(Return.getAs<Stmt>());
15299   }
15300 
15301   if (Invalid) {
15302     MoveAssignOperator->setInvalidDecl();
15303     return;
15304   }
15305 
15306   StmtResult Body;
15307   {
15308     CompoundScopeRAII CompoundScope(*this);
15309     Body = ActOnCompoundStmt(Loc, Loc, Statements,
15310                              /*isStmtExpr=*/false);
15311     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15312   }
15313   MoveAssignOperator->setBody(Body.getAs<Stmt>());
15314   MoveAssignOperator->markUsed(Context);
15315 
15316   if (ASTMutationListener *L = getASTMutationListener()) {
15317     L->CompletedImplicitDefinition(MoveAssignOperator);
15318   }
15319 }
15320 
15321 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
15322                                                     CXXRecordDecl *ClassDecl) {
15323   // C++ [class.copy]p4:
15324   //   If the class definition does not explicitly declare a copy
15325   //   constructor, one is declared implicitly.
15326   assert(ClassDecl->needsImplicitCopyConstructor());
15327 
15328   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
15329   if (DSM.isAlreadyBeingDeclared())
15330     return nullptr;
15331 
15332   QualType ClassType = Context.getTypeDeclType(ClassDecl);
15333   QualType ArgType = ClassType;
15334   ArgType = Context.getElaboratedType(ETK_None, nullptr, ArgType, nullptr);
15335   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
15336   if (Const)
15337     ArgType = ArgType.withConst();
15338 
15339   LangAS AS = getDefaultCXXMethodAddrSpace();
15340   if (AS != LangAS::Default)
15341     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15342 
15343   ArgType = Context.getLValueReferenceType(ArgType);
15344 
15345   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
15346                                                      CXXCopyConstructor,
15347                                                      Const);
15348 
15349   DeclarationName Name
15350     = Context.DeclarationNames.getCXXConstructorName(
15351                                            Context.getCanonicalType(ClassType));
15352   SourceLocation ClassLoc = ClassDecl->getLocation();
15353   DeclarationNameInfo NameInfo(Name, ClassLoc);
15354 
15355   //   An implicitly-declared copy constructor is an inline public
15356   //   member of its class.
15357   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
15358       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15359       ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15360       /*isInline=*/true,
15361       /*isImplicitlyDeclared=*/true,
15362       Constexpr ? ConstexprSpecKind::Constexpr
15363                 : ConstexprSpecKind::Unspecified);
15364   CopyConstructor->setAccess(AS_public);
15365   CopyConstructor->setDefaulted();
15366 
15367   setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
15368 
15369   if (getLangOpts().CUDA)
15370     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
15371                                             CopyConstructor,
15372                                             /* ConstRHS */ Const,
15373                                             /* Diagnose */ false);
15374 
15375   // During template instantiation of special member functions we need a
15376   // reliable TypeSourceInfo for the parameter types in order to allow functions
15377   // to be substituted.
15378   TypeSourceInfo *TSI = nullptr;
15379   if (inTemplateInstantiation() && ClassDecl->isLambda())
15380     TSI = Context.getTrivialTypeSourceInfo(ArgType);
15381 
15382   // Add the parameter to the constructor.
15383   ParmVarDecl *FromParam =
15384       ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc,
15385                           /*IdentifierInfo=*/nullptr, ArgType,
15386                           /*TInfo=*/TSI, SC_None, nullptr);
15387   CopyConstructor->setParams(FromParam);
15388 
15389   CopyConstructor->setTrivial(
15390       ClassDecl->needsOverloadResolutionForCopyConstructor()
15391           ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
15392           : ClassDecl->hasTrivialCopyConstructor());
15393 
15394   CopyConstructor->setTrivialForCall(
15395       ClassDecl->hasAttr<TrivialABIAttr>() ||
15396       (ClassDecl->needsOverloadResolutionForCopyConstructor()
15397            ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
15398              TAH_ConsiderTrivialABI)
15399            : ClassDecl->hasTrivialCopyConstructorForCall()));
15400 
15401   // Note that we have declared this constructor.
15402   ++getASTContext().NumImplicitCopyConstructorsDeclared;
15403 
15404   Scope *S = getScopeForContext(ClassDecl);
15405   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
15406 
15407   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
15408     ClassDecl->setImplicitCopyConstructorIsDeleted();
15409     SetDeclDeleted(CopyConstructor, ClassLoc);
15410   }
15411 
15412   if (S)
15413     PushOnScopeChains(CopyConstructor, S, false);
15414   ClassDecl->addDecl(CopyConstructor);
15415 
15416   return CopyConstructor;
15417 }
15418 
15419 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
15420                                          CXXConstructorDecl *CopyConstructor) {
15421   assert((CopyConstructor->isDefaulted() &&
15422           CopyConstructor->isCopyConstructor() &&
15423           !CopyConstructor->doesThisDeclarationHaveABody() &&
15424           !CopyConstructor->isDeleted()) &&
15425          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
15426   if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
15427     return;
15428 
15429   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
15430   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
15431 
15432   SynthesizedFunctionScope Scope(*this, CopyConstructor);
15433 
15434   // The exception specification is needed because we are defining the
15435   // function.
15436   ResolveExceptionSpec(CurrentLocation,
15437                        CopyConstructor->getType()->castAs<FunctionProtoType>());
15438   MarkVTableUsed(CurrentLocation, ClassDecl);
15439 
15440   // Add a context note for diagnostics produced after this point.
15441   Scope.addContextNote(CurrentLocation);
15442 
15443   // C++11 [class.copy]p7:
15444   //   The [definition of an implicitly declared copy constructor] is
15445   //   deprecated if the class has a user-declared copy assignment operator
15446   //   or a user-declared destructor.
15447   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
15448     diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
15449 
15450   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
15451     CopyConstructor->setInvalidDecl();
15452   }  else {
15453     SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
15454                              ? CopyConstructor->getEndLoc()
15455                              : CopyConstructor->getLocation();
15456     Sema::CompoundScopeRAII CompoundScope(*this);
15457     CopyConstructor->setBody(
15458         ActOnCompoundStmt(Loc, Loc, std::nullopt, /*isStmtExpr=*/false)
15459             .getAs<Stmt>());
15460     CopyConstructor->markUsed(Context);
15461   }
15462 
15463   if (ASTMutationListener *L = getASTMutationListener()) {
15464     L->CompletedImplicitDefinition(CopyConstructor);
15465   }
15466 }
15467 
15468 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
15469                                                     CXXRecordDecl *ClassDecl) {
15470   assert(ClassDecl->needsImplicitMoveConstructor());
15471 
15472   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
15473   if (DSM.isAlreadyBeingDeclared())
15474     return nullptr;
15475 
15476   QualType ClassType = Context.getTypeDeclType(ClassDecl);
15477 
15478   QualType ArgType = ClassType;
15479   ArgType = Context.getElaboratedType(ETK_None, nullptr, ArgType, nullptr);
15480   LangAS AS = getDefaultCXXMethodAddrSpace();
15481   if (AS != LangAS::Default)
15482     ArgType = Context.getAddrSpaceQualType(ClassType, AS);
15483   ArgType = Context.getRValueReferenceType(ArgType);
15484 
15485   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
15486                                                      CXXMoveConstructor,
15487                                                      false);
15488 
15489   DeclarationName Name
15490     = Context.DeclarationNames.getCXXConstructorName(
15491                                            Context.getCanonicalType(ClassType));
15492   SourceLocation ClassLoc = ClassDecl->getLocation();
15493   DeclarationNameInfo NameInfo(Name, ClassLoc);
15494 
15495   // C++11 [class.copy]p11:
15496   //   An implicitly-declared copy/move constructor is an inline public
15497   //   member of its class.
15498   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
15499       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15500       ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15501       /*isInline=*/true,
15502       /*isImplicitlyDeclared=*/true,
15503       Constexpr ? ConstexprSpecKind::Constexpr
15504                 : ConstexprSpecKind::Unspecified);
15505   MoveConstructor->setAccess(AS_public);
15506   MoveConstructor->setDefaulted();
15507 
15508   setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
15509 
15510   if (getLangOpts().CUDA)
15511     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
15512                                             MoveConstructor,
15513                                             /* ConstRHS */ false,
15514                                             /* Diagnose */ false);
15515 
15516   // Add the parameter to the constructor.
15517   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
15518                                                ClassLoc, ClassLoc,
15519                                                /*IdentifierInfo=*/nullptr,
15520                                                ArgType, /*TInfo=*/nullptr,
15521                                                SC_None, nullptr);
15522   MoveConstructor->setParams(FromParam);
15523 
15524   MoveConstructor->setTrivial(
15525       ClassDecl->needsOverloadResolutionForMoveConstructor()
15526           ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
15527           : ClassDecl->hasTrivialMoveConstructor());
15528 
15529   MoveConstructor->setTrivialForCall(
15530       ClassDecl->hasAttr<TrivialABIAttr>() ||
15531       (ClassDecl->needsOverloadResolutionForMoveConstructor()
15532            ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
15533                                     TAH_ConsiderTrivialABI)
15534            : ClassDecl->hasTrivialMoveConstructorForCall()));
15535 
15536   // Note that we have declared this constructor.
15537   ++getASTContext().NumImplicitMoveConstructorsDeclared;
15538 
15539   Scope *S = getScopeForContext(ClassDecl);
15540   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
15541 
15542   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
15543     ClassDecl->setImplicitMoveConstructorIsDeleted();
15544     SetDeclDeleted(MoveConstructor, ClassLoc);
15545   }
15546 
15547   if (S)
15548     PushOnScopeChains(MoveConstructor, S, false);
15549   ClassDecl->addDecl(MoveConstructor);
15550 
15551   return MoveConstructor;
15552 }
15553 
15554 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
15555                                          CXXConstructorDecl *MoveConstructor) {
15556   assert((MoveConstructor->isDefaulted() &&
15557           MoveConstructor->isMoveConstructor() &&
15558           !MoveConstructor->doesThisDeclarationHaveABody() &&
15559           !MoveConstructor->isDeleted()) &&
15560          "DefineImplicitMoveConstructor - call it for implicit move ctor");
15561   if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
15562     return;
15563 
15564   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
15565   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
15566 
15567   SynthesizedFunctionScope Scope(*this, MoveConstructor);
15568 
15569   // The exception specification is needed because we are defining the
15570   // function.
15571   ResolveExceptionSpec(CurrentLocation,
15572                        MoveConstructor->getType()->castAs<FunctionProtoType>());
15573   MarkVTableUsed(CurrentLocation, ClassDecl);
15574 
15575   // Add a context note for diagnostics produced after this point.
15576   Scope.addContextNote(CurrentLocation);
15577 
15578   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
15579     MoveConstructor->setInvalidDecl();
15580   } else {
15581     SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
15582                              ? MoveConstructor->getEndLoc()
15583                              : MoveConstructor->getLocation();
15584     Sema::CompoundScopeRAII CompoundScope(*this);
15585     MoveConstructor->setBody(
15586         ActOnCompoundStmt(Loc, Loc, std::nullopt, /*isStmtExpr=*/false)
15587             .getAs<Stmt>());
15588     MoveConstructor->markUsed(Context);
15589   }
15590 
15591   if (ASTMutationListener *L = getASTMutationListener()) {
15592     L->CompletedImplicitDefinition(MoveConstructor);
15593   }
15594 }
15595 
15596 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
15597   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
15598 }
15599 
15600 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
15601                             SourceLocation CurrentLocation,
15602                             CXXConversionDecl *Conv) {
15603   SynthesizedFunctionScope Scope(*this, Conv);
15604   assert(!Conv->getReturnType()->isUndeducedType());
15605 
15606   QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
15607   CallingConv CC =
15608       ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
15609 
15610   CXXRecordDecl *Lambda = Conv->getParent();
15611   FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
15612   FunctionDecl *Invoker =
15613       CallOp->isStatic() ? CallOp : Lambda->getLambdaStaticInvoker(CC);
15614 
15615   if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
15616     CallOp = InstantiateFunctionDeclaration(
15617         CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
15618     if (!CallOp)
15619       return;
15620 
15621     if (CallOp != Invoker) {
15622       Invoker = InstantiateFunctionDeclaration(
15623           Invoker->getDescribedFunctionTemplate(), TemplateArgs,
15624           CurrentLocation);
15625       if (!Invoker)
15626         return;
15627     }
15628   }
15629 
15630   if (CallOp->isInvalidDecl())
15631     return;
15632 
15633   // Mark the call operator referenced (and add to pending instantiations
15634   // if necessary).
15635   // For both the conversion and static-invoker template specializations
15636   // we construct their body's in this function, so no need to add them
15637   // to the PendingInstantiations.
15638   MarkFunctionReferenced(CurrentLocation, CallOp);
15639 
15640   if (Invoker != CallOp) {
15641     // Fill in the __invoke function with a dummy implementation. IR generation
15642     // will fill in the actual details. Update its type in case it contained
15643     // an 'auto'.
15644     Invoker->markUsed(Context);
15645     Invoker->setReferenced();
15646     Invoker->setType(Conv->getReturnType()->getPointeeType());
15647     Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
15648   }
15649 
15650   // Construct the body of the conversion function { return __invoke; }.
15651   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), VK_LValue,
15652                                        Conv->getLocation());
15653   assert(FunctionRef && "Can't refer to __invoke function?");
15654   Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
15655   Conv->setBody(CompoundStmt::Create(Context, Return, FPOptionsOverride(),
15656                                      Conv->getLocation(), Conv->getLocation()));
15657   Conv->markUsed(Context);
15658   Conv->setReferenced();
15659 
15660   if (ASTMutationListener *L = getASTMutationListener()) {
15661     L->CompletedImplicitDefinition(Conv);
15662     if (Invoker != CallOp)
15663       L->CompletedImplicitDefinition(Invoker);
15664   }
15665 }
15666 
15667 void Sema::DefineImplicitLambdaToBlockPointerConversion(
15668     SourceLocation CurrentLocation, CXXConversionDecl *Conv) {
15669   assert(!Conv->getParent()->isGenericLambda());
15670 
15671   SynthesizedFunctionScope Scope(*this, Conv);
15672 
15673   // Copy-initialize the lambda object as needed to capture it.
15674   Expr *This = ActOnCXXThis(CurrentLocation).get();
15675   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
15676 
15677   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
15678                                                         Conv->getLocation(),
15679                                                         Conv, DerefThis);
15680 
15681   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
15682   // behavior.  Note that only the general conversion function does this
15683   // (since it's unusable otherwise); in the case where we inline the
15684   // block literal, it has block literal lifetime semantics.
15685   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
15686     BuildBlock = ImplicitCastExpr::Create(
15687         Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
15688         BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride());
15689 
15690   if (BuildBlock.isInvalid()) {
15691     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15692     Conv->setInvalidDecl();
15693     return;
15694   }
15695 
15696   // Create the return statement that returns the block from the conversion
15697   // function.
15698   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
15699   if (Return.isInvalid()) {
15700     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15701     Conv->setInvalidDecl();
15702     return;
15703   }
15704 
15705   // Set the body of the conversion function.
15706   Stmt *ReturnS = Return.get();
15707   Conv->setBody(CompoundStmt::Create(Context, ReturnS, FPOptionsOverride(),
15708                                      Conv->getLocation(), Conv->getLocation()));
15709   Conv->markUsed(Context);
15710 
15711   // We're done; notify the mutation listener, if any.
15712   if (ASTMutationListener *L = getASTMutationListener()) {
15713     L->CompletedImplicitDefinition(Conv);
15714   }
15715 }
15716 
15717 /// Determine whether the given list arguments contains exactly one
15718 /// "real" (non-default) argument.
15719 static bool hasOneRealArgument(MultiExprArg Args) {
15720   switch (Args.size()) {
15721   case 0:
15722     return false;
15723 
15724   default:
15725     if (!Args[1]->isDefaultArgument())
15726       return false;
15727 
15728     [[fallthrough]];
15729   case 1:
15730     return !Args[0]->isDefaultArgument();
15731   }
15732 
15733   return false;
15734 }
15735 
15736 ExprResult
15737 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15738                             NamedDecl *FoundDecl,
15739                             CXXConstructorDecl *Constructor,
15740                             MultiExprArg ExprArgs,
15741                             bool HadMultipleCandidates,
15742                             bool IsListInitialization,
15743                             bool IsStdInitListInitialization,
15744                             bool RequiresZeroInit,
15745                             unsigned ConstructKind,
15746                             SourceRange ParenRange) {
15747   bool Elidable = false;
15748 
15749   // C++0x [class.copy]p34:
15750   //   When certain criteria are met, an implementation is allowed to
15751   //   omit the copy/move construction of a class object, even if the
15752   //   copy/move constructor and/or destructor for the object have
15753   //   side effects. [...]
15754   //     - when a temporary class object that has not been bound to a
15755   //       reference (12.2) would be copied/moved to a class object
15756   //       with the same cv-unqualified type, the copy/move operation
15757   //       can be omitted by constructing the temporary object
15758   //       directly into the target of the omitted copy/move
15759   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
15760       // FIXME: Converting constructors should also be accepted.
15761       // But to fix this, the logic that digs down into a CXXConstructExpr
15762       // to find the source object needs to handle it.
15763       // Right now it assumes the source object is passed directly as the
15764       // first argument.
15765       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
15766     Expr *SubExpr = ExprArgs[0];
15767     // FIXME: Per above, this is also incorrect if we want to accept
15768     //        converting constructors, as isTemporaryObject will
15769     //        reject temporaries with different type from the
15770     //        CXXRecord itself.
15771     Elidable = SubExpr->isTemporaryObject(
15772         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
15773   }
15774 
15775   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
15776                                FoundDecl, Constructor,
15777                                Elidable, ExprArgs, HadMultipleCandidates,
15778                                IsListInitialization,
15779                                IsStdInitListInitialization, RequiresZeroInit,
15780                                ConstructKind, ParenRange);
15781 }
15782 
15783 ExprResult
15784 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15785                             NamedDecl *FoundDecl,
15786                             CXXConstructorDecl *Constructor,
15787                             bool Elidable,
15788                             MultiExprArg ExprArgs,
15789                             bool HadMultipleCandidates,
15790                             bool IsListInitialization,
15791                             bool IsStdInitListInitialization,
15792                             bool RequiresZeroInit,
15793                             unsigned ConstructKind,
15794                             SourceRange ParenRange) {
15795   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
15796     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
15797     // The only way to get here is if we did overlaod resolution to find the
15798     // shadow decl, so we don't need to worry about re-checking the trailing
15799     // requires clause.
15800     if (DiagnoseUseOfOverloadedDecl(Constructor, ConstructLoc))
15801       return ExprError();
15802   }
15803 
15804   return BuildCXXConstructExpr(
15805       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
15806       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
15807       RequiresZeroInit, ConstructKind, ParenRange);
15808 }
15809 
15810 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
15811 /// including handling of its default argument expressions.
15812 ExprResult
15813 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15814                             CXXConstructorDecl *Constructor,
15815                             bool Elidable,
15816                             MultiExprArg ExprArgs,
15817                             bool HadMultipleCandidates,
15818                             bool IsListInitialization,
15819                             bool IsStdInitListInitialization,
15820                             bool RequiresZeroInit,
15821                             unsigned ConstructKind,
15822                             SourceRange ParenRange) {
15823   assert(declaresSameEntity(
15824              Constructor->getParent(),
15825              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
15826          "given constructor for wrong type");
15827   MarkFunctionReferenced(ConstructLoc, Constructor);
15828   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
15829     return ExprError();
15830 
15831   return CheckForImmediateInvocation(
15832       CXXConstructExpr::Create(
15833           Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
15834           HadMultipleCandidates, IsListInitialization,
15835           IsStdInitListInitialization, RequiresZeroInit,
15836           static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
15837           ParenRange),
15838       Constructor);
15839 }
15840 
15841 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
15842   if (VD->isInvalidDecl()) return;
15843   // If initializing the variable failed, don't also diagnose problems with
15844   // the destructor, they're likely related.
15845   if (VD->getInit() && VD->getInit()->containsErrors())
15846     return;
15847 
15848   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
15849   if (ClassDecl->isInvalidDecl()) return;
15850   if (ClassDecl->hasIrrelevantDestructor()) return;
15851   if (ClassDecl->isDependentContext()) return;
15852 
15853   if (VD->isNoDestroy(getASTContext()))
15854     return;
15855 
15856   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
15857   // The result of `LookupDestructor` might be nullptr if the destructor is
15858   // invalid, in which case it is marked as `IneligibleOrNotSelected` and
15859   // will not be selected by `CXXRecordDecl::getDestructor()`.
15860   if (!Destructor)
15861     return;
15862   // If this is an array, we'll require the destructor during initialization, so
15863   // we can skip over this. We still want to emit exit-time destructor warnings
15864   // though.
15865   if (!VD->getType()->isArrayType()) {
15866     MarkFunctionReferenced(VD->getLocation(), Destructor);
15867     CheckDestructorAccess(VD->getLocation(), Destructor,
15868                           PDiag(diag::err_access_dtor_var)
15869                               << VD->getDeclName() << VD->getType());
15870     DiagnoseUseOfDecl(Destructor, VD->getLocation());
15871   }
15872 
15873   if (Destructor->isTrivial()) return;
15874 
15875   // If the destructor is constexpr, check whether the variable has constant
15876   // destruction now.
15877   if (Destructor->isConstexpr()) {
15878     bool HasConstantInit = false;
15879     if (VD->getInit() && !VD->getInit()->isValueDependent())
15880       HasConstantInit = VD->evaluateValue();
15881     SmallVector<PartialDiagnosticAt, 8> Notes;
15882     if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
15883         HasConstantInit) {
15884       Diag(VD->getLocation(),
15885            diag::err_constexpr_var_requires_const_destruction) << VD;
15886       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15887         Diag(Notes[I].first, Notes[I].second);
15888     }
15889   }
15890 
15891   if (!VD->hasGlobalStorage() || !VD->needsDestruction(Context))
15892     return;
15893 
15894   // Emit warning for non-trivial dtor in global scope (a real global,
15895   // class-static, function-static).
15896   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
15897 
15898   // TODO: this should be re-enabled for static locals by !CXAAtExit
15899   if (!VD->isStaticLocal())
15900     Diag(VD->getLocation(), diag::warn_global_destructor);
15901 }
15902 
15903 /// Given a constructor and the set of arguments provided for the
15904 /// constructor, convert the arguments and add any required default arguments
15905 /// to form a proper call to this constructor.
15906 ///
15907 /// \returns true if an error occurred, false otherwise.
15908 bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
15909                                    QualType DeclInitType, MultiExprArg ArgsPtr,
15910                                    SourceLocation Loc,
15911                                    SmallVectorImpl<Expr *> &ConvertedArgs,
15912                                    bool AllowExplicit,
15913                                    bool IsListInitialization) {
15914   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
15915   unsigned NumArgs = ArgsPtr.size();
15916   Expr **Args = ArgsPtr.data();
15917 
15918   const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
15919   unsigned NumParams = Proto->getNumParams();
15920 
15921   // If too few arguments are available, we'll fill in the rest with defaults.
15922   if (NumArgs < NumParams)
15923     ConvertedArgs.reserve(NumParams);
15924   else
15925     ConvertedArgs.reserve(NumArgs);
15926 
15927   VariadicCallType CallType =
15928     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
15929   SmallVector<Expr *, 8> AllArgs;
15930   bool Invalid = GatherArgumentsForCall(
15931       Loc, Constructor, Proto, 0, llvm::ArrayRef(Args, NumArgs), AllArgs,
15932       CallType, AllowExplicit, IsListInitialization);
15933   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
15934 
15935   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
15936 
15937   CheckConstructorCall(Constructor, DeclInitType,
15938                        llvm::ArrayRef(AllArgs.data(), AllArgs.size()), Proto,
15939                        Loc);
15940 
15941   return Invalid;
15942 }
15943 
15944 static inline bool
15945 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
15946                                        const FunctionDecl *FnDecl) {
15947   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
15948   if (isa<NamespaceDecl>(DC)) {
15949     return SemaRef.Diag(FnDecl->getLocation(),
15950                         diag::err_operator_new_delete_declared_in_namespace)
15951       << FnDecl->getDeclName();
15952   }
15953 
15954   if (isa<TranslationUnitDecl>(DC) &&
15955       FnDecl->getStorageClass() == SC_Static) {
15956     return SemaRef.Diag(FnDecl->getLocation(),
15957                         diag::err_operator_new_delete_declared_static)
15958       << FnDecl->getDeclName();
15959   }
15960 
15961   return false;
15962 }
15963 
15964 static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef,
15965                                              const PointerType *PtrTy) {
15966   auto &Ctx = SemaRef.Context;
15967   Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
15968   PtrQuals.removeAddressSpace();
15969   return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType(
15970       PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
15971 }
15972 
15973 static inline bool
15974 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
15975                             CanQualType ExpectedResultType,
15976                             CanQualType ExpectedFirstParamType,
15977                             unsigned DependentParamTypeDiag,
15978                             unsigned InvalidParamTypeDiag) {
15979   QualType ResultType =
15980       FnDecl->getType()->castAs<FunctionType>()->getReturnType();
15981 
15982   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15983     // The operator is valid on any address space for OpenCL.
15984     // Drop address space from actual and expected result types.
15985     if (const auto *PtrTy = ResultType->getAs<PointerType>())
15986       ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15987 
15988     if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>())
15989       ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
15990   }
15991 
15992   // Check that the result type is what we expect.
15993   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) {
15994     // Reject even if the type is dependent; an operator delete function is
15995     // required to have a non-dependent result type.
15996     return SemaRef.Diag(
15997                FnDecl->getLocation(),
15998                ResultType->isDependentType()
15999                    ? diag::err_operator_new_delete_dependent_result_type
16000                    : diag::err_operator_new_delete_invalid_result_type)
16001            << FnDecl->getDeclName() << ExpectedResultType;
16002   }
16003 
16004   // A function template must have at least 2 parameters.
16005   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
16006     return SemaRef.Diag(FnDecl->getLocation(),
16007                       diag::err_operator_new_delete_template_too_few_parameters)
16008         << FnDecl->getDeclName();
16009 
16010   // The function decl must have at least 1 parameter.
16011   if (FnDecl->getNumParams() == 0)
16012     return SemaRef.Diag(FnDecl->getLocation(),
16013                         diag::err_operator_new_delete_too_few_parameters)
16014       << FnDecl->getDeclName();
16015 
16016   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
16017   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
16018     // The operator is valid on any address space for OpenCL.
16019     // Drop address space from actual and expected first parameter types.
16020     if (const auto *PtrTy =
16021             FnDecl->getParamDecl(0)->getType()->getAs<PointerType>())
16022       FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
16023 
16024     if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>())
16025       ExpectedFirstParamType =
16026           RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
16027   }
16028 
16029   // Check that the first parameter type is what we expect.
16030   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
16031       ExpectedFirstParamType) {
16032     // The first parameter type is not allowed to be dependent. As a tentative
16033     // DR resolution, we allow a dependent parameter type if it is the right
16034     // type anyway, to allow destroying operator delete in class templates.
16035     return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType()
16036                                                    ? DependentParamTypeDiag
16037                                                    : InvalidParamTypeDiag)
16038            << FnDecl->getDeclName() << ExpectedFirstParamType;
16039   }
16040 
16041   return false;
16042 }
16043 
16044 static bool
16045 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
16046   // C++ [basic.stc.dynamic.allocation]p1:
16047   //   A program is ill-formed if an allocation function is declared in a
16048   //   namespace scope other than global scope or declared static in global
16049   //   scope.
16050   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16051     return true;
16052 
16053   CanQualType SizeTy =
16054     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
16055 
16056   // C++ [basic.stc.dynamic.allocation]p1:
16057   //  The return type shall be void*. The first parameter shall have type
16058   //  std::size_t.
16059   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
16060                                   SizeTy,
16061                                   diag::err_operator_new_dependent_param_type,
16062                                   diag::err_operator_new_param_type))
16063     return true;
16064 
16065   // C++ [basic.stc.dynamic.allocation]p1:
16066   //  The first parameter shall not have an associated default argument.
16067   if (FnDecl->getParamDecl(0)->hasDefaultArg())
16068     return SemaRef.Diag(FnDecl->getLocation(),
16069                         diag::err_operator_new_default_arg)
16070       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
16071 
16072   return false;
16073 }
16074 
16075 static bool
16076 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
16077   // C++ [basic.stc.dynamic.deallocation]p1:
16078   //   A program is ill-formed if deallocation functions are declared in a
16079   //   namespace scope other than global scope or declared static in global
16080   //   scope.
16081   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16082     return true;
16083 
16084   auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
16085 
16086   // C++ P0722:
16087   //   Within a class C, the first parameter of a destroying operator delete
16088   //   shall be of type C *. The first parameter of any other deallocation
16089   //   function shall be of type void *.
16090   CanQualType ExpectedFirstParamType =
16091       MD && MD->isDestroyingOperatorDelete()
16092           ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
16093                 SemaRef.Context.getRecordType(MD->getParent())))
16094           : SemaRef.Context.VoidPtrTy;
16095 
16096   // C++ [basic.stc.dynamic.deallocation]p2:
16097   //   Each deallocation function shall return void
16098   if (CheckOperatorNewDeleteTypes(
16099           SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
16100           diag::err_operator_delete_dependent_param_type,
16101           diag::err_operator_delete_param_type))
16102     return true;
16103 
16104   // C++ P0722:
16105   //   A destroying operator delete shall be a usual deallocation function.
16106   if (MD && !MD->getParent()->isDependentContext() &&
16107       MD->isDestroyingOperatorDelete() &&
16108       !SemaRef.isUsualDeallocationFunction(MD)) {
16109     SemaRef.Diag(MD->getLocation(),
16110                  diag::err_destroying_operator_delete_not_usual);
16111     return true;
16112   }
16113 
16114   return false;
16115 }
16116 
16117 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
16118 /// of this overloaded operator is well-formed. If so, returns false;
16119 /// otherwise, emits appropriate diagnostics and returns true.
16120 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
16121   assert(FnDecl && FnDecl->isOverloadedOperator() &&
16122          "Expected an overloaded operator declaration");
16123 
16124   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
16125 
16126   // C++ [over.oper]p5:
16127   //   The allocation and deallocation functions, operator new,
16128   //   operator new[], operator delete and operator delete[], are
16129   //   described completely in 3.7.3. The attributes and restrictions
16130   //   found in the rest of this subclause do not apply to them unless
16131   //   explicitly stated in 3.7.3.
16132   if (Op == OO_Delete || Op == OO_Array_Delete)
16133     return CheckOperatorDeleteDeclaration(*this, FnDecl);
16134 
16135   if (Op == OO_New || Op == OO_Array_New)
16136     return CheckOperatorNewDeclaration(*this, FnDecl);
16137 
16138   // C++ [over.oper]p7:
16139   //   An operator function shall either be a member function or
16140   //   be a non-member function and have at least one parameter
16141   //   whose type is a class, a reference to a class, an enumeration,
16142   //   or a reference to an enumeration.
16143   // Note: Before C++23, a member function could not be static. The only member
16144   //       function allowed to be static is the call operator function.
16145   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
16146     if (MethodDecl->isStatic()) {
16147       if (Op == OO_Call || Op == OO_Subscript)
16148         Diag(FnDecl->getLocation(),
16149              (LangOpts.CPlusPlus23
16150                   ? diag::warn_cxx20_compat_operator_overload_static
16151                   : diag::ext_operator_overload_static))
16152             << FnDecl;
16153       else
16154         return Diag(FnDecl->getLocation(), diag::err_operator_overload_static)
16155                << FnDecl;
16156     }
16157   } else {
16158     bool ClassOrEnumParam = false;
16159     for (auto *Param : FnDecl->parameters()) {
16160       QualType ParamType = Param->getType().getNonReferenceType();
16161       if (ParamType->isDependentType() || ParamType->isRecordType() ||
16162           ParamType->isEnumeralType()) {
16163         ClassOrEnumParam = true;
16164         break;
16165       }
16166     }
16167 
16168     if (!ClassOrEnumParam)
16169       return Diag(FnDecl->getLocation(),
16170                   diag::err_operator_overload_needs_class_or_enum)
16171         << FnDecl->getDeclName();
16172   }
16173 
16174   // C++ [over.oper]p8:
16175   //   An operator function cannot have default arguments (8.3.6),
16176   //   except where explicitly stated below.
16177   //
16178   // Only the function-call operator (C++ [over.call]p1) and the subscript
16179   // operator (CWG2507) allow default arguments.
16180   if (Op != OO_Call) {
16181     ParmVarDecl *FirstDefaultedParam = nullptr;
16182     for (auto *Param : FnDecl->parameters()) {
16183       if (Param->hasDefaultArg()) {
16184         FirstDefaultedParam = Param;
16185         break;
16186       }
16187     }
16188     if (FirstDefaultedParam) {
16189       if (Op == OO_Subscript) {
16190         Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
16191                                         ? diag::ext_subscript_overload
16192                                         : diag::error_subscript_overload)
16193             << FnDecl->getDeclName() << 1
16194             << FirstDefaultedParam->getDefaultArgRange();
16195       } else {
16196         return Diag(FirstDefaultedParam->getLocation(),
16197                     diag::err_operator_overload_default_arg)
16198                << FnDecl->getDeclName()
16199                << FirstDefaultedParam->getDefaultArgRange();
16200       }
16201     }
16202   }
16203 
16204   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
16205     { false, false, false }
16206 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
16207     , { Unary, Binary, MemberOnly }
16208 #include "clang/Basic/OperatorKinds.def"
16209   };
16210 
16211   bool CanBeUnaryOperator = OperatorUses[Op][0];
16212   bool CanBeBinaryOperator = OperatorUses[Op][1];
16213   bool MustBeMemberOperator = OperatorUses[Op][2];
16214 
16215   // C++ [over.oper]p8:
16216   //   [...] Operator functions cannot have more or fewer parameters
16217   //   than the number required for the corresponding operator, as
16218   //   described in the rest of this subclause.
16219   unsigned NumParams = FnDecl->getNumParams()
16220                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
16221   if (Op != OO_Call && Op != OO_Subscript &&
16222       ((NumParams == 1 && !CanBeUnaryOperator) ||
16223        (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||
16224        (NumParams > 2))) {
16225     // We have the wrong number of parameters.
16226     unsigned ErrorKind;
16227     if (CanBeUnaryOperator && CanBeBinaryOperator) {
16228       ErrorKind = 2;  // 2 -> unary or binary.
16229     } else if (CanBeUnaryOperator) {
16230       ErrorKind = 0;  // 0 -> unary
16231     } else {
16232       assert(CanBeBinaryOperator &&
16233              "All non-call overloaded operators are unary or binary!");
16234       ErrorKind = 1;  // 1 -> binary
16235     }
16236     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
16237       << FnDecl->getDeclName() << NumParams << ErrorKind;
16238   }
16239 
16240   if (Op == OO_Subscript && NumParams != 2) {
16241     Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
16242                                     ? diag::ext_subscript_overload
16243                                     : diag::error_subscript_overload)
16244         << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);
16245   }
16246 
16247   // Overloaded operators other than operator() and operator[] cannot be
16248   // variadic.
16249   if (Op != OO_Call &&
16250       FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
16251     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
16252            << FnDecl->getDeclName();
16253   }
16254 
16255   // Some operators must be member functions.
16256   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
16257     return Diag(FnDecl->getLocation(),
16258                 diag::err_operator_overload_must_be_member)
16259       << FnDecl->getDeclName();
16260   }
16261 
16262   // C++ [over.inc]p1:
16263   //   The user-defined function called operator++ implements the
16264   //   prefix and postfix ++ operator. If this function is a member
16265   //   function with no parameters, or a non-member function with one
16266   //   parameter of class or enumeration type, it defines the prefix
16267   //   increment operator ++ for objects of that type. If the function
16268   //   is a member function with one parameter (which shall be of type
16269   //   int) or a non-member function with two parameters (the second
16270   //   of which shall be of type int), it defines the postfix
16271   //   increment operator ++ for objects of that type.
16272   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
16273     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
16274     QualType ParamType = LastParam->getType();
16275 
16276     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
16277         !ParamType->isDependentType())
16278       return Diag(LastParam->getLocation(),
16279                   diag::err_operator_overload_post_incdec_must_be_int)
16280         << LastParam->getType() << (Op == OO_MinusMinus);
16281   }
16282 
16283   return false;
16284 }
16285 
16286 static bool
16287 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
16288                                           FunctionTemplateDecl *TpDecl) {
16289   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
16290 
16291   // Must have one or two template parameters.
16292   if (TemplateParams->size() == 1) {
16293     NonTypeTemplateParmDecl *PmDecl =
16294         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
16295 
16296     // The template parameter must be a char parameter pack.
16297     if (PmDecl && PmDecl->isTemplateParameterPack() &&
16298         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
16299       return false;
16300 
16301     // C++20 [over.literal]p5:
16302     //   A string literal operator template is a literal operator template
16303     //   whose template-parameter-list comprises a single non-type
16304     //   template-parameter of class type.
16305     //
16306     // As a DR resolution, we also allow placeholders for deduced class
16307     // template specializations.
16308     if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
16309         !PmDecl->isTemplateParameterPack() &&
16310         (PmDecl->getType()->isRecordType() ||
16311          PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
16312       return false;
16313   } else if (TemplateParams->size() == 2) {
16314     TemplateTypeParmDecl *PmType =
16315         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
16316     NonTypeTemplateParmDecl *PmArgs =
16317         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
16318 
16319     // The second template parameter must be a parameter pack with the
16320     // first template parameter as its type.
16321     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
16322         PmArgs->isTemplateParameterPack()) {
16323       const TemplateTypeParmType *TArgs =
16324           PmArgs->getType()->getAs<TemplateTypeParmType>();
16325       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
16326           TArgs->getIndex() == PmType->getIndex()) {
16327         if (!SemaRef.inTemplateInstantiation())
16328           SemaRef.Diag(TpDecl->getLocation(),
16329                        diag::ext_string_literal_operator_template);
16330         return false;
16331       }
16332     }
16333   }
16334 
16335   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
16336                diag::err_literal_operator_template)
16337       << TpDecl->getTemplateParameters()->getSourceRange();
16338   return true;
16339 }
16340 
16341 /// CheckLiteralOperatorDeclaration - Check whether the declaration
16342 /// of this literal operator function is well-formed. If so, returns
16343 /// false; otherwise, emits appropriate diagnostics and returns true.
16344 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
16345   if (isa<CXXMethodDecl>(FnDecl)) {
16346     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
16347       << FnDecl->getDeclName();
16348     return true;
16349   }
16350 
16351   if (FnDecl->isExternC()) {
16352     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
16353     if (const LinkageSpecDecl *LSD =
16354             FnDecl->getDeclContext()->getExternCContext())
16355       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
16356     return true;
16357   }
16358 
16359   // This might be the definition of a literal operator template.
16360   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
16361 
16362   // This might be a specialization of a literal operator template.
16363   if (!TpDecl)
16364     TpDecl = FnDecl->getPrimaryTemplate();
16365 
16366   // template <char...> type operator "" name() and
16367   // template <class T, T...> type operator "" name() are the only valid
16368   // template signatures, and the only valid signatures with no parameters.
16369   //
16370   // C++20 also allows template <SomeClass T> type operator "" name().
16371   if (TpDecl) {
16372     if (FnDecl->param_size() != 0) {
16373       Diag(FnDecl->getLocation(),
16374            diag::err_literal_operator_template_with_params);
16375       return true;
16376     }
16377 
16378     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
16379       return true;
16380 
16381   } else if (FnDecl->param_size() == 1) {
16382     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
16383 
16384     QualType ParamType = Param->getType().getUnqualifiedType();
16385 
16386     // Only unsigned long long int, long double, any character type, and const
16387     // char * are allowed as the only parameters.
16388     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
16389         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
16390         Context.hasSameType(ParamType, Context.CharTy) ||
16391         Context.hasSameType(ParamType, Context.WideCharTy) ||
16392         Context.hasSameType(ParamType, Context.Char8Ty) ||
16393         Context.hasSameType(ParamType, Context.Char16Ty) ||
16394         Context.hasSameType(ParamType, Context.Char32Ty)) {
16395     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
16396       QualType InnerType = Ptr->getPointeeType();
16397 
16398       // Pointer parameter must be a const char *.
16399       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
16400                                 Context.CharTy) &&
16401             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
16402         Diag(Param->getSourceRange().getBegin(),
16403              diag::err_literal_operator_param)
16404             << ParamType << "'const char *'" << Param->getSourceRange();
16405         return true;
16406       }
16407 
16408     } else if (ParamType->isRealFloatingType()) {
16409       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16410           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
16411       return true;
16412 
16413     } else if (ParamType->isIntegerType()) {
16414       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16415           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
16416       return true;
16417 
16418     } else {
16419       Diag(Param->getSourceRange().getBegin(),
16420            diag::err_literal_operator_invalid_param)
16421           << ParamType << Param->getSourceRange();
16422       return true;
16423     }
16424 
16425   } else if (FnDecl->param_size() == 2) {
16426     FunctionDecl::param_iterator Param = FnDecl->param_begin();
16427 
16428     // First, verify that the first parameter is correct.
16429 
16430     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
16431 
16432     // Two parameter function must have a pointer to const as a
16433     // first parameter; let's strip those qualifiers.
16434     const PointerType *PT = FirstParamType->getAs<PointerType>();
16435 
16436     if (!PT) {
16437       Diag((*Param)->getSourceRange().getBegin(),
16438            diag::err_literal_operator_param)
16439           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16440       return true;
16441     }
16442 
16443     QualType PointeeType = PT->getPointeeType();
16444     // First parameter must be const
16445     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
16446       Diag((*Param)->getSourceRange().getBegin(),
16447            diag::err_literal_operator_param)
16448           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16449       return true;
16450     }
16451 
16452     QualType InnerType = PointeeType.getUnqualifiedType();
16453     // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
16454     // const char32_t* are allowed as the first parameter to a two-parameter
16455     // function
16456     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
16457           Context.hasSameType(InnerType, Context.WideCharTy) ||
16458           Context.hasSameType(InnerType, Context.Char8Ty) ||
16459           Context.hasSameType(InnerType, Context.Char16Ty) ||
16460           Context.hasSameType(InnerType, Context.Char32Ty))) {
16461       Diag((*Param)->getSourceRange().getBegin(),
16462            diag::err_literal_operator_param)
16463           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16464       return true;
16465     }
16466 
16467     // Move on to the second and final parameter.
16468     ++Param;
16469 
16470     // The second parameter must be a std::size_t.
16471     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
16472     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
16473       Diag((*Param)->getSourceRange().getBegin(),
16474            diag::err_literal_operator_param)
16475           << SecondParamType << Context.getSizeType()
16476           << (*Param)->getSourceRange();
16477       return true;
16478     }
16479   } else {
16480     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
16481     return true;
16482   }
16483 
16484   // Parameters are good.
16485 
16486   // A parameter-declaration-clause containing a default argument is not
16487   // equivalent to any of the permitted forms.
16488   for (auto *Param : FnDecl->parameters()) {
16489     if (Param->hasDefaultArg()) {
16490       Diag(Param->getDefaultArgRange().getBegin(),
16491            diag::err_literal_operator_default_argument)
16492         << Param->getDefaultArgRange();
16493       break;
16494     }
16495   }
16496 
16497   const IdentifierInfo *II = FnDecl->getDeclName().getCXXLiteralIdentifier();
16498   ReservedLiteralSuffixIdStatus Status = II->isReservedLiteralSuffixId();
16499   if (Status != ReservedLiteralSuffixIdStatus::NotReserved &&
16500       !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
16501     // C++23 [usrlit.suffix]p1:
16502     //   Literal suffix identifiers that do not start with an underscore are
16503     //   reserved for future standardization. Literal suffix identifiers that
16504     //   contain a double underscore __ are reserved for use by C++
16505     //   implementations.
16506     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
16507         << static_cast<int>(Status)
16508         << StringLiteralParser::isValidUDSuffix(getLangOpts(), II->getName());
16509   }
16510 
16511   return false;
16512 }
16513 
16514 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
16515 /// linkage specification, including the language and (if present)
16516 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
16517 /// language string literal. LBraceLoc, if valid, provides the location of
16518 /// the '{' brace. Otherwise, this linkage specification does not
16519 /// have any braces.
16520 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
16521                                            Expr *LangStr,
16522                                            SourceLocation LBraceLoc) {
16523   StringLiteral *Lit = cast<StringLiteral>(LangStr);
16524   assert(Lit->isUnevaluated() && "Unexpected string literal kind");
16525 
16526   StringRef Lang = Lit->getString();
16527   LinkageSpecDecl::LanguageIDs Language;
16528   if (Lang == "C")
16529     Language = LinkageSpecDecl::lang_c;
16530   else if (Lang == "C++")
16531     Language = LinkageSpecDecl::lang_cxx;
16532   else {
16533     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
16534       << LangStr->getSourceRange();
16535     return nullptr;
16536   }
16537 
16538   // FIXME: Add all the various semantics of linkage specifications
16539 
16540   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
16541                                                LangStr->getExprLoc(), Language,
16542                                                LBraceLoc.isValid());
16543 
16544   /// C++ [module.unit]p7.2.3
16545   /// - Otherwise, if the declaration
16546   ///   - ...
16547   ///   - ...
16548   ///   - appears within a linkage-specification,
16549   ///   it is attached to the global module.
16550   ///
16551   /// If the declaration is already in global module fragment, we don't
16552   /// need to attach it again.
16553   if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
16554     Module *GlobalModule = PushImplicitGlobalModuleFragment(
16555         ExternLoc, /*IsExported=*/D->isInExportDeclContext());
16556     D->setLocalOwningModule(GlobalModule);
16557   }
16558 
16559   CurContext->addDecl(D);
16560   PushDeclContext(S, D);
16561   return D;
16562 }
16563 
16564 /// ActOnFinishLinkageSpecification - Complete the definition of
16565 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
16566 /// valid, it's the position of the closing '}' brace in a linkage
16567 /// specification that uses braces.
16568 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
16569                                             Decl *LinkageSpec,
16570                                             SourceLocation RBraceLoc) {
16571   if (RBraceLoc.isValid()) {
16572     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
16573     LSDecl->setRBraceLoc(RBraceLoc);
16574   }
16575 
16576   // If the current module doesn't has Parent, it implies that the
16577   // LinkageSpec isn't in the module created by itself. So we don't
16578   // need to pop it.
16579   if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
16580       getCurrentModule()->isImplicitGlobalModule() &&
16581       getCurrentModule()->Parent)
16582     PopImplicitGlobalModuleFragment();
16583 
16584   PopDeclContext();
16585   return LinkageSpec;
16586 }
16587 
16588 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
16589                                   const ParsedAttributesView &AttrList,
16590                                   SourceLocation SemiLoc) {
16591   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
16592   // Attribute declarations appertain to empty declaration so we handle
16593   // them here.
16594   ProcessDeclAttributeList(S, ED, AttrList);
16595 
16596   CurContext->addDecl(ED);
16597   return ED;
16598 }
16599 
16600 /// Perform semantic analysis for the variable declaration that
16601 /// occurs within a C++ catch clause, returning the newly-created
16602 /// variable.
16603 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
16604                                          TypeSourceInfo *TInfo,
16605                                          SourceLocation StartLoc,
16606                                          SourceLocation Loc,
16607                                          IdentifierInfo *Name) {
16608   bool Invalid = false;
16609   QualType ExDeclType = TInfo->getType();
16610 
16611   // Arrays and functions decay.
16612   if (ExDeclType->isArrayType())
16613     ExDeclType = Context.getArrayDecayedType(ExDeclType);
16614   else if (ExDeclType->isFunctionType())
16615     ExDeclType = Context.getPointerType(ExDeclType);
16616 
16617   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
16618   // The exception-declaration shall not denote a pointer or reference to an
16619   // incomplete type, other than [cv] void*.
16620   // N2844 forbids rvalue references.
16621   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
16622     Diag(Loc, diag::err_catch_rvalue_ref);
16623     Invalid = true;
16624   }
16625 
16626   if (ExDeclType->isVariablyModifiedType()) {
16627     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
16628     Invalid = true;
16629   }
16630 
16631   QualType BaseType = ExDeclType;
16632   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
16633   unsigned DK = diag::err_catch_incomplete;
16634   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
16635     BaseType = Ptr->getPointeeType();
16636     Mode = 1;
16637     DK = diag::err_catch_incomplete_ptr;
16638   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
16639     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
16640     BaseType = Ref->getPointeeType();
16641     Mode = 2;
16642     DK = diag::err_catch_incomplete_ref;
16643   }
16644   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
16645       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
16646     Invalid = true;
16647 
16648   if (!Invalid && BaseType.isWebAssemblyReferenceType()) {
16649     Diag(Loc, diag::err_wasm_reftype_tc) << 1;
16650     Invalid = true;
16651   }
16652 
16653   if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
16654     Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
16655     Invalid = true;
16656   }
16657 
16658   if (!Invalid && !ExDeclType->isDependentType() &&
16659       RequireNonAbstractType(Loc, ExDeclType,
16660                              diag::err_abstract_type_in_decl,
16661                              AbstractVariableType))
16662     Invalid = true;
16663 
16664   // Only the non-fragile NeXT runtime currently supports C++ catches
16665   // of ObjC types, and no runtime supports catching ObjC types by value.
16666   if (!Invalid && getLangOpts().ObjC) {
16667     QualType T = ExDeclType;
16668     if (const ReferenceType *RT = T->getAs<ReferenceType>())
16669       T = RT->getPointeeType();
16670 
16671     if (T->isObjCObjectType()) {
16672       Diag(Loc, diag::err_objc_object_catch);
16673       Invalid = true;
16674     } else if (T->isObjCObjectPointerType()) {
16675       // FIXME: should this be a test for macosx-fragile specifically?
16676       if (getLangOpts().ObjCRuntime.isFragile())
16677         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
16678     }
16679   }
16680 
16681   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
16682                                     ExDeclType, TInfo, SC_None);
16683   ExDecl->setExceptionVariable(true);
16684 
16685   // In ARC, infer 'retaining' for variables of retainable type.
16686   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
16687     Invalid = true;
16688 
16689   if (!Invalid && !ExDeclType->isDependentType()) {
16690     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
16691       // Insulate this from anything else we might currently be parsing.
16692       EnterExpressionEvaluationContext scope(
16693           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
16694 
16695       // C++ [except.handle]p16:
16696       //   The object declared in an exception-declaration or, if the
16697       //   exception-declaration does not specify a name, a temporary (12.2) is
16698       //   copy-initialized (8.5) from the exception object. [...]
16699       //   The object is destroyed when the handler exits, after the destruction
16700       //   of any automatic objects initialized within the handler.
16701       //
16702       // We just pretend to initialize the object with itself, then make sure
16703       // it can be destroyed later.
16704       QualType initType = Context.getExceptionObjectType(ExDeclType);
16705 
16706       InitializedEntity entity =
16707         InitializedEntity::InitializeVariable(ExDecl);
16708       InitializationKind initKind =
16709         InitializationKind::CreateCopy(Loc, SourceLocation());
16710 
16711       Expr *opaqueValue =
16712         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
16713       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
16714       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
16715       if (result.isInvalid())
16716         Invalid = true;
16717       else {
16718         // If the constructor used was non-trivial, set this as the
16719         // "initializer".
16720         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
16721         if (!construct->getConstructor()->isTrivial()) {
16722           Expr *init = MaybeCreateExprWithCleanups(construct);
16723           ExDecl->setInit(init);
16724         }
16725 
16726         // And make sure it's destructable.
16727         FinalizeVarWithDestructor(ExDecl, recordType);
16728       }
16729     }
16730   }
16731 
16732   if (Invalid)
16733     ExDecl->setInvalidDecl();
16734 
16735   return ExDecl;
16736 }
16737 
16738 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
16739 /// handler.
16740 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
16741   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16742   bool Invalid = D.isInvalidType();
16743 
16744   // Check for unexpanded parameter packs.
16745   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16746                                       UPPC_ExceptionType)) {
16747     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
16748                                              D.getIdentifierLoc());
16749     Invalid = true;
16750   }
16751 
16752   IdentifierInfo *II = D.getIdentifier();
16753   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
16754                                              LookupOrdinaryName,
16755                                              ForVisibleRedeclaration)) {
16756     // The scope should be freshly made just for us. There is just no way
16757     // it contains any previous declaration, except for function parameters in
16758     // a function-try-block's catch statement.
16759     assert(!S->isDeclScope(PrevDecl));
16760     if (isDeclInScope(PrevDecl, CurContext, S)) {
16761       Diag(D.getIdentifierLoc(), diag::err_redefinition)
16762         << D.getIdentifier();
16763       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
16764       Invalid = true;
16765     } else if (PrevDecl->isTemplateParameter())
16766       // Maybe we will complain about the shadowed template parameter.
16767       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16768   }
16769 
16770   if (D.getCXXScopeSpec().isSet() && !Invalid) {
16771     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
16772       << D.getCXXScopeSpec().getRange();
16773     Invalid = true;
16774   }
16775 
16776   VarDecl *ExDecl = BuildExceptionDeclaration(
16777       S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
16778   if (Invalid)
16779     ExDecl->setInvalidDecl();
16780 
16781   // Add the exception declaration into this scope.
16782   if (II)
16783     PushOnScopeChains(ExDecl, S);
16784   else
16785     CurContext->addDecl(ExDecl);
16786 
16787   ProcessDeclAttributes(S, ExDecl, D);
16788   return ExDecl;
16789 }
16790 
16791 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
16792                                          Expr *AssertExpr,
16793                                          Expr *AssertMessageExpr,
16794                                          SourceLocation RParenLoc) {
16795   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
16796     return nullptr;
16797 
16798   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
16799                                       AssertMessageExpr, RParenLoc, false);
16800 }
16801 
16802 /// Convert \V to a string we can present to the user in a diagnostic
16803 /// \T is the type of the expression that has been evaluated into \V
16804 static bool ConvertAPValueToString(const APValue &V, QualType T,
16805                                    SmallVectorImpl<char> &Str) {
16806   if (!V.hasValue())
16807     return false;
16808 
16809   switch (V.getKind()) {
16810   case APValue::ValueKind::Int:
16811     if (T->isBooleanType()) {
16812       // Bools are reduced to ints during evaluation, but for
16813       // diagnostic purposes we want to print them as
16814       // true or false.
16815       int64_t BoolValue = V.getInt().getExtValue();
16816       assert((BoolValue == 0 || BoolValue == 1) &&
16817              "Bool type, but value is not 0 or 1");
16818       llvm::raw_svector_ostream OS(Str);
16819       OS << (BoolValue ? "true" : "false");
16820     } else if (T->isCharType()) {
16821       // Same is true for chars.
16822       Str.push_back('\'');
16823       Str.push_back(V.getInt().getExtValue());
16824       Str.push_back('\'');
16825     } else
16826       V.getInt().toString(Str);
16827 
16828     break;
16829 
16830   case APValue::ValueKind::Float:
16831     V.getFloat().toString(Str);
16832     break;
16833 
16834   case APValue::ValueKind::LValue:
16835     if (V.isNullPointer()) {
16836       llvm::raw_svector_ostream OS(Str);
16837       OS << "nullptr";
16838     } else
16839       return false;
16840     break;
16841 
16842   case APValue::ValueKind::ComplexFloat: {
16843     llvm::raw_svector_ostream OS(Str);
16844     OS << '(';
16845     V.getComplexFloatReal().toString(Str);
16846     OS << " + ";
16847     V.getComplexFloatImag().toString(Str);
16848     OS << "i)";
16849   } break;
16850 
16851   case APValue::ValueKind::ComplexInt: {
16852     llvm::raw_svector_ostream OS(Str);
16853     OS << '(';
16854     V.getComplexIntReal().toString(Str);
16855     OS << " + ";
16856     V.getComplexIntImag().toString(Str);
16857     OS << "i)";
16858   } break;
16859 
16860   default:
16861     return false;
16862   }
16863 
16864   return true;
16865 }
16866 
16867 /// Some Expression types are not useful to print notes about,
16868 /// e.g. literals and values that have already been expanded
16869 /// before such as int-valued template parameters.
16870 static bool UsefulToPrintExpr(const Expr *E) {
16871   E = E->IgnoreParenImpCasts();
16872   // Literals are pretty easy for humans to understand.
16873   if (isa<IntegerLiteral, FloatingLiteral, CharacterLiteral, CXXBoolLiteralExpr,
16874           CXXNullPtrLiteralExpr, FixedPointLiteral, ImaginaryLiteral>(E))
16875     return false;
16876 
16877   // These have been substituted from template parameters
16878   // and appear as literals in the static assert error.
16879   if (isa<SubstNonTypeTemplateParmExpr>(E))
16880     return false;
16881 
16882   // -5 is also simple to understand.
16883   if (const auto *UnaryOp = dyn_cast<UnaryOperator>(E))
16884     return UsefulToPrintExpr(UnaryOp->getSubExpr());
16885 
16886   // Ignore nested binary operators. This could be a FIXME for improvements
16887   // to the diagnostics in the future.
16888   if (isa<BinaryOperator>(E))
16889     return false;
16890 
16891   return true;
16892 }
16893 
16894 /// Try to print more useful information about a failed static_assert
16895 /// with expression \E
16896 void Sema::DiagnoseStaticAssertDetails(const Expr *E) {
16897   if (const auto *Op = dyn_cast<BinaryOperator>(E);
16898       Op && Op->getOpcode() != BO_LOr) {
16899     const Expr *LHS = Op->getLHS()->IgnoreParenImpCasts();
16900     const Expr *RHS = Op->getRHS()->IgnoreParenImpCasts();
16901 
16902     // Ignore comparisons of boolean expressions with a boolean literal.
16903     if ((isa<CXXBoolLiteralExpr>(LHS) && RHS->getType()->isBooleanType()) ||
16904         (isa<CXXBoolLiteralExpr>(RHS) && LHS->getType()->isBooleanType()))
16905       return;
16906 
16907     // Don't print obvious expressions.
16908     if (!UsefulToPrintExpr(LHS) && !UsefulToPrintExpr(RHS))
16909       return;
16910 
16911     struct {
16912       const clang::Expr *Cond;
16913       Expr::EvalResult Result;
16914       SmallString<12> ValueString;
16915       bool Print;
16916     } DiagSide[2] = {{LHS, Expr::EvalResult(), {}, false},
16917                      {RHS, Expr::EvalResult(), {}, false}};
16918     for (unsigned I = 0; I < 2; I++) {
16919       const Expr *Side = DiagSide[I].Cond;
16920 
16921       Side->EvaluateAsRValue(DiagSide[I].Result, Context, true);
16922 
16923       DiagSide[I].Print = ConvertAPValueToString(
16924           DiagSide[I].Result.Val, Side->getType(), DiagSide[I].ValueString);
16925     }
16926     if (DiagSide[0].Print && DiagSide[1].Print) {
16927       Diag(Op->getExprLoc(), diag::note_expr_evaluates_to)
16928           << DiagSide[0].ValueString << Op->getOpcodeStr()
16929           << DiagSide[1].ValueString << Op->getSourceRange();
16930     }
16931   }
16932 }
16933 
16934 bool Sema::EvaluateStaticAssertMessageAsString(Expr *Message,
16935                                                std::string &Result,
16936                                                ASTContext &Ctx,
16937                                                bool ErrorOnInvalidMessage) {
16938   assert(Message);
16939   assert(!Message->isTypeDependent() && !Message->isValueDependent() &&
16940          "can't evaluate a dependant static assert message");
16941 
16942   if (const auto *SL = dyn_cast<StringLiteral>(Message)) {
16943     assert(SL->isUnevaluated() && "expected an unevaluated string");
16944     Result.assign(SL->getString().begin(), SL->getString().end());
16945     return true;
16946   }
16947 
16948   SourceLocation Loc = Message->getBeginLoc();
16949   QualType T = Message->getType().getNonReferenceType();
16950   auto *RD = T->getAsCXXRecordDecl();
16951   if (!RD) {
16952     Diag(Loc, diag::err_static_assert_invalid_message);
16953     return false;
16954   }
16955 
16956   auto FindMember = [&](StringRef Member, bool &Empty,
16957                         bool Diag = false) -> std::optional<LookupResult> {
16958     QualType ObjectType = Message->getType();
16959     Expr::Classification ObjectClassification =
16960         Message->Classify(getASTContext());
16961 
16962     DeclarationName DN = PP.getIdentifierInfo(Member);
16963     LookupResult MemberLookup(*this, DN, Loc, Sema::LookupMemberName);
16964     LookupQualifiedName(MemberLookup, RD);
16965     Empty = MemberLookup.empty();
16966     OverloadCandidateSet Candidates(MemberLookup.getNameLoc(),
16967                                     OverloadCandidateSet::CSK_Normal);
16968     for (NamedDecl *D : MemberLookup) {
16969       AddMethodCandidate(DeclAccessPair::make(D, D->getAccess()), ObjectType,
16970                          ObjectClassification, /*Args=*/{}, Candidates);
16971     }
16972     OverloadCandidateSet::iterator Best;
16973     switch (Candidates.BestViableFunction(*this, Loc, Best)) {
16974     case OR_Success:
16975       return std::move(MemberLookup);
16976     default:
16977       if (Diag)
16978         Candidates.NoteCandidates(
16979             PartialDiagnosticAt(
16980                 Loc, PDiag(diag::err_static_assert_invalid_mem_fn_ret_ty)
16981                          << (Member == "data")),
16982             *this, OCD_AllCandidates, /*Args=*/{});
16983     }
16984     return std::nullopt;
16985   };
16986 
16987   bool SizeNotFound, DataNotFound;
16988   std::optional<LookupResult> SizeMember = FindMember("size", SizeNotFound);
16989   std::optional<LookupResult> DataMember = FindMember("data", DataNotFound);
16990   if (SizeNotFound || DataNotFound) {
16991     Diag(Loc, diag::err_static_assert_missing_member_function)
16992         << ((SizeNotFound && DataNotFound) ? 2
16993             : SizeNotFound                 ? 0
16994                                            : 1);
16995     return false;
16996   }
16997 
16998   if (!SizeMember || !DataMember) {
16999     if (!SizeMember)
17000       FindMember("size", SizeNotFound, /*Diag=*/true);
17001     if (!DataMember)
17002       FindMember("data", DataNotFound, /*Diag=*/true);
17003     return false;
17004   }
17005 
17006   auto BuildExpr = [&](LookupResult &LR) {
17007     ExprResult Res = BuildMemberReferenceExpr(
17008         Message, Message->getType(), Message->getBeginLoc(), false,
17009         CXXScopeSpec(), SourceLocation(), nullptr, LR, nullptr, nullptr);
17010     if (Res.isInvalid())
17011       return ExprError();
17012     Res = BuildCallExpr(nullptr, Res.get(), Loc, std::nullopt, Loc, nullptr,
17013                         false, true);
17014     if (Res.isInvalid())
17015       return ExprError();
17016     if (Res.get()->isTypeDependent() || Res.get()->isValueDependent())
17017       return ExprError();
17018     return TemporaryMaterializationConversion(Res.get());
17019   };
17020 
17021   ExprResult SizeE = BuildExpr(*SizeMember);
17022   ExprResult DataE = BuildExpr(*DataMember);
17023 
17024   QualType SizeT = Context.getSizeType();
17025   QualType ConstCharPtr =
17026       Context.getPointerType(Context.getConstType(Context.CharTy));
17027 
17028   ExprResult EvaluatedSize =
17029       SizeE.isInvalid() ? ExprError()
17030                         : BuildConvertedConstantExpression(
17031                               SizeE.get(), SizeT, CCEK_StaticAssertMessageSize);
17032   if (EvaluatedSize.isInvalid()) {
17033     Diag(Loc, diag::err_static_assert_invalid_mem_fn_ret_ty) << /*size*/ 0;
17034     return false;
17035   }
17036 
17037   ExprResult EvaluatedData =
17038       DataE.isInvalid()
17039           ? ExprError()
17040           : BuildConvertedConstantExpression(DataE.get(), ConstCharPtr,
17041                                              CCEK_StaticAssertMessageData);
17042   if (EvaluatedData.isInvalid()) {
17043     Diag(Loc, diag::err_static_assert_invalid_mem_fn_ret_ty) << /*data*/ 1;
17044     return false;
17045   }
17046 
17047   if (!ErrorOnInvalidMessage &&
17048       Diags.isIgnored(diag::warn_static_assert_message_constexpr, Loc))
17049     return true;
17050 
17051   Expr::EvalResult Status;
17052   SmallVector<PartialDiagnosticAt, 8> Notes;
17053   Status.Diag = &Notes;
17054   if (!Message->EvaluateCharRangeAsString(Result, EvaluatedSize.get(),
17055                                           EvaluatedData.get(), Ctx, Status) ||
17056       !Notes.empty()) {
17057     Diag(Message->getBeginLoc(),
17058          ErrorOnInvalidMessage ? diag::err_static_assert_message_constexpr
17059                                : diag::warn_static_assert_message_constexpr);
17060     for (const auto &Note : Notes)
17061       Diag(Note.first, Note.second);
17062     return !ErrorOnInvalidMessage;
17063   }
17064   return true;
17065 }
17066 
17067 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
17068                                          Expr *AssertExpr, Expr *AssertMessage,
17069                                          SourceLocation RParenLoc,
17070                                          bool Failed) {
17071   assert(AssertExpr != nullptr && "Expected non-null condition");
17072   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
17073       (!AssertMessage || (!AssertMessage->isTypeDependent() &&
17074                           !AssertMessage->isValueDependent())) &&
17075       !Failed) {
17076     // In a static_assert-declaration, the constant-expression shall be a
17077     // constant expression that can be contextually converted to bool.
17078     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
17079     if (Converted.isInvalid())
17080       Failed = true;
17081 
17082     ExprResult FullAssertExpr =
17083         ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
17084                             /*DiscardedValue*/ false,
17085                             /*IsConstexpr*/ true);
17086     if (FullAssertExpr.isInvalid())
17087       Failed = true;
17088     else
17089       AssertExpr = FullAssertExpr.get();
17090 
17091     llvm::APSInt Cond;
17092     Expr *BaseExpr = AssertExpr;
17093     AllowFoldKind FoldKind = NoFold;
17094 
17095     if (!getLangOpts().CPlusPlus) {
17096       // In C mode, allow folding as an extension for better compatibility with
17097       // C++ in terms of expressions like static_assert("test") or
17098       // static_assert(nullptr).
17099       FoldKind = AllowFold;
17100     }
17101 
17102     if (!Failed && VerifyIntegerConstantExpression(
17103                        BaseExpr, &Cond,
17104                        diag::err_static_assert_expression_is_not_constant,
17105                        FoldKind).isInvalid())
17106       Failed = true;
17107 
17108     // If the static_assert passes, only verify that
17109     // the message is grammatically valid without evaluating it.
17110     if (!Failed && AssertMessage && Cond.getBoolValue()) {
17111       std::string Str;
17112       EvaluateStaticAssertMessageAsString(AssertMessage, Str, Context,
17113                                           /*ErrorOnInvalidMessage=*/false);
17114     }
17115 
17116     // CWG2518
17117     // [dcl.pre]/p10  If [...] the expression is evaluated in the context of a
17118     // template definition, the declaration has no effect.
17119     bool InTemplateDefinition =
17120         getLangOpts().CPlusPlus && CurContext->isDependentContext();
17121 
17122     if (!Failed && !Cond && !InTemplateDefinition) {
17123       SmallString<256> MsgBuffer;
17124       llvm::raw_svector_ostream Msg(MsgBuffer);
17125       bool HasMessage = AssertMessage;
17126       if (AssertMessage) {
17127         std::string Str;
17128         HasMessage =
17129             EvaluateStaticAssertMessageAsString(
17130                 AssertMessage, Str, Context, /*ErrorOnInvalidMessage=*/true) ||
17131             !Str.empty();
17132         Msg << Str;
17133       }
17134       Expr *InnerCond = nullptr;
17135       std::string InnerCondDescription;
17136       std::tie(InnerCond, InnerCondDescription) =
17137         findFailedBooleanCondition(Converted.get());
17138       if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {
17139         // Drill down into concept specialization expressions to see why they
17140         // weren't satisfied.
17141         Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
17142             << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
17143         ConstraintSatisfaction Satisfaction;
17144         if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
17145           DiagnoseUnsatisfiedConstraint(Satisfaction);
17146       } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
17147                            && !isa<IntegerLiteral>(InnerCond)) {
17148         Diag(InnerCond->getBeginLoc(),
17149              diag::err_static_assert_requirement_failed)
17150             << InnerCondDescription << !HasMessage << Msg.str()
17151             << InnerCond->getSourceRange();
17152         DiagnoseStaticAssertDetails(InnerCond);
17153       } else {
17154         Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
17155             << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
17156         PrintContextStack();
17157       }
17158       Failed = true;
17159     }
17160   } else {
17161     ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
17162                                                     /*DiscardedValue*/false,
17163                                                     /*IsConstexpr*/true);
17164     if (FullAssertExpr.isInvalid())
17165       Failed = true;
17166     else
17167       AssertExpr = FullAssertExpr.get();
17168   }
17169 
17170   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
17171                                         AssertExpr, AssertMessage, RParenLoc,
17172                                         Failed);
17173 
17174   CurContext->addDecl(Decl);
17175   return Decl;
17176 }
17177 
17178 /// Perform semantic analysis of the given friend type declaration.
17179 ///
17180 /// \returns A friend declaration that.
17181 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
17182                                       SourceLocation FriendLoc,
17183                                       TypeSourceInfo *TSInfo) {
17184   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
17185 
17186   QualType T = TSInfo->getType();
17187   SourceRange TypeRange = TSInfo->getTypeLoc().getSourceRange();
17188 
17189   // C++03 [class.friend]p2:
17190   //   An elaborated-type-specifier shall be used in a friend declaration
17191   //   for a class.*
17192   //
17193   //   * The class-key of the elaborated-type-specifier is required.
17194   if (!CodeSynthesisContexts.empty()) {
17195     // Do not complain about the form of friend template types during any kind
17196     // of code synthesis. For template instantiation, we will have complained
17197     // when the template was defined.
17198   } else {
17199     if (!T->isElaboratedTypeSpecifier()) {
17200       // If we evaluated the type to a record type, suggest putting
17201       // a tag in front.
17202       if (const RecordType *RT = T->getAs<RecordType>()) {
17203         RecordDecl *RD = RT->getDecl();
17204 
17205         SmallString<16> InsertionText(" ");
17206         InsertionText += RD->getKindName();
17207 
17208         Diag(TypeRange.getBegin(),
17209              getLangOpts().CPlusPlus11 ?
17210                diag::warn_cxx98_compat_unelaborated_friend_type :
17211                diag::ext_unelaborated_friend_type)
17212           << (unsigned) RD->getTagKind()
17213           << T
17214           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
17215                                         InsertionText);
17216       } else {
17217         Diag(FriendLoc,
17218              getLangOpts().CPlusPlus11 ?
17219                diag::warn_cxx98_compat_nonclass_type_friend :
17220                diag::ext_nonclass_type_friend)
17221           << T
17222           << TypeRange;
17223       }
17224     } else if (T->getAs<EnumType>()) {
17225       Diag(FriendLoc,
17226            getLangOpts().CPlusPlus11 ?
17227              diag::warn_cxx98_compat_enum_friend :
17228              diag::ext_enum_friend)
17229         << T
17230         << TypeRange;
17231     }
17232 
17233     // C++11 [class.friend]p3:
17234     //   A friend declaration that does not declare a function shall have one
17235     //   of the following forms:
17236     //     friend elaborated-type-specifier ;
17237     //     friend simple-type-specifier ;
17238     //     friend typename-specifier ;
17239     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
17240       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
17241   }
17242 
17243   //   If the type specifier in a friend declaration designates a (possibly
17244   //   cv-qualified) class type, that class is declared as a friend; otherwise,
17245   //   the friend declaration is ignored.
17246   return FriendDecl::Create(Context, CurContext,
17247                             TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
17248                             FriendLoc);
17249 }
17250 
17251 /// Handle a friend tag declaration where the scope specifier was
17252 /// templated.
17253 DeclResult Sema::ActOnTemplatedFriendTag(
17254     Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc,
17255     CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17256     const ParsedAttributesView &Attr, MultiTemplateParamsArg TempParamLists) {
17257   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
17258 
17259   bool IsMemberSpecialization = false;
17260   bool Invalid = false;
17261 
17262   if (TemplateParameterList *TemplateParams =
17263           MatchTemplateParametersToScopeSpecifier(
17264               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
17265               IsMemberSpecialization, Invalid)) {
17266     if (TemplateParams->size() > 0) {
17267       // This is a declaration of a class template.
17268       if (Invalid)
17269         return true;
17270 
17271       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
17272                                 NameLoc, Attr, TemplateParams, AS_public,
17273                                 /*ModulePrivateLoc=*/SourceLocation(),
17274                                 FriendLoc, TempParamLists.size() - 1,
17275                                 TempParamLists.data()).get();
17276     } else {
17277       // The "template<>" header is extraneous.
17278       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
17279         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
17280       IsMemberSpecialization = true;
17281     }
17282   }
17283 
17284   if (Invalid) return true;
17285 
17286   bool isAllExplicitSpecializations = true;
17287   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
17288     if (TempParamLists[I]->size()) {
17289       isAllExplicitSpecializations = false;
17290       break;
17291     }
17292   }
17293 
17294   // FIXME: don't ignore attributes.
17295 
17296   // If it's explicit specializations all the way down, just forget
17297   // about the template header and build an appropriate non-templated
17298   // friend.  TODO: for source fidelity, remember the headers.
17299   if (isAllExplicitSpecializations) {
17300     if (SS.isEmpty()) {
17301       bool Owned = false;
17302       bool IsDependent = false;
17303       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, Attr,
17304                       AS_public,
17305                       /*ModulePrivateLoc=*/SourceLocation(),
17306                       MultiTemplateParamsArg(), Owned, IsDependent,
17307                       /*ScopedEnumKWLoc=*/SourceLocation(),
17308                       /*ScopedEnumUsesClassTag=*/false,
17309                       /*UnderlyingType=*/TypeResult(),
17310                       /*IsTypeSpecifier=*/false,
17311                       /*IsTemplateParamOrArg=*/false, /*OOK=*/OOK_Outside);
17312     }
17313 
17314     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
17315     ElaboratedTypeKeyword Keyword
17316       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
17317     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
17318                                    *Name, NameLoc);
17319     if (T.isNull())
17320       return true;
17321 
17322     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
17323     if (isa<DependentNameType>(T)) {
17324       DependentNameTypeLoc TL =
17325           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
17326       TL.setElaboratedKeywordLoc(TagLoc);
17327       TL.setQualifierLoc(QualifierLoc);
17328       TL.setNameLoc(NameLoc);
17329     } else {
17330       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
17331       TL.setElaboratedKeywordLoc(TagLoc);
17332       TL.setQualifierLoc(QualifierLoc);
17333       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
17334     }
17335 
17336     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
17337                                             TSI, FriendLoc, TempParamLists);
17338     Friend->setAccess(AS_public);
17339     CurContext->addDecl(Friend);
17340     return Friend;
17341   }
17342 
17343   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
17344 
17345 
17346 
17347   // Handle the case of a templated-scope friend class.  e.g.
17348   //   template <class T> class A<T>::B;
17349   // FIXME: we don't support these right now.
17350   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
17351     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
17352   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
17353   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
17354   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
17355   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
17356   TL.setElaboratedKeywordLoc(TagLoc);
17357   TL.setQualifierLoc(SS.getWithLocInContext(Context));
17358   TL.setNameLoc(NameLoc);
17359 
17360   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
17361                                           TSI, FriendLoc, TempParamLists);
17362   Friend->setAccess(AS_public);
17363   Friend->setUnsupportedFriend(true);
17364   CurContext->addDecl(Friend);
17365   return Friend;
17366 }
17367 
17368 /// Handle a friend type declaration.  This works in tandem with
17369 /// ActOnTag.
17370 ///
17371 /// Notes on friend class templates:
17372 ///
17373 /// We generally treat friend class declarations as if they were
17374 /// declaring a class.  So, for example, the elaborated type specifier
17375 /// in a friend declaration is required to obey the restrictions of a
17376 /// class-head (i.e. no typedefs in the scope chain), template
17377 /// parameters are required to match up with simple template-ids, &c.
17378 /// However, unlike when declaring a template specialization, it's
17379 /// okay to refer to a template specialization without an empty
17380 /// template parameter declaration, e.g.
17381 ///   friend class A<T>::B<unsigned>;
17382 /// We permit this as a special case; if there are any template
17383 /// parameters present at all, require proper matching, i.e.
17384 ///   template <> template \<class T> friend class A<int>::B;
17385 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
17386                                 MultiTemplateParamsArg TempParams) {
17387   SourceLocation Loc = DS.getBeginLoc();
17388 
17389   assert(DS.isFriendSpecified());
17390   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
17391 
17392   // C++ [class.friend]p3:
17393   // A friend declaration that does not declare a function shall have one of
17394   // the following forms:
17395   //     friend elaborated-type-specifier ;
17396   //     friend simple-type-specifier ;
17397   //     friend typename-specifier ;
17398   //
17399   // Any declaration with a type qualifier does not have that form. (It's
17400   // legal to specify a qualified type as a friend, you just can't write the
17401   // keywords.)
17402   if (DS.getTypeQualifiers()) {
17403     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
17404       Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
17405     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
17406       Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
17407     if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
17408       Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
17409     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
17410       Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
17411     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
17412       Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
17413   }
17414 
17415   // Try to convert the decl specifier to a type.  This works for
17416   // friend templates because ActOnTag never produces a ClassTemplateDecl
17417   // for a TUK_Friend.
17418   Declarator TheDeclarator(DS, ParsedAttributesView::none(),
17419                            DeclaratorContext::Member);
17420   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
17421   QualType T = TSI->getType();
17422   if (TheDeclarator.isInvalidType())
17423     return nullptr;
17424 
17425   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
17426     return nullptr;
17427 
17428   // This is definitely an error in C++98.  It's probably meant to
17429   // be forbidden in C++0x, too, but the specification is just
17430   // poorly written.
17431   //
17432   // The problem is with declarations like the following:
17433   //   template <T> friend A<T>::foo;
17434   // where deciding whether a class C is a friend or not now hinges
17435   // on whether there exists an instantiation of A that causes
17436   // 'foo' to equal C.  There are restrictions on class-heads
17437   // (which we declare (by fiat) elaborated friend declarations to
17438   // be) that makes this tractable.
17439   //
17440   // FIXME: handle "template <> friend class A<T>;", which
17441   // is possibly well-formed?  Who even knows?
17442   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
17443     Diag(Loc, diag::err_tagless_friend_type_template)
17444       << DS.getSourceRange();
17445     return nullptr;
17446   }
17447 
17448   // C++98 [class.friend]p1: A friend of a class is a function
17449   //   or class that is not a member of the class . . .
17450   // This is fixed in DR77, which just barely didn't make the C++03
17451   // deadline.  It's also a very silly restriction that seriously
17452   // affects inner classes and which nobody else seems to implement;
17453   // thus we never diagnose it, not even in -pedantic.
17454   //
17455   // But note that we could warn about it: it's always useless to
17456   // friend one of your own members (it's not, however, worthless to
17457   // friend a member of an arbitrary specialization of your template).
17458 
17459   Decl *D;
17460   if (!TempParams.empty())
17461     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
17462                                    TempParams,
17463                                    TSI,
17464                                    DS.getFriendSpecLoc());
17465   else
17466     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
17467 
17468   if (!D)
17469     return nullptr;
17470 
17471   D->setAccess(AS_public);
17472   CurContext->addDecl(D);
17473 
17474   return D;
17475 }
17476 
17477 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
17478                                         MultiTemplateParamsArg TemplateParams) {
17479   const DeclSpec &DS = D.getDeclSpec();
17480 
17481   assert(DS.isFriendSpecified());
17482   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
17483 
17484   SourceLocation Loc = D.getIdentifierLoc();
17485   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17486 
17487   // C++ [class.friend]p1
17488   //   A friend of a class is a function or class....
17489   // Note that this sees through typedefs, which is intended.
17490   // It *doesn't* see through dependent types, which is correct
17491   // according to [temp.arg.type]p3:
17492   //   If a declaration acquires a function type through a
17493   //   type dependent on a template-parameter and this causes
17494   //   a declaration that does not use the syntactic form of a
17495   //   function declarator to have a function type, the program
17496   //   is ill-formed.
17497   if (!TInfo->getType()->isFunctionType()) {
17498     Diag(Loc, diag::err_unexpected_friend);
17499 
17500     // It might be worthwhile to try to recover by creating an
17501     // appropriate declaration.
17502     return nullptr;
17503   }
17504 
17505   // C++ [namespace.memdef]p3
17506   //  - If a friend declaration in a non-local class first declares a
17507   //    class or function, the friend class or function is a member
17508   //    of the innermost enclosing namespace.
17509   //  - The name of the friend is not found by simple name lookup
17510   //    until a matching declaration is provided in that namespace
17511   //    scope (either before or after the class declaration granting
17512   //    friendship).
17513   //  - If a friend function is called, its name may be found by the
17514   //    name lookup that considers functions from namespaces and
17515   //    classes associated with the types of the function arguments.
17516   //  - When looking for a prior declaration of a class or a function
17517   //    declared as a friend, scopes outside the innermost enclosing
17518   //    namespace scope are not considered.
17519 
17520   CXXScopeSpec &SS = D.getCXXScopeSpec();
17521   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
17522   assert(NameInfo.getName());
17523 
17524   // Check for unexpanded parameter packs.
17525   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
17526       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
17527       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
17528     return nullptr;
17529 
17530   // The context we found the declaration in, or in which we should
17531   // create the declaration.
17532   DeclContext *DC;
17533   Scope *DCScope = S;
17534   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
17535                         ForExternalRedeclaration);
17536 
17537   // There are five cases here.
17538   //   - There's no scope specifier and we're in a local class. Only look
17539   //     for functions declared in the immediately-enclosing block scope.
17540   // We recover from invalid scope qualifiers as if they just weren't there.
17541   FunctionDecl *FunctionContainingLocalClass = nullptr;
17542   if ((SS.isInvalid() || !SS.isSet()) &&
17543       (FunctionContainingLocalClass =
17544            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
17545     // C++11 [class.friend]p11:
17546     //   If a friend declaration appears in a local class and the name
17547     //   specified is an unqualified name, a prior declaration is
17548     //   looked up without considering scopes that are outside the
17549     //   innermost enclosing non-class scope. For a friend function
17550     //   declaration, if there is no prior declaration, the program is
17551     //   ill-formed.
17552 
17553     // Find the innermost enclosing non-class scope. This is the block
17554     // scope containing the local class definition (or for a nested class,
17555     // the outer local class).
17556     DCScope = S->getFnParent();
17557 
17558     // Look up the function name in the scope.
17559     Previous.clear(LookupLocalFriendName);
17560     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
17561 
17562     if (!Previous.empty()) {
17563       // All possible previous declarations must have the same context:
17564       // either they were declared at block scope or they are members of
17565       // one of the enclosing local classes.
17566       DC = Previous.getRepresentativeDecl()->getDeclContext();
17567     } else {
17568       // This is ill-formed, but provide the context that we would have
17569       // declared the function in, if we were permitted to, for error recovery.
17570       DC = FunctionContainingLocalClass;
17571     }
17572     adjustContextForLocalExternDecl(DC);
17573 
17574     // C++ [class.friend]p6:
17575     //   A function can be defined in a friend declaration of a class if and
17576     //   only if the class is a non-local class (9.8), the function name is
17577     //   unqualified, and the function has namespace scope.
17578     if (D.isFunctionDefinition()) {
17579       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
17580     }
17581 
17582   //   - There's no scope specifier, in which case we just go to the
17583   //     appropriate scope and look for a function or function template
17584   //     there as appropriate.
17585   } else if (SS.isInvalid() || !SS.isSet()) {
17586     // C++11 [namespace.memdef]p3:
17587     //   If the name in a friend declaration is neither qualified nor
17588     //   a template-id and the declaration is a function or an
17589     //   elaborated-type-specifier, the lookup to determine whether
17590     //   the entity has been previously declared shall not consider
17591     //   any scopes outside the innermost enclosing namespace.
17592     bool isTemplateId =
17593         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
17594 
17595     // Find the appropriate context according to the above.
17596     DC = CurContext;
17597 
17598     // Skip class contexts.  If someone can cite chapter and verse
17599     // for this behavior, that would be nice --- it's what GCC and
17600     // EDG do, and it seems like a reasonable intent, but the spec
17601     // really only says that checks for unqualified existing
17602     // declarations should stop at the nearest enclosing namespace,
17603     // not that they should only consider the nearest enclosing
17604     // namespace.
17605     while (DC->isRecord())
17606       DC = DC->getParent();
17607 
17608     DeclContext *LookupDC = DC->getNonTransparentContext();
17609     while (true) {
17610       LookupQualifiedName(Previous, LookupDC);
17611 
17612       if (!Previous.empty()) {
17613         DC = LookupDC;
17614         break;
17615       }
17616 
17617       if (isTemplateId) {
17618         if (isa<TranslationUnitDecl>(LookupDC)) break;
17619       } else {
17620         if (LookupDC->isFileContext()) break;
17621       }
17622       LookupDC = LookupDC->getParent();
17623     }
17624 
17625     DCScope = getScopeForDeclContext(S, DC);
17626 
17627   //   - There's a non-dependent scope specifier, in which case we
17628   //     compute it and do a previous lookup there for a function
17629   //     or function template.
17630   } else if (!SS.getScopeRep()->isDependent()) {
17631     DC = computeDeclContext(SS);
17632     if (!DC) return nullptr;
17633 
17634     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
17635 
17636     LookupQualifiedName(Previous, DC);
17637 
17638     // C++ [class.friend]p1: A friend of a class is a function or
17639     //   class that is not a member of the class . . .
17640     if (DC->Equals(CurContext))
17641       Diag(DS.getFriendSpecLoc(),
17642            getLangOpts().CPlusPlus11 ?
17643              diag::warn_cxx98_compat_friend_is_member :
17644              diag::err_friend_is_member);
17645 
17646     if (D.isFunctionDefinition()) {
17647       // C++ [class.friend]p6:
17648       //   A function can be defined in a friend declaration of a class if and
17649       //   only if the class is a non-local class (9.8), the function name is
17650       //   unqualified, and the function has namespace scope.
17651       //
17652       // FIXME: We should only do this if the scope specifier names the
17653       // innermost enclosing namespace; otherwise the fixit changes the
17654       // meaning of the code.
17655       SemaDiagnosticBuilder DB
17656         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
17657 
17658       DB << SS.getScopeRep();
17659       if (DC->isFileContext())
17660         DB << FixItHint::CreateRemoval(SS.getRange());
17661       SS.clear();
17662     }
17663 
17664   //   - There's a scope specifier that does not match any template
17665   //     parameter lists, in which case we use some arbitrary context,
17666   //     create a method or method template, and wait for instantiation.
17667   //   - There's a scope specifier that does match some template
17668   //     parameter lists, which we don't handle right now.
17669   } else {
17670     if (D.isFunctionDefinition()) {
17671       // C++ [class.friend]p6:
17672       //   A function can be defined in a friend declaration of a class if and
17673       //   only if the class is a non-local class (9.8), the function name is
17674       //   unqualified, and the function has namespace scope.
17675       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
17676         << SS.getScopeRep();
17677     }
17678 
17679     DC = CurContext;
17680     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
17681   }
17682 
17683   if (!DC->isRecord()) {
17684     int DiagArg = -1;
17685     switch (D.getName().getKind()) {
17686     case UnqualifiedIdKind::IK_ConstructorTemplateId:
17687     case UnqualifiedIdKind::IK_ConstructorName:
17688       DiagArg = 0;
17689       break;
17690     case UnqualifiedIdKind::IK_DestructorName:
17691       DiagArg = 1;
17692       break;
17693     case UnqualifiedIdKind::IK_ConversionFunctionId:
17694       DiagArg = 2;
17695       break;
17696     case UnqualifiedIdKind::IK_DeductionGuideName:
17697       DiagArg = 3;
17698       break;
17699     case UnqualifiedIdKind::IK_Identifier:
17700     case UnqualifiedIdKind::IK_ImplicitSelfParam:
17701     case UnqualifiedIdKind::IK_LiteralOperatorId:
17702     case UnqualifiedIdKind::IK_OperatorFunctionId:
17703     case UnqualifiedIdKind::IK_TemplateId:
17704       break;
17705     }
17706     // This implies that it has to be an operator or function.
17707     if (DiagArg >= 0) {
17708       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
17709       return nullptr;
17710     }
17711   }
17712 
17713   // FIXME: This is an egregious hack to cope with cases where the scope stack
17714   // does not contain the declaration context, i.e., in an out-of-line
17715   // definition of a class.
17716   Scope FakeDCScope(S, Scope::DeclScope, Diags);
17717   if (!DCScope) {
17718     FakeDCScope.setEntity(DC);
17719     DCScope = &FakeDCScope;
17720   }
17721 
17722   bool AddToScope = true;
17723   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
17724                                           TemplateParams, AddToScope);
17725   if (!ND) return nullptr;
17726 
17727   assert(ND->getLexicalDeclContext() == CurContext);
17728 
17729   // If we performed typo correction, we might have added a scope specifier
17730   // and changed the decl context.
17731   DC = ND->getDeclContext();
17732 
17733   // Add the function declaration to the appropriate lookup tables,
17734   // adjusting the redeclarations list as necessary.  We don't
17735   // want to do this yet if the friending class is dependent.
17736   //
17737   // Also update the scope-based lookup if the target context's
17738   // lookup context is in lexical scope.
17739   if (!CurContext->isDependentContext()) {
17740     DC = DC->getRedeclContext();
17741     DC->makeDeclVisibleInContext(ND);
17742     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
17743       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
17744   }
17745 
17746   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
17747                                        D.getIdentifierLoc(), ND,
17748                                        DS.getFriendSpecLoc());
17749   FrD->setAccess(AS_public);
17750   CurContext->addDecl(FrD);
17751 
17752   if (ND->isInvalidDecl()) {
17753     FrD->setInvalidDecl();
17754   } else {
17755     if (DC->isRecord()) CheckFriendAccess(ND);
17756 
17757     FunctionDecl *FD;
17758     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
17759       FD = FTD->getTemplatedDecl();
17760     else
17761       FD = cast<FunctionDecl>(ND);
17762 
17763     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
17764     // default argument expression, that declaration shall be a definition
17765     // and shall be the only declaration of the function or function
17766     // template in the translation unit.
17767     if (functionDeclHasDefaultArgument(FD)) {
17768       // We can't look at FD->getPreviousDecl() because it may not have been set
17769       // if we're in a dependent context. If the function is known to be a
17770       // redeclaration, we will have narrowed Previous down to the right decl.
17771       if (D.isRedeclaration()) {
17772         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
17773         Diag(Previous.getRepresentativeDecl()->getLocation(),
17774              diag::note_previous_declaration);
17775       } else if (!D.isFunctionDefinition())
17776         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
17777     }
17778 
17779     // Mark templated-scope function declarations as unsupported.
17780     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
17781       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
17782         << SS.getScopeRep() << SS.getRange()
17783         << cast<CXXRecordDecl>(CurContext);
17784       FrD->setUnsupportedFriend(true);
17785     }
17786   }
17787 
17788   warnOnReservedIdentifier(ND);
17789 
17790   return ND;
17791 }
17792 
17793 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
17794   AdjustDeclIfTemplate(Dcl);
17795 
17796   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
17797   if (!Fn) {
17798     Diag(DelLoc, diag::err_deleted_non_function);
17799     return;
17800   }
17801 
17802   // Deleted function does not have a body.
17803   Fn->setWillHaveBody(false);
17804 
17805   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
17806     // Don't consider the implicit declaration we generate for explicit
17807     // specializations. FIXME: Do not generate these implicit declarations.
17808     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
17809          Prev->getPreviousDecl()) &&
17810         !Prev->isDefined()) {
17811       Diag(DelLoc, diag::err_deleted_decl_not_first);
17812       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
17813            Prev->isImplicit() ? diag::note_previous_implicit_declaration
17814                               : diag::note_previous_declaration);
17815       // We can't recover from this; the declaration might have already
17816       // been used.
17817       Fn->setInvalidDecl();
17818       return;
17819     }
17820 
17821     // To maintain the invariant that functions are only deleted on their first
17822     // declaration, mark the implicitly-instantiated declaration of the
17823     // explicitly-specialized function as deleted instead of marking the
17824     // instantiated redeclaration.
17825     Fn = Fn->getCanonicalDecl();
17826   }
17827 
17828   // dllimport/dllexport cannot be deleted.
17829   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
17830     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
17831     Fn->setInvalidDecl();
17832   }
17833 
17834   // C++11 [basic.start.main]p3:
17835   //   A program that defines main as deleted [...] is ill-formed.
17836   if (Fn->isMain())
17837     Diag(DelLoc, diag::err_deleted_main);
17838 
17839   // C++11 [dcl.fct.def.delete]p4:
17840   //  A deleted function is implicitly inline.
17841   Fn->setImplicitlyInline();
17842   Fn->setDeletedAsWritten();
17843 }
17844 
17845 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
17846   if (!Dcl || Dcl->isInvalidDecl())
17847     return;
17848 
17849   auto *FD = dyn_cast<FunctionDecl>(Dcl);
17850   if (!FD) {
17851     if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
17852       if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
17853         Diag(DefaultLoc, diag::err_defaulted_comparison_template);
17854         return;
17855       }
17856     }
17857 
17858     Diag(DefaultLoc, diag::err_default_special_members)
17859         << getLangOpts().CPlusPlus20;
17860     return;
17861   }
17862 
17863   // Reject if this can't possibly be a defaultable function.
17864   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
17865   if (!DefKind &&
17866       // A dependent function that doesn't locally look defaultable can
17867       // still instantiate to a defaultable function if it's a constructor
17868       // or assignment operator.
17869       (!FD->isDependentContext() ||
17870        (!isa<CXXConstructorDecl>(FD) &&
17871         FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
17872     Diag(DefaultLoc, diag::err_default_special_members)
17873         << getLangOpts().CPlusPlus20;
17874     return;
17875   }
17876 
17877   // Issue compatibility warning. We already warned if the operator is
17878   // 'operator<=>' when parsing the '<=>' token.
17879   if (DefKind.isComparison() &&
17880       DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
17881     Diag(DefaultLoc, getLangOpts().CPlusPlus20
17882                          ? diag::warn_cxx17_compat_defaulted_comparison
17883                          : diag::ext_defaulted_comparison);
17884   }
17885 
17886   FD->setDefaulted();
17887   FD->setExplicitlyDefaulted();
17888   FD->setDefaultLoc(DefaultLoc);
17889 
17890   // Defer checking functions that are defaulted in a dependent context.
17891   if (FD->isDependentContext())
17892     return;
17893 
17894   // Unset that we will have a body for this function. We might not,
17895   // if it turns out to be trivial, and we don't need this marking now
17896   // that we've marked it as defaulted.
17897   FD->setWillHaveBody(false);
17898 
17899   if (DefKind.isComparison()) {
17900     // If this comparison's defaulting occurs within the definition of its
17901     // lexical class context, we have to do the checking when complete.
17902     if (auto const *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()))
17903       if (!RD->isCompleteDefinition())
17904         return;
17905   }
17906 
17907   // If this member fn was defaulted on its first declaration, we will have
17908   // already performed the checking in CheckCompletedCXXClass. Such a
17909   // declaration doesn't trigger an implicit definition.
17910   if (isa<CXXMethodDecl>(FD)) {
17911     const FunctionDecl *Primary = FD;
17912     if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
17913       // Ask the template instantiation pattern that actually had the
17914       // '= default' on it.
17915       Primary = Pattern;
17916     if (Primary->getCanonicalDecl()->isDefaulted())
17917       return;
17918   }
17919 
17920   if (DefKind.isComparison()) {
17921     if (CheckExplicitlyDefaultedComparison(nullptr, FD, DefKind.asComparison()))
17922       FD->setInvalidDecl();
17923     else
17924       DefineDefaultedComparison(DefaultLoc, FD, DefKind.asComparison());
17925   } else {
17926     auto *MD = cast<CXXMethodDecl>(FD);
17927 
17928     if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember(),
17929                                               DefaultLoc))
17930       MD->setInvalidDecl();
17931     else
17932       DefineDefaultedFunction(*this, MD, DefaultLoc);
17933   }
17934 }
17935 
17936 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
17937   for (Stmt *SubStmt : S->children()) {
17938     if (!SubStmt)
17939       continue;
17940     if (isa<ReturnStmt>(SubStmt))
17941       Self.Diag(SubStmt->getBeginLoc(),
17942                 diag::err_return_in_constructor_handler);
17943     if (!isa<Expr>(SubStmt))
17944       SearchForReturnInStmt(Self, SubStmt);
17945   }
17946 }
17947 
17948 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
17949   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
17950     CXXCatchStmt *Handler = TryBlock->getHandler(I);
17951     SearchForReturnInStmt(*this, Handler);
17952   }
17953 }
17954 
17955 void Sema::SetFunctionBodyKind(Decl *D, SourceLocation Loc,
17956                                FnBodyKind BodyKind) {
17957   switch (BodyKind) {
17958   case FnBodyKind::Delete:
17959     SetDeclDeleted(D, Loc);
17960     break;
17961   case FnBodyKind::Default:
17962     SetDeclDefaulted(D, Loc);
17963     break;
17964   case FnBodyKind::Other:
17965     llvm_unreachable(
17966         "Parsed function body should be '= delete;' or '= default;'");
17967   }
17968 }
17969 
17970 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
17971                                              const CXXMethodDecl *Old) {
17972   const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
17973   const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
17974 
17975   if (OldFT->hasExtParameterInfos()) {
17976     for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
17977       // A parameter of the overriding method should be annotated with noescape
17978       // if the corresponding parameter of the overridden method is annotated.
17979       if (OldFT->getExtParameterInfo(I).isNoEscape() &&
17980           !NewFT->getExtParameterInfo(I).isNoEscape()) {
17981         Diag(New->getParamDecl(I)->getLocation(),
17982              diag::warn_overriding_method_missing_noescape);
17983         Diag(Old->getParamDecl(I)->getLocation(),
17984              diag::note_overridden_marked_noescape);
17985       }
17986   }
17987 
17988   // Virtual overrides must have the same code_seg.
17989   const auto *OldCSA = Old->getAttr<CodeSegAttr>();
17990   const auto *NewCSA = New->getAttr<CodeSegAttr>();
17991   if ((NewCSA || OldCSA) &&
17992       (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
17993     Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
17994     Diag(Old->getLocation(), diag::note_previous_declaration);
17995     return true;
17996   }
17997 
17998   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
17999 
18000   // If the calling conventions match, everything is fine
18001   if (NewCC == OldCC)
18002     return false;
18003 
18004   // If the calling conventions mismatch because the new function is static,
18005   // suppress the calling convention mismatch error; the error about static
18006   // function override (err_static_overrides_virtual from
18007   // Sema::CheckFunctionDeclaration) is more clear.
18008   if (New->getStorageClass() == SC_Static)
18009     return false;
18010 
18011   Diag(New->getLocation(),
18012        diag::err_conflicting_overriding_cc_attributes)
18013     << New->getDeclName() << New->getType() << Old->getType();
18014   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18015   return true;
18016 }
18017 
18018 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
18019                                              const CXXMethodDecl *Old) {
18020   QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
18021   QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
18022 
18023   if (Context.hasSameType(NewTy, OldTy) ||
18024       NewTy->isDependentType() || OldTy->isDependentType())
18025     return false;
18026 
18027   // Check if the return types are covariant
18028   QualType NewClassTy, OldClassTy;
18029 
18030   /// Both types must be pointers or references to classes.
18031   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
18032     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
18033       NewClassTy = NewPT->getPointeeType();
18034       OldClassTy = OldPT->getPointeeType();
18035     }
18036   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
18037     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
18038       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
18039         NewClassTy = NewRT->getPointeeType();
18040         OldClassTy = OldRT->getPointeeType();
18041       }
18042     }
18043   }
18044 
18045   // The return types aren't either both pointers or references to a class type.
18046   if (NewClassTy.isNull()) {
18047     Diag(New->getLocation(),
18048          diag::err_different_return_type_for_overriding_virtual_function)
18049         << New->getDeclName() << NewTy << OldTy
18050         << New->getReturnTypeSourceRange();
18051     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18052         << Old->getReturnTypeSourceRange();
18053 
18054     return true;
18055   }
18056 
18057   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
18058     // C++14 [class.virtual]p8:
18059     //   If the class type in the covariant return type of D::f differs from
18060     //   that of B::f, the class type in the return type of D::f shall be
18061     //   complete at the point of declaration of D::f or shall be the class
18062     //   type D.
18063     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
18064       if (!RT->isBeingDefined() &&
18065           RequireCompleteType(New->getLocation(), NewClassTy,
18066                               diag::err_covariant_return_incomplete,
18067                               New->getDeclName()))
18068         return true;
18069     }
18070 
18071     // Check if the new class derives from the old class.
18072     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
18073       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
18074           << New->getDeclName() << NewTy << OldTy
18075           << New->getReturnTypeSourceRange();
18076       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18077           << Old->getReturnTypeSourceRange();
18078       return true;
18079     }
18080 
18081     // Check if we the conversion from derived to base is valid.
18082     if (CheckDerivedToBaseConversion(
18083             NewClassTy, OldClassTy,
18084             diag::err_covariant_return_inaccessible_base,
18085             diag::err_covariant_return_ambiguous_derived_to_base_conv,
18086             New->getLocation(), New->getReturnTypeSourceRange(),
18087             New->getDeclName(), nullptr)) {
18088       // FIXME: this note won't trigger for delayed access control
18089       // diagnostics, and it's impossible to get an undelayed error
18090       // here from access control during the original parse because
18091       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
18092       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18093           << Old->getReturnTypeSourceRange();
18094       return true;
18095     }
18096   }
18097 
18098   // The qualifiers of the return types must be the same.
18099   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
18100     Diag(New->getLocation(),
18101          diag::err_covariant_return_type_different_qualifications)
18102         << New->getDeclName() << NewTy << OldTy
18103         << New->getReturnTypeSourceRange();
18104     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18105         << Old->getReturnTypeSourceRange();
18106     return true;
18107   }
18108 
18109 
18110   // The new class type must have the same or less qualifiers as the old type.
18111   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
18112     Diag(New->getLocation(),
18113          diag::err_covariant_return_type_class_type_more_qualified)
18114         << New->getDeclName() << NewTy << OldTy
18115         << New->getReturnTypeSourceRange();
18116     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18117         << Old->getReturnTypeSourceRange();
18118     return true;
18119   }
18120 
18121   return false;
18122 }
18123 
18124 /// Mark the given method pure.
18125 ///
18126 /// \param Method the method to be marked pure.
18127 ///
18128 /// \param InitRange the source range that covers the "0" initializer.
18129 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
18130   SourceLocation EndLoc = InitRange.getEnd();
18131   if (EndLoc.isValid())
18132     Method->setRangeEnd(EndLoc);
18133 
18134   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
18135     Method->setPure();
18136     return false;
18137   }
18138 
18139   if (!Method->isInvalidDecl())
18140     Diag(Method->getLocation(), diag::err_non_virtual_pure)
18141       << Method->getDeclName() << InitRange;
18142   return true;
18143 }
18144 
18145 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
18146   if (D->getFriendObjectKind())
18147     Diag(D->getLocation(), diag::err_pure_friend);
18148   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
18149     CheckPureMethod(M, ZeroLoc);
18150   else
18151     Diag(D->getLocation(), diag::err_illegal_initializer);
18152 }
18153 
18154 /// Determine whether the given declaration is a global variable or
18155 /// static data member.
18156 static bool isNonlocalVariable(const Decl *D) {
18157   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
18158     return Var->hasGlobalStorage();
18159 
18160   return false;
18161 }
18162 
18163 /// Invoked when we are about to parse an initializer for the declaration
18164 /// 'Dcl'.
18165 ///
18166 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
18167 /// static data member of class X, names should be looked up in the scope of
18168 /// class X. If the declaration had a scope specifier, a scope will have
18169 /// been created and passed in for this purpose. Otherwise, S will be null.
18170 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
18171   // If there is no declaration, there was an error parsing it.
18172   if (!D || D->isInvalidDecl())
18173     return;
18174 
18175   // We will always have a nested name specifier here, but this declaration
18176   // might not be out of line if the specifier names the current namespace:
18177   //   extern int n;
18178   //   int ::n = 0;
18179   if (S && D->isOutOfLine())
18180     EnterDeclaratorContext(S, D->getDeclContext());
18181 
18182   // If we are parsing the initializer for a static data member, push a
18183   // new expression evaluation context that is associated with this static
18184   // data member.
18185   if (isNonlocalVariable(D))
18186     PushExpressionEvaluationContext(
18187         ExpressionEvaluationContext::PotentiallyEvaluated, D);
18188 }
18189 
18190 /// Invoked after we are finished parsing an initializer for the declaration D.
18191 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
18192   // If there is no declaration, there was an error parsing it.
18193   if (!D || D->isInvalidDecl())
18194     return;
18195 
18196   if (isNonlocalVariable(D))
18197     PopExpressionEvaluationContext();
18198 
18199   if (S && D->isOutOfLine())
18200     ExitDeclaratorContext(S);
18201 }
18202 
18203 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
18204 /// C++ if/switch/while/for statement.
18205 /// e.g: "if (int x = f()) {...}"
18206 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
18207   // C++ 6.4p2:
18208   // The declarator shall not specify a function or an array.
18209   // The type-specifier-seq shall not contain typedef and shall not declare a
18210   // new class or enumeration.
18211   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
18212          "Parser allowed 'typedef' as storage class of condition decl.");
18213 
18214   Decl *Dcl = ActOnDeclarator(S, D);
18215   if (!Dcl)
18216     return true;
18217 
18218   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
18219     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
18220       << D.getSourceRange();
18221     return true;
18222   }
18223 
18224   return Dcl;
18225 }
18226 
18227 void Sema::LoadExternalVTableUses() {
18228   if (!ExternalSource)
18229     return;
18230 
18231   SmallVector<ExternalVTableUse, 4> VTables;
18232   ExternalSource->ReadUsedVTables(VTables);
18233   SmallVector<VTableUse, 4> NewUses;
18234   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
18235     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
18236       = VTablesUsed.find(VTables[I].Record);
18237     // Even if a definition wasn't required before, it may be required now.
18238     if (Pos != VTablesUsed.end()) {
18239       if (!Pos->second && VTables[I].DefinitionRequired)
18240         Pos->second = true;
18241       continue;
18242     }
18243 
18244     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
18245     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
18246   }
18247 
18248   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
18249 }
18250 
18251 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
18252                           bool DefinitionRequired) {
18253   // Ignore any vtable uses in unevaluated operands or for classes that do
18254   // not have a vtable.
18255   if (!Class->isDynamicClass() || Class->isDependentContext() ||
18256       CurContext->isDependentContext() || isUnevaluatedContext())
18257     return;
18258   // Do not mark as used if compiling for the device outside of the target
18259   // region.
18260   if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice &&
18261       !isInOpenMPDeclareTargetContext() &&
18262       !isInOpenMPTargetExecutionDirective()) {
18263     if (!DefinitionRequired)
18264       MarkVirtualMembersReferenced(Loc, Class);
18265     return;
18266   }
18267 
18268   // Try to insert this class into the map.
18269   LoadExternalVTableUses();
18270   Class = Class->getCanonicalDecl();
18271   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
18272     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
18273   if (!Pos.second) {
18274     // If we already had an entry, check to see if we are promoting this vtable
18275     // to require a definition. If so, we need to reappend to the VTableUses
18276     // list, since we may have already processed the first entry.
18277     if (DefinitionRequired && !Pos.first->second) {
18278       Pos.first->second = true;
18279     } else {
18280       // Otherwise, we can early exit.
18281       return;
18282     }
18283   } else {
18284     // The Microsoft ABI requires that we perform the destructor body
18285     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
18286     // the deleting destructor is emitted with the vtable, not with the
18287     // destructor definition as in the Itanium ABI.
18288     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
18289       CXXDestructorDecl *DD = Class->getDestructor();
18290       if (DD && DD->isVirtual() && !DD->isDeleted()) {
18291         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
18292           // If this is an out-of-line declaration, marking it referenced will
18293           // not do anything. Manually call CheckDestructor to look up operator
18294           // delete().
18295           ContextRAII SavedContext(*this, DD);
18296           CheckDestructor(DD);
18297         } else {
18298           MarkFunctionReferenced(Loc, Class->getDestructor());
18299         }
18300       }
18301     }
18302   }
18303 
18304   // Local classes need to have their virtual members marked
18305   // immediately. For all other classes, we mark their virtual members
18306   // at the end of the translation unit.
18307   if (Class->isLocalClass())
18308     MarkVirtualMembersReferenced(Loc, Class->getDefinition());
18309   else
18310     VTableUses.push_back(std::make_pair(Class, Loc));
18311 }
18312 
18313 bool Sema::DefineUsedVTables() {
18314   LoadExternalVTableUses();
18315   if (VTableUses.empty())
18316     return false;
18317 
18318   // Note: The VTableUses vector could grow as a result of marking
18319   // the members of a class as "used", so we check the size each
18320   // time through the loop and prefer indices (which are stable) to
18321   // iterators (which are not).
18322   bool DefinedAnything = false;
18323   for (unsigned I = 0; I != VTableUses.size(); ++I) {
18324     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
18325     if (!Class)
18326       continue;
18327     TemplateSpecializationKind ClassTSK =
18328         Class->getTemplateSpecializationKind();
18329 
18330     SourceLocation Loc = VTableUses[I].second;
18331 
18332     bool DefineVTable = true;
18333 
18334     // If this class has a key function, but that key function is
18335     // defined in another translation unit, we don't need to emit the
18336     // vtable even though we're using it.
18337     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
18338     if (KeyFunction && !KeyFunction->hasBody()) {
18339       // The key function is in another translation unit.
18340       DefineVTable = false;
18341       TemplateSpecializationKind TSK =
18342           KeyFunction->getTemplateSpecializationKind();
18343       assert(TSK != TSK_ExplicitInstantiationDefinition &&
18344              TSK != TSK_ImplicitInstantiation &&
18345              "Instantiations don't have key functions");
18346       (void)TSK;
18347     } else if (!KeyFunction) {
18348       // If we have a class with no key function that is the subject
18349       // of an explicit instantiation declaration, suppress the
18350       // vtable; it will live with the explicit instantiation
18351       // definition.
18352       bool IsExplicitInstantiationDeclaration =
18353           ClassTSK == TSK_ExplicitInstantiationDeclaration;
18354       for (auto *R : Class->redecls()) {
18355         TemplateSpecializationKind TSK
18356           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
18357         if (TSK == TSK_ExplicitInstantiationDeclaration)
18358           IsExplicitInstantiationDeclaration = true;
18359         else if (TSK == TSK_ExplicitInstantiationDefinition) {
18360           IsExplicitInstantiationDeclaration = false;
18361           break;
18362         }
18363       }
18364 
18365       if (IsExplicitInstantiationDeclaration)
18366         DefineVTable = false;
18367     }
18368 
18369     // The exception specifications for all virtual members may be needed even
18370     // if we are not providing an authoritative form of the vtable in this TU.
18371     // We may choose to emit it available_externally anyway.
18372     if (!DefineVTable) {
18373       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
18374       continue;
18375     }
18376 
18377     // Mark all of the virtual members of this class as referenced, so
18378     // that we can build a vtable. Then, tell the AST consumer that a
18379     // vtable for this class is required.
18380     DefinedAnything = true;
18381     MarkVirtualMembersReferenced(Loc, Class);
18382     CXXRecordDecl *Canonical = Class->getCanonicalDecl();
18383     if (VTablesUsed[Canonical])
18384       Consumer.HandleVTable(Class);
18385 
18386     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
18387     // no key function or the key function is inlined. Don't warn in C++ ABIs
18388     // that lack key functions, since the user won't be able to make one.
18389     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
18390         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation &&
18391         ClassTSK != TSK_ExplicitInstantiationDefinition) {
18392       const FunctionDecl *KeyFunctionDef = nullptr;
18393       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
18394                            KeyFunctionDef->isInlined()))
18395         Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
18396     }
18397   }
18398   VTableUses.clear();
18399 
18400   return DefinedAnything;
18401 }
18402 
18403 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
18404                                                  const CXXRecordDecl *RD) {
18405   for (const auto *I : RD->methods())
18406     if (I->isVirtual() && !I->isPure())
18407       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
18408 }
18409 
18410 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
18411                                         const CXXRecordDecl *RD,
18412                                         bool ConstexprOnly) {
18413   // Mark all functions which will appear in RD's vtable as used.
18414   CXXFinalOverriderMap FinalOverriders;
18415   RD->getFinalOverriders(FinalOverriders);
18416   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
18417                                             E = FinalOverriders.end();
18418        I != E; ++I) {
18419     for (OverridingMethods::const_iterator OI = I->second.begin(),
18420                                            OE = I->second.end();
18421          OI != OE; ++OI) {
18422       assert(OI->second.size() > 0 && "no final overrider");
18423       CXXMethodDecl *Overrider = OI->second.front().Method;
18424 
18425       // C++ [basic.def.odr]p2:
18426       //   [...] A virtual member function is used if it is not pure. [...]
18427       if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
18428         MarkFunctionReferenced(Loc, Overrider);
18429     }
18430   }
18431 
18432   // Only classes that have virtual bases need a VTT.
18433   if (RD->getNumVBases() == 0)
18434     return;
18435 
18436   for (const auto &I : RD->bases()) {
18437     const auto *Base =
18438         cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
18439     if (Base->getNumVBases() == 0)
18440       continue;
18441     MarkVirtualMembersReferenced(Loc, Base);
18442   }
18443 }
18444 
18445 /// SetIvarInitializers - This routine builds initialization ASTs for the
18446 /// Objective-C implementation whose ivars need be initialized.
18447 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
18448   if (!getLangOpts().CPlusPlus)
18449     return;
18450   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
18451     SmallVector<ObjCIvarDecl*, 8> ivars;
18452     CollectIvarsToConstructOrDestruct(OID, ivars);
18453     if (ivars.empty())
18454       return;
18455     SmallVector<CXXCtorInitializer*, 32> AllToInit;
18456     for (unsigned i = 0; i < ivars.size(); i++) {
18457       FieldDecl *Field = ivars[i];
18458       if (Field->isInvalidDecl())
18459         continue;
18460 
18461       CXXCtorInitializer *Member;
18462       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
18463       InitializationKind InitKind =
18464         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
18465 
18466       InitializationSequence InitSeq(*this, InitEntity, InitKind, std::nullopt);
18467       ExprResult MemberInit =
18468           InitSeq.Perform(*this, InitEntity, InitKind, std::nullopt);
18469       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
18470       // Note, MemberInit could actually come back empty if no initialization
18471       // is required (e.g., because it would call a trivial default constructor)
18472       if (!MemberInit.get() || MemberInit.isInvalid())
18473         continue;
18474 
18475       Member =
18476         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
18477                                          SourceLocation(),
18478                                          MemberInit.getAs<Expr>(),
18479                                          SourceLocation());
18480       AllToInit.push_back(Member);
18481 
18482       // Be sure that the destructor is accessible and is marked as referenced.
18483       if (const RecordType *RecordTy =
18484               Context.getBaseElementType(Field->getType())
18485                   ->getAs<RecordType>()) {
18486         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
18487         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
18488           MarkFunctionReferenced(Field->getLocation(), Destructor);
18489           CheckDestructorAccess(Field->getLocation(), Destructor,
18490                             PDiag(diag::err_access_dtor_ivar)
18491                               << Context.getBaseElementType(Field->getType()));
18492         }
18493       }
18494     }
18495     ObjCImplementation->setIvarInitializers(Context,
18496                                             AllToInit.data(), AllToInit.size());
18497   }
18498 }
18499 
18500 static
18501 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
18502                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
18503                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
18504                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
18505                            Sema &S) {
18506   if (Ctor->isInvalidDecl())
18507     return;
18508 
18509   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
18510 
18511   // Target may not be determinable yet, for instance if this is a dependent
18512   // call in an uninstantiated template.
18513   if (Target) {
18514     const FunctionDecl *FNTarget = nullptr;
18515     (void)Target->hasBody(FNTarget);
18516     Target = const_cast<CXXConstructorDecl*>(
18517       cast_or_null<CXXConstructorDecl>(FNTarget));
18518   }
18519 
18520   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
18521                      // Avoid dereferencing a null pointer here.
18522                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
18523 
18524   if (!Current.insert(Canonical).second)
18525     return;
18526 
18527   // We know that beyond here, we aren't chaining into a cycle.
18528   if (!Target || !Target->isDelegatingConstructor() ||
18529       Target->isInvalidDecl() || Valid.count(TCanonical)) {
18530     Valid.insert(Current.begin(), Current.end());
18531     Current.clear();
18532   // We've hit a cycle.
18533   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
18534              Current.count(TCanonical)) {
18535     // If we haven't diagnosed this cycle yet, do so now.
18536     if (!Invalid.count(TCanonical)) {
18537       S.Diag((*Ctor->init_begin())->getSourceLocation(),
18538              diag::warn_delegating_ctor_cycle)
18539         << Ctor;
18540 
18541       // Don't add a note for a function delegating directly to itself.
18542       if (TCanonical != Canonical)
18543         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
18544 
18545       CXXConstructorDecl *C = Target;
18546       while (C->getCanonicalDecl() != Canonical) {
18547         const FunctionDecl *FNTarget = nullptr;
18548         (void)C->getTargetConstructor()->hasBody(FNTarget);
18549         assert(FNTarget && "Ctor cycle through bodiless function");
18550 
18551         C = const_cast<CXXConstructorDecl*>(
18552           cast<CXXConstructorDecl>(FNTarget));
18553         S.Diag(C->getLocation(), diag::note_which_delegates_to);
18554       }
18555     }
18556 
18557     Invalid.insert(Current.begin(), Current.end());
18558     Current.clear();
18559   } else {
18560     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
18561   }
18562 }
18563 
18564 
18565 void Sema::CheckDelegatingCtorCycles() {
18566   llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
18567 
18568   for (DelegatingCtorDeclsType::iterator
18569            I = DelegatingCtorDecls.begin(ExternalSource.get()),
18570            E = DelegatingCtorDecls.end();
18571        I != E; ++I)
18572     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
18573 
18574   for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
18575     (*CI)->setInvalidDecl();
18576 }
18577 
18578 namespace {
18579   /// AST visitor that finds references to the 'this' expression.
18580   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
18581     Sema &S;
18582 
18583   public:
18584     explicit FindCXXThisExpr(Sema &S) : S(S) { }
18585 
18586     bool VisitCXXThisExpr(CXXThisExpr *E) {
18587       S.Diag(E->getLocation(), diag::err_this_static_member_func)
18588         << E->isImplicit();
18589       return false;
18590     }
18591   };
18592 }
18593 
18594 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
18595   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
18596   if (!TSInfo)
18597     return false;
18598 
18599   TypeLoc TL = TSInfo->getTypeLoc();
18600   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
18601   if (!ProtoTL)
18602     return false;
18603 
18604   // C++11 [expr.prim.general]p3:
18605   //   [The expression this] shall not appear before the optional
18606   //   cv-qualifier-seq and it shall not appear within the declaration of a
18607   //   static member function (although its type and value category are defined
18608   //   within a static member function as they are within a non-static member
18609   //   function). [ Note: this is because declaration matching does not occur
18610   //  until the complete declarator is known. - end note ]
18611   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
18612   FindCXXThisExpr Finder(*this);
18613 
18614   // If the return type came after the cv-qualifier-seq, check it now.
18615   if (Proto->hasTrailingReturn() &&
18616       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
18617     return true;
18618 
18619   // Check the exception specification.
18620   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
18621     return true;
18622 
18623   // Check the trailing requires clause
18624   if (Expr *E = Method->getTrailingRequiresClause())
18625     if (!Finder.TraverseStmt(E))
18626       return true;
18627 
18628   return checkThisInStaticMemberFunctionAttributes(Method);
18629 }
18630 
18631 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
18632   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
18633   if (!TSInfo)
18634     return false;
18635 
18636   TypeLoc TL = TSInfo->getTypeLoc();
18637   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
18638   if (!ProtoTL)
18639     return false;
18640 
18641   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
18642   FindCXXThisExpr Finder(*this);
18643 
18644   switch (Proto->getExceptionSpecType()) {
18645   case EST_Unparsed:
18646   case EST_Uninstantiated:
18647   case EST_Unevaluated:
18648   case EST_BasicNoexcept:
18649   case EST_NoThrow:
18650   case EST_DynamicNone:
18651   case EST_MSAny:
18652   case EST_None:
18653     break;
18654 
18655   case EST_DependentNoexcept:
18656   case EST_NoexceptFalse:
18657   case EST_NoexceptTrue:
18658     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
18659       return true;
18660     [[fallthrough]];
18661 
18662   case EST_Dynamic:
18663     for (const auto &E : Proto->exceptions()) {
18664       if (!Finder.TraverseType(E))
18665         return true;
18666     }
18667     break;
18668   }
18669 
18670   return false;
18671 }
18672 
18673 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
18674   FindCXXThisExpr Finder(*this);
18675 
18676   // Check attributes.
18677   for (const auto *A : Method->attrs()) {
18678     // FIXME: This should be emitted by tblgen.
18679     Expr *Arg = nullptr;
18680     ArrayRef<Expr *> Args;
18681     if (const auto *G = dyn_cast<GuardedByAttr>(A))
18682       Arg = G->getArg();
18683     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
18684       Arg = G->getArg();
18685     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
18686       Args = llvm::ArrayRef(AA->args_begin(), AA->args_size());
18687     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
18688       Args = llvm::ArrayRef(AB->args_begin(), AB->args_size());
18689     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
18690       Arg = ETLF->getSuccessValue();
18691       Args = llvm::ArrayRef(ETLF->args_begin(), ETLF->args_size());
18692     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
18693       Arg = STLF->getSuccessValue();
18694       Args = llvm::ArrayRef(STLF->args_begin(), STLF->args_size());
18695     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
18696       Arg = LR->getArg();
18697     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
18698       Args = llvm::ArrayRef(LE->args_begin(), LE->args_size());
18699     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
18700       Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
18701     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
18702       Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
18703     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
18704       Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
18705     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
18706       Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
18707 
18708     if (Arg && !Finder.TraverseStmt(Arg))
18709       return true;
18710 
18711     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
18712       if (!Finder.TraverseStmt(Args[I]))
18713         return true;
18714     }
18715   }
18716 
18717   return false;
18718 }
18719 
18720 void Sema::checkExceptionSpecification(
18721     bool IsTopLevel, ExceptionSpecificationType EST,
18722     ArrayRef<ParsedType> DynamicExceptions,
18723     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
18724     SmallVectorImpl<QualType> &Exceptions,
18725     FunctionProtoType::ExceptionSpecInfo &ESI) {
18726   Exceptions.clear();
18727   ESI.Type = EST;
18728   if (EST == EST_Dynamic) {
18729     Exceptions.reserve(DynamicExceptions.size());
18730     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
18731       // FIXME: Preserve type source info.
18732       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
18733 
18734       if (IsTopLevel) {
18735         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
18736         collectUnexpandedParameterPacks(ET, Unexpanded);
18737         if (!Unexpanded.empty()) {
18738           DiagnoseUnexpandedParameterPacks(
18739               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
18740               Unexpanded);
18741           continue;
18742         }
18743       }
18744 
18745       // Check that the type is valid for an exception spec, and
18746       // drop it if not.
18747       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
18748         Exceptions.push_back(ET);
18749     }
18750     ESI.Exceptions = Exceptions;
18751     return;
18752   }
18753 
18754   if (isComputedNoexcept(EST)) {
18755     assert((NoexceptExpr->isTypeDependent() ||
18756             NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
18757             Context.BoolTy) &&
18758            "Parser should have made sure that the expression is boolean");
18759     if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
18760       ESI.Type = EST_BasicNoexcept;
18761       return;
18762     }
18763 
18764     ESI.NoexceptExpr = NoexceptExpr;
18765     return;
18766   }
18767 }
18768 
18769 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
18770              ExceptionSpecificationType EST,
18771              SourceRange SpecificationRange,
18772              ArrayRef<ParsedType> DynamicExceptions,
18773              ArrayRef<SourceRange> DynamicExceptionRanges,
18774              Expr *NoexceptExpr) {
18775   if (!MethodD)
18776     return;
18777 
18778   // Dig out the method we're referring to.
18779   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
18780     MethodD = FunTmpl->getTemplatedDecl();
18781 
18782   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
18783   if (!Method)
18784     return;
18785 
18786   // Check the exception specification.
18787   llvm::SmallVector<QualType, 4> Exceptions;
18788   FunctionProtoType::ExceptionSpecInfo ESI;
18789   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
18790                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
18791                               ESI);
18792 
18793   // Update the exception specification on the function type.
18794   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
18795 
18796   if (Method->isStatic())
18797     checkThisInStaticMemberFunctionExceptionSpec(Method);
18798 
18799   if (Method->isVirtual()) {
18800     // Check overrides, which we previously had to delay.
18801     for (const CXXMethodDecl *O : Method->overridden_methods())
18802       CheckOverridingFunctionExceptionSpec(Method, O);
18803   }
18804 }
18805 
18806 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
18807 ///
18808 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
18809                                        SourceLocation DeclStart, Declarator &D,
18810                                        Expr *BitWidth,
18811                                        InClassInitStyle InitStyle,
18812                                        AccessSpecifier AS,
18813                                        const ParsedAttr &MSPropertyAttr) {
18814   IdentifierInfo *II = D.getIdentifier();
18815   if (!II) {
18816     Diag(DeclStart, diag::err_anonymous_property);
18817     return nullptr;
18818   }
18819   SourceLocation Loc = D.getIdentifierLoc();
18820 
18821   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
18822   QualType T = TInfo->getType();
18823   if (getLangOpts().CPlusPlus) {
18824     CheckExtraCXXDefaultArguments(D);
18825 
18826     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
18827                                         UPPC_DataMemberType)) {
18828       D.setInvalidType();
18829       T = Context.IntTy;
18830       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
18831     }
18832   }
18833 
18834   DiagnoseFunctionSpecifiers(D.getDeclSpec());
18835 
18836   if (D.getDeclSpec().isInlineSpecified())
18837     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
18838         << getLangOpts().CPlusPlus17;
18839   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
18840     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
18841          diag::err_invalid_thread)
18842       << DeclSpec::getSpecifierName(TSCS);
18843 
18844   // Check to see if this name was declared as a member previously
18845   NamedDecl *PrevDecl = nullptr;
18846   LookupResult Previous(*this, II, Loc, LookupMemberName,
18847                         ForVisibleRedeclaration);
18848   LookupName(Previous, S);
18849   switch (Previous.getResultKind()) {
18850   case LookupResult::Found:
18851   case LookupResult::FoundUnresolvedValue:
18852     PrevDecl = Previous.getAsSingle<NamedDecl>();
18853     break;
18854 
18855   case LookupResult::FoundOverloaded:
18856     PrevDecl = Previous.getRepresentativeDecl();
18857     break;
18858 
18859   case LookupResult::NotFound:
18860   case LookupResult::NotFoundInCurrentInstantiation:
18861   case LookupResult::Ambiguous:
18862     break;
18863   }
18864 
18865   if (PrevDecl && PrevDecl->isTemplateParameter()) {
18866     // Maybe we will complain about the shadowed template parameter.
18867     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
18868     // Just pretend that we didn't see the previous declaration.
18869     PrevDecl = nullptr;
18870   }
18871 
18872   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
18873     PrevDecl = nullptr;
18874 
18875   SourceLocation TSSL = D.getBeginLoc();
18876   MSPropertyDecl *NewPD =
18877       MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
18878                              MSPropertyAttr.getPropertyDataGetter(),
18879                              MSPropertyAttr.getPropertyDataSetter());
18880   ProcessDeclAttributes(TUScope, NewPD, D);
18881   NewPD->setAccess(AS);
18882 
18883   if (NewPD->isInvalidDecl())
18884     Record->setInvalidDecl();
18885 
18886   if (D.getDeclSpec().isModulePrivateSpecified())
18887     NewPD->setModulePrivate();
18888 
18889   if (NewPD->isInvalidDecl() && PrevDecl) {
18890     // Don't introduce NewFD into scope; there's already something
18891     // with the same name in the same scope.
18892   } else if (II) {
18893     PushOnScopeChains(NewPD, S);
18894   } else
18895     Record->addDecl(NewPD);
18896 
18897   return NewPD;
18898 }
18899 
18900 void Sema::ActOnStartFunctionDeclarationDeclarator(
18901     Declarator &Declarator, unsigned TemplateParameterDepth) {
18902   auto &Info = InventedParameterInfos.emplace_back();
18903   TemplateParameterList *ExplicitParams = nullptr;
18904   ArrayRef<TemplateParameterList *> ExplicitLists =
18905       Declarator.getTemplateParameterLists();
18906   if (!ExplicitLists.empty()) {
18907     bool IsMemberSpecialization, IsInvalid;
18908     ExplicitParams = MatchTemplateParametersToScopeSpecifier(
18909         Declarator.getBeginLoc(), Declarator.getIdentifierLoc(),
18910         Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
18911         ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
18912         /*SuppressDiagnostic=*/true);
18913   }
18914   if (ExplicitParams) {
18915     Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
18916     llvm::append_range(Info.TemplateParams, *ExplicitParams);
18917     Info.NumExplicitTemplateParams = ExplicitParams->size();
18918   } else {
18919     Info.AutoTemplateParameterDepth = TemplateParameterDepth;
18920     Info.NumExplicitTemplateParams = 0;
18921   }
18922 }
18923 
18924 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
18925   auto &FSI = InventedParameterInfos.back();
18926   if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
18927     if (FSI.NumExplicitTemplateParams != 0) {
18928       TemplateParameterList *ExplicitParams =
18929           Declarator.getTemplateParameterLists().back();
18930       Declarator.setInventedTemplateParameterList(
18931           TemplateParameterList::Create(
18932               Context, ExplicitParams->getTemplateLoc(),
18933               ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
18934               ExplicitParams->getRAngleLoc(),
18935               ExplicitParams->getRequiresClause()));
18936     } else {
18937       Declarator.setInventedTemplateParameterList(
18938           TemplateParameterList::Create(
18939               Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
18940               SourceLocation(), /*RequiresClause=*/nullptr));
18941     }
18942   }
18943   InventedParameterInfos.pop_back();
18944 }
18945